text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement, SimpleChange } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { PcapFiltersComponent } from './pcap-filters.component';
import { DatePickerModule } from '../../shared/date-picker/date-picker.module';
import { PcapRequest } from '../model/pcap.request';
import { DEFAULT_TIMESTAMP_FORMAT } from '../../utils/constants';
import * as moment from 'moment/moment';
describe('PcapFiltersComponent', () => {
let component: PcapFiltersComponent;
let fixture: ComponentFixture<PcapFiltersComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
FormsModule,
ReactiveFormsModule,
DatePickerModule,
],
declarations: [
PcapFiltersComponent,
]
})
.compileComponents();
fixture = TestBed.createComponent(PcapFiltersComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should be created', () => {
expect(component).toBeTruthy();
});
it('From date should be bound to the component', () => {
let input = fixture.debugElement.query(By.css('[data-qe-id="start-time"]'));
const dateString = '2020-11-11 11:11:11';
input.componentInstance.onChange(dateString);
fixture.detectChanges();
expect(component.filterForm.controls.startTime.value).toBe(dateString);
});
it('To date should be bound to the component', () => {
let input = fixture.debugElement.query(By.css('[data-qe-id="end-time"]'));
const dateString = '2030-11-11 11:11:11';
input.componentInstance.onChange(dateString);
fixture.detectChanges();
expect(component.filterForm.controls.endTime.value).toBe(dateString);
});
it('IP Source Address should be bound to the model', () => {
let input: HTMLInputElement = fixture.nativeElement.querySelector('[data-qe-id="ip-src-addr"]');
input.value = '192.168.0.1';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.filterForm.controls.ipSrcAddr.value).toBe('192.168.0.1');
});
it('IP Source Port should be bound to the property', () => {
let input: HTMLInputElement = fixture.nativeElement.querySelector('[data-qe-id="ip-src-port"]');
input.value = '9345';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.filterForm.controls.ipSrcPort.value).toBe('9345');
});
it('IP Source Port should be converted to number on submit', () => {
component.filterForm.patchValue({ ipSrcPort: '42' });
component.search.emit = (model: PcapRequest) => {
expect(model.ipSrcPort).toBe('42');
};
component.onSubmit();
});
it('IP Dest Address should be bound to the model', () => {
let input: HTMLInputElement = fixture.nativeElement.querySelector('[data-qe-id="ip-dst-addr"]');
input.value = '256.0.0.7';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.filterForm.controls.ipDstAddr.value).toBe('256.0.0.7');
});
it('IP Dest Port should be bound to the property', () => {
let input: HTMLInputElement = fixture.nativeElement.querySelector('[data-qe-id="ip-dst-port"]');
input.value = '8989';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.filterForm.controls.ipDstPort.value).toBe('8989');
});
it('IP Dest Port should be converted to number on submit', () => {
component.filterForm.patchValue({ ipDstPort: '42' });
component.search.emit = (model: PcapRequest) => {
expect(model.ipDstPort).toBe('42');
};
component.onSubmit();
});
it('Protocol should be bound to the model', () => {
let input: HTMLInputElement = fixture.nativeElement.querySelector('[data-qe-id="protocol"]');
input.value = 'TCP';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.filterForm.controls.protocol.value).toBe('TCP');
});
it('Include Reverse Traffic should be bound to the model', () => {
let input: HTMLInputElement = fixture.nativeElement.querySelector('[data-qe-id="include-reverse"]');
input.click();
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.filterForm.controls.includeReverse.value).toBe(true);
});
it('Text filter should be bound to the model', () => {
let input: HTMLInputElement = fixture.nativeElement.querySelector('[data-qe-id="packet-filter"]');
input.value = 'TestStringFilter';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.filterForm.controls.packetFilter.value).toBe('TestStringFilter');
});
it('From date should be converted to timestamp on submit', () => {
component.filterForm.patchValue({ startTime: '2220-12-12 12:12:12' });
component.search.emit = (model: PcapRequest) => {
expect(model.startTimeMs).toBe(new Date(component.filterForm.controls.startTime.value).getTime());
};
component.onSubmit();
});
it('To date should be converted to timestamp on submit', () => {
component.filterForm.patchValue({ endTimeStr: '2320-03-13 13:13:13' });
component.search.emit = (model: PcapRequest) => {
expect(model.endTimeMs).toBe(new Date(component.filterForm.controls.endTime.value).getTime());
};
component.onSubmit();
});
it('Port fields should be missing by default', () => {
component.search.emit = (model: PcapRequest) => {
expect(model.ipSrcPort).toBeFalsy();
expect(model.ipDstPort).toBeFalsy();
};
component.onSubmit();
});
it('Filter should have an output called search', () => {
component.search.subscribe((filterModel) => {
expect(filterModel).toBeDefined();
});
component.onSubmit();
});
it('Filter should emit search event on submit', () => {
spyOn(component.search, 'emit');
component.onSubmit();
expect(component.search.emit).toHaveBeenCalled();
});
it('should update request on changes', () => {
const startTimeStr = '2220-12-12 12:12:12';
const endTimeStr = '2320-03-13 13:13:13';
const newModel = new PcapRequest();
newModel.startTimeMs = new Date(startTimeStr).getTime();
newModel.endTimeMs = new Date(endTimeStr).getTime();
newModel.ipSrcPort = '9345';
newModel.ipDstPort = '8989';
component.ngOnChanges({
model: new SimpleChange(null, newModel, false)
});
expect(component.filterForm.controls.startTime.value).toBe(startTimeStr);
expect(component.filterForm.controls.endTime.value).toBe(endTimeStr);
expect(component.filterForm.controls.ipSrcPort.value).toBe('9345');
expect(component.filterForm.controls.ipDstPort.value).toBe('8989');
});
it('should update request on changes with missing port filters', () => {
const startTimeStr = '2220-12-12 12:12:12';
const endTimeStr = '2320-03-13 13:13:13';
let newModel = new PcapRequest();
newModel.startTimeMs = new Date(startTimeStr).getTime();
newModel.endTimeMs = new Date(endTimeStr).getTime();
component.ngOnChanges({
model: new SimpleChange(null, newModel, false)
});
expect(component.filterForm.controls.startTime.value).toBe(startTimeStr);
expect(component.filterForm.controls.endTime.value).toBe(endTimeStr);
expect(component.filterForm.controls.ipSrcPort.value).toBe('');
expect(component.filterForm.controls.ipDstPort.value).toBe('');
});
describe('Filter validation', () => {
function setup() {
component.queryRunning = false;
fixture.detectChanges();
}
function getFieldWithSubmit(fieldId: string): { field: DebugElement, submit: DebugElement } {
const field = fixture.debugElement.query(By.css('[data-qe-id="' + fieldId + '"]'));
const submit = fixture.debugElement.query(By.css('[data-qe-id="submit-button"]'));
return {
field,
submit
};
}
function setFieldValue(field: DebugElement, value: any) {
field.nativeElement.value = value;
field.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
}
function isSubmitDisabled(submit: DebugElement): boolean {
return submit.classes['disabled'] && submit.nativeElement.disabled;
}
function isFieldInvalid(field: DebugElement): boolean {
return field.classes['ng-invalid'];
}
function tearDown(field: DebugElement) {
setFieldValue(field, '');
};
beforeEach(setup);
it('should disable the form if the ip source port is invalid', () => {
const invalidValues = [
'-42',
'-1',
'foobar',
'.',
'-',
'+',
'e',
'E',
'3.14',
'123456',
'65536',
'99999',
'2352363474576',
'1e3',
];
invalidValues.forEach((value) => {
const els = getFieldWithSubmit('ip-src-port');
expect(isFieldInvalid(els.field)).toBe(false, 'the field should be valid without ' + value);
expect(isSubmitDisabled(els.submit)).toBe(false, 'the submit button should be enabled without ' + value);
setFieldValue(els.field, value);
expect(isFieldInvalid(els.field)).toBe(true, 'the field should be invalid with ' + value);
expect(isSubmitDisabled(els.submit)).toBe(true, 'the submit button should be disabled with ' + value);
tearDown(els.field);
});
});
it('should keep the form enabled if the ip source port is valid', () => {
const validValues = [
'8080',
'1024',
'3000',
'1',
'0',
'12345',
'65535',
];
validValues.forEach((value) => {
const els = getFieldWithSubmit('ip-src-port');
expect(isFieldInvalid(els.field)).toBe(false, 'the field should be valid without ' + value);
expect(isSubmitDisabled(els.submit)).toBe(false, 'the submit button should be enabled without ' + value);
setFieldValue(els.field, value);
expect(isFieldInvalid(els.field)).toBe(false, 'the field should be valid with ' + value);
expect(isSubmitDisabled(els.submit)).toBe(false, 'the submit button should be enabled with ' + value);
tearDown(els.field);
});
});
it('should disable the form if the ip destination port is invalid', () => {
const invalidValues = [
'-42',
'-1',
'foobar',
'.',
'-',
'+',
'e',
'E',
'3.14',
'123456',
'65536',
'99999',
'2352363474576',
'1e3',
];
invalidValues.forEach((value) => {
const els = getFieldWithSubmit('ip-dst-port');
expect(isFieldInvalid(els.field)).toBe(false, 'the field should be valid without ' + value);
expect(isSubmitDisabled(els.submit)).toBe(false, 'the submit button should be enabled without ' + value);
setFieldValue(els.field, value);
expect(isFieldInvalid(els.field)).toBe(true, 'the field should be invalid with ' + value);
expect(isSubmitDisabled(els.submit)).toBe(true, 'the submit button should be disabled with ' + value);
tearDown(els.field);
});
});
it('should keep the form enabled if the ip destination port is valid', () => {
const validValues = [
'8080',
'1024',
'3000',
'1',
'0',
'12345',
'65535',
];
validValues.forEach((value) => {
const els = getFieldWithSubmit('ip-dst-port');
expect(isFieldInvalid(els.field)).toBe(false, 'the field should be valid without ' + value);
expect(isSubmitDisabled(els.submit)).toBe(false, 'the submit button should be enabled without ' + value);
setFieldValue(els.field, value);
expect(isFieldInvalid(els.field)).toBe(false, 'the field should be valid with ' + value);
expect(isSubmitDisabled(els.submit)).toBe(false, 'the submit button should be enabled with ' + value);
tearDown(els.field);
});
});
it('should disable the form if the ip source field is invalid', () => {
const invalidValues = [
'tst',
0o0,
0,
'111.111.111',
'222.222.222.222.222',
'333.333.333.333',
];
invalidValues.forEach((value) => {
const els = getFieldWithSubmit('ip-src-addr');
expect(isFieldInvalid(els.field)).toBe(false, 'the field should be valid without ' + value);
expect(isSubmitDisabled(els.submit)).toBe(false, 'the submit button should be enabled without ' + value);
setFieldValue(els.field, value);
expect(isFieldInvalid(els.field)).toBe(true, 'the field should be invalid with ' + value);
expect(isSubmitDisabled(els.submit)).toBe(true, 'the submit button should be disabled with ' + value);
tearDown(els.field);
});
});
it('should keep the form enabled if the ip source field is valid', () => {
const validValues = [
'0.0.0.0',
'222.222.222.222',
'255.255.255.255',
];
validValues.forEach((value) => {
const els = getFieldWithSubmit('ip-src-addr');
expect(isFieldInvalid(els.field)).toBe(false, 'the field should be valid without ' + value);
expect(isSubmitDisabled(els.submit)).toBe(false, 'the submit button should be enabled without ' + value);
setFieldValue(els.field, value);
expect(isFieldInvalid(els.field)).toBe(false, 'the field should be valid with ' + value);
expect(isSubmitDisabled(els.submit)).toBe(false, 'the submit button should be enabled with ' + value);
tearDown(els.field);
});
});
it('start date should be valid by default', () => {
expect(component.filterForm.get('startTime').valid).toBe(true);
});
it('start date is invalid if it is bigger than end date', () => {
// start time is bigger than end time
component.filterForm.patchValue({
startTime: '2018-08-24 16:30:00',
endTime: '2018-08-23 16:30:00'
});
expect(component.filterForm.get('startTime').valid).toBe(false);
});
it('start date should be valid again based on the end date', () => {
// start time is bigger than end time
component.filterForm.patchValue({
startTime: '2018-08-24 16:30:00',
endTime: '2018-08-23 16:30:00'
});
expect(component.filterForm.get('startTime').valid).toBe(false);
component.filterForm.patchValue({
endTime: '2018-08-25 16:30:00'
});
expect(component.filterForm.get('startTime').valid).toBe(true);
});
it('end date should be valid by default', () => {
expect(component.filterForm.get('endTime').valid).toBe(true);
});
it('end date is invalid if it is in the future', () => {
expect(component.filterForm.get('endTime').valid).toBe(true);
component.filterForm.patchValue({
endTime: moment(new Date()).add(2, 'days').format(DEFAULT_TIMESTAMP_FORMAT)
});
expect(component.filterForm.get('endTime').valid).toBe(false);
});
});
}); | the_stack |
import { Server } from "http";
import express from "express";
import nock from "nock";
import _ from "lodash";
import { expect } from "chai";
import queryString from "query-string";
import Registry from "magda-typescript-common/src/registry/AuthorizedRegistryClient";
import { Record } from "magda-typescript-common/src/generated/registry/api";
import { lcAlphaNumStringArbNe } from "magda-typescript-common/src/test/arbitraries";
import jsc from "magda-typescript-common/src/test/jsverify";
import MinionOptions from "../MinionOptions";
import fakeArgv from "./fakeArgv";
import baseSpec from "./baseSpec";
import Crawler from "../Crawler";
import { MAGDA_ADMIN_PORTAL_ID } from "magda-typescript-common/src/registry/TenantConsts";
baseSpec(
"Crawler",
(
expressApp: () => express.Express,
_expressServer: () => Server,
listenPort: () => number,
beforeEachProperty: () => void
) => {
//--- avoid different property test hit into the same registry domain
let registryDomainCounter = 0;
//--- function implements generic crawler testing logic
async function basecrawlerTest(
registryTotalRecordsNumber: number,
domain: string,
jwtSecret: string,
concurrency: number,
async: boolean,
enableMultiTenant: boolean,
// --- init func creates other context variables shared among callbacks
envInit: () => any,
onRecordFound: (
record: Record,
registry: Registry
) => Promise<void>,
registryReplyFunc: (uri: string, requestBody: string) => any,
propertyCheckingFunc: () => boolean
) {
beforeEachProperty();
const internalUrl = `http://${domain}.com`;
const registryDomain = "registry_" + registryDomainCounter;
const tenantDomain = "tenant_" + registryDomainCounter;
registryDomainCounter++;
const registryUrl = `http://${registryDomain}.com:80`;
const tenantUrl = `http://${tenantDomain}.com:80`;
const registryScope = nock(registryUrl);
const tenantId = MAGDA_ADMIN_PORTAL_ID;
const userId = "b1fddd6f-e230-4068-bd2c-1a21844f1598";
const registry = new Registry({
baseUrl: registryUrl,
jwtSecret: jwtSecret,
userId: userId,
tenantId: tenantId
});
let context: any = {
registryTotalRecordsNumber,
domain,
jwtSecret,
userId,
concurrency,
async,
registryScope,
registry
};
const env = envInit.bind(context)();
if (env && typeof env === "object")
context = { ...context, ...env };
const options: MinionOptions = {
argv: fakeArgv({
internalUrl,
registryUrl,
enableMultiTenant,
tenantUrl,
jwtSecret,
userId,
listenPort: listenPort()
}),
id: "id",
aspects: [],
optionalAspects: [],
writeAspectDefs: [],
async,
express: expressApp,
concurrency: concurrency,
onRecordFound: onRecordFound.bind(context)
};
registryScope
.persist()
.get("/records")
.query(true)
.reply(registryReplyFunc.bind(context));
const crawler = new Crawler(registry, options);
context.crawler = crawler;
await crawler.start();
registryScope.done();
return propertyCheckingFunc.bind(context)();
}
function basePropertyTest(
// --- init func creates other context variables shared among callbacks
envInit: () => any,
onRecordFound: (
record: Record,
registry: Registry
) => Promise<void>,
registryReplyFunc: (uri: string, requestBody: string) => any,
propertyCheckingFunc: () => boolean
) {
return jsc.assert(
jsc.forall(
jsc.nat(100),
lcAlphaNumStringArbNe,
lcAlphaNumStringArbNe,
jsc.integer(1, 10),
jsc.bool,
jsc.bool,
_.partialRight(
basecrawlerTest,
envInit,
onRecordFound,
registryReplyFunc,
propertyCheckingFunc
)
)
);
}
it("should crawl all records in registry ONCE start() called ", () => {
return basePropertyTest(
function (this: any) {
//---envInit
//--- this table records whether all records are sent to onRecordFound for only once
const recordsTestTable: number[] = new Array(
this.registryTotalRecordsNumber
).fill(0);
const registryRecords: Record[] = recordsTestTable.map(
(item, idx) => ({
id: String(idx),
name: "",
aspects: {},
sourceTag: "",
tenantId: MAGDA_ADMIN_PORTAL_ID,
authnReadPolicyId: undefined
})
);
return { recordsTestTable, registryRecords };
},
function (
//---onRecordFound
this: any,
foundRecord: Record,
registry: Registry
) {
const idx = parseInt(foundRecord.id, 10);
if (typeof this.recordsTestTable[idx] !== "number") {
throw new Error(
`try to increase invalid counter at ${idx}`
);
}
this.recordsTestTable[idx]++;
return Promise.resolve();
},
function (this: any, uri: string, requestBody: string) {
//---registryReplyFunc
const params = queryString.parseUrl(uri).query;
const pageIdx = params.pageToken
? parseInt(params.pageToken as string, 10)
: 0;
const limit = parseInt(params.limit as string, 10);
if (limit < 1)
throw new Error("Invalid limit param received!");
if (pageIdx >= this.registryRecords.length)
return [
200,
{
totalCount: this.registryRecords.length,
hasMore: false,
records: new Array()
}
];
const recordPage = this.registryRecords.slice(
pageIdx,
pageIdx + limit - 1
);
const resData: any = {
totalCount: this.registryRecords.length,
hasMore: true,
records: recordPage
};
const nextPageToken = pageIdx + recordPage.length;
if (nextPageToken < this.registryRecords.length) {
resData.nextPageToken = String(nextPageToken);
} else {
resData.hasMore = false;
}
return [200, resData];
},
function (this: any) {
//---propertyCheckingFunc
return (
this.recordsTestTable.findIndex(
(item: any) => item !== 1
) === -1
);
}
);
}).timeout(20000);
it("should correctly return crawling progress at every step via getProgress()", () => {
return basePropertyTest(
function (this: any) {
//---envInit
const totalCrawledRecordsNumber = 0;
const registryRecords: Record[] = new Array(
this.registryTotalRecordsNumber
)
.fill(0)
.map((item, idx) => ({
id: String(idx),
name: "",
aspects: {},
sourceTag: "",
tenantId: MAGDA_ADMIN_PORTAL_ID,
authnReadPolicyId: undefined
}));
return {
totalCrawledRecordsNumber,
registryRecords
};
},
function (
//---onRecordFound
this: any,
foundRecord: Record,
registry: Registry
) {
return Promise.resolve();
},
function (this: any, uri: string, requestBody: string) {
//---registryReplyFunc
const params = queryString.parseUrl(uri).query;
const pageIdx = params.pageToken
? parseInt(params.pageToken as string, 10)
: 0;
const limit = parseInt(params.limit as string, 10);
if (limit < 1)
throw new Error("Invalid limit param received!");
if (pageIdx >= this.registryRecords.length) {
return [
200,
{
totalCount: this.registryRecords.length,
hasMore: false,
records: []
}
];
}
const recordPage = this.registryRecords.slice(
pageIdx,
pageIdx + limit - 1
);
const crawlingPageTokenValue = pageIdx + recordPage.length;
const crawlingPageToken = String(crawlingPageTokenValue);
this.totalCrawledRecordsNumber += recordPage.length;
const progress = this.crawler.getProgress();
expect(progress).to.deep.equal({
isCrawling: true,
crawlingPageToken: String(pageIdx ? pageIdx : ""),
crawledRecordNumber: pageIdx
});
return [
200,
{
totalCount: this.registryRecords.length,
hasMore: true,
nextPageToken: crawlingPageToken,
records: recordPage
}
];
},
function (this: any) {
//---propertyCheckingFunc
return true;
}
);
}).timeout(200000);
}
); | the_stack |
import { Cache } from '../src/Cache';
import { MicroMemoize } from '../src/types';
import { isSameValueZero } from '../src/utils';
describe('create cache', () => {
it('should create a new cache instance with correct defaults', () => {
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {};
const cache = new Cache(options);
expect(cache.keys).toEqual([]);
expect(cache.values).toEqual([]);
expect(cache.getKeyIndex).toEqual(cache._getKeyIndexForSingle);
expect(cache.canTransformKey).toBe(false);
expect(cache.shouldCloneArguments).toBe(false);
expect(cache.shouldUpdateOnAdd).toBe(false);
expect(cache.shouldUpdateOnChange).toBe(false);
expect(cache.shouldUpdateOnHit).toBe(false);
});
it('should create a new cache instance with correct values when not matching key', () => {
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
maxSize: 5,
transformKey(): any[] {
return [];
},
onCacheAdd() {},
onCacheChange() {},
onCacheHit() {},
};
const cache = new Cache(options);
expect(cache.keys).toEqual([]);
expect(cache.values).toEqual([]);
expect(cache.getKeyIndex).toEqual(cache._getKeyIndexForMany);
expect(cache.canTransformKey).toBe(true);
expect(cache.shouldCloneArguments).toBe(true);
expect(cache.shouldUpdateOnAdd).toBe(true);
expect(cache.shouldUpdateOnChange).toBe(true);
expect(cache.shouldUpdateOnHit).toBe(true);
});
it('should create a new cache instance with correct values when matching key', () => {
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
isMatchingKey() {
return true;
},
};
const cache = new Cache(options);
expect(cache.keys).toEqual([]);
expect(cache.values).toEqual([]);
expect(cache.getKeyIndex).toEqual(cache._getKeyIndexFromMatchingKey);
expect(cache.canTransformKey).toBe(false);
expect(cache.shouldCloneArguments).toBe(true);
expect(cache.shouldUpdateOnAdd).toBe(false);
expect(cache.shouldUpdateOnChange).toBe(false);
expect(cache.shouldUpdateOnHit).toBe(false);
});
});
describe('cache methods', () => {
describe('getKeyIndex', () => {
it('will return -1 if no keys exist', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = { isEqual };
const cache = new Cache(options);
const keyToMatch = ['key'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(-1);
});
it('will return the index of the match found', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = { isEqual };
const cache = new Cache(options);
cache.keys = [['key']];
const keyToMatch = ['key'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(0);
});
it('will return the index of the match found with a larger key', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = { isEqual };
const cache = new Cache(options);
cache.keys = [['key1', 'key2']];
const keyToMatch = ['key1', 'key2'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(0);
});
it('will return -1 if the key length is different', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = { isEqual };
const cache = new Cache(options);
cache.keys = [['key']];
const keyToMatch = ['some', 'other key'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(-1);
});
it('will return -1 if no match found', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = { isEqual };
const cache = new Cache(options);
cache.keys = [['key']];
const keyToMatch = ['other key'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(-1);
});
it('will return -1 if no match found with a larger key', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = { isEqual };
const cache = new Cache(options);
cache.keys = [['key1', 'key2']];
const keyToMatch = ['keyA', 'keyB'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(-1);
});
it('will return -1 if no keys exist with larger maxSize', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = { isEqual, maxSize: 2 };
const cache = new Cache(options);
const keyToMatch = ['key'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(-1);
});
it('will return the index of the match found with larger maxSize', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = { isEqual, maxSize: 2 };
const cache = new Cache(options);
cache.keys = [['key'], ['other key']];
const keyToMatch = ['other key'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(1);
});
it('will return -1 if the key length is different with larger maxSize', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = { isEqual, maxSize: 2 };
const cache = new Cache(options);
cache.keys = [['key'], ['not other key']];
const keyToMatch = ['some', 'other key'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(-1);
});
it('will return -1 if no match found with larger maxSize', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = { isEqual, maxSize: 2 };
const cache = new Cache(options);
cache.keys = [['key'], ['other key']];
const keyToMatch = ['not present key'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(-1);
});
it('will use the isMatchingKey method is passed', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
const isMatchingKey = (o1: any, o2: any) => {
const existingKey = o1[0];
const key = o2[0];
return (
existingKey.hasOwnProperty('foo') &&
key.hasOwnProperty('foo') &&
(existingKey.bar === 'bar' || key.bar === 'baz')
);
};
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
isEqual,
isMatchingKey,
};
const cache = new Cache(options);
cache.keys = [
[
{
bar: 'bar',
foo: 'foo',
},
],
];
const keyToMatch = [
{
bar: 'baz',
foo: 'bar',
},
];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(0);
});
it('will use the isMatchingKey method is passed and maxSize is greater than 1', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
const isMatchingKey = (o1: any, o2: any) => {
const existingKey = o1[0];
const key = o2[0];
return (
existingKey.hasOwnProperty('foo') &&
key.hasOwnProperty('foo') &&
(existingKey.bar === 'bar' || key.bar === 'baz')
);
};
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
isEqual,
isMatchingKey,
maxSize: 2,
};
const cache = new Cache(options);
cache.keys = [
[
{
bar: 'baz',
baz: 'quz',
},
],
[
{
bar: 'bar',
foo: 'foo',
},
],
];
const keyToMatch = [
{
bar: 'baz',
foo: 'bar',
},
];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(1);
});
it('will return -1 if the isMatchingKey method is passed and there are no keys', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
const isMatchingKey = (o1: any, o2: any) => {
const existingKey = o1[0];
const key = o2[0];
return (
existingKey.hasOwnProperty('foo') &&
key.hasOwnProperty('foo') &&
(existingKey.bar === 'bar' || key.bar === 'baz')
);
};
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
isEqual,
isMatchingKey,
};
const cache = new Cache(options);
const keyToMatch = ['key'];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(-1);
});
it('will return -1 if the isMatchingKey method is passed and no match is found', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
const isMatchingKey = (o1: any, o2: any) => {
const existingKey = o1[0];
const key = o2[0];
return (
existingKey.hasOwnProperty('foo') &&
key.hasOwnProperty('foo') &&
(existingKey.bar === 'bar' || key.bar === 'baz')
);
};
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
isEqual,
isMatchingKey,
};
const cache = new Cache(options);
cache.keys = [
[
{
bar: 'baz',
baz: 'quz',
},
],
];
const keyToMatch = [
{
bar: 'baz',
foo: 'bar',
},
];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(-1);
});
it('will return -1 if the isMatchingKey method is passed and no match is found with a larger maxSize', () => {
const isEqual = (o1: any, o2: any) => o1 === o2;
const isMatchingKey = (o1: any, o2: any) => {
const existingKey = o1[0];
const key = o2[0];
return (
existingKey.hasOwnProperty('foo') &&
key.hasOwnProperty('foo') &&
(existingKey.bar === 'bar' || key.bar === 'baz')
);
};
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
isEqual,
isMatchingKey,
maxSize: 2,
};
const cache = new Cache(options);
cache.keys = [
[
{
bar: 'baz',
baz: 'quz',
},
{
baz: 'quz',
quz: 'blah',
},
],
];
const keyToMatch = [
{
bar: 'baz',
foo: 'bar',
},
];
const result = cache.getKeyIndex(keyToMatch);
expect(result).toEqual(-1);
});
});
describe('orderByLru', () => {
it('will do nothing if the itemIndex is 0', () => {
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
maxSize: 3,
};
const cache = new Cache(options);
cache.keys = [['first'], ['second'], ['third']];
cache.values = ['first', 'second', 'third'];
const itemIndex = 0;
const key = cache.keys[itemIndex];
const value = cache.values[itemIndex];
cache.orderByLru(key, value, itemIndex);
expect(cache.snapshot).toEqual({
keys: [['first'], ['second'], ['third']],
size: 3,
values: ['first', 'second', 'third'],
});
});
it('will place the itemIndex first in order when non-zero', () => {
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
maxSize: 3,
};
const cache = new Cache(options);
cache.keys = [['first'], ['second'], ['third']];
cache.values = ['first', 'second', 'third'];
const itemIndex = 1;
const key = cache.keys[itemIndex];
const value = cache.values[itemIndex];
cache.orderByLru(key, value, itemIndex);
expect(cache.snapshot).toEqual({
keys: [['second'], ['first'], ['third']],
size: 3,
values: ['second', 'first', 'third'],
});
});
it('will add the new item to the array and remove the last when the itemIndex is the array length', () => {
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
maxSize: 10,
};
const cache = new Cache(options);
cache.keys = [['first'], ['second'], ['third']];
cache.values = ['first', 'second', 'third'];
const itemIndex = cache.keys.length;
const key = ['key'];
const value = 'new';
cache.orderByLru(key, value, itemIndex);
expect(cache.snapshot).toEqual({
keys: [key, ['first'], ['second'], ['third']],
size: 4,
values: [value, 'first', 'second', 'third'],
});
});
it('will truncate the cache to the max size if too large by manual additions', () => {
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
maxSize: 2,
};
const cache = new Cache(options);
cache.keys = [['first'], ['second'], ['third']];
cache.values = ['first', 'second', 'third'];
const itemIndex = cache.keys.length;
const key = ['key'];
const value = 'new';
cache.orderByLru(key, value, itemIndex);
expect(cache.snapshot).toEqual({
keys: [key, ['first']],
size: 2,
values: [value, 'first'],
});
});
});
describe('updateAsyncCache', () => {
it('will handle being settled', async () => {
const timeout = 200;
const fn = async () => {
await new Promise((resolve: Function) => {
setTimeout(resolve, timeout);
});
return 'resolved';
};
const key = ['foo'];
const memoized = ((() => {}) as unknown) as MicroMemoize.Memoized<Function>;
const value = fn();
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
isEqual: isSameValueZero,
isPromise: true,
};
const cache = new Cache(options);
cache.keys = [key];
cache.values = [value];
cache.updateAsyncCache(memoized);
// this is just to prevent the unhandled rejection noise
cache.values[0].catch(() => {});
expect(cache.snapshot).toEqual({
keys: [key],
size: 1,
values: [value],
});
await new Promise((resolve: Function) => {
setTimeout(resolve, timeout + 50);
});
expect(cache.snapshot).toEqual({
keys: [key],
size: 1,
values: [value],
});
});
it('will fire cache callbacks if resolved', async () => {
const timeout = 200;
const fn = async () => {
await new Promise((resolve: Function) => {
setTimeout(resolve, timeout);
});
return 'resolved';
};
const key = ['foo'];
const memoized = ((() => {}) as unknown) as MicroMemoize.Memoized<Function>;
const value = fn();
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
isEqual: isSameValueZero,
isPromise: true,
onCacheChange: jest.fn(),
onCacheHit: jest.fn(),
};
const cache = new Cache(options);
cache.keys = [key];
cache.values = [value];
cache.updateAsyncCache(memoized);
// this is just to prevent the unhandled rejection noise
cache.values[0].catch(() => {});
expect(cache.snapshot).toEqual({
keys: [key],
size: 1,
values: [value],
});
await new Promise((resolve: Function) => {
setTimeout(resolve, timeout + 50);
});
expect(cache.snapshot).toEqual({
keys: [key],
size: 1,
values: [value],
});
expect(options.onCacheHit).toHaveBeenCalledTimes(1);
expect(options.onCacheHit).toHaveBeenCalledWith(cache, options, memoized);
expect(options.onCacheChange).toHaveBeenCalledTimes(1);
expect(options.onCacheChange).toHaveBeenCalledWith(
cache,
options,
memoized,
);
});
it('will remove the key from cache when the promise is rejected', async () => {
const timeout = 200;
const fn = async () => {
await new Promise((resolve: Function, reject: Function) => {
setTimeout(() => reject(new Error('boom')), timeout);
});
};
const key = ['foo'];
const value = fn();
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
isEqual: isSameValueZero,
isPromise: true,
onCacheChange: jest.fn(),
onCacheHit: jest.fn(),
};
const cache = new Cache(options);
cache.keys = [key];
cache.values = [value];
const memoized = ((() => {}) as unknown) as MicroMemoize.Memoized<Function>;
cache.updateAsyncCache(memoized);
const catcher = jest.fn();
cache.values[0].catch(catcher);
expect(cache.snapshot).toEqual({
keys: [key],
size: 1,
values: [value],
});
await new Promise((resolve: Function) => {
setTimeout(resolve, timeout + 50);
});
expect(catcher).toHaveBeenCalledTimes(1);
expect(cache.snapshot).toEqual({
keys: [],
size: 0,
values: [],
});
expect(options.onCacheHit).toHaveBeenCalledTimes(0);
expect(options.onCacheChange).toHaveBeenCalledTimes(0);
});
it('will not remove the key from cache when the promise is rejected but the key no longer exists', async () => {
const timeout = 200;
const fn = async () => {
await new Promise((resolve: Function, reject: Function) => {
setTimeout(() => reject(new Error('boom')), timeout);
});
};
const key = ['foo'];
const value = fn();
// @ts-ignore
const options: MicroMemoize.NormalizedOptions = {
isEqual: isSameValueZero,
isPromise: true,
onCacheChange: jest.fn(),
onCacheHit: jest.fn(),
};
const cache = new Cache(options);
cache.keys = [key];
cache.values = [value];
const memoized = ((() => {}) as unknown) as MicroMemoize.Memoized<Function>;
cache.updateAsyncCache(memoized);
const newValue = cache.values[0];
const catcher = jest.fn();
newValue.catch(catcher);
expect(cache.snapshot).toEqual({
keys: [key],
size: 1,
values: [value],
});
cache.keys = [['bar']];
// @ts-ignore
cache.values = [Promise.resolve('baz')];
await new Promise((resolve: Function) => {
setTimeout(resolve, timeout + 50);
});
expect(catcher).toHaveBeenCalledTimes(1);
expect(options.onCacheHit).toHaveBeenCalledTimes(0);
expect(options.onCacheChange).toHaveBeenCalledTimes(0);
});
});
}); | the_stack |
"use strict"
import Blok = require("./blok");
import Css = require("./css");
import BlokContainerUserSettings = require("./blok-container-user-settings");
import Rect = require("./rect");
import BlokAdapter = require("./blok-adapter");
import Utils = require("./utils");
var JSON2 = require("JSON2");
require("./shim/myshims");
var cssLayout = require("css-layout");
class BlokContainer extends Blok {
/**
* DO NOT CALL, use a BlokAdapter method.
*
* @param pageItem - art to wrap
*/
constructor(pageItem: any) {
super(pageItem);
}
/** For css flex-direction */
public getFlexDirection(): Css.FlexDirections {
return this.getSavedProperty<Css.FlexDirections>("flexDirection");
}
/** For css flex-direction. Cannot be set to undefined */
public setFlexDirection(value: Css.FlexDirections): void {
if (value === undefined) {
throw new TypeError("flex-direction cannot be undefined");
}
this.setSavedProperty<Css.FlexDirections>("flexDirection", value);
}
/** For css justify-content */
public getJustifyContent(): Css.Justifications {
return this.getSavedProperty<Css.Justifications>("justifyContent");
}
/** For css justify-content. Cannot be set to undefined */
public setJustifyContent(value: Css.Justifications): void {
if (value === undefined) {
throw new TypeError("justify-content cannot be undefined");
}
this.setSavedProperty<Css.Justifications>("justifyContent", value);
}
/** For css align-items */
public getAlignItems(): Css.Alignments {
return this.getSavedProperty<Css.Alignments>("alignItems");
}
/** For css justify-content. Cannot be set to undefined */
public setAlignItems(value: Css.Alignments): void {
if (value === undefined) {
throw new TypeError("align-items cannot be undefined");
}
this.setSavedProperty<Css.Alignments>("alignItems", value);
}
/** For css flex-wrap */
public getFlexWrap(): Css.FlexWraps {
return this.getSavedProperty<Css.FlexWraps>("flexWrap");
}
/** For css flex-wrap. Cannot be set to undefined */
public setFlexWrap(value: Css.FlexWraps): void {
if (value === undefined) {
throw new TypeError("flex-wrap cannot be undefined");
}
this.setSavedProperty<Css.FlexWraps>("flexWrap", value);
}
/** The visible position and size, relative to the parent BlokContainer,
or to the current artboard if there is no container */
public /*override*/ getRect(): Rect {
let actualArtboard = new Rect(Blok.getPageItemBounds(this._pageItem));
let container = this.getContainer();
if (container) {
let actualContainerArtboard = new Rect(Blok.getPageItemBounds(this.getContainer()._pageItem));
// Translate to coordinates relative to container
let relativeX = actualArtboard.getX() - actualContainerArtboard.getX();
let relativeY = actualArtboard.getY() - actualContainerArtboard.getY();
actualArtboard.setX(relativeX);
actualArtboard.setY(relativeY);
}
return actualArtboard;
}
/** Create a settings object reflecting our current state */
public /*override*/ getUserSettings(): BlokContainerUserSettings {
let settings = <BlokContainerUserSettings>super.getUserSettings();
settings.flexDirection = this.getFlexDirection();
settings.justifyContent = this.getJustifyContent();
settings.alignItems = this.getAlignItems();
settings.flexWrap = this.getFlexWrap();
return settings;
}
/** Make our current state match the given user settings */
public /*override*/ setUserSettings(value: BlokContainerUserSettings): void {
super.setUserSettings(value);
if (value.alignItems === Css.Alignments.STRETCH &&
this.getAlignItems() !== Css.Alignments.STRETCH) {
let children = this.getChildren();
for (let i = 0; i < children.length; i++) {
let child = children[i];
let rect = child.getRect();
child.setCachedPrestretchWidth(rect.getWidth());
child.setCachedPrestretchHeight(rect.getHeight());
}
}
else if (this.getAlignItems() === Css.Alignments.STRETCH &&
value.alignItems !== Css.Alignments.STRETCH) {
let children = this.getChildren();
for (let i = 0; i < children.length; i++) {
let child = children[i];
child.setUseCachedPrestretch(true);
}
}
this.setFlexDirection(value.flexDirection);
this.setJustifyContent(value.justifyContent);
this.setAlignItems(value.alignItems);
this.setFlexWrap(value.flexWrap);
}
/** Return a pre-layout css-layout node for this BlokContainer and all child Bloks */
public /*override*/ computeCssNode(): any {
let cssNode = super.computeCssNode();
// Handle BlokContainer-specific fixed width/height rules
let w = cssNode.style.width;
let h = cssNode.style.height;
if (this.getOverrideWidth() !== undefined) {
w = this.getOverrideWidth();
this.setOverrideWidth(undefined);
}
if (this.getOverrideHeight() !== undefined) {
h = this.getOverrideHeight();
this.setOverrideHeight(undefined);
}
cssNode.style.width = undefined;
cssNode.style.height = undefined;
if (this.getJustifyContent() === Css.Justifications.SPACE_BETWEEN) {
if (this.getFlexDirection() === Css.FlexDirections.ROW) {
cssNode.style.width = w;
}
else if (this.getFlexDirection() === Css.FlexDirections.COLUMN) {
cssNode.style.height = h;
}
else {
throw new Error("Unknown flexDirection!");
}
}
if (this.getFlexWrap() === Css.FlexWraps.WRAP) {
throw new Error("flexWrap=WRAP not implemented!");
}
cssNode.style.flexDirection = Css.enumStringToCssString(Css.FlexDirections[this.getFlexDirection()]);
cssNode.style.justifyContent = Css.enumStringToCssString(Css.Justifications[this.getJustifyContent()]);
cssNode.style.alignItems = Css.enumStringToCssString(Css.Alignments[this.getAlignItems()]);
cssNode.style.flexWrap = Css.enumStringToCssString(Css.FlexWraps[this.getFlexWrap()]);
// Add padding if we have a .bg and they supplied a padding. Ex:
// .bg padding: 2 0 2 0;
if (this.hasBg()) {
let bg = this.getBg();
let paddingRegex = /padding:\s?(\d+) (\d+) (\d+) (\d+);/;
if (paddingRegex.test(bg.name)) {
let matches = paddingRegex.exec(bg.name);
cssNode.style.paddingTop = parseFloat(matches[1]);
cssNode.style.paddingRight = parseFloat(matches[2]);
cssNode.style.paddingBottom = parseFloat(matches[3]);
cssNode.style.paddingLeft = parseFloat(matches[4]);
}
}
cssNode.children = [];
let blokChildren = this.getChildren();
blokChildren.forEach((blok) => {
let childCssNode = blok.computeCssNode();
// Clear a dim from the child if we're stretching and give ourself
// a fixed dimension. If even a single Blok child is set to stretch,
// the BlokContainer must layout with a fixed w/h, otherwise the Blok child
// has no defined container to stretch in
if (blok.getAlignSelf() === Css.Alignments.STRETCH ||
(this.getAlignItems() === Css.Alignments.STRETCH && blok.getAlignSelf() === undefined)) {
if (this.getFlexDirection() === Css.FlexDirections.ROW) {
cssNode.style.height = h;
childCssNode.style.height = undefined;
}
else if (this.getFlexDirection() === Css.FlexDirections.COLUMN) {
cssNode.style.width = w;
childCssNode.style.width = undefined;
}
else {
throw new Error("Unknown FlexDirections value: " + this.getFlexDirection());
}
}
if (blok.getFlex() !== undefined && blok.getFlex() > 0) {
if (this.getFlexDirection() === Css.FlexDirections.ROW) {
cssNode.style.width = w;
childCssNode.style.width = undefined;
}
else if (this.getFlexDirection() === Css.FlexDirections.COLUMN) {
cssNode.style.height = h;
childCssNode.style.height = undefined;
}
else {
throw new Error("Unknown FlexDirections value: " + this.getFlexDirection());
}
}
cssNode.children.push(childCssNode);
});
return cssNode;
}
/** Trigger a layout */
public /*override*/ invalidate(): void {
// Start at the root of our layout tree
let root = this.getRootContainer();
let rootNode = root.computeCssNode();
cssLayout(rootNode);
root.layout(undefined, rootNode);
}
public /*override*/ checkForRelayout(lastSelection: any): void {
let z = this.getZIndex();
let cachedZ = this.getCachedZIndex();
let isZIndexInvalid = cachedZ !== undefined && cachedZ !== z;
if (this.getCachedChildCount() !== this._pageItem.pageItems.length) {
// Short circut for new child count
this.invalidate();
}
else {
let rect = this.getRect();
let isWidthInvalid = !Utils.nearlyEqual(this.getCachedWidth(), rect.getWidth());
let isHeightInvalid = !Utils.nearlyEqual(this.getCachedHeight(), rect.getHeight());
if (isWidthInvalid || isHeightInvalid) {
let sel = app.activeDocument.selection;
if ((sel.length === 1 && sel[0] && sel[0] === this._pageItem) &&
(lastSelection.length === 1 && lastSelection[0] && lastSelection[0] === this._pageItem)) {
// If this was the only thing selected for the past 2 selections and our size changed in
// betwen selections, enable some ease-of-use scenarios that attempt to use the new size
// the user wants for the BlokContainer
// We already have the new size in rect. Now undo their change, our layout will take their
// desires into account. Also:
//
// Illustrator messes with CharacterAttributes size, leading, and horizontalScale
// when you scale a GroupItem that contains a TextFrameItem that is AREATEXT (Area Type).
// Attempting to fix those values is difficult, since a TextFrameItem can have many
// TextRanges, all with different settings. Rather than attempt to store/restore those
// values, we just undo the resize, but not before we record our new desired size.
app.undo();
this.setOverrideWidth(rect.getWidth());
this.setOverrideHeight(rect.getHeight());
this.invalidate();
}
else {
this.invalidate();
}
}
else {
if (isZIndexInvalid) {
// We are a Blok child that is at a new z
this.invalidate();
}
else {
// Check to see if one of our Blok children is out of order
let children = this.getChildren();
let shouldInvalidate = false;
for (let i = 0; i < children.length; i++) {
let child = children[i];
let childZ = child.getZIndex();
let cachedChildZ = child.getCachedZIndex();
if (cachedChildZ !== undefined && cachedChildZ != childZ) {
shouldInvalidate = true;
}
child.setCachedZIndex(childZ);
}
if (shouldInvalidate) {
this.invalidate();
}
}
}
}
// Update z index cache
this.setCachedZIndex(z);
}
/** A (possible) reference to the parent BlokContainer */
public /*override*/ getContainer(): BlokContainer {
let container = undefined;
try {
container = super.getContainer();
}
catch (ex) { /* It's OK if a BlokContainer isn't nested */ }
return container;
}
public /*override*/ getRootContainer(): BlokContainer {
let container = super.getRootContainer();
if (!container) {
container = this;
}
return container;
}
/** Get our current set of Blok children */
protected getChildren(): Blok[] {
// Update cache
this.setCachedChildCount(this._pageItem.pageItems.length);
// sync the order of our children with the reverse z-order or the pageItems
let sortedChildren: Blok[] = [];
// low z-index to high z-index
for (let i = this._pageItem.pageItems.length - 1; i >= 0; i--) {
let pageItem = this._pageItem.pageItems[i];
// Forego this check. Just convert all children, always
/*if (!Blok.isBlokAttached(pageItem)) {
throw new Error("We have non-Blok children?");
}*/
if (!Utils.isKeyInString(pageItem.name, ".bg")) {
// Check to see if this is a BlokContainer. We'll convert a normal groupItem if it has
// a specific name. This is mostly to keep test files easy to create
if (pageItem.name === "<BlokGroup>" ||
(pageItem.pageItems && BlokAdapter.isBlokContainerAttached(pageItem))) {
sortedChildren.push(BlokAdapter.getBlokContainer(pageItem));
}
else {
sortedChildren.push(BlokAdapter.getBlok(pageItem));
}
}
}
return sortedChildren;
}
/**
* PROTECTED: Resize and position all art in this group.
*
* @param desired - a rectangle for the new location and size. Possibly ignored
* depending on settings
* @param rootNode - a matching CSS node with full style and layout information
* @param skipScaleTransform - if true, don't perform any scale
*/
public /*override*/ layout(desired: Rect, rootNode: any, skipScaleTransform = false): void {
// Layout our children
let children = this.getChildren();
for (let i = 0; i < children.length; i++) {
let blok = children[i];
let node = rootNode.children[i];
// apply layout
let blokRect = blok.getRect();
blokRect.setX(node.layout.left);
blokRect.setY(node.layout.top);
blokRect.setWidth(node.layout.width);
blokRect.setHeight(node.layout.height);
blok.layout(blokRect, node);
}
// Layout the .bg
if (this.hasBg()) {
let bg = this.getBg();
// Hack, we shouldn't be calling the constructor directly, but it's an easy way to get the layout func
let bgBlok = new Blok(bg);
bgBlok.layout(
new Rect([0, 0, rootNode.layout.width, rootNode.layout.height]),
rootNode,
false,
true
);
}
if (desired) {
// Layout ourselves, but never ask a BlokContainer to scale as part of layout
super.layout(desired, undefined, true);
}
let curR = this.getRect();
this.setCachedWidth(curR.getWidth());
this.setCachedHeight(curR.getHeight());
}
/** Optional positive number for the number of Bloks this BlokContainer has */
private getCachedChildCount(): number {
return this.getSavedProperty<number>("cachedChildCount");
}
/** Optional positive number for the number of Bloks this BlokContainer has */
private setCachedChildCount(value: number): void {
if (value !== undefined && value < 0) {
throw new RangeError("Cannot set a negative cached child count!");
}
this.setSavedProperty<number>("cachedChildCount", value);
}
/** Optional positive number that should be used as the BlokContainer's width in place of the
real width */
private getOverrideWidth(): number {
return this.getSavedProperty<number>("overrideWidth");
}
/** Optional positive number that should be used as the BlokContainer's width in place of the
real width */
private setOverrideWidth(value: number): void {
if (value !== undefined && value < 0) {
throw new RangeError("Cannot set a negative override width!");
}
this.setSavedProperty<number>("overrideWidth", value);
}
/** Optional positive number that should be used as the BlokContainer's width in place of the
real height */
private getOverrideHeight(): number {
return this.getSavedProperty<number>("overrideHeight");
}
/** Optional positive number that should be used as the BlokContainer's width in place of the
real height */
private setOverrideHeight(value: number): void {
if (value !== undefined && value < 0) {
throw new RangeError("Cannot set a negative override height!");
}
this.setSavedProperty<number>("overrideHeight", value);
}
/** Check to see if this BlokGroup has a .bg layer at the bottom of z-order */
private hasBg(): boolean {
if (this._pageItem.pageItems.length > 0 &&
Utils.isKeyInString(this._pageItem.pageItems[this._pageItem.pageItems.length - 1].name, ".bg")) {
return true;
}
}
/** Get the .bg */
private getBg(): any {
if (this.hasBg()) {
return this._pageItem.pageItems[this._pageItem.pageItems.length - 1];
}
return undefined;
}
}
export = BlokContainer; | the_stack |
import {flipColDirection, parseSortColRefs} from 'app/client/lib/sortUtil';
import {reportError} from 'app/client/models/AppModel';
import {ColumnRec, DocModel, ViewFieldRec, ViewRec, ViewSectionRec} from 'app/client/models/DocModel';
import {CustomComputed} from 'app/client/models/modelUtil';
import {attachColumnFilterMenu} from 'app/client/ui/ColumnFilterMenu';
import {addFilterMenu} from 'app/client/ui/FilterBar';
import {hoverTooltip} from 'app/client/ui/tooltips';
import {makeViewLayoutMenu} from 'app/client/ui/ViewLayoutMenu';
import {basicButton, primaryButton} from 'app/client/ui2018/buttons';
import {colors, vars} from 'app/client/ui2018/cssVars';
import {icon} from 'app/client/ui2018/icons';
import {menu} from 'app/client/ui2018/menus';
import {Computed, dom, fromKo, IDisposableOwner, makeTestId, Observable, styled} from 'grainjs';
import difference = require('lodash/difference');
import {PopupControl} from 'popweasel';
const testId = makeTestId('test-section-menu-');
const TOOLTIP_DELAY_OPEN = 750;
async function doSave(docModel: DocModel, viewSection: ViewSectionRec): Promise<void> {
await docModel.docData.bundleActions("Update Sort&Filter settings", () => Promise.all([
viewSection.activeSortJson.save(), // Save sort
viewSection.saveFilters(), // Save filter
viewSection.activeFilterBar.save(), // Save bar
]));
}
function doRevert(viewSection: ViewSectionRec) {
viewSection.activeSortJson.revert(); // Revert sort
viewSection.revertFilters(); // Revert filter
viewSection.activeFilterBar.revert(); // Revert bar
}
export function viewSectionMenu(owner: IDisposableOwner, docModel: DocModel, viewSection: ViewSectionRec,
viewModel: ViewRec, isReadonly: Observable<boolean>) {
const popupControls = new WeakMap<ViewFieldRec, PopupControl>();
const anyFilter = Computed.create(owner, (use) => Boolean(use(viewSection.filteredFields).length));
const displaySaveObs: Computed<boolean> = Computed.create(owner, (use) => (
use(viewSection.filterSpecChanged)
|| !use(viewSection.activeSortJson.isSaved)
|| !use(viewSection.activeFilterBar.isSaved)
));
const save = () => { doSave(docModel, viewSection).catch(reportError); };
const revert = () => doRevert(viewSection);
return [
cssFilterMenuWrapper(
cssFixHeight.cls(''),
cssFilterMenuWrapper.cls('-unsaved', displaySaveObs),
testId('wrapper'),
cssMenu(
testId('sortAndFilter'),
cssFilterIconWrapper(
testId('filter-icon'),
cssFilterIconWrapper.cls('-any', anyFilter),
cssFilterIcon('Filter')
),
menu(ctl => [
dom.domComputed(use => {
use(viewSection.activeSortJson.isSaved); // Rebuild sort panel if sort gets saved. A little hacky.
return makeSortPanel(viewSection, use(viewSection.activeSortSpec),
(row: number) => docModel.columns.getRowModel(row));
}),
dom.domComputed(viewSection.filteredFields, fields =>
makeFilterPanel(viewSection, fields, popupControls, () => ctl.close())),
makeAddFilterButton(viewSection, popupControls),
makeFilterBarToggle(viewSection.activeFilterBar),
dom.domComputed(displaySaveObs, displaySave => [
displaySave ? cssMenuInfoHeader(
cssSaveButton('Save', testId('btn-save'),
dom.on('click', () => { save(); ctl.close(); }),
dom.boolAttr('disabled', isReadonly)),
basicButton('Revert', testId('btn-revert'),
dom.on('click', () => { revert(); ctl.close(); }))
) : null,
]),
]),
),
dom.maybe(displaySaveObs, () => cssSaveIconsWrapper(
cssSmallIconWrapper(
cssIcon('Tick'), cssSmallIconWrapper.cls('-green'),
dom.on('click', save),
hoverTooltip(() => 'Save', {key: 'sortFilterButton', openDelay: TOOLTIP_DELAY_OPEN}),
testId('small-btn-save'),
dom.hide(isReadonly),
),
cssSmallIconWrapper(
cssIcon('CrossSmall'), cssSmallIconWrapper.cls('-gray'),
dom.on('click', revert),
hoverTooltip(() => 'Revert', {key: 'sortFilterButton', openDelay: TOOLTIP_DELAY_OPEN}),
testId('small-btn-revert'),
),
)),
),
cssMenu(
testId('viewLayout'),
cssFixHeight.cls(''),
cssDotsIconWrapper(cssIcon('Dots')),
menu(_ctl => makeViewLayoutMenu(viewModel, viewSection, isReadonly.get()))
)
];
}
function makeSortPanel(section: ViewSectionRec, sortSpec: number[], getColumn: (row: number) => ColumnRec) {
const changedColumns = difference(sortSpec, parseSortColRefs(section.sortColRefs.peek()));
const sortColumns = sortSpec.map(colRef => {
// colRef is a rowId of a column or its negative value (indicating descending order).
const col = getColumn(Math.abs(colRef));
return cssMenuText(
cssMenuIconWrapper(
cssMenuIconWrapper.cls('-changed', changedColumns.includes(colRef)),
cssMenuIconWrapper.cls(colRef < 0 ? '-desc' : '-asc'),
cssIcon('Sort',
dom.style('transform', colRef < 0 ? 'none' : 'scaleY(-1)'),
dom.on('click', () => {
section.activeSortSpec(flipColDirection(sortSpec, colRef));
})
)
),
cssMenuTextLabel(col.colId()),
cssMenuIconWrapper(
cssIcon('Remove', testId('btn-remove-sort'), dom.on('click', () => {
const idx = sortSpec.findIndex(c => c === colRef);
if (idx !== -1) {
sortSpec.splice(idx, 1);
section.activeSortSpec(sortSpec);
}
}))
),
testId('sort-col')
);
});
return [
cssMenuInfoHeader('Sorted by', testId('heading-sorted')),
sortColumns.length > 0 ? sortColumns : cssGrayedMenuText('(Default)')
];
}
export function makeAddFilterButton(viewSectionRec: ViewSectionRec,
popupControls: WeakMap<ViewFieldRec, PopupControl>) {
return dom.domComputed((use) => {
const fields = use(use(viewSectionRec.viewFields).getObservable());
return cssMenuText(
cssMenuIconWrapper(
cssIcon('Plus'),
addFilterMenu(fields, popupControls, {
placement: 'bottom-end',
// Attach content to triggerElem's parent, which is needed to prevent view section menu to
// close when clicking an item of the add filter menu.
attach: null
}),
testId('plus-button'),
dom.on('click', (ev) => ev.stopPropagation()),
),
cssMenuTextLabel('Add Filter'),
);
});
}
export function makeFilterBarToggle(activeFilterBar: CustomComputed<boolean>) {
return cssMenuText(
cssMenuIconWrapper(
testId('btn'),
cssMenuIconWrapper.cls('-changed', (use) => !use(activeFilterBar.isSaved)),
dom.domComputed((use) => {
const filterBar = use(activeFilterBar);
const isSaved = use(activeFilterBar.isSaved);
return cssIcon(filterBar ? "Tick" : (isSaved ? "Plus" : "CrossSmall"),
cssIcon.cls('-green', Boolean(filterBar)),
testId('icon'));
}),
),
dom.on('click', () => activeFilterBar(!activeFilterBar.peek())),
cssMenuTextLabel("Toggle Filter Bar"),
);
}
function makeFilterPanel(section: ViewSectionRec, filteredFields: ViewFieldRec[],
popupControls: WeakMap<ViewFieldRec, PopupControl>,
onCloseContent: () => void) {
const fields = filteredFields.map(field => {
const fieldChanged = Computed.create(null, fromKo(field.activeFilter.isSaved), (_use, isSaved) => !isSaved);
return cssMenuText(
dom.autoDispose(fieldChanged),
cssMenuIconWrapper(
cssMenuIconWrapper.cls('-changed', fieldChanged),
cssIcon('FilterSimple'),
attachColumnFilterMenu(section, field, {
placement: 'bottom-end',
trigger: ['click', (_el, popupControl) => popupControls.set(field, popupControl)],
onCloseContent,
}),
testId('filter-icon'),
),
cssMenuTextLabel(field.label()),
cssMenuIconWrapper(cssIcon('Remove', testId('btn-remove-filter')), dom.on('click', () => field.activeFilter(''))),
testId('filter-col')
);
});
return [
cssMenuInfoHeader('Filtered by', {style: 'margin-top: 4px'}, testId('heading-filtered')),
filteredFields.length > 0 ? fields : cssGrayedMenuText('(Not filtered)')
];
}
const clsOldUI = styled('div', ``);
const cssFixHeight = styled('div', `
margin-top: -3px; /* Section header is 24px, so need to move this up a little bit */
`);
const cssMenu = styled('div', `
display: inline-flex;
cursor: pointer;
border-radius: 3px;
border: 1px solid transparent;
&.${clsOldUI.className} {
margin-top: 0px;
border-radius: 0px;
}
&:hover, &.weasel-popup-open {
background-color: ${colors.mediumGrey};
}
`);
const cssIconWrapper = styled('div', `
padding: 3px;
border-radius: 3px;
cursor: pointer;
user-select: none;
`);
const cssMenuIconWrapper = styled(cssIconWrapper, `
display: flex;
margin: -3px 0;
width: 22px;
height: 22px;
&:hover, &.weasel-popup-open {
background-color: ${colors.mediumGrey};
}
&-changed {
background-color: ${colors.lightGreen};
}
&-changed:hover, &-changed:hover.weasel-popup-open {
background-color: ${colors.darkGreen};
}
`);
const cssFilterMenuWrapper = styled('div', `
display: inline-flex;
margin-right: 10px;
border-radius: 3px;
align-items: center;
&-unsaved {
border: 1px solid ${colors.lightGreen};
}
& .${cssMenu.className} {
border: none;
}
`);
const cssIcon = styled(icon, `
flex: none;
cursor: pointer;
background-color: ${colors.slate};
.${cssMenuIconWrapper.className}-changed & {
background-color: white;
}
.${clsOldUI.className} & {
background-color: white;
}
&-green {
background-color: ${colors.lightGreen};
}
`);
const cssDotsIconWrapper = styled(cssIconWrapper, `
border-radius: 0px 2px 2px 0px;
.${clsOldUI.className} & {
border-radius: 0px;
}
`);
const cssFilterIconWrapper = styled(cssIconWrapper, `
border-radius: 2px 0px 0px 2px;
.${cssFilterMenuWrapper.className}-unsaved & {
background-color: ${colors.lightGreen};
}
`);
const cssFilterIcon = styled(cssIcon, `
.${cssFilterIconWrapper.className}-any & {
background-color: ${colors.lightGreen};
}
.${cssFilterMenuWrapper.className}-unsaved & {
background-color: white;
}
`);
const cssMenuInfoHeader = styled('div', `
font-weight: ${vars.bigControlTextWeight};
padding: 8px 24px 8px 24px;
cursor: default;
`);
const cssMenuText = styled('div', `
display: flex;
align-items: center;
padding: 0px 24px 8px 24px;
cursor: default;
white-space: nowrap;
`);
const cssGrayedMenuText = styled(cssMenuText, `
color: ${colors.slate};
padding-left: 24px;
`);
const cssMenuTextLabel = styled('span', `
flex-grow: 1;
padding: 0 4px;
overflow: hidden;
text-overflow: ellipsis;
`);
const cssSaveButton = styled(primaryButton, `
margin-right: 8px;
`);
const cssSmallIconWrapper = styled('div', `
width: 16px;
height: 16px;
border-radius: 8px;
margin: 0 5px 0 5px;
&-green {
background-color: ${colors.lightGreen};
}
&-gray {
background-color: ${colors.slate};
}
& > .${cssIcon.className} {
background-color: white;
}
`);
const cssSaveIconsWrapper = styled('div', `
padding: 0 1px 0 1px;
display: flex;
justify-content: space-between;
`); | the_stack |
import Backburner from 'backburner';
import lolex from 'lolex';
const DATE_NOW = Date.now;
let fakeClock;
QUnit.module('tests/debounce', {
afterEach() {
if (fakeClock) {
fakeClock.uninstall();
}
}
});
QUnit.test('debounce', function(assert) {
assert.expect(14);
let bb = new Backburner(['zomg']);
let step = 0;
let done = assert.async();
let wasCalled = false;
function debouncee() {
assert.ok(!wasCalled);
wasCalled = true;
}
// let's debounce the function `debouncee` for 40ms
// it will be executed 40ms after
bb.debounce(null, debouncee, 40);
assert.equal(step++, 0);
// let's schedule `debouncee` to run in 10ms
setTimeout(() => {
assert.equal(step++, 1);
assert.ok(!wasCalled, '@10ms, should not yet have been called');
bb.debounce(null, debouncee, 40);
}, 10);
// let's schedule `debouncee` to run again in 30ms
setTimeout(() => {
assert.equal(step++, 2);
assert.ok(!wasCalled, '@ 30ms, should not yet have been called');
bb.debounce(null, debouncee, 40);
}, 30);
// let's schedule `debouncee` to run yet again in 60ms
setTimeout(() => {
assert.equal(step++, 3);
assert.ok(!wasCalled, '@ 60ms, should not yet have been called');
bb.debounce(null, debouncee, 40);
}, 60);
// now, let's schedule an assertion to occur at 110ms,
// 10ms after `debouncee` has been called the last time
setTimeout(() => {
assert.equal(step++, 4);
assert.ok(wasCalled, '@ 110ms should have been called');
}, 110);
// great, we've made it this far, there's one more thing
// we need to test. we want to make sure we can call `debounce`
// again with the same target/method after it has executed
// at the 120ms mark, let's schedule another call to `debounce`
setTimeout(() => {
wasCalled = false; // reset the flag
// assert call order
assert.equal(step++, 5);
// call debounce for the second time
bb.debounce(null, debouncee, 100);
// assert that it is called in the future and not blackholed
setTimeout(() => {
assert.equal(step++, 6);
assert.ok(wasCalled, 'Another debounce call with the same function can be executed later');
done();
}, 230);
}, 120);
});
QUnit.test('debounce - immediate', function(assert) {
assert.expect(16);
let done = assert.async();
let bb = new Backburner(['zomg']);
let step = 0;
let wasCalled = false;
function debouncee() {
assert.ok(!wasCalled);
wasCalled = true;
}
// let's debounce the function `debouncee` for 40ms
// it will be executed immediately, and prevent
// any actions for 40ms after
bb.debounce(null, debouncee, 40, true);
assert.equal(step++, 0);
assert.ok(wasCalled);
wasCalled = false;
// let's schedule `debouncee` to run in 10ms
setTimeout(() => {
assert.equal(step++, 1);
assert.ok(!wasCalled);
bb.debounce(null, debouncee, 40, true);
}, 10);
// let's schedule `debouncee` to run again in 30ms
setTimeout(() => {
assert.equal(step++, 2);
assert.ok(!wasCalled);
bb.debounce(null, debouncee, 40, true);
}, 30);
// let's schedule `debouncee` to run yet again in 60ms
setTimeout(() => {
assert.equal(step++, 3);
assert.ok(!wasCalled);
bb.debounce(null, debouncee, 40, true);
}, 60);
// now, let's schedule an assertion to occur at 110ms,
// 10ms after `debouncee` has been called the last time
setTimeout(() => {
assert.equal(step++, 4);
assert.ok(!wasCalled);
}, 110);
// great, we've made it this far, there's one more thing
// we need to QUnit.test. we want to make sure we can call `debounce`
// again with the same target/method after it has executed
// at the 120ms mark, let's schedule another call to `debounce`
setTimeout(() => {
wasCalled = false; // reset the flag
// assert call order
assert.equal(step++, 5);
// call debounce for the second time
bb.debounce(null, debouncee, 100, true);
assert.ok(wasCalled, 'Another debounce call with the same function can be executed later');
wasCalled = false;
// assert that it is called in the future and not blackholed
setTimeout(() => {
assert.equal(step++, 6);
assert.ok(!wasCalled);
done();
}, 230);
}, 120);
});
QUnit.test('debounce + immediate joins existing run loop instances', function(assert) {
assert.expect(1);
function onError(error) {
throw error;
}
let bb = new Backburner(['errors'], {
onError: onError
});
bb.run(() => {
let parentInstance = bb.currentInstance;
bb.debounce(null, () => {
assert.equal(bb.currentInstance, parentInstance);
}, 20, true);
});
});
QUnit.test('debounce accept time interval like string numbers', function(assert) {
let done = assert.async();
let bb = new Backburner(['zomg']);
let step = 0;
let wasCalled = false;
function debouncee() {
assert.ok(!wasCalled);
wasCalled = true;
}
bb.debounce(null, debouncee, '40');
assert.equal(step++, 0);
setTimeout(() => {
assert.equal(step++, 1);
assert.ok(!wasCalled);
bb.debounce(null, debouncee, '40');
}, 10);
setTimeout(() => {
assert.equal(step++, 2);
assert.ok(wasCalled);
done();
}, 60);
});
QUnit.test('debounce returns timer information usable for canceling', function(assert) {
assert.expect(3);
let done = assert.async();
let bb = new Backburner(['batman']);
let wasCalled = false;
function debouncee() {
assert.ok(false, 'this method shouldn\'t be called');
wasCalled = true;
}
let timer = bb.debounce(null, debouncee, 1);
assert.ok(bb.cancel(timer), 'the timer is cancelled');
// should return false second time around
assert.ok(!bb.cancel(timer), 'the timer no longer exists in the list');
setTimeout(() => {
assert.ok(!wasCalled, 'the timer wasn\'t called after waiting');
done();
}, 60);
});
QUnit.test('debounce cancelled after it\'s executed returns false', function(assert) {
assert.expect(3);
let done = assert.async();
let bb = new Backburner(['darkknight']);
let wasCalled = false;
function debouncee() {
assert.ok(true, 'the debounced method was called');
wasCalled = true;
}
let timer = bb.debounce(null, debouncee, 1);
setTimeout(() => {
assert.ok(!bb.cancel(timer), 'no timer existed to cancel');
assert.ok(wasCalled, 'the timer was actually called');
done();
}, 10);
});
QUnit.test('debounced function is called with final argument', function(assert) {
assert.expect(1);
let done = assert.async();
let bb = new Backburner(['joker']);
function debouncee(arg) {
assert.equal('bus', arg, 'the debounced is called with right argument');
done();
}
bb.debounce(null, debouncee, 'car', 10);
bb.debounce(null, debouncee, 'bicycle', 10);
bb.debounce(null, debouncee, 'bus', 10);
});
QUnit.test('debounce cancelled doesn\'t cancel older items', function(assert) {
assert.expect(4);
let bb = new Backburner(['robin']);
let wasCalled = false;
let done = assert.async();
function debouncee() {
assert.ok(true, 'the debounced method was called');
if (wasCalled) {
done();
}
wasCalled = true;
}
let timer = bb.debounce(null, debouncee, 1);
setTimeout(() => {
bb.debounce(null, debouncee, 1);
assert.ok(!bb.cancel(timer), 'the second timer isn\'t removed, despite appearing to be the same');
assert.ok(wasCalled, 'the timer was actually called');
}, 10);
});
QUnit.test('debounce that is immediate, and cancelled and called again happens immediately', function(assert) {
assert.expect(3);
let done = assert.async();
let bb = new Backburner(['robin']);
let calledCount = 0;
function debouncee() {
calledCount++;
}
let timer = bb.debounce(null, debouncee, 1000, true);
setTimeout(() => { // 10 millisecond delay
assert.equal(1, calledCount, 'debounced method was called');
assert.ok(bb.cancel(timer), 'debounced delay was cancelled');
bb.debounce(null, debouncee, 1000, true);
setTimeout(() => { // 10 millisecond delay
assert.equal(2, calledCount, 'debounced method was called again immediately');
done();
}, 10);
}, 10);
});
QUnit.test('debounce without a target, without args', function(assert) {
let done = assert.async();
let bb = new Backburner(['batman']);
let calledCount = 0;
let calledWith = new Array();
function debouncee(...args) {
calledCount++;
calledWith.push(args);
}
bb.debounce(debouncee, 10);
bb.debounce(debouncee, 10);
bb.debounce(debouncee, 10);
assert.equal(calledCount, 0, 'debounced method was not called immediately');
setTimeout(() => {
assert.equal(calledCount, 0, 'debounced method was not called on next tick');
}, 0);
setTimeout(() => {
assert.equal(calledCount, 1, 'debounced method was was only called once');
assert.deepEqual(calledWith, [ [] ], 'debounce called once without arguments');
done();
}, 20);
});
QUnit.test('debounce without a target, without args - can be canceled', function(assert) {
let done = assert.async();
let bb = new Backburner(['batman']);
let calledCount = 0;
function debouncee() {
calledCount++;
}
bb.debounce(debouncee, 10);
bb.debounce(debouncee, 10);
let timer = bb.debounce(debouncee, 10);
assert.equal(calledCount, 0, 'debounced method was not called immediately');
setTimeout(() => {
bb.cancel(timer);
assert.equal(calledCount, 0, 'debounced method was not called on next tick');
}, 0);
setTimeout(() => {
assert.equal(calledCount, 0, 'debounced method was canceled properly');
done();
}, 20);
});
QUnit.test('debounce without a target, without args, immediate', function(assert) {
let done = assert.async();
let bb = new Backburner(['batman']);
let calledCount = 0;
let calledWith = new Array();
function debouncee(...args) {
calledCount++;
calledWith.push(args);
}
bb.debounce(debouncee, 10, true);
bb.debounce(debouncee, 10, true);
bb.debounce(debouncee, 10, true);
assert.equal(calledCount, 1, 'debounced method was called immediately');
assert.deepEqual(calledWith, [ [] ], 'debounce method was called with the correct arguments');
setTimeout(() => {
bb.debounce(debouncee, 10, true);
assert.equal(calledCount, 1, 'debounced method was not called again within the time window');
}, 0);
setTimeout(() => {
assert.equal(calledCount, 1, 'debounced method was was only called once');
done();
}, 20);
});
QUnit.test('debounce without a target, without args, immediate - can be canceled', function(assert) {
let bb = new Backburner(['batman']);
let fooCalledCount = 0;
let barCalledCount = 0;
function foo() {
fooCalledCount++;
}
function bar() {
barCalledCount++;
}
bb.debounce(foo, 10, true);
bb.debounce(foo, 10, true);
assert.equal(fooCalledCount, 1, 'foo was called immediately, then debounced');
bb.debounce(bar, 10, true);
let timer = bb.debounce(bar, 10, true);
assert.equal(barCalledCount, 1, 'bar was called immediately, then debounced');
bb.cancel(timer);
bb.debounce(bar, 10, true);
assert.equal(barCalledCount, 2, 'after canceling the prior debounce, bar was called again');
});
QUnit.test('debounce without a target, with args', function(assert) {
let done = assert.async();
let bb = new Backburner(['batman']);
let calledCount = 0;
let calledWith: object[] = [];
function debouncee(first) {
calledCount++;
calledWith.push(first);
}
let foo = { isFoo: true };
let bar = { isBar: true };
let baz = { isBaz: true };
bb.debounce(debouncee, foo, 10);
bb.debounce(debouncee, bar, 10);
bb.debounce(debouncee, baz, 10);
assert.equal(calledCount, 0, 'debounced method was not called immediately');
setTimeout(() => {
assert.deepEqual(calledWith, [{ isBaz: true }], 'debounce method was only called once, with correct argument');
done();
}, 20);
});
QUnit.test('debounce without a target, with args - can be canceled', function(assert) {
let done = assert.async();
let bb = new Backburner(['batman']);
let calledCount = 0;
let calledWith: object[] = [];
function debouncee(first) {
calledCount++;
calledWith.push(first);
}
let foo = { isFoo: true };
let bar = { isBar: true };
let baz = { isBaz: true };
bb.debounce(debouncee, foo, 10);
bb.debounce(debouncee, bar, 10);
let timer = bb.debounce(debouncee, baz, 10);
assert.equal(calledCount, 0, 'debounced method was not called immediately');
setTimeout(() => {
assert.deepEqual(calledWith, [], 'debounce method has not been called on next tick');
bb.cancel(timer);
}, 0);
setTimeout(() => {
assert.deepEqual(calledWith, [], 'debounce method is not called when canceled');
done();
}, 20);
});
QUnit.test('debounce without a target, with args, immediate', function(assert) {
let done = assert.async();
let bb = new Backburner(['batman']);
let calledCount = 0;
let calledWith = new Array();
function debouncee(first) {
calledCount++;
calledWith.push(first);
}
let foo = { isFoo: true };
let bar = { isBar: true };
let baz = { isBaz: true };
let qux = { isQux: true };
bb.debounce(debouncee, foo, 10, true);
bb.debounce(debouncee, bar, 10, true);
bb.debounce(debouncee, baz, 10, true);
assert.deepEqual(calledWith, [{ isFoo: true }], 'debounce method was only called once, with correct argument');
setTimeout(() => {
bb.debounce(debouncee, qux, 10, true);
assert.deepEqual(calledWith, [{ isFoo: true }], 'debounce method was only called once, with correct argument');
}, 0);
setTimeout(() => {
assert.deepEqual(calledWith, [{ isFoo: true }], 'debounce method was only called once, with correct argument');
done();
}, 20);
});
QUnit.test('debounce without a target, with args, immediate - can be canceled', function(assert) {
let done = assert.async();
let bb = new Backburner(['batman']);
let calledCount = 0;
let calledWith: object[] = [];
function debouncee(first) {
calledCount++;
calledWith.push(first);
}
let foo = { isFoo: true };
let bar = { isBar: true };
let baz = { isBaz: true };
let qux = { isQux: true };
bb.debounce(debouncee, foo, 10, true);
bb.debounce(debouncee, bar, 10, true);
let timer = bb.debounce(debouncee, baz, 10, true);
assert.deepEqual(calledWith, [{ isFoo: true }], 'debounce method was only called once, with correct argument');
setTimeout(() => {
bb.cancel(timer);
bb.debounce(debouncee, qux, 10, true);
assert.deepEqual(calledWith, [{ isFoo: true }, { isQux: true }], 'debounce method was called again after canceling prior timer');
}, 0);
setTimeout(() => {
assert.deepEqual(calledWith, [{ isFoo: true }, { isQux: true }], 'debounce method was not called again');
done();
}, 20);
});
QUnit.test('onError', function(assert) {
assert.expect(1);
let done = assert.async();
function onError(error) {
assert.equal('QUnit.test error', error.message);
done();
}
let bb = new Backburner(['errors'], {
onError
});
bb.debounce(null, () => { throw new Error('QUnit.test error'); }, 20);
});
QUnit.test('debounce within a debounce can be canceled GH#183', function(assert) {
assert.expect(3);
let done = assert.async();
let bb = new Backburner(['zomg']);
let foo = () => {
assert.ok(true, 'foo called');
return bb.debounce(bar, 10);
};
let bar = () => {
assert.ok(true, 'bar called');
let timer = foo();
bb.cancel(timer);
setTimeout(done, 10);
};
foo();
});
QUnit.test('when [callback, string] args passed', function(assert) {
assert.expect(2);
let bb = new Backburner(['one']);
let functionWasCalled = false;
bb.run(() => {
bb.debounce(function(name) {
assert.equal(name, 'batman');
functionWasCalled = true;
}, 'batman', 100, true);
});
assert.ok(functionWasCalled, 'function was called');
});
QUnit.test('can be ran "early" with fake timers GH#351', function(assert) {
assert.expect(1);
let done = assert.async();
let bb = new Backburner(['one']);
fakeClock = lolex.install();
let startTime = DATE_NOW();
bb.debounce(() => {
let endTime = DATE_NOW();
assert.ok(endTime - startTime < 100, 'executed in less than 5000ms');
done();
}, 5000);
fakeClock.tick(5001);
}); | the_stack |
/// <reference types="chrome"/>
/// <reference types="filesystem"/>
////////////////////
// App
////////////////////
declare namespace chrome.app {
export interface AppDetails extends chrome.runtime.Manifest {
id: string;
}
export function getDetails(): AppDetails;
}
////////////////////
// App Runtime
////////////////////
declare namespace chrome.app.runtime {
enum LaunchSource {
"untracked" = "untracked",
"app_launcher" = "app_launcher",
"new_tab_page" = "new_tab_page",
"reload" = "reload",
"restart" = "restart",
"load_and_launch" = "load_and_launch",
"command_line" = "command_line",
"file_handler" = "file_handler",
"url_handler" = "url_handler",
"system_tray" = "system_tray",
"about_page" = "about_page",
"keyboard" = "keyboard",
"extensions_page" = "extensions_page",
"management_api" = "management_api",
"ephemeral_app" = "ephemeral_app",
"background" = "background",
"kiosk" = "kiosk",
"chrome_internal" = "chrome_internal",
"test" = "test",
"installed_notification" = "installed_notification",
"context_menu" = "context_menu",
}
interface LaunchData {
id?: string;
items?: LaunchDataItem[];
url?: string;
referrerUrl?: string;
isKioskSession?: boolean;
isPublicSession?: boolean;
source?: LaunchSource;
actionData?: {};
}
export interface LaunchDataItem {
entry: FileEntry;
type: string;
}
export interface LaunchedEvent extends chrome.events.Event<(launchData: LaunchData) => void> { }
export interface RestartedEvent extends chrome.events.Event<() => void> { }
export var onLaunched: LaunchedEvent;
export var onRestarted: RestartedEvent;
}
////////////////////
// App Window
////////////////////
declare namespace chrome.app.window {
export interface ContentBounds {
left?: number;
top?: number;
width?: number;
height?: number;
}
export interface BoundsSpecification {
left?: number;
top?: number;
width?: number;
height?: number;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
}
export interface Bounds {
left: number;
top: number;
width: number;
height: number;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
setPosition(left: number, top: number): void;
setSize(width: number, height: number): void;
setMinimumSize(minWidth: number, minHeight: number): void;
setMaximumSize(maxWidth: number, maxHeight: number): void;
}
export interface FrameOptions {
type?: string;
color?: string;
activeColor?: string;
inactiveColor?: string;
}
export interface CreateWindowOptions {
id?: string;
innerBounds?: BoundsSpecification;
outerBounds?: BoundsSpecification;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
/**
* @description
* @type {(string | FrameOptions)} string ("none", "chrome") or FrameOptions
* @memberof CreateWindowOptions
*/
frame?: string | FrameOptions;
bounds?: ContentBounds;
alphaEnabled?: boolean;
/**
* @description
* @type {string} "normal", "fullscreen", "maximized", "minimized"
* @memberof CreateWindowOptions
*/
state?: string;
hidden?: boolean;
resizable?: boolean;
singleton?: boolean;
alwaysOnTop?: boolean;
focused?: boolean;
visibleOnAllWorkspaces?: boolean;
}
export interface AppWindow {
focus: () => void;
fullscreen: () => void;
isFullscreen: () => boolean;
minimize: () => void;
isMinimized: () => boolean;
maximize: () => void;
isMaximized: () => boolean;
restore: () => void;
moveTo: (left: number, top: number) => void;
resizeTo: (width: number, height: number) => void;
drawAttention: () => void;
clearAttention: () => void;
close: () => void;
show: () => void;
hide: () => void;
getBounds: () => ContentBounds;
setBounds: (bounds: ContentBounds) => void;
isAlwaysOnTop: () => boolean;
setAlwaysOnTop: (alwaysOnTop: boolean) => void;
setVisibleOnAllWorkspaces: (alwaysVisible: boolean) => void;
contentWindow: Window;
id: string;
innerBounds: Bounds;
outerBounds: Bounds;
onBoundsChanged: WindowEvent;
onClosed: WindowEvent;
onFullscreened: WindowEvent;
onMaximized: WindowEvent;
onMinimized: WindowEvent;
onRestored: WindowEvent;
}
export function create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void;
export function current(): AppWindow;
export function get(id: string): AppWindow;
export function getAll(): AppWindow[];
export function canSetVisibleOnAllWorkspaces(): boolean;
export interface WindowEvent extends chrome.events.Event<() => void> { }
export var onBoundsChanged: WindowEvent;
export var onClosed: WindowEvent;
export var onFullscreened: WindowEvent;
export var onMaximized: WindowEvent;
export var onMinimized: WindowEvent;
export var onRestored: WindowEvent;
}
////////////////////
// fileSystem
////////////////////
declare namespace chrome.fileSystem {
export interface AcceptOptions {
description?: string;
mimeTypes?: string[];
extensions?: string[];
}
export interface ChooseEntryOptions {
type?: string;
suggestedName?: string;
accepts?: AcceptOptions[];
acceptsAllTypes?: boolean;
acceptsMultiple?: boolean;
}
export function getDisplayPath(entry: Entry, callback: (displayPath: string) => void): void;
export function getWritableEntry(entry: Entry, callback: (entry: Entry) => void): void;
export function isWritableEntry(entry: Entry, callback: (isWritable: boolean) => void): void;
export function chooseEntry(callback: (entry: Entry) => void): void;
export function chooseEntry(callback: (fileEntries: FileEntry[]) => void): void;
export function chooseEntry(options: ChooseEntryOptions, callback: (entry: Entry) => void): void;
export function chooseEntry(options: ChooseEntryOptions, callback: (fileEntries: FileEntry[]) => void): void;
export function restoreEntry(id: string, callback: (entry: Entry) => void): void;
export function isRestorable(id: string, callback: (isRestorable: boolean) => void): void;
export function retainEntry(entry: Entry): string;
}
////////////////////
// Media Galleries
////////////////////
declare namespace chrome.mediaGalleries {
export interface MediaFileSystemsOptions {
interactive?: 'no' | 'yes' | 'if_needed';
}
export interface MediaFileSystemMetadata {
name: string;
galleryId: string;
deviceId?: string;
isRemovable: boolean;
isMediaDevice: boolean;
isAvailable: boolean;
}
export interface MetadataOptions {
metadataType: 'all' | 'mimeTypeAndTags' | 'mimeTypeOnly';
}
export interface RawTag {
type: string;
tags: { [name: string]: string; };
}
export interface Metadata {
// The browser sniffed mime type.
mimeType: string;
// Defined for images and video. In pixels.
height?: number;
width?: number;
// Defined for images only.
xResolution?: number;
yResolution?: number;
// Defined for audio and video. In seconds.
duration?: number;
// Defined for images and video. In degrees.
rotation?: number;
// Defined for images only.
cameraMake?: string;
cameraModel?: string;
exposureTimeSeconds?: number;
flashFired?: boolean;
fNumber?: number;
focalLengthMm?: number;
isoEquivalent?: number;
// Defined for audio and video only.
album?: string;
artist?: string;
comment?: string;
copyright?: string;
disc?: number;
genre?: string;
language?: string;
title?: string;
track?: number;
// All the metadata in the media file. For formats with multiple streams, stream order will be preserved. Container metadata is the first element.
rawTags: RawTag[];
// The images embedded in the media file's metadata. This is most often used for album art or video thumbnails.
attachedImages: Blob[];
}
export interface GalleryWatchResult {
galleryId: string;
success: boolean;
}
export interface GalleryChangedEventArgs {
type: 'contents_changed' | 'watch_dropped';
galleryId: string;
}
export interface ScanProgressEventArgs {
// The type of progress event, i.e. start, finish, etc.
type: 'start' | 'cancel' | 'finish' | 'error';
// The number of Galleries found.
galleryCount?: number;
// Appoximate number of media files found; some file types can be either audio or video and are included in both counts.
audioCount?: number;
imageCount?: number;
videoCount?: number;
}
export function getMediaFileSystems(callback: (mediaFileSystems: FileSystem[]) => void): void;
export function getMediaFileSystems(options: MediaFileSystemsOptions, callback: (mediaFileSystems: FileSystem[]) => void): void;
export function addUserSelectedFolder(callback: (mediaFileSystems: FileSystem[], selectedFileSystemName: string) => void): void;
export function dropPermissionForMediaFileSystem(galleryId: string, callback?: () => void): void;
export function startMediaScan(): void;
export function cancelMediaScan(): void;
export function addScanResults(callback: (mediaFileSystems: FileSystem[]) => void): void;
export function getMediaFileSystemMetadata(mediaFileSystem: FileSystem): MediaFileSystemMetadata;
export function getAllMediaFileSystemMetadata(callback: (metadatas: MediaFileSystemMetadata[]) => void): void;
export function getMetadata(mediaFile: Blob, callback: (metadata: Metadata) => void): void;
export function getMetadata(mediaFile: Blob, options: MetadataOptions, callback: (metadata: Metadata) => void): void;
export function addGalleryWatch(galleryId: string, callback: (result: GalleryWatchResult) => void): void;
export function removeGalleryWatch(galleryId: string): void;
export function getAllGalleryWatch(callback: (galleryIds: string[]) => void): void;
export function removeAllGalleryWatch(): void;
export var onGalleryChanged: chrome.events.Event<(args: GalleryChangedEventArgs) => void>;
export var onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>;
}
////////////////////
// Sockets
////////////////////
declare namespace chrome.sockets.tcp {
export interface CreateInfo {
socketId: number;
}
export interface SendInfo {
resultCode: number;
bytesSent?: number;
}
export interface ReceiveEventArgs {
socketId: number;
data: ArrayBuffer;
}
export interface ReceiveErrorEventArgs {
socketId: number;
resultCode: number;
}
export interface SocketProperties {
persistent?: boolean;
name?: string;
bufferSize?: number;
}
export interface SocketInfo {
socketId: number;
persistent: boolean;
name?: string;
bufferSize?: number;
paused: boolean;
connected: boolean;
localAddress?: string;
localPort?: number;
peerAddress?: string;
peerPort?: number;
}
export function create(callback: (createInfo: CreateInfo) => void): void;
export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void;
export function update(socketId: number, properties: SocketProperties, callback?: () => void): void;
export function setPaused(socketId: number, paused: boolean, callback?: () => void): void;
export function setKeepAlive(socketId: number,
enable: boolean, callback: (result: number) => void): void;
export function setKeepAlive(socketId: number,
enable: boolean, delay: number, callback: (result: number) => void): void;
export function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void;
export function connect(socketId: number,
peerAddress: string, peerPort: number, callback: (result: number) => void): void;
export function disconnect(socketId: number, callback?: () => void): void;
export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void;
export function close(socketId: number, callback?: () => void): void;
export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void;
export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void;
export var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>;
export var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>;
}
/**
* Use the chrome.sockets.udp API to send and receive data over the network
* using UDP connections. This API supersedes the UDP functionality previously
* found in the "socket" API.
*
* @since Chrome 33
* @see https://developer.chrome.com/apps/sockets_udp
*/
declare namespace chrome.sockets.udp {
export interface CreateInfo {
socketId: number;
}
export interface SendInfo {
resultCode: number;
bytesSent?: number;
}
export interface ReceiveEventArgs {
socketId: number;
data: ArrayBuffer;
remoteAddress: string;
remotePort: number;
}
export interface ReceiveErrorEventArgs {
socketId: number;
resultCode: number;
}
/**
* @see https://developer.chrome.com/apps/sockets_udp#type-SocketProperties
*/
export interface SocketProperties {
/**
* Flag indicating if the socket is left open when the event page of the
* application is unloaded. The default value is "false." When the
* application is loaded, any sockets previously opened with
* persistent=true can be fetched with getSockets.
* @see http://developer.chrome.com/apps/app_lifecycle.html
*/
persistent?: boolean;
/** An application-defined string associated with the socket. */
name?: string;
/**
* The size of the buffer used to receive data. If the buffer is too
* small to receive the UDP packet, data is lost. The default value is
* 4096.
*/
bufferSize?: number;
}
/**
* @see https://developer.chrome.com/apps/sockets_udp#type-SocketInfo
*/
export interface SocketInfo {
/** The socket identifier. */
socketId: number;
/**
* Flag indicating whether the socket is left open when the application
* is suspended (see SocketProperties.persistent).
*/
persistent: boolean;
/** Application-defined string associated with the socket. */
name?: string;
/**
* The size of the buffer used to receive data. If no buffer size ha
* been specified explictly, the value is not provided.
*/
bufferSize?: number;
/**
* Flag indicating whether the socket is blocked from firing onReceive
* events.
*/
paused: boolean;
/**
* If the underlying socket is bound, contains its local IPv4/6 address.
*/
localAddress?: string;
/**
* If the underlying socket is bound, contains its local port.
*/
localPort?: number;
}
/**
* Creates a UDP socket with default properties.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-create
* @param createInfo.socketId The ID of the newly created socket.
*/
export function create(callback: (createInfo: CreateInfo) => void): void;
/**
* Creates a UDP socket with the given properties.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-create
* @param properties The socket properties.
* @param createInfo.socketId The ID of the newly created socket.
*/
export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void;
/**
* Updates the socket properties.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-update
* @param socketId The socket ID.
* @param properties The properties to update.
* @param callback Called when the properties are updated.
*/
export function update(socketId: number, properties: SocketProperties, callback?: () => void): void;
/**
* Pauses or unpauses a socket. A paused socket is blocked from firing
* onReceive events.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-setPaused
* @param socketId The socket ID.
* @param paused Flag to indicate whether to pause or unpause.
* @param callback Called when the socket has been successfully paused or
* unpaused.
*/
export function setPaused(socketId: number, paused: boolean, callback?: () => void): void;
/**
* Binds the local address and port for the socket. For a client socket, it
* is recommended to use port 0 to let the platform pick a free port.
*
* Once the bind operation completes successfully, onReceive events are
* raised when UDP packets arrive on the address/port specified -- unless
* the socket is paused.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-bind
* @param socketId The socket ID.
* @param address The address of the local machine. DNS name, IPv4 and IPv6
* formats are supported. Use "0.0.0.0" to accept packets
* from all local available network interfaces.
* @param port The port of the local machine. Use "0" to bind to a free
* port.
* @param callback Called when the bind operation completes.
*/
export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void;
/**
* Sends data on the given socket to the given address and port. The socket
* must be bound to a local port before calling this method.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-send
* @param socketId The socket ID.
* @param data The data to send.
* @param address The address of the remote machine.
* @param port The port of the remote machine.
* @param callback Called when the send operation completes.
*/
export function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void;
/**
* Closes the socket and releases the address/port the socket is bound to.
* Each socket created should be closed after use. The socket id is no
* longer valid as soon at the function is called. However, the socket is
* guaranteed to be closed only when the callback is invoked.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-close
* @param socketId The socket ID.
* @param callback Called when the close operation completes.
*/
export function close(socketId: number, callback?: () => void): void;
/**
* Retrieves the state of the given socket.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-getInfo
* @param socketId The socket ID.
* @param callback Called when the socket state is available.
*/
export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void;
/**
* Retrieves the list of currently opened sockets owned by the application.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-getSockets
* @param callback Called when the list of sockets is available.
*/
export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void;
/**
* Joins the multicast group and starts to receive packets from that group.
* The socket must be bound to a local port before calling this method.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-joinGroup
* @param socketId The socket ID.
* @param address The group address to join. Domain names are not supported.
* @param callback Called when the joinGroup operation completes.
*/
export function joinGroup(socketId: number, address: string, callback: (result: number) => void): void;
/**
* Leaves the multicast group previously joined using joinGroup. This is
* only necessary to call if you plan to keep using the socket afterwards,
* since it will be done automatically by the OS when the socket is closed.
*
* Leaving the group will prevent the router from sending multicast
* datagrams to the local host, presuming no other process on the host is
* still joined to the group.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-leaveGroup
* @param socketId The socket ID.
* @param address The group address to leave. Domain names are not
* supported.
* @param callback Called when the leaveGroup operation completes.
*/
export function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void;
/**
* Sets the time-to-live of multicast packets sent to the multicast group.
*
* Calling this method does not require multicast permissions.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-setMulticastTimeToLive
* @param socketId The socket ID.
* @param ttl The time-to-live value.
* @param callback Called when the configuration operation completes.
*/
export function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void;
/**
* Sets whether multicast packets sent from the host to the multicast group
* will be looped back to the host.
*
* Note: the behavior of setMulticastLoopbackMode is slightly different
* between Windows and Unix-like systems. The inconsistency happens only
* when there is more than one application on the same host joined to the
* same multicast group while having different settings on multicast
* loopback mode. On Windows, the applications with loopback off will not
* RECEIVE the loopback packets; while on Unix-like systems, the
* applications with loopback off will not SEND the loopback packets to
* other applications on the same host.
* @see MSDN: http://goo.gl/6vqbj
*
* Calling this method does not require multicast permissions.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-setMulticastLoopbackMode
* @param socketId The socket ID.
* @param enabled Indicate whether to enable loopback mode.
* @param callback Called when the configuration operation completes.
*/
export function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void;
/**
* Gets the multicast group addresses the socket is currently joined to.
*
* @see https://developer.chrome.com/apps/sockets_udp#method-getJoinedGroups
* @param socketId The socket ID.
* @param callback Called with an array of strings of the result.
*/
export function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void;
/**
* Enables or disables broadcast packets on this socket.
*
* @since Chrome 44
* @see https://developer.chrome.com/apps/sockets_udp#method-setBroadcast
* @param socketId The socket ID.
* @param enabled true to enable broadcast packets, false to disable them.
* @param callback Callback from the setBroadcast method.
*/
export function setBroadcast(socketId: number, enabled: boolean, callback?: (result: number) => void): void;
/**
* Event raised when a UDP packet has been received for the given socket.
*
* @see https://developer.chrome.com/apps/sockets_udp#event-onReceive
*/
export var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>;
/**
* Event raised when a network error occured while the runtime was waiting
* for data on the socket address and port. Once this event is raised, the
* socket is paused and no more onReceive events will be raised for this
* socket until the socket is resumed.
*
* @see https://developer.chrome.com/apps/sockets_udp#event-onReceiveError
*/
export var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>;
}
/**
* Use the chrome.sockets.tcpServer API to create server applications using TCP
* connections. This API supersedes the TCP functionality previously found in
* the chrome.socket API.
*
* @since Chrome 33
* @see https://developer.chrome.com/apps/sockets_tcpServer
*/
declare namespace chrome.sockets.tcpServer {
export interface CreateInfo {
socketId: number;
}
export interface AcceptEventArgs {
socketId: number;
clientSocketId: number;
}
export interface AcceptErrorEventArgs {
socketId: number;
resultCode: number;
}
/**
* @see https://developer.chrome.com/apps/sockets_tcpServer#type-SocketProperties
*/
export interface SocketProperties {
/**
* Flag indicating if the socket remains open when the event page of the
* application is unloaded. The default value is "false." When the
* application is loaded, any sockets previously opened with
* persistent=true can be fetched with getSockets.
*
* @see http://developer.chrome.com/apps/app_lifecycle.html
*/
persistent?: boolean;
/** An application-defined string associated with the socket. */
name?: string;
}
/**
* @see https://developer.chrome.com/apps/sockets_tcpServer#type-SocketInfo
*/
export interface SocketInfo {
/** The socket identifier. */
socketId: number;
/**
* Flag indicating if the socket remains open when the event page of the
* application is unloaded (see SocketProperties.persistent). The
* default value is "false".
*/
persistent: boolean;
/** Application-defined string associated with the socket. */
name?: string;
/**
* Flag indicating whether connection requests on a listening socket are
* dispatched through the onAccept event or queued up in the listen
* queue backlog. See setPaused. The default value is "false"
*/
paused: boolean;
/** If the socket is listening, contains its local IPv4/6 address. */
localAddress?: string;
/** If the socket is listening, contains its local port. */
localPort?: number;
}
/**
* Creates a TCP server socket.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#method-create
* @param callback Called when the socket has been created.
*/
export function create(callback: (createInfo: CreateInfo) => void): void;
/**
* Creates a TCP server socket.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#method-create
* @param properties The socket properties.
* @param callback Called when the socket has been created.
*/
export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void;
/**
* Updates the socket properties.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#method-update
* @param socketId The socket identifier.
* @param properties The properties to update.
* @param callback Called when the properties are updated.
*/
export function update(socketId: number, properties: SocketProperties, callback?: () => void): void;
/**
* Enables or disables a listening socket from accepting new connections.
* When paused, a listening socket accepts new connections until its backlog
* (see listen function) is full then refuses additional connection
* requests. onAccept events are raised only when the socket is un-paused.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#method-setPaused
* @param callback Callback from the setPaused method.
*/
export function setPaused(socketId: number, paused: boolean, callback?: () => void): void;
/**
* Listens for connections on the specified port and address. If the
* port/address is in use, the callback indicates a failure.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#method-listen
* @param socketId The socket identifier.
* @param address The address of the local machine.
* @param port The port of the local machine. When set to 0, a free port
* is chosen dynamically. The dynamically allocated port can
* be found by calling getInfo.
* @param backlog Length of the socket's listen queue. The default value
* depends on the Operating System (SOMAXCONN), which
* ensures a reasonable queue length for most applications.
* @param callback Called when listen operation completes.
*/
export function listen(socketId: number, address: string, port: number, backlog: number, callback: (result: number) => void): void;
/**
* Listens for connections on the specified port and address. If the
* port/address is in use, the callback indicates a failure.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#method-listen
* @param socketId The socket identifier.
* @param address The address of the local machine.
* @param port The port of the local machine. When set to 0, a free port
* is chosen dynamically. The dynamically allocated port can
* be found by calling getInfo.
* @param callback Called when listen operation completes.
*/
export function listen(socketId: number, address: string, port: number, callback: (result: number) => void): void;
/**
* Disconnects the listening socket, i.e. stops accepting new connections
* and releases the address/port the socket is bound to. The socket
* identifier remains valid, e.g. it can be used with listen to accept
* connections on a new port and address.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#method-disconnect
* @param socketId The socket identifier.
* @param callback Called when the disconnect attempt is complete.
*/
export function disconnect(socketId: number, callback?: () => void): void;
/**
* Disconnects and destroys the socket. Each socket created should be closed
* after use. The socket id is no longer valid as soon at the function is
* called. However, the socket is guaranteed to be closed only when the
* callback is invoked.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#method-close
* @param socketId The socket identifier.
* @param callback Called when the close operation completes.
*/
export function close(socketId: number, callback?: () => void): void;
/**
* Retrieves the state of the given socket.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#method-getInfo
* @param socketId The socket identifier.
* @param callback Called when the socket state is available.
*/
export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void;
/**
* Retrieves the list of currently opened sockets owned by the application.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#method-getSockets
* @param callback Called when the list of sockets is available.
*/
export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void;
/**
* Event raised when a connection has been made to the server socket.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAccept
*/
export var onAccept: chrome.events.Event<(args: AcceptEventArgs) => void>;
/**
* Event raised when a network error occured while the runtime was waiting
* for new connections on the socket address and port. Once this event is
* raised, the socket is set to paused and no more onAccept events are
* raised for this socket until the socket is resumed.
*
* @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAcceptError
*/
export var onAcceptError: chrome.events.Event<(args: AcceptErrorEventArgs) => void>;
}
////////////////////
// System Display
////////////////////
/**
* Use the system.display API to query display metadata.
* Permissions: "system.display"
* @since Chrome 30.
*/
declare namespace chrome.system.display {
export interface Bounds {
/** The x-coordinate of the upper-left corner. */
left: number;
/** The y-coordinate of the upper-left corner. */
top: number;
/** The width of the display in pixels. */
width: number;
/** The height of the display in pixels. */
height: number;
}
export interface Insets {
/** The x-axis distance from the left bound. */
left: number;
/** The y-axis distance from the top bound. */
top: number;
/** The x-axis distance from the right bound. */
right: number;
/** The y-axis distance from the bottom bound. */
bottom: number;
}
/**
* @since Chrome 57
*/
export interface Point {
/** The x-coordinate of the point. */
x: number;
/** The y-coordinate of the point. */
y: number;
}
/**
* @since Chrome 57
*/
export interface TouchCalibrationPair {
/** The coordinates of the display point. */
displayPoint: Point;
/** The coordinates of the touch point corresponding to the display point. */
touchPoint: Point;
}
/**
* @since Chrome 52
*/
export interface DisplayMode {
/** The display mode width in device independent (user visible) pixels. */
width: number;
/** The display mode height in device independent (user visible) pixels. */
height: number;
/** The display mode width in native pixels. */
widthInNativePixels: number;
/** The display mode height in native pixels. */
heightInNativePixels: number;
/** The display mode UI scale factor. */
uiScale: number;
/** The display mode device scale factor. */
deviceScaleFactor: number;
/** True if the mode is the display's native mode. */
isNative: boolean;
/** True if the display mode is currently selected. */
isSelected: boolean;
}
/**
* @since Chrome 53
*/
export interface DisplayLayout {
/** The unique identifier of the display. */
id: string;
/** The unique identifier of the parent display. Empty if this is the root. */
parentId: string;
/** The layout position of this display relative to the parent. This will be ignored for the root. */
position: 'top' | 'right' | 'bottom' | 'left';
/** The offset of the display along the connected edge. 0 indicates that the topmost or leftmost corners are aligned. */
offset: number;
}
/**
* @description The pairs of point used to calibrate the display.
* @export
* @interface TouchCalibrationPairs
*/
export interface TouchCalibrationPairs {
/** First pair of touch and display point required for touch calibration. */
pair1: TouchCalibrationPair,
/** Second pair of touch and display point required for touch calibration. */
pair2: TouchCalibrationPair,
/** Third pair of touch and display point required for touch calibration. */
pair3: TouchCalibrationPair,
/** Fourth pair of touch and display point required for touch calibration. */
pair4: TouchCalibrationPair
}
/**
* @description Representation of info data to be used in chrome.system.display.setDisplayProperties()
* @export
* @interface DisplayPropertiesInfo
*/
export interface DisplayPropertiesInfo {
/**
* @description Chrome OS only. If set to true, changes the display mode to unified desktop (see enableUnifiedDesktop for details). If set to false, unified desktop mode will be disabled. This is only valid for the primary display. If provided, mirroringSourceId must not be provided and other properties may not apply. This is has no effect if not provided.
* @since Chrome 59
* */
isUnified?: boolean;
/**
* Chrome OS only. If set and not empty, enables mirroring for this display. Otherwise disables mirroring for this display. This value should indicate the id of the source display to mirror, which must not be the same as the id passed to setDisplayProperties. If set, no other property may be set.
*/
mirroringSourceId?: string;
/** If set to true, makes the display primary. No-op if set to false. */
isPrimary?: boolean;
/** If set, sets the display's overscan insets to the provided values. Note that overscan values may not be negative or larger than a half of the screen's size. Overscan cannot be changed on the internal monitor. It's applied after isPrimary parameter. */
overscan?: Insets;
/** If set, updates the display's rotation. Legal values are [0, 90, 180, 270]. The rotation is set clockwise, relative to the display's vertical position. It's applied after overscan paramter. */
rotation?: 0 | 90 | 180 | 270;
/** If set, updates the display's logical bounds origin along x-axis. Applied together with boundsOriginY, if boundsOriginY is set. Note that, when updating the display origin, some constraints will be applied, so the final bounds origin may be different than the one set. The final bounds can be retrieved using getInfo. The bounds origin is applied after rotation. The bounds origin cannot be changed on the primary display. Note that is also invalid to set bounds origin values if isPrimary is also set (as isPrimary parameter is applied first). */
boundsOriginX?: number;
/** If set, updates the display's logical bounds origin along y-axis. See documentation for boundsOriginX parameter. */
boundsOriginY: number;
/**
* @since Chrome 52
* @description If set, updates the display mode to the mode matching this value.
*/
displayMode?: DisplayMode;
}
/**
* @description Options affecting how the information is returned.
* @since Chrome 59
* @export
* @interface DisplayInfoFlags
*/
export interface DisplayInfoFlags {
/**
* @description If set to true, only a single DisplayUnitInfo will be returned by getInfo when in unified desktop mode (see enableUnifiedDesktop). Defaults to false.
* @type {boolean}
* @memberof DisplayInfoFlags
*/
singleUnified?: boolean;
}
/** Information about display properties. */
export interface DisplayInfo {
/** The unique identifier of the display. */
id: string;
/** The user-friendly name (e.g. "HP LCD monitor"). */
name: string;
/** Identifier of the display that is being mirrored on the display unit. If mirroring is not in progress, set to an empty string. Currently exposed only on ChromeOS. Will be empty string on other platforms. */
mirroringSourceId: string;
/** True if this is the primary display. */
isPrimary: boolean;
/** True if this is an internal display. */
isInternal: boolean;
/** True if this display is enabled. */
isEnabled: boolean;
/** The number of pixels per inch along the x-axis. */
dpiX: number;
/** The number of pixels per inch along the y-axis. */
dpiY: number;
/** The display's clockwise rotation in degrees relative to the vertical position. Currently exposed only on ChromeOS. Will be set to 0 on other platforms. */
rotation: number;
/** The display's logical bounds. */
bounds: Bounds;
/** The display's insets within its screen's bounds. Currently exposed only on ChromeOS. Will be set to empty insets on other platforms. */
overscan: Insets;
/** The usable work area of the display within the display bounds. The work area excludes areas of the display reserved for OS, for example taskbar and launcher. */
workArea: Bounds;
}
/** The information about display properties that should be changed. A property will be changed only if a new value for it is specified in |info|. */
export interface DisplayProps {
/** If set and not empty, starts mirroring between this and the display with the provided id (the system will determine which of the displays is actually mirrored). If set and not empty, stops mirroring between this and the display with the specified id (if mirroring is in progress). If set, no other parameter may be set. */
mirroringSourceId?: string;
/** If set to true, makes the display primary. No-op if set to false. */
isPrimary?: boolean;
/** If set, sets the display's overscan insets to the provided values. Note that overscan values may not be negative or larger than a half of the screen's size. Overscan cannot be changed on the internal monitor. It's applied after isPrimary parameter. */
overscan?: Insets;
/** If set, updates the display's rotation. Legal values are [0, 90, 180, 270]. The rotation is set clockwise, relative to the display's vertical position. It's applied after overscan paramter. */
rotation?: number;
/** If set, updates the display's logical bounds origin along x-axis. Applied together with boundsOriginY, if boundsOriginY is set. Note that, when updating the display origin, some constraints will be applied, so the final bounds origin may be different than the one set. The final bounds can be retrieved using getInfo. The bounds origin is applied after rotation. The bounds origin cannot be changed on the primary display. Note that is also invalid to set bounds origin values if isPrimary is also set (as isPrimary parameter is applied first). */
boundsOriginX?: number;
/** If set, updates the display's logical bounds origin along y-axis. See documentation for boundsOriginX parameter. */
boundsOriginY?: number;
}
/**
* @description Fired when anything changes to the display configuration.
* @export
* @interface DisplayChangedEvent
* @extends {chrome.events.Event<() => void>}
*/
export interface DisplayChangedEvent extends chrome.events.Event<() => void> { }
/**
* @description Requests the information for all attached display devices.
* @export
* @param {(info: DisplayInfo[]) => void} callback The callback to invoke with the results.
*/
export function getInfo(callback: (info: DisplayInfo[]) => void): void;
/**
* @description Requests the information for all attached display devices.
* @export
* @since Chrome 59
* @param {DisplayInfoFlags} [flags] Options affecting how the information is returned.
* @param {(info: DisplayInfo[]) => void} callback The callback to invoke with the results.
*/
export function getInfo(flags: DisplayInfoFlags, callback: (info: DisplayInfo[]) => void): void;
/**
* @description Requests the layout info for all displays. NOTE: This is only available to Chrome OS Kiosk apps and Web UI.
* @since Chrome 53
* @export
* @param {(layouts: DisplayLayout[]) => void} callback The callback to invoke with the results.
*/
export function getDisplayLayout(callback: (layouts: DisplayLayout[]) => void): void;
/**
* @description Updates the properties for the display specified by |id|, according to the information provided in |info|. On failure, runtime.lastError will be set. NOTE: This is only available to Chrome OS Kiosk apps and Web UI.
* @export
* @param {string} id The display's unique identifier.
* @param {DisplayPropertiesInfo} info The information about display properties that should be changed. A property will be changed only if a new value for it is specified in |info|.
* @param {() => void} [callback] Empty function called when the function finishes. To find out whether the function succeeded, runtime.lastError should be queried.
*/
export function setDisplayProperties(id: string, info: DisplayPropertiesInfo, callback?: () => void): void;
/**
* @description Set the layout for all displays. Any display not included will use the default layout. If a layout would overlap or be otherwise invalid it will be adjusted to a valid layout. After layout is resolved, an onDisplayChanged event will be triggered. NOTE: This is only available to Chrome OS Kiosk apps and Web UI.
* @since Chrome 53
* @export
* @param {DisplayLayout[]} layouts The layout information, required for all displays except the primary display.
* @param {() => void} callback Empty function called when the function finishes. To find out whether the function succeeded, runtime.lastError should be queried.
*/
export function setDisplayLayout(layouts: DisplayLayout[], callback?: () => void): void;
/**
* @description Enables/disables the unified desktop feature. Note that this simply enables the feature, but will not change the actual desktop mode. (That is, if the desktop is in mirror mode, it will stay in mirror mode) NOTE: This is only available to Chrome OS Kiosk apps and Web UI.
* @since Chrome 46
* @export
* @param {boolean} enabled True if unified desktop should be enabled.
*/
export function enableUnifiedDesktop(enabled: boolean): void;
/**
* @description Starts overscan calibration for a display. This will show an overlay on the screen indicating the current overscan insets. If overscan calibration for display |id| is in progress this will reset calibration.
* @since Chrome 53
* @export
* @param {string} id The display's unique identifier.
*/
export function overscanCalibrationStart(id: string): void;
/**
* @description Adjusts the current overscan insets for a display. Typically this should etiher move the display along an axis (e.g. left+right have the same value) or scale it along an axis (e.g. top+bottom have opposite values). Each Adjust call is cumulative with previous calls since Start.
* @since Chrome 53
* @export
* @param {string} id The display's unique identifier.
* @param {Insets} delta The amount to change the overscan insets.
*/
export function overscanCalibrationAdjust(id: string, delta: Insets): void;
/**
* @description Resets the overscan insets for a display to the last saved value (i.e before Start was called).
* @since Chrome 53
* @export
* @param {string} id The display's unique identifier.
*/
export function overscanCalibrationReset(id: string): void;
/**
* @description Complete overscan adjustments for a display by saving the current values and hiding the overlay.
* @since Chrome 53
* @export
* @param {string} id The display's unique identifier.
*/
export function overscanCalibrationComplete(id: string): void;
/**
* @description Displays the native touch calibration UX for the display with |id| as display id. This will show an overlay on the screen with required instructions on how to proceed. The callback will be invoked in case of successful calibraion only. If the calibration fails, this will throw an error.
* @since Chrome 57
* @export
* @param {string} id The display's unique identifier.
* @param {(success) => void} callback Optional callback to inform the caller that the touch calibration has ended. The argument of the callback informs if the calibration was a success or not.
*/
export function showNativeTouchCalibration(id: string, callback: (success: boolean) => void): void;
/**
* @description Starts custom touch calibration for a display. This should be called when using a custom UX for collecting calibration data. If another touch calibration is already in progress this will throw an error.
* @since Chrome 57
* @export
* @param {string} id The display's unique identifier.
*/
export function startCustomTouchCalibration(id: string): void;
/**
* @description Sets the touch calibration pairs for a display. These |pairs| would be used to calibrate the touch screen for display with |id| called in startCustomTouchCalibration(). Always call |startCustomTouchCalibration| before calling this method. If another touch calibration is already in progress this will throw an error.
* @since Chrome 57
* @export
* @param {TouchCalibrationPairs} pairs The pairs of point used to calibrate the display.
* @param {Bounds} bounds Bounds of the display when the touch calibration was performed. |bounds.left| and |bounds.top| values are ignored.
*/
export function completeCustomTouchCalibration(pairs: TouchCalibrationPairs, bounds: Bounds): void;
/**
* @description Resets the touch calibration for the display and brings it back to its default state by clearing any touch calibration data associated with the display.
* @since Chrome 57
* @export
* @param {string} id The display's unique identifier.
*/
export function clearTouchCalibration(id: string): void;
/**
* @description Fired when anything changes to the display configuration.
* @export
*/
export var onDisplayChanged: DisplayChangedEvent;
}
////////////////////
// System - Network
////////////////////
declare namespace chrome.system.network {
export interface NetworkInterface {
name: string;
address: string;
prefixLength: number;
}
export function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void;
}
declare namespace chrome.runtime {
export interface Manifest {
app?: {
background?: {
scripts?: string[];
}
},
bluetooth?: {
uuids?: string[];
socket?: boolean;
low_energy?: boolean;
peripheral?: boolean;
},
file_handlers?: {
[name: string]: {
types?: string[];
extensions?: string[];
title?: string;
}
},
kiosk_enabled?: boolean,
kiosk_only?: boolean,
url_handlers?: {
[name: string]: {
matches: string[];
title?: string;
}
},
usb_printers?: {
filters: {
vendorId?: number;
productId?: number;
interfaceClass?: number;
interfaceSubclass?: number;
interfaceProtocol?: number;
}[]
},
webview?: {
partitions?: {
name: string;
accessible_resources: string[];
}[]
}
}
}
////////////////////
// USB
////////////////////
declare namespace chrome.usb {
type Direction = 'in' | 'out';
export interface Device {
device: number,
vendorId: number,
productId: number,
productName: string,
manufacturerName: string,
serialNumber: string
}
export interface ConnectionHandle {
handle: number,
vendorId: number,
productId: number
}
export interface EndpointDescriptor {
address: number,
type: 'control' | 'interrupt' | 'isochronous' | 'bulk',
direction: Direction,
maximumPacketSize: number,
synchronization?: 'asynchronous' | 'adaptive' | 'synchronous',
usage?: 'data' | 'feedback' | 'explicitFeedback',
pollingInterval?: number,
extra_data: ArrayBuffer
}
export interface InterfaceDescriptor {
interfaceNumber: number,
alternateSetting: number,
interfaceClass: number,
interfaceSubclass: number,
interfaceProtocol: number,
description?: string,
endpoints: EndpointDescriptor[],
extra_data: ArrayBuffer
}
export interface ConfigDescriptor {
active: boolean,
configurationValue: number,
description?: string,
selfPowered: boolean,
remoteWakeup: boolean,
maxPower: number,
interfaces: InterfaceDescriptor[],
extra_data: ArrayBuffer
}
export interface GenericTransferInfo {
direction: Direction,
endpoint: number,
length?: number,
data?: ArrayBuffer,
timeout?: number
}
export interface TransferResultInfo {
resultCode: number,
data?: ArrayBuffer
}
export interface DeviceFilter {
vendorId?: number,
productId?: number,
interfaceClass?: number,
interfaceSubclass?: number,
interfaceProtocol?: number
}
export interface TransferInfo {
direction: Direction;
recipient: 'device' | 'interface' | 'endpoint' | 'other';
requestType: 'standard' | 'class' | 'vendor' | 'reserved';
request: number;
value: number;
index: number;
length?: number;
data?: ArrayBuffer;
timeout?: number;
}
export interface DeviceEvent extends chrome.events.Event<(device: Device) => void> { }
export var onDeviceAdded: DeviceEvent;
export var onDeviceRemoved: DeviceEvent;
export function getDevices(options: { vendorId?: number, productId?: number, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void;
export function getUserSelectedDevices(options: { multiple?: boolean, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void;
export function getConfigurations(device: Device, callback: (configs: ConfigDescriptor[]) => void): void;
export function requestAccess(device: Device, interfaceId: number, callback: (success: boolean) => void): void;
export function openDevice(device: Device, callback: (handle: ConnectionHandle) => void): void;
export function findDevices(options: { vendorId: number, productId: number, interfaceId?: number }, callback: (handles: ConnectionHandle[]) => void): void;
export function closeDevice(handle: ConnectionHandle, callback?: () => void): void;
export function setConfiguration(handle: ConnectionHandle, configurationValue: number, callback: () => void): void;
export function getConfiguration(handle: ConnectionHandle, callback: (config: ConfigDescriptor) => void): void;
export function listInterfaces(handle: ConnectionHandle, callback: (descriptors: InterfaceDescriptor[]) => void): void;
export function claimInterface(handle: ConnectionHandle, interfaceNumber: number, callback: () => void): void;
export function releaseInterface(handle: ConnectionHandle, interfaceNumber: number, callback: () => void): void;
export function setInterfaceAlternateSetting(handle: ConnectionHandle, interfaceNumber: number, alternateSetting: number, callback: () => void): void;
export function controlTransfer(handle: ConnectionHandle, transferInfo: TransferInfo, callback: (info: TransferResultInfo) => void): void;
export function bulkTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void;
export function interruptTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void;
export function isochronousTransfer(handle: ConnectionHandle, transferInfo: { transferInfo: GenericTransferInfo, packets: number, packetLength: number }, callback: (info: TransferResultInfo) => void): void;
export function resetDevice(handle: ConnectionHandle, callback: (success: boolean) => void): void;
}
declare namespace chrome.networking.onc {
export type ActivationStateType = 'Activated' | 'Activating' | 'NotActivated' | 'PartiallyActivated';
export type CaptivePortalStatus = 'Unknown' | 'Offline' | 'Online' | 'Portal' | 'ProxyAuthRequired';
export type ConnectionStateType = 'Connected' | 'Connecting' | 'NotConnected';
export type IPConfigType = 'DHCP' | 'Static';
export type NetworkType = 'All' | 'Cellular' | 'Ethernet' | 'VPN' | 'Wireless' | 'WiFi' | 'WiMAX';
export type ProxySettingsType = 'Direct' | 'Manual' | 'PAC' | 'WPAD';
export interface ManagedBoolean {
/**
* @description The active value currently used by the network configuration manager (e.g. Shill).
* @type {boolean}
* @memberof ManagedBoolean
*/
Active?: boolean,
/**
* @description The source from which the effective property value was determined.
* @type {string}
* @memberof ManagedBoolean
*/
Effective?: string,
/**
* @description The property value provided by the user policy.
* @type {boolean}
* @memberof ManagedBoolean
*/
UserPolicy?: boolean,
/**
* @description The property value provided by the device policy.
* @type {boolean}
* @memberof ManagedBoolean
*/
DevicePolicy?: boolean,
/**
* @description The property value set by the logged in user. Only provided if |UserEditable| is true.
* @type {boolean}
* @memberof ManagedBoolean
*/
UserSettings?: boolean,
/**
* @description The value set for all users of the device. Only provided if |DeviceEditiable| is true.
* @type {boolean}
* @memberof ManagedBoolean
*/
SharedSettings?: boolean,
/**
* @description Whether a UserPolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false.
* @type {boolean}
* @memberof ManagedBoolean
*/
UserEditable?: boolean,
/**
* @description Whether a DevicePolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false.
* @type {boolean}
* @memberof ManagedBoolean
*/
DeviceEditable?: boolean
}
export interface ManagedLong {
/**
* @description The active value currently used by the network configuration manager (e.g. Shill).
* @type {number}
* @memberof ManagedLong
*/
Active?: number,
/**
* @description The source from which the effective property value was determined.
* @type {string}
* @memberof ManagedLong
*/
Effective?: string,
/**
* @description The property value provided by the user policy.
* @type {number}
* @memberof ManagedLong
*/
UserPolicy?: number,
/**
* @description The property value provided by the device policy.
* @type {number}
* @memberof ManagedLong
*/
DevicePolicy?: number,
/**
* @description The property value set by the logged in user. Only provided if |UserEditable| is true.
* @type {number}
* @memberof ManagedLong
*/
UserSettings?: number,
/**
* @description The value set for all users of the device. Only provided if |DeviceEditiable| is true.
* @type {number}
* @memberof ManagedLong
*/
SharedSettings?: number,
/**
* @description Whether a UserPolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false.
* @type {boolean}
* @memberof ManagedLong
*/
UserEditable?: boolean,
/**
* @description Whether a DevicePolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false.
* @type {boolean}
* @memberof ManagedLong
*/
DeviceEditable?: boolean
}
} | the_stack |
import { DynamsoftEnums as Dynamsoft } from "./Dynamsoft.Enum";
import { WebTwainUtil } from "./WebTwain.Util";
export interface WebTwainIO extends WebTwainUtil {
/**
* The password to connect to the FTP.
*/
FTPPassword: string;
/**
* The port to connect to the FTP.
*/
FTPPort: number;
/**
* The password to connect to the FTP.
*/
FTPUserName: string;
/**
* Return or set whether to use passive mode when connect to the FTP.
*/
IfPASVMode: boolean;
/**
* Return or set the field name for the uploaded file.
* By default, it's "RemoteFile".
*/
HttpFieldNameOfUploadedImage: string;
/**
* [Deprecation] Return or set the password used to log into the HTTP server.
*/
HTTPPassword: string;
/**
* [Deprecation] Return or set the user name used to log into the HTTP server.
*/
HTTPUserName: string;
/**
* Return or set the HTTP Port.
*/
HTTPPort: number;
/**
* Return or set whether to use SSL in HTTP requests.
*/
IfSSL: boolean;
/**
* Return the response string of the latest HTTP Post request.
*/
readonly HTTPPostResponseString: string;
/**
* Return or set whether to show open/save file dialog when saving images in the buffer or loading images from a local directory.
*/
IfShowFileDialog: boolean;
/**
* Return or set whether to show the progress of an operation with a button to cancel it.
*/
IfShowCancelDialogWhenImageTransfer: boolean;
/**
* Return or set whether to show the progressbar.
*/
IfShowProgressBar: boolean;
/**
* Return or set the quality for JPEG compression.
* The values range from 0 to 100.
*/
JPEGQuality: number;
/**
* Return or set whether to insert or append images when they are scanned/loaded.
*/
IfAppendImage: boolean;
/**
* Return or set whether to append to or replace an existing TIFF file with the same name.
*/
IfTiffMultiPage: boolean;
/**
* Return or set the compression type for TIFF files.
*/
TIFFCompressionType: Dynamsoft.EnumDWT_TIFFCompressionType | number;
/**
* Return or set the name of the person who creates the PDF document.
*/
PDFAuthor: string;
/**
* Return or set the compression type of PDF files. This is a runtime property.
*/
PDFCompressionType: Dynamsoft.EnumDWT_PDFCompressionType;
/**
* Return or set the date when the PDF document is created.
*/
PDFCreationDate: string;
/**
* Return or set the name of the application that created the original document, if the PDF document is converted from another form.
*/
PDFCreator: string;
/**
* Return or set the keywords associated with the PDF document.
*/
PDFKeywords: string;
/**
* Return or set the date when the PDF document is last modified.
*/
PDFModifiedDate: string;
/**
* Return or set the name of the application that converted the PDF document from its native.
*/
PDFProducer: string;
/**
* Return or set the subject of the PDF document.
*/
PDFSubject: string;
/**
* Return or set the title of the PDF document.
*/
PDFTitle: string;
/**
* Return or set the value of the PDF version.
*/
PDFVersion: string;
/**
* Clear all the custom fields from the HTTP Post Form.
*/
ClearAllHTTPFormField(): boolean;
/**
* Clear the content of all custom tiff tags.
*/
ClearTiffCustomTag(): boolean;
/**
* Convert the specified images to a base64 string.
* @param indices Specify one or multiple images.
* @param type The file type.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument result The resulting base64 string.
* @argument indices The indices of the converted images.
* @argument type The file type.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
ConvertToBase64(
indices: number[],
type: Dynamsoft.EnumDWT_ImageType | number,
successCallback: (
result: Base64Result,
indices: number[],
type: number) => void,
failureCallBack: (
errorCode: number,
errorString: string) => void
): void;
/**
* Convert the specified images to a blob.
* @param indices Specify one or multiple images.
* @param type The file type.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument result The resulting blob.
* @argument indices The indices of the converted images.
* @argument type The file type.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
ConvertToBlob(
indices: number[],
type: Dynamsoft.EnumDWT_ImageType | number,
successCallback: (
result: Blob,
indices: number[],
type: number) => void,
failureCallBack: (
errorCode: number,
errorString: string) => void
): void;
/**
* Download the specified file via FTP
* @param host The FTP Host.
* @param path Specify the file to download.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
FTPDownload(
host: string,
path: string,
successCallback: () => void,
failureCallBack: (
errorCode: number,
errorString: string) => void
): void;
/**
* Download the specified file via FTP.
* @param host The FTP Host.
* @param path Specify the file to download.
* @param type The format of the file.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
FTPDownloadEx(
host: string,
path: string,
type: Dynamsoft.EnumDWT_ImageType | number,
successCallback: () => void,
failureCallBack: (
errorCode: number,
errorString: string) => void
): void;
/**
* Upload the specified image via FTP.
* @param host The FTP Host.
* @param index Specify the image.
* @param path The path to save the file.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
FTPUpload(
host: string,
index: number,
path: string,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Upload the specified image via FTP.
* @param host The FTP Host.
* @param index Specify the image.
* @param path The path to save the file.
* @param type The format of the file.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
FTPUploadEx(
host: string,
index: number,
path: string,
type: Dynamsoft.EnumDWT_ImageType | number,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Upload all images as a multi-page TIFF via FTP.
* @param host The FTP Host.
* @param path Specify the path to save the file.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
FTPUploadAllAsMultiPageTIFF(
host: string,
path: string,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Upload all images as a multi-page PDF via FTP.
* @param host The FTP Host.
* @param path Specify the path to save the file.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
FTPUploadAllAsPDF(
host: string,
path: string,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Upload selected images as a multi-page PDF via FTP.
* @param host The FTP Host.
* @param path Specify the path to save the file.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
FTPUploadAsMultiPagePDF(
host: string,
path: string,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Upload selected images as a multi-page TIFF via FTP.
* @param host The FTP Host.
* @param path Specify the path to save the file.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
FTPUploadAsMultiPageTIFF(
host: string,
path: string,
type: Dynamsoft.EnumDWT_ImageType | number,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Download the specified file via a HTTP Get request.
* @param host The HTTP Host.
* @param path Specify the path of the file to download.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
HTTPDownload(
host: string,
path: string,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Download the specified file via a HTTP Get request.
* @param host The HTTP Host.
* @param path Specify the path of the file to download.
* @param type The format of the file.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
HTTPDownloadEx(
host: string,
path: string,
type: Dynamsoft.EnumDWT_ImageType | number,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Download the specified file via a HTTP Post request.
* @param host The HTTP Host.
* @param path Specify the path of the file to download.
* @param type The format of the file.
* @param onEmptyResponse A callback function that is executed if the response is empty.
* @param onServerReturnedSomething A callback function that is executed if the response is not empty.
* @argument errorCode The error code.
* @argument errorString The error string.
* @argument response The response string.
*/
HTTPDownloadThroughPost(
host: string,
path: string,
type: Dynamsoft.EnumDWT_ImageType | number,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
/**
* Download the specified file via a HTTP Get request.
* @param host The HTTP Host.
* @param path Specify the path of the file to download.
* @param localPath Specify where to save the file.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
HTTPDownloadDirectly(
host: string,
path: string,
localPath: string,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Upload the specified image(s) via a HTTP Post.
* @param URL The server-side script to receive the post.
* @param indices Specify the image(s).
* @param type The format of the file.
* @param dataFormat Whether to upload the file as binary or a base64 string.
* @param fileName The file name.
* @param onEmptyResponse A callback function that is executed if the response is empty.
* @param onServerReturnedSomething A callback function that is executed if the response is not empty.
* @argument errorCode The error code.
* @argument errorString The error string.
* @argument response The response string.
*/
HTTPUpload(
URL: string,
indices: number[],
type: Dynamsoft.EnumDWT_ImageType | number,
dataFormat: Dynamsoft.EnumDWT_UploadDataFormat | number,
fileName: string,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
HTTPUpload(
URL: string,
indices: number[],
type: Dynamsoft.EnumDWT_ImageType | number,
dataFormat: Dynamsoft.EnumDWT_UploadDataFormat | number,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
HTTPUpload(
URL: string,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
/**
* Upload the specified image via a HTTP Put request.
* @param host The HTTP Host.
* @param index Specify the image.
* @param path Specify the path to put the file.
* @param type The format of the file.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
HTTPUploadThroughPutEx(
host: string,
index: number,
path: string,
type: Dynamsoft.EnumDWT_ImageType | number,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Upload the specified image via a HTTP Post request.
* @param host The HTTP Host.
* @param index Specify the image.
* @param target The target wherethe request is sent.
* @param type The format of the file.
* @param fileName The file name.
* @param onEmptyResponse A callback function that is executed if the response is empty.
* @param onServerReturnedSomething A callback function that is executed if the response is not empty.
* @argument errorCode The error code.
* @argument errorString The error string.
* @argument response The response string.
*/
HTTPUploadThroughPost(
host: string,
index: number,
target: string,
fileName: string,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
/**
* Upload the specified image via a HTTP Post request.
* @param host The HTTP Host.
* @param index Specify the image.
* @param target The target wherethe request is sent.
* @param fileName The file name.
* @param type The format of the file.
* @param onEmptyResponse A callback function that is executed if the response is empty.
* @param onServerReturnedSomething A callback function that is executed if the response is not empty.
* @argument errorCode The error code.
* @argument errorString The error string.
* @argument response The response string.
*/
HTTPUploadThroughPostEx(
host: string,
index: number,
target: string,
fileName: string,
type: Dynamsoft.EnumDWT_ImageType | number,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
/**
* Upload all images in the buffer as a TIFF file via a HTTP Post request.
* @param host The HTTP Host.
* @param target The target wherethe request is sent.
* @param fileName The file name.
* @param onEmptyResponse A callback function that is executed if the response is empty.
* @param onServerReturnedSomething A callback function that is executed if the response is not empty.
* @argument errorCode The error code.
* @argument errorString The error string.
* @argument response The response string.
*/
HTTPUploadAllThroughPostAsMultiPageTIFF(
host: string,
target: string,
fileName: string,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
/**
* Upload all images in the buffer as a PDF file via a HTTP Post request.
* @param host The HTTP Host.
* @param target The target wherethe request is sent.
* @param fileName The file name.
* @param onEmptyResponse A callback function that is executed if the response is empty.
* @param onServerReturnedSomething A callback function that is executed if the response is not empty.
* @argument errorCode The error code.
* @argument errorString The error string.
* @argument response The response string.
*/
HTTPUploadAllThroughPostAsPDF(
host: string,
target: string,
fileName: string,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
/**
* Upload all selected images in the buffer as a PDF file via a HTTP Post request.
* @param host The HTTP Host.
* @param target The target wherethe request is sent.
* @param fileName The file name.
* @param onEmptyResponse A callback function that is executed if the response is empty.
* @param onServerReturnedSomething A callback function that is executed if the response is not empty.
* @argument errorCode The error code.
* @argument errorString The error string.
* @argument response The response string.
*/
HTTPUploadThroughPostAsMultiPagePDF(
host: string,
target: string,
fileName: string,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
/**
* Upload all selected images in the buffer as a TIFF file via a HTTP Post request.
* @param host The HTTP Host.
* @param target The target wherethe request is sent.
* @param fileName The file name.
* @param onEmptyResponse A callback function that is executed if the response is empty.
* @param onServerReturnedSomething A callback function that is executed if the response is not empty.
* @argument errorCode The error code.
* @argument errorString The error string.
* @argument response The response string.
*/
HTTPUploadThroughPostAsMultiPageTIFF(
host: string,
target: string,
fileName: string,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
/**
* Upload the specified file via a HTTP Post request.
* @param host The HTTP Host.
* @param path Specify the file to upload.
* @param target The target wherethe request is sent.
* @param fileName The file name.
* @param onEmptyResponse A callback function that is executed if the response is empty.
* @param onServerReturnedSomething A callback function that is executed if the response is not empty.
* @argument errorCode The error code.
* @argument errorString The error string.
* @argument response The response string.
*/
HTTPUploadThroughPostDirectly(
host: string,
path: string,
target: string,
fileName: string,
onEmptyResponse: () => void,
onServerReturnedSomething: (
errorCode: number,
errorString: string,
response: string) => void
): void;
/**
* Load image(s) specified by its absolute path.
* @param fileName The path of the image to load.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
LoadImage(
fileName: string,
successCallback?: () => void,
failureCallback?: (
errorCode: number,
errorString: string) => void
): void | boolean;
/**
* Load image(s) specified by its absolute path.
* @param fileName The path of the image to load.
* @param type The format of the image.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
LoadImageEx(
fileName: string,
type: Dynamsoft.EnumDWT_ImageType | number,
successCallback?: () => void,
failureCallback?: (
errorCode: number,
errorString: string) => void
): void | boolean;
/**
* Load image(s) from a base64 string.
* @param imageData The image data which is a base64 string without the data URI scheme.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
LoadImageFromBase64Binary(
imageData: string,
imageType: Dynamsoft.EnumDWT_ImageType,
successCallback?: () => void,
failureCallback?: (
errorCode: number,
errorString: string) => void
): void | boolean;
/**
* Load image(s) from a binary object (Blob | ArrayBuffer).
* @param imageData The image data.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
LoadImageFromBinary(
imageData: Blob | ArrayBuffer,
successCallback: () => void,
failureCallback: (
errorCode: number,
errorString: string) => void
): void;
/**
* Load an image from the system clipboard. The image must be in DIB format.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
LoadDibFromClipboard(
successCallback?: () => void,
failureCallback?: (
errorCode: number,
errorString: string) => void
): void | boolean;
/**
* [Deprecation] Return or set how many threads can be used when you upload files through POST.
*/
MaxInternetTransferThreads: number;
/**
* Return or set the maximum allowed size of a file to upload (in bytes).
*/
MaxUploadImageSize: number;
/**
* Export all image data in the buffer to a new browser window and use the browser's built-in print feature to print the image(s).
* @param useOSPrintWindow Whether to use the print feature of the operating system instead.
*/
Print(useOSPrintWindow?: boolean): boolean;
/**
* Save the specified image as a BMP file.
* @param fileName The name to save to.
* @param index The index which specifies the image to save.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
SaveAsBMP(
fileName: string,
index: number,
successCallback?: () => void,
failureCallback?: (errorCode: number, errorString: string) => void
): void | boolean;
/**
* Save the specified image as a JPEG file.
* @param fileName The name to save to.
* @param index The index which specifies the image to save.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
SaveAsJPEG(
fileName: string,
index: number,
successCallback?: () => void,
failureCallback?: (errorCode: number, errorString: string) => void
): void | boolean;
/**
* Save the specified image as a PDF file.
* @param fileName The name to save to.
* @param index The index which specifies the image to save.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
SaveAsPDF(
fileName: string,
index: number,
successCallback?: () => void,
failureCallback?: (errorCode: number, errorString: string) => void
): void | boolean;
/**
* Save the specified image as a PNG file.
* @param fileName The name to save to.
* @param index The index which specifies the image to save.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
SaveAsPNG(
fileName: string,
index: number,
successCallback?: () => void,
failureCallback?: (errorCode: number, errorString: string) => void
): void | boolean;
/**
* Save the specified image as a TIFF file.
* @param fileName The name to save to.
* @param index The index which specifies the image to save.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
SaveAsTIFF(
fileName: string,
index: number,
successCallback?: () => void,
failureCallback?: (errorCode: number, errorString: string) => void
): void | boolean;
/**
* Saves all the images in buffer as a multi-page TIFF file.
* @param fileName The name to save to.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
SaveAllAsMultiPageTIFF(
fileName: string,
successCallback?: () => void,
failureCallback?: (errorCode: number, errorString: string) => void
): void | boolean;
/**
* Saves all the images in buffer as a multi-page PDF file.
* @param fileName The name to save to.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
SaveAllAsPDF(
fileName: string,
successCallback?: () => void,
failureCallback?: (errorCode: number, errorString: string) => void
): void | boolean;
/**
* Saves all selected images in buffer as a multi-page PDF file.
* @param fileName The name to save to.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
SaveSelectedImagesAsMultiPagePDF(
fileName: string,
successCallback?: () => void,
failureCallback?: (errorCode: number, errorString: string) => void
): void | boolean;
/**
* Saves all selected images in buffer as a multi-page TIFF file.
* @param fileName The name to save to.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
SaveSelectedImagesAsMultiPageTIFF(
fileName: string,
successCallback?: () => void,
failureCallback?: (
errorCode: number,
errorString: string) => void
): void | boolean;
/**
* [Deprecation] Return an index from the selected indices array. Read SelectedImagesIndices instead.
* [Alternative] Read SelectedImagesIndices instead.
* @param indexOfIndices Specify the index of the specified image.
*/
SaveSelectedImagesToBase64Binary(indexOfIndices: number): number;
/**
* [Deprecation] Saves the selected images in the buffer to a base64 string.
* [Alternative] Use ConvertToBase64 instead.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
* @argument result The resulting array of strings.
* @argument errorCode The error code.
* @argument errorString The error string.
*/
SaveSelectedImagesToBase64Binary(
successCallback?: (result: string[]) => void,
failureCallback?: (errorCode: number, errorString: string) => void
): string | boolean;
/**
* Add a custom field to the HTTP Post Form.
* @param name The name of the field.
* @param value The value of the field.
*/
SetHTTPFormField(
name: string,
value: string
): boolean;
/**
* Add a binary file to the HTTP Post Form.
* @param name The name of the field.
* @param content The content of the file.
* @param fileName The name of the file.
*/
SetHTTPFormField(
name: string,
content: Blob,
fileName?: string
): boolean;
/**
* Add a custom header to the HTTP Post Form.
* @param name The name of the field.
* @param value The value of the field.
*/
SetHTTPHeader(
name: string,
value: string
): boolean;
/**
* Clear the content of all custom tiff tags.
* @param id The id of the custom tag.
* @param content The content of the tag.
* @param useBase64Encoding Whether the content is encoded.
*/
SetTiffCustomTag(
id: number,
content: string,
useBase64Encoding: boolean
): boolean;
/**
* Set the segmentation threshold and segment size.
* @param threshold Specify the threshold (in MB).
* @param size Specify the segment size (in KB).
*/
SetUploadSegment(
threshold: number,
size: number
): boolean;
/**
* Show the system's save-file dialog or open-file dialog.
* @param isSave Whether to show a save-file dialog or an open-file dialog
* @param filter The filter pattern like "JPG | *.jpg".
* @param filterIndex The order of the filter. Normally, just put 0.
* @param defaultExtension Extension to be appended to the file name. Only valid in a save-file dialog
* @param initialDirectory The initial directory that the dialog opens.
* @param allowMultiSelect Whether or not multiple files can be selected at the same time. Only valid in an open-file dialog.
* @param showOverwritePrompt Whether or not a prompt shows up when saving a file may overwrite an existing file.
* @param flag If set to 0, bAllowMultiSelect and bShowOverwritePrompt will be effective. Otherwise, these two parameters are ignored.
*/
ShowFileDialog(
isSave: boolean,
filter: string,
filterIndex: number,
defaultExtension: string,
initialDirectory: string,
allowMultiSelect: boolean,
showOverwritePrompt: boolean,
flag: number
): boolean;
/**
* [Deprecation] Set a cookie string into the Http Header to be used when uploading scanned images through POST.
* @param cookie The cookie.
*/
SetCookie(cookie: string): boolean;
}
export interface Base64Result {
/**
* Return the length of the result string.
*/
getLength(): number;
/**
* Return part of the string.
* @param offset The starting position.
* @param length The length of the expected string.
*/
getData(offset: number, length: number): string;
/**
* Return the MD5 value of the result.
*/
getMD5(): string;
}
/**
* Details for each license
*/
export interface LicenseDetailItem {
readonly Browser: string;
readonly EnumLicenseType: string;
readonly ExpireDate: string;
readonly LicenseType: string;
readonly OS: string;
readonly Trial: string;
readonly Version: string;
} | the_stack |
import '@ui5/webcomponents-fiori/dist/illustrations/UnableToLoad.js';
import '@ui5/webcomponents-icons/dist/decline.js';
import '@ui5/webcomponents-icons/dist/navigation-down-arrow.js';
import '@ui5/webcomponents-icons/dist/search.js';
import { useI18nBundle } from '@ui5/webcomponents-react-base/dist/hooks';
import { ThemingParameters } from '@ui5/webcomponents-react-base/dist/ThemingParameters';
import { enrichEventWithDetails } from '@ui5/webcomponents-react-base/dist/Utils';
import {
CANCEL,
MANAGE,
MY_VIEWS,
RESET,
SAVE,
SAVE_AS,
SEARCH,
SEARCH_VARIANT,
SELECT_VIEW
} from '@ui5/webcomponents-react/dist/assets/i18n/i18n-defaults';
import { Bar } from '@ui5/webcomponents-react/dist/Bar';
import { Button } from '@ui5/webcomponents-react/dist/Button';
import { ButtonDesign } from '@ui5/webcomponents-react/dist/ButtonDesign';
import { FlexBox } from '@ui5/webcomponents-react/dist/FlexBox';
import { Icon } from '@ui5/webcomponents-react/dist/Icon';
import { IllustratedMessage } from '@ui5/webcomponents-react/dist/IllustratedMessage';
import { IllustrationMessageType } from '@ui5/webcomponents-react/dist/IllustrationMessageType';
import { Input } from '@ui5/webcomponents-react/dist/Input';
import { List } from '@ui5/webcomponents-react/dist/List';
import { ListMode } from '@ui5/webcomponents-react/dist/ListMode';
import { PopoverPlacementType } from '@ui5/webcomponents-react/dist/PopoverPlacementType';
import { ResponsivePopover, ResponsivePopoverDomRef } from '@ui5/webcomponents-react/dist/ResponsivePopover';
import { Title } from '@ui5/webcomponents-react/dist/Title';
import { TitleLevel } from '@ui5/webcomponents-react/dist/TitleLevel';
import { SelectedVariant, VariantManagementContext } from '@ui5/webcomponents-react/dist/VariantManagementContext';
import { CommonProps } from '@ui5/webcomponents-react/interfaces/CommonProps';
import React, {
Children,
cloneElement,
ComponentElement,
forwardRef,
isValidElement,
ReactNode,
Ref,
useCallback,
useEffect,
useRef,
useState
} from 'react';
import { createPortal } from 'react-dom';
import { createUseStyles } from 'react-jss';
import { Ui5CustomEvent } from '../../interfaces/Ui5CustomEvent';
import { stopPropagation } from '../../internal/stopPropagation';
import { ManageViewsDialog } from './ManageViewsDialog';
import { SaveViewDialog } from './SaveViewDialog';
import { VariantItemPropTypes } from './VariantItem';
import clsx from 'clsx';
interface UpdatedVariant extends SelectedVariant {
prevVariant?: VariantItemPropTypes;
}
export interface VariantManagementPropTypes extends Omit<CommonProps, 'onSelect'> {
/**
* Variant items displayed by the VariantManagement component.
*
* __Note:__ Although this prop accepts all HTML Elements, it is strongly recommended that you only use `VariantItem` in order to preserve the intended design.
*/
children?: ReactNode | ReactNode[];
/**
* Determines on which side the VariantManagement popover is placed at.
*/
placement?: PopoverPlacementType | keyof typeof PopoverPlacementType;
/**
* Describes the title of the VariantManagement popover.
*
* __Note:__ If not set, the default title is used.
*/
titleText?: string;
/**
* Defines whether the VariantManagement should be closed if an item was selected.
*/
closeOnItemSelect?: boolean;
/**
* Describes the `HTML Title` level of the variants.
*/
level?: TitleLevel | keyof typeof TitleLevel;
/**
* Defines whether the VariantManagement is disabled.
*/
disabled?: boolean;
/**
* Fired after a variant has been selected.
*/
onSelect?: (
event: Ui5CustomEvent<
HTMLElement,
{
selectedVariant: SelectedVariant;
selectedItems: unknown[];
previouslySelectedItems: unknown[];
}
>
) => void;
/**
* Indicator for modified but not saved variants.
*
* __Note:__ You can change the indicator by setting `dirtyStateText`.
*/
dirtyState?: boolean;
/**
* Text for the dirty state indicator.
*/
dirtyStateText?: string;
/**
* Indicates that the 'Favorites' feature is used. Only variants marked as favorites will be displayed in the variant list.
*/
showOnlyFavorites?: boolean;
/**
* Indicates that set as default is visible in the Save View and the Manage Views dialogs.
*/
hideSetAsDefault?: boolean;
/**
* Indicates that the Public indicator is visible in the Save View and the Manage Views dialogs.
*/
hideShare?: boolean;
/**
* Indicates that Apply Automatically is visible in the Save View and the Manage Views dialogs.
*/
hideApplyAutomatically?: boolean;
/**
* Indicates that the Save View dialog button is visible.
*/
hideSaveAs?: boolean;
/**
* Indicates that the Manage Views dialog button is visible.
*/
hideManageVariants?: boolean;
/**
* Displays the cancel button in the popover.
*/
showCancelButton?: boolean;
/**
* Indicates that the control is in error state. If set to true error message will be displayed whenever the variant is opened.
*/
inErrorState?: boolean;
/**
* Defines where modals are rendered into via `React.createPortal`.
*
* Defaults to: `document.body`
*/
portalContainer?: Element;
/**
* The event is fired when the "Save" button is clicked inside the Save View dialog.
*/
onSaveAs?: (e: CustomEvent<SelectedVariant>) => void;
/**
* The event is fired when the "Save" button is clicked inside the Manage Views dialog.
*/
onSaveManageViews?: (
e: CustomEvent<{
deletedVariants: VariantItemPropTypes[];
prevVariants: VariantItemPropTypes[];
updatedVariants: UpdatedVariant[];
variants: SelectedVariant[];
}>
) => void;
/**
* The event is fired when the "Save" button is clicked in the `VariantManagement` popover.
*
* __Note:__ The save button is only displayed if the `VariantManagement` is in `dirtyState` and the selected variant is not in `readOnly` mode.
*/
onSave?: (e: CustomEvent<SelectedVariant>) => void;
}
const styles = {
container: {
display: 'flex',
alignItems: 'center',
textAlign: 'center'
},
title: {
cursor: 'pointer',
color: ThemingParameters.sapButton_TextColor,
'&:hover': {
color: ThemingParameters.sapButton_Hover_TextColor
}
},
disabled: {
'& $title': {
color: ThemingParameters.sapGroup_TitleTextColor,
cursor: 'default',
'&:hover': {
color: 'ThemingParameters.sapGroup_TitleTextColor'
}
}
},
dirtyState: {
color: ThemingParameters.sapGroup_TitleTextColor,
padding: '0 0.125rem',
fontWeight: 'bold',
font: ThemingParameters.sapFontFamily,
fontSize: ThemingParameters.sapFontSize,
flexGrow: 1
},
dirtyStateText: {
fontSize: ThemingParameters.sapFontSmallSize,
fontWeight: 'normal'
},
footer: {
margin: '0.4375rem 1rem 0.4325rem auto'
},
inputIcon: { cursor: 'pointer', color: ThemingParameters.sapContent_IconColor },
searchInput: { padding: '0.25rem 0.5rem 0.25rem 0.25rem' },
popover: { minWidth: '25rem' }
};
const useStyles = createUseStyles(styles, { name: 'VariantManagement' });
/**
* The `VariantManagement` component can be used to manage variants, such as FilterBar variants or AnalyticalTable variants.
*/
const VariantManagement = forwardRef((props: VariantManagementPropTypes, ref: Ref<HTMLDivElement>) => {
const i18nBundle = useI18nBundle('@ui5/webcomponents-react');
const {
titleText = i18nBundle.getText(MY_VIEWS),
className,
style,
tooltip,
placement,
level,
onSelect,
closeOnItemSelect,
disabled,
onSaveAs,
onSaveManageViews,
showOnlyFavorites,
inErrorState,
hideShare,
children,
hideManageVariants,
hideApplyAutomatically,
hideSetAsDefault,
hideSaveAs,
dirtyStateText,
dirtyState,
showCancelButton,
onSave,
portalContainer,
...rest
} = props;
const classes = useStyles();
const popoverRef = useRef<ResponsivePopoverDomRef>(null);
const [safeChildren, setSafeChildren] = useState(Children.toArray(children));
const [showInput, setShowInput] = useState(safeChildren.length > 9);
useEffect(() => {
setSafeChildren(Children.toArray(children));
}, [children]);
useEffect(() => {
if (safeChildren.length > 9) {
setShowInput(true);
} else {
setShowInput(false);
}
}, [safeChildren.length]);
const [manageViewsDialogOpen, setManageViewsDialogOpen] = useState(false);
const [saveAsDialogOpen, setSaveAsDialogOpen] = useState(false);
const [selectedVariant, setSelectedVariant] = useState<SelectedVariant | undefined>(() => {
const currentSelectedVariant = safeChildren.find(
(item) => isValidElement(item) && item.props.selected
) as ComponentElement<any, any>;
if (currentSelectedVariant) {
return { ...currentSelectedVariant.props, variantItem: currentSelectedVariant.ref };
}
});
const handleClose = () => {
popoverRef.current.close();
};
const handleManageClick = () => {
setManageViewsDialogOpen(true);
};
const handleManageClose = () => {
setManageViewsDialogOpen(false);
};
const handleOpenSaveAsDialog = () => {
setSaveAsDialogOpen(true);
};
const handleSaveAsClose = () => {
setSaveAsDialogOpen(false);
};
const handleSave = (e) => {
if (typeof onSave === 'function') {
onSave(enrichEventWithDetails(e, selectedVariant as Record<string, any>));
}
};
const handleSaveView = (e, selectedVariant) => {
if (typeof onSaveAs === 'function') {
onSaveAs(enrichEventWithDetails(e, selectedVariant));
}
handleSaveAsClose();
};
const handleSaveManageViews = (e, payload) => {
const { defaultView, updatedRows, deletedRows } = payload;
let callbackProperties = { deletedVariants: [], prevVariants: [], updatedVariants: [], variants: [] };
if (typeof onSaveManageViews === 'function') {
onSaveManageViews(enrichEventWithDetails(e, callbackProperties));
}
setSafeChildren((prev) =>
prev
.map((child: ComponentElement<any, any>) => {
let updatedProps: Omit<SelectedVariant, 'children' | 'variantItem'> = {};
const currentVariant = popoverRef.current.querySelector(`ui5-li[data-text="${child.props.children}"]`);
callbackProperties.prevVariants.push(child.props);
if (defaultView) {
if (defaultView === child.props.children) {
updatedProps.isDefault = true;
} else if (child.props.isDefault) {
updatedProps.isDefault = false;
}
}
if (Object.keys(updatedRows).includes(child.props.children)) {
const { currentVariant, ...rest } = updatedRows[child.props.children];
updatedProps = { ...updatedProps, ...rest };
}
if (deletedRows.has(child.props.children)) {
callbackProperties.deletedVariants.push(child.props);
return false;
}
if (Object.keys(updatedProps).length > 0) {
callbackProperties.updatedVariants.push({
...child.props,
...updatedProps,
variantItem: currentVariant,
prevVariant: { ...child.props }
});
}
callbackProperties.variants.push({ ...child.props, ...updatedProps, variantItem: currentVariant });
return cloneElement(child, updatedProps);
})
.filter(Boolean)
);
handleManageClose();
};
const handleOpenVariantManagement = useCallback(
(e) => {
popoverRef.current.showAt(e.target);
},
[popoverRef]
);
const cancelText = i18nBundle.getText(CANCEL);
const searchText = i18nBundle.getText(SEARCH);
const saveAsText = i18nBundle.getText(SAVE_AS);
const manageText = i18nBundle.getText(MANAGE);
const saveText = i18nBundle.getText(SAVE);
const a11ySearchText = i18nBundle.getText(SEARCH_VARIANT);
const selectViewText = i18nBundle.getText(SELECT_VIEW);
const resetIconTitleText = i18nBundle.getText(RESET);
const variantManagementClasses = clsx(classes.container, disabled && classes.disabled, className);
const dirtyStateClasses = clsx(classes.dirtyState, dirtyStateText !== '*' && classes.dirtyStateText);
const selectVariantEventRef = useRef();
useEffect(() => {
if (selectVariantEventRef.current) {
if (typeof onSelect === 'function') {
onSelect(enrichEventWithDetails(selectVariantEventRef.current, { selectedVariant }));
selectVariantEventRef.current = undefined;
}
}
}, [selectedVariant, onSelect]);
const handleVariantItemSelect = (e) => {
setSelectedVariant({ ...e.detail.selectedItems[0].dataset, variantItem: e.detail.selectedItems[0] });
selectVariantEventRef.current = e;
if (closeOnItemSelect) {
handleClose();
}
};
const variantNames = safeChildren.map((item: ComponentElement<any, any>) =>
typeof item.props?.children === 'string' ? item.props.children : ''
);
const [favoriteChildren, setFavoriteChildren] = useState(undefined);
useEffect(() => {
if (showOnlyFavorites) {
setFavoriteChildren(
safeChildren.filter((child: ComponentElement<any, any>) => child.props.favorite || child.props.isDefault)
);
}
if (!showOnlyFavorites && favoriteChildren?.length > 0) {
setFavoriteChildren(undefined);
}
}, [showOnlyFavorites, safeChildren]);
const safeChildrenWithFavorites = favoriteChildren ?? safeChildren;
const [filteredChildren, setFilteredChildren] = useState(undefined);
const [searchValue, setSearchValue] = useState('');
const handleSearchInput = (e) => {
setSearchValue(e.target.value);
setFilteredChildren(
safeChildrenWithFavorites.filter(
(child: ComponentElement<any, any>) =>
typeof child?.props?.children === 'string' &&
child.props.children.toLowerCase().includes(e.target.value.toLowerCase())
)
);
};
useEffect(() => {
if (filteredChildren) {
setFilteredChildren(
safeChildrenWithFavorites.filter(
(child: ComponentElement<any, any>) =>
typeof child?.props?.children === 'string' && child.props.children.toLowerCase().includes(searchValue)
)
);
}
}, [safeChildrenWithFavorites]);
const handleSpaceInput = (e) => {
if (e.code === 'Space') {
setSearchValue((prev) => prev + ' ');
}
};
const handleResetFilter = () => {
setSearchValue('');
setFilteredChildren(undefined);
};
const showSaveBtn = dirtyState && !selectedVariant?.readOnly;
return (
<div className={variantManagementClasses} style={style} title={tooltip} {...rest} ref={ref}>
<VariantManagementContext.Provider
value={{
selectVariantItem: setSelectedVariant
}}
>
<FlexBox onClick={disabled ? undefined : handleOpenVariantManagement}>
<Title level={level} className={classes.title}>
{selectedVariant?.children}
</Title>
{dirtyState && <div className={dirtyStateClasses}>{dirtyStateText}</div>}
</FlexBox>
<Button
tooltip={selectViewText}
aria-label={selectViewText}
onClick={handleOpenVariantManagement}
design={ButtonDesign.Transparent}
icon="navigation-down-arrow"
disabled={disabled}
/>
{createPortal(
<ResponsivePopover
className={classes.popover}
ref={popoverRef}
headerText={titleText}
placementType={placement}
footer={
(showSaveBtn || !hideSaveAs || !hideManageVariants || showCancelButton) && (
<Bar
endContent={
<>
{!inErrorState && showSaveBtn && (
<Button onClick={handleSave} design={ButtonDesign.Emphasized}>
{saveText}
</Button>
)}
{!inErrorState && !hideSaveAs && (
<Button
onClick={handleOpenSaveAsDialog}
design={showSaveBtn ? ButtonDesign.Transparent : ButtonDesign.Emphasized}
disabled={!selectedVariant || Object.keys(selectedVariant).length === 0}
>
{saveAsText}
</Button>
)}
{!inErrorState && !hideManageVariants && (
<Button
onClick={handleManageClick}
design={showSaveBtn || !hideSaveAs ? ButtonDesign.Transparent : ButtonDesign.Emphasized}
>
{manageText}
</Button>
)}
{showCancelButton && (
<Button
onClick={handleClose}
design={
!inErrorState && (showSaveBtn || !hideSaveAs || !hideManageVariants)
? ButtonDesign.Transparent
: ButtonDesign.Emphasized
}
>
{cancelText}
</Button>
)}
</>
}
/>
)
}
onAfterClose={stopPropagation}
>
{inErrorState ? (
<IllustratedMessage name={IllustrationMessageType.UnableToLoad} />
) : (
<List
onSelectionChange={handleVariantItemSelect}
mode={ListMode.SingleSelect}
header={
showInput ? (
<div className={classes.searchInput} tabIndex={-1}>
<Input
accessibleName={a11ySearchText}
value={searchValue}
placeholder={searchText}
onInput={handleSearchInput}
// todo remove when fixed
onKeyDown={handleSpaceInput}
icon={
<>
{filteredChildren && (
<Icon
accessibleName={resetIconTitleText}
tooltip={resetIconTitleText}
name="decline"
interactive
onClick={handleResetFilter}
className={classes.inputIcon}
/>
)}
<Icon name="search" className={classes.inputIcon} />
</>
}
/>
</div>
) : undefined
}
>
{filteredChildren ?? safeChildrenWithFavorites}
</List>
)}
</ResponsivePopover>,
portalContainer
)}
{manageViewsDialogOpen && (
<ManageViewsDialog
onAfterClose={handleManageClose}
handleSaveManageViews={handleSaveManageViews}
showShare={!hideShare}
showApplyAutomatically={!hideApplyAutomatically}
showSetAsDefault={!hideSetAsDefault}
variantNames={variantNames}
portalContainer={portalContainer}
>
{safeChildren}
</ManageViewsDialog>
)}
{saveAsDialogOpen && (
<SaveViewDialog
showShare={!hideShare}
showApplyAutomatically={!hideApplyAutomatically}
showSetAsDefault={!hideSetAsDefault}
onAfterClose={handleSaveAsClose}
handleSave={handleSaveView}
selectedVariant={selectedVariant}
variantNames={variantNames}
/>
)}
</VariantManagementContext.Provider>
</div>
);
});
VariantManagement.defaultProps = {
placement: PopoverPlacementType.Bottom,
level: TitleLevel.H4,
dirtyStateText: '*',
portalContainer: document.body
};
VariantManagement.displayName = 'VariantManagement';
export { VariantManagement }; | the_stack |
import fs from 'fs';
import path from 'path';
import fse from 'fs-extra';
import semver from 'semver';
import globby from 'globby';
import {
uniq, fastCloneDeep, get, trim
} from '@terascope/utils';
import toposort from 'toposort';
import MultiMap from 'mnemonist/multi-map';
import packageJson from 'package-json';
import sortPackageJson from 'sort-package-json';
import * as misc from './misc';
import * as i from './interfaces';
let _packages: i.PackageInfo[] = [];
let _e2eDir: string|undefined;
export function getE2EDir(): string|undefined {
if (_e2eDir) return _e2eDir;
if (fs.existsSync(path.join(misc.getRootDir(), 'e2e'))) {
_e2eDir = path.join(misc.getRootDir(), 'e2e');
return _e2eDir;
}
return undefined;
}
function _loadPackage(packagePath: string): i.PackageInfo|undefined {
const pkgJsonPath = path.join(packagePath, 'package.json');
if (fs.existsSync(pkgJsonPath)) {
return readPackageInfo(packagePath);
}
return undefined;
}
function _resolveWorkspaces(workspaces: string[], rootDir: string) {
return workspaces
.reduce(
(pkgDirs, pkgGlob) => [
...pkgDirs,
...(globby.hasMagic(pkgGlob)
? globby.sync(path.join(rootDir, pkgGlob), {
onlyDirectories: true,
})
: [path.join(rootDir, pkgGlob)]),
],
[] as string[]
);
}
export function listPackages(
ignoreCache?: boolean
): i.PackageInfo[] {
if (!ignoreCache && _packages && _packages.length) return _packages.slice();
const rootPkg = misc.getRootInfo();
if (!rootPkg.workspaces) return [];
const workspaces = (
Array.isArray(rootPkg.workspaces)
? rootPkg.workspaces
: rootPkg.workspaces.packages
).slice();
if (!workspaces) return [];
const hasE2E = workspaces.find((workspacePath) => workspacePath.includes('e2e'));
if (!hasE2E) {
workspaces.push('e2e');
}
const workspacePaths = _resolveWorkspaces(workspaces, misc.getRootDir());
const packages = workspacePaths
.map(_loadPackage)
.filter((pkg): pkg is i.PackageInfo => pkg?.name != null);
const sortedNames = getSortedPackages(packages);
_packages = sortedNames.map((name) => (
packages.find((pkg) => pkg.name === name)!
));
return _packages;
}
/**
* Sort the packages by dependencies
*/
function getSortedPackages(packages: i.PackageInfo[]): readonly string[] {
const used: [string, string|undefined][] = [];
const noDependencies: string[] = [];
const noDependents: string[] = [];
const names = new Set(packages.map((pkg) => pkg.name));
const deps = new MultiMap<string, string>(Set);
for (const pkg of packages) {
const allDeps = {
...pkg.dependencies,
...pkg.devDependencies,
...pkg.peerDependencies,
};
for (const name of Object.keys(allDeps)) {
if (names.has(name)) {
deps.set(name, pkg.name);
used.push([name, pkg.name]);
}
}
}
for (const name of names) {
if (!deps.get(name)?.size) {
noDependencies.push(name);
}
let hasDependent = false;
if (deps.has(name)) {
hasDependent = true;
} else {
for (const [otherName, otherDepSet] of deps.associations()) {
if (otherName !== name && otherDepSet.has(name)) {
// something is dependant on it
hasDependent = true;
break;
}
}
}
if (!hasDependent) noDependents.push(name);
}
const sorted = toposort(used);
const result = uniq(
noDependents.concat(
sorted,
noDependencies
)
);
return result;
}
export function getWorkspaceNames(): string[] {
const rootDir = misc.getRootDir();
const rootName = path.basename(rootDir);
return uniq(
listPackages()
.filter((pkg) => !('workspaces' in pkg))
.map((pkg) => path.basename(path.dirname(pkg.dir)))
.filter((name) => name && name !== '.' && name !== rootName)
);
}
export function getJestAliases(): Record<string, string> {
const aliases: Record<string, string> = {};
listPackages().forEach((pkg) => {
const key = `^${pkg.name}$`;
const mainFile = pkg.srcMain || pkg.main;
if (!mainFile) return;
aliases[key] = path.join(pkg.dir, mainFile);
});
return aliases;
}
export function getMainPackageInfo(): i.PackageInfo | undefined {
return listPackages().find(isMainPackage);
}
export function isMainPackage(pkgInfo: i.PackageInfo): boolean {
return get(pkgInfo, 'terascope.main', false);
}
export function addPackageConfig(pkgInfo: i.PackageInfo): void {
for (const _key of Object.keys(pkgInfo.terascope)) {
const key = _key as (keyof i.PackageConfig);
if (!i.AvailablePackageConfigKeys.includes(key)) {
throw new Error(`Unknown terascope config "${key}" found in "${pkgInfo.name}" package`);
}
}
}
export function readPackageInfo(folderPath: string): i.PackageInfo {
const dir = path.isAbsolute(folderPath)
? path.join(folderPath)
: path.join(misc.getRootDir(), folderPath);
const pkgJSONPath = path.join(dir, 'package.json');
const pkgJSON = getSortedPkgJSON(fse.readJSONSync(pkgJSONPath));
pkgJSON.dir = dir;
updatePkgInfo(pkgJSON);
return pkgJSON;
}
/** A stricter version of `getPkgInfo` */
export function findPackageByName(packages: i.PackageInfo[], name: string): i.PackageInfo {
const found = packages.find((info) => info.name === name);
if (!found) {
throw new Error(`Unable to find package ${name}`);
}
return found;
}
export function getPkgInfo(name: string): i.PackageInfo {
const found = listPackages().find((info) => [info.name, info.folderName].includes(name));
if (!found) {
throw new Error(`Unable to find package ${name}`);
}
return found;
}
export function getPkgNames(packages: i.PackageInfo[]): string[] {
return uniq(packages.map((pkgInfo) => pkgInfo.folderName)).sort();
}
export function updatePkgInfo(pkgInfo: i.PackageInfo): void {
if (!pkgInfo.dir) {
throw new Error('Missing dir on package.json reference');
}
if (!pkgInfo.terascope) pkgInfo.terascope = {};
if (pkgInfo.terascope.enableTypedoc && !fs.existsSync(path.join(pkgInfo.dir, 'tsconfig.json'))) {
pkgInfo.terascope.enableTypedoc = false;
}
const rootInfo = misc.getRootInfo();
if (!pkgInfo.private) {
if (!pkgInfo.publishConfig) {
pkgInfo.publishConfig = {
access: 'public',
registry: rootInfo.terascope.npm.registry,
};
} else {
pkgInfo.publishConfig = Object.assign({}, {
access: 'public',
registry: rootInfo.terascope.npm.registry,
}, pkgInfo.publishConfig);
}
} else {
delete pkgInfo.publishConfig;
}
pkgInfo.folderName = path.basename(pkgInfo.dir);
pkgInfo.relativeDir = path.relative(rootInfo.dir, pkgInfo.dir);
addPackageConfig(pkgInfo);
if (!pkgInfo.displayName) {
pkgInfo.displayName = misc.getName(pkgInfo.folderName);
}
if (!pkgInfo.license) {
pkgInfo.license = 'MIT';
}
pkgInfo.engines = { ...rootInfo.engines };
}
export function updatePkgJSON(
pkgInfo: i.PackageInfo|i.RootPackageInfo,
log?: boolean
): Promise<boolean> {
if (!get(pkgInfo, 'terascope.root')) {
updatePkgInfo(pkgInfo as i.PackageInfo);
}
const pkgJSON = getSortedPkgJSON(pkgInfo) as Partial<i.PackageInfo>;
delete pkgJSON.folderName;
delete pkgJSON.dir;
delete pkgJSON.relativeDir;
return misc.writeIfChanged(path.join(pkgInfo.dir, 'package.json'), pkgJSON, {
log,
});
}
function getSortedPkgJSON<T extends Record<string, any>>(pkgInfo: T): T {
return fastCloneDeep(sortPackageJson(pkgInfo));
}
export function getDocPath(pkgInfo: i.PackageInfo, withFileName: boolean, withExt = true): string {
const suite = pkgInfo.terascope.testSuite;
if (suite === 'e2e') {
const e2eDevDocs = path.join('docs/development');
fse.ensureDirSync(e2eDevDocs);
if (withFileName) {
return path.join(
e2eDevDocs,
withExt ? `${pkgInfo.folderName}.md` : pkgInfo.folderName
);
}
return e2eDevDocs;
}
const docPath = path.join('docs', pkgInfo.relativeDir);
fse.ensureDirSync(docPath);
if (withFileName) {
return path.join(
docPath,
withExt ? 'overview.md' : 'overview'
);
}
return docPath;
}
export function fixDepPkgName(name: string): string {
return trim(name).replace(/^\*\*\//, '').trim();
}
export async function getRemotePackageVersion(
pkgInfo: i.PackageInfo,
/** @internal this is used internally within this function and should not be used externally */
forceTag?: 'prerelease'|'latest'
): Promise<string> {
if (pkgInfo.private) return pkgInfo.version;
const registryUrl: string|undefined = get(pkgInfo, 'publishConfig.registry');
const tag = forceTag ?? getPublishTag(pkgInfo.version);
try {
const { version } = await packageJson(pkgInfo.name, {
version: tag,
registryUrl
});
return version as string;
} catch (err) {
if (err instanceof packageJson.VersionNotFoundError) {
if (tag === 'prerelease') {
// this will happen if there has never been a prerelease
// for this package, so lets check the latest so we
// get the correct package version
return getRemotePackageVersion(pkgInfo, 'latest');
}
return pkgInfo.version;
}
if (err instanceof packageJson.PackageNotFoundError) {
return '0.1.0';
}
throw err;
}
}
export function getPublishTag(version: string): 'prerelease'|'latest' {
const parsed = semver.parse(version);
if (!parsed) {
throw new Error(`Unable to publish invalid version "${version}"`);
}
if (parsed.prerelease.length) return 'prerelease';
return 'latest';
} | the_stack |
import { JiraIssue } from 'src/interfaces/jira/jira-issue.interface';
import { Vulnerability } from '../entity/Vulnerability';
import { JiraInit } from 'src/interfaces/jira/jira-init.interface';
import { decrypt } from './crypto.utility';
import { JiraResult } from 'src/interfaces/jira/jira-result.interface';
const j2m = require('jira2md');
const fetch = require('node-fetch');
import * as fs from 'fs';
import * as mime from 'mime-types';
import { IssueLink } from 'src/interfaces/jira/jira-issue-link.interface';
const JiraApi = require('jira-client');
let jira = null;
/**
* @description Entry function to create or update a JIRA ticket associated to a vulnerability
* @param {JiraInit} jiraInit
* @param {Vulnerability} vulnerability
* @returns success: return object errror: error message
*/
/* istanbul ignore next */
export const exportToJiraIssue = (vuln: Vulnerability, jiraInit: JiraInit): Promise<JiraResult> => {
return new Promise(async (resolve, reject) => {
initializeJira(jiraInit);
const assessment = vuln.assessment;
const parentKey = getIssueKey(assessment.jiraId);
let assessmentIssue;
try {
assessmentIssue = await jira.getIssue(parentKey);
} catch (err) {
reject(
`An error has occured. The JIRA issue ${getIssueKey(
vuln.jiraId
)} does not exist. Please update the JIRA URL and try again`
);
return;
}
const jiraIssue = await mapVulnToJiraIssue(vuln, assessmentIssue.fields.project.id);
if (!vuln.jiraId) {
try {
const result = await addNewJiraIssue(jiraIssue, parentKey, vuln);
resolve(result);
} catch (err) {
reject(err);
return;
}
} else {
try {
const result = await updateExistingJiraIssue(
jiraIssue,
parentKey,
vuln,
assessmentIssue.fields.project.id,
jiraInit
);
resolve(result);
} catch (err) {
reject(err);
return;
}
}
});
};
/**
* @description Add new Jira issue
* @param {any} jiraIssue
* @param {string} parentUrl
* @param {Vulnerability} vuln
* @returns Jira result
*/
/* istanbul ignore next */
const addNewJiraIssue = (jiraIssue: any, parentKey: string, vuln: Vulnerability): Promise<JiraResult> => {
return new Promise(async (resolve, reject) => {
let saved: any;
try {
saved = await jira.addNewIssue(jiraIssue);
if (parentKey) {
await issueLink(parentKey, saved.key, (err, res) => {
if (err) {
console.error(err);
}
});
}
} catch (err) {
console.error(err);
reject('The Jira export has failed.');
return;
}
const returnObj: JiraResult = {
id: saved.id,
key: saved.key,
self: saved.self,
message: `The vulnerability for "${vuln.name}" has been exported to Jira. Key: ${saved.key}`
};
if (vuln.screenshots) {
attachImages(vuln, returnObj.id);
}
resolve(returnObj);
});
};
/**
* @description Update existing Jira issue
* @param {any} jiraIssue
* @param {string} parentUrl
* @param {Vulnerability} vuln
* @returns Jira result
*/
/* istanbul ignore next */
const updateExistingJiraIssue = (
jiraIssue: any,
parentKey: string,
vuln: Vulnerability,
projectId: string,
jiraInit: JiraInit
): Promise<JiraResult> => {
return new Promise(async (resolve, reject) => {
let issueKey: string;
let existingIssue: any;
try {
issueKey = getIssueKey(vuln.jiraId);
existingIssue = await jira.getIssue(issueKey);
const updatedJiraIssue = await mapVulnToJiraIssue(vuln, projectId);
await jira.updateIssue(existingIssue.id, updatedJiraIssue);
if (parentKey) {
await issueLink(parentKey, existingIssue.key, (err, res) => {
if (err) {
console.error(err);
}
});
}
} catch (err) {
reject(
`An error has occured. The JIRA issue ${issueKey} does not exist. Please update the Jira field with a valid URL and try again.`
);
return;
}
if (vuln.screenshots) {
for await (const existScreenshot of existingIssue.fields.attachment) {
deleteIssueAttachment(existScreenshot.id, jiraInit);
}
attachImages(vuln, existingIssue.id);
}
const returnObj: JiraResult = {
id: existingIssue.id,
key: existingIssue.key,
self: existingIssue.self,
message: `The vulnerability for "${vuln.name}" has been updated in JIRA. Key: ${existingIssue.key}`
};
resolve(returnObj);
});
};
/**
* @description Links Jira ticket to parent ticket
* @param callback
* @param {string} issueKey
* @param {string} parentUrl
* @returns success: links jira issue to parent ticket
*/
/* istanbul ignore next */
const issueLink = async (parentUrl: string, issueKey: string, callback) => {
const parentKey = getIssueKey(parentUrl);
const link: IssueLink = {
outwardIssue: {
key: parentKey
},
inwardIssue: {
key: issueKey
},
type: {
name: 'Blocks'
}
};
try {
await jira.issueLink(link);
return;
} catch (err) {
console.error(err);
callback(`The JIRA Project "${parentKey}" does not exist.`);
}
};
/**
* @description Deletes Jira ticket attachment
* @param {string} id
* @param {JiraInit} jiraInit
* @returns success: return object errror: error message
*/
/* istanbul ignore next */
const deleteIssueAttachment = (id: string, jiraInit: JiraInit) => {
const auth = `${jiraInit.username}:${decrypt(jiraInit.apiKey)}`;
fetch(`https://${jiraInit.host}/rest/api/3/attachment/${id}`, {
method: 'DELETE',
headers: {
Authorization: `Basic ${Buffer.from(auth).toString('base64')}`
}
})
.then((response) => {
// tslint:disable-next-line: no-console
console.info(`${response.status} ${response.statusText}`);
})
.catch((err) => {
console.error(err);
});
};
/**
* @description Returns Jira issue key
* @param {string} url
* @returns string of key
*/
export const getIssueKey = (url: string): string => {
const ary: string[] = url.split('/');
return ary[ary.length - 1];
};
/**
* @description Initializes Jira
* @param {JiraInit} jiraInit
* @returns nothing
*/
/* istanbul ignore next */
const initializeJira = (jiraInit: JiraInit) => {
jira = new JiraApi({
protocol: 'https',
host: jiraInit.host,
username: jiraInit.username,
password: decrypt(jiraInit.apiKey),
apiVersion: '3',
strictSSL: true
});
};
/**
* @description Attaches one-to-many images to Jira ticket
* @param {string} issueId
* @param {Vulnerability} vulnerability
* @returns nothing
*/
/* istanbul ignore next */
const attachImages = async (vuln: Vulnerability, issueId: string) => {
for await (const screenshot of vuln.screenshots) {
// TODO: Figure out a way to create a stream from the buffer and pass that in
// Instead of creating a temporary file on the file system
const extension = mime.extension(screenshot.mimetype);
const path = `./src/temp/${screenshot.originalname}`;
await fs.writeFileSync(path, screenshot.buffer);
const stream = await fs.createReadStream(path);
await fs.unlinkSync(path);
try {
jira.addAttachmentOnIssue(issueId, stream);
} catch (err) {
console.error(err);
}
}
};
/**
* @description Maps Vulnerability information to Jira ticket
* @param {string} projectId
* @param {Vulnerability} vulnerability
* @returns JiraIssue object
*/
export const mapVulnToJiraIssue = async (vuln: Vulnerability, projectId: string) => {
const probLocRows = await dynamicProbLocTableRows(vuln);
const resourceRows = await dynamicResourceTableRows(vuln);
const jiraIssue: JiraIssue = {
update: {},
fields: {
project: {
id: projectId.toString()
},
priority: {
name: mapRiskToSeverity(vuln.risk)
},
summary: vuln.name,
description: {
type: 'doc',
version: 1,
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: `Impact: ${vuln.impact}`,
marks: [
{
type: 'strong'
}
]
}
]
},
{
type: 'paragraph',
content: [
{
type: 'text',
text: `Likelihood: ${vuln.likelihood}`,
marks: [
{
type: 'strong'
}
]
}
]
},
{
type: 'paragraph',
content: [
{
type: 'text',
text: `Overall Risk: ${vuln.risk}`,
marks: [
{
type: 'strong'
}
]
}
]
},
{
type: 'paragraph',
content: [
{
type: 'text',
text: `Systemic: ${vuln.systemic}`,
marks: [
{
type: 'strong'
}
]
}
]
},
{
type: 'paragraph',
content: [
{
type: 'text',
text: `CVSS Score: ${vuln.cvssScore}`,
marks: [
{
type: 'link',
attrs: {
href: vuln.cvssUrl
}
}
]
}
]
},
{
type: 'table',
attrs: {
isNumberColumnEnabled: false,
layout: 'default'
},
content: probLocRows
},
{
type: 'paragraph',
content: [
{
text: j2m.to_jira(vuln.description),
type: 'text'
}
]
},
{
type: 'paragraph',
content: [
{
text: j2m.to_jira(vuln.detailedInfo),
type: 'text'
}
]
},
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'Remediation',
marks: [
{
type: 'strong'
}
]
}
]
},
{
type: 'paragraph',
content: [
{
text: j2m.to_jira(vuln.remediation),
type: 'text'
}
]
},
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'Resources',
marks: [
{
type: 'strong'
}
]
}
]
},
{
type: 'table',
attrs: {
isNumberColumnEnabled: false,
layout: 'default'
},
content: resourceRows
}
]
},
issuetype: {
name: 'Bug'
}
}
};
return jiraIssue;
};
/**
* @description Dynamically creates Jira table for problem locations
* @param {Vulnerability} vulnerability
* @returns table rows
*/
const dynamicProbLocTableRows = async (vuln: Vulnerability) => {
const rows = [];
rows.push({
type: 'tableRow',
content: [
{
type: 'tableHeader',
attrs: {},
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'Problem Location'
}
]
}
]
},
{
type: 'tableHeader',
attrs: {},
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'Target'
}
]
}
]
}
]
});
if (vuln.problemLocations && vuln.problemLocations.length) {
for await (const probLoc of vuln.problemLocations) {
const row = {
type: 'tableRow',
content: [
{
type: 'tableCell',
attrs: {},
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: probLoc.location
}
]
}
]
},
{
type: 'tableCell',
attrs: {},
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: probLoc.target
}
]
}
]
}
]
};
rows.push(row);
}
}
return rows;
};
/**
* @description Dynamically creates Jira table for resources
* @param {Vulnerability} vulnerability
* @returns table rows
*/
const dynamicResourceTableRows = async (vuln: Vulnerability) => {
const rows = [];
rows.push({
type: 'tableRow',
content: [
{
type: 'tableHeader',
attrs: {},
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'Description'
}
]
}
]
},
{
type: 'tableHeader',
attrs: {},
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'Resource URL'
}
]
}
]
}
]
});
if (vuln.resources && vuln.resources.length) {
for await (const resource of vuln.resources) {
const row = {
type: 'tableRow',
content: [
{
type: 'tableCell',
attrs: {},
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: resource.description
}
]
}
]
},
{
type: 'tableCell',
attrs: {},
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: resource.url,
marks: [
{
type: 'link',
attrs: {
href: resource.url
}
}
]
}
]
}
]
}
]
};
rows.push(row);
}
}
return rows;
};
/**
* @description Maps overall risk severity to Jira priority
* @param {Vulnerability} vulnerability
* @returns jira priority string
*/
export const mapRiskToSeverity = (risk: string) => {
switch (risk) {
case 'Informational':
return 'Lowest';
case 'Low':
return 'Low';
case 'Medium':
return 'Medium';
case 'High':
return 'High';
case 'Critical':
return 'Highest';
default:
return '';
}
}; | the_stack |
declare module com {
export module vincent {
export module filepicker {
export class BuildConfig {
public static class: java.lang.Class<com.vincent.filepicker.BuildConfig>;
public static DEBUG: boolean;
public static APPLICATION_ID: string;
public static BUILD_TYPE: string;
public static FLAVOR: string;
public static VERSION_CODE: number;
public static VERSION_NAME: string;
public constructor();
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export class Constant {
public static class: java.lang.Class<com.vincent.filepicker.Constant>;
public static MAX_NUMBER: string;
public static MAX_VIDEO_DURATION: string;
public static VIDEO_QUALITY: string;
public static MAX_AUDIO_SIZE: string;
public static REQUEST_CODE_PICK_IMAGE: number;
public static RESULT_PICK_IMAGE: string;
public static REQUEST_CODE_TAKE_IMAGE: number;
public static REQUEST_CODE_BROWSER_IMAGE: number;
public static RESULT_BROWSER_IMAGE: string;
public static REQUEST_CODE_PICK_VIDEO: number;
public static RESULT_PICK_VIDEO: string;
public static REQUEST_CODE_TAKE_VIDEO: number;
public static REQUEST_CODE_PICK_AUDIO: number;
public static RESULT_PICK_AUDIO: string;
public static REQUEST_CODE_TAKE_AUDIO: number;
public static REQUEST_CODE_PICK_FILE: number;
public static RESULT_PICK_FILE: string;
public constructor();
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export class DividerGridItemDecoration {
public static class: java.lang.Class<com.vincent.filepicker.DividerGridItemDecoration>;
public drawVertical(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.support.v7.widget.RecyclerView): void;
public constructor(param0: globalAndroid.content.Context);
public onDraw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.support.v7.widget.RecyclerView, param2: globalAndroid.support.v7.widget.RecyclerView.State): void;
public getItemOffsets(param0: globalAndroid.graphics.Rect, param1: number, param2: globalAndroid.support.v7.widget.RecyclerView): void;
public drawHorizontal(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.support.v7.widget.RecyclerView): void;
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export class DividerListItemDecoration {
public static class: java.lang.Class<com.vincent.filepicker.DividerListItemDecoration>;
public getItemOffsets(param0: globalAndroid.graphics.Rect, param1: globalAndroid.view.View, param2: globalAndroid.support.v7.widget.RecyclerView, param3: globalAndroid.support.v7.widget.RecyclerView.State): void;
public onDraw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.support.v7.widget.RecyclerView, param2: globalAndroid.support.v7.widget.RecyclerView.State): void;
public constructor(param0: globalAndroid.content.Context, param1: number);
public constructor(param0: globalAndroid.content.Context, param1: number, param2: number);
public onDrawOver(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.support.v7.widget.RecyclerView, param2: globalAndroid.support.v7.widget.RecyclerView.State): void;
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export class FolderListHelper {
public static class: java.lang.Class<com.vincent.filepicker.FolderListHelper>;
public setFolderListListener(param0: com.vincent.filepicker.adapter.FolderListAdapter.FolderListListener): void;
public toggle(param0: globalAndroid.view.View): void;
public initFolderListView(param0: globalAndroid.content.Context): void;
public fillData(param0: java.util.List<com.vincent.filepicker.filter.entity.Directory<any>>): void;
public constructor();
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export class MaxHeightLayout {
public static class: java.lang.Class<com.vincent.filepicker.MaxHeightLayout>;
public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet);
public constructor(param0: globalAndroid.content.Context);
public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number);
public onMeasure(param0: number, param1: number): void;
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export class ToastUtil {
public static class: java.lang.Class<com.vincent.filepicker.ToastUtil>;
public showToast(param0: string): void;
public cancelToast(): void;
public showToast(param0: number): void;
public static getInstance(param0: globalAndroid.content.Context): com.vincent.filepicker.ToastUtil;
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export class Util {
public static class: java.lang.Class<com.vincent.filepicker.Util>;
public static dip2px(param0: globalAndroid.content.Context, param1: number): number;
public static extractFileNameWithoutSuffix(param0: string): string;
public static getScreenWidth(param0: globalAndroid.content.Context): number;
public static getDurationString(param0: number): string;
public static extractPathWithSeparator(param0: string): string;
public static extractPathWithoutSeparator(param0: string): string;
public static extractFileSuffix(param0: string): string;
public static extractFileNameWithSuffix(param0: string): string;
public static getScreenHeight(param0: globalAndroid.content.Context): number;
public static px2dip(param0: globalAndroid.content.Context, param1: number): number;
public static detectIntent(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): boolean;
public constructor();
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module activity {
export class AudioPickActivity extends com.vincent.filepicker.activity.BaseActivity {
public static class: java.lang.Class<com.vincent.filepicker.activity.AudioPickActivity>;
public static IS_NEED_RECORDER: string;
public static IS_TAKEN_AUTO_SELECTED: string;
public static DEFAULT_MAX_NUMBER: number;
public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void;
public onCreate(param0: globalAndroid.os.Bundle): void;
public constructor();
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module activity {
export abstract class BaseActivity {
public static class: java.lang.Class<com.vincent.filepicker.activity.BaseActivity>;
public mFolderHelper: com.vincent.filepicker.FolderListHelper;
public isNeedFolderList: boolean;
public static IS_NEED_FOLDER_LIST: string;
public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void;
public onCreate(param0: globalAndroid.os.Bundle): void;
public onPermissionsDenied(param0: number, param1: java.util.List<string>): void;
public constructor();
public onPostCreate(param0: globalAndroid.os.Bundle): void;
public onBackClick(param0: globalAndroid.view.View): void;
public onRequestPermissionsResult(param0: number, param1: native.Array<string>, param2: native.Array<number>): void;
public onPermissionsGranted(param0: number, param1: java.util.List<string>): void;
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module activity {
export class ImageBrowserActivity extends com.vincent.filepicker.activity.BaseActivity {
public static class: java.lang.Class<com.vincent.filepicker.activity.ImageBrowserActivity>;
public static IMAGE_BROWSER_INIT_INDEX: string;
public static IMAGE_BROWSER_SELECTED_LIST: string;
public onCreate(param0: globalAndroid.os.Bundle): void;
public onCreateOptionsMenu(param0: globalAndroid.view.Menu): boolean;
public constructor();
public onBackPressed(): void;
public onOptionsItemSelected(param0: globalAndroid.view.MenuItem): boolean;
}
export module ImageBrowserActivity {
export class ImageBrowserAdapter {
public static class: java.lang.Class<com.vincent.filepicker.activity.ImageBrowserActivity.ImageBrowserAdapter>;
public isViewFromObject(param0: globalAndroid.view.View, param1: any): boolean;
public destroyItem(param0: globalAndroid.view.ViewGroup, param1: number, param2: any): void;
public getCount(): number;
public instantiateItem(param0: globalAndroid.view.ViewGroup, param1: number): any;
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module activity {
export class ImagePickActivity extends com.vincent.filepicker.activity.BaseActivity {
public static class: java.lang.Class<com.vincent.filepicker.activity.ImagePickActivity>;
public static IS_NEED_CAMERA: string;
public static IS_NEED_IMAGE_PAGER: string;
public static IS_TAKEN_AUTO_SELECTED: string;
public static DEFAULT_MAX_NUMBER: number;
public static COLUMN_NUMBER: number;
public mSelectedList: java.util.ArrayList<com.vincent.filepicker.filter.entity.ImageFile>;
public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void;
public onCreate(param0: globalAndroid.os.Bundle): void;
public constructor();
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module activity {
export class NormalFilePickActivity extends com.vincent.filepicker.activity.BaseActivity {
public static class: java.lang.Class<com.vincent.filepicker.activity.NormalFilePickActivity>;
public static DEFAULT_MAX_NUMBER: number;
public static SUFFIX: string;
public onCreate(param0: globalAndroid.os.Bundle): void;
public constructor();
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module activity {
export class VideoPickActivity extends com.vincent.filepicker.activity.BaseActivity {
public static class: java.lang.Class<com.vincent.filepicker.activity.VideoPickActivity>;
public static THUMBNAIL_PATH: string;
public static IS_NEED_CAMERA: string;
public static IS_TAKEN_AUTO_SELECTED: string;
public static DEFAULT_MAX_NUMBER: number;
public static DEFAULT_MAX_VIDEO_DURATION: number;
public static COLUMN_NUMBER: number;
public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void;
public onCreate(param0: globalAndroid.os.Bundle): void;
public constructor();
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module adapter {
export class AudioPickAdapter extends com.vincent.filepicker.adapter.BaseAdapter<com.vincent.filepicker.filter.entity.AudioFile,com.vincent.filepicker.adapter.AudioPickAdapter.AudioPickViewHolder> {
public static class: java.lang.Class<com.vincent.filepicker.adapter.AudioPickAdapter>;
public onBindViewHolder(param0: com.vincent.filepicker.adapter.AudioPickAdapter.AudioPickViewHolder, param1: number): void;
public constructor(param0: globalAndroid.content.Context, param1: number);
public getItemCount(): number;
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<com.vincent.filepicker.filter.entity.AudioFile>, param2: number);
public setCurrentNumber(param0: number): void;
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<any>);
public isUpToMax(): boolean;
public onCreateViewHolder(param0: globalAndroid.view.ViewGroup, param1: number): com.vincent.filepicker.adapter.AudioPickAdapter.AudioPickViewHolder;
}
export module AudioPickAdapter {
export class AudioPickViewHolder {
public static class: java.lang.Class<com.vincent.filepicker.adapter.AudioPickAdapter.AudioPickViewHolder>;
public constructor(param0: com.vincent.filepicker.adapter.AudioPickAdapter, param1: globalAndroid.view.View);
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module adapter {
export abstract class BaseAdapter<T, VH> extends globalAndroid.support.v7.widget.RecyclerView.Adapter<any> {
public static class: java.lang.Class<com.vincent.filepicker.adapter.BaseAdapter<any,any>>;
public mContext: globalAndroid.content.Context;
public mList: java.util.ArrayList<any>;
public mListener: com.vincent.filepicker.adapter.OnSelectStateListener<any>;
public add(param0: any): void;
public add(param0: number, param1: any): void;
public refresh(param0: any): void;
public setOnSelectStateListener(param0: com.vincent.filepicker.adapter.OnSelectStateListener<any>): void;
public add(param0: java.util.List<any>): void;
public refresh(param0: java.util.List<any>): void;
public getDataSet(): java.util.List<any>;
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<any>);
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module adapter {
export class FolderListAdapter extends com.vincent.filepicker.adapter.BaseAdapter<com.vincent.filepicker.filter.entity.Directory<any>,com.vincent.filepicker.adapter.FolderListAdapter.FolderListViewHolder> {
public static class: java.lang.Class<com.vincent.filepicker.adapter.FolderListAdapter>;
public onCreateViewHolder(param0: globalAndroid.view.ViewGroup, param1: number): com.vincent.filepicker.adapter.FolderListAdapter.FolderListViewHolder;
public onBindViewHolder(param0: com.vincent.filepicker.adapter.FolderListAdapter.FolderListViewHolder, param1: number): void;
public setListener(param0: com.vincent.filepicker.adapter.FolderListAdapter.FolderListListener): void;
public getItemCount(): number;
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<any>);
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<com.vincent.filepicker.filter.entity.Directory<any>>);
}
export module FolderListAdapter {
export class FolderListListener {
public static class: java.lang.Class<com.vincent.filepicker.adapter.FolderListAdapter.FolderListListener>;
/**
* Constructs a new instance of the com.vincent.filepicker.adapter.FolderListAdapter$FolderListListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onFolderListClick(param0: com.vincent.filepicker.filter.entity.Directory<any>): void;
});
public constructor();
public onFolderListClick(param0: com.vincent.filepicker.filter.entity.Directory<any>): void;
}
export class FolderListViewHolder {
public static class: java.lang.Class<com.vincent.filepicker.adapter.FolderListAdapter.FolderListViewHolder>;
public constructor(param0: com.vincent.filepicker.adapter.FolderListAdapter, param1: globalAndroid.view.View);
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module adapter {
export class ImagePickAdapter extends com.vincent.filepicker.adapter.BaseAdapter<com.vincent.filepicker.filter.entity.ImageFile,com.vincent.filepicker.adapter.ImagePickAdapter.ImagePickViewHolder> {
public static class: java.lang.Class<com.vincent.filepicker.adapter.ImagePickAdapter>;
public mImagePath: string;
public mImageUri: globalAndroid.net.Uri;
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<com.vincent.filepicker.filter.entity.ImageFile>, param2: boolean, param3: boolean, param4: number);
public onBindViewHolder(param0: com.vincent.filepicker.adapter.ImagePickAdapter.ImagePickViewHolder, param1: number): void;
public getItemCount(): number;
public constructor(param0: globalAndroid.content.Context, param1: boolean, param2: boolean, param3: number);
public onCreateViewHolder(param0: globalAndroid.view.ViewGroup, param1: number): com.vincent.filepicker.adapter.ImagePickAdapter.ImagePickViewHolder;
public setCurrentNumber(param0: number): void;
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<any>);
public isUpToMax(): boolean;
}
export module ImagePickAdapter {
export class ImagePickViewHolder {
public static class: java.lang.Class<com.vincent.filepicker.adapter.ImagePickAdapter.ImagePickViewHolder>;
public constructor(param0: com.vincent.filepicker.adapter.ImagePickAdapter, param1: globalAndroid.view.View);
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module adapter {
export class NormalFilePickAdapter extends com.vincent.filepicker.adapter.BaseAdapter<com.vincent.filepicker.filter.entity.NormalFile,com.vincent.filepicker.adapter.NormalFilePickAdapter.NormalFilePickViewHolder> {
public static class: java.lang.Class<com.vincent.filepicker.adapter.NormalFilePickAdapter>;
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<com.vincent.filepicker.filter.entity.NormalFile>, param2: number);
public constructor(param0: globalAndroid.content.Context, param1: number);
public getItemCount(): number;
public onBindViewHolder(param0: com.vincent.filepicker.adapter.NormalFilePickAdapter.NormalFilePickViewHolder, param1: number): void;
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<any>);
public onCreateViewHolder(param0: globalAndroid.view.ViewGroup, param1: number): com.vincent.filepicker.adapter.NormalFilePickAdapter.NormalFilePickViewHolder;
}
export module NormalFilePickAdapter {
export class NormalFilePickViewHolder {
public static class: java.lang.Class<com.vincent.filepicker.adapter.NormalFilePickAdapter.NormalFilePickViewHolder>;
public constructor(param0: com.vincent.filepicker.adapter.NormalFilePickAdapter, param1: globalAndroid.view.View);
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module adapter {
export class OnSelectStateListener<T> extends java.lang.Object {
public static class: java.lang.Class<com.vincent.filepicker.adapter.OnSelectStateListener<any>>;
/**
* Constructs a new instance of the com.vincent.filepicker.adapter.OnSelectStateListener<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
OnSelectStateChanged(param0: boolean, param1: T): void;
});
public constructor();
public OnSelectStateChanged(param0: boolean, param1: T): void;
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module adapter {
export class VideoPickAdapter extends com.vincent.filepicker.adapter.BaseAdapter<com.vincent.filepicker.filter.entity.VideoFile,com.vincent.filepicker.adapter.VideoPickAdapter.VideoPickViewHolder> {
public static class: java.lang.Class<com.vincent.filepicker.adapter.VideoPickAdapter>;
public mVideoPath: string;
public constructor(param0: globalAndroid.content.Context, param1: boolean, param2: number, param3: number, param4: number);
public onBindViewHolder(param0: com.vincent.filepicker.adapter.VideoPickAdapter.VideoPickViewHolder, param1: number): void;
public getItemCount(): number;
public onCreateViewHolder(param0: globalAndroid.view.ViewGroup, param1: number): com.vincent.filepicker.adapter.VideoPickAdapter.VideoPickViewHolder;
public setCurrentNumber(param0: number): void;
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<any>);
public isUpToMax(): boolean;
public constructor(param0: globalAndroid.content.Context, param1: java.util.ArrayList<com.vincent.filepicker.filter.entity.VideoFile>, param2: boolean, param3: number, param4: number, param5: number);
}
export module VideoPickAdapter {
export class VideoPickViewHolder {
public static class: java.lang.Class<com.vincent.filepicker.adapter.VideoPickAdapter.VideoPickViewHolder>;
public constructor(param0: com.vincent.filepicker.adapter.VideoPickAdapter, param1: globalAndroid.view.View);
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export class FileFilter {
public static class: java.lang.Class<com.vincent.filepicker.filter.FileFilter>;
public static getAudios(param0: globalAndroid.support.v4.app.FragmentActivity, param1: com.vincent.filepicker.filter.callback.FilterResultCallback<com.vincent.filepicker.filter.entity.AudioFile>): void;
public constructor();
public static getImages(param0: globalAndroid.support.v4.app.FragmentActivity, param1: com.vincent.filepicker.filter.callback.FilterResultCallback<com.vincent.filepicker.filter.entity.ImageFile>): void;
public static getFiles(param0: globalAndroid.support.v4.app.FragmentActivity, param1: com.vincent.filepicker.filter.callback.FilterResultCallback<com.vincent.filepicker.filter.entity.NormalFile>, param2: native.Array<string>): void;
public static getVideos(param0: globalAndroid.support.v4.app.FragmentActivity, param1: com.vincent.filepicker.filter.callback.FilterResultCallback<com.vincent.filepicker.filter.entity.VideoFile>): void;
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module callback {
export class FileLoaderCallbacks extends globalAndroid.support.v4.app.LoaderManager.LoaderCallbacks<globalAndroid.database.Cursor> {
public static class: java.lang.Class<com.vincent.filepicker.filter.callback.FileLoaderCallbacks>;
public static TYPE_IMAGE: number;
public static TYPE_VIDEO: number;
public static TYPE_AUDIO: number;
public static TYPE_FILE: number;
public constructor(param0: globalAndroid.content.Context, param1: com.vincent.filepicker.filter.callback.FilterResultCallback<any>, param2: number, param3: native.Array<string>);
public constructor(param0: globalAndroid.content.Context, param1: com.vincent.filepicker.filter.callback.FilterResultCallback<any>, param2: number);
public onCreateLoader(param0: number, param1: globalAndroid.os.Bundle): globalAndroid.support.v4.content.Loader<globalAndroid.database.Cursor>;
public onLoaderReset(param0: globalAndroid.support.v4.content.Loader<globalAndroid.database.Cursor>): void;
public onLoadFinished(param0: globalAndroid.support.v4.content.Loader<globalAndroid.database.Cursor>, param1: globalAndroid.database.Cursor): void;
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module callback {
export class FilterResultCallback<T> extends java.lang.Object {
public static class: java.lang.Class<com.vincent.filepicker.filter.callback.FilterResultCallback<any>>;
/**
* Constructs a new instance of the com.vincent.filepicker.filter.callback.FilterResultCallback<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onResult(param0: java.util.List<com.vincent.filepicker.filter.entity.Directory<T>>): void;
});
public constructor();
public onResult(param0: java.util.List<com.vincent.filepicker.filter.entity.Directory<T>>): void;
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module entity {
export class AudioFile extends com.vincent.filepicker.filter.entity.BaseFile {
public static class: java.lang.Class<com.vincent.filepicker.filter.entity.AudioFile>;
public static CREATOR: globalAndroid.os.Parcelable.Creator<com.vincent.filepicker.filter.entity.AudioFile>;
public constructor();
public describeContents(): number;
public getDuration(): number;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public setDuration(param0: number): void;
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module entity {
export class BaseFile {
public static class: java.lang.Class<com.vincent.filepicker.filter.entity.BaseFile>;
public static CREATOR: globalAndroid.os.Parcelable.Creator<com.vincent.filepicker.filter.entity.BaseFile>;
public setSize(param0: number): void;
public setDate(param0: number): void;
public constructor();
public describeContents(): number;
public setName(param0: string): void;
public getBucketName(): string;
public isSelected(): boolean;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public equals(param0: any): boolean;
public hashCode(): number;
public getPath(): string;
public getName(): string;
public setBucketId(param0: string): void;
public getId(): number;
public setId(param0: number): void;
public setPath(param0: string): void;
public getSize(): number;
public setSelected(param0: boolean): void;
public getBucketId(): string;
public getDate(): number;
public setBucketName(param0: string): void;
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module entity {
export class Directory<T> extends java.lang.Object {
public static class: java.lang.Class<com.vincent.filepicker.filter.entity.Directory<any>>;
public setPath(param0: string): void;
public constructor();
public getFiles(): java.util.List<T>;
public setName(param0: string): void;
public setId(param0: string): void;
public setFiles(param0: java.util.List<T>): void;
public equals(param0: any): boolean;
public hashCode(): number;
public getId(): string;
public getPath(): string;
public getName(): string;
public addFile(param0: T): void;
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module entity {
export class ImageFile extends com.vincent.filepicker.filter.entity.BaseFile {
public static class: java.lang.Class<com.vincent.filepicker.filter.entity.ImageFile>;
public static CREATOR: globalAndroid.os.Parcelable.Creator<com.vincent.filepicker.filter.entity.ImageFile>;
public constructor();
public describeContents(): number;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public setOrientation(param0: number): void;
public getOrientation(): number;
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module entity {
export class NormalFile extends com.vincent.filepicker.filter.entity.BaseFile {
public static class: java.lang.Class<com.vincent.filepicker.filter.entity.NormalFile>;
public static CREATOR: globalAndroid.os.Parcelable.Creator<com.vincent.filepicker.filter.entity.NormalFile>;
public constructor();
public describeContents(): number;
public getMimeType(): string;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public setMimeType(param0: string): void;
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module entity {
export class VideoFile extends com.vincent.filepicker.filter.entity.BaseFile {
public static class: java.lang.Class<com.vincent.filepicker.filter.entity.VideoFile>;
public static CREATOR: globalAndroid.os.Parcelable.Creator<com.vincent.filepicker.filter.entity.VideoFile>;
public constructor();
public describeContents(): number;
public getDuration(): number;
public getThumbnail(): string;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public setThumbnail(param0: string): void;
public setDuration(param0: number): void;
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module loader {
export class AudioLoader {
public static class: java.lang.Class<com.vincent.filepicker.filter.loader.AudioLoader>;
public constructor(param0: globalAndroid.content.Context);
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module loader {
export class FileLoader {
public static class: java.lang.Class<com.vincent.filepicker.filter.loader.FileLoader>;
public constructor(param0: globalAndroid.content.Context);
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module loader {
export class ImageLoader {
public static class: java.lang.Class<com.vincent.filepicker.filter.loader.ImageLoader>;
public constructor(param0: globalAndroid.content.Context);
}
}
}
}
}
}
declare module com {
export module vincent {
export module filepicker {
export module filter {
export module loader {
export class VideoLoader {
public static class: java.lang.Class<com.vincent.filepicker.filter.loader.VideoLoader>;
public constructor(param0: globalAndroid.content.Context);
}
}
}
}
}
}
//Generics information:
//com.vincent.filepicker.adapter.BaseAdapter:2
//com.vincent.filepicker.adapter.OnSelectStateListener:1
//com.vincent.filepicker.filter.callback.FilterResultCallback:1
//com.vincent.filepicker.filter.entity.Directory:1 | the_stack |
// ~/bundles/shared/common
export { setLanguagePreferenceCookie } from '@Shared/TopBar';
export { default as ui } from '@Shared/MessagesTyped';
export { default as functions } from '@Shared/GlobalFunctions';
export { default as HttpClient } from '@Shared/HttpClient';
export { default as UrlMapper } from '@Shared/UrlMapper';
import '@KnockoutExtensions/StopBinding';
import '@KnockoutExtensions/Show';
export { default as EntryReportRepository } from '@Repositories/EntryReportRepository';
export { default as UserRepository } from '@Repositories/UserRepository';
export { default as TopBarViewModel } from '@ViewModels/TopBarViewModel';
export { default as SharedLayoutScripts } from '@Shared/LayoutScripts';
// ~/bundles/shared/main
export { default as EntryUrlMapper } from '@Shared/EntryUrlMapper';
import '@KnockoutExtensions/ConfirmClick';
import '@KnockoutExtensions/Dialog';
import '@KnockoutExtensions/EntryToolTip';
import '@KnockoutExtensions/jqButton';
import '@KnockoutExtensions/jqButtonset';
import '@KnockoutExtensions/Markdown';
import '@KnockoutExtensions/ToggleClick';
import '@KnockoutExtensions/Song/SongTypeLabel';
import '@KnockoutExtensions/Bootstrap/Tooltip';
import '@KnockoutExtensions/qTip';
import '@KnockoutExtensions/TagAutoComplete';
import '@KnockoutExtensions/Filters/Truncate';
export { default as RepositoryFactory } from '@Repositories/RepositoryFactory';
export { default as TagRepository } from '@Repositories/TagRepository';
export { default as ResourceRepository } from '@Repositories/ResourceRepository';
export { default as SongRepository } from '@Repositories/SongRepository';
export { default as ArtistRepository } from '@Repositories/ArtistRepository';
// ~/bundles/shared/edit
export { default as DialogService } from '@Shared/DialogService';
import '@KnockoutExtensions/ArtistAutoComplete';
import '@KnockoutExtensions/SongAutoComplete';
import '@KnockoutExtensions/FocusOut';
import '@KnockoutExtensions/InitialValue';
// ~/bundles/Home/Index
export { default as NewsListViewModel } from '@ViewModels/NewsListViewModel';
export { default as HomeIndex } from './Home/Index';
// ~/bundles/ActivityEntry/Index
import '@KnockoutExtensions/MomentJsTimeAgo';
//export { default as ResourceRepository } from '@Repositories/ResourceRepository';
export { default as ActivityEntryListViewModel } from '@ViewModels/ActivityEntry/ActivityEntryListViewModel';
export { default as ActivityEntryIndex } from './ActivityEntry/Index';
// ~/bundles/Admin/ManageEntryTagMappings
import '@KnockoutExtensions/TagAutoComplete';
export { default as ManageEntryTagMappingsViewModel } from '@ViewModels/Admin/ManageEntryTagMappingsViewModel';
export { default as AdminManageEntryTagMappings } from './Admin/ManageEntryTagMappings';
// ~/bundles/Admin/ManageTagMappings
import '@KnockoutExtensions/TagAutoComplete';
export { default as ManageTagMappingsViewModel } from '@ViewModels/Admin/ManageTagMappingsViewModel';
export { default as AdminManageTagMappings } from './Admin/ManageTagMappings';
// ~/bundles/Admin/ManageIPRules
import '@KnockoutExtensions/FormatDateFilter';
export { default as AdminRepository } from '@Repositories/AdminRepository';
export { default as ManageIPRulesViewModel } from '@ViewModels/Admin/ManageIPRulesViewModel';
export { default as AdminManageIPRules } from './Admin/ManageIPRules';
// ~/bundles/Admin/ManageWebhooks
export { default as AdminManageWebhooks } from './Admin/ManageWebhooks';
// ~/bundles/Admin/PVsByAuthor
export { default as AdminPVsByAuthor } from './Admin/PVsByAuthor';
// ~/bundles/Admin/ViewAuditLog
export { default as ViewAuditLogViewModel } from '@ViewModels/Admin/ViewAuditLogViewModel';
export { default as AdminViewAuditLog } from './Admin/ViewAuditLog';
// ~/bundles/Album/Create
export { default as AlbumCreateViewModel } from '@ViewModels/Album/AlbumCreateViewModel';
export { default as AlbumCreate } from './Album/Create';
// ~/bundles/Album/Deleted
export { default as AlbumRepository } from '@Repositories/AlbumRepository';
export { default as DeletedAlbumsViewModel } from '@ViewModels/Album/DeletedAlbumsViewModel';
export { default as AlbumDeleted } from './Album/Deleted';
// ~/bundles/Album/Details
import '@KnockoutExtensions/MomentJsTimeAgo';
import '@KnockoutExtensions/FormatDateFilter';
export { default as AlbumDetailsViewModel } from '@ViewModels/Album/AlbumDetailsViewModel';
export { default as AlbumDetails } from './Album/Details';
// ~/bundles/Album/Edit
import '@KnockoutExtensions/ParseInteger';
import '@KnockoutExtensions/FormatLengthSecondsFilter';
import '@KnockoutExtensions/BindingHandlers/ReleaseEventAutoComplete';
import '@KnockoutExtensions/FormatDateFilter';
export { default as AlbumEditViewModel } from '@ViewModels/Album/AlbumEditViewModel';
export { default as AlbumEdit } from './Album/Edit';
// ~/bundles/Album/Merge
import '@KnockoutExtensions/AlbumAutoComplete';
//export { default as AlbumRepository } from '@Repositories/AlbumRepository';
export { default as AlbumMergeViewModel } from '@ViewModels/Album/AlbumMergeViewModel';
export { default as AlbumMerge } from './Album/Merge';
// ~/bundles/Album/ViewVersion
//export { default as AlbumRepository } from '@Repositories/AlbumRepository';
export { default as ArchivedAlbumViewModel } from '@ViewModels/Album/ArchivedAlbumViewModel';
export { default as AlbumViewVersion } from './Album/ViewVersion';
// ~/bundles/Artist/Create
export { default as ArtistCreateViewModel } from '@ViewModels/ArtistCreateViewModel';
export { default as ArtistCreate } from './Artist/Create';
// ~/bundles/Artist/Details
import '@KnockoutExtensions/MomentJsTimeAgo';
import '@KnockoutExtensions/SlideVisible';
import '@KnockoutExtensions/ScrollEnd';
import '@KnockoutExtensions/Highcharts';
export { default as PVPlayersFactory } from '@ViewModels/PVs/PVPlayersFactory';
export { default as ArtistDetailsViewModel } from '@ViewModels/Artist/ArtistDetailsViewModel';
export { default as ArtistDetails } from './Artist/Details';
// ~/bundles/Artist/Edit
import '@KnockoutExtensions/BindingHandlers/DatePicker';
export { default as ArtistEditViewModel } from '@ViewModels/Artist/ArtistEditViewModel';
export { default as ArtistEdit } from './Artist/Edit';
// ~/bundles/Artist/Merge
import '@KnockoutExtensions/ArtistAutoComplete';
export { default as ArtistMergeViewModel } from '@ViewModels/Artist/ArtistMergeViewModel';
export { default as ArtistMerge } from './Artist/Merge';
// ~/bundles/Artist/ViewVersion
export { default as ArchivedArtistViewModel } from '@ViewModels/Artist/ArchivedArtistViewModel';
export { default as ArtistViewVersion } from './Artist/ViewVersion';
// ~/bundles/Comment/Index
export { default as CommentListViewModel } from '@ViewModels/Comment/CommentListViewModel';
// ~/bundles/Comment/CommentsByUser
export { default as CommentCommentsByUser } from './Comment/CommentsByUser';
// ~/bundles/Discussion/Index
import '@KnockoutExtensions/FormatDateFilter';
import '@KnockoutExtensions/MomentJsTimeAgo';
export { default as DiscussionIndexViewModel } from '@ViewModels/Discussion/DiscussionIndexViewModel';
export { default as DiscussionIndex } from './Discussion/Index';
// ~/bundles/EventSeries/Details
export { default as EventSeriesDetailsViewModel } from '@ViewModels/ReleaseEvent/EventSeriesDetailsViewModel';
export { default as EventSeriesDetails } from './Event/SeriesDetails';
// ~/bundles/EventSeries/Edit
export { default as ReleaseEventRepository } from '@Repositories/ReleaseEventRepository';
export { default as ReleaseEventSeriesEditViewModel } from '@ViewModels/ReleaseEvent/ReleaseEventSeriesEditViewModel';
export { default as EventEditSeries } from './Event/EditSeries';
// ~/bundles/EventSeries/ViewVersion
//export { default as ReleaseEventRepository } from '@Repositories/ReleaseEventRepository';
export { default as ArchivedEntryViewModel } from '@ViewModels/ArchivedEntryViewModel';
export { default as EventViewSeriesVersion } from './Event/ViewSeriesVersion';
// ~/bundles/MikuDbAlbum/Index
export { default as MikuDbAlbumIndex } from './MikuDbAlbum/Index';
// ~/bundles/MikuDbAlbum/PrepareForImport
export { default as MikuDbAlbumPrepareForImport } from './MikuDbAlbum/PrepareForImport';
// ~/bundles/ReleaseEvent/Details
//export { default as ReleaseEventRepository } from '@Repositories/ReleaseEventRepository';
export { default as ReleaseEventDetailsViewModel } from '@ViewModels/ReleaseEvent/ReleaseEventDetailsViewModel';
export { default as EventDetails } from './Event/Details';
// ~/bundles/ReleaseEvent/Edit
import '@KnockoutExtensions/BindingHandlers/DatePicker';
import '@KnockoutExtensions/ReleaseEventSeriesAutoComplete';
import '@KnockoutExtensions/BindingHandlers/SongListAutoComplete';
import '@KnockoutExtensions/BindingHandlers/VenueAutoComplete';
import '@KnockoutExtensions/FormatDateFilter';
import '@KnockoutExtensions/FormatLengthSecondsFilter';
export { default as ReleaseEventEditViewModel } from '@ViewModels/ReleaseEvent/ReleaseEventEditViewModel';
export { default as EventEdit } from './Event/Edit';
// ~/bundles/ReleaseEvent/EventsBySeries
export { default as EventEventsBySeries } from './Event/EventsBySeries';
// ~/bundles/ReleaseEvent/EventsByVenue
export { default as EventEventsByVenue } from './Event/EventsByVenue';
// ~/bundles/ReleaseEvent/Index
export { default as EventIndex } from './Event/Index';
// ~/bundles/ReleaseEvent/ViewVersion
//export { default as ReleaseEventRepository } from '@Repositories/ReleaseEventRepository';
//export { default as ReleaseEventDetailsViewModel } from '@ViewModels/ReleaseEvent/ReleaseEventDetailsViewModel'
export { default as EventViewVersion } from './Event/ViewVersion';
// ~/bundles/Search/Index
import '@KnockoutExtensions/Artist/ArtistTypeLabel';
import '@KnockoutExtensions/Tag/TagCategoryAutoComplete';
import '@KnockoutExtensions/ArtistAutoComplete';
import '@KnockoutExtensions/SlideVisible';
import '@KnockoutExtensions/ScrollEnd';
import '@KnockoutExtensions/BindingHandlers/ReleaseEventAutoComplete';
import '@KnockoutExtensions/BindingHandlers/DatePicker';
import '@KnockoutExtensions/SongAutoComplete';
//export { default as PVPlayersFactory } from '@ViewModels/PVs/PVPlayersFactory';
export { default as SearchViewModel } from '@ViewModels/Search/SearchViewModel';
export { default as SearchIndex } from './Search/Index';
// ~/bundles/Song/Create
import '@KnockoutExtensions/Artist/ArtistTypeLabel';
export { default as SongCreateViewModel } from '@ViewModels/SongCreateViewModel';
export { default as SongCreate } from './Song/Create';
// ~/bundles/Song/Details
import '@KnockoutExtensions/MomentJsTimeAgo';
export { default as SongDetailsViewModel } from '@ViewModels/Song/SongDetailsViewModel';
export { default as SongDetails } from './Song/Details';
// ~/bundles/Song/Edit
import '@KnockoutExtensions/FormatDateFilter';
import '@KnockoutExtensions/FormatLengthSecondsFilter';
import '@KnockoutExtensions/BindingHandlers/DatePicker';
import '@KnockoutExtensions/BindingHandlers/ReleaseEventAutoComplete';
export { default as SongEditViewModel } from '@ViewModels/Song/SongEditViewModel';
export { default as SongEdit } from './Song/Edit';
// ~/bundles/Song/Merge
export { default as SongMergeViewModel } from '@ViewModels/Song/SongMergeViewModel';
export { default as SongMerge } from './Song/Merge';
// ~/bundles/Song/TopRated
import '@KnockoutExtensions/SlideVisible';
import '@KnockoutExtensions/FormatDateFilter';
export { default as RankingsViewModel } from '@ViewModels/Song/RankingsViewModel';
export { default as SongRankings } from './Song/Rankings';
// ~/bundles/Song/ViewVersion
export { default as ArchivedSongViewModel } from '@ViewModels/Song/ArchivedSongViewModel';
export { default as SongViewVersion } from './Song/ViewVersion';
// ~/bundles/SongList/Details
import '@KnockoutExtensions/SlideVisible';
import '@KnockoutExtensions/ScrollEnd';
import '@KnockoutExtensions/ArtistAutoComplete';
//export { default as PVPlayersFactory } from '@ViewModels/PVs/PVPlayersFactory';
export { default as SongListViewModel } from '@ViewModels/SongList/SongListViewModel';
export { default as SongListDetails } from './SongList/Details';
// ~/bundles/SongList/Edit
import '@KnockoutExtensions/BindingHandlers/DatePicker';
export { default as SongListEditViewModel } from '@ViewModels/SongList/SongListEditViewModel';
export { default as SongListEdit } from './SongList/Edit';
// ~/bundles/SongList/Featured
import '@KnockoutExtensions/FormatDateFilter';
export { default as FeaturedSongListsViewModel } from '@ViewModels/SongList/FeaturedSongListsViewModel';
export { default as SongListFeatured } from './SongList/Featured';
// ~/bundles/SongList/Import
export { default as ImportSongListViewModel } from '@ViewModels/SongList/ImportSongListViewModel';
export { default as SongListImport } from './SongList/Import';
// ~/bundles/Stats/Index
import '@KnockoutExtensions/Highcharts';
export { default as StatsViewModel } from '@ViewModels/StatsViewModel';
export { default as StatsIndex } from './Stats/Index';
// ~/bundles/Tag/Details
import '@KnockoutExtensions/MomentJsTimeAgo';
//export { default as TagRepository } from '@Repositories/TagRepository';
export { default as TagDetailsViewModel } from '@ViewModels/Tag/TagDetailsViewModel';
export { default as TagDetails } from './Tag/Details';
// ~/bundles/Tag/Edit
import '@KnockoutExtensions/Tag/TagCategoryAutoComplete';
//export { default as TagRepository } from '@Repositories/TagRepository';
export { default as TagEditViewModel } from '@ViewModels/TagEditViewModel';
export { default as TagEdit } from './Tag/Edit';
// ~/bundles/Tag/Index
//export { default as TagRepository } from '@Repositories/TagRepository';
export { default as TagCreateViewModel } from '@ViewModels/Tag/TagCreateViewModel';
export { default as TagIndex } from './Tag/Index';
// ~/bundles/Tag/Merge
//export { default as TagRepository } from '@Repositories/TagRepository';
export { default as TagMergeViewModel } from '@ViewModels/Tag/TagMergeViewModel';
export { default as TagMerge } from './Tag/Merge';
// ~/bundles/Tag/ViewVersion
//export { default as TagRepository } from '@Repositories/TagRepository';
//export { default as ArchivedEntryViewModel } from '@ViewModels/ArchivedEntryViewModel';
export { default as TagViewVersion } from './Tag/ViewVersion';
// ~/bundles/User/AlbumCollection
import '@KnockoutExtensions/ArtistAutoComplete';
import '@KnockoutExtensions/BindingHandlers/ReleaseEventAutoComplete';
export { default as AlbumCollectionViewModel } from '@ViewModels/User/AlbumCollectionViewModel';
export { default as UserAlbumCollection } from './User/AlbumCollection';
// ~/bundles/User/Details
import '@KnockoutExtensions/SlideVisible';
import '@KnockoutExtensions/ArtistAutoComplete';
import '@KnockoutExtensions/MomentJsTimeAgo';
import '@KnockoutExtensions/BindingHandlers/ReleaseEventAutoComplete';
import '@KnockoutExtensions/Highcharts';
import '@KnockoutExtensions/ScrollEnd';
import '@KnockoutExtensions/FormatDateFilter';
//export { default as PVPlayersFactory } from '@ViewModels/PVs/PVPlayersFactory';
export { default as FollowedArtistsViewModel } from '@ViewModels/User/FollowedArtistsViewModel';
export { default as RatedSongsSearchViewModel } from '@ViewModels/User/RatedSongsSearchViewModel';
//export { default as AlbumCollectionViewModel } from '@ViewModels/User/AlbumCollectionViewModel';
export { default as UserDetailsViewModel } from '@ViewModels/User/UserDetailsViewModel';
export { default as UserDetails } from './User/Details';
// ~/bundles/User/Edit
export { default as UserEdit } from './User/Edit';
// ~/bundles/User/EntryEdits
export { default as UserEntryEdits } from './User/EntryEdits';
// ~/bundles/User/FavoriteSongs
export { default as UserFavoriteSongs } from './User/FavoriteSongs';
// ~/bundles/User/Index
export { default as ListUsersViewModel } from '@ViewModels/User/ListUsersViewModel';
export { default as UserIndex } from './User/Index';
// ~/bundles/User/Messages
import '@KnockoutExtensions/BindingHandlers/UserAutoComplete';
export { default as UserMessagesViewModel } from '@ViewModels/User/UserMessagesViewModel';
export { default as UserMessages } from './User/Messages';
// ~/bundles/User/MySettings
export { default as MySettingsViewModel } from '@ViewModels/User/MySettingsViewModel';
export { default as UserMySettings } from './User/MySettings';
// ~/bundles/User/RatedSongs
import '@KnockoutExtensions/SlideVisible';
import '@KnockoutExtensions/ArtistAutoComplete';
import '@KnockoutExtensions/ScrollEnd';
//export { default as PVPlayersFactory } from '@ViewModels/PVs/PVPlayersFactory';
//export { default as RatedSongsSearchViewModel } from '@ViewModels/User/RatedSongsSearchViewModel';
// ~/bundles/User/RequestVerification
export { default as RequestVerificationViewModel } from '@ViewModels/User/RequestVerificationViewModel';
export { default as UserRequestVerification } from './User/RequestVerification';
// ~/bundles/User/Stats
export { default as UserStats } from './User/Stats';
// ~/bundles/Venue/Details
export { default as VenueDetailsViewModel } from '@ViewModels/Venue/VenueDetailsViewModel';
export { default as VenueDetails } from './Venue/Details';
// ~/bundles/Venue/Edit
export { default as VenueEditViewModel } from '@ViewModels/Venue/VenueEditViewModel';
export { default as VenueEdit } from './Venue/Edit';
// ~/bundles/Venue/ViewVersion
export { default as VenueRepository } from '@Repositories/VenueRepository';
export { default as VenueViewVersion } from './Venue/ViewVersion'; | the_stack |
import { vtkObject } from "../../../interfaces";
export enum InterpolationType {
NEAREST,
LINEAR,
FAST_LINEAR,
}
export enum OpacityMode {
FRACTIONAL,
PROPORTIONAL,
}
interface IVolumePropertyInitialValues {
independentComponents?: boolean;
shade?: number;
ambient?: number;
diffuse?: number;
specular?: number;
specularPower?: number;
useLabelOutline?: boolean;
labelOutlineThickness?: number;
}
export interface vtkVolumeProperty extends vtkObject {
/**
* Get the ambient lighting coefficient.
*/
getAmbient(): number;
/**
* Return the `Modified Time` which is a monotonic increasing integer
* global for all vtkObjects.
*
* This allow to solve a question such as:
* - Is that object created/modified after another one?
* - Do I need to re-execute this filter, or not? ...
*
* @return {Number} the global modified time.
*/
getMTime(): number;
/**
*
* @param {Number} index
*/
getColorChannels(index: number): number;
/**
* Get the diffuse lighting coefficient.
*/
getDiffuse(): number;
/**
*
* @param {Number} index
*/
getGradientOpacityMaximumOpacity(index: number): number;
/**
*
* @param {Number} index
*/
getGradientOpacityMaximumValue(index: number): number;
/**
*
* @param {Number} index
*/
getGradientOpacityMinimumOpacity(index: number): number;
/**
*
* @param {Number} index
*/
getGradientOpacityMinimumValue(index: number): number;
/**
*
*/
getIndependentComponents(): boolean;
/**
* Get the unit distance on which the scalar opacity transfer function is defined.
* @param {Number} index
*/
getScalarOpacityUnitDistance(index: number): number;
/**
* Get the currently set gray transfer function. Create one if none set.
* @param {Number} index
*/
getGrayTransferFunction(index: number): any;
/**
*
* @default FRACTIONAL
*/
getOpacityMode(index: number): OpacityMode;
/**
*
*/
getLabelOutlineThickness(): number;
/**
* Get the currently set RGB transfer function. Create one if none set.
* @param {Number} index
*/
getRGBTransferFunction(index: number): any;
/**
* Get the scalar opacity transfer function. Create one if none set.
* @param {Number} index
*/
getScalarOpacity(index: number): any;
/**
* Get the shading of a volume.
*/
getShade(): number;
/**
*
*/
getSpecular(): number;
/**
* Get the specular power.
*/
getSpecularPower(): number;
/**
*
* @param {Number} index
*/
getUseGradientOpacity(index: number): boolean;
/**
*
*/
getUseLabelOutline(): boolean;
/**
* Set the ambient lighting coefficient.
* @param {Number} ambient The ambient lighting coefficient.
*/
setAmbient(ambient: number): boolean;
/**
* Set the diffuse lighting coefficient.
* @param {Number} diffuse The diffuse lighting coefficient.
*/
setDiffuse(diffuse: number): boolean;
/**
*
* @param {Number} index
* @param {Number} value
*/
setGradientOpacityMaximumOpacity(index: number, value: number): boolean;
/**
*
* @param {Number} index
* @param {Number} value
*/
setGradientOpacityMaximumValue(index: number, value: number): boolean;
/**
*
* @param {Number} index
* @param {Number} value
*/
setGradientOpacityMinimumOpacity(index: number, value: number): boolean;
/**
*
* @param {Number} index
* @param {Number} value
*/
setGradientOpacityMinimumValue(index: number, value: number): boolean;
/**
* Set the color of a volume to a gray transfer function
* @param {Number} index
* @param func
*/
setGrayTransferFunction(index: number, func: any): boolean;
/**
* Does the data have independent components, or do some define color only?
* If IndependentComponents is On (the default) then each component will be
* independently passed through a lookup table to determine RGBA, shaded.
*
* Some volume Mappers can handle 1 to 4 component unsigned char or unsigned
* short data (see each mapper header file to determine functionality). If
* IndependentComponents is Off, then you must have either 2 or 4 component
* data. For 2 component data, the first is passed through the first color
* transfer function and the second component is passed through the first
* scalar opacity (and gradient opacity) transfer function. Normals will be
* generated off of the second component. When using gradient based opacity
* modulation, the gradients are computed off of the second component. For 4
* component data, the first three will directly represent RGB (no lookup
* table). The fourth component will be passed through the first scalar
* opacity transfer function for opacity and first gradient opacity transfer
* function for gradient based opacity modulation. Normals will be generated
* from the fourth component. When using gradient based opacity modulation,
* the gradients are computed off of the fourth component.
* @param {Boolean} independentComponents
*/
setIndependentComponents(independentComponents: boolean): boolean;
/**
*
* @param {Number} labelOutlineThickness
*/
setLabelOutlineThickness(labelOutlineThickness: number): boolean;
/**
*
* @param {Number} index
* @param {Number} value
*/
setOpacityMode(index: number, value: number): boolean;
/**
* Set the unit distance on which the scalar opacity transfer function is
* defined.
* @param {Number} index
* @param {Number} value
*/
setScalarOpacityUnitDistance(index: number, value: number): boolean;
/**
* Set the shading of a volume.
*
* If shading is turned off, then the mapper for the volume will not perform
* shading calculations. If shading is turned on, the mapper may perform
* shading calculations - in some cases shading does not apply (for example,
* in a maximum intensity projection) and therefore shading will not be
* performed even if this flag is on. For a compositing type of mapper,
* turning shading off is generally the same as setting ambient=1,
* diffuse=0, specular=0. Shading can be independently turned on/off per
* component.
* @param {Number} shade
*/
setShade(shade: number): boolean;
/**
*
* @param {Number} specular
*/
setSpecular(specular: number): boolean;
/**
* Set the specular power.
* @param {Number} specularPower
*/
setSpecularPower(specularPower: number): boolean;
/**
*
* @param {Number} index
* @param {Number} value
*/
setUseGradientOpacity(index: number, value: number): boolean;
/**
*
* @param {Boolean} useLabelOutline
*/
setUseLabelOutline(useLabelOutline: boolean): boolean;
/**
* Set the color of a volume to an RGB transfer function
* @param {Number} index
* @param func
*/
setRGBTransferFunction(index: number, func: any): boolean;
/**
* Set the scalar opacity of a volume to a transfer function
* @param {Number} index
* @param func
*/
setScalarOpacity(index: number, func: any): boolean;
/**
* Set the scalar component weights.
* @param {Number} index
* @param {Number} value
*/
setComponentWeight(index: number, value: number): boolean;
/**
* Get the scalar component weights.
* @param {Number} index
*/
getComponentWeight(index: number): number;
/**
* Set the interpolation type for sampling a volume.
* @param {InterpolationType} interpolationType
*/
setInterpolationType(interpolationType: InterpolationType): boolean;
/**
* Set interpolation type to NEAREST
*/
setInterpolationTypeToNearest(): boolean;
/**
* Set interpolation type to LINEAR
*/
setInterpolationTypeToLinear(): boolean;
/**
* Set interpolation type to FAST_LINEAR
*/
setInterpolationTypeToFastLinear(): boolean;
/**
* Get the interpolation type for sampling a volume.
*/
getInterpolationType(): InterpolationType;
/**
* Get the interpolation type for sampling a volume as a string.
*/
getInterpolationTypeAsString(): string;
}
/**
* Method use to decorate a given object (publicAPI+model) with vtkVolumeProperty characteristics.
*
* @param publicAPI object on which methods will be bounds (public)
* @param model object on which data structure will be bounds (protected)
* @param {IVolumePropertyInitialValues} [initialValues] (default: {})
*/
export function extend(publicAPI: object, model: object, initialValues?: IVolumePropertyInitialValues): void;
/**
* Method use to create a new instance of vtkVolumeProperty
*/
export function newInstance(initialValues?: IVolumePropertyInitialValues): vtkVolumeProperty;
/**
* vtkVolumeProperty is used to represent common properties associated
* with volume rendering. This includes properties for determining the type
* of interpolation to use when sampling a volume, the color of a volume,
* the scalar opacity of a volume, the gradient opacity of a volume, and the
* shading parameters of a volume.
* When the scalar opacity or the gradient opacity of a volume is not set,
* then the function is defined to be a constant value of 1.0. When a
* scalar and gradient opacity are both set simultaneously, then the opacity
* is defined to be the product of the scalar opacity and gradient opacity
* transfer functions.
*
* Most properties can be set per "component" for volume mappers that
* support multiple independent components. If you are using 2 component
* data as LV or 4 component data as RGBV (as specified in the mapper)
* only the first scalar opacity and gradient opacity transfer functions
* will be used (and all color functions will be ignored). Omitting the
* index parameter on the Set/Get methods will access index = 0.
*
* When independent components is turned on, a separate feature (useful
* for volume rendering labelmaps) is available. By default all components
* have an "opacityMode" of `FRACTIONAL`, which results in the usual
* addition of that components scalar opacity function value to the final
* opacity of the fragment. By setting one or more components to have a
* `PROPORTIONAL` "opacityMode" instead, the scalar opacity lookup value
* for those components will not be used to adjust the fragment opacity,
* but rather used to multiply the color of that fragment. This kind of
* rendering makes sense for labelmap components because the gradient of
* those fields is meaningless and should not be used in opacity
* computation. At the same time, multiplying the color value by the
* piecewise scalar opacity function value provides an opportunity to
* design piecewise constant opacity functions (step functions) that can
* highlight any subset of label values.
*
* vtkColorTransferFunction is a color mapping in RGB or HSV space that
* uses piecewise hermite functions to allow interpolation that can be
* piecewise constant, piecewise linear, or somewhere in-between
* (a modified piecewise hermite function that squishes the function
* according to a sharpness parameter). The function also allows for
* the specification of the midpoint (the place where the function
* reaches the average of the two bounding nodes) as a normalize distance
* between nodes.
*
* See the description of class vtkPiecewiseFunction for an explanation of
* midpoint and sharpness.
*
* @example
* ```js
* // create color and opacity transfer functions
* const ctfun = vtkColorTransferFunction.newInstance();
* ctfun.addRGBPoint(200.0, 1.0, 1.0, 1.0);
* ctfun.addRGBPoint(2000.0, 0.0, 0.0, 0.0);
* const ofun = vtkPiecewiseFunction.newInstance();
* ofun.addPoint(200.0, 0.0);
* ofun.addPoint(1200.0, 0.2);
* ofun.addPoint(4000.0, 0.4);
*
* // set them on the property
* volume.getProperty().setRGBTransferFunction(0, ctfun);
* volume.getProperty().setScalarOpacity(0, ofun);
* volume.getProperty().setScalarOpacityUnitDistance(0, 4.5);
* volume.getProperty().setInterpolationTypeToLinear();
* ```
*/
export declare const vtkVolumeProperty: {
newInstance: typeof newInstance,
extend: typeof extend,
};
export default vtkVolumeProperty; | the_stack |
import 'jest-extended';
import http from 'http';
import { Message } from '../src/messenger';
import { Messenger, formatURL, newMsgId } from '../src';
import { findPort, pDelay } from './helpers';
jest.setTimeout(10000);
describe('Messenger', () => {
describe('->Core', () => {
describe('when constructed without a valid actionTimeout', () => {
it('should throw an error', () => {
expect(() => {
new Messenger.Core({} as any);
}).toThrowError('Messenger requires a valid actionTimeout');
});
});
describe('when constructed without a valid networkLatencyBuffer', () => {
it('should throw an error', () => {
expect(() => {
new Messenger.Core({
actionTimeout: 10,
// @ts-expect-error
networkLatencyBuffer: 'abc'
});
}).toThrowError('Messenger requires a valid networkLatencyBuffer');
});
});
it('should throw an error when calling isClientReady', () => {
const errorMsg = 'isClientReady should be implemented on the server and client class';
const core = new Messenger.Core({
actionTimeout: 10,
networkLatencyBuffer: 0,
});
expect(() => {
core.isClientReady();
}).toThrowError(errorMsg);
});
});
describe('->Client', () => {
describe('when constructed without a valid hostUrl', () => {
it('should throw an error', () => {
expect(() => {
// @ts-expect-error
new Messenger.Client({
actionTimeout: 1,
networkLatencyBuffer: 0
});
}).toThrowError('Messenger.Client requires a valid hostUrl');
});
});
describe('when constructed without a valid clientId', () => {
it('should throw an error', () => {
expect(() => {
// @ts-expect-error
new Messenger.Client({
actionTimeout: 1,
networkLatencyBuffer: 0,
hostUrl: 'some-host',
});
}).toThrowError('Messenger.Client requires a valid clientId');
});
});
describe('when constructed without a valid clientType', () => {
it('should throw an error', async () => {
const clientId = await newMsgId();
expect(() => {
// @ts-expect-error
new Messenger.Client({
actionTimeout: 1,
networkLatencyBuffer: 0,
hostUrl: 'some-host',
clientId,
});
}).toThrowError('Messenger.Client requires a valid clientType');
});
});
describe('when constructed without a valid serverName', () => {
it('should throw an error', () => {
expect(() => {
// @ts-expect-error
new Messenger.Client({
actionTimeout: 1,
networkLatencyBuffer: 0,
hostUrl: 'some-host',
clientId: 'hello',
clientType: 'some-client'
});
}).toThrowError('Messenger.Client requires a valid serverName');
});
});
describe('when constructed without a valid connectTimeout', () => {
it('should throw an error', () => {
expect(() => {
// @ts-expect-error
new Messenger.Client({
actionTimeout: 1,
networkLatencyBuffer: 0,
hostUrl: 'some-host',
clientId: 'hello',
clientType: 'some-client',
serverName: 'some-server-name'
});
}).toThrowError('Messenger.Client requires a valid connectTimeout');
});
});
});
describe('->Server', () => {
describe('when constructed without a valid port', () => {
it('should throw an error', () => {
expect(() => {
// @ts-expect-error
new Messenger.Server({
actionTimeout: 1,
networkLatencyBuffer: 0
});
}).toThrowError('Messenger.Server requires a valid port');
});
});
describe('when constructed without a valid clientDisconnectTimeout', () => {
it('should throw an error', () => {
expect(() => {
// @ts-expect-error
new Messenger.Server({
actionTimeout: 1,
networkLatencyBuffer: 0,
port: 80,
serverName: 'hello'
});
}).toThrowError('Messenger.Server requires a valid clientDisconnectTimeout');
});
});
describe('when constructed without a valid serverName', () => {
it('should throw an error', () => {
expect(() => {
// @ts-expect-error
new Messenger.Server({
actionTimeout: 1,
networkLatencyBuffer: 0,
port: 80,
clientDisconnectTimeout: 1,
});
}).toThrowError('Messenger.Server requires a valid serverName');
});
});
describe('when the port is already in-use', () => {
let port: number;
beforeAll((done) => {
findPort().then((_port) => {
port = _port;
http.createServer((req, res) => {
res.end(req.url);
}).listen(port, done);
});
});
it('should throw error', () => {
const server = new Messenger.Server({
actionTimeout: 1,
networkLatencyBuffer: 0,
port,
clientDisconnectTimeout: 1,
serverName: 'hello'
});
const error = `Port ${port} is already in-use`;
return expect(server.listen()).rejects.toThrowError(error);
});
});
});
describe('Client & Server', () => {
let clientId: string;
let client: Messenger.Client;
let server: Messenger.Server;
type ClientFn = (id: string) => void;
let clientAvailableFn: ClientFn;
const clientUnavailableFn: ClientFn = jest.fn();
const clientOnlineFn: ClientFn = jest.fn();
const clientDisconnectFn: ClientFn = jest.fn();
const clientReconnectFn: ClientFn = jest.fn();
const clientShutdownFn: ClientFn = jest.fn();
const clientErrorFn: ClientFn = jest.fn();
beforeAll((done) => {
clientAvailableFn = jest.fn(() => { done(); });
async function setup() {
clientId = await newMsgId();
const port = await findPort();
const hostUrl = formatURL('localhost', port);
server = new Messenger.Server({
port,
networkLatencyBuffer: 0,
actionTimeout: 1000,
serverTimeout: 2000,
clientDisconnectTimeout: 3000,
serverName: 'example'
});
server.onClientOnline(clientOnlineFn);
server.onClientAvailable(clientAvailableFn);
server.onClientUnavailable(clientUnavailableFn);
server.onClientDisconnect(clientDisconnectFn);
server.onClientReconnect(clientReconnectFn);
server.onClientShutdown(clientShutdownFn);
server.onClientError(clientErrorFn);
client = new Messenger.Client({
serverName: 'example',
clientId,
clientType: 'example',
hostUrl,
clientDisconnectTimeout: 1000,
networkLatencyBuffer: 0,
actionTimeout: 1000,
connectTimeout: 5000,
// this last arg is for overriding the
// connect timeout for the socket.io client
}, 500);
// let the client connect first so
// we can test that client can come up
// before the server
await Promise.all([
client.connect(),
pDelay(1000).then(() => server.listen())
]);
await client.sendAvailable();
}
setup();
});
afterAll(async () => {
await Promise.all([
client.shutdown(),
server.shutdown(),
]);
});
it('should have the correct client properties', () => {
expect(server.onlineClientCount).toEqual(1);
expect(server.onlineClients).toBeArrayOfSize(1);
expect(server.availableClientCount).toEqual(1);
expect(server.availableClients).toBeArrayOfSize(1);
expect(server.disconnectedClientCount).toEqual(0);
expect(server.disconnectedClients).toBeArrayOfSize(0);
expect(server.unavailableClientCount).toEqual(0);
expect(server.unavailableClients).toBeArrayOfSize(0);
});
it('should call server.onClientOnline', () => {
expect(clientOnlineFn).toHaveBeenCalledWith(clientId);
});
it('should call server.onClientAvailable', () => {
expect(clientAvailableFn).toHaveBeenCalledWith(clientId);
});
it('should not call server.onClientUnavailable', () => {
expect(clientUnavailableFn).not.toHaveBeenCalled();
});
it('should not call server.onClientDisconnect', () => {
expect(clientDisconnectFn).not.toHaveBeenCalled();
});
it('should not call server.onClientShutdown', () => {
expect(clientShutdownFn).not.toHaveBeenCalled();
});
it('should not call server.onClientReconnect', () => {
expect(clientReconnectFn).not.toHaveBeenCalled();
});
it('should not call server.onClientError', () => {
expect(clientErrorFn).not.toHaveBeenCalled();
});
it('should be able to handle getTimeoutWithMax', () => {
expect(server.getTimeoutWithMax(100)).toBe(100);
expect(server.getTimeoutWithMax(20000)).toBe(1000);
});
it('should be able to handle waitForClientReady', async () => {
try {
await server.waitForClientReady('hello', 100);
} catch (err) {
expect(err.message).toEqual('Client hello is not ready');
}
const clientReady = await server.waitForClientReady(client.clientId, 100);
expect(clientReady).toBeTrue();
const serverReady = await client.waitForClientReady(client.serverName, 100);
expect(serverReady).toBeTrue();
});
describe('when testing onceWithTimeout', () => {
it('should be able to handle timeouts', async () => {
expect(server.listenerCount('timeout:event')).toBe(0);
const once = server.onceWithTimeout('timeout:event', 500);
expect(server.listenerCount('timeout:event')).toBe(1);
const msg = await once;
expect(msg).toBeUndefined();
expect(server.listenerCount('timeout:event')).toBe(0);
});
it('should be able to handle timeouts when given a specific scope', () => {
const once = server.onceWithTimeout(`timeout:event:${clientId}`, 500);
return expect(once).resolves.toBeUndefined();
});
it('should be able to resolve the message', async () => {
expect(server.listenerCount('success:event')).toBe(0);
const once = server.onceWithTimeout('success:event', 500);
expect(server.listenerCount('success:event')).toBe(1);
await server.emit('success:event', {
scope: clientId,
payload: {
hello: true
}
});
const msg = await once;
expect(server.listenerCount('success:event')).toBe(0);
expect(msg).toEqual({
hello: true
});
});
it('should be able to resolve the message when given a specific scope', () => {
const once = server.onceWithTimeout(`success:event:${clientId}`, 500);
server.emit('success:event', {
scope: clientId,
payload: {
hello: true
}
});
return expect(once).resolves.toEqual({
hello: true
});
});
});
describe('when waiting for message that will never come', () => {
it('should throw a timeout error', async () => {
expect.hasAssertions();
// @ts-expect-error
server.handleResponse(server.server.to(clientId), 'hello', async () => {
await pDelay(1000);
});
try {
// @ts-expect-error
await client.send('hello', {}, {
response: true,
volatile: false,
timeout: 500
});
} catch (err) {
expect(err).not.toBeNil();
expect(err.message).toStartWith('Timed out after');
expect(err.message).toEndWith('waiting for message "hello"');
}
});
});
describe('when sending a message to client that does not exist', () => {
it('should throw a timeout error', async () => {
expect.hasAssertions();
try {
// @ts-expect-error
await server.send('mystery-client', 'hello');
} catch (err) {
expect(err).not.toBeNil();
expect(err.message).toEqual('No client found by that id "mystery-client"');
}
});
});
// eslint-disable-next-line jest/no-disabled-tests
xdescribe('when the client responds with an error', () => {
let responseMsg: Message | Record<string, any> | undefined;
let responseErr: Error | undefined;
beforeAll(async () => {
client.socket.once('failure:message', (msg: Message) => {
msg.error = 'this should fail';
client.socket.emit('message:response', msg);
});
try {
// @ts-expect-error
responseMsg = await server.send(clientId, 'failure:message', { hi: true });
} catch (err) {
responseErr = err;
}
});
it('server should get an error back', () => {
expect(responseMsg).toBeNil();
expect(responseErr && responseErr.toString()).toEqual('Error: Message Response Failure: this should fail');
});
});
describe('when testing reconnect', () => {
it('should call server.onClientReconnect', (done) => {
server.onClientReconnect(() => {
done();
});
client.forceReconnect();
});
});
});
}); | the_stack |
import { TilesNextExtension } from './tilesNextExtension';
const Cesium = require('cesium');
const clone = Cesium.clone;
const Cartesian3 = Cesium.Cartesian3;
const CesiumMath = Cesium.Math;
const Matrix4 = Cesium.Matrix4;
const Quaternion = Cesium.Quaternion;
const gltfPipeline = require('gltf-pipeline');
import { GeneratorArgs } from './arguments';
import {
largeGeometricError,
parentRegion,
smallGeometricError,
parentContentRegion,
llRegion,
lrRegion,
urRegion,
ulRegion,
parentTileOptions,
llTileOptions,
lrTileOptions,
urTileOptions,
ulTileOptions,
childrenRegion,
latitude,
wgs84Transform,
longitude,
instancesModelSize,
instancesTileWidth,
instancesLength,
instancesUri,
buildingTemplate,
smallBoxLocal,
instancesGeometricError,
instancesBoxLocal,
buildingsTransform,
longitudeExtent,
latitudeExtent,
TileOptions, tilesNextTilesetJsonVersion, gltfConversionOptions
} from './constants';
import { Gltf } from './gltfType';
import path = require('path');
import { writeTileset, writeTile, writeTilesetAndTile } from './ioUtil';
import saveJson = require('./saveJson');
import { getGltfFromGlbUri } from './gltfFromUri';
import { TilesetUtilsNext } from './tilesetUtilsNext';
import { InstanceTileUtils } from './instanceUtilsNext';
import { addBinaryBuffers } from './gltfUtil';
import { createEXTMeshInstancingExtension } from './createEXTMeshInstancing';
import { FeatureMetadata } from './featureMetadata';
import { FeatureTableUtils } from './featureMetatableUtilsNext';
import { createBuildings } from './createBuilding';
import { Mesh } from './Mesh';
import { generateBuildingBatchTable } from './createBuildingsTile';
import { TilesetJson } from './tilesetJson';
import createGltf = require('./createGltf');
import { createPointCloudTile } from './createPointCloudTile';
const getProperties = require('./getProperties');
export namespace TilesetSamplesNext {
const rootDir = path.join('output', 'Tilesets');
export async function createTileset(args: GeneratorArgs) {
const tilesetDirectory = path.join(rootDir, 'Tileset');
const tileOptions = [
parentTileOptions,
llTileOptions,
lrTileOptions,
urTileOptions,
ulTileOptions
];
const tileNames = ['parent', 'll', 'lr', 'ur', 'ul'];
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const batchTables = result.batchTables;
const gltfs = result.gltfs;
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetJson: TilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion,
tilesetVersion: '1.2.3'
},
extras: {
name: 'Sample Tileset'
},
properties: undefined,
geometricError: largeGeometricError,
root: {
boundingVolume: {
region: parentRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
content: {
uri: 'parent' + ext,
boundingVolume: {
region: parentContentRegion
}
},
children: [
{
boundingVolume: {
region: llRegion
},
geometricError: 0.0,
content: {
uri: 'll' + ext
}
},
{
boundingVolume: {
region: lrRegion
},
geometricError: 0.0,
content: {
uri: 'lr' + ext
},
extras: {
id: 'Special Tile'
}
},
{
boundingVolume: {
region: urRegion
},
geometricError: 0.0,
content: {
uri: 'ur' + ext
}
},
{
boundingVolume: {
region: ulRegion
},
geometricError: 0.0,
content: {
uri: 'ul' + ext
}
}
]
}
};
tilesetJson.properties = getProperties(batchTables);
await writeTileset(tilesetDirectory, tilesetJson, args);
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tileFilename = tileNames[i] + ext;
await writeTile(tilesetDirectory, tileFilename, gltf, args);
}
}
export async function createTilesetEmptyRoot(args: GeneratorArgs) {
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tileOptions = [
llTileOptions,
lrTileOptions,
urTileOptions,
ulTileOptions
];
const tileNames = ['ll', 'lr', 'ur', 'ul'];
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const gltfs = result.gltfs;
const batchTables = result.batchTables;
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
properties: undefined,
geometricError: smallGeometricError,
root: {
boundingVolume: {
region: childrenRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
children: [
{
boundingVolume: {
region: llRegion
},
geometricError: 0.0,
content: {
uri: 'll' + ext
}
},
{
boundingVolume: {
region: lrRegion
},
geometricError: 0.0,
content: {
uri: 'lr' + ext
}
},
{
boundingVolume: {
region: urRegion
},
geometricError: 0.0,
content: {
uri: 'ur' + ext
}
},
{
boundingVolume: {
region: ulRegion
},
geometricError: 0.0,
content: {
uri: 'ul' + ext
}
}
]
}
};
const fullPath = path.join(rootDir, 'TilesetEmptyRoot');
tilesetJson.properties = getProperties(batchTables);
await writeTileset(fullPath, tilesetJson as any, args);
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tileFilename = tileNames[i] + ext;
await writeTile(fullPath, tileFilename, gltf, args);
}
}
export async function createTilesetOfTilesets(args: GeneratorArgs) {
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetOfTilesets';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const tileset2Path = path.join(tilesetDirectory, 'tileset2.json');
const tileset3Path = path.join(
tilesetDirectory,
'tileset3',
'tileset3.json'
);
const llPath = path.join('tileset3', 'll');
const tileNames = ['parent', llPath, 'lr', 'ur', 'ul'];
const tileOptions = [
parentTileOptions,
llTileOptions,
lrTileOptions,
urTileOptions,
ulTileOptions
];
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion,
tilesetVersion: '1.2.3'
},
properties: undefined,
geometricError: largeGeometricError,
root: {
boundingVolume: {
region: parentRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
content: {
uri: 'tileset2.json'
}
}
};
const tileset2Json = {
asset: {
version: tilesNextTilesetJsonVersion
},
geometricError: largeGeometricError,
root: {
boundingVolume: {
region: parentRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
content: {
uri: 'parent' + ext
},
children: [
{
boundingVolume: {
region: llRegion
},
geometricError: 0.0,
content: {
uri: 'tileset3/tileset3.json'
}
},
{
boundingVolume: {
region: lrRegion
},
geometricError: 0.0,
content: {
uri: 'lr' + ext
}
},
{
boundingVolume: {
region: urRegion
},
geometricError: 0.0,
content: {
uri: 'ur' + ext
}
},
{
boundingVolume: {
region: ulRegion
},
geometricError: 0.0,
content: {
uri: 'ul' + ext
}
}
]
}
};
const tileset3Json = {
asset: {
version: tilesNextTilesetJsonVersion
},
geometricError: smallGeometricError,
root: {
boundingVolume: {
region: llRegion
},
geometricError: 0.0,
refine: 'ADD',
content: {
uri: 'll' + ext
}
}
};
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const gltfs = result.gltfs;
const batchTables = result.batchTables;
tilesetJson.properties = getProperties(batchTables);
await saveJson(tilesetPath, tilesetJson, args.prettyJson, args.gzip);
await saveJson(tileset2Path, tileset2Json, args.prettyJson, args.gzip);
await saveJson(tileset3Path, tileset3Json, args.prettyJson, args.gzip);
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tileFilename = tileNames[i] + ext;
await writeTile(tilesetDirectory, tileFilename, gltf, args);
}
}
export async function createTilesetRefinementMix(args: GeneratorArgs) {
// Create a tileset with a mix of additive and replacement refinement
// A - add
// R - replace
// A
// A R (not rendered)
// R A R A
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetRefinementMix';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const tileNames = ['parent', 'll', 'lr', 'ur', 'ul'];
const tileOptions = [
parentTileOptions,
llTileOptions,
lrTileOptions,
urTileOptions,
ulTileOptions
];
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const gltfs = result.gltfs;
const batchTables = result.batchTables;
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
properties: undefined,
geometricError: largeGeometricError,
root: {
boundingVolume: {
region: parentRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
content: {
uri: 'parent' + ext,
boundingVolume: {
region: parentContentRegion
}
},
children: [
{
boundingVolume: {
region: parentContentRegion
},
geometricError: smallGeometricError,
refine: 'REPLACE',
content: {
uri: 'parent' + ext
},
children: [
{
boundingVolume: {
region: llRegion
},
geometricError: 0.0,
refine: 'ADD',
content: {
uri: 'll' + ext
}
},
{
boundingVolume: {
region: urRegion
},
geometricError: 0.0,
refine: 'REPLACE',
content: {
uri: 'ur' + ext
}
}
]
},
{
boundingVolume: {
region: parentContentRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
content: {
uri: 'parent' + ext
},
children: [
{
boundingVolume: {
region: ulRegion
},
geometricError: 0.0,
refine: 'ADD',
content: {
uri: 'ul' + ext
}
},
{
boundingVolume: {
region: lrRegion
},
geometricError: 0.0,
refine: 'REPLACE',
content: {
uri: 'lr' + ext
}
}
]
}
]
}
};
tilesetJson.properties = getProperties(batchTables);
await saveJson(tilesetPath, tilesetJson, args.prettyJson, args.gzip);
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tileFilename = tileNames[i] + ext;
await writeTile(tilesetDirectory, tileFilename, gltf, args);
}
}
export async function createTilesetReplacement1(args: GeneratorArgs) {
// No children have content, but all grandchildren have content. Root uses replacement refinement.
// C - content
// E - empty
// C
// E E
// C C C C
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetReplacement1';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const tileNames = ['parent', 'll', 'lr', 'ur', 'ul'];
const tileOptions = [
parentTileOptions,
llTileOptions,
lrTileOptions,
urTileOptions,
ulTileOptions
];
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const gltfs = result.gltfs;
const batchTables = result.batchTables;
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
properties: undefined,
geometricError: largeGeometricError,
root: {
boundingVolume: {
region: parentRegion
},
geometricError: smallGeometricError,
refine: 'REPLACE',
content: {
uri: 'parent' + ext,
boundingVolume: {
region: parentContentRegion
}
},
children: [
{
boundingVolume: {
region: childrenRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
children: [
{
boundingVolume: {
region: llRegion
},
geometricError: 0.0,
content: {
uri: 'll' + ext
}
},
{
boundingVolume: {
region: urRegion
},
geometricError: 0.0,
content: {
uri: 'ur' + ext
}
}
]
},
{
boundingVolume: {
region: childrenRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
children: [
{
boundingVolume: {
region: lrRegion
},
geometricError: 0.0,
content: {
uri: 'lr' + ext
}
},
{
boundingVolume: {
region: ulRegion
},
geometricError: 0.0,
content: {
uri: 'ul' + ext
}
}
]
}
]
}
};
tilesetJson.properties = getProperties(batchTables);
await saveJson(tilesetPath, tilesetJson, args.prettyJson, args.gzip);
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tileFilename = tileNames[i] + ext;
await writeTile(tilesetDirectory, tileFilename, gltf, args);
}
}
export async function createTilesetReplacement2(args: GeneratorArgs) {
// C
// E
// C E
// C (smaller geometric error)
//
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetReplacement2';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const tileNames = ['parent', 'll', 'ur'];
const tileOptions = [parentTileOptions, llTileOptions, urTileOptions];
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const gltfs = result.gltfs;
const batchTables = result.batchTables;
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
properties: undefined,
geometricError: largeGeometricError,
root: {
boundingVolume: {
region: parentRegion
},
geometricError: smallGeometricError,
refine: 'REPLACE',
content: {
uri: 'parent' + ext,
boundingVolume: {
region: parentContentRegion
}
},
children: [
{
boundingVolume: {
region: childrenRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
children: [
{
boundingVolume: {
region: urRegion
},
geometricError: 7.0,
refine: 'REPLACE',
children: [
{
boundingVolume: {
region: urRegion
},
geometricError: 0.0,
content: {
uri: 'ur' + ext
}
}
]
},
{
boundingVolume: {
region: llRegion
},
geometricError: 0.0,
content: {
uri: 'll' + ext
}
}
]
}
]
}
};
tilesetJson.properties = getProperties(batchTables);
await saveJson(tilesetPath, tilesetJson, args.prettyJson, args.gzip);
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tileFilename = tileNames[i] + ext;
await writeTile(tilesetDirectory, tileFilename, gltf, args);
}
}
export async function createTilesetReplacement3(args: GeneratorArgs) {
// C
// T (external tileset ref)
// E (root of external tileset)
// C C C C
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetReplacement3';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const tileset2Path = path.join(tilesetDirectory, 'tileset2.json');
const tileNames = ['parent', 'll', 'lr', 'ur', 'ul'];
const tileOptions = [
parentTileOptions,
llTileOptions,
lrTileOptions,
urTileOptions,
ulTileOptions
];
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const gltfs = result.gltfs;
const batchTables = result.batchTables;
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
properties: undefined,
geometricError: largeGeometricError,
root: {
boundingVolume: {
region: parentRegion
},
geometricError: smallGeometricError,
refine: 'REPLACE',
content: {
uri: 'parent' + ext,
boundingVolume: {
region: parentContentRegion
}
},
children: [
{
boundingVolume: {
region: childrenRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
content: {
uri: 'tileset2.json'
}
}
]
}
};
const tileset2Json = {
asset: {
version: tilesNextTilesetJsonVersion
},
geometricError: smallGeometricError,
root: {
boundingVolume: {
region: childrenRegion
},
geometricError: smallGeometricError,
refine: 'REPLACE',
children: [
{
boundingVolume: {
region: llRegion
},
geometricError: 0.0,
content: {
uri: 'll' + ext
}
},
{
boundingVolume: {
region: lrRegion
},
geometricError: 0.0,
content: {
uri: 'lr' + ext
}
},
{
boundingVolume: {
region: urRegion
},
geometricError: 0.0,
content: {
uri: 'ur' + ext
}
},
{
boundingVolume: {
region: ulRegion
},
geometricError: 0.0,
content: {
uri: 'ul' + ext
}
}
]
}
};
tilesetJson.properties = getProperties(batchTables);
await saveJson(tilesetPath, tilesetJson, args.prettyJson, args.gzip);
await saveJson(tileset2Path, tileset2Json, args.prettyJson, args.gzip);
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tileFilename = tileNames[i] + ext;
await writeTile(tilesetDirectory, tileFilename, gltf, args);
}
}
export async function createTilesetWithTransforms(args: GeneratorArgs) {
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetWithTransforms';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const buildingsTileName = 'buildings' + ext;
const buildingsTilePath = path.join(
tilesetDirectory,
buildingsTileName
);
const instancesTileName = 'instances' + ext;
const instancesTilePath = path.join(
tilesetDirectory,
instancesTileName
);
const rootTransform = Matrix4.pack(buildingsTransform, new Array(16));
const rotation = Quaternion.fromAxisAngle(
Cartesian3.UNIT_Z,
CesiumMath.PI_OVER_FOUR
);
const translation = new Cartesian3(0, 0, 5.0);
const scale = new Cartesian3(0.5, 0.5, 0.5);
const childMatrix = Matrix4.fromTranslationQuaternionRotationScale(
translation,
rotation,
scale
);
const childTransform = Matrix4.pack(childMatrix, new Array(16));
const buildingsOptions = {
buildingOptions: buildingTemplate,
transform: Matrix4.IDENTITY
};
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
properties: undefined,
geometricError: smallGeometricError,
root: {
boundingVolume: {
box: smallBoxLocal
},
transform: rootTransform,
geometricError: instancesGeometricError,
refine: 'ADD',
content: {
uri: buildingsTileName
},
children: [
{
boundingVolume: {
box: instancesBoxLocal
},
transform: childTransform,
geometricError: 0.0,
content: {
uri: instancesTileName
}
}
]
}
};
const instancedTile = await getGltfFromGlbUri(
instancesUri,
gltfConversionOptions
);
//
// i3dm (gltf)
//
const instancedPositions = InstanceTileUtils.getPositions(
instancesLength,
instancesTileWidth,
instancesModelSize,
Matrix4.IDENTITY
);
// add EXT_mesh_gpu_instancing
const positionAccessorIndex = instancedTile.accessors.length;
addBinaryBuffers(instancedTile, instancedPositions);
createEXTMeshInstancingExtension(
instancedTile,
instancedTile.nodes[0],
{
attributes: {
TRANSLATION: positionAccessorIndex
}
}
);
// CESIUM_3dtiles_feature_metadata
const prim = instancedTile.meshes[0].primitives[0];
FeatureMetadata.updateExtensionUsed(instancedTile);
FeatureMetadata.addFeatureLayer(prim, {
featureTable: 0,
vertexAttribute: {
implicit: {
increment: 0,
start: 0
}
}
});
FeatureMetadata.addFeatureTable(instancedTile, {
featureCount: instancesLength,
properties: {
Height: {
values: new Array(instancesLength).fill(instancesModelSize)
}
}
});
//
// b3dm (gltf)
//
const buildings = createBuildings(buildingsOptions.buildingOptions);
const buildingTable = generateBuildingBatchTable(buildings);
delete buildingTable.id;
const batchedMesh = Mesh.batch(
FeatureTableUtils.createMeshes(buildingsTransform, buildings, false)
);
const gltfOptions = {
mesh: batchedMesh,
useBatchIds: false,
relativeToCenter: true,
deprecated: false,
use3dTilesNext: true,
featureTableJson: undefined
};
const buildingTile = createGltf(gltfOptions) as Gltf;
FeatureMetadata.updateExtensionUsed(buildingTile);
buildingTile.meshes[0].primitives[0].extensions = {
CESIUM_3dtiles_feature_metadata: {
featureLayers: [
{
featureTable: 0,
vertexAttribute: {
implicit: {
increment: 1,
start: 0
}
}
}
]
}
};
buildingTile.extensions = {
CESIUM_3dtiles_feature_metadata: {
featureTables: [
{
featureCount: buildingTable.Height.length,
properties: {
Height: { values: buildingTable.Height },
Longitude: { values: buildingTable.Longitude },
Latitude: { values: buildingTable.Latitude }
}
}
]
}
};
await writeTileset(tilesetDirectory, tilesetJson as any, args);
await writeTile(
tilesetDirectory,
buildingsTileName,
buildingTile,
args
);
await writeTile(
tilesetDirectory,
instancesTileName,
instancedTile,
args
);
}
export async function createTilesetWithViewerRequestVolume(
args: GeneratorArgs
) {
// Create a tileset with one root tile and four child tiles
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetWithViewerRequestVolume';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const tileNames = ['ll', 'lr', 'ur', 'ul'];
const tileOptions = [
llTileOptions,
lrTileOptions,
urTileOptions,
ulTileOptions
];
const pointCloudTileName = 'points' + ext;
const pointCloudTilePath = path.join(
tilesetDirectory,
pointCloudTileName
);
const pointsLength = 1000;
const pointCloudTileWidth = 20.0;
const pointCloudRadius = pointCloudTileWidth / 2.0;
const pointCloudSphereLocal = [0.0, 0.0, 0.0, pointCloudRadius];
const pointCloudHeight = pointCloudRadius + 5.0;
const pointCloudMatrix = wgs84Transform(
longitude,
latitude,
pointCloudHeight
);
const pointCloudTransform = Matrix4.pack(
pointCloudMatrix,
new Array(16)
);
const pointCloudViewerRequestSphere = [
0.0,
0.0,
0.0,
pointCloudTileWidth * 50.0
]; // Point cloud only become visible when you are inside the request volume
const pointCloudOptions = {
tileWidth: pointCloudTileWidth,
pointsLength: pointsLength,
transform: Matrix4.IDENTITY,
shape: 'sphere',
use3dTilesNext: true
};
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
geometricError: largeGeometricError,
root: {
boundingVolume: {
region: childrenRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
children: [
{
boundingVolume: {
region: llRegion
},
geometricError: 0.0,
content: {
uri: 'll' + ext
}
},
{
boundingVolume: {
region: lrRegion
},
geometricError: 0.0,
content: {
uri: 'lr' + ext
}
},
{
boundingVolume: {
region: urRegion
},
geometricError: 0.0,
content: {
uri: 'ur' + ext
}
},
{
boundingVolume: {
region: ulRegion
},
geometricError: 0.0,
content: {
uri: 'ul' + ext
}
},
{
transform: pointCloudTransform,
viewerRequestVolume: {
sphere: pointCloudViewerRequestSphere
},
boundingVolume: {
sphere: pointCloudSphereLocal
},
geometricError: 0.0,
content: {
uri: 'points' + ext
}
}
]
}
};
// TODO: Abstract the point cloud creation logic into smaller functions
// so the `use-3dtiles-next` flag is unnecessary and this code
// matches compositeSamplesNext / instanceSamplesNext
const gltf = (await createPointCloudTile(pointCloudOptions)).gltf;
await writeTilesetAndTile(
tilesetDirectory,
pointCloudTileName,
tilesetJson as any,
gltf,
args
);
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const gltfs = result.gltfs;
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tileFilename = tileNames[i] + ext;
await writeTile(tilesetDirectory, tileFilename, gltf, args);
}
}
export async function createTilesetReplacementWithViewerRequestVolume(
args: GeneratorArgs
) {
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetReplacementWithViewerRequestVolume';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const tileNames = ['parent', 'll', 'lr', 'ur', 'ul'];
const tileOptions = [
parentTileOptions,
llTileOptions,
lrTileOptions,
urTileOptions,
ulTileOptions
];
const requestHeight = 50.0;
const childRequestRegion = [
longitude - longitudeExtent / 2.0,
latitude - latitudeExtent / 2.0,
longitude + longitudeExtent / 2.0,
latitude + latitudeExtent / 2.0,
0.0,
requestHeight
];
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
properties: undefined,
geometricError: largeGeometricError,
root: {
boundingVolume: {
region: parentRegion
},
geometricError: largeGeometricError,
refine: 'REPLACE',
children: [
{
boundingVolume: {
region: parentRegion
},
geometricError: smallGeometricError,
refine: 'REPLACE',
content: {
uri: 'parent' + ext,
boundingVolume: {
region: parentContentRegion
}
},
children: [
{
boundingVolume: {
region: llRegion
},
viewerRequestVolume: {
region: childRequestRegion
},
geometricError: 0.0,
content: {
uri: 'll' + ext
}
},
{
boundingVolume: {
region: lrRegion
},
viewerRequestVolume: {
region: childRequestRegion
},
geometricError: 0.0,
content: {
uri: 'lr' + ext
}
},
{
boundingVolume: {
region: urRegion
},
viewerRequestVolume: {
region: childRequestRegion
},
geometricError: 0.0,
content: {
uri: 'ur' + ext
}
},
{
boundingVolume: {
region: ulRegion
},
viewerRequestVolume: {
region: childRequestRegion
},
geometricError: 0.0,
content: {
uri: 'ul' + ext
}
}
]
}
]
}
};
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const gltfs = result.gltfs;
const batchTables = result.batchTables;
tilesetJson.properties = getProperties(batchTables);
await saveJson(tilesetPath, tilesetJson, args.prettyJson, args.gzip);
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tileFilename = tileNames[i] + ext;
await writeTile(tilesetDirectory, tileFilename, gltf, args);
}
}
export async function createTilesetSubtreeExpiration(args: GeneratorArgs) {
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetSubtreeExpiration';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const subtreePath = path.join(tilesetDirectory, 'subtree.json');
const tileNames = ['parent', 'll', 'lr', 'ur', 'ul'];
const tileOptions = [
parentTileOptions,
llTileOptions,
lrTileOptions,
urTileOptions,
ulTileOptions
];
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
properties: undefined,
geometricError: largeGeometricError,
root: {
boundingVolume: {
region: parentRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
content: {
boundingVolume: {
region: parentContentRegion
},
uri: 'parent' + ext
},
children: [
{
expire: {
duration: 5.0
},
boundingVolume: {
region: childrenRegion
},
geometricError: smallGeometricError,
content: {
uri: 'subtree.json'
}
}
]
}
};
const subtreeJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
properties: undefined,
geometricError: smallGeometricError,
root: {
boundingVolume: {
region: childrenRegion
},
geometricError: smallGeometricError,
refine: 'ADD',
children: [
{
boundingVolume: {
region: llRegion
},
geometricError: 0.0,
content: {
uri: 'll' + ext
}
},
{
boundingVolume: {
region: lrRegion
},
geometricError: 0.0,
content: {
uri: 'lr' + ext
}
},
{
boundingVolume: {
region: urRegion
},
geometricError: 0.0,
content: {
uri: 'ur' + ext
}
},
{
boundingVolume: {
region: ulRegion
},
geometricError: 0.0,
content: {
uri: 'ul' + ext
}
}
]
}
};
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const gltfs = result.gltfs;
const batchTables = result.batchTables;
tilesetJson.properties = getProperties(batchTables);
await saveJson(tilesetPath, tilesetJson, args.prettyJson, args.gzip);
await saveJson(subtreePath, subtreeJson, args.prettyJson, args.gzip);
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tilePath = path.join(tilesetDirectory, tileNames[i] + ext);
await writeTile(tilePath, '', gltf, args);
}
}
export async function createTilesetPoints(args: GeneratorArgs) {
// Create a tileset with one root tile and eight child tiles
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetPoints';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const pointsLength = 1000;
const parentTileWidth = 10.0;
const parentTileHalfWidth = parentTileWidth / 2.0;
const parentGeometricError = 1.732 * parentTileWidth; // Diagonal of the point cloud box
const parentMatrix = wgs84Transform(
longitude,
latitude,
parentTileHalfWidth
);
const parentTransform = Matrix4.pack(parentMatrix, new Array(16));
const parentBoxLocal = [
0.0,
0.0,
0.0, // center
parentTileHalfWidth,
0.0,
0.0, // width
0.0,
parentTileHalfWidth,
0.0, // depth
0.0,
0.0,
parentTileHalfWidth // height
];
const parentTile = (await createPointCloudTile({
tileWidth: parentTileWidth * 2.0,
pointsLength: pointsLength,
relativeToCenter: false,
use3dTilesNext: true,
useGlb: args.useGlb
})).gltf;
const childrenJson = [];
const childTiles: Gltf[] = [];
const childTileWidth = 5.0;
const childTileHalfWidth = childTileWidth / 2.0;
const childGeometricError = 1.732 * childTileWidth; // Diagonal of the point cloud box
const childCenters = [
[-childTileHalfWidth, -childTileHalfWidth, -childTileHalfWidth],
[-childTileHalfWidth, childTileHalfWidth, childTileHalfWidth],
[-childTileHalfWidth, -childTileHalfWidth, childTileHalfWidth],
[-childTileHalfWidth, childTileHalfWidth, -childTileHalfWidth],
[childTileHalfWidth, -childTileHalfWidth, -childTileHalfWidth],
[childTileHalfWidth, childTileHalfWidth, -childTileHalfWidth],
[childTileHalfWidth, -childTileHalfWidth, childTileHalfWidth],
[childTileHalfWidth, childTileHalfWidth, childTileHalfWidth]
];
for (let i = 0; i < 8; ++i) {
const childCenter = childCenters[i];
const childTransform = Matrix4.fromTranslation(
Cartesian3.unpack(childCenter)
);
childTiles.push(
(await createPointCloudTile({
tileWidth: childTileWidth * 2.0,
transform: childTransform,
pointsLength: pointsLength,
relativeToCenter: false,
use3dTilesNext: true,
useGlb: args.useGlb
})).gltf as Gltf
);
const childBoxLocal = [
childCenter[0],
childCenter[1],
childCenter[2],
childTileHalfWidth,
0.0,
0.0, // width
0.0,
childTileHalfWidth,
0.0, // depth
0.0,
0.0,
childTileHalfWidth // height
];
childrenJson.push({
boundingVolume: {
box: childBoxLocal
},
geometricError: 0.0,
content: {
uri: i + ext
}
});
}
const tilesetJson = {
asset: {
version: tilesNextTilesetJsonVersion
},
properties: undefined,
geometricError: parentGeometricError,
root: {
boundingVolume: {
box: parentBoxLocal
},
transform: parentTransform,
geometricError: childGeometricError,
refine: 'ADD',
content: {
uri: 'parent' + ext
},
children: childrenJson
}
};
await writeTile(tilesetDirectory, 'parent' + ext, parentTile, args);
await writeTileset(tilesetDirectory, tilesetJson as any, args);
for (let i = 0; i < 8; ++i) {
await writeTile(
tilesetDirectory,
i + ext,
childTiles[i] as Gltf,
args
);
}
}
export async function createTilesetUniform(args: GeneratorArgs) {
const ext = args.useGlb
? TilesNextExtension.Glb
: TilesNextExtension.Gltf;
const tilesetName = 'TilesetUniform';
const tilesetDirectory = path.join(rootDir, tilesetName);
const tilesetPath = path.join(tilesetDirectory, 'tileset.json');
const tileset2Path = path.join(tilesetDirectory, 'tileset2.json');
// Only subdivide the middle tile in level 1. Helps reduce tileset size.
const subdivideCallback = (level: number, x: number, y: number) =>
level === 0 || (level === 1 && x === 1 && y === 1);
const results = TilesetUtilsNext.createUniformTileset(
3,
3,
ext,
subdivideCallback
);
const tileOptions = results.tileOptions as TileOptions[];
const tileNames = results.tileNames;
const tilesetJson: any = results.tilesetJson;
// Insert an external tileset
const externalTile1 = clone(tilesetJson.root, true);
delete externalTile1.transform;
delete externalTile1.refine;
delete externalTile1.children;
externalTile1.content.uri = 'tileset2.json';
const externalTile2 = clone(tilesetJson.root, true);
delete externalTile2.transform;
delete externalTile2.content;
const tileset2Json = clone(tilesetJson, true);
tileset2Json.root = externalTile2;
tilesetJson.root.children = [externalTile1];
const result = TilesetUtilsNext.createBuildingGltfsWithFeatureMetadata(
tileOptions
);
const gltfs = result.gltfs;
const batchTables = result.batchTables;
tilesetJson.properties = getProperties(batchTables);
saveJson(tilesetPath, tilesetJson, args.prettyJson, args.gzip);
saveJson(tileset2Path, tileset2Json, args.prettyJson, args.gzip);
for (let i = 0; i < gltfs.length; ++i) {
const gltf = gltfs[i];
const tilePath = path.join(tilesetDirectory, tileNames[i]);
await writeTile(tilePath, '', gltf, args);
}
}
} | the_stack |
import { mockNavigatorOnLine, sleep } from '../../react/tests/utils'
import { QueryCache } from '../queryCache'
import { QueryClient } from '../queryClient'
import { dehydrate, hydrate } from '../hydration'
async function fetchData<TData>(value: TData, ms?: number): Promise<TData> {
await sleep(ms || 0)
return value
}
describe('dehydration and rehydration', () => {
test('should work with serializeable values', async () => {
const queryCache = new QueryCache()
const queryClient = new QueryClient({ queryCache })
await queryClient.prefetchQuery('string', () => fetchData('string'))
await queryClient.prefetchQuery('number', () => fetchData(1))
await queryClient.prefetchQuery('boolean', () => fetchData(true))
await queryClient.prefetchQuery('null', () => fetchData(null))
await queryClient.prefetchQuery('array', () => fetchData(['string', 0]))
await queryClient.prefetchQuery('nested', () =>
fetchData({ key: [{ nestedKey: 1 }] })
)
const dehydrated = dehydrate(queryClient)
const stringified = JSON.stringify(dehydrated)
// ---
const parsed = JSON.parse(stringified)
const hydrationCache = new QueryCache()
const hydrationClient = new QueryClient({ queryCache: hydrationCache })
hydrate(hydrationClient, parsed)
expect(hydrationCache.find('string')?.state.data).toBe('string')
expect(hydrationCache.find('number')?.state.data).toBe(1)
expect(hydrationCache.find('boolean')?.state.data).toBe(true)
expect(hydrationCache.find('null')?.state.data).toBe(null)
expect(hydrationCache.find('array')?.state.data).toEqual(['string', 0])
expect(hydrationCache.find('nested')?.state.data).toEqual({
key: [{ nestedKey: 1 }],
})
const fetchDataAfterHydration = jest.fn()
await hydrationClient.prefetchQuery('string', fetchDataAfterHydration, {
staleTime: 1000,
})
await hydrationClient.prefetchQuery('number', fetchDataAfterHydration, {
staleTime: 1000,
})
await hydrationClient.prefetchQuery('boolean', fetchDataAfterHydration, {
staleTime: 1000,
})
await hydrationClient.prefetchQuery('null', fetchDataAfterHydration, {
staleTime: 1000,
})
await hydrationClient.prefetchQuery('array', fetchDataAfterHydration, {
staleTime: 1000,
})
await hydrationClient.prefetchQuery('nested', fetchDataAfterHydration, {
staleTime: 1000,
})
expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0)
queryClient.clear()
hydrationClient.clear()
})
test('should use the cache time from the client', async () => {
const queryCache = new QueryCache()
const queryClient = new QueryClient({ queryCache })
await queryClient.prefetchQuery('string', () => fetchData('string'), {
cacheTime: 50,
})
const dehydrated = dehydrate(queryClient)
const stringified = JSON.stringify(dehydrated)
await sleep(20)
// ---
const parsed = JSON.parse(stringified)
const hydrationCache = new QueryCache()
const hydrationClient = new QueryClient({ queryCache: hydrationCache })
hydrate(hydrationClient, parsed)
expect(hydrationCache.find('string')?.state.data).toBe('string')
await sleep(100)
expect(hydrationCache.find('string')).toBeTruthy()
queryClient.clear()
hydrationClient.clear()
})
test('should be able to provide default options for the hydrated queries', async () => {
const queryCache = new QueryCache()
const queryClient = new QueryClient({ queryCache })
await queryClient.prefetchQuery('string', () => fetchData('string'))
const dehydrated = dehydrate(queryClient)
const stringified = JSON.stringify(dehydrated)
const parsed = JSON.parse(stringified)
const hydrationCache = new QueryCache()
const hydrationClient = new QueryClient({ queryCache: hydrationCache })
hydrate(hydrationClient, parsed, {
defaultOptions: { queries: { retry: 10 } },
})
expect(hydrationCache.find('string')?.options.retry).toBe(10)
queryClient.clear()
hydrationClient.clear()
})
test('should work with complex keys', async () => {
const queryCache = new QueryCache()
const queryClient = new QueryClient({ queryCache })
await queryClient.prefetchQuery(
['string', { key: ['string'], key2: 0 }],
() => fetchData('string')
)
const dehydrated = dehydrate(queryClient)
const stringified = JSON.stringify(dehydrated)
// ---
const parsed = JSON.parse(stringified)
const hydrationCache = new QueryCache()
const hydrationClient = new QueryClient({ queryCache: hydrationCache })
hydrate(hydrationClient, parsed)
expect(
hydrationCache.find(['string', { key: ['string'], key2: 0 }])?.state.data
).toBe('string')
const fetchDataAfterHydration = jest.fn()
await hydrationClient.prefetchQuery(
['string', { key: ['string'], key2: 0 }],
fetchDataAfterHydration,
{ staleTime: 100 }
)
expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0)
queryClient.clear()
hydrationClient.clear()
})
test('should only hydrate successful queries by default', async () => {
const consoleMock = jest.spyOn(console, 'error')
consoleMock.mockImplementation(() => undefined)
const queryCache = new QueryCache()
const queryClient = new QueryClient({ queryCache })
await queryClient.prefetchQuery('success', () => fetchData('success'))
queryClient.prefetchQuery('loading', () => fetchData('loading', 10000))
await queryClient.prefetchQuery('error', () => {
throw new Error()
})
const dehydrated = dehydrate(queryClient)
const stringified = JSON.stringify(dehydrated)
// ---
const parsed = JSON.parse(stringified)
const hydrationCache = new QueryCache()
const hydrationClient = new QueryClient({ queryCache: hydrationCache })
hydrate(hydrationClient, parsed)
expect(hydrationCache.find('success')).toBeTruthy()
expect(hydrationCache.find('loading')).toBeFalsy()
expect(hydrationCache.find('error')).toBeFalsy()
queryClient.clear()
hydrationClient.clear()
consoleMock.mockRestore()
})
test('should filter queries via shouldDehydrateQuery', async () => {
const queryCache = new QueryCache()
const queryClient = new QueryClient({ queryCache })
await queryClient.prefetchQuery('string', () => fetchData('string'))
await queryClient.prefetchQuery('number', () => fetchData(1))
const dehydrated = dehydrate(queryClient, {
shouldDehydrateQuery: query => query.queryKey !== 'string',
})
// This is testing implementation details that can change and are not
// part of the public API, but is important for keeping the payload small
const dehydratedQuery = dehydrated?.queries.find(
query => query?.queryKey === 'string'
)
expect(dehydratedQuery).toBeUndefined()
const stringified = JSON.stringify(dehydrated)
// ---
const parsed = JSON.parse(stringified)
const hydrationCache = new QueryCache()
const hydrationClient = new QueryClient({ queryCache: hydrationCache })
hydrate(hydrationClient, parsed)
expect(hydrationCache.find('string')).toBeUndefined()
expect(hydrationCache.find('number')?.state.data).toBe(1)
queryClient.clear()
hydrationClient.clear()
})
test('should not overwrite query in cache if hydrated query is older', async () => {
const queryCache = new QueryCache()
const queryClient = new QueryClient({ queryCache })
await queryClient.prefetchQuery('string', () =>
fetchData('string-older', 5)
)
const dehydrated = dehydrate(queryClient)
const stringified = JSON.stringify(dehydrated)
// ---
const parsed = JSON.parse(stringified)
const hydrationCache = new QueryCache()
const hydrationClient = new QueryClient({ queryCache: hydrationCache })
await hydrationClient.prefetchQuery('string', () =>
fetchData('string-newer', 5)
)
hydrate(hydrationClient, parsed)
expect(hydrationCache.find('string')?.state.data).toBe('string-newer')
queryClient.clear()
hydrationClient.clear()
})
test('should overwrite query in cache if hydrated query is newer', async () => {
const hydrationCache = new QueryCache()
const hydrationClient = new QueryClient({ queryCache: hydrationCache })
await hydrationClient.prefetchQuery('string', () =>
fetchData('string-older', 5)
)
// ---
const queryCache = new QueryCache()
const queryClient = new QueryClient({ queryCache })
await queryClient.prefetchQuery('string', () =>
fetchData('string-newer', 5)
)
const dehydrated = dehydrate(queryClient)
const stringified = JSON.stringify(dehydrated)
// ---
const parsed = JSON.parse(stringified)
hydrate(hydrationClient, parsed)
expect(hydrationCache.find('string')?.state.data).toBe('string-newer')
queryClient.clear()
hydrationClient.clear()
})
test('should be able to dehydrate mutations and continue on hydration', async () => {
const consoleMock = jest.spyOn(console, 'error')
consoleMock.mockImplementation(() => undefined)
mockNavigatorOnLine(false)
const serverAddTodo = jest
.fn()
.mockImplementation(() => Promise.reject('offline'))
const serverOnMutate = jest.fn().mockImplementation(variables => {
const optimisticTodo = { id: 1, text: variables.text }
return { optimisticTodo }
})
const serverOnSuccess = jest.fn()
const serverClient = new QueryClient()
serverClient.setMutationDefaults('addTodo', {
mutationFn: serverAddTodo,
onMutate: serverOnMutate,
onSuccess: serverOnSuccess,
retry: 3,
retryDelay: 10,
})
serverClient
.executeMutation({
mutationKey: 'addTodo',
variables: { text: 'text' },
})
.catch(() => undefined)
await sleep(50)
const dehydrated = dehydrate(serverClient)
const stringified = JSON.stringify(dehydrated)
serverClient.clear()
// ---
mockNavigatorOnLine(true)
const parsed = JSON.parse(stringified)
const client = new QueryClient()
const clientAddTodo = jest.fn().mockImplementation(variables => {
return { id: 2, text: variables.text }
})
const clientOnMutate = jest.fn().mockImplementation(variables => {
const optimisticTodo = { id: 1, text: variables.text }
return { optimisticTodo }
})
const clientOnSuccess = jest.fn()
client.setMutationDefaults('addTodo', {
mutationFn: clientAddTodo,
onMutate: clientOnMutate,
onSuccess: clientOnSuccess,
retry: 3,
retryDelay: 10,
})
hydrate(client, parsed)
await client.resumePausedMutations()
expect(clientAddTodo).toHaveBeenCalledTimes(1)
expect(clientOnMutate).not.toHaveBeenCalled()
expect(clientOnSuccess).toHaveBeenCalledTimes(1)
expect(clientOnSuccess).toHaveBeenCalledWith(
{ id: 2, text: 'text' },
{ text: 'text' },
{ optimisticTodo: { id: 1, text: 'text' } }
)
client.clear()
consoleMock.mockRestore()
})
}) | the_stack |
import { BigNumber } from "bignumber.js";
import * as moment from "moment";
import * as Web3 from "web3";
// Utils
import * as Units from "../../../../../utils/units";
import { Web3Utils } from "../../../../../utils/web3_utils";
// Scenarios
import { ReturnCollateralScenario, SeizeCollateralScenario } from "../scenarios";
// Adapters
import { CollateralizedSimpleInterestLoanAdapter } from "../../../../../src/adapters/collateralized_simple_interest_loan_adapter";
// Wrappers
import { CollateralizedSimpleInterestTermsContractContract } from "../../../../../src/wrappers/contract_wrappers/collateralized_simple_interest_terms_contract_wrapper";
import { DebtKernelContract } from "../../../../../src/wrappers/contract_wrappers/debt_kernel_wrapper";
import { DummyTokenContract } from "../../../../../src/wrappers/contract_wrappers/dummy_token_wrapper";
import { RepaymentRouterContract } from "../../../../../src/wrappers/contract_wrappers/repayment_router_wrapper";
import { TokenTransferProxyContract } from "../../../../../src/wrappers/contract_wrappers/token_transfer_proxy_wrapper";
// APIs
import { OrderAPI } from "../../../../../src/apis/order_api";
import { ServicingAPI } from "../../../../../src/apis/servicing_api";
import { SignerAPI } from "../../../../../src/apis/signer_api";
// Types
import { DebtOrderData } from "../../../../../src/types/debt_order_data";
// Accounts
import { ACCOUNTS } from "../../../../../__test__/accounts";
import { ContractsAPI } from "../../../../../src/apis/contracts_api";
import { TokenAPI } from "../../../../../src/apis/token_api";
const CONTRACT_OWNER = ACCOUNTS[0];
const DEBTOR = ACCOUNTS[1];
const CREDITOR = ACCOUNTS[2];
const UNDERWRITER = ACCOUNTS[3];
const RELAYER = ACCOUNTS[4];
const TX_DEFAULTS = { from: CONTRACT_OWNER.address, gas: 4712388 };
export interface APIs {
orderApi: OrderAPI;
signerApi: SignerAPI;
servicingApi: ServicingAPI;
contractsApi: ContractsAPI;
tokenApi: TokenAPI;
}
export abstract class BaseCollateralRunner {
protected adapter: CollateralizedSimpleInterestLoanAdapter;
protected debtKernel: DebtKernelContract;
protected repaymentRouter: RepaymentRouterContract;
protected principalToken: DummyTokenContract;
protected collateralToken: DummyTokenContract;
protected termsContract: CollateralizedSimpleInterestTermsContractContract;
protected orderApi: OrderAPI;
protected signerApi: SignerAPI;
protected tokenTransferProxy: TokenTransferProxyContract;
protected web3: Web3;
protected web3Utils: Web3Utils;
protected servicingApi: ServicingAPI;
protected contractsApi: ContractsAPI;
protected tokenApi: TokenAPI;
protected snapshotId: number;
protected debtOrderData: DebtOrderData;
constructor(web3: Web3, adapter: CollateralizedSimpleInterestLoanAdapter, apis: APIs) {
this.web3 = web3;
this.orderApi = apis.orderApi;
this.signerApi = apis.signerApi;
this.servicingApi = apis.servicingApi;
this.contractsApi = apis.contractsApi;
this.tokenApi = apis.tokenApi;
this.adapter = adapter;
this.web3Utils = new Web3Utils(web3);
this.testScenario = this.testScenario.bind(this);
this.revertToSavedSnapshot = this.revertToSavedSnapshot.bind(this);
}
public async saveSnapshotAsync() {
this.snapshotId = await this.web3Utils.saveTestSnapshot();
}
public async revertToSavedSnapshot() {
await this.web3Utils.revertToSnapshot(this.snapshotId);
}
public abstract testScenario(scenario: ReturnCollateralScenario | SeizeCollateralScenario);
// Increases EVM time to a given new time in seconds since unix epoch.
protected async increaseTime(newTime: number): Promise<void> {
const secondsUntilNewTime = newTime - (await this.web3Utils.getCurrentBlockTime());
await this.web3Utils.increaseTime(secondsUntilNewTime + 1);
}
protected async setBalances(
scenario: ReturnCollateralScenario | SeizeCollateralScenario,
): Promise<void> {
// 1. Set up Debtor balances.
// The debtor has the exact amount of the collateral token as
// they are going to set up as collateral.
await this.collateralToken.setBalance.sendTransactionAsync(
DEBTOR.address,
scenario.collateralTerms.collateralAmount,
{
from: CONTRACT_OWNER.address,
},
);
// The debtor has more than enough of the principal token to repay debts.
await this.principalToken.setBalance.sendTransactionAsync(
DEBTOR.address,
scenario.simpleTerms.principalAmount.mul(2),
{
from: CONTRACT_OWNER.address,
},
);
// 2. Set up creditor balances.
// The creditor has exactly the amount necessary to loan to the debtor,
// as well as to pay for the creditor fee.
await this.principalToken.setBalance.sendTransactionAsync(
CREDITOR.address,
scenario.simpleTerms.principalAmount.add(this.debtOrderData.creditorFee),
{
from: CONTRACT_OWNER.address,
},
);
// 3. Set up underwriter balances.
// The underwriter has enough balance to pay the underwriter fee.
await this.principalToken.setBalance.sendTransactionAsync(
UNDERWRITER.address,
this.debtOrderData.underwriterFee,
{
from: CONTRACT_OWNER.address,
},
);
}
protected async setApprovals(
scenario: ReturnCollateralScenario | SeizeCollateralScenario,
): Promise<void> {
const { debtor, creditor, principalAmount } = this.debtOrderData;
// The debtor grants the transfer proxy an allowance for moving the collateral.
await this.tokenApi.setProxyAllowanceAsync(
this.collateralToken.address,
scenario.collateralTerms.collateralAmount,
{ from: debtor },
);
// The debtor grants the transfer proxy some sufficient allowance for making repayments.
await this.tokenApi.setProxyAllowanceAsync(
this.principalToken.address,
principalAmount.mul(2),
{ from: debtor },
);
// The creditor grants allowance of the principal token being loaned,
// as well as the creditor fee.
await this.tokenApi.setProxyAllowanceAsync(
this.principalToken.address,
principalAmount.add(this.debtOrderData.creditorFee),
{ from: creditor },
);
}
protected async signOrder(): Promise<void> {
this.debtOrderData.debtorSignature = await this.signerApi.asDebtor(
this.debtOrderData,
false,
);
this.debtOrderData.creditorSignature = await this.signerApi.asCreditor(
this.debtOrderData,
false,
);
this.debtOrderData.underwriterSignature = await this.signerApi.asUnderwriter(
this.debtOrderData,
false,
);
}
protected async repayDebt(agreementId, termEnd): Promise<void> {
const amount = await this.termsContract.getExpectedRepaymentValue.callAsync(
agreementId,
termEnd,
);
await this.servicingApi.makeRepayment(agreementId, amount, this.principalToken.address, {
from: this.debtOrderData.debtor,
});
}
protected generateDebtOrderData(
scenario: ReturnCollateralScenario | SeizeCollateralScenario,
): DebtOrderData {
const termsParams = this.adapter.packParameters(
scenario.simpleTerms,
scenario.collateralTerms,
);
return {
kernelVersion: this.debtKernel.address,
issuanceVersion: this.repaymentRouter.address,
principalAmount: scenario.simpleTerms.principalAmount,
principalToken: this.principalToken.address,
debtor: DEBTOR.address,
debtorFee: Units.ether(0.001),
creditor: CREDITOR.address,
creditorFee: Units.ether(0.002),
relayer: RELAYER.address,
relayerFee: Units.ether(0.0015),
termsContract: this.termsContract.address,
termsContractParameters: termsParams,
expirationTimestampInSec: new BigNumber(
moment()
.add(7, "days")
.unix(),
),
underwriter: UNDERWRITER.address,
underwriterFee: Units.ether(0.0015),
underwriterRiskRating: new BigNumber(1350),
salt: new BigNumber(0),
};
}
protected async generateAndFillOrder(
scenario: ReturnCollateralScenario | SeizeCollateralScenario,
): Promise<void> {
this.debtOrderData = this.generateDebtOrderData(scenario);
await this.signOrder();
await this.setBalances(scenario);
await this.setApprovals(scenario);
await this.orderApi.fillAsync(this.debtOrderData, {
from: CREDITOR.address,
// NOTE: Using the maximum gas here, to prevent potentially confusing
// reverts due to insufficient gas. This wouldn't be applied in practice.
gas: 4712388,
});
}
protected async initializeWrappers(
scenario: ReturnCollateralScenario | SeizeCollateralScenario,
) {
this.debtKernel = await DebtKernelContract.deployed(this.web3);
this.repaymentRouter = await RepaymentRouterContract.deployed(this.web3);
this.termsContract = await this.contractsApi.loadCollateralizedSimpleInterestTermsContract(
TX_DEFAULTS,
);
const principalTokenSymbol = await this.contractsApi.getTokenSymbolByIndexAsync(
scenario.simpleTerms.principalTokenIndex,
);
const collateralTokenSymbol = await this.contractsApi.getTokenSymbolByIndexAsync(
scenario.collateralTerms.collateralTokenIndex,
);
this.principalToken = await DummyTokenContract.at(
(await this.contractsApi.loadTokenBySymbolAsync(principalTokenSymbol)).address,
this.web3,
TX_DEFAULTS,
);
this.collateralToken = await DummyTokenContract.at(
(await this.contractsApi.loadTokenBySymbolAsync(collateralTokenSymbol)).address,
this.web3,
TX_DEFAULTS,
);
this.tokenTransferProxy = await this.contractsApi.loadTokenTransferProxyAsync();
}
} | the_stack |
import React from 'react';
import createClass from 'create-react-class';
import { Button, CloseIcon, EditIcon, Expander } from './../../index';
export default {
title: 'Layout/Expander',
component: Expander,
parameters: {
docs: {
description: {
component: (Expander as any).peek.description,
},
},
},
};
/* Expanded */
export const Expanded = () => {
const Component = createClass({
render() {
return (
<div>
<Expander isExpanded={true}>
<Expander.Label>Show Less</Expander.Label>
<p>
You can't get rid of me. Keep clicking that icon as much as you
want, but I'm here to stay!
</p>
</Expander>
</div>
);
},
});
return <Component />;
};
Expanded.storyName = 'Expanded';
/* Interactive With Changing Labels */
export const InteractiveWithChangingLabels = () => {
const Component = createClass({
getInitialState() {
return {
isExpanded: false,
};
},
render() {
return (
<div>
<Expander
isExpanded={this.state.isExpanded}
onToggle={this.handleExpanded}
>
<Expander.Label>
{this.state.isExpanded ? 'Show Less' : 'Show More'}
</Expander.Label>
<p>
Artisan helvetica quinoa kogi fingerstache, biodiesel church-key
blue bottle everyday carry schlitz seitan locavore. Retro +1
tilde, normcore post-ironic chillwave PBR&B umami. Mlkshk
mumblecore meh, kitsch pickled wolf helvetica man bun cronut
keffiyeh meggings ramps. Banh mi stumptown cronut wayfarers. Banh
mi venmo street art chicharrones, put a bird on it yuccie cornhole
poutine knausgaard echo park tilde retro. Occupy XOXO etsy meh
pabst blue bottle. Photo booth four loko biodiesel, cornhole
chicharrones echo park actually pork belly gochujang DIY
gluten-free plaid microdosing salvia pinterest.
</p>
<p>
Cred lumbersexual organic, echo park hashtag roof party pinterest
shabby chic green juice salvia scenester hella ramps. Schlitz
knausgaard church-key disrupt, four loko XOXO bicycle rights
post-ironic four dollar toast fixie butcher mustache tousled
humblebrag. Bushwick 8-bit swag, wolf intelligentsia kickstarter
roof party cred meh semiotics flannel. Typewriter umami narwhal
irony, slow-carb VHS street art cold-pressed wayfarers sriracha
everyday carry church-key wolf humblebrag. Skateboard polaroid man
braid organic, chambray mustache mixtape freegan humblebrag brunch
ugh. Wayfarers VHS brooklyn, fashion axe green juice next level
kombucha cray shabby chic lo-fi. Lumbersexual pug farm-to-table,
authentic chartreuse street art church-key.
</p>
<p>
3 wolf moon pickled messenger bag knausgaard venmo, retro aliquip
portland asymmetrical cliche non pabst pinterest culpa. Laboris
beard intelligentsia, pickled viral brooklyn YOLO tempor do cliche
fugiat. Messenger bag fanny pack reprehenderit bicycle rights
tilde, tumblr neutra do intelligentsia godard street art. Gentrify
consectetur laboris, pug venmo literally you probably haven't
heard of them actually locavore distillery commodo occupy franzen
umami. Slow-carb bespoke pariatur four dollar toast, selfies tofu
salvia artisan tousled meggings kinfolk chambray marfa direct
trade single-origin coffee. Exercitation fap umami mollit deep v
wolf, sint lomo sunt four dollar toast elit selvage vegan
truffaut. Cillum pickled sartorial flexitarian chartreuse
brooklyn.
</p>
<p>
Artisan helvetica quinoa kogi fingerstache, biodiesel church-key
blue bottle everyday carry schlitz seitan locavore. Retro +1
tilde, normcore post-ironic chillwave PBR&B umami. Mlkshk
mumblecore meh, kitsch pickled wolf helvetica man bun cronut
keffiyeh meggings ramps. Banh mi stumptown cronut wayfarers. Banh
mi venmo street art chicharrones, put a bird on it yuccie cornhole
poutine knausgaard echo park tilde retro. Occupy XOXO etsy meh
pabst blue bottle. Photo booth four loko biodiesel, cornhole
chicharrones echo park actually pork belly gochujang DIY
gluten-free plaid microdosing salvia pinterest.
</p>
<p>
Cred lumbersexual organic, echo park hashtag roof party pinterest
shabby chic green juice salvia scenester hella ramps. Schlitz
knausgaard church-key disrupt, four loko XOXO bicycle rights
post-ironic four dollar toast fixie butcher mustache tousled
humblebrag. Bushwick 8-bit swag, wolf intelligentsia kickstarter
roof party cred meh semiotics flannel. Typewriter umami narwhal
irony, slow-carb VHS street art cold-pressed wayfarers sriracha
everyday carry church-key wolf humblebrag. Skateboard polaroid man
braid organic, chambray mustache mixtape freegan humblebrag brunch
ugh. Wayfarers VHS brooklyn, fashion axe green juice next level
kombucha cray shabby chic lo-fi. Lumbersexual pug farm-to-table,
authentic chartreuse street art church-key.
</p>
<p>
3 wolf moon pickled messenger bag knausgaard venmo, retro aliquip
portland asymmetrical cliche non pabst pinterest culpa. Laboris
beard intelligentsia, pickled viral brooklyn YOLO tempor do cliche
fugiat. Messenger bag fanny pack reprehenderit bicycle rights
tilde, tumblr neutra do intelligentsia godard street art. Gentrify
consectetur laboris, pug venmo literally you probably haven't
heard of them actually locavore distillery commodo occupy franzen
umami. Slow-carb bespoke pariatur four dollar toast, selfies tofu
salvia artisan tousled meggings kinfolk chambray marfa direct
trade single-origin coffee. Exercitation fap umami mollit deep v
wolf, sint lomo sunt four dollar toast elit selvage vegan
truffaut. Cillum pickled sartorial flexitarian chartreuse
brooklyn.
</p>
</Expander>
</div>
);
},
handleExpanded(isExpanded: any) {
this.setState({
isExpanded,
});
},
});
return <Component />;
};
InteractiveWithChangingLabels.storyName = 'InteractiveWithChangingLabels';
/* Interactive Without Changing Labels */
export const InteractiveWithoutChangingLabels = () => {
const Component = createClass({
render() {
return (
<div>
<Expander>
<Expander.Label>Show Stuff</Expander.Label>
<p>
Tacos craft beer humblebrag meditation. Cold-pressed next level
man bun readymade beard, wayfarers fanny pack keytar helvetica
knausgaard biodiesel lumbersexual. Knausgaard echo park whatever
four loko messenger bag hella. Cardigan church-key brooklyn
letterpress artisan venmo, gastropub hella. Single-origin coffee
selfies four loko, biodiesel health goth truffaut migas
sustainable kale chips disrupt locavore meggings mustache actually
retro. Mlkshk poutine flexitarian scenester 3 wolf moon, vice
kinfolk chia blog ennui bitters brooklyn quinoa marfa. Literally
before they sold out gochujang pork belly franzen.
</p>
<p>
Sriracha put a bird on it chia, locavore wolf affogato tote bag
neutra umami food truck austin keytar cronut man bun. Kitsch man
braid occupy art party, tousled waistcoat tilde YOLO keytar street
art selvage. Salvia pour-over keytar intelligentsia. Marfa yr
stumptown, before they sold out lo-fi literally art party
williamsburg blue bottle slow-carb brooklyn. Gochujang post-ironic
aesthetic kickstarter, dreamcatcher four dollar toast whatever
tattooed quinoa. Single-origin coffee blog lomo, freegan next
level ramps small batch put a bird on it listicle stumptown.
Stumptown mumblecore vinyl, mustache street art wayfarers
lumbersexual everyday carry irony pitchfork gochujang pug DIY
gentrify.
</p>
<p>
Kale chips pug jean shorts cardigan, ramps plaid mlkshk photo
booth migas whatever. Ramps affogato bespoke, crucifix ennui PBR&B
asymmetrical meggings kombucha banh mi meh skateboard artisan man
braid. Ugh semiotics intelligentsia sustainable, craft beer next
level meggings before they sold out heirloom iPhone try-hard.
Listicle blog literally marfa plaid brooklyn humblebrag retro, VHS
thundercats man braid waistcoat ennui. Church-key knausgaard
austin organic farm-to-table neutra franzen bespoke, mlkshk
narwhal DIY raw denim retro. Mlkshk locavore try-hard roof party
flexitarian. Letterpress beard fixie, umami waistcoat salvia ennui
four loko seitan lomo franzen pickled shoreditch master cleanse.
</p>
<p>
Tacos craft beer humblebrag meditation. Cold-pressed next level
man bun readymade beard, wayfarers fanny pack keytar helvetica
knausgaard biodiesel lumbersexual. Knausgaard echo park whatever
four loko messenger bag hella. Cardigan church-key brooklyn
letterpress artisan venmo, gastropub hella. Single-origin coffee
selfies four loko, biodiesel health goth truffaut migas
sustainable kale chips disrupt locavore meggings mustache actually
retro. Mlkshk poutine flexitarian scenester 3 wolf moon, vice
kinfolk chia blog ennui bitters brooklyn quinoa marfa. Literally
before they sold out gochujang pork belly franzen.
</p>
<p>
Sriracha put a bird on it chia, locavore wolf affogato tote bag
neutra umami food truck austin keytar cronut man bun. Kitsch man
braid occupy art party, tousled waistcoat tilde YOLO keytar street
art selvage. Salvia pour-over keytar intelligentsia. Marfa yr
stumptown, before they sold out lo-fi literally art party
williamsburg blue bottle slow-carb brooklyn. Gochujang post-ironic
aesthetic kickstarter, dreamcatcher four dollar toast whatever
tattooed quinoa. Single-origin coffee blog lomo, freegan next
level ramps small batch put a bird on it listicle stumptown.
Stumptown mumblecore vinyl, mustache street art wayfarers
lumbersexual everyday carry irony pitchfork gochujang pug DIY
gentrify.
</p>
<p>
Kale chips pug jean shorts cardigan, ramps plaid mlkshk photo
booth migas whatever. Ramps affogato bespoke, crucifix ennui PBR&B
asymmetrical meggings kombucha banh mi meh skateboard artisan man
braid. Ugh semiotics intelligentsia sustainable, craft beer next
level meggings before they sold out heirloom iPhone try-hard.
Listicle blog literally marfa plaid brooklyn humblebrag retro, VHS
thundercats man braid waistcoat ennui. Church-key knausgaard
austin organic farm-to-table neutra franzen bespoke, mlkshk
narwhal DIY raw denim retro. Mlkshk locavore try-hard roof party
flexitarian. Letterpress beard fixie, umami waistcoat salvia ennui
four loko seitan lomo franzen pickled shoreditch master cleanse.
</p>
</Expander>
</div>
);
},
});
return <Component />;
};
InteractiveWithoutChangingLabels.storyName = 'InteractiveWithoutChangingLabels';
/* Interactive With Changing Labels And Additional Label Content */
export const InteractiveWithChangingLabelsAndAdditionalLabelContent = () => {
const Component = createClass({
render() {
return (
<div>
<Expander>
<Expander.Label>Show Stuff</Expander.Label>
<Expander.AdditionalLabelContent>
<Button kind='invisible'>
<EditIcon />
Edit
</Button>
<Button kind='invisible'>
<CloseIcon />
Clear All
</Button>
</Expander.AdditionalLabelContent>
<p>
Tacos craft beer humblebrag meditation. Cold-pressed next level
man bun readymade beard, wayfarers fanny pack keytar helvetica
knausgaard biodiesel lumbersexual. Knausgaard echo park whatever
four loko messenger bag hella. Cardigan church-key brooklyn
letterpress artisan venmo, gastropub hella. Single-origin coffee
selfies four loko, biodiesel health goth truffaut migas
sustainable kale chips disrupt locavore meggings mustache actually
retro. Mlkshk poutine flexitarian scenester 3 wolf moon, vice
kinfolk chia blog ennui bitters brooklyn quinoa marfa. Literally
before they sold out gochujang pork belly franzen.
</p>
<p>
Sriracha put a bird on it chia, locavore wolf affogato tote bag
neutra umami food truck austin keytar cronut man bun. Kitsch man
braid occupy art party, tousled waistcoat tilde YOLO keytar street
art selvage. Salvia pour-over keytar intelligentsia. Marfa yr
stumptown, before they sold out lo-fi literally art party
williamsburg blue bottle slow-carb brooklyn. Gochujang post-ironic
aesthetic kickstarter, dreamcatcher four dollar toast whatever
tattooed quinoa. Single-origin coffee blog lomo, freegan next
level ramps small batch put a bird on it listicle stumptown.
Stumptown mumblecore vinyl, mustache street art wayfarers
lumbersexual everyday carry irony pitchfork gochujang pug DIY
gentrify.
</p>
<p>
Kale chips pug jean shorts cardigan, ramps plaid mlkshk photo
booth migas whatever. Ramps affogato bespoke, crucifix ennui PBR&B
asymmetrical meggings kombucha banh mi meh skateboard artisan man
braid. Ugh semiotics intelligentsia sustainable, craft beer next
level meggings before they sold out heirloom iPhone try-hard.
Listicle blog literally marfa plaid brooklyn humblebrag retro, VHS
thundercats man braid waistcoat ennui. Church-key knausgaard
austin organic farm-to-table neutra franzen bespoke, mlkshk
narwhal DIY raw denim retro. Mlkshk locavore try-hard roof party
flexitarian. Letterpress beard fixie, umami waistcoat salvia ennui
four loko seitan lomo franzen pickled shoreditch master cleanse.
</p>
<p>
Tacos craft beer humblebrag meditation. Cold-pressed next level
man bun readymade beard, wayfarers fanny pack keytar helvetica
knausgaard biodiesel lumbersexual. Knausgaard echo park whatever
four loko messenger bag hella. Cardigan church-key brooklyn
letterpress artisan venmo, gastropub hella. Single-origin coffee
selfies four loko, biodiesel health goth truffaut migas
sustainable kale chips disrupt locavore meggings mustache actually
retro. Mlkshk poutine flexitarian scenester 3 wolf moon, vice
kinfolk chia blog ennui bitters brooklyn quinoa marfa. Literally
before they sold out gochujang pork belly franzen.
</p>
<p>
Sriracha put a bird on it chia, locavore wolf affogato tote bag
neutra umami food truck austin keytar cronut man bun. Kitsch man
braid occupy art party, tousled waistcoat tilde YOLO keytar street
art selvage. Salvia pour-over keytar intelligentsia. Marfa yr
stumptown, before they sold out lo-fi literally art party
williamsburg blue bottle slow-carb brooklyn. Gochujang post-ironic
aesthetic kickstarter, dreamcatcher four dollar toast whatever
tattooed quinoa. Single-origin coffee blog lomo, freegan next
level ramps small batch put a bird on it listicle stumptown.
Stumptown mumblecore vinyl, mustache street art wayfarers
lumbersexual everyday carry irony pitchfork gochujang pug DIY
gentrify.
</p>
<p>
Kale chips pug jean shorts cardigan, ramps plaid mlkshk photo
booth migas whatever. Ramps affogato bespoke, crucifix ennui PBR&B
asymmetrical meggings kombucha banh mi meh skateboard artisan man
braid. Ugh semiotics intelligentsia sustainable, craft beer next
level meggings before they sold out heirloom iPhone try-hard.
Listicle blog literally marfa plaid brooklyn humblebrag retro, VHS
thundercats man braid waistcoat ennui. Church-key knausgaard
austin organic farm-to-table neutra franzen bespoke, mlkshk
narwhal DIY raw denim retro. Mlkshk locavore try-hard roof party
flexitarian. Letterpress beard fixie, umami waistcoat salvia ennui
four loko seitan lomo franzen pickled shoreditch master cleanse.
</p>
</Expander>
</div>
);
},
});
return <Component />;
};
InteractiveWithChangingLabelsAndAdditionalLabelContent.storyName =
'InteractiveWithChangingLabelsAndAdditionalLabelContent';
/* Highlighted */
export const Highlighted = () => {
const Component = createClass({
render() {
return (
<div>
<Expander kind='highlighted'>
<Expander.Label>Show Less</Expander.Label>
<p>
You can't get rid of me. Keep clicking that icon as much as you
want, but I'm here to stay!
</p>
</Expander>
</div>
);
},
});
return <Component />;
};
Highlighted.storyName = 'Highlighted'; | the_stack |
import {
ATTRIBUTE_TYPE,
RangeOperator,
ScalarType,
SimpleOperator,
UpdateType,
} from '@typedorm/common';
import {isEmptyObject} from '../../helpers/is-empty-object';
import {KeyCondition} from './key-condition';
import {Filter} from './filter';
import {BaseExpressionInput, MERGE_STRATEGY} from './base-expression-input';
import {isScalarType} from '../../helpers/is-scalar-type';
import {FilterOptions} from './filter-options-type';
import {ConditionOptions} from './condition-options-type';
import {Condition} from './condition';
import {Projection} from './projection';
import {KeyConditionOptions} from './key-condition-options-type';
import {ProjectionKeys} from './projection-keys-options-type';
import {isSetOperatorComplexValueType, UpdateBody} from './update-body-type';
import {SetUpdate} from './update/set-update';
import {AddUpdate} from './update/add-update';
import {Update} from './update/update';
import {DeleteUpdate} from './update/delete-update';
import {RemoveUpdate} from './update/remove-update';
import {isObject} from '../../helpers/is-object';
import {nestedKeyAccessRegex} from '../../helpers/constants';
/**
* Parses expression input to expression instances
*/
export class ExpressionInputParser {
parseToKeyCondition(key: string, options: KeyConditionOptions) {
return this.operatorToBaseExpression(key, options, new KeyCondition());
}
parseToFilter<Entity, PrimaryKey>(
options: FilterOptions<Entity, PrimaryKey>
) {
return this.recursiveParseToBaseExpression(options, Filter).pop();
}
parseToCondition<Entity>(options: ConditionOptions<Entity>) {
return this.recursiveParseToBaseExpression(options, Condition).pop();
}
parseToProjection<Entity>(keys: ProjectionKeys<Entity>) {
const projection = new Projection();
projection.addProjectionAttributes(keys as string[]);
return projection;
}
parseToUpdate<Entity, AdditionalProperties = {}>(
body: UpdateBody<Entity, AdditionalProperties>,
attrValueOverrideMap: Record<string, any> = {}
) {
return this.parseToUpdateExpression(body, attrValueOverrideMap);
}
/**
* Parses complex update object to a value and type
*/
parseAttributeToUpdateValue(
attr: string,
value: any
): {value: any; type: 'static' | 'dynamic'} {
if (isObject(value) && !isEmptyObject(value)) {
const [operator, operatorValue] = Object.entries(value as any)[0];
const parsedUpdate = this.parseValueToUpdateExp(
attr,
value,
operator as any,
operatorValue
);
const parsedValue = Object.values(parsedUpdate.values ?? {})[0];
// if expression contains any dynamic operation such as value manipulation or nested attribute manipulation in a list
if (
!(parsedUpdate instanceof SetUpdate) ||
parsedUpdate.expression.includes(' + ') ||
parsedUpdate.expression.includes(' - ') ||
nestedKeyAccessRegex.test(parsedUpdate.expression)
) {
return {
value: parsedValue,
type: 'dynamic',
};
}
// return static value
return {
type: 'static',
value: parsedValue,
};
} else {
// if tried to update nested value for key, it is considered dynamic, as we do not know full value of updating attribute
if (nestedKeyAccessRegex.test(attr)) {
return {
type: 'dynamic',
value,
};
}
// return value as a default value
return {type: 'static', value};
}
}
/**
* Generic Recursive input parser
* Recursively parses nested object to build expression of type ExpClass
* @param options Complex options object to parse
* @param ExpClass Type of expression to build, can be of type Filter, Condition etc.
*
*/
private recursiveParseToBaseExpression<T extends BaseExpressionInput>(
options: any,
ExpClass: new () => T
) {
return Object.entries(options).map(
([operatorOrAttr, value]): T => {
// if top level key is one of the logical operators, rerun parse with it's values
if (['AND', 'OR', 'NOT'].includes(operatorOrAttr)) {
const parsedExpList = this.recursiveParseToBaseExpression<T>(
value,
ExpClass
);
const base = parsedExpList.shift();
if (!base) {
throw new Error(
`Value for operator "${operatorOrAttr}" can not be empty`
);
}
switch (operatorOrAttr) {
case 'AND': {
if (!parsedExpList?.length) {
throw new Error(
`Value for operator "${operatorOrAttr}" must contain more that 1 attributes.`
);
}
return base.mergeMany(parsedExpList as T[], MERGE_STRATEGY.AND);
}
case 'OR': {
if (!parsedExpList?.length) {
throw new Error(
`Value for operator "${operatorOrAttr}" must contain more that 1 attributes.`
);
}
return base.mergeMany(parsedExpList as T[], MERGE_STRATEGY.OR);
}
case 'NOT': {
if (parsedExpList?.length) {
throw new Error(
`Value for operator "${operatorOrAttr}" can not contain more than 1 attributes.`
);
}
return base.not();
}
default: {
throw new Error(
`Unsupported logical operator "${operatorOrAttr}"`
);
}
}
} else {
// when top level attribute is something other than actual logical operators, try to parse it to expression
return this.operatorToBaseExpression(
operatorOrAttr,
value,
new ExpClass()
);
}
}
);
}
/**
* Parses input to update expression
* @param body body to parse
*/
private parseToUpdateExpression(
body: any,
attrValueOverrideMap: Record<string, any>
) {
return (
Object.entries(body)
.map(([attr, value]) => {
if (isObject(value) && !isEmptyObject(value)) {
const [operator, operatorValue] = Object.entries(
value as any
)[0] as [
(
| UpdateType.ArithmeticOperator
| UpdateType.SetUpdateOperator
| UpdateType.Action
),
any
];
return this.parseValueToUpdateExp(
attr,
value,
operator,
operatorValue,
attrValueOverrideMap[attr] // get any override value if exists
);
} else {
// fallback to default `SET` action based update
return new SetUpdate().setTo(
attr,
attrValueOverrideMap[attr] || value
);
}
})
// merge all expressions with matching action
.reduce(
(acc, currExp) => {
acc
.find(instance => instance.constructor === currExp.constructor)!
.merge(currExp);
return acc;
},
[
new SetUpdate(),
new AddUpdate(),
new RemoveUpdate(),
new DeleteUpdate(),
]
)
// merge all expressions of different actions
.reduce((acc, curr) => {
acc.merge(curr);
return acc;
}, new Update())
);
}
/**
* Parses single attribute into update expression instance
* @param attribute name/path of the attribute
* @param attributeValue value to update
*/
private parseValueToUpdateExp(
attribute: string,
attributeValue: any, // attribute value to set
operator:
| UpdateType.ArithmeticOperator
| UpdateType.SetUpdateOperator
| UpdateType.Action,
operatorValue: any,
staticValueToOverride?: any // value to override for attribute, this is set in cases where there was a custom property transform was requested
): Update {
switch (operator) {
case 'INCREMENT_BY':
case 'DECREMENT_BY': {
return new SetUpdate().setTo(attribute, operatorValue, operator);
}
case 'IF_NOT_EXISTS': {
if (isSetOperatorComplexValueType(operatorValue)) {
return new SetUpdate().setToIfNotExists(
attribute,
staticValueToOverride || operatorValue.$VALUE,
operatorValue.$PATH
);
} else {
return new SetUpdate().setToIfNotExists(attribute, operatorValue);
}
}
case 'LIST_APPEND': {
if (isSetOperatorComplexValueType(operatorValue)) {
return new SetUpdate().setOrAppendToList(
attribute,
operatorValue.$VALUE,
operatorValue.$PATH
);
} else {
return new SetUpdate().setOrAppendToList(attribute, operatorValue);
}
}
case 'SET': {
/**
* aliased set support, this allows access patterns like
* {id: { SET: '1'}}
* behaves similar to {id: '1'}
*/
// handle explicit set exp
if (isObject(operatorValue) && !isEmptyObject(operatorValue)) {
const [nestedOperator, nestedOperatorValue] = Object.entries(
operatorValue
)[0] as [
UpdateType.ArithmeticOperator | UpdateType.SetUpdateOperator,
any
];
return this.parseValueToUpdateExp(
attribute,
nestedOperatorValue,
nestedOperator,
nestedOperatorValue,
staticValueToOverride
);
} else {
// handle attribute with map type
return new SetUpdate().setTo(
attribute,
staticValueToOverride || operatorValue
);
}
}
case 'ADD': {
if (isEmptyObject(operatorValue)) {
throw new Error(
`Invalid value ${operatorValue} received for action "ADD", Only numbers and lists are supported.`
);
}
return new AddUpdate().addTo(attribute, operatorValue);
}
case 'DELETE': {
return new DeleteUpdate().delete(attribute, operatorValue);
}
case 'REMOVE': {
if (typeof operatorValue === 'boolean' && !!operatorValue) {
return new RemoveUpdate().remove(attribute);
} else if (
!isEmptyObject(operatorValue) &&
Array.isArray(operatorValue.$AT_INDEX)
) {
return new RemoveUpdate().remove(attribute, {
atIndexes: operatorValue.$AT_INDEX,
});
} else {
throw new Error(
`Invalid value ${operatorValue} received for action "REMOVE". Value must be set to boolean
In addition, You may use special value type {$AT_INDEX: Array<number>} for attribute of type list..`
);
}
}
default: {
// handle attribute with map type
return new SetUpdate().setTo(
attribute,
staticValueToOverride || attributeValue
);
}
}
}
/**
* When this is run, it is assumed that attribute/value are validated to not have any nested objects,
* therefor this function will not running in any recursion itself
* @param attribute Attribute or path on entity to build comparison condition for
* @param value value to expect
* @param exp expression to append operators to
*/
private operatorToBaseExpression<T extends BaseExpressionInput>(
attribute: any,
value: any,
exp: T
) {
switch (typeof value) {
case 'string': {
if (value === 'ATTRIBUTE_EXISTS') {
exp.attributeExists(attribute);
return exp;
} else if (value === 'ATTRIBUTE_NOT_EXISTS') {
exp.attributeNotExists(attribute);
return exp;
} else {
throw new Error(
`Operator used must be one of "ATTRIBUTE_EXISTS", "ATTRIBUTE_NOT_EXISTS" for
attribute "${attribute}".`
);
}
}
case 'object': {
if (isEmptyObject(value)) {
throw new Error(
`Value for attribute "${attribute}" can not be empty`
);
}
const operatorAndValue = Object.entries(value);
if (operatorAndValue.length !== 1) {
throw new Error(
`Invalid value "${JSON.stringify(
value
)}" found for attribute: ${attribute}`
);
}
const [innerOp, innerVal] = operatorAndValue[0] as [any, ScalarType];
if (isScalarType(innerVal)) {
return this.parseScalarValueToExp(innerOp, attribute, innerVal, exp);
} else {
return this.parseNonScalarValueToExp(
innerOp,
attribute,
innerVal,
exp
);
}
}
default: {
throw new Error(
`Value for attribute "${attribute}" must be of type object or string`
);
}
}
}
/**
* Builds comparison expression for operators with scalar values
* @param operator operator that supports scalar values
* @param attrPath attribute path to include in built expression
* @param value value to expect in expression
* @param exp expression type
*/
private parseScalarValueToExp<T extends BaseExpressionInput>(
operator: SimpleOperator | 'BEGINS_WITH' | 'CONTAINS' | 'ATTRIBUTE_TYPE',
attrPath: string,
value: ScalarType,
exp: T
) {
switch (operator) {
case 'EQ': {
exp.equals(attrPath, value);
return exp;
}
case 'LT': {
exp.lessThan(attrPath, value);
return exp;
}
case 'LE': {
exp.lessThanAndEqualTo(attrPath, value);
return exp;
}
case 'GT': {
exp.greaterThan(attrPath, value);
return exp;
}
case 'GE': {
exp.greaterThanAndEqualTo(attrPath, value);
return exp;
}
case 'NE': {
exp.notEquals(attrPath, value);
return exp;
}
case 'BEGINS_WITH': {
exp.beginsWith(attrPath, value);
return exp;
}
case 'CONTAINS': {
exp.contains(attrPath, value);
return exp;
}
case 'ATTRIBUTE_TYPE': {
exp.attributeType(attrPath, value as ATTRIBUTE_TYPE);
return exp;
}
default: {
throw new Error(`Unsupported operator: ${operator}`);
}
}
}
/**
* Builds comparison expression for operators with Non scalar values, i.e ranges and size
* @param operator operator that supports scalar values
* @param attrPath attribute path to include in built expression
* @param value value to expect in expression
* @param exp expression type
*/
private parseNonScalarValueToExp<T extends BaseExpressionInput>(
operator: RangeOperator | 'SIZE',
attrPath: string,
value: any,
exp: T
) {
switch (operator) {
case 'BETWEEN': {
if (!Array.isArray(value) || value.length !== 2) {
throw new Error(
`Value for operator ${operator} must be of type array with exact two items.`
);
}
exp.between(attrPath, value as [ScalarType, ScalarType]);
return exp;
}
case 'IN': {
if (!Array.isArray(value) || value.length < 1) {
throw new Error(
`Value for operator ${operator} must be of type array with at least one item.`
);
}
exp.in(attrPath, value as ScalarType[]);
return exp;
}
case 'SIZE': {
const operatorAndValue = Object.entries(value);
if (operatorAndValue.length !== 1) {
throw new Error(
`Invalid value "${JSON.stringify(
value
)}" found for operator: ${operator}`
);
}
const [innerOp, innerVal] = operatorAndValue[0] as [any, ScalarType];
const parsedExp = this.parseScalarValueToExp(
innerOp,
attrPath,
innerVal,
exp
);
// once operator condition has applied, pass it through size
parsedExp.size(attrPath);
return parsedExp;
}
default: {
throw new Error(`Unsupported operator: ${operator}`);
}
}
}
} | the_stack |
import LayerBase from "ol/layer/Base";
import { LayerProperty, IExternalBaseLayer, LayerTransparencySet, RefreshMode, Bounds, Size, ILayerInfo, Dictionary } from './common';
import { ILayerSetOL, IImageLayerEvents } from './layer-set-contracts';
import Feature from 'ol/Feature';
import { isMapGuideImageSource } from './ol-mapguide-source-factory';
import { getLayerInfo } from './layer-manager';
import { MgError } from './error';
import { tr } from './i18n';
import { setOLVectorLayerStyle } from './ol-style-helpers';
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Source from 'ol/source/Source';
import ImageSource from 'ol/source/Image';
import ImageWMSSource from "ol/source/ImageWMS";
import TileWMSSource from "ol/source/TileWMS";
import TileImageSource from "ol/source/TileImage";
import Map from "ol/Map";
import OverviewMap from "ol/control/OverviewMap"
import View from 'ol/View';
import { IInitialExternalLayer } from '../actions/defs';
import { createOLLayerFromSubjectDefn } from '../components/external-layer-factory';
import Geometry from 'ol/geom/Geometry';
import TileLayer from 'ol/layer/Tile';
import UrlTile from 'ol/source/UrlTile';
import ImageLayer from 'ol/layer/Image';
import { debug } from '../utils/logger';
import { OLVectorLayer } from "./ol-types";
import Fill from "ol/style/Fill";
import Stroke from "ol/style/Stroke";
import Style from "ol/style/Style";
import Text from "ol/style/Text";
import Heatmap from "ol/layer/Heatmap";
const HIGHLIGHT_STYLE = new Style({
stroke: new Stroke({
color: '#f00',
width: 3,
}),
fill: new Fill({
color: 'rgba(255,0,0,0.1)',
}),
text: new Text({
font: '12px Calibri,sans-serif',
fill: new Fill({
color: '#000',
}),
stroke: new Stroke({
color: '#f00',
width: 3,
}),
}),
});
export abstract class LayerSetGroupBase {
protected mainSet: ILayerSetOL;
protected overviewSet: ILayerSetOL;
protected wmsSelOverlayLayer: OLVectorLayer;
protected scratchLayer: OLVectorLayer;
protected hoverHighlightLayer: OLVectorLayer;
protected _customLayers: {
[name: string]: {
layer: LayerBase,
order: number
}
};
constructor(protected callback: IImageLayerEvents) {
this._customLayers = {};
this.scratchLayer = new VectorLayer({
source: new VectorSource()
});
this.scratchLayer.set(LayerProperty.LAYER_NAME, "__SCRATCH__"); //NOXLATE
this.scratchLayer.set(LayerProperty.IS_SCRATCH, true);
this.wmsSelOverlayLayer = new VectorLayer({
source: new VectorSource()
});
this.wmsSelOverlayLayer.set(LayerProperty.LAYER_NAME, "__WMS_SELECTION_OVERLAY__");
this.wmsSelOverlayLayer.set(LayerProperty.IS_WMS_SELECTION_OVERLAY, true);
this.hoverHighlightLayer = new VectorLayer({
source: new VectorSource(),
style: feature => {
return HIGHLIGHT_STYLE
}
});
this.hoverHighlightLayer.set(LayerProperty.LAYER_NAME, "__HOVER_HIGHLIGHT__"); //NOXLATE
this.hoverHighlightLayer.set(LayerProperty.IS_HOVER_HIGHLIGHT, true)
}
addHighlightedFeature(feature: Feature<Geometry>) {
this.hoverHighlightLayer.getSource().addFeature(feature);
}
removeHighlightedFeature(feature: Feature<Geometry>) {
const hs = this.hoverHighlightLayer.getSource();
if (hs.hasFeature(feature)) {
hs.removeFeature(feature);
}
}
clearHighlightedFeatures() {
this.hoverHighlightLayer.getSource().clear();
}
/**
* @virtual
* @returns {(LayerBase | undefined)}
* @memberof LayerSetGroupBase
*/
public tryGetSubjectLayer(): LayerBase | undefined { return undefined; }
public addWmsSelectionOverlay(feat: Feature<Geometry>) {
this.wmsSelOverlayLayer.getSource().addFeature(feat);
}
public clearWmsSelectionOverlay() {
this.wmsSelOverlayLayer.getSource().clear();
}
public addScratchFeature(feat: Feature<Geometry>) {
this.scratchLayer.getSource().addFeature(feat);
}
public clearScratchLayer() {
this.scratchLayer.getSource().clear();
}
public abstract tryGetWmsSource(): [LayerBase, (ImageWMSSource | TileWMSSource)] | undefined;
protected registerSourceEvents(source: Source): void {
if (source instanceof ImageSource) {
source.on("imageloadstart", this.callback.addImageLoading);
//onImageError is a MapGuide-specific callback
if (isMapGuideImageSource(source)) {
source.on("imageloaderror", this.callback.onImageError);
}
source.on("imageloaderror", this.callback.addImageLoaded);
source.on("imageloadend", this.callback.addImageLoaded);
} else if (source instanceof TileImageSource) {
source.on("tileloadstart", this.callback.addImageLoading);
source.on("tileloaderror", this.callback.addImageLoaded);
source.on("tileloadend", this.callback.addImageLoaded);
}
}
public updateExternalBaseLayers(externalBaseLayers: IExternalBaseLayer[]) {
this.mainSet.updateExternalBaseLayers(externalBaseLayers);
this.overviewSet.updateExternalBaseLayers(externalBaseLayers);
}
public updateTransparency = (trans: LayerTransparencySet) => this.mainSet.updateTransparency(trans);
public fitViewToExtent = () => this.mainSet.view.fit(this.mainSet.extent);
public getView = () => this.mainSet.view;
public getDpi = () => this.mainSet.dpi;
public getExtent = () => this.mainSet.extent;
public getLayersForOverviewMap = () => this.overviewSet.getLayers();
public getProjection = () => this.mainSet.projection;
public refreshMap = (mode: RefreshMode) => this.mainSet.refreshMap(mode);
public showActiveSelectedFeature = (mapExtent: Bounds, size: Size, uri: string) => this.mainSet.showActiveSelectedFeature(mapExtent, size, uri);
public getMetersPerUnit = () => this.mainSet.getMetersPerUnit();
public scaleToResolution = (scale: number) => this.mainSet.scaleToResolution(scale);
public resolutionToScale = (resolution: number) => this.mainSet.resolutionToScale(resolution);
public attach(map: Map, ovMapControl: OverviewMap, bSetLayers = true): void {
// To guard against the possibility that we may be attaching layers to a map that
// already has layers (eg. Measurements), we reverse iterate all the layers we need to
// add and insert them to the front one-by-one, ensuring all the layers we add will be
// at the bottom of the draw order
const layers = map.getLayers();
// Attach hover layers
layers.insertAt(0, this.hoverHighlightLayer);
// Attach scratch layer
layers.insertAt(0, this.scratchLayer);
// Attach custom layers
const customLayers = Object.keys(this._customLayers).map(k => this._customLayers[k]);
customLayers.sort((a, b) => {
return a.order - b.order;
});
// External layers may have been pre-loaded, to clear out any existing external layers
for (const item of customLayers) {
layers.remove(item.layer);
}
for (const item of customLayers) {
layers.insertAt(0, item.layer);
}
// Then the regular layers
const allLayers = this.mainSet.getLayers();
for (let i = allLayers.length - 1; i >= 0; i--) {
layers.insertAt(0, allLayers[i]);
}
map.setView(this.mainSet.view);
if (bSetLayers) {
const ovMap = ovMapControl.getOverviewMap();
const ovLayers = this.getLayersForOverviewMap();
for (const layer of ovLayers) {
ovMap.addLayer(layer);
}
//ol.View has immutable projection, so we have to replace the whole view on the OverviewMap
const center = this.mainSet.view.getCenter();
if (center) {
ovMap.setView(new View({
center: [center[0], center[1]],
resolution: this.mainSet.view.getResolution(),
projection: this.mainSet.view.getProjection()
}));
} else {
const view = new View({
projection: this.mainSet.view.getProjection()
});
ovMap.setView(view);
view.fit(this.mainSet.extent, { size: ovMap.getSize() });
}
}
}
public detach(map: Map, ovMapControl: OverviewMap): void {
const allLayers = this.mainSet.getLayers();
for (const layer of allLayers) {
map.removeLayer(layer);
}
//Detach custom layers
for (const layerName in this._customLayers) {
map.removeLayer(this._customLayers[layerName].layer);
}
//Detach scratch layer
map.removeLayer(this.scratchLayer);
//Detach hover highlight layer
map.removeLayer(this.hoverHighlightLayer);
const ovLayers = this.getLayersForOverviewMap();
const ovMap = ovMapControl.getOverviewMap();
for (const layer of ovLayers) {
ovMap.removeLayer(layer);
}
}
public getCustomLayers(map: Map): ILayerInfo[] {
const larr = map.getLayers().getArray();
const layers = larr
.filter(l => this._customLayers[l.get(LayerProperty.LAYER_NAME)] != null)
.map(l => ({
...getLayerInfo(l, true),
//Smuggle these values out for debugging purposes
isSelectable: this._customLayers[l.get(LayerProperty.LAYER_NAME)].layer.get(LayerProperty.IS_SELECTABLE) == true,
order: this._customLayers[l.get(LayerProperty.LAYER_NAME)].order
}));
return layers.reverse();
}
public hasLayer(name: string): boolean {
return this._customLayers[name] != null;
}
public addExternalLayer(map: Map, extLayer: IInitialExternalLayer, appSettings: Dictionary<string>): ILayerInfo {
const layer = createOLLayerFromSubjectDefn(extLayer, map.getView().getProjection(), true, appSettings);
return this.addLayer(map, extLayer.name, layer);
}
public addLayer<T extends LayerBase>(map: Map, name: string, layer: T, allowReplace?: boolean): ILayerInfo {
const bAllow = !!allowReplace;
if (this._customLayers[name]) {
if (!bAllow) {
throw new MgError(tr("LAYER_NAME_EXISTS", this.callback.getLocale(), { name: name }));
} else {
//Remove the layer that is about to be replaced first
map.removeLayer(this._customLayers[name].layer);
}
}
//These layer properties may have already been set, so only set if not set already (display name) or it is different (layer name)
if (layer.get(LayerProperty.LAYER_NAME) != name)
layer.set(LayerProperty.LAYER_NAME, name);
if (!layer.get(LayerProperty.LAYER_DISPLAY_NAME))
layer.set(LayerProperty.LAYER_DISPLAY_NAME, name);
//console.log(`addLayer(): ${layer.get(LayerProperty.LAYER_NAME)}`);
//HACK: For reasons unknown, measurement layers aren't being cleanly detached/attached during apply() so there is a possibility
//we are re-adding this measurement layer (from measure context activation), and the layer is already there!
//
//So as a nuclear solution, remove the layer we're about to add (as un-intutitive as that sounds!)
map.removeLayer(layer);
map.addLayer(layer);
this._customLayers[name] = { layer, order: map.getLayers().getArray().indexOf(layer) };
const tileLoaders = this.callback.getTileLoaders();
for (const k in tileLoaders) {
const func = tileLoaders[k];
const layer = this.getLayer(k);
if (layer) {
if (layer instanceof TileLayer) {
const source = layer.getSource();
if (source instanceof UrlTile) {
source.setTileLoadFunction(func);
debug(`Added custom tile loader for layer: ${k}`);
}/* else {
warn(`Layer has a source is not a valid candidate for adding a custom tile loader: ${k}`);
}*/
}/* else {
warn(`Layer is not a valid candidate for adding a custom tile loader: ${k}`);
}*/
}
}
const imageLoaders = this.callback.getImageLoaders();
for (const k in imageLoaders) {
const func = imageLoaders[k];
const layer = this.getLayer(k);
if (layer) {
if (layer instanceof ImageLayer) {
const source: any = layer.getSource();
if (typeof (source.setImageLoadFunction) == 'function') {
source.setImageLoadFunction(func);
debug(`Added custom tile loader for layer: ${k}`);
}/* else {
warn(`Layer has a source is not a valid candidate for adding a custom tile loader: ${k}`);
}*/
}/* else {
warn(`Layer is not a valid candidate for adding a custom tile loader: ${k}`);
}*/
}
}
return {
...getLayerInfo(layer, true),
//Smuggle these values out for debugging purposes
...{
isSelectable: this._customLayers[name].layer.get(LayerProperty.IS_SELECTABLE) == true,
order: this._customLayers[name].order
}
};
}
public removeLayer(map: Map, name: string): LayerBase | undefined {
let layer: LayerBase;
if (this._customLayers[name]) {
layer = this._customLayers[name].layer;
//console.log(`removeLayer(): ${layer.get(LayerProperty.LAYER_NAME)}`);
map.removeLayer(layer);
delete this._customLayers[name];
return layer;
}
}
public getLayer<T extends LayerBase>(name: string): T | undefined {
let layer: T | undefined;
if (this._customLayers[name]) {
layer = this._customLayers[name]?.layer as T;
}
return layer;
}
public apply(map: Map, layers: ILayerInfo[]): void {
const layersByName = layers.reduce((current, layer) => {
current[layer.name] = layer;
return current;
}, {} as any);
//Apply opacity/visibility/styling and other top-level properties
for (const layer of layers) {
const oll = this._customLayers[layer.name]?.layer;
if (oll) {
oll.setVisible(layer.visible);
oll.setOpacity(layer.opacity);
oll.set(LayerProperty.BUSY_WORKER_COUNT, layer.busyWorkerCount);
if (oll instanceof VectorLayer && layer.vectorStyle) {
setOLVectorLayerStyle(oll, layer.vectorStyle, layer.cluster);
}
if (layer.heatmap) {
if (oll instanceof Heatmap) {
oll.setBlur(layer.heatmap.blur);
oll.setRadius(layer.heatmap.radius);
}
}
}
}
//Measurement layer is hidden and is not tracked by the layer manager (in terms of round-tripped layer information)
//so if it is present in our custom layers set, it may be removed. So if we find it, capture it for restoration
let theMeasureLayer: LayerBase | undefined;
//Apply removals
for (const layerName in this._customLayers) {
if (!layersByName[layerName]) {
const removed = this.removeLayer(map, layerName);
if (removed?.get(LayerProperty.IS_MEASURE) === true) {
//console.log(`Removed measurement layer: ${removed.get(LayerProperty.LAYER_NAME)}`);
theMeasureLayer = removed;
}
}
}
//Fix order if required
//First item, top-most
//Last item, bottom-most
const cCurrentLayers = map.getLayers();
const aCurrentLayers = cCurrentLayers.getArray();
const currentLayers = aCurrentLayers.map(l => ({
name: l.get(LayerProperty.LAYER_NAME),
type: l.get(LayerProperty.LAYER_TYPE),
isExternal: l.get(LayerProperty.IS_EXTERNAL),
isGroup: l.get(LayerProperty.IS_GROUP),
layer: l
})).filter(l => l.isExternal == true);
//console.assert(currentLayers.length == layers.length);
//console.table(currentLayers);
//console.table(layers);
//If sizes don't match, do a full invalidation
if (currentLayers.length != layers.length) {
//Clear everything custom
for (const toRemove of currentLayers) {
map.removeLayer(toRemove.layer);
}
for (const rn in this._customLayers) {
const toRemove = this._customLayers[rn];
map.removeLayer(toRemove.layer);
}
//Re-add in order according to layers array
for (let i = layers.length - 1; i >= 0; i--) {
const item = this._customLayers[layers[i].name];
if (item) {
map.addLayer(item.layer);
item.order = cCurrentLayers.getArray().indexOf(item.layer);
}
}
} else { //Otherwise see if we need to re-order
let bReorder = false;
let ii = 0;
for (let i = layers.length - 1; i >= 0; i--) {
const layer = layers[i];
//console.log(`Checking if layer (${layer.name}) needs re-ordering`);
if (layer.name != currentLayers[ii].name) {
bReorder = true;
break;
}
ii++;
}
if (bReorder) {
//console.log("Re-ordering layers");
for (const toRemove of currentLayers) {
map.removeLayer(toRemove.layer);
}
//Re-add in order according to layers array
for (let i = layers.length - 1; i >= 0; i--) {
const toAdd = currentLayers.filter(l => l.name == layers[i].name)[0];
map.addLayer(toAdd.layer);
const item = this._customLayers[layers[i].name];
if (item) {
item.order = cCurrentLayers.getArray().indexOf(toAdd.layer);
}
}
}
}
// The scratch layer (where client-side selection overlays and other temp vector features reside) must always be topmost
if (cCurrentLayers.item(cCurrentLayers.getLength() - 1) != this.scratchLayer) {
map.removeLayer(this.scratchLayer);
map.addLayer(this.scratchLayer);
//const layers2 = cCurrentLayers.getArray();
//console.log(layers2);
}
// And the wms selection overlay layer
if (cCurrentLayers.item(cCurrentLayers.getLength() - 1) != this.wmsSelOverlayLayer) {
map.removeLayer(this.wmsSelOverlayLayer);
map.addLayer(this.wmsSelOverlayLayer);
//const layers2 = cCurrentLayers.getArray();
//console.log(layers2);
}
// And the hover highlight layer on top of that
if (cCurrentLayers.item(cCurrentLayers.getLength() - 1) != this.hoverHighlightLayer) {
map.removeLayer(this.hoverHighlightLayer);
map.addLayer(this.hoverHighlightLayer);
//const layers2 = cCurrentLayers.getArray();
//console.log(layers2);
}
// And then the measurement layer, if present
if (theMeasureLayer) {
if (cCurrentLayers.item(cCurrentLayers.getLength() - 1) != theMeasureLayer) {
map.removeLayer(theMeasureLayer);
map.addLayer(theMeasureLayer);
//console.log(`Re-adding measurement layer: ${theMeasureLayer.get(LayerProperty.LAYER_NAME)}`);
}
}
}
} | the_stack |
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzfu {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzfu>;
public static VERSION: string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzfw extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzfw>;
public constructor();
}
export module zzfw {
export class zza extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzfw.zza>;
public getReason(): string;
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzfx {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzfx>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzfy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzfy>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzfz {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzfz>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzfz.zza*/);
}
export module zzfz {
export class zza {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzfz.zza>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzhd*/, param1: string, param2: string, param3: any /* com.google.android.gms.internal.firebase_ml.zzji*/, param4: any /* com.google.android.gms.internal.firebase_ml.zzgw*/);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzga {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzga>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgb<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zziy*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgb<any>>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzfz*/, param1: string, param2: string, param3: any /* com.google.android.gms.internal.firebase_ml.zzgp*/, param4: java.lang.Class<any>);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgc extends com.google.android.gms.internal.firebase_ml.zzgf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgc>;
public constructor();
public constructor(param0: string);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgd>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzge extends com.google.android.gms.internal.firebase_ml.zzfz {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzge>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzgh*/);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzfz.zza*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgf>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzgf interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: any /* com.google.android.gms.internal.firebase_ml.zzgb<any>*/): void;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgg<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzgb<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgg<any>>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzfz*/, param1: string, param2: string, param3: any /* com.google.android.gms.internal.firebase_ml.zzgp*/, param4: java.lang.Class<any>);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzge*/, param1: string, param2: string, param3: any, param4: java.lang.Class<any>);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgh extends com.google.android.gms.internal.firebase_ml.zzfz.zza {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgh>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzhd*/, param1: string, param2: string, param3: any /* com.google.android.gms.internal.firebase_ml.zzji*/, param4: any /* com.google.android.gms.internal.firebase_ml.zzgw*/);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzhd*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzht*/, param2: string, param3: string, param4: any /* com.google.android.gms.internal.firebase_ml.zzgw*/, param5: boolean);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzgj extends com.google.android.gms.internal.firebase_ml.zzgc {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzgj>;
public constructor();
public constructor(param0: string);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhi {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhi>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzhi interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: java.net.URL): java.net.HttpURLConnection;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhk {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhk>;
public addHeader(param0: string, param1: string): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhl extends com.google.android.gms.internal.firebase_ml.zzhi {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhl>;
public constructor();
public constructor(param0: java.net.Proxy);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhm {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhm>;
public skip(param0: number): number;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzhn*/, param1: java.io.InputStream);
public read(): number;
public read(param0: native.Array<number>, param1: number, param2: number): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhn {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhn>;
public getStatusCode(): number;
public getContent(): java.io.InputStream;
public disconnect(): void;
public getContentEncoding(): string;
public getContentType(): string;
public getContentLength(): number;
public getReasonPhrase(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzho {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzho>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzht*/, param1: any);
public writeTo(param0: java.io.OutputStream): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhp>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhq>;
public constructor();
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhr {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhr>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzhs {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhs>;
public constructor();
public writeBoolean(param0: boolean): void;
public flush(): void;
public writeString(param0: string): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzht {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzht>;
public constructor();
public toString(param0: any): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhu {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhu>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzht*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhv {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhv>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzhu*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhw {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhw>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzhx {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhx>;
public constructor();
public close(): void;
public getText(): string;
public getIntValue(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhy>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzhy interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzhp(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzhy.zza>*/;
});
public constructor();
}
export module zzhy {
export class zza {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhy.zza>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzhy$zza interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzhn(): string;
zzho(): java.lang.Class<any>;
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzhz {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzhz>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzhz>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzia {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzia>;
/**
* Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzia interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzib {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzib>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzic extends com.google.android.gms.internal.firebase_ml.zzht {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzic>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzid extends com.google.android.gms.internal.firebase_ml.zzhx {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzid>;
public close(): void;
public getText(): string;
public getIntValue(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzie extends com.google.android.gms.internal.firebase_ml.zzhs {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzie>;
public writeBoolean(param0: boolean): void;
public flush(): void;
public writeString(param0: string): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzig {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzig>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjx extends com.google.android.gms.internal.firebase_ml.zzgh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjx>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzhd*/, param1: string, param2: string, param3: any /* com.google.android.gms.internal.firebase_ml.zzji*/, param4: any /* com.google.android.gms.internal.firebase_ml.zzgw*/);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzhd*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzht*/, param2: string, param3: string, param4: any /* com.google.android.gms.internal.firebase_ml.zzgw*/, param5: boolean);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzhd*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzht*/, param2: any /* com.google.android.gms.internal.firebase_ml.zzgw*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjy extends com.google.android.gms.internal.firebase_ml.zzge {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjy>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzjz extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzkc<com.google.android.gms.internal.firebase_ml.zzkf>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzjz>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzfz*/, param1: string, param2: string, param3: any /* com.google.android.gms.internal.firebase_ml.zzgp*/, param4: java.lang.Class<any>);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzge*/, param1: string, param2: string, param3: any, param4: java.lang.Class<any>);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzjy*/, param1: string, param2: string, param3: any, param4: java.lang.Class<any>);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzka*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzkg*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzka {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzka>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzjy*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkb extends com.google.android.gms.internal.firebase_ml.zzgj {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkb>;
public constructor();
public constructor(param0: string);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkc<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzgg<any>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkc<any>>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzfz*/, param1: string, param2: string, param3: any /* com.google.android.gms.internal.firebase_ml.zzgp*/, param4: java.lang.Class<any>);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzge*/, param1: string, param2: string, param3: any, param4: java.lang.Class<any>);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzjy*/, param1: string, param2: string, param3: any, param4: java.lang.Class<any>);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkd extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkd>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzke extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzke>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkf extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkf>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkg extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkg>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkh extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkh>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzki extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzki>;
public constructor();
public getParagraphs(): any /* java.util.List<com.google.android.gms.internal.firebase_ml.zzla>*/;
public getConfidence(): java.lang.Float;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkj extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkj>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkk extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkk>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkl extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkl>;
public constructor();
public getLanguageCode(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkm extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkm>;
public constructor();
public getType(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkn extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkn>;
public constructor();
public getMid(): string;
public getDescription(): string;
public getLocations(): any /* java.util.List<com.google.android.gms.internal.firebase_ml.zzky>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzko extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzko>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkp extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkp>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkq extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkq>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkr extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkr>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzks extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzks>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkt extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkt>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzku extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzku>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkv extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkv>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkw extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkw>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkx extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkx>;
public constructor();
public getBlocks(): any /* java.util.List<com.google.android.gms.internal.firebase_ml.zzki>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzky extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzky>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzkz extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzkz>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzla extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzla>;
public constructor();
public getConfidence(): java.lang.Float;
public getWords(): any /* java.util.List<com.google.android.gms.internal.firebase_ml.zzlj>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlb extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlb>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlc extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlc>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzld extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzld>;
public constructor();
public getConfidence(): java.lang.Float;
public getText(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzle extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzle>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlf extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlf>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlg extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlg>;
public constructor();
public getPages(): any /* java.util.List<com.google.android.gms.internal.firebase_ml.zzkx>*/;
public getText(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlh extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlh>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzli extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzli>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlj extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlj>;
public constructor();
public getConfidence(): java.lang.Float;
public getSymbols(): any /* java.util.List<com.google.android.gms.internal.firebase_ml.zzld>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzlk extends com.google.android.gms.internal.firebase_ml.zzhq {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzlk>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzqx {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqx>;
public features: any /* java.util.List<com.google.android.gms.internal.firebase_ml.zzkq>*/;
public imageContext: any /* com.google.android.gms.internal.firebase_ml.zzkr*/;
public constructor(param0: native.Array<number>, param1: number, param2: any /* java.util.List<com.google.android.gms.internal.firebase_ml.zzkq>*/, param3: any /* com.google.android.gms.internal.firebase_ml.zzkr*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzqy {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqy>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzqz extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqz>;
public release(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export abstract class zzra<ResultType> extends java.io.Closeable {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzra<any>>;
public close(): void;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: string, param2: any /* com.google.android.gms.internal.firebase_ml.zzkr*/, param3: boolean);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: string, param2: com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrb extends com.google.android.gms.internal.firebase_ml.zzkb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrb>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml.zzpc<com.google.android.gms.internal.firebase_ml.zzkd,com.google.android.gms.internal.firebase_ml.zzqx>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrd>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzre extends com.google.android.gms.internal.firebase_ml.zzkb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzre>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrf>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrg {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrg>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrh {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrh>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzri<TDetectionResult> extends java.io.Closeable {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzri<any>>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzpc<any,com.google.android.gms.internal.firebase_ml.zzrl>*/);
public close(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrj extends java.lang.Object /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.internal.firebase_ml.zzrk>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrj>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrk {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrk>;
public static CREATOR: any /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.internal.firebase_ml.zzrk>*/;
public width: number;
public height: number;
public rotation: number;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public constructor(param0: number, param1: number, param2: number, param3: number, param4: number);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrl {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrl>;
public constructor(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage, param1: com.google.android.gms.vision.Frame);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrm {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrm>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrn {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrn>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzro extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzro>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions);
public release(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrp {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrp>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrq extends com.google.android.gms.internal.firebase_ml.zzri<java.util.List<com.google.firebase.ml.vision.label.FirebaseVisionImageLabel>> implements java.io.Closeable {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrq>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzpc<any,com.google.android.gms.internal.firebase_ml.zzrl>*/);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceImageLabelerOptions);
public detectInImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.ml.vision.label.FirebaseVisionImageLabel>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrr extends com.google.android.gms.internal.firebase_ml.zzra<java.util.List<com.google.firebase.ml.vision.label.FirebaseVisionImageLabel>> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrr>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: string, param2: any /* com.google.android.gms.internal.firebase_ml.zzkr*/, param3: boolean);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: string, param2: com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions);
public detectInImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.ml.vision.label.FirebaseVisionImageLabel>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrs {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrs>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrt extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrt>;
public release(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzru extends com.google.android.gms.internal.firebase_ml.zzri<java.util.List<com.google.firebase.ml.vision.label.FirebaseVisionImageLabel>> implements java.io.Closeable {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzru>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzpc<any,com.google.android.gms.internal.firebase_ml.zzrl>*/);
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceAutoMLImageLabelerOptions);
public detectInImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.ml.vision.label.FirebaseVisionImageLabel>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrv {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrv>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrw {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrw>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrx extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrx>;
public release(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzry {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzry>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzrz extends com.google.android.gms.internal.firebase_ml.zzri<com.google.firebase.ml.vision.text.FirebaseVisionText> implements java.io.Closeable {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzrz>;
public processImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<com.google.firebase.ml.vision.text.FirebaseVisionText>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsa extends com.google.android.gms.internal.firebase_ml.zzra<com.google.firebase.ml.vision.text.FirebaseVisionText> {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsa>;
public processImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<com.google.firebase.ml.vision.text.FirebaseVisionText>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsb {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsb>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsc extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsc>;
public release(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsd {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsd>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzse {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzse>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsf>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsh extends com.google.android.gms.internal.firebase_ml.zzsf {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsh>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsi {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsi>;
public nextBoolean(): boolean;
public close(): void;
public endArray(): void;
public nextNull(): void;
public nextName(): string;
public nextString(): string;
public beginArray(): void;
public constructor(param0: java.io.Reader);
public toString(): string;
public beginObject(): void;
public endObject(): void;
public setLenient(param0: boolean): void;
public skipValue(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsj {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsj>;
public close(): void;
public setIndent(param0: string): void;
public constructor(param0: java.io.Writer);
public setLenient(param0: boolean): void;
public flush(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsk {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsk>;
public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml.zzsk>*/;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module firebase_ml {
export class zzsm {
public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzsm>;
public constructor(param0: string);
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export class FirebaseVision {
public static class: java.lang.Class<com.google.firebase.ml.vision.FirebaseVision>;
public getVisionBarcodeDetector(param0: com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetector;
public getVisionBarcodeDetector(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetector;
public getVisionFaceDetector(): com.google.firebase.ml.vision.face.FirebaseVisionFaceDetector;
public isStatsCollectionEnabled(): boolean;
public getCloudTextRecognizer(param0: com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions): com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer;
public getOnDeviceImageLabeler(): com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler;
public getOnDeviceImageLabeler(param0: com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceImageLabelerOptions): com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler;
public getVisionCloudLandmarkDetector(): com.google.firebase.ml.vision.cloud.landmark.FirebaseVisionCloudLandmarkDetector;
public getCloudDocumentTextRecognizer(param0: com.google.firebase.ml.vision.document.FirebaseVisionCloudDocumentRecognizerOptions): com.google.firebase.ml.vision.document.FirebaseVisionDocumentTextRecognizer;
public getOnDeviceObjectDetector(): com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetector;
public setStatsCollectionEnabled(param0: boolean): void;
public getOnDeviceAutoMLImageLabeler(param0: com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceAutoMLImageLabelerOptions): com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler;
public static getInstance(): com.google.firebase.ml.vision.FirebaseVision;
public getVisionCloudLandmarkDetector(param0: com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions): com.google.firebase.ml.vision.cloud.landmark.FirebaseVisionCloudLandmarkDetector;
public static getInstance(param0: com.google.firebase.FirebaseApp): com.google.firebase.ml.vision.FirebaseVision;
public getOnDeviceTextRecognizer(): com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer;
public getOnDeviceObjectDetector(param0: com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions): com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetector;
public getCloudTextRecognizer(): com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer;
public getVisionFaceDetector(param0: com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions): com.google.firebase.ml.vision.face.FirebaseVisionFaceDetector;
public getCloudImageLabeler(param0: com.google.firebase.ml.vision.label.FirebaseVisionCloudImageLabelerOptions): com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler;
public getCloudImageLabeler(): com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler;
public getCloudDocumentTextRecognizer(): com.google.firebase.ml.vision.document.FirebaseVisionDocumentTextRecognizer;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export class VisionRegistrar {
public static class: java.lang.Class<com.google.firebase.ml.vision.VisionRegistrar>;
public constructor();
public getComponents(): java.util.List<com.google.firebase.components.Component<any>>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export class FirebaseAutoMLLocalModel {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.FirebaseAutoMLLocalModel>;
}
export module FirebaseAutoMLLocalModel {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.FirebaseAutoMLLocalModel.Builder>;
public setAssetFilePath(param0: string): com.google.firebase.ml.vision.automl.FirebaseAutoMLLocalModel.Builder;
public build(): com.google.firebase.ml.vision.automl.FirebaseAutoMLLocalModel;
public setFilePath(param0: string): com.google.firebase.ml.vision.automl.FirebaseAutoMLLocalModel.Builder;
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export class FirebaseAutoMLRemoteModel {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.FirebaseAutoMLRemoteModel>;
}
export module FirebaseAutoMLRemoteModel {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.FirebaseAutoMLRemoteModel.Builder>;
public build(): com.google.firebase.ml.vision.automl.FirebaseAutoMLRemoteModel;
public constructor(param0: string);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class IOnDeviceAutoMLImageLabeler {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.IOnDeviceAutoMLImageLabeler>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.automl.internal.IOnDeviceAutoMLImageLabeler interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: any /* com.google.android.gms.internal.firebase_ml.zzrk*/): any /* native.Array<com.google.firebase.ml.vision.automl.internal.zzj>*/;
zznu(): void;
close(): void;
zzod(): boolean;
});
public constructor();
public close(): void;
}
export module IOnDeviceAutoMLImageLabeler {
export abstract class zza implements com.google.firebase.ml.vision.automl.internal.IOnDeviceAutoMLImageLabeler {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.IOnDeviceAutoMLImageLabeler.zza>;
public constructor();
public close(): void;
public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean;
}
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class OnDeviceAutoMLImageLabelerOptionsParcel {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.OnDeviceAutoMLImageLabelerOptionsParcel>;
public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.firebase.ml.vision.automl.internal.OnDeviceAutoMLImageLabelerOptionsParcel>;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public constructor(param0: number, param1: string, param2: string, param3: string);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zza extends com.google.firebase.ml.common.internal.modeldownload.RemoteModelManagerInterface<com.google.firebase.ml.vision.automl.FirebaseAutoMLRemoteModel> {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zza>;
public getDownloadedModels(): com.google.android.gms.tasks.Task<java.util.Set<com.google.firebase.ml.vision.automl.FirebaseAutoMLRemoteModel>>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzpo*/);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zzb {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzb>;
public onComplete(param0: com.google.android.gms.tasks.Task): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zzc {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzc>;
public call(): any;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zzd {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzd>;
public onComplete(param0: com.google.android.gms.tasks.Task): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zze {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zze>;
public call(): any;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zzf {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzf>;
public then(param0: any): com.google.android.gms.tasks.Task;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zzg implements com.google.firebase.ml.vision.automl.internal.IOnDeviceAutoMLImageLabeler {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzg>;
public close(): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export abstract class zzh implements com.google.firebase.ml.vision.automl.internal.zzi {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzh>;
public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean;
public static asInterface(param0: globalAndroid.os.IBinder): any /* com.google.firebase.ml.vision.automl.internal.zzi*/;
public constructor();
public newOnDeviceAutoMLImageLabeler(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.firebase.ml.vision.automl.internal.OnDeviceAutoMLImageLabelerOptionsParcel): com.google.firebase.ml.vision.automl.internal.IOnDeviceAutoMLImageLabeler;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zzi {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzi>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.automl.internal.zzi interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
newOnDeviceAutoMLImageLabeler(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.firebase.ml.vision.automl.internal.OnDeviceAutoMLImageLabelerOptionsParcel): com.google.firebase.ml.vision.automl.internal.IOnDeviceAutoMLImageLabeler;
});
public constructor();
public newOnDeviceAutoMLImageLabeler(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.firebase.ml.vision.automl.internal.OnDeviceAutoMLImageLabelerOptionsParcel): com.google.firebase.ml.vision.automl.internal.IOnDeviceAutoMLImageLabeler;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zzj {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzj>;
public static CREATOR: any /* globalAndroid.os.Parcelable.Creator<com.google.firebase.ml.vision.automl.internal.zzj>*/;
public text: string;
public constructor(param0: string, param1: string, param2: number);
public equals(param0: any): boolean;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public hashCode(): number;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zzk implements com.google.firebase.ml.vision.automl.internal.zzi {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzk>;
public newOnDeviceAutoMLImageLabeler(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.firebase.ml.vision.automl.internal.OnDeviceAutoMLImageLabelerOptionsParcel): com.google.firebase.ml.vision.automl.internal.IOnDeviceAutoMLImageLabeler;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zzl extends java.lang.Object /* globalAndroid.os.Parcelable.Creator<com.google.firebase.ml.vision.automl.internal.zzj>*/ {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzl>;
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export module internal {
export class zzm extends globalAndroid.os.Parcelable.Creator<com.google.firebase.ml.vision.automl.internal.OnDeviceAutoMLImageLabelerOptionsParcel> {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.internal.zzm>;
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export class zzh {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.zzh>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module automl {
export class zzi {
public static class: java.lang.Class<com.google.firebase.ml.vision.automl.zzi>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export class FirebaseVisionBarcode {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode>;
public static FORMAT_UNKNOWN: number;
public static FORMAT_ALL_FORMATS: number;
public static FORMAT_CODE_128: number;
public static FORMAT_CODE_39: number;
public static FORMAT_CODE_93: number;
public static FORMAT_CODABAR: number;
public static FORMAT_DATA_MATRIX: number;
public static FORMAT_EAN_13: number;
public static FORMAT_EAN_8: number;
public static FORMAT_ITF: number;
public static FORMAT_QR_CODE: number;
public static FORMAT_UPC_A: number;
public static FORMAT_UPC_E: number;
public static FORMAT_PDF417: number;
public static FORMAT_AZTEC: number;
public static TYPE_UNKNOWN: number;
public static TYPE_CONTACT_INFO: number;
public static TYPE_EMAIL: number;
public static TYPE_ISBN: number;
public static TYPE_PHONE: number;
public static TYPE_PRODUCT: number;
public static TYPE_SMS: number;
public static TYPE_TEXT: number;
public static TYPE_URL: number;
public static TYPE_WIFI: number;
public static TYPE_GEO: number;
public static TYPE_CALENDAR_EVENT: number;
public static TYPE_DRIVER_LICENSE: number;
public getSms(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Sms;
public getWifi(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.WiFi;
public getGeoPoint(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.GeoPoint;
public getRawBytes(): native.Array<number>;
public getCalendarEvent(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.CalendarEvent;
public getContactInfo(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.ContactInfo;
public getCornerPoints(): native.Array<globalAndroid.graphics.Point>;
public getValueType(): number;
public getUrl(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.UrlBookmark;
public getEmail(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Email;
public getFormat(): number;
public getDriverLicense(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.DriverLicense;
public getPhone(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Phone;
public getRawValue(): string;
public getDisplayValue(): string;
public getBoundingBox(): globalAndroid.graphics.Rect;
public constructor(param0: any /* com.google.firebase.ml.vision.barcode.internal.zzf*/);
}
export module FirebaseVisionBarcode {
export class Address {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Address>;
public static TYPE_UNKNOWN: number;
public static TYPE_WORK: number;
public static TYPE_HOME: number;
public getType(): number;
public getAddressLines(): native.Array<string>;
public constructor(param0: number, param1: native.Array<string>);
}
export module Address {
export class AddressType {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Address.AddressType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode$Address$AddressType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
export class BarcodeFormat {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.BarcodeFormat>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode$BarcodeFormat interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
export class BarcodeValueType {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.BarcodeValueType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode$BarcodeValueType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
export class CalendarDateTime {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.CalendarDateTime>;
public getDay(): number;
public isUtc(): boolean;
public getRawValue(): string;
public constructor(param0: number, param1: number, param2: number, param3: number, param4: number, param5: number, param6: boolean, param7: string);
public getHours(): number;
public getMinutes(): number;
public getYear(): number;
public getSeconds(): number;
public getMonth(): number;
}
export class CalendarEvent {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.CalendarEvent>;
public getSummary(): string;
public getOrganizer(): string;
public getEnd(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.CalendarDateTime;
public getDescription(): string;
public getStatus(): string;
public getStart(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.CalendarDateTime;
public constructor(param0: string, param1: string, param2: string, param3: string, param4: string, param5: com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.CalendarDateTime, param6: com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.CalendarDateTime);
public getLocation(): string;
}
export class ContactInfo {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.ContactInfo>;
public getOrganization(): string;
public getTitle(): string;
public getEmails(): java.util.List<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Email>;
public getName(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.PersonName;
public constructor(param0: com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.PersonName, param1: string, param2: string, param3: java.util.List<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Phone>, param4: java.util.List<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Email>, param5: native.Array<string>, param6: java.util.List<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Address>);
public getPhones(): java.util.List<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Phone>;
public getAddresses(): java.util.List<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Address>;
public getUrls(): native.Array<string>;
}
export class DriverLicense {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.DriverLicense>;
public getLicenseNumber(): string;
public getAddressStreet(): string;
public getAddressZip(): string;
public getExpiryDate(): string;
public getAddressCity(): string;
public getFirstName(): string;
public constructor(param0: string, param1: string, param2: string, param3: string, param4: string, param5: string, param6: string, param7: string, param8: string, param9: string, param10: string, param11: string, param12: string, param13: string);
public getIssueDate(): string;
public getBirthDate(): string;
public getDocumentType(): string;
public getIssuingCountry(): string;
public getLastName(): string;
public getMiddleName(): string;
public getGender(): string;
public getAddressState(): string;
}
export class Email {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Email>;
public static TYPE_UNKNOWN: number;
public static TYPE_WORK: number;
public static TYPE_HOME: number;
public getType(): number;
public getAddress(): string;
public getBody(): string;
public constructor(param0: number, param1: string, param2: string, param3: string);
public getSubject(): string;
}
export module Email {
export class FormatType {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Email.FormatType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode$Email$FormatType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
export class GeoPoint {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.GeoPoint>;
public getLng(): number;
public constructor(param0: number, param1: number);
public getLat(): number;
}
export class PersonName {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.PersonName>;
public getFormattedName(): string;
public getSuffix(): string;
public getFirst(): string;
public constructor(param0: string, param1: string, param2: string, param3: string, param4: string, param5: string, param6: string);
public getPrefix(): string;
public getMiddle(): string;
public getPronunciation(): string;
public getLast(): string;
}
export class Phone {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Phone>;
public static TYPE_UNKNOWN: number;
public static TYPE_WORK: number;
public static TYPE_HOME: number;
public static TYPE_FAX: number;
public static TYPE_MOBILE: number;
public getType(): number;
public getNumber(): string;
public constructor(param0: string, param1: number);
}
export module Phone {
export class FormatType {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Phone.FormatType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode$Phone$FormatType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
export class Sms {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Sms>;
public getPhoneNumber(): string;
public constructor(param0: string, param1: string);
public getMessage(): string;
}
export class UrlBookmark {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.UrlBookmark>;
public getTitle(): string;
public constructor(param0: string, param1: string);
public getUrl(): string;
}
export class WiFi {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.WiFi>;
public static TYPE_OPEN: number;
public static TYPE_WPA: number;
public static TYPE_WEP: number;
public constructor(param0: string, param1: string, param2: number);
public getSsid(): string;
public getPassword(): string;
public getEncryptionType(): number;
}
export module WiFi {
export class EncryptionType {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.WiFi.EncryptionType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode$WiFi$EncryptionType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export class FirebaseVisionBarcodeDetector extends com.google.android.gms.internal.firebase_ml.zzri<java.util.List<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode>> implements java.io.Closeable {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetector>;
public close(): void;
public detectInImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export class FirebaseVisionBarcodeDetectorOptions {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions>;
public hashCode(): number;
public equals(param0: any): boolean;
}
export module FirebaseVisionBarcodeDetectorOptions {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions.Builder>;
public build(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions;
public constructor();
public setBarcodeFormats(param0: number, param1: native.Array<number>): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions.Builder;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class BarcodeDetectorOptionsParcel {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.BarcodeDetectorOptionsParcel>;
public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.firebase.ml.vision.barcode.internal.BarcodeDetectorOptionsParcel>;
public constructor(param0: number);
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class IBarcodeDetector {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.IBarcodeDetector>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.barcode.internal.IBarcodeDetector interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
start(): void;
zzb(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: any /* com.google.android.gms.internal.firebase_ml.zzrk*/): com.google.android.gms.dynamic.IObjectWrapper;
stop(): void;
});
public constructor();
public stop(): void;
public start(): void;
}
export module IBarcodeDetector {
export abstract class zza implements com.google.firebase.ml.vision.barcode.internal.IBarcodeDetector {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.IBarcodeDetector.zza>;
public constructor();
public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean;
public start(): void;
public stop(): void;
}
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class zza extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.zza>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions);
public release(): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class zzb extends globalAndroid.os.Parcelable.Creator<com.google.firebase.ml.vision.barcode.internal.BarcodeDetectorOptionsParcel> {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.zzb>;
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class zzc {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.zzc>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class zzd {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.zzd>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class zze extends com.google.firebase.ml.vision.barcode.internal.zzf {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.zze>;
public getDisplayValue(): string;
public getGeoPoint(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.GeoPoint;
public constructor(param0: com.google.android.gms.vision.barcode.Barcode);
public getContactInfo(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.ContactInfo;
public getDriverLicense(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.DriverLicense;
public getCalendarEvent(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.CalendarEvent;
public getValueType(): number;
public getFormat(): number;
public getPhone(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Phone;
public getBoundingBox(): globalAndroid.graphics.Rect;
public getWifi(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.WiFi;
public getRawValue(): string;
public getUrl(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.UrlBookmark;
public getCornerPoints(): native.Array<globalAndroid.graphics.Point>;
public getRawBytes(): native.Array<number>;
public getSms(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Sms;
public getEmail(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Email;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class zzf {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.zzf>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.barcode.internal.zzf interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getBoundingBox(): globalAndroid.graphics.Rect;
getCornerPoints(): native.Array<globalAndroid.graphics.Point>;
getRawValue(): string;
getRawBytes(): native.Array<number>;
getDisplayValue(): string;
getFormat(): number;
getValueType(): number;
getEmail(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Email;
getPhone(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Phone;
getSms(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Sms;
getWifi(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.WiFi;
getUrl(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.UrlBookmark;
getGeoPoint(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.GeoPoint;
getCalendarEvent(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.CalendarEvent;
getContactInfo(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.ContactInfo;
getDriverLicense(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.DriverLicense;
});
public constructor();
public getDisplayValue(): string;
public getGeoPoint(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.GeoPoint;
public getContactInfo(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.ContactInfo;
public getDriverLicense(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.DriverLicense;
public getCalendarEvent(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.CalendarEvent;
public getValueType(): number;
public getFormat(): number;
public getPhone(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Phone;
public getBoundingBox(): globalAndroid.graphics.Rect;
public getWifi(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.WiFi;
public getRawValue(): string;
public getUrl(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.UrlBookmark;
public getCornerPoints(): native.Array<globalAndroid.graphics.Point>;
public getRawBytes(): native.Array<number>;
public getSms(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Sms;
public getEmail(): com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode.Email;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class zzg {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.zzg>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.barcode.internal.zzg interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
newBarcodeDetector(param0: com.google.firebase.ml.vision.barcode.internal.BarcodeDetectorOptionsParcel): com.google.firebase.ml.vision.barcode.internal.IBarcodeDetector;
});
public constructor();
public newBarcodeDetector(param0: com.google.firebase.ml.vision.barcode.internal.BarcodeDetectorOptionsParcel): com.google.firebase.ml.vision.barcode.internal.IBarcodeDetector;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class zzh implements com.google.firebase.ml.vision.barcode.internal.IBarcodeDetector {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.zzh>;
public stop(): void;
public start(): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export class zzi implements com.google.firebase.ml.vision.barcode.internal.zzg {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.zzi>;
public newBarcodeDetector(param0: com.google.firebase.ml.vision.barcode.internal.BarcodeDetectorOptionsParcel): com.google.firebase.ml.vision.barcode.internal.IBarcodeDetector;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export module internal {
export abstract class zzj implements com.google.firebase.ml.vision.barcode.internal.zzg {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.internal.zzj>;
public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean;
public constructor();
public static asInterface(param0: globalAndroid.os.IBinder): any /* com.google.firebase.ml.vision.barcode.internal.zzg*/;
public newBarcodeDetector(param0: com.google.firebase.ml.vision.barcode.internal.BarcodeDetectorOptionsParcel): com.google.firebase.ml.vision.barcode.internal.IBarcodeDetector;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module barcode {
export class zzc {
public static class: java.lang.Class<com.google.firebase.ml.vision.barcode.zzc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module cloud {
export class FirebaseVisionCloudDetectorOptions {
public static class: java.lang.Class<com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions>;
public static STABLE_MODEL: number;
public static LATEST_MODEL: number;
public static DEFAULT: com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions;
public getMaxResults(): number;
public hashCode(): number;
public isEnforceCertFingerprintMatch(): boolean;
public builder(): com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions.Builder;
public equals(param0: any): boolean;
public getModelType(): number;
}
export module FirebaseVisionCloudDetectorOptions {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions.Builder>;
public build(): com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions;
public setMaxResults(param0: number): com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions.Builder;
public setModelType(param0: number): com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions.Builder;
public constructor();
public enforceCertFingerprintMatch(): com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions.Builder;
}
export class ModelType {
public static class: java.lang.Class<com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions.ModelType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions$ModelType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module cloud {
export module landmark {
export class FirebaseVisionCloudLandmark {
public static class: java.lang.Class<com.google.firebase.ml.vision.cloud.landmark.FirebaseVisionCloudLandmark>;
public getConfidence(): number;
public getLocations(): java.util.List<com.google.firebase.ml.vision.common.FirebaseVisionLatLng>;
public getLandmark(): string;
public getBoundingBox(): globalAndroid.graphics.Rect;
public getEntityId(): string;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module cloud {
export module landmark {
export class FirebaseVisionCloudLandmarkDetector extends com.google.android.gms.internal.firebase_ml.zzra<java.util.List<com.google.firebase.ml.vision.cloud.landmark.FirebaseVisionCloudLandmark>> {
public static class: java.lang.Class<com.google.firebase.ml.vision.cloud.landmark.FirebaseVisionCloudLandmarkDetector>;
public detectInImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.ml.vision.cloud.landmark.FirebaseVisionCloudLandmark>>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module cloud {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.cloud.zza>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module common {
export class FirebaseVisionImage {
public static class: java.lang.Class<com.google.firebase.ml.vision.common.FirebaseVisionImage>;
public static fromByteBuffer(param0: java.nio.ByteBuffer, param1: com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata): com.google.firebase.ml.vision.common.FirebaseVisionImage;
public static fromBitmap(param0: globalAndroid.graphics.Bitmap): com.google.firebase.ml.vision.common.FirebaseVisionImage;
public static fromByteArray(param0: native.Array<number>, param1: com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata): com.google.firebase.ml.vision.common.FirebaseVisionImage;
public getBitmap(): globalAndroid.graphics.Bitmap;
public static fromMediaImage(param0: globalAndroid.media.Image, param1: number): com.google.firebase.ml.vision.common.FirebaseVisionImage;
public static fromFilePath(param0: globalAndroid.content.Context, param1: globalAndroid.net.Uri): com.google.firebase.ml.vision.common.FirebaseVisionImage;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module common {
export class FirebaseVisionImageMetadata {
public static class: java.lang.Class<com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata>;
public static ROTATION_0: number;
public static ROTATION_90: number;
public static ROTATION_180: number;
public static ROTATION_270: number;
public static IMAGE_FORMAT_NV21: number;
public static IMAGE_FORMAT_YV12: number;
public getWidth(): number;
public getHeight(): number;
public constructor(param0: com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata);
public getRotation(): number;
public getFormat(): number;
}
export module FirebaseVisionImageMetadata {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.Builder>;
public setWidth(param0: number): com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.Builder;
public setFormat(param0: number): com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.Builder;
public constructor();
public setRotation(param0: number): com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.Builder;
public setHeight(param0: number): com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.Builder;
public build(): com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata;
}
export class ImageFormat {
public static class: java.lang.Class<com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.ImageFormat>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata$ImageFormat interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
export class Rotation {
public static class: java.lang.Class<com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata.Rotation>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata$Rotation interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module common {
export class FirebaseVisionLatLng {
public static class: java.lang.Class<com.google.firebase.ml.vision.common.FirebaseVisionLatLng>;
public getLongitude(): number;
public constructor(param0: number, param1: number);
public getLatitude(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module common {
export class FirebaseVisionPoint {
public static class: java.lang.Class<com.google.firebase.ml.vision.common.FirebaseVisionPoint>;
public getX(): java.lang.Float;
public hashCode(): number;
public constructor(param0: java.lang.Float, param1: java.lang.Float, param2: java.lang.Float);
public toString(): string;
public getY(): java.lang.Float;
public getZ(): java.lang.Float;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module common {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.common.zza>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module document {
export class FirebaseVisionCloudDocumentRecognizerOptions {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionCloudDocumentRecognizerOptions>;
public hashCode(): number;
public isEnforceCertFingerprintMatch(): boolean;
public getHintedLanguages(): java.util.List<string>;
public equals(param0: any): boolean;
}
export module FirebaseVisionCloudDocumentRecognizerOptions {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionCloudDocumentRecognizerOptions.Builder>;
public setLanguageHints(param0: java.util.List<string>): com.google.firebase.ml.vision.document.FirebaseVisionCloudDocumentRecognizerOptions.Builder;
public enforceCertFingerprintMatch(): com.google.firebase.ml.vision.document.FirebaseVisionCloudDocumentRecognizerOptions.Builder;
public build(): com.google.firebase.ml.vision.document.FirebaseVisionCloudDocumentRecognizerOptions;
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module document {
export class FirebaseVisionDocumentText {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText>;
public getText(): string;
public getBlocks(): java.util.List<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.Block>;
}
export module FirebaseVisionDocumentText {
export class Block extends com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.DocumentTextBase {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.Block>;
public getParagraphs(): java.util.List<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.Paragraph>;
}
export class DocumentTextBase {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.DocumentTextBase>;
public getRecognizedBreak(): com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.RecognizedBreak;
public getText(): string;
public getBoundingBox(): globalAndroid.graphics.Rect;
public getRecognizedLanguages(): java.util.List<com.google.firebase.ml.vision.text.RecognizedLanguage>;
public getConfidence(): java.lang.Float;
}
export class Paragraph extends com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.DocumentTextBase {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.Paragraph>;
public getWords(): java.util.List<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.Word>;
}
export class RecognizedBreak {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.RecognizedBreak>;
public static UNKNOWN: number;
public static SPACE: number;
public static SURE_SPACE: number;
public static EOL_SURE_SPACE: number;
public static HYPHEN: number;
public static LINE_BREAK: number;
public getDetectedBreakType(): number;
public getIsPrefix(): boolean;
}
export module RecognizedBreak {
export class BreakType {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.RecognizedBreak.BreakType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.document.FirebaseVisionDocumentText$RecognizedBreak$BreakType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
export class Symbol extends com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.DocumentTextBase {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.Symbol>;
}
export class Word extends com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.DocumentTextBase {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.Word>;
public getSymbols(): java.util.List<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText.Symbol>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module document {
export class FirebaseVisionDocumentTextRecognizer extends com.google.android.gms.internal.firebase_ml.zzra<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText> {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.FirebaseVisionDocumentTextRecognizer>;
public processImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<com.google.firebase.ml.vision.document.FirebaseVisionDocumentText>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module document {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.zza>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module document {
export class zzb {
public static class: java.lang.Class<com.google.firebase.ml.vision.document.zzb>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module face {
export class FirebaseVisionFace {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFace>;
public static UNCOMPUTED_PROBABILITY: number;
public static INVALID_ID: number;
public getHeadEulerAngleY(): number;
public getRightEyeOpenProbability(): number;
public getHeadEulerAngleZ(): number;
public getBoundingBox(): globalAndroid.graphics.Rect;
public getLandmark(param0: number): com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark;
public toString(): string;
public getContour(param0: number): com.google.firebase.ml.vision.face.FirebaseVisionFaceContour;
public getLeftEyeOpenProbability(): number;
public constructor(param0: com.google.android.gms.vision.face.Face);
public getSmilingProbability(): number;
public getTrackingId(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module face {
export class FirebaseVisionFaceContour {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceContour>;
public static ALL_POINTS: number;
public static FACE: number;
public static LEFT_EYEBROW_TOP: number;
public static LEFT_EYEBROW_BOTTOM: number;
public static RIGHT_EYEBROW_TOP: number;
public static RIGHT_EYEBROW_BOTTOM: number;
public static LEFT_EYE: number;
public static RIGHT_EYE: number;
public static UPPER_LIP_TOP: number;
public static UPPER_LIP_BOTTOM: number;
public static LOWER_LIP_TOP: number;
public static LOWER_LIP_BOTTOM: number;
public static NOSE_BRIDGE: number;
public static NOSE_BOTTOM: number;
public constructor(param0: number, param1: java.util.List<com.google.firebase.ml.vision.common.FirebaseVisionPoint>);
public getFaceContourType(): number;
public toString(): string;
public getPoints(): java.util.List<com.google.firebase.ml.vision.common.FirebaseVisionPoint>;
}
export module FirebaseVisionFaceContour {
export class ContourType {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceContour.ContourType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.face.FirebaseVisionFaceContour$ContourType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module face {
export class FirebaseVisionFaceDetector extends com.google.android.gms.internal.firebase_ml.zzri<java.util.List<com.google.firebase.ml.vision.face.FirebaseVisionFace>> implements java.io.Closeable {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceDetector>;
public close(): void;
public detectInImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.ml.vision.face.FirebaseVisionFace>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module face {
export class FirebaseVisionFaceDetectorOptions {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions>;
public static NO_LANDMARKS: number;
public static ALL_LANDMARKS: number;
public static NO_CONTOURS: number;
public static ALL_CONTOURS: number;
public static NO_CLASSIFICATIONS: number;
public static ALL_CLASSIFICATIONS: number;
public static FAST: number;
public static ACCURATE: number;
public getLandmarkMode(): number;
public getContourMode(): number;
public isTrackingEnabled(): boolean;
public getPerformanceMode(): number;
public hashCode(): number;
public getClassificationMode(): number;
public getMinFaceSize(): number;
public toString(): string;
public equals(param0: any): boolean;
}
export module FirebaseVisionFaceDetectorOptions {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.Builder>;
public setPerformanceMode(param0: number): com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.Builder;
public setContourMode(param0: number): com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.Builder;
public setMinFaceSize(param0: number): com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.Builder;
public build(): com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions;
public enableTracking(): com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.Builder;
public setClassificationMode(param0: number): com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.Builder;
public constructor();
public setLandmarkMode(param0: number): com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.Builder;
}
export class ClassificationMode {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.ClassificationMode>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions$ClassificationMode interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
export class ContourMode {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.ContourMode>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions$ContourMode interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
export class LandmarkMode {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.LandmarkMode>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions$LandmarkMode interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
export class PerformanceMode {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions.PerformanceMode>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions$PerformanceMode interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module face {
export class FirebaseVisionFaceLandmark {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark>;
public static MOUTH_BOTTOM: number;
public static MOUTH_RIGHT: number;
public static MOUTH_LEFT: number;
public static RIGHT_EYE: number;
public static LEFT_EYE: number;
public static RIGHT_EAR: number;
public static LEFT_EAR: number;
public static RIGHT_CHEEK: number;
public static LEFT_CHEEK: number;
public static NOSE_BASE: number;
public getPosition(): com.google.firebase.ml.vision.common.FirebaseVisionPoint;
public getLandmarkType(): number;
public toString(): string;
}
export module FirebaseVisionFaceLandmark {
export class LandmarkType {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark.LandmarkType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark$LandmarkType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module face {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.face.zza>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module label {
export class FirebaseVisionCloudImageLabelerOptions {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.FirebaseVisionCloudImageLabelerOptions>;
public hashCode(): number;
public isEnforceCertFingerprintMatch(): boolean;
public getConfidenceThreshold(): number;
public equals(param0: any): boolean;
}
export module FirebaseVisionCloudImageLabelerOptions {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.FirebaseVisionCloudImageLabelerOptions.Builder>;
public setConfidenceThreshold(param0: number): com.google.firebase.ml.vision.label.FirebaseVisionCloudImageLabelerOptions.Builder;
public enforceCertFingerprintMatch(): com.google.firebase.ml.vision.label.FirebaseVisionCloudImageLabelerOptions.Builder;
public build(): com.google.firebase.ml.vision.label.FirebaseVisionCloudImageLabelerOptions;
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module label {
export class FirebaseVisionImageLabel {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.FirebaseVisionImageLabel>;
public getConfidence(): number;
public getText(): string;
public hashCode(): number;
public constructor(param0: com.google.android.gms.vision.label.ImageLabel);
public getEntityId(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module label {
export class FirebaseVisionImageLabeler {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler>;
public static ON_DEVICE: number;
public static CLOUD: number;
public static ON_DEVICE_AUTOML: number;
public getImageLabelerType(): number;
public close(): void;
public processImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.ml.vision.label.FirebaseVisionImageLabel>>;
}
export module FirebaseVisionImageLabeler {
export class ImageLabelerType {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler.ImageLabelerType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler$ImageLabelerType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module label {
export class FirebaseVisionOnDeviceAutoMLImageLabelerOptions {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceAutoMLImageLabelerOptions>;
public hashCode(): number;
public getConfidenceThreshold(): number;
public equals(param0: any): boolean;
}
export module FirebaseVisionOnDeviceAutoMLImageLabelerOptions {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder>;
public setConfidenceThreshold(param0: number): com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder;
public constructor(param0: com.google.firebase.ml.vision.automl.FirebaseAutoMLRemoteModel);
public constructor(param0: com.google.firebase.ml.vision.automl.FirebaseAutoMLLocalModel);
public build(): com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceAutoMLImageLabelerOptions;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module label {
export class FirebaseVisionOnDeviceImageLabelerOptions {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceImageLabelerOptions>;
public hashCode(): number;
public getConfidenceThreshold(): number;
public equals(param0: any): boolean;
}
export module FirebaseVisionOnDeviceImageLabelerOptions {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceImageLabelerOptions.Builder>;
public build(): com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceImageLabelerOptions;
public constructor();
public setConfidenceThreshold(param0: number): com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceImageLabelerOptions.Builder;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module label {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.zza>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module label {
export class zzb extends com.google.android.gms.tasks.Continuation<java.util.List<com.google.firebase.ml.vision.label.FirebaseVisionImageLabel>,java.util.List<com.google.firebase.ml.vision.label.FirebaseVisionImageLabel>> {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.zzb>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module label {
export class zzc {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.zzc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module label {
export class zzd {
public static class: java.lang.Class<com.google.firebase.ml.vision.label.zzd>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export class FirebaseVisionObject {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.FirebaseVisionObject>;
public static CATEGORY_UNKNOWN: number;
public static CATEGORY_HOME_GOOD: number;
public static CATEGORY_FASHION_GOOD: number;
public static CATEGORY_FOOD: number;
public static CATEGORY_PLACE: number;
public static CATEGORY_PLANT: number;
public getClassificationConfidence(): java.lang.Float;
public getClassificationCategory(): number;
public getTrackingId(): java.lang.Integer;
public constructor(param0: any /* com.google.firebase.ml.vision.objects.internal.zzh*/);
public getBoundingBox(): globalAndroid.graphics.Rect;
}
export module FirebaseVisionObject {
export class Category {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.FirebaseVisionObject.Category>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.objects.FirebaseVisionObject$Category interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export class FirebaseVisionObjectDetector extends com.google.android.gms.internal.firebase_ml.zzri<java.util.List<com.google.firebase.ml.vision.objects.FirebaseVisionObject>> implements java.io.Closeable {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetector>;
public processImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<java.util.List<com.google.firebase.ml.vision.objects.FirebaseVisionObject>>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export class FirebaseVisionObjectDetectorOptions {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions>;
public static STREAM_MODE: number;
public static SINGLE_IMAGE_MODE: number;
public hashCode(): number;
public equals(param0: any): boolean;
}
export module FirebaseVisionObjectDetectorOptions {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions.Builder>;
public build(): com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions;
public enableMultipleObjects(): com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions.Builder;
public constructor();
public setDetectorMode(param0: number): com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions.Builder;
public enableClassification(): com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions.Builder;
}
export class DetectorMode {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions.DetectorMode>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions$DetectorMode interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class IObjectDetector {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.IObjectDetector>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.objects.internal.IObjectDetector interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzc(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: any /* com.google.android.gms.internal.firebase_ml.zzrk*/): any /* native.Array<com.google.firebase.ml.vision.objects.internal.zzh>*/;
start(): void;
stop(): void;
});
public constructor();
public stop(): void;
public start(): void;
}
export module IObjectDetector {
export abstract class zza implements com.google.firebase.ml.vision.objects.internal.IObjectDetector {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.IObjectDetector.zza>;
public constructor();
public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean;
public start(): void;
public stop(): void;
}
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class ObjectDetectorOptionsParcel {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.ObjectDetectorOptionsParcel>;
public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.firebase.ml.vision.objects.internal.ObjectDetectorOptionsParcel>;
public constructor(param0: number, param1: boolean, param2: boolean);
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.zza>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.objects.internal.zza interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
newObjectDetector(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.firebase.ml.vision.objects.internal.ObjectDetectorOptionsParcel): com.google.firebase.ml.vision.objects.internal.IObjectDetector;
});
public constructor();
public newObjectDetector(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.firebase.ml.vision.objects.internal.ObjectDetectorOptionsParcel): com.google.firebase.ml.vision.objects.internal.IObjectDetector;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class zzb implements com.google.firebase.ml.vision.objects.internal.IObjectDetector {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.zzb>;
public stop(): void;
public start(): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class zzc implements com.google.firebase.ml.vision.objects.internal.zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.zzc>;
public newObjectDetector(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.firebase.ml.vision.objects.internal.ObjectDetectorOptionsParcel): com.google.firebase.ml.vision.objects.internal.IObjectDetector;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export abstract class zzd implements com.google.firebase.ml.vision.objects.internal.zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.zzd>;
public static asInterface(param0: globalAndroid.os.IBinder): any /* com.google.firebase.ml.vision.objects.internal.zza*/;
public newObjectDetector(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: com.google.firebase.ml.vision.objects.internal.ObjectDetectorOptionsParcel): com.google.firebase.ml.vision.objects.internal.IObjectDetector;
public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean;
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class zze extends globalAndroid.os.Parcelable.Creator<com.google.firebase.ml.vision.objects.internal.ObjectDetectorOptionsParcel> {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.zze>;
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class zzf {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.zzf>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class zzg extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.zzg>;
public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions);
public release(): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class zzh {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.zzh>;
public static CREATOR: any /* globalAndroid.os.Parcelable.Creator<com.google.firebase.ml.vision.objects.internal.zzh>*/;
public confidence: java.lang.Float;
public category: number;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public constructor(param0: native.Array<number>, param1: java.lang.Integer, param2: java.lang.Float, param3: string, param4: number);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class zzi {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.zzi>;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export module internal {
export class zzj extends java.lang.Object /* globalAndroid.os.Parcelable.Creator<com.google.firebase.ml.vision.objects.internal.zzh>*/ {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.internal.zzj>;
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module objects {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.objects.zza>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module text {
export class FirebaseVisionCloudTextRecognizerOptions {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions>;
public static SPARSE_MODEL: number;
public static DENSE_MODEL: number;
public hashCode(): number;
public isEnforceCertFingerprintMatch(): boolean;
public getHintedLanguages(): java.util.List<string>;
public equals(param0: any): boolean;
public getModelType(): number;
}
export module FirebaseVisionCloudTextRecognizerOptions {
export class Builder {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions.Builder>;
public build(): com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions;
public setModelType(param0: number): com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions.Builder;
public constructor();
public setLanguageHints(param0: java.util.List<string>): com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions.Builder;
public enforceCertFingerprintMatch(): com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions.Builder;
}
export class CloudTextModelType {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions.CloudTextModelType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions$CloudTextModelType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module text {
export class FirebaseVisionText {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.FirebaseVisionText>;
public getTextBlocks(): java.util.List<com.google.firebase.ml.vision.text.FirebaseVisionText.TextBlock>;
public getText(): string;
public constructor(param0: globalAndroid.util.SparseArray<com.google.android.gms.vision.text.TextBlock>);
public constructor(param0: string, param1: java.util.List<com.google.firebase.ml.vision.text.FirebaseVisionText.TextBlock>);
}
export module FirebaseVisionText {
export class Element extends com.google.firebase.ml.vision.text.FirebaseVisionText.TextBase {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.FirebaseVisionText.Element>;
public constructor(param0: string, param1: globalAndroid.graphics.Rect, param2: java.util.List<com.google.firebase.ml.vision.text.RecognizedLanguage>, param3: java.lang.Float);
}
export class Line extends com.google.firebase.ml.vision.text.FirebaseVisionText.TextBase {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.FirebaseVisionText.Line>;
public getElements(): java.util.List<com.google.firebase.ml.vision.text.FirebaseVisionText.Element>;
public constructor(param0: string, param1: globalAndroid.graphics.Rect, param2: java.util.List<com.google.firebase.ml.vision.text.RecognizedLanguage>, param3: java.util.List<com.google.firebase.ml.vision.text.FirebaseVisionText.Element>, param4: java.lang.Float);
}
export class TextBase {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.FirebaseVisionText.TextBase>;
public getCornerPoints(): native.Array<globalAndroid.graphics.Point>;
public getText(): string;
public getBoundingBox(): globalAndroid.graphics.Rect;
public getConfidence(): java.lang.Float;
public getRecognizedLanguages(): java.util.List<com.google.firebase.ml.vision.text.RecognizedLanguage>;
}
export class TextBlock extends com.google.firebase.ml.vision.text.FirebaseVisionText.TextBase {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.FirebaseVisionText.TextBlock>;
public getLines(): java.util.List<com.google.firebase.ml.vision.text.FirebaseVisionText.Line>;
public constructor(param0: string, param1: globalAndroid.graphics.Rect, param2: java.util.List<com.google.firebase.ml.vision.text.RecognizedLanguage>, param3: java.util.List<com.google.firebase.ml.vision.text.FirebaseVisionText.Line>, param4: java.lang.Float);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module text {
export class FirebaseVisionTextRecognizer {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer>;
public static ON_DEVICE: number;
public static CLOUD: number;
public close(): void;
public getRecognizerType(): number;
public processImage(param0: com.google.firebase.ml.vision.common.FirebaseVisionImage): com.google.android.gms.tasks.Task<com.google.firebase.ml.vision.text.FirebaseVisionText>;
}
export module FirebaseVisionTextRecognizer {
export class RecognizerType {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer.RecognizerType>;
/**
* Constructs a new instance of the com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer$RecognizerType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module text {
export class RecognizedLanguage {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.RecognizedLanguage>;
public hashCode(): number;
public getLanguageCode(): string;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module text {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.zza>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export module text {
export class zzb {
public static class: java.lang.Class<com.google.firebase.ml.vision.text.zzb>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export class zza {
public static class: java.lang.Class<com.google.firebase.ml.vision.zza>;
public create(param0: com.google.firebase.components.ComponentContainer): any;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export class zzb {
public static class: java.lang.Class<com.google.firebase.ml.vision.zzb>;
public create(param0: com.google.firebase.components.ComponentContainer): any;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module ml {
export module vision {
export class zzc {
public static class: java.lang.Class<com.google.firebase.ml.vision.zzc>;
public create(param0: com.google.firebase.components.ComponentContainer): any;
}
}
}
}
}
}
//Generics information:
//com.google.android.gms.internal.firebase_ml.zzgb:1
//com.google.android.gms.internal.firebase_ml.zzgg:1
//com.google.android.gms.internal.firebase_ml.zzkc:1
//com.google.android.gms.internal.firebase_ml.zzra:1
//com.google.android.gms.internal.firebase_ml.zzri:1 | the_stack |
import FibonacciNode from './fibonacci-node'
import * as utils from '../../utils'
/*******************************************************************************
* A fibonacci heap is a lazy binomial heap with lazy decreaseKey(). Some important
* algorithms heavily rely on decreaseKey(). Dijkstra's shortest path, Prim's
* minimum spanning tree. Fibonacci heaps give the theoretically optimal implementation
* of Prim's and Dijkstra's algorithms.
*
* decreaseKey() is implemented as follows:
*
* If a node's value gets decreased such that it's value is less than it's parents,
* (violating heap invariant), we don't swim it up. Instead, we cut the child off
* from it's parent and make it a root in our list of roots.
*
* However, if we're allowed to cut off any number of nodes from a tree, than
* our trees will degenerate into trees into shapes we don't want. A tree of
* degree k will only have k + 1 nodes. Then, the number of nodes in the tree
* is no longer exponential (2^k). This in turn makes decreaseKey() inefficient,
* running in O(n) time.
*
* The problem is that a rank k tree thinks they're big. But the'yre losing all their
* descendants. We need to convey to them that they're losing all their
* children/descendants.
*
* We want the tree's to only become somewhat imbalanced, slowly propagating this
* information to the root.
*
* Here's the solution:
* ===================
* Rule 1. Lose one child, you’re a loser.
* Rule 2. Lose two, and you're dumped into the root list.
*
* If a node loses two children, we'll cut it from IT'S parent and move it to
* our main root list.
*
* Then, a tree can only become "maximally damaged". The number of nodes in the
* sequence of maximally damaged trees is the fibonacci sequence, hence the name
* of the data structure.
*
* enqueue() - O(1)
* extractMin() - O(logn) amortized
* findMin() - O(1)
* merge() - O(1)
* decreaseKey() - O(1) ~~ down from O(logn) due to being lazy :)
*
* More info can be found here: https://en.wikipedia.org/wiki/Fibonacci_heap
*
* The implementation below is based off the Fibonacci Heap pseudocode from CLRS Chapter 20
******************************************************************************/
class MinFibonacciHeap<T> {
head: FibonacciNode<T> | null
size: number
minRoot: FibonacciNode<T> | null
// smallestValue for deleteNode(node)
// deleteNode will decrease the node to the smallest value so it swims up to
// the root, and then calls dequeue()
private smallestValue: T
// comparison function if the generic type T is non-primitive
private compare: utils.CompareFunction<T>
constructor(smallestValue: T, compareFunction?: utils.CompareFunction<T>) {
this.head = null
this.minRoot = null
this.size = 0
this.smallestValue = smallestValue
this.compare = compareFunction || utils.defaultCompare
}
/*****************************************************************************
INSPECTION
*****************************************************************************/
/**
* Returns true if the heap is empty, false otherwise - O(1)
* @returns {boolean}
*/
isEmpty(): boolean {
return this.size === 0
}
/*****************************************************************************
INSERTION/DELETION
*****************************************************************************/
/**
* Enqueues element onto the heap - O(1)
* @param {T} element
* @returns {void}
*/
enqueue(element: T): FibonacciNode<T> {
const newRoot = new FibonacciNode(element)
// lazily enqueue the element to the forest
if (this.head) {
newRoot.sibling = this.head
this.head.prevSibling = newRoot
}
this.head = newRoot
this.size += 1
// set minRoot pointer
if (!this.minRoot) this.minRoot = this.head
if (this.compare(this.head.value, this.minRoot.value) < 0) this.minRoot = this.head
return this.head
}
/**
* Dequeues the smallest element from the heap // O(logn)
* @param {T} element
* @returns {void}
*/
dequeue(): FibonacciNode<T> | null {
// remove smallest root of smallest tree B_k from heap
const smallestRoot = this.removeSmallestRoot() // O(logn)
this.size -= 1
if (!smallestRoot) return smallestRoot
// if the root has children, add it to the forest
if (smallestRoot.child) {
let child: FibonacciNode<T> | null = smallestRoot.child
let lastChild: FibonacciNode<T> | null = null
// delete all parent pointers in children while traversing to the last child
while (child) {
lastChild = child
child.parent = null
child = child.sibling
}
if (this.head) {
lastChild!.sibling = this.head
this.head.prevSibling = lastChild
}
this.head = smallestRoot.child
}
this.head = this.consolidate()
// if we removed the smallest root, recalculate the minRoot pointer
if (this.minRoot === smallestRoot) this.recalculateMin()
// return the removed root
return smallestRoot
}
// O(logn)
private removeSmallestRoot(): FibonacciNode<T> | null {
if (!this.head) return null
let cur: FibonacciNode<T> | null = this.head
let prev = cur
let min = cur
let prevMin = null
cur = cur.sibling
// find the min root in O(logn)
while (cur) {
const currentIsLessThanMin = this.compare(cur.value, min.value) < 0
if (currentIsLessThanMin) {
min = cur
prevMin = prev
}
prev = cur
cur = cur.sibling
}
// if smallest root is head, then move heap.head pointer one root forwards
if (prev === null || prevMin === null) {
this.head = this.head.sibling
if (this.head) this.head.prevSibling = null
} else {
// otherwise link prev root with min's right root
prevMin.sibling = min.sibling
if (min.sibling) min.sibling.prevSibling = prevMin
}
return min
}
// O(logn)
private recalculateMin(): void {
if (!this.head) return
let cur = this.head.sibling
let min = this.head
while (cur) {
if (cur.value < min.value) min = cur
cur = cur.sibling
}
this.minRoot = min
}
/**
* Deletes the given node - O(logn)
* @param {FibonacciNode<T>} node
* @returns {void}
*/
deleteNode(node: FibonacciNode<T>): FibonacciNode<T> | null {
// make it the smallest node in the heap so it swims up
this.decreaseKey(node, this.smallestValue) // O(logn)
// dequeue the smallest node from the heap
return this.dequeue() // O(logn)
}
/*****************************************************************************
READING
*****************************************************************************/
/**
* Returns the smallest node in the heap, null if the heap is empty O(1)
* @returns {FibonacciNode<T> | null}
*/
peek(): FibonacciNode<T> | null {
if (!this.head) return null
return this.minRoot
}
/*****************************************************************************
UPDATING
*****************************************************************************/
/**
* Unions supplied heap with current heap - O(1). Current implementation
* is destructive.
* @param {FibonacciHeap<T>} otherHeap
* @returns {FibonacciHeap<T>}
*/
union(otherHeap: MinFibonacciHeap<T>): MinFibonacciHeap<T> {
const unionedHeap = new MinFibonacciHeap<T>(this.smallestValue)
unionedHeap.head = this.head
let cur = unionedHeap.head
while (cur && cur.sibling) {
cur = cur.sibling
}
cur!.sibling = otherHeap.head
if (otherHeap.head) otherHeap.head.prevSibling = cur
unionedHeap.size = this.size + otherHeap.size
return unionedHeap
}
/**
* Consolidates the current state of the heap such that only one tree exists
* for degree k - O(t + logn)
* @returns {MinFibonacciHeap<T>}
*/
private consolidate(): FibonacciNode<T> | null {
// 1. sort the trees according to degree with bucket sort O(t + logn)
const sortedTrees = this.sortForest() // O(t + logn)
// 2. link trees until at most one tree remains for a specific degree k - O(t)
for (let k = 0; k < sortedTrees.length; k++) {
const degreeKTrees = sortedTrees[k]
if (!degreeKTrees) continue
let numberOfDegreeKTrees = degreeKTrees.length
while (numberOfDegreeKTrees >= 2) {
const treeA = degreeKTrees.pop()!
const treeB = degreeKTrees.pop()!
const linkedTree =
treeA.value < treeB.value ? this.linkTrees(treeA, treeB) : this.linkTrees(treeB, treeA)
sortedTrees[k + 1].push(linkedTree)
numberOfDegreeKTrees -= 2
}
}
let cur = null
let head = null
for (let i = sortedTrees.length - 1; i >= 0; i--) {
const trees = sortedTrees[i]
if (trees.length === 0) continue
const tree = trees[0]
if (!cur) {
cur = tree
head = cur
} else {
cur.sibling = tree
tree.prevSibling = cur
cur = cur.sibling
}
}
return head
}
// Links two trees with degree k-1, B_(k-1), and makes one tree with degree
// k, B_k, where nodeA becomes the root of the new tree.
// It does this by making treeB the new head of treeA's children in O(1)
private linkTrees(treeA: FibonacciNode<T>, treeB: FibonacciNode<T>): FibonacciNode<T> {
treeB.parent = treeA
treeB.sibling = treeA.child
if (treeA.child) treeA.child.prevSibling = treeB
treeB.prevSibling = null
treeB.mark = false // important
treeA.child = treeB
treeA.degree += 1
treeA.sibling = null
treeB.prevSibling = null
return treeA
}
// Sorts the list of trees (forest) in O(t + logn) time using bucket sort.
// Bucket sort is used because we have a cap on the degrees of our tree - logt.
// Using a traditional sorting algorithm would take O(tlogt).
private sortForest(): Array<Array<FibonacciNode<T>>> {
// Initialize an array of size logn - O(logn)
const sortedTrees = new Array<Array<FibonacciNode<T>>>(Math.ceil(Math.log2(this.size + 1)))
// intialize buckets in sortedTrees
for (let i = 0; i < sortedTrees.length; i++) {
sortedTrees[i] = []
}
let cur = this.head
// distribute the trees into buckets - O(t)
while (cur) {
const nextCur = cur.sibling
cur.parent = null
cur.sibling = null
cur.prevSibling = null
const index = cur.degree
sortedTrees[index].push(cur)
cur = nextCur
}
return sortedTrees
}
/**
* Decreases the value of the given node to the new value. If the new value is
* smaller than it's parent, it lazily promotes the node to become a root of
* the forest instead of swimming it up. Returns true if successful, and false
* otherwise - O(1)
* @param {FibonacciNode<T>} node
* @param {T} newValue
* @returns {boolean}
*/
decreaseKey(node: FibonacciNode<T>, newValue: T): boolean {
// if newKey >= key, don't update
if (this.compare(node.value, newValue) < 0) return false
node.value = newValue
if (node.parent && node.value < node.parent.value) {
this.cut(node.parent, node)
this.cascadingCut(node.parent)
const nodeIsSmallestNode = !this.minRoot || node.value < this.minRoot.value
if (nodeIsSmallestNode) this.minRoot = node
}
return true
}
// Cuts child from parent in O(1) time
private cut(parent: FibonacciNode<T>, child: FibonacciNode<T>): void {
// remove the node from the parent's list of children
if (parent.child === child) {
parent.child = child.sibling
child.prevSibling = null
} else {
if (!child.prevSibling) throw new Error()
child.prevSibling.sibling = child.sibling
}
// decrement parents degree
parent.degree -= 1
// prepare child to become a root
child.parent = null
child.mark = false
// promote child to a root of a new tree
if (this.head) {
child.sibling = this.head
child.prevSibling = null
this.head.prevSibling = child
}
this.head = child
}
private cascadingCut(parent: FibonacciNode<T>): void {
if (!parent || !parent.parent) return
// if the parent.mark is false, it's first child was just removed
// so let's set parent.mark to true now
if (parent.mark === false) {
parent.mark = true
} else {
// O/w, parent.mark is true. This means it's second child was just removed,
// so we have to cut the current node, and cascade
this.cut(parent.parent, parent)
this.cascadingCut(parent.parent)
}
}
}
export default MinFibonacciHeap | the_stack |
import options from '../../util/options';
import Settings from '../../Settings';
import Math from '../../common/Math';
import Vec2 from '../../common/Vec2';
import Rot from '../../common/Rot';
import Joint, { JointOpt, JointDef } from '../Joint';
import Body from '../Body';
import { TimeStep } from "../Solver";
const inactiveLimit = 0;
const atLowerLimit = 1;
const atUpperLimit = 2;
const equalLimits = 3;
/**
* Rope joint definition. This requires two body anchor points and a maximum
* lengths. Note: by default the connected objects will not collide. see
* collideConnected in JointDef.
*/
export interface RopeJointOpt extends JointOpt {
/**
* The maximum length of the rope.
* Warning: this must be larger than linearSlop or the joint will have no effect.
*/
maxLength?: number;
}
/**
* Rope joint definition. This requires two body anchor points and a maximum
* lengths. Note: by default the connected objects will not collide. see
* collideConnected in JointDef.
*/
export interface RopeJointDef extends JointDef, RopeJointOpt {
/**
* The local anchor point relative to bodyA's origin.
*/
localAnchorA: Vec2;
/**
* The local anchor point relative to bodyB's origin.
*/
localAnchorB: Vec2;
}
const DEFAULTS = {
maxLength : 0.0,
};
/**
* A rope joint enforces a maximum distance between two points on two bodies. It
* has no other effect.
*
* Warning: if you attempt to change the maximum length during the simulation
* you will get some non-physical behavior.
*
* A model that would allow you to dynamically modify the length would have some
* sponginess, so I chose not to implement it that way. See {@link DistanceJoint} if you
* want to dynamically control length.
*/
export default class RopeJoint extends Joint {
static TYPE: 'rope-joint' = 'rope-joint';
/** @internal */ m_type: 'rope-joint';
/** @internal */ m_localAnchorA: Vec2;
/** @internal */ m_localAnchorB: Vec2;
/** @internal */ m_maxLength: number;
/** @internal */ m_mass: number;
/** @internal */ m_impulse: number;
/** @internal */ m_length: number;
/** @internal */ m_state: number; // TODO enum
// Solver temp
/** @internal */ m_u: Vec2;
/** @internal */ m_rA: Vec2;
/** @internal */ m_rB: Vec2;
/** @internal */ m_localCenterA: Vec2;
/** @internal */ m_localCenterB: Vec2;
/** @internal */ m_invMassA: number;
/** @internal */ m_invMassB: number;
/** @internal */ m_invIA: number;
/** @internal */ m_invIB: number;
constructor(def: RopeJointDef);
constructor(def: RopeJointOpt, bodyA: Body, bodyB: Body, anchor: Vec2);
constructor(def: RopeJointDef, bodyA?: Body, bodyB?: Body, anchor?: Vec2) {
// @ts-ignore
if (!(this instanceof RopeJoint)) {
return new RopeJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
super(def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = RopeJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.neo(-1.0, 0.0);
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.neo(1.0, 0.0);
this.m_maxLength = def.maxLength;
this.m_mass = 0.0;
this.m_impulse = 0.0;
this.m_length = 0.0;
this.m_state = inactiveLimit;
// Limit:
// C = norm(pB - pA) - L
// u = (pB - pA) / norm(pB - pA)
// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA))
// J = [-u -cross(rA, u) u cross(rB, u)]
// K = J * invM * JT
// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2
}
/** @internal */
_serialize(): object {
return {
type: this.m_type,
bodyA: this.m_bodyA,
bodyB: this.m_bodyB,
collideConnected: this.m_collideConnected,
localAnchorA: this.m_localAnchorA,
localAnchorB: this.m_localAnchorB,
maxLength: this.m_maxLength,
};
}
/** @internal */
static _deserialize(data: any, world: any, restore: any): RopeJoint {
data = {...data};
data.bodyA = restore(Body, data.bodyA, world);
data.bodyB = restore(Body, data.bodyB, world);
const joint = new RopeJoint(data);
return joint;
}
/**
* The local anchor point relative to bodyA's origin.
*/
getLocalAnchorA(): Vec2 {
return this.m_localAnchorA;
}
/**
* The local anchor point relative to bodyB's origin.
*/
getLocalAnchorB(): Vec2 {
return this.m_localAnchorB;
}
/**
* Set the maximum length of the rope.
*/
setMaxLength(length: number): void {
this.m_maxLength = length;
}
/**
* Get the maximum length of the rope.
*/
getMaxLength(): number {
return this.m_maxLength;
}
getLimitState(): number {
// TODO LimitState
return this.m_state;
}
/**
* Get the anchor point on bodyA in world coordinates.
*/
getAnchorA(): Vec2 {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
}
/**
* Get the anchor point on bodyB in world coordinates.
*/
getAnchorB(): Vec2 {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
}
/**
* Get the reaction force on bodyB at the joint anchor in Newtons.
*/
getReactionForce(inv_dt: number): Vec2 {
return Vec2.mul(this.m_impulse, this.m_u).mul(inv_dt);
}
/**
* Get the reaction torque on bodyB in N*m.
*/
getReactionTorque(inv_dt: number): number {
return 0.0;
}
initVelocityConstraints(step: TimeStep): void {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
const cA = this.m_bodyA.c_position.c;
const aA = this.m_bodyA.c_position.a;
const vA = this.m_bodyA.c_velocity.v;
let wA = this.m_bodyA.c_velocity.w;
const cB = this.m_bodyB.c_position.c;
const aB = this.m_bodyB.c_position.a;
const vB = this.m_bodyB.c_velocity.v;
let wB = this.m_bodyB.c_velocity.w;
const qA = Rot.neo(aA);
const qB = Rot.neo(aB);
this.m_rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA);
this.m_rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB);
this.m_u = Vec2.zero();
this.m_u.addCombine(1, cB, 1, this.m_rB);
this.m_u.subCombine(1, cA, 1, this.m_rA); // Vec2
this.m_length = this.m_u.length();
const C = this.m_length - this.m_maxLength; // float
if (C > 0.0) {
this.m_state = atUpperLimit;
} else {
this.m_state = inactiveLimit;
}
if (this.m_length > Settings.linearSlop) {
this.m_u.mul(1.0 / this.m_length);
} else {
this.m_u.setZero();
this.m_mass = 0.0;
this.m_impulse = 0.0;
return;
}
// Compute effective mass.
const crA = Vec2.cross(this.m_rA, this.m_u); // float
const crB = Vec2.cross(this.m_rB, this.m_u); // float
const invMass = this.m_invMassA + this.m_invIA * crA * crA + this.m_invMassB
+ this.m_invIB * crB * crB; // float
this.m_mass = invMass != 0.0 ? 1.0 / invMass : 0.0;
if (step.warmStarting) {
// Scale the impulse to support a variable time step.
this.m_impulse *= step.dtRatio;
const P = Vec2.mul(this.m_impulse, this.m_u);
vA.subMul(this.m_invMassA, P);
wA -= this.m_invIA * Vec2.cross(this.m_rA, P);
vB.addMul(this.m_invMassB, P);
wB += this.m_invIB * Vec2.cross(this.m_rB, P);
} else {
this.m_impulse = 0.0;
}
this.m_bodyA.c_velocity.v.set(vA);
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v.set(vB);
this.m_bodyB.c_velocity.w = wB;
}
solveVelocityConstraints(step: TimeStep): void {
const vA = this.m_bodyA.c_velocity.v;
let wA = this.m_bodyA.c_velocity.w;
const vB = this.m_bodyB.c_velocity.v;
let wB = this.m_bodyB.c_velocity.w;
// Cdot = dot(u, v + cross(w, r))
const vpA = Vec2.addCross(vA, wA, this.m_rA); // Vec2
const vpB = Vec2.addCross(vB, wB, this.m_rB); // Vec2
const C = this.m_length - this.m_maxLength; // float
let Cdot = Vec2.dot(this.m_u, Vec2.sub(vpB, vpA)); // float
// Predictive constraint.
if (C < 0.0) {
Cdot += step.inv_dt * C;
}
let impulse = -this.m_mass * Cdot; // float
const oldImpulse = this.m_impulse; // float
this.m_impulse = Math.min(0.0, this.m_impulse + impulse);
impulse = this.m_impulse - oldImpulse;
const P = Vec2.mul(impulse, this.m_u); // Vec2
vA.subMul(this.m_invMassA, P);
wA -= this.m_invIA * Vec2.cross(this.m_rA, P);
vB.addMul(this.m_invMassB, P);
wB += this.m_invIB * Vec2.cross(this.m_rB, P);
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
}
/**
* This returns true if the position errors are within tolerance.
*/
solvePositionConstraints(step: TimeStep): boolean {
const cA = this.m_bodyA.c_position.c; // Vec2
let aA = this.m_bodyA.c_position.a; // float
const cB = this.m_bodyB.c_position.c; // Vec2
let aB = this.m_bodyB.c_position.a; // float
const qA = Rot.neo(aA);
const qB = Rot.neo(aB);
const rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA);
const rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB);
const u = Vec2.zero();
u.addCombine(1, cB, 1, rB);
u.subCombine(1, cA, 1, rA); // Vec2
const length = u.normalize(); // float
let C = length - this.m_maxLength; // float
C = Math.clamp(C, 0.0, Settings.maxLinearCorrection);
const impulse = -this.m_mass * C; // float
const P = Vec2.mul(impulse, u); // Vec2
cA.subMul(this.m_invMassA, P);
aA -= this.m_invIA * Vec2.cross(rA, P);
cB.addMul(this.m_invMassB, P);
aB += this.m_invIB * Vec2.cross(rB, P);
this.m_bodyA.c_position.c.set(cA);
this.m_bodyA.c_position.a = aA;
this.m_bodyB.c_position.c.set(cB);
this.m_bodyB.c_position.a = aB;
return length - this.m_maxLength < Settings.linearSlop;
}
} | the_stack |
import {Component, EventEmitter, ViewEncapsulation} from '@angular/core';
import {NavParams, ViewController} from 'ionic-angular';
import {DateService} from './datepicker.service';
import {FormControl} from '@angular/forms';
@Component({
template: `
<div class="datepicker-wrapper">
<div class="datepicker-header"
[ngClass]="config.headerClasses">
<div class="weekday-header">
<div class="weekday-title">{{getSelectedWeekday()}}</div>
</div>
<div class="date-header">
<div class="row">
<div class="col datepicker-month">
{{limitTo(getSelectedMonth(), 3)}}
</div>
</div>
<div class="row">
<div class="col datepicker-day-of-month ">
{{selectedDate | date: 'd'}}
</div>
</div>
<div class="row">
<div class="col datepicker-year ">
{{selectedDate | date: 'yyyy'}}
</div>
</div>
</div>
</div>
<div class="datepicker-calendar"
[ngClass]="config.bodyClasses">
<div class="row col datepicker-controls">
<button (click)="prevMonth()" [disabled]="previousDisabled"
ion-button=""
class="disable-hover button button-ios button-default button-default-ios">
<span class="button-inner">
<ion-icon name="arrow-back" role="img"
class="icon icon-ios ion-ios-arrow-back" aria-label="arrow-back" ng-reflect-name="arrow-back">
</ion-icon></span>
<div class="button-effect"></div>
</button>
<select title="Month" name="equiptype" class="form-control" [formControl]="monthChanged" [(ngModel)]="selectedMonth" required>
<option></option>
<option *ngFor="let mon of months" [ngValue]="mon">{{mon}}</option>
</select>
<select title="Month" name="equiptype" class="form-control" [formControl]="yearChanged" [(ngModel)]="selectedYear" required>
<option></option>
<option *ngFor="let yea of yearsMaxMin" [ngValue]="yea">{{yea}}</option>
</select>
<button (click)="nextMonth()" [disabled]="nextDisabled"
ion-button=""
class="disable-hover button button-ios button-default button-default-ios">
<span class="button-inner">
<ion-icon name="arrow-forward" role="img"
class="icon icon-ios ion-ios-arrow-forward" aria-label="arrow-forward" ng-reflect-name="arrow-forward">
</ion-icon></span>
<div class="button-effect"></div>
</button>
</div>
<div class="weekdays-row row">
<span class="col calendar-cell"
*ngFor="let dayOfWeek of weekdays">
{{limitTo(dayOfWeek, 3)}}
</span>
</div>
<div class="calendar-wrapper">
<div class="row calendar-row"
*ngFor="let week of rows;let i = index;">
<span class="col calendar-cell"
*ngFor="let day of cols;let j=index;"
[ngClass]="{
'datepicker-date-col': getDate(i, j) !== undefined,
'datepicker-selected': isSelectedDate(getDate(i, j)),
'datepicker-current' : isActualDate(getDate(i, j)),
'datepicker-disabled': isDisabled(getDate(i, j))
}"
(click)="selectDate(getDate(i, j))">
{{getDate(i, j) | date:'d'}}
</span>
</div>
</div>
</div>
<div class="datepicker-footer">
<button (click)="onCancel($event)"
ion-button=""
class="button button-clear button-small col-offset-33 disable-hover button button-ios button-default button-default-ios">
<span class="button-inner">{{config.cancelText || 'Cancel'}}</span>
<div class="button-effect"></div>
</button>
<button (click)="onDone($event)"
ion-button=""
class="button button-clear button-small disable-hover button button-ios button-default button-default-ios">
<span class="button-inner">{{config.okText || 'OK'}}</span>
<div class="button-effect"></div>
</button>
</div>
</div>
`,
styles: [`
ionic2-datepicker .datepicker-wrapper {
height: 100%;
background-color: white;
display: flex;
flex-direction: column;
justify-content: space-between;
}
ionic2-datepicker .datepicker-wrapper .datepicker-header {
color: white;
background-color: #009688;
display: flex;
flex-flow: column;
height: 35%;
}
ionic2-datepicker .datepicker-wrapper .datepicker-header .date-header {
display: flex;
flex-flow: column;
text-align: center;
}
ionic2-datepicker .datepicker-wrapper .datepicker-header .date-header .datepicker-day-of-month {
font-size: 60px;
font-weight: 700;
}
ionic2-datepicker .datepicker-wrapper .datepicker-header .date-header .datepicker-year, ionic2-datepicker .datepicker-wrapper .datepicker-header .date-header .datepicker-month {
font-size: 14px;
margin-top: 10px;
margin-bottom: 10px;
}
ionic2-datepicker .datepicker-wrapper .datepicker-header .weekday-header {
padding: 8px 10px;
background-color: #008d7f;
}
ionic2-datepicker .datepicker-wrapper .datepicker-header .weekday-header .weekday-title {
font-weight: bold;
text-align: center;
}
ionic2-datepicker .weekdays-row {
text-align: center;
}
ionic2-datepicker .datepicker-calendar {
height: calc(100% - (35% + 60px));
}
ionic2-datepicker .datepicker-calendar .datepicker-controls {
align-items: center;
justify-content: space-between;
}
ionic2-datepicker .datepicker-calendar .calendar-wrapper {
height: calc(100% - 60px - 40px);
display: flex;
flex-direction: column;
justify-content: space-around;
}
ionic2-datepicker .datepicker-calendar .calendar-wrapper .datepicker-mark {
background-color: #5b6c6b;
border-radius: 20px;
}
ionic2-datepicker .datepicker-calendar .calendar-wrapper .datepicker-selected {
background-color: #b6d9d6;
border-radius: 20px;
}
ionic2-datepicker .datepicker-calendar .calendar-wrapper .datepicker-current {
color: #3caa9f;
border-radius: 20px;
}
ionic2-datepicker .datepicker-calendar .calendar-wrapper .datepicker-disabled {
color: #aaaaaa;
}
ionic2-datepicker .datepicker-calendar .calendar-wrapper .calendar-cell {
flex-flow: row wrap;
text-align: center;
}
ionic2-datepicker .datepicker-footer {
display: flex;
justify-content: space-between;
height: 60px;
}
ionic2-datepicker .datepicker-footer button {
width: 100%;
}
`],
selector: 'ionic2-datepicker',
encapsulation: ViewEncapsulation.None,
})
export class DatePickerComponent {
public config: {
okText: string,
cancelText: string,
min: Date,
max: Date,
ionChanged: EventEmitter<Date>,
ionSelected: EventEmitter<Date>,
ionCanceled: EventEmitter<void>,
headerClasses: string[],
bodyClasses: string[],
date: Date,
disabledDates: Date[],
markDates: Date[],
showMaxAndMin: boolean;
};
public selectedDate: Date = new Date();
public dateList: Date[];
public cols: number[];
public rows: number[];
public weekdays: string[];
public months: string[];
public years: string[];
public active: boolean = false;
private tempDate: Date;
private today: Date = new Date();
public yearsMaxMin: number[];
public selectedMonth;
public selectedYear;
public monthChanged: FormControl;
public yearChanged: FormControl;
public nextDisabled: boolean = false;
public previousDisabled: boolean = false;
private maxYear: number;
private minYear: number;
constructor(public viewCtrl: ViewController,
public navParams: NavParams,
public DatepickerService: DateService) {
this.config = this.navParams.data;
this.selectedDate = this.navParams.data.date;
this.initialize();
}
/**
* @function initialize - Initializes date variables
*/
public initialize(): void {
this.tempDate = this.selectedDate;
this.createDateList(this.selectedDate);
this.weekdays = this.DatepickerService.getDaysOfWeek();
this.months = this.DatepickerService.getMonths();
this.years = this.DatepickerService.getYears();
this.initSelectBoxes();
this.initSelectBoxListener();
}
/**
* initializes the selectbox and considers max and min date
*/
private initSelectBoxes() {
let maxDate = this.config.max;
let minDate = this.config.min;
this.maxYear = Number.parseInt(this.years[this.years.length - 1]);
this.minYear = Number.parseInt(this.years[0]);
if (maxDate) {
this.maxYear = maxDate.getFullYear();
}
if (minDate) {
this.minYear = minDate.getFullYear();
}
this.yearsMaxMin = [];
for (let _minYear = this.minYear; _minYear <= this.maxYear; _minYear++) {
this.yearsMaxMin.push(_minYear);
}
this.selectedMonth = this.getSelectedMonth();
this.selectedYear = this.getSelectedYear();
}
/**
* initializes the listener to change the dategrid if that changes
*/
private initSelectBoxListener() {
this.monthChanged = new FormControl();
this.monthChanged.valueChanges
.subscribe(selectedMonth => {
let monthAsNumber = this.months.indexOf(selectedMonth);
let testDate: Date = new Date(this.tempDate.getTime());
testDate.setMonth(monthAsNumber);
this.tempDate = testDate;
this.createDateList(this.tempDate);
this.checkDisableButtons(monthAsNumber, testDate.getFullYear());
});
this.yearChanged = new FormControl();
this.yearChanged.valueChanges
.subscribe(selectedYear => {
let testDate: Date = new Date(this.tempDate.getTime());
testDate.setFullYear(selectedYear);
this.tempDate = testDate;
this.createDateList(this.tempDate);
this.checkDisableButtons(testDate.getMonth(), selectedYear);
});
}
/**
* checks if the forward/previos buttons should be disabled or not
* @param selectedMonth
* @param selectedYear
*/
checkDisableButtons(selectedMonth, selectedYear) {
this.nextDisabled = selectedMonth == 11 && this.maxYear === selectedYear;
this.previousDisabled = selectedMonth == 0 && this.minYear === selectedYear;
}
/**
* @function createDateList - creates the list of dates
* @param selectedDate - creates the list based on the currently selected date
*/
public createDateList(selectedDate: Date): void {
this.dateList = this.DatepickerService.createDateList(selectedDate);
this.cols = new Array(7);
this.rows = new Array(Math.ceil(this.dateList.length / this.cols.length));
}
/**
* @function getDate - gets the actual date of date from the list of dates
* @param row - the row of the date in a month. For instance 14 date would be 3rd or 2nd row
* @param col - the column of the date in a month. For instance 1 would be on the column of the weekday.
*/
public getDate(row: number, col: number): Date {
/**
* @description The locale en-US is noted for the sake of starting with monday if its in usa
*/
return this.dateList[(row * 7 + col) + ((this.DatepickerService.doesStartFromMonday()) ? 1 : 0)];
}
/**
* @function getDate - gets the actual number of date from the list of dates
* @param row - the row of the date in a month. For instance 14 date would be 3rd or 2nd row
* @param col - the column of the date in a month. For instance 1 would be on the column of the weekday.
*/
public getDateAsDay(row: number, col: number): number {
let date = this.getDate(row, col);
if (date) return date.getDate();
}
/**
* @function isDisabled - Checks whether the date should be disabled or not
* @param date - the date to test against
*/
public isDisabled(date: Date): boolean {
if (!date) return true;
if (this.config.min) {
this.config.min.setHours(0, 0, 0, 0);
if (date < this.config.min) return true;
}
if (this.config.max) {
this.config.max.setHours(0, 0, 0, 0);
if (date > this.config.max) return true;
}
if (this.config.disabledDates) {
return this.config.disabledDates.some(disabledDate =>
this.areEqualDates(new Date(disabledDate), date));
}
return false;
}
public isMark(date: Date): boolean {
if (!date) return false;
if (this.config.markDates) {
return this.config.markDates.some(markDate =>
this.areEqualDates(new Date(markDate), date));
}
return false
}
public isActualDate(date: Date): boolean {
if (!date) return false;
return this.areEqualDates(date, this.today);
}
public isActualMonth(month: number): boolean {
return month === this.today.getMonth();
}
public isActualYear(year: number): boolean {
return year === this.today.getFullYear();
}
public isSelectedDate(date: Date): boolean {
if (!date) return false;
return this.areEqualDates(date, this.selectedDate);
}
public isSelectedMonth(month: number): boolean {
return month === this.tempDate.getMonth();
}
public isSelectedYear(year: number): boolean {
return year === this.tempDate.getFullYear();
}
public selectDate(date: Date): void {
if (this.isDisabled(date)) return;
this.selectedDate = date;
this.selectedDate.setHours(0, 0, 0, 0);
this.tempDate = this.selectedDate;
this.config.ionSelected.emit(this.tempDate);
}
public getSelectedWeekday(): string {
return this.weekdays[this.selectedDate.getDay()];
}
public getSelectedMonth(date?: Date): string {
if (!date) {
return this.months[this.selectedDate.getMonth()];
} else {
return this.months[date.getMonth()];
}
}
public getTempMonth() {
return this.months[this.tempDate.getMonth()];
}
public getTempYear() {
return (this.tempDate || this.selectedDate).getFullYear();
}
public getSelectedDate() {
return (this.selectedDate || new Date()).getDate();
}
public getSelectedYear() {
return (this.selectedDate || new Date()).getFullYear();
}
public onCancel(e: Event) {
if (this.config.date)
this.selectedDate = this.config.date || new Date();
this.config.ionCanceled.emit();
this.viewCtrl.dismiss();
};
public onDone(e: Event) {
this.config.date = this.selectedDate;
this.config.ionChanged.emit(this.config.date);
this.viewCtrl.dismiss();
};
public selectMonthOrYear() {
this.createDateList(this.tempDate);
if (this.isDisabled(this.tempDate)) return;
this.selectedDate = this.tempDate;
}
private areEqualDates(dateA: Date, dateB: Date) {
return dateA.getDate() === dateB.getDate() &&
dateA.getMonth() === dateB.getMonth() &&
dateA.getFullYear() === dateB.getFullYear();
}
public limitTo(arr: Array<string> | string, limit: number): Array<string> | string {
if (this.DatepickerService.locale === 'custom') return arr;
if (this.DatepickerService.locale === 'de') limit = 2;
if (Array.isArray(arr))
return arr.splice(0, limit);
if (this.DatepickerService.locale === 'zh-CN' || this.DatepickerService.locale === 'zh-TW')
arr = arr.replace('星期', '')
return (<string>arr).slice(0, limit);
}
public getMonthRows(): {}[] {
return [];
}
public nextMonth() {
//if (this.max.getMonth() < this.tempDate.getMonth() + 1 && this.min.getFullYear() === this.tempDate.getFullYear()) return;
let testDate: Date = new Date(this.tempDate.getTime());
testDate.setDate(1);
if (testDate.getMonth() === 11) {
testDate.setFullYear(testDate.getFullYear() + 1);
testDate.setMonth(0);
}
else {
testDate.setMonth(testDate.getMonth() + 1);
}
if ((!this.config.max || this.config.max >= testDate) || this.config.showMaxAndMin) {
this.setDateAfterSelection(testDate);
}
}
public prevMonth() {
let testDate: Date = new Date(this.tempDate.getTime());
testDate.setDate(0);
// testDate.setDate(this.tempDate.getDate());
if ((!this.config.min ||
(this.config.min <= testDate)) || this.config.showMaxAndMin) {
this.setDateAfterSelection(testDate);
}
}
/**
* calls to create the days (list/grid) if applicable
* @param {Date} testDate
*/
private setDateAfterSelection(testDate: Date) {
this.tempDate = testDate;
this.createDateList(this.tempDate);
this.selectedMonth = this.getSelectedMonth(this.tempDate);
this.selectedYear = this.tempDate.getFullYear();
this.checkDisableButtons(this.tempDate.getMonth(), this.selectedYear);
}
} | the_stack |
import { PointModel } from './../primitives/point-model';
import { identityMatrix, rotateMatrix, transformPointByMatrix, Matrix } from './../primitives/matrix';
import { Corners } from '../core/elements/drawing-element';
import { DrawingElement } from '../core/elements/drawing-element';
import { Container } from './../core/containers/container';
import { StrokeStyle } from './../core/appearance';
import { TextStyleModel } from './../core/appearance-model';
import { Point } from './../primitives/point';
import { TextElement } from '../core/elements/text-element';
import { rotatePoint } from './base-util';
import { IElement } from '../objects/interface/IElement';
/**
* Implements the drawing functionalities
*/
/** @private */
export function findNearestPoint(reference: PointModel, start: PointModel, end: PointModel): PointModel {
let shortestPoint: PointModel;
let shortest: number = Point.findLength(start, reference);
let shortest1: number = Point.findLength(end, reference);
if (shortest > shortest1) {
shortestPoint = end;
} else {
shortestPoint = start;
}
let angleBWStAndEnd: number = Point.findAngle(start, end);
let angleBWStAndRef: number = Point.findAngle(shortestPoint, reference);
let r: number = Point.findLength(shortestPoint, reference);
let vaAngle: number = angleBWStAndRef + ((angleBWStAndEnd - angleBWStAndRef) * 2);
return {
x:
(shortestPoint.x + r * Math.cos(vaAngle * Math.PI / 180)),
y: (shortestPoint.y + r * Math.sin(vaAngle * Math.PI / 180))
};
}
/** @private */
export function findElementUnderMouse(obj: IElement, position: PointModel, padding?: number): DrawingElement {
return findTargetElement(obj.wrapper, position, padding);
}
/** @private */
export function findTargetElement(container: Container, position: PointModel, padding?: number): DrawingElement {
for (let i: number = container.children.length - 1; i >= 0; i--) {
let element: DrawingElement = container.children[i];
if (element && element.bounds.containsPoint(position, 0)) {
if (element instanceof Container) {
let target: DrawingElement = this.findTargetElement(element, position);
if (target) {
return target;
}
}
if (element.bounds.containsPoint(position, 0)) {
return element;
}
}
}
if (container.bounds.containsPoint(position, padding) && container.style.fill !== 'none') {
return container;
}
return null;
}
/** @private */
export function intersect3(lineUtil1: Segment, lineUtil2: Segment): Intersection {
let point: PointModel = { x: 0, y: 0 };
let l1: Segment = lineUtil1;
let l2: Segment = lineUtil2;
let d: number = (l2.y2 - l2.y1) * (l1.x2 - l1.x1) - (l2.x2 - l2.x1) * (l1.y2 - l1.y1);
let na: number = (l2.x2 - l2.x1) * (l1.y1 - l2.y1) - (l2.y2 - l2.y1) * (l1.x1 - l2.x1);
let nb: number = (l1.x2 - l1.x1) * (l1.y1 - l2.y1) - (l1.y2 - l1.y1) * (l1.x1 - l2.x1);
if (d === 0) {
return { enabled: false, intersectPt: point };
}
let ua: number = na / d;
let ub: number = nb / d;
if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) {
point.x = l1.x1 + (ua * (l1.x2 - l1.x1));
point.y = l1.y1 + (ua * (l1.y2 - l1.y1));
return { enabled: true, intersectPt: point };
}
return { enabled: false, intersectPt: point };
}
/** @private */
export function intersect2(start1: PointModel, end1: PointModel, start2: PointModel, end2: PointModel): PointModel {
let point: PointModel = { x: 0, y: 0 };
let lineUtil1: Segment = getLineSegment(start1.x, start1.y, end1.x, end1.y);
let lineUtil2: Segment = getLineSegment(start2.x, start2.y, end2.x, end2.y);
let line3: Intersection = intersect3(lineUtil1, lineUtil2);
if (line3.enabled) {
return line3.intersectPt;
} else {
return point;
}
}
/** @private */
export function getLineSegment(x1: number, y1: number, x2: number, y2: number): Segment {
return { 'x1': Number(x1) || 0, 'y1': Number(y1) || 0, 'x2': Number(x2) || 0, 'y2': Number(y2) || 0 };
}
/** @private */
export function getPoints(element: DrawingElement, corners: Corners, padding?: number): PointModel[] {
let line: PointModel[] = [];
padding = padding || 0;
let left: PointModel = { x: corners.topLeft.x - padding, y: corners.topLeft.y };
let right: PointModel = { x: corners.topRight.x + padding, y: corners.topRight.y };
let top: PointModel = { x: corners.bottomRight.x, y: corners.bottomRight.y - padding };
let bottom: PointModel = { x: corners.bottomLeft.x, y: corners.bottomLeft.y + padding };
line.push(left);
line.push(right);
line.push(top);
line.push(bottom);
return line;
}
/** @private */
export function getBezierDirection(src: PointModel, tar: PointModel): string {
if (Math.abs(tar.x - src.x) > Math.abs(tar.y - src.y)) {
return src.x < tar.x ? 'right' : 'left';
} else {
return src.y < tar.y ? 'bottom' : 'top';
}
}
/** @private */
export function updateStyle(changedObject: TextStyleModel, target: DrawingElement): void {
//since text style model is the super set of shape style model, we used text style model
let style: TextStyleModel = target.style as TextStyleModel;
let textElement: TextElement = target as TextElement;
for (let key of Object.keys(changedObject)) {
switch (key) {
case 'fill':
style.fill = changedObject.fill;
if (style instanceof StrokeStyle) {
/* tslint:disable:no-string-literal */
style['fill'] = 'transparent';
}
break;
case 'textOverflow':
style.textOverflow = changedObject.textOverflow;
break;
case 'opacity':
style.opacity = changedObject.opacity;
break;
case 'strokeColor':
style.strokeColor = changedObject.strokeColor;
break;
case 'strokeDashArray':
style.strokeDashArray = changedObject.strokeDashArray;
break;
case 'strokeWidth':
style.strokeWidth = changedObject.strokeWidth;
break;
case 'bold':
style.bold = changedObject.bold;
break;
case 'color':
style.color = changedObject.color;
break;
case 'textWrapping':
style.textWrapping = changedObject.textWrapping;
break;
case 'fontFamily':
style.fontFamily = changedObject.fontFamily;
break;
case 'fontSize':
style.fontSize = changedObject.fontSize;
break;
case 'italic':
style.italic = changedObject.italic;
break;
case 'textAlign':
style.textAlign = changedObject.textAlign;
break;
case 'whiteSpace':
style.whiteSpace = changedObject.whiteSpace;
break;
case 'textDecoration':
style.textDecoration = changedObject.textDecoration;
break;
}
}
if (target instanceof TextElement) {
textElement.refreshTextElement();
}
}
/** @private */
export function scaleElement(element: DrawingElement, sw: number, sh: number, refObject: DrawingElement): void {
if (element.width !== undefined && element.height !== undefined) {
element.width *= sw;
element.height *= sh;
}
if (element instanceof Container) {
let matrix: Matrix = identityMatrix();
let width: number = refObject.width || refObject.actualSize.width;
let height: number = refObject.height || refObject.actualSize.height;
if (width !== undefined && height !== undefined) {
let x: number = refObject.offsetX - width * refObject.pivot.x;
let y: number = refObject.offsetY - height * refObject.pivot.y;
let refPoint: PointModel = {
x: x + width * refObject.pivot.x,
y: y + height * refObject.pivot.y
};
refPoint = rotatePoint(refObject.rotateAngle, refObject.offsetX, refObject.offsetY, refPoint);
rotateMatrix(matrix, -refObject.rotateAngle, refPoint.x, refPoint.y);
// scaleMatrix(matrix, sw, sh, refPoint.x, refPoint.y);
rotateMatrix(matrix, refObject.rotateAngle, refPoint.x, refPoint.y);
for (let child of element.children) {
if (child.width !== undefined && child.height !== undefined) {
let newPosition: PointModel = transformPointByMatrix(matrix, { x: child.offsetX, y: child.offsetY });
child.offsetX = newPosition.x;
child.offsetY = newPosition.y;
scaleElement(child, sw, sh, refObject);
}
}
}
}
}
/** @private */
export function contains(mousePosition: PointModel, corner: PointModel, padding: number): boolean {
if (mousePosition.x >= corner.x - padding && mousePosition.x <= corner.x + padding) {
if (mousePosition.y >= corner.y - padding && mousePosition.y <= corner.y + padding) {
return true;
}
}
return false;
}
/** @private */
export function getPoint(
x: number, y: number, w: number, h: number, angle: number, offsetX: number, offsetY: number, cornerPoint: PointModel): PointModel {
let pivot: PointModel = { x: 0, y: 0 };
let trans: Matrix = identityMatrix();
rotateMatrix(trans, angle, offsetX, offsetY);
switch (cornerPoint.x) {
case 0:
switch (cornerPoint.y) {
case 0:
pivot = transformPointByMatrix(trans, ({ x: x, y: y }));
break;
case 0.5:
pivot = transformPointByMatrix(trans, ({ x: x, y: y + h / 2 }));
break;
case 1:
pivot = transformPointByMatrix(trans, ({ x: x, y: y + h }));
break;
}
break;
case 0.5:
switch (cornerPoint.y) {
case 0:
pivot = transformPointByMatrix(trans, ({ x: x + w / 2, y: y }));
break;
case 0.5:
pivot = transformPointByMatrix(trans, ({ x: x + w / 2, y: y + h / 2 }));
break;
case 1:
pivot = transformPointByMatrix(trans, ({ x: x + w / 2, y: y + h }));
break;
}
break;
case 1:
switch (cornerPoint.y) {
case 0:
pivot = transformPointByMatrix(trans, ({ x: x + w, y: y }));
break;
case 0.5:
pivot = transformPointByMatrix(trans, ({ x: x + w, y: y + h / 2 }));
break;
case 1:
pivot = transformPointByMatrix(trans, ({ x: x + w, y: y + h }));
break;
}
break;
}
return { x: pivot.x, y: pivot.y };
}
export interface Segment {
x1: number;
y1: number;
x2: number;
y2: number;
}
/** @private */
export interface Intersection {
enabled: boolean;
intersectPt: PointModel;
}
/** @private */
export interface Info {
ctrlKey?: boolean;
shiftKey?: boolean;
} | the_stack |
import { CircularGauge } from '../circular-gauge';
import { ColorStopModel, GradientPositionModel } from './gradient-model';
import { Property, ChildProperty, Complex, Collection, isNullOrUndefined } from '@syncfusion/ej2-base';
import { GradientColor, LinearGradient as Linear, RadialGradient as Radial } from '@syncfusion/ej2-svg-base';
import { PointerModel, CapModel, NeedleTailModel, RangeModel } from '../axes/axis-model';
import { SvgRenderer } from '@syncfusion/ej2-svg-base';
/**
* Specifies the color information for the gradient in the circular gauge.
*/
export class ColorStop extends ChildProperty<ColorStop> {
/**
* Defines the color to be used in the gradient.
*
* @default '#000000'
*/
@Property('#000000')
public color: string;
/**
* Defines the opacity to be used in the gradient.
*
* @default 1
*/
@Property(1)
public opacity: number;
/**
* Defines the gradient color begin and end in percentage
*
* @default '0%'
*/
@Property('0%')
public offset: string;
/**
* Defines the style of the color stop in the gradient element.
*
* @default ''
*/
@Property('')
public style: string;
}
/**
* Specifies the position in percentage from which the radial gradient must be applied.
*/
export class GradientPosition extends ChildProperty<GradientPosition> {
/**
* Defines the horizontal position in percentage.
*
* @default '0%'
*/
@Property('0%')
public x: string;
/**
* Defines the vertical position in percentage.
*
* @default '0%'
*/
@Property('0%')
public y: string;
}
/**
* This specifies the properties of the linear gradient colors for the circular gauge.
*/
export class LinearGradient extends ChildProperty<LinearGradient> {
/**
* Defines the start value of the linear gradient.
*
* @default ''
*/
@Property(null)
public startValue: string;
/**
* Defines the end value of the linear gradient.
*
* @default ''
*/
@Property(null)
public endValue: string;
/**
* Defines the color range properties for the gradient.
*
*/
@Collection<ColorStopModel>([{ color: '#000000', opacity: 1, offset: '0%', style: '' }], ColorStop)
public colorStop: ColorStopModel[];
}
/**
* This specifies the properties of the radial gradient colors for the circular gauge.
*/
export class RadialGradient extends ChildProperty<RadialGradient> {
/**
* Defines the radius of the radial gradient in percentage.
*
* @default '0%'
*/
@Property('0%')
public radius: string;
/**
* Defines the outer circle of the radial gradient.
*/
@Complex<GradientPositionModel>({ x: '0%', y: '0%' }, GradientPosition)
public outerPosition: GradientPositionModel;
/**
* Defines the inner circle of the radial gradient.
*/
@Complex<GradientPositionModel>({ x: '0%', y: '0%' }, GradientPosition)
public innerPosition: GradientPositionModel;
/**
* Defines the color range properties for the gradient.
*/
@Collection<ColorStopModel>([{ color: '#000000', opacity: 1, offset: '0%', style: '' }], ColorStop)
public colorStop: ColorStopModel[];
}
/**
* Sets and gets the module that enables the gradient option for pointers and ranges.
*
* @hidden
*/
export class Gradient {
private gauge: CircularGauge;
/**
* Constructor for gauge
*
* @param {CircularGauge} gauge - Specifies the instance of the gauge
*/
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
constructor(gauge: CircularGauge) {
this.gauge = gauge;
}
/**
* To get linear gradient string for pointers and ranges
*
* @param { PointerModel | CapModel | NeedleTailModel | RangeModel} element - Specifies the element.
* @param {name} name - Specifies the name of the gradient.
* @param {name} direction - Specifies the gradient position.
* @returns {string} - Returns the string value.
* @private
*/
private calculateLinearGradientPosition(
element: PointerModel | CapModel | NeedleTailModel | RangeModel,
name: string, direction: string
): Linear {
const linearPosition: Linear = {
id: name,
x1: (isNullOrUndefined(element.linearGradient.startValue) && name.indexOf('range') !== -1
? (direction === 'right' ? '100%' : '0%')
: (!isNullOrUndefined(element.linearGradient.startValue) ? ((element.linearGradient.startValue.indexOf('%') === -1 ?
element.linearGradient.startValue :
parseFloat(element.linearGradient.startValue).toString()) + '%') : '0%')),
x2: (isNullOrUndefined(element.linearGradient.endValue) && name.indexOf('range') !== -1 ?
(direction === 'left' ? '100%' : '0%') :
(!isNullOrUndefined(element.linearGradient.endValue) ? ((element.linearGradient.endValue.indexOf('%') === -1 ?
element.linearGradient.endValue : parseFloat(element.linearGradient.endValue).toString()) + '%') : '100%')),
y1: (isNullOrUndefined(element.linearGradient.startValue) && name.indexOf('range') !== -1
? (direction === 'bottom' ? '100%' : '0%') : '0%'),
y2: (isNullOrUndefined(element.linearGradient.endValue) && name.indexOf('range') !== -1
? (direction === 'top' ? '100%' : '0%') : '0%')
};
return linearPosition;
}
/**
* To get linear gradient string for pointers and ranges
*
* @param { PointerModel | CapModel | NeedleTailModel | RangeModel} element - Specifies the element.
* @param {number} index - Specifies the index of the axis.
* @param { string } direction - Specifies the gradient position.
* @param { number } rangeIndex - Specifies the index of the range.
* @returns {string} - Returns the string value.
* @private
*/
private getLinearGradientColor(
element: PointerModel | CapModel | NeedleTailModel | RangeModel,
index : number, direction : string, rangeIndex : number
): string {
const render: SvgRenderer = new SvgRenderer('');
const colors: GradientColor[] = (isNullOrUndefined(element.linearGradient.startValue) &&
isNullOrUndefined(element.linearGradient.endValue) && !isNullOrUndefined(rangeIndex)) ?
this.getCircularGradientColor(element.linearGradient.colorStop, index) :
this.getGradientColor(element.linearGradient.colorStop);
const name: string = (isNullOrUndefined(element.linearGradient.startValue) &&
isNullOrUndefined(element.linearGradient.endValue) && !isNullOrUndefined(rangeIndex)) ?
'_' + this.gauge.svgObject.id + '_range_' +
rangeIndex + '_color_' + index + '_' + 'linearGradient'
: '_' + this.gauge.svgObject.id + '_' + this.gauge.gradientCount + '_' + 'linearGradient';
let gradientPosition: Linear = this.calculateLinearGradientPosition(element, name, direction);
gradientPosition = {
id: gradientPosition.id,
x1: gradientPosition.x1,
x2: gradientPosition.x2,
y1: gradientPosition.y1,
y2: gradientPosition.y2
};
const def: Element = render.drawGradient('linearGradient', gradientPosition, colors);
this.gauge.svgObject.appendChild(def);
return 'url(#' + name + ')';
}
// eslint-disable-next-line valid-jsdoc
/**
* To get color, opacity, offset and style for circular gradient path.
*
* @private
*/
private getCircularGradientColor(colorStop: ColorStopModel[], index : number): GradientColor[] {
const colors: GradientColor[] = []; let colorIndex : number = index;
for (let j: number = colorIndex; j < (index === (colorStop.length - 1) ? index + 1 : index + 2); j++) {
const color: GradientColor = {
color: colorStop[j].color,
colorStop: colorStop[j].offset,
opacity: colorStop[j].opacity ? colorStop[j].opacity.toString() : '1',
style: colorStop[j].style
};
colors.push(color);
colorIndex++;
}
return colors;
}
/**
* To get the radial gradient string.
*
* @param {PointerModel | CapModel | NeedleTailModel | RangeModel} element - Specifies the element.
* @returns {string} - Returns the string.
* @private
*/
private getRadialGradientColor(element: PointerModel | CapModel | NeedleTailModel | RangeModel): string {
const render: SvgRenderer = new SvgRenderer('');
const colors: GradientColor[] = this.getGradientColor(element.radialGradient.colorStop);
const name: string = '_' + this.gauge.svgObject.id + '_' + this.gauge.gradientCount + '_' + 'radialGradient';
const gradientPosition: Radial = {
id: name,
r: (element.radialGradient.radius.indexOf('%') === -1 ?
element.radialGradient.radius :
parseFloat(element.radialGradient.radius).toString()) + '%',
cx: (element.radialGradient.outerPosition.x.indexOf('%') === -1 ?
element.radialGradient.outerPosition.x :
parseFloat(element.radialGradient.outerPosition.x).toString()) + '%',
cy: (element.radialGradient.outerPosition.y.indexOf('%') === -1 ?
element.radialGradient.outerPosition.y :
parseFloat(element.radialGradient.outerPosition.y).toString()) + '%',
fx: (element.radialGradient.innerPosition.x.indexOf('%') === -1 ?
element.radialGradient.innerPosition.x :
parseFloat(element.radialGradient.innerPosition.x).toString()) + '%',
fy: (element.radialGradient.innerPosition.y.indexOf('%') === -1 ?
element.radialGradient.innerPosition.y :
parseFloat(element.radialGradient.innerPosition.y).toString()) + '%'
};
const def: Element = render.drawGradient('radialGradient', gradientPosition, colors);
this.gauge.svgObject.appendChild(def);
return 'url(#' + name + ')';
}
/**
* To get color, opacity, offset and style.
*
* @param { ColorStopModel[]} colorStop - Specifies the color stop.
* @returns {GradientColor[]} - Returns the gradientColor.
* @private
*/
private getGradientColor(colorStop: ColorStopModel[]): GradientColor[] {
const colors: GradientColor[] = [];
for (let j: number = 0; j < colorStop.length; j++) {
const color: GradientColor = {
color: colorStop[j].color,
colorStop: colorStop[j].offset,
opacity: colorStop[j].opacity ? colorStop[j].opacity.toString() : '1',
style: colorStop[j].style
};
colors.push(color);
}
return colors;
}
// eslint-disable-next-line valid-jsdoc
/**
* To get a gradient color string
*
* @param {PointerModel | CapModel | NeedleTailModel | RangeModel} element - Specifies the element.
* @returns {string} - Returns the string
* @private
*/
public getGradientColorString(
element: PointerModel | CapModel | NeedleTailModel | RangeModel,
index?: number, direction?: string, rangeIndex?: number
): string {
let gradientColor: string;
if ((element.linearGradient && !isNullOrUndefined(element.linearGradient.colorStop)) ||
(element.radialGradient && !isNullOrUndefined(element.radialGradient.colorStop))) {
if (element.linearGradient) {
gradientColor = this.getLinearGradientColor(element, index, direction, rangeIndex);
} else {
gradientColor = this.getRadialGradientColor(element);
}
this.gauge.gradientCount = this.gauge.gradientCount + 1;
} else {
return null;
}
return gradientColor;
}
protected getModuleName(): string {
// Returns te module name
return 'Gradient';
}
/**
* To destroy the Gradient.
*
* @param {CircularGauge} gauge - Specifies the instance of the gauge.
* @returns {void}
* @private
*/
public destroy(gauge: CircularGauge): void {
// Destroy method performed here
}
} | the_stack |
import { AllowedOperator, FieldFilterRowData, FieldFilterRowSettings } from '../common/FieldFilterContracts';
import { WorkItemField } from 'TFS/WorkItemTracking/Contracts';
import { ConfigurationContext } from 'VSS/Common/Contracts/Platform';
import { Widget } from '../widget/Widget';
import { AnalyticsWidgetSettings, WidgetSettings } from '../Common/WidgetSettings';
import { AggregationMode, Aggregation, AggregationConfigurationState} from '../Common/AggregationContracts';
import * as Q from 'q';
import * as React from 'react';
import { Props, State, ComponentBase, ActionsBase, ActionCreator } from "../components/FluxTypes";
import { Project, Team, WorkItemTypeField } from "../data/AnalyticsTypes";
import { Store } from "VSS/Flux/Store";
import { Picker, PickerProps } from "../components/PickerComponent";
import { ODataClient } from "../data/OdataClient";
import { ProjectsQuery, TeamsQuery, WitFieldsQuery } from "../data/CommonQueries";
import { PopularValueQuery, PopularValueQueryOptions, PopularValueQueryResults } from "../data/PopularValueQuery";
import { AnalyticsConfigState, ConfigOptions, QueryConfigProps } from "./AnalyticsConfigInterfaces";
import { getService } from "VSS/Service";
import { CacheableQueryService } from "../data/CacheableQueryService";
import { MetadataQuery, MetadataInformation, hasMetadataMapping, mapReferenceNameForQuery } from "../data/MetadataQuery";
/** Responsible for handling events and translating them into service operations.
*/
export class AnalyticsConfigActionCreator extends ActionCreator<AnalyticsConfigState>{
// Config UI state + Configuration information for the widget
private state: AnalyticsConfigState;
//change notification event method monitored by Config View, which needs to communicate to widget Framework to save & repaint widget.
private onConfigurationChange: (AnalyticsWidgetSettings) => void;
constructor(actions: ActionsBase, configuration: AnalyticsWidgetSettings, onConfigurationChange: (AnalyticsWidgetSettings) => void) {
super(actions);
this.state = {
configOptions: {
projects: [],
teams: [],
types: [],
fields: [],
typeFields: [],
fieldFilter: {
fieldFilterRowValues: [],
addRow: () => {
this.addFieldFilterRow();
}
},
aggregation: {
aggregationModes: this.getAllowedAggregationModes(),
allowedFields: []
}
},
configuration: configuration
} as AnalyticsConfigState;
if (configuration.fields != null) {
configuration.fields.forEach(o => {
this.addFilterRowImpl(o); // Adds the saved field filter data to the current display.
});
}
this.onConfigurationChange = onConfigurationChange;
}
public getInitialState(): AnalyticsConfigState {
return this.state;
}
public requestData(): IPromise<AnalyticsConfigState> {
if (!this.state.configuration.projectId) {
this.state.configuration.projectId = VSS.getWebContext().project.id;
this.state.configuration.teamId = VSS.getWebContext().team.id;
}
if (!this.state.configuration.aggregation) {
this.state.configuration.aggregation = { aggregationMode: AggregationMode.count, displayName: null, queryableName: null, fieldReferenceName: null}
}
return getService(CacheableQueryService).getCacheableQueryResult(new ProjectsQuery()).then(projects => {
this.state.configOptions.projects = projects;
this.notifyListenersOfStateChange(this.state);
//If we have a project selected, keep loading on other data.
let teamPromise = this.state.configuration.projectId ? this.loadTeams(this.state.configuration.projectId) : this.endChain();
return teamPromise.then((teams) => {
return this.loadTypeFields(this.state.configuration.projectId).then(() => {
return this.state;
});
});
});
}
private loadTeams(projectId: string): IPromise<AnalyticsConfigState> {
return getService(CacheableQueryService).getCacheableQueryResult(new TeamsQuery(projectId)).then(teams => {
this.state.configOptions.teams = teams;
if (!this.state.configuration.teamId) {
this.state.configuration.teamId = teams[0].TeamId;
}
this.notifyListenersOfStateChange(this.state);
return this.state;
});
}
private loadTypeFields(projectId: string): IPromise<AnalyticsConfigState> {
return getService(CacheableQueryService).getCacheableQueryResult(new MetadataQuery(projectId, MetadataQuery.WorkItemSnapshot)).then(metadata => {
this.state.configOptions.metadata = metadata;
return getService(CacheableQueryService).getCacheableQueryResult(new WitFieldsQuery(projectId)).then(typeFields => {
this.state.configOptions.typeFields = typeFields;
if (typeFields) {
this.state.configOptions.types = this.filterUniqueTypes(typeFields, projectId);
//if work item type isn't selected, choose a default. For sample purpose, use the first type.
if (this.state.configuration.workItemType == null) {
if (this.state.configOptions.types.length > 0) {
this.state.configuration.workItemType = this.state.configOptions.types[0];
} else {
throw "No WorkItemTypes were found on the active project.";
}
}
this.state.configOptions.fields = this.filterFieldsOfType(typeFields, this.state.configuration.workItemType, projectId, this.state.configOptions.metadata,(o)=>{ return this.isAcceptedFilterField(o);});
this.updateFieldFilterControlOptions();
this.updateAggregationControlOptions();
return this.state;
}
this.notifyListenersOfStateChange(this.state);
return this.state;
});
})
}
private loadSuggestedFieldValues(projectId: string, teamId: string, workItemType: string, fieldName: string): IPromise<AnalyticsConfigState> {
let params = {
projectId: projectId,
teamId: teamId,
workItemType: workItemType,
fieldName: fieldName
};
return getService(CacheableQueryService).getCacheableQueryResult(new PopularValueQuery(params)).then(results => {
let suggestedValues = this.sortAllowedValues(results);
//Update Fields matching the result FieldName.
this.state.configOptions.fieldFilter.fieldFilterRowValues.forEach(o => {
if (o.settings.fieldReferenceName == fieldName) {
o.suggestedValues = suggestedValues;
if (o.settings.value == null) {
o.settings.value = (o.suggestedValues.length > 0) ? o.suggestedValues[0] : null;
}
}
});
return this.state;
});
}
private endChain(): IPromise<AnalyticsConfigState> {
this.notifyListenersOfStateChange(this.state);
let state = Q(this.state);
return state as IPromise<AnalyticsConfigState>;
}
/** Notify the contained UI to update state and signal to the parent config(which will pass a state change event to Dashboard, if the config is valid) */
public notifyListenersOfStateChange(state: AnalyticsConfigState, notifyParentOfConfigChange: boolean = true): void {
this.exposeLatestFilters(state);
super.notifyListenersOfStateChange(state);
if (notifyParentOfConfigChange) {
this.onConfigurationChange(state.configuration);
}
}
/** Get Unique Work Item Types from analytics-supplied list of WorkItemTypeFields. Map out the work Item Type name, filter unique, and sort. */
private filterUniqueTypes(typeFields: WorkItemTypeField[], projectId: string): string[] {
return typeFields
.filter((o) => {
//Operate at project scope.
return o.ProjectSK == projectId;
})
.map((o) => {
return o.WorkItemType
})
.filter((item, i, arr) => {
return arr.indexOf(item) === i;
})
.sort((a, b) => {
return a.localeCompare(b);
});
}
/**
* Returns Fields of specified type in the supplied project, which are interesting to use in a field picker scenario.
*/
private filterFieldsOfType(typeFields: WorkItemTypeField[], activeTypeName: string, projectId: string, metadata: MetadataInformation, isAcceptedField: (WorkItemTypeField)=>boolean) : WorkItemTypeField[]{
return typeFields
.filter((o) => {
//Ensure uniqueness at project-type scope, and filter for supported fields
return o.WorkItemType === activeTypeName
&& o.ProjectSK === projectId
&& hasMetadataMapping(o.FieldReferenceName, metadata)
&& isAcceptedField(o)
})
.sort((a, b) => {
return a.FieldName.localeCompare(b.FieldName);
});
}
private sortAllowedValues(results: PopularValueQueryResults[]): string[] {
//Ensure the values are exposed as sorted strings
return results.map(o => {
return (o.Value != null) ? "" + o.Value : "";
})
.sort((a, b) => { return a.localeCompare(b); });
}
/**
* Filters for accepted filter fields, and discards irrelevant system fields.
* @param field
*/
private isAcceptedFilterField(field: WorkItemTypeField):boolean {
return ((field.FieldType === "String" ||
field.FieldType === "Integer" ||
field.FieldType === "Double")
&& !this.isNoisyField(field));
}
/**
* Filters for accepted Aggregation fields, and discards irrelevant system fields.
* @param field
*/
private isAcceptedAggregationField(field: WorkItemTypeField):boolean {
return ((field.FieldType === "Integer" ||
field.FieldType === "Double")
&& !this.isNoisyField(field));
}
private isNoisyField(field:WorkItemTypeField):boolean{
return (field.FieldName === "Rev" ||
field.FieldName === "ID" ||
field.FieldName === "Title" ||
field.FieldName === "Watermark");
}
/** If a new project was selected, and load information which uses project scoping. */
public setSelectedProject(projectId: string): IPromise<AnalyticsConfigState> {
if (projectId != this.state.configuration.projectId) {
this.state.configuration.projectId = projectId;
return this.loadTeams(projectId).then(() => {
return this.loadTypeFields(projectId);
});
}
}
/** If a new team was selected, and load information which relies on team scoping. */
public setSelectedTeam(teamId: string) {
if (teamId != this.state.configuration.teamId) {
this.state.configuration.teamId = teamId;
this.notifyListenersOfStateChange(this.state);
}
}
/** If a new team was selected, reset all downstream state of project-team, and load information which relies on team scoping. */
public setSelectedWorkItemType(workItemType: string) {
if (workItemType != this.state.configuration.workItemType) {
this.state.configuration.workItemType = workItemType;
this.updateFieldFilterControlOptions();
this.updateAggregationControlOptions();
this.notifyListenersOfStateChange(this.state);
}
}
public setSelectedAggregationMode(mode: AggregationMode) {
if (this.state.configuration.aggregation && mode == this.state.configuration.aggregation.aggregationMode) {
return;
}
this.state.configuration.aggregation = { aggregationMode: mode, displayName: null, queryableName: null, fieldReferenceName: null}
this.notifyListenersOfStateChange(this.state);
}
public setSelectedAggregationValue(field: Aggregation) {
if (this.state.configuration.aggregation && field.fieldReferenceName == this.state.configuration.aggregation.fieldReferenceName) {
return;
}
this.state.configuration.aggregation = field;
this.notifyListenersOfStateChange(this.state);
}
public loadValues(fieldName: string) {
let queryOptions = {
projectId: this.state.configuration.projectId,
teamId: this.state.configuration.teamId,
workItemType: this.state.configuration.workItemType,
fieldName: fieldName
};
return getService(CacheableQueryService).getCacheableQueryResult(new PopularValueQuery(queryOptions));
}
private getAllowedOperators() {
return [{
DisplayText: "=",
value: " eq ",
}, {
DisplayText: "<>",
value: " ne ",
}];
}
private updateFieldFilterControlOptions() {
let fields = this.filterFieldsOfType(this.state.configOptions.typeFields, this.state.configuration.workItemType, this.state.configuration.projectId, this.state.configOptions.metadata, (o)=>{return this.isAcceptedFilterField(o)});
let allowedOperators = this.getAllowedOperators();
//Update the field Pickers to show options relevant to this type.
this.state.configOptions.fieldFilter.fieldFilterRowValues.forEach((o) => {
this.populateFilterRowOptions(o, fields, allowedOperators);
});
}
private updateAggregationControlOptions() {
//Filter the non integer values to get a list of values that can be Summed.
let fields = this.filterFieldsOfType(this.state.configOptions.typeFields, this.state.configuration.workItemType, this.state.configuration.projectId, this.state.configOptions.metadata, (o)=>{return this.isAcceptedAggregationField(o)});
this.state.configOptions.aggregation.allowedFields = fields.map(o => {
return {
aggregationMode: AggregationMode.sum,
displayName: o.FieldName,
fieldReferenceName: o.FieldReferenceName,
queryableName: this.getQueryableAggregationName(o.FieldReferenceName)
}
});
}
private populateFilterRowOptions(rowData: FieldFilterRowData, fields: WorkItemTypeField[], allowedOperators: AllowedOperator[]): void {
//Update field picker to reflect current Type.
rowData.allowedFields = fields;
rowData.allowedOperators = allowedOperators;
if (!rowData.settings.fieldReferenceName || rowData.allowedFields.map(o => o.FieldReferenceName).indexOf(rowData.settings.fieldReferenceName) < 0) {
rowData.settings.fieldReferenceName = fields[0].FieldReferenceName;
rowData.settings.operator = null;
rowData.settings.value = null;
}
//Set up a default operator if not set
if (rowData.settings.fieldReferenceName && rowData.settings.operator == null) {
rowData.settings.operator = allowedOperators[0].value;
}
if (rowData.settings.fieldReferenceName) {
this.loadSuggestedFieldValues(this.state.configuration.projectId, this.state.configuration.teamId, this.state.configuration.workItemType, rowData.settings.fieldReferenceName).then((values) => {
this.notifyListenersOfStateChange(this.state);
});
}
}
/**
* Adds additional rows on the "add row event"
*/
public addFieldFilterRow() {
let row = this.addFilterRowImpl({
fieldType: null,
operator: null,
value: null,
fieldQueryName: null,
fieldReferenceName: null
});
this.notifyListenersOfStateChange(this.state);
}
/**
* Used for creation implementation at load and "Add" event.
*/
private addFilterRowImpl(settings: FieldFilterRowSettings): FieldFilterRowData {
let row = {
allowedFields: this.state.configOptions.fields,
allowedOperators: this.getAllowedOperators(),
suggestedValues: [],
settings: settings,
removeRow: null
} as FieldFilterRowData;
let container = this.state.configOptions.fieldFilter.fieldFilterRowValues;
container.push(row);
row.removeRow = () => {
let position = container.indexOf(row);
this.removeFieldFilterRow(position);
};
row.updateField = (field: WorkItemTypeField) => {
let position = container.indexOf(row);
this.updateFieldFilterFieldState(position, field);
};
row.updateOperator = (operator: string) => {
let position = container.indexOf(row);
this.updateFieldFilterOperatorState(position, operator);
};
row.updateValue = (value: string) => {
let position = container.indexOf(row);
this.updateFieldFilterValueState(position, value);
};
if (this.state.configOptions.typeFields.length && this.state.configOptions.metadata) {
let fields = this.filterFieldsOfType(this.state.configOptions.typeFields, this.state.configuration.workItemType, this.state.configuration.projectId, this.state.configOptions.metadata, (o)=>{return this.isAcceptedFilterField(o)});
let allowedOperators = this.getAllowedOperators();
this.populateFilterRowOptions(row, fields, allowedOperators);
}
return row;
}
public removeFieldFilterRow(rowIndex: number) {
this.state.configOptions.fieldFilter.fieldFilterRowValues.splice(rowIndex, 1);
this.notifyListenersOfStateChange(this.state);
}
/**
* Update visual state of filters to reflect new field, and then ensure the value picker settings for the current state is up to date.
*/
public updateFieldFilterFieldState(rowIndex: number, field: WorkItemTypeField) {
let row = this.state.configOptions.fieldFilter.fieldFilterRowValues[rowIndex];
let priorState = row.settings.fieldReferenceName;
row.settings.fieldReferenceName = field.FieldReferenceName;
row.settings.fieldType = field.FieldType;
row.settings.value = null;
this.notifyListenersOfStateChange(this.state);
return getService(CacheableQueryService).getCacheableQueryResult(new MetadataQuery(this.state.configuration.projectId, MetadataQuery.WorkItemSnapshot)).then(metadata => {
row.settings.fieldQueryName = mapReferenceNameForQuery(field.FieldReferenceName, metadata);
if (priorState != field.FieldReferenceName) {
this.loadSuggestedFieldValues(this.state.configuration.projectId, this.state.configuration.teamId, this.state.configuration.workItemType, field.FieldReferenceName).then(() => {
this.notifyListenersOfStateChange(this.state);
})
}
});
}
/**
* Update state to reflect new operator selection
*/
public updateFieldFilterOperatorState(rowIndex: number, operator: string) {
let settings = this.state.configOptions.fieldFilter.fieldFilterRowValues[rowIndex].settings;
settings.operator = operator;
this.notifyListenersOfStateChange(this.state);
}
/**
* Update state to reflect new value selection
*/
public updateFieldFilterValueState(rowIndex: number, value: string) {
let settings = this.state.configOptions.fieldFilter.fieldFilterRowValues[rowIndex].settings;
settings.value = value;
this.notifyListenersOfStateChange(this.state);
}
private exposeLatestFilters(state) {
this.state.configuration.fields = [];
this.state.configOptions.fieldFilter.fieldFilterRowValues.forEach((o, i) => {
this.state.configuration.fields[i] = o.settings;
})
}
private getQueryableAggregationName(fieldReferenceName: string): string {
return this.state.configOptions.metadata.fieldMappings.find(o => o.referenceName == fieldReferenceName).queryableName;
}
private getAllowedAggregationModes(): string[] {
return [AggregationMode.count.toString(), AggregationMode.sum.toString()];
}
} | the_stack |
module BABYLONX {
export class CompoundShader {
private _scene;
private _shader;
private _params;
private _texGen;
private _texMix;
constructor(scene,texGen,texMix,{stepx=0.005,stepy=0.005,invR=false,invG=false,balance=0.9,invH=false,filter=true,level=7,strength=0.5,time=1} = {}) {
this._scene = scene;
this._texGen = texGen;
this._texMix = texMix;
var pars = {
stepx: stepx, stepy: stepy, iR: invR ? 1 : -1, iG: invG ? -1 : 1, balance: balance, iH: invH ? -1 : 1, fSobel: filter ? 1 : 0, strength: strength, level: level, time: time
};
this._params = pars;
this.init();
}
init() {
var opacity1 = 1.0;
var opacity2 = 1.0;
var shader = new BABYLONX.ShaderBuilder()
.SetUniform('dyTxt', 'sampler2D')
.SetUniform('mxTxt', 'sampler2D')
.SetUniform('stepx', 'float')
.SetUniform('stepy', 'float')
.SetUniform('invR', 'float')
.SetUniform('invG', 'float')
.SetUniform('balance', 'float')
.SetUniform('invH', 'float')
.SetUniform('fSobel', 'float')
.SetUniform('level', 'float')
.SetUniform('strength', 'float')
.Multi([{
result: BABYLONX.Helper().Map({ index: 'mxTxt' })
.InLine`result=vec4((1.0-balance) *result.xyz, 1.0);`
.Build(), opacity: opacity1
},
{
result: BABYLONX.Helper()
.Map({ index: 'dyTxt' })
//.Map({ path: path, alpha: true }, 1.)
//.Transparency()
.InLine(`
float invertR=invR;
float invertG=invG;
float invertH=invH;
//float pulse=*sin(time) *sin(time);
//float level=7.;
//float strength=1.5;
//float dz= filterdz;//500.;
float dz=1.0/strength*(1.+pow(2.0, level));
//int type=1.-fSobel;
float type=fSobel;
vec2 step=vec2(stepx,stepy);// vec2(0.01, 0.01);
vec2 vUv=vec2(vuv);
vec2 tlv = vec2(vUv.x - step.x, vUv.y + step.y );
vec2 lv = vec2(vUv.x - step.x, vUv.y );
vec2 blv = vec2(vUv.x - step.x, vUv.y - step.y);
vec2 tv = vec2(vUv.x , vUv.y + step.y );
vec2 bv = vec2(vUv.x , vUv.y - step.y);
vec2 trv = vec2(vUv.x + step.x, vUv.y + step.y );
vec2 rv = vec2(vUv.x + step.x, vUv.y );
vec2 brv = vec2(vUv.x +step.x, vUv.y -step.y);
tlv = vec2(tlv.x >= 0.0 ? tlv.x : (1.0 + tlv.x), tlv.y >= 0.0 ? tlv.y : (1.0 + tlv.y));
tlv = vec2(tlv.x < 1.0 ? tlv.x : (tlv.x - 1.0 ), tlv.y < 1.0 ? tlv.y : (tlv.y - 1.0 ));
lv = vec2( lv.x >= 0.0 ? lv.x : (1.0 + lv.x), lv.y >= 0.0 ? lv.y : (1.0 + lv.y));
lv = vec2( lv.x < 1.0 ? lv.x : ( lv.x - 1.0 ), lv.y < 1.0 ? lv.y : ( lv.y - 1.0 ));
blv = vec2(blv.x >= 0.0 ? blv.x : (1.0 + blv.x), blv.y >= 0.0 ? blv.y : (1.0 + blv.y));
blv = vec2(blv.x < 1.0 ? blv.x : (blv.x - 1.0 ), blv.y < 1.0 ? blv.y : (blv.y - 1.0 ));
tv = vec2( tv.x >= 0.0 ? tv.x : (1.0 + tv.x), tv.y >= 0.0 ? tv.y : (1.0 + tv.y));
tv = vec2( tv.x < 1.0 ? tv.x : ( tv.x - 1.0 ), tv.y < 1.0 ? tv.y : ( tv.y - 1.0 ));
bv = vec2( bv.x >= 0.0 ? bv.x : (1.0 + bv.x), bv.y >= 0.0 ? bv.y : (1.0 + bv.y));
bv = vec2( bv.x < 1.0 ? bv.x : ( bv.x - 1.0 ), bv.y < 1.0 ? bv.y : ( bv.y - 1.0 ));
trv = vec2(trv.x >= 0.0 ? trv.x : (1.0 + trv.x), trv.y >= 0.0 ? trv.y : (1.0 + trv.y));
trv = vec2(trv.x < 1.0 ? trv.x : (trv.x - 1.0 ), trv.y < 1.0 ? trv.y : (trv.y - 1.0 ));
rv = vec2( rv.x >= 0.0 ? rv.x : (1.0 + rv.x), rv.y >= 0.0 ? rv.y : (1.0 + rv.y));
rv = vec2( rv.x < 1.0 ? rv.x : ( rv.x - 1.0 ), rv.y < 1.0 ? rv.y : ( rv.y - 1.0 ));
brv = vec2(brv.x >= 0.0 ? brv.x : (1.0 + brv.x), brv.y >= 0.0 ? brv.y : (1.0 + brv.y));
brv = vec2(brv.x < 1.0 ? brv.x : (brv.x - 1.0 ), brv.y < 1.0 ? brv.y : (brv.y - 1.0 ));
float tl = abs(texture2D(dyTxt, tlv).r);
float l = abs(texture2D(dyTxt, lv).r);
float bl = abs(texture2D(dyTxt, blv).r);
float t = abs(texture2D(dyTxt, tv).r);
float b = abs(texture2D(dyTxt, bv).r);
float tr = abs(texture2D(dyTxt, trv).r);
float r = abs(texture2D(dyTxt, rv).r);
float br = abs(texture2D(dyTxt, brv).r);
float dx = 0.0, dy = 0.0;
//if(type == 0){ // Sobel
if(type > 0.5) { // Sobel
dx = tl +l*2.0 +bl -tr -r*2.0 -br;
dy = tl + t*2.0 + tr - bl - b*2.0 - br;
}
else{ // Scharr
dx = tl*3.0 + l*10.0 + bl*3.0 - tr*3.0 - r*10.0 - br*3.0;
dy = tl*3.0 + t*10.0 + tr*3.0 - bl*3.0 - b*10.0 - br*3.0;
}
vec4 normal = vec4(normalize(vec3(dx * invertR * invertH * 255.0, dy * invertG * invertH * 255.0, dz)), texture2D(dyTxt, vUv).a);
vec4 res=vec4(normal.xyz * 0.5 +0.5, 1.0);
vec3 nrm1 = vec3(normalize(nrm-(normalize(res.xyz) *2.0-1.) *0.5));
//result = vec4(normal.xy * 0.5 +0.5, normal.zw);
//*
vec4 specular = vec4(normal.xy * 0.5 +0.5, normal.zw);
vec4 textureColor =texture2D(dyTxt, vuv);
textureColor.a = 1.;
result= clamp(2.*textureColor*specular*balance, 0.0, 1.);
//result= vec4(vec3(vuv.x,vuv.y,0.),1.);
//result.w=0.7;
//*/
`)
.Light({ phonge: .025195, specular: 15.5, normal: 'nrm1', direction: 'camera' })
//.Light({ darkColorMode:true,specularPower: .01, phonge: 1., color: { r: 0.8, g: 0.8, b: 0.8, a: 1. }, specular: 1.0, normal: BABYLONX.Normals.Flat, direction: 'camera' })
.Build(), opacity: opacity2
}], false).BuildMaterial(this._scene);
shader.setTexture('dyTxt', this._texGen);
shader.setTexture('mxTxt', this._texMix);
shader.setFloat('stepx', this._params.stepx);
shader.setFloat('stepy', this._params.stepy);
shader.setFloat('invR', this._params.iR);
shader.setFloat('invG', this._params.iG);
shader.setFloat('balance', this._params.balance);
shader.setFloat('invH', this._params.iH);
shader.setFloat('fSobel', this._params.fSobel);
shader.setFloat('level', this._params.level);
shader.setFloat('strength', this._params.strength);
shader.setFloat('time', this._params.time);
this._shader = shader;
var me = this;
Object.defineProperty(this._shader, 'shader', {
get: function () {
return me;
}
});
return this;
}
updateParams(params) {
if (params.stepx != null) this._params.stepx = params.stepx;
if (params.stepy != null) this._params.stepy = params.stepy;
if (params.balance != null) this._params.balance = params.balance;
if (params.strength != null) this._params.strength = params.strength;
if (params.level != null) this._params.level = params.level;
if (params.time != null) this._params.time = params.time;
if (params.invR != null) this._params.iR = params.invR ? 1 : -1;
if (params.invG != null) this._params.iG = params.invG ? 1 : -1;
if (params.invH != null) this._params.iH = params.invH ? 1 : -1;
if (params.filter != null) this._params.fSobel = params.filter ? 1 : 0;
//this._shader.setTexture('dyTxt', params.texGen);
//this._shader.setTexture('mxTxt', params.texMix);
this._shader.setFloat('stepx', this._params.stepx);
this._shader.setFloat('stepy', this._params.stepy);
this._shader.setFloat('invR', this._params.iR);
this._shader.setFloat('invG', this._params.iG);
this._shader.setFloat('balance', this._params.balance);
this._shader.setFloat('invH', this._params.iH);
this._shader.setFloat('fSobel', this._params.fSobel);
this._shader.setFloat('level', this._params.level);
this._shader.setFloat('strength', this._params.strength);
this._shader.setFloat('time', this._params.time);
return this;
}
updateGenTex(texGen) {
this._texGen = texGen;
this._shader.setTexture('dyTxt', this._texGen);
return this;
}
updateMixTex(texMix) {
this._texMix = texMix;
this._shader.setTexture('mxTxt', this._texMix);
return this;
}
get material() {
return this._shader;
}
get scene() {
return this.scene;
}
}
} | the_stack |
import {
ChannelDispute,
CoreChannelState,
CoreTransferState,
FullChannelState,
FullTransferState,
GetTransfersFilterOpts,
IChainServiceStore,
IEngineStore,
ResolveUpdateDetails,
StoredTransaction,
StoredTransactionAttempt,
StoredTransactionReceipt,
StoredTransactionStatus,
TransactionReason,
TransferDispute,
UpdateType,
WithdrawCommitmentJson,
} from "@connext/vector-types";
import { TransactionResponse, TransactionReceipt } from "@ethersproject/providers";
import Dexie, { DexieOptions } from "dexie";
import { BaseLogger } from "pino";
type StoredTransfer = FullTransferState & {
createUpdateNonce: number;
resolveUpdateNonce: number;
routingId: string;
createdAt: Date;
};
const storedTransferToTransferState = (stored: StoredTransfer): FullTransferState => {
const transfer: any = stored;
delete transfer.createUpdateNonce;
delete transfer.resolveUpdateNonce;
delete transfer.routingId;
delete transfer.createdAt;
return transfer as FullTransferState;
};
const getStoreName = (publicIdentifier: string) => {
return `${publicIdentifier}-store`;
};
const NON_NAMESPACED_STORE = "VectorIndexedDBDatabase";
class VectorIndexedDBDatabase extends Dexie {
channels: Dexie.Table<FullChannelState, string>;
transfers: Dexie.Table<StoredTransfer, string>;
transactions: Dexie.Table<StoredTransaction, string>;
withdrawCommitment: Dexie.Table<WithdrawCommitmentJson & { transferId: string }, string>;
channelDisputes: Dexie.Table<
{ channelAddress: string; channelDispute: ChannelDispute; disputedChannel?: CoreChannelState },
string
>;
transferDisputes: Dexie.Table<
{ transferId: string; transferDispute: TransferDispute; disputedTransfer?: CoreTransferState },
string
>;
values: Dexie.Table<any, string>;
// database name
name: string;
constructor(
name: string,
// eslint-disable-next-line @typescript-eslint/ban-types
indexedDB?: { open: Function },
// eslint-disable-next-line @typescript-eslint/ban-types
idbKeyRange?: { bound: Function; lowerBound: Function; upperBound: Function },
) {
let options: DexieOptions | undefined;
if (indexedDB && idbKeyRange) {
options = { indexedDB, IDBKeyRange: idbKeyRange };
}
super(name, options);
this.version(1).stores({
channels:
"channelAddress, [aliceIdentifier+bobIdentifier+networkContext.chainId], [alice+bob+networkContext.chainId]",
transfers:
"transferId, [routingId+channelAddress], [createUpdateNonce+channelAddress], [resolveUpdateNonce+channelAddress], [transferResolver+channelAddress]",
transactions: "transactionHash",
withdrawCommitment: "transferId",
values: "key",
});
this.version(2)
.stores({
channels:
"channelAddress, [aliceIdentifier+bobIdentifier+networkContext.chainId], [alice+bob+networkContext.chainId], createdAt",
transfers:
"transferId, [routingId+channelAddress], [createUpdateNonce+channelAddress], [resolveUpdateNonce+channelAddress], [transferResolver+channelAddress], createdAt, resolveUpdateNonce, channelAddress",
})
.upgrade((tx) => {
// An upgrade function for version 3 will upgrade data based on version 2.
tx.table("channels")
.toCollection()
.modify((channel) => {
channel.createdAt = new Date();
});
tx.table("transfers")
.toCollection()
.modify((transfer) => {
transfer.createdAt = new Date();
});
});
this.version(3).stores({
withdrawCommitment: "transferId,transactionHash",
});
this.version(4).stores({
channelDisputes: "channelAddress",
transferDisputes: "transferId",
});
// Using a temp table (transactions2) to migrate which column is the primary key
// (transactionHash -> id)
this.version(5)
.stores({
withdrawCommitment: "transferId,channelAddress,transactionHash",
transactions2: "id, transactionHash",
})
.upgrade(async (tx) => {
const transactions = await tx.table("transactions").toArray();
await tx.table("transactions2").bulkAdd(transactions);
});
this.version(6).stores({
transactions: null,
});
this.version(7)
.stores({
transactions: "id, transactionHash",
})
.upgrade(async (tx) => {
const transactions2 = await tx.table("transactions2").toArray();
await tx.table("transactions").bulkAdd(transactions2);
});
this.version(8).stores({
transactions2: null,
});
this.version(9).stores({
updates: "id.id, [channelAddress+nonce]",
});
this.channels = this.table("channels");
this.transfers = this.table("transfers");
this.transactions = this.table("transactions");
this.withdrawCommitment = this.table("withdrawCommitment");
this.channelDisputes = this.table("channelDisputes");
this.transferDisputes = this.table("transferDisputes");
this.values = this.table("values");
this.name = name;
}
}
export class BrowserStore implements IEngineStore, IChainServiceStore {
private db: VectorIndexedDBDatabase;
// NOTE: this could be private, but makes it difficult to test because
// you can't mock the `Dexie.exists` call used in the static `create`
// function. However, the constructor should *not* be used when creating
// an instance of the BrowserStore
constructor(
private readonly dbName: string,
private readonly log: BaseLogger,
// eslint-disable-next-line @typescript-eslint/ban-types
indexedDB?: { open: Function },
// eslint-disable-next-line @typescript-eslint/ban-types
idbKeyRange?: { bound: Function; lowerBound: Function; upperBound: Function },
) {
this.db = new VectorIndexedDBDatabase(dbName, indexedDB, idbKeyRange);
}
public static async create(
publicIdentifer: string,
log: BaseLogger,
// eslint-disable-next-line @typescript-eslint/ban-types
indexedDB?: { open: Function },
// eslint-disable-next-line @typescript-eslint/ban-types
idbKeyRange?: { bound: Function; lowerBound: Function; upperBound: Function },
): Promise<BrowserStore> {
const name = (await Dexie.exists(NON_NAMESPACED_STORE)) ? NON_NAMESPACED_STORE : getStoreName(publicIdentifer);
const store = new BrowserStore(name, log, indexedDB, idbKeyRange);
await store.connect();
return store;
}
public async connect(): Promise<void> {
await this.db.open();
}
disconnect(): Promise<void> {
return Promise.resolve(this.db.close());
}
getSchemaVersion(): Promise<number | undefined> {
return Promise.resolve(1);
}
updateSchemaVersion(version?: number): Promise<void> {
throw new Error("Method not implemented.");
}
async clear(): Promise<void> {
await this.db.channels.clear();
await this.db.transfers.clear();
await this.db.transactions.clear();
}
// TODO (@jakekidd): Does this belong in utils somewhere? I believe it's only use case is here.
/// Santitize TransactionReceipt for input as StoredTransactionReceipt.
private sanitizeReceipt(receipt: TransactionReceipt): StoredTransactionReceipt {
return {
transactionHash: receipt.transactionHash,
contractAddress: receipt.contractAddress,
transactionIndex: receipt.transactionIndex,
root: receipt.root,
gasUsed: receipt.gasUsed.toString(),
cumulativeGasUsed: receipt.cumulativeGasUsed.toString(),
logsBloom: receipt.logsBloom,
blockHash: receipt.blockHash,
blockNumber: receipt.blockNumber,
logs: receipt.logs.toString(),
byzantium: receipt.byzantium,
status: receipt.status,
} as StoredTransactionReceipt;
}
async saveChannelStateAndTransfers(
channelState: FullChannelState,
activeTransfers: FullTransferState[],
): Promise<void> {
await this.db.transaction("rw", this.db.channels, this.db.transfers, async () => {
// remove all "active" transfers
const currActive = await this.getActiveTransfers(channelState.channelAddress);
// TODO: can we "unassociate" them without deleting them? GH #431
await this.db.transfers.bulkDelete(currActive.map((t) => t.transferId));
// save channel
await this.db.channels.put(channelState);
// save all active transfers
await this.db.transfers.bulkPut(
activeTransfers.map((transfer) => {
return {
...transfer,
createUpdateNonce: transfer.channelNonce + 1,
resolveUpdateNonce: 0,
routingId: transfer?.meta?.routingId,
createdAt: new Date(),
};
}),
);
});
}
async saveChannelState(channelState: FullChannelState, transfer?: FullTransferState): Promise<void> {
await this.db.transaction("rw", this.db.channels, this.db.transfers, async () => {
await this.db.channels.put(channelState);
if (channelState.latestUpdate.type === UpdateType.create) {
await this.db.transfers.put({
...transfer!,
createUpdateNonce: channelState.latestUpdate.nonce,
resolveUpdateNonce: 0,
routingId: transfer?.meta?.routingId, // allow indexing on routingId
createdAt: new Date(),
});
} else if (channelState.latestUpdate.type === UpdateType.resolve) {
await this.db.transfers.update((channelState.latestUpdate.details as ResolveUpdateDetails).transferId, {
resolveUpdateNonce: channelState.latestUpdate.nonce,
transferResolver: (channelState.latestUpdate.details as ResolveUpdateDetails).transferResolver,
} as Partial<StoredTransfer>);
}
});
}
async getChannelStates(): Promise<FullChannelState[]> {
const channels = await this.db.channels.toArray();
return channels;
}
async getChannelState(channelAddress: string): Promise<FullChannelState | undefined> {
const channel = await this.db.channels.get(channelAddress);
return channel;
}
async getChannelStateByParticipants(
publicIdentifierA: string,
publicIdentifierB: string,
chainId: number,
): Promise<FullChannelState | undefined> {
const channel = await this.db.channels
.where("[aliceIdentifier+bobIdentifier+networkContext.chainId]")
.equals([publicIdentifierA, publicIdentifierB, chainId])
.or("[aliceIdentifier+bobIdentifier+networkContext.chainId]")
.equals([publicIdentifierB, publicIdentifierA, chainId])
.first();
return channel;
}
async getActiveTransfers(channelAddress: string): Promise<FullTransferState[]> {
const collection = this.db.transfers.where("[resolveUpdateNonce+channelAddress]").equals([0, channelAddress]);
const transfers = await collection.toArray();
return transfers.map(storedTransferToTransferState);
}
async getTransferState(transferId: string): Promise<FullTransferState | undefined> {
const transfer = await this.db.transfers.get(transferId);
return transfer ? storedTransferToTransferState(transfer) : undefined;
}
async getTransferByRoutingId(channelAddress: string, routingId: string): Promise<FullTransferState | undefined> {
const transfer = await this.db.transfers.get({ channelAddress, routingId });
return transfer ? storedTransferToTransferState(transfer) : undefined;
}
async getTransfersByRoutingId(routingId: string): Promise<FullTransferState[]> {
const transfers = this.db.transfers.where({ routingId });
const ret = await transfers.toArray();
return ret.map(storedTransferToTransferState);
}
async getTransfers(filterOpts?: GetTransfersFilterOpts): Promise<FullTransferState[]> {
const filterQuery: any = [];
if (filterOpts?.channelAddress) {
filterQuery.push({ index: "channelAddress", function: "equals", params: filterOpts.channelAddress });
}
// start and end
if (filterOpts?.startDate && filterOpts.endDate) {
filterQuery.push({ index: "channelAddress", function: "between", params: filterOpts.channelAddress });
} else if (filterOpts?.startDate) {
filterQuery.push({ index: "channelAddress", function: "equals", params: filterOpts.channelAddress });
} else if (filterOpts?.endDate) {
filterQuery.push({ index: "channelAddress", function: "equals", params: filterOpts.channelAddress });
}
let collection = this.db.transfers.toCollection();
if (filterOpts?.channelAddress) {
collection = collection.filter((transfer) => transfer.channelAddress === filterOpts.channelAddress);
}
if (filterOpts?.startDate && filterOpts.endDate) {
collection = collection.filter(
(transfer) => transfer.createdAt >= filterOpts.startDate! && transfer.createdAt <= filterOpts.endDate!,
);
} else if (filterOpts?.startDate) {
collection = collection.filter((transfer) => transfer.createdAt >= filterOpts.startDate!);
} else if (filterOpts?.endDate) {
collection = collection.filter((transfer) => transfer.createdAt <= filterOpts.endDate!);
}
if (filterOpts?.active) {
collection = collection.filter((transfer) => transfer.resolveUpdateNonce === 0);
}
if (filterOpts?.routingId) {
collection = collection.filter((transfer) => transfer.routingId === filterOpts.routingId);
}
if (filterOpts?.transferDefinition) {
collection = collection.filter((transfer) => transfer.transferDefinition === filterOpts.transferDefinition);
}
const transfers = await collection.toArray();
return transfers.map(storedTransferToTransferState);
}
async getTransactionById(onchainTransactionId: string): Promise<StoredTransaction | undefined> {
return await this.db.transactions.get({ id: onchainTransactionId });
}
async getActiveTransactions(): Promise<StoredTransaction[]> {
const tx = await this.db.transactions
.filter((tx) => {
return !tx.receipt && tx.status === StoredTransactionStatus.submitted;
})
.toArray();
return tx;
}
async saveTransactionAttempt(
onchainTransactionId: string,
channelAddress: string,
reason: TransactionReason,
response: TransactionResponse,
): Promise<void> {
// Populate nested attempts array.
let attempts: StoredTransactionAttempt[] = [];
const res = await this.db.transactions.where(":id").equals(onchainTransactionId).first();
if (res) {
attempts = Array.from(res.attempts);
}
attempts.push({
// TransactionResponse fields (defined when submitted)
gasLimit: response.gasLimit.toString(),
gasPrice: response.gasPrice.toString(),
transactionHash: response.hash,
createdAt: new Date(),
} as StoredTransactionAttempt);
await this.db.transactions.put(
{
id: onchainTransactionId,
//// Helper fields
channelAddress,
status: StoredTransactionStatus.submitted,
reason,
//// Provider fields
// Minimum fields (should always be defined)
to: response.to!,
from: response.from,
data: response.data,
value: response.value.toString(),
chainId: response.chainId,
nonce: response.nonce,
attempts,
} as StoredTransaction,
onchainTransactionId,
);
}
async saveTransactionReceipt(onchainTransactionId: string, receipt: TransactionReceipt): Promise<void> {
await this.db.transactions.update(onchainTransactionId, {
status: StoredTransactionStatus.mined,
receipt: this.sanitizeReceipt(receipt),
});
}
async saveTransactionFailure(
onchainTransactionId: string,
error: string,
receipt?: TransactionReceipt,
): Promise<void> {
await this.db.transactions.update(onchainTransactionId, {
status: StoredTransactionStatus.failed,
error,
receipt: receipt ? this.sanitizeReceipt(receipt) : undefined,
});
}
async getTransactionByHash(transactionHash: string): Promise<StoredTransaction | undefined> {
const tx = await this.db.transactions.get(transactionHash);
return tx;
}
async saveWithdrawalCommitment(transferId: string, withdrawCommitment: WithdrawCommitmentJson): Promise<void> {
await this.db.withdrawCommitment.put({ ...withdrawCommitment, transferId });
}
async getWithdrawalCommitment(transferId: string): Promise<WithdrawCommitmentJson | undefined> {
const w = await this.db.withdrawCommitment.get(transferId);
if (!w) {
return w;
}
const { transferId: t, ...commitment } = w;
return commitment;
}
async getWithdrawalCommitmentByTransactionHash(transactionHash: string): Promise<WithdrawCommitmentJson | undefined> {
const w = await this.db.withdrawCommitment.get({ transactionHash });
if (!w) {
return w;
}
const { transferId, ...commitment } = w;
return commitment;
}
// TOOD: dont really need this yet, but prob will soon
getUnsubmittedWithdrawals(
channelAddress: string,
withdrawalDefinition: string,
): Promise<
{
commitment: WithdrawCommitmentJson; // function. However, the constructor should *not* be used when creating
// function. However, the constructor should *not* be used when creating
// an instance of the BrowserStore
transfer: FullTransferState<any>;
}[]
> {
throw new Error("Method not implemented.");
}
async saveTransferDispute(
transferId: string,
transferDispute: TransferDispute,
disputedTransfer?: CoreTransferState,
): Promise<void> {
await this.db.transferDisputes.put({ transferDispute, transferId, disputedTransfer });
}
async getTransferDispute(transferId: string): Promise<TransferDispute | undefined> {
const entity = await this.db.transferDisputes.get({ transferId });
if (!entity) {
return undefined;
}
return entity.transferDispute;
}
async saveChannelDispute(
channelAddress: string,
channelDispute: ChannelDispute,
disputedChannel?: CoreChannelState,
): Promise<void> {
await this.db.channelDisputes.put({ channelDispute, disputedChannel, channelAddress });
}
async getChannelDispute(channelAddress: string): Promise<ChannelDispute | undefined> {
const entity = await this.db.channelDisputes.get({ channelAddress });
if (!entity) {
return undefined;
}
return entity.channelDispute;
}
} | the_stack |
import { CommonContentClientConfig } from './config/CommonContentClientConfig';
import { RenderedContentItem } from './rendering/model/RenderedContentItem';
import { RenderContentItem } from './rendering/coordinators/RenderContentItem';
import { FilterBy } from './content/coordinators/FilterBy';
import { ContentItem } from './content/model/ContentItem';
import { ContentBody, DefaultContentBody } from './content/model/ContentBody';
import { GetContentItemV1Impl } from './content/coordinators/GetContentItemV1Impl';
import { ContentMapper } from './content/mapper/ContentMapper';
import { GetContentItemById } from './content/coordinators/GetContentItemById';
import { GetContentItemV2Impl } from './content/coordinators/GetContentItemV2Impl';
import { GetContentItemByKey } from './content/coordinators/GetContentItemByKey';
import { ContentClientConfigV1 } from './config/ContentClientConfigV1';
import { ContentClientConfigV2 } from './config/ContentClientConfigV2';
import { FilterByImpl } from './content/coordinators/FilterByImpl';
import { FilterByRequest, FilterByResponse } from './content/model/FilterBy';
/**
* Amplience [Content Delivery API](https://docs.amplience.net/integration/deliveryapi.html?h=delivery) client.
*
* This client is intended to be used by end user applications to fetch content so that it can be displayed to users.
*
* You must provide some basic account information in order to create an instance of ContentClient.
*
* Example:
*
* ```typescript
* const client = new ContentClient({
* account: 'test'
* });
* ```
*
* You may override other settings when constructing the client but if no additional configuration is provided sensible defaults will be used.
*/
export class ContentClient implements GetContentItemById, GetContentItemByKey {
private readonly contentMapper: ContentMapper;
/**
* Creates a Delivery API Client instance. You must provide a configuration object with the account you wish to fetch content from.
* @param config Client configuration options
*/
constructor(
private readonly config: ContentClientConfigV1 | ContentClientConfigV2
) {
if (!config) {
throw new TypeError('Parameter "config" is required');
}
if (
!(config as ContentClientConfigV1).account &&
!(config as ContentClientConfigV2).hubName
) {
throw new TypeError(
'Parameter "config" must contain a valid "account" name or "hubName" property'
);
}
if (
config.stagingEnvironment &&
config.stagingEnvironment.indexOf('://') !== -1
) {
throw new TypeError(
'Parameter "stagingEnvironment" should be a hostname not a URL'
);
}
this.contentMapper = this.createContentMapper(config);
}
/**
* @hidden
*/
private isContentClientConfigV1(
config: ContentClientConfigV1 | ContentClientConfigV2
): config is ContentClientConfigV1 {
return (config as ContentClientConfigV1).account !== undefined;
}
/**
* @hidden
*/
private isContentClientConfigV2(
config: ContentClientConfigV1 | ContentClientConfigV2
): config is ContentClientConfigV2 {
return (config as ContentClientConfigV2).hubName !== undefined;
}
/**
* @deprecated use getContentItemById
*/
getContentItem<T extends ContentBody = DefaultContentBody>(
contentItemId: string
): Promise<ContentItem<T>> {
return this.getContentItemById(contentItemId);
}
/**
* This function will load a Content Item or Slot by id and return a Promise of the result.
* If the content is not found the promise will reject with an error.
* If the content is found the promise will resolve with a parsed version of the content with all dependencies.
*
* The content body will match the format defined by your content type, however keep in mind that if you have evolved your content type some published content may still be in the older format.
*
* Some pre-processing is applied to the content body to make it easier to work with:
*
* * Linked content items are joined together into the root content item to create a single JSON document.
* * Media references (images and videos) are replaced with wrapper objects [[Image]] and [[Video]] which provide helper functions.
* * Content created using V1 of the CMS will be upgraded to the V2 format.
*
* You can convert the content back to plain JSON by calling the toJSON() function on the returned ContentItem.
* @typeparam T The type of content returned. This is optional and by default the content returned is assumed to be “any”.
* @param id Unique id of the Content Item or Slot to load
*/
getContentItemById<T extends ContentBody = DefaultContentBody>(
id: string
): Promise<ContentItem<T>> {
if (this.isContentClientConfigV2(this.config)) {
return new GetContentItemV2Impl(
this.config,
this.contentMapper
).getContentItemById(id);
}
return new GetContentItemV1Impl(
this.config,
this.contentMapper
).getContentItemById(id);
}
/**
* This function will load a Content Item or Slot by key and return a Promise of the result.
* If the content is not found the promise will reject with an error.
* If the content is found the promise will resolve with a parsed version of the content with all dependencies.
*
* A delivery key can be a simple string or a path such as "home-page/feature-banner". This makes it simpler to write your integration code and allows users more control over where items of content are delivered. You can add a delivery key to a slot in the Dynamic Content app or to a content item or slot using the Dynamic Content Management API.
* Note that a delivery key may not start or end with "/" and must be between 1 and 150 characters. Delivery keys can contain the following alphanumeric characters: a to z, A to Z and 0 to 9. You can also include "-" and "_" and "/" as long as it is not included at the start or end of the key.
*
* The content body will match the format defined by your content type.
*
* Some pre-processing is applied to the content body to make it easier to work with:
*
* * Linked content items are joined together into the root content item to create a single JSON document.
* * Media references (images and videos) are replaced with wrapper objects [[Image]] and [[Video]] which provide helper functions.
* * Content created using V1 of the CMS will be upgraded to the V2 format.
*
* You can convert the content back to plain JSON by calling the toJSON() function on the returned ContentItem.
* @typeparam T The type of content returned. This is optional and by default the content returned is assumed to be “any”.
* @param id Unique id of the Content Item or Slot to load
*/
getContentItemByKey<T extends ContentBody = DefaultContentBody>(
key: string
): Promise<ContentItem<T>> {
if (!this.isContentClientConfigV2(this.config)) {
throw new Error(
'Not supported. You need to define "hubName" configuration property to use getContentItemByKey()'
);
}
return new GetContentItemV2Impl(
this.config,
this.contentMapper
).getContentItemByKey(key);
}
/**
* This function will help construct requests for filtering Content Items or Slots
*
* @param filterBy - API options for `/content/filter` endpoint [docs](https://amplience.com/docs/development/contentdelivery/filterandsort.html)
* @returns
*/
filterContentItems<Body = any>(
filterBy: FilterByRequest
): Promise<FilterByResponse<Body>> {
if (!this.isContentClientConfigV2(this.config)) {
throw new Error(
'Not supported. You need to define "hubName" configuration property to use filterContentItems()'
);
}
return new FilterByImpl<Body>(this.config).fetch(filterBy);
}
/**
* This function will help construct requests for filtering Content Items or Slots
*
* @param path - json path to property you wish to filter by e.g `/_meta/schema`
* @param value - value you want to return matches for
*
* @returns `FilterBy<Body>`
*/
filterBy<Body = any, Value = any>(
path: string,
value: Value
): FilterBy<Body> {
if (!this.isContentClientConfigV2(this.config)) {
throw new Error(
'Not supported. You need to define "hubName" configuration property to use filterBy()'
);
}
return new FilterBy<Body>(this.config).filterBy<Value>(path, value);
}
/**
*
* This function will help construct requests for filtering Content Items or Slots
*
* equivalent to:
*
* ```ts
* client.filterBy('/_meta/schema', contentTypeUri)
* ```
*
* @param contentTypeUri - Content Type Uri you want to filter
*
* @returns `FilterBy<Body>`
*/
filterByContentType<Body = any>(contentTypeUri: string): FilterBy<Body> {
if (!this.isContentClientConfigV2(this.config)) {
throw new Error(
'Not supported. You need to define "hubName" configuration property to use filterByContentType()'
);
}
return new FilterBy<Body>(this.config).filterByContentType(contentTypeUri);
}
/**
* This function will help construct requests for filtering Content Items or Slots
*
* equivalent to:
*
* ```ts
* client.filterBy('/_meta/hierarchy/parentId', id)
* ```
*
* @param id - ID of a Hierarchy Content Item
*
* @returns `FilterBy<Body>`
*/
filterByParentId<Body = any>(id: string): FilterBy<Body> {
if (!this.isContentClientConfigV2(this.config)) {
throw new Error(
'Not supported. You need to define "hubName" configuration property to use filterByParentId()'
);
}
return new FilterBy<Body>(this.config).filterByParentId(id);
}
/**
* Converts a Content Item or Slot into a custom format (e.g. HTML / XML) by applying a template server side.
* @param contentItemId Unique id of the Content Item or Slot to convert using the rendering service
* @param templateName Name of the template to render the content item or slot with. The template must be setup in your account
* @param customParameters Custom parameters which will be sent to the rendering API and made avaliable to your template
*/
renderContentItem(
contentItemId: string,
templateName: string,
customParameters?: { [id: string]: string }
): Promise<RenderedContentItem> {
if (!this.isContentClientConfigV1(this.config)) {
throw new Error(
'Not supported. You need to define "account" configuration property to use renderContentItem()'
);
}
return new RenderContentItem(this.config).renderContentItem(
contentItemId,
templateName,
customParameters
);
}
/**
* Creates a parser which converts content JSON into classes and objects used by the SDK
* @param config
* @hidden
*/
protected createContentMapper(
config: CommonContentClientConfig
): ContentMapper {
return new ContentMapper(config);
}
} | the_stack |
import { Observable, Subject } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
import { PblDataSource, unrx } from '@pebula/ngrid/core';
import { PblNgridInternalExtensionApi, PblNgridExtensionApi } from '../../../../../ext/grid-ext-api';
import { PblCdkVirtualScrollViewportComponent } from '../../virtual-scroll-viewport.component';
import { PblNgridVirtualScrollStrategy } from '../types';
import { Sizer } from './sizer';
declare module '../types' {
interface PblNgridVirtualScrollStrategyMap {
vScrollDynamic: PblNgridDynamicVirtualScrollStrategy;
}
}
export class PblNgridDynamicVirtualScrollStrategy implements PblNgridVirtualScrollStrategy<'vScrollDynamic'> {
readonly type: 'vScrollDynamic' = 'vScrollDynamic';
protected _scrolledIndexChange = new Subject<number>();
/** @docs-private Implemented as part of VirtualScrollStrategy. */
scrolledIndexChange: Observable<number> = this._scrolledIndexChange.pipe(distinctUntilChanged());
/** The attached viewport. */
protected _viewport: PblCdkVirtualScrollViewportComponent | null = null;
/** The minimum amount of buffer rendered beyond the viewport (in pixels). */
protected _minBufferPx: number;
/** The number of buffer items to render beyond the edge of the viewport (in pixels). */
protected _maxBufferPx: number;
protected _lastRenderedContentOffset: number;
protected _lastExcessHeight = 0;
protected sizer: Sizer;
private extApi: PblNgridInternalExtensionApi;
/**
* @param itemSize The size of the items in the virtually scrolling list.
* @param minBufferPx The minimum amount of buffer (in pixels) before needing to render more
* @param maxBufferPx The amount of buffer (in pixels) to render when rendering more.
*/
constructor(itemSize: number, minBufferPx: number, maxBufferPx: number) {
this.sizer = new Sizer();
this.sizer.itemSize = itemSize;
this._minBufferPx = minBufferPx;
this._maxBufferPx = maxBufferPx;
}
/**
* Update the item size and buffer size.
* @param itemSize The size of the items in the virtually scrolling list.
* @param minBufferPx The minimum amount of buffer (in pixels) before needing to render more
* @param maxBufferPx The amount of buffer (in pixels) to render when rendering more.
*/
updateItemAndBufferSize(itemSize: number, minBufferPx: number, maxBufferPx: number) {
if (maxBufferPx < minBufferPx && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('CDK virtual scroll: maxBufferPx must be greater than or equal to minBufferPx');
}
this.sizer.itemSize = itemSize;
this._minBufferPx = minBufferPx;
this._maxBufferPx = maxBufferPx;
this._updateTotalContentSize();
this._updateRenderedRange();
}
attachExtApi(extApi: PblNgridExtensionApi): void {
this.extApi = extApi as PblNgridInternalExtensionApi;
this.extApi.events
.subscribe( event => {
if (event.kind === 'onDataSource') {
this.onDatasource(event.curr, event.prev);
}
});
if (this.extApi.grid.ds) {
this.onDatasource(this.extApi.grid.ds);
}
}
attach(viewport: PblCdkVirtualScrollViewportComponent): void {
if (!this.extApi) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
throw new Error('Invalid use of attach, you must first attach `PblNgridExtensionApi`');
}
}
this._viewport = viewport;
this._updateSizeAndRange();
}
detach(): void {
this._scrolledIndexChange.complete();
this._viewport = null;
}
onContentScrolled() {
this._updateRenderedRange();
}
onDataLengthChanged() {
this.sizer.itemsLength = this._viewport.getDataLength();
this._updateSizeAndRange();
}
onContentRendered() {
this._checkRenderedContentSize();
}
onRenderedOffsetChanged() {
if (this._viewport) {
this._lastRenderedContentOffset = this._viewport.getOffsetToRenderedContentStart();
}
}
/**
* Scroll to the offset for the given index.
* @param index The index of the element to scroll to.
* @param behavior The ScrollBehavior to use when scrolling.
*/
scrollToIndex(index: number, behavior: ScrollBehavior): void {
if (this._viewport) {
this._viewport.scrollToOffset(this.sizer.getSizeBefore(index), behavior);
}
}
protected onDatasource(curr: PblDataSource, prev?: PblDataSource) {
if (prev) {
unrx.kill(this, prev);
}
if (curr) {
curr.onSourceChanging
.pipe(unrx(this, curr))
.subscribe(() => {
this.sizer.clear();
});
}
}
protected _updateSizeAndRange() {
this._updateTotalContentSize();
this._updateRenderedRange(true);
}
/** Update the viewport's total content size. */
protected _updateTotalContentSize() {
if (!this._viewport) {
return;
}
for (const row of this.extApi.rowsApi.dataRows()) {
if (row.context) {
this.sizer.setSize(row.context.dsIndex, row.height);
}
}
this._viewport.setTotalContentSize(this.sizer.getTotalContentSize());
}
protected _checkRenderedContentSize() {
this._updateTotalContentSize();
}
/** Update the viewport's rendered range. */
protected _updateRenderedRange(skipSizeSync?: boolean) {
if (!this._viewport) {
return;
}
const renderedRange = this._viewport.getRenderedRange();
// if (!skipSizeSync) {
// for (let i = renderedRange.start; i <= renderedRange.end; i++) {
// this.sizer.setSize(i, this.extApi.rowsApi.findDataRowByDsIndex(i)?.height ?? this.sizer.itemSize);
// }
// }
const newRange = {start: renderedRange.start, end: renderedRange.end};
const viewportSize = this._viewport.getViewportSize();
const dataLength = this._viewport.getDataLength();
let scrollOffset = this._viewport.measureScrollOffset();
let firstVisibleIndex = this.sizer.findRenderItemAtOffset(scrollOffset);
let excessHeight = 0;
// When user scrolls to the top, rows change context, sometimes new rows are added etc.
// With dynamic size, rows with additional size payload will cause the scroll offset to change because they are added
// before the visible rows, this will throw the entire scroll out of sync.
// To solve this we use a 2 step process.
// 1) For each `_updateRenderRange` cycle of scrolling to the TOP, we sum up excess all height and save them.
// 2) If we had excess height it will create a scroll change which will lead us back here. Now we check if we
// have previously saved access height, if so we reduce the scroll offset back to what it was supposed to be, like adding the height did not effect the offset.
// Since the first step causes a scroll offset flicker, the grid will jump forward and show rows not in the range we want, if we just move back on the 2nd tick
// it will cause a flicker in the grid. To prevent it we compensate by pushing in the 1st tick, the rendered content offset forward to match the offset change.
// In the second tick we revet it and restore the offset.
if (this._lastExcessHeight) {
const lastExcessHeight = this._lastExcessHeight;
this._lastExcessHeight = 0;
this._viewport.setRenderedContentOffset(this._lastRenderedContentOffset - lastExcessHeight);
this._viewport.scrollToOffset(scrollOffset - lastExcessHeight);
return;
}
// If user scrolls to the bottom of the list and data changes to a smaller list
if (newRange.end > dataLength) {
// We have to recalculate the first visible index based on new data length and viewport size.
let spaceToFill = viewportSize;
let expandEnd = firstVisibleIndex;
while (spaceToFill > 0) {
spaceToFill -= this.sizer.getSizeForItem(++expandEnd);
}
const maxVisibleItems = expandEnd - firstVisibleIndex;
const newVisibleIndex = Math.max(0, Math.min(firstVisibleIndex, dataLength - maxVisibleItems));
// If first visible index changed we must update scroll offset to handle start/end buffers
// Current range must also be adjusted to cover the new position (bottom of new list).
if (firstVisibleIndex !== newVisibleIndex) {
firstVisibleIndex = newVisibleIndex;
scrollOffset = this.sizer.getSizeBefore(firstVisibleIndex);
newRange.start = firstVisibleIndex;
}
newRange.end = Math.max(0, Math.min(dataLength, newRange.start + maxVisibleItems));
}
let contentOffset = this.sizer.getSizeBefore(newRange.start);
const currentStartBuffer = scrollOffset - contentOffset;
if (currentStartBuffer < this._minBufferPx && newRange.start !== 0) {
let spaceToFill = this._maxBufferPx - currentStartBuffer;
if (spaceToFill < 0) {
spaceToFill = Math.abs(spaceToFill) + this._maxBufferPx;
}
let expandStart = newRange.start;
while (spaceToFill > 0) {
const newSize = this.sizer.getSizeForItem(--expandStart);
spaceToFill -= newSize;
excessHeight += newSize - this.sizer.itemSize;
}
expandStart = Math.max(0, expandStart);
if (expandStart !== newRange.start) {
newRange.start = expandStart;
contentOffset = this.sizer.getSizeBefore(expandStart);
}
spaceToFill = viewportSize + this._minBufferPx;
let expandEnd = firstVisibleIndex;
while (spaceToFill > 0) {
spaceToFill -= this.sizer.getSizeForItem(++expandEnd);
}
newRange.end = Math.min(dataLength, expandEnd);
} else {
const renderDataEnd = contentOffset + this.sizer.getSizeForRange(newRange.start, newRange.end);
const currentEndBuffer = renderDataEnd - (scrollOffset + viewportSize);
if (currentEndBuffer < this._minBufferPx && newRange.end !== dataLength) {
let spaceToFill = this._maxBufferPx - currentEndBuffer;
if (spaceToFill < 0) {
spaceToFill = Math.abs(spaceToFill) + this._maxBufferPx;
}
let expandEnd = newRange.end;
while (spaceToFill > 0) {
spaceToFill -= this.sizer.getSizeForItem(++expandEnd);
}
if (expandEnd > 0) {
newRange.end = Math.min(dataLength, expandEnd);
spaceToFill = this._minBufferPx;
let expandStart = firstVisibleIndex;
while (spaceToFill > 0) {
spaceToFill -= this.sizer.getSizeForItem(--expandStart);
}
expandStart = Math.max(0, expandStart);
if (expandStart !== newRange.start) {
newRange.start = expandStart;
contentOffset = this.sizer.getSizeBefore(expandStart);
}
}
}
}
this._lastExcessHeight = excessHeight;
this._viewport.setRenderedRange(newRange);
this._viewport.setRenderedContentOffset(contentOffset + excessHeight);
this._scrolledIndexChange.next(Math.floor(firstVisibleIndex));
}
} | the_stack |
import { Theme, withTheme, WithTheme } from "@material-ui/core";
import { grey } from "@material-ui/core/colors";
import Tooltip from "@material-ui/core/Tooltip/Tooltip";
import { createStyles, withStyles, WithStyles } from "@material-ui/styles";
import * as chartjs from "chart.js";
import { format } from "date-fns";
import React from "react";
// @ts-ignore
import { ChartData, Line } from "react-chartjs-2";
import { MetricList } from "types/common";
import { getStartTimestamp, TimestampFilter } from "utils/date";
import { formatCPU, formatMemory } from "utils/sizeConv";
import { KTooltip } from "widgets/KTooltip";
const smallLineChartStyles = (theme: Theme) =>
createStyles({
root: {
position: "relative",
display: "inline-block",
verticalAlign: "middle",
border: `2px solid ${theme.palette.type === "light" ? grey[300] : grey[700]}`,
borderRadius: 4,
overflow: "hidden",
},
text: {
left: 0,
right: 0,
top: 0,
bottom: 0,
position: "absolute",
display: "flex",
alignItems: "center",
justifyContent: "space-around",
},
});
interface Props extends WithStyles<typeof smallLineChartStyles>, WithTheme {
data?: MetricList;
hoverText?: string;
width: number | string;
height: number | string;
formatValue?: (value: number) => string;
borderColor?: string;
backgroundColor?: string;
limit?: number;
}
const emptyChartDataX = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const emptyChartDataY = [1, 3, 1, 5, 2, 7, 2, 5, 8];
class SmallLineChartRaw extends React.PureComponent<Props> {
private generateData = (): ChartData<chartjs.ChartData> => {
const { data, borderColor, backgroundColor, theme } = this.props;
let dataX = emptyChartDataX;
let dataY = emptyChartDataY;
let backgroundColorFixed = backgroundColor;
let borderColorFixed = borderColor;
if (data && data.length > 0) {
dataY = data.map((n) => n.y);
dataX = data.map((n) => n.x);
} else {
backgroundColorFixed = theme.palette.type === "light" ? grey[400] : grey[800];
borderColorFixed = theme.palette.type === "light" ? grey[400] : grey[800];
}
return {
labels: dataX,
datasets: [
{
lineTension: 0.1,
borderColor: borderColorFixed || "#DDD",
borderWidth: 2,
backgroundColor: backgroundColorFixed || "rgba(75,192,192,0.4)",
pointHoverRadius: 0,
pointRadius: 0,
pointHitRadius: 0,
data: dataY,
},
],
};
};
private renderText() {
const { data, formatValue } = this.props;
// let text = "Data available soon";
let text = "";
let percentage: React.ReactNode;
let title: string = "";
if (data && data.length > 0) {
if (formatValue) {
text = formatValue(data[data.length - 1]!.y);
} else {
text = data[data.length - 1]!.y.toString();
}
}
const content = (
<div className={this.props.classes.text}>
{text}
{percentage}
</div>
);
return title !== "" ? <Tooltip title={title}>{content}</Tooltip> : content;
}
private hasData = () => {
const { data } = this.props;
return data && data.length > 0;
};
public render() {
const { classes, width, height, hoverText } = this.props;
const hasData = this.hasData();
const line = (
<div style={{ width, height }} className={classes.root}>
{this.renderText()}
<Line
legend={{ display: false }}
options={{
responsive: true,
maintainAspectRatio: false,
tooltips: {
enabled: false,
},
scales: {
yAxes: [
{
display: false,
gridLines: {
display: false,
},
ticks: {
beginAtZero: true,
},
},
],
xAxes: [
{
display: false,
gridLines: {
display: false,
},
},
],
},
animation: {
duration: 0,
animateScale: false,
animateRotate: false,
},
}}
data={this.generateData()}
/>
</div>
);
if (hasData) {
return line;
}
return <KTooltip title={hoverText || "Data available soon"}>{line}</KTooltip>;
}
}
export const SmallLineChart = withStyles(smallLineChartStyles)(withTheme(SmallLineChartRaw));
const lineChartStyles = (theme: Theme) =>
createStyles({
root: {
position: "relative",
// background: "white",
display: "inline-block",
},
text: {
left: 0,
right: 0,
top: 0,
bottom: 0,
position: "absolute",
display: "flex",
alignItems: "center",
justifyContent: "space-around",
},
});
interface LineChartProps extends WithStyles<typeof lineChartStyles> {
data: MetricList;
filter?: TimestampFilter;
title?: string;
width: number | string;
height: number | string;
yAxesWidth?: number;
formatValue?: (value: number) => string;
borderColor?: string;
backgroundColor?: string;
limit?: number;
}
class LineChartRaw extends React.PureComponent<LineChartProps> {
private generateData = (): ChartData<chartjs.ChartData> => {
const { data, borderColor, backgroundColor, filter } = this.props;
const startTimestamp = getStartTimestamp(filter);
return {
labels: data
? data
.filter((item) => {
if (!filter || filter === "all") {
return true;
}
return item.x >= startTimestamp;
})
.map((n) => n.x)
: [],
datasets: [
{
lineTension: 0.1,
borderColor: borderColor,
borderWidth: 1,
backgroundColor: backgroundColor,
pointRadius: 1,
data: data
? data
.filter((item) => {
if (!filter || filter === "all") {
return true;
}
return item.x >= startTimestamp;
})
.map((n) => n.y)
: [],
},
],
};
};
public render() {
const { classes, width, limit, height, formatValue, title, yAxesWidth } = this.props;
return (
<div style={{ width, height }} className={classes.root}>
<Line
legend={{ display: false }}
options={{
title: {
display: title ? true : false,
text: title,
},
responsive: true,
maintainAspectRatio: false,
tooltips: {
intersect: false,
callbacks: {
label: (tooltipItem: chartjs.ChartTooltipItem, data: chartjs.ChartData): string => {
// @ts-ignore
const value: number = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
// @ts-ignore
let res = formatValue ? formatValue(value) : value.toString();
if (limit) {
res = res + ` (${3}%)`;
}
return res;
},
title: (tooltipItem: chartjs.ChartTooltipItem[], data: chartjs.ChartData): string => {
// @ts-ignore
return format(tooltipItem[0].xLabel, "yyyy-MM-dd HH:mm");
},
},
},
scales: {
yAxes: [
{
afterFit: yAxesWidth
? (scaleInstance) => {
scaleInstance.width = 80; // sets the width to 100px
}
: undefined,
ticks: {
maxTicksLimit: 5,
beginAtZero: true,
callback: formatValue,
},
},
],
xAxes: [
{
ticks: {
maxTicksLimit: 10,
callback: (value) => {
return format(value, "HH:mm");
},
},
},
],
},
}}
data={this.generateData()}
/>
</div>
);
}
}
export const LineChart = withStyles(lineChartStyles)(LineChartRaw);
export const BigCPULineChart = (props: Pick<LineChartProps, "data" | "yAxesWidth" | "filter">) => {
return (
<LineChart
{...props}
title={"CPU"}
formatValue={formatCPU}
height={170}
width={"100%"}
borderColor="rgba(33, 150, 243, 1)"
backgroundColor="rgba(33, 150, 243, 0.5)"
/>
);
};
export const BigMemoryLineChart = (props: Pick<LineChartProps, "data" | "yAxesWidth" | "filter">) => {
return (
<LineChart
title="Memory"
{...props}
formatValue={formatMemory}
height={170}
width={"100%"}
borderColor="rgba(75,192,192, 1)"
backgroundColor="rgba(75,192,192,0.5)"
/>
);
};
export const SmallMemoryLineChart = (props: Pick<Props, "limit" | "data" | "hoverText">) => {
return (
<SmallLineChart
{...props}
formatValue={formatMemory}
width={120}
height={24}
borderColor="#00DD66"
backgroundColor="rgba(0,221,102,0.25)"
/>
);
};
export const SmallCPULineChart = (props: Pick<Props, "limit" | "data" | "hoverText">) => {
return (
<SmallLineChart
{...props}
formatValue={formatCPU}
width={120}
height={24}
borderColor="#36A7FC"
backgroundColor="rgba(54, 167, 252, 0.25)"
/>
);
};
export const CardMemoryLineChart = (props: Pick<Props, "limit" | "data" | "hoverText">) => {
return (
<SmallLineChart
{...props}
formatValue={formatMemory}
width={200}
height={24}
borderColor="#00DD66"
backgroundColor="rgba(0,221,102,0.25)"
/>
);
};
export const CardCPULineChart = (props: Pick<Props, "limit" | "data" | "hoverText">) => {
return (
<SmallLineChart
{...props}
formatValue={formatCPU}
width={200}
height={24}
borderColor="#36A7FC"
backgroundColor="rgba(54, 167, 252, 0.25)"
/>
);
}; | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormAgreement_Booking_Setup {
interface tab__B08D1E73_C885_4AC5_8E1A_ECD3CF34E01D_Sections {
_B08D1E73_C885_4AC5_8E1A_ECD3CF34E01D_SECTION_3: DevKit.Controls.Section;
_B08D1E73_C885_4AC5_8E1A_ECD3CF34E01D_SECTION_5: DevKit.Controls.Section;
_B08D1E73_C885_4AC5_8E1A_ECD3CF34E01D_SECTION_6: DevKit.Controls.Section;
_E2317057_FAF8_42F6_A483_57D828596C17: DevKit.Controls.Section;
tab_3_section_1: DevKit.Controls.Section;
tab_4_section_1: DevKit.Controls.Section;
}
interface tab_tab_6_Sections {
tab_6_section_1: DevKit.Controls.Section;
}
interface tab_tab_7_Sections {
tab_7_section_1: DevKit.Controls.Section;
}
interface tab_tab_8_Sections {
tab_8_section_1: DevKit.Controls.Section;
}
interface tab__B08D1E73_C885_4AC5_8E1A_ECD3CF34E01D extends DevKit.Controls.ITab {
Section: tab__B08D1E73_C885_4AC5_8E1A_ECD3CF34E01D_Sections;
}
interface tab_tab_6 extends DevKit.Controls.ITab {
Section: tab_tab_6_Sections;
}
interface tab_tab_7 extends DevKit.Controls.ITab {
Section: tab_tab_7_Sections;
}
interface tab_tab_8 extends DevKit.Controls.ITab {
Section: tab_tab_8_Sections;
}
interface Tabs {
_B08D1E73_C885_4AC5_8E1A_ECD3CF34E01D: tab__B08D1E73_C885_4AC5_8E1A_ECD3CF34E01D;
tab_6: tab_tab_6;
tab_7: tab_tab_7;
tab_8: tab_tab_8;
}
interface Body {
Tab: Tabs;
/** Agreement this Booking Setup relates to */
msdyn_Agreement: DevKit.Controls.Lookup;
/** Enable if the system should automatically generate Order Bookings for the Booking Dates of this Booking Setup */
msdyn_AutoGenerateBooking: DevKit.Controls.Boolean;
/** Enable if the system should automatically generate Work Orders for the Booking Dates of this Booking Setup */
msdyn_AutoGenerateWO: DevKit.Controls.Boolean;
/** Type a description of this booking setup. */
msdyn_Description: DevKit.Controls.String;
/** Shows the duration of the booking. */
msdyn_EstimatedDuration: DevKit.Controls.Integer;
/** Specify how many days in advance of the Booking Date the system should automatically generate a Work Order */
msdyn_GenerateWODaysInAdvance: DevKit.Controls.Integer;
/** Only used when Work Location is a Facility. Latitude is used when trying to locate nearby facilities. */
msdyn_Latitude: DevKit.Controls.Double;
/** Only used when Work Location is a Facility. Longitude is used when trying to locate nearby facilities. */
msdyn_Longitude: DevKit.Controls.Double;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Shows the flexibility of days after the booking date. */
msdyn_PostBookingFlexibility: DevKit.Controls.Integer;
/** Shows the flexibility of days prior to the booking date. */
msdyn_PreBookingFlexibility: DevKit.Controls.Integer;
/** Preferred Resource to booked */
msdyn_PreferredResource: DevKit.Controls.Lookup;
/** Shows the preferred time to booking. */
msdyn_PreferredStartTime: DevKit.Controls.DateTime;
/** Booking Priority */
msdyn_Priority: DevKit.Controls.Lookup;
/** Stores the booking recurrence settings. */
msdyn_RecurrenceSettings: DevKit.Controls.String;
/** Shows the time window up until when this can be booked. */
msdyn_TimeWindowEnd: DevKit.Controls.DateTime;
/** Shows the time window from when this can be booked. */
msdyn_TimeWindowStart: DevKit.Controls.DateTime;
msdyn_WorkLocation: DevKit.Controls.OptionSet;
/** Shows the work order summary to be set on the work orders generated. */
msdyn_WorkOrderSummary: DevKit.Controls.String;
/** Work Order Type to be used on generated Work Orders */
msdyn_WorkOrderType: DevKit.Controls.Lookup;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
WebResource_PreferredStartTime_TimeField: DevKit.Controls.WebResource;
WebResource_TimeWindowEnd_TimeField: DevKit.Controls.WebResource;
WebResource_TimeWindowStart_TimeField: DevKit.Controls.WebResource;
}
interface Footer extends DevKit.Controls.IFooter {
/** Status of the Agreement Booking Setup */
statecode: DevKit.Controls.OptionSet;
}
interface Navigation {
nav_msdyn_msdyn_agreementbookingsetup_msdyn_agreementbookingdate_BookingSetup: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_agreementbookingsetup_msdyn_agreementbookingincident_AgreementBookingSetup: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_agreementbookingsetup_msdyn_agreementbookingproduct_AgreementBookingSetup: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_agreementbookingsetup_msdyn_agreementbookingservice_AgreementBookingSetup: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_agreementbookingsetup_msdyn_agreementbookingservicetask_AgreementBookingSetup: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
interface Grid {
incidentsgrid: DevKit.Controls.Grid;
schecduledategrid: DevKit.Controls.Grid;
AgreementBookingProductsGrid: DevKit.Controls.Grid;
AgreementBookingServicesGrid: DevKit.Controls.Grid;
AgreementBookingServiceTasksGrid: DevKit.Controls.Grid;
}
}
class FormAgreement_Booking_Setup extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Agreement_Booking_Setup
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Agreement_Booking_Setup */
Body: DevKit.FormAgreement_Booking_Setup.Body;
/** The Footer section of form Agreement_Booking_Setup */
Footer: DevKit.FormAgreement_Booking_Setup.Footer;
/** The Navigation of form Agreement_Booking_Setup */
Navigation: DevKit.FormAgreement_Booking_Setup.Navigation;
/** The Grid of form Agreement_Booking_Setup */
Grid: DevKit.FormAgreement_Booking_Setup.Grid;
}
namespace FormAgreement_Booking_Setup_Mobile {
interface tab_fstab_general_Sections {
fstab_general_column_2_section_1: DevKit.Controls.Section;
fstab_general_column_3_section_1: DevKit.Controls.Section;
fstab_general_section_booking_settings: DevKit.Controls.Section;
fstab_general_section_preferences: DevKit.Controls.Section;
fstab_general_section_summary: DevKit.Controls.Section;
fstab_general_section_work_order_settings: DevKit.Controls.Section;
}
interface tab_fstab_other_Sections {
tab_4_section_2: DevKit.Controls.Section;
tab_4_section_3: DevKit.Controls.Section;
tab_4_section_4: DevKit.Controls.Section;
}
interface tab_fstab_sub_grids_Sections {
tab_9_section_1: DevKit.Controls.Section;
tab_9_section_2: DevKit.Controls.Section;
tab_9_section_3: DevKit.Controls.Section;
}
interface tab_fstab_general extends DevKit.Controls.ITab {
Section: tab_fstab_general_Sections;
}
interface tab_fstab_other extends DevKit.Controls.ITab {
Section: tab_fstab_other_Sections;
}
interface tab_fstab_sub_grids extends DevKit.Controls.ITab {
Section: tab_fstab_sub_grids_Sections;
}
interface Tabs {
fstab_general: tab_fstab_general;
fstab_other: tab_fstab_other;
fstab_sub_grids: tab_fstab_sub_grids;
}
interface Body {
Tab: Tabs;
/** Agreement this Booking Setup relates to */
msdyn_Agreement: DevKit.Controls.Lookup;
/** Enable if the system should automatically generate Order Bookings for the Booking Dates of this Booking Setup */
msdyn_AutoGenerateBooking: DevKit.Controls.Boolean;
/** Enable if the system should automatically generate Work Orders for the Booking Dates of this Booking Setup */
msdyn_AutoGenerateWO: DevKit.Controls.Boolean;
/** Type a description of this booking setup. */
msdyn_Description: DevKit.Controls.String;
/** Shows the duration of the booking. */
msdyn_EstimatedDuration: DevKit.Controls.Integer;
/** Specify how many days in advance of the Booking Date the system should automatically generate a Work Order */
msdyn_GenerateWODaysInAdvance: DevKit.Controls.Integer;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Shows the flexibility of days after the booking date. */
msdyn_PostBookingFlexibility: DevKit.Controls.Integer;
/** Shows the flexibility of days prior to the booking date. */
msdyn_PreBookingFlexibility: DevKit.Controls.Integer;
/** Preferred Resource to booked */
msdyn_PreferredResource: DevKit.Controls.Lookup;
/** Shows the preferred time to booking. */
msdyn_PreferredStartTime: DevKit.Controls.DateTime;
/** Booking Priority */
msdyn_Priority: DevKit.Controls.Lookup;
/** Stores the booking recurrence settings. */
msdyn_RecurrenceSettings: DevKit.Controls.String;
/** Shows the time window up until when this can be booked. */
msdyn_TimeWindowEnd: DevKit.Controls.DateTime;
/** Shows the time window from when this can be booked. */
msdyn_TimeWindowStart: DevKit.Controls.DateTime;
/** Shows the work order summary to be set on the work orders generated. */
msdyn_WorkOrderSummary: DevKit.Controls.String;
/** Work Order Type to be used on generated Work Orders */
msdyn_WorkOrderType: DevKit.Controls.Lookup;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
WebResource_PreferredStartTime_TimeField: DevKit.Controls.WebResource;
WebResource_TimeWindowEnd_TimeField: DevKit.Controls.WebResource;
WebResource_TimeWindowStart_TimeField: DevKit.Controls.WebResource;
}
interface Navigation {
nav_msdyn_msdyn_agreementbookingsetup_msdyn_agreementbookingdate_BookingSetup: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_agreementbookingsetup_msdyn_agreementbookingincident_AgreementBookingSetup: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_agreementbookingsetup_msdyn_agreementbookingproduct_AgreementBookingSetup: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_agreementbookingsetup_msdyn_agreementbookingservice_AgreementBookingSetup: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_agreementbookingsetup_msdyn_agreementbookingservicetask_AgreementBookingSetup: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
interface Grid {
incidentsgrid: DevKit.Controls.Grid;
AgreementBookingProductsGrid: DevKit.Controls.Grid;
AgreementBookingServicesGrid: DevKit.Controls.Grid;
AgreementBookingServiceTasksGrid: DevKit.Controls.Grid;
schecduledategrid: DevKit.Controls.Grid;
}
}
class FormAgreement_Booking_Setup_Mobile extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Agreement_Booking_Setup_Mobile
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Agreement_Booking_Setup_Mobile */
Body: DevKit.FormAgreement_Booking_Setup_Mobile.Body;
/** The Navigation of form Agreement_Booking_Setup_Mobile */
Navigation: DevKit.FormAgreement_Booking_Setup_Mobile.Navigation;
/** The Grid of form Agreement_Booking_Setup_Mobile */
Grid: DevKit.FormAgreement_Booking_Setup_Mobile.Grid;
}
class msdyn_agreementbookingsetupApi {
/**
* DynamicsCrm.DevKit msdyn_agreementbookingsetupApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Agreement this Booking Setup relates to */
msdyn_Agreement: DevKit.WebApi.LookupValue;
/** Shows the entity instances. */
msdyn_agreementbookingsetupId: DevKit.WebApi.GuidValue;
/** Enable if the system should automatically generate Order Bookings for the Booking Dates of this Booking Setup */
msdyn_AutoGenerateBooking: DevKit.WebApi.BooleanValue;
/** Enable if the system should automatically generate Work Orders for the Booking Dates of this Booking Setup */
msdyn_AutoGenerateWO: DevKit.WebApi.BooleanValue;
/** Type a description of this booking setup. */
msdyn_Description: DevKit.WebApi.StringValue;
/** Shows the duration of the booking. */
msdyn_EstimatedDuration: DevKit.WebApi.IntegerValue;
/** Specify how many days in advance of the Booking Date the system should automatically generate a Work Order */
msdyn_GenerateWODaysInAdvance: DevKit.WebApi.IntegerValue;
/** For internal use only. */
msdyn_InternalFlags: DevKit.WebApi.StringValue;
/** Only used when Work Location is a Facility. Latitude is used when trying to locate nearby facilities. */
msdyn_Latitude: DevKit.WebApi.DoubleValue;
/** Only used when Work Location is a Facility. Longitude is used when trying to locate nearby facilities. */
msdyn_Longitude: DevKit.WebApi.DoubleValue;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
/** Shows the flexibility of days after the booking date. */
msdyn_PostBookingFlexibility: DevKit.WebApi.IntegerValue;
/** Intended for internal use. Manipulating values in this field is not supported and can lead to unexpected system behavior. */
msdyn_PostponeGenerationUntil_TimezoneDateAndTime: DevKit.WebApi.TimezoneDateAndTimeValue;
/** Shows the flexibility of days prior to the booking date. */
msdyn_PreBookingFlexibility: DevKit.WebApi.IntegerValue;
/** Preferred Resource to booked */
msdyn_PreferredResource: DevKit.WebApi.LookupValue;
/** Shows the preferred time to booking. */
msdyn_PreferredStartTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Booking Priority */
msdyn_Priority: DevKit.WebApi.LookupValue;
/** For internal use only */
msdyn_ProcessStartedOn_TimezoneDateAndTime: DevKit.WebApi.TimezoneDateAndTimeValue;
/** Stores the booking recurrence settings. */
msdyn_RecurrenceSettings: DevKit.WebApi.StringValue;
/** For internal use only. */
msdyn_Revision: DevKit.WebApi.IntegerValue;
/** Shows the time window up until when this can be booked. */
msdyn_TimeWindowEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows the time window from when this can be booked. */
msdyn_TimeWindowStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
msdyn_WorkLocation: DevKit.WebApi.OptionSetValue;
/** Shows the work order summary to be set on the work orders generated. */
msdyn_WorkOrderSummary: DevKit.WebApi.StringValue;
/** Work Order Type to be used on generated Work Orders */
msdyn_WorkOrderType: DevKit.WebApi.LookupValue;
/** Shows the date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Contains the ID of the process associated with the entity. */
processid: DevKit.WebApi.GuidValue;
/** Contains the ID of the stage where the entity is located. */
stageid: DevKit.WebApi.GuidValue;
/** Status of the Agreement Booking Setup */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Agreement Booking Setup */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows a comma-separated list of string values that represent the unique identifiers of stages in a business process flow instance in the order that they occur. */
traversedpath: DevKit.WebApi.StringValue;
/** Shows the time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_agreementbookingsetup {
enum msdyn_WorkLocation {
/** 690970001 */
Facility,
/** 690970002 */
Location_Agnostic,
/** 690970000 */
Onsite
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Agreement Booking Setup','Agreement Booking Setup - Mobile'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import {
amalgamatingBinaryOperators,
binaryExpressionStrings,
simpleBinaryOperators,
unaryExpressions
} from "./constants";
import { OpenAnIssueIfThisOccursError, ParseError, UnpositionableParseError } from "./errors";
import { lex } from "./lexer";
import { ASTApplicationExpression, ASTExpression, LexToken } from "./types";
/*
* To all who dare enter:
* The parser below is a maelstrom of spaghetti, but is very small.
* Please refactor it if you can, but keep bundle size down to a minimum.
*/
const amalgamationTechniques: {
[key: string]: (start: ASTExpression[]) => ASTExpression;
} = {
" ": (asts) => ({
type: "application",
function: asts[0],
arguments: asts.slice(1),
_shouldntWrapInPipedExpressions: true,
}),
"|": (asts) => ({
type: "pipeline",
stages: [].concat(
asts.slice(0, 1),
asts.slice(1).map((expr) => {
if (
expr.type === "application" &&
expr._shouldntWrapInPipedExpressions
) {
return expr;
}
return {
type: "application",
function: expr,
arguments: [],
};
})
),
}),
};
type ParseResult = {
result: ASTExpression;
offset: number;
};
type ParseContext = {
rawQuery: string;
};
type Parser = (
tokens: LexToken[],
offset: number,
ctx: ParseContext
) => ParseResult;
type ParameterizedParser = (
sourceItem: ASTExpression,
tokens: LexToken[],
offset: number,
ctx: ParseContext
) => ParseResult;
const tmatch = (token: string, value: unknown, root: LexToken) => {
return root !== undefined && root.token === token && root.value === value;
};
const buildTMatchThrower =
(ErrorConstructor: any) =>
(token: string, value: unknown, root: LexToken) => {
if (!tmatch(token, value, root)) {
throw new ErrorConstructor("Expected " + value + ", got " + root.value);
}
};
const tmatchOrThrow = buildTMatchThrower(ParseError);
const tmatchOrThrowBad = buildTMatchThrower(OpenAnIssueIfThisOccursError);
const isBinExp = (token: LexToken) => {
const res =
token.token === "special" &&
binaryExpressionStrings.indexOf(token.value) > -1;
return res;
};
const isUnExp = (token: LexToken) => {
const res =
token.token === "special" && unaryExpressions.indexOf(token.value) > -1;
return res;
};
const consumeParenthetical: Parser = (tokens, offset, ctx) => {
tmatchOrThrowBad("special", "(", tokens[offset]);
offset++;
const { result, offset: nextOffset } = consumeExpression(tokens, offset, ctx);
offset = nextOffset;
if (!tokens[offset]) {
throw new ParseError(
"Unexpected EOF",
ctx.rawQuery.length - 1,
ctx.rawQuery
);
}
tmatchOrThrow("special", ")", tokens[offset]);
offset++;
return {
result: {
type: "parenthetical",
expression: result,
},
offset,
};
};
const consumeArray: Parser = (tokens, offset, ctx) => {
tmatchOrThrowBad("special", "[", tokens[offset]);
offset++;
let entries: ASTExpression[] = [];
// dirty explicit check for an empty array -- should be fixed up
while (true) {
if (tmatch("special", "]", tokens[offset])) {
offset++;
break;
}
const { result, offset: newOffset } = consumeExpression(
tokens,
offset,
ctx
);
entries.push(result);
offset = newOffset;
if (tmatch("special", ",", tokens[offset])) {
offset++;
continue;
} else if (tmatch("special", "]", tokens[offset])) {
offset++;
break;
} else {
throw new ParseError(
"Unexpected token " + tokens[offset].value,
tokens[offset].position,
ctx.rawQuery
);
}
}
return {
result: {
type: "literal",
valueType: "array",
value: entries,
},
offset,
};
};
const consumeIndexer: Parser = (tokens, offset, ctx) => {
tmatchOrThrowBad("special", "[", tokens[offset]);
offset++;
let entries: ASTExpression[] = [];
while (true) {
// This could be simplified dramaticallly.
if (tmatch("special", ":", tokens[offset])) {
offset++;
entries.push({
type: "literal",
valueType: "null",
value: null,
});
continue;
} else if (tmatch("special", "]", tokens[offset])) {
offset++;
entries.push({
type: "literal",
valueType: "null",
value: null,
});
break;
}
const { result, offset: newOffset } = consumeExpression(
tokens,
offset,
ctx
);
entries.push(result);
offset = newOffset;
if (tmatch("special", ":", tokens[offset])) {
offset++;
continue;
} else if (tmatch("special", "]", tokens[offset])) {
offset++;
break;
} else {
throw new ParseError(
"Unexpected token " + tokens[offset].value,
tokens[offset].position,
ctx.rawQuery
);
}
}
const app: ASTExpression = {
type: "application",
function: {
type: "reference",
ref: "index",
internal: true,
},
arguments: entries,
};
return {
result: app,
offset,
};
};
const consumeStruct: Parser = (tokens, offset, ctx) => {
tmatchOrThrowBad("special", "{", tokens[offset]);
offset++;
let entries: { [key: string]: ASTExpression } = {};
while (true) {
if (tmatch("special", "}", tokens[offset])) {
offset++;
break;
}
if (tokens[offset] === undefined) {
throw new ParseError("Unexpected EOF", ctx.rawQuery.length, ctx.rawQuery);
}
let key: string;
if (tokens[offset].token === "ref" || tokens[offset].token === "value") {
key = tokens[offset].value.toString();
offset++;
} else {
throw new ParseError(
"Unexpected token " + tokens[offset].value,
tokens[offset].position,
ctx.rawQuery
);
}
tmatchOrThrow("special", ":", tokens[offset]);
offset++;
const { result, offset: newOffset } = consumeExpression(
tokens,
offset,
ctx
);
offset = newOffset;
entries[key] = result;
if (tmatch("special", ",", tokens[offset])) {
offset++;
continue;
} else if (tmatch("special", "}", tokens[offset])) {
offset++;
break;
} else {
throw new ParseError(
"Unexpected token " + tokens[offset].value,
tokens[offset].position,
ctx.rawQuery
);
}
}
return {
result: {
type: "literal",
valueType: "object",
value: entries,
},
offset,
};
};
const consumeDotAccess: ParameterizedParser = (left, tokens, offset, ctx) => {
tmatchOrThrowBad("special", ".", tokens[offset]);
offset++;
let ref: string;
let refToken = tokens[offset];
if (!refToken || refToken.token !== "ref") {
throw new ParseError(
"Unexpected token " + tokens[offset].value + ", expected :",
tokens[offset].position,
ctx.rawQuery
);
}
ref = refToken.value;
offset++;
const result: ASTExpression = {
type: "application",
function: {
type: "reference",
ref: ".",
internal: true,
},
arguments: [left, { type: "reference", ref: ref }],
};
return { result, offset };
};
// This might be the worst function i've ever written.
// But at least it's a contained transformation.
type BinaryExpressionSequence = { items: ASTExpression[]; joiners: string[] };
const turnBinaryExpressionSequenceIntoASTExpression = (
bexpseq: BinaryExpressionSequence
): ASTExpression => {
if (bexpseq.items.length === 0) {
throw new UnpositionableParseError("Tried to parse empty expression!");
}
if (bexpseq.items.length === 1 && bexpseq.joiners.length === 0) {
// this is the majority case by a long shot.
return bexpseq.items[0];
}
if (bexpseq.items.length - 1 !== bexpseq.joiners.length) {
throw new UnpositionableParseError(
"Invalid sequence of binary expressions!"
);
}
let current = bexpseq;
// First Stage: Simple Binary Expressions -> Applications
for (let i = 0; i < simpleBinaryOperators.length; i++) {
const currentPrecedenceLevel = simpleBinaryOperators[i];
const newItems = [current.items[0]];
const newJoiners = [];
for (let j = 0; j < current.joiners.length; j++) {
newItems.push(current.items[j + 1]);
if (currentPrecedenceLevel.indexOf(current.joiners[j]) > -1) {
const l = newItems[newItems.length - 2];
const r = newItems[newItems.length - 1];
newItems[newItems.length - 2] = {
type: "application",
function: {
type: "reference",
ref: current.joiners[j],
internal: true,
},
arguments: [l, r],
};
newItems.length = newItems.length - 1;
} else {
newJoiners.push(current.joiners[j]);
}
}
current = {
items: newItems,
joiners: newJoiners,
};
}
// Second Stage: Amalgamating Binary Expressions
for (let i = 0; i < amalgamatingBinaryOperators.length; i++) {
const currentExpression = amalgamatingBinaryOperators[i];
const newItems = [current.items[0]];
const newJoiners = [];
const amalgamationTechnique = amalgamationTechniques[currentExpression]!;
let streak: ASTExpression[] = [];
const flushStreak = () => {
if (streak.length > 0) {
newItems.push(amalgamationTechnique(streak));
streak = [];
}
};
for (let j = 0; j < current.joiners.length; j++) {
if (current.joiners[j] === currentExpression) {
if (streak.length === 0) {
streak.push(current.items[j]);
newItems.pop();
}
streak.push(current.items[j + 1]);
} else {
// Flush the current streak.
flushStreak();
newItems.push(current.items[j + 1]);
newJoiners.push(current.joiners[j]);
}
}
flushStreak();
current = {
items: newItems,
joiners: newJoiners,
};
}
if (current.joiners.length !== 0) {
throw new UnpositionableParseError(
"Expected expression following binary expression " + current.joiners[0]
);
}
return current.items[0];
};
const consumeExpression: Parser = (tokens, offset, ctx) => {
let items: ASTExpression[] = [];
let joiners: LexToken[] = [];
const itemPushGuard = (token: LexToken) => {
if (joiners.length !== items.length) {
// Now parsing an item, so guard
throw new ParseError(
"Unexpected Token " + token.value,
token.position,
ctx.rawQuery
);
}
};
const binExpDoesntMakeSense = () => {
return joiners.length + 1 !== items.length;
};
const joinerPushGuard = (token: LexToken) => {
if (binExpDoesntMakeSense()) {
// Now parsing an item, so guard
throw new ParseError(
"Unexpected Token " + token.value,
token.position,
ctx.rawQuery
);
}
};
while (offset < tokens.length) {
let next = tokens[offset];
// --- NASTY HACK ALERT ---
// Weird dirty hack that should be sorted out.
// only if binary expression WOULD throw, parse as a unary as a "backup"
let hackyUnaryPostProcess:
| ((ast: ASTExpression) => ASTExpression)
| undefined = undefined;
if (isUnExp(next) && binExpDoesntMakeSense()) {
// turn all further unaries into a big ol' stack.
let i = offset; // index of first non-unary item.
for (; i < tokens.length; i++) {
if (!isUnExp(tokens[i])) {
break;
}
}
const unaries = tokens.slice(offset, i);
offset = i;
next = tokens[offset];
hackyUnaryPostProcess = (item) =>
unaries.reduceRight(
(acc, cur) => ({
type: "application",
function: {
type: "reference",
ref: (cur.value as string) + "/unary",
internal: true,
},
arguments: [acc],
}),
item
);
}
if (tmatch("special", "(", next)) {
itemPushGuard(next);
const { result, offset: newOffset } = consumeParenthetical(
tokens,
offset,
ctx
);
items.push(result);
offset = newOffset;
} else if (tmatch("special", ".", next)) {
if (items.length === 0) {
throw new ParseError("Unexpected Token .", next.position, ctx.rawQuery);
}
const { result, offset: newOffset } = consumeDotAccess(
items.pop(),
tokens,
offset,
ctx
);
items.push(result);
offset = newOffset;
} else if (tmatch("special", "[", next)) {
// If it doesn't make sense as an item, then it should be parsed
// as an indexing expression instead!!
if (joiners.length === items.length) {
const { result, offset: newOffset } = consumeArray(tokens, offset, ctx);
items.push(result);
offset = newOffset;
} else {
// We can always postfix an expression with an indexing term. Binds at maximum depth.
// Replaces the previous
const { result: app, offset: newOffset } = consumeIndexer(
tokens,
offset,
ctx
);
items[items.length - 1] = {
type: "application",
function: (app as ASTApplicationExpression).function,
arguments: (app as ASTApplicationExpression).arguments.concat([
items[items.length - 1],
]),
};
offset = newOffset;
}
} else if (tmatch("special", "{", next)) {
itemPushGuard(next);
const { result, offset: newOffset } = consumeStruct(tokens, offset, ctx);
items.push(result);
offset = newOffset;
} else if (next.token === "value") {
itemPushGuard(next);
items.push({
type: "literal",
valueType: next.value !== null ? (typeof next.value as any) : "null",
value: next.value,
});
offset++;
} else if (next.token === "ref") {
itemPushGuard(next);
items.push({
type: "reference",
ref: next.value,
});
offset++;
} else if (isBinExp(next) && !hackyUnaryPostProcess) {
joinerPushGuard(next);
joiners.push(next);
offset++;
} else {
break;
// An unexpected token! Stop parsing this expression
}
// This is incredibly gross
if (hackyUnaryPostProcess) {
items[items.length - 1] = hackyUnaryPostProcess(items[items.length - 1]);
}
}
let resolvedSequence = turnBinaryExpressionSequenceIntoASTExpression({
items,
// We know the below is a string because we only add specials
joiners: joiners.map((joiner) => joiner.value as string),
});
// We can always postfix an expression with an indexing term. Binds at maximum depth.
if (tmatch("special", "[", tokens[offset])) {
const { result: app, offset: nextOffset } = consumeIndexer(
tokens,
offset,
ctx
);
resolvedSequence = {
type: "application",
function: (app as ASTApplicationExpression).function,
arguments: (app as ASTApplicationExpression).arguments.concat([
resolvedSequence,
]),
};
offset = nextOffset;
}
return {
result: turnBinaryExpressionSequenceIntoASTExpression({
items,
// We know the below is a string because we only add specials
joiners: joiners.map((joiner) => joiner.value as string),
}),
offset,
};
};
function parseQuery(tokens: LexToken[], ctx: ParseContext): ASTExpression {
const { result, offset } = consumeExpression(tokens, 0, ctx);
if (offset !== tokens.length) {
throw new ParseError(
"Unexpected token " + tokens[offset].value + ", expected EOF",
ctx.rawQuery.length,
ctx.rawQuery
);
}
return result;
}
function parse(raw: string): ASTExpression {
const lexed = lex(raw);
const ctx: ParseContext = {
rawQuery: raw,
}
const parsed = parseQuery(lexed, ctx);
return parsed;
}
export const parseOrThrow = parse; | the_stack |
import { FormGroup as NativeFormGroup } from '@angular/forms';
import { Observable } from 'rxjs';
import {
Status,
StringKeys,
ValidatorFn,
AsyncValidatorFn,
ValidatorsModel,
ValidationErrors,
AbstractControlOptions,
ControlType,
ExtractGroupValue,
} from './types';
export class FormGroup<T extends object = any, V extends object = ValidatorsModel> extends NativeFormGroup {
readonly value: ExtractGroupValue<T>;
readonly valueChanges: Observable<ExtractGroupValue<T>>;
readonly status: Status;
readonly statusChanges: Observable<Status>;
readonly errors: ValidationErrors<V> | null;
/**
* Creates a new `FormGroup` instance.
*
* @param controls A collection of child controls. The key for each child is the name
* under which it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains validation functions
* and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions
*
* @todo Chechout how to respect optional and require properties modifyers for the controls.
*/
constructor(
public controls: { [P in keyof T]: ControlType<T[P], V> },
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null
) {
super(controls, validatorOrOpts, asyncValidator);
}
/**
* Registers a control with the group's list of controls.
*
* This method does not update the value or validity of the control.
* Use [addControl](https://angular.io/api/forms/FormGroup#addControl) instead.
*
* @param name The control name to register in the collection
* @param control Provides the control for the given name
*/
registerControl<K extends StringKeys<T>, CV extends object = ValidatorsModel>(
name: K,
control: ControlType<T[K], CV>
) {
return super.registerControl(name, control) as ControlType<T[K], CV>;
}
/**
* Add a control to this group.
*
* This method also updates the value and validity of the control.
*
* @param name The control name to add to the collection
* @param control Provides the control for the given name
*/
addControl<K extends StringKeys<T>, CV extends object = ValidatorsModel>(name: K, control: ControlType<T[K], CV>) {
return super.addControl(name, control);
}
/**
* Remove a control from this group.
*
* @param name The control name to remove from the collection
*/
removeControl<K extends StringKeys<T>>(name: K) {
return super.removeControl(name);
}
/**
* Replace an existing control.
*
* @param name The control name to replace in the collection
* @param control Provides the control for the given name
*/
setControl<K extends StringKeys<T>, CV extends object = ValidatorsModel>(name: K, control: ControlType<T[K], CV>) {
return super.setControl(name, control);
}
/**
* Check whether there is an enabled control with the given name in the group.
*
* Reports false for disabled controls. If you'd like to check for existence in the group
* only, use [get](https://angular.io/api/forms/AbstractControl#get) instead.
*
* @param name The control name to check for existence in the collection
*
* @returns false for disabled controls, true otherwise.
*/
contains<K extends StringKeys<T>>(name: K) {
return super.contains(name);
}
/**
* Sets the value of the `FormGroup`. It accepts an object that matches
* the structure of the group, with control names as keys.
*
* ### Set the complete value for the form group
*
```ts
const form = new FormGroup({
first: new FormControl(),
last: new FormControl()
});
console.log(form.value); // {first: null, last: null}
form.setValue({first: 'Nancy', last: 'Drew'});
console.log(form.value); // {first: 'Nancy', last: 'Drew'}
```
*
* @throws When strict checks fail, such as setting the value of a control
* that doesn't exist or if you excluding the value of a control.
*
* @param value The new value for the control that matches the structure of the group.
* @param options Configuration options that determine how the control propagates changes
* and emits events after the value changes.
* The configuration options are passed to the
* [updateValueAndValidity](https://angular.io/api/forms/AbstractControl#updateValueAndValidity) method.
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
*/
setValue(value: ExtractGroupValue<T>, options: { onlySelf?: boolean; emitEvent?: boolean } = {}) {
return super.setValue(value, options);
}
/**
* Patches the value of the `FormGroup`. It accepts an object with control
* names as keys, and does its best to match the values to the correct controls
* in the group.
*
* It accepts both super-sets and sub-sets of the group without throwing an error.
*
* ### Patch the value for a form group
*
```ts
const form = new FormGroup({
first: new FormControl(),
last: new FormControl()
});
console.log(form.value); // {first: null, last: null}
form.patchValue({first: 'Nancy'});
console.log(form.value); // {first: 'Nancy', last: null}
```
*
* @param value The object that matches the structure of the group.
* @param options Configuration options that determine how the control propagates changes and
* emits events after the value is patched.
* * `onlySelf`: When true, each change only affects this control and not its parent. Default is
* true.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
* The configuration options are passed to the
* [updateValueAndValidity](https://angular.io/api/forms/AbstractControl#updateValueAndValidity) method.
*/
patchValue(value: Partial<ExtractGroupValue<T>>, options: { onlySelf?: boolean; emitEvent?: boolean } = {}) {
return super.patchValue(value, options);
}
/**
* Resets the `FormGroup`, marks all descendants are marked `pristine` and `untouched`, and
* the value of all descendants to null.
*
* You reset to a specific form state by passing in a map of states
* that matches the structure of your form, with control names as keys. The state
* is a standalone value or a form state object with both a value and a disabled
* status.
*
* @param formState Resets the control with an initial value,
* or an object that defines the initial value and disabled state.
*
* @param options Configuration options that determine how the control propagates changes
* and emits events when the group is reset.
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is reset.
* When false, no events are emitted.
* The configuration options are passed to the
* [updateValueAndValidity](https://angular.io/api/forms/AbstractControl#updateValueAndValidity) method.
*
*
* ### Reset the form group values
*
```ts
const form = new FormGroup({
first: new FormControl('first name'),
last: new FormControl('last name')
});
console.log(form.value); // {first: 'first name', last: 'last name'}
form.reset({ first: 'name', last: 'last name' });
console.log(form.value); // {first: 'name', last: 'last name'}
```
*
* ### Reset the form group values and disabled status
*
```ts
const form = new FormGroup({
first: new FormControl('first name'),
last: new FormControl('last name')
});
form.reset({
first: {value: 'name', disabled: true},
last: 'last'
});
console.log(this.form.value); // {first: 'name', last: 'last name'}
console.log(this.form.get('first').status); // 'DISABLED'
```
*/
reset(value: ExtractGroupValue<T> = {} as any, options: { onlySelf?: boolean; emitEvent?: boolean } = {}) {
return super.reset(value, options);
}
/**
* The aggregate value of the `FormGroup`, including any disabled controls.
*
* Retrieves all values regardless of disabled status.
* The `value` property is the best way to get the value of the group, because
* it excludes disabled controls in the `FormGroup`.
*/
getRawValue() {
return super.getRawValue() as ExtractGroupValue<T>;
}
/**
* Retrieves a child control given the control's name.
*
* ### Retrieve a nested control
*
* For example, to get a `name` control nested within a `person` sub-group:
```ts
this.form.get('person').get('name');
```
*/
get<K extends StringKeys<T>, CV extends object = ValidatorsModel>(controlName: K): ControlType<T[K], CV> | null {
return super.get(controlName) as ControlType<T[K], CV> | null;
}
/**
* Sets the synchronous validators that are active on this control. Calling
* this overwrites any existing sync validators.
*/
setValidators(newValidator: ValidatorFn | ValidatorFn[] | null) {
return super.setValidators(newValidator);
}
/**
* Sets the async validators that are active on this control. Calling this
* overwrites any existing async validators.
*/
setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[] | null) {
return super.setAsyncValidators(newValidator);
}
/**
* Sets errors on a form control when running validations manually, rather than automatically.
*
* Calling `setErrors` also updates the validity of the parent control.
*
* ### Manually set the errors for a control
*
* ```ts
* const login = new FormControl('someLogin');
* login.setErrors({
* notUnique: true
* });
*
* expect(login.valid).toEqual(false);
* expect(login.errors).toEqual({ notUnique: true });
*
* login.setValue('someOtherLogin');
*
* expect(login.valid).toEqual(true);
* ```
*/
setErrors(errors: ValidationErrors | null, opts: { emitEvent?: boolean } = {}) {
return super.setErrors(errors, opts);
}
/**
* Reports error data for the control with the given controlName.
*
* @param errorCode The code of the error to check
* @param controlName A control name that designates how to move from the current control
* to the control that should be queried for errors.
*
* For example, for the following `FormGroup`:
*
```ts
form = new FormGroup({
address: new FormGroup({ street: new FormControl() })
});
```
*
* The controlName to the 'street' control from the root form would be 'address' -> 'street'.
*
* It can be provided to this method in combination with `get()` method:
*
```ts
form.get('address').getError('someErrorCode', 'street');
```
*
* @returns error data for that particular error. If the control or error is not present,
* null is returned.
*/
getError<P extends StringKeys<V>, K extends StringKeys<T>>(errorCode: P, controlName?: K) {
return super.getError(errorCode, controlName) as V[P] | null;
}
/**
* Reports whether the control with the given controlName has the error specified.
*
* @param errorCode The code of the error to check
* @param controlName A control name that designates how to move from the current control
* to the control that should be queried for errors.
*
* For example, for the following `FormGroup`:
*
```ts
form = new FormGroup({
address: new FormGroup({ street: new FormControl() })
});
```
*
* The controlName to the 'street' control from the root form would be 'address' -> 'street'.
*
* It can be provided to this method in combination with `get()` method:
```ts
form.get('address').hasError('someErrorCode', 'street');
```
*
* If no controlName is given, this method checks for the error on the current control.
*
* @returns whether the given error is present in the control at the given controlName.
*
* If the control is not present, false is returned.
*/
hasError<P extends StringKeys<V>, K extends StringKeys<T>>(errorCode: P, controlName?: K) {
return super.hasError(errorCode, controlName);
}
} | the_stack |
declare namespace smarthome {
/**
* Request and response interfaces for communicating with local devices
* over BLE, TCP, UDP, and HTTP.
* @preferred
*/
namespace DataFlow {
interface BleOptions {
characteristicUuid: string;
serviceUuid: string;
operation: Constants.BleOperation;
waitForNotification?: boolean;
mtu?: number;
}
interface BleRequestData extends Command, BleOptions {}
/** For sending BLE commands using DeviceManager.send API. */
class BleRequestData implements BleRequestData {}
interface BleResponse {
value: string;
characteristicUuid: string;
serviceUuid: string;
}
/** Describes the response for a BLE Request. */
interface BleResponseData extends CommandSuccess {
bleResponse: BleResponse;
}
interface HttpOptions {
/** HTTP Content-Type header */
dataType: string;
/**
* List of HTTP headers for the request.
* @deprecated use [[HttpRequestData.additionalHeaders]]
*/
headers: string;
/**
* Additional HTTP headers for the request, as an object containing
* key/value pairs.
* ```
* {
* 'Authorization': 'Bearer ...',
* 'Accept': 'application/json',
* }
* ```
*/
additionalHeaders: {[key: string]: string};
/** @hidden @deprecated True to send using HTTPS, false for HTTP */
isSecure?: boolean;
/** HTTP method to perform */
method: Constants.HttpOperation;
/** URI path on the target device */
path: string;
/** Port number on the target device. Default is port 80. */
port?: number;
}
/** Content of an HTTP response */
interface HttpResponse {
/** HTTP response code */
statusCode: number;
/** HTTP response body */
body: unknown;
}
/** @hidden */
interface Template {}
/** @hidden Supported Cipher Suites */
type CipherSuites = 'EC-JPAKE';
interface TcpOptions {
/** @hidden True to enable TLS for this request */
isSecure?: boolean;
/** Port number on the target device */
port: number;
/** TCP operation to perform */
operation: Constants.TcpOperation;
/** Hostname on the target device */
hostname?: string;
/** For read requests, number of expected bytes */
bytesToRead?: number;
/** @hidden Cipher suite to be used for TLS */
cipher?: CipherSuites;
/** @hidden Short code needed with EC-JPAKE */
shortCode?: string;
}
/** Content of a TCP response */
interface TcpResponse {
/** Hex-encoded payload received from the device. */
data: string;
}
interface UdpOptions {
/** Port number on the target device */
port: number;
/**
* Expected number of UDP response packets. Actual number of packets
* received in the [[UdpResponseData]] may not match expected value if
* timeout of 1 second is exceeded.
*/
expectedResponsePackets?: number;
}
/** Content of a UDP response */
interface UdpResponse {
/** Array of hex-encoded packets received from the device. */
responsePackets?: string[];
}
interface CommandBase {
/** Request ID from the associated `EXECUTE` intent. */
requestId: string;
/** Device ID of the target device. */
deviceId: string;
/** Protocol to use when sending this command */
protocol: Constants.Protocol;
}
interface Command extends CommandBase {
/** Payload sent to the target device */
data: string;
/** @hidden Experimental feature, to apply template parameters to data */
template?: Template;
}
interface HttpRequestData extends Command, HttpOptions {}
interface TcpRequestData extends Command, TcpOptions {}
interface UdpRequestData extends Command, UdpOptions {}
/**
* Request to send a local device command over HTTP.
* Commands are sent to the device using [[DeviceManager.send]].
*
* Example [[GET]] request:
* ```typescript
* const command = new DataFlow.HttpRequestData();
* command.requestId = request.requestId;
* command.deviceId = 'device-id';
* command.method = Constants.HttpOperation.GET;
* command.port = 80;
* command.path = '/endpoint/control?state=on';
* ```
*
* Example [[POST]] request:
* ```typescript
* const postData = {
* on: true,
* };
*
* const command = new DataFlow.HttpRequestData();
* command.requestId = request.requestId;
* command.deviceId = 'device-id';
* command.method = Constants.HttpOperation.POST;
* command.port = 80;
* command.path = '/endpoint/control';
* command.dataType = 'application/json';
* command.data = JSON.stringify(postData);
* ```
*
* ## Handle the response
*
* If the command succeeds, [[DeviceManager.send]] returns an
* [[HttpResponseData]] result, which contains the [[HttpResponse]].
*
* ```typescript
* const command = new DataFlow.HttpRequestData();
* ...
*
* localHomeApp.getDeviceManager()
* .send(command)
* .then((result: DataFlow.CommandSuccess) => {
* const httpResult = result as DataFlow.HttpResponseData;
* const responseBody = httpResult.httpResponse.body;
* })
* .catch((err: IntentFlow.HandlerError) => {
* // Handle command error
* });
* ```
*/
class HttpRequestData implements HttpRequestData {}
/**
* Request to send a local device command over TCP sockets.
* Commands are sent to the device using [[DeviceManager.send]].
*
* Example TCP command:
* ```typescript
* const payload = new Uint8Array([0x00, 0xFF, 0x00, 0xFF]);
*
* const command = new DataFlow.TcpRequestData();
* command.requestId = request.requestId;
* command.deviceId = 'device-id';
* command.port = 5555;
* command.operation = Constants.TcpOperation.WRITE;
* command.data = Buffer.from(payload).toString('hex');
* ```
*
* ## Handle the response
*
* If the command succeeds, [[DeviceManager.send]] returns a
* [[TcpResponseData]] result. For [[TcpOperation.READ]] commands, the
* result contains a [[TcpResponse]].
*
* ```typescript
* const command = new DataFlow.TcpRequestData();
* command.operation = Constants.TcpOperation.READ;
* ...
*
* localHomeApp.getDeviceManager()
* .send(command)
* .then((result: DataFlow.CommandSuccess) => {
* const tcpResult = result as DataFlow.TcpResponseData;
* const response = tcpResult.tcpResponse.data;
* })
* .catch((err: IntentFlow.HandlerError) => {
* // Handle command error
* });
* ```
*/
class TcpRequestData implements TcpRequestData {}
/**
* Request to send a local device command over UDP datagram.
* Commands are sent to the device using [[DeviceManager.send]].
*
* Example UDP command:
* ```typescript
* const payload = new Uint8Array([0x00, 0xFF, 0x00, 0xFF]);
*
* const command = new DataFlow.UdpRequestData();
* command.requestId = request.requestId;
* command.deviceId = 'device-id';
* command.port = 5555;
* command.data = Buffer.from(payload).toString('hex');
* command.expectedResponsePackets = 1;
* ```
*
* ## Handle the response
*
* If the command succeeds, [[DeviceManager.send]] returns a
* [[UdpResponseData]] result. For commands with
* [[UdpRequestData.expectedResponsePackets]] set, the result contains a
* [[UdpResponse]].
*
* ```typescript
* const command = new DataFlow.UdpRequestData();
* command.expectedResponsePackets = 1;
* ...
*
* localHomeApp.getDeviceManager()
* .send(command)
* .then((result: DataFlow.CommandSuccess) => {
* const udpResult = result as DataFlow.UdpResponseData;
* const packets = udpResult.udpResponse.responsePackets;
* })
* .catch((err: IntentFlow.HandlerError) => {
* // Handle command error
* });
* ```
*/
class UdpRequestData implements UdpRequestData {}
/**
* Successful response to a [[DeviceManager]] command.
*/
interface CommandSuccess extends CommandBase {}
/** Command result containing an [[HttpResponse]]. */
interface HttpResponseData extends CommandSuccess {
/** Response to an HTTP request */
httpResponse: HttpResponse;
}
/** Command result containing a [[TcpResponse]]. */
interface TcpResponseData extends CommandSuccess {
/** Response to a TCP request */
tcpResponse: TcpResponse;
}
/** Command result containing a [[UdpResponse]]. */
interface UdpResponseData extends CommandSuccess {
/** Response to a UDP request. */
udpResponse: UdpResponse;
}
/**
* Response to a [[DeviceManager]] command that resulted
* in an error.
*
* @deprecated See [[HandlerError]] for handling command failures.
*/
interface CommandFailure extends CommandBase {
/** The cause for this error */
errorCode: string;
/** Human readable description of this error */
debugString?: string;
}
}
/**
* Options for [[DeviceManager.send]] API.
* Use `send(command, {commandTimeout: 1000});` to wait for the platform to
* respond with success or timeout after 1000ms.
* Use `send(command, {retries: 2, delayInMilliseconds: 20});` to retry a
* command 2 times with 20ms delay between each retry.
*/
interface SendOptions {
/**
* Waits for command response for upto `commandTimeout` ms but no less than
* 1000ms. Usage outside execute handler is not recommended. In addition, it
* should be used only when platform provided timeouts are not enough.
*/
commandTimeout?: number;
/**
* Retries the command upto `retries` times upto 3 times. `commandTimeout`
* applies to each command. Each retry will also get the timeout.
*/
retries?: number;
/** Delay in ms between each retry. Default is no-delay between commands. */
delayInMilliseconds?: number;
}
} | the_stack |
import * as Json from "jsonc-parser"
import forEach = require("lodash/forEach")
import noop = require("lodash/noop")
import {
DocumentType,
JSONSchema,
JSONSchemaMap,
YAMLDocument
} from "@serverless-ide/config"
import { TextDocument } from "vscode-languageserver"
import * as nls from "vscode-nls"
import URI from "vscode-uri"
import { sendException } from "../analytics"
import requestService from "../request"
import { applyDocumentMutations } from "./mutation"
const localize = nls.loadMessageBundle()
function getParseErrorMessage(errorCode: Json.ParseErrorCode): string {
switch (errorCode) {
case Json.ParseErrorCode.InvalidSymbol:
return localize("error.invalidSymbol", "Invalid symbol")
case Json.ParseErrorCode.InvalidNumberFormat:
return localize(
"error.invalidNumberFormat",
"Invalid number format"
)
case Json.ParseErrorCode.PropertyNameExpected:
return localize(
"error.propertyNameExpected",
"Property name expected"
)
case Json.ParseErrorCode.ValueExpected:
return localize("error.valueExpected", "Value expected")
case Json.ParseErrorCode.ColonExpected:
return localize("error.colonExpected", "Colon expected")
case Json.ParseErrorCode.CommaExpected:
return localize("error.commaExpected", "Comma expected")
case Json.ParseErrorCode.CloseBraceExpected:
return localize(
"error.closeBraceExpected",
"Closing brace expected"
)
case Json.ParseErrorCode.CloseBracketExpected:
return localize(
"error.closeBracketExpected",
"Closing bracket expected"
)
case Json.ParseErrorCode.EndOfFileExpected:
return localize("error.endOfFileExpected", "End of file expected")
default:
return ""
}
}
// tslint:disable-next-line: max-classes-per-file
export class UnresolvedSchema {
schema: JSONSchema
errors: string[]
constructor(schema: JSONSchema, errors: string[] = []) {
this.schema = schema
this.errors = errors
}
}
// tslint:disable-next-line: max-classes-per-file
export class ResolvedSchema {
schema: JSONSchema
errors: string[]
constructor(schema: JSONSchema, errors: string[] = []) {
this.schema = schema
this.errors = errors
}
getLastDescription(path: string[]): string | void {
let description = undefined
this.getSectionRecursive(path, this.schema, schemaNode => {
if (schemaNode && schemaNode.description) {
description = schemaNode.description
}
})
return description
}
getSection(path: string[]): JSONSchema | null {
return this.getSectionRecursive(path, this.schema)
}
private getSectionRecursive(
path: string[],
schema: JSONSchema,
visitor: (schema: JSONSchema) => void = noop
): JSONSchema | null {
visitor(schema)
if (!schema || path.length === 0) {
return schema
}
// independently process each "oneOf" entry to see if our path matches any of them
if (schema.oneOf && Array.isArray(schema.oneOf)) {
for (const oneOfEntry of schema.oneOf) {
const result = this.getSectionRecursive(
path.slice(),
oneOfEntry,
visitor
)
if (result) {
// found a match, no need to look further
return result
}
}
return null
}
const next = path.shift()
if (!next) {
return null
}
if (schema.properties && schema.properties[next]) {
return this.getSectionRecursive(
path,
schema.properties[next],
visitor
)
} else if (schema.patternProperties) {
Object.keys(schema.patternProperties).forEach(pattern => {
const regex = new RegExp(pattern)
if (regex.test(next)) {
return this.getSectionRecursive(
path,
schema.patternProperties[pattern],
visitor
)
}
})
} else if (schema.additionalProperties) {
return this.getSectionRecursive(
path,
schema.additionalProperties,
visitor
)
} else if (next.match("[0-9]+")) {
if (schema.items) {
return this.getSectionRecursive(path, schema.items, visitor)
} else if (Array.isArray(schema.items)) {
try {
const index = parseInt(next, 10)
if (schema.items[index]) {
return this.getSectionRecursive(
path,
schema.items[index],
visitor
)
}
return null
} catch (err) {
sendException(err)
return null
}
}
}
return null
}
}
const resolveSchemaContent = async (
schemaToResolve: UnresolvedSchema
): Promise<ResolvedSchema> => {
const resolveErrors: string[] = schemaToResolve.errors.slice(0)
const schema = schemaToResolve.schema
const findSection = (
selectonSchema: JSONSchema,
path: string
): JSONSchema | false => {
if (!path) {
return selectonSchema
}
let current = selectonSchema
if (path[0] === "/") {
path = path.substr(1)
}
path.split("/").some(part => {
current = current[part]
return !current
})
return current
}
const resolveLink = (
node: any,
linkedSchema: JSONSchema,
linkPath: string
): void => {
const section = findSection(linkedSchema, linkPath)
if (section) {
for (const key in section) {
if (section.hasOwnProperty(key) && !node.hasOwnProperty(key)) {
node[key] = section[key]
}
}
} else {
resolveErrors.push(
localize(
"json.schema.invalidref",
"$ref '{0}' in {1} can not be resolved.",
linkPath,
linkedSchema.id
)
)
}
delete node.$ref
}
const resolveRefs = (
node: JSONSchema,
parentSchema: JSONSchema
): Promise<any> => {
if (!node) {
return Promise.resolve(null)
}
const toWalk: JSONSchema[] = [node]
const seen: JSONSchema[] = []
const openPromises: Promise<any>[] = []
const collectEntries = (...entries: JSONSchema[]) => {
for (const entry of entries) {
if (typeof entry === "object") {
toWalk.push(entry)
}
}
}
const collectMapEntries = (...maps: JSONSchemaMap[]) => {
for (const map of maps) {
if (typeof map === "object") {
forEach(map, (value, key) => {
const entry = map[key]
toWalk.push(entry)
})
}
}
}
const collectArrayEntries = (...arrays: JSONSchema[][]) => {
for (const array of arrays) {
if (Array.isArray(array)) {
toWalk.push.apply(toWalk, array)
}
}
}
while (toWalk.length) {
const next = toWalk.pop()
if (seen.indexOf(next) >= 0) {
continue
}
seen.push(next)
if (next.$ref) {
const segments = next.$ref.split("#", 2)
resolveLink(next, parentSchema, segments[1])
}
collectEntries(next.items, next.additionalProperties, next.not)
collectMapEntries(
next.definitions,
next.properties,
next.patternProperties,
next.dependencies as JSONSchemaMap
)
collectArrayEntries(
next.anyOf,
next.allOf,
next.oneOf,
next.items as JSONSchema[]
)
}
return Promise.all(openPromises)
}
await resolveRefs(schema, schema)
return new ResolvedSchema(schema, resolveErrors)
}
interface PartialSchema {
properties: {
[key: string]: ResolvedSchema
}
global?: ResolvedSchema
}
// tslint:disable-next-line: max-classes-per-file
export class JSONSchemaService {
private schemas: { [Key in DocumentType]: Promise<ResolvedSchema | void> }
private partialSchemas: { [uri: string]: PartialSchema }
constructor() {
const samSchema = require("@serverless-ide/sam-schema/schema.json") as JSONSchema
const cloudformationSchema = require("@serverless-ide/cloudformation-schema/schema.json") as JSONSchema
const serverlessFrameworkSchema = require("@serverless-ide/serverless-framework-schema/schema.json") as JSONSchema
this.schemas = {
[DocumentType.CLOUD_FORMATION]: resolveSchemaContent(
new UnresolvedSchema(cloudformationSchema)
),
[DocumentType.SAM]: resolveSchemaContent(
new UnresolvedSchema(samSchema)
),
[DocumentType.SERVERLESS_FRAMEWORK]: resolveSchemaContent(
new UnresolvedSchema(serverlessFrameworkSchema)
),
[DocumentType.UNKNOWN]: Promise.resolve(undefined)
}
this.partialSchemas = {}
}
async getSchemaForDocument(
document: TextDocument,
yamlDocument: YAMLDocument
): Promise<ResolvedSchema | void> {
if (this.partialSchemas[document.uri]) {
return this.getPartialSchemaForDocumentUri(document.uri)
} else {
const schema = await this.getSchemaForDocumentType(
yamlDocument.documentType
)
if (schema) {
return applyDocumentMutations(schema, yamlDocument)
}
}
}
async getPartialSchemaForDocumentUri(
uri: string
): Promise<ResolvedSchema | void> {
const partialSchema = this.partialSchemas[uri]
if (partialSchema) {
let schema: JSONSchema = { allOf: [] }
if (partialSchema.global) {
schema.allOf.push(partialSchema.global.schema)
}
forEach(
partialSchema.properties,
(propertySchema: ResolvedSchema, key: string) => {
schema.allOf.push({
type: "object",
properties: {
[key]: propertySchema.schema
},
required: [key]
})
}
)
if (schema.allOf.length === 1) {
schema = schema.allOf[0]
}
return new ResolvedSchema(schema)
}
}
registerPartialSchema(uri: string, schema: JSONSchema, property?: string) {
const resolvedSchema = new ResolvedSchema(schema)
if (!this.partialSchemas[uri]) {
this.partialSchemas[uri] = {
properties: {}
}
}
if (property) {
this.partialSchemas[uri].properties[property] = resolvedSchema
} else {
this.partialSchemas[uri].global = resolvedSchema
}
}
clearPartialSchema(uri: string) {
delete this.partialSchemas[uri]
}
private async getSchemaForDocumentType(documentType: DocumentType) {
return await this.schemas[documentType]
}
private async loadSchema(url: string): Promise<UnresolvedSchema> {
try {
const content = await requestService(url)
if (!content) {
const errorMessage = localize(
"json.schema.nocontent",
"Unable to load schema from '{0}': No content.",
toDisplayString(url)
)
const defaultSchema: JSONSchema = {}
return new UnresolvedSchema(defaultSchema, [errorMessage])
}
let schemaContent: JSONSchema = {}
const jsonErrors = []
schemaContent = Json.parse(content, jsonErrors)
const errors = jsonErrors.length
? [
localize(
"json.schema.invalidFormat",
"Unable to parse content from '{0}': {1}.",
toDisplayString(url),
getParseErrorMessage(jsonErrors[0])
)
]
: []
return new UnresolvedSchema(schemaContent, errors)
} catch (error) {
const errorMessage = localize(
"json.schema.unabletoload",
"Unable to load schema from '{0}': {1}",
toDisplayString(url),
error.toString()
)
const defaultSchema: JSONSchema = {}
return new UnresolvedSchema(defaultSchema, [errorMessage])
}
}
}
function toDisplayString(url: string) {
try {
const uri = URI.parse(url)
if (uri.scheme === "file") {
return uri.fsPath
}
} catch (e) {
// ignore
}
return url
} | the_stack |
import React from "react";
import { User } from "../../../app/auth/auth_service";
import Button, { OutlinedButton } from "../../../app/components/button/button";
import CheckboxButton from "../../../app/components/button/checkbox_button";
import Checkbox from "../../../app/components/checkbox/checkbox";
import alertService from "../../../app/alert/alert_service";
import errorService from "../../../app/errors/error_service";
import rpcService from "../../../app/service/rpc_service";
import { grp } from "../../../proto/group_ts_proto";
import Modal from "../../../app/components/modal/modal";
import Dialog, {
DialogBody,
DialogFooter,
DialogFooterButtons,
DialogHeader,
DialogTitle,
} from "../../../app/components/dialog/dialog";
import Select, { Option } from "../../../app/components/select/select";
import { user_id } from "../../../proto/user_id_ts_proto";
import Spinner from "../../../app/components/spinner/spinner";
export type OrgMembersProps = {
user: User;
};
type State = {
loading?: boolean;
response?: grp.GetGroupUsersResponse;
isSelectingAll?: boolean;
selectedUserIds: Set<string>;
isEditRoleModalVisible?: boolean;
roleToApply?: grp.Group.Role;
isRoleUpdateLoading?: boolean;
isRemoveModalVisible?: boolean;
isRemoveLoading?: boolean;
};
const ROLE_LABELS: Record<grp.Group.Role, string> = {
[grp.Group.Role.UNKNOWN_ROLE]: "",
[grp.Group.Role.ADMIN_ROLE]: "Admin",
[grp.Group.Role.DEVELOPER_ROLE]: "Developer",
};
const DEFAULT_ROLE = grp.Group.Role.DEVELOPER_ROLE;
export default class OrgMembersComponent extends React.Component<OrgMembersProps, State> {
state: State = {
loading: true,
selectedUserIds: new Set<string>(),
roleToApply: DEFAULT_ROLE,
};
componentDidMount() {
this.fetch();
}
private fetch() {
this.setState({ loading: true });
rpcService.service
.getGroupUsers(
new grp.GetGroupUsersRequest({
groupId: this.props.user.selectedGroup.id,
// Only show existing members in this table for now.
// TODO(bduffany): render 2 separate tables; one for membership
// requests and one for existing members.
groupMembershipStatus: [grp.GroupMembershipStatus.MEMBER],
})
)
.then((response) => this.setState({ response }))
.catch((e) => errorService.handleError(e))
.finally(() => this.setState({ loading: false }));
}
private onClickRow(userID: string) {
const clone = new Set(this.state.selectedUserIds);
if (clone.has(userID)) {
clone.delete(userID);
} else {
clone.add(userID);
}
this.setState({
isSelectingAll: (this.state.isSelectingAll && clone.size > 0) || clone.size === this.state.response.user.length,
selectedUserIds: clone,
});
}
private onClickSelectAllToggle() {
if (this.state.isSelectingAll) {
this.setState({
isSelectingAll: false,
selectedUserIds: new Set(),
});
} else {
this.setState({
isSelectingAll: true,
selectedUserIds: new Set(this.state.response.user.map((member) => member.user.userId.id)),
});
}
}
// Edit role modal
private onClickEditRole() {
this.setState({
isEditRoleModalVisible: true,
// Set the initially selected role to match the current role of the
// first user. This is a sensible default when there's only one user
// selected.
roleToApply: this.getSelectedMembers()[0]?.role || DEFAULT_ROLE,
});
}
private onRequestCloseEditRoleModal() {
if (this.state.isRoleUpdateLoading) return;
this.setState({ isEditRoleModalVisible: false });
}
private onChangeRoleToApply(event: React.ChangeEvent) {
const roleToApply = Number((event.target as HTMLSelectElement).value) as grp.Group.Role;
this.setState({ roleToApply });
}
private onClickApplyRoleEdits() {
this.setState({ isRoleUpdateLoading: true });
rpcService.service
.updateGroupUsers(
new grp.UpdateGroupUsersRequest({
groupId: this.props.user.selectedGroup.id,
update: [...this.state.selectedUserIds].map(
(id) =>
new grp.UpdateGroupUsersRequest.Update({
userId: new user_id.UserId({ id }),
role: this.state.roleToApply,
})
),
})
)
.then(() => {
alertService.success("Changes applied successfully.");
this.setState({
isEditRoleModalVisible: false,
selectedUserIds: new Set(),
});
this.fetch();
})
.catch((e) => errorService.handleError(e))
.finally(() => this.setState({ isRoleUpdateLoading: false }));
}
// Remove modal
private onClickRemove() {
this.setState({ isRemoveModalVisible: true });
}
private onRequestCloseRemoveModal() {
if (this.state.isRemoveLoading) return;
this.setState({ isRemoveModalVisible: false });
}
private onClickConfirmRemove() {
this.setState({ isRemoveLoading: true });
rpcService.service
.updateGroupUsers(
new grp.UpdateGroupUsersRequest({
groupId: this.props.user.selectedGroup.id,
update: [...this.state.selectedUserIds].map(
(id) =>
new grp.UpdateGroupUsersRequest.Update({
userId: new user_id.UserId({ id }),
membershipAction: grp.UpdateGroupUsersRequest.Update.MembershipAction.REMOVE,
})
),
})
)
.then(() => {
alertService.success("Changes applied successfully.");
this.setState({
isRemoveModalVisible: false,
selectedUserIds: new Set(),
});
this.fetch();
})
.catch((e) => errorService.handleError(e))
.finally(() => this.setState({ isRemoveLoading: false }));
}
private isLoggedInUser(member: grp.GetGroupUsersResponse.IGroupUser) {
return member.user.userId.id === this.props.user.displayUser.userId.id;
}
private getSelectedMembers(): grp.GetGroupUsersResponse.IGroupUser[] {
return this.state.response.user.filter((member) => this.state.selectedUserIds.has(member.user.userId.id));
}
private renderAffectedUsersList({ verb }: { verb: string }) {
const selectedMembers = this.getSelectedMembers();
return (
<>
<div>
{verb} <b>{selectedMembers.length}</b> user{selectedMembers.length === 1 ? "" : "s"}:
</div>
<div className="affected-users-list">
{selectedMembers.map((member) => (
<div className={`affected-users-list-item ${this.isLoggedInUser(member) ? "flagged-self-user" : ""}`}>
{member.user.email}
</div>
))}
</div>
{selectedMembers.some((member) => this.isLoggedInUser(member)) && (
<div className="editing-self-warning">
<b>Warning</b>: Your account is selected.
</div>
)}
</>
);
}
render() {
if (this.state.loading) {
return <div className="loading" />;
}
if (!this.state.response) return null;
const isSelectionEmpty = this.state.selectedUserIds.size === 0;
return (
<div className="org-members">
<div className="org-members-list-controls">
<CheckboxButton
className="select-all-button"
checked={this.state.isSelectingAll}
onClick={this.onClickSelectAllToggle.bind(this)}
checkboxOnLeft>
Select all
</CheckboxButton>
<Button onClick={this.onClickEditRole.bind(this)} disabled={isSelectionEmpty}>
Edit role
</Button>
<Button
onClick={this.onClickRemove.bind(this)}
disabled={isSelectionEmpty}
className="destructive org-member-remove-button">
Remove
</Button>
</div>
<div className="org-members-list">
{this.state.response.user.map((member) => (
<div
className={`org-members-list-item ${
this.state.selectedUserIds.has(member.user.userId.id) ? "selected" : ""
}`}
onClick={this.onClickRow.bind(this, member.user.userId.id)}>
<div>
<Checkbox
title={`Select ${member.user.email}`}
className="org-member-checkbox"
checked={this.state.selectedUserIds.has(member.user.userId.id)}
/>
</div>
<div className="org-member-email">{member.user.email}</div>
<div className="org-member-role">{ROLE_LABELS[member.role]}</div>
</div>
))}
</div>
{/* Edit role modal */}
<Modal
className="org-members-edit-modal"
isOpen={Boolean(this.state.isEditRoleModalVisible)}
onRequestClose={this.onRequestCloseEditRoleModal.bind(this)}>
<Dialog>
<DialogHeader>
<DialogTitle>Edit role</DialogTitle>
</DialogHeader>
<DialogBody className="modal-body">
{this.renderAffectedUsersList({ verb: "Editing" })}
<div className="select-role-row">
<div>Role</div>
<Select value={this.state.roleToApply} onChange={this.onChangeRoleToApply.bind(this)}>
<Option value={grp.Group.Role.DEVELOPER_ROLE}>{ROLE_LABELS[grp.Group.Role.DEVELOPER_ROLE]}</Option>
<Option value={grp.Group.Role.ADMIN_ROLE}>{ROLE_LABELS[grp.Group.Role.ADMIN_ROLE]}</Option>
</Select>
</div>
<div className="role-description">
{/* TODO(bduffany): Get role metadata from the server so that we
don't have to keep these descriptions in sync. */}
{this.state.roleToApply === grp.Group.Role.DEVELOPER_ROLE && (
<>
Developers can view invocations and stats, but do not have access to org settings, usage data, or
workflow configuration.
</>
)}
{this.state.roleToApply === grp.Group.Role.ADMIN_ROLE && (
<>
Admins have <b>full access</b> to all data within the organization.
</>
)}
</div>
</DialogBody>
<DialogFooter>
<DialogFooterButtons>
{this.state.isRoleUpdateLoading && <Spinner />}
<OutlinedButton
onClick={this.onRequestCloseEditRoleModal.bind(this)}
disabled={this.state.isRoleUpdateLoading}>
Cancel
</OutlinedButton>
<Button onClick={this.onClickApplyRoleEdits.bind(this)} disabled={this.state.isRoleUpdateLoading}>
Apply
</Button>
</DialogFooterButtons>
</DialogFooter>
</Dialog>
</Modal>
{/* Remove modal */}
<Modal
className="org-members-edit-modal"
isOpen={Boolean(this.state.isRemoveModalVisible)}
onRequestClose={this.onRequestCloseRemoveModal.bind(this)}>
<Dialog>
<DialogHeader>
<DialogTitle>Confirm removal</DialogTitle>
</DialogHeader>
<DialogBody className="modal-body">{this.renderAffectedUsersList({ verb: "Removing" })}</DialogBody>
<DialogFooter>
<DialogFooterButtons>
{this.state.isRemoveLoading && <Spinner />}
<OutlinedButton
onClick={this.onRequestCloseRemoveModal.bind(this)}
disabled={this.state.isRemoveLoading}>
Cancel
</OutlinedButton>
<Button
className="destructive"
onClick={this.onClickConfirmRemove.bind(this)}
disabled={this.state.isRemoveLoading}>
Remove
</Button>
</DialogFooterButtons>
</DialogFooter>
</Dialog>
</Modal>
</div>
);
}
} | the_stack |
import {Balloon} from '../api/balloon';
import {Emitter, EventHandlerMap} from '../event';
import {Plugins} from '../plugins';
import * as utils from '../utils/utils';
import * as utilsDom from '../utils/utils-dom';
import {
d3_setClasses as setClasses,
d3_transition as transition
} from '../utils/d3-decorators';
import {GrammarRegistry} from '../grammar-registry';
import {unitsRegistry} from '../units-registry';
import {scalesRegistry} from '../scales-registry';
import {ScalesFactory} from '../scales-factory';
import {DataProcessor} from '../data-processor';
import {getLayout, ChartLayout} from '../utils/layout-template';
import {SpecConverter} from '../spec-converter';
import {SpecTransformAutoLayout} from '../spec-transform-auto-layout';
import {SpecTransformCalcSize} from '../spec-transform-calc-size';
import {SpecTransformApplyRatio} from '../spec-transform-apply-ratio';
import {SpecTransformExtractAxes} from '../spec-transform-extract-axes';
import {CSS_PREFIX} from '../const';
import {GPL} from './tau.gpl';
import {UnitDomainPeriodGenerator} from '../unit-domain-period-generator';
import * as d3_selection from 'd3-selection';
const d3 = {...d3_selection};
import 'd3-transition';
import TaskRunner from './task-runner';
var selectOrAppend = utilsDom.selectOrAppend;
var selectImmediate = utilsDom.selectImmediate;
import {
ChartConfig,
ChartDimensionsMap,
ChartSettings,
ChartSpec,
DataFrameObject,
DataSources,
d3Selection,
GPLSpec,
GrammarElement,
PointerEventArgs,
Size,
SpecTransformConstructor,
Unit
} from '../definitions';
interface Filter {
tag: string;
src?: string;
predicate: (row) => boolean;
id?: number;
}
interface ExcludeFilter {
excludeFilter?: string[];
}
export class Plot extends Emitter {
protected _nodes: GrammarElement[];
protected _svg: SVGSVGElement;
protected _filtersStore: {
filters: {[tag: string]: Filter[]};
tick: number;
};
protected _layout: ChartLayout;
configGPL: GPLSpec;
transformers: SpecTransformConstructor[];
onUnitsStructureExpandedTransformers: SpecTransformConstructor[];
protected _originData: DataSources;
protected _chartDataModel: (dataSources: DataSources) => DataSources;
protected _liveSpec: GPLSpec;
protected _plugins: Plugins;
protected _reportProgress: (value: number) => void;
protected _taskRunner: TaskRunner;
protected _renderingPhase: 'spec' | 'draw' | null;
protected _emptyContainer: string;
protected _pointerAnimationFrameId: number;
protected _target: HTMLElement | string;
protected _defaultSize: Size;
protected _renderedItems: GrammarElement[];
protected _dataRefs: {
references: WeakMap<any, number>;
refCounter: () => number;
};
on(
event: 'render' | 'beforerender',
callback: (chart: Plot, svg: SVGSVGElement) => void,
context?
): EventHandlerMap;
on(
event: 'specready' | 'unitsstructureexpanded',
callback: (chart: Plot, spec: GPLSpec) => void,
context?
): EventHandlerMap;
on(event: 'renderingtimeout', callback: (chart: Plot, timeout: number) => void, context?): EventHandlerMap;
on(event: 'renderingerror', callback: (chart: Plot, error: Error) => void, context?): EventHandlerMap;
on(event: 'unitdraw', callback: (chart: Plot, unit: GrammarElement) => void, context?): EventHandlerMap;
on(
event: 'elementclick' | 'elementmouseout' | 'elementmouseover',
callback: (chart: Plot, data: PointerEvent) => void,
context?
): EventHandlerMap;
on(event: string, callback: (chart: Plot, data) => void, context?) {
return super.on(event, callback, context);
}
constructor(config: ChartConfig) {
super();
this._nodes = [];
this._svg = null;
this._filtersStore = {
filters: {},
tick: 0
};
this._layout = getLayout();
this.transformers = [
SpecTransformApplyRatio,
SpecTransformAutoLayout
];
this.onUnitsStructureExpandedTransformers = [
SpecTransformExtractAxes,
SpecTransformCalcSize
];
this._chartDataModel = (src => src);
this._reportProgress = null;
this._taskRunner = null;
this._renderingPhase = null;
this.applyConfig(config);
}
updateConfig(config: ChartConfig) {
this.applyConfig(config);
this.refresh();
}
applyConfig(config: ChartConfig) {
this._filtersStore.filters = {};
config = this.setupConfigSettings(config);
this.configGPL = this.createGPLConfig(config);
this._originData = Object.assign({}, this.configGPL.sources);
this._liveSpec = this.configGPL;
this._emptyContainer = config.emptyContainer || '';
this.setupPlugins(config);
}
createGPLConfig(config: ChartConfig) {
let configGPL: GPLSpec;
if (this.isGPLConfig(config)) {
configGPL = config as GPLSpec;
} else {
config = this.setupConfig(config);
configGPL = new SpecConverter(config).convert();
}
configGPL = Plot.setupPeriodData(configGPL);
return configGPL;
}
isGPLConfig(config: ChartConfig) {
return (['sources', 'scales'].filter((p) => config.hasOwnProperty(p)).length === 2);
}
setupPlugins(config: ChartConfig) {
const plugins = (config.plugins || []);
if (this._plugins) {
this._plugins.destroy();
}
this._plugins = new Plugins(plugins, this);
}
setupConfigSettings(config: ChartConfig) {
this._dataRefs = this._dataRefs || (() => {
let iref = 0;
return {
references: new WeakMap(),
refCounter: (() => (++iref))
};
})();
config.settings = Plot.setupSettings(utils.defaults(
(config.settings || {}),
this._dataRefs
));
return config;
}
destroy() {
this.destroyNodes();
d3.select(this._svg).remove();
d3.select(this._layout.layout).remove();
this._cancelRendering();
super.destroy();
}
setupChartSourceModel(fnModelTransformation: (sources: DataSources) => DataSources) {
this._chartDataModel = fnModelTransformation;
}
setupConfig(config: ChartConfig) {
if (!config.spec || !config.spec.unit) {
throw new Error('Provide spec for plot');
}
var resConfig: ChartConfig = utils.defaults(
config,
{
spec: {},
data: [],
plugins: [],
settings: {}
});
resConfig.spec.dimensions = Plot.setupMetaInfo(resConfig.spec.dimensions, resConfig.data);
var log = resConfig.settings.log;
if (resConfig.settings.excludeNull) {
this.addFilter({
tag: 'default',
src: '/',
predicate: DataProcessor.excludeNullValues(
resConfig.spec.dimensions,
(item) => log([item, 'point was excluded, because it has undefined values.'], 'WARN')
)
});
}
return resConfig;
}
static setupPeriodData(spec: GPLSpec) {
var tickPeriod: typeof UnitDomainPeriodGenerator = Plot.__api__.tickPeriod;
var log = spec.settings.log;
var scales = Object
.keys(spec.scales)
.map(s => spec.scales[s]);
scales
.filter(s => (s.type === 'period'))
.forEach((scaleRef) => {
var periodCaster = tickPeriod.get(scaleRef.period, {utc: spec.settings.utcTime});
if (!periodCaster) {
log([
`Unknown period "${scaleRef.period}".`,
`Docs: https://api.taucharts.com/plugins/customticks.html#how-to-add-custom-tick-period`
], 'WARN');
scaleRef.period = null;
}
});
return spec;
}
static setupMetaInfo(dims: ChartDimensionsMap, data: any[]) {
var meta = (dims) ? dims : DataProcessor.autoDetectDimTypes(data);
return DataProcessor.autoAssignScales(meta);
}
static setupSettings(configSettings: ChartSettings) {
var globalSettings = Plot.globalSettings;
var localSettings = Object
.keys(globalSettings)
.reduce((memo, k) => {
memo[k] = (typeof globalSettings[k] === 'function') ?
globalSettings[k] :
utils.clone(globalSettings[k]);
return memo;
}, {} as ChartSettings);
var r = utils.defaults(configSettings || {}, localSettings);
if (!Array.isArray(r.specEngine)) {
r.specEngine = [{width: Number.MAX_VALUE, name: r.specEngine}];
}
return r;
}
insertToLeftSidebar(el: Element) {
return utilsDom.appendTo(el, this._layout.leftSidebar);
}
insertToRightSidebar(el: Element) {
return utilsDom.appendTo(el, this._layout.rightSidebar);
}
insertToFooter(el: Element) {
return utilsDom.appendTo(el, this._layout.footer);
}
insertToHeader(el: Element) {
return utilsDom.appendTo(el, this._layout.header);
}
addBalloon(conf) {
return new (<any>Balloon)('', conf || {});
}
destroyNodes() {
this._nodes.forEach((node) => node.destroy());
this._nodes = [];
this._renderedItems = [];
}
onUnitDraw(unitNode: GrammarElement) {
this._nodes.push(unitNode);
this.fire('unitdraw', unitNode);
['click', 'mouseover', 'mouseout']
.forEach((eventName) => unitNode.on(
(eventName),
(sender, e) => {
this.fire(
`element${eventName}`,
<PointerEventArgs>{
element: sender,
data: e.data,
event: e.event
}
);
}));
}
onUnitsStructureExpanded(specRef: GPLSpec) {
this.onUnitsStructureExpandedTransformers
.forEach((TClass) => (new TClass(specRef)).transform(this));
this.fire('unitsstructureexpanded', specRef);
}
_getClosestElementPerUnit(x0: number, y0: number) {
return this._renderedItems
.filter((d) => d.getClosestElement)
.map((item) => {
var closest = item.getClosestElement(x0, y0);
var unit = item.node();
return {unit, closest};
});
}
disablePointerEvents() {
this._layout.layout.style.pointerEvents = 'none';
}
enablePointerEvents() {
this._layout.layout.style.pointerEvents = '';
}
_handlePointerEvent(event: MouseEvent) {
// TODO: Highlight API seems not consistent.
// Just predicate is not enough, also
// need coordinates or event object.
const svgRect = this._svg.getBoundingClientRect();
const x = (event.clientX - svgRect.left);
const y = (event.clientY - svgRect.top);
const eventType = event.type;
const isClick = (eventType === 'click');
const dataEvent = (isClick ? 'data-click' : 'data-hover');
var data = null;
var node: Element = null;
var unit: GrammarElement = null;
const items = this._getClosestElementPerUnit(x, y);
const nonEmpty = items
.filter((d) => d.closest)
.sort((a, b) => (a.closest.distance === b.closest.distance ?
(a.closest.secondaryDistance - b.closest.secondaryDistance) :
(a.closest.distance - b.closest.distance)));
if (nonEmpty.length > 0) {
const largerDistIndex = nonEmpty.findIndex((d) => (
(d.closest.distance !== nonEmpty[0].closest.distance) ||
(d.closest.secondaryDistance !== nonEmpty[0].closest.secondaryDistance)
));
const sameDistItems = (largerDistIndex < 0 ? nonEmpty : nonEmpty.slice(0, largerDistIndex));
if (sameDistItems.length === 1) {
data = sameDistItems[0].closest.data;
node = sameDistItems[0].closest.node;
unit = sameDistItems[0].unit;
} else {
const mx = (sameDistItems.reduce((sum, item) => sum + item.closest.x, 0) / sameDistItems.length);
const my = (sameDistItems.reduce((sum, item) => sum + item.closest.y, 0) / sameDistItems.length);
const angle = (Math.atan2(my - y, mx - x) + Math.PI);
const index = Math.round((sameDistItems.length - 1) * angle / 2 / Math.PI);
const {closest} = sameDistItems[index];
data = closest.data;
node = closest.node;
unit = sameDistItems[index].unit;
}
}
items.forEach((item) => item.unit.fire(dataEvent, {event, data, node, unit}));
}
_initPointerEvents() {
if (!this._liveSpec.settings.syncPointerEvents) {
this._pointerAnimationFrameId = null;
}
const svg = d3.select(this._svg);
const wrapEventHandler = (this._liveSpec.settings.syncPointerEvents ?
((handler) => () => handler(d3_selection.event)) :
((handler) => (() => {
var e = d3_selection.event;
if (this._pointerAnimationFrameId && e.type !== 'mousemove') {
this._cancelPointerAnimationFrame();
}
if (!this._pointerAnimationFrameId) {
this._pointerAnimationFrameId = requestAnimationFrame(() => {
this._pointerAnimationFrameId = null;
handler(e);
});
}
}))
);
const handler = ((e) => this._handlePointerEvent(e));
svg.on('mousemove', wrapEventHandler(handler));
svg.on('click', wrapEventHandler(handler));
svg.on('mouseleave', wrapEventHandler((event) => {
if (window.getComputedStyle(this._svg).pointerEvents !== 'none') {
this.select(() => true)
.forEach((unit) => unit.fire('data-hover', {event, data: null, node: null, unit: null}));
}
}));
}
_cancelPointerAnimationFrame() {
cancelAnimationFrame(this._pointerAnimationFrameId);
this._pointerAnimationFrameId = null;
}
_setupTaskRunner(liveSpec: GPLSpec) {
this._resetTaskRunner();
this._taskRunner = new TaskRunner({
timeout: (liveSpec.settings.renderingTimeout || Number.MAX_SAFE_INTEGER),
syncInterval: (liveSpec.settings.asyncRendering ?
liveSpec.settings.syncRenderingInterval :
Number.MAX_SAFE_INTEGER),
callbacks: {
done: () => {
this._completeRendering();
this._renderingPhase = null;
},
timeout: (timeout, taskRunner) => {
this._displayTimeoutWarning({
timeout,
proceed: () => {
this.disablePointerEvents();
taskRunner.setTimeoutDuration(Number.MAX_SAFE_INTEGER);
taskRunner.run();
},
cancel: () => {
this._cancelRendering();
}
});
this.enablePointerEvents();
this.fire('renderingtimeout', timeout);
},
progress: (progress) => {
var phases = {
spec: 0,
draw: 1
};
var p = (phases[this._renderingPhase] / 2 + progress / 2);
this._reportProgress(p);
},
error: (liveSpec.settings.handleRenderingErrors ?
((err) => {
this._cancelRendering();
this._displayRenderingError(err);
this.fire('renderingerror', err);
liveSpec.settings.log([
`An error occured during chart rendering.`,
`Set "handleRenderingErrors: false" in chart settings to debug.`,
`Error message: ${err.message}`
].join(' '), 'ERROR');
}) :
null)
}
});
return this._taskRunner;
}
_resetTaskRunner() {
if (this._taskRunner && this._taskRunner.isRunning()) {
this._taskRunner.stop();
this._taskRunner = null;
}
}
renderTo(target: HTMLElement | string, xSize?: Size) {
this._resetProgressLayout();
this.disablePointerEvents();
this._insertLayout(target, xSize);
const liveSpec = this._createLiveSpec();
if (!liveSpec) {
this._svg = null;
this._layout.content.innerHTML = this._emptyContainer;
this.enablePointerEvents();
return;
}
var gpl = this._createGPL(liveSpec);
var taskRunner = this._setupTaskRunner(liveSpec);
this._scheduleDrawScenario(taskRunner, gpl);
this._scheduleDrawing(taskRunner, gpl);
taskRunner.run();
}
_insertLayout(target: HTMLElement | string, xSize?: Size) {
this._target = target;
this._defaultSize = Object.assign({}, xSize);
var targetNode: Element = d3.select(target as any).node();
if (targetNode === null) {
throw new Error('Target element not found');
}
if (this._layout.layout.parentNode !== targetNode) {
targetNode.appendChild(this._layout.layout);
}
var content = this._layout.content;
// Set padding to fit scrollbar size
var s = utilsDom.getScrollbarSize(this._layout.contentContainer);
this._layout.contentContainer.style.padding = `0 ${s.width}px ${s.height}px 0`;
utilsDom.setScrollPadding(this._layout.rightSidebarContainer, 'vertical');
var size = Object.assign({}, xSize) || {};
if (!size.width || !size.height) {
let {scrollLeft, scrollTop} = content.parentElement;
content.style.display = 'none';
size = utils.defaults(size, utilsDom.getContainerSize(content.parentNode as HTMLElement));
content.style.display = '';
content.parentElement.scrollLeft = scrollLeft;
content.parentElement.scrollTop = scrollTop;
// TODO: fix this issue
if (!size.height) {
size.height = utilsDom.getContainerSize(this._layout.layout).height;
}
}
this.configGPL.settings.size = size;
}
_createLiveSpec() {
this._liveSpec = utils.clone(utils.omit(this.configGPL, 'plugins'));
this._liveSpec.sources = this.getDataSources();
this._liveSpec.settings = this.configGPL.settings;
this._experimentalSetupAnimationSpeed(this._liveSpec);
if (this.isEmptySources(this._liveSpec.sources)) {
return null;
}
this._liveSpec = this
.transformers
.reduce((memo, TransformClass) => (new TransformClass(memo).transform(this)), this._liveSpec);
this.destroyNodes();
this.fire('specready', this._liveSpec);
return this._liveSpec;
}
_experimentalSetupAnimationSpeed(spec: GPLSpec) {
// Determine if it's better to draw chart without animation
(<any>spec.settings).initialAnimationSpeed = (
(<any>spec.settings).initialAnimationSpeed ||
spec.settings.animationSpeed);
const animationSpeed = (spec.settings.experimentalShouldAnimate(spec) ?
(<any>spec.settings).initialAnimationSpeed : 0);
spec.settings.animationSpeed = animationSpeed;
const setUnitAnimation = (u: Unit) => {
u.guide = (u.guide || {});
u.guide.animationSpeed = animationSpeed;
if (u.units) {
u.units.forEach(setUnitAnimation);
}
};
setUnitAnimation(spec.unit);
}
_createGPL(liveSpec: GPLSpec) {
var gpl = new GPL(liveSpec, this.getScaleFactory(), unitsRegistry, GrammarRegistry);
var structure = gpl.unfoldStructure();
this.onUnitsStructureExpanded(structure);
return gpl;
}
_scheduleDrawScenario(taskRunner: TaskRunner, gpl: GPL) {
const d3Target = d3.select(this._layout.content);
const newSize = gpl.config.settings.size;
taskRunner.addTask(() => this._renderingPhase = 'spec');
gpl.getDrawScenarioQueue({
allocateRect: () => ({
slot: ((uid) => d3Target.selectAll(`.uid_${uid}`) as d3Selection),
frameId: 'root',
left: 0,
top: 0,
width: newSize.width,
containerWidth: newSize.width,
height: newSize.height,
containerHeight: newSize.height
})
}).forEach((task) => taskRunner.addTask(task));
}
_scheduleDrawing(taskRunner: TaskRunner, gpl: GPL) {
const newSize = gpl.config.settings.size;
taskRunner.addTask((scenario: GrammarElement[]) => {
this._renderingPhase = 'draw';
this._renderRoot({scenario, newSize});
this._cancelPointerAnimationFrame();
this._scheduleRenderScenario(scenario);
});
}
_resetProgressLayout() {
this._createProgressBar();
this._clearRenderingError();
this._clearTimeoutWarning();
}
_renderRoot({scenario, newSize}: {scenario: GrammarElement[]; newSize: Size;}) {
const d3Target = d3.select(this._layout.content);
var frameRootId = scenario[0].config.uid;
var svg = selectOrAppend(d3Target, `svg`)
.attr('width', Math.floor(newSize.width))
.attr('height', Math.floor(newSize.height));
if (!svg.attr('class')) {
svg.attr('class', `${CSS_PREFIX}svg`);
}
this._svg = svg.node() as SVGSVGElement;
this._initPointerEvents();
this.fire('beforerender', this._svg);
var roots = (svg.selectAll('g.frame-root') as d3.Selection<SVGElement, string, SVGSVGElement, any>)
.data([frameRootId], x => x);
// NOTE: Fade out removed root, fade-in if removing interrupted.
roots.enter()
.append('g')
.classed(`${CSS_PREFIX}cell cell frame-root uid_${frameRootId}`, true)
.merge(roots)
.call((selection) => {
selection.classed('tau-active', true);
transition(selection, this.configGPL.settings.animationSpeed, 'frameRootToggle')
.attr('opacity', 1);
});
roots.exit()
.call((selection) => {
selection.classed('tau-active', false);
transition(selection, this.configGPL.settings.animationSpeed, 'frameRootToggle')
.attr('opacity', 1e-6)
.remove();
});
}
_scheduleRenderScenario(scenario: GrammarElement[]) {
scenario.forEach((item) => {
this._taskRunner.addTask(() => {
item.draw();
this.onUnitDraw(item.node());
this._renderedItems.push(item);
});
});
}
_completeRendering() {
// TODO: Render panels before chart, to
// prevent chart size shrink. Use some other event.
utilsDom.setScrollPadding(this._layout.contentContainer);
this._layout.rightSidebar.style.maxHeight = (`${this._liveSpec.settings.size.height}px`);
this.enablePointerEvents();
if (this._svg) {
this.fire('render', this._svg);
}
// NOTE: After plugins have rendered, the panel scrollbar may appear, so need to handle it again.
utilsDom.setScrollPadding(this._layout.rightSidebarContainer, 'vertical');
}
_cancelRendering() {
this.enablePointerEvents();
this._resetTaskRunner();
this._cancelPointerAnimationFrame();
}
_createProgressBar() {
var header = d3.select(this._layout.header);
var progressBar = selectOrAppend(header, `div.${CSS_PREFIX}progress`);
progressBar.select(`div.${CSS_PREFIX}progress__value`).remove();
var progressValue = progressBar.append('div')
.classed(`${CSS_PREFIX}progress__value`, true)
.style('width', 0);
this._reportProgress = function (value) {
requestAnimationFrame(() => {
progressBar.classed(`${CSS_PREFIX}progress_active`, value < 1);
progressValue.style('width', `${value * 100}%`);
});
};
}
_displayRenderingError(error?: Error) {
this._layout.layout.classList.add(`${CSS_PREFIX}layout_rendering-error`);
}
_clearRenderingError() {
this._layout.layout.classList.remove(`${CSS_PREFIX}layout_rendering-error`);
}
getScaleFactory(dataSources: DataSources = null) {
return new ScalesFactory(
scalesRegistry.instance(this._liveSpec.settings),
dataSources || this._liveSpec.sources,
this._liveSpec.scales
);
}
getScaleInfo(name: string, dataFrame: DataFrameObject = null) {
return this
.getScaleFactory()
.createScaleInfoByName(name, dataFrame);
}
getSourceFiltersIterator(rejectFiltersPredicate: (filter: Filter) => boolean) {
var filters = utils.flatten(Object.keys(this._filtersStore.filters).map(key => this._filtersStore.filters[key]))
.filter((f) => !rejectFiltersPredicate(f))
.map(x => x.predicate);
return (row) => filters.reduce((prev, f) => (prev && f(row)), true);
}
getDataSources(param: ExcludeFilter = {}) {
var excludeFiltersByTagAndSource = (k: string) =>
((f: Filter) => (param.excludeFilter && param.excludeFilter.indexOf(f.tag) !== -1) || f.src !== k);
var chartDataModel = this._chartDataModel(this._originData);
return Object
.keys(chartDataModel)
.filter((k) => k !== '?')
.reduce((memo, k) => {
var item = chartDataModel[k];
var filterIterator = this.getSourceFiltersIterator(excludeFiltersByTagAndSource(k));
memo[k] = {
dims: item.dims,
data: item.data.filter(filterIterator)
};
return memo;
},
{
'?': chartDataModel['?']
} as DataSources);
}
isEmptySources(sources: DataSources) {
return !Object
.keys(sources)
.filter((k) => k !== '?')
.filter((k) => sources[k].data.length > 0)
.length;
}
getChartModelData(param: ExcludeFilter = {}, src = '/') {
var sources = this.getDataSources(param);
return sources[src].data;
}
getDataDims(src = '/') {
return this._originData[src].dims;
}
getData(src = '/') {
return this._originData[src].data;
}
setData(data: any[], src = '/') {
this._originData[src].data = data;
this.refresh();
}
getSVG() {
return this._svg;
}
addFilter(filter: Filter) {
filter.src = filter.src || '/';
var tag = filter.tag;
var filters = this._filtersStore.filters[tag] = this._filtersStore.filters[tag] || [];
var id = this._filtersStore.tick++;
filter.id = id;
filters.push(filter);
return id;
}
removeFilter(id: number) {
Object.keys(this._filtersStore.filters).map((key) => {
this._filtersStore.filters[key] = this._filtersStore.filters[key].filter((item) => item.id !== id);
});
return this;
}
refresh() {
if (this._target) {
this.renderTo(this._target, this._defaultSize);
}
}
resize(sizes: Size = {}) {
this.renderTo(this._target, sizes);
}
select(queryFilter: (unit?: GrammarElement) => boolean) {
return this._nodes.filter(queryFilter);
}
traverseSpec(spec: ChartSpec, iterator: (node: Unit, parentNode: Unit, parentFrame: DataFrameObject) => void) {
var traverse = (node, iterator, parentNode, parentFrame) => {
iterator(node, parentNode, parentFrame);
if (node.frames) {
node.frames.forEach((frame) => {
(frame.units || []).map((x) => traverse(x, iterator, node, frame));
});
} else {
(node.units || []).map((x) => traverse(x, iterator, node, null));
}
};
traverse(spec.unit, iterator, null, null);
}
// use from plugins to get the most actual chart config
getSpec() {
return this._liveSpec;
}
getLayout() {
return this._layout;
}
_displayTimeoutWarning({proceed, cancel, timeout}: {proceed: () => void, cancel: () => void, timeout: number}) {
var width = 200;
var height = 100;
var linesCount = 3;
var lineSpacing = 1.5;
var midX = width / 2;
var fontSize = Math.round(height / linesCount / lineSpacing);
var getY = function (line) {
return Math.round(height / linesCount / lineSpacing * line);
};
this._layout.content.style.height = '100%';
this._layout.content.insertAdjacentHTML('beforeend', `
<div class="${CSS_PREFIX}rendering-timeout-warning">
<svg
viewBox="0 0 ${width} ${height}">
<text
text-anchor="middle"
font-size="${fontSize}">
<tspan x="${midX}" y="${getY(1)}">Rendering took more than ${Math.round(timeout) / 1000}s</tspan>
<tspan x="${midX}" y="${getY(2)}">Would you like to continue?</tspan>
</text>
<text
class="${CSS_PREFIX}rendering-timeout-continue-btn"
text-anchor="end"
font-size="${fontSize}"
cursor="pointer"
text-decoration="underline"
x="${midX - fontSize / 3}"
y="${getY(3)}">
Continue
</text>
<text
class="${CSS_PREFIX}rendering-timeout-cancel-btn"
text-anchor="start"
font-size="${fontSize}"
cursor="pointer"
text-decoration="underline"
x="${midX + fontSize / 3}"
y="${getY(3)}">
Cancel
</text>
</svg>
</div>
`);
this._layout.content
.querySelector(`.${CSS_PREFIX}rendering-timeout-continue-btn`)
.addEventListener('click', () => {
this._clearTimeoutWarning();
proceed.call(this);
});
this._layout.content
.querySelector(`.${CSS_PREFIX}rendering-timeout-cancel-btn`)
.addEventListener('click', () => {
this._clearTimeoutWarning();
cancel.call(this);
});
}
_clearTimeoutWarning() {
var warning = selectImmediate(this._layout.content, `.${CSS_PREFIX}rendering-timeout-warning`);
if (warning) {
this._layout.content.removeChild(warning);
this._layout.content.style.height = '';
}
}
static globalSettings: ChartSettings;
static __api__;
} | the_stack |
import React from "react";
import {render, fireEvent, wait, waitForElement, act, cleanup} from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import {AuthoritiesContext, AuthoritiesService} from "../util/authorities";
import axiosMock from "axios";
import mocks from "../api/__mocks__/mocks.data";
import Load from "./Load";
import {MemoryRouter} from "react-router-dom";
import tiles from "../config/tiles.config";
import {getViewSettings} from "../util/user-context";
import moment from "moment";
import loadData from "../assets/mock-data/curation/ingestion.data";
jest.mock("axios");
jest.setTimeout(30000);
const DEFAULT_VIEW = "card";
describe("Load component", () => {
beforeEach(() => {
mocks.loadAPI(axiosMock);
});
afterEach(() => {
jest.clearAllMocks();
cleanup();
});
test("Verify cannot edit with only readIngestion authority", async () => {
const authorityService = new AuthoritiesService();
authorityService.setAuthorities(["readIngestion"]);
const {baseElement, getByText, getByPlaceholderText, getByLabelText, getByTestId, queryByTestId, queryByTitle} = render(
<MemoryRouter><AuthoritiesContext.Provider value={authorityService}><Load/></AuthoritiesContext.Provider></MemoryRouter>
);
expect(await(waitForElement(() => getByLabelText("switch-view-list")))).toBeInTheDocument();
// Check for steps to be populated
expect(axiosMock.get).toBeCalledWith("/api/steps/ingestion");
expect(getByText("testLoad")).toBeInTheDocument();
// Check list view
fireEvent.click(getByLabelText("switch-view-list"));
// Open settings
await act(async () => {
await fireEvent.click(getByText("testLoad"));
});
expect(getByText("Loading Step Settings")).toBeInTheDocument();
expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active");
expect(getByText("Advanced").closest("div")).not.toHaveClass("ant-tabs-tab-active");
// Basic settings
expect(getByPlaceholderText("Enter name")).toHaveValue("testLoad");
expect(getByPlaceholderText("Enter name")).toBeDisabled();
expect(getByPlaceholderText("Enter description")).toBeDisabled();
expect(baseElement.querySelector("#sourceFormat")).toHaveClass("ant-select-disabled");
expect(baseElement.querySelector("#targetFormat")).toHaveClass("ant-select-disabled");
expect(baseElement.querySelector("#outputUriPrefix")).toHaveClass("ant-input-disabled");
// Advanced settings
await wait(() => {
fireEvent.click(getByText("Advanced"));
});
expect(getByText("Basic").closest("div")).not.toHaveClass("ant-tabs-tab-active");
expect(getByText("Advanced").closest("div")).toHaveClass("ant-tabs-tab-active");
expect(await(waitForElement(() => getByText("Target Database")))).toBeInTheDocument();
expect(getByLabelText("headers-textarea")).toBeDisabled();
fireEvent.click(getByText("Interceptors"));
expect(getByLabelText("interceptors-textarea")).toBeDisabled();
fireEvent.click(getByText("Custom Hook"));
expect(getByLabelText("customHook-textarea")).toBeDisabled();
expect(getByTestId("testLoad-save-settings")).toBeDisabled();
await act(async () => {
await fireEvent.click(getByTestId("testLoad-cancel-settings"));
});
// test delete
expect(queryByTestId("testLoad-delete")).not.toBeInTheDocument();
// Check card layout
fireEvent.click(getByLabelText("switch-view-card"));
// test delete
expect(queryByTitle("delete")).not.toBeInTheDocument();
});
test("Verify edit with readIngestion and writeIngestion authorities", async () => {
const authorityService = new AuthoritiesService();
authorityService.setAuthorities(["readIngestion", "writeIngestion"]);
const {baseElement, getByText, getAllByText, getByLabelText, getByPlaceholderText, getByTestId, queryAllByText} = render(
<MemoryRouter><AuthoritiesContext.Provider value={authorityService}><Load/></AuthoritiesContext.Provider></MemoryRouter>
);
expect(await(waitForElement(() => getByLabelText("switch-view-list")))).toBeInTheDocument();
// Check for steps to be populated
expect(axiosMock.get).toBeCalledWith("/api/steps/ingestion");
expect(getByText("testLoad")).toBeInTheDocument();
// Check list view
fireEvent.click(getByLabelText("switch-view-list"));
// test 'Add New' button
expect(getByText("Add New")).toBeInTheDocument();
// Open settings
await act(async () => {
await fireEvent.click(getByText("testLoad"));
});
expect(getByText("Loading Step Settings")).toBeInTheDocument();
expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active");
expect(getByText("Advanced").closest("div")).not.toHaveClass("ant-tabs-tab-active");
// Basic settings
expect(getByPlaceholderText("Enter name")).toHaveValue("testLoad");
expect(getByPlaceholderText("Enter name")).toBeDisabled();
expect(getByPlaceholderText("Enter description")).toBeEnabled();
expect(baseElement.querySelector("#sourceFormat")).not.toHaveClass("ant-select-disabled");
expect(baseElement.querySelector("#targetFormat")).not.toHaveClass("ant-select-disabled");
expect(baseElement.querySelector("#outputUriPrefix")).not.toHaveClass("ant-input-disabled");
// Advanced settings
await wait(() => {
fireEvent.click(getByText("Advanced"));
});
expect(getByText("Basic").closest("div")).not.toHaveClass("ant-tabs-tab-active");
expect(getByText("Advanced").closest("div")).toHaveClass("ant-tabs-tab-active");
expect(getByLabelText("headers-textarea")).not.toBeDisabled();
fireEvent.click(getByText("Interceptors"));
expect(getByLabelText("interceptors-textarea")).not.toBeDisabled();
fireEvent.click(getByText("Custom Hook"));
expect(getByLabelText("customHook-textarea")).not.toBeDisabled();
// No JSON (empty field)
fireEvent.change(getByLabelText("headers-textarea"), {target: {value: ""}});
expect(queryAllByText("Invalid JSON").length === 0);
fireEvent.change(getByLabelText("interceptors-textarea"), {target: {value: ""}});
expect(queryAllByText("Invalid JSON").length === 0);
fireEvent.change(getByLabelText("customHook-textarea"), {target: {value: ""}});
expect(queryAllByText("Invalid JSON").length === 0);
// Invalid JSON
fireEvent.change(getByLabelText("headers-textarea"), {target: {value: "{\"badJSON\": \"noClosingBracket\""}});
expect(queryAllByText("Invalid JSON").length === 1);
fireEvent.change(getByLabelText("interceptors-textarea"), {target: {value: "{\"badJSON\": \"noClosingBracket\""}});
expect(queryAllByText("Invalid JSON").length === 2);
fireEvent.change(getByLabelText("customHook-textarea"), {target: {value: "{\"badJSON\": \"noClosingBracket\""}});
expect(queryAllByText("Invalid JSON").length === 3);
// Valid JSON
fireEvent.change(getByLabelText("headers-textarea"), {target: {value: "{\"goodJSON\": true}"}});
expect(queryAllByText("Invalid JSON").length === 2);
fireEvent.change(getByLabelText("interceptors-textarea"), {target: {value: "{\"goodJSON\": true}"}});
expect(queryAllByText("Invalid JSON").length === 1);
getByLabelText("customHook-textarea").focus();
fireEvent.change(getByLabelText("customHook-textarea"), {target: {value: "{\"goodJSON\": true}"}});
expect(queryAllByText("Invalid JSON").length === 0);
getByLabelText("customHook-textarea").blur();
expect(getByTestId("testLoad-save-settings")).not.toBeDisabled();
fireEvent.click(getByTestId("testLoad-cancel-settings"));
fireEvent.click(getAllByText("No")[0]); // Handle cancel confirmation
// test delete
fireEvent.click(getByTestId("testLoad-delete"));
fireEvent.click(getAllByText("No")[1]);
// Check card layout
fireEvent.click(getByLabelText("switch-view-card"));
// test 'Add New' button
expect(getByText("Add New")).toBeInTheDocument();
// test delete
fireEvent.click(getByTestId("testLoad-delete"));
expect(await(waitForElement(() => getByText("Yes")))).toBeInTheDocument();
await act(async () => {
fireEvent.click(getByText("Yes"));
});
expect(axiosMock.delete).toHaveBeenNthCalledWith(1, "/api/steps/ingestion/testLoad");
});
test("Verify list and card views", async () => {
const authorityService = new AuthoritiesService();
authorityService.setAuthorities(["readIngestion", "writeIngestion"]);
const {getByText, getAllByText, getByLabelText, getByTestId} = render(
<MemoryRouter><AuthoritiesContext.Provider value={authorityService}><Load/></AuthoritiesContext.Provider></MemoryRouter>
);
expect(await(waitForElement(() => getByLabelText("switch-view-list")))).toBeInTheDocument();
expect(getByText(tiles.load.intro)).toBeInTheDocument(); // tile intro text
// Check for steps to be populated in default view
expect(axiosMock.get).toBeCalledWith("/api/steps/ingestion");
expect(getByText("testLoad")).toBeInTheDocument();
expect(getByLabelText("load-" + DEFAULT_VIEW)).toBeInTheDocument();
// Check list view
fireEvent.click(getByLabelText("switch-view-list"));
expect(getByText("testLoad")).toBeInTheDocument();
expect(getByText("Test JSON.")).toBeInTheDocument();
expect(getAllByText("json").length > 0);
let ts: string = loadData.loads.data[0].lastUpdated; // "2000-01-01T12:00:00.000000-00:00"
let tsExpected: string = moment(ts).format("MM/DD/YYYY H:mmA");
expect(getByText(tsExpected)).toBeInTheDocument(); // "01/01/2000 4:00AM"
expect(getByLabelText("icon: delete")).toBeInTheDocument();
// Check card view
fireEvent.click(getByLabelText("switch-view-card"));
expect(getByText("testLoad")).toBeInTheDocument();
expect(getByText("JSON")).toBeInTheDocument();
let ts2: string = loadData.loads.data[0].lastUpdated; // "2000-01-01T12:00:00.000000-00:00"
let tsExpected2: string = moment(ts2).format("MM/DD/YYYY H:mmA");
expect(getByText("Last Updated: " + tsExpected2)).toBeInTheDocument(); // "Last Updated: 01/01/2000 4:00AM"
expect(getByTestId("testLoad-edit")).toBeInTheDocument();
expect(getByLabelText("icon: delete")).toBeInTheDocument();
});
});
describe("getViewSettings", () => {
beforeEach(() => {
window.sessionStorage.clear();
jest.restoreAllMocks();
});
const sessionStorageMock = (() => {
let store = {};
return {
getItem(key) {
return store[key] || null;
},
setItem(key, value) {
store[key] = value.toString();
},
removeItem(key) {
delete store[key];
},
clear() {
store = {};
}
};
})();
Object.defineProperty(window, "sessionStorage", {
value: sessionStorageMock
});
it("should get page number from session storage", () => {
const getItemSpy = jest.spyOn(window.sessionStorage, "getItem");
window.sessionStorage.setItem("dataHubViewSettings", JSON.stringify({load: {page: 2}}));
const actualValue = getViewSettings();
expect(actualValue).toEqual({load: {page: 2}});
expect(getItemSpy).toBeCalledWith("dataHubViewSettings");
});
it("should get view mode from session storage", () => {
const getItemSpy = jest.spyOn(window.sessionStorage, "getItem");
window.sessionStorage.setItem("dataHubViewSettings", JSON.stringify({load: {viewMode: "list"}}));
let actualValue = getViewSettings();
expect(actualValue).toEqual({load: {viewMode: "list"}});
expect(getItemSpy).toBeCalledWith("dataHubViewSettings");
window.sessionStorage.setItem("dataHubViewSettings", JSON.stringify({load: {viewMode: "card"}}));
actualValue = getViewSettings();
expect(actualValue).toEqual({load: {viewMode: "card"}});
expect(getItemSpy).toBeCalledWith("dataHubViewSettings");
});
it("should get sort order from session storage", () => {
const getItemSpy = jest.spyOn(window.sessionStorage, "getItem");
window.sessionStorage.setItem("dataHubViewSettings", JSON.stringify({load: {columnKey: "name", order: "ascend"}}));
let actualValue = getViewSettings();
expect(actualValue).toEqual({load: {columnKey: "name", order: "ascend"}});
expect(getItemSpy).toBeCalledWith("dataHubViewSettings");
window.sessionStorage.setItem("dataHubViewSettings", JSON.stringify({load: {columnKey: "name", order: "descend"}}));
actualValue = getViewSettings();
expect(actualValue).toEqual({load: {columnKey: "name", order: "descend"}});
expect(getItemSpy).toBeCalledWith("dataHubViewSettings");
});
it("should get empty object if no info in session storage", () => {
const getItemSpy = jest.spyOn(window.sessionStorage, "getItem");
const actualValue = getViewSettings();
expect(actualValue).toEqual({});
expect(window.sessionStorage.getItem).toBeCalledWith("dataHubViewSettings");
expect(getItemSpy).toBeCalledWith("dataHubViewSettings");
});
}); | the_stack |
import { browser, element, by } from 'protractor';
import {
waitForElementPresence, waitForTextChange, waitForElementVisibility,
waitForElementInVisibility, waitForCssClass, waitForStalenessOf,
waitForElementCountGreaterThan, reduce_for_get_all, scrollIntoView
} from '../../utils/e2e_util';
export class TreeViewPage {
navigateToAlertsList() {
return browser.get('/alerts-list');
}
clickOnRow(id: string) {
let idElement = element(by.css('a[title="' + id +'"]'));
let td = idElement.element(by.xpath('../..')).all(by.css('td')).get(9);
let detailsPane = element(by.css('.metron-slider-pane-details'));
return waitForElementPresence(idElement)
.then(() => browser.actions().mouseMove(idElement).perform())
.then(() => browser.actions().mouseMove(td).perform())
.then(() => browser.actions().click().perform())
.then(() => waitForElementVisibility(detailsPane))
.then(() => browser.sleep(2000));
}
getActiveGroups() {
return waitForElementCountGreaterThan('app-group-by .group-by-items .name', 4)
.then(() => element.all(by.css('app-group-by .group-by-items.active .name')).reduce(reduce_for_get_all(), []));
}
getGroupByCount() {
return waitForElementPresence(element(by.css('app-group-by .group-by-items'))).then(() => {
return element.all(by.css('app-group-by .group-by-items')).count();
});
}
getGroupByItemNames() {
return element.all(by.css('app-group-by .group-by-items .name')).reduce(reduce_for_get_all(), []);
}
getGroupByItemCounts() {
return element.all(by.css('app-group-by .group-by-items .count')).reduce(reduce_for_get_all(), []);
}
getSubGroupValues(name: string, rowName: string) {
return this.getSubGroupValuesByPosition(name, rowName, 0);
}
getSubGroupValuesByPosition(name: string, rowName: string, position: number) {
return element.all(by.css('[data-name="' + name + '"] table tbody tr[data-name="' + rowName + '"]')).get(position).getText();
}
selectGroup(name: string) {
return element(by.css('app-group-by div[data-name="' + name + '"]')).click()
.then(() => waitForCssClass(element(by.css('app-group-by div[data-name="' + name + '"]')), 'active'))
.then(() => browser.waitForAngular());
}
async simulateDragAndDrop(target: string, destination: string) {
target = `app-group-by div[data-name=\"${target}\"]`;
destination = `app-group-by div[data-name=\"${destination}\"]`;
return await browser.executeScript((target, destination) => {
let getEventOptions = (el, relatedElement) => {
//coordinates from destination element
const coords = el.getBoundingClientRect();
const x = coords.x || coords.left;
const y = coords.y || coords.top;
return {
x: x,
y: y,
clientX: x,
clientY: y,
screenX: x,
screenY: y,
//target reference
relatedTarget: relatedElement
};
};
let raise = (el, type, options?) => {
const o = options || { which: 1 };
const e = document.createEvent('Event');
e.initEvent(type, true, true);
Object.keys(o).forEach(apply);
el.dispatchEvent(e);
function apply(key) {
e[key] = o[key];
}
};
let targetEl = document.querySelector(target);
let destinationEl = document.querySelector(destination);
let options = getEventOptions(destinationEl, targetEl);
//start drag
raise(targetEl, 'mousedown');
raise(targetEl, 'mousemove');
//set event on location
raise(destinationEl, 'mousemove', options);
//drop
raise(destinationEl, 'mouseup', options);
}, target, destination);
}
async getDashGroupValues(name: string) {
let dashScore = await element(by.css('[data-name="' + name + '"] .dash-score')).getText();
let groupName = await element(by.css('[data-name="' + name + '"] .text-light.severity-padding .title')).getText();
let title = await element(by.css('[data-name="' + name + '"] .text-light.two-line .text-dark')).getText();
let count = await element(by.css('[data-name="' + name + '"] .text-light.two-line .title')).getText();
return Promise.all([dashScore, groupName, title, count]);
}
expandDashGroup(name: string) {
let cardElement = element(by.css('.card[data-name="' + name +'"]'));
let cardHeader = element(by.css('.card[data-name="' + name + '"] .card-header'));
let cardBody = element(by.css('.card[data-name="' + name + '"] .collapse'));
return waitForElementPresence(cardBody)
.then(() => waitForElementVisibility(cardHeader))
.then(() => browser.actions().mouseMove(element(by.css('.card[data-name="' + name + '"] .card-header .down-arrow'))).perform())
.then(() => cardHeader.click())
.then(() => waitForCssClass(cardBody, 'show'))
.then(() => waitForElementVisibility(element(by.css('.card[data-name="' + name + '"] .collapse table tbody tr:nth-child(1)'))));
}
expandSubGroup(groupName: string, rowName: string) {
return this.expandSubGroupByPosition(groupName, rowName, 0);
}
expandSubGroupByPosition(groupName: string, rowName: string, position: number) {
let subGroupElement = element.all(by.css('[data-name="' + groupName + '"] tr[data-name="' + rowName + '"]')).get(position);
return waitForElementVisibility(subGroupElement)
.then(() => scrollIntoView(subGroupElement.element(by.css('.fa-caret-right')), true))
.then(() => subGroupElement.click())
.then(() => waitForElementVisibility(subGroupElement.element(by.css('.fa-caret-down'))));
}
async getTableValuesByRowId(name: string, rowId: number, waitForAnchor: string) {
await waitForElementPresence(element(by. cssContainingText('[data-name="' + name + '"] a', waitForAnchor)));
return element.all(by.css('[data-name="' + name + '"] table tbody tr')).get(rowId).all(by.css('td a')).reduce(reduce_for_get_all(), []);
}
getTableValuesForRow(name: string, rowName: string, waitForAnchor: string) {
return waitForElementPresence(element(by. cssContainingText('[data-name="' + name + '"] a', waitForAnchor))).then(() => {
return element.all(by.css('[data-name="' + name + '"] tr[data-name="' + rowName + '"]')).all(by.css('td')).getText();
});
}
scrollToDashRow(name: string) {
let scrollToEle = element(by.css('[data-name="' + name + '"] .card-header'));
return scrollIntoView(scrollToEle, true);
}
clickOnNextPage(name: string) {
return element(by.css('[data-name="' + name + '"] i.fa-chevron-right')).click();
}
unGroup() {
return element(by.css('app-group-by .ungroup-button')).click()
.then(() => waitForStalenessOf(element(by.css('app-tree-view'))));
}
getIdOfAllExpandedRows() {
return element.all(by.css('[data-name="' + name + '"] table tbody tr')).then(row => {
});
}
getNumOfSubGroups(groupName: string) {
return element.all(by.css('[data-name="' + groupName + '"] table tbody tr')).count();
}
getCellValuesFromTable(groupName: string, cellName: string, waitForAnchor: string) {
let waitForEle = element.all(by.cssContainingText(`[data-name="${cellName}"] a`, waitForAnchor)).get(0);
return waitForElementPresence(waitForEle)
.then(() => scrollIntoView(waitForEle, true))
.then(() => element.all(by.css(`[data-name="${groupName}"] [data-name="${cellName}"]`)).reduce(reduce_for_get_all(), []))
}
sortSubGroup(groupName: string, colName: string) {
return element(by.css(`[data-name="${groupName}"] metron-config-sorter[title="${colName}"]`)).click();
}
toggleAlertInTree(index: number) {
let selector = by.css('app-tree-view tbody tr');
let checkbox = element.all(selector).get(index).element(by.css('label'));
return waitForElementPresence(checkbox)
.then(() => browser.actions().mouseMove(checkbox).perform())
.then(() => checkbox.click());
}
getAlertStatusForTreeView(rowIndex: number, previousText) {
let row = element.all(by.css('app-tree-view tbody tr')).get(rowIndex);
let column = row.all(by.css('td a')).get(8);
return waitForTextChange(column, previousText).then(() => {
return column.getText();
});
}
clickOnMergeAlerts(groupName: string) {
return element(by.css('[data-name="' + groupName + '"] .fa-link')).click();
}
clickOnMergeAlertsInTable(groupName: string, waitForAnchor: string, rowIndex: number) {
let elementFinder = element.all(by.css('[data-name="' + groupName + '"] table tbody tr')).get(rowIndex).element(by.css('.fa-link'));
return waitForElementVisibility(elementFinder)
.then(() => elementFinder.click());
}
getConfirmationText() {
let maskElement = element(by.className('modal-backdrop'));
return waitForElementVisibility(maskElement)
.then(() => element(by.css('.metron-dialog .modal-body')).getText());
}
clickNoForConfirmation() {
let maskElement = element(by.className('modal-backdrop'));
let closeButton = element(by.css('.metron-dialog')).element(by.buttonText('Cancel'));
return waitForElementVisibility(maskElement)
.then(() => closeButton.click())
.then(() => waitForElementInVisibility(maskElement));
}
clickYesForConfirmation() {
let okButton = element(by.css('.metron-dialog')).element(by.buttonText('OK'));
let maskElement = element(by.className('modal-backdrop'));
return waitForElementVisibility(maskElement)
.then(() => okButton.click())
.then(() => waitForElementInVisibility(maskElement));
}
waitForElementToDisappear(groupName: string) {
return waitForElementInVisibility(element.all(by.css('[data-name="' + groupName + '"]')));
}
waitForTextChangeAndExpand(groupName: string, subGroupName: string, previousValue: string) {
return waitForTextChange(element(by.css(`[data-name="${subGroupName}"] .group-value`)), previousValue)
.then(() => this.expandSubGroup(groupName, subGroupName));
}
} | the_stack |
import _ from 'lodash';
import { pipe } from 'fp-ts/function';
import { NodeSchema, isNodeSchema, NodeDataType, CompositeValue } from '@alilc/lowcode-types';
import {
IScope,
CodeGeneratorError,
PIECE_TYPE,
CodePiece,
NodeGenerator,
NodeGeneratorConfig,
NodePlugin,
AttrData,
} from '../types';
import { generateCompositeType } from './compositeType';
import { getStaticExprValue } from './common';
import { executeFunctionStack } from './aopHelper';
import { encodeJsxStringNode } from './encodeJsxAttrString';
import { unwrapJsExprQuoteInJsx } from './jsxHelpers';
import { transformThis2Context } from '../core/jsx/handlers/transformThis2Context';
function mergeNodeGeneratorConfig(
cfg1: NodeGeneratorConfig,
cfg2: NodeGeneratorConfig = {},
): NodeGeneratorConfig {
const resCfg: NodeGeneratorConfig = {};
if (cfg1.handlers || cfg2.handlers) {
resCfg.handlers = {
...(cfg1.handlers || {}),
...(cfg2.handlers || {}),
};
}
if (cfg1.tagMapping || cfg2.tagMapping) {
resCfg.tagMapping = cfg2.tagMapping || cfg1.tagMapping;
}
if (cfg1.attrPlugins || cfg2.attrPlugins) {
resCfg.attrPlugins = [];
resCfg.attrPlugins.push(...(cfg2.attrPlugins || []));
resCfg.attrPlugins.push(...(cfg1.attrPlugins || []));
}
if (cfg1.nodePlugins || cfg2.nodePlugins) {
resCfg.nodePlugins = [];
resCfg.nodePlugins.push(...(cfg2.nodePlugins || []));
resCfg.nodePlugins.push(...(cfg1.nodePlugins || []));
}
return resCfg;
}
export function isPureString(v: string) {
// FIXME: 目前的方式不够严谨
return (v[0] === "'" && v[v.length - 1] === "'") || (v[0] === '"' && v[v.length - 1] === '"');
}
function generateAttrValue(
attrData: { attrName: string; attrValue: CompositeValue },
scope: IScope,
config?: NodeGeneratorConfig,
): CodePiece[] {
const valueStr = generateCompositeType(attrData.attrValue, scope, {
handlers: config?.handlers,
nodeGenerator: config?.self,
});
return [
{
type: PIECE_TYPE.ATTR,
name: attrData.attrName,
value: valueStr,
},
];
}
function generateAttr(
attrName: string,
attrValue: CompositeValue,
scope: IScope,
config?: NodeGeneratorConfig,
): CodePiece[] {
let pieces: CodePiece[];
if (config?.attrPlugins) {
pieces = executeFunctionStack<AttrData, CodePiece[], NodeGeneratorConfig>(
{ attrName, attrValue },
scope,
config.attrPlugins,
generateAttrValue,
config,
);
} else {
pieces = generateAttrValue({ attrName, attrValue }, scope, config);
}
pieces = pieces.map((p) => {
// FIXME: 在经过 generateCompositeType 处理过之后,其实已经无法通过传入值的类型判断传出值是否为纯字面值字符串了(可能包裹了加工函数之类的)
// 因此这个处理最好的方式是对传出值做语法分析,判断以哪种模版产出 Attr 值
let newValue: string;
if (p.value && isPureString(p.value)) {
// 似乎多次一举,目前的诉求是处理多种引号类型字符串的 case,正确处理转义
const content = getStaticExprValue<string>(p.value);
newValue = JSON.stringify(encodeJsxStringNode(content));
} else {
newValue = `{${p.value}}`;
}
return {
value: `${p.name}=${newValue}`,
type: PIECE_TYPE.ATTR,
};
});
return pieces;
}
function generateAttrs(
nodeItem: NodeSchema,
scope: IScope,
config?: NodeGeneratorConfig,
): CodePiece[] {
const { props } = nodeItem;
let pieces: CodePiece[] = [];
if (props) {
if (!Array.isArray(props)) {
Object.keys(props).forEach((propName: string) => {
pieces = pieces.concat(generateAttr(propName, props[propName], scope, config));
});
} else {
props.forEach((prop) => {
if (prop.name && !prop.spread) {
pieces = pieces.concat(generateAttr(prop.name, prop.value, scope, config));
}
// TODO: 处理 spread 场景(<Xxx {...(something)}/>)
// 这种在 schema 里面怎么描述
});
}
}
return pieces;
}
function generateBasicNode(
nodeItem: NodeSchema,
scope: IScope,
config?: NodeGeneratorConfig,
): CodePiece[] {
const pieces: CodePiece[] = [];
const tagName = (config?.tagMapping || _.identity)(nodeItem.componentName);
pieces.push({
value: tagName || '', // FIXME: type detection error
type: PIECE_TYPE.TAG,
});
return pieces;
}
function generateSimpleNode(
nodeItem: NodeSchema,
scope: IScope,
config?: NodeGeneratorConfig,
): CodePiece[] {
const basicParts = generateBasicNode(nodeItem, scope, config) || [];
const attrParts = generateAttrs(nodeItem, scope, config) || [];
const childrenParts: CodePiece[] = [];
if (nodeItem.children && config?.self) {
const childrenStr = config.self(nodeItem.children, scope);
childrenParts.push({
type: PIECE_TYPE.CHILDREN,
value: childrenStr,
});
}
return [...basicParts, ...attrParts, ...childrenParts];
}
function linkPieces(pieces: CodePiece[]): string {
const tagsPieces = pieces.filter((p) => p.type === PIECE_TYPE.TAG);
if (tagsPieces.length !== 1) {
throw new CodeGeneratorError('One node only need one tag define');
}
const tagName = tagsPieces[0].value;
const beforeParts = pieces
.filter((p) => p.type === PIECE_TYPE.BEFORE)
.map((p) => p.value)
.join('');
const afterParts = pieces
.filter((p) => p.type === PIECE_TYPE.AFTER)
.map((p) => p.value)
.join('');
const childrenParts = pieces
.filter((p) => p.type === PIECE_TYPE.CHILDREN)
.map((p) => p.value)
.join('');
let attrsParts = pieces
.filter((p) => p.type === PIECE_TYPE.ATTR)
.map((p) => p.value)
.join(' ');
attrsParts = attrsParts ? ` ${attrsParts}` : '';
if (childrenParts) {
return `${beforeParts}<${tagName}${attrsParts}>${childrenParts}</${tagName}>${afterParts}`;
}
return `${beforeParts}<${tagName}${attrsParts} />${afterParts}`;
}
function generateNodeSchema(
nodeItem: NodeSchema,
scope: IScope,
config?: NodeGeneratorConfig,
): string {
const pieces: CodePiece[] = [];
if (config?.nodePlugins) {
const res = executeFunctionStack<NodeSchema, CodePiece[], NodeGeneratorConfig>(
nodeItem,
scope,
config.nodePlugins,
generateSimpleNode,
config,
);
pieces.push(...res);
} else {
pieces.push(...generateSimpleNode(nodeItem, scope, config));
}
return linkPieces(pieces);
}
// TODO: 生成文档
// 为包裹的代码片段生成子上下文,集成父级上下文,并传入子级上下文新增内容。(如果存在多级上下文怎么处理?)
// 创建新的上下文,并从作用域中取对应同名变量塞到作用域里面?
// export function createSubContext() {}
/**
* JSX 生成逻辑插件。在 React 代码模式下生成 loop 相关的逻辑代码
* @type NodePlugin Extended
*
* @export
* @param {NodeSchema} nodeItem 当前 UI 节点
* @returns {CodePiece[]} 实现功能的相关代码片段
*/
export function generateReactLoopCtrl(
nodeItem: NodeSchema,
scope: IScope,
config?: NodeGeneratorConfig,
next?: NodePlugin,
): CodePiece[] {
if (nodeItem.loop) {
const tolerateEvalErrors = config?.tolerateEvalErrors ?? true;
const loopItemName = nodeItem.loopArgs?.[0] || 'item';
const loopIndexName = nodeItem.loopArgs?.[1] || 'index';
// 新建作用域
const subScope = scope.createSubScope([loopItemName, loopIndexName]);
const pieces: CodePiece[] = next ? next(nodeItem, subScope, config) : [];
// 生成循环变量表达式
const loopDataExpr = pipe(
nodeItem.loop,
// 将 JSExpression 转换为 JS 表达式代码:
(expr) =>
generateCompositeType(expr, scope, {
handlers: config?.handlers,
tolerateEvalErrors: false, // 这个内部不需要包 try catch, 下面会统一加的
}),
// 将 this.xxx 转换为 __$$context.xxx:
(expr) => transformThis2Context(expr, scope, { ignoreRootScope: true }),
// 如果要容忍错误,则包一层 try catch (基于助手函数 __$$evalArray)
(expr) => (tolerateEvalErrors ? `__$$evalArray(() => (${expr}))` : expr),
);
pieces.unshift({
value: `(${loopDataExpr}).map((${loopItemName}, ${loopIndexName}) => ((__$$context) => (`,
type: PIECE_TYPE.BEFORE,
});
pieces.push({
value: `))(__$$createChildContext(__$$context, { ${loopItemName}, ${loopIndexName} })))`,
type: PIECE_TYPE.AFTER,
});
return pieces;
}
return next ? next(nodeItem, scope, config) : [];
}
/**
* JSX 生成逻辑插件。在 React 代码模式下生成 condition 相关的逻辑代码
* @type NodePlugin
*
* @export
* @param {NodeSchema} nodeItem 当前 UI 节点
* @returns {CodePiece[]} 实现功能的相关代码片段
*/
export function generateConditionReactCtrl(
nodeItem: NodeSchema,
scope: IScope,
config?: NodeGeneratorConfig,
next?: NodePlugin,
): CodePiece[] {
const pieces: CodePiece[] = next ? next(nodeItem, scope, config) : [];
if (nodeItem.condition != null && nodeItem.condition !== true) {
const value = generateCompositeType(nodeItem.condition, scope, {
handlers: config?.handlers,
});
pieces.unshift({
value: `!!(${value}) && (`,
type: PIECE_TYPE.BEFORE,
});
pieces.push({
value: ')',
type: PIECE_TYPE.AFTER,
});
}
return pieces;
}
/**
* JSX 生成逻辑插件。在 React 代码模式下,如果 Node 生成结果是一个表达式,则对其进行 { Expression } 包装
* @type NodePlugin
*
* @export
* @param {NodeSchema} nodeItem 当前 UI 节点
* @returns {CodePiece[]} 实现功能的相关代码片段
*/
export function generateReactExprInJS(
nodeItem: NodeSchema,
scope: IScope,
config?: NodeGeneratorConfig,
next?: NodePlugin,
): CodePiece[] {
const pieces: CodePiece[] = next ? next(nodeItem, scope, config) : [];
if ((nodeItem.condition != null && nodeItem.condition !== true) || nodeItem.loop != null) {
pieces.unshift({
value: '{',
type: PIECE_TYPE.BEFORE,
});
pieces.push({
value: '}',
type: PIECE_TYPE.AFTER,
});
}
return pieces;
}
const handleChildren = (v: string[]) => v.join('');
export function createNodeGenerator(cfg: NodeGeneratorConfig = {}): NodeGenerator<string> {
const generateNode = (nodeItem: NodeDataType, scope: IScope): string => {
if (_.isArray(nodeItem)) {
const resList = nodeItem.map((n) => generateNode(n, scope));
return handleChildren(resList);
}
if (isNodeSchema(nodeItem)) {
return generateNodeSchema(nodeItem, scope, {
...cfg,
self: generateNode,
});
}
const valueStr = generateCompositeType(nodeItem, scope, {
handlers: cfg.handlers,
nodeGenerator: generateNode,
});
if (isPureString(valueStr)) {
return encodeJsxStringNode(getStaticExprValue<string>(valueStr));
}
return `{${valueStr}}`;
};
return (nodeItem: NodeDataType, scope: IScope) =>
unwrapJsExprQuoteInJsx(generateNode(nodeItem, scope));
}
const defaultReactGeneratorConfig: NodeGeneratorConfig = {
nodePlugins: [generateReactExprInJS, generateReactLoopCtrl, generateConditionReactCtrl],
};
export function createReactNodeGenerator(cfg?: NodeGeneratorConfig): NodeGenerator<string> {
const newCfg = mergeNodeGeneratorConfig(defaultReactGeneratorConfig, cfg);
return createNodeGenerator(newCfg);
} | the_stack |
/// <reference types="node" />
declare namespace Pushbullet {
/**
* Push Direction
*/
enum MessageDirection {
incoming = 'incoming',
outgoing = 'outgoing',
self = 'self',
}
/**
* Base Push Types
*/
enum PushType {
Default = 'push',
Note = 'note',
Link = 'link',
File = 'file',
}
/**
* Image URLs
*/
enum ImageUrl {
Everything = '/img/deviceicons/everything.png',
System = '/img/deviceicons/system.png',
User = '/img/deviceicons/user.png',
Phone = '/img/deviceicons/phone.png',
Group = '/img/deviceicons/system.png'
}
/**
* Ephemeral Types
*/
enum EphemeralType {
Sms = 'messaging_extension_reply',
SmsChanged = 'sms_changed',
Notification = 'mirror',
Dismissal = 'dismissal',
Clipboard = 'clip'
}
/**
* Package Names
*/
enum PackageName {
Android = 'com.pushbullet.android',
}
/**
* Package Names
*/
enum URI {
Api = 'https://api.pushbullet.com',
Log = 'https://ocelot.pushbullet.com',
Redirect = 'https://www.pushbullet.com/'
}
/**
* Objects (such as pushes and devices) can be created, modified,
* listed and deleted. All timestamps that appear on objects are
* floating point seconds since the epoch, also called Unix Time.
*/
interface Item {
/**
* Unique identifier for this object
* Example: "ujpah72o0sjAoRtnM0jc"
*/
iden: string
/**
* false if the item has been deleted
* Example: true
*/
active: boolean
/**
* Creation time in floating point seconds (unix timestamp)
* Example: 1.381092887398433e+09
*/
created: number
/**
* Last modified time in floating point seconds (unix timestamp)
* Example: 1.441054560741007e+09
*/
modified: number
}
/**
* A Push.
*/
interface Push extends Item {
/**
* Type of the push, one of "note", "file", "link".
* Example: "note"
*/
type: PushType
/**
* true if the push has been dismissed by any device or if any device
* was active when the push was received
* Example: false
*/
dismissed: boolean
/**
* Unique identifier set by the client, used to identify a push in case you
* receive it from /v2/everything before the call to /v2/pushes has completed.
* This should be a unique value. Pushes with guid set are mostly idempotent,
* meaning that sending another push with the same guid is unlikely to create
* another push (it will return the previously created push).
* Example: "993aaa48567d91068e96c75a74644159"
*/
guid: string
/**
* Direction the push was sent in, can be "self", "outgoing", or "incoming"
* Example: "self"
*/
direction: MessageDirection
/**
* User iden of the sender
* Example: "ujpah72o0"
*/
sender_iden: string
/**
* Email address of the sender
* Example: "elon@teslamotors.com"
*/
sender_email: string
/**
* Canonical email address of the sender
* Example: "elon@teslamotors.com"
*/
sender_email_normalized: string
/**
* Name of the sender
* Example: "Elon Musk"
*/
sender_name: string
/**
* User iden of the receiver
* Example: "ujpah72o0"
*/
receiver_iden: string
/**
* Email address of the receiver
* Example: "elon@teslamotors.com"
*/
receiver_email: string
/**
* Canonical email address of the receiver
* Example: "elon@teslamotors.com"
*/
receiver_email_normalized: string
/**
* Device iden of the target device, if sending to a single device
* Example: "ujpah72o0sjAoRtnM0jc"
*/
target_device_iden: string
/**
* Device iden of the sending device. Optionally set by the sender when creating a push
* Example: "ujpah72o0sjAoRtnM0jc"
*/
source_device_iden: string
/**
* If the push was created by a client, set to the iden of that client.
* Example: "ujpah72o0sjAoRtnM0jc"
*/
client_iden: string
/**
* If the push was created by a channel, set to the iden of that channel
* Example: "ujpah72o0sjAoRtnM0jc"
*/
channel_iden: string
/**
* List of guids (client side identifiers, not the guid field on pushes)
* for awake apps at the time the push was sent. If the length of this
* list is > 0, dismissed will be set to true and the awake app(s) must
* decide what to do with the notification
* Example: ["web-2d8cdf2a2b9b","web-cdb2313c74e"]
*/
awake_app_guids: string[]
/**
* Title of the push, used for all types of pushes
* Example: "Space Travel Ideas"
*/
title: string
/**
* Body of the push, used for all types of pushes
* Example: "Space Elevator, Mars Hyperloop, Space Model S (Model Space?)
*/
body: string
/**
* URL field, used for type="link" pushes
* Example: "http://www.teslamotors.com/"
*/
url: string
/**
* File name, used for type="file" pushes
* Example: "john.jpg"
*/
file_name: string
/**
* File mime type, used for type="file" pushes
* Example: "image/jpeg"
*/
file_type: string
/**
* File download url, used for type="file" pushes
* Example: "https://dl.pushbulletusercontent.com
* /foGfub1jtC6yYcOMACk1AbHwTrTKvrDc/john.jpg"
*/
file_url: string
/**
* URL to an image to use for this push, present on
* type="file" pushes if file_type matches image/*
* Example: "https://lh3.googleuserconten.com
* /mrrz35lLbiYAz8ejkJcpdsYhN3tMEtrXxj93k_gQPin4GfdD
* jVy2Bj26pOGrpFQmAM7OFBHcDfdMjrScg3EUIJrgJeY"
*/
image_url: string
/**
* Width of image in pixels, only present if image_url is set
* Example: 322
*/
image_width: number
/**
* Height of image in pixels, only present if image_url is set
* Example: 484
*/
image_height: number
}
/**
* Chats are created whenever you send a message to someone or a receive
* a message from them and there is no existing chat between you and the
* other user.
*/
interface Chat extends Item {
/**
* If true, notifications from this chat will not be shown
* Example: false
*/
muted: boolean
/**
* The user or email that the chat is with
*/
with: {
/**
* If this is a user, the iden of that user
* Example: "ujlMns72k"
*/
iden: string
/**
* "email" or "user"
* Example: "user"
*/
type: ('email' | 'user')
/**
* Name of the person
* Example: "John Carmack"
*/
name: string
/**
* Email address of the person
* Example: "carmack@idsoftware.com"
*/
email: string
/**
* Canonical email address of the person
* Example: "carmack@idsoftware.com"
*/
email_normalized: string
/**
* Image to display for the person
* Example: "https://dl.pushbulletusercontent.com
* /foGfub1jtC6yYcOMACk1AbHwTrTKvrDc/john.jpg"
*/
image_url: string
}
}
/**
* A Device.
*/
interface Device extends Item {
/**
* Icon to use for this device, can be an arbitrary string.
* Commonly used values are: "desktop", "browser", "website", "laptop", "tablet", "phone", "watch", "system"
* Example: ios
*/
icon?: string
/**
* Name to use when displaying the device
* Example: "Elon Musk's iPhone"
*/
nickname?: string
/**
* true if the nickname was automatically generated from the manufacturer and model fields (only used for some android phones)
* Example: true
*/
generated_nickname?: boolean
/**
* Manufacturer of the device
* Example: "Apple
*/
manufacturer?: string
/**
* Model of the device
* Example: "iPhone 5s (GSM)"
*/
model: string
/**
* Version of the Pushbullet application installed on the device
* Example: 8623
*/
app_version?: number
/**
* String fingerprint for the device, used by apps to avoid duplicate
* devices. Value is platform-specific.
* Example: "nLN19IRNzS5xidPF+X8mKGNRpQo2X6XBgyO30FL6OiQ="
*/
fingerprint?: string
/**
* Fingerprint for the device's end-to-end encryption key, used to
* determine which devices the current device (based on its own
* key fingerprint) will be able to talk to.
* Example: "5ae6ec7e1fe681861b0cc85c53accc13bf94c11db7461a2808903f7469bfda56"
*/
key_fingerprint?: string
/**
* Platform-specific push token. If you are making your own device, leave
* this blank and you can listen for events on the Realtime Event Stream.
* Example: "production:f73be0ee7877c8c7fa69b1468cde764f"
*/
push_token?: (string | null)
/**
* true if the devices has SMS capability, currently only true for type="android" devices
* Example: true
*/
has_sms?: boolean
/**
* true if the devices has MMS capability, currently only true for type="android" devices
* Example: true
*/
has_mms?: boolean
/**
* @deprecated use {@link icon} field instead
* Type of device, can be an arbitrary string.
* Commonly used values are: "android", "chrome", "firefox", "ios", "windows", "stream", "safari", "mac", "opera", "website"
*/
type?: string
/**
* @deprecated old name for {@link type}
*/
kind?: string
/**
* @deprecated used to be for partially-initialized type="android" devices
*/
pushable?: string
}
/**
* Subscribe to channels to receive any updates pushed to that channel.
* Channels can be created on the website. Each channel has a unique tag to identify it.
* When you push to a channel, all people subscribed to that channel will receive a push.
* To push to a channel, use the channel_tag parameter on create-push
*/
interface Subscription extends Item {
/**
* If true, notifications from this chat will not be shown
* Example: false
*/
muted: boolean
/**
* Information about the channel that is being subscribed to
*/
channel: {
/**
* Unique identifier for the channel
* Example: "ujpah72o0sjAoRtnM0jc"
*/
iden: string
/**
* Unique tag for this channel
* Example: "elonmusknews"
*/
tag: string
/**
* Name of the channel
* Example: "Elon Musk News"
*/
name: string
/**
* Description of the channel
* Example: "News about Elon Musk."
*/
description: string
/**
* Image for the channel
* Example: "https://dl.pushbulletusercontent.com/StzRmwdkIe8gluBH3XoJ9HjRqjlUYSf4/musk.jpg"
*/
image_url: string
/**
/**
* Link to a website for the channel
* Example: "https://twitter.com/elonmusk"
*/
website_url: string
}
}
/**
* User
*/
interface User extends Item {
/**
* Email address
* Example: "elon@teslamotors.com"
*/
email: string
/**
* Canonical email address
* Example: "elon@teslamotors.com"
*/
email_normalized: string
/**
* Full name if available
* Example: "Elon Musk"
*/
name: string
/**
* URL for image of user or placeholder image
* Example: "https://static.pushbullet.com/missing-image/55a7dc-45"
*/
image_url: string
/**
* Maximum upload size in bytes
* Example: 26214400
*/
max_upload_size: number
/**
* Number of users referred by this user
* Example: 2
*/
referred_count: number
/**
* User iden for the user that referred the current user, if set
* Example: "ujlxm0aiz2"
*/
referrer_iden: string
}
/**
* OAuth Grants (Connected Apps)
*/
interface Grant extends Item {
client: {
/**
* Unique identifier for the grant
* Example: "ujpah72o0sjAoRtnM0jc"
*/
iden: string
/**
* Image for the grant
* Example: "https://dl.pushbulletusercontent.com/StzRmwdkIe8gluBH3XoJ9HjRqjlUYSf4/musk.jpg"
*/
image_url: string
/**
* Name of the grant
* Example: "Elon Musk News"
*/
name: string
/**
/**
* Link to a website for the grant
* Example: "https://twitter.com/elonmusk"
*/
website_url: string
}
}
/**
* Text
*/
interface Text extends Item {
data: {
/**
* The iden of the device corresponding to the phone that should send the text.
* Example: "ujpah72o0sjAoRtnM0jc"
*/
target_device_iden: string
/**
* The phone numbers the text should be sent to.
* Example: "000155533133"
*/
addresses: string[]
/**
* The text message to send.
* Example: "Hello!"
*/
message: string
/**
* File mime type, used for type="file" pushes
* Example: "image/jpeg"
*/
file_type: string
}
}
/**
* You can send arbitrary JSON messages, called "ephemerals", to all
* devices on your account. Ephemerals are stored for a short period of
* time (if at all) and are sent directly to devices.
*/
interface BaseEphemeral {
/**
* Must be set to push which is the only type of ephemeral currently.
*/
type: "push"
/**
* true if the message is encrypted
* Example: "MXAdvN64uXWtLXCRaqYHEtGhiogR1VHyXX21Lpjp4jv3v+JWygMBA9Wp5npbQdfeZAgOZI+JT3y3pbmq+OrKXrK1rg=="
*/
encrypted?: boolean
/**
* Base64-Encoded JSON Object
* Example: "MXAdvN64uXWtLXCRaqYHEtGhiogR1VHyXX21Lpjp4jv3v+JWygMBA9Wp5npbQdfeZAgOZI+JT3y3pbmq+OrKXrK1rg=="
*/
ciphertext?: string
/**
* JSON Data
* Example: "MXAdvN64uXWtLXCRaqYHEtGhiogR1VHyXX21Lpjp4jv3v+JWygMBA9Wp5npbQdfeZAgOZI+JT3y3pbmq+OrKXrK1rg=="
*/
push?: (SmsEphemeral | SmsChangeEphemeral | NotificationEphemeral | DismissalEphemeral | ClipboardEphemeral)
}
/**
* SMS Ephemeral
*/
interface SmsEphemeral {
/**
* "messaging_extension_reply" for sending SMS.
*/
type: EphemeralType.Sms
/**
* The user iden of the user sending this message.
* Example: "ujpah72o0"
*/
source_user_iden: string
/**
* "com.pushbullet.android" for sending SMS.
*/
package_name: PackageName.Android
/**
* The iden of the device corresponding to the phone that should send the SMS.
* Example: "ujpah72o0sjAoRtnM0jc"
*/
target_device_iden: string
/**
* Phone number to send the SMS to.
* Example: "+1 303 555 1212"
*/
conversation_iden: string
/**
* The SMS message to send.
* Example: "Hello!"
*/
message: string
}
/**
* SmS Change Ephemeral Data
*/
interface SmsChangeEphemeral {
/**
* "clip" for clipboard messages.
*/
type: EphemeralType.SmsChanged
/**
* The iden of the device sending this message.
* Example: "ujpah72o0sjAoRtnM0jc"
*/
source_device_iden: string
/**
* The iden of the device sending this message.
* Example: "ujpah72o0sjAoRtnM0jc"
*/
notifications: {
/**
* The SMS message text
* Example: "Hello!"
*/
body: string
/**
* The SMS messages' originating phone number
* Example: "6505551212"
*/
title: string
/**
* The SMS messages' timestamp
* Example: 1546022176
*/
timestamp: number
/**
* Unique identifier of the corresponding SMS message thread
* Example: "3"
*/
thread_id: string
}
}
/**
* Mirrored Notification Ephemeral
*/
interface NotificationEphemeral {
/**
* "mirror" for mirrored notifications.
*/
type: EphemeralType.Notification
/**
* The user iden of the user sending this message.
* Example: "ujpah72o0"
*/
source_user_iden: string
/**
* Base64-encoded JPEG image to use as the icon of the push.
* Example: "/9j/4AAQSkZJRgABAQAA [..]"
*/
icon: string
/**
* The title of the notification.
* Example: "Mirroring test"
*/
title: string
/**
* The body of the notification.
* Example: "If you see this on your computer, Android-to-PC notifications are working!\n"
*/
body: string
/**
* The iden of the device sending this message.
* Example: "ujpah72o0sjAoRtnM0jc"
*/
source_device_iden: string
/**
* The name of the application that created the notification.
* Example: "Pushbullet"
*/
application_name: string
/**
* True if the notification can be dismissed.
* Example: true
*/
dismissable: boolean
/**
* The package that made the notification, used when updating/dismissing an existing notification.
* Example: "com.pushbullet.android"
*/
package_name: string
/**
* The id of the notification, used when updating/dismissing an existing notification.
* Example: "-8"
*/
notification_id: string
/**
* The tag of the notification, used when updating/dismissing an existing notification.
* Example: null
*/
notification_tag: (string | null)
/**
* The phone is rooted.
* Example: false
*/
has_root: boolean
/**
* The client version of the app sending this message.
* Example: 125
*/
client_version: number
}
/**
* Dismissal Ephemeral
*/
interface DismissalEphemeral {
/**
* "dismissal" for notification dismissals.
*/
type: EphemeralType.Dismissal
/**
* The user iden of the user sending this message.
* Example: "ujpah72o0"
*/
source_user_iden: string
/**
* Set to the package_name field from the mirrored notification.
*/
package_name: string
/**
* Set to the notification_id field from the mirrored notification.
* Example: "-8"
*/
notification_id: string
/**
* Set to the notification_tag field from the mirrored notification.
* Example: null
*/
notification_tag: (string | null)
}
/**
* Clipboard Ephemeral Data
*/
interface ClipboardEphemeral {
/**
* "clip" for clipboard messages.
*/
type: EphemeralType.Dismissal
/**
* The user iden of the user sending this message.
* Example: "ujpah72o0"
*/
source_user_iden: string
/**
* The text to copy to the clipboard.
*/
body: string
/**
* The iden of the device sending this message.
* Example: "ujpah72o0sjAoRtnM0jc"
*/
source_device_iden: string
}
}
/**
* Pushbullet Web Client Interface via window.pb
*/
declare namespace PushbulletBrowserClient {
interface Window {
/**
* window.pb
*/
pb: {
VERSION: number
DEBUG: boolean
API_SERVER: Pushbullet.URI.Api
AUTH_REDIRECT_URI: Pushbullet.URI.Log
LOG_SERVER: Pushbullet.URI.Log
URLS: {
android: 'https://play.google.com/store/apps/details?id=com.pushbullet.android&referrer=utm_source%3Dpushbullet.com'
chrome: 'https://chrome.google.com/webstore/detail/chlffgpmiacpedhhbkiomidkjlcfhogd'
firefox: 'https://addons.mozilla.org/en-US/firefox/addon/pushbullet/versions/'
ios: 'https://itunes.apple.com/us/app/pushbullet/id810352052?ls=1&mt=8'
mac: 'https://itunes.apple.com/us/app/pushbullet-from-pushbullet/id948415170?ls=1&mt=12'
opera: 'https://addons.opera.com/en/extensions/details/pushbullet/'
safari: 'http://update.pushbullet.com/extension.safariextz'
windows: 'https://update.pushbullet.com/pushbullet_installer.exe'
}
session_id: string
file_dragging: boolean
in_frame: boolean
PUSH_PER_PAGE: number
show_pushes: number
client_id: string
stuff_loaded: boolean
delete_mode: null
rename_mode: null
logging_in: boolean
pro: {
plan: string
upgrading: boolean
}
db: {
VERSION: number
local_storage: boolean
}
channels: {
uploading: boolean
file_url: string
}
channel_create: {
expanded: boolean
}
chats: {
picker: Picker
}
everything: {
modified_after: string
cursor: {}
}
net: {
API_VERSION: string
USER_AGENT: string
}
header: {
height: number
navs: Array<[string, string]>
mobile: boolean
}
path: string[]
visit_info: {
path: string
referrer: string
browser_name: string
browser_version: string
browser_mobile: boolean
user_agent: string
platform: string
language: string
encryption: boolean
}
browser: {
name: string
version: string
mobile: boolean
}
setup: {
invite_picker: Picker
invite_emails: {}
}
account: Pushbullet.User
pushbox: {
target: object
scroll_lock: boolean
width_minibar: number
width_sidebar: number
width_mainbar: number
}
support: {
email: string
message: string
message_sent: boolean
guesses: object[]
name: string
}
remotefiles: {
view: string
device_started: boolean
popup: object
}
pushform: {
target: object
expanded: boolean
type: string
title?: string
content?: string
url?: string
address?: string
file_name: string
file_url?: string
file_type?: string
file_progress: number
message: string
error_message: string
waiting: boolean
to_selection: number
picker: {
props: {
direction: string
placeholder: string
clear_on_click: boolean
}
search?: string
target: string
}
showing: boolean
}
search: {
type: string
q: string
}
targets: {
delete_check_iden: string
block_check_iden: string
}
sms: {
q: string[]
message_time_out: number
count: number
form_showing: boolean
picker: Picker
new_sms_picker: Picker
target: object
wants_thread_id: string
}
chat_heads: object
clients: object
oauth: object
widget: object
error: object
pushes: object
/**
* Pushbullet Backend API Suites
*/
api: {
accounts: PushbulletApiSuite.AccountsApi
devices: PushbulletApiSuite.DevicesApi
grants: PushbulletApiSuite.GrantsApi
pinger: PushbulletApiSuite.PingerSuite
pushes: PushbulletApiSuite.PushesApi
sms: PushbulletApiSuite.SmsApi
text: PushbulletApiSuite.TextsApi
},
/**
* E2E Utilities
*/
e2e: {
decrypt(encrypted: string): string
enabled: boolean
encrypt(plaintext: string): string
error: boolean
init(): void
key_fingerprint: string
set_password(plaintext: string): string
}
},
/**
* UI Utilities
*/
onecup: {
/**
* Navigates to the given URL.
*/
goto(url: string): void
/**
* Marks the UI as requiring a refresh.
*/
refresh(): void
}
/**
* Sidebar Utilities
*/
sidebar: {
needs_update: boolean
/**
* Marks the Sidebar as requiring a refresh.
*/
update(): void
},
/**
* SMS Utilities
*/
sms: {
message_time_out: 30000
count: number
form_showing: boolean
picker: object
send(message: string): void
send_new(): void
send_file(file: Pushbullet.Push): void
target: {
desc: string
image_url: string
info: {
blurb: ""
count: number
recent: number
}
name: string
obj: Pushbullet.Device
type: string
url: string
}
}
/**
* Websocket Utilities
*/
ws: {
last_message: 30000
connected: boolean
socket: WebSocket
}
/**
* Push Targeting Utilities
*/
targets: {
block_check_iden: string
by_device_iden(iden: string): Pushbullet.Item
by_email(email: string): Pushbullet.Item
by_tag(tag: string): Pushbullet.Item
chats(): Pushbullet.Chat[]
delete_check_iden: string
devices: Pushbullet.Device[]
generate(): void
make(obj: Pushbullet.Item, force_type?: string): Pushbullet.Item
make_ac_target(ac: Pushbullet.Chat): Pushbullet.Item
make_email(email: string): Pushbullet.Item
make_phone(phone: string): Pushbullet.Item
match(target: object): boolean
subscriptions(): Pushbullet.Item[]
}
/**
* Generate Random Identifier
*/
rand_iden(): string
/**
* Database Utilities
*/
db: {
VERSION: number
local_storage: boolean
check(): void
clear(): void
del_simple(key: string): void
get(key: string): string
get_simple(key: string): string
set(key: string, data: any): void
set_simple(key: string, data: any): void
space(): void
version_guard(): boolean
}
}
/**
* SMS Message Thread
*/
interface SmsMessageRecipient {
number: string
name: string
address: string
}
/**
* SMS Message Thread
*/
interface SmsMessageThread {
/**
* Unique identifier for this Thread
*/
id: string
/**
* Latest SMS Message in Thread
*/
latest: {
type: 'sms'
id: string
guid: string
body: string
direction: Pushbullet.MessageDirection
status: ('sent' | 'not sent')
timestamp: number
}
recipients: SmsMessageRecipient[]
}
}
interface Picker {
props: {
placeholder: string
label: string
direction: ('bottom' | 'top')
clear_on_click: boolean
phone_suggest?: boolean
email_suggest?: boolean
cb(): void
[key: string]: any
}
}
declare namespace PushbulletApiSuite {
/**
* Base API Suite
*/
interface BaseApiSuite {
type: string
name: string
nice_name: string
uri: string
all: (Pushbullet.Item[] | [])
objs: { [key: string]: Pushbullet.Item[] }
_load_storage(): void
_save_storage(): void
build_all(): void
clear_error(): void
create(item: BasePushCreationOptions | NoteCreationOptions | LinkCreationOptions | FileCreationOptions | Object): void
delete(item: Pushbullet.Item): void
new_item(push: Pushbullet.Item): void
post_create(): void
post_get(): void
reset(): void
save(): void
set_all(items: Pushbullet.Item[]): void
start(): void
update(item: Pushbullet.Item): void
new_obj: {}
loaded: boolean
getting: boolean
creating: boolean
updating: boolean
deleting: boolean
delete_check: boolean
have_fetched: boolean
modified_after: number
}
/**
* Base Push Creation Options
*/
interface BasePushCreationOptions {
/**
* Type of the push, one of "note", "file", "link".
* Example: "note"
*/
type: (Pushbullet.PushType | string)
/**
* Send the push to a specific device. Appears as target_device_iden on the push.
*/
device_iden?: string
/**
* Send the push to this email address. If that email address is associated with
* a Pushbullet user, we will send it directly to that user, otherwise we will
* fallback to sending an email to the email address (this will also happen if
* a user exists but has no devices registered).
*/
email?: string
/**
* Send the push to all subscribers to your channel that has this tag.
*/
channel_tag?: string
/**
* Send the push to all users who have granted access to your OAuth client that has this iden.
*/
client_iden?: string
/**
* A message associated with the push.
*/
body: string
}
/**
* Note Creation Options
*/
interface NoteCreationOptions extends BasePushCreationOptions {
/**
* The note's title.
*/
title: string
}
/**
* Link Creation Options
*/
interface LinkCreationOptions extends BasePushCreationOptions {
/**
* The link's title.
*/
title: string
/**
* URL field, used for type="link" pushes
* Example: "http://www.teslamotors.com/"
*/
url: string
}
/**
* File Creation Options
*/
interface FileCreationOptions extends BasePushCreationOptions {
/**
* The name of the file.
* Example: "john.jpg"
*/
file_name: string
/**
* The MIME type of the file.
* Example: "image/jpeg"
*/
file_type: string
/**
* The url for the file. See pushing files for how to get a file_url
* Example: "https://dl.pushbulletusercontent.com/foGfub1jtC6yYcOMACk1AbHwTrTKvrDc/john.jpg"
*/
file_url: string
}
/**
* Pushes API
*/
interface PushesApi extends BaseApiSuite {
type: (Pushbullet.PushType | string)
name: "pushes"
nice_name: "Push"
uri: "/v2/pushes"
default_image_url: Pushbullet.ImageUrl.Everything
queue: Pushbullet.Push[]
error_queue: Pushbullet.Push[]
file_queue: Pushbullet.Push[]
dismissing: { [key: string]: boolean[] }
notified_push_idens: string[]
add_target(push: Pushbullet.Push): void
delete_all(): void
dismiss(push: Pushbullet.Push): void
do_file_queue(): void
do_push_queue(): void
notified(): void
notify_after: boolean
post_get(): void
queue_push(push: Pushbullet.Push): void
remove_from_error_queue(push: Pushbullet.Push): void
remove_from_file_queue(push: Pushbullet.Push): void
remove_from_queue(push: Pushbullet.Push): void
retry_send(push: Pushbullet.Push): void
send(): void
send_file(): void
should_notify(): void
start(): void
upload_abort(push: Pushbullet.Push): void
upload_file(file: string, callback: Function): void
upload_file_finish(upload: object, push: Pushbullet.Push): void
upload_file_parts(upload: object, push: Pushbullet.Push, index: number): void
upload_push(push: Pushbullet.Push): void
}
/**
* SMS API
*/
interface SmsApi extends BaseApiSuite {
default_image_url: Pushbullet.ImageUrl.User
default_group_image_url: Pushbullet.ImageUrl.Group
thread: Pushbullet.SmsEphemeral[]
threads: Pushbullet.SmsEphemeral[]
fetch_device(): void
fetch_thread(): void
first_sms_device(): Pushbullet.Device
get_phonebook(): void
phonebook_cache: {}
set_limit(limit: number): void
start(): void
tickle(): void
}
/**
* Accounts API
*/
interface AccountsApi extends BaseApiSuite {
type: "account"
default_image_url: Pushbullet.ImageUrl.User
name: "accounts"
nice_name: "Account"
uri: "/v2/accounts"
fetch_device(): void
fetch_thread(): void
get_phonebook(): void
phonebook_cache: {}
set_limit(limit: number): void
start(): void
tickle(): void
}
/**
* Devices API
*/
interface DevicesApi extends BaseApiSuite {
type: "device"
default_image_url: Pushbullet.ImageUrl.Phone
name: "devices"
nice_name: "Device"
uri: "/v2/devices"
last_awake_time: number
last_awake_state: boolean
is_awake(): boolean
awake(state: boolean): void
guess_icon(device: Pushbullet.Device): string
}
/**
* Texts API
*/
interface TextsApi extends BaseApiSuite {
type: "text"
name: "texts"
nice_name: "Text"
send(device: Pushbullet.Device, addresses: string[], message: string, guid: string, thread_id: string, file_type: string, file_url: string): boolean
}
/**
* Grants API
*/
interface GrantsApi extends BaseApiSuite {
type: "grant"
name: "grants"
nice_name: "OAuth Grant"
default_image_url: Pushbullet.ImageUrl.System
uri: "/v2/grants"
by_client_iden(iden: string): Pushbullet.Grant
}
/**
* Account API
*/
interface Account {
last_active: number
preferences: {}
track_active(): void
start(): void
get(): void
save(): void
set(account: object): void
delete(): void
delete_all_access_tokens(): void
create_access_token(): void
setup_done(type: string): void
setup_restart(type: string): void
load_preferences(): void
migrate_preferences(): void
save_preferences(): void
upgrade_pro(token_id: string, plan_id: string): void
downgrade_pro(): void;
}
/**
* Pinger Suite
*/
interface PingerSuite {
online: {}
last_ping_time: number
pong_iden(device_iden: string): void
ping_all(): void
}
} | the_stack |
import {
useRef,
useLayoutEffect,
ReactNode,
MouseEventHandler,
LegacyRef,
} from 'react';
import isEqual from 'lodash/isEqual';
import { warning, filterDataAttributes } from '@commercetools-uikit/utils';
import { usePrevious } from '@commercetools-uikit/hooks';
import {
TableContainer,
TableGrid,
Header,
Body,
Row,
} from './data-table.styles';
import Footer from './footer';
import HeaderCell from './header-cell';
import DataRow from './data-row';
import useManualColumnResizing from './use-manual-column-resizing-reducer';
import ColumnResizingContext from './column-resizing-context';
export interface TRow {
id: string;
}
const getColumnsLayoutInfo = (columns: TColumn[]) =>
columns.reduce<Pick<TColumn, 'key' | 'width'>[]>(
(acc, currentValue) => [
...acc,
{ key: currentValue.key, width: currentValue.width },
],
[]
);
const shouldRenderRowBottomBorder = (
rowIndex: number,
rowCount: number,
footer: ReactNode
) => {
if (!footer) return true;
if (rowIndex + 1 < rowCount) return true;
return false;
};
const defaultProps: Pick<
TDataTableProps,
| 'columns'
| 'isCondensed'
| 'wrapHeaderLabels'
| 'horizontalCellAlignment'
| 'verticalCellAlignment'
| 'disableSelfContainment'
| 'itemRenderer'
> = {
columns: [],
isCondensed: false,
wrapHeaderLabels: true,
verticalCellAlignment: 'top',
horizontalCellAlignment: 'left',
disableSelfContainment: false,
// @ts-ignore
itemRenderer: (row, column) => row[column.key],
};
export type TColumn<Row extends TRow = TRow> = {
/**
* The unique key of the column that is used to identify your data type.
* You can use this value to determine which value from a row item should be rendered.
* <br>
* For example, if the data is a list of users, where each user has a `firstName` property,
* the column key should be `firstName`, which renders the correct value by default.
* The key can also be some custom or computed value, in which case you need to provide
* an explicit mapping of the value by implementing either the `itemRendered` function or
* the column-specific `renderItem` function.
*/
key: string;
/**
* The label of the column that will be shown on the column header.
*/
label: ReactNode;
/**
* Sets a width for this column. Accepts the same values as the ones specified for
* individual [grid-template-columns](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns).
* <br>
* For example, using `minmax` pairs (e.g. `minmax(200px, 400px)`), a combinations of
* fraction values (`1fr`/`2fr`/etc), or fixed values such as `200px`.
* By default, the column grows according to the content and respecting the total table available width.
*
* @@defaultValue@@: auto
*/
width?: string;
/**
* Use this to override the table's own `horizontalCellAlignment` prop for this specific column.
*/
align?: 'left' | 'center' | 'right';
/**
* A callback function, called when the header cell is clicked.
* <br>
* Signature: `(event) => void`
*/
onClick?: (event: MouseEventHandler) => void;
/**
* A callback function to render the content of cells under this column, overriding
* the default `itemRenderer` prop of the table.
* <br>
* Signature: `(row: object, isRowCollapsed: boolean) => React.Node`
*/
renderItem?: (row: Row, isRowCollapsed: boolean) => ReactNode;
/**
* Use this prop to place an `Icon` or `IconButton` on the left of the column label.
* It is advised to place these types of components through this prop instead of `label`,
* in order to properly position and align the elements.
* This is particularly useful for medium-sized icons which require more vertical space than the typography.
*/
headerIcon?: ReactNode;
/**
* Set this to `true` to allow text content of this cell to be truncated with an ellipsis,
* instead of breaking into multiple lines.
* <br>
* NOTE: when using this option, it is recommended to specify a `width` for the column, because
* if the table doesn't have enough space for all columns, it will start clipping the columns
* with _truncated_ content, and if no `width` is set (or the value is set `auto` -- the default)
* it can shrink until the column disappears completely.
* By enforcing a minimum width for these columns, the table will respect them and grow horizontally,
* adding scrollbars if needed.
*
* @@defaultValue@@: false
*/
isTruncated?: boolean;
/**
* Set this to `true` to show a sorting button, which calls `onSortChange` upon being clicked.
* You should enable this flag for every column you want to be able to sort.
* When at least one column is sortable, the table props `sortBy`, `sortDirection` and `onSortChange` should be provided.
*
* @@defaultValue@@: false
*/
isSortable?: boolean;
/**
* Set this to `true` to prevent this column from being manually resized by dragging
* the edge of the header with a mouse.
*
* @@defaultValue@@: false
*/
disableResizing?: boolean;
/**
* Set this to `true` to prevent click event propagation for this cell.
* You might want this if you need the column to have its own call-to-action or input while
* the row also has a defined `onRowClick`.
*
* @@defaultValue@@: false
*/
shouldIgnoreRowClick?: boolean;
};
export type TDataTableProps<Row extends TRow = TRow> = {
/**
* The list of data that needs to be rendered in the table. Each object in the list can
* have any shape as long as it has a unique identifier.
* The data is rendered by using the callback render function `itemRenderer`.
*/
rows: Row[];
/**
* Each object requires a unique `key` which should correspond to property key of
* the items of `rows` that you want to render under this column, and a `label`
* which defines the name shown on the header.
* The list of columns to be rendered.
* Each column can be customized (see properties below).
*/
columns: TColumn[];
/**
* Element to render within the `tfoot` (footer) element of the table.
*/
footer?: ReactNode;
/**
* The max width (a number of pixels or a css value string with units) for which the table
* is allowed to grow. If unset, the table will grow horizontally to fill its parent.
*/
maxWidth?: number | string;
/**
* The max height (a number of pixels or a css value string with units) for which the table
* is allowed to grow. If unset, the table will grow vertically to fill its parent.
*/
maxHeight?: number | string;
/**
* A callback function, called when a user clicks on a row.
* <br>
* Signature `(row: object, rowIndex: number, columnKey: string) => void`
*/
onRowClick?: (row: TRow, rowIndex: number, columnKey: string) => void;
/**
* Set this to `true` to reduce the paddings of all cells, allowing the table to display
* more data in less space.
*/
isCondensed?: boolean;
/**
* A callback function, called when a column has been resized.
* Use this callback to get the resized column widths and save them, to be able to restore the
* value once the user comes back to the page.
* <br>
* Signature: `([{key: string, width: number} ...]) => func()`
*/
onColumnResized?: (args: TColumn<Row>[]) => void;
/**
* Set this to `true` to take control of the containment of the table and doing it on a parent element.
* This means that the table will grow in size without adding scrollbars on itself,
* both vertically and horizontally and, as a consequence, the `maxHeight` and `maxWidth` props are ignored.
* If you need to enforce these constraints, you must also apply them on the parent element.
* Additionally, the sticky behaviour of the header will get fixed relatively to the closest
* parent element with `position: relative`.
*/
disableSelfContainment?: boolean;
/**
* Set this to `true` to prevent the header from being sticky.
*/
disableHeaderStickiness?: boolean;
/**
* The default function used to render the content of each item in a cell.
* In case a column has its own `renderItem` render function, it will take precedence over this function.
* <br>
* Signature: `(item: object, column: object, isRowCollapsed: boolean) => React.Node`
*/
itemRenderer: (
item: TRow,
column: TColumn<Row>,
isRowCollapsed: boolean
) => ReactNode;
/**
* Set this to `false` to ensure that every column can render their label in one line.
* By default the header cell grows in height in case the label does not fit in one line.
*/
wrapHeaderLabels?: boolean;
/**
* The default cell vertical alignment of each row (not the table header).
*/
verticalCellAlignment?: 'top' | 'center' | 'bottom';
/**
* The default cell horizontal alignment.
* In case a column has its own `align` property, it will take precedence over this value.
*/
horizontalCellAlignment?: 'left' | 'center' | 'right';
/**
* The key of the column for which the data is currently sorted by.
*/
sortedBy?: string;
/**
* A callback function, called when a sortable column's header is clicked.
* It's required when the `isSortable` flag is set on at least one column.
* <br>
* Signature: `(columnKey: string, sortDirection: string) => void`.
*/
onSortChange?: (columnKey: string, sortDirection: 'asc' | 'desc') => void;
/**
* The sorting direction.
*/
sortDirection?: 'desc' | 'asc';
};
const DataTable = <Row extends TRow = TRow>(props: TDataTableProps<Row>) => {
warning(
props.columns.length > 0,
`ui-kit/DataTable: empty table "columns", expected at least one column. If you are using DataTableManager you need to pass the "columns" there and they will be injected into DataTable.`
);
const tableRef = useRef<HTMLTableElement>();
const columnResizingReducer = useManualColumnResizing(tableRef);
// if the table columns have been measured
// and if the list of columns, their width field, or the isCondensed prop has changed
// then we need to reset the resized column widths
const columnsInfo = getColumnsLayoutInfo(props.columns);
const prevLayout = usePrevious({
columns: columnsInfo,
isCondensed: props.isCondensed,
});
const currentLayout = {
columns: columnsInfo,
isCondensed: props.isCondensed,
};
const hasLayoutChanged = !isEqual(prevLayout, currentLayout);
useLayoutEffect(() => {
if (hasLayoutChanged) {
columnResizingReducer.reset();
}
}, [columnResizingReducer, hasLayoutChanged]);
const hasTableBeenResized = columnResizingReducer.getHasTableBeenResized();
const resizedTotalWidth =
hasTableBeenResized && tableRef.current
? columnResizingReducer.getTotalResizedTableWidth() +
// if the table has a maxHeight, it might add a scrollbar which takes space inside the container
(tableRef.current.offsetWidth - tableRef.current.clientWidth)
: undefined;
return (
<TableContainer
maxWidth={props.maxWidth}
isBeingResized={columnResizingReducer.getIsAnyColumnBeingResized()}
disableSelfContainment={!!props.disableSelfContainment}
>
<TableGrid
ref={tableRef as LegacyRef<HTMLTableElement>}
{...filterDataAttributes(props)}
columns={props.columns}
maxHeight={props.maxHeight}
disableSelfContainment={!!props.disableSelfContainment}
resizedTotalWidth={resizedTotalWidth}
>
<ColumnResizingContext.Provider value={columnResizingReducer}>
<Header>
<Row>
{props.columns.map((column) => (
<HeaderCell
key={column.key}
shouldWrap={props.wrapHeaderLabels}
isCondensed={props.isCondensed}
iconComponent={column.headerIcon}
onColumnResized={props.onColumnResized}
disableResizing={column.disableResizing}
horizontalCellAlignment={
column.align ? column.align : props.horizontalCellAlignment
}
disableHeaderStickiness={props.disableHeaderStickiness}
columnWidth={column.width}
/* Sorting Props */
onClick={props.onSortChange && props.onSortChange}
sortedBy={props.sortedBy}
columnKey={column.key}
isSortable={column.isSortable}
sortDirection={props.sortDirection}
>
{column.label}
</HeaderCell>
))}
</Row>
</Header>
<Body>
{props.rows.map((row, rowIndex) => (
<DataRow
{...props}
row={row}
key={row.id}
rowIndex={rowIndex}
shouldClipContent={
columnResizingReducer.getIsAnyColumnBeingResized() ||
hasTableBeenResized
}
shouldRenderBottomBorder={shouldRenderRowBottomBorder(
rowIndex,
props.rows.length,
props.footer
)}
/>
))}
</Body>
</ColumnResizingContext.Provider>
</TableGrid>
{props.footer && (
<Footer
data-testid="footer"
isCondensed={props.isCondensed}
horizontalCellAlignment={props.horizontalCellAlignment}
resizedTotalWidth={resizedTotalWidth}
>
{props.footer}
</Footer>
)}
</TableContainer>
);
};
DataTable.defaultProps = defaultProps;
DataTable.displayName = 'DataTable';
export default DataTable; | the_stack |
import * as coreHttp from "@azure/core-http";
/** List of job details. */
export interface JobDetailsList {
/** NOTE: This property will not be serialized. It can only be populated by the server. */
readonly value?: JobDetails[];
/** Total records count number. */
count?: number;
/**
* Link to the next page of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Job details. */
export interface JobDetails {
/** The job id. */
id?: string;
/** The job name. Is not required for the name to be unique and it's only used for display purposes. */
name?: string;
/** The blob container SAS uri, the container is used to host job data. */
containerUri: string;
/** The input blob SAS uri, if specified, it will override the default input blob in the container. */
inputDataUri?: string;
/** The format of the input data. */
inputDataFormat: string;
/** The input parameters for the job. JSON object used by the target solver. It is expected that the size of this object is small and only used to specify parameters for the execution target, not the input data. */
inputParams?: any;
/** The unique identifier for the provider. */
providerId: string;
/** The target identifier to run the job. */
target: string;
/** The job metadata. Metadata provides client the ability to store client-specific information */
metadata?: { [propertyName: string]: string };
/** The output blob SAS uri. When a job finishes successfully, results will be uploaded to this blob. */
outputDataUri?: string;
/** The format of the output data. */
outputDataFormat?: string;
/**
* The job status.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: JobStatus;
/**
* The creation time of the job.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly creationTime?: Date;
/**
* The time when the job began execution.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly beginExecutionTime?: Date;
/**
* The time when the job finished execution.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly endExecutionTime?: Date;
/**
* The time when a job was successfully cancelled.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly cancellationTime?: Date;
/**
* The error data for the job. This is expected only when Status 'Failed'.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly errorData?: ErrorData;
}
/** An error response from Azure. */
export interface ErrorData {
/** An identifier for the error. Codes are invariant and are intended to be consumed programmatically. */
code?: string;
/** A message describing the error, intended to be suitable for displaying in a user interface. */
message?: string;
}
/** Error information returned by the API */
export interface RestError {
/** An error response from Azure. */
error?: ErrorData;
}
/** Providers status. */
export interface ProviderStatusList {
/** NOTE: This property will not be serialized. It can only be populated by the server. */
readonly value?: ProviderStatus[];
/**
* Link to the next page of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Providers status. */
export interface ProviderStatus {
/**
* Provider id.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* Provider availability.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly currentAvailability?: ProviderAvailability;
/** NOTE: This property will not be serialized. It can only be populated by the server. */
readonly targets?: TargetStatus[];
}
/** Target status. */
export interface TargetStatus {
/**
* Target id.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* Target availability.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly currentAvailability?: TargetAvailability;
/**
* Average queue time in seconds.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly averageQueueTime?: number;
/**
* A page with detailed status of the provider.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly statusPage?: string;
}
/** Blob details. */
export interface BlobDetails {
/** The container name. */
containerName: string;
/** The blob name. */
blobName?: string;
}
/** Get SAS URL operation response. */
export interface SasUriResponse {
/** A URL with a SAS token to upload a blob for execution in the given workspace. */
sasUri?: string;
}
/** List of quotas. */
export interface QuotaList {
/** NOTE: This property will not be serialized. It can only be populated by the server. */
readonly value?: Quota[];
/**
* Link to the next page of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Quota information. */
export interface Quota {
/** The name of the dimension associated with the quota. */
dimension?: string;
/** The scope at which the quota is applied. */
scope?: DimensionScope;
/** The unique identifier for the provider. */
providerId?: string;
/** The amount of the usage that has been applied for the current period. */
utilization?: number;
/** The amount of the usage that has been reserved but not applied for the current period. */
holds?: number;
/** The maximum amount of usage allowed for the current period. */
limit?: number;
/** The time period in which the quota's underlying meter is accumulated. Based on calendar year. 'None' is used for concurrent quotas. */
period?: MeterPeriod;
}
/** Known values of {@link JobStatus} that the service accepts. */
export const enum KnownJobStatus {
Waiting = "Waiting",
Executing = "Executing",
Succeeded = "Succeeded",
Failed = "Failed",
Cancelled = "Cancelled"
}
/**
* Defines values for JobStatus. \
* {@link KnownJobStatus} can be used interchangeably with JobStatus,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **Waiting** \
* **Executing** \
* **Succeeded** \
* **Failed** \
* **Cancelled**
*/
export type JobStatus = string;
/** Known values of {@link ProviderAvailability} that the service accepts. */
export const enum KnownProviderAvailability {
Available = "Available",
Degraded = "Degraded",
Unavailable = "Unavailable"
}
/**
* Defines values for ProviderAvailability. \
* {@link KnownProviderAvailability} can be used interchangeably with ProviderAvailability,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **Available** \
* **Degraded** \
* **Unavailable**
*/
export type ProviderAvailability = string;
/** Known values of {@link TargetAvailability} that the service accepts. */
export const enum KnownTargetAvailability {
Available = "Available",
Degraded = "Degraded",
Unavailable = "Unavailable"
}
/**
* Defines values for TargetAvailability. \
* {@link KnownTargetAvailability} can be used interchangeably with TargetAvailability,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **Available** \
* **Degraded** \
* **Unavailable**
*/
export type TargetAvailability = string;
/** Known values of {@link DimensionScope} that the service accepts. */
export const enum KnownDimensionScope {
Workspace = "Workspace",
Subscription = "Subscription"
}
/**
* Defines values for DimensionScope. \
* {@link KnownDimensionScope} can be used interchangeably with DimensionScope,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **Workspace** \
* **Subscription**
*/
export type DimensionScope = string;
/** Known values of {@link MeterPeriod} that the service accepts. */
export const enum KnownMeterPeriod {
None = "None",
Monthly = "Monthly"
}
/**
* Defines values for MeterPeriod. \
* {@link KnownMeterPeriod} can be used interchangeably with MeterPeriod,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **None** \
* **Monthly**
*/
export type MeterPeriod = string;
/** Contains response data for the list operation. */
export type JobsListResponse = JobDetailsList & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: JobDetailsList;
};
};
/** Contains response data for the get operation. */
export type JobsGetResponse = JobDetails & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: JobDetails;
};
};
/** Contains response data for the create operation. */
export type JobsCreateResponse = JobDetails & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: JobDetails;
};
};
/** Contains response data for the listNext operation. */
export type JobsListNextResponse = JobDetailsList & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: JobDetailsList;
};
};
/** Contains response data for the getStatus operation. */
export type ProvidersGetStatusResponse = ProviderStatusList & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: ProviderStatusList;
};
};
/** Contains response data for the getStatusNext operation. */
export type ProvidersGetStatusNextResponse = ProviderStatusList & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: ProviderStatusList;
};
};
/** Contains response data for the sasUri operation. */
export type StorageSasUriResponse = SasUriResponse & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: SasUriResponse;
};
};
/** Contains response data for the list operation. */
export type QuotasListResponse = QuotaList & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: QuotaList;
};
};
/** Contains response data for the listNext operation. */
export type QuotasListNextResponse = QuotaList & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: QuotaList;
};
};
/** Optional parameters. */
export interface QuantumJobClientOptionalParams
extends coreHttp.ServiceClientOptions {
/** server parameter */
$host?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import { select } from 'd3-selection';
import { setTooltipAccess } from './accessibilityUtils';
import { formatStats } from './formatStats';
import { capitalized } from './calculation';
import { formatDataLabel } from './dataLabel';
import { formatDate } from './formatDate';
import { transition } from 'd3-transition';
const buildTooltipContent = ({
data,
tooltipLabel,
xAxis,
yAxis,
dataLabel,
layout,
ordinalAccessor,
valueAccessor,
xAccessor, // equivalent to joinNameAccessor / markerNameAccessor in map
yAccessor, // equivalent to joinAccessor / markerAccessor in map
groupAccessor, // equivalent to seriesAccessor in line, dumbbell, parallel
diffLabelDetails,
normalized,
chartType
}: {
data?: any;
tooltipLabel?: any;
xAxis?: any;
yAxis?: any;
dataLabel?: any;
layout?: any;
ordinalAccessor?: any;
valueAccessor?: any;
xAccessor?: any;
yAccessor?: any;
groupAccessor?: any;
diffLabelDetails?: any;
normalized?: any;
chartType?: any;
}) => {
// user assigned tooltipLabel
if (tooltipLabel && tooltipLabel.labelAccessor.length > 0) {
let labelStr = '';
tooltipLabel.labelAccessor.map((k, i) => {
const title =
tooltipLabel.labelTitle && tooltipLabel.labelTitle[i] !== '' ? tooltipLabel.labelTitle[i] + ': ' : '';
labelStr += `${title}<b>${
tooltipLabel.format && tooltipLabel.format[i]
? data[k] instanceof Date
? formatDate({
date: data[k],
format: tooltipLabel.format[i],
offsetTimezone: true
})
: normalized && tooltipLabel.format[i] === 'normalized' // only for stacked-bar value
? formatDataLabel(data, k, dataLabel.format, k === valueAccessor)
: !isNaN(parseFloat(data[k]))
? formatStats(data[k], tooltipLabel.format[i])
: data[k]
: data[k]
} </b><br/>`;
});
labelStr.replace(',', '');
return labelStr;
} else {
//default tooltip
let defaultLabel = '';
const firstTitle =
xAxis && yAxis
? (layout === 'horizontal' ? yAxis.label : xAxis.label) || xAccessor || ordinalAccessor
: ordinalAccessor;
const secondTitle =
xAxis && yAxis
? (layout === 'horizontal' ? xAxis.label : yAxis.label) || yAccessor || valueAccessor
: valueAccessor;
// bar, pie
if (chartType === 'bar') {
defaultLabel = `
<b>${groupAccessor ? data[groupAccessor] + '<br/>' : ''} </b>
${capitalized(firstTitle) + ': <b>' + data[ordinalAccessor]} </b><br/>
${capitalized(secondTitle) + ':'}
<b>${formatStats(data[valueAccessor], dataLabel.format)}</b>`;
}
// if we have normalized then we output percent and value
else if (chartType === 'pie') {
defaultLabel = `
${capitalized(firstTitle) + ': <b>' + data[ordinalAccessor]} </b><br/>
${
normalized
? capitalized(secondTitle) +
' (%): <b>' +
formatDataLabel(data, valueAccessor, '0[.][0]%', normalized) +
'</b><br/>'
: ''
}
${capitalized(secondTitle) + ': '}
<b>${formatStats(data[valueAccessor], dataLabel.format === 'normalized' ? '0[.][0]a' : dataLabel.format)}</b>
`;
}
// scatter-plot
else if (chartType === 'scatter') {
defaultLabel = `
<b>${groupAccessor ? data[groupAccessor] + '<br/>' : ''} </b>
${capitalized(firstTitle) + ':'}
<b>${formatStats(data[xAccessor], xAxis.format || '')} </b><br/>
${capitalized(secondTitle) + ':'}
<b>${formatStats(data[yAccessor], yAxis.format || '')}</b>`;
}
// line, parallel
else if (chartType === 'line' || chartType === 'parallel') {
defaultLabel = `
<b>${groupAccessor ? data[groupAccessor] + '<br/>' : ''}</b>
${capitalized(firstTitle) + ':'}
<b>${
data[ordinalAccessor] instanceof Date
? formatDate({
date: data[ordinalAccessor],
format: xAxis.format,
offsetTimezone: true
})
: data[ordinalAccessor]
} </b><br/>
${capitalized(secondTitle) + ':'}
<b>${formatStats(data[valueAccessor], dataLabel.format || '')}</b>`;
}
// stacked-bar, clustered-bar
else if (chartType === 'stacked' || chartType === 'clustered') {
defaultLabel = `
<b>${data[groupAccessor] + '<br/>'}</b>
${capitalized(firstTitle) + ':'}
<b>${data[ordinalAccessor]} </b><br/>
${
normalized
? capitalized(secondTitle) +
' (%): <b>' +
formatDataLabel(data, valueAccessor, '0[.][0]%', normalized) +
'</b><br/>'
: ''
}
${capitalized(secondTitle) + ': '}
<b>${formatStats(data[valueAccessor], dataLabel.format === 'normalized' ? '0[.][0]a' : dataLabel.format)}</b>
`;
}
// heat-map
else if (chartType === 'heat-map') {
defaultLabel = `
${capitalized(firstTitle) + ':'}
<b>${
data[xAccessor] instanceof Date
? formatDate({
date: data[xAccessor],
format: xAxis.format,
offsetTimezone: true
})
: data[xAccessor]
} </b><br/>
${capitalized(secondTitle) + ':'}
<b>${
data[yAccessor] instanceof Date
? formatDate({
date: data[yAccessor],
format: yAxis.format,
offsetTimezone: true
})
: data[yAccessor]
} </b><br/>
${capitalized(valueAccessor) + ':'}
<b>${formatStats(data[valueAccessor], dataLabel.format || '')}</b>`;
}
// circle-packing
else if (chartType === 'circle-packing') {
defaultLabel = `
<b>${capitalized(data[ordinalAccessor])} </b><br/>
${capitalized(groupAccessor) + ': <b>' + data[groupAccessor]} </b><br/>
${capitalized(valueAccessor) + ':'}
<b>${formatStats(data[valueAccessor], dataLabel.format || '')}</b>`;
}
// world-map
else if (chartType === 'world-map') {
defaultLabel = `
<b>${data[xAccessor]} (${data[yAccessor]}) </b><br/>
${valueAccessor}:
<b>${formatStats(data[valueAccessor], dataLabel.format || '')}</b>`;
}
// dumbbell
else if (chartType === 'dumbbell') {
if (data && data.key && data.values) {
defaultLabel =
`<b>
${
data.values[0][ordinalAccessor] instanceof Date
? formatDate({
date: data.values[0][ordinalAccessor],
format: xAxis.format,
offsetTimezone: true
})
: data.values[0][ordinalAccessor]
} </b><br/>` +
'Difference: ' +
`<b>${
dataLabel.format
? formatStats(data[diffLabelDetails.calculation], dataLabel.format)
: data[diffLabelDetails.calculation]
} <br/></b>` +
data.values[0][groupAccessor] +
': ' +
`<b>${
dataLabel.format
? formatStats(data.values[0][valueAccessor], dataLabel.format)
: data.values[0][valueAccessor]
} </b><br/>` +
data.values[1][groupAccessor] +
': ' +
`<b>${
dataLabel.format
? formatStats(data.values[1][valueAccessor], dataLabel.format)
: data.values[1][valueAccessor]
}</b>
`;
} else {
defaultLabel =
`<b>
${
data[ordinalAccessor] instanceof Date
? formatDate({
date: data[ordinalAccessor],
format: xAxis.format,
offsetTimezone: true
})
: data[ordinalAccessor]
} </b><br/>` +
data[groupAccessor] +
': ' +
`<b>${dataLabel.format ? formatStats(data[valueAccessor], dataLabel.format) : data[valueAccessor]}</b>
`;
}
}
// alluvial-diagram
else if (chartType === 'alluvial-diagram') {
defaultLabel = `
<b>${capitalized(data['source'][ordinalAccessor])}</b> to <b>${capitalized(
data['target'][ordinalAccessor]
)} </b><br/>
${capitalized(valueAccessor) + ':'}
<b>${dataLabel && dataLabel.format ? formatStats(data['value'], dataLabel.format) : data['value']}</b>`;
}
return defaultLabel;
}
};
export const overrideTitleTooltip = (uniqueID, toRemove) => {
const paddingIdBegin = 'visa-viz-padding-container-g-';
const paddingG = select(`#${paddingIdBegin}${uniqueID}`);
if (toRemove) {
if (paddingG.select('title').size() === 0) {
paddingG.append('title').text('');
}
} else {
paddingG.select('title').remove();
}
};
export const initTooltipStyle = root => {
root
.style('position', 'absolute')
.style('padding', '0.5rem')
.style('opacity', 0)
.style('background-color', '#ffffff')
.style('font-size', '14px')
.style('font-weight', '400')
.style('color', '#222222')
.style('border', '1px solid #565656')
.style('border-radius', '3px')
.style('pointer-events', 'none')
.style('min-width', '80px')
.style('max-width', '300px');
root.append('p').style('margin', 0);
};
export const drawTooltip = ({
root,
data,
event,
isToShow,
tooltipLabel,
xAxis,
yAxis,
dataLabel,
layout,
ordinalAccessor,
valueAccessor,
xAccessor, // equivalent to joinNameAccessor / markerNameAccessor in map
yAccessor, // equivalent to joinAccessor / markerAccessor in map
groupAccessor, // equivalent to seriesAccessor in line, dumbbell, parallel
diffLabelDetails,
normalized,
chartType
}: {
root?: any;
data?: any;
event?: any;
isToShow?: any;
tooltipLabel?: any;
xAxis?: any;
yAxis?: any;
dataLabel?: any;
layout?: any;
ordinalAccessor?: any;
valueAccessor?: any;
xAccessor?: any;
yAccessor?: any;
groupAccessor?: any;
diffLabelDetails?: any;
normalized?: any;
chartType?: any;
}) => {
const toShow = () => {
const positions = [event.pageX, event.pageY];
const tooltipContent = buildTooltipContent({
data,
tooltipLabel,
xAxis,
yAxis,
dataLabel,
layout,
ordinalAccessor,
valueAccessor,
xAccessor, // equivalent to joinNameAccessor / markerNameAccessor in map
yAccessor, // equivalent to joinAccessor / markerAccessor in map
groupAccessor, // equivalent to seriesAccessor in line, dumbbell, parallel
diffLabelDetails,
normalized,
chartType
});
// get bounds of parent (e.g., placement of chart container)
const parentBounds = root.node().parentElement.getBoundingClientRect();
// place tooltip on top left temporary to populate and not have wrap
root.style('left', '0px').style('top', '0px');
// populate tooltip so we can get its bounds as well
root.select('p').html(tooltipContent);
// now we get bounds for height/width/top/left after populating content
const bounds = root.node().getBoundingClientRect();
// if the page has been scrolled we need to account for that
const adjLeft = (document.body.scrollLeft || 0) + (document.documentElement.scrollLeft || 0);
const adjLeftFlip = parentBounds.width / 2 - (positions[0] - bounds.left - adjLeft) < 0 ? bounds.width : 0;
const adjTop = (document.body.scrollTop || 0) + (document.documentElement.scrollTop || 0);
// place tooltip and then fade in
// left = mouse position - adjust left for parent container location (bounds.left) - adjust for scroll - adjust to left if on right half of graph
// right = mouse position - adjust up for parent container location (bounds.right) - adjust for height of tooltip - adjust for scroll
root
.style('left', `${positions[0] - bounds.left - adjLeft - adjLeftFlip}px`)
.style('top', `${positions[1] - bounds.top - bounds.height - adjTop}px`)
.transition(transition().duration(200))
.style('opacity', 1);
};
const toHide = () => {
root.transition(transition().duration(500)).style('opacity', 0);
};
if (root) {
isToShow ? toShow() : toHide();
setTooltipAccess(root.node());
}
}; | the_stack |
const branchingFactor = 32;
const branchBits = 5;
const mask = 31;
interface Setoid {
"fantasy-land/equals"(b: any): boolean;
}
function isSetoid(a: any): a is Setoid {
return a && typeof a["fantasy-land/equals"] === "function";
}
function elementEquals(a: any, b: any): boolean {
if (a === b) {
return true;
} else if (isSetoid(a)) {
return a["fantasy-land/equals"](b);
} else {
return false;
}
}
function createPath(depth: number, value: any): any {
let current = value;
for (let i = 0; i < depth; ++i) {
current = new Node(undefined, [current]);
}
return current;
}
// Array helper functions
function copyArray(source: any[]): any[] {
const array = [];
for (let i = 0; i < source.length; ++i) {
array[i] = source[i];
}
return array;
}
function pushElements<A>(
source: A[],
target: A[],
offset: number,
amount: number
): void {
for (let i = offset; i < offset + amount; ++i) {
target.push(source[i]);
}
}
function copyIndices(
source: any[],
sourceStart: number,
target: any[],
targetStart: number,
length: number
): void {
for (let i = 0; i < length; ++i) {
target[targetStart + i] = source[sourceStart + i];
}
}
function arrayPrepend<A>(value: A, array: A[]): A[] {
const newLength = array.length + 1;
const result = new Array(newLength);
result[0] = value;
for (let i = 1; i < newLength; ++i) {
result[i] = array[i - 1];
}
return result;
}
/**
* Create a reverse _copy_ of an array.
*/
function reverseArray<A>(array: A[]): A[] {
return array.slice().reverse();
}
function arrayFirst<A>(array: A[]): A {
return array[0];
}
function arrayLast<A>(array: A[]): A {
return array[array.length - 1];
}
const pathResult = { path: 0, index: 0, updatedOffset: 0 };
type PathResult = typeof pathResult;
function getPath(
index: number,
offset: number,
depth: number,
sizes: Sizes
): PathResult {
if (sizes === undefined && offset !== 0) {
pathResult.updatedOffset = 0;
index = handleOffset(depth, offset, index);
}
let path = (index >> (depth * branchBits)) & mask;
if (sizes !== undefined) {
while (sizes[path] <= index) {
path++;
}
const traversed = path === 0 ? 0 : sizes[path - 1];
index -= traversed;
pathResult.updatedOffset = offset;
}
pathResult.path = path;
pathResult.index = index;
return pathResult;
}
function updateNode(
node: Node,
depth: number,
index: number,
offset: number,
value: any
): Node {
const { path, index: newIndex, updatedOffset } = getPath(
index,
offset,
depth,
node.sizes
);
const array = copyArray(node.array);
array[path] =
depth > 0
? updateNode(array[path], depth - 1, newIndex, updatedOffset, value)
: value;
return new Node(node.sizes, array);
}
export type Sizes = number[] | undefined;
/** @private */
export class Node {
constructor(public sizes: Sizes, public array: any[]) {}
}
function cloneNode({ sizes, array }: Node): Node {
return new Node(
sizes === undefined ? undefined : copyArray(sizes),
copyArray(array)
);
}
// This array should not be mutated. Thus a dummy element is placed in
// it. Thus the affix will not be owned and thus not mutated.
const emptyAffix: any[] = [0];
// We store a bit field in list. From right to left, the first five
// bits are suffix length, the next five are prefix length and the
// rest is depth. The functions below are for working with the bits in
// a sane way.
const affixBits = 6;
const affixMask = 0b111111;
function getSuffixSize(l: List<any>): number {
return l.bits & affixMask;
}
function getPrefixSize(l: List<any>): number {
return (l.bits >> affixBits) & affixMask;
}
function getDepth(l: List<any>): number {
return l.bits >> (affixBits * 2);
}
function setPrefix(size: number, bits: number): number {
return (size << affixBits) | (bits & ~(affixMask << affixBits));
}
function setSuffix(size: number, bits: number): number {
return size | (bits & ~affixMask);
}
function setDepth(depth: number, bits: number): number {
return (
(depth << (affixBits * 2)) | (bits & (affixMask | (affixMask << affixBits)))
);
}
function incrementPrefix(bits: number): number {
return bits + (1 << affixBits);
}
function incrementSuffix(bits: number): number {
return bits + 1;
}
function incrementDepth(bits: number): number {
return bits + (1 << (affixBits * 2));
}
function decrementDepth(bits: number): number {
return bits - (1 << (affixBits * 2));
}
/*
* Invariants that any list `l` should satisfy
*
* 1. If `l.root !== undefined` then `getSuffixSize(l) !== 0` and
* `getPrefixSize(l) !== 0`. The invariant ensures that `first` and
* `last` never have to look in the root and that they therefore
* take O(1) time.
* 2. If a tree or sub-tree does not have a size-table then all leaf
* nodes in the tree are of size 32.
*/
/**
* Represents a list of elements.
*/
export class List<A> implements Iterable<A> {
constructor(
/** @private */
readonly bits: number,
/** @private */
readonly offset: number,
/** The number of elements in the list. */
readonly length: number,
/** @private */
readonly prefix: A[],
/** @private */
readonly root: Node | undefined,
/** @private */
readonly suffix: A[]
) {}
[Symbol.iterator](): Iterator<A> {
return new ForwardListIterator(this);
}
toJSON(): A[] {
return toArray(this);
}
}
type MutableList<A> = { -readonly [K in keyof List<A>]: List<A>[K] } & {
[Symbol.iterator]: () => Iterator<A>;
// This property doesn't exist at run-time. It exists to prevent a
// MutableList from being assignable to a List.
"@@mutable": true;
};
function cloneList<A>(l: List<A>): MutableList<A> {
return new List(
l.bits,
l.offset,
l.length,
l.prefix,
l.root,
l.suffix
) as any;
}
abstract class ListIterator<A> implements Iterator<A> {
stack: any[][];
indices: number[];
idx: number;
prefixSize: number;
middleSize: number;
result: IteratorResult<A> = { done: false, value: undefined as any };
constructor(protected l: List<A>, direction: 1 | -1) {
this.idx = direction === 1 ? -1 : l.length;
this.prefixSize = getPrefixSize(l);
this.middleSize = l.length - getSuffixSize(l);
if (l.root !== undefined) {
const depth = getDepth(l);
this.stack = new Array(depth + 1);
this.indices = new Array(depth + 1);
let currentNode = l.root.array;
for (let i = depth; 0 <= i; --i) {
this.stack[i] = currentNode;
const idx = direction === 1 ? 0 : currentNode.length - 1;
this.indices[i] = idx;
currentNode = currentNode[idx].array;
}
this.indices[0] -= direction;
}
}
abstract next(): IteratorResult<A>;
}
class ForwardListIterator<A> extends ListIterator<A> {
constructor(l: List<A>) {
super(l, 1);
}
nextInTree(): void {
for (var i = 0; ++this.indices[i] === this.stack[i].length; ++i) {
this.indices[i] = 0;
}
for (; 0 < i; --i) {
this.stack[i - 1] = this.stack[i][this.indices[i]].array;
}
}
next(): IteratorResult<A> {
let newVal;
const idx = ++this.idx;
if (idx < this.prefixSize) {
newVal = this.l.prefix[this.prefixSize - idx - 1];
} else if (idx < this.middleSize) {
this.nextInTree();
newVal = this.stack[0][this.indices[0]];
} else if (idx < this.l.length) {
newVal = this.l.suffix[idx - this.middleSize];
} else {
this.result.done = true;
}
this.result.value = newVal;
return this.result;
}
}
class BackwardsListIterator<A> extends ListIterator<A> {
constructor(l: List<A>) {
super(l, -1);
}
prevInTree(): void {
for (var i = 0; this.indices[i] === 0; ++i) {}
--this.indices[i];
for (; 0 < i; --i) {
const n = this.stack[i][this.indices[i]].array;
this.stack[i - 1] = n;
this.indices[i - 1] = n.length - 1;
}
}
next(): IteratorResult<A> {
let newVal;
const idx = --this.idx;
if (this.middleSize <= idx) {
newVal = this.l.suffix[idx - this.middleSize];
} else if (this.prefixSize <= idx) {
this.prevInTree();
newVal = this.stack[0][this.indices[0]];
} else if (0 <= idx) {
newVal = this.l.prefix[this.prefixSize - idx - 1];
} else {
this.result.done = true;
}
this.result.value = newVal;
return this.result;
}
}
/**
* Returns an iterable that iterates backwards over the given list.
*
* @complexity O(1)
* @category Folds
* @example
* const emptyList = empty(); //=> list()
* const l = list(0, 1, 2, 3, 4)
* for (const n of backwards(l)) {
* if (l < 2) {
* break;
* }
* console.log(l);
* }
* // => logs 4, 3, and then 2
*/
export function backwards<A>(l: List<A>): Iterable<A> {
return {
[Symbol.iterator](): Iterator<A> {
return new BackwardsListIterator(l);
}
};
}
function emptyPushable<A>(): MutableList<A> {
return new List(0, 0, 0, [], undefined, []) as any;
}
/** Appends the value to the list by _mutating_ the list and its content. */
function push<A>(value: A, l: MutableList<A>): MutableList<A> {
const suffixSize = getSuffixSize(l);
if (l.length === 0) {
l.bits = setPrefix(1, l.bits);
l.prefix = [value];
} else if (suffixSize < 32) {
l.bits = incrementSuffix(l.bits);
l.suffix.push(value);
} else if (l.root === undefined) {
l.root = new Node(undefined, l.suffix);
l.suffix = [value];
l.bits = setSuffix(1, l.bits);
} else {
const newNode = new Node(undefined, l.suffix);
const index = l.length - 1 - 32 + 1;
let current = l.root!;
let depth = getDepth(l);
l.suffix = [value];
l.bits = setSuffix(1, l.bits);
if (index - 1 < branchingFactor ** (depth + 1)) {
for (; depth >= 0; --depth) {
const path = (index >> (depth * branchBits)) & mask;
if (path < current.array.length) {
current = current.array[path];
} else {
current.array.push(createPath(depth - 1, newNode));
break;
}
}
} else {
l.bits = incrementDepth(l.bits);
l.root = new Node(undefined, [l.root, createPath(depth, newNode)]);
}
}
l.length++;
return l;
}
/**
* Creates a list of the given elements.
*
* @complexity O(n)
* @category Constructors
* @example
* list(0, 1, 2, 3); //=> list(0, 1, 2, 3)
*/
export function list<A>(...elements: A[]): List<A> {
let l = emptyPushable<A>();
for (const element of elements) {
push(element, l);
}
return l;
}
/**
* Creates an empty list.
*
* @complexity O(1)
* @category Constructors
* @example
* const emptyList = empty(); //=> list()
*/
export function empty<A = any>(): List<A> {
return new List(0, 0, 0, emptyAffix, undefined, emptyAffix);
}
/**
* Takes a single arguments and returns a singleton list that contains it.
*
* @complexity O(1)
* @category Constructors
* @example
* of("foo"); //=> list("foo")
*/
export function of<A>(a: A): List<A> {
return list(a);
}
/**
* Takes two arguments and returns a list that contains them.
*
* @complexity O(1)
* @category Constructors
* @example
* pair("foo", "bar"); //=> list("foo", "bar")
*/
export function pair<A>(first: A, second: A): List<A> {
return new List(2, 0, 2, emptyAffix, undefined, [first, second]);
}
/**
* Converts an array, an array-like, or an iterable into a list.
*
* @complexity O(n)
* @category Constructors
* @example
* from([0, 1, 2, 3, 4]); //=> list(0, 1, 2, 3, 4)
* from(new Set([0, 1, 2, 3]); //=> list(0, 1, 2, 3)
* from("hello"); //=> list("h", "e", "l", "l", "o"));
*/
export function from<A>(sequence: A[] | ArrayLike<A> | Iterable<A>): List<A>;
export function from<A>(sequence: any): List<A> {
let l = emptyPushable<A>();
if (sequence.length > 0 && (sequence[0] !== undefined || 0 in sequence)) {
for (let i = 0; i < sequence.length; ++i) {
push(sequence[i], l);
}
} else if (Symbol.iterator in sequence) {
const iterator = sequence[Symbol.iterator]();
let cur;
// tslint:disable-next-line:no-conditional-assignment
while (!(cur = iterator.next()).done) {
push(cur.value, l);
}
}
return l;
}
/**
* Returns a list of numbers between an inclusive lower bound and an exclusive upper bound.
*
* @complexity O(n)
* @category Constructors
* @example
* range(3, 8); //=> list(3, 4, 5, 6, 7)
*/
export function range(start: number, end: number): List<number> {
let list = emptyPushable<number>();
for (let i = start; i < end; ++i) {
push(i, list);
}
return list;
}
/**
* Returns a list of a given length that contains the specified value
* in all positions.
*
* @complexity O(n)
* @category Constructors
* @example
* repeat(1, 7); //=> list(1, 1, 1, 1, 1, 1, 1)
* repeat("foo", 3); //=> list("foo", "foo", "foo")
*/
export function repeat<A>(value: A, times: number): List<A> {
let l = emptyPushable<A>();
while (--times >= 0) {
push(value, l);
}
return l;
}
/**
* Generates a new list by calling a function with the current index
* `n` times.
*
* @complexity O(n)
* @category Constructors
* @example
* times(i => i, 5); //=> list(0, 1, 2, 3, 4)
* times(i => i * 2 + 1, 4); //=> list(1, 3, 5, 7)
* times(() => Math.round(Math.random() * 10), 5); //=> list(9, 1, 4, 3, 4)
*/
export function times<A>(func: (index: number) => A, times: number): List<A> {
let l = emptyPushable<A>();
for (let i = 0; i < times; i++) {
push(func(i), l);
}
return l;
}
function nodeNthDense(node: Node, depth: number, index: number): any {
let current = node;
for (; depth >= 0; --depth) {
current = current.array[(index >> (depth * branchBits)) & mask];
}
return current;
}
function handleOffset(depth: number, offset: number, index: number): number {
index += offset;
for (; depth >= 0; --depth) {
index = index - (offset & (mask << (depth * branchBits)));
if (((index >> (depth * branchBits)) & mask) !== 0) {
break;
}
}
return index;
}
function nodeNth(
node: Node,
depth: number,
offset: number,
index: number
): any {
let path;
let current = node;
while (current.sizes !== undefined) {
path = (index >> (depth * branchBits)) & mask;
while (current.sizes[path] <= index) {
path++;
}
if (path !== 0) {
index -= current.sizes[path - 1];
offset = 0; // Offset is discarded if the left spine isn't traversed
}
depth--;
current = current.array[path];
}
return nodeNthDense(
current,
depth,
offset === 0 ? index : handleOffset(depth, offset, index)
);
}
/**
* Gets the nth element of the list. If `n` is out of bounds
* `undefined` is returned.
*
* @complexity O(log(n))
* @category Folds
* @example
* const l = list(0, 1, 2, 3, 4);
* nth(2, l); //=> 2
*/
export function nth<A>(index: number, l: List<A>): A | undefined {
if (index < 0 || l.length <= index) {
return undefined;
}
const prefixSize = getPrefixSize(l);
const suffixSize = getSuffixSize(l);
if (index < prefixSize) {
return l.prefix[prefixSize - index - 1];
} else if (index >= l.length - suffixSize) {
return l.suffix[index - (l.length - suffixSize)];
}
const { offset } = l;
const depth = getDepth(l);
return l.root!.sizes === undefined
? nodeNthDense(
l.root!,
depth,
offset === 0
? index - prefixSize
: handleOffset(depth, offset, index - prefixSize)
)
: nodeNth(l.root!, depth, offset, index - prefixSize);
}
function setSizes(node: Node, height: number): Node {
let sum = 0;
const sizeTable = [];
for (let i = 0; i < node.array.length; ++i) {
sum += sizeOfSubtree(node.array[i], height - 1);
sizeTable[i] = sum;
}
node.sizes = sizeTable;
return node;
}
/**
* Returns the number of elements stored in the node.
*/
function sizeOfSubtree(node: Node, height: number): number {
if (height !== 0) {
if (node.sizes !== undefined) {
return arrayLast(node.sizes);
} else {
// the node is leftwise dense so all all but the last child are full
const lastSize = sizeOfSubtree(arrayLast(node.array), height - 1);
return ((node.array.length - 1) << (height * branchBits)) + lastSize;
}
} else {
return node.array.length;
}
}
// prepend & append
function affixPush<A>(a: A, array: A[], length: number): A[] {
if (array.length === length) {
array.push(a);
return array;
} else {
const newArray: A[] = [];
copyIndices(array, 0, newArray, 0, length);
newArray.push(a);
return newArray;
}
}
/**
* Prepends an element to the front of a list and returns the new list.
*
* @complexity O(1)
* @category Transformers
* @example
* prepend(0, list(1, 2, 3)); //=> list(0, 1, 2, 3)
* prepend("h", list("e", "l", "l", "o")); //=> list("h", "e", "l", "l", "o")
*/
export function prepend<A>(value: A, l: List<A>): List<A> {
const prefixSize = getPrefixSize(l);
if (prefixSize < 32) {
return new List<A>(
incrementPrefix(l.bits),
l.offset,
l.length + 1,
affixPush(value, l.prefix, prefixSize),
l.root,
l.suffix
);
} else {
const newList = cloneList(l);
prependNodeToTree(newList, reverseArray(l.prefix));
const newPrefix = [value];
newList.prefix = newPrefix;
newList.length++;
newList.bits = setPrefix(1, newList.bits);
return newList;
}
}
/**
* Traverses down the left edge of the tree and copies k nodes.
* Returns the last copied node.
* @param l
* @param k The number of nodes to copy. Should always be at least 1.
*/
function copyLeft(l: MutableList<any>, k: number): Node {
let currentNode = cloneNode(l.root!); // copy root
l.root = currentNode; // install copy of root
for (let i = 1; i < k; ++i) {
const index = 0; // go left
if (currentNode.sizes !== undefined) {
for (let i = 0; i < currentNode.sizes.length; ++i) {
currentNode.sizes[i] += 32;
}
}
const newNode = cloneNode(currentNode.array[index]);
// Install the copied node
currentNode.array[index] = newNode;
currentNode = newNode;
}
return currentNode;
}
/**
* Prepends an element to a node
*/
function nodePrepend(value: any, size: number, node: Node): Node {
const array = arrayPrepend(value, node.array);
let sizes = undefined;
if (node.sizes !== undefined) {
sizes = new Array(node.sizes.length + 1);
sizes[0] = size;
for (let i = 0; i < node.sizes.length; ++i) {
sizes[i + 1] = node.sizes[i] + size;
}
}
return new Node(sizes, array);
}
/**
* Prepends a node to a tree. Either by shifting the nodes in the root
* left or by increasing the height
*/
function prependTopTree<A>(
l: MutableList<A>,
depth: number,
node: Node
): number {
let newOffset;
if (l.root!.array.length < branchingFactor) {
// There is space in the root, there is never a size table in this
// case
newOffset = 32 ** depth - 32;
l.root = new Node(
undefined,
arrayPrepend(createPath(depth - 1, node), l.root!.array)
);
} else {
// We need to create a new root
l.bits = incrementDepth(l.bits);
const sizes =
l.root!.sizes === undefined
? undefined
: [32, arrayLast(l.root!.sizes!) + 32];
newOffset = depth === 0 ? 0 : 32 ** (depth + 1) - 32;
l.root = new Node(sizes, [createPath(depth, node), l.root]);
}
return newOffset;
}
/**
* Takes a list and a node tail. It then prepends the node to the tree
* of the list.
* @param l The subject for prepending. `l` will be mutated. Nodes in
* the tree will _not_ be mutated.
* @param node The node that should be prepended to the tree.
*/
function prependNodeToTree<A>(l: MutableList<A>, array: A[]): List<A> {
if (l.root === undefined) {
if (getSuffixSize(l) === 0) {
// ensure invariant 1
l.bits = setSuffix(array.length, l.bits);
l.suffix = array;
} else {
l.root = new Node(undefined, array);
}
return l;
} else {
const node = new Node(undefined, array);
const depth = getDepth(l);
let newOffset = 0;
if (l.root.sizes === undefined) {
if (l.offset !== 0) {
newOffset = l.offset - branchingFactor;
l.root = prependDense(l.root, depth, l.offset, node);
} else {
// in this case we can be sure that the is not room in the tree
// for the new node
newOffset = prependTopTree(l, depth, node);
}
} else {
// represents how many nodes _with size-tables_ that we should copy.
let copyableCount = 0;
// go down while there is size tables
let nodesTraversed = 0;
let currentNode = l.root;
while (currentNode.sizes !== undefined && nodesTraversed < depth) {
++nodesTraversed;
if (currentNode.array.length < 32) {
// there is room if offset is > 0 or if the first node does not
// contain as many nodes as it possibly can
copyableCount = nodesTraversed;
}
currentNode = currentNode.array[0];
}
if (l.offset !== 0) {
const copiedNode = copyLeft(l, nodesTraversed);
for (let i = 0; i < copiedNode.sizes!.length; ++i) {
copiedNode.sizes![i] += branchingFactor;
}
copiedNode.array[0] = prependDense(
copiedNode.array[0],
depth - nodesTraversed,
l.offset,
node
);
l.offset = l.offset - branchingFactor;
return l;
} else {
if (copyableCount === 0) {
l.offset = prependTopTree(l, depth, node);
} else {
let parent: Node | undefined;
let prependableNode: Node;
// Copy the part of the path with size tables
if (copyableCount > 1) {
parent = copyLeft(l, copyableCount - 1);
prependableNode = parent.array[0];
} else {
parent = undefined;
prependableNode = l.root!;
}
const path = createPath(depth - copyableCount, node);
// add offset
l.offset = 32 ** (depth - copyableCount + 1) - 32;
const prepended = nodePrepend(path, 32, prependableNode);
if (parent === undefined) {
l.root = prepended;
} else {
parent.array[0] = prepended;
}
}
return l;
}
}
l.offset = newOffset;
return l;
}
}
/**
* Prepends a node to a dense tree. The given `offset` is never zero.
*/
function prependDense(
node: Node,
depth: number,
offset: number,
value: Node
): Node {
// We're indexing down `offset - 1`. At each step `path` is either 0 or -1.
const curOffset = (offset >> (depth * branchBits)) & mask;
const path = (((offset - 1) >> (depth * branchBits)) & mask) - curOffset;
if (path < 0) {
return new Node(
undefined,
arrayPrepend(createPath(depth - 1, value), node.array)
);
} else {
const array = copyArray(node.array);
array[0] = prependDense(array[0], depth - 1, offset, value);
return new Node(undefined, array);
}
}
/**
* Appends an element to the end of a list and returns the new list.
*
* @complexity O(n)
* @category Transformers
* @example
* append(3, list(0, 1, 2)); //=> list(0, 1, 2, 3)
*/
export function append<A>(value: A, l: List<A>): List<A> {
const suffixSize = getSuffixSize(l);
if (suffixSize < 32) {
return new List(
incrementSuffix(l.bits),
l.offset,
l.length + 1,
l.prefix,
l.root,
affixPush(value, l.suffix, suffixSize)
);
}
const newSuffix = [value];
const newList = cloneList(l);
appendNodeToTree(newList, l.suffix);
newList.suffix = newSuffix;
newList.length++;
newList.bits = setSuffix(1, newList.bits);
return newList;
}
/**
* Gets the length of a list.
*
* @complexity `O(1)`
* @category Folds
* @example
* length(list(0, 1, 2, 3)); //=> 4
*/
export function length(l: List<any>): number {
return l.length;
}
/**
* Returns the first element of the list. If the list is empty the
* function returns undefined.
*
* @complexity O(1)
* @category Folds
* @example
* first(list(0, 1, 2, 3)); //=> 0
* first(list()); //=> undefined
*/
export function first<A>(l: List<A>): A | undefined {
const prefixSize = getPrefixSize(l);
return prefixSize !== 0
? l.prefix[prefixSize - 1]
: l.length !== 0
? l.suffix[0]
: undefined;
}
/**
* Alias for [`first`](#first).
*
* @category Folds
*/
export const head = first;
/**
* Returns the last element of the list. If the list is empty the
* function returns `undefined`.
*
* @complexity O(1)
* @category Folds
* @example
* last(list(0, 1, 2, 3)); //=> 3
* last(list()); //=> undefined
*/
export function last<A>(l: List<A>): A | undefined {
const suffixSize = getSuffixSize(l);
return suffixSize !== 0
? l.suffix[suffixSize - 1]
: l.length !== 0
? l.prefix[0]
: undefined;
}
// map
function mapArray<A, B>(f: (a: A) => B, array: A[]): B[] {
const result = new Array(array.length);
for (let i = 0; i < array.length; ++i) {
result[i] = f(array[i]);
}
return result;
}
function mapNode<A, B>(f: (a: A) => B, node: Node, depth: number): Node {
if (depth !== 0) {
const { array } = node;
const result = new Array(array.length);
for (let i = 0; i < array.length; ++i) {
result[i] = mapNode(f, array[i], depth - 1);
}
return new Node(node.sizes, result);
} else {
return new Node(undefined, mapArray(f, node.array));
}
}
function mapPrefix<A, B>(f: (a: A) => B, prefix: A[], length: number): B[] {
const newPrefix = new Array(length);
for (let i = length - 1; 0 <= i; --i) {
newPrefix[i] = f(prefix[i]);
}
return newPrefix;
}
function mapAffix<A, B>(f: (a: A) => B, suffix: A[], length: number): B[] {
const newSuffix = new Array(length);
for (let i = 0; i < length; ++i) {
newSuffix[i] = f(suffix[i]);
}
return newSuffix;
}
/**
* Applies a function to each element in the given list and returns a
* new list of the values that the function return.
*
* @complexity O(n)
* @category Transformers
* @example
* map(n => n * n, list(0, 1, 2, 3, 4)); //=> list(0, 1, 4, 9, 16)
*/
export function map<A, B>(f: (a: A) => B, l: List<A>): List<B> {
return new List(
l.bits,
l.offset,
l.length,
mapPrefix(f, l.prefix, getPrefixSize(l)),
l.root === undefined ? undefined : mapNode(f, l.root, getDepth(l)),
mapAffix(f, l.suffix, getSuffixSize(l))
);
}
/**
* Extracts the specified property from each object in the list.
*
* @category Transformers
* @example
*
* const l = list(
* { foo: 0, bar: "a" },
* { foo: 1, bar: "b" },
* { foo: 2, bar: "c" }
* );
* pluck("foo", l); //=> list(0, 1, 2)
* pluck("bar", l); //=> list("a", "b", "c")
*/
export function pluck<A, K extends keyof A>(key: K, l: List<A>): List<A[K]> {
return map(a => a[key], l);
}
// fold
function foldlSuffix<A, B>(
f: (acc: B, value: A) => B,
acc: B,
array: A[],
length: number
): B {
for (let i = 0; i < length; ++i) {
acc = f(acc, array[i]);
}
return acc;
}
function foldlPrefix<A, B>(
f: (acc: B, value: A) => B,
acc: B,
array: A[],
length: number
): B {
for (let i = length - 1; 0 <= i; --i) {
acc = f(acc, array[i]);
}
return acc;
}
function foldlNode<A, B>(
f: (acc: B, value: A) => B,
acc: B,
node: Node,
depth: number
): B {
const { array } = node;
if (depth === 0) {
return foldlSuffix(f, acc, array, array.length);
}
for (let i = 0; i < array.length; ++i) {
acc = foldlNode(f, acc, array[i], depth - 1);
}
return acc;
}
/**
* Folds a function over a list. Left-associative.
*
* @category Folds
* @example
* foldl((n, m) => n - m, 1, list(2, 3, 4, 5));
* //=> (((1 - 2) - 3) - 4) - 5 === -13
*/
export function foldl<A, B>(
f: (acc: B, value: A) => B,
initial: B,
l: List<A>
): B {
const suffixSize = getSuffixSize(l);
const prefixSize = getPrefixSize(l);
initial = foldlPrefix(f, initial, l.prefix, prefixSize);
if (l.root !== undefined) {
initial = foldlNode(f, initial, l.root, getDepth(l));
}
return foldlSuffix(f, initial, l.suffix, suffixSize);
}
/**
* Alias for [`foldl`](#foldl).
*
* @category Folds
*/
export const reduce = foldl;
export interface Of {
"fantasy-land/of"<B>(a: B): Applicative<B>;
}
export interface Applicative<A> {
"fantasy-land/map"<B>(f: (a: A) => B): Applicative<B>;
"fantasy-land/ap"<B>(fa: Applicative<(a: A) => B>): Applicative<B>;
}
/**
* Map each element of list to an applicative, evaluate these
* applicatives from left to right, and collect the results.
*
* This works with Fantasy Land
* [applicatives](https://github.com/fantasyland/fantasy-land#applicative).
*
* @category Folds
* @example
* const l = list(1, 3, 5, 4, 2);
* L.scan((n, m) => n + m, 0, l); //=> list(0, 1, 4, 9, 13, 15));
* L.scan((s, m) => s + m.toString(), "", l); //=> list("", "1", "13", "135", "1354", "13542")
*/
export function traverse<A, B>(
of: Of,
f: (a: A) => Applicative<B>,
l: List<A>
): any {
return foldr(
(a, fl) =>
fl["fantasy-land/ap"](
f(a)["fantasy-land/map"](a => (l: List<any>) => prepend(a, l))
),
of["fantasy-land/of"](empty()),
l
);
}
/**
* Evaluate each applicative in the list from left to right, and and
* collect the results.
*
* @complexity O(n)
* @category Folds
* @example
* L.sequence(Maybe, list(just(1), just(2), just(3))); //=> just(list(1, 2, 3))
* L.sequence(Maybe, list(just(1), just(2), nothing())); //=> nothing
*/
export function sequence<A>(ofObj: Of, l: List<Applicative<A>>): any {
return traverse(ofObj, a => a, l);
}
/**
* Folds a function over a list from left to right while collecting
* all the intermediate steps in a resulting list.
*
* @category Transformers
* @example
* const l = list(1, 3, 5, 4, 2);
* L.scan((n, m) => n + m, 0, l); //=> list(0, 1, 4, 9, 13, 15));
* L.scan((s, m) => s + m.toString(), "", l); //=> list("", "1", "13", "135", "1354", "13542")
*/
export function scan<A, B>(
f: (acc: B, value: A) => B,
initial: B,
l: List<A>
): List<B> {
return foldl(
(l2, a) => push(f(last(l2)!, a), l2),
push(initial, emptyPushable<B>()),
l
);
}
/**
* Invokes a given callback for each element in the list from left to
* right. Returns `undefined`.
*
* This function is very similar to map. It should be used instead of
* `map` when the mapping function has side-effects. Whereas `map`
* constructs a new list `forEach` merely returns `undefined`. This
* makes `forEach` faster when the new list is unneeded.
*
* @complexity O(n)
* @category Folds
* @example
* const l = list(0, 1, 2);
* forEach(element => console.log(element)); // Prints 0, then 1, and then 2
*/
export function forEach<A>(callback: (a: A) => void, l: List<A>): void {
foldl((_, element) => callback(element), undefined as void, l);
}
/**
* Returns a new list that only contains the elements of the original
* list for which the predicate returns `true`.
*
* @complexity O(n)
* @category Transformers
* @example
* filter(isEven, list(0, 1, 2, 3, 4, 5, 6)); //=> list(0, 2, 4, 6)
*/
export function filter<A, B extends A>(
predicate: (a: A) => a is B,
l: List<A>
): List<B>;
export function filter<A>(predicate: (a: A) => boolean, l: List<A>): List<A>;
export function filter<A>(predicate: (a: A) => boolean, l: List<A>): List<A> {
return foldl(
(acc, a) => (predicate(a) ? push(a, acc) : acc),
emptyPushable(),
l
);
}
/**
* Returns a new list that only contains the elements of the original
* list for which the predicate returns `false`.
*
* @complexity O(n)
* @category Transformers
* @example
* reject(isEven, list(0, 1, 2, 3, 4, 5, 6)); //=> list(1, 3, 5)
*/
export function reject<A>(predicate: (a: A) => boolean, l: List<A>): List<A> {
return foldl(
(acc, a) => (predicate(a) ? acc : push(a, acc)),
emptyPushable(),
l
);
}
/**
* Splits the list into two lists. One list that contains all the
* values for which the predicate returns `true` and one containing
* the values for which it returns `false`.
*
* @complexity O(n)
* @category Transformers
* @example
* partition(isEven, list(0, 1, 2, 3, 4, 5)); //=> [(list(0, 2, 4), list(1, 3, 5)]
*/
export function partition<A, B extends A>(
predicate: (a: A) => a is B,
l: List<A>
): [List<B>, List<Exclude<A, B>>];
export function partition<A>(
predicate: (a: A) => boolean,
l: List<A>
): [List<A>, List<A>];
export function partition<A>(
predicate: (a: A) => boolean,
l: List<A>
): [List<A>, List<A>] {
return foldl(
(arr, a) => (predicate(a) ? push(a, arr[0]) : push(a, arr[1]), arr),
[emptyPushable<A>(), emptyPushable<A>()] as [
MutableList<A>,
MutableList<A>
],
l
);
}
/**
* Concats the strings in the list separated by a specified separator.
*
* @category Folds
* @example
* join(", ", list("one", "two", "three")); //=> "one, two, three"
*/
export function join(separator: string, l: List<string>): string {
return foldl((a, b) => (a.length === 0 ? b : a + separator + b), "", l);
}
function foldrSuffix<A, B>(
f: (value: A, acc: B) => B,
initial: B,
array: A[],
length: number
): B {
let acc = initial;
for (let i = length - 1; 0 <= i; --i) {
acc = f(array[i], acc);
}
return acc;
}
function foldrPrefix<A, B>(
f: (value: A, acc: B) => B,
initial: B,
array: A[],
length: number
): B {
let acc = initial;
for (let i = 0; i < length; ++i) {
acc = f(array[i], acc);
}
return acc;
}
function foldrNode<A, B>(
f: (value: A, acc: B) => B,
initial: B,
{ array }: Node,
depth: number
): B {
if (depth === 0) {
return foldrSuffix(f, initial, array, array.length);
}
let acc = initial;
for (let i = array.length - 1; 0 <= i; --i) {
acc = foldrNode(f, acc, array[i], depth - 1);
}
return acc;
}
/**
* Folds a function over a list. Right-associative.
*
* @complexity O(n)
* @category Folds
* @example
* foldr((n, m) => n - m, 5, list(1, 2, 3, 4));
* 1 - (2 - (3 - (4 - 5))); //=> 3
*/
export function foldr<A, B>(
f: (value: A, acc: B) => B,
initial: B,
l: List<A>
): B {
const suffixSize = getSuffixSize(l);
const prefixSize = getPrefixSize(l);
let acc = foldrSuffix(f, initial, l.suffix, suffixSize);
if (l.root !== undefined) {
acc = foldrNode(f, acc, l.root, getDepth(l));
}
return foldrPrefix(f, acc, l.prefix, prefixSize);
}
/**
* Alias for [`foldr`](#foldr).
*
* @category Folds
*/
export const reduceRight = foldr;
/**
* Applies a list of functions to a list of values.
*
* @category Transformers
* @example
* ap(list((n: number) => n + 2, n => 2 * n, n => n * n), list(1, 2, 3));
* //=> list(3, 4, 5, 2, 4, 6, 1, 4, 9)
*/
export function ap<A, B>(listF: List<(a: A) => B>, l: List<A>): List<B> {
return flatten(map(f => map(f, l), listF));
}
/**
* Flattens a list of lists into a list. Note that this function does
* not flatten recursively. It removes one level of nesting only.
*
* @complexity O(n * log(m)), where n is the length of the outer list and m the length of the inner lists.
* @category Transformers
* @example
* const nested = list(list(0, 1, 2, 3), list(4), empty(), list(5, 6));
* flatten(nested); //=> list(0, 1, 2, 3, 4, 5, 6)
*/
export function flatten<A>(nested: List<List<A>>): List<A> {
return foldl<List<A>, List<A>>(concat, empty(), nested);
}
/**
* Maps a function over a list and concatenates all the resulting
* lists together.
*
* @category Transformers
* @example
* flatMap(n => list(n, 2 * n, n * n), list(1, 2, 3)); //=> list(1, 2, 1, 2, 4, 4, 3, 6, 9)
*/
export function flatMap<A, B>(f: (a: A) => List<B>, l: List<A>): List<B> {
return flatten(map(f, l));
}
/**
* Alias for [`flatMap`](#flatMap).
* @category Transformers
*/
export const chain = flatMap;
// callback fold
type FoldCb<Input, State> = (input: Input, state: State) => boolean;
function foldlArrayCb<A, B>(
cb: FoldCb<A, B>,
state: B,
array: A[],
from: number,
to: number
): boolean {
for (var i = from; i < to && cb(array[i], state); ++i) {}
return i === to;
}
function foldrArrayCb<A, B>(
cb: FoldCb<A, B>,
state: B,
array: A[],
from: number,
to: number
): boolean {
for (var i = from - 1; to <= i && cb(array[i], state); --i) {}
return i === to - 1;
}
function foldlNodeCb<A, B>(
cb: FoldCb<A, B>,
state: B,
node: Node,
depth: number
): boolean {
const { array } = node;
if (depth === 0) {
return foldlArrayCb(cb, state, array, 0, array.length);
}
const to = array.length;
for (let i = 0; i < to; ++i) {
if (!foldlNodeCb(cb, state, array[i], depth - 1)) {
return false;
}
}
return true;
}
/**
* This function is a lot like a fold. But the reducer function is
* supposed to mutate its state instead of returning it. Instead of
* returning a new state it returns a boolean that tells wether or not
* to continue the fold. `true` indicates that the folding should
* continue.
*/
function foldlCb<A, B>(cb: FoldCb<A, B>, state: B, l: List<A>): B {
const prefixSize = getPrefixSize(l);
if (
!foldrArrayCb(cb, state, l.prefix, prefixSize, 0) ||
(l.root !== undefined && !foldlNodeCb(cb, state, l.root, getDepth(l)))
) {
return state;
}
const suffixSize = getSuffixSize(l);
foldlArrayCb(cb, state, l.suffix, 0, suffixSize);
return state;
}
function foldrNodeCb<A, B>(
cb: FoldCb<A, B>,
state: B,
node: Node,
depth: number
): boolean {
const { array } = node;
if (depth === 0) {
return foldrArrayCb(cb, state, array, array.length, 0);
}
for (let i = array.length - 1; 0 <= i; --i) {
if (!foldrNodeCb(cb, state, array[i], depth - 1)) {
return false;
}
}
return true;
}
function foldrCb<A, B>(cb: FoldCb<A, B>, state: B, l: List<A>): B {
const suffixSize = getSuffixSize(l);
const prefixSize = getPrefixSize(l);
if (
!foldrArrayCb(cb, state, l.suffix, suffixSize, 0) ||
(l.root !== undefined && !foldrNodeCb(cb, state, l.root, getDepth(l)))
) {
return state;
}
const prefix = l.prefix;
foldlArrayCb(cb, state, l.prefix, prefix.length - prefixSize, prefix.length);
return state;
}
// functions based on foldlCb
type FoldlWhileState<A, B> = {
predicate: (b: B, a: A) => boolean;
result: B;
f: (acc: B, value: A) => B;
};
/**
* Similar to `foldl`. But, for each element it calls the predicate function
* _before_ the folding function and stops folding if it returns `false`.
*
* @category Folds
* @example
* const isOdd = (_acc:, x) => x % 2 === 1;
*
* const xs = L.list(1, 3, 5, 60, 777, 800);
* foldlWhile(isOdd, (n, m) => n + m, 0, xs) //=> 9
*
* const ys = L.list(2, 4, 6);
* foldlWhile(isOdd, (n, m) => n + m, 111, ys) //=> 111
*/
function foldlWhileCb<A, B>(a: A, state: FoldlWhileState<A, B>): boolean {
if (state.predicate(state.result, a) === false) {
return false;
}
state.result = state.f(state.result, a);
return true;
}
export function foldlWhile<A, B>(
predicate: (acc: B, value: A) => boolean,
f: (acc: B, value: A) => B,
initial: B,
l: List<A>
): B {
return foldlCb<A, FoldlWhileState<A, B>>(
foldlWhileCb,
{ predicate, f, result: initial },
l
).result;
}
/**
* Alias for [`foldlWhile`](#foldlWhile).
*
* @category Folds
*/
export const reduceWhile = foldlWhile;
type PredState = {
predicate: (a: any) => boolean;
result: any;
};
function everyCb<A>(value: A, state: any): boolean {
return (state.result = state.predicate(value));
}
/**
* Returns `true` if and only if the predicate function returns `true`
* for all elements in the given list.
*
* @complexity O(n)
* @category Folds
* @example
* every(isEven, empty()); //=> true
* every(isEven, list(2, 4, 6, 8)); //=> true
* every(isEven, list(2, 3, 4, 6, 7, 8)); //=> false
* every(isEven, list(1, 3, 5, 7)); //=> false
*/
export function every<A>(predicate: (a: A) => boolean, l: List<A>): boolean {
return foldlCb<A, PredState>(everyCb, { predicate, result: true }, l).result;
}
/**
* Alias for [`every`](#every).
*
* @category Folds
*/
export const all = every;
function someCb<A>(value: A, state: any): boolean {
return !(state.result = state.predicate(value));
}
/**
* Returns true if and only if there exists an element in the list for
* which the predicate returns true.
*
* @complexity O(n)
* @category Folds
* @example
* const isEven = n => n % 2 === 0;
* some(isEven, empty()); //=> false
* some(isEven, list(2, 4, 6, 8)); //=> true
* some(isEven, list(2, 3, 4, 6, 7, 8)); //=> true
* some(isEven, list(1, 3, 5, 7)); //=> false
*/
export function some<A>(predicate: (a: A) => boolean, l: List<A>): boolean {
return foldlCb<A, PredState>(someCb, { predicate, result: false }, l).result;
}
/**
* Alias for [`some`](#some).
*
* @category Folds
*/
// tslint:disable-next-line:variable-name
export const any = some;
/**
* Returns `true` if and only if the predicate function returns
* `false` for every element in the given list.
*
* @complexity O(n)
* @category Folds
* @example
* none(isEven, empty()); //=> true
* none(isEven, list(2, 4, 6, 8)); //=> false
* none(isEven, list(2, 3, 4, 6, 7, 8)); //=> false
* none(isEven, list(1, 3, 5, 7)); //=> true
*/
export function none<A>(predicate: (a: A) => boolean, l: List<A>): boolean {
return !some(predicate, l);
}
function findCb<A>(value: A, state: PredState): boolean {
if (state.predicate(value)) {
state.result = value;
return false;
} else {
return true;
}
}
/**
* Returns the _first_ element for which the predicate returns `true`.
* If no such element is found the function returns `undefined`.
*
* @complexity O(n)
* @category Folds
* @example
* find(isEven, list(1, 3, 5, 6, 7, 8, 9)); //=> 6
* find(isEven, list(1, 3, 5, 7, 9)); //=> undefined
*/
export function find<A>(
predicate: (a: A) => boolean,
l: List<A>
): A | undefined {
return foldlCb<A, PredState>(findCb, { predicate, result: undefined }, l)
.result;
}
/**
* Returns the _last_ element for which the predicate returns `true`.
* If no such element is found the function returns `undefined`.
*
* @complexity O(n)
* @category Folds
* @example
* find(isEven, list(1, 3, 5, 6, 7, 8, 9)); //=> 8
* find(isEven, list(1, 3, 5, 7, 9)); //=> undefined
*/
export function findLast<A>(
predicate: (a: A) => boolean,
l: List<A>
): A | undefined {
return foldrCb<A, PredState>(findCb, { predicate, result: undefined }, l)
.result;
}
type IndexOfState = {
element: any;
found: boolean;
index: number;
};
function indexOfCb(value: any, state: IndexOfState): boolean {
++state.index;
return !(state.found = elementEquals(value, state.element));
}
/**
* Returns the index of the _first_ element in the list that is equal
* to the given element. If no such element is found `-1` is returned.
*
* @complexity O(n)
* @category Folds
* @example
* const l = list(12, 4, 2, 89, 6, 18, 7);
* indexOf(12, l); //=> 0
* indexOf(89, l); //=> 3
* indexOf(10, l); //=> -1
*/
export function indexOf<A>(element: A, l: List<A>): number {
const state = { element, found: false, index: -1 };
foldlCb(indexOfCb, state, l);
return state.found ? state.index : -1;
}
/**
* Returns the index of the _last_ element in the list that is equal
* to the given element. If no such element is found `-1` is returned.
*
* @complexity O(n)
* @category Folds
* @example
* const l = L.list(12, 4, 2, 18, 89, 2, 18, 7);
* L.lastIndexOf(18, l); //=> 6
* L.lastIndexOf(2, l); //=> 5
* L.lastIndexOf(12, l); //=> 0
*/
export function lastIndexOf<A>(element: A, l: List<A>): number {
const state = { element, found: false, index: 0 };
foldrCb(indexOfCb, state, l);
return state.found ? l.length - state.index : -1;
}
type FindIndexState = {
predicate: (a: any) => boolean;
found: boolean;
index: number;
};
function findIndexCb<A>(value: A, state: FindIndexState): boolean {
++state.index;
return !(state.found = state.predicate(value));
}
/**
* Returns the index of the `first` element for which the predicate
* returns true. If no such element is found the function returns
* `-1`.
*
* @complexity O(n)
* @category Folds
* @example
* findIndex(isEven, list(1, 3, 5, 6, 7, 9, 10)); //=> 3
* findIndex(isEven, list(1, 3, 5, 7, 9)); //=> -1
*/
export function findIndex<A>(predicate: (a: A) => boolean, l: List<A>): number {
const { found, index } = foldlCb<A, FindIndexState>(
findIndexCb,
{ predicate, found: false, index: -1 },
l
);
return found ? index : -1;
}
type ContainsState = {
element: any;
result: boolean;
};
const containsState: ContainsState = {
element: undefined,
result: false
};
function containsCb(value: any, state: ContainsState): boolean {
return !(state.result = value === state.element);
}
/**
* Returns `true` if the list contains the specified element.
* Otherwise it returns `false`.
*
* @complexity O(n)
* @category Folds
* @example
* includes(3, list(0, 1, 2, 3, 4, 5)); //=> true
* includes(3, list(0, 1, 2, 4, 5)); //=> false
*/
export function includes<A>(element: A, l: List<A>): boolean {
containsState.element = element;
containsState.result = false;
return foldlCb(containsCb, containsState, l).result;
}
/**
* Alias for [`includes`](#includes).
*
* @category Folds
*/
export const contains = includes;
type EqualsState<A> = {
iterator: Iterator<A>;
f: (a: A, b: A) => boolean;
equals: boolean;
};
function equalsCb<A>(value2: A, state: EqualsState<A>): boolean {
const { value } = state.iterator.next();
return (state.equals = state.f(value, value2));
}
/**
* Returns true if the two lists are equivalent.
*
* @complexity O(n)
* @category Folds
* @example
* equals(list(0, 1, 2, 3), list(0, 1, 2, 3)); //=> true
* equals(list("a", "b", "c"), list("a", "z", "c")); //=> false
*/
export function equals<A>(l1: List<A>, l2: List<A>): boolean {
return equalsWith(elementEquals, l1, l2);
}
/**
* Returns true if the two lists are equivalent when comparing each
* pair of elements with the given comparison function.
*
* @complexity O(n)
* @category Folds
* @example
* equalsWith(
* (n, m) => n.length === m.length,
* list("foo", "hello", "one"),
* list("bar", "world", "two")
* ); //=> true
*/
export function equalsWith<A>(
f: (a: A, b: A) => boolean,
l1: List<A>,
l2: List<A>
): boolean {
if (l1 === l2) {
return true;
} else if (l1.length !== l2.length) {
return false;
} else {
const s = { iterator: l2[Symbol.iterator](), equals: true, f };
return foldlCb<A, EqualsState<A>>(equalsCb, s, l1).equals;
}
}
// concat
const eMax = 2;
function createConcatPlan(array: Node[]): number[] | undefined {
const sizes = [];
let sum = 0;
for (let i = 0; i < array.length; ++i) {
sum += array[i].array.length; // FIXME: maybe only access array once
sizes[i] = array[i].array.length;
}
const optimalLength = Math.ceil(sum / branchingFactor);
let n = array.length;
let i = 0;
if (optimalLength + eMax >= n) {
return undefined; // no rebalancing needed
}
while (optimalLength + eMax < n) {
while (sizes[i] > branchingFactor - eMax / 2) {
// Skip nodes that are already sufficiently balanced
++i;
}
// the node at this index is too short
let remaining = sizes[i]; // number of elements to re-distribute
do {
const size = Math.min(remaining + sizes[i + 1], branchingFactor);
sizes[i] = size;
remaining = remaining - (size - sizes[i + 1]);
++i;
} while (remaining > 0);
// Shift nodes after
for (let j = i; j <= n - 1; ++j) {
sizes[j] = sizes[j + 1];
}
--i;
--n;
}
sizes.length = n;
return sizes;
}
/**
* Combines the children of three nodes into an array. The last child
* of `left` and the first child of `right is ignored as they've been
* concatenated into `center`.
*/
function concatNodeMerge(
left: Node | undefined,
center: Node,
right: Node | undefined
): Node[] {
const array = [];
if (left !== undefined) {
for (let i = 0; i < left.array.length - 1; ++i) {
array.push(left.array[i]);
}
}
for (let i = 0; i < center.array.length; ++i) {
array.push(center.array[i]);
}
if (right !== undefined) {
for (let i = 1; i < right.array.length; ++i) {
array.push(right.array[i]);
}
}
return array;
}
function executeConcatPlan(
merged: Node[],
plan: number[],
height: number
): any[] {
const result = [];
let sourceIdx = 0; // the current node we're copying from
let offset = 0; // elements in source already used
for (let toMove of plan) {
let source = merged[sourceIdx].array;
if (toMove === source.length && offset === 0) {
// source matches target exactly, reuse source
result.push(merged[sourceIdx]);
++sourceIdx;
} else {
const node = new Node(undefined, []);
while (toMove > 0) {
const available = source.length - offset;
const itemsToCopy = Math.min(toMove, available);
pushElements(source, node.array, offset, itemsToCopy);
if (toMove >= available) {
++sourceIdx;
source = merged[sourceIdx].array;
offset = 0;
} else {
offset += itemsToCopy;
}
toMove -= itemsToCopy;
}
if (height > 1) {
// Set sizes on children unless they are leaf nodes
setSizes(node, height - 1);
}
result.push(node);
}
}
return result;
}
/**
* Takes three nodes and returns a new node with the content of the
* three nodes. Note: The returned node does not have its size table
* set correctly. The caller must do that.
*/
function rebalance(
left: Node | undefined,
center: Node,
right: Node | undefined,
height: number,
top: boolean
): Node {
const merged = concatNodeMerge(left, center, right);
const plan = createConcatPlan(merged);
const balanced =
plan !== undefined ? executeConcatPlan(merged, plan, height) : merged;
if (balanced.length <= branchingFactor) {
if (top === true) {
return new Node(undefined, balanced);
} else {
// Return a single node with extra height for balancing at next
// level
return new Node(undefined, [
setSizes(new Node(undefined, balanced), height)
]);
}
} else {
return new Node(undefined, [
setSizes(new Node(undefined, balanced.slice(0, branchingFactor)), height),
setSizes(new Node(undefined, balanced.slice(branchingFactor)), height)
]);
}
}
function concatSubTree<A>(
left: Node,
lDepth: number,
right: Node,
rDepth: number,
isTop: boolean
): Node {
if (lDepth > rDepth) {
const c = concatSubTree(
arrayLast(left.array),
lDepth - 1,
right,
rDepth,
false
);
return rebalance(left, c, undefined, lDepth, isTop);
} else if (lDepth < rDepth) {
const c = concatSubTree(
left,
lDepth,
arrayFirst(right.array),
rDepth - 1,
false
);
return rebalance(undefined, c, right, rDepth, isTop);
} else if (lDepth === 0) {
return new Node(undefined, [left, right]);
} else {
const c = concatSubTree<A>(
arrayLast(left.array),
lDepth - 1,
arrayFirst(right.array),
rDepth - 1,
false
);
return rebalance(left, c, right, lDepth, isTop);
}
}
function getHeight(node: Node): number {
if (node.array[0] instanceof Node) {
return 1 + getHeight(node.array[0]);
} else {
return 0;
}
}
/**
* Takes a RRB-tree and an affix. It then appends the node to the
* tree.
* @param l The subject for appending. `l` will be mutated. Nodes in
* the tree will _not_ be mutated.
* @param array The affix that should be appended to the tree.
*/
function appendNodeToTree<A>(l: MutableList<A>, array: A[]): MutableList<A> {
if (l.root === undefined) {
// The old list has no content in tree, all content is in affixes
if (getPrefixSize(l) === 0) {
l.bits = setPrefix(array.length, l.bits);
l.prefix = reverseArray(array);
} else {
l.root = new Node(undefined, array);
}
return l;
}
const depth = getDepth(l);
let index = handleOffset(depth, l.offset, l.length - 1 - getPrefixSize(l));
let nodesToCopy = 0;
let nodesVisited = 0;
let shift = depth * 5;
let currentNode = l.root;
if (32 ** (depth + 1) < index) {
shift = 0; // there is no room
nodesVisited = depth;
}
while (shift > 5) {
let childIndex: number;
if (currentNode.sizes === undefined) {
// does not have size table
childIndex = (index >> shift) & mask;
index &= ~(mask << shift); // wipe just used bits
} else {
childIndex = currentNode.array.length - 1;
index -= currentNode.sizes[childIndex - 1];
}
nodesVisited++;
if (childIndex < mask) {
// we are not going down the far right path, this implies that
// there is still room in the current node
nodesToCopy = nodesVisited;
}
currentNode = currentNode.array[childIndex];
if (currentNode === undefined) {
// This will only happened in a pvec subtree. The index does not
// exist so we'll have to create a new path from here on.
nodesToCopy = nodesVisited;
shift = 5; // Set shift to break out of the while-loop
}
shift -= 5;
}
if (shift !== 0) {
nodesVisited++;
if (currentNode.array.length < branchingFactor) {
// there is room in the found node
nodesToCopy = nodesVisited;
}
}
const node = new Node(undefined, array);
if (nodesToCopy === 0) {
// there was no room in the found node
const newPath = nodesVisited === 0 ? node : createPath(nodesVisited, node);
const newRoot = new Node(undefined, [l.root, newPath]);
l.root = newRoot;
l.bits = incrementDepth(l.bits);
} else {
const copiedNode = copyFirstK(l, nodesToCopy, array.length);
copiedNode.array.push(createPath(depth - nodesToCopy, node));
}
return l;
}
/**
* Traverses down the right edge of the tree and copies k nodes.
* @param oldList
* @param newList
* @param k The number of nodes to copy. Will always be at least 1.
* @param leafSize The number of elements in the leaf that will be inserted.
*/
function copyFirstK(
newList: MutableList<any>,
k: number,
leafSize: number
): Node {
let currentNode = cloneNode(newList.root!); // copy root
newList.root = currentNode; // install root
for (let i = 1; i < k; ++i) {
const index = currentNode.array.length - 1;
if (currentNode.sizes !== undefined) {
currentNode.sizes[index] += leafSize;
}
const newNode = cloneNode(currentNode.array[index]);
// Install the copied node
currentNode.array[index] = newNode;
currentNode = newNode;
}
if (currentNode.sizes !== undefined) {
currentNode.sizes.push(arrayLast(currentNode.sizes) + leafSize);
}
return currentNode;
}
const concatBuffer = new Array(3);
function concatAffixes<A>(left: List<A>, right: List<A>): number {
// TODO: Try and find a neat way to reduce the LOC here
var nr = 0;
var arrIdx = 0;
var i = 0;
var length = getSuffixSize(left);
concatBuffer[nr] = [];
for (i = 0; i < length; ++i) {
concatBuffer[nr][arrIdx++] = left.suffix[i];
}
length = getPrefixSize(right);
for (i = 0; i < length; ++i) {
if (arrIdx === 32) {
arrIdx = 0;
++nr;
concatBuffer[nr] = [];
}
concatBuffer[nr][arrIdx++] = right.prefix[length - 1 - i];
}
length = getSuffixSize(right);
for (i = 0; i < length; ++i) {
if (arrIdx === 32) {
arrIdx = 0;
++nr;
concatBuffer[nr] = [];
}
concatBuffer[nr][arrIdx++] = right.suffix[i];
}
return nr;
}
/**
* Concatenates two lists.
*
* @complexity O(log(n))
* @category Transformers
* @example
* concat(list(0, 1, 2), list(3, 4)); //=> list(0, 1, 2, 3, 4)
*/
export function concat<A>(left: List<A>, right: List<A>): List<A> {
if (left.length === 0) {
return right;
} else if (right.length === 0) {
return left;
}
const newSize = left.length + right.length;
const rightSuffixSize = getSuffixSize(right);
let newList = cloneList(left);
if (right.root === undefined) {
// right is nothing but a prefix and a suffix
const nrOfAffixes = concatAffixes(left, right);
for (var i = 0; i < nrOfAffixes; ++i) {
newList = appendNodeToTree(newList, concatBuffer[i]);
newList.length += concatBuffer[i].length;
// wipe pointer, otherwise it might end up keeping the array alive
concatBuffer[i] = undefined;
}
newList.length = newSize;
newList.suffix = concatBuffer[nrOfAffixes];
newList.bits = setSuffix(concatBuffer[nrOfAffixes].length, newList.bits);
concatBuffer[nrOfAffixes] = undefined;
return newList;
} else {
const leftSuffixSize = getSuffixSize(left);
if (leftSuffixSize > 0) {
newList = appendNodeToTree(newList, left.suffix.slice(0, leftSuffixSize));
newList.length += leftSuffixSize;
}
newList = appendNodeToTree(
newList,
right.prefix.slice(0, getPrefixSize(right)).reverse()
);
const newNode = concatSubTree(
newList.root!,
getDepth(newList),
right.root,
getDepth(right),
true
);
const newDepth = getHeight(newNode);
setSizes(newNode, newDepth);
newList.root = newNode;
newList.offset &= ~(mask << (getDepth(left) * branchBits));
newList.length = newSize;
newList.bits = setSuffix(rightSuffixSize, setDepth(newDepth, newList.bits));
newList.suffix = right.suffix;
return newList;
}
}
/**
* Returns a list that has the entry specified by the index replaced with the given value.
*
* If the index is out of bounds the given list is returned unchanged.
*
* @complexity O(log(n))
* @category Transformers
* @example
* update(2, "X", list("a", "b", "c", "d", "e")); //=> list("a", "b", "X", "d", "e")
*/
export function update<A>(index: number, a: A, l: List<A>): List<A> {
if (index < 0 || l.length <= index) {
return l;
}
const prefixSize = getPrefixSize(l);
const suffixSize = getSuffixSize(l);
const newList = cloneList(l);
if (index < prefixSize) {
const newPrefix = copyArray(newList.prefix);
newPrefix[newPrefix.length - index - 1] = a;
newList.prefix = newPrefix;
} else if (index >= l.length - suffixSize) {
const newSuffix = copyArray(newList.suffix);
newSuffix[index - (l.length - suffixSize)] = a;
newList.suffix = newSuffix;
} else {
newList.root = updateNode(
l.root!,
getDepth(l),
index - prefixSize,
l.offset,
a
);
}
return newList;
}
/**
* Returns a list that has the entry specified by the index replaced with
* the value returned by applying the function to the value.
*
* If the index is out of bounds the given list is
* returned unchanged.
*
* @complexity `O(log(n))`
* @category Transformers
* @example
* adjust(2, inc, list(0, 1, 2, 3, 4, 5)); //=> list(0, 1, 3, 3, 4, 5)
*/
export function adjust<A>(index: number, f: (a: A) => A, l: List<A>): List<A> {
if (index < 0 || l.length <= index) {
return l;
}
return update(index, f(nth(index, l)!), l);
}
// slice and slice based functions
let newAffix: any[];
// function getBitsForDepth(n: number, depth: number): number {
// return n & ~(~0 << ((depth + 1) * branchBits));
// }
function sliceNode(
node: Node,
index: number,
depth: number,
pathLeft: number,
pathRight: number,
childLeft: Node | undefined,
childRight: Node | undefined
): Node {
let array = node.array.slice(pathLeft, pathRight + 1);
if (childLeft !== undefined) {
array[0] = childLeft;
}
if (childRight !== undefined) {
array[array.length - 1] = childRight;
}
let sizes = node.sizes;
if (sizes !== undefined) {
sizes = sizes.slice(pathLeft, pathRight + 1);
let slicedOffLeft = pathLeft !== 0 ? node.sizes![pathLeft - 1] : 0;
if (childLeft !== undefined) {
// If the left child has been sliced into a new child we need to know
// how many elements have been removed from the child.
if (childLeft.sizes !== undefined) {
// If the left child has a size table we can simply look at that.
const oldChild: Node = node.array[pathLeft];
slicedOffLeft +=
arrayLast(oldChild.sizes!) - arrayLast(childLeft.sizes);
} else {
// If the left child does not have a size table we can
// calculate how many elements have been removed from it by
// looking at the index. Note that when we slice into a leaf
// the leaf is moved up as a prefix. Thus slicing, for
// instance, at index 20 will remove 32 elements from the
// child. Similarly slicing at index 50 will remove 64
// elements at slicing at 64 will remove 92 elements.
slicedOffLeft += ((index - slicedOffLeft) & ~0b011111) + 32;
}
}
for (let i = 0; i < sizes.length; ++i) {
sizes[i] -= slicedOffLeft;
}
if (childRight !== undefined) {
const slicedOffRight =
sizeOfSubtree(node.array[pathRight], depth - 1) -
sizeOfSubtree(childRight, depth - 1);
sizes[sizes.length - 1] -= slicedOffRight;
}
}
return new Node(sizes, array);
}
let newOffset = 0;
function sliceLeft(
tree: Node,
depth: number,
index: number,
offset: number,
top: boolean
): Node | undefined {
let { path, index: newIndex, updatedOffset } = getPath(
index,
offset,
depth,
tree.sizes
);
if (depth === 0) {
newAffix = tree.array.slice(path).reverse();
// This leaf node is moved up as a suffix so there is nothing here
// after slicing
return undefined;
} else {
const child = sliceLeft(
tree.array[path],
depth - 1,
newIndex,
updatedOffset,
false
);
if (child === undefined) {
// There is nothing in the child after slicing so we don't include it
++path;
if (path === tree.array.length) {
return undefined;
}
}
// If we've sliced something away and it's not a the root, update offset
if (tree.sizes === undefined && top === false) {
newOffset |= (32 - (tree.array.length - path)) << (depth * branchBits);
}
return sliceNode(
tree,
index,
depth,
path,
tree.array.length - 1,
child,
undefined
);
}
}
/** Slice elements off of a tree from the right */
function sliceRight(
node: Node,
depth: number,
index: number,
offset: number
): Node | undefined {
let { path, index: newIndex } = getPath(index, offset, depth, node.sizes);
if (depth === 0) {
newAffix = node.array.slice(0, path + 1);
// this leaf node is moved up as a suffix so there is nothing here
// after slicing
return undefined;
} else {
// slice the child, note that we subtract 1 then the radix lookup
// algorithm can find the last element that we want to include
// and sliceRight will do a slice that is inclusive on the index.
const child = sliceRight(
node.array[path],
depth - 1,
newIndex,
path === 0 ? offset : 0
);
if (child === undefined) {
// there is nothing in the child after slicing so we don't include it
--path;
if (path === -1) {
return undefined;
}
}
// note that we add 1 to the path since we want the slice to be
// inclusive on the end index. Only at the leaf level do we want
// to do an exclusive slice.
let array = node.array.slice(0, path + 1);
if (child !== undefined) {
array[array.length - 1] = child;
}
let sizes: Sizes | undefined = node.sizes;
if (sizes !== undefined) {
sizes = sizes.slice(0, path + 1);
if (child !== undefined) {
const slicedOff =
sizeOfSubtree(node.array[path], depth - 1) -
sizeOfSubtree(child, depth - 1);
sizes[sizes.length - 1] -= slicedOff;
}
}
return new Node(sizes, array);
}
}
function sliceTreeList<A>(
from: number,
to: number,
tree: Node,
depth: number,
offset: number,
l: MutableList<A>
): List<A> {
const sizes = tree.sizes;
let { path: pathLeft, index: newFrom } = getPath(from, offset, depth, sizes);
let { path: pathRight, index: newTo } = getPath(to, offset, depth, sizes);
if (depth === 0) {
// we are slicing a piece off a leaf node
l.prefix = emptyAffix;
l.suffix = tree.array.slice(pathLeft, pathRight + 1);
l.root = undefined;
l.bits = setSuffix(pathRight - pathLeft + 1, 0);
return l;
} else if (pathLeft === pathRight) {
// Both ends are located in the same subtree, this means that we
// can reduce the height
l.bits = decrementDepth(l.bits);
return sliceTreeList(
newFrom,
newTo,
tree.array[pathLeft],
depth - 1,
pathLeft === 0 ? offset : 0,
l
);
} else {
const childRight = sliceRight(tree.array[pathRight], depth - 1, newTo, 0);
l.bits = setSuffix(newAffix.length, l.bits);
l.suffix = newAffix;
if (childRight === undefined) {
--pathRight;
}
newOffset = 0;
const childLeft = sliceLeft(
tree.array[pathLeft],
depth - 1,
newFrom,
pathLeft === 0 ? offset : 0,
pathLeft === pathRight
);
l.offset = newOffset;
l.bits = setPrefix(newAffix.length, l.bits);
l.prefix = newAffix;
if (childLeft === undefined) {
++pathLeft;
}
if (pathLeft >= pathRight) {
if (pathLeft > pathRight) {
// This only happens when `pathLeft` originally was equal to
// `pathRight + 1` and `childLeft === childRight === undefined`.
// In this case there is no tree left.
l.bits = setDepth(0, l.bits);
l.root = undefined;
} else {
// Height can be reduced
l.bits = decrementDepth(l.bits);
const newRoot =
childRight !== undefined
? childRight
: childLeft !== undefined
? childLeft
: tree.array[pathLeft];
l.root = new Node(newRoot.sizes, newRoot.array); // Is this size handling good enough?
}
} else {
l.root = sliceNode(
tree,
from,
depth,
pathLeft,
pathRight,
childLeft,
childRight
);
}
return l;
}
}
/**
* Returns a slice of a list. Elements are removed from the beginning and
* end. Both the indices can be negative in which case they will count
* from the right end of the list.
*
* @complexity**: `O(log(n))`
* @category Transformers
* @example**
* const l = list(0, 1, 2, 3, 4, 5);
* slice(1, 4, l); //=> list(1, 2, 3)
* slice(2, -2, l); //=> list(2, 3)
*/
export function slice<A>(from: number, to: number, l: List<A>): List<A> {
let { bits, length } = l;
to = Math.min(length, to);
// Handle negative indices
if (from < 0) {
from = length + from;
}
if (to < 0) {
to = length + to;
}
// Should we just return the empty list?
if (to <= from || to <= 0 || length <= from) {
return empty();
}
// Return list unchanged if we are slicing nothing off
if (from <= 0 && length <= to) {
return l;
}
const newLength = to - from;
let prefixSize = getPrefixSize(l);
const suffixSize = getSuffixSize(l);
// Both indices lie in the prefix
if (to <= prefixSize) {
return new List(
setPrefix(newLength, 0),
0,
newLength,
l.prefix.slice(prefixSize - to, prefixSize - from),
undefined,
emptyAffix
);
}
const suffixStart = length - suffixSize;
// Both indices lie in the suffix
if (suffixStart <= from) {
return new List(
setSuffix(newLength, 0),
0,
newLength,
emptyAffix,
undefined,
l.suffix.slice(from - suffixStart, to - suffixStart)
);
}
const newList = cloneList(l);
newList.length = newLength;
// Both indices lie in the tree
if (prefixSize <= from && to <= suffixStart) {
sliceTreeList(
from - prefixSize + l.offset,
to - prefixSize + l.offset - 1,
l.root!,
getDepth(l),
l.offset,
newList
);
return newList;
}
if (0 < from) {
// we need to slice something off of the left
if (from < prefixSize) {
// shorten the prefix even though it's not strictly needed,
// so that referenced items can be GC'd
newList.prefix = l.prefix.slice(0, prefixSize - from);
bits = setPrefix(prefixSize - from, bits);
} else {
// if we're here `to` can't lie in the tree, so we can set the
// root
newOffset = 0;
newList.root = sliceLeft(
newList.root!,
getDepth(l),
from - prefixSize,
l.offset,
true
);
newList.offset = newOffset;
if (newList.root === undefined) {
bits = setDepth(0, bits);
}
bits = setPrefix(newAffix.length, bits);
prefixSize = newAffix.length;
newList.prefix = newAffix;
}
}
if (to < length) {
// we need to slice something off of the right
if (length - to < suffixSize) {
bits = setSuffix(suffixSize - (length - to), bits);
// slice the suffix even though it's not strictly needed,
// to allow the removed items to be GC'd
newList.suffix = l.suffix.slice(0, suffixSize - (length - to));
} else {
newList.root = sliceRight(
newList.root!,
getDepth(l),
to - prefixSize - 1,
newList.offset
);
if (newList.root === undefined) {
bits = setDepth(0, bits);
newList.offset = 0;
}
bits = setSuffix(newAffix.length, bits);
newList.suffix = newAffix;
}
}
newList.bits = bits;
return newList;
}
/**
* Takes the first `n` elements from a list and returns them in a new list.
*
* @complexity `O(log(n))`
* @category Transformers
* @example
* take(3, list(0, 1, 2, 3, 4, 5)); //=> list(0, 1, 2)
*/
export function take<A>(n: number, l: List<A>): List<A> {
return slice(0, n, l);
}
type FindNotIndexState = {
predicate: (a: any) => boolean;
index: number;
};
function findNotIndexCb(value: any, state: FindNotIndexState): boolean {
if (state.predicate(value)) {
++state.index;
return true;
} else {
return false;
}
}
/**
* Takes the first elements in the list for which the predicate returns
* `true`.
*
* @complexity `O(k + log(n))` where `k` is the number of elements satisfying
* the predicate.
* @category Transformers
* @example
* takeWhile(n => n < 4, list(0, 1, 2, 3, 4, 5, 6)); //=> list(0, 1, 2, 3)
* takeWhile(_ => false, list(0, 1, 2, 3, 4, 5)); //=> list()
*/
export function takeWhile<A>(
predicate: (a: A) => boolean,
l: List<A>
): List<A> {
const { index } = foldlCb(findNotIndexCb, { predicate, index: 0 }, l);
return slice(0, index, l);
}
/**
* Takes the last elements in the list for which the predicate returns
* `true`.
*
* @complexity `O(k + log(n))` where `k` is the number of elements
* satisfying the predicate.
* @category Transformers
* @example
* takeLastWhile(n => n > 2, list(0, 1, 2, 3, 4, 5)); //=> list(3, 4, 5)
* takeLastWhile(_ => false, list(0, 1, 2, 3, 4, 5)); //=> list()
*/
export function takeLastWhile<A>(
predicate: (a: A) => boolean,
l: List<A>
): List<A> {
const { index } = foldrCb(findNotIndexCb, { predicate, index: 0 }, l);
return slice(l.length - index, l.length, l);
}
/**
* Removes the first elements in the list for which the predicate returns
* `true`.
*
* @complexity `O(k + log(n))` where `k` is the number of elements
* satisfying the predicate.
* @category Transformers
* @example
* dropWhile(n => n < 4, list(0, 1, 2, 3, 4, 5, 6)); //=> list(4, 5, 6)
*/
export function dropWhile<A>(
predicate: (a: A) => boolean,
l: List<A>
): List<A> {
const { index } = foldlCb(findNotIndexCb, { predicate, index: 0 }, l);
return slice(index, l.length, l);
}
/**
* Returns a new list without repeated elements.
*
* @complexity `O(n)`
* @category Transformers
* @example
* dropRepeats(L.list(0, 0, 1, 1, 1, 2, 3, 3, 4, 4)); //=> list(0, 1, 2, 3, 4)
*/
export function dropRepeats<A>(l: List<A>): List<A> {
return dropRepeatsWith(elementEquals, l);
}
/**
* Returns a new list without repeated elements by using the given
* function to determine when elements are equal.
*
* @complexity `O(n)`
* @category Transformers
* @example
*
* dropRepeatsWith(
* (n, m) => Math.floor(n) === Math.floor(m),
* list(0, 0.4, 1.2, 1.1, 1.8, 2.2, 3.8, 3.4, 4.7, 4.2)
* ); //=> list(0, 1, 2, 3, 4)
*/
export function dropRepeatsWith<A>(
predicate: (a: A, b: A) => Boolean,
l: List<A>
): List<A> {
return foldl(
(acc, a) =>
acc.length !== 0 && predicate(last(acc)!, a) ? acc : push(a, acc),
emptyPushable(),
l
);
}
/**
* Takes the last `n` elements from a list and returns them in a new
* list.
*
* @complexity `O(log(n))`
* @category Transformers
* @example
* takeLast(3, list(0, 1, 2, 3, 4, 5)); //=> list(3, 4, 5)
*/
export function takeLast<A>(n: number, l: List<A>): List<A> {
return slice(l.length - n, l.length, l);
}
/**
* Splits a list at the given index and return the two sides in a pair.
* The left side will contain all elements before but not including the
* element at the given index. The right side contains the element at the
* index and all elements after it.
*
* @complexity `O(log(n))`
* @category Transformers
* @example
* const l = list(0, 1, 2, 3, 4, 5, 6, 7, 8);
* splitAt(4, l); //=> [list(0, 1, 2, 3), list(4, 5, 6, 7, 8)]
*/
export function splitAt<A>(index: number, l: List<A>): [List<A>, List<A>] {
return [slice(0, index, l), slice(index, l.length, l)];
}
/**
* Splits a list at the first element in the list for which the given
* predicate returns `true`.
*
* @complexity `O(n)`
* @category Transformers
* @example
* const l = list(0, 1, 2, 3, 4, 5, 6, 7);
* splitWhen((n) => n > 3, l); //=> [list(0, 1, 2, 3), list(4, 5, 6, 7)]
*/
export function splitWhen<A>(
predicate: (a: A) => boolean,
l: List<A>
): [List<A>, List<A>] {
const idx = findIndex(predicate, l);
return idx === -1 ? [l, empty()] : splitAt(idx, l);
}
/**
* Splits the list into chunks of the given size.
*
* @category Transformers
* @example
* splitEvery(2, list(0, 1, 2, 3, 4)); //=> list(list(0, 1), list(2, 3), list(4))
*/
export function splitEvery<A>(size: number, l: List<A>): List<List<A>> {
const { l2, buffer } = foldl(
({ l2, buffer }, elm) => {
push(elm, buffer);
if (buffer.length === size) {
return { l2: push(buffer, l2), buffer: emptyPushable<A>() };
} else {
return { l2, buffer };
}
},
{ l2: emptyPushable<List<A>>(), buffer: emptyPushable<A>() },
l
);
return buffer.length === 0 ? l2 : push(buffer, l2);
}
/**
* Takes an index, a number of elements to remove and a list. Returns a
* new list with the given amount of elements removed from the specified
* index.
*
* @complexity `O(log(n))`
* @category Transformers
* @example
* const l = list(0, 1, 2, 3, 4, 5, 6, 7, 8);
* remove(4, 3, l); //=> list(0, 1, 2, 3, 7, 8)
* remove(2, 5, l); //=> list(0, 1, 7, 8)
*/
export function remove<A>(from: number, amount: number, l: List<A>): List<A> {
return concat(slice(0, from, l), slice(from + amount, l.length, l));
}
/**
* Returns a new list without the first `n` elements.
*
* @complexity `O(log(n))`
* @category Transformers
* @example
* drop(2, list(0, 1, 2, 3, 4, 5)); //=> list(2, 3, 4, 5)
*/
export function drop<A>(n: number, l: List<A>): List<A> {
return slice(n, l.length, l);
}
/**
* Returns a new list without the last `n` elements.
*
* @complexity `O(log(n))`
* @category Transformers
* @example
* dropLast(2, list(0, 1, 2, 3, 4, 5)); //=> list(0, 1, 2, 3)
*/
export function dropLast<A>(n: number, l: List<A>): List<A> {
return slice(0, l.length - n, l);
}
/**
* Returns a new list with the last element removed. If the list is
* empty the empty list is returned.
*
* @complexity `O(1)`
* @category Transformers
* @example
* pop(list(0, 1, 2, 3)); //=> list(0, 1, 2)
*/
export function pop<A>(l: List<A>): List<A> {
return slice(0, -1, l);
}
/**
* Alias for [`pop`](#pop).
*
* @category Transformers
*/
export const init = pop;
/**
* Returns a new list with the first element removed. If the list is
* empty the empty list is returned.
*
* @complexity `O(1)`
* @category Transformers
* @example
* tail(list(0, 1, 2, 3)); //=> list(1, 2, 3)
* tail(empty()); //=> list()
*/
export function tail<A>(l: List<A>): List<A> {
return slice(1, l.length, l);
}
function arrayPush<A>(array: A[], a: A): A[] {
array.push(a);
return array;
}
/**
* Converts a list into an array.
*
* @complexity `O(n)`
* @category Folds
* @example
* toArray(list(0, 1, 2, 3, 4)); //=> [0, 1, 2, 3, 4]
*/
export function toArray<A>(l: List<A>): A[] {
return foldl<A, A[]>(arrayPush, [], l);
}
/**
* Inserts the given element at the given index in the list.
*
* @complexity O(log(n))
* @category Transformers
* @example
* insert(2, "c", list("a", "b", "d", "e")); //=> list("a", "b", "c", "d", "e")
*/
export function insert<A>(index: number, element: A, l: List<A>): List<A> {
return concat(append(element, slice(0, index, l)), slice(index, l.length, l));
}
/**
* Inserts the given list of elements at the given index in the list.
*
* @complexity `O(log(n))`
* @category Transformers
* @example
* insertAll(2, list("c", "d"), list("a", "b", "e", "f")); //=> list("a", "b", "c", "d", "e", "f")
*/
export function insertAll<A>(
index: number,
elements: List<A>,
l: List<A>
): List<A> {
return concat(
concat(slice(0, index, l), elements),
slice(index, l.length, l)
);
}
/**
* Reverses a list.
* @category Transformers
* @complexity O(n)
* @example
* reverse(list(0, 1, 2, 3, 4, 5)); //=> list(5, 4, 3, 2, 1, 0)
*/
export function reverse<A>(l: List<A>): List<A> {
return foldl((newL, element) => prepend(element, newL), empty(), l);
}
/**
* Returns `true` if the given argument is a list and `false`
* otherwise.
*
* @complexity O(1)
* @category Folds
* @example
* isList(list(0, 1, 2)); //=> true
* isList([0, 1, 2]); //=> false
* isList("string"); //=> false
* isList({ foo: 0, bar: 1 }); //=> false
*/
export function isList<A>(l: any): l is List<A> {
return typeof l === "object" && Array.isArray(l.suffix);
}
/**
* Iterate over two lists in parallel and collect the pairs.
*
* @complexity `O(log(n))`, where `n` is the length of the smallest
* list.
*
* @category Transformers
* @example
* const names = list("a", "b", "c", "d", "e");
* const years = list(0, 1, 2, 3, 4, 5, 6);
* //=> list(["a", 0], ["b", 1], ["c", 2], ["d", 3], ["e", 4]);
*/
export function zip<A, B>(as: List<A>, bs: List<B>): List<[A, B]> {
return zipWith((a, b) => [a, b] as [A, B], as, bs);
}
/**
* This is like mapping over two lists at the same time. The two lists
* are iterated over in parallel and each pair of elements is passed
* to the function. The returned values are assembled into a new list.
*
* The shortest list determines the size of the result.
*
* @complexity `O(log(n))` where `n` is the length of the smallest
* list.
* @category Transformers
* @example
* const names = list("Turing", "Curry");
* const years = list(1912, 1900);
* zipWith((name, year) => ({ name, year }), names, years);
* //=> list({ name: "Turing", year: 1912 }, { name: "Curry", year: 1900 });
*/
export function zipWith<A, B, C>(
f: (a: A, b: B) => C,
as: List<A>,
bs: List<B>
): List<C> {
const swapped = bs.length < as.length;
const iterator = (swapped ? as : bs)[Symbol.iterator]();
return map(
(a: any) => {
const b: any = iterator.next().value;
return swapped ? f(b, a) : f(a, b);
},
(swapped ? bs : as) as any
);
}
function isPrimitive(value: any): value is number | string {
return typeof value === "number" || typeof value === "string";
}
export type Ordering = -1 | 0 | 1;
function comparePrimitive<A extends number | string>(a: A, b: A): Ordering {
return a === b ? 0 : a < b ? -1 : 1;
}
export interface Ord {
"fantasy-land/lte"(b: any): boolean;
}
export type Comparable = number | string | Ord;
const ord = "fantasy-land/lte";
function compareOrd(a: Ord, b: Ord): Ordering {
return a[ord](b) ? (b[ord](a) ? 0 : -1) : 1;
}
/**
* Sorts the given list. The list should contain values that can be
* compared using the `<` operator or values that implement the
* Fantasy Land [Ord](https://github.com/fantasyland/fantasy-land#ord)
* specification.
*
* Performs a stable sort.
*
* @complexity O(n * log(n))
* @category Transformers
* @example
* sort(list(5, 3, 1, 8, 2)); //=> list(1, 2, 3, 5, 8)
* sort(list("e", "a", "c", "b", "d"); //=> list("a", "b", "c", "d", "e")
*/
export function sort<A extends Comparable>(l: List<A>): List<A> {
if (l.length === 0) {
return l;
} else if (isPrimitive(first(l))) {
return from(toArray(l).sort(comparePrimitive as any));
} else {
return sortWith(compareOrd, l as any) as any;
}
}
/**
* Sort the given list by comparing values using the given function.
* The function receieves two values and should return `-1` if the
* first value is stricty larger than the second, `0` is they are
* equal and `1` if the first values is strictly smaller than the
* second.
*
* Note that the comparison function is equivalent to the one required
* by
* [`Array.prototype.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).
*
* Performs a stable sort.
*
* @complexity O(n * log(n))
* @category Transformers
* @example
*
* sortWith((a, b) => {
* if (a === b) {
* return 0;
* } else if (a < b) {
* return -1;
* } else {
* return 1;
* }
* }, list(5, 3, 1, 8, 2)); //=> list(1, 2, 3, 5, 8)
*/
export function sortWith<A>(
comparator: (a: A, b: A) => Ordering,
l: List<A>
): List<A> {
const arr: { idx: number; elm: A }[] = [];
let i = 0;
forEach(elm => arr.push({ idx: i++, elm }), l);
arr.sort(({ elm: a, idx: i }, { elm: b, idx: j }) => {
const c = comparator(a, b);
return c !== 0 ? c : i < j ? -1 : 1;
});
let newL = emptyPushable<A>();
for (let i = 0; i < arr.length; ++i) {
push(arr[i].elm, newL);
}
return newL;
}
/**
* Sort the given list by passing each value through the function and
* comparing the resulting value. The function should either return
* values comparable using `<` or values that implement the Fantasy
* Land [Ord](https://github.com/fantasyland/fantasy-land#ord)
* specification.
*
* Performs a stable sort.
*
* @complexity O(n * log(n))
* @category Transformers
* @example
*
* sortBy(
* o => o.n,
* list({ n: 4, m: "foo" }, { n: 3, m: "bar" }, { n: 1, m: "baz" })
* ); //=> list({ n: 1, m: "baz" }, { n: 3, m: "bar" }, { n: 4, m: "foo" })
*
* sortBy(s => s.length, list("foo", "bar", "ba", "aa", "list", "z"));
* //=> list("z", "ba", "aa", "foo", "bar", "list")
*/
export function sortBy<A, B extends Comparable>(
f: (a: A) => B,
l: List<A>
): List<A> {
if (l.length === 0) {
return l;
}
const arr: { elm: A; prop: B; idx: number }[] = [];
let i = 0;
forEach(elm => arr.push({ idx: i++, elm, prop: f(elm) }), l);
const comparator: any = isPrimitive(arr[0].prop)
? comparePrimitive
: compareOrd;
arr.sort(({ prop: a, idx: i }, { prop: b, idx: j }) => {
const c = comparator(a, b);
return c !== 0 ? c : i < j ? -1 : 1;
});
let newL = emptyPushable<A>();
for (let i = 0; i < arr.length; ++i) {
push(arr[i].elm, newL);
}
return newL;
}
/**
* Returns a list of lists where each sublist's elements are all
* equal.
*
* @category Transformers
* @example
* group(list(0, 0, 1, 2, 2, 2, 3, 3)); //=> list(list(0, 0), list(1), list(2, 2, 2), list(3, 3))
*/
export function group<A>(l: List<A>): List<List<A>> {
return groupWith(elementEquals, l);
}
/**
* Returns a list of lists where each sublist's elements are pairwise
* equal based on the given comparison function.
*
* Note that only adjacent elements are compared for equality. If all
* equal elements should be grouped together the list should be sorted
* before grouping.
*
* @category Transformers
* @example
* const floorEqual = (a, b) => Math.round(a) === Math.round(b);
* groupWith(floorEqual, list(1.1, 1.3, 1.8, 2, 2.2, 3.3, 3.4));
* //=> list(list(1.1, 1.3), list(1.8, 2, 2.2), list(3.3, 3.4))
*
* const sameLength = (a, b) => a.length === b.length;
* groupWith(sameLength, list("foo", "bar", "ab", "bc", "baz"));
* //=> list(list("foo", "bar"), list("ab", "bc"), list("baz))
*/
export function groupWith<A>(
f: (a: A, b: A) => boolean,
l: List<A>
): List<List<A>> {
const result = emptyPushable<MutableList<A>>();
let buffer = emptyPushable<A>();
forEach(a => {
if (buffer.length !== 0 && !f(last(buffer)!, a)) {
push(buffer, result);
buffer = emptyPushable();
}
push(a, buffer);
}, l);
return buffer.length === 0 ? result : push(buffer, result);
}
/**
* Inserts a separator between each element in a list.
*
* @category Transformers
* @example
* intersperse("n", list("ba", "a", "a")); //=> list("ba", "n", "a", "n", "a")
*/
export function intersperse<A>(separator: A, l: List<A>): List<A> {
return pop(
foldl((l2, a) => push(separator, push(a, l2)), emptyPushable(), l)
);
}
/**
* Returns `true` if the given list is empty and `false` otherwise.
*
* @category Folds
* @example
* isEmpty(list()); //=> true
* isEmpty(list(0, 1, 2)); //=> false
*/
export function isEmpty(l: List<any>): boolean {
return l.length === 0;
} | the_stack |
import { addClassName } from "../../../../compat";
import isNonEmptyString from "../../../../utils/is_non_empty_string";
import objectAssign from "../../../../utils/object_assign";
import getParentElementsByTagName from "../get_parent_elements_by_tag_name";
import {
getStylingAttributes,
IStyleList,
IStyleObject,
} from "../get_styling";
import applyExtent from "./apply_extent";
import applyFontSize from "./apply_font_size";
import applyLineHeight from "./apply_line_height";
import applyOrigin from "./apply_origin";
import applyPadding from "./apply_padding";
import generateCSSTextOutline from "./generate_css_test_outline";
import ttmlColorToCSSColor from "./ttml_color_to_css_color";
// Styling which can be applied to <span> from any level upper.
// Added here as an optimization
const SPAN_LEVEL_ATTRIBUTES = [ "color",
"direction",
"display",
"fontFamily",
"fontSize",
"fontStyle",
"fontWeight",
"textDecoration",
"textOutline",
"unicodeBidi",
"visibility",
"wrapOption" ];
// TODO
// tts:showBackground (applies to region)
// tts:zIndex (applies to region)
/**
* Apply style set for a singular text span of the current cue.
* @param {HTMLElement} element - The text span
* @param {Object} style - The style to apply
*/
function applyTextStyle(
element : HTMLElement,
style : Partial<Record<string, string>>,
shouldTrimWhiteSpace : boolean
) {
// applies to span
const color = style.color;
if (isNonEmptyString(color)) {
element.style.color = ttmlColorToCSSColor(color);
}
// applies to body, div, p, region, span
const backgroundColor = style.backgroundColor;
if (isNonEmptyString(backgroundColor)) {
element.style.backgroundColor = ttmlColorToCSSColor(backgroundColor);
}
// applies to span
const textOutline = style.textOutline;
if (isNonEmptyString(textOutline)) {
const outlineData = textOutline
.trim()
.replace(/\s+/g, " ")
.split(" ");
const len = outlineData.length;
if (len === 3) {
const outlineColor = ttmlColorToCSSColor(outlineData[0]);
const thickness = outlineData[1];
element.style.textShadow =
generateCSSTextOutline(outlineColor, thickness);
} else if (isNonEmptyString(color) && len === 1) {
const thickness = outlineData[0];
element.style.textShadow = generateCSSTextOutline(color, thickness);
} else if (len === 2) {
const isFirstArgAColor = /^[#A-Z]/i.test(outlineData[0]);
const isFirstArgANumber = /^[0-9]/.test(outlineData[0]);
// XOR-ing to be sure we get what we have
if (isFirstArgAColor !== isFirstArgANumber) {
if (isFirstArgAColor) {
const outlineColor = ttmlColorToCSSColor(outlineData[0]);
const thickness = outlineData[1];
element.style.textShadow = generateCSSTextOutline(outlineColor, thickness);
} else if (isNonEmptyString(color)) {
const thickness = outlineData[0];
element.style.textShadow = generateCSSTextOutline(color, thickness);
}
}
}
}
// applies to span
const textDecoration = style.textDecoration;
if (isNonEmptyString(textDecoration)) {
switch (textDecoration) {
case "noUnderline":
case "noLineThrough":
case "noOverline":
element.style.textDecoration = "none";
break;
case "lineThrough":
element.style.textDecoration = "line-through";
break;
default:
element.style.textDecoration = textDecoration;
break;
}
}
// applies to span
const fontFamily = style.fontFamily;
if (isNonEmptyString(fontFamily)) {
switch (fontFamily) {
case "proportionalSansSerif":
element.style.fontFamily =
"Arial, Helvetica, Liberation Sans, sans-serif";
break;
// TODO monospace or sans-serif or font with both?
case "monospaceSansSerif":
case "sansSerif":
element.style.fontFamily = "sans-serif";
break;
case "monospaceSerif":
case "default":
element.style.fontFamily = "Courier New, Liberation Mono, monospace";
break;
// TODO font with both?
case "proportionalSerif":
element.style.fontFamily = "serif";
break;
default:
element.style.fontFamily = fontFamily;
}
}
// applies to span
const fontStyle = style.fontStyle;
if (isNonEmptyString(fontStyle)) {
element.style.fontStyle = fontStyle;
}
// applies to span
const fontWeight = style.fontWeight;
if (isNonEmptyString(fontWeight)) {
element.style.fontWeight = fontWeight;
}
// applies to span
const fontSize = style.fontSize;
if (isNonEmptyString(fontSize)) {
applyFontSize(element, fontSize);
} else {
addClassName(element, "proportional-style");
element.setAttribute("data-proportional-font-size", "1");
}
// applies to p, span
const direction = style.direction;
if (isNonEmptyString(direction)) {
element.style.direction = direction;
}
// applies to p, span
const unicodeBidi = style.unicodeBidi;
if (isNonEmptyString(unicodeBidi)) {
switch (unicodeBidi) {
case "bidiOverride":
element.style.unicodeBidi = "bidi-override";
break;
case "embed":
element.style.unicodeBidi = "embed";
break;
default:
element.style.unicodeBidi = "normal";
}
}
// applies to body, div, p, region, span
const visibility = style.visibility;
if (isNonEmptyString(visibility)) {
element.style.visibility = visibility;
}
// applies to body, div, p, region, span
const display = style.display;
if (display === "none") {
element.style.display = "none";
}
// applies to body, div, p, region, span
const wrapOption = style.wrapOption;
element.style.whiteSpace = wrapOption === "noWrap" ?
(shouldTrimWhiteSpace ? "nowrap" : "pre") :
(shouldTrimWhiteSpace ? "normal" : "pre-wrap");
}
/**
* Apply style for the general text track div.
* @param {HTMLElement} element - The <div> the style will be applied on.
* @param {Object} style - The general style object of the paragraph.
*/
function applyGeneralStyle(
element : HTMLElement,
style : Partial<Record<string, string>>
) {
// Set default text color. It can be overrided by text element color.
element.style.color = "white";
element.style.position = "absolute";
// applies to tt, region
const extent = style.extent;
if (isNonEmptyString(extent)) {
applyExtent(element, extent);
}
// applies to region
const writingMode = style.writingMode;
if (isNonEmptyString(writingMode)) {
// TODO
}
// applies to region
const overflow = style.overflow;
element.style.overflow = isNonEmptyString(overflow) ? overflow :
"hidden";
// applies to region
const padding = style.padding;
if (isNonEmptyString(padding)) {
applyPadding(element, padding);
}
// applies to region
const origin = style.origin;
if (isNonEmptyString(origin)) {
applyOrigin(element, origin);
}
// applies to region
const displayAlign = style.displayAlign;
if (isNonEmptyString(displayAlign)) {
element.style.display = "flex";
element.style.flexDirection = "column";
switch (displayAlign) {
case "before":
element.style.justifyContent = "flex-start";
break;
case "center":
element.style.justifyContent = "center";
break;
case "after":
element.style.justifyContent = "flex-end";
break;
}
}
// applies to region
const opacity = style.opacity;
if (isNonEmptyString(opacity)) {
element.style.opacity = opacity;
}
// applies to body, div, p, region, span
const visibility = style.visibility;
if (isNonEmptyString(visibility)) {
element.style.visibility = visibility;
}
// applies to body, div, p, region, span
const display = style.display;
if (display === "none") {
element.style.display = "none";
}
}
/**
* Apply style set for a <p> element
* @param {HTMLElement} element - The <p> element
* @param {Object} style - The general style object of the paragraph.
*/
function applyPStyle(
element : HTMLElement,
style : Partial<Record<string, string>>
) {
element.style.margin = "0px";
// applies to body, div, p, region, span
const paragraphBackgroundColor = style.backgroundColor;
if (isNonEmptyString(paragraphBackgroundColor)) {
element.style.backgroundColor = ttmlColorToCSSColor(paragraphBackgroundColor);
}
// applies to p
const lineHeight = style.lineHeight;
if (isNonEmptyString(lineHeight)) {
applyLineHeight(element, lineHeight);
}
// applies to p
const textAlign = style.textAlign;
if (isNonEmptyString(textAlign)) {
switch (textAlign) {
case "center":
element.style.textAlign = "center";
break;
case "left":
case "start":
// TODO check what start means (difference with left, writing direction?)
element.style.textAlign = "left";
break;
case "right":
case "end":
// TODO check what end means (difference with right, writing direction?)
element.style.textAlign = "right";
break;
}
}
}
/**
* Creates span of text for the given #text element, with the right style.
*
* TODO create text elements as string? Might help performances.
* @param {Element} el - the #text element, which text content should be
* displayed
* @param {Object} style - the style object for the given text
* @param {Boolean} shouldTrimWhiteSpace - True if the space should be
* trimmed.
* @returns {HTMLElement}
*/
function createTextElement(
el : Node,
style : Partial<Record<string, string>>,
shouldTrimWhiteSpace : boolean
) : HTMLElement {
const textElement = document.createElement("span");
let textContent = el.textContent === null ? "" :
el.textContent;
if (shouldTrimWhiteSpace) {
// 1. Trim leading and trailing whitespace.
// 2. Collapse multiple spaces into one.
let trimmed = textContent.trim();
trimmed = trimmed.replace(/\s+/g, " ");
textContent = trimmed;
}
textElement.innerHTML = textContent;
textElement.className = "rxp-texttrack-span";
applyTextStyle(textElement, style, shouldTrimWhiteSpace);
return textElement;
}
/**
* Generate every text elements to display in a given paragraph.
* @param {Element} paragraph - The <p> tag.
* @param {Array.<Object>} regions
* @param {Array.<Object>} styles
* @param {Object} paragraphStyle - The general style object of the paragraph.
* @param {Boolean} shouldTrimWhiteSpace
* @returns {Array.<HTMLElement>}
*/
function generateTextContent(
paragraph : Element,
regions : IStyleObject[],
styles : IStyleObject[],
paragraphStyle : Partial<Record<string, string>>,
shouldTrimWhiteSpace : boolean
) : HTMLElement[] {
/**
* Recursive function, taking a node in argument and returning the
* corresponding array of HTMLElement in order.
* @param {Node} node - the node in question
* @param {Object} style - the current state of the style for the node.
* /!\ The style object can be mutated, provide a copy of it.
* @param {Array.<Element>} spans - The spans parent of this node.
* @param {Boolean} shouldTrimWhiteSpaceFromParent - True if the space should be
* trimmed by default. From the parent xml:space parameter.
* @returns {Array.<HTMLElement>}
*/
function loop(
node : Node,
style : IStyleList,
spans : Node[],
shouldTrimWhiteSpaceFromParent : boolean
) : HTMLElement[] {
const childNodes = node.childNodes;
const elements : HTMLElement[] = [];
for (let i = 0; i < childNodes.length; i++) {
const currentNode = childNodes[i];
if (currentNode.nodeName === "#text") {
const { backgroundColor } = getStylingAttributes(["backgroundColor"],
spans,
styles,
regions);
if (isNonEmptyString(backgroundColor)) {
style.backgroundColor = backgroundColor;
} else {
delete style.backgroundColor;
}
const el = createTextElement(currentNode, style, shouldTrimWhiteSpaceFromParent);
elements.push(el);
} else if (currentNode.nodeName === "br") {
const br = document.createElement("BR");
elements.push(br);
} else if (currentNode.nodeName === "span" &&
currentNode.nodeType === Node.ELEMENT_NODE &&
currentNode.childNodes.length > 0)
{
const spaceAttribute = (currentNode as Element).getAttribute("xml:space");
const shouldTrimWhiteSpaceOnSpan =
isNonEmptyString(spaceAttribute) ? spaceAttribute === "default" :
shouldTrimWhiteSpaceFromParent;
// compute the new applyable style
const newStyle = objectAssign({},
style,
getStylingAttributes(SPAN_LEVEL_ATTRIBUTES,
[currentNode],
styles,
regions));
elements.push(...loop(currentNode,
newStyle,
[currentNode, ...spans],
shouldTrimWhiteSpaceOnSpan));
}
}
return elements;
}
return loop(paragraph,
objectAssign({}, paragraphStyle),
[],
shouldTrimWhiteSpace);
}
/**
* @param {Element} paragraph
* @param {Element} body
* @param {Array.<Object>} regions
* @param {Array.<Object>} styles
* @param {Object} paragraphStyle
* @param {Object}
* @returns {HTMLElement}
*/
export default function createElement(
paragraph : Element,
body : Element|null,
regions : IStyleObject[],
styles : IStyleObject[],
paragraphStyle : IStyleList,
{ cellResolution,
shouldTrimWhiteSpace } : { shouldTrimWhiteSpace : boolean;
cellResolution : { columns : number;
rows : number; }; }
) : HTMLElement {
const divs = getParentElementsByTagName(paragraph, "div");
const parentElement = document.createElement("DIV");
parentElement.className = "rxp-texttrack-region";
parentElement.setAttribute("data-resolution-columns",
String(cellResolution.columns));
parentElement.setAttribute("data-resolution-rows",
String(cellResolution.rows));
applyGeneralStyle(parentElement, paragraphStyle);
if (body !== null) {
// applies to body, div, p, region, span
const { bodyBackgroundColor } = getStylingAttributes(
["backgroundColor"], [...divs, body], styles, regions);
if (isNonEmptyString(bodyBackgroundColor)) {
parentElement.style.backgroundColor = ttmlColorToCSSColor(bodyBackgroundColor);
}
}
const pElement = document.createElement("p");
pElement.className = "rxp-texttrack-p";
applyPStyle(pElement, paragraphStyle);
const textContent = generateTextContent(
paragraph, regions, styles, paragraphStyle, shouldTrimWhiteSpace);
for (let i = 0; i < textContent.length; i++) {
pElement.appendChild(textContent[i]);
}
// NOTE:
// The following code is for the inclusion of div elements. This has no
// advantage for now, and might only with future evolutions.
// (This is only an indication of what the base of the code could look like).
// if (divs.length) {
// let container = parentElement;
// for (let i = divs.length - 1; i >= 0; i--) {
// // TODO manage style at div level?
// // They are: visibility, display and backgroundColor
// // All these do not have any difference if applied to the <p> element
// // instead of the div.
// // The advantage might only be for multiple <p> elements dispatched
// // in multiple div Which we do not manage anyway for now.
// const divEl = document.createElement("DIV");
// divEl.className = "rxp-texttrack-div";
// container.appendChild(divEl);
// container = divEl;
// }
// container.appendChild(pElement);
// parentElement.appendChild(container);
// } else {
// parentElement.appendChild(pElement);
// }
parentElement.appendChild(pElement);
return parentElement;
} | the_stack |
import React from "react";
import { x2c, y2r } from "../api/converters";
import { clip } from "../api/clipboard";
import {
blur,
clear,
escape,
select,
setEditingCell,
undo,
redo,
arrow,
walk,
write,
copy,
cut,
paste,
setSearchQuery,
setEntering,
} from "../store/actions";
import { CellOptionType } from "../types";
import { Renderer as DefaultRenderer } from "../renderers/core";
import { Parser as DefaultParser } from "../parsers/core";
import { EditorLayout } from "./styles/EditorLayout";
import { Context } from "../store";
import { stackOption } from "../api/arrays";
export const Editor: React.FC = () => {
const { store, dispatch } = React.useContext(Context);
const {
matrix,
editorRect,
cellsOption,
editingCell,
choosing,
selectingZone,
entering,
renderers,
parsers,
searchQuery,
editorRef,
searchInputRef,
editingOnEnter,
onSave,
} = store;
const [y, x] = choosing;
const rowId = `${y2r(y)}`;
const colId = x2c(x);
const cellId = `${colId}${rowId}`;
const [before, setBefore] = React.useState("");
const editing = editingCell === cellId;
if ((matrix && matrix[y] == null) || matrix[y][x] == null) {
return <div />;
}
const value = matrix[y][x];
const [numRows, numCols] = [matrix.length, matrix[0].length];
const defaultOption: CellOptionType = cellsOption.default || {};
const rowOption: CellOptionType = cellsOption[rowId] || {};
const colOption: CellOptionType = cellsOption[colId] || {};
const cellOption: CellOptionType = cellsOption[cellId] || {};
// defaultOption < rowOption < colOption < cellOption
const rendererKey = stackOption(cellsOption, y, x).renderer;
const parserKey = stackOption(cellsOption, y, x).parser;
const renderer = renderers[rendererKey || ""] || new DefaultRenderer();
const parser = parsers[parserKey || ""] || new DefaultParser();
const [top, left, height, width] = editorRect;
const writeCell = (value: string) => {
if (before !== value) {
dispatch(write(value));
}
setBefore("");
};
return (
<EditorLayout
className={`gs-editor ${editing ? "gs-editing" : ""}`}
style={editing ? { top, left, height, width } : {}}
>
<div className="gs-cell-label">{cellId}</div>
<textarea
autoFocus
draggable={false}
ref={editorRef}
style={{ height, width }}
rows={typeof value === "string" ? value.split("\n").length : 1}
onFocus={(e) => {
e.currentTarget.value = "";
}}
onDoubleClick={(e) => {
const input = e.currentTarget;
if (!editing) {
input.value = renderer.stringify(value);
setBefore(input.value);
dispatch(setEditingCell(cellId));
setTimeout(() => {
input.style.width = `${input.scrollWidth}px`;
const length = new String(input.value).length;
input.setSelectionRange(length, length);
}, 20);
}
}}
onBlur={(e) => {
if (editing) {
writeCell(e.target.value);
}
e.target.value = "";
dispatch(blur(null));
setTimeout(() => entering && e.target.focus(), 100);
}}
onKeyDown={(e) => {
const input = e.currentTarget;
const shiftKey = e.shiftKey;
switch (e.key) {
case "Tab": // TAB
e.preventDefault();
if (editing) {
writeCell(input.value);
dispatch(setEditingCell(""));
input.value = "";
}
dispatch(
walk({
numRows,
numCols,
deltaY: 0,
deltaX: shiftKey ? -1 : 1,
})
);
dispatch(setEditingCell(""));
return false;
case "Enter": // ENTER
if (editing) {
if (e.altKey) {
input.value = `${input.value}\n`;
input.style.height = `${input.clientHeight + 20}px`;
return false;
} else {
if (e.nativeEvent.isComposing) {
return false;
}
writeCell(input.value);
dispatch(setEditingCell(""));
input.value = "";
}
} else if (editingOnEnter && selectingZone[0] === -1) {
const dblclick = document.createEvent("MouseEvents");
dblclick.initEvent("dblclick", true, true);
input.dispatchEvent(dblclick);
e.preventDefault();
return false;
}
dispatch(
walk({
numRows,
numCols,
deltaY: shiftKey ? -1 : 1,
deltaX: 0,
})
);
// gridRef.current?.scrollToItem({ rowIndex: y + 1, align: "end" });
e.preventDefault();
return false;
case "Backspace": // BACKSPACE
if (!editing) {
dispatch(clear(null));
return false;
}
case "Shift": // SHIFT
return false;
case "Control": // CTRL
return false;
case "Alt": // OPTION
return false;
case "Meta": // COMMAND
return false;
case "NumLock": // NUMLOCK
return false;
case "Escape": // ESCAPE
dispatch(escape(null));
dispatch(setSearchQuery(undefined));
input.value = "";
// input.blur();
return false;
case "ArrowLeft": // LEFT
if (!editing) {
dispatch(
arrow({
shiftKey,
numRows,
numCols,
deltaY: 0,
deltaX: -1,
})
);
return false;
}
case "ArrowUp": // UP
if (!editing) {
dispatch(
arrow({
shiftKey,
numRows,
numCols,
deltaY: -1,
deltaX: 0,
})
);
return false;
}
case "ArrowRight": // RIGHT
if (!editing) {
dispatch(
arrow({
shiftKey,
numRows,
numCols,
deltaY: 0,
deltaX: 1,
})
);
return false;
}
case "ArrowDown": // DOWN
if (!editing) {
dispatch(
arrow({
shiftKey,
numRows,
numCols,
deltaY: 1,
deltaX: 0,
})
);
return false;
}
case "a": // A
if (e.ctrlKey || e.metaKey) {
if (!editing) {
e.preventDefault();
dispatch(select([0, 0, numRows - 1, numCols - 1]));
return false;
}
}
case "c": // C
if (e.ctrlKey || e.metaKey) {
if (!editing) {
e.preventDefault();
const area = clip(
selectingZone,
choosing,
matrix,
editorRef,
cellsOption,
renderers,
);
dispatch(copy(area));
input.focus(); // refocus
return false;
}
}
case "f": // F
if (e.ctrlKey || e.metaKey) {
if (!editing) {
e.preventDefault();
if (typeof searchQuery === "undefined") {
dispatch(setSearchQuery(""));
}
dispatch(setEntering(false));
setTimeout(() => searchInputRef.current?.focus(), 100);
return false;
}
}
case "r": // R
if (e.ctrlKey || e.metaKey) {
if (!editing) {
e.preventDefault();
dispatch(redo(null));
setTimeout(() => (input.value = ""), 100); // resetting textarea
return false;
}
}
case "s": // S
if (e.ctrlKey || e.metaKey) {
if (!editing) {
e.preventDefault();
onSave && onSave(matrix, cellsOption, {
pointing: choosing,
selectingFrom: [selectingZone[0], selectingZone[1]],
selectingTo: [selectingZone[2], selectingZone[3]],
});
return false;
}
}
case "v": // V
if (e.ctrlKey || e.metaKey) {
if (!editing) {
setTimeout(() => {
dispatch(paste({ text: input.value, parser }));
input.value = "";
}, 50);
return false;
}
}
case "x": // X
if (e.ctrlKey || e.metaKey) {
if (!editing) {
e.preventDefault();
const area = clip(
selectingZone,
choosing,
matrix,
editorRef,
cellsOption,
renderers,
);
dispatch(cut(area));
input.focus(); // refocus
return false;
}
}
case "z": // Z
if (e.ctrlKey || e.metaKey) {
if (!editing) {
e.preventDefault();
if (e.shiftKey) {
dispatch(redo(null));
setTimeout(() => (input.value = ""), 100); // resetting textarea
} else {
dispatch(undo(null));
}
return false;
}
}
case ";": // semicolon
if (e.ctrlKey || e.metaKey) {
if (!editing) {
e.preventDefault();
// MAYBE: need to aware timezone.
writeCell(new Date().toDateString());
}
}
}
if (e.ctrlKey || e.metaKey) {
return false;
}
input.style.width = `${input.scrollWidth}px`;
dispatch(setEditingCell(cellId));
return false;
}}
/>
</EditorLayout>
);
}; | the_stack |
import { createReadStream } from 'fs'
import { createServer, IncomingMessage, Server, ServerResponse } from 'http'
import { basename, extname, join, resolve } from 'path'
import { readdir, stat } from 'fs/promises'
import { types } from 'util'
const { isPromise } = types
const fontFamily = "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif"
export const escapeHtml = (unsafe: string) => {
if (unsafe && typeof unsafe === 'string')
return unsafe
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
return unsafe
}
export const makeHtml = (body: string, more: { head?: string[] } = {}) => {
const { head = [] } = more
return `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
${head.join('\n')}
</head>
<body>
${body}
</body>
</html>`
}
// https://github.com/nginx/nginx/blob/master/conf/mime.types
const mime = (fileName: string) => {
switch (extname(fileName)) {
case '.css':
return 'text/css'
case '.js':
return 'application/javascript'
case '.html':
return 'text/html'
case '.json':
return 'application/json'
case '.jpg':
case '.jpeg':
return 'image/jpeg'
case '.png':
return 'image/png'
case '.svg':
case '.svgz':
return 'image/svg+xml'
default:
return 'text/plain'
}
}
export type Path = string | RegExp
export type Method = 'any' | 'get' | 'patch' | 'post' | 'put' | 'delete'
export class Request extends IncomingMessage {
url!: string
params: { [param: string]: string } = {}
route!: Omit<Route, 'handler'>
}
export class Response extends ServerResponse {
public status(statusCode: number) {
this.statusCode = statusCode
return this
}
private __send(body: string, contentType = 'text/plain') {
this.writeHead(this.statusCode || 200, { 'Content-Type': contentType })
this.end(body)
}
public get send() {
return {
html: (html: string) => {
this.__send(html, 'text/html')
},
text: (text: string) => {
this.__send(text, 'text/plain')
},
json: (json: object) => {
this.__send(JSON.stringify(json), 'application/json')
},
/**
* Send a file.
* Pass a relativePath (without leading slash) or an absolute path
*
* @example
* // absolute path
* res.send.file(join(resolve(), 'assets/styles.css')))
* // relative path
* res.send.file('assets/styles.css')
*/
file: async (filePath: string) => {
let isFile = false
try {
// check file
const stats = await stat(filePath)
isFile = stats.isFile()
if (!isFile) return new Error()
// prepare response
const contentType = mime(filePath)
this.writeHead(200, { 'Content-Type': contentType })
// send file
createReadStream(filePath).pipe(this, { end: true })
} catch (err: any) {
return err
}
}
}
}
}
export type Context = {
req: Request
res: Response
}
export interface NextFunction {
(err?: any): void
}
export interface Handler {
(ctx: Context): void | Promise<any>
}
export interface ExpressHandler {
(req: Request, res: Response, next: NextFunction): void | Promise<any>
}
interface Route {
handler: Handler | ExpressHandler
path: Path
method?: Method
isMiddleware?: boolean
}
export type Routes = (Route | Handler)[]
type UseMiddleware = {
(handler: ExpressHandler): void
(path: Path, handler: ExpressHandler): void
}
export class Router {
private _routes: Routes = []
get route() {
/** Add a middleware */
const use: UseMiddleware = (a: Path | ExpressHandler, b?: ExpressHandler): void => {
if (typeof a === 'string' && typeof b === 'function') {
this.routes.add({ path: a, handler: b, isMiddleware: true })
} else if (a instanceof RegExp && typeof b === 'function') {
this.routes.add({ path: a, handler: b, isMiddleware: true })
} else if (typeof a === 'function') {
this.routes.add({ path: '/', handler: a, isMiddleware: true })
}
}
return {
use: use,
add: (method: Method, path: Path, handler: Handler) => {
this.routes.add({ method, path, handler })
},
any: (path: Path, handler: Handler) => this.route.add('any', path, handler),
get: (path: Path, handler: Handler) => this.route.add('get', path, handler),
patch: (path: Path, handler: Handler) => this.route.add('patch', path, handler),
post: (path: Path, handler: Handler) => this.route.add('post', path, handler),
put: (path: Path, handler: Handler) => this.route.add('put', path, handler),
delete: (path: Path, handler: Handler) => this.route.add('delete', path, handler)
}
}
get routes() {
return {
add: (route: Handler | Route) => {
// if has params, convert to RegEx
if (typeof route !== 'function' && typeof route.path === 'string' && route.path.includes('/:')) {
try {
route.path = route.path.replace('/', '\\/')
route.path = route.path.replace(/\/:([^/]+)/gm, '\\/(?<$1>[^\\/]+)')
route.path = new RegExp(`^${route.path}$`, 'gm')
} catch (err: any) {
console.log('WARNING:', err.message)
}
}
this._routes.push(route)
}
}
}
async handle(req: Request, res: Response) {
const method = req.method?.toLowerCase() as Method
routesLoop: for (let i = 0; i < this._routes.length; i++) {
if (res.headersSent) break routesLoop
const route = this._routes[i]
const url = req.url as string
const pathIsRegex = typeof route !== 'function' && route.path instanceof RegExp && url.match(route.path) !== null
const pathIsExact = typeof route !== 'function' && route.path === req.url
const pathMatches = typeof route !== 'function' && typeof route.path === 'string' && url.startsWith(route.path)
// is handle without path
if (typeof route === 'function') {
await route({ req, res })
} else {
// pass some data to the request
const { handler, ...rest } = route
req.route = rest
// is middleware
if (route.isMiddleware) {
if (pathMatches) {
const next = (err?: any) => {} // console.log('FROM NEXT', err)
const handle = (route.handler as ExpressHandler)(req, res, next)
if (isPromise(handle))
try {
await handle
} catch (err) {
return next(err)
}
}
}
// is route
else if (pathIsExact || pathIsRegex) {
// get all regex capture groups and pass them as params to req.params
if (pathIsRegex) {
//const array = [...req.url.matchAll(route.path as RegExp)]
const matches = req.url.matchAll(route.path as RegExp)
for (const match of matches) {
req.params = { ...match.groups }
}
}
if (route.method === method) await (route.handler as Handler)({ req, res })
else if (route.method === 'any') await (route.handler as Handler)({ req, res })
}
}
}
}
}
export class TinyServer {
public router = new Router()
private server!: Server
/** alias for this.router.route */
public r = this.router.route
constructor() {}
/**
* Serve static files.
* @param directory Has to be an absolute path.
*/
static static(directory: string) {
return (async (req, res, next) => {
if (req.route.path instanceof RegExp) return next('Static middleware does not accept "RegExp" paths.')
const pathName = new URL(req.url, `http://${req.headers.host}`).pathname
const filePath = join(directory, pathName.substring(req.route.path.length))
try {
await res.send.file(filePath)
} catch (err) {
return next(err)
}
}) as ExpressHandler
}
private createServer(): Server {
const server = createServer({ IncomingMessage: Request, ServerResponse: Response }, async (_req, _res) => {
const req = <Request>_req
const res = <Response>_res
const result = (await this.router.handle(req, res)) as any
// notfound/error
if (!res.headersSent) {
if (result instanceof Error) {
res.status(500).send.text('500: Error')
} else {
res.status(404).send.text('404: Not Found')
}
}
})
return server
}
public listen(port: number): Promise<void> {
return new Promise(resolve => {
this.server = this.createServer()
this.server.listen(port, () => {
// graceful shutdown
process.on('SIGTERM', async () => {
console.log('Server is closing...')
await this.close()
})
resolve()
})
})
}
public close(): Promise<void> {
return new Promise(resolve => {
this.server.close(() => {
resolve()
})
})
}
}
interface ServeExplorerConfig {
dotFiles?: boolean
}
export const ServeExplorer = (config: ServeExplorerConfig = {}) => {
const { dotFiles = false } = config
return async (req: Request, res: Response, next: NextFunction) => {
const absolutePath = join(resolve(), req.url)
const stats = await stat(absolutePath)
// isFile()
if (await stats.isFile()) {
return res.send.file(absolutePath)
}
// isDirectory()
if (await stats.isDirectory()) {
let files = await readdir(absolutePath)
if (!dotFiles) files = files.filter(f => !basename(f).startsWith('.'))
const html = `
<style>
html {
margin: 0;
padding: 0;
}
body {
font-family: ${fontFamily};
margin: 0;
padding: 2.5% 5%;
}
h1 {
margin-left: 24px;
font-size: 26px;
}
ul {
display: flex;
flex-direction: column;
list-style: none;
}
li {
padding: 4px 0px;
}
li::before {
content: "\\2022";
color: black;
display: inline-block;
width: 1em;
margin-left: -1em;
}
li.directory::before {
font-weight:bold;
content: "/";
}
a {
color: blue;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
<h1>${req.url.split('/').join(' / ')}</h1>
<ul>
${files
.sort((a: string, b: string) => {
if (!extname(a) && !extname(b)) return 0
if (!extname(a)) return -1
else return 1
})
.map(f => {
const url = `${req.url}/${f}`.replace(/\/+/gm, '/')
return `<li class="${!extname(f) ? 'directory' : ''}"><a href="${url}">${f}</a></li>`
})
.join('')}
</ul>`
return res.send.html(makeHtml(html))
}
next()
}
}
/**
* quick testing section
*/
// const logger: ExpressHandler = (req, res, next) => {
// console.log('LOG:', req.url)
// }
// const main = async () => {
// const s = new TinyServer()
// s.r.use(ServeExplorer())
// s.r.get('/user/:user/:id/hello', async ({ req, res }) => {
// // console.log('Params:', req.url, req.params)
// res.send.text(`user ${req.params.user}`)
// })
// s.r.use('/static', TinyServer.static(join(resolve(), 'readme')))
// s.r.use(logger)
// s.r.get('/', ctx => {
// return ctx.res.send.text('hello')
// })
// await s.listen(7000)
// console.log('listening on http://localhost:7000/')
// }
// main() | the_stack |
import path from "path";
import COMMON_CONFIG from "./config";
import {log, BaseSpider, CategoryItem} from "./base";
import PromiseTool from 'bluebird';
interface TableItem {
category: string; // 分类
images: string[];
torrents: string[];
}
const Sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
/**
* 解析列表页,获取种子链接,下载种子文件
*/
export default class ParseTableList extends BaseSpider {
currentPage: number = ~~process.env.START_PAGE || 1; //当前页数
jsonPath: string = ""; // 列表页结果路径
tableList: any = {}; // 当前分类下的列表页
parseAllCategory: boolean;
categoryIndex: number;
parseListUrl: string;
categoryList: any;
constructor(
categoryIndex: number = 0,
parseAllCategory: boolean = false,
parseListUrl: string = "",
categoryList: any = {}
) {
super();
this.parseAllCategory = parseAllCategory; // 是否解析所有分类
this.parseListUrl = parseListUrl; // 当前解析的 url
this.categoryIndex = categoryIndex; // 当前爬取的分类
this.categoryList = categoryList;
if (this.isEmpty(categoryList)) {
console.log("分类列表为空,请重新启动!");
return;
}
this.startTimeCount();
this.recursionExecutive();
}
/**
* 入口
*/
recursionExecutive() {
if (this.categoryIndex >= Object.keys(this.categoryList).length) {
console.log("全部爬取完毕!");
this.endTimeCount();
return false;
}
let currentCategory: string = this.getCurrentCategory();
this.parseListUrl = this.parseListUrl || currentCategory;
this.jsonPath =
COMMON_CONFIG.tableList +
"/" +
currentCategory.split("?").pop() +
".json";
this.tableList = this.readJsonFile(this.jsonPath) || {};
this.generateDirectory(this.getParentDirectory());
this.innerRecursion();
}
/**
* 列表页面请求
*/
async innerRecursion() {
console.log("爬取列表中...");
let connectTasks: number = COMMON_CONFIG.connectTasks;
let endPage: number = ~~this.getEndPage();
let currentPage: number = this.currentPage;
if (this.currentPage > endPage) {
this.endInnerRecursion();
return false;
}
console.log(currentPage);
let pageLimit: number = Math.min(endPage, currentPage + connectTasks);
let requestUrls: string[] = [];
for (let i = currentPage; i <= pageLimit; i++) {
let requestUrl = COMMON_CONFIG.baseUrl + this.parseListUrl;
if (i > 1) {
requestUrl += "&page=" + i;
}
requestUrls.push(requestUrl);
}
PromiseTool.map(requestUrls, async (url: string) => {
return await this.requestPage(url);
}, {
concurrency: COMMON_CONFIG.connectTasks
}).then((results: any) => {
let detailLinks: string[] = [];
let repeatCount: number = 0;
for (let result of results) {
let {links, repeat} = this.parseHtml(result);
repeatCount = repeatCount + ~~repeat;
detailLinks = [...detailLinks, ...links];
}
detailLinks = this.filterRepeat(detailLinks);
let isRepeat =
repeatCount >
(COMMON_CONFIG.connectTasks * COMMON_CONFIG.pageSize) / 2;
this.getDetailPage(detailLinks, isRepeat);
}
);
}
/**
*
* 请求详情页面
* @param {string[]} detailLinks
* @param {boolean} isRepeat
* @memberof ParseTableList
*/
async getDetailPage(detailLinks: string[], isRepeat: boolean) {
console.log("爬取种子中...");
let tableList = this.tableList;
for (let link of detailLinks) {
// 详情页已经爬取了,直接下载种子
if (tableList[link] && tableList[link].title) {
let directory =
this.getParentDirectory() +
"/" +
this.filterIllegalPath(tableList[link].title);
await this.downloadResult(
directory,
tableList[link].torrents,
tableList[link].images
);
} else {
let result = await this.requestPage(COMMON_CONFIG.baseUrl + link);
await this.parseDetailHtml(result, link);
}
await Sleep(100);
}
this.endDetailRecursion(isRepeat);
}
isParentCategory() {
let lists = Object.keys(this.categoryList);
return lists.includes(this.parseListUrl);
}
/**
* 获取列表页面的结束页面
*/
getEndPage() {
let currentCategory = this.getCurrentCategory();
if (this.isParentCategory()) {
return this.categoryList[currentCategory].endPage;
} else {
let childCategory = this.categoryList[currentCategory].childCategory;
let item = childCategory.find((v: CategoryItem): boolean => v.link === this.parseListUrl);
return Math.min(item.endPage, COMMON_CONFIG.connectTasks);
}
}
/**
* 获取父文件夹路径
*
*/
getParentDirectory() {
let temp = "";
let currentCategory = this.getCurrentCategory();
if (!this.isParentCategory()) {
let childCategory = this.categoryList[currentCategory].childCategory;
let item =
childCategory.find((v: CategoryItem): boolean => v.link === this.parseListUrl) || {};
temp = "_" + item.title;
}
return (
COMMON_CONFIG.result +
"/" +
this.categoryList[currentCategory].title +
temp
);
}
/**
* 结束详情页递归
* @param {Boolean} isRepeat 是否重复
*/
endDetailRecursion(isRepeat: boolean) {
this.currentPage += COMMON_CONFIG.connectTasks;
if (isRepeat) {
this.currentPage = COMMON_CONFIG.connectTasks + this.getTotalCount();
}
this.innerRecursion();
}
/**
* 获取已经爬取的页数
*/
getTotalCount() {
let totalLen = 0;
let tableList = this.tableList;
if (!this.isParentCategory()) {
for (let key in tableList) {
if (tableList[key].category === this.parseListUrl) {
totalLen++;
}
}
console.log("根据已有数据更新页数", totalLen);
} else {
totalLen = Object.keys(tableList).length;
}
return Math.ceil(totalLen / COMMON_CONFIG.pageSize);
}
/**
* 获取当前的分类
*/
getCurrentCategory() {
return Object.keys(this.categoryList)[this.categoryIndex];
}
/**
* 判断是否爬取所有分类的列表页面
*/
endInnerRecursion() {
if (this.parseAllCategory) {
this.currentPage = 1;
this.categoryIndex++;
this.parseListUrl = this.getCurrentCategory();
this.recursionExecutive();
} else {
console.log("爬取完毕!");
this.endTimeCount();
}
}
/**
* 解析列表页面
* @param {Object} $ cheerio 对象
*/
parseHtml($: any) {
let trDoms = $("#ajaxtable tr");
let detailLinks: string[] = [];
let repeatCount: number = 0;
let tableList: any = this.tableList;
let category: string = this.parseListUrl;
let isParentCategory = this.isParentCategory();
let currentCategory = this.getCurrentCategory();
trDoms.each(function () {
// 详情页面链接
let link = $(this)
.find("h3>a")
.eq(0)
.attr("href");
if (link && tableList[link]) {
repeatCount++;
}
if (link) {
detailLinks.push(link);
tableList[link] = {
category: isParentCategory ? currentCategory : category, // 分类
images: [],
torrents: []
};
}
});
this.updateTableList();
return {
links: detailLinks,
repeat: repeatCount === trDoms.length
};
}
/**
* 解析详情页面
* @param {Object} $ cheerio 对象
* @param {String} seed 详情页链接
*/
async parseDetailHtml($: any, seed: string) {
if (!$) {
return;
}
let torrents: string[] = [];
/**
* 获取页面上的每一个链接
* 不放过任何一个种子,是不是很贴心!!
*/
$("body a").each(function () {
let href = $(this).attr("href");
if (href && COMMON_CONFIG.seedSite.some(item => href.includes(item))) {
torrents.push(href);
}
});
// 去重
torrents = this.filterRepeat(torrents);
let images: string[] = [];
$("#td_tpc img").each(function () {
let src = $(this).attr("src");
let extName = path.extname(src);
const extList = [".jpg", ".png", ".jpeg", ".gif", ".bmp"];
// 去掉无效的图片下载链接
if (src && extList.includes(extName)) {
images.push(src);
}
});
images = this.filterRepeat(images);
// title 字段非空,可以在下次不用爬取该页面,直接下载种子文件
let title =
$("#td_tpc h1")
.eq(0)
.text() || "已经爬取了该详情页" + ~~(Math.random() * 1e5);
// 存放爬取结果,下次直接下载种子文件
let tableList = this.tableList;
tableList[seed] = Object.assign(tableList[seed], {
title,
torrents,
images
});
this.updateTableList();
let directory =
this.getParentDirectory() + "/" + this.filterIllegalPath(title);
await this.downloadResult(directory, torrents, images);
}
/**
* 更新列表数据
*/
updateTableList() {
this.updateJsonFile(this.tableList, this.jsonPath, false);
}
} | the_stack |
import {EntityConfig} from "../../config/entity.config";
import {DataEntityType} from "../entity/data-entity.base";
import {combineLatest, defer, merge, Observable, of, Subject, throwError} from "rxjs";
import {IRepository} from "./repository.interface";
import {ModelBase} from "../../config/model.base";
import {EntityModelBase} from "../../config/entity-model.base";
import {Paris} from "../../paris";
import {HttpOptions, RequestMethod, SaveRequestMethod} from "../../data_access/http.service";
import {SaveEntityEvent} from "../events/save-entity.event";
import {RemoveEntitiesEvent} from "../events/remove-entities.event";
import {ReadonlyRepository} from "./readonly-repository";
import {AjaxError} from "rxjs/ajax";
import {catchError, map, mergeMap, tap} from "rxjs/operators";
import {findIndex, flatMap} from "lodash-es";
import {DataSet} from "../../data_access/dataset";
/**
* A Repository is a service through which all of an Entity's data is fetched, cached and saved back to the backend.
*
* This class handles entities that can be added, updated or removed. see `ReadonlyRepository` base class.
*/
export class Repository<TEntity extends ModelBase, TRawData = any> extends ReadonlyRepository<TEntity, TRawData> implements IRepository<TEntity> {
save$: Observable<SaveEntityEvent>;
remove$: Observable<RemoveEntitiesEvent>;
private _saveSubject$: Subject<SaveEntityEvent>;
private _removeSubject$: Subject<RemoveEntitiesEvent>;
constructor(entityConstructor: DataEntityType<TEntity>,
paris: Paris) {
super(entityConstructor, paris);
const getAllItems$: Observable<Array<TEntity>> = defer(() => this.query().pipe(map((dataSet:DataSet<TEntity>) => dataSet.items)));
this._allItemsSubject$ = new Subject<Array<TEntity>>();
this._allItems$ = merge(getAllItems$, this._allItemsSubject$.asObservable());
this._saveSubject$ = new Subject();
this._removeSubject$ = new Subject();
this.save$ = this._saveSubject$.asObservable();
this.remove$ = this._removeSubject$.asObservable();
}
get entity():EntityConfig<TEntity, TRawData> {
return <EntityConfig<TEntity>>this.entityConstructor.entityConfig;
}
/**
* Saves an entity to the server
* @param item
* @param {HttpOptions} options
* @param {any} serializationData Any data to pass to serialize or serializeItem
*/
save(item: Partial<TEntity>, options?:HttpOptions, serializationData?:any): Observable<TEntity> {
if (!this.entityBackendConfig.endpoint)
throw new Error(`Entity ${this.entityConstructor.entityConfig.singularName || this.entityConstructor.name} can't be saved - it doesn't specify an endpoint.`);
try {
const isNewItem:boolean = item.id === undefined;
const saveData: TRawData = this.serializeItem(item, serializationData);
const endpointName:string = this.getEndpointName(options && options.params ? { where: options.params } : null);
const endpoint:string = this.entityBackendConfig.parseSaveQuery ? this.entityBackendConfig.parseSaveQuery(item, this.entity, this.paris.config, options) : `${endpointName}/${item.id || ''}`;
let httpOptions = this.addCustomHeaders(item);
(<any>httpOptions).data = saveData;
return this.paris.dataStore.save(endpoint, this.getSaveMethod(item), Object.assign({}, options, httpOptions), this.getBaseUrl(options && {where: options.params}))
.pipe(
catchError((err: AjaxError) => {
this.emitEntityHttpErrorEvent(err);
throw err;
}),
mergeMap((savedItemData: TRawData) =>
savedItemData ? this.createItem(savedItemData) : of(null)),
tap((savedItem: TEntity) => {
if (savedItem && this._allValues) {
this._allValues = [...this._allValues, savedItem];
this._allItemsSubject$.next(this._allValues);
}
this._saveSubject$.next({ entity: this.entityConstructor, newValue: item, isNew: isNewItem });
})
);
}
catch(e){
return throwError(e);
}
}
private getSaveMethod(item:Partial<TEntity>):SaveRequestMethod{
return this.entityBackendConfig.saveMethod
? this.entityBackendConfig.saveMethod instanceof Function ? this.entityBackendConfig.saveMethod(item, this.paris.config) : this.entityBackendConfig.saveMethod
: item.id === undefined ? "POST" : "PUT";
}
/**
* Saves multiple items to the server, all at once
* @param {Array<T extends EntityModelBase>} items
* @returns {Observable<Array<T extends EntityModelBase>>}
*/
saveItems(items:Array<TEntity>, options?:HttpOptions):Observable<Array<TEntity>>{
if (!this.entityBackendConfig.endpoint)
throw new Error(`${this.entity.pluralName} can't be saved - it doesn't specify an endpoint.`);
let newItems:SaveItems = { method: "POST", items: [] },
existingItems:SaveItems = { method: "PUT", items: [] };
items.forEach((item:any) => {
let saveMethod:RequestMethod = this.getSaveMethod(item);
(saveMethod === "POST" ? newItems : existingItems).items.push(this.serializeItem(item));
});
let saveItemsArray:Array<Observable<Array<TEntity>>> = [newItems, existingItems]
.filter((saveItems:SaveItems) => saveItems.items.length)
.map((saveItems:SaveItems) => this.doSaveItems(saveItems.items, saveItems.method, options));
return combineLatest.apply(this, saveItemsArray).pipe(
map((savedItems:Array<Array<TEntity>>) => flatMap(savedItems)),
tap((savedItems:Array<TEntity>) => {
if (savedItems && savedItems.length && this._allValues) {
let itemsAdded: Array<TEntity> = [];
savedItems.forEach((item:TEntity) => {
const originalItemIndex:number = findIndex(this._allValues,_item => item.id === _item.id);
if (!!~originalItemIndex)
this._allValues[originalItemIndex] = item;
else itemsAdded.push(item);
});
if (itemsAdded.length)
this._allValues = [...this._allValues, ...itemsAdded];
this._allItemsSubject$.next(this._allValues);
this._saveSubject$.next({ entity: this.entityConstructor, newValue: savedItems, isNew: !!itemsAdded });
}
})
);
}
/**
* Does the actual saving to server for a list of items.
* @param {Array<any>} itemsData
* @param {"PUT" | "POST"} method
* @returns {Observable<Array<T extends EntityModelBase>>}
*/
private doSaveItems(itemsData:Array<any>, method:"PUT" | "POST", options?:HttpOptions):Observable<Array<TEntity>>{
const saveHttpOptions:HttpOptions = this.entity.parseSaveItemsQuery
? this.entity.parseSaveItemsQuery(itemsData, options, this.entity, this.paris.config)
: Object.assign({}, options, {data: {items: itemsData}});
const endpointName:string = this.getEndpointName(options && options.params ? { where: options.params } : null);
let currentOptions = this.addCustomHeaders(itemsData);
return this.paris.dataStore.save(`${endpointName}/`, method, Object.assign({}, saveHttpOptions, currentOptions), this.getBaseUrl(options && {where: options.params}))
.pipe(
catchError((err: AjaxError) => {
this.emitEntityHttpErrorEvent(err);
throw err
}),
mergeMap((savedItemsData?: Array<any> | {items:Array<any>}) => {
if (!savedItemsData)
return of([]);
let itemsData:Array<any> = savedItemsData instanceof Array ? savedItemsData : savedItemsData.items;
let itemCreators:Array<Observable<TEntity>> = itemsData.map(savedItemData => this.createItem(savedItemData));
return combineLatest(itemCreators);
})
)
}
/**
* Sends a DELETE request to the backend for deleting an item.
*/
removeItem(item:TEntity, options?:HttpOptions):Observable<TEntity>{
if (!item)
return of(null);
if (!this.entityBackendConfig.endpoint)
throw new Error(`Entity ${this.entity.singularName} can't be deleted - it doesn't specify an endpoint.`);
try {
let httpOptions:HttpOptions = options || { data: {}};
if (!httpOptions.data)
httpOptions.data = {};
let currentOptions = this.addCustomHeaders(item);
if (this.entityBackendConfig.getRemoveData)
Object.assign(httpOptions.data, this.entityBackendConfig.getRemoveData([item]));
const endpointName:string = this.getEndpointName(options && options.params ? { where: options.params } : null);
const endpoint:string = this.entityBackendConfig.parseRemoveQuery ? this.entityBackendConfig.parseRemoveQuery([item], this.entity, this.paris.config) : `${endpointName}/${item.id || ''}`;
return this.paris.dataStore.delete(endpoint, Object.assign({}, httpOptions, currentOptions), this.getBaseUrl(options && {where: options.params}))
.pipe(
catchError((err: AjaxError) => {
this.emitEntityHttpErrorEvent(err);
throw err;
}),
tap(() => {
if (this._allValues) {
let itemIndex:number = findIndex(this._allValues, (_item:TEntity) => _item.id === item.id);
if (~itemIndex)
this._allValues.splice(itemIndex, 1);
this._allItemsSubject$.next(this._allValues);
}
this._removeSubject$.next({ entity: this.entityConstructor, items: [item] });
}),
map(() => item)
)
}
catch(e){
return throwError(e);
}
}
/**
* Sends a DELETE request to the backend for deleting multiple entities.
* @param {Array<TEntity extends ModelBase>} items
* @param {HttpOptions} options
* @returns {Observable<Array<TEntity extends ModelBase>>}
*/
remove(items:Array<TEntity>, options?:HttpOptions):Observable<Array<TEntity>>{
if (!items)
throw new Error(`No ${this.entity.pluralName.toLowerCase()} specified for removing.`);
if (!(items instanceof Array))
items = [items];
if (!items.length)
return of([]);
if (!this.entityBackendConfig.endpoint)
throw new Error(`Entity ${this.entity.singularName} can't be deleted - it doesn't specify an endpoint.`);
try {
let httpOptions:HttpOptions = options || { data: {}};
if (!httpOptions.data)
httpOptions.data = {};
let currentOptions = this.addCustomHeaders(items);
Object.assign(httpOptions.data, this.entityBackendConfig.getRemoveData
? this.entityBackendConfig.getRemoveData(items)
: { ids: items.map(item => item.id) }
);
const endpointName:string = this.getEndpointName(options && options.params ? { where: options.params } : null);
const endpoint:string = this.entityBackendConfig.parseRemoveQuery ? this.entityBackendConfig.parseRemoveQuery(items, this.entity, this.paris.config) : endpointName;
return this.paris.dataStore.delete(endpoint, Object.assign({}, httpOptions, currentOptions), this.getBaseUrl(options && {where: options.params}))
.pipe(
catchError((err: AjaxError) => {
this.emitEntityHttpErrorEvent(err);
throw err;
}),
tap(() => {
if (this._allValues) {
items.forEach((item:TEntity) => {
let itemIndex:number = findIndex(this._allValues, (_item:TEntity) => _item.id === item.id);
if (~itemIndex)
this._allValues.splice(itemIndex, 1);
});
this._allItemsSubject$.next(this._allValues);
}
this._removeSubject$.next({ entity: this.entityConstructor, items: items });
}),
map(() => items)
)
}
catch(e){
return throwError(e);
}
}
}
interface SaveItems{
method: "POST" | "PUT",
items:Array<any>
} | the_stack |
import { config } from "../../config";
import { RunStrategy, IRunStrategyResult, ILoadResult } from "./RunStrategy";
import { Page } from "puppeteer";
import { events } from "../events";
import { sleep } from "../../utils/utils";
import { IQuery } from "../query";
import { logger } from "../../logger/logger";
import { urls } from "../constants";
export const selectors = {
container: '.jobs-search-two-pane__container',
chatPanel: '.msg-overlay-list-bubble',
jobs: 'div.job-card-container',
links: 'a.job-card-container__link',
title: '.artdeco-entity-lockup__title',
companies: '.artdeco-entity-lockup__subtitle',
places: '.artdeco-entity-lockup__caption',
dates: 'time',
description: '.jobs-description',
detailsPanel: '.jobs-search__job-details--container',
detailsTop: '.jobs-details-top-card',
details: '.jobs-details__main-content',
criteria: '.jobs-box__group h3',
pagination: '.jobs-search-two-pane__pagination',
paginationNextBtn: 'li[data-test-pagination-page-btn].selected + li',
paginationBtn: (index: number) => `li[data-test-pagination-page-btn="${index}"] button`,
};
/**
* @class LoggedInRunStrategy
* @extends RunStrategy
*/
export class LoggedInRunStrategy extends RunStrategy {
/**
* Check if session is authenticated
* @param {Page} page
* @returns {Promise<boolean>}
* @returns {Promise<ILoadResult>}
* @static
* @private
*/
private static _isAuthenticatedSession = async (page: Page): Promise<boolean> => {
const cookies = await page.cookies();
return cookies.some(e => e.name === "li_at");
};
/**
* Try to load job details
* @param {Page} page
* @param {string} jobId
* @param {number} timeout
* @static
* @private
*/
private static _loadJobDetails = async (
page: Page,
jobId: string,
timeout: number = 2000,
): Promise<ILoadResult> => {
const pollingTime = 100;
let elapsed = 0;
let loaded = false;
await sleep(pollingTime); // Baseline to wait
while(!loaded) {
loaded = await page.evaluate(
(jobId, panelSelector, descriptionSelector) => {
const detailsPanel = document.querySelector(panelSelector);
const description = document.querySelector(descriptionSelector);
return detailsPanel && detailsPanel.innerHTML.includes(jobId) &&
description && description.innerText.length > 0;
},
jobId,
selectors.detailsPanel,
selectors.description,
);
if (loaded) return { success: true };
await sleep(pollingTime);
elapsed += pollingTime;
if (elapsed >= timeout) {
return {
success: false,
error: `Timeout on loading job details`
};
}
}
return { success: true };
}
/**
* Try to paginate
* @param {Page} page
* @param {number} timeout
* @param {string} tag
* @returns {Promise<ILoadResult>}
* @static
* @private
*/
private static _paginate = async (
page: Page,
tag: string,
timeout: number = 2000,
): Promise<ILoadResult> => {
// Check if there is a new page to load
try {
await page.waitForSelector(selectors.paginationNextBtn, {timeout: timeout});
}
catch(err) {
return {
success: false,
error: `There are no more pages to visit`
};
}
const url = new URL(page.url());
// Extract offset from url
let offset = parseInt(url.searchParams.get('start') || "0", 10);
offset += 25;
// Update offset in url
url.searchParams.set('start', '' + offset);
logger.debug(tag, "Opening", url.toString());
// Navigate new url
await page.goto(url.toString(), {
waitUntil: 'load',
});
const pollingTime = 100;
let elapsed = 0;
let loaded = false;
// Wait for new jobs to load
while (!loaded) {
loaded = await page.evaluate(
(selector) => {
return document.querySelectorAll(selector).length > 0;
},
selectors.jobs,
);
if (loaded) return { success: true };
await sleep(pollingTime);
elapsed += pollingTime;
if (elapsed >= timeout) {
return {
success: false,
error: `Timeout on pagination`
};
}
}
return { success: true };
};
/**
* Hide chat panel
* @param {Page} page
* @param {string} tag
*/
private static _hideChatPanel = async (
page: Page,
tag: string,
): Promise<void> => {
try {
await page.evaluate((selector) => {
const div = document.querySelector(selector);
if (div) {
div.style.display = "none";
}
},
selectors.chatPanel);
}
catch (err) {
logger.debug(tag, "Failed to hide chat panel");
}
};
/**
* Accept cookies
* @param {Page} page
* @param {string} tag
*/
private static _acceptCookies = async (
page: Page,
tag: string,
): Promise<void> => {
try {
await page.evaluate(() => {
const buttons = Array.from(document.querySelectorAll('button'));
const cookieButton = buttons.find(e => e.innerText.includes('Accept cookies'));
if (cookieButton) {
cookieButton.click();
}
});
}
catch (err) {
logger.debug(tag, "Failed to accept cookies");
}
};
/**
* Run strategy
* @param page
* @param url
* @param query
* @param location
*/
public run = async (
page: Page,
url: string,
query: IQuery,
location: string,
): Promise<IRunStrategyResult> => {
let tag = `[${query.query}][${location}]`;
let processed = 0;
let paginationIndex = 1;
// Navigate to home page
logger.debug(tag, "Opening", urls.home);
await page.goto(urls.home, {
waitUntil: 'load',
});
// Set cookie
logger.info("Setting authentication cookie");
await page.setCookie({
name: "li_at",
value: config.LI_AT_COOKIE!,
domain: ".www.linkedin.com"
});
logger.info(tag, "Opening", url);
await page.goto(url, {
waitUntil: 'load',
});
// Verify session
if (!(await LoggedInRunStrategy._isAuthenticatedSession(page))) {
logger.error("The provided session cookie is invalid. Check the documentation on how to obtain a valid session cookie.");
this.scraper.emit(events.scraper.invalidSession);
return { exit: true };
}
try {
await page.waitForSelector(selectors.container, { timeout: 5000 });
}
catch(err) {
logger.info(tag, `No jobs found, skip`);
return { exit: false };
}
// Pagination loop
while (processed < query.options!.limit!) {
// Verify session in the loop
if (!(await LoggedInRunStrategy._isAuthenticatedSession(page))) {
logger.warn(tag, "Session is invalid, this may cause the scraper to fail.");
this.scraper.emit(events.scraper.invalidSession);
}
else {
logger.info(tag, "Session is valid");
}
// Try to hide chat panel
await LoggedInRunStrategy._hideChatPanel(page, tag);
// Accept cookies
await LoggedInRunStrategy._acceptCookies(page, tag);
let jobIndex = 0;
// Get number of all job links in the page
let jobsTot = await page.evaluate(
(selector) => document.querySelectorAll(selector).length,
selectors.jobs
);
if (jobsTot === 0) {
logger.info(tag, `No jobs found, skip`);
break;
}
logger.info(tag, "Jobs fetched: " + jobsTot);
// Jobs loop
while (jobIndex < jobsTot && processed < query.options!.limit!) {
tag = `[${query.query}][${location}][${processed + 1}]`;
let jobId;
let jobLink;
let jobTitle;
let jobCompany;
let jobPlace;
let jobDescription;
let jobDescriptionHTML;
let jobDate;
let jobSenorityLevel;
let jobFunction;
let jobEmploymentType;
let jobIndustry;
let loadDetailsResult;
try {
// Extract job main fields
logger.debug(tag, 'Evaluating selectors', [
selectors.jobs,
selectors.links,
selectors.companies,
selectors.places,
selectors.dates,
]);
[jobId, jobLink, jobTitle, jobCompany, jobPlace, jobDate] = await page.evaluate(
(
jobsSelector: string,
linksSelector: string,
titleSelector: string,
companiesSelector: string,
placesSelector: string,
datesSelector: string,
jobIndex: number
) => {
const job = document.querySelectorAll(jobsSelector)[jobIndex];
const link = job.querySelector(linksSelector) as HTMLElement;
// Click job link and scroll
link.scrollIntoView();
link.click();
// Extract job link (relative)
const protocol = window.location.protocol + "//";
const hostname = window.location.hostname;
const linkUrl = protocol + hostname + link.getAttribute("href");
const jobId = job.getAttribute("data-job-id");
const title = job.querySelector(titleSelector) ?
(<HTMLElement>job.querySelector(titleSelector)).innerText : "";
const company = job.querySelector(companiesSelector) ?
(<HTMLElement>job.querySelector(companiesSelector)).innerText : "";
const place = job.querySelector(placesSelector) ?
(<HTMLElement>job.querySelector(placesSelector)).innerText : "";
const date = job.querySelector(datesSelector) ?
(<HTMLElement>job.querySelector(datesSelector)).getAttribute('datetime') : "";
return [
jobId,
linkUrl,
title,
company,
place,
date,
];
},
selectors.jobs,
selectors.links,
selectors.title,
selectors.companies,
selectors.places,
selectors.dates,
jobIndex
);
// Try to load job details and extract job link
logger.debug(tag, 'Evaluating selectors', [
selectors.jobs,
]);
loadDetailsResult = await LoggedInRunStrategy._loadJobDetails(page, jobId!);
// Check if loading job details has failed
if (!loadDetailsResult.success) {
logger.error(tag, loadDetailsResult.error);
jobIndex += 1;
continue;
}
// Use custom description function if available
logger.debug(tag, 'Evaluating selectors', [
selectors.description,
]);
if (query.options?.descriptionFn) {
[jobDescription, jobDescriptionHTML] = await Promise.all([
page.evaluate(`(${query.options.descriptionFn.toString()})();`),
page.evaluate((selector) => {
return (<HTMLElement>document.querySelector(selector)).outerHTML;
}, selectors.description)
]);
}
else {
[jobDescription, jobDescriptionHTML] = await page.evaluate((selector) => {
const el = (<HTMLElement>document.querySelector(selector));
return [el.innerText, el.outerHTML];
},
selectors.description
);
}
jobDescription = jobDescription as string;
// Extract job criteria
logger.debug(tag, 'Evaluating selectors', [
selectors.criteria,
]);
[
jobSenorityLevel,
jobEmploymentType,
jobIndustry,
jobFunction,
] = await page.evaluate(
(
jobCriteriaSelector: string
) => {
const nodes = document.querySelectorAll<HTMLElement>(jobCriteriaSelector);
const criteria = [
"Seniority Level",
"Employment Type",
"Industry",
"Job Functions",
];
const [
senoriotyLevel,
employmentType,
industry,
jobFunctions,
] = criteria.map(criteria => {
const el = Array.from(nodes)
.find(node => node.innerText.trim() === criteria);
if (el && el.nextElementSibling) {
const sibling = el.nextElementSibling as HTMLElement;
return sibling.innerText
.replace(/[\s]{2,}/g, ", ")
.replace(/[\n\r]+/g, " ")
.trim();
}
else {
return "";
}
});
return [
senoriotyLevel,
employmentType,
industry,
jobFunctions
];
},
selectors.criteria
);
}
catch(err) {
const errorMessage = `${tag}\t${err.message}`;
this.scraper.emit(events.scraper.error, errorMessage);
jobIndex++;
continue;
}
// Emit data
this.scraper.emit(events.scraper.data, {
query: query.query || "",
location: location,
jobId: jobId!,
jobIndex: jobIndex,
link: jobLink!,
title: jobTitle!,
company: jobCompany!,
place: jobPlace!,
description: jobDescription! as string,
descriptionHTML: jobDescriptionHTML! as string,
date: jobDate!,
senorityLevel: jobSenorityLevel,
jobFunction: jobFunction,
employmentType: jobEmploymentType,
industries: jobIndustry,
});
jobIndex += 1;
processed += 1;
logger.info(tag, `Processed`);
if (processed < query.options!.limit! && jobIndex === jobsTot) {
logger.info(tag, 'Fecthing more jobs');
const fetched = await page.evaluate(
(selector) => document.querySelectorAll(selector).length,
selectors.jobs
);
if (fetched === jobsTot) {
logger.info(tag, "No more jobs available in this page");
}
else {
jobsTot = fetched;
}
}
}
// Check if we reached the limit of jobs to process
if (processed === query.options!.limit!) break;
// Try pagination to load more jobs
paginationIndex += 1;
logger.info(tag, `Pagination requested (${paginationIndex})`);
// const paginationResult = await LoggedInRunStrategy._paginate(page, paginationIndex);
const paginationResult = await LoggedInRunStrategy._paginate(page, tag);
// Check if loading jobs has failed
if (!paginationResult.success) {
logger.info(tag, paginationResult.error);
logger.info(tag, "There are no more jobs available for the current query");
break;
}
}
return { exit: false };
}
} | the_stack |
import type { Logger } from '../../../logger'
import type { AcceptanceMechanisms, AuthorAgreement, IndyPool } from '../IndyPool'
import type {
default as Indy,
CredDef,
LedgerReadReplyResponse,
LedgerRequest,
LedgerWriteReplyResponse,
NymRole,
Schema,
} from 'indy-sdk'
import { Lifecycle, scoped } from 'tsyringe'
import { AgentConfig } from '../../../agent/AgentConfig'
import { IndySdkError } from '../../../error/IndySdkError'
import { didFromCredentialDefinitionId, didFromSchemaId } from '../../../utils/did'
import { isIndyError } from '../../../utils/indyError'
import { IndyWallet } from '../../../wallet/IndyWallet'
import { IndyIssuerService } from '../../indy'
import { IndyPoolService } from './IndyPoolService'
@scoped(Lifecycle.ContainerScoped)
export class IndyLedgerService {
private wallet: IndyWallet
private indy: typeof Indy
private logger: Logger
private indyIssuer: IndyIssuerService
private indyPoolService: IndyPoolService
public constructor(
wallet: IndyWallet,
agentConfig: AgentConfig,
indyIssuer: IndyIssuerService,
indyPoolService: IndyPoolService
) {
this.wallet = wallet
this.indy = agentConfig.agentDependencies.indy
this.logger = agentConfig.logger
this.indyIssuer = indyIssuer
this.indyPoolService = indyPoolService
}
public async registerPublicDid(
submitterDid: string,
targetDid: string,
verkey: string,
alias: string,
role?: NymRole
) {
const pool = this.indyPoolService.ledgerWritePool
try {
this.logger.debug(`Register public did '${targetDid}' on ledger '${pool.id}'`)
const request = await this.indy.buildNymRequest(submitterDid, targetDid, verkey, alias, role || null)
const response = await this.submitWriteRequest(pool, request, submitterDid)
this.logger.debug(`Registered public did '${targetDid}' on ledger '${pool.id}'`, {
response,
})
return targetDid
} catch (error) {
this.logger.error(`Error registering public did '${targetDid}' on ledger '${pool.id}'`, {
error,
submitterDid,
targetDid,
verkey,
alias,
role,
pool,
})
throw error
}
}
public async getPublicDid(did: string) {
// Getting the pool for a did also retrieves the DID. We can just use that
const { did: didResponse } = await this.indyPoolService.getPoolForDid(did)
return didResponse
}
public async registerSchema(did: string, schemaTemplate: SchemaTemplate): Promise<Schema> {
const pool = this.indyPoolService.ledgerWritePool
try {
this.logger.debug(`Register schema on ledger '${pool.id}' with did '${did}'`, schemaTemplate)
const { name, attributes, version } = schemaTemplate
const schema = await this.indyIssuer.createSchema({ originDid: did, name, version, attributes })
const request = await this.indy.buildSchemaRequest(did, schema)
const response = await this.submitWriteRequest(pool, request, did)
this.logger.debug(`Registered schema '${schema.id}' on ledger '${pool.id}'`, {
response,
schema,
})
schema.seqNo = response.result.txnMetadata.seqNo
return schema
} catch (error) {
this.logger.error(`Error registering schema for did '${did}' on ledger '${pool.id}'`, {
error,
did,
schemaTemplate,
})
throw isIndyError(error) ? new IndySdkError(error) : error
}
}
public async getSchema(schemaId: string) {
const did = didFromSchemaId(schemaId)
const { pool } = await this.indyPoolService.getPoolForDid(did)
try {
this.logger.debug(`Get schema '${schemaId}' from ledger '${pool.id}'`)
const request = await this.indy.buildGetSchemaRequest(null, schemaId)
this.logger.debug(`Submitting get schema request for schema '${schemaId}' to ledger '${pool.id}'`)
const response = await this.submitReadRequest(pool, request)
const [, schema] = await this.indy.parseGetSchemaResponse(response)
this.logger.debug(`Got schema '${schemaId}' from ledger '${pool.id}'`, {
response,
schema,
})
return schema
} catch (error) {
this.logger.error(`Error retrieving schema '${schemaId}' from ledger '${pool.id}'`, {
error,
schemaId,
})
throw isIndyError(error) ? new IndySdkError(error) : error
}
}
public async registerCredentialDefinition(
did: string,
credentialDefinitionTemplate: CredentialDefinitionTemplate
): Promise<CredDef> {
const pool = this.indyPoolService.ledgerWritePool
try {
this.logger.debug(
`Register credential definition on ledger '${pool.id}' with did '${did}'`,
credentialDefinitionTemplate
)
const { schema, tag, signatureType, supportRevocation } = credentialDefinitionTemplate
const credentialDefinition = await this.indyIssuer.createCredentialDefinition({
issuerDid: did,
schema,
tag,
signatureType,
supportRevocation,
})
const request = await this.indy.buildCredDefRequest(did, credentialDefinition)
const response = await this.submitWriteRequest(pool, request, did)
this.logger.debug(`Registered credential definition '${credentialDefinition.id}' on ledger '${pool.id}'`, {
response,
credentialDefinition: credentialDefinition,
})
return credentialDefinition
} catch (error) {
this.logger.error(
`Error registering credential definition for schema '${credentialDefinitionTemplate.schema.id}' on ledger '${pool.id}'`,
{
error,
did,
credentialDefinitionTemplate,
}
)
throw isIndyError(error) ? new IndySdkError(error) : error
}
}
public async getCredentialDefinition(credentialDefinitionId: string) {
const did = didFromCredentialDefinitionId(credentialDefinitionId)
const { pool } = await this.indyPoolService.getPoolForDid(did)
this.logger.debug(`Using ledger '${pool.id}' to retrieve credential definition '${credentialDefinitionId}'`)
try {
this.logger.debug(`Get credential definition '${credentialDefinitionId}' from ledger '${pool.id}'`)
const request = await this.indy.buildGetCredDefRequest(null, credentialDefinitionId)
this.logger.debug(
`Submitting get credential definition request for credential definition '${credentialDefinitionId}' to ledger '${pool.id}'`
)
const response = await this.submitReadRequest(pool, request)
const [, credentialDefinition] = await this.indy.parseGetCredDefResponse(response)
this.logger.debug(`Got credential definition '${credentialDefinitionId}' from ledger '${pool.id}'`, {
response,
credentialDefinition,
})
return credentialDefinition
} catch (error) {
this.logger.error(`Error retrieving credential definition '${credentialDefinitionId}' from ledger '${pool.id}'`, {
error,
credentialDefinitionId,
pool: pool.id,
})
throw isIndyError(error) ? new IndySdkError(error) : error
}
}
private async submitWriteRequest(
pool: IndyPool,
request: LedgerRequest,
signDid: string
): Promise<LedgerWriteReplyResponse> {
try {
const requestWithTaa = await this.appendTaa(pool, request)
const signedRequestWithTaa = await this.signRequest(signDid, requestWithTaa)
const response = await pool.submitWriteRequest(signedRequestWithTaa)
return response
} catch (error) {
throw isIndyError(error) ? new IndySdkError(error) : error
}
}
private async submitReadRequest(pool: IndyPool, request: LedgerRequest): Promise<LedgerReadReplyResponse> {
try {
const response = await pool.submitReadRequest(request)
return response
} catch (error) {
throw isIndyError(error) ? new IndySdkError(error) : error
}
}
private async signRequest(did: string, request: LedgerRequest): Promise<LedgerRequest> {
try {
return this.indy.signRequest(this.wallet.handle, did, request)
} catch (error) {
throw isIndyError(error) ? new IndySdkError(error) : error
}
}
private async appendTaa(pool: IndyPool, request: Indy.LedgerRequest) {
try {
const authorAgreement = await this.getTransactionAuthorAgreement(pool)
// If ledger does not have TAA, we can just send request
if (authorAgreement == null) {
return request
}
const requestWithTaa = await this.indy.appendTxnAuthorAgreementAcceptanceToRequest(
request,
authorAgreement.text,
authorAgreement.version,
authorAgreement.digest,
this.getFirstAcceptanceMechanism(authorAgreement),
// Current time since epoch
// We can't use ratification_ts, as it must be greater than 1499906902
Math.floor(new Date().getTime() / 1000)
)
return requestWithTaa
} catch (error) {
throw isIndyError(error) ? new IndySdkError(error) : error
}
}
private async getTransactionAuthorAgreement(pool: IndyPool): Promise<AuthorAgreement | null> {
try {
// TODO Replace this condition with memoization
if (pool.authorAgreement !== undefined) {
return pool.authorAgreement
}
const taaRequest = await this.indy.buildGetTxnAuthorAgreementRequest(null)
const taaResponse = await this.submitReadRequest(pool, taaRequest)
const acceptanceMechanismRequest = await this.indy.buildGetAcceptanceMechanismsRequest(null)
const acceptanceMechanismResponse = await this.submitReadRequest(pool, acceptanceMechanismRequest)
// TAA can be null
if (taaResponse.result.data == null) {
pool.authorAgreement = null
return null
}
// If TAA is not null, we can be sure AcceptanceMechanisms is also not null
const authorAgreement = taaResponse.result.data as AuthorAgreement
const acceptanceMechanisms = acceptanceMechanismResponse.result.data as AcceptanceMechanisms
pool.authorAgreement = {
...authorAgreement,
acceptanceMechanisms,
}
return pool.authorAgreement
} catch (error) {
throw isIndyError(error) ? new IndySdkError(error) : error
}
}
private getFirstAcceptanceMechanism(authorAgreement: AuthorAgreement) {
const [firstMechanism] = Object.keys(authorAgreement.acceptanceMechanisms.aml)
return firstMechanism
}
}
export interface SchemaTemplate {
name: string
version: string
attributes: string[]
}
export interface CredentialDefinitionTemplate {
schema: Schema
tag: string
signatureType: 'CL'
supportRevocation: boolean
} | the_stack |
import * as sast from "ts-morph"
import {SourceFile, SyntaxKind, TypeGuards, ts} from "ts-morph";
import * as emitter from "./CSharpEmitter";
import {ContextInterface} from "./Context";
import {
addWhitespace,
getWhitespace,
emitStatic,
addLeadingComment,
addTrailingComment,
addSemicolon,
addComma,
endNode,
generateExportForClass,
generateExportForProperty,
generateExportForMethod,
pushContext,
swapContext,
popContext,
identifyInterfaces,
isDeclarationOfInterface,
generateExportForInterfaceDeclaration,
loadInterfaceProperties,
loadInterfaceMethods,
loadInterfaceIndexers,
hasAccessModifiers,
isMap,
emitDefaultNameSpace,
emitUsings,
} from './GeneratorHelpers';
export function TsToCSharpGenerator(node: SourceFile, context: ContextInterface): string {
const source: string[] = [];
emitUsings(source, context);
emitDefaultNameSpace(source, context, true);
//console.log("Identifying interfaces for later class implementations")
identifyInterfaces(node, context);
//console.log("Total interfaces identified: %d", context.diagnostics.identifiedInterfaces);
visitStatements(source, node, context);
addWhitespace(source, node, context);
endNode(node, context);
emitDefaultNameSpace(source, context, false);
return source.join('');
}
function visit(node: sast.Node, context: ContextInterface): string {
if ((visitor as any)[node.getKind()]) {
return (visitor as any)[node.getKind()](node, context);
}
throw new Error(`Unknown node kind ${SyntaxKind[node.getKind()]}`);
}
// tslint:disable-next-line cyclomatic-complexity
function visitStatements(source: string[], node: sast.SourceFile, context: ContextInterface): void {
node.getStatements().forEach(statement =>
source.push(visitStatement(statement, context))
);
}
// tslint:disable-next-line cyclomatic-complexity
function visitStatement(node: sast.Statement, context: ContextInterface): string {
switch (node.getKind()) {
case SyntaxKind.VariableStatement:
return visitVariableStatement(node as sast.VariableStatement, context);
case SyntaxKind.TypeAliasDeclaration:
return visitTypeAliasDeclaration(node as sast.TypeAliasDeclaration, context);
case SyntaxKind.InterfaceDeclaration:
return visitInterfaceDeclaration(node as sast.InterfaceDeclaration, context);
default:
throw new Error(`Unknown statement kind '${SyntaxKind[node.getKind()]}'`);
}
}
function visitModifiers(source: string[], node: sast.ModifierableNode, context: ContextInterface): void {
node.getModifiers().forEach(modifier => {
source.push(emitter.emitModifierable(modifier, context));
});
}
function visitTypeParameters(source: string[], node: sast.TypeParameteredNode, context: ContextInterface): void {
node.getTypeParameters().forEach(typeParameter => {
source.push(emitter.emitTypeParameter(typeParameter, context));
});
}
function visitMembers(source: string[],
node: (sast.InterfaceDeclaration | sast.ClassDeclaration | sast.TypeLiteralNode),
context: ContextInterface): void {
const members = node.getMembers();
for (let x = 0; x < members.length; x++)
{
let member = members[x];
source.push(visit(member, context));
addTrailingComment(source, context.offset, node, context);
}
}
function visitIndexSignature(node: sast.IndexSignatureDeclaration, context: ContextInterface): string {
const source: string[] = [];
addLeadingComment(source, node, context);
addWhitespace(source, node, context);
if (hasAccessModifiers(node))
{
// visit the modifiers.
visitModifiers(source, node, context);
}
else
{
// If there were no modifiers present then we should default to
if (context.emitImplementation)
{
source.push(context.genOptions.interfaceAccessModifier, " ");
}
}
if (node.compilerNode.modifiers) {
node.compilerNode.modifiers.forEach(modifier => {
source.push(emitter.emitModifierable(sast.createWrappedNode(modifier), context));
});
}
// let's push the name node offset so spacing will be ok.
// Modifiers seem to mess the spacing up with whitespace
context.offset = node.getKeyNameNode().getStart();
pushContext(context);
// // emit our property type which is at the end.
source.push(visitTypeNode(node.getReturnTypeNode(), context));
// make sure we put a spacer in there but we do not have optional properties.
// if (node.hasQuestionToken()) {
// source.push("? ");
// }
// else
// {
source.push(" ");
//}
// now reposition back to the start
swapContext(context);
emitStatic(source, 'this[', node, context);
source.push(visitTypeNode(node.getKeyTypeNode(), context));
source.push(" ");
source.push(emitter.emitParameterName(node.getKeyNameNode() as sast.Identifier, context));
emitStatic(source, ']', node, context);
if (node.isReadonly())
{
if (context.emitImplementation)
{
source.push(" => throw new NotImplementedException();");
}
else
source.push(" { get; }");
}
else
{
if (context.emitImplementation)
{
source.push(" { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }");
}
else
source.push(" { get; set; }");
}
// Now reposition to the end of the indexer type
popContext(context);
endNode(node, context);
addTrailingComment(source, node, context);
return source.join('');
}
function visitHeritageClause(node: sast.HeritageClause, context: ContextInterface): string {
const source: string[] = [];
addLeadingComment(source, node, context);
const clauseTypes = node.getTypeNodes();
const n = clauseTypes.length;
if (n > 0)
{
for (let t = 0; t < n; t++)
{
source.push(emitter.emit(clauseTypes[t], context));
if ((t < n - 1)) {
source.push(", ");
}
};
}
return source.join('');
}
function visitHeritageClauses(source: string[],
node: (sast.HeritageClauseableNode),
context: ContextInterface): void {
const ancestors = node.getHeritageClauses();
const n = ancestors.length;
if (ancestors.length > 0)
{
source.push(" : ");
for (let x = 0; x < n; x++)
{
const leaf = ancestors[x];
source.push(visit(leaf, context));
if ((x < n - 1)) {
source.push(", ");
}
}
}
}
function visitInterfaceDeclaration(node: sast.InterfaceDeclaration, context: ContextInterface): string {
const source: string[] = [];
// if this is just a Map node then we will not output it.
if (isMap(node))
{
endNode(node, context);
addTrailingComment(source, node, context);
return source.join('');
}
addLeadingComment(source, node, context);
addWhitespace(source, node, context);
if (node.getModifiers().length == 0)
{
if (context.genOptions.interfaceAccessModifier && context.genOptions.interfaceAccessModifier.length > 0)
{
source.push(context.genOptions.interfaceAccessModifier, " ");
}
}
else
{
visitModifiers(source, node, context);
}
// emit first punctuation which should be an opening brace.
source.push(emitter.emit(node.getFirstChildByKind(SyntaxKind.InterfaceKeyword), context));
addWhitespace(source, node, context);
source.push(emitter.emitInterfaceName(node.getNameNode(), context));
emitter.emitTypeParameters(source, node, context);
visitHeritageClauses(source, node, context);
emitter.emitTypeConstraints(source, node, context);
addTrailingComment(source, context.offset, node, context);
// emit first punctuation which should be an opening brace.
source.push(emitter.emit(node.getFirstChildByKind(SyntaxKind.FirstPunctuation), context));
addTrailingComment(source, context.offset, node, context);
visitMembers(source, node, context);
addLeadingComment(source, context.offset, node, context);
// emit the closing brace
source.push(emitter.emit(node.getLastToken(), context));
endNode(node, context);
addTrailingComment(source, node, context);
return source.join('');
}
function visitTypeNode(node: sast.Node,
context: ContextInterface): string {
return emitter.emitTypeNode(node, context);
}
function isPropertyAnEventHandler(node: sast.PropertySignature, context: ContextInterface): boolean {
if (node.getName().length > 2 && node.getName().substr(0,2).toLowerCase() === "on")
{
const typeNode = node.getTypeNode();
if (TypeGuards.isFunctionTypeNode(typeNode) && typeNode.getReturnTypeNode().getKind() === SyntaxKind.AnyKeyword)
{
const parameters = typeNode.getParameters();
if (parameters && parameters.length === 2)
{
// This might be too specific by checking for 'this'
if (parameters[0].getName() === "this")
{
const parm2Type = parameters[1].getTypeNode();
if (TypeGuards.isTypeReferenceNode(parm2Type))
{
// Note we may want to check for a specific type reference here such as Event
// or if the type reference extends a DOM Event.
return true;
}
}
}
}
}
return false;
}
function visitPropertySignature(node: sast.PropertySignature, context: ContextInterface): string {
const source: string[] = [];
if (node.getNameNode().getKind() === SyntaxKind.StringLiteral)
return "";
addLeadingComment(source, node, context);
if (isPropertyAnEventHandler(node, context))
{
source.push(emitter.emitDOMEventHandler(node, context));
}
else
{
// This will generate an Export attribute as well as takes into account whitespace
source.push(generateExportForProperty(node, context));
if (hasAccessModifiers(node))
{
// visit the modifiers.
visitModifiers(source, node, context);
}
else
{
// If there were no modifiers present then we should default to
if (context.emitImplementation)
{
source.push(context.genOptions.interfaceAccessModifier, " ");
}
}
// let's push the name node offset so spacing will be ok.
// Modifiers seem to mess the spacing up with whitespace
context.offset = node.getNameNode().getStart();
pushContext(context);
// emit our property type which is at the end.
source.push(visitTypeNode(node.getTypeNode(), context));
// make sure we put a spacer in there but we do not have optional properties.
// if (node.hasQuestionToken()) {
// source.push("? ");
// }
// else
// {
source.push(" ");
//}
// now reposition back to the start
swapContext(context);
source.push(emitter.emitPropertyName(node.getNameNode(), context));
// Emit the C# Body code of the property
source.push(emitter.emitPropertyBody(node, context));
// Now reposition to the end of the method type
popContext(context);
}
endNode(node, context);
addTrailingComment(source, node, context);
return source.join('');
}
function visitParameter(source: string[], node: sast.ParameterDeclaration, context: ContextInterface): void {
// We have to take into account that the type follows the name
// let's push the parameter name node offset so spacing will be ok.
// The comma separator will mess the spacing up with whitespace
context.offset = node.getStart();
pushContext(context);
// First check if it is a rest parameter
if (node.isRestParameter())
{
// emit our parameter type which is at the end.
source.push(emitter.emitRestParameter(node.getTypeNode(), context));
}
else
{
// emit our parameter type which is at the end.
source.push(visitTypeNode(node.getTypeNode(), context));
}
// let's also put a spacer in there
source.push(" ");
// now reposition back to the start
swapContext(context);
source.push(emitter.emitParameterName(node.getNameNode(), context));
// now reposition back to the start
popContext(context);
}
function visitParameters(source: string[], node: sast.ParameteredNode, context: ContextInterface): void {
const parmList = node.getParameters();
let n = node.getParameters().length;
if (n > 0)
{
for (let p = 0; p < n; p++)
{
visitParameter(source, parmList[p], context);
if (p < n - 1)
{
source.push(", ");
}
}
}
}
// tslint:disable-next-line cyclomatic-complexity
function visitMethodSignature(node: sast.MethodSignature, context: ContextInterface): string {
const source: string[] = [];
// We will skip KeyOf Maps for now.
const types = node.getTypeParameters();
if (types && types.length > 0)
{
const keyof = types[0];
if (TypeGuards.isTypeParameterDeclaration(keyof))
{
endNode(node, context);
return source.join('');
}
}
addLeadingComment(source, node, context);
// This will generate an Export attribute as well as takes into account whitespace
source.push(generateExportForMethod(node, context));
// If there were no modifiers present then we should default to
if (context.emitImplementation)
{
source.push(context.genOptions.interfaceAccessModifier, " ");
}
// let's push the name node offset so spacing will be ok.
// Modifiers seem to mess the spacing up with whitespace
context.offset = node.getNameNode().getStart();
pushContext(context);
// emit our method type which is at the end.
source.push(visitTypeNode(node.getReturnTypeNode(), context));
// make sure we put a spacer in there
source.push(" ");
// now reposition back to the start
swapContext(context);
visitTypeParameters(source, node, context);
source.push(emitter.emitMethodName(node.getNameNode(), context));
emitStatic(source, '(', node, context);
visitParameters(source, node, context);
emitStatic(source, ')', node, context);
// Now reposition to the end of the method type
popContext(context);
source.push(emitter.emitMethodBody(node, context));
endNode(node, context);
addTrailingComment(source, context.offset, node, context);
return source.join('');
}
function visitVariableStatement(node: sast.VariableStatement, context: ContextInterface): string {
const source: string[] = [];
addLeadingComment(source, node, context);
visitVariableDeclarationList(source, node.getDeclarationList(), context);
endNode(node, context);
addTrailingComment(source, node, context);
return source.join('');
}
function visitVariableDeclarationList(source: string[], node: sast.VariableDeclarationList, context: ContextInterface) : void {
switch(node.getDeclarationKindKeyword().getKind())
{
case SyntaxKind.VarKeyword:
visitVariableDeclarations(source, node, context);
break;
default:
context.diagnostics.pushErrorAtLoc("Declaration type " + node.getDeclarationKindKeyword().getKindName() + " is not yet supported", node);
}
}
function visitVariableDeclarations(source: string[], node: sast.VariableDeclarationList, context: ContextInterface) : void {
const declarations = node.getDeclarations();
for (let x = 0; x < declarations.length; x++)
{
let declaration = declarations[x];
source.push(visit(declaration, context));
addTrailingComment(source, context.offset, node, context);
}
}
function visitVariableDeclaration(node: sast.VariableDeclaration, context: ContextInterface): string {
const source: string[] = [];
addLeadingComment(source, node, context);
if (isDeclarationOfInterface(node))
{
source.push(visitDeclarationOfInterface(node, context));
}
else
{
context.diagnostics.pushWarningAtLoc("Variable Declarations other than Interfaces are not supported", node);
}
endNode(node, context);
addTrailingComment(source, node, context);
return source.join('');
}
function visitDeclarationOfInterface(node: sast.VariableDeclaration, context: ContextInterface): string {
const source: string[] = [];
addLeadingComment(source, node, context);
// This will generate an Export attribute as well as takes into account whitespace
source.push(generateExportForInterfaceDeclaration(node, context));
// Here we emit the C# definition
emitter.emitClassDefinitionOfInterfaceDeclaration(source, node, context, context.genOptions.isCaseChange && context.genOptions.isCaseChangeClasses);
source.push(visit(node.getTypeNode(), context));
return source.join('');
}
// A TypeLiteral is the declaration node for an anonymous symbol.
function visitTypeLiteral(node: sast.TypeLiteralNode, context: ContextInterface) : string {
const source: string[] = [];
addLeadingComment(source, node, context);
addWhitespace(source, node, context);
// emit first punctuation which should be an opening brace.
source.push(emitter.emit(node.getFirstChildByKind(SyntaxKind.FirstPunctuation), context));
addTrailingComment(source, node.getFirstChildByKind(SyntaxKind.FirstPunctuation), context );
addWhitespace(source, node, context);
// save off our context
pushContext(context);
emitter.emitClassConstructor(source, node, context);
// now reposition back to the start
swapContext(context);
// Emit the constructors of the anonymous symbol
visitConstructors(source, node, context);
addTrailingComment(source, context.offset, node, context);
// Tell the emitter that we will be emitting implementations
context.emitImplementation = true;
// First process properties.
// create a property signature bag
const propertiesBag = new Map<string, sast.PropertySignature>();
// accumulate all the existing properties defined in the type.
const propertySignatures = node.getDescendantsOfKind(SyntaxKind.PropertySignature);
let prototypeDefinition : sast.InterfaceDeclaration = null;
// load all the properties except for the "prototype" property which defines the interface implementation
for (let x = 0; x < propertySignatures.length; x++)
{
let property = propertySignatures[x];
if (property.getName() === "prototype")
{
const propertyTypeNode = property.getTypeNode();
if (TypeGuards.isTypeReferenceNode(propertyTypeNode))
{
const interfaceName = propertyTypeNode.getText();
prototypeDefinition = propertyTypeNode.getSourceFile().getInterface(interfaceName);
}
}
else
{
propertiesBag.set(property.getName(), property);
}
}
// We now need to load all the properties of the interface defined by the "prototype" property
// definition for the TypeLiteralNode.
if (prototypeDefinition)
{
loadInterfaceProperties(propertiesBag, prototypeDefinition)
}
for (const property of propertiesBag.values()) {
pushContext(context);
context.offset = property.getPos();
source.push(visit(property, context));
addTrailingComment(source, context.offset, node, context);
popContext(context);
}
// Then process functions.
const methods = node.getDescendantsOfKind(SyntaxKind.MethodSignature);
// create a method signature bag
const methodsBag = new Map<string, sast.MethodSignature>();
for (let x = 0; x < methods.length; x++)
{
let method = methods[x];
methodsBag.set(method.getName(), method);
}
// We now need to load all the methods of the interface defined by the "prototype" property
// definition for the TypeLiteralNode.
if (prototypeDefinition)
{
loadInterfaceMethods(methodsBag, prototypeDefinition)
}
for (const method of methodsBag.values()) {
pushContext(context);
context.offset = method.getPos();
source.push(visit(method, context));
addTrailingComment(source, context.offset, node, context);
popContext(context);
}
// Then process indexers.
const indexers = node.getDescendantsOfKind(SyntaxKind.IndexSignature);
// create an index signature bag
const indexersBag = new Map<string, sast.IndexSignatureDeclaration>();
for (let x = 0; x < indexers.length; x++)
{
let indexer = indexers[x];
indexersBag.set("this[]", indexer);
}
// We now need to load all the inexers of the interface defined by the "prototype" property
// definition for the TypeLiteralNode.
if (prototypeDefinition)
{
loadInterfaceIndexers(indexersBag, prototypeDefinition)
}
for (const indexer of indexersBag.values()) {
pushContext(context);
context.offset = indexer.getPos();
source.push(visit(indexer, context));
addTrailingComment(source, context.offset, node, context);
popContext(context);
}
// Reset the flag for emitting implementations
context.emitImplementation = false;
source.push(emitter.emit(node.getFirstChildByKind(SyntaxKind.CloseBraceToken), context));
endNode(node, context);
return source.join('');
}
function visitConstructors(source: string[], node: sast.TypeLiteralNode, context: ContextInterface) : void {
const constructors = node.getConstructSignatures();
for (let c = 0; c < constructors.length; c++)
{
source.push(visit(constructors[c], context));
}
}
// tslint:disable-next-line cyclomatic-complexity
function visitConstructSignature(node: sast.ConstructSignatureDeclaration, context: ContextInterface): string {
const source: string[] = [];
// We may be jumping around processing AST nodes out of order so we need to actually set the
// context offset ourselves. Here we set the context offset to be the begging of the node.
context.offset = node.getPos();
addLeadingComment(source, node.getPos(), node, context);
addWhitespace(source, node, context);
const parameters = node.getTypeParameters();
pushContext(context);
// the constructors in this case do not allow modifiers so we will make it public by default
source.push("public");
// emit our constructor type which is at the end.
const savePrefixInterface = context.genOptions.isPrefixInterface;
const saveCaseChangeInterfaces = context.genOptions.isCaseChangeInterfaces;
context.genOptions.isPrefixInterface = false;
context.genOptions.isCaseChangeInterfaces = false;
addWhitespace(source, node.getReturnTypeNode(), context);
source.push(visitTypeNode(node.getReturnTypeNode(), context));
context.genOptions.isCaseChangeInterfaces = saveCaseChangeInterfaces;
context.genOptions.isPrefixInterface = savePrefixInterface;
// make sure we put a spacer in there
source.push(" ");
// now reposition back to the start
swapContext(context);
visitTypeParameters(source, node, context);
emitStatic(source, '(', node, context);
visitParameters(source, node, context);
emitStatic(source, ')', node, context);
// Now reposition to the end of the method type
popContext(context);
// Make sure we add a body
source.push(" { }");
endNode(node, context);
addTrailingComment(source, context.offset, node, context);
return source.join('');
}
function visitTypeAliasDeclaration(node: sast.TypeAliasDeclaration, context: ContextInterface): string {
const source: string[] = [];
context.diagnostics.pushWarningAtLoc("Nodes of type TypeAliasDeclaration are not supported at this time ", node);
return source.join('');
}
// tslint:disable-next-line cyclomatic-complexity
function visitCallSignature(node: sast.CallSignatureDeclaration, context: ContextInterface): string {
const source: string[] = [];
// We may be jumping around processing AST nodes out of order so we need to actually set the
// context offset ourselves. Here we set the context offset to be the begging of the node.
context.offset = node.getPos();
addLeadingComment(source, node.getPos(), node, context);
addWhitespace(source, node, context);
// const parameters = node.getTypeParameters();
// pushContext(context);
// // the constructors in this case do not allow modifiers so we will make it public by default
// source.push("public");
// // emit our constructor type which is at the end.
// const savePrefixInterface = context.genOptions.isPrefixInterface;
// const saveCaseChangeInterfaces = context.genOptions.isCaseChangeInterfaces;
// context.genOptions.isPrefixInterface = false;
// context.genOptions.isCaseChangeInterfaces = false;
// addWhitespace(source, node.getReturnTypeNode(), context);
// source.push(visitTypeNode(node.getReturnTypeNode(), context));
// context.genOptions.isCaseChangeInterfaces = saveCaseChangeInterfaces;
// context.genOptions.isPrefixInterface = savePrefixInterface;
// // make sure we put a spacer in there
// source.push(" ");
// // now reposition back to the start
// swapContext(context);
// visitTypeParameters(source, node, context);
// emitStatic(source, '(', node, context);
// visitParameters(source, node, context);
// emitStatic(source, ')', node, context);
// // Now reposition to the end of the method type
// popContext(context);
// // Make sure we add a body
// source.push(" { }");
addSemicolon(source, node, context);
endNode(node, context);
addTrailingComment(source, context.offset, node, context);
return source.join('');
}
const visitor = {
[SyntaxKind.SourceFile]: TsToCSharpGenerator,
[SyntaxKind.PropertySignature]: visitPropertySignature,
[SyntaxKind.MethodSignature]: visitMethodSignature,
[SyntaxKind.HeritageClause]: visitHeritageClause,
[SyntaxKind.IndexSignature]: visitIndexSignature,
[SyntaxKind.VariableDeclaration]: visitVariableDeclaration,
[SyntaxKind.ConstructSignature]: visitConstructSignature,
[SyntaxKind.TypeLiteral]: visitTypeLiteral,
[SyntaxKind.CallSignature]: visitCallSignature,
}; | the_stack |
import "mocha";
import * as expect from "expect";
import { InputStream } from "../../src/z80lang/parser/input-stream";
import { TokenStream, TokenType } from "../../src/z80lang/parser/token-stream";
describe("Parser - token: whitespaces/comments", () => {
it("get: empty stream results EOF", () => {
const ts = new TokenStream(new InputStream(""));
const token = ts.get();
expect(token.type).toBe(TokenType.Eof);
expect(token.text).toBe("");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(0);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(0);
});
it("get: whitespace #1", () => {
const ts = new TokenStream(new InputStream(" "));
const token = ts.get(true); // --- We intend to obtain whitespaces
expect(token.type).toBe(TokenType.Ws);
expect(token.text).toBe(" ");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(1);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(1);
});
it("get: whitespace #2", () => {
const ts = new TokenStream(new InputStream("\t"));
const token = ts.get(true); // --- We intend to obtain whitspaces
expect(token.type).toBe(TokenType.Ws);
expect(token.text).toBe("\t");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(1);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(1);
});
it("get: whitespace #3", () => {
const ts = new TokenStream(new InputStream(" a"));
const token = ts.get(true); // --- We intend to obtain whitespaces
expect(token.type).toBe(TokenType.Ws);
expect(token.text).toBe(" ");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(1);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(1);
});
it("get: whitespace #4", () => {
const ts = new TokenStream(new InputStream("\ta"));
const token = ts.get(true); // --- We intend to obtain whitespaces
expect(token.type).toBe(TokenType.Ws);
expect(token.text).toBe("\t");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(1);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(1);
});
it("get: whitespace #5", () => {
const ts = new TokenStream(new InputStream(" \t a"));
const token = ts.get(true); // --- We intend to obtain whitespaces
expect(token.type).toBe(TokenType.Ws);
expect(token.text).toBe(" \t ");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(3);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(3);
});
it("get: whitespace #6", () => {
const ts = new TokenStream(new InputStream("\t \ta"));
const token = ts.get(true); // --- We intend to obtain whitespaces
expect(token.type).toBe(TokenType.Ws);
expect(token.text).toBe("\t \t");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(3);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(3);
});
it("get: semicolon comment #1", () => {
const ts = new TokenStream(new InputStream("; This is a comment"));
const token = ts.get(true); // --- We intend to obtain whitespaces
expect(token.type).toBe(TokenType.EolComment);
expect(token.text).toBe("; This is a comment");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(19);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(19);
});
it("get: semicolon comment #2", () => {
const ts = new TokenStream(new InputStream(" ; This is a comment"));
expect(ts.get(true).type).toBe(TokenType.Ws);
const token = ts.get(true); // --- We intend to obtain whitespaces
expect(token.type).toBe(TokenType.EolComment);
expect(token.text).toBe("; This is a comment");
expect(token.location.startPos).toBe(2);
expect(token.location.endPos).toBe(21);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(2);
expect(token.location.endColumn).toBe(21);
});
it("get: semicolon comment #3", () => {
const ts = new TokenStream(new InputStream("\t ; This is a comment\n"));
expect(ts.get(true).type).toBe(TokenType.Ws);
const token = ts.get(true); // --- We intend to obtain whitespaces
expect(token.type).toBe(TokenType.EolComment);
expect(token.text).toBe("; This is a comment");
expect(token.location.startPos).toBe(2);
expect(token.location.endPos).toBe(21);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(2);
expect(token.location.endColumn).toBe(21);
});
it("get: semicolon comment #4", () => {
const ts = new TokenStream(new InputStream("\t ; This is a comment\r\n"));
expect(ts.get(true).type).toBe(TokenType.Ws);
const token = ts.get(true); // --- We intend to obtain whitespaces
expect(token.type).toBe(TokenType.EolComment);
expect(token.text).toBe("; This is a comment");
expect(token.location.startPos).toBe(2);
expect(token.location.endPos).toBe(21);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(2);
expect(token.location.endColumn).toBe(21);
});
it("get: divide operator #1", () => {
const ts = new TokenStream(new InputStream("/"));
const token = ts.get();
expect(token.type).toBe(TokenType.Divide);
expect(token.text).toBe("/");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(1);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(1);
});
it("get: divide operator #2", () => {
const ts = new TokenStream(new InputStream(" /"));
const token = ts.get();
expect(token.type).toBe(TokenType.Divide);
expect(token.text).toBe("/");
expect(token.location.startPos).toBe(2);
expect(token.location.endPos).toBe(3);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(2);
expect(token.location.endColumn).toBe(3);
});
it("get: divide operator #3", () => {
const ts = new TokenStream(new InputStream("/a"));
const token = ts.get();
expect(token.type).toBe(TokenType.Divide);
expect(token.text).toBe("/");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(1);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(1);
});
it("get: EOL comment #1", () => {
const ts = new TokenStream(new InputStream("//"));
const token = ts.get(true); // --- We intend to obtain comments
expect(token.type).toBe(TokenType.EolComment);
expect(token.text).toBe("//");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(2);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(2);
});
it("get: EOL comment #3", () => {
const ts = new TokenStream(new InputStream("// comment"));
const token = ts.get(true); // --- We intend to obtain comments
expect(token.type).toBe(TokenType.EolComment);
expect(token.text).toBe("// comment");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(10);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(10);
});
it("get: EOL comment #4", () => {
const ts = new TokenStream(new InputStream("// comment\r"));
const token = ts.get(true); // --- We intend to obtain comments
expect(token.type).toBe(TokenType.EolComment);
expect(token.text).toBe("// comment");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(10);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(10);
});
it("get: EOL comment #5", () => {
const ts = new TokenStream(new InputStream("// comment\r\n"));
const token = ts.get(true); // --- We intend to obtain comments
expect(token.type).toBe(TokenType.EolComment);
expect(token.text).toBe("// comment");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(10);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(10);
});
it("get: Inline comment #1", () => {
const ts = new TokenStream(new InputStream("/* comment */"));
const token = ts.get(true); // --- We intend to obtain comments
expect(token.type).toBe(TokenType.InlineComment);
expect(token.text).toBe("/* comment */");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(13);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(13);
});
it("get: Inline comment #2", () => {
const ts = new TokenStream(new InputStream("/* com*ent */"));
const token = ts.get(true); // --- We intend to obtain comments
expect(token.type).toBe(TokenType.InlineComment);
expect(token.text).toBe("/* com*ent */");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(13);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(13);
});
it("get: Inline comment #3", () => {
const ts = new TokenStream(new InputStream("/*"));
const token = ts.get(true); // --- We intend to obtain comments
expect(token.type).toBe(TokenType.Unknown);
expect(token.text).toBe("/*");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(2);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(2);
});
it("get: Inline comment #4", () => {
const ts = new TokenStream(new InputStream("/* com\nent */"));
const token = ts.get(true); // --- We intend to obtain comments
expect(token.type).toBe(TokenType.Unknown);
expect(token.text).toBe("/* com");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(6);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(6);
});
it("get: Inline comment #5", () => {
const ts = new TokenStream(new InputStream("/* com\rent */"));
const token = ts.get(true); // --- We intend to obtain comments
expect(token.type).toBe(TokenType.Unknown);
expect(token.text).toBe("/* com");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(6);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(6);
});
it("get: Inline comment #6", () => {
const ts = new TokenStream(new InputStream("/* comment *"));
const token = ts.get(true); // --- We intend to obtain comments
expect(token.type).toBe(TokenType.Unknown);
expect(token.text).toBe("/* comment *");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(12);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(12);
});
it("get: Inline comment #7", () => {
const ts = new TokenStream(new InputStream("/* comment *//"));
const token = ts.get(); // --- We skip comments
expect(token.type).toBe(TokenType.Divide);
expect(token.text).toBe("/");
expect(token.location.startPos).toBe(13);
expect(token.location.endPos).toBe(14);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(13);
expect(token.location.endColumn).toBe(14);
});
it("get: new line #1", () => {
const ts = new TokenStream(new InputStream("\r"));
const token = ts.get();
expect(token.type).toBe(TokenType.NewLine);
expect(token.text).toBe("\r");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(1);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(1);
});
it("get: new line #2", () => {
const ts = new TokenStream(new InputStream("\r/"));
const token = ts.get();
expect(token.type).toBe(TokenType.NewLine);
expect(token.text).toBe("\r");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(1);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(1);
});
it("get: new line #3", () => {
const ts = new TokenStream(new InputStream("\n"));
const token = ts.get();
expect(token.type).toBe(TokenType.NewLine);
expect(token.text).toBe("\n");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(1);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(1);
});
it("get: new line #4", () => {
const ts = new TokenStream(new InputStream("\n/"));
const token = ts.get();
expect(token.type).toBe(TokenType.NewLine);
expect(token.text).toBe("\n");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(1);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(1);
});
it("get: new line #5", () => {
const ts = new TokenStream(new InputStream("\r\n"));
const token = ts.get();
expect(token.type).toBe(TokenType.NewLine);
expect(token.text).toBe("\r\n");
expect(token.location.startPos).toBe(0);
expect(token.location.endPos).toBe(2);
expect(token.location.line).toBe(1);
expect(token.location.startColumn).toBe(0);
expect(token.location.endColumn).toBe(2);
});
}); | the_stack |
import { ImmutableFeatureCollection } from '../src/lib/immutable-feature-collection';
let pointFeature;
let lineStringFeature;
let polygonFeature;
let multiPointFeature;
let multiLineStringFeature;
let multiPolygonFeature;
let featureCollection;
beforeEach(() => {
pointFeature = {
type: 'Feature',
properties: {},
geometry: { type: 'Point', coordinates: [1, 2] },
};
lineStringFeature = {
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: [
[1, 2],
[2, 3],
[3, 4],
],
},
};
polygonFeature = {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [
// exterior ring
[
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
[-1, -1],
],
// hole
[
[-0.5, -0.5],
[-0.5, 0.5],
[0.5, 0.5],
[0.5, -0.5],
[-0.5, -0.5],
],
],
},
};
multiPointFeature = {
type: 'Feature',
properties: {},
geometry: {
type: 'MultiPoint',
coordinates: [
[1, 2],
[3, 4],
],
},
};
multiLineStringFeature = {
type: 'Feature',
properties: {},
geometry: {
type: 'MultiLineString',
coordinates: [
[
[1, 2],
[2, 3],
[3, 4],
],
[
[5, 6],
[6, 7],
[7, 8],
],
],
},
};
multiPolygonFeature = {
type: 'Feature',
properties: {},
geometry: {
type: 'MultiPolygon',
coordinates: [
[
// exterior ring polygon 1
[
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
[-1, -1],
],
// hole polygon 1
[
[-0.5, -0.5],
[-0.5, 0.5],
[0.5, 0.5],
[0.5, -0.5],
[-0.5, -0.5],
],
],
[
// exterior ring polygon 2
[
[2, -1],
[4, -1],
[4, 1],
[2, 1],
[2, -1],
],
],
],
},
};
featureCollection = {
type: 'FeatureCollection',
features: [
pointFeature,
lineStringFeature,
polygonFeature,
multiPointFeature,
multiLineStringFeature,
multiPolygonFeature,
],
};
});
describe('getObject()', () => {
it('can get real object', () => {
const editable = new ImmutableFeatureCollection(featureCollection);
expect(editable.getObject()).toBe(featureCollection);
});
});
describe('replacePosition()', () => {
it(`doesn't mutate original`, () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [pointFeature],
});
const updatedFeatures = features.replacePosition(0, [], [10, 20]);
expect(updatedFeatures).not.toBe(features);
expect(pointFeature.geometry.coordinates).toEqual([1, 2]);
});
it('replaces position in Point', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [pointFeature],
});
const updatedFeatures = features.replacePosition(0, [], [10, 20]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [10, 20];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('replaces first position in LineString', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [lineStringFeature],
});
const updatedFeatures = features.replacePosition(0, [0], [10, 20]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[10, 20],
[2, 3],
[3, 4],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('replaces middle position in Polygon', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [polygonFeature],
});
const updatedFeatures = features
.replacePosition(0, [0, 1], [1.1, -1.1])
.replacePosition(0, [1, 2], [0.6, 0.6]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[
[-1, -1],
[1.1, -1.1],
[1, 1],
[-1, 1],
[-1, -1],
],
[
[-0.5, -0.5],
[-0.5, 0.5],
[0.6, 0.6],
[0.5, -0.5],
[-0.5, -0.5],
],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('replaces last position when replacing first position in Polygon', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [polygonFeature],
});
const updatedFeatures = features.replacePosition(0, [0, 0], [-1.1, -1.1]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[
[-1.1, -1.1],
[1, -1],
[1, 1],
[-1, 1],
[-1.1, -1.1],
],
[
[-0.5, -0.5],
[-0.5, 0.5],
[0.5, 0.5],
[0.5, -0.5],
[-0.5, -0.5],
],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('replaces first position when replacing last position in Polygon', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [polygonFeature],
});
const updatedFeatures = features.replacePosition(0, [0, 4], [-1.1, -1.1]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[
[-1.1, -1.1],
[1, -1],
[1, 1],
[-1, 1],
[-1.1, -1.1],
],
[
[-0.5, -0.5],
[-0.5, 0.5],
[0.5, 0.5],
[0.5, -0.5],
[-0.5, -0.5],
],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
});
describe('removePosition()', () => {
it(`doesn't mutate original`, () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [lineStringFeature],
});
const updatedFeatures = features.removePosition(0, [0]);
expect(updatedFeatures).not.toBe(features);
expect(lineStringFeature.geometry.coordinates).toEqual([
[1, 2],
[2, 3],
[3, 4],
]);
});
it('throws exception when attempting to remove Point', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [pointFeature],
});
expect(() => features.removePosition(0, [0])).toThrow(
`Can't remove a position from a Point or there'd be nothing left`
);
});
it('removes first position in LineString', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [lineStringFeature],
});
const updatedFeatures = features.removePosition(0, [0]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[2, 3],
[3, 4],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('removes middle position in Polygon', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [polygonFeature],
});
const updatedFeatures = features.removePosition(0, [0, 1]).removePosition(0, [1, 3]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[
[-1, -1],
[1, 1],
[-1, 1],
[-1, -1],
],
[
[-0.5, -0.5],
[-0.5, 0.5],
[0.5, 0.5],
[-0.5, -0.5],
],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('changes last position when removing first position in Polygon', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [polygonFeature],
});
const updatedFeatures = features.removePosition(0, [1, 0]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
[-1, -1],
],
[
[-0.5, 0.5],
[0.5, 0.5],
[0.5, -0.5],
[-0.5, 0.5],
],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('changes first position when removing last position in Polygon', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [polygonFeature],
});
const updatedFeatures = features.removePosition(0, [1, 4]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
[-1, -1],
],
[
[0.5, -0.5],
[-0.5, 0.5],
[0.5, 0.5],
[0.5, -0.5],
],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('throws exception when LineString has only 2 positions', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [
[0, 1],
[2, 3],
],
},
},
],
});
expect(() => features.removePosition(0, [0])).toThrow(
`Can't remove position. LineString must have at least two positions`
);
});
it('throws exception when Polygon outer ring has only 4 positions (triangle)', () => {
let features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [polygonFeature],
});
features = features
// Convert from quadrilateral to triangle
.removePosition(0, [0, 1]);
expect(() => features.removePosition(0, [0, 1])).toThrow(
`Can't remove position. Polygon's outer ring must have at least four positions`
);
});
it('removes hole from Polygon when it has less than four positions', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [polygonFeature],
});
const updatedFeatures = features.removePosition(0, [1, 1]).removePosition(0, [1, 1]);
const actualGeometry = updatedFeatures.getObject().features[0].geometry;
const expectedGeometry = {
type: 'Polygon',
coordinates: [
[
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
[-1, -1],
],
],
};
expect(actualGeometry).toEqual(expectedGeometry);
});
it('removes LineString from MultiLineString when it has only one position', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiLineStringFeature],
});
const updatedFeatures = features.removePosition(0, [1, 0]).removePosition(0, [1, 0]);
const actualGeometry = updatedFeatures.getObject().features[0].geometry;
const expectedGeometry = {
type: 'MultiLineString',
coordinates: [
[
[1, 2],
[2, 3],
[3, 4],
],
],
};
expect(actualGeometry).toEqual(expectedGeometry);
});
it('throws exception when MultiLineString has only 2 positions', () => {
let features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiLineStringFeature],
});
features = features
// remove one of the LineStrings
.removePosition(0, [0, 0])
.removePosition(0, [0, 0])
// shrink the remaining LineString to two positions
.removePosition(0, [0, 0]);
expect(() => features.removePosition(0, [0, 0])).toThrow(
`Can't remove position. MultiLineString must have at least two positions`
);
});
it('removes Polygon from MultiPolygon when outer ring has less than four positions', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiPolygonFeature],
});
const updatedFeatures = features.removePosition(0, [1, 0, 0]).removePosition(0, [1, 0, 0]);
const actualGeometry = updatedFeatures.getObject().features[0].geometry;
const expectedGeometry = {
type: 'MultiPolygon',
coordinates: [multiPolygonFeature.geometry.coordinates[0]],
};
expect(actualGeometry).toEqual(expectedGeometry);
});
it('removes hole from MultiPolygon when it has less than four positions', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiPolygonFeature],
});
const updatedFeatures = features.removePosition(0, [0, 1, 0]).removePosition(0, [0, 1, 0]);
const actualGeometry = updatedFeatures.getObject().features[0].geometry;
const expectedGeometry = {
type: 'MultiPolygon',
coordinates: [
[
[
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
[-1, -1],
],
],
[
[
[2, -1],
[4, -1],
[4, 1],
[2, 1],
[2, -1],
],
],
],
};
expect(actualGeometry).toEqual(expectedGeometry);
});
it('throws exception when MultiPolygon outer ring has only 4 positions', () => {
let features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiPolygonFeature],
});
features = features
// Remove the second polygon
.removePosition(0, [1, 0, 0])
.removePosition(0, [1, 0, 0])
// Remove positions from outer ring
.removePosition(0, [0, 0, 1]);
expect(() => features.removePosition(0, [0, 0, 1])).toThrow(
`Can't remove position. MultiPolygon's outer ring must have at least four positions`
);
});
});
describe('addPosition()', () => {
it(`doesn't mutate original`, () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [lineStringFeature],
});
const updatedFeatures = features.addPosition(0, [1], [2, 3]);
expect(updatedFeatures).not.toBe(features);
expect(lineStringFeature.geometry.coordinates).toEqual([
[1, 2],
[2, 3],
[3, 4],
]);
});
it('throws exception when attempting to add position to Point', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [pointFeature],
});
expect(() => features.addPosition(0, [], [3, 4])).toThrow(
'Unable to add a position to a Point feature'
);
});
it('adds position to beginning of LineString', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [lineStringFeature],
});
const updatedFeatures = features.addPosition(0, [0], [10, 20]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[10, 20],
[1, 2],
[2, 3],
[3, 4],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('adds position to middle of LineString', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [lineStringFeature],
});
const updatedFeatures = features.addPosition(0, [1], [10, 20]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[1, 2],
[10, 20],
[2, 3],
[3, 4],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('adds position to end of LineString', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [lineStringFeature],
});
const updatedFeatures = features.addPosition(0, [3], [10, 20]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[1, 2],
[2, 3],
[3, 4],
[10, 20],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('adds position in Polygon', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [polygonFeature],
});
const updatedFeatures = features
.addPosition(0, [0, 1], [0, -1])
.addPosition(0, [1, 4], [0, -0.5]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[
[-1, -1],
[0, -1],
[1, -1],
[1, 1],
[-1, 1],
[-1, -1],
],
[
[-0.5, -0.5],
[-0.5, 0.5],
[0.5, 0.5],
[0.5, -0.5],
[0, -0.5],
[-0.5, -0.5],
],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
});
describe('addFeature()', () => {
it(`doesn't mutate original`, () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [],
});
features.addFeature(pointFeature);
expect(features.getObject().features.length).toEqual(0);
});
it('adds feature to empty array', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [],
});
const actualFeatures = features.addFeature(pointFeature).getObject();
const expectedFeatures = {
type: 'FeatureCollection',
features: [pointFeature],
};
expect(actualFeatures).toEqual(expectedFeatures);
});
it('adds feature to end of array', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiPointFeature],
});
const actualFeatures = features.addFeature(multiLineStringFeature).getObject();
const expectedFeatures = {
type: 'FeatureCollection',
features: [multiPointFeature, multiLineStringFeature],
};
expect(actualFeatures).toEqual(expectedFeatures);
});
});
describe('addFeatures()', () => {
it(`doesn't mutate original`, () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [],
});
features.addFeatures([multiPointFeature, pointFeature]);
expect(features.getObject().features.length).toEqual(0);
});
it('adds features to empty array', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [],
});
const actualFeatures = features.addFeatures([multiPointFeature, pointFeature]).getObject();
const expectedFeatures = {
type: 'FeatureCollection',
features: [multiPointFeature, pointFeature],
};
expect(actualFeatures).toEqual(expectedFeatures);
});
it('adds features to end of array', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiPointFeature],
});
const actualFeatures = features.addFeatures([multiLineStringFeature]).getObject();
const expectedFeatures = {
type: 'FeatureCollection',
features: [multiPointFeature, multiLineStringFeature],
};
expect(actualFeatures).toEqual(expectedFeatures);
});
});
describe('deleteFeature()', () => {
it(`Do nothing when empty array`, () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [],
});
features.deleteFeature(0);
expect(features.getObject().features.length).toEqual(0);
});
it(`doesn't mutate original`, () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiPointFeature],
});
features.deleteFeature(0);
expect(features.getObject().features.length).toEqual(1);
});
it('delete feature', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiPointFeature, multiLineStringFeature],
});
const actualFeatures = features.deleteFeature(1).getObject();
const expectedFeatures = {
type: 'FeatureCollection',
features: [multiPointFeature],
};
expect(actualFeatures).toEqual(expectedFeatures);
});
});
describe('deleteFeatures()', () => {
it(`Do nothing when empty array`, () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [],
});
features.deleteFeatures([0, 1]);
expect(features.getObject().features.length).toEqual(0);
});
it(`doesn't mutate original`, () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiPointFeature],
});
features.deleteFeatures([0]);
expect(features.getObject().features.length).toEqual(1);
});
it('delete single feature', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiPointFeature, multiLineStringFeature],
});
const actualFeatures = features.deleteFeatures([1]).getObject();
const expectedFeatures = {
type: 'FeatureCollection',
features: [multiPointFeature],
};
expect(actualFeatures).toEqual(expectedFeatures);
});
it('delete multiple features', () => {
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
features: [multiPointFeature, multiLineStringFeature],
});
const actualFeatures = features.deleteFeatures([0, 1]).getObject();
const expectedFeatures = {
type: 'FeatureCollection',
features: [],
};
expect(actualFeatures).toEqual(expectedFeatures);
});
});
describe('replacePosition() with elevation', () => {
it('replaces position in Point', () => {
const elevatedPointFeature = {
type: 'Feature',
properties: {},
geometry: { type: 'Point', coordinates: [1, 2, 1000] },
};
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
// @ts-ignore
features: [elevatedPointFeature],
});
const updatedFeatures = features.replacePosition(0, [], [10, 20]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [10, 20, 1000];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
it('replaces first position in LineString', () => {
const elevatedLineStringFeature = {
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: [
[1, 2, 1000],
[2, 3, 2000],
[3, 4, 3000],
],
},
};
const features = new ImmutableFeatureCollection({
type: 'FeatureCollection',
// @ts-ignore
features: [elevatedLineStringFeature],
});
const updatedFeatures = features.replacePosition(0, [0], [10, 20]);
const actualCoordinates = updatedFeatures.getObject().features[0].geometry.coordinates;
const expectedCoordinates = [
[10, 20, 1000],
[2, 3, 2000],
[3, 4, 3000],
];
expect(actualCoordinates).toEqual(expectedCoordinates);
});
}); | the_stack |
import { debounce, find, flatten, isArray, pickBy } from 'lodash'
import { ProjectEventEmitter } from '@lib/frameworks/emitter'
import { IFramework } from '@lib/frameworks/framework'
import { ISuiteResult } from '@lib/frameworks/suite'
import { ITest, ITestResult } from '@lib/frameworks/test'
import { Status, parseStatus } from '@lib/frameworks/status'
/**
* Nuggets are the testable elements inside a repository
* (i.e. either a suite or a test).
*/
export abstract class Nugget extends ProjectEventEmitter {
public tests: Array<ITest> = []
public selected = false
public expanded = false
public partial = false
protected framework: IFramework
protected result?: any
protected fresh = false
protected bloomed = false
protected updateCountsListener: _.DebouncedFunc<(nugget: Nugget, toggle: boolean) => Promise<void>>
constructor (framework: IFramework) {
super(framework.getApplicationWindow())
this.framework = framework
this.updateCountsListener = debounce(this.updateSelectedCounts.bind(this), 50)
}
/**
* Get the nugget's id.
*/
public abstract getId (): string
/**
* Prepares the test for sending out to renderer process.
*
* @param status Which status to recursively set on tests. False will persist current status.
*/
public abstract render (status?: Status | false): ISuiteResult | ITestResult;
/**
* Instantiate a new test.
*
* @param result The test result with which to instantiate a new test.
*/
protected abstract newTest (result: ITestResult): ITest
/**
* Get this nugget's tests' results, if any.
*/
public getTestResults (): Array<ITestResult> {
return this.result.tests || []
}
/**
* Count this nugget's children.
*/
public countChildren (): number {
return this.bloomed
? this.tests.length
: this.getTestResults().length
}
/**
* Whether this nugget has children.
*/
public hasChildren (): boolean {
return this.countChildren() > 0
}
/**
* Returns a given test result object to default values.
*
* @param result The result object that will be persisted.
* @param status Which status to recursively set on tests. False will persist current status.
*/
protected defaults (result: ITestResult, status: Status | false = 'idle'): ITestResult {
return (pickBy({
id: result.id,
name: result.name,
displayName: result.displayName !== result.name ? result.displayName : null,
status: status || result.status,
// @TODO: Offload to separate store
feedback: result.feedback,
console: result.console,
params: result.params,
stats: result.stats,
// ...
tests: (result.tests || []).map((test: ITestResult) => this.defaults(test, status))
}, property => {
return isArray(property) ? property.length : !!property
}) as any)
}
/**
* Find the test by a given identifier in the nugget's current children.
*
* @param id The identifier of the test to try to find.
*/
public findTest (id: string): ITest | undefined {
return find(this.tests, test => test.getId() === id)
}
/**
* Factory function for creating a new child test.
*
* @param result The test result with which to instantiate a new test.
* @param force Whether to bypass looking for the test in the nugget's current children.
*/
protected makeTest (result: ITestResult, force = false): ITest {
let test: ITest | undefined | boolean = force ? false : this.findTest(result.id)
if (!test) {
test = this.newTest(result)
test.on('selected', this.updateCountsListener)
// If nugget is selected, newly created test should be, too.
test.selected = this.selected
this.tests.push(test)
}
return test
}
/**
* Trigger an update of this nugget's selected count.
*/
protected async updateSelectedCounts (): Promise<void> {
const total = this.tests.length
const selectedChildren = this.tests.filter(test => test.selected).length
const partial = selectedChildren > 0 && total > 0 && total > selectedChildren
// Update partial status
if (this.partial !== partial) {
this.partial = partial
this.emit('selective', this)
this.emitToRenderer(`${this.getId()}:selective`, this.render())
}
// Update whether this nugget should be selected or not, based on children
if (selectedChildren && !this.selected) {
this.toggleSelected(true, false)
} else if (!selectedChildren && this.selected) {
this.toggleSelected(false, false)
}
}
/**
* Debrief the tests inside this nugget.
*
* @param tests An array of test results.
* @param cleanup Whether to clean obsolete tests after debriefing. Can be overridden by the method's logic.
*/
protected async debriefTests (tests: Array<ITestResult>, cleanup: boolean): Promise<void> {
return new Promise((resolve, reject) => {
// Attempt to find out if this is the last test to run.
//
// 1) isLast === -1 : No `isLast` key is found on result object,
// which means the framework producing the results does not
// support debriefing state.
//
// 2) isLast === 0 : Framework supports debriefing state, but
// the result object is stating this is not the last test.
//
// 3) isLast > 0 : Framework supports debriefing state and
// result object is stating this is the last test.
//
const isLast = tests
.map(test => typeof test.isLast === 'undefined' ? -1 : Number(test.isLast))
.reduce((accumulator, value) => accumulator + value, 0)
// If test is marked as last, force cleanup.
if (isLast >= 1) {
cleanup = true
}
// If test is not marked as last, but `isLast` property was found
// on the test, override cleanup value.
if (isLast === 0) {
cleanup = false
}
Promise.all(tests.map((result: ITestResult) => {
return this.makeTest(result).debrief(result, cleanup)
})).then(() => {
this.afterDebrief(cleanup).then(() => {
resolve()
})
})
})
}
/**
* A function that runs after debriefing this nugget.
*
* @param cleanup Whether we should clean-up idle children (i.e. obsolete)
*/
protected async afterDebrief (cleanup: boolean): Promise<void> {
if (cleanup) {
this.cleanTestsByStatus('queued')
if (!this.expanded) {
await this.wither()
}
}
this.updateStatus()
if (this.expanded) {
this.emitTestsToRenderer()
}
}
/**
* Clean currently loaded tests by a given status.
*
* @param status The status by which to clean the tests.
*/
protected cleanTestsByStatus (status: Status): void {
this.tests = this.tests.filter(test => {
return test.getStatus() !== status
})
}
/**
* Get the status from a result object recursively. Useful to defer status
* calculations from reporters to the app's logic (e.g. Jest), when a
* chain of statuses cannot be reliably calculated in the reporter itself.
*
* @param result The test result we're extracting the status from
*/
protected getRecursiveStatus (result: ITestResult): Status {
if (!result.status) {
result.status = parseStatus((result.tests || []).map((test: ITestResult) => this.getRecursiveStatus(test)))
}
return result.status
}
/**
* Update this nugget's status.
*
* @param to The status we're updating to.
*/
protected updateStatus (to?: Status): void {
if (typeof to === 'undefined') {
const statuses = this.bloomed
? this.tests.map((test: ITest) => test.getStatus())
: this.getTestResults().map((test: ITestResult) => this.framework.getNuggetStatus(test.id))
to = parseStatus(statuses)
}
const from = this.getStatus()
if (to !== from) {
this.framework.setNuggetStatus(this.getId(), to, from, false)
}
}
/**
* Get this nugget's status.
*/
public getStatus (): Status {
return this.framework.getNuggetStatus(this.getId())
}
/**
* Whether the nugget can run tests selectively.
*/
public canToggleTests (): boolean {
return false
}
/**
* Toggle this nugget's selected state.
*
* @param toggle Whether it should be toggled on or off. Leave blank for inverting toggle.
* @param cascade Whether toggling should apply to nugget's children.
*/
public async toggleSelected (toggle?: boolean, cascade?: boolean): Promise<void> {
this.selected = typeof toggle === 'undefined' ? !this.selected : toggle
// Selected nuggets should always bloom its tests.
if (this.selected) {
await this.bloom()
} else if (!this.expanded) {
await this.wither()
}
if (this.canToggleTests() && cascade !== false) {
this.tests.forEach(test => {
test.toggleSelected(this.selected, true)
})
}
this.emit('selected', this, toggle)
this.emitToRenderer(`${this.getId()}:selected`, this.render(), toggle)
}
/**
* Toggle this nugget's expanded state.
*
* @param toggle Whether it should be expanded or collapsed. Leave blank for inverting toggle.
* @param cascade Whether toggling should apply to nugget's children.
*/
public async toggleExpanded (toggle?: boolean, cascade?: boolean): Promise<void> {
this.expanded = typeof toggle === 'undefined' ? !this.expanded : toggle
if (this.expanded) {
await this.bloom()
} else {
await this.wither()
}
if (cascade !== false) {
this.tests.forEach(test => {
test.toggleExpanded(this.expanded)
})
}
}
/**
* Make the test objects nested to this nugget.
*/
protected async bloom (): Promise<void> {
if (this.bloomed) {
return
}
return new Promise((resolve, reject) => {
this.tests = this.getTestResults().map((result: ITestResult) => {
return this.makeTest(result, true)
})
this.bloomed = true
resolve()
})
}
/**
* Destroy the test objects nested to this nugget, leaving only the static
* JSON structure with which to build them again.
*/
protected async wither (): Promise<void> {
if (!this.bloomed) {
return
}
// Never wither a selected nugget.
if (this.selected) {
return
}
this.result.tests = this.tests.map((test: ITest) => test.persist(false))
this.tests = []
this.bloomed = false
}
/**
* Set the freshness state of a nugget.
*
* @param fresh The freshness state to set.
*/
public setFresh (fresh: boolean): void {
this.fresh = fresh
}
/**
* Get the freshness state of a nugget.
*/
public isFresh (): boolean {
return this.fresh
}
/**
* Send all tests to renderer process.
*/
public async emitTestsToRenderer (): Promise<void> {
if (!this.bloomed) {
await this.bloom()
}
this.emitToRenderer(
`${this.getId()}:framework-tests`,
this.tests.map((test: ITest) => test.render(false))
)
}
/**
* Get the ids of this nuggets and its children.
*/
protected getRecursiveNuggetIds (result: ITestResult): Array<string> {
return flatten([
result.id,
...(result.tests || []).map((test: ITestResult) => {
return this.getRecursiveNuggetIds(test)
})
])
}
/**
* A chance for nuggets to append items to the context menus of
* their representation in the renderer.
*/
public contextMenu (): Array<Electron.MenuItemConstructorOptions> {
return []
}
} | the_stack |
import { getZapParamType } from "common";
import { BufferData, MutableBufferData, ZapArray, ZapParamType } from "types";
import { inTest } from "test_suite/test_helpers";
// TODO(Paras) - Make sure we monkeypatch on web workers as well
export class ZapBuffer extends SharedArrayBuffer {
// This class supports both SharedArrayBuffer (wasm usecase) and ArrayBuffer (CEF)
// In the future we can migrate to SharedArrayBuffer-s only once CEF supports those
__zaplibWasmBuffer: SharedArrayBuffer | ArrayBuffer;
__zaplibBufferData: BufferData;
constructor(buffer: SharedArrayBuffer | ArrayBuffer, bufferData: BufferData) {
super(0);
this.__zaplibWasmBuffer = buffer;
this.__zaplibBufferData = bufferData;
}
// TODO(Paras): Actually enforce this flag and prevent mutation of ZapArrays marked as readonly.
// Potentially, we can do this by hashing read only buffer data and periodically checking in debug
// builds if they have been modified/raising errors.
get readonly(): boolean {
return this.__zaplibBufferData.readonly;
}
// The only 2 methods on SharedArrayBuffer class to override:
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#instance_properties
get byteLength(): number {
return this.__zaplibWasmBuffer.byteLength;
}
slice(...args: Parameters<SharedArrayBuffer["slice"]>): any {
return this.__zaplibWasmBuffer.slice(...args);
}
}
// This class is a drop-in replacement for all typed arrays
// It uses ZapBuffer as a handle for underlying buffer as the object that keeps underlying data around
// Requirements:
// * The underlying typed array behaves like it was created over the original view
// * When the new typed array (potentially with different class name) is created from the buffer of the original one,
// they share the same handle
//
// The Rust side assumes that underlying data buffer is immutable,
// however it still could be accidentally modified on JS side leading to weird behavior
// TODO(Dmitry): Throw an error if there is mutation of the data
function zapBufferExtends(cls: any) {
return class ZapTypedArray extends cls {
constructor(...args: any) {
const buffer = args[0];
if (typeof buffer === "object" && buffer instanceof ZapBuffer) {
// Fill in byteOffset if that's omitted.
if (args.length < 2) {
args[1] = buffer.__zaplibBufferData.bufferPtr;
}
// Fill in length (in elements, not in bytes) if that's omitted.
if (args.length < 3) {
args[2] = Math.floor(
(buffer.__zaplibBufferData.bufferPtr +
buffer.__zaplibBufferData.bufferLen -
args[1]) /
cls.BYTES_PER_ELEMENT
);
}
if (args[1] < buffer.__zaplibBufferData.bufferPtr) {
throw new Error(`Byte_offset ${args[1]} is out of bounds`);
}
if (
args[1] + args[2] * cls.BYTES_PER_ELEMENT >
buffer.__zaplibBufferData.bufferPtr +
buffer.__zaplibBufferData.bufferLen
) {
throw new Error(
`Byte_offset ${args[1]} + length ${args[2]} is out of bounds`
);
}
// Whenever we create ZapUintArray using ZapBuffer as first argument
// pass the underlying full wasm_buffer further
args[0] = buffer.__zaplibWasmBuffer;
super(...args);
this.__zaplibBuffer = buffer;
} else {
super(...args);
}
}
get buffer() {
return this.__zaplibBuffer || super.buffer;
}
subarray(begin = 0, end = this.length) {
if (begin < 0) {
begin = this.length + begin;
}
if (end < 0) {
end = this.length + end;
}
if (end < begin) {
end = begin;
}
return new ZapTypedArray(
this.buffer,
this.byteOffset + begin * this.BYTES_PER_ELEMENT,
end - begin
);
}
};
}
// Extending all typed arrays
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects#indexed_collections
export const classesToExtend = {
Int8Array: "ZapInt8Array",
Uint8Array: "ZapUint8Array",
Uint8ClampedArray: "ZapUint8ClampedArray",
Int16Array: "ZapInt16Array",
Uint16Array: "ZapUint16Array",
Uint16ClampedArray: "ZapUint16ClampedArray",
Int32Array: "ZapInt32Array",
Uint32Array: "ZapUint32Array",
Float32Array: "ZapFloat32Array",
Float64Array: "ZapFloat64Array",
BigInt64Array: "ZapBigInt64Array",
BigUint64Array: "ZapBigUint64Array",
DataView: "ZapDataView",
};
for (const [cls, zapCls] of Object.entries(classesToExtend)) {
// Get a new type name by prefixing old one with "Zaplib".
// e.g. Uint8Array is extended by ZapUint8Array, etc
if (cls in globalThis) {
// @ts-ignore
globalThis[zapCls] = zapBufferExtends(globalThis[cls]);
}
}
// Checks if the given object itself or recursively contains ZapBuffers.
// Exported for tests.
export function containsZapBuffer(object: unknown): boolean {
if (typeof object != "object" || object === null) {
return false;
}
if (Object.prototype.hasOwnProperty.call(object, "__zaplibBuffer")) {
return true;
}
// Only supporting nesting for arrays, plain objects, maps and sets similar to StructuredClone algorithm
// See https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types
if (Array.isArray(object) || object instanceof Set || object instanceof Map) {
for (const entry of object) {
if (containsZapBuffer(entry)) {
return true;
}
}
} else if (Object.getPrototypeOf(object) === Object.getPrototypeOf({})) {
for (const entry of Object.entries(object)) {
if (containsZapBuffer(entry)) {
return true;
}
}
}
return false;
}
function patchPostMessage(cls: any) {
const origPostMessage = cls.postMessage;
// Explicitly NOT a fat arrow (=>) since we want to keep the original `this`.
cls.postMessage = function (...args: Parameters<Worker["postMessage"]>) {
if (containsZapBuffer(args[0])) {
// TODO(Dmitry): add a better error message showing the exact location of typed arrays
throw new Error(
"Sending ZapBuffers to/from workers is not supported - " +
"use .slice() on typed array instead to make an explicit copy"
);
}
origPostMessage.apply(this, args);
};
}
let overwriteTypedArraysWithZapArraysCalled = false;
export function overwriteTypedArraysWithZapArrays(): void {
// Make sure this is called at most once
if (overwriteTypedArraysWithZapArraysCalled) return;
for (const [cls, zapCls] of Object.entries(classesToExtend)) {
if (cls in globalThis) {
// @ts-ignore
globalThis[cls] = globalThis[zapCls];
}
}
patchPostMessage(globalThis);
// In Safari nested workers are not defined.
if (globalThis.Worker) {
patchPostMessage(globalThis.Worker);
}
// Skipping this in nodejs case as web-worker polyfill doesn't provide MessagePort
if (globalThis.MessagePort) {
patchPostMessage(globalThis.MessagePort);
}
overwriteTypedArraysWithZapArraysCalled = true;
}
const zapBufferCache = new WeakMap<ZapBuffer, ZapArray>();
export function getCachedZapBuffer(
zapBuffer: ZapBuffer,
fallbackArray: ZapArray
): ZapArray {
if (
!(
// Overwrite the cached value if we return a pointer to a buffer of a different type
// For example, Rust code may cast a float to an u8 and return the same buffer pointer.
(
zapBufferCache.get(zapBuffer)?.BYTES_PER_ELEMENT ===
fallbackArray.BYTES_PER_ELEMENT
)
)
) {
zapBufferCache.set(zapBuffer, fallbackArray);
}
return zapBufferCache.get(zapBuffer) as ZapArray;
}
export function isZapBuffer(potentialZapBuffer: ArrayBufferLike): boolean {
return (
typeof potentialZapBuffer === "object" &&
potentialZapBuffer instanceof ZapBuffer
);
}
export function checkValidZapArray(zapArray: ZapArray): void {
if (!isZapBuffer(zapArray.buffer)) {
throw new Error("zapArray.buffer is not a ZapBuffer in checkValidZapArray");
}
const buffer = zapArray.buffer as ZapBuffer;
const bufferCoversZapBuffer =
zapArray.byteOffset === buffer.__zaplibBufferData.bufferPtr &&
zapArray.byteLength === buffer.__zaplibBufferData.bufferLen;
if (!bufferCoversZapBuffer) {
throw new Error(
"Called Rust with a buffer that does not span the entire underlying ZapBuffer"
);
}
const paramType = getZapParamType(zapArray, buffer.readonly);
if (paramType !== buffer.__zaplibBufferData.paramType) {
throw new Error(
`Cannot call Rust with a buffer which has been cast to a different type. Expected ${
ZapParamType[buffer.__zaplibBufferData.paramType]
} but got ${ZapParamType[paramType]}`
);
}
}
// Cache ZapBuffers so that we have a stable identity for ZapBuffers pointing to the same
// Arc. This is useful for any downstream caches in user code.
const bufferCache: { [arcPtr: number]: WeakRef<ZapBuffer> } = {};
export const allocatedArcs: Record<number, boolean> = {};
export const allocatedVecs: Record<number, boolean> = {};
const bufferRegistry = new FinalizationRegistry(
({
arcPtr,
destructor,
}: {
arcPtr: number;
destructor?: (arcPtr: number) => void;
}) => {
if (inTest) {
if (allocatedArcs[arcPtr] === false) {
throw new Error(`Deallocating an already deallocated arcPtr ${arcPtr}`);
} else if (allocatedArcs[arcPtr] === undefined) {
throw new Error(`Deallocating an unallocated arcPtr ${arcPtr}`);
}
allocatedArcs[arcPtr] = false;
}
delete bufferCache[arcPtr];
if (destructor) destructor(arcPtr);
}
);
const mutableZapBufferRegistry = new FinalizationRegistry(
({
bufferData,
destructor,
}: {
bufferData: MutableBufferData;
destructor: (bufferData: MutableBufferData) => void;
}) => {
if (inTest) {
const { bufferPtr } = bufferData;
if (allocatedVecs[bufferPtr] === false) {
throw new Error(
`Deallocating an already deallocated bufferPtr ${bufferPtr}`
);
} else if (allocatedVecs[bufferPtr] === undefined) {
throw new Error(`Deallocating an unallocated bufferPtr ${bufferPtr}`);
}
allocatedVecs[bufferPtr] = false;
}
destructor(bufferData);
}
);
// Return a buffer with a stable identity based on arcPtr.
// Register callbacks so we de-allocate the buffer when it goes out of scope.
export const getZapBufferWasm = (
wasmMemory: WebAssembly.Memory,
bufferData: BufferData,
destructor: (arcPtr: number) => void,
mutableDestructor: (bufferData: MutableBufferData) => void
): ZapBuffer => {
if (bufferData.readonly) {
if (!bufferCache[bufferData.arcPtr]?.deref()) {
if (inTest) {
allocatedArcs[bufferData.arcPtr] = true;
}
const zapBuffer = new ZapBuffer(wasmMemory.buffer, bufferData);
bufferRegistry.register(zapBuffer, {
arcPtr: bufferData.arcPtr,
destructor,
/* no unregisterToken here since we never need to unregister */
});
bufferCache[bufferData.arcPtr] = new WeakRef(zapBuffer);
} else {
// If we already hold a reference, decrement the Arc we were just given;
// otherwise we leak memory.
destructor(bufferData.arcPtr);
}
return bufferCache[bufferData.arcPtr].deref() as ZapBuffer;
} else {
if (inTest) {
allocatedVecs[bufferData.bufferPtr] = true;
}
const zapBuffer = new ZapBuffer(wasmMemory.buffer, bufferData);
mutableZapBufferRegistry.register(
zapBuffer,
{
bufferData,
destructor: mutableDestructor,
},
zapBuffer
);
return zapBuffer;
}
};
// Remove mutable ZapBuffers without running destructors. This is useful
// when transferring ownership of buffers to Rust without deallocating data.
export const unregisterMutableBuffer = (zapBuffer: ZapBuffer): void => {
if (zapBuffer.readonly) {
throw new Error(
"`unregisterMutableBuffer` should only be called on mutable ZapBuffers"
);
}
mutableZapBufferRegistry.unregister(zapBuffer);
if (inTest) {
allocatedVecs[zapBuffer.__zaplibBufferData.bufferPtr] = false;
}
};
// Return a buffer with a stable identity based on arcPtr
export const getZapBufferCef = (
buffer: ArrayBuffer,
arcPtr: number | undefined,
paramType: ZapParamType
): ZapBuffer => {
if (arcPtr) {
if (!bufferCache[arcPtr]?.deref()) {
const zapBuffer = new ZapBuffer(buffer, {
bufferPtr: 0,
bufferLen: buffer.byteLength,
readonly: true,
paramType,
// TODO(Paras): These fields below do not apply to CEF
arcPtr: -1,
});
bufferRegistry.register(zapBuffer, { arcPtr });
bufferCache[arcPtr] = new WeakRef(zapBuffer);
}
return bufferCache[arcPtr].deref() as ZapBuffer;
} else {
return new ZapBuffer(buffer, {
bufferPtr: 0,
bufferLen: buffer.byteLength,
bufferCap: buffer.byteLength,
paramType,
readonly: false,
});
}
}; | the_stack |
import { AppStoreModel, PlayerStoreModel } from '../stores/AppStoreModel';
import Player from '../libraries/Player';
import {
shuffleList,
updatePlayerStateCursor,
updatePlayerState,
} from '../utilities/QueueUtils';
// tslint:disable-next-line:import-name
import produce from 'immer';
export async function togglePlayPause(
state?: AppStoreModel
): Promise<AppStoreModel> {
return produce<AppStoreModel>(state, draft => {
draft.player.playing ? Player.pause() : Player.play();
draft.player.playing = !draft.player.playing;
});
}
export async function nextSong(state?: AppStoreModel): Promise<AppStoreModel> {
return produce<AppStoreModel>(state, draft => {
let cursor;
if (draft.settings.player.repeat) {
Player.replay();
} else {
cursor = draft.player.cursor + 1;
cursor = cursor === draft.player.queue.length ? 0 : cursor;
Player.setAudioSrc(draft.player.queue[cursor].source);
Player.play();
draft.player.cursor = cursor;
updatePlayerStateCursor(cursor);
}
});
}
export async function prevSong(state?: AppStoreModel): Promise<AppStoreModel> {
return produce<AppStoreModel>(state, draft => {
let cursor;
if (draft.settings.player.repeat) {
Player.replay();
} else {
cursor = draft.player.cursor - 1;
cursor = cursor === -1 ? draft.player.queue.length - 1 : cursor;
Player.setAudioSrc(draft.player.queue[cursor].source);
Player.play();
draft.player.cursor = cursor;
updatePlayerStateCursor(cursor);
}
});
}
export async function shuffleToggle(
state?: AppStoreModel
): Promise<AppStoreModel> {
return produce<AppStoreModel>(state, draft => {
// Shuffle Code here. Use Fisher-Yates Shuffle Algorithm.
const trackId = draft.player.queue[draft.player.cursor].id;
if (draft.settings.player.shuffle) {
const shuffled = shuffleList([...draft.player.queue]);
draft.player.queue = shuffled;
draft.player.cursor = shuffled.findIndex(i => i.id === trackId);
} else {
draft.player.queue = draft.player.originalQueue;
draft.player.cursor = draft.player.originalQueue.findIndex(
i => i.id === trackId
);
}
updatePlayerStateCursor(draft.player.cursor);
});
}
export async function seekSong(
index: number,
state?: AppStoreModel
): Promise<AppStoreModel> {
return produce<AppStoreModel>(state, draft => {
Player.setAudioSrc(draft.player.queue[index].source);
Player.play();
draft.player.cursor = index;
updatePlayerStateCursor(index);
});
}
export async function createPlayerQueue(
index: number,
state?: AppStoreModel
): Promise<AppStoreModel> {
return produce<AppStoreModel>(state, draft => {
const trackId = draft.library[index].id;
if (draft.settings.player.shuffle) {
let shuffled = shuffleList([...draft.library]);
let newindex = shuffled.findIndex(i => i.id === trackId);
Player.setAudioSrc(shuffled[newindex].source);
Player.play();
// Data Assignments
draft.player.queue = shuffled;
draft.player.originalQueue = draft.library;
draft.player.cursor = newindex;
draft.player.playing = true;
} else {
Player.setAudioSrc(draft.library[index].source);
Player.play();
// Data Assignments
draft.player.queue = draft.library;
draft.player.originalQueue = draft.library;
draft.player.cursor = index;
draft.player.playing = true;
}
let queue: number[] = draft.player.queue.map(value => value.id);
let originalQueue: number[] = draft.player.originalQueue.map(
value => value.id
);
updatePlayerState(queue, originalQueue, draft.player.cursor);
});
}
export async function newQueue(index: number, state?: AppStoreModel) {
return produce(state, draft => {
draft.player.queue = [];
draft.player.originalQueue = [];
draft.player.originalQueue.push(draft.library[index]);
draft.player.queue.push(draft.library[index]);
draft.player.cursor = 0;
draft.player.playing = true;
Player.setAudioSrc(draft.player.queue[0].source);
Player.play();
updatePlayerState(
[draft.player.queue[0].id],
[draft.player.queue[0].id],
0
);
});
}
export async function existingQueue(index: number, state?: AppStoreModel) {
return produce(state, draft => {
draft.player.originalQueue.push(draft.library[index]);
draft.player.queue.push(draft.library[index]);
if (draft.settings.player.shuffle && draft.player.queue.length > 1) {
const trackId = draft.player.queue[draft.player.cursor].id;
let shuffled = shuffleList([...draft.player.queue]);
let newindex = shuffled.findIndex(i => i.id === trackId);
draft.player.queue = shuffled;
draft.player.cursor = newindex;
}
if (draft.player.queue.length === 1) {
draft.player.cursor = 0;
draft.player.playing = true;
Player.setAudioSrc(draft.player.queue[0].source);
Player.play();
}
let queue: number[] = draft.player.queue.map(value => value.id);
let originalQueue: number[] = draft.player.originalQueue.map(
value => value.id
);
updatePlayerState(queue, originalQueue, draft.player.cursor);
});
}
export async function createPlayerQueueFromPlaylist(
index: number,
state?: AppStoreModel
): Promise<AppStoreModel> {
return produce<AppStoreModel>(state, draft => {
const trackId = draft.playlist.currentTracks[index].id;
if (draft.settings.player.shuffle) {
let shuffled = shuffleList([...draft.playlist.currentTracks]);
let newindex = shuffled.findIndex(i => i.id === trackId);
Player.setAudioSrc(shuffled[newindex].source);
Player.play();
// Data Assignments
draft.player.queue = shuffled;
draft.player.originalQueue = draft.playlist.currentTracks;
draft.player.cursor = newindex;
draft.player.playing = true;
} else {
Player.setAudioSrc(draft.playlist.currentTracks[index].source);
Player.play();
// Data Assignments
draft.player.queue = draft.playlist.currentTracks;
draft.player.originalQueue = draft.playlist.currentTracks;
draft.player.cursor = index;
draft.player.playing = true;
}
let queue: number[] = draft.player.queue.map(value => value.id);
let originalQueue: number[] = draft.player.originalQueue.map(
value => value.id
);
updatePlayerState(queue, originalQueue, draft.player.cursor);
});
}
export async function newQueueFromPlaylist(index: number, state?: AppStoreModel) {
return produce(state, draft => {
draft.player.queue = [];
draft.player.originalQueue = [];
draft.player.originalQueue.push(draft.playlist.currentTracks[index]);
draft.player.queue.push(draft.playlist.currentTracks[index]);
draft.player.cursor = 0;
draft.player.playing = true;
Player.setAudioSrc(draft.player.queue[0].source);
Player.play();
updatePlayerState(
[draft.player.queue[0].id],
[draft.player.queue[0].id],
0
);
});
}
export async function existingQueueFromPlaylist(index: number, state?: AppStoreModel) {
return produce(state, draft => {
draft.player.originalQueue.push(draft.playlist.currentTracks[index]);
draft.player.queue.push(draft.playlist.currentTracks[index]);
if (draft.settings.player.shuffle && draft.player.queue.length > 1) {
const trackId = draft.player.queue[draft.player.cursor].id;
let shuffled = shuffleList([...draft.player.queue]);
let newindex = shuffled.findIndex(i => i.id === trackId);
draft.player.queue = shuffled;
draft.player.cursor = newindex;
}
if (draft.player.queue.length === 1) {
draft.player.cursor = 0;
draft.player.playing = true;
Player.setAudioSrc(draft.player.queue[0].source);
Player.play();
}
let queue: number[] = draft.player.queue.map(value => value.id);
let originalQueue: number[] = draft.player.originalQueue.map(
value => value.id
);
updatePlayerState(queue, originalQueue, draft.player.cursor);
});
}
export async function removeFromQueue(index: number, state?: AppStoreModel) {
return produce(state, draft => {
let ind = draft.player.originalQueue.findIndex(
element => element.id === draft.player.queue[index].id
);
if (index < draft.player.cursor) {
draft.player.cursor -= 1;
} else if (index === draft.player.cursor) {
Player.setAudioSrc(draft.player.queue[index + 1].source);
Player.play();
}
draft.player.originalQueue.splice(ind, 1);
draft.player.queue.splice(index, 1);
let queue: number[] = draft.player.queue.map(value => value.id);
let originalQueue: number[] = draft.player.originalQueue.map(
value => value.id
);
updatePlayerState(queue, originalQueue, draft.player.cursor);
});
}
export async function clearQueue(state?: AppStoreModel) {
return produce(state, draft => {
draft.player.queue = [];
draft.player.originalQueue = [];
draft.player.playing = false;
draft.player.cursor = -2;
Player.reset();
updatePlayerState([], [], -2);
});
} | the_stack |
import {
InstanceClass,
InstanceSize,
InstanceType,
} from '@aws-cdk/aws-ec2';
import { Expiration } from '@aws-cdk/core';
import * as AWS from 'aws-sdk';
import {
SpotEventPluginDisplayInstanceStatus,
SpotEventPluginLoggingLevel,
SpotEventPluginPreJobTaskMode,
SpotEventPluginState,
SpotFleetAllocationStrategy,
SpotFleetRequestType,
SpotFleetResourceType,
} from '../../../../deadline';
import { SEPConfiguratorResource } from '../handler';
import {
ConnectionOptions,
SEPConfiguratorResourceProps,
PluginSettings,
SpotFleetRequestConfiguration,
LaunchSpecification,
SpotFleetRequestProps,
} from '../types';
jest.mock('../../lib/secrets-manager/read-certificate');
const secretArn: string = 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert';
// @ts-ignore
async function successRequestMock(request: { [key: string]: string}, returnValue: any): Promise<{ [key: string]: any }> {
return returnValue;
}
describe('SEPConfiguratorResource', () => {
const validConnection: ConnectionOptions = {
hostname: 'internal-hostname.com',
protocol: 'HTTPS',
port: '4433',
caCertificateArn: secretArn,
};
const validLaunchSpecification: LaunchSpecification = {
IamInstanceProfile: {
Arn: 'iamInstanceProfileArn',
},
ImageId: 'any-ami',
InstanceType: InstanceType.of(InstanceClass.T2, InstanceSize.SMALL).toString(),
SecurityGroups: [{
GroupId: 'sg-id',
}],
TagSpecifications: [{
ResourceType: SpotFleetResourceType.INSTANCE,
Tags: [
{
Key: 'name',
Value: 'test',
},
],
}],
UserData: 'userdata',
KeyName: 'keyname',
SubnetId: 'subnet-id',
BlockDeviceMappings: [{
DeviceName: 'device',
NoDevice: '',
VirtualName: 'virtualname',
Ebs: {
DeleteOnTermination: true,
Encrypted: true,
Iops: 10,
SnapshotId: 'snapshot-id',
VolumeSize: 10,
VolumeType: 'volume-type',
},
}],
};
const validSpotFleetRequestProps: SpotFleetRequestProps = {
AllocationStrategy: SpotFleetAllocationStrategy.CAPACITY_OPTIMIZED,
IamFleetRole: 'roleArn',
LaunchSpecifications: [validLaunchSpecification],
ReplaceUnhealthyInstances: true,
TargetCapacity: 1,
TerminateInstancesWithExpiration: true,
Type: SpotFleetRequestType.MAINTAIN,
TagSpecifications: [{
ResourceType: SpotFleetResourceType.SPOT_FLEET_REQUEST,
Tags: [
{
Key: 'name',
Value: 'test',
},
],
}],
ValidUntil: Expiration.atDate(new Date(2022, 11, 17)).date.toISOString(),
};
const validConvertedLaunchSpecifications = {
BlockDeviceMappings: [{
DeviceName: 'device',
Ebs: {
DeleteOnTermination: true,
Encrypted: true,
Iops: 10,
SnapshotId: 'snapshot-id',
VolumeSize: 10,
VolumeType: 'volume-type',
},
NoDevice: '',
VirtualName: 'virtualname',
}],
IamInstanceProfile: {
Arn: 'iamInstanceProfileArn',
},
ImageId: 'any-ami',
KeyName: 'keyname',
SecurityGroups: [{
GroupId: 'sg-id',
}],
SubnetId: 'subnet-id',
TagSpecifications: [{
ResourceType: 'instance',
Tags: [
{
Key: 'name',
Value: 'test',
},
],
}],
UserData: 'userdata',
InstanceType: 't2.small',
};
const validConvertedSpotFleetRequestProps = {
AllocationStrategy: 'capacityOptimized',
IamFleetRole: 'roleArn',
LaunchSpecifications: [validConvertedLaunchSpecifications],
ReplaceUnhealthyInstances: true,
TargetCapacity: 1,
TerminateInstancesWithExpiration: true,
Type: 'maintain',
ValidUntil: Expiration.atDate(new Date(2022, 11, 17)).date.toISOString(),
TagSpecifications: [{
ResourceType: 'spot-fleet-request',
Tags: [
{
Key: 'name',
Value: 'test',
},
],
}],
};
const validSpotFleetRequestConfig: SpotFleetRequestConfiguration = {
group_name1: validSpotFleetRequestProps,
};
const validConvertedSpotFleetRequestConfig = {
group_name1: validConvertedSpotFleetRequestProps,
};
const validSpotEventPluginConfig: PluginSettings = {
AWSInstanceStatus: SpotEventPluginDisplayInstanceStatus.DISABLED,
DeleteInterruptedSlaves: true,
DeleteTerminatedSlaves: true,
IdleShutdown: 20,
Logging: SpotEventPluginLoggingLevel.STANDARD,
PreJobTaskMode: SpotEventPluginPreJobTaskMode.CONSERVATIVE,
Region: 'us-west-2',
ResourceTracker: true,
StaggerInstances: 50,
State: SpotEventPluginState.GLOBAL_ENABLED,
StrictHardCap: true,
};
const validConvertedPluginConfig = {
AWSInstanceStatus: 'Disabled',
DeleteInterruptedSlaves: true,
DeleteTerminatedSlaves: true,
IdleShutdown: 20,
Logging: 'Standard',
PreJobTaskMode: 'Conservative',
Region: 'us-west-2',
ResourceTracker: true,
StaggerInstances: 50,
State: 'Global Enabled',
StrictHardCap: true,
};
// Valid configurations
const noPluginConfigs: SEPConfiguratorResourceProps = {
connection: validConnection,
spotFleetRequestConfigurations: validSpotFleetRequestConfig,
};
const noFleetRequestConfigs: SEPConfiguratorResourceProps = {
spotPluginConfigurations: validSpotEventPluginConfig,
connection: validConnection,
};
const deadlineGroups = ['group_name'];
const deadlinePools = ['pool_name'];
const allConfigs: SEPConfiguratorResourceProps = {
spotPluginConfigurations: validSpotEventPluginConfig,
connection: validConnection,
spotFleetRequestConfigurations: validSpotFleetRequestConfig,
deadlineGroups,
deadlinePools,
};
const noConfigs: SEPConfiguratorResourceProps = {
connection: validConnection,
};
async function returnTrue(_v1: any): Promise<boolean> {
return true;
}
async function returnFalse(_v1: any): Promise<boolean> {
return false;
}
describe('doCreate', () => {
let handler: SEPConfiguratorResource;
let mockSpotEventPluginClient: {
saveServerData: jest.Mock<any, any>;
configureSpotEventPlugin: jest.Mock<any, any>;
addGroups: jest.Mock<any, any>;
addPools: jest.Mock<any, any>;
};
beforeEach(() => {
mockSpotEventPluginClient = {
saveServerData: jest.fn( (a) => returnTrue(a) ),
configureSpotEventPlugin: jest.fn( (a) => returnTrue(a) ),
addGroups: jest.fn( (a) => returnTrue(a) ),
addPools: jest.fn( (a) => returnTrue(a) ),
};
handler = new SEPConfiguratorResource(new AWS.SecretsManager());
jest.requireMock('../../lib/secrets-manager/read-certificate').readCertificateData.mockReturnValue(Promise.resolve('BEGIN CERTIFICATE'));
async function returnSpotEventPluginClient(_v1: any): Promise<any> {
return mockSpotEventPluginClient;
}
// eslint-disable-next-line dot-notation
handler['spotEventPluginClient'] = jest.fn( (a) => returnSpotEventPluginClient(a) );
});
afterEach(() => {
jest.clearAllMocks();
});
test('with no configs', async () => {
// GIVEN
const mockSaveServerData = jest.fn( (a) => returnTrue(a) );
mockSpotEventPluginClient.saveServerData = mockSaveServerData;
const mockConfigureSpotEventPlugin = jest.fn( (a) => returnTrue(a) );
mockSpotEventPluginClient.configureSpotEventPlugin = mockConfigureSpotEventPlugin;
// WHEN
const result = await handler.doCreate('physicalId', noConfigs);
// THEN
expect(result).toBeUndefined();
expect(mockSaveServerData.mock.calls.length).toBe(0);
expect(mockConfigureSpotEventPlugin.mock.calls.length).toBe(0);
});
test('save spot fleet request configs', async () => {
// GIVEN
const mockSaveServerData = jest.fn( (a) => returnTrue(a) );
mockSpotEventPluginClient.saveServerData = mockSaveServerData;
// WHEN
const result = await handler.doCreate('physicalId', noPluginConfigs);
// THEN
expect(result).toBeUndefined();
expect(mockSaveServerData.mock.calls.length).toBe(1);
const calledWithString = mockSaveServerData.mock.calls[0][0];
const calledWithObject = JSON.parse(calledWithString);
expect(calledWithObject).toEqual(validConvertedSpotFleetRequestConfig);
});
test('save spot fleet request configs without BlockDeviceMappings', async () => {
// GIVEN
const mockSaveServerData = jest.fn( (a) => returnTrue(a) );
mockSpotEventPluginClient.saveServerData = mockSaveServerData;
const noEbs = {
...noPluginConfigs,
spotFleetRequestConfigurations: {
...validSpotFleetRequestConfig,
group_name1: {
...validSpotFleetRequestProps,
LaunchSpecifications: [
{
...validLaunchSpecification,
BlockDeviceMappings: undefined,
},
],
},
},
};
const convertedNoEbs = {
...validConvertedSpotFleetRequestConfig,
group_name1: {
...validConvertedSpotFleetRequestProps,
LaunchSpecifications: [
{
...validConvertedLaunchSpecifications,
BlockDeviceMappings: undefined,
},
],
},
};
// WHEN
await handler.doCreate('physicalId', noEbs);
const calledWithString = mockSaveServerData.mock.calls[0][0];
const calledWithObject = JSON.parse(calledWithString);
// THEN
expect(calledWithObject).toEqual(convertedNoEbs);
});
test('save spot fleet request configs without Ebs', async () => {
// GIVEN
const mockSaveServerData = jest.fn( (a) => returnTrue(a) );
mockSpotEventPluginClient.saveServerData = mockSaveServerData;
const blockDevicesNoEbs = [{
DeviceName: 'device',
}];
const noEbs = {
...noPluginConfigs,
spotFleetRequestConfigurations: {
...validSpotFleetRequestConfig,
group_name1: {
...validSpotFleetRequestProps,
LaunchSpecifications: [
{
...validLaunchSpecification,
BlockDeviceMappings: blockDevicesNoEbs,
},
],
},
},
};
const convertedNoEbs = {
...validConvertedSpotFleetRequestConfig,
group_name1: {
...validConvertedSpotFleetRequestProps,
LaunchSpecifications: [
{
...validConvertedLaunchSpecifications,
BlockDeviceMappings: blockDevicesNoEbs,
},
],
},
};
// WHEN
await handler.doCreate('physicalId', noEbs);
const calledWithString = mockSaveServerData.mock.calls[0][0];
const calledWithObject = JSON.parse(calledWithString);
// THEN
expect(calledWithObject).toEqual(convertedNoEbs);
});
test('save spot event plugin configs', async () => {
// GIVEN
const mockConfigureSpotEventPlugin = jest.fn( (a) => returnTrue(a) );
mockSpotEventPluginClient.configureSpotEventPlugin = mockConfigureSpotEventPlugin;
const configs: { Key: string, Value: any }[] = [];
for (const [key, value] of Object.entries(validConvertedPluginConfig)) {
configs.push({
Key: key,
Value: value,
});
}
const securitySettings = [{
Key: 'UseLocalCredentials',
Value: true,
},
{
Key: 'NamedProfile',
Value: '',
}];
// WHEN
const result = await handler.doCreate('physicalId', noFleetRequestConfigs);
// THEN
expect(result).toBeUndefined();
expect(mockConfigureSpotEventPlugin.mock.calls.length).toBe(1);
expect(mockConfigureSpotEventPlugin.mock.calls[0][0]).toEqual([...configs, ...securitySettings]);
});
test('save server data', async () => {
// GIVEN
const mockSaveServerData = jest.fn( (a) => returnTrue(a) );
mockSpotEventPluginClient.saveServerData = mockSaveServerData;
// WHEN
const result = await handler.doCreate('physicalId', allConfigs);
// THEN
expect(result).toBeUndefined();
expect(mockSaveServerData.mock.calls.length).toBe(1);
expect(mockSaveServerData.mock.calls[0][0]).toEqual(JSON.stringify(validConvertedSpotFleetRequestConfig));
});
test('configure spot event plugin', async () => {
// GIVEN
const mockConfigureSpotEventPlugin = jest.fn( (a) => returnTrue(a) );
mockSpotEventPluginClient.configureSpotEventPlugin = mockConfigureSpotEventPlugin;
const configs: { Key: string, Value: any }[] = [];
for (const [key, value] of Object.entries(validConvertedPluginConfig)) {
configs.push({
Key: key,
Value: value,
});
}
const securitySettings = [{
Key: 'UseLocalCredentials',
Value: true,
},
{
Key: 'NamedProfile',
Value: '',
}];
// WHEN
await handler.doCreate('physicalId', allConfigs);
// THEN
expect(mockConfigureSpotEventPlugin.mock.calls.length).toBe(1);
expect(mockConfigureSpotEventPlugin.mock.calls[0][0]).toEqual([...configs, ...securitySettings]);
});
test('create groups', async () => {
// GIVEN
const mockAddGroups = jest.fn( (a) => returnTrue(a) );
mockSpotEventPluginClient.addGroups = mockAddGroups;
// WHEN
await handler.doCreate('physicalId', allConfigs);
// THEN
expect(mockAddGroups.mock.calls.length).toBe(1);
expect(mockAddGroups).toHaveBeenCalledWith(deadlineGroups);
});
test('create pools', async () => {
// GIVEN
const mockAddPools = jest.fn( (a) => returnTrue(a) );
mockSpotEventPluginClient.addPools = mockAddPools;
// WHEN
await handler.doCreate('physicalId', allConfigs);
// THEN
expect(mockAddPools.mock.calls.length).toBe(1);
expect(mockAddPools).toHaveBeenCalledWith(deadlinePools);
});
test('throw when cannot add groups', async () => {
// GIVEN
mockSpotEventPluginClient.addGroups = jest.fn( (a) => returnFalse(a) );
// WHEN
const promise = handler.doCreate('physicalId', allConfigs);
// THEN
await expect(promise)
.rejects
.toThrowError(`Failed to add Deadline group(s) ${allConfigs.deadlineGroups}`);
});
test('throw when cannot add pools', async () => {
// GIVEN
mockSpotEventPluginClient.addPools = jest.fn( (a) => returnFalse(a) );
// WHEN
const promise = handler.doCreate('physicalId', allConfigs);
// THEN
await expect(promise)
.rejects
.toThrowError(`Failed to add Deadline pool(s) ${allConfigs.deadlinePools}`);
});
test('throw when cannot save spot fleet request configs', async () => {
// GIVEN
const mockSaveServerData = jest.fn( (a) => returnFalse(a) );
mockSpotEventPluginClient.saveServerData = mockSaveServerData;
// WHEN
const promise = handler.doCreate('physicalId', noPluginConfigs);
// THEN
await expect(promise)
.rejects
.toThrowError(/Failed to save spot fleet request with configuration/);
});
test('throw when cannot save spot event plugin configs', async () => {
// GIVEN
const mockConfigureSpotEventPlugin = jest.fn( (a) => returnFalse(a) );
mockSpotEventPluginClient.configureSpotEventPlugin = mockConfigureSpotEventPlugin;
// WHEN
const promise = handler.doCreate('physicalId', noFleetRequestConfigs);
// THEN
await expect(promise)
.rejects
.toThrowError(/Failed to save Spot Event Plugin Configurations/);
});
});
test('doDelete does not do anything', async () => {
// GIVEN
const handler = new SEPConfiguratorResource(new AWS.SecretsManager());
// WHEN
const promise = await handler.doDelete('physicalId', noConfigs);
// THEN
await expect(promise).toBeUndefined();
});
describe('.validateInput()', () => {
describe('should return true', () => {
test.each<any>([
allConfigs,
noPluginConfigs,
noFleetRequestConfigs,
noConfigs,
])('with valid input', async (input: any) => {
// WHEN
const handler = new SEPConfiguratorResource(new AWS.SecretsManager());
const returnValue = handler.validateInput(input);
// THEN
expect(returnValue).toBeTruthy();
});
});
// Invalid connection
const noProtocolConnection = {
hostname: 'internal-hostname.us-east-1.elb.amazonaws.com',
port: '4433',
};
const noHostnameConnection = {
protocol: 'HTTPS',
port: '4433',
};
const noPortConnection = {
hostname: 'internal-hostname.us-east-1.elb.amazonaws.com',
protocol: 'HTTPS',
caCertificateArn: secretArn,
};
const invalidHostnameConnection = {
hostname: 10,
protocol: 'HTTPS',
port: '4433',
};
const invalidProtocolConnection = {
hostname: 'internal-hostname.us-east-1.elb.amazonaws.com',
protocol: 'TCP',
port: '4433',
};
const invalidProtocolTypeConnection = {
hostname: 'internal-hostname.us-east-1.elb.amazonaws.com',
protocol: ['HTTPS'],
port: '4433',
};
const invalidPortTypeConnection = {
hostname: 'internal-hostname.us-east-1.elb.amazonaws.com',
protocol: 'HTTPS',
port: 4433,
};
const invalidPortRange1Connection = {
hostname: 'internal-hostname.us-east-1.elb.amazonaws.com',
protocol: 'HTTPS',
port: '-1',
};
const invalidPortRange2Connection = {
hostname: 'internal-hostname.us-east-1.elb.amazonaws.com',
protocol: 'HTTPS',
port: '65536',
};
const invalidPortRange3Connection = {
hostname: 'internal-hostname.us-east-1.elb.amazonaws.com',
protocol: 'HTTPS',
port: Number.NaN.toString(),
};
const invalidCaCertConnection = {
hostname: 'internal-hostname.us-east-1.elb.amazonaws.com',
protocol: 'HTTPS',
port: '4433',
caCertificateArn: 'notArn',
};
describe('should return false if', () => {
test.each<any>([
noProtocolConnection,
noHostnameConnection,
noPortConnection,
invalidCaCertConnection,
invalidHostnameConnection,
invalidProtocolConnection,
invalidProtocolTypeConnection,
invalidPortTypeConnection,
invalidPortRange1Connection,
invalidPortRange2Connection,
invalidPortRange3Connection,
undefined,
[],
])('invalid connection', (invalidConnection: any) => {
// GIVEN
const input = {
spotPluginConfigurations: validSpotEventPluginConfig,
connection: invalidConnection,
spotFleetRequestConfigurations: validSpotFleetRequestConfig,
};
// WHEN
const handler = new SEPConfiguratorResource(new AWS.SecretsManager());
const returnValue = handler.validateInput(input);
// THEN
expect(returnValue).toBeFalsy();
});
test.each<any>([
undefined,
[],
'',
])('{input=%s}', (input) => {
// WHEN
const handler = new SEPConfiguratorResource(new AWS.SecretsManager());
const returnValue = handler.validateInput(input);
// THEN
expect(returnValue).toBeFalsy();
});
});
});
describe('.isSecretArnOrUndefined()', () => {
describe('should return true if', () => {
test.each<string | undefined>([
secretArn,
undefined,
])('{input=%s}', async (input: string | undefined) => {
// WHEN
const handler = new SEPConfiguratorResource(new AWS.SecretsManager());
// eslint-disable-next-line dot-notation
const returnValue = handler['isSecretArnOrUndefined'](input);
expect(returnValue).toBeTruthy();
});
});
describe('should return false if', () => {
test.each<any>([
'any string',
10,
[],
])('{input=%s}', async (input: any) => {
// WHEN
const handler = new SEPConfiguratorResource(new AWS.SecretsManager());
// eslint-disable-next-line dot-notation
const returnValue = handler['isSecretArnOrUndefined'](input);
expect(returnValue).toBeFalsy();
});
});
});
describe('.spotEventPluginClient()', () => {
test('creates a valid object with http', async () => {
// GIVEN
const validHTTPConnection: ConnectionOptions = {
hostname: 'internal-hostname.com',
protocol: 'HTTP',
port: '8080',
};
// WHEN
const handler = new SEPConfiguratorResource(new AWS.SecretsManager());
// eslint-disable-next-line dot-notation
const result = await handler['spotEventPluginClient'](validHTTPConnection);
expect(result).toBeDefined();
});
test('creates a valid object with https', async () => {
// GIVEN
const validHTTPSConnection: ConnectionOptions = {
hostname: 'internal-hostname.com',
protocol: 'HTTP',
port: '8080',
caCertificateArn: secretArn,
};
// WHEN
const handler = new SEPConfiguratorResource(new AWS.SecretsManager());
jest.requireMock('../../lib/secrets-manager/read-certificate').readCertificateData.mockReturnValue(Promise.resolve('BEGIN CERTIFICATE'));
// eslint-disable-next-line dot-notation
const result = await handler['spotEventPluginClient'](validHTTPSConnection);
expect(result).toBeDefined();
});
});
describe('.toKeyValueArray()', () => {
test('converts to array of key value pairs', () => {
// GIVEN
const pluginConfig = {
AWSInstanceStatus: 'Disabled',
} as unknown;
const expectedResult = {
Key: 'AWSInstanceStatus',
Value: 'Disabled',
};
// WHEN
const handler = new SEPConfiguratorResource(new AWS.SecretsManager());
// eslint-disable-next-line dot-notation
const returnValue = handler['toKeyValueArray'](pluginConfig as PluginSettings);
// THEN
expect(returnValue).toContainEqual(expectedResult);
});
test('throws with undefined values', () => {
// GIVEN
const pluginConfig = {
AWSInstanceStatus: undefined,
} as unknown;
// WHEN
const handler = new SEPConfiguratorResource(new AWS.SecretsManager());
function toKeyValueArray() {
// eslint-disable-next-line dot-notation
handler['toKeyValueArray'](pluginConfig as PluginSettings);
}
// THEN
expect(toKeyValueArray).toThrowError();
});
});
}); | the_stack |
export const sourceMap: {
[source: string]: string;
} = {
// React
'@workday/canvas-kit-react-action-bar': '@workday/canvas-kit-react/action-bar',
'@workday/canvas-kit-react-avatar': '@workday/canvas-kit-react/avatar',
'@workday/canvas-kit-react-badge': '@workday/canvas-kit-react/badge',
'@workday/canvas-kit-react-banner': '@workday/canvas-kit-react/banner',
'@workday/canvas-kit-react-button': '@workday/canvas-kit-react/button',
'@workday/canvas-kit-react-card': '@workday/canvas-kit-react/card',
'@workday/canvas-kit-react-checkbox': '@workday/canvas-kit-react/checkbox',
'@workday/canvas-kit-react-color-picker': '@workday/canvas-kit-react/color-picker',
'@workday/canvas-kit-react-common': '@workday/canvas-kit-react/common',
'@workday/canvas-kit-react-cookie-banner': '@workday/canvas-kit-react/cookie-banner',
'@workday/canvas-kit-react-core': '@workday/canvas-kit-react/core',
'@workday/canvas-kit-react-form-field': '@workday/canvas-kit-react/form-field',
'@workday/canvas-kit-react-icon': '@workday/canvas-kit-react/icon',
'@workday/canvas-kit-react-layout': '@workday/canvas-kit-react/layout',
'@workday/canvas-kit-react-loading-animation': '@workday/canvas-kit-react/loading-animation',
'@workday/canvas-kit-react-modal': '@workday/canvas-kit-react/modal',
'@workday/canvas-kit-react-page-header': '@workday/canvas-kit-react/page-header',
'@workday/canvas-kit-react-popup': '@workday/canvas-kit-react/popup',
'@workday/canvas-kit-react-radio': '@workday/canvas-kit-react/radio',
'@workday/canvas-kit-react-segmented-control': '@workday/canvas-kit-react/segmented-control',
'@workday/canvas-kit-react-select': '@workday/canvas-kit-react/select',
'@workday/canvas-kit-react-side-panel': '@workday/canvas-kit-react/side-panel',
'@workday/canvas-kit-react-skeleton': '@workday/canvas-kit-react/skeleton',
'@workday/canvas-kit-react-status-indicator': '@workday/canvas-kit-react/status-indicator',
'@workday/canvas-kit-react-switch': '@workday/canvas-kit-react/switch',
'@workday/canvas-kit-react-table': '@workday/canvas-kit-react/table',
'@workday/canvas-kit-react-text-area': '@workday/canvas-kit-react/text-area',
'@workday/canvas-kit-react-text-input': '@workday/canvas-kit-react/text-input',
'@workday/canvas-kit-react-toast': '@workday/canvas-kit-react/toast',
'@workday/canvas-kit-react-tooltip': '@workday/canvas-kit-react/tooltip',
// CSS
// '@workday/canvas-kit-css-action-bar': '@workday/canvas-kit-css/action-bar',
// '@workday/canvas-kit-css-badge': '@workday/canvas-kit-css/badge',
// '@workday/canvas-kit-css-banner': '@workday/canvas-kit-css/banner',
// '@workday/canvas-kit-css-button': '@workday/canvas-kit-css/button',
// '@workday/canvas-kit-css-card': '@workday/canvas-kit-css/card',
// '@workday/canvas-kit-css-checkbox': '@workday/canvas-kit-css/checkbox',
// '@workday/canvas-kit-css-common': '@workday/canvas-kit-css/common',
// '@workday/canvas-kit-css-core': '@workday/canvas-kit-css/core',
// '@workday/canvas-kit-css-form-field': '@workday/canvas-kit-css/form-field',
// '@workday/canvas-kit-css-icon': '@workday/canvas-kit-css/icon',
// '@workday/canvas-kit-css-layout': '@workday/canvas-kit-css/layout',
// '@workday/canvas-kit-css-loading-animation': '@workday/canvas-kit-css/loading-animation',
// '@workday/canvas-kit-css-menu': '@workday/canvas-kit-css/menu',
// '@workday/canvas-kit-css-modal': '@workday/canvas-kit-css/modal',
// '@workday/canvas-kit-css-page-header': '@workday/canvas-kit-css/page-header',
// '@workday/canvas-kit-css-popup': '@workday/canvas-kit-css/popup',
// '@workday/canvas-kit-css-radio': '@workday/canvas-kit-css/radio',
// '@workday/canvas-kit-css-select': '@workday/canvas-kit-css/select',
// '@workday/canvas-kit-css-table': '@workday/canvas-kit-css/table',
// '@workday/canvas-kit-css-text-area': '@workday/canvas-kit-css/text-area',
// '@workday/canvas-kit-css-text-input': '@workday/canvas-kit-css/text-input',
// '@workday/canvas-kit-css-tooltip': '@workday/canvas-kit-css/tooltip',
// Labs
'@workday/canvas-kit-labs-react-breadcrumbs': '@workday/canvas-kit-labs-react/breadcrumbs',
'@workday/canvas-kit-labs-react-color-picker': '@workday/canvas-kit-labs-react/color-picker',
'@workday/canvas-kit-labs-react-combobox': '@workday/canvas-kit-labs-react/combobox',
'@workday/canvas-kit-labs-react-core': '@workday/canvas-kit-labs-react/core',
'@workday/canvas-kit-labs-react-drawer': '@workday/canvas-kit-labs-react/drawer',
'@workday/canvas-kit-labs-react-header': '@workday/canvas-kit-labs-react/header',
'@workday/canvas-kit-labs-react-menu': '@workday/canvas-kit-labs-react/menu',
'@workday/canvas-kit-labs-react-pagination': '@workday/canvas-kit-labs-react/pagination',
'@workday/canvas-kit-labs-react-select': '@workday/canvas-kit-labs-react/select',
'@workday/canvas-kit-labs-react-side-panel': '@workday/canvas-kit-labs-react/side-panel',
'@workday/canvas-kit-labs-react-tabs': '@workday/canvas-kit-labs-react/tabs',
};
export const bundleExportMap: {
[_import: string]: string;
} = {
canvas: '@workday/canvas-kit-react/core',
ActionBar: '@workday/canvas-kit-react/action-bar',
Avatar: '@workday/canvas-kit-react/avatar',
AvatarVariant: '@workday/canvas-kit-react/avatar',
CountBadge: '@workday/canvas-kit-react/badge',
Banner: '@workday/canvas-kit-react/banner',
BannerVariant: '@workday/canvas-kit-react/banner',
Button: '@workday/canvas-kit-react/button',
beta_Button: '@workday/canvas-kit-react/button',
DeleteButton: '@workday/canvas-kit-react/button',
deprecated_Button: '@workday/canvas-kit-react/button',
DropdownButton: '@workday/canvas-kit-react/button',
HighlightButton: '@workday/canvas-kit-react/button',
OutlineButton: '@workday/canvas-kit-react/button',
IconButton: '@workday/canvas-kit-react/button',
TextButton: '@workday/canvas-kit-react/button',
ToolbarIconButton: '@workday/canvas-kit-react/button',
ToolbarDropdownButton: '@workday/canvas-kit-react/button',
Hyperlink: '@workday/canvas-kit-react/button',
ButtonVariant: '@workday/canvas-kit-react/button',
ButtonIconPosition: '@workday/canvas-kit-react/button',
ButtonSize: '@workday/canvas-kit-react/button',
OutlineButtonVariant: '@workday/canvas-kit-react/button',
DropdownButtonVariant: '@workday/canvas-kit-react/button',
IconButtonVariant: '@workday/canvas-kit-react/button',
TextButtonVariant: '@workday/canvas-kit-react/button',
DeprecatedButtonVariant: '@workday/canvas-kit-react/button',
Card: '@workday/canvas-kit-react/card',
Checkbox: '@workday/canvas-kit-react/checkbox',
ColorInput: '@workday/canvas-kit-react/color-picker',
ColorPreview: '@workday/canvas-kit-react/color-picker',
ColorSwatch: '@workday/canvas-kit-react/color-picker',
dubLogoBlue: '@workday/canvas-kit-react/common',
dubLogoWhite: '@workday/canvas-kit-react/common',
wdayLogoBlue: '@workday/canvas-kit-react/common',
wdayLogoWhite: '@workday/canvas-kit-react/common',
miniWdayLogoBlue: '@workday/canvas-kit-react/common',
ErrorType: '@workday/canvas-kit-react/common',
BreakpointKey: '@workday/canvas-kit-react/common',
breakpointKeys: '@workday/canvas-kit-react/common',
breakpoints: '@workday/canvas-kit-react/common',
up: '@workday/canvas-kit-react/common',
down: '@workday/canvas-kit-react/common',
between: '@workday/canvas-kit-react/common',
only: '@workday/canvas-kit-react/common',
createCanvasTheme: '@workday/canvas-kit-react/common',
ContentDirection: '@workday/canvas-kit-react/common',
styled: '@workday/canvas-kit-react/common',
defaultCanvasTheme: '@workday/canvas-kit-react/common',
useTheme: '@workday/canvas-kit-react/common',
accessibleHide: '@workday/canvas-kit-react/common',
getErrorColors: '@workday/canvas-kit-react/common',
errorRing: '@workday/canvas-kit-react/common',
memoizedFocusRing: '@workday/canvas-kit-react/common',
focusRing: '@workday/canvas-kit-react/common',
hideMouseFocus: '@workday/canvas-kit-react/common',
mouseFocusBehavior: '@workday/canvas-kit-react/common',
expandHex: '@workday/canvas-kit-react/common',
pickForegroundColor: '@workday/canvas-kit-react/common',
getTranslateFromOrigin: '@workday/canvas-kit-react/common',
makeMq: '@workday/canvas-kit-react/common',
mergeCallback: '@workday/canvas-kit-react/common',
useUniqueId: '@workday/canvas-kit-react/common',
uniqueId: '@workday/canvas-kit-react/common',
CanvasProvider: '@workday/canvas-kit-react/common',
CookieBanner: '@workday/canvas-kit-react/cookie-banner',
FormField: '@workday/canvas-kit-react/form-field',
Hint: '@workday/canvas-kit-react/form-field',
Label: '@workday/canvas-kit-react/form-field',
FormFieldLabelPosition: '@workday/canvas-kit-react/form-field',
AccentIcon: '@workday/canvas-kit-react/icon',
AppletIcon: '@workday/canvas-kit-react/icon',
SystemIcon: '@workday/canvas-kit-react/icon',
SystemIconCircle: '@workday/canvas-kit-react/icon',
Graphic: '@workday/canvas-kit-react/icon',
Svg: '@workday/canvas-kit-react/icon',
accentIconStyles: '@workday/canvas-kit-react/icon',
appletIconStyles: '@workday/canvas-kit-react/icon',
systemIconStyles: '@workday/canvas-kit-react/icon',
SystemIconCircleSize: '@workday/canvas-kit-react/icon',
graphicStyles: '@workday/canvas-kit-react/icon',
Layout: '@workday/canvas-kit-react/layout',
Column: '@workday/canvas-kit-react/layout',
LoadingAnimation: '@workday/canvas-kit-react/loading-animation',
LoadingDots: '@workday/canvas-kit-react/loading-animation',
Modal: '@workday/canvas-kit-react/modal',
ModalWidth: '@workday/canvas-kit-react/modal',
useModal: '@workday/canvas-kit-react/modal',
PageHeader: '@workday/canvas-kit-react/page-header',
Popup: '@workday/canvas-kit-react/popup',
PopupPadding: '@workday/canvas-kit-react/popup',
usePopup: '@workday/canvas-kit-react/popup',
Popper: '@workday/canvas-kit-react/popup',
useCloseOnEscape: '@workday/canvas-kit-react/popup',
useFocusTrap: '@workday/canvas-kit-react/popup',
useCloseOnOutsideClick: '@workday/canvas-kit-react/popup',
usePopupStack: '@workday/canvas-kit-react/popup',
useAssistiveHideSiblings: '@workday/canvas-kit-react/popup',
useBringToTopOnClick: '@workday/canvas-kit-react/popup',
getTransformFromPlacement: '@workday/canvas-kit-react/popup',
Radio: '@workday/canvas-kit-react/radio',
RadioGroup: '@workday/canvas-kit-react/radio',
SegmentedControl: '@workday/canvas-kit-react/segmented-control',
Select: '@workday/canvas-kit-react/select',
SelectOption: '@workday/canvas-kit-react/select',
SidePanel: '@workday/canvas-kit-react/side-panel',
SidePanelOpenDirection: '@workday/canvas-kit-react/side-panel',
SidePanelBackgroundColor: '@workday/canvas-kit-react/side-panel',
Skeleton: '@workday/canvas-kit-react/skeleton',
SkeletonText: '@workday/canvas-kit-react/skeleton',
SkeletonHeader: '@workday/canvas-kit-react/skeleton',
SkeletonShape: '@workday/canvas-kit-react/skeleton',
BOTTOM_MARGIN: '@workday/canvas-kit-react/skeleton',
StatusIndicator: '@workday/canvas-kit-react/status-indicator',
StatusIndicatorType: '@workday/canvas-kit-react/status-indicator',
StatusIndicatorEmphasis: '@workday/canvas-kit-react/status-indicator',
statusIndicatorStyles: '@workday/canvas-kit-react/status-indicator',
Switch: '@workday/canvas-kit-react/switch',
Table: '@workday/canvas-kit-react/table',
TableRow: '@workday/canvas-kit-react/table',
borderWidth: '@workday/canvas-kit-react/table',
borderColor: '@workday/canvas-kit-react/table',
cellBorder: '@workday/canvas-kit-react/table',
TableRowState: '@workday/canvas-kit-react/table',
TextArea: '@workday/canvas-kit-react/text-area',
TextAreaResizeDirection: '@workday/canvas-kit-react/text-area',
InputIconContainer: '@workday/canvas-kit-react/text-input',
TextInput: '@workday/canvas-kit-react/text-input',
Toast: '@workday/canvas-kit-react/toast',
Tooltip: '@workday/canvas-kit-react/tooltip',
TooltipContainer: '@workday/canvas-kit-react/tooltip',
useTooltip: '@workday/canvas-kit-react/tooltip',
}; | the_stack |
import { TogableProduction } from '../units/togableProductions';
import { Production } from '../production';
import { WorldInterface } from './worldInterface';
import { Unit } from '../units/unit';
import { GameModel } from '../gameModel';
import { BuyAction, BuyAndUnlockAction, UpAction, UpHire, UpSpecial, Research } from '../units/action';
import { Cost } from '../cost';
import { TypeList } from '../typeList';
import { World } from '../world';
import { Engineers } from './engineer';
export class Bee implements WorldInterface {
foragingBee: Unit
workerBee: Unit
queenBee: Unit
hiveBee: Unit
beeResearch: Research
universityBee: Unit
bear: Unit
panda: Unit
bearCrystalProduction: Production
bearSoilProduction: Production
bearRes: Research
padaRes: Research
bear2Res: Research
bear3Res: Research
scientistBee: Unit
foodBee: Unit
advancedBee: Research
universityResBee: Research
universityResBee2: Research
engineersProd: Production
listBee = new Array<Unit>()
constructor(public game: GameModel) { }
declareStuff() {
this.foragingBee = new Unit(this.game, "forBee", "Foraging Bee",
"Foraging Bee yields nectar.")
this.queenBee = new Unit(this.game, "qBee", "Queen Bee",
"Yields Foraging Bee.")
this.hiveBee = new Unit(this.game, "hBee", "Hive Bee",
"Hives yields queens and instructs foraging bees to become workers.")
this.workerBee = new Unit(this.game, "worBee", "Worker Bee",
"Worker Bee converts nectar to honey.")
this.scientistBee = new Unit(this.game, "scBee", "Scientist Bee",
"Scientist bee study honey properties.")
this.foodBee = new Unit(this.game, "foodBee", "Food Bee",
"Converts honey to food.")
this.universityBee = new Unit(this.game, "universityBee", "University of Bee",
"Instruct new Scientist Bee")
this.bear = new Unit(this.game, "bear", "Bear",
"Bear will do anything for honey.")
this.panda = new Unit(this.game, "panda", "Panda",
"Pandas are great scientist.")
this.listBee.push(this.hiveBee)
this.listBee.push(this.queenBee)
this.listBee.push(this.foragingBee)
this.listBee.push(this.workerBee)
this.listBee.push(this.universityBee)
this.listBee.push(this.scientistBee)
this.listBee.push(this.foodBee)
this.listBee.push(this.bear)
this.listBee.push(this.panda)
this.game.lists.push(new TypeList("Bee", this.listBee))
this.engineersProd = new Production(this.universityBee, new Decimal(0.1), false)
this.bearCrystalProduction = new Production(this.bear, this.game.machines.machineryProd.times(30), false)
this.bearSoilProduction = new Production(this.bear, this.game.machines.machineryProd.times(40), false)
}
initStuff() {
const beeTeamUp = this.game.upgradeScienceExp.times(0.8)
const beeHireUp = this.game.upgradeScienceHireExp.times(0.8)
// Foragging
// this.foragingBee.types = [Type.Bee]
this.foragingBee.actions.push(new BuyAction(this.game,
this.foragingBee,
[new Cost(this.game.baseWorld.food, new Decimal(100), this.game.buyExp)]
))
this.game.baseWorld.nectar.addProductor(new Production(this.foragingBee))
this.foragingBee.actions.push(new UpAction(this.game,
this.foragingBee, [new Cost(this.game.baseWorld.science, this.game.scienceCost1, beeTeamUp)]))
this.foragingBee.actions.push(new UpHire(this.game,
this.foragingBee, [new Cost(this.game.baseWorld.science, this.game.scienceCost1, beeHireUp)]))
// this.queenBee.types = [Type.Bee]
// this.hiveBee.types = [Type.Bee]
// Worker
// this.workerBee.types = [Type.Bee]
this.workerBee.actions.push(new BuyAndUnlockAction(this.game,
this.workerBee,
[
new Cost(this.game.baseWorld.nectar, new Decimal(100), this.game.buyExp),
new Cost(this.game.baseWorld.food, new Decimal(1000), this.game.buyExp),
new Cost(this.foragingBee, new Decimal(1), this.game.buyExpUnit)
], [this.queenBee]
))
this.game.baseWorld.nectar.addProductor(new Production(this.workerBee, new Decimal(-2)))
this.game.baseWorld.honey.addProductor(new Production(this.workerBee, new Decimal(1.5)))
this.workerBee.actions.push(new UpAction(this.game,
this.workerBee, [new Cost(this.game.baseWorld.science, this.game.scienceCost2, beeTeamUp)]))
this.workerBee.actions.push(new UpHire(this.game,
this.workerBee, [new Cost(this.game.baseWorld.science, this.game.scienceCost2, beeHireUp)]))
// Queen
this.queenBee.actions.push(new BuyAndUnlockAction(this.game,
this.queenBee,
[
new Cost(this.foragingBee, new Decimal(50), this.game.buyExpUnit),
new Cost(this.game.baseWorld.honey, new Decimal(1E3), this.game.buyExp),
new Cost(this.game.baseWorld.food, new Decimal(1E6), this.game.buyExp),
], [this.hiveBee]
))
this.foragingBee.addProductor(new Production(this.queenBee))
// Hive
this.hiveBee.actions.push(new BuyAction(this.game,
this.hiveBee,
[
new Cost(this.queenBee, new Decimal(100), this.game.buyExpUnit),
new Cost(this.game.baseWorld.honey, this.game.baseWorld.prestigeOther1.times(1.5),
this.game.buyExp.times(1.1)),
new Cost(this.game.baseWorld.food, this.game.baseWorld.prestigeFood.times(0.8), this.game.buyExp),
]
))
this.queenBee.addProductor(new Production(this.hiveBee))
this.foragingBee.addProductor(new Production(this.hiveBee, new Decimal(-5)))
this.workerBee.addProductor(new Production(this.hiveBee, new Decimal(5)))
this.queenBee.actions.push(new UpAction(this.game, this.queenBee,
[new Cost(this.game.baseWorld.science, this.game.scienceCost3, beeTeamUp)]))
this.queenBee.actions.push(new UpHire(this.game, this.queenBee,
[new Cost(this.game.baseWorld.science, this.game.scienceCost3, new Decimal(10))]))
this.hiveBee.actions.push(new UpAction(this.game, this.hiveBee,
[new Cost(this.game.baseWorld.science, this.game.scienceCost4, beeTeamUp)]))
this.hiveBee.actions.push(new UpHire(this.game, this.hiveBee,
[new Cost(this.game.baseWorld.science, this.game.scienceCost4, beeHireUp)]))
// Scientist
// this.scientistBee.types = [Type.Bee]
this.scientistBee.actions.push(new BuyAction(this.game,
this.scientistBee,
[
new Cost(this.foragingBee, new Decimal(1), this.game.buyExpUnit),
new Cost(this.game.baseWorld.honey, new Decimal(6E3), this.game.buyExp),
new Cost(this.game.baseWorld.crystal, new Decimal(4E3), this.game.buyExp),
]
))
this.game.baseWorld.science.addProductor(new Production(this.scientistBee, new Decimal(15)))
this.game.baseWorld.honey.addProductor(new Production(this.scientistBee, new Decimal(-2)))
this.game.baseWorld.crystal.addProductor(new Production(this.scientistBee, new Decimal(-1)))
this.scientistBee.actions.push(new UpAction(this.game, this.scientistBee,
[new Cost(this.game.baseWorld.science, this.game.scienceCost2, beeTeamUp)]))
this.scientistBee.actions.push(new UpHire(this.game, this.scientistBee,
[new Cost(this.game.baseWorld.science, this.game.scienceCost2, beeHireUp)]))
// Food
// this.foodBee.types = [Type.Bee]
this.foodBee.actions.push(new BuyAction(this.game,
this.foodBee,
[
new Cost(this.foragingBee, new Decimal(1), this.game.buyExpUnit),
new Cost(this.game.baseWorld.honey, new Decimal(1E3), this.game.buyExp)
]
))
this.game.baseWorld.food.addProductor(new Production(this.foodBee, new Decimal(15)))
this.game.baseWorld.honey.addProductor(new Production(this.foodBee, new Decimal(-5)))
this.foodBee.actions.push(new UpAction(this.game, this.foodBee,
[new Cost(this.game.baseWorld.science, new Decimal(1E3), new Decimal(10))]))
this.foodBee.actions.push(new UpHire(this.game, this.foodBee,
[new Cost(this.game.baseWorld.science, new Decimal(1E3), new Decimal(10))]))
// University
this.universityBee.actions.push(new BuyAction(this.game,
this.universityBee,
[
new Cost(this.foragingBee, new Decimal(1E3), this.game.buyExpUnit),
new Cost(this.game.baseWorld.wood, this.game.machines.price1, this.game.buyExp),
new Cost(this.game.baseWorld.crystal, this.game.machines.price2, this.game.buyExp),
new Cost(this.game.baseWorld.honey, this.game.machines.price2, this.game.buyExp)
]
))
this.game.baseWorld.science.addProductor(new Production(this.universityBee, new Decimal(600)))
this.scientistBee.addProductor(new Production(this.universityBee, new Decimal(0.01)))
this.game.engineers.beeEnginer.addProductor(this.engineersProd)
this.universityBee.togableProductions = [new TogableProduction("Generate engineers", [this.engineersProd])]
// Bear
this.bear.actions.push(new BuyAction(this.game,
this.bear,
[
new Cost(this.game.baseWorld.food, this.game.machines.price1.times(50000), this.game.buyExp),
new Cost(this.game.baseWorld.honey, this.game.machines.price1.times(5), this.game.buyExp)
]
))
this.bear.actions.push(new UpAction(this.game, this.bear,
[new Cost(this.game.baseWorld.science, this.game.scienceCost3, this.game.upgradeScienceExp)]))
this.bear.actions.push(new UpHire(this.game, this.bear,
[new Cost(this.game.baseWorld.science, this.game.scienceCost3, this.game.upgradeScienceHireExp)]))
this.game.baseWorld.honey.addProductor(new Production(this.bear, this.game.machines.machineryCost))
this.game.baseWorld.wood.addProductor(new Production(this.bear, this.game.machines.machineryProd.times(50)))
this.game.baseWorld.soil.addProductor(this.bearSoilProduction)
this.game.baseWorld.crystal.addProductor(this.bearCrystalProduction)
// Panda
this.panda.actions.push(new BuyAction(this.game,
this.panda,
[
new Cost(this.game.baseWorld.food, this.game.machines.price1.times(50000), this.game.buyExp),
new Cost(this.game.baseWorld.honey, this.game.machines.price1.times(5), this.game.buyExp)
]
))
this.panda.actions.push(new UpAction(this.game, this.panda,
[new Cost(this.game.baseWorld.science, this.game.scienceCost3.div(5), this.game.upgradeScienceExp)]))
this.panda.actions.push(new UpHire(this.game, this.panda,
[new Cost(this.game.baseWorld.science, this.game.scienceCost3.div(5), this.game.upgradeScienceHireExp)]))
this.game.baseWorld.honey.addProductor(new Production(this.panda, this.game.machines.machineryCost))
this.game.baseWorld.science.addProductor(new Production(this.panda, this.game.machines.machineryProd.times(50)))
// Bears crystall
this.bear3Res = new Research(
"bg3Res",
"Mining Bears", "Bears also yield crystalls.",
[new Cost(this.game.baseWorld.science, new Decimal(1E8))],
[this.bearCrystalProduction],
this.game
)
// Bears soil
this.bear2Res = new Research(
"bg2Res",
"Carpenter Bears", "Bears also yield soils.",
[new Cost(this.game.baseWorld.science, new Decimal(5E6))],
[this.bearSoilProduction, this.bear3Res],
this.game
)
// Bears
this.bearRes = new Research(
"bgRes",
"Bears", "Bears like honey.",
[new Cost(this.game.baseWorld.science, new Decimal(1E5))],
[this.bear, this.panda, this.bear2Res],
this.game
)
// Dep of bee
this.universityResBee2 = new Research(
"uniResBee2",
"Department of Bee Engineering", "Bee university also yield bee engineers.",
[new Cost(this.game.baseWorld.science, new Decimal(7E7))],
[this.engineersProd],
this.game
)
// Research
this.universityResBee = new Research(
"universityResBee",
"University of Bee", "Get an university of bee.",
[new Cost(this.game.baseWorld.science, new Decimal(6E6))],
[this.universityBee, this.universityResBee2],
this.game
)
// Research
this.advancedBee = new Research(
"advBee",
"Advanced Bee", "More jobs for bees.",
[new Cost(this.game.baseWorld.science, new Decimal(1E3))],
[this.scientistBee, this.foodBee, this.universityResBee, this.bearRes],
this.game
)
// Bee
this.beeResearch = new Research(
"beeRes",
"Bee", "Unlock Bee !",
[new Cost(this.game.baseWorld.science, new Decimal(0))],
[this.game.baseWorld.nectar, this.foragingBee, this.workerBee, this.game.baseWorld.honey, this.advancedBee],
this.game
)
this.beeResearch.avabileBaseWorld = false
}
addWorld() {
World.worldPrefix.push(
new World(this.game, "Apian", "",
[this.game.machines.honeyMaker, this.game.engineers.beeEnginer],
[],
[
new Cost(this.hiveBee, new Decimal(20)),
new Cost(this.game.baseWorld.honey, this.game.baseWorld.prestigeFood)
],
[],
[],
[[this.beeResearch, new Decimal(0)]],
new Decimal(3)
)
)
World.worldSuffix.push(
new World(this.game, "of Bee", "",
[this.game.machines.honeyMaker, this.game.engineers.beeEnginer],
[],
[
new Cost(this.hiveBee, new Decimal(25)),
new Cost(this.game.baseWorld.honey, this.game.baseWorld.prestigeFood)
],
[[this.foragingBee, new Decimal(2)]],
[],
[[this.beeResearch, new Decimal(0)]],
new Decimal(3)
),
new World(this.game, "of Bear", "",
[this.game.machines.honeyMaker, this.game.engineers.beeEnginer],
[],
[
new Cost(this.bear, new Decimal(250)),
new Cost(this.game.baseWorld.honey, this.game.baseWorld.prestigeFood)
],
[
[this.bear, new Decimal(3)],
[this.panda, new Decimal(3)]
],
[],
[[this.beeResearch, new Decimal(0)]],
new Decimal(3)
)
)
}
} | the_stack |
export const signalStages = [
'Unknown',
'Threat Intelligence',
'Traffic Anomaly',
'External Recon',
'Attack Stage',
'Exploitation',
'Collection',
'Internal Recon',
'Execution',
'Persistence',
'Privilege Escalation',
'Defense Evasion',
'Credential Access',
'Discovery',
'Lateral Movement',
'Exfiltration',
'C2',
'Rule'
];
// export const signals = [
// {
// id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
// category: 'Threat Intelligence',
// contentType: 'threatintel',
// description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
// name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
// severity: 6,
// timestamp: generateDate(8)
// },
// {
// id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
// category: 'Defense Evasion',
// contentType: 'rule',
// description: 'TAudit Log Cleared',
// name: 'Windows Audit Log Was Cleared',
// severity: 2,
// timestamp: generateDate(7)
// },
// {
// id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
// category: 'C2',
// contentType: 'anomaly',
// description:
// 'The flows detected have a repeating pattern indicating periodic communication.',
// name: 'Beaconing Communication Detected',
// severity: 5,
// timestamp: generateDate(7)
// },
// {
// id: '232233232-de85-5c67-a616-3ee7f38c9422',
// category: 'Threat Intelligence',
// contentType: 'threatintel',
// description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
// name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
// severity: 0,
// timestamp: generateDate(5)
// },
// {
// id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
// category: 'Exploitation',
// contentType: 'rule',
// description: 'EDR Log Alert',
// name: 'EDR Log Alert',
// severity: 10,
// timestamp: generateDate(2)
// }
// ];
// export const signalChartData = (() => {
// return signals.map(s => ({
// key: s.timestamp,
// data: s.severity,
// metadata: s,
// id: s.id
// }));
// })();
export const signalChartData = [
{
key: new Date('2020-02-23T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422'
},
{
key: new Date('2020-02-24T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422'
},
{
key: new Date('2020-02-24T08:00:00.000Z'),
data: 5,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422'
},
{
key: new Date('2020-02-26T08:00:00.000Z'),
data: 0,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '232233232-de85-5c67-a616-3ee7f38c9422'
},
{
key: new Date('2020-02-29T08:00:00.000Z'),
data: 10,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422'
}
];
// export const largeSignalChartData = (() => {
// return range(150)
// .map(i => ({
// key: generateDate(i / randomNumber(1, 3)),
// data: randomNumber(1, 10),
// metadata: {
// ...signals[randomNumber(0, signals.length - 1)]
// },
// id: `${new Date().getTime()}-${i}-${randomNumber(0, 500)}`
// }))
// .reverse();
// })();
export const largeSignalChartData = [
{
key: new Date('2019-12-18T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802589-149-242'
},
{
key: new Date('2019-10-06T07:00:00.000Z'),
data: 10,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802589-148-263'
},
{
key: new Date('2019-12-19T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802589-147-90'
},
{
key: new Date('2019-12-20T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802589-146-53'
},
{
key: new Date('2019-12-20T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802589-145-28'
},
{
key: new Date('2019-12-21T08:00:00.000Z'),
data: 8,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802589-144-22'
},
{
key: new Date('2020-01-14T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802589-143-288'
},
{
key: new Date('2020-01-15T08:00:00.000Z'),
data: 4,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802589-142-463'
},
{
key: new Date('2019-12-22T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802589-141-370'
},
{
key: new Date('2019-12-23T08:00:00.000Z'),
data: 3,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802589-140-231'
},
{
key: new Date('2019-10-15T07:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802589-139-266'
},
{
key: new Date('2019-12-24T08:00:00.000Z'),
data: 3,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802588-138-417'
},
{
key: new Date('2019-12-24T08:00:00.000Z'),
data: 3,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-137-43'
},
{
key: new Date('2019-12-25T08:00:00.000Z'),
data: 3,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-136-486'
},
{
key: new Date('2019-12-25T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-135-133'
},
{
key: new Date('2019-12-26T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-134-248'
},
{
key: new Date('2019-12-26T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-133-425'
},
{
key: new Date('2019-12-27T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-132-441'
},
{
key: new Date('2019-10-23T07:00:00.000Z'),
data: 3,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802588-131-292'
},
{
key: new Date('2019-10-24T07:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-130-420'
},
{
key: new Date('2019-10-25T07:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-129-365'
},
{
key: new Date('2019-12-29T08:00:00.000Z'),
data: 5,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802588-128-147'
},
{
key: new Date('2019-12-29T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-127-193'
},
{
key: new Date('2020-01-20T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802588-126-16'
},
{
key: new Date('2019-10-29T07:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802588-125-81'
},
{
key: new Date('2019-12-31T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802588-124-300'
},
{
key: new Date('2020-01-21T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802588-123-279'
},
{
key: new Date('2019-11-01T07:00:00.000Z'),
data: 5,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802588-122-221'
},
{
key: new Date('2019-11-02T07:00:00.000Z'),
data: 3,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-121-461'
},
{
key: new Date('2020-01-02T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802588-120-238'
},
{
key: new Date('2019-11-04T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-119-268'
},
{
key: new Date('2020-01-23T08:00:00.000Z'),
data: 5,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802588-118-211'
},
{
key: new Date('2019-11-06T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802588-117-131'
},
{
key: new Date('2019-11-07T08:00:00.000Z'),
data: 2,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802588-116-113'
},
{
key: new Date('2020-01-04T08:00:00.000Z'),
data: 10,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802588-115-314'
},
{
key: new Date('2019-11-09T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802588-114-434'
},
{
key: new Date('2020-01-24T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-113-114'
},
{
key: new Date('2020-01-06T08:00:00.000Z'),
data: 3,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-112-239'
},
{
key: new Date('2019-11-12T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-111-94'
},
{
key: new Date('2020-01-07T08:00:00.000Z'),
data: 5,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802588-110-381'
},
{
key: new Date('2019-11-14T08:00:00.000Z'),
data: 1,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802588-109-388'
},
{
key: new Date('2020-01-08T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-108-48'
},
{
key: new Date('2019-11-16T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-107-301'
},
{
key: new Date('2020-01-27T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-106-328'
},
{
key: new Date('2019-11-18T08:00:00.000Z'),
data: 1,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802588-105-335'
},
{
key: new Date('2020-01-10T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802588-104-226'
},
{
key: new Date('2019-11-20T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-103-372'
},
{
key: new Date('2019-11-21T08:00:00.000Z'),
data: 5,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802588-102-159'
},
{
key: new Date('2020-01-28T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802587-101-217'
},
{
key: new Date('2020-01-12T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-100-87'
},
{
key: new Date('2019-11-24T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802587-99-63'
},
{
key: new Date('2019-11-25T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-98-314'
},
{
key: new Date('2020-01-13T08:00:00.000Z'),
data: 8,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802587-97-339'
},
{
key: new Date('2019-11-27T08:00:00.000Z'),
data: 4,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802587-96-333'
},
{
key: new Date('2020-01-14T08:00:00.000Z'),
data: 3,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802587-95-390'
},
{
key: new Date('2020-01-15T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-94-253'
},
{
key: new Date('2020-01-15T08:00:00.000Z'),
data: 5,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-93-391'
},
{
key: new Date('2020-01-16T08:00:00.000Z'),
data: 9,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802587-92-367'
},
{
key: new Date('2020-01-16T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802587-91-12'
},
{
key: new Date('2020-01-17T08:00:00.000Z'),
data: 1,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802587-90-35'
},
{
key: new Date('2020-01-17T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-89-383'
},
{
key: new Date('2019-12-05T08:00:00.000Z'),
data: 1,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802587-88-451'
},
{
key: new Date('2020-02-02T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-87-174'
},
{
key: new Date('2020-01-19T08:00:00.000Z'),
data: 7,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802587-86-397'
},
{
key: new Date('2020-02-03T08:00:00.000Z'),
data: 5,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802587-85-102'
},
{
key: new Date('2020-01-20T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-84-430'
},
{
key: new Date('2019-12-10T08:00:00.000Z'),
data: 10,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-83-404'
},
{
key: new Date('2020-01-21T08:00:00.000Z'),
data: 10,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802587-82-259'
},
{
key: new Date('2020-02-04T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802587-81-123'
},
{
key: new Date('2020-01-22T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-80-351'
},
{
key: new Date('2020-01-22T08:00:00.000Z'),
data: 5,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-79-146'
},
{
key: new Date('2020-02-05T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-78-326'
},
{
key: new Date('2020-01-23T08:00:00.000Z'),
data: 5,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802587-77-20'
},
{
key: new Date('2020-02-06T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-76-449'
},
{
key: new Date('2020-01-24T08:00:00.000Z'),
data: 6,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802587-75-175'
},
{
key: new Date('2019-12-19T08:00:00.000Z'),
data: 3,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802587-74-341'
},
{
key: new Date('2020-02-07T08:00:00.000Z'),
data: 1,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-73-259'
},
{
key: new Date('2020-02-07T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-72-317'
},
{
key: new Date('2020-02-07T08:00:00.000Z'),
data: 1,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-71-226'
},
{
key: new Date('2020-02-08T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802587-70-214'
},
{
key: new Date('2019-12-24T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-69-226'
},
{
key: new Date('2020-02-08T08:00:00.000Z'),
data: 8,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802587-68-244'
},
{
key: new Date('2020-02-09T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802587-67-328'
},
{
key: new Date('2020-01-29T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-66-242'
},
{
key: new Date('2020-01-29T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802587-65-485'
},
{
key: new Date('2020-02-10T08:00:00.000Z'),
data: 3,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802586-64-365'
},
{
key: new Date('2020-01-30T08:00:00.000Z'),
data: 10,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-63-82'
},
{
key: new Date('2020-02-10T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-62-162'
},
{
key: new Date('2020-02-11T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-61-12'
},
{
key: new Date('2020-02-11T08:00:00.000Z'),
data: 1,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-60-294'
},
{
key: new Date('2020-02-01T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-59-141'
},
{
key: new Date('2020-02-02T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-58-238'
},
{
key: new Date('2020-02-02T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-57-309'
},
{
key: new Date('2020-02-03T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-56-18'
},
{
key: new Date('2020-01-07T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-55-297'
},
{
key: new Date('2020-01-08T08:00:00.000Z'),
data: 9,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802586-54-405'
},
{
key: new Date('2020-02-13T08:00:00.000Z'),
data: 3,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-53-79'
},
{
key: new Date('2020-01-10T08:00:00.000Z'),
data: 1,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-52-296'
},
{
key: new Date('2020-01-11T08:00:00.000Z'),
data: 8,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802586-51-13'
},
{
key: new Date('2020-01-12T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-50-160'
},
{
key: new Date('2020-02-06T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802586-49-400'
},
{
key: new Date('2020-02-15T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-48-302'
},
{
key: new Date('2020-01-15T08:00:00.000Z'),
data: 5,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-47-242'
},
{
key: new Date('2020-02-16T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-46-236'
},
{
key: new Date('2020-02-08T08:00:00.000Z'),
data: 5,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-45-97'
},
{
key: new Date('2020-02-16T08:00:00.000Z'),
data: 8,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802586-44-133'
},
{
key: new Date('2020-02-09T08:00:00.000Z'),
data: 6,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802586-43-197'
},
{
key: new Date('2020-02-10T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-42-9'
},
{
key: new Date('2020-02-10T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-41-260'
},
{
key: new Date('2020-02-11T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-40-102'
},
{
key: new Date('2020-02-11T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802586-39-132'
},
{
key: new Date('2020-02-12T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-38-313'
},
{
key: new Date('2020-02-12T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802586-37-372'
},
{
key: new Date('2020-02-13T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802586-36-200'
},
{
key: new Date('2020-02-13T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802586-35-406'
},
{
key: new Date('2020-02-14T08:00:00.000Z'),
data: 5,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-34-424'
},
{
key: new Date('2020-02-20T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802585-33-195'
},
{
key: new Date('2020-02-15T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-32-26'
},
{
key: new Date('2020-02-15T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-31-227'
},
{
key: new Date('2020-02-01T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-30-223'
},
{
key: new Date('2020-02-16T08:00:00.000Z'),
data: 7,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802585-29-260'
},
{
key: new Date('2020-02-17T08:00:00.000Z'),
data: 1,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-28-31'
},
{
key: new Date('2020-02-22T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-27-161'
},
{
key: new Date('2020-02-22T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802585-26-493'
},
{
key: new Date('2020-02-23T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-25-139'
},
{
key: new Date('2020-02-19T08:00:00.000Z'),
data: 9,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-24-5'
},
{
key: new Date('2020-02-19T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-23-202'
},
{
key: new Date('2020-02-09T08:00:00.000Z'),
data: 3,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802585-22-432'
},
{
key: new Date('2020-02-20T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-21-466'
},
{
key: new Date('2020-02-21T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-20-317'
},
{
key: new Date('2020-02-25T08:00:00.000Z'),
data: 3,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802585-19-392'
},
{
key: new Date('2020-02-13T08:00:00.000Z'),
data: 6,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-18-358'
},
{
key: new Date('2020-02-22T08:00:00.000Z'),
data: 6,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802585-17-22'
},
{
key: new Date('2020-02-15T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802585-16-351'
},
{
key: new Date('2020-02-23T08:00:00.000Z'),
data: 3,
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583219802585-15-372'
},
{
key: new Date('2020-02-17T08:00:00.000Z'),
data: 3,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802585-14-425'
},
{
key: new Date('2020-02-24T08:00:00.000Z'),
data: 9,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802585-13-86'
},
{
key: new Date('2020-02-19T08:00:00.000Z'),
data: 3,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802585-12-307'
},
{
key: new Date('2020-02-25T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-11-429'
},
{
key: new Date('2020-02-26T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-10-162'
},
{
key: new Date('2020-02-26T08:00:00.000Z'),
data: 2,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-9-115'
},
{
key: new Date('2020-02-27T08:00:00.000Z'),
data: 9,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802585-8-335'
},
{
key: new Date('2020-02-27T08:00:00.000Z'),
data: 1,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802585-7-29'
},
{
key: new Date('2020-02-28T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802585-6-148'
},
{
key: new Date('2020-02-26T08:00:00.000Z'),
data: 4,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802584-5-183'
},
{
key: new Date('2020-02-29T08:00:00.000Z'),
data: 4,
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583219802584-4-376'
},
{
key: new Date('2020-03-01T08:00:00.000Z'),
data: 8,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802584-3-494'
},
{
key: new Date('2020-03-01T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802584-2-87'
},
{
key: new Date('2020-03-02T08:00:00.000Z'),
data: 7,
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583219802584-1-112'
},
{
key: new Date('2020-03-02T08:00:00.000Z'),
data: 1,
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583219802584-0-422'
}
];
export const medSignalChartData = [...largeSignalChartData].splice(0, 50);
// export const signalStageData = (() => {
// return range(15)
// .map(i => ({
// key: generateDate(i / randomNumber(1, 3)),
// data: signals[randomNumber(0, signals.length - 1)].category,
// metadata: {
// ...signals[randomNumber(0, signals.length - 1)]
// },
// id: `${new Date().getTime()}-${i}-${randomNumber(0, 500)}`
// }))
// .reverse();
// })();
export const signalStageData = [
{
key: new Date('2020-02-24T08:00:00.000Z'),
data: 'Threat Intelligence',
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583220135633-14-161'
},
{
key: new Date('2020-02-24T08:00:00.000Z'),
data: 'C2',
metadata: {
id: '4e228d1cd-de85-5c47-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 6,
timestamp: new Date('2020-02-23T08:00:00.000Z')
},
id: '1583220135633-13-114'
},
{
key: new Date('2020-02-27T08:00:00.000Z'),
data: 'Exploitation',
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583220135633-12-299'
},
{
key: new Date('2020-02-25T08:00:00.000Z'),
data: 'Threat Intelligence',
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583220135633-11-114'
},
{
key: new Date('2020-02-26T08:00:00.000Z'),
data: 'Defense Evasion',
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583220135633-10-66'
},
{
key: new Date('2020-02-26T08:00:00.000Z'),
data: 'C2',
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583220135632-9-398'
},
{
key: new Date('2020-02-23T08:00:00.000Z'),
data: 'Threat Intelligence',
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583220135632-8-290'
},
{
key: new Date('2020-02-27T08:00:00.000Z'),
data: 'C2',
metadata: {
id: '4e18d1cd-de85-5c67-a616-3ee7f3349422',
category: 'Defense Evasion',
contentType: 'rule',
description: 'TAudit Log Cleared',
name: 'Windows Audit Log Was Cleared',
severity: 2,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583220135632-7-370'
},
{
key: new Date('2020-02-28T08:00:00.000Z'),
data: 'Defense Evasion',
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583220135632-6-193'
},
{
key: new Date('2020-02-28T08:00:00.000Z'),
data: 'Defense Evasion',
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583220135632-5-351'
},
{
key: new Date('2020-03-01T08:00:00.000Z'),
data: 'Threat Intelligence',
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583220135632-4-175'
},
{
key: new Date('2020-03-01T08:00:00.000Z'),
data: 'Defense Evasion',
metadata: {
id: '232233232-de85-5c67-a616-3ee7f38c9422',
category: 'Threat Intelligence',
contentType: 'threatintel',
description: 'Threat Intelligence match for IOC sunhwakwon.2waky.com',
name: 'Threat Intelligence match for Hostname: sunhwakwon.2waky.com',
severity: 0,
timestamp: new Date('2020-02-26T08:00:00.000Z')
},
id: '1583220135632-3-283'
},
{
key: new Date('2020-03-01T08:00:00.000Z'),
data: 'Defense Evasion',
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583220135632-2-125'
},
{
key: new Date('2020-03-01T08:00:00.000Z'),
data: 'Threat Intelligence',
metadata: {
id: '4e18d1cd-de85-5c67-a616-3e344f38c9422',
category: 'C2',
contentType: 'anomaly',
description:
'The flows detected have a repeating pattern indicating periodic communication.',
name: 'Beaconing Communication Detected',
severity: 5,
timestamp: new Date('2020-02-24T08:00:00.000Z')
},
id: '1583220135632-1-443'
},
{
key: new Date('2020-03-02T08:00:00.000Z'),
data: 'C2',
metadata: {
id: '4e18d1cd-de85-3433-a616-3ee7f38c9422',
category: 'Exploitation',
contentType: 'rule',
description: 'EDR Log Alert',
name: 'EDR Log Alert',
severity: 10,
timestamp: new Date('2020-02-29T08:00:00.000Z')
},
id: '1583220135632-0-158'
}
]; | the_stack |
import * as vscode from "vscode";
import * as path from "path";
import { FolderContext } from "./FolderContext";
import { StatusItem } from "./ui/StatusItem";
import { SwiftOutputChannel } from "./ui/SwiftOutputChannel";
import {
getSwiftExecutable,
pathExists,
isPathInsidePath,
swiftLibraryPathKey,
} from "./utilities/utilities";
import { getLLDBLibPath } from "./debugger/lldb";
import { LanguageClientManager } from "./sourcekit-lsp/LanguageClientManager";
import { TemporaryFolder } from "./utilities/tempFolder";
import { SwiftToolchain } from "./toolchain/toolchain";
import { TaskManager } from "./TaskManager";
import { BackgroundCompilation } from "./BackgroundCompilation";
import { makeDebugConfigurations } from "./debugger/launch";
import configuration from "./configuration";
/**
* Context for whole workspace. Holds array of contexts for each workspace folder
* and the ExtensionContext
*/
export class WorkspaceContext implements vscode.Disposable {
public folders: FolderContext[] = [];
public currentFolder: FolderContext | null | undefined;
public outputChannel: SwiftOutputChannel;
public statusItem: StatusItem;
public languageClientManager: LanguageClientManager;
public tasks: TaskManager;
public subscriptions: { dispose(): unknown }[];
private constructor(public tempFolder: TemporaryFolder, public toolchain: SwiftToolchain) {
this.outputChannel = new SwiftOutputChannel();
this.statusItem = new StatusItem();
this.languageClientManager = new LanguageClientManager(this);
this.outputChannel.log(this.toolchain.swiftVersionString);
this.toolchain.logDiagnostics(this.outputChannel);
this.tasks = new TaskManager();
const onChangeConfig = vscode.workspace.onDidChangeConfiguration(event => {
// on toolchain config change, reload window
if (event.affectsConfiguration("swift.path")) {
vscode.window
.showInformationMessage(
"Changing the Swift path requires the project be reloaded.",
"Ok"
)
.then(selected => {
if (selected === "Ok") {
vscode.commands.executeCommand("workbench.action.reloadWindow");
}
});
}
// on sdk config change, restart sourcekit-lsp
if (event.affectsConfiguration("swift.SDK")) {
// FIXME: There is a bug stopping us from restarting SourceKit-LSP directly.
// As long as it's fixed we won't need to reload on newer versions.
vscode.window
.showInformationMessage(
"Changing the Swift SDK path requires the project be reloaded.",
"Ok"
)
.then(selected => {
if (selected === "Ok") {
vscode.commands.executeCommand("workbench.action.reloadWindow");
}
});
}
// on runtime path config change, regenerate launch.json
if (event.affectsConfiguration("swift.runtimePath")) {
if (!configuration.autoGenerateLaunchConfigurations) {
return;
}
vscode.window
.showInformationMessage(
`Launch configurations need to be updated after changing the Swift runtime path. Custom versions of environment variable '${swiftLibraryPathKey()}' may be overridden. Do you want to update?`,
"Update",
"Cancel"
)
.then(async selected => {
if (selected === "Update") {
this.folders.forEach(
async ctx => await makeDebugConfigurations(ctx, true)
);
}
});
}
});
const backgroundCompilationOnDidSave = BackgroundCompilation.start(this);
this.subscriptions = [
backgroundCompilationOnDidSave,
onChangeConfig,
this.tasks,
this.languageClientManager,
this.outputChannel,
this.statusItem,
];
}
dispose() {
this.folders.forEach(f => f.dispose());
this.subscriptions.forEach(item => item.dispose());
}
get swiftVersion() {
return this.toolchain.swiftVersion;
}
/** Get swift version and create WorkspaceContext */
static async create(): Promise<WorkspaceContext> {
const tempFolder = await TemporaryFolder.create();
const toolchain = await SwiftToolchain.create();
return new WorkspaceContext(tempFolder, toolchain);
}
/** Setup the vscode event listeners to catch folder changes and active window changes */
setupEventListeners() {
// add event listener for when a workspace folder is added/removed
const onWorkspaceChange = vscode.workspace.onDidChangeWorkspaceFolders(event => {
if (this === undefined) {
console.log("Trying to run onDidChangeWorkspaceFolders on deleted context");
return;
}
this.onDidChangeWorkspaceFolders(event);
});
// add event listener for when the active edited text document changes
const onDidChangeActiveWindow = vscode.window.onDidChangeActiveTextEditor(async editor => {
if (this === undefined) {
console.log("Trying to run onDidChangeWorkspaceFolders on deleted context");
return;
}
await this.focusTextEditor(editor);
});
this.subscriptions.push(onWorkspaceChange, onDidChangeActiveWindow);
}
/** Add workspace folders at initialisation */
async addWorkspaceFolders() {
// add workspace folders, already loaded
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) {
for (const folder of vscode.workspace.workspaceFolders) {
await this.addWorkspaceFolder(folder);
}
}
// If we don't have a current selected folder Start up language server by firing focus event
// on either null folder or the first folder if there is only one
if (this.currentFolder === undefined) {
if (this.folders.length === 1) {
await this.fireEvent(this.folders[0], FolderEvent.focus);
} else {
await this.fireEvent(null, FolderEvent.focus);
}
}
}
/**
* Fire an event to all folder observers
* @param folder folder to fire event for
* @param event event type
*/
async fireEvent(folder: FolderContext | null, event: FolderEvent) {
for (const observer of this.observers) {
await observer(folder, event, this);
}
}
/**
* set the focus folder
* @param folder folder that has gained focus, you can have a null folder
*/
async focusFolder(folderContext: FolderContext | null) {
// null and undefined mean different things here. Undefined means nothing
// has been setup, null means we want to send focus events but for a null
// folder
if (folderContext === this.currentFolder) {
return;
}
// send unfocus event for previous folder observers
if (this.currentFolder !== undefined) {
await this.fireEvent(this.currentFolder, FolderEvent.unfocus);
}
this.currentFolder = folderContext;
// send focus event to all observers
await this.fireEvent(folderContext, FolderEvent.focus);
}
/**
* catch workspace folder changes and add or remove folders based on those changes
* @param event workspace folder event
*/
async onDidChangeWorkspaceFolders(event: vscode.WorkspaceFoldersChangeEvent) {
for (const folder of event.added) {
await this.addWorkspaceFolder(folder);
}
for (const folder of event.removed) {
await this.removeFolder(folder);
}
}
/**
* Called whenever a folder is added to the workspace
* @param folder folder being added
*/
async addWorkspaceFolder(folder: vscode.WorkspaceFolder) {
// add folder if Package.swift exists
if (await pathExists(folder.uri.fsPath, "Package.swift")) {
await this.addPackageFolder(folder.uri, folder);
}
if (this.getActiveWorkspaceFolder(vscode.window.activeTextEditor) === folder) {
await this.focusTextEditor(vscode.window.activeTextEditor);
}
}
async addPackageFolder(
folder: vscode.Uri,
workspaceFolder: vscode.WorkspaceFolder
): Promise<FolderContext> {
const folderContext = await FolderContext.create(folder, workspaceFolder, this);
this.folders.push(folderContext);
await this.fireEvent(folderContext, FolderEvent.add);
return folderContext;
}
/**
* called when a folder is removed from workspace
* @param folder folder being removed
*/
async removeFolder(folder: vscode.WorkspaceFolder) {
// find context with root folder
const index = this.folders.findIndex(context => context.workspaceFolder === folder);
if (index === -1) {
console.error(`Trying to delete folder ${folder} which has no record`);
return;
}
const context = this.folders[index];
// if current folder is this folder send unfocus event by setting
// current folder to undefined
if (this.currentFolder === context) {
this.focusFolder(null);
}
// run observer functions in reverse order when removing
const observersReversed = [...this.observers];
observersReversed.reverse();
for (const observer of observersReversed) {
await observer(context, FolderEvent.remove, this);
}
context.dispose();
// remove context
this.folders.splice(index, 1);
}
/**
* Add workspace folder event observer
* @param fn observer function to be called when event occurs
* @returns disposable object
*/
observeFolders(fn: WorkspaceFoldersObserver): vscode.Disposable {
this.observers.add(fn);
return { dispose: () => this.observers.delete(fn) };
}
/** find LLDB version and setup path in CodeLLDB */
async setLLDBVersion() {
const libPath = await getLLDBLibPath(getSwiftExecutable("lldb"));
if (!libPath) {
return;
}
const lldbConfig = vscode.workspace.getConfiguration("lldb");
const configLLDBPath = lldbConfig.get<string>("library");
if (configLLDBPath === libPath) {
return;
}
// show dialog for setting up LLDB
vscode.window
.showInformationMessage(
"CodeLLDB requires the correct Swift version of LLDB for debugging. Do you want to set this up in your global settings or the workspace settings?",
"Global",
"Workspace",
"Cancel"
)
.then(result => {
switch (result) {
case "Global":
lldbConfig.update("library", libPath, vscode.ConfigurationTarget.Global);
// clear workspace setting
lldbConfig.update(
"library",
undefined,
vscode.ConfigurationTarget.Workspace
);
break;
case "Workspace":
lldbConfig.update("library", libPath, vscode.ConfigurationTarget.Workspace);
break;
}
});
}
async focusTextEditor(editor?: vscode.TextEditor) {
if (!editor || !editor.document || editor.document.uri.scheme !== "file") {
return;
}
const url = editor.document.uri;
const packageFolder = await this.getPackageFolder(url);
if (packageFolder instanceof FolderContext) {
this.focusFolder(packageFolder);
} else if (packageFolder instanceof vscode.Uri) {
const workspaceFolder = vscode.workspace.getWorkspaceFolder(packageFolder);
if (!workspaceFolder) {
return;
}
await this.unfocusCurrentFolder();
const folderContext = await this.addPackageFolder(packageFolder, workspaceFolder);
this.focusFolder(folderContext);
} else {
this.focusFolder(null);
}
}
/** return workspace folder from text editor */
private getWorkspaceFolder(url: vscode.Uri): vscode.WorkspaceFolder | undefined {
return vscode.workspace.getWorkspaceFolder(url);
}
/** return workspace folder from text editor */
private getActiveWorkspaceFolder(
editor?: vscode.TextEditor
): vscode.WorkspaceFolder | undefined {
if (!editor || !editor.document) {
return;
}
return vscode.workspace.getWorkspaceFolder(editor.document.uri);
}
/** Return Package folder for url.
*
* First the functions checks in the currently loaded folders to see if it exists inside
* one of those. If not then it searches up the tree to find the uppermost folder in the
* workspace that contains a Package.swift
*/
private async getPackageFolder(
url: vscode.Uri
): Promise<FolderContext | vscode.Uri | undefined> {
// is editor document in any of the current FolderContexts
const folder = this.folders.find(context => {
return isPathInsidePath(url.fsPath, context.folder.fsPath);
});
if (folder) {
return folder;
}
// if not search directory tree for 'Package.swift' files
const workspaceFolder = this.getWorkspaceFolder(url);
if (!workspaceFolder) {
return;
}
const workspacePath = workspaceFolder.uri.fsPath;
let packagePath: string | undefined = undefined;
let currentFolder = path.dirname(url.fsPath);
do {
if (await pathExists(currentFolder, "Package.swift")) {
packagePath = currentFolder;
}
currentFolder = path.dirname(currentFolder);
} while (currentFolder !== workspacePath);
if (packagePath) {
return vscode.Uri.file(packagePath);
} else {
return;
}
}
/** send unfocus event to current focussed folder and clear current folder */
private async unfocusCurrentFolder() {
// send unfocus event for previous folder observers
if (this.currentFolder !== undefined) {
await this.fireEvent(this.currentFolder, FolderEvent.unfocus);
}
this.currentFolder = undefined;
}
private observers: Set<WorkspaceFoldersObserver> = new Set();
}
/** Workspace Folder events */
export class FolderEvent {
/** Workspace folder has been added */
static add = new FolderEvent("add");
/** Workspace folder has been removed */
static remove = new FolderEvent("remove");
/** Workspace folder has gained focus via a file inside the folder becoming the actively edited file */
static focus = new FolderEvent("focus");
/** Workspace folder loses focus because another workspace folder gained it */
static unfocus = new FolderEvent("unfocus");
/** Package.swift has been updated */
static packageUpdated = new FolderEvent("packageUpdated");
/** Package.resolved has been updated */
static resolvedUpdated = new FolderEvent("resolvedUpdated");
constructor(private readonly name: string) {
this.name = name;
}
toString() {
return this.name;
}
}
/** Workspace Folder observer function */
export type WorkspaceFoldersObserver = (
folder: FolderContext | null,
operation: FolderEvent,
workspace: WorkspaceContext
) => unknown; | the_stack |
import { MeshRenderer } from "./meshRenderer";
import { Material } from "./material/material";
import { Screen } from "./webgl2/screen";
import { gltfScene } from "./gltfScene";
import { EntityMgr } from "./ECS/entityMgr";
import { Shader } from "./shader";
import { Mesh, bufferView, Accessor } from "./mesh/mesh";
import { Texture } from "./texture";
import { glsl } from "./glsl";
import { Camera } from "./camera";
export class Asset {
// static load(url, type: XMLHttpRequestResponseType = 'json') {
// return new Promise((resolve, reject) => {
// let xhr = new XMLHttpRequest();
// xhr.open('GET', url);
// xhr.responseType = type;
// xhr.onload = function () {
// if (this.status >= 200 && this.status < 300) {
// resolve(xhr.response);
// } else {
// reject(xhr.statusText);
// }
// }
// xhr.onerror = function () {
// reject(xhr.statusText);
// }
// xhr.send();
// });
// }
// Analyze
static totalTask: number = 0;
static finishedTask: number = 0;
static addTask() {
this.totalTask++;
if (this.taskObserve)
this.taskObserve(this.finishedTask, this.totalTask);
};
static finishTask() {
this.finishedTask++;
if(this.taskObserve)
this.taskObserve(this.finishedTask, this.totalTask);
};
static taskObserve = null;
static loadImage(url) {
return new Promise((resolve, reject) => {
this.addTask();
let image = new Image();
image.crossOrigin = "anonymous";
image.src = url;
image.onload = () => {
resolve(image);
this.finishTask();
}
});
}
static loadBufferImage(buffer: DataView, mimeType) {
return new Promise((resolve, reject) => {
var blob = new Blob([buffer], { type: mimeType });
var url = URL.createObjectURL(blob);
let image = new Image();
image.src = url;
image.onload = () => {
resolve(image);
}
})
}
static adjustDataUri(root, uri) {
return uri.substr(0, 5) == "data:" ? uri : root + uri;
}
static glbMagic = 0x46546C67;
static decoder = new TextDecoder();
static async glbParse(path: string) {
let json, bin = [];
let glb = await this.loadBuffer(path);
let offset = 0;
// HEADER
let header = new Int32Array(glb, offset, 3);
offset += 3*4;
let [magic, version, length] = header;
if(magic != this.glbMagic) {
console.error('Magic number incorrect! - ' + header[0]);
return;
}
while(offset < length) {
let [chunkLength, chunkType] = new Int32Array(glb, offset, 2);
offset += 2*4;
let chunkData = glb.slice(offset, offset + chunkLength)
switch(chunkType) {
// JSON
case 0x4E4F534A:
json = JSON.parse(this.decoder.decode(chunkData));
break;
// BIN
case 0x004E4942:
bin.push(chunkData);
break;
}
offset += chunkLength;
}
return {
json: json,
bin: bin
}
}
static brdfLUT: Texture;
static async loadGLTF(path: string, screen: Screen, envmap?: Texture, diffmap?: Texture, shader?) {
let gltf;
// parse current path
let root: any = path.split('/');
let [filename, format] = root.pop().split('.');
root = root.join('/') + '/';
if(format == 'glb') {
let glb = await this.glbParse(path);
gltf = glb.json;
gltf.buffers = glb.bin;
// BufferViews
gltf.bufferViews = gltf.bufferViews.map(bv => new bufferView(gltf.buffers[bv.buffer], bv));
if (gltf.images) {
gltf.images = await Promise.all(gltf.images.map(i => this.loadBufferImage(gltf.bufferViews[i.bufferView].dataView, i.mimeType)));
}
} else if(format == 'gltf') {
// Load gltf
gltf = await (await fetch(path)).json();
// Download buffers
gltf.buffers = await Promise.all(gltf.buffers.map(({ uri }) => this.loadBuffer(this.adjustDataUri(root, uri))));
// BufferViews
gltf.bufferViews = gltf.bufferViews.map(bv => new bufferView(gltf.buffers[bv.buffer], bv));
// then download images
if (gltf.images) {
gltf.images = await Promise.all(gltf.images.map(({ uri }) => this.loadImage(this.adjustDataUri(root, uri))));
}
} else {
console.error('Wrong file!');
return;
}
// Camera components
if(gltf.cameras) {
gltf.cameras = gltf.cameras.map(cam => {
if(cam.perspective) {
// NOTE: Infinite perspective camera is not support yet
let { aspectRatio, yfov, znear, zfar } = cam.perspective;
let camera = new Camera(screen.width/screen.height, yfov*180/Math.PI, znear, zfar);
camera.name = cam.name;
return camera;
}
});
}
// Textures
if (gltf.textures) {
gltf.textures = gltf.textures.map(tex => {
let { source, sampler } = tex;
let currentSampler;
if (gltf.samplers != null)
currentSampler = gltf.samplers[sampler];
let texture = new Texture(gltf.images[source], currentSampler);
return texture;
})
}
// Load shader
gltf.commonShader = shader || Screen.platform == 'iOS'
? new Shader(glsl.stylize.vs, glsl.stylize.fs)
: new Shader(glsl.stylize2.vs, glsl.stylize2.fs);
// Load brdfLUT
if(this.brdfLUT === undefined) {
const brdfurl = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Viewer/a30e03a164ad04df03018046a187f9e797118567/assets/images/lut_ggx.png'
this.brdfLUT = await this.loadTexture(brdfurl, { minFilter: WebGL2RenderingContext.LINEAR });
}
gltf.brdfLUT = this.brdfLUT;
if(envmap != null) {
gltf.hasEnvmap = true;
gltf.envmap = envmap;
gltf.diffmap = diffmap;
} else {
gltf.hasEnvmap = false;
}
// Parse scene
let {scene} = await new gltfScene(gltf).assemble();
// Create meshRenders
// filter mesh & material which meshRenderer required
let renderTargets = EntityMgr.getEntites([Mesh.name, Material.name], scene);
for(let entity of renderTargets) {
let mesh = entity.components.Mesh;
let material = entity.components.Material;
if(material.name == 'outline') {
entity.components.Transform.isVisible = false;
}
entity.addComponent(new MeshRenderer(screen, mesh, material));
}
return scene;
}
static async loadBuffer(bufferPath) {
this.addTask();
let buffer = await (await fetch(bufferPath)).arrayBuffer()
this.finishTask();
return buffer;
}
static async LoadShaderProgram(url) {
url = Material.SHADER_PATH + url;
let vertPath = url + '.vs.glsl';
let fragPath = url + '.fs.glsl';
let [vert, frag] = await Promise.all([vertPath, fragPath].map(path => fetch(path).then(e=>e.text())));
// console.log(vert);
// console.log(frag);
return new Shader(vert, frag);
}
static async LoadMaterial(matName) {
this.addTask();
let shader = await this.LoadShaderProgram(matName);
this.finishTask();
return new Material(shader);
}
static HDRParse(raw: ArrayBuffer) {
const data = new Uint8Array(raw);
let p = 0;
while (!(data[p] == 10 && data[p+1] == 10)) {
p++;
}
let info = this.decoder.decode(data.subarray(0, p)).split('\n');
if (info[0] != '#?RADIANCE') {
console.table(info);
}
p += 2;
const size_start = p;
while (data[++p] != 10) {
}
let size: any[] = this.decoder.decode(data.subarray(size_start, p)).split(' ');
// let buffer = raw.slice(p+1);
let rgbeData = data.subarray(p+1);
size[1] *= 1;
size[3] *= 1;
const total = size[1] * size[3];
let scanline_num = size[1];
let scanline_width = size[3];
// let buffer = new Float32Array(total * 3);
let buffer = new Uint8Array(total * 4);
let ptr = 0;
if(total * 4 != rgbeData.length) {
console.time('RLE decoding');
// console.error('RLE encoding!');
// 4 channels
for(let y = 0; y < scanline_num; y++) {
let flag = rgbeData.subarray(ptr, ptr+4);
ptr += 4;
if(flag[0] != 2 || flag[1] != 2) {
console.log('this file is not run length encoded');
} else {
// const scanline_buf = [[], [], [], []];
const scanline_buf = [
new Uint8Array(scanline_width),
new Uint8Array(scanline_width),
new Uint8Array(scanline_width),
new Uint8Array(scanline_width),
];
for(let ch = 0; ch < 4; ch++) {
let line_p = 0;
const line = scanline_buf[ch];
while(line_p < scanline_width) {
// while(line.length < scanline_width) {
let count = 0;
let data = rgbeData.subarray(ptr, ptr+2);
ptr += 2;
if(data[0] > 128) {
count = data[0] - 128;
while(count--)
line[line_p++] = data[1];
// line.push(data[1]);
} else {
count = data[0] - 1;
line[line_p++] = data[1];
// line.push(data[1]);
while(count--)
line[line_p++] = rgbeData.subarray(ptr, ++ptr)[0];
// line.push(rgbeData.subarray(ptr, ++ptr)[0])
}
}
}
for(let x = 0; x < scanline_width; x++) {
// const [r, g, b, e] = scanline_buf[0][1];
const pixel = buffer.subarray((y * scanline_width + x) * 4, (y * scanline_width + (x + 1)) * 4);
pixel[0] = scanline_buf[0][x];
pixel[1] = scanline_buf[1][x];
pixel[2] = scanline_buf[2][x];
pixel[3] = scanline_buf[3][x];
}
}
}
console.timeEnd('RLE decoding');
} else {
for(let x = 0; x < total; x++) {
const [r, g, b, e] = rgbeData.subarray(x * 4, (x + 1) * 4);
const pixel = buffer.subarray(x * 4, (x + 1) * 4);
pixel[0] = r;
pixel[1] = g;
pixel[2] = b;
pixel[3] = e;
// if(e != 0) {
// pixel[0] = r * Math.pow(2, e - 128 - 8);
// pixel[1] = g * Math.pow(2, e - 128 - 8);
// pixel[2] = b * Math.pow(2, e - 128 - 8);
// }
}
}
return {
size,
buffer,
decodeRGBE: () => {
const rgb = new Float32Array(total * 3);
for(let x = 0; x < total; x++) {
const [r, g, b, e] = buffer.subarray(x * 4, (x + 1) * 4);
const pixel = rgb.subarray(x * 3, (x + 1) * 3);
if(e != 0) {
pixel[0] = r * Math.pow(2, e - 128 - 8);
pixel[1] = g * Math.pow(2, e - 128 - 8);
pixel[2] = b * Math.pow(2, e - 128 - 8);
}
}
return {size, buffer, rgb};
}
};
}
static cubemapOrder = [
'posx.',
'negx.',
'posy.',
'negy.',
'posz.',
'negz.',
];
static async loadCubeimg(folder, format = 'jpg') {
return await Promise.all(this.cubemapOrder.map(name => this.loadImage(folder + name + format)));
}
static async loadCubemap(folder, format = 'jpg') {
let rawImages;
if(format == 'hdr') {
rawImages = await Promise.all(this.cubemapOrder.map(name => fetch(folder + name + format)));
rawImages = await Promise.all(rawImages.map(raw => raw.arrayBuffer()));
} else {
rawImages = await this.loadCubeimg(folder, format);
}
let tex = new Texture(rawImages, {
magFilter: WebGL2RenderingContext.LINEAR,
minFilter: WebGL2RenderingContext.LINEAR_MIPMAP_LINEAR,
wrapS: WebGL2RenderingContext.CLAMP_TO_EDGE,
wrapT: WebGL2RenderingContext.CLAMP_TO_EDGE,
});
if(format == 'hdr') {
// Parse
let s;
tex.data = rawImages.map(raw => {
const {size, buffer} = this.HDRParse(raw);
s = size;
return buffer;
});
tex.height = s[1];
tex.width = s[3];
// tex.format = WebGL2RenderingContext.RGB;
// tex.internalformat = WebGL2RenderingContext.RGB32F;
// tex.type = WebGL2RenderingContext.FLOAT;
// // tex.internalformat = WebGL2RenderingContext.RGB16F;
// // tex.type = WebGL2RenderingContext.HALF_FLOAT;
tex.glType = WebGL2RenderingContext.TEXTURE_CUBE_MAP;
tex.image = null;
tex.isDirty = true;
}
return tex;
}
static async loadTexture(url: string, option) {
const format = url.split('.').pop();
if(format == 'hdr') {
let raw = await (await fetch(url)).arrayBuffer();
const {size, rgb} = this.HDRParse(raw).decodeRGBE();
const tex = new Texture(null, {
magFilter: WebGL2RenderingContext.LINEAR,
minFilter: WebGL2RenderingContext.LINEAR,
wrapS: WebGL2RenderingContext.CLAMP_TO_EDGE,
wrapT: WebGL2RenderingContext.CLAMP_TO_EDGE,
});
tex.data = rgb;
tex.height = size[1];
tex.width = size[3];
tex.format = WebGL2RenderingContext.RGB;
tex.internalformat = WebGL2RenderingContext.RGB32F;
tex.type = WebGL2RenderingContext.FLOAT;
tex.image = null;
tex.isDirty = true;
return tex;
} else {
let image = await this.loadImage(url);
return new Texture(image, option);
}
}
} | the_stack |
import get from 'lodash/get';
import set from 'lodash/set';
import isEmpty from 'lodash/isEmpty';
import each from 'lodash/each';
import find from 'lodash/find';
import defaultsDeep from 'lodash/defaultsDeep';
import cloneDeep from 'lodash/cloneDeep';
import first from 'lodash/first';
import isEqual from 'lodash/isEqual';
import uniqWith from 'lodash/uniqWith';
import { isBrowser } from './utils';
const defaultMeta = (pwaSchema: any) => [
{
charSet: 'utf-8',
},
{
name: 'robots',
content: 'all',
},
{
name: 'author',
content: 'Atyantik Technologies Private Limited',
},
{
httpEquiv: 'x-ua-compatible',
content: 'ie=edge',
},
{
name: 'viewport',
content: 'width=device-width, initial-scale=1, shrink-to-fit=no',
},
{
name: 'application-name',
content: get(pwaSchema, 'name', ''),
},
{
name: 'generator',
content: 'PawJS',
},
{
name: 'rating',
content: 'General',
},
{
name: 'mobile-web-app-capable',
content: 'yes',
},
{
name: 'theme-color',
content: get(pwaSchema, 'theme_color', '#fff'),
},
{
name: 'apple-mobile-web-app-capable',
content: 'yes',
},
{
name: 'apple-mobile-web-app-status-bar-style',
content: get(pwaSchema, 'theme_color', '#fff'),
},
{
name: 'apple-mobile-web-app-title',
content: get(pwaSchema, 'name', ''),
},
{
name: 'msapplication-tooltip',
content: get(pwaSchema, 'description', ''),
},
{
name: 'msapplication-starturl',
content: get(pwaSchema, 'start_url', ''),
},
{
name: 'msapplication-TileColor',
content: get(pwaSchema, 'background_color', '#fff'),
},
{
name: 'renderer',
content: 'webkit|ie-comp|ie-stand',
},
{
name: 'full-screen',
content: 'yes',
},
];
/**
* Standard meta keys to differentiate
* @type {[*]}
*/
export const metaKeys = [
'name',
'itemProp',
'property',
'charSet',
];
/**
* Get full url appended with base url if no protocol present in the provided link
* @param url
* @param baseUrl
* @returns {*}
*/
const getFullUrl = (url: string, baseUrl = '') => {
let fullImageUrl = url;
if (!fullImageUrl.startsWith('http')) {
fullImageUrl = `${baseUrl}${!fullImageUrl.startsWith('/') ? '/' : ''}${fullImageUrl}`;
}
return fullImageUrl;
};
/**
* Return the meta key detected from the meta provided.
* if no meta key from our standard metaKeys is found then return false
* @param meta
* @returns {boolean|string}
*/
const getMetaKey = (meta: any): string => {
let selectedMetaKey: string = '';
each(metaKeys, (key) => {
if (!selectedMetaKey && get(meta, key, false)) {
selectedMetaKey = key;
}
});
return selectedMetaKey;
};
/**
* Update the source directly,
* thus pass as array
* @param source {Array}
* @param customMetas {Array}
*/
const addUpdateMeta = (source: any [] = [], customMetas: any [] = []) => {
each(customMetas, (meta) => {
const metaKey = getMetaKey(meta);
let metaUpdated = false;
if (metaKey) {
// Suppose we got a meta key in our generatedSchema
// then we need to update the generated schema
const generatedSchemaObj: any = find(source, { [metaKey]: meta[metaKey] });
if (generatedSchemaObj) {
each(meta, (value, key) => {
set(generatedSchemaObj, key, value);
});
metaUpdated = true;
}
}
// This means user is trying to add some meta that does
// not match our standard criteria or is not present in our source, maybe for site verification
// or google webmaster meta key etc
if (!metaUpdated) {
// Add data to source
source.push(meta);
}
});
};
/**
* Get text from html string
* @param str
* @returns {string}
*/
export const getTextFromHtml = (str = '') => str.replace(/<(?:.|\n)*?>/gm, '').trim();
/**
* Return array of meta tags required for the route
* Pass seo data to the function and get array of meta data
* @param data
* @param options
* @returns {Array}
*/
export const generateMeta = (data = {}, options = {
baseUrl: '', url: '', pwaSchema: {}, seoSchema: {},
}) => {
// deep defaults the seoSchema we have in config file and the data provided to us.
const seoData = defaultsDeep(data, options.seoSchema);
// Let store the generated Schema in following variable
let generatedSchema: any [] = [];
const descriptionText = getTextFromHtml(seoData.description);
// Get 155 words out of description
// const desc155words = trimTillLastSentence(seoData.description, 155);
const desc155chars = descriptionText.slice(0, 155);
// Get 200 words out of description
const desc200chars = descriptionText.slice(0, 200);
// const desc200words = trimTillLastSentence(seoData.description, 200);
// Base url after removing the end slash
const baseUrl = options.baseUrl.replace(/\/$/, '');
// Add meta required for at top of head
addUpdateMeta(generatedSchema, cloneDeep(defaultMeta(options.pwaSchema)));
/**
* Manage name/title
*/
// Meta name
generatedSchema.push({
name: 'title',
content: seoData.title,
});
// Twitter title
generatedSchema.push({
name: 'twitter:title',
content: seoData.title,
});
generatedSchema.push({
property: 'og:title',
content: seoData.title,
});
/**
* Manage keywords (allow string and array as well)
*/
if (process.env.ENABLE_KEYWORDS
&& (
process.env.ENABLE_KEYWORDS === 'true'
|| process.env.ENABLE_KEYWORDS === '1'
|| process.env.ENABLE_KEYWORDS === 'yes'
)
) {
if (typeof seoData.keywords === 'string' && seoData.keywords.trim().length) {
generatedSchema.push({
name: 'keywords',
content: seoData.keywords,
});
}
if (Array.isArray(seoData.keywords) && seoData.keywords.length) {
generatedSchema.push({
name: 'keywords',
content: seoData.keywords.join(','),
});
}
}
/**
* Manage twitter site & author
*/
const twitterSite = get(seoData, 'twitter.site', '');
if (twitterSite.length) {
generatedSchema.push({
name: 'twitter:site',
content: twitterSite,
});
}
const twitterCreator = get(seoData, 'twitter.creator', '');
if (twitterCreator.length) {
generatedSchema.push({
name: 'twitter:creator',
content: twitterCreator,
});
}
/**
* Manage facebook admins
*/
const fbAdmins = get(seoData, 'facebook.admins', []);
if (fbAdmins && fbAdmins.length) {
generatedSchema.push({
property: 'fb:admins',
content: fbAdmins.join(','),
});
}
/**
* Manage description
*/
// Meta description
generatedSchema.push({
name: 'description',
content: desc155chars,
});
generatedSchema.push({
name: 'twitter:description',
content: desc200chars,
});
generatedSchema.push({
property: 'og:description',
content: descriptionText,
});
/**
* Site name
*/
if (seoData.site_name && seoData.site_name.length) {
generatedSchema.push({
property: 'og:site_name',
content: seoData.site_name,
});
}
/**
* Manage Primary Image
*/
const hasImage = (seoData.image && !!seoData.image.length);
if (hasImage) {
let images = hasImage ? seoData.image : [];
if (!Array.isArray(images)) {
images = [images];
}
const image: string = first(images) || '';
const fullImageUrl = getFullUrl(image, baseUrl);
generatedSchema.push({
itemProp: 'image',
content: fullImageUrl,
});
generatedSchema.push({
name: 'twitter:image:src',
content: fullImageUrl,
});
if (image.length > 1) {
each(images, (img) => {
generatedSchema.push({
property: 'og:image',
content: getFullUrl(img, baseUrl),
});
});
} else {
generatedSchema.push({
property: 'og:image',
content: fullImageUrl,
});
}
// Add type of twitter card
generatedSchema.push({
name: 'twitter:card',
content: 'summary_large_image',
});
} else {
generatedSchema.push({
name: 'twitter:card',
content: 'summary',
});
}
/**
* Manage Type article/product/music/movie etc
*/
generatedSchema.push({
property: 'og:type',
content: seoData.type,
});
let twitterDataCounter = 1;
each(seoData.type_details, (value, key) => {
if (typeof value === 'object' && value !== null) {
each(value, (subValue, subKey) => {
if (!isEmpty(subValue)) {
generatedSchema.push({
property: `${seoData.type}:${key}:${subKey}`,
content: subValue,
});
generatedSchema.push({
name: `twitter:data${twitterDataCounter}`,
content: subValue,
});
generatedSchema.push({
name: `twitter:label${twitterDataCounter}`,
content: subKey,
});
twitterDataCounter += 1;
}
});
} else if (!isEmpty(value)) {
generatedSchema.push({
property: `${seoData.type}:${key}`,
content: value,
});
generatedSchema.push({
name: `twitter:data${twitterDataCounter}`,
content: value,
});
generatedSchema.push({
name: `twitter:label${twitterDataCounter}`,
content: key,
});
twitterDataCounter += 1;
}
});
let url = get(seoData, 'url', get(options, 'url', ''));
if (!url.length && isBrowser()) {
url = get(window, 'location.href', '');
}
if (url.trim().length) {
generatedSchema.push({
property: 'og:url',
content: url,
});
}
const userMeta = get(seoData, 'meta', []);
addUpdateMeta(generatedSchema, userMeta);
generatedSchema = uniqWith(generatedSchema, isEqual);
return generatedSchema;
};
/**
* Process string to get appropriate trimmed data
* Thus string "Tirth Bodawala" should return "Tirth Bodawala" with length 14
* & should return "Tirth" with length 13, first it tries to search for "." and then
* for " "(space)
* @param str
* @param length
* @returns String
*/
export const trimTillLastSentence = (str: string, length = 0) => {
// Get pure text from string provided, necessary
// to remove html tags
let strr: string = getTextFromHtml(str);
// If no min length specified or no string
// length then return string
if (!length || !strr.length) {
return strr;
}
// Add leading space to preserve string length
strr += ' ';
// trim the string to the maximum length
let trimmedString = strr.substr(0, length + 1);
// Re-trim if we are in the middle of a word
let separator = '.';
// Check if there is a sentence and a "." exists
if (trimmedString.lastIndexOf(separator) === -1) {
separator = ' ';
if (trimmedString.lastIndexOf(separator) === -1) {
// if no space exists at all then return the string
// with max length value
trimmedString = str.substr(0, length);
return trimmedString;
}
}
return trimmedString.substr(
0,
Math.min(trimmedString.length - 1, trimmedString.lastIndexOf(separator)),
).trim();
}; | the_stack |
import React from "react";
import { orderBy as _, range, debounce } from "lodash";
import Mousetrap from "mousetrap";
import 'mousetrap-global-bind';
import { DraggableData, DraggableCore } from "react-draggable";
import { Dispatch } from "redux";
import {
Column,
RowMouseEventHandlerParams,
SortDirection,
SortDirectionType,
SortIndicator,
Table,
TableCellRenderer,
TableHeaderProps,
WindowScroller,
WindowScrollerChildProps
} from "react-virtualized";
import "react-virtualized/styles.css"; // only needs to be imported once
import { updateSelectedCount, updateTracksTick } from "./actions";
import "./Table.css";
import { Track, TrackFileType } from "./types";
import { fileTypeString, msToTime } from "./utility";
const toLodashDirection = (direction: SortDirectionType) => {
switch (direction) {
case "ASC":
return "asc";
case "DESC":
return "desc";
}
}
interface TrackTableProps {
tracks: Track[];
query: string;
dispatch?: Dispatch<any>;
hidden: boolean;
}
interface TrackTableState {
widths: { [tableKey: string]: number };
sortBy: string;
sortDirection: SortDirectionType;
sortedList: Track[];
selected: boolean[] | undefined;
cursor: number | undefined;
pivot: number | undefined;
prevTrackLength?: number;
prevQuery?: string;
scrollToRow?: number
}
const TOTAL_WIDTH = 3000;
// tslint:disable:jsx-no-lambda
class TrackTable extends React.Component<TrackTableProps, TrackTableState> {
tableRef: React.RefObject<WindowScroller>;
constructor(props: TrackTableProps) {
super(props);
const sortBy = "updated";
const sortDirection = SortDirection.DESC;
this.tableRef = React.createRef<WindowScroller>();
this.state = {
// tslint:disable:object-literal-sort-keys
widths: {
track: 0.05,
title: 0.2,
album: 0.2,
artist: 0.2,
albumArtists: 0.2,
duration: 0.07,
fileType: 0.1,
bitrate: 0.07,
sampleRate: 0.07,
hasCoverArt: 0.03,
coverArtHeight: 0.05,
coverArtWidth: 0.05,
source: 0.05,
musicbrainzTrackId: 0.2,
updated: 0.07,
filePath: 0.7
},
sortBy,
sortDirection,
sortedList: TrackTable.sortList({ list: this.props.tracks, sortBy, sortDirection }),
selected: [],
cursor: undefined,
pivot: undefined,
};
const keyDown = debounce(this.keyDownEventHandler).bind(this)
window.addEventListener("keydown", (event) => {
if (event.key === "ArrowUp" || event.key === "ArrowDown") {
event.preventDefault();
keyDown(event);
}
});
Mousetrap.bindGlobal(['command+r', 'ctrl+r'], () => {
const tracksToRefresh = this.state.sortedList.filter(
(_track, index) => this.state.selected?.[index] === true
).map(track => track.filePath);
window.seiri.refreshTracks(tracksToRefresh)
// tslint:disable-next-line:no-console
// console.log("REFRESHED!");
// tslint:disable-next-line:no-console
// console.log(tracksToRefresh);
this.setState(this.asSelected([], undefined, undefined));
this.props.dispatch?.(updateTracksTick.action({}));
return false;
});
this.rowClassName = this.rowClassName.bind(this);
this.handleClick = this.handleClick.bind(this);
this.handleDoubleClick = this.handleDoubleClick.bind(this);
this.sort = this.sort.bind(this);
this.rowGetter = this.rowGetter.bind(this);
this.albumArtistCellRenderer = this.albumArtistCellRenderer.bind(this);
this.durationCellRenderer = this.durationCellRenderer.bind(this);
this.fileTypeCellRenderer = this.fileTypeCellRenderer.bind(this);
this.hasCoverArtCellRenderer = this.hasCoverArtCellRenderer.bind(this);
}
keyDownEventHandler(event: KeyboardEvent) {
if (event.key === "ArrowUp" || event.key === "ArrowDown") {
event.preventDefault();
let newSelected = this.state.cursor
if (newSelected === undefined) {
newSelected = 0
} else {
if (event.key === "ArrowDown") newSelected++;
if (event.key === "ArrowUp") newSelected--;
if (newSelected < 0) newSelected = 0;
if (newSelected >= this.props.tracks.length) newSelected = this.props.tracks.length - 1;
}
if (event.shiftKey) {
// everything between the cursor and the pivot is selected.
let newSelectionKeys = [];
const selected = [];
const lastSelected = this.state.pivot ?? newSelected;
if (newSelected > lastSelected) {
newSelectionKeys = range(lastSelected, newSelected + 1);
} else {
newSelectionKeys = range(newSelected, lastSelected + 1);
}
for (const key of newSelectionKeys) {
selected[key] = true;
}
this.setState({
scrollToRow: newSelected,
...this.asSelected(selected, newSelected, this.state.pivot ?? newSelected)
});
return;
} else if (event.ctrlKey) {
this.setState({ scrollToRow: newSelected, cursor: newSelected });
} else {
const clearState = [];
clearState[newSelected] = true;
this.setState({scrollToRow: newSelected, ...this.asSelected(clearState, newSelected, newSelected)});
}
}
}
asSelected(selected: boolean[], cursor: number | undefined, pivot: number | undefined)
{
return { selected, cursor, pivot }
}
UNSAFE_componentWillReceiveProps(newProps: TrackTableProps) {
const { sortBy, sortDirection } = this.state;
if (newProps.query !== this.props.query || newProps.tracks.length !== this.props.tracks.length) {
this.setState({
sortedList: TrackTable.sortList({ list: newProps.tracks, sortBy, sortDirection }),
selected: [],
cursor: undefined,
pivot: undefined,
});
} else {
this.setState({ sortedList: TrackTable.sortList({ list: newProps.tracks, sortBy, sortDirection }) });
}
}
// static getDerivedStateFromProps(newProps: TrackTableProps, prevState: TrackTableState)
// {
// const { sortBy, sortDirection, prevQuery, prevTrackLength } = prevState;
// // Need this so setting selected stuff actually works
// if (newProps.query !== prevQuery || newProps.tracks.length !== prevTrackLength) {
// newProps.dispatch?.(updateSelectedCount({ count: 0 }))
// return {
// sortedList: TrackTable.sortList({ list: newProps.tracks, sortBy, sortDirection }),
// selected: [],
// cursor: undefined,
// pivot: undefined,
// prevQuery: newProps.query,
// prevTrackLength: newProps.tracks.length
// }
// } else {
// return { sortedList: TrackTable.sortList({ list: newProps.tracks, sortBy, sortDirection }) }
// }
// }
rowClassName({ index }: { index: number }) {
if (index < 0) {
return "table-row table-header";
}
let tableRowClass = "table-row";
if (!!this.state.selected?.[index]) {
tableRowClass += " selected";
}
if (this.state.cursor === index) {
tableRowClass += " cursor";
}
if (this.state.pivot === index) {
tableRowClass += " pivot";
}
if (index % 2 === 0) {
tableRowClass += " evenRow";
} else {
tableRowClass += " oddRow";
}
return tableRowClass;
}
UNSAFE_componentWillUpdate(nextProps: TrackTableProps, nextState: TrackTableState) {
this.props.dispatch?.(updateSelectedCount({ count: nextState.selected?.filter(s => s).length ?? 0 }));
}
rowGetter = ({ index }: { index: number }) =>
this.getDatum(this.state.sortedList, index);
getDatum(list: Track[], index: number) {
return list[index] || {};
}
sort({
sortBy,
sortDirection
}: {
sortBy: string;
sortDirection: SortDirectionType;
}) {
const sortedList = TrackTable.sortList({ list: this.props.tracks, sortBy, sortDirection });
this.setState({
sortBy, sortDirection, sortedList,
...this.asSelected([], undefined, undefined)
});
}
static sortList({
list,
sortBy,
sortDirection
}: {
list: Track[];
sortBy: string;
sortDirection: SortDirectionType;
}) {
return _(
list,
[sortBy, "album", "tracknumber"],
[toLodashDirection(sortDirection), "asc", "asc"]
);
}
headerResizeHandler(dataKey: string, event: MouseEvent, { deltaX }: DraggableData) {
this.resizeRow({
dataKey,
deltaX
})
}
headerRenderer = ({
columnData,
dataKey,
disableSort,
label,
sortBy,
sortDirection
}: TableHeaderProps) => {
return (
<React.Fragment key={dataKey}>
<div className="ReactVirtualized__Table__headerTruncatedText">
<span className="table-header-label">{label}</span>
</div>
{sortBy === dataKey && <SortIndicator sortDirection={sortDirection} />}
<DraggableCore
handle=".DragHandleIcon"
scale={0.5}
onDrag={this.headerResizeHandler.bind(this, dataKey)}
>
<span className="DragHandleIcon">⋮</span>
</DraggableCore>
</React.Fragment>
);
};
resizeRow = ({
dataKey,
deltaX
}: {
dataKey: string;
deltaX: number;
}) => {
window.requestAnimationFrame(() => {
this.setState(prevState => {
const prevWidths = prevState.widths;
const percentDelta = deltaX / TOTAL_WIDTH;
// This is me being lazy :)
const nextDataKey = dataKey === "name" ? "location" : "description";
return {
widths: {
...prevWidths,
[dataKey]: prevWidths[dataKey] + percentDelta,
[nextDataKey]: prevWidths[nextDataKey] - percentDelta
}
};
});
});
};
handleDoubleClick(event: RowMouseEventHandlerParams) {
const track: Track = event.rowData;
window.seiri.openTrackFolder(track);
}
// tslint:disable:no-shadowed-variable
handleClick(event: RowMouseEventHandlerParams) {
const mouseEvent = event.event;
if (this.state.pivot === undefined) {
const newSelection = !!!this.state.selected?.[event.index];
const clearState = [];
clearState[event.index] = newSelection;
this.setState(this.asSelected(clearState, event.index, event.index));
return;
}
if (mouseEvent.shiftKey) {
// const selectedIndexes = Object.keys(this.state.selected) as any as number[];
let newSelectionKeys = [];
const selected = [];
const lastSelected = this.state.pivot;
if (event.index > lastSelected) {
newSelectionKeys = range(lastSelected, event.index + 1);
} else {
newSelectionKeys = range(event.index, lastSelected + 1);
}
for (const key of newSelectionKeys) {
selected[key] = true;
}
this.setState(this.asSelected(selected, event.index, this.state.pivot));
return;
}
if (mouseEvent.ctrlKey) {
const selected = this.state.selected;
if (selected) {
selected[event.index] = !!!this.state.selected?.[event.index];
this.setState(this.asSelected(selected, event.index, event.index));
}
return;
}
const newSelection = this.state.pivot !== event.index;
const clearState = [];
clearState[event.index] = newSelection;
this.setState(this.asSelected(clearState, event.index, newSelection ? event.index : undefined));
return;
}
albumArtistCellRenderer: TableCellRenderer = ({ cellData }: { cellData?: string[] }) => (cellData || []).join(";")
durationCellRenderer: TableCellRenderer = ({ cellData }: { cellData?: number }) => msToTime(cellData ?? 0)
fileTypeCellRenderer: TableCellRenderer = ({ cellData }: { cellData?: TrackFileType }) => fileTypeString(cellData ?? TrackFileType.Unknown)
hasCoverArtCellRenderer: TableCellRenderer = ({ cellData }: { cellData?: boolean }) => (cellData ? "Yes" : "No")
// tslint:disable-next-line:member-ordering
render() {
return (
<div className={this.props.hidden ? "table-container hidden" : "table-container"}>
<WindowScroller ref={this.tableRef}>
{({ height, isScrolling, scrollTop, onChildScroll }: Pick<WindowScrollerChildProps, "height" | "isScrolling" | "scrollTop" | "onChildScroll">) => (
<Table
autoHeight={true}
isScrolling={isScrolling}
scrollTop={scrollTop}
onScroll={onChildScroll}
scrollToIndex={this.state.scrollToRow}
className="Table"
rowClassName={this.rowClassName}
headerClassName="table-header"
width={TOTAL_WIDTH}
height={height}
headerHeight={20}
overscanRowCount={50}
rowHeight={20}
rowCount={this.props.tracks.length}
onRowDoubleClick={this.handleDoubleClick}
onRowClick={this.handleClick}
sort={this.sort}
sortBy={this.state.sortBy}
sortDirection={this.state.sortDirection}
rowGetter={this.rowGetter}
>
<Column
headerRenderer={this.headerRenderer}
label="Track"
dataKey="trackNumber"
width={this.state.widths.track * TOTAL_WIDTH}
/>
<Column
headerRenderer={this.headerRenderer}
label="Title"
dataKey="title"
width={this.state.widths.title * TOTAL_WIDTH}
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.album * TOTAL_WIDTH}
label="Album"
dataKey="album"
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.artist * TOTAL_WIDTH}
label="Artist"
dataKey="artist"
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.albumArtists * TOTAL_WIDTH}
label="Album Artists"
dataKey="albumArtists"
cellRenderer={this.albumArtistCellRenderer}
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.duration * TOTAL_WIDTH}
label="Duration"
dataKey="duration"
cellRenderer={this.durationCellRenderer}
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.fileType * TOTAL_WIDTH}
label="File Type"
dataKey="fileType"
cellRenderer={this.fileTypeCellRenderer}
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.bitrate * TOTAL_WIDTH}
label="Bitrate"
dataKey="bitrate"
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.sampleRate * TOTAL_WIDTH}
label="Sample Rate"
dataKey="sampleRate"
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.hasCoverArt * TOTAL_WIDTH}
label="Art"
dataKey="hasFrontCover"
cellRenderer={this.hasCoverArtCellRenderer}
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.coverArtWidth * TOTAL_WIDTH}
label="Width"
dataKey="frontCoverWidth"
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.coverArtHeight * TOTAL_WIDTH}
label="Height"
dataKey="frontCoverHeight"
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.source * TOTAL_WIDTH}
label="Source"
dataKey="source"
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.musicbrainzTrackId * TOTAL_WIDTH}
label="MusicBrainz ID"
dataKey="musicbrainzTrackId"
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.updated * TOTAL_WIDTH}
label="Updated"
dataKey="updated"
/>
<Column
headerRenderer={this.headerRenderer}
width={this.state.widths.filePath * TOTAL_WIDTH}
label="Path"
dataKey="filePath"
/>
</Table>
)}
</WindowScroller>
</div>
);
}
}
export default TrackTable; | the_stack |
import {
createDeploymentMachine,
createRollbackDeploymentMachine,
DeployMachineContext,
DeploymentMachineOp,
StateMachineHelperFunctions,
StateMachineRollbackHelperFunctions,
} from '../../iterative-deployment/state-machine';
import { interpret } from 'xstate';
describe('deployment state machine', () => {
const fns: StateMachineHelperFunctions = {
deployFn: jest.fn().mockResolvedValue(undefined),
deploymentWaitFn: jest.fn().mockResolvedValue(undefined),
rollbackFn: jest.fn().mockResolvedValue(undefined),
rollbackWaitFn: jest.fn().mockResolvedValue(undefined),
tableReadyWaitFn: jest.fn().mockResolvedValue(undefined),
startRollbackFn: jest.fn().mockResolvedValue(undefined),
stackEventPollFn: jest.fn().mockImplementation(() => {
return () => {};
}),
};
const baseDeploymentStep: Omit<DeploymentMachineOp, 'stackTemplateUrl'> = {
parameters: {},
stackName: 'amplify-multideploytest-dev-162313-apimultideploytest-1E3B7HVOV09VD',
stackTemplatePath: 'stack1/cfn.json',
tableNames: ['table1'],
region: 'us-east-2',
capabilities: [],
};
const initialContext: DeployMachineContext = {
currentIndex: -1,
region: 'us-east-2',
deploymentBucket: 'https://s3.amazonaws.com/amplify-multideploytest-dev-162313-deployment',
stacks: [
{
deployment: {
...baseDeploymentStep,
stackTemplateUrl: 'step1.json',
tableNames: ['table1'],
},
rollback: {
...baseDeploymentStep,
stackTemplateUrl: 'rollback1.json',
parameters: { rollback: 'true' },
tableNames: ['table1'],
},
},
{
deployment: {
...baseDeploymentStep,
stackTemplateUrl: 'step2.json',
tableNames: ['table1', 'table2'],
},
rollback: {
...baseDeploymentStep,
stackTemplateUrl: 'rollback2.json',
parameters: { rollback: 'true' },
tableNames: ['table1', 'table2'],
},
},
{
deployment: {
...baseDeploymentStep,
stackTemplateUrl: 'step3.json',
tableNames: ['table1', 'table3'],
},
rollback: {
...baseDeploymentStep,
stackTemplateUrl: 'rollback3.json',
parameters: { rollback: 'true' },
tableNames: ['table1', 'table3'],
},
},
],
};
beforeEach(() => {
jest.resetAllMocks();
(fns.deployFn as jest.Mock).mockResolvedValue(undefined);
(fns.deploymentWaitFn as jest.Mock).mockResolvedValue(undefined);
(fns.rollbackFn as jest.Mock).mockResolvedValue(undefined);
(fns.rollbackWaitFn as jest.Mock).mockResolvedValue(undefined);
(fns.startRollbackFn as jest.Mock).mockResolvedValue(undefined);
(fns.tableReadyWaitFn as jest.Mock).mockResolvedValue(undefined);
});
it('should call deployment function multiple times when there are multiple stacks to be deployed', done => {
const machine = createDeploymentMachine(initialContext, fns);
interpret(machine)
.onTransition(state => {
if (state.value === 'deployed') {
expect(fns.deployFn).toHaveBeenCalledTimes(3);
expect(fns.deploymentWaitFn).toHaveBeenCalledTimes(3);
expect(fns.tableReadyWaitFn).toHaveBeenCalledTimes(3);
// 1st stack
const firstStackArg = initialContext.stacks[0].deployment;
expect((fns.deployFn as jest.Mock).mock.calls[0][0]).toEqual(firstStackArg);
expect((fns.deploymentWaitFn as jest.Mock).mock.calls[0][0]).toEqual(firstStackArg);
expect((fns.tableReadyWaitFn as jest.Mock).mock.calls[0][0]).toEqual(firstStackArg);
// second stack
const secondStackArg = initialContext.stacks[1].deployment;
expect((fns.deployFn as jest.Mock).mock.calls[1][0]).toEqual(secondStackArg);
expect((fns.deploymentWaitFn as jest.Mock).mock.calls[1][0]).toEqual(secondStackArg);
expect((fns.tableReadyWaitFn as jest.Mock).mock.calls[1][0]).toEqual(secondStackArg);
// third stack
const thirdStackArg = initialContext.stacks[2].deployment;
expect((fns.deployFn as jest.Mock).mock.calls[2][0]).toEqual(thirdStackArg);
expect((fns.deploymentWaitFn as jest.Mock).mock.calls[2][0]).toEqual(thirdStackArg);
expect((fns.tableReadyWaitFn as jest.Mock).mock.calls[2][0]).toEqual(thirdStackArg);
done();
}
})
.start()
.send('DEPLOY');
});
it('should rollback when one of the deployment fails in reverse order of deployment', done => {
// mock deployment fn to fail for second deployment
(fns.deployFn as jest.Mock).mockImplementation(stack => {
if (stack.stackTemplateUrl === initialContext.stacks[2].deployment.stackTemplateUrl) {
return Promise.reject();
}
return Promise.resolve();
});
const firstStackDeploymentArg = initialContext.stacks[0].deployment;
const secondStackDeploymentArg = initialContext.stacks[1].deployment;
const thirdStackDeploymentArg = initialContext.stacks[2].deployment;
const firstStackRollbackArg = initialContext.stacks[0].rollback;
const secoondStackRollbackArg = initialContext.stacks[1].rollback;
const thirdStackRollbackArg = initialContext.stacks[2].rollback;
const machine = createDeploymentMachine(initialContext, fns);
interpret(machine)
.onTransition(state => {
if (state.value === 'rolledBack') {
const rollbackMock = fns.rollbackFn as jest.Mock;
const deployMock = fns.deployFn as jest.Mock;
const deployWaitMock = fns.deploymentWaitFn as jest.Mock;
const tableReadWaitMock = fns.tableReadyWaitFn as jest.Mock;
expect(deployMock).toHaveBeenCalledTimes(3);
expect(deployWaitMock).toHaveBeenCalledTimes(2);
expect(tableReadWaitMock).toHaveBeenCalledTimes(5); // 2 times for deploy and 2 times for rollback and 1 time for before starting rollback
// First stack deployed
expect(deployMock.mock.calls[0][0]).toEqual(firstStackDeploymentArg);
expect(deployWaitMock.mock.calls[0][0]).toEqual(firstStackDeploymentArg);
expect(tableReadWaitMock.mock.calls[0][0]).toEqual(firstStackDeploymentArg);
// second stack deployment
expect(deployMock.mock.calls[1][0]).toEqual(secondStackDeploymentArg);
expect(deployWaitMock.mock.calls[1][0]).toEqual(secondStackDeploymentArg);
expect(tableReadWaitMock.mock.calls[1][0]).toEqual(secondStackDeploymentArg);
// third stack deployment fails
expect(deployMock.mock.calls[2][0]).toEqual(thirdStackDeploymentArg);
// rollback kicks and waits for the table to be ready
expect(tableReadWaitMock.mock.calls[2][0]).toEqual(thirdStackRollbackArg);
expect(rollbackMock).toHaveBeenCalledTimes(2);
// rollback of second stack as the thrid stack is automatically rolled back by CFN
expect(rollbackMock.mock.calls[0][0]).toEqual(secoondStackRollbackArg);
expect(tableReadWaitMock.mock.calls[3]).toContainEqual(secoondStackRollbackArg);
// rollback of first stack after second one is complete
expect(rollbackMock.mock.calls[1][0]).toEqual(firstStackRollbackArg);
expect(tableReadWaitMock.mock.calls[4]).toContainEqual(firstStackRollbackArg);
// Notify rollback
expect(fns.startRollbackFn).toHaveBeenCalledTimes(1);
done();
}
})
.start()
.send('DEPLOY');
});
it('should go to failed state when rollback fails', done => {
const deployFn = fns.deployFn as jest.Mock;
deployFn.mockImplementation(stack => {
if (stack.stackTemplateUrl === initialContext.stacks[2].deployment.stackTemplateUrl) {
return Promise.reject();
}
return Promise.resolve();
});
const rollBackFn = fns.rollbackFn as jest.Mock;
rollBackFn.mockRejectedValue(undefined);
const machine = createDeploymentMachine(initialContext, fns);
interpret(machine)
.onTransition(state => {
if (state.value === 'failed') {
expect(deployFn).toHaveBeenCalledTimes(3);
expect(rollBackFn).toHaveBeenCalledTimes(1);
done();
}
})
.start()
.send('DEPLOY');
});
});
describe('rollback state machine', () => {
const fns: StateMachineRollbackHelperFunctions = {
preRollbackTableCheck: jest.fn().mockResolvedValue(undefined),
rollbackFn: jest.fn().mockResolvedValue(undefined),
rollbackWaitFn: jest.fn().mockResolvedValue(undefined),
tableReadyWaitFn: jest.fn().mockResolvedValue(undefined),
startRollbackFn: jest.fn().mockResolvedValue(undefined),
stackEventPollFn: jest.fn().mockImplementation(() => {
return () => {};
}),
};
const baseDeploymentStep: Omit<DeploymentMachineOp, 'stackTemplateUrl'> = {
parameters: {},
stackName: 'amplify-multideploytest-dev-162313-apimultideploytest-1E3B7HVOV09VD',
stackTemplatePath: 'stack1/cfn.json',
tableNames: ['table1'],
region: 'us-east-2',
capabilities: [],
};
const initialContext: DeployMachineContext = {
previousDeploymentIndex: 2,
currentIndex: 3,
region: 'us-east-2',
deploymentBucket: 'https://s3.amazonaws.com/amplify-multideploytest-dev-162313-deployment',
stacks: [
{
deployment: null,
rollback: {
...baseDeploymentStep,
stackTemplateUrl: 'rollback1.json',
parameters: { rollback: 'true' },
tableNames: ['table1'],
},
},
{
deployment: null,
rollback: {
...baseDeploymentStep,
stackTemplateUrl: 'rollback2.json',
parameters: { rollback: 'true' },
tableNames: ['table1', 'table2'],
},
},
{
deployment: null,
rollback: {
...baseDeploymentStep,
stackTemplateUrl: 'rollback3.json',
parameters: { rollback: 'true' },
tableNames: ['table1', 'table3'],
},
},
],
};
beforeEach(() => {
jest.resetAllMocks();
(fns.preRollbackTableCheck as jest.Mock).mockResolvedValue(undefined), (fns.rollbackFn as jest.Mock).mockResolvedValue(undefined);
(fns.rollbackWaitFn as jest.Mock).mockResolvedValue(undefined);
(fns.startRollbackFn as jest.Mock).mockResolvedValue(undefined);
(fns.tableReadyWaitFn as jest.Mock).mockResolvedValue(undefined);
});
it('should call deployment function multiple times when there are multiple stacks to be deployed', done => {
const machine = createRollbackDeploymentMachine(initialContext, fns);
interpret(machine)
.onTransition(state => {
if (state.value === 'rolledBack') {
// pre deployment functions only called once
expect(fns.preRollbackTableCheck).toHaveBeenCalledTimes(1);
expect(fns.rollbackWaitFn).toHaveBeenCalledTimes(4);
expect(fns.rollbackFn).toHaveBeenCalledTimes(3);
const firstStackArg = initialContext.stacks[2].rollback;
// Pre Stack Check
expect((fns.rollbackWaitFn as jest.Mock).mock.calls[0][0]).toEqual(firstStackArg);
// 1st stack
expect((fns.rollbackFn as jest.Mock).mock.calls[0][0]).toEqual(firstStackArg);
expect((fns.tableReadyWaitFn as jest.Mock).mock.calls[0][0]).toEqual(firstStackArg);
expect((fns.rollbackWaitFn as jest.Mock).mock.calls[1][0]).toEqual(firstStackArg);
// second stack
const secondStackArg = initialContext.stacks[1].rollback;
expect((fns.rollbackFn as jest.Mock).mock.calls[1][0]).toEqual(secondStackArg);
expect((fns.tableReadyWaitFn as jest.Mock).mock.calls[1][0]).toEqual(secondStackArg);
expect((fns.rollbackWaitFn as jest.Mock).mock.calls[2][0]).toEqual(secondStackArg);
// third stack
const thirdStackArg = initialContext.stacks[0].rollback;
expect((fns.rollbackFn as jest.Mock).mock.calls[2][0]).toEqual(thirdStackArg);
expect((fns.tableReadyWaitFn as jest.Mock).mock.calls[2][0]).toEqual(thirdStackArg);
expect((fns.rollbackWaitFn as jest.Mock).mock.calls[3][0]).toEqual(thirdStackArg);
done();
}
})
.start()
.send('ROLLBACK');
});
it('should go to failed state when rollback deployment fails', done => {
const rollbackFn = fns.rollbackFn as jest.Mock;
rollbackFn.mockImplementation(stack => {
if (stack.stackTemplateUrl === initialContext.stacks[1].rollback.stackTemplateUrl) {
return Promise.reject();
}
return Promise.resolve();
});
const machine = createRollbackDeploymentMachine(initialContext, fns);
interpret(machine)
.onTransition(state => {
if (state.value === 'failed') {
// pre deployment functions only called once
expect(fns.preRollbackTableCheck).toHaveBeenCalledTimes(1);
expect(fns.tableReadyWaitFn).toHaveBeenCalledTimes(1);
expect(rollbackFn).toHaveBeenCalledTimes(2);
done();
}
})
.start()
.send('ROLLBACK');
});
}); | the_stack |
import * as os from 'os';
import * as path from 'path';
import { metricScope, Unit } from 'aws-embedded-metrics';
import type { PromiseResult } from 'aws-sdk/lib/request';
import * as fs from 'fs-extra';
import * as docgen from 'jsii-docgen';
import { CacheStrategy } from '../../caching';
import type { TransliteratorInput } from '../payload-schema';
import * as aws from '../shared/aws.lambda-shared';
import { logInWithCodeArtifact } from '../shared/code-artifact.lambda-shared';
import { compressContent } from '../shared/compress-content.lambda-shared';
import * as constants from '../shared/constants';
import { requireEnv } from '../shared/env.lambda-shared';
import { DocumentationLanguage } from '../shared/language';
import { shellOut } from '../shared/shell-out.lambda-shared';
import { MetricName, METRICS_NAMESPACE } from './constants';
import { writeFile } from './util';
const ASSEMBLY_KEY_REGEX = new RegExp(`^${constants.STORAGE_KEY_PREFIX}((?:@[^/]+/)?[^/]+)/v([^/]+)${constants.ASSEMBLY_KEY_SUFFIX}$`);
// Capture groups: ┗━━━━━━━━━1━━━━━━━┛ ┗━━2━━┛
/**
* This function receives an S3 event, and for each record, proceeds to download
* the `.jsii` assembly the event refers to, transliterates it to the language,
* configured in `TARGET_LANGUAGE`, and uploads the resulting `.jsii.<lang>`
* object to S3.
*
* @param event an S3 event payload
* @param context a Lambda execution context
*
* @returns nothing
*/
export function handler(event: TransliteratorInput): Promise<{ created: S3Object[]; deleted: S3Object[] }> {
console.log(`Event: ${JSON.stringify(event, null, 2)}`);
// We'll need a writable $HOME directory, or this won't work well, because
// npm will try to write stuff like the `.npmrc` or package caches in there
// and that'll bail out on EROFS if that fails.
return ensureWritableHome(async () => {
const endpoint = process.env.CODE_ARTIFACT_REPOSITORY_ENDPOINT;
if (!endpoint) {
console.log('No CodeArtifact endpoint configured - using npm\'s default registry');
} else {
console.log(`Using CodeArtifact registry: ${endpoint}`);
const domain = requireEnv('CODE_ARTIFACT_DOMAIN_NAME');
const domainOwner = process.env.CODE_ARTIFACT_DOMAIN_OWNER;
const apiEndpoint = process.env.CODE_ARTIFACT_API_ENDPOINT;
await logInWithCodeArtifact({ endpoint, domain, domainOwner, apiEndpoint });
}
// Set up NPM shared cache directory (https://docs.npmjs.com/cli/v7/using-npm/config#cache)
const npmCacheDir = process.env.NPM_CACHE;
if (npmCacheDir) {
// Create it if it does not exist yet...
await fs.mkdirp(npmCacheDir);
console.log(`Using shared NPM cache at: ${npmCacheDir}`);
await shellOut('npm', 'config', 'set', `cache=${npmCacheDir}`);
}
const created = new Array<S3Object>();
const deleted = new Array<S3Object>();
const [, packageName, packageVersion] = event.assembly.key.match(ASSEMBLY_KEY_REGEX) ?? [];
if (packageName == null) {
throw new Error(`Invalid object key: "${event.assembly.key}". It was expected to match ${ASSEMBLY_KEY_REGEX}!`);
}
const packageFqn = `${packageName}@${packageVersion}`;
console.log(`Source Bucket: ${event.bucket}`);
console.log(`Source Key: ${event.assembly.key}`);
console.log(`Source Version: ${event.assembly.versionId}`);
console.log(`Fetching assembly: ${event.assembly.key}`);
const assemblyResponse = await aws.s3().getObject({ Bucket: event.bucket, Key: event.assembly.key }).promise();
if (!assemblyResponse.Body) {
throw new Error(`Response body for assembly at key ${event.assembly.key} is empty`);
}
const assembly = JSON.parse(assemblyResponse.Body.toString('utf-8'));
const submodules = Object.keys(assembly.submodules ?? {}).map(s => s.split('.')[1]);
console.log(`Fetching package: ${event.package.key}`);
const tarballExists = await aws.s3ObjectExists(event.bucket, event.package.key);
if (!tarballExists) {
throw new Error(`Tarball does not exist at key ${event.package.key} in bucket ${event.bucket}.`);
}
const readStream = aws.s3().getObject({ Bucket: event.bucket, Key: event.package.key }).createReadStream();
const tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), 'packages-'));
const tarball = path.join(tmpdir, 'package.tgz');
await writeFile(tarball, readStream);
const uploads = new Map<string, Promise<PromiseResult<AWS.S3.PutObjectOutput, AWS.AWSError>>>();
const deletions = new Map<string, Promise<PromiseResult<AWS.S3.DeleteObjectOutput, AWS.AWSError>>>();
let unprocessable: boolean = false;
function markPackage(e: Error, marker: string) {
const key = event.assembly.key.replace(/\/[^/]+$/, marker);
const upload = uploadFile(event.bucket, key, event.assembly.versionId, Buffer.from(e.message));
uploads.set(key, upload);
}
async function unmarkPackage(marker: string) {
const key = event.assembly.key.replace(/\/[^/]+$/, marker);
const marked = await aws.s3ObjectExists(event.bucket, key);
if (!marked) {
return;
}
const deletion = deleteFile(event.bucket, key);
deletions.set(key, deletion);
}
console.log(`Generating documentation for ${packageFqn}...`);
try {
const docs = await docgen.Documentation.forPackage(tarball, { name: assembly.name });
// if the package used to not be installabe, remove the marker for it.
await unmarkPackage(constants.UNINSTALLABLE_PACKAGE_SUFFIX);
for (const language of DocumentationLanguage.ALL) {
if (event.languages && !event.languages[language.toString()]) {
console.log(`Skipping language ${language} as it was not requested!`);
continue;
}
const generateDocs = metricScope((metrics) => async (lang: DocumentationLanguage) => {
metrics.setDimensions();
metrics.setNamespace(METRICS_NAMESPACE);
async function renderAndDispatch(submodule?: string) {
try {
console.log(`Rendering documentation in ${lang} for ${packageFqn} (submodule: ${submodule})`);
const markdown = await docs.render({
submodule,
linkFormatter: linkFormatter,
language: docgen.Language.fromString(lang.name),
});
// if the package used to have a corrupt assembly, remove the marker for it.
await unmarkPackage(constants.corruptAssemblyKeySuffix(language, submodule));
const page = Buffer.from(markdown.render());
metrics.putMetric(MetricName.DOCUMENT_SIZE, page.length, Unit.Bytes);
const { buffer: body, contentEncoding } = compressContent(page);
metrics.putMetric(MetricName.COMPRESSED_DOCUMENT_SIZE, body.length, Unit.Bytes);
const key = event.assembly.key.replace(/\/[^/]+$/, constants.docsKeySuffix(lang, submodule));
console.log(`Uploading ${key}`);
const upload = uploadFile(event.bucket, key, event.assembly.versionId, body, contentEncoding);
uploads.set(key, upload);
} catch (e) {
if (e instanceof docgen.LanguageNotSupportedError) {
markPackage(e, constants.notSupportedKeySuffix(language, submodule));
} else if (e instanceof docgen.CorruptedAssemblyError) {
markPackage(e, constants.corruptAssemblyKeySuffix(language, submodule));
unprocessable = true;
} else {
throw e;
}
}
}
await renderAndDispatch();
for (const submodule of submodules) {
await renderAndDispatch(submodule);
}
});
await generateDocs(language);
}
} catch (error) {
if (error instanceof docgen.UnInstallablePackageError) {
markPackage(error, constants.UNINSTALLABLE_PACKAGE_SUFFIX);
unprocessable = true;
} else {
throw error;
}
}
for (const [key, upload] of uploads.entries()) {
const response = await upload;
created.push({ bucket: event.bucket, key, versionId: response.VersionId });
console.log(`Finished uploading ${key} (Version ID: ${response.VersionId})`);
}
for (const [key, deletion] of deletions.entries()) {
const response = await deletion;
deleted.push({ bucket: event.bucket, key, versionId: response.VersionId });
console.log(`Finished deleting ${key} (Version ID: ${response.VersionId})`);
}
if (unprocessable) {
// the message here doesn't matter, we only use the error name
// to divert this message away from the DLQ.
const error = new Error();
error.name = constants.UNPROCESSABLE_PACKAGE_ERROR_NAME;
}
return { created, deleted };
});
}
async function ensureWritableHome<T>(cb: () => Promise<T>): Promise<T> {
// Since $HOME is not set, or is not writable, we'll just go make our own...
const fakeHome = await fs.mkdtemp(path.join(os.tmpdir(), 'fake-home'));
console.log(`Made temporary $HOME directory: ${fakeHome}`);
const oldHome = process.env.HOME;
try {
process.env.HOME = fakeHome;
return await cb();
} finally {
process.env.HOME = oldHome;
await fs.remove(fakeHome);
console.log(`Cleaned-up temporary $HOME directory: ${fakeHome}`);
}
}
function uploadFile(bucket: string, key: string, sourceVersionId?: string, body?: AWS.S3.Body, contentEncoding?: 'gzip') {
return aws.s3().putObject({
Bucket: bucket,
Key: key,
Body: body,
CacheControl: CacheStrategy.default().toString(),
ContentEncoding: contentEncoding,
ContentType: 'text/markdown; charset=UTF-8',
Metadata: {
'Origin-Version-Id': sourceVersionId ?? 'N/A',
},
}).promise();
}
function deleteFile(bucket: string, key: string) {
return aws.s3().deleteObject({
Bucket: bucket,
Key: key,
}).promise();
}
/**
* A link formatter to make sure type links redirect to the appropriate package
* page in the webapp.
*/
function linkFormatter(type: docgen.TranspiledType): string {
const packageName = type.source.assembly.name;
const packageVersion = type.source.assembly.version;
// the webapp sanitizes anchors - so we need to as well when
// linking to them.
const hash = sanitize(type.fqn);
const query = `?lang=${type.language.toString()}${type.submodule ? `&submodule=${type.submodule}` : ''}`;
return `/packages/${packageName}/v/${packageVersion}/api/${hash}${query}`;
}
function sanitize(input: string): string {
return input
.toLowerCase()
.replace(/[^a-zA-Z0-9 ]/g, '')
.replace(/ /g, '-');
};
interface S3Object {
readonly bucket: string;
readonly key: string;
readonly versionId?: string;
} | the_stack |
declare module 'react' {
interface ComponentClass<P> {
new(props: P): Component<any, any>;
}
//
// Component
// ----------------------------------------------------------------------
class Component<P extends BaseProps, S> {
constructor(initialProps: P);
public getDOMNode(): Element;
public isMounted(): boolean;
props: P;
protected setProps(nextProps: P, callback?: () => void): void;
protected replaceProps(nextProps: P, callback?: () => void): void;
state: S;
protected setState(nextState: S, callback?: () => void): void;
protected replaceState(nextState: S, callback?: () => void): void;
protected context: any; // I won't introduce a third generic type for that sorry
protected render(): ReactElement | string;
protected componentWillMount(): void;
protected componentDidMount(): void;
protected componentWillReceiveProps(nextProps: P): void;
protected shouldComponentUpdate(nextProps: P, nextState: S): boolean;
protected componentWillUpdate(nextProps: P, nextState: S): void;
protected componentDidUpdate(prevProps: P, prevState: S): void;
protected componentWillUnmount(): void;
static defaultProps: any;
static propTypes: ValidationMap<any>;
static contextTypes: ValidationMap<any>;
static childContextTypes: ValidationMap<any>;
}
//
// ReactElement
// ----------------------------------------------------------------------
interface ReactCompositeElement<P> {
type: ComponentClass<P>
ref: (c: Component<any, any>) => any;
key : string | boolean | number;
props: P;
}
interface ReactHTMLElement {
type: string;
ref: (c: Component<HTMLAttributes, any>) => any;
key : string | boolean | number;
props: HTMLAttributes;
}
interface ReactSVGElement {
type: string;
ref: (c: Component<SVGAttributes, any>) => any;
key : string | boolean | number;
props: SVGAttributes;
}
type ReactElement = ReactHTMLElement | ReactSVGElement | ReactCompositeElement<any>;
interface ReactElementArray extends Array<string | ReactElement | ReactElementArray> {}
function createElement(type: string, props: HTMLAttributes, ...children: any[]): ReactHTMLElement;
function createElement(type: string, props: SVGAttributes, ...children: any[]): ReactSVGElement;
function createElement<P extends BaseProps>(type: ComponentClass<P>, props: P, ...children: any[]): ReactCompositeElement<P>
//
// Event System
// ----------------------------------------------------------------------
interface SyntheticEvent {
bubbles: boolean;
cancelable: boolean;
currentTarget: EventTarget;
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
nativeEvent: Event;
preventDefault(): void;
stopPropagation(): void;
target: EventTarget;
timeStamp: Date;
type: string;
}
interface ClipboardEvent extends SyntheticEvent {
clipboardData: DataTransfer;
}
interface KeyboardEvent extends SyntheticEvent {
altKey: boolean;
charCode: number;
ctrlKey: boolean;
getModifierState(key: string): boolean;
key: string;
keyCode: number;
locale: string;
location: number;
metaKey: boolean;
repeat: boolean;
shiftKey: boolean;
which: number;
}
interface FocusEvent extends SyntheticEvent {
relatedTarget: EventTarget;
}
interface FormEvent extends SyntheticEvent {
}
interface MouseEvent extends SyntheticEvent {
altKey: boolean;
button: number;
buttons: number;
clientX: number;
clientY: number;
ctrlKey: boolean;
getModifierState(key: string): boolean;
metaKey: boolean;
pageX: number;
pageY: number;
relatedTarget: EventTarget;
screenX: number;
screenY: number;
shiftKey: boolean;
}
interface TouchEvent extends SyntheticEvent {
altKey: boolean;
changedTouches: TouchList;
ctrlKey: boolean;
getModifierState(key: string): boolean;
metaKey: boolean;
shiftKey: boolean;
targetTouches: TouchList;
touches: TouchList;
}
interface UIEvent extends SyntheticEvent {
detail: number;
view: AbstractView;
}
interface WheelEvent extends SyntheticEvent {
deltaMode: number;
deltaX: number;
deltaY: number;
deltaZ: number;
}
//
// Event Handler Types
// ----------------------------------------------------------------------
interface EventHandler<E extends SyntheticEvent> {
(event: E): void;
}
interface ClipboardEventHandler extends EventHandler<ClipboardEvent> {}
interface KeyboardEventHandler extends EventHandler<KeyboardEvent> {}
interface FocusEventHandler extends EventHandler<FocusEvent> {}
interface FormEventHandler extends EventHandler<FormEvent> {}
interface MouseEventHandler extends EventHandler<MouseEvent> {}
interface TouchEventHandler extends EventHandler<TouchEvent> {}
interface UIEventHandler extends EventHandler<UIEvent> {}
interface WheelEventHandler extends EventHandler<WheelEvent> {}
//
// Attributes
// ----------------------------------------------------------------------
interface BaseProps {
children?: string | ReactElement | ReactElementArray;
key?: string;
ref?: (c: Component<any, any>) => void
}
interface ReactBaseElementAttributes extends BaseProps {
// Event Attributes
onCopy?: ClipboardEventHandler;
onCut?: ClipboardEventHandler;
onPaste?: ClipboardEventHandler;
onKeyDown?: KeyboardEventHandler;
onKeyPress?: KeyboardEventHandler;
onKeyUp?: KeyboardEventHandler;
onFocus?: FocusEventHandler;
onBlur?: FocusEventHandler;
onChange?: FormEventHandler;
onInput?: FormEventHandler;
onSubmit?: FormEventHandler;
onClick?: MouseEventHandler;
onDoubleClick?: MouseEventHandler;
onDrag?: MouseEventHandler;
onDragEnd?: MouseEventHandler;
onDragEnter?: MouseEventHandler;
onDragExit?: MouseEventHandler;
onDragLeave?: MouseEventHandler;
onDragOver?: MouseEventHandler;
onDragStart?: MouseEventHandler;
onDrop?: MouseEventHandler;
onMouseDown?: MouseEventHandler;
onMouseEnter?: MouseEventHandler;
onMouseLeave?: MouseEventHandler;
onMouseMove?: MouseEventHandler;
onMouseOut?: MouseEventHandler;
onMouseOver?: MouseEventHandler;
onMouseUp?: MouseEventHandler;
onTouchCancel?: TouchEventHandler;
onTouchEnd?: TouchEventHandler;
onTouchMove?: TouchEventHandler;
onTouchStart?: TouchEventHandler;
onScroll?: UIEventHandler;
onWheel?: WheelEventHandler;
dangerouslySetInnerHTML?: {
__html: string;
};
}
interface CSSProperties {
columnCount?: number;
flex?: number | string;
flexGrow?: number;
flexShrink?: number;
fontWeight?: number;
lineClamp?: number;
lineHeight?: number;
opacity?: number;
order?: number;
orphans?: number;
widows?: number;
zIndex?: number;
zoom?: number;
// SVG-related properties
fillOpacity?: number;
strokeOpacity?: number;
}
interface HTMLAttributes extends ReactBaseElementAttributes {
accept?: string;
acceptCharset?: string;
accessKey?: string;
action?: string;
allowFullScreen?: boolean;
allowTransparency?: boolean;
alt?: string;
async?: boolean;
autoComplete?: boolean;
autoFocus?: boolean;
autoPlay?: boolean;
cellPadding?: number | string;
cellSpacing?: number | string;
charSet?: string;
checked?: boolean;
classID?: string;
className?: string;
cols?: number;
colSpan?: number;
content?: string;
contentEditable?: boolean;
contextMenu?: string;
controls?: any;
coords?: string;
crossOrigin?: string;
data?: string;
dateTime?: string;
defer?: boolean;
dir?: string;
disabled?: boolean;
download?: any;
draggable?: boolean;
encType?: string;
form?: string;
formNoValidate?: boolean;
frameBorder?: number | string;
height?: number | string;
hidden?: boolean;
href?: string;
hrefLang?: string;
htmlFor?: string;
httpEquiv?: string;
icon?: string;
id?: string;
label?: string;
lang?: string;
list?: string;
loop?: boolean;
manifest?: string;
max?: number | string;
maxLength?: number;
media?: string;
mediaGroup?: string;
method?: string;
min?: number | string;
multiple?: boolean;
muted?: boolean;
name?: string;
noValidate?: boolean;
open?: boolean;
pattern?: string;
placeholder?: string;
poster?: string;
preload?: string;
radioGroup?: string;
readOnly?: boolean;
rel?: string;
required?: boolean;
role?: string;
rows?: number;
rowSpan?: number;
sandbox?: string;
scope?: string;
scrollLeft?: number;
scrolling?: string;
scrollTop?: number;
seamless?: boolean;
selected?: boolean;
shape?: string;
size?: number;
sizes?: string;
span?: number;
spellCheck?: boolean;
src?: string;
srcDoc?: string;
srcSet?: string;
start?: number;
step?: number | string;
style?: CSSProperties;
tabIndex?: number;
target?: string;
title?: string;
type?: string;
useMap?: string;
value?: string;
width?: number | string;
wmode?: string;
// Non-standard Attributes
autoCapitalize?: boolean;
autoCorrect?: boolean;
property?: string;
itemProp?: string;
itemScope?: boolean;
itemType?: string;
}
interface SVGAttributes extends ReactBaseElementAttributes {
cx?: SVGLength | SVGAnimatedLength;
cy?: any;
d?: string;
dx?: SVGLength | SVGAnimatedLength;
dy?: SVGLength | SVGAnimatedLength;
fill?: any; // SVGPaint | string
fillOpacity?: number | string;
fontFamily?: string;
fontSize?: number | string;
fx?: SVGLength | SVGAnimatedLength;
fy?: SVGLength | SVGAnimatedLength;
gradientTransform?: SVGTransformList | SVGAnimatedTransformList;
gradientUnits?: string;
markerEnd?: string;
markerMid?: string;
markerStart?: string;
offset?: number | string;
opacity?: number | string;
patternContentUnits?: string;
patternUnits?: string;
points?: string;
preserveAspectRatio?: string;
r?: SVGLength | SVGAnimatedLength;
rx?: SVGLength | SVGAnimatedLength;
ry?: SVGLength | SVGAnimatedLength;
spreadMethod?: string;
stopColor?: any; // SVGColor | string
stopOpacity?: number | string;
stroke?: any; // SVGPaint
strokeDasharray?: string;
strokeLinecap?: string;
strokeOpacity?: number | string;
strokeWidth?: SVGLength | SVGAnimatedLength;
textAnchor?: string;
transform?: SVGTransformList | SVGAnimatedTransformList;
version?: string;
viewBox?: string;
x1?: SVGLength | SVGAnimatedLength;
x2?: SVGLength | SVGAnimatedLength;
x?: SVGLength | SVGAnimatedLength;
y1?: SVGLength | SVGAnimatedLength;
y2?: SVGLength | SVGAnimatedLength
y?: SVGLength | SVGAnimatedLength;
}
//
// Browser Interfaces
// https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts
// ----------------------------------------------------------------------
interface AbstractView {
styleMedia: StyleMedia;
document: Document;
}
interface Touch {
identifier: number;
target: EventTarget;
screenX: number;
screenY: number;
clientX: number;
clientY: number;
pageX: number;
pageY: number;
}
interface TouchList {
[index: number]: Touch;
length: number;
item(index: number): Touch;
identifiedTouch(identifier: number): Touch;
}
//
// React.PropTypes
// ----------------------------------------------------------------------
interface Validator<T> {
(object: T, key: string, componentName: string): Error;
}
interface Requireable<T> extends Validator<T> {
isRequired: Validator<T>;
}
interface ValidationMap<T> {
[key: string]: Validator<T>;
}
var PropTypes: {
any: Requireable<any>;
array: Requireable<any>;
bool: Requireable<any>;
func: Requireable<any>;
number: Requireable<any>;
object: Requireable<any>;
string: Requireable<any>;
node: Requireable<any>;
element: Requireable<any>;
instanceOf(expectedClass: {}): Requireable<any>;
oneOf(types: any[]): Requireable<any>;
oneOfType(types: Validator<any>[]): Requireable<any>;
arrayOf(type: Validator<any>): Requireable<any>;
objectOf(type: Validator<any>): Requireable<any>;
shape(type: ValidationMap<any>): Requireable<any>;
}
//
// React.Children
// ----------------------------------------------------------------------
type ReactChild = string | ReactElement;
type ReactChildList = string | ReactElement | ReactElementArray
interface ReactChildren {
map<T>(children: ReactElementArray, fn: (child: ReactChild) => T): Array<T>;
forEach(children: ReactElementArray, fn: (child: ReactChild) => any): void;
count(children: ReactElementArray): number;
only(children: ReactElementArray): ReactChild;
}
function render(element: ReactElement, container: Element, callback?: () => void): Component<any, any>;
function renderToString(element: ReactElement): string;
function renderToStaticMarkup(element: ReactElement): string;
function isValidElement(element: any): boolean;
function unmountComponentAtNode(container: Element): boolean;
function initializeTouchEvents(shouldUseTouch: boolean): void;
} | the_stack |
import { createParser } from './parser';
import { isObject } from './utils';
import {
RequestParams,
Sink,
StreamMessage,
ExecutionResult,
ExecutionPatchResult,
TOKEN_HEADER_KEY,
} from './common';
/** This file is the entry point for browsers, re-export common elements. */
export * from './common';
/** @category Client */
export interface ClientOptions {
/**
* Reuses a single SSE connection for all GraphQL operations.
*
* When instantiating with `false` (default), the client will run
* in a "distinct connections mode" mode. Meaning, a new SSE
* connection will be established on each subscribe.
*
* On the other hand, when instantiating with `true`, the client
* will run in a "single connection mode" mode. Meaning, a single SSE
* connection will be used to transmit all operation results while
* separate HTTP requests will be issued to dictate the behaviour.
*
* @default false
*/
singleConnection?: boolean;
/**
* Controls when should the connection be established while using the
* client in "single connection mode" (see `singleConnection ` option).
*
* - `false`: Establish a connection immediately.
* - `true`: Establish a connection on first subscribe and close on last unsubscribe.
*
* Note that the `lazy` option has NO EFFECT when using the client
* in "distinct connection mode" (`singleConnection = false`).
*
* @default true
*/
lazy?: boolean;
/**
* Used ONLY when the client is in non-lazy mode (`lazy = false`). When
* using this mode, errors might have no sinks to report to; however,
* to avoid swallowing errors, `onNonLazyError` will be called when either:
* - An unrecoverable error/close event occurs
* - Silent retry attempts have been exceeded
*
* After a client has errored out, it will NOT perform any automatic actions.
*
* @default console.error
*/
onNonLazyError?: (error: unknown) => void;
/**
* URL of the GraphQL over SSE server to connect.
*
* If the option is a function, it will be called on each connection attempt.
* Returning a Promise is supported too and the connection phase will stall until it
* resolves with the URL.
*
* A good use-case for having a function is when using the URL for authentication,
* where subsequent reconnects (due to auth) may have a refreshed identity token in
* the URL.
*/
url: string | (() => Promise<string> | string);
/**
* HTTP headers to pass along the request.
*
* If the option is a function, it will be called on each connection attempt.
* Returning a Promise is supported too and the connection phase will stall until it
* resolves with the headers.
*
* A good use-case for having a function is when using the headers for authentication,
* where subsequent reconnects (due to auth) may have a refreshed identity token in
* the header.
*/
headers?:
| Record<string, string>
| (() => Promise<Record<string, string>> | Record<string, string>);
/**
* The Fetch function to use.
*
* For NodeJS environments consider using [`node-fetch`](https://github.com/node-fetch/node-fetch).
*
* @default global.fetch
*/
fetchFn?: unknown;
/**
* The AbortController implementation to use.
*
* For NodeJS environments before v15 consider using [`node-abort-controller`](https://github.com/southpolesteve/node-abort-controller).
*
* @default global.AbortController
*/
abortControllerImpl?: unknown;
/**
* A custom ID generator for identifying subscriptions.
*
* The default generates a v4 UUID to be used as the ID using `Math`
* as the random number generator. Supply your own generator
* in case you need more uniqueness.
*
* Reference: https://gist.github.com/jed/982883
*/
generateID?: () => string;
/**
* How many times should the client try to reconnect before it errors out?
*
* @default 5
*/
retryAttempts?: number;
/**
* Control the wait time between retries. You may implement your own strategy
* by timing the resolution of the returned promise with the retries count.
*
* `retries` argument counts actual reconnection attempts, so it will begin with
* 0 after the first retryable disconnect.
*
* @default 'Randomised exponential backoff, 5 times'
*/
retry?: (retries: number) => Promise<void>;
}
/** @category Client */
export interface Client {
/**
* Subscribes to receive through a SSE connection.
*
* It uses the `sink` to emit received data or errors. Returns a _dispose_
* function used for dropping the subscription and cleaning up.
*/
subscribe<Data = Record<string, unknown>, Extensions = unknown>(
request: RequestParams,
sink: Sink<ExecutionResult<Data, Extensions>>,
): () => void;
/**
* Dispose of the client, destroy connections and clean up resources.
*/
dispose: () => void;
}
/**
* Creates a disposable GraphQL over SSE client to transmit
* GraphQL operation results.
*
* If you have an HTTP/2 server, it is recommended to use the client
* in "distinct connections mode" (`singleConnection = false`) which will
* create a new SSE connection for each subscribe. This is the default.
*
* However, when dealing with HTTP/1 servers from a browser, consider using
* the "single connection mode" (`singleConnection = true`) which will
* use only one SSE connection.
*
* @category Client
*/
export function createClient(options: ClientOptions): Client {
const {
singleConnection = false,
lazy = true,
onNonLazyError = console.error,
/**
* Generates a v4 UUID to be used as the ID using `Math`
* as the random number generator. Supply your own generator
* in case you need more uniqueness.
*
* Reference: https://gist.github.com/jed/982883
*/
generateID = function generateUUID() {
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);
});
},
retryAttempts = 5,
retry = async function randomisedExponentialBackoff(retries) {
let retryDelay = 1000; // start with 1s delay
for (let i = 0; i < retries; i++) {
retryDelay *= 2;
}
await new Promise((resolve) =>
setTimeout(
resolve,
retryDelay +
// add random timeout from 300ms to 3s
Math.floor(Math.random() * (3000 - 300) + 300),
),
);
},
} = options;
const fetchFn = (options.fetchFn || fetch) as typeof fetch;
const AbortControllerImpl = (options.abortControllerImpl ||
AbortController) as typeof AbortController;
// we dont use yet another AbortController here because of
// node's max EventEmitters listeners being only 10
const client = (() => {
let disposed = false;
const listeners: (() => void)[] = [];
return {
get disposed() {
return disposed;
},
onDispose(cb: () => void) {
if (disposed) {
// empty the call stack and then call the cb
setTimeout(() => cb(), 0);
return () => {
// noop
};
}
listeners.push(cb);
return () => {
listeners.splice(listeners.indexOf(cb), 1);
};
},
dispose() {
if (disposed) return;
disposed = true;
// we copy the listeners so that onDispose unlistens dont "pull the rug under our feet"
for (const listener of [...listeners]) {
listener();
}
},
};
})();
let connCtrl: AbortController,
conn: Promise<Connection> | undefined,
locks = 0,
retryingErr = null as unknown,
retries = 0;
async function getOrConnect(): Promise<NonNullable<typeof conn>> {
try {
if (client.disposed) throw new Error('Client has been disposed');
return await (conn ??
(conn = (async () => {
if (retryingErr) {
await retry(retries);
// connection might've been aborted while waiting for retry
if (connCtrl.signal.aborted)
throw new Error('Connection aborted by the client');
retries++;
}
// we must create a new controller here because lazy mode aborts currently active ones
connCtrl = new AbortControllerImpl();
const unlistenDispose = client.onDispose(() => connCtrl.abort());
connCtrl.signal.addEventListener('abort', () => {
unlistenDispose();
conn = undefined;
});
const url =
typeof options.url === 'function'
? await options.url()
: options.url;
if (connCtrl.signal.aborted)
throw new Error('Connection aborted by the client');
const headers =
typeof options.headers === 'function'
? await options.headers()
: options.headers ?? {};
if (connCtrl.signal.aborted)
throw new Error('Connection aborted by the client');
let res;
try {
res = await fetchFn(url, {
signal: connCtrl.signal,
method: 'PUT',
headers,
});
} catch (err) {
throw new NetworkError(err);
}
if (res.status !== 201) throw new NetworkError(res);
const token = await res.text();
headers[TOKEN_HEADER_KEY] = token;
const connected = await connect({
signal: connCtrl.signal,
headers,
url,
fetchFn,
});
retryingErr = null; // future connects are not retries
retries = 0; // reset the retries on connect
connected.waitForThrow().catch(() => (conn = undefined));
return connected;
})()));
} catch (err) {
// whatever problem happens during connect means the connection was not established
conn = undefined;
throw err;
}
}
// non-lazy mode always holds one lock to persist the connection
if (singleConnection && !lazy) {
(async () => {
locks++;
for (;;) {
try {
const { waitForThrow } = await getOrConnect();
await waitForThrow();
} catch (err) {
if (client.disposed) return;
// all non-network errors are worth reporting immediately
if (!(err instanceof NetworkError)) return onNonLazyError?.(err);
// retries are not allowed or we tried to many times, report error
if (!retryAttempts || retries >= retryAttempts)
return onNonLazyError?.(err);
// try again
retryingErr = err;
}
}
})();
}
return {
subscribe(request, sink) {
if (!singleConnection) {
// distinct connections mode
const control = new AbortControllerImpl();
const unlisten = client.onDispose(() => {
unlisten();
control.abort();
});
(async () => {
let retryingErr = null as unknown,
retries = 0;
for (;;) {
try {
if (retryingErr) {
await retry(retries);
// connection might've been aborted while waiting for retry
if (control.signal.aborted)
throw new Error('Connection aborted by the client');
retries++;
}
const url =
typeof options.url === 'function'
? await options.url()
: options.url;
if (control.signal.aborted)
throw new Error('Connection aborted by the client');
const headers =
typeof options.headers === 'function'
? await options.headers()
: options.headers ?? {};
if (control.signal.aborted)
throw new Error('Connection aborted by the client');
const { getResults } = await connect({
signal: control.signal,
headers,
url,
body: JSON.stringify(request),
fetchFn,
});
retryingErr = null; // future connects are not retries
retries = 0; // reset the retries on connect
for await (const result of getResults()) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sink.next(result as any);
}
return control.abort();
} catch (err) {
if (control.signal.aborted) return;
// all non-network errors are worth reporting immediately
if (!(err instanceof NetworkError)) throw err;
// retries are not allowed or we tried to many times, report error
if (!retryAttempts || retries >= retryAttempts) throw err;
// try again
retryingErr = err;
}
}
})()
.then(() => sink.complete())
.catch((err) => sink.error(err));
return () => control.abort();
}
// single connection mode
locks++;
const control = new AbortControllerImpl();
const unlisten = client.onDispose(() => {
unlisten();
control.abort();
});
(async () => {
const operationId = generateID();
request = {
...request,
extensions: { ...request.extensions, operationId },
};
let complete: (() => Promise<void>) | null = null;
for (;;) {
complete = null;
try {
const { url, headers, getResults } = await getOrConnect();
let res;
try {
res = await fetchFn(url, {
signal: control.signal,
method: 'POST',
headers,
body: JSON.stringify(request),
});
} catch (err) {
throw new NetworkError(err);
}
if (res.status !== 202) throw new NetworkError(res);
complete = async () => {
let res;
try {
const control = new AbortControllerImpl();
const unlisten = client.onDispose(() => {
unlisten();
control.abort();
});
res = await fetchFn(url + '?operationId=' + operationId, {
signal: control.signal,
method: 'DELETE',
headers,
});
} catch (err) {
throw new NetworkError(err);
}
if (res.status !== 200) throw new NetworkError(res);
};
for await (const result of getResults({
signal: control.signal,
operationId,
})) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sink.next(result as any);
}
complete = null; // completed by the server
return control.abort();
} catch (err) {
if (control.signal.aborted) return await complete?.();
// all non-network errors are worth reporting immediately
if (!(err instanceof NetworkError)) throw err;
// retries are not allowed or we tried to many times, report error
if (!retryAttempts || retries >= retryAttempts) throw err;
// try again
retryingErr = err;
} finally {
// release lock if aborted, and disconnect if no more locks
if (control.signal.aborted && --locks === 0) connCtrl.abort();
}
}
})()
.then(() => sink.complete())
.catch((err) => sink.error(err));
return () => control.abort();
},
dispose() {
client.dispose();
},
};
}
/**
* A network error caused by the client or an unexpected response from the server.
*
* Network errors are considered retryable, all others error types will be reported
* immediately.
*
* To avoid bundling DOM typings (because the client can run in Node env too),
* you should supply the `Response` generic depending on your Fetch implementation.
*
* @category Client
*/
export class NetworkError<
Response extends ResponseLike = ResponseLike,
> extends Error {
/**
* The underlyig response thats considered an error.
*
* Will be undefined when no response is received,
* instead an unexpected network error.
*/
public response: Response | undefined;
constructor(msgOrErrOrResponse: string | Error | Response) {
let message, response: Response | undefined;
if (isResponseLike(msgOrErrOrResponse)) {
response = msgOrErrOrResponse;
message =
'Server responded with ' +
msgOrErrOrResponse.status +
': ' +
msgOrErrOrResponse.statusText;
} else if (msgOrErrOrResponse instanceof Error)
message = msgOrErrOrResponse.message;
else message = String(msgOrErrOrResponse);
super(message);
this.name = this.constructor.name;
this.response = response;
}
}
interface ResponseLike {
readonly ok: boolean;
readonly status: number;
readonly statusText: string;
}
function isResponseLike(val: unknown): val is ResponseLike {
return (
isObject(val) &&
typeof val['ok'] === 'boolean' &&
typeof val['status'] === 'number' &&
typeof val['statusText'] === 'string'
);
}
interface Connection {
url: string;
headers: Record<string, string> | undefined;
waitForThrow: () => Promise<void>;
getResults: (options?: {
signal: AbortSignal;
operationId: string;
}) => AsyncIterable<ExecutionResult | ExecutionPatchResult>;
}
interface ConnectOptions {
signal: AbortSignal;
url: string;
headers?: Record<string, string> | undefined;
body?: string;
fetchFn: typeof fetch;
}
async function connect(options: ConnectOptions): Promise<Connection> {
const { signal, url, headers, body, fetchFn } = options;
const waiting: {
[id: string]: { proceed: () => void };
} = {};
const queue: {
[id: string]: (ExecutionResult | ExecutionPatchResult | 'complete')[];
} = {};
let res;
try {
res = await fetchFn(url, {
signal,
method: body ? 'POST' : 'GET',
headers: {
...headers,
accept: 'text/event-stream',
},
body,
});
} catch (err) {
throw new NetworkError(err);
}
if (!res.ok) throw new NetworkError(res);
if (!res.body) throw new Error('Missing response body');
let error: unknown = null;
let waitingForThrow: ((error: unknown) => void) | null = null;
(async () => {
try {
const parse = createParser();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
for await (const chunk of toAsyncIterator(res.body!)) {
if (typeof chunk === 'string')
throw new Error(`Unexpected string chunk "${chunk}"`);
// read chunk and if messages are ready, yield them
const msgs = parse(chunk);
if (!msgs) continue;
for (const msg of msgs) {
const operationId =
msg.data && 'id' in msg.data
? msg.data.id // StreamDataForID
: ''; // StreamData
if (!(operationId in queue)) queue[operationId] = [];
switch (msg.event) {
case 'next':
if (operationId)
queue[operationId].push(
(msg as StreamMessage<true, 'next'>).data.payload,
);
else
queue[operationId].push(
(msg as StreamMessage<false, 'next'>).data,
);
break;
case 'complete':
queue[operationId].push('complete');
break;
default:
throw new Error(`Unexpected message event "${msg.event}"`);
}
waiting[operationId]?.proceed();
}
}
} catch (err) {
error = err;
if (waitingForThrow) waitingForThrow(err);
} finally {
Object.values(waiting).forEach(({ proceed }) => proceed());
}
})();
return {
url,
headers,
waitForThrow: () =>
new Promise((_, reject) => {
if (error) return reject(error);
waitingForThrow = reject;
}),
async *getResults(options) {
const { signal, operationId = '' } = options ?? {};
// operationId === '' ? StreamData : StreamDataForID
try {
for (;;) {
while (queue[operationId]?.length) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const result = queue[operationId].shift()!;
if (result === 'complete') return;
yield result;
}
if (error) throw error;
if (signal?.aborted)
throw new Error('Getting results aborted by the client');
await new Promise<void>((resolve) => {
const proceed = () => {
signal?.removeEventListener('abort', proceed);
delete waiting[operationId];
resolve();
};
signal?.addEventListener('abort', proceed);
waiting[operationId] = { proceed };
});
}
} finally {
delete queue[operationId];
}
},
};
}
/** Isomorphic ReadableStream to AsyncIterator converter. */
function toAsyncIterator(
val: ReadableStream | NodeJS.ReadableStream,
): AsyncIterable<string | Buffer | Uint8Array> {
// node stream is already async iterable
if (typeof Object(val)[Symbol.asyncIterator] === 'function') {
val = val as NodeJS.ReadableStream;
return val[Symbol.asyncIterator]();
}
// convert web stream to async iterable
return (async function* () {
val = val as ReadableStream;
const reader = val.getReader();
for (;;) {
const { value, done } = await reader.read();
if (done) return value;
yield value;
}
})();
} | the_stack |
import { EthersContractContextV5 } from 'ethereum-abi-types-generator';
import { BigNumber, BigNumberish, ContractTransaction } from 'ethersv5';
export type ContractContext = EthersContractContextV5<
UniswapExchangeContract,
UniswapExchangeContractMethodNames,
UniswapExchangeContractEventsContext,
UniswapExchangeContractEvents
>;
export declare type EventFilter = {
address?: string;
topics?: Array<string>;
fromBlock?: string | number;
toBlock?: string | number;
};
export interface ContractTransactionOverrides {
/**
* The maximum units of gas for the transaction to use
*/
gasLimit?: number;
/**
* The price (in wei) per unit of gas
*/
gasPrice?: BigNumber | string | number | Promise<any>;
/**
* The nonce to use in the transaction
*/
nonce?: number;
/**
* The amount to send with the transaction (i.e. msg.value)
*/
value?: BigNumber | string | number | Promise<any>;
/**
* The chain ID (or network ID) to use
*/
chainId?: number;
}
export interface ContractCallOverrides {
/**
* The address to execute the call as
*/
from?: string;
/**
* The maximum units of gas for the transaction to use
*/
gasLimit?: number;
}
export type UniswapExchangeContractEvents =
| 'TokenPurchase'
| 'EthPurchase'
| 'AddLiquidity'
| 'RemoveLiquidity'
| 'Transfer'
| 'Approval';
export interface UniswapExchangeContractEventsContext {
TokenPurchase(...parameters: any): EventFilter;
EthPurchase(...parameters: any): EventFilter;
AddLiquidity(...parameters: any): EventFilter;
RemoveLiquidity(...parameters: any): EventFilter;
Transfer(...parameters: any): EventFilter;
Approval(...parameters: any): EventFilter;
}
export type UniswapExchangeContractMethodNames =
| 'setup'
| 'addLiquidity'
| 'removeLiquidity'
| '__default__'
| 'ethToTokenSwapInput'
| 'ethToTokenTransferInput'
| 'ethToTokenSwapOutput'
| 'ethToTokenTransferOutput'
| 'tokenToEthSwapInput'
| 'tokenToEthTransferInput'
| 'tokenToEthSwapOutput'
| 'tokenToEthTransferOutput'
| 'tokenToTokenSwapInput'
| 'tokenToTokenTransferInput'
| 'tokenToTokenSwapOutput'
| 'tokenToTokenTransferOutput'
| 'tokenToExchangeSwapInput'
| 'tokenToExchangeTransferInput'
| 'tokenToExchangeSwapOutput'
| 'tokenToExchangeTransferOutput'
| 'getEthToTokenInputPrice'
| 'getEthToTokenOutputPrice'
| 'getTokenToEthInputPrice'
| 'getTokenToEthOutputPrice'
| 'tokenAddress'
| 'factoryAddress'
| 'balanceOf'
| 'transfer'
| 'transferFrom'
| 'approve'
| 'allowance'
| 'name'
| 'symbol'
| 'decimals'
| 'totalSupply';
export interface UniswapExchangeContract {
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param token_addr Type: address, Indexed: false
*/
setup(
token_addr: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: true
* Constant: false
* StateMutability: undefined
* Type: function
* @param min_liquidity Type: uint256, Indexed: false
* @param max_tokens Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
*/
addLiquidity(
min_liquidity: BigNumberish,
max_tokens: BigNumberish,
deadline: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param amount Type: uint256, Indexed: false
* @param min_eth Type: uint256, Indexed: false
* @param min_tokens Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
*/
removeLiquidity(
amount: BigNumberish,
min_eth: BigNumberish,
min_tokens: BigNumberish,
deadline: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: true
* Constant: false
* StateMutability: undefined
* Type: function
*/
__default__(
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: true
* Constant: false
* StateMutability: undefined
* Type: function
* @param min_tokens Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
*/
ethToTokenSwapInput(
min_tokens: BigNumberish,
deadline: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: true
* Constant: false
* StateMutability: undefined
* Type: function
* @param min_tokens Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param recipient Type: address, Indexed: false
*/
ethToTokenTransferInput(
min_tokens: BigNumberish,
deadline: BigNumberish,
recipient: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: true
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_bought Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
*/
ethToTokenSwapOutput(
tokens_bought: BigNumberish,
deadline: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: true
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_bought Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param recipient Type: address, Indexed: false
*/
ethToTokenTransferOutput(
tokens_bought: BigNumberish,
deadline: BigNumberish,
recipient: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_sold Type: uint256, Indexed: false
* @param min_eth Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
*/
tokenToEthSwapInput(
tokens_sold: BigNumberish,
min_eth: BigNumberish,
deadline: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_sold Type: uint256, Indexed: false
* @param min_eth Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param recipient Type: address, Indexed: false
*/
tokenToEthTransferInput(
tokens_sold: BigNumberish,
min_eth: BigNumberish,
deadline: BigNumberish,
recipient: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param eth_bought Type: uint256, Indexed: false
* @param max_tokens Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
*/
tokenToEthSwapOutput(
eth_bought: BigNumberish,
max_tokens: BigNumberish,
deadline: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param eth_bought Type: uint256, Indexed: false
* @param max_tokens Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param recipient Type: address, Indexed: false
*/
tokenToEthTransferOutput(
eth_bought: BigNumberish,
max_tokens: BigNumberish,
deadline: BigNumberish,
recipient: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_sold Type: uint256, Indexed: false
* @param min_tokens_bought Type: uint256, Indexed: false
* @param min_eth_bought Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param token_addr Type: address, Indexed: false
*/
tokenToTokenSwapInput(
tokens_sold: BigNumberish,
min_tokens_bought: BigNumberish,
min_eth_bought: BigNumberish,
deadline: BigNumberish,
token_addr: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_sold Type: uint256, Indexed: false
* @param min_tokens_bought Type: uint256, Indexed: false
* @param min_eth_bought Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param recipient Type: address, Indexed: false
* @param token_addr Type: address, Indexed: false
*/
tokenToTokenTransferInput(
tokens_sold: BigNumberish,
min_tokens_bought: BigNumberish,
min_eth_bought: BigNumberish,
deadline: BigNumberish,
recipient: string,
token_addr: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_bought Type: uint256, Indexed: false
* @param max_tokens_sold Type: uint256, Indexed: false
* @param max_eth_sold Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param token_addr Type: address, Indexed: false
*/
tokenToTokenSwapOutput(
tokens_bought: BigNumberish,
max_tokens_sold: BigNumberish,
max_eth_sold: BigNumberish,
deadline: BigNumberish,
token_addr: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_bought Type: uint256, Indexed: false
* @param max_tokens_sold Type: uint256, Indexed: false
* @param max_eth_sold Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param recipient Type: address, Indexed: false
* @param token_addr Type: address, Indexed: false
*/
tokenToTokenTransferOutput(
tokens_bought: BigNumberish,
max_tokens_sold: BigNumberish,
max_eth_sold: BigNumberish,
deadline: BigNumberish,
recipient: string,
token_addr: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_sold Type: uint256, Indexed: false
* @param min_tokens_bought Type: uint256, Indexed: false
* @param min_eth_bought Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param exchange_addr Type: address, Indexed: false
*/
tokenToExchangeSwapInput(
tokens_sold: BigNumberish,
min_tokens_bought: BigNumberish,
min_eth_bought: BigNumberish,
deadline: BigNumberish,
exchange_addr: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_sold Type: uint256, Indexed: false
* @param min_tokens_bought Type: uint256, Indexed: false
* @param min_eth_bought Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param recipient Type: address, Indexed: false
* @param exchange_addr Type: address, Indexed: false
*/
tokenToExchangeTransferInput(
tokens_sold: BigNumberish,
min_tokens_bought: BigNumberish,
min_eth_bought: BigNumberish,
deadline: BigNumberish,
recipient: string,
exchange_addr: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_bought Type: uint256, Indexed: false
* @param max_tokens_sold Type: uint256, Indexed: false
* @param max_eth_sold Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param exchange_addr Type: address, Indexed: false
*/
tokenToExchangeSwapOutput(
tokens_bought: BigNumberish,
max_tokens_sold: BigNumberish,
max_eth_sold: BigNumberish,
deadline: BigNumberish,
exchange_addr: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param tokens_bought Type: uint256, Indexed: false
* @param max_tokens_sold Type: uint256, Indexed: false
* @param max_eth_sold Type: uint256, Indexed: false
* @param deadline Type: uint256, Indexed: false
* @param recipient Type: address, Indexed: false
* @param exchange_addr Type: address, Indexed: false
*/
tokenToExchangeTransferOutput(
tokens_bought: BigNumberish,
max_tokens_sold: BigNumberish,
max_eth_sold: BigNumberish,
deadline: BigNumberish,
recipient: string,
exchange_addr: string,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
* @param eth_sold Type: uint256, Indexed: false
*/
getEthToTokenInputPrice(
eth_sold: BigNumberish,
overrides?: ContractCallOverrides
): Promise<BigNumber>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
* @param tokens_bought Type: uint256, Indexed: false
*/
getEthToTokenOutputPrice(
tokens_bought: BigNumberish,
overrides?: ContractCallOverrides
): Promise<BigNumber>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
* @param tokens_sold Type: uint256, Indexed: false
*/
getTokenToEthInputPrice(
tokens_sold: BigNumberish,
overrides?: ContractCallOverrides
): Promise<BigNumber>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
* @param eth_bought Type: uint256, Indexed: false
*/
getTokenToEthOutputPrice(
eth_bought: BigNumberish,
overrides?: ContractCallOverrides
): Promise<BigNumber>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
*/
tokenAddress(overrides?: ContractCallOverrides): Promise<string>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
*/
factoryAddress(overrides?: ContractCallOverrides): Promise<string>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
* @param _owner Type: address, Indexed: false
*/
balanceOf(
_owner: string,
overrides?: ContractCallOverrides
): Promise<BigNumber>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param _to Type: address, Indexed: false
* @param _value Type: uint256, Indexed: false
*/
transfer(
_to: string,
_value: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param _from Type: address, Indexed: false
* @param _to Type: address, Indexed: false
* @param _value Type: uint256, Indexed: false
*/
transferFrom(
_from: string,
_to: string,
_value: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: false
* StateMutability: undefined
* Type: function
* @param _spender Type: address, Indexed: false
* @param _value Type: uint256, Indexed: false
*/
approve(
_spender: string,
_value: BigNumberish,
overrides?: ContractTransactionOverrides
): Promise<ContractTransaction>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
* @param _owner Type: address, Indexed: false
* @param _spender Type: address, Indexed: false
*/
allowance(
_owner: string,
_spender: string,
overrides?: ContractCallOverrides
): Promise<BigNumber>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
*/
name(overrides?: ContractCallOverrides): Promise<string>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
*/
symbol(overrides?: ContractCallOverrides): Promise<string>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
*/
decimals(overrides?: ContractCallOverrides): Promise<BigNumber>;
/**
* Payable: false
* Constant: true
* StateMutability: undefined
* Type: function
*/
totalSupply(overrides?: ContractCallOverrides): Promise<BigNumber>;
} | the_stack |
import {tap} from 'rxjs/operators';
import * as Faker from 'faker';
import {
randomAsyncSystemConfig,
randomBoolean,
randomSelectMultiple,
randomValidValue,
randomValue,
selectRandom,
times,
} from './utils';
import {AsyncSystemConfig, AsyncSystemStreamObservableProducer} from '../models/async-system';
import {isValidId} from '../utils/funcs';
import {UnitConfig} from '../models/units';
import {AsyncSystem} from '../lib/async-system';
import {Configuration} from '../lib/configuration';
import {Base} from '../lib/abstract-base';
import {Stream} from '../lib/stream';
import {BoolUnit} from '../lib/bool-unit';
import {GenericUnit} from '../lib/generic-unit';
import {UnitBase} from '../lib/abstract-unit-base';
import createSpy = jasmine.createSpy;
const unitConfigOptions: Array<keyof UnitConfig<any>> = [
// 'id', // tests with id are done separately to keep other tests simple
// 'immutable', // immutability tests are done separately to keep other tests simple
// 'persistent', // persistence tests are done separately to keep other tests simple
'replay',
'initialValue',
'cacheSize',
'distinctDispatchCheck',
'customDispatchCheck',
'dispatchDebounce',
'dispatchDebounceMode',
];
const asyncSystemConfigOptions: Array<keyof AsyncSystemConfig<any, any, any>> = [
// 'id', // tests with id are done separately to keep other tests simple
'replay',
'autoUpdatePendingValue',
'freezeQueryWhilePending',
'clearDataOnError',
'clearDataOnQuery',
'clearErrorOnData',
'clearErrorOnQuery',
'clearQueryOnData',
'clearQueryOnError',
'initialValue',
'UNITS',
'QUERY_UNIT',
'DATA_UNIT',
'ERROR_UNIT',
'PENDING_UNIT',
];
describe(
'AsyncSystem',
times(30, () => {
beforeAll(() => {
Configuration.reset();
});
describe('configuration', () => {
let asyncSystem: AsyncSystem<any, any, any>;
beforeEach(() => {
Configuration.reset();
});
it('should extend Base', () => {
expect(new AsyncSystem<any, any, any>()).toBeInstanceOf(Base);
});
it('should inherit global configuration', () => {
Configuration.set({
ASYNC_SYSTEM: randomAsyncSystemConfig(asyncSystemConfigOptions, unitConfigOptions),
});
const inlineConfig = randomAsyncSystemConfig(asyncSystemConfigOptions, unitConfigOptions);
asyncSystem = new AsyncSystem(inlineConfig);
const globalConfig = Configuration.ASYNC_SYSTEM;
const {config} = asyncSystem;
Object.keys(config).forEach(key => {
if (inlineConfig.hasOwnProperty(key)) {
expect(config[key]).toEqual(inlineConfig[key]);
} else {
expect(config[key]).toEqual(globalConfig[key]);
}
});
});
it('expect invalid id to throw', () => {
const systemId = randomValue(1);
const systemConfig = {
...randomAsyncSystemConfig(asyncSystemConfigOptions, unitConfigOptions),
id: systemId,
};
if (systemId === undefined || isValidId(systemId)) {
asyncSystem = new AsyncSystem(systemConfig);
expect(asyncSystem.config.id).toBe(systemId);
} else {
expect(() => new AsyncSystem(systemConfig)).toThrow(
new TypeError(
`Invalid id provided, expected a non-empty string, got ${String(systemId)}`
)
);
}
});
it('auto assign derived ids to the units', () => {
const systemId = Faker.random.alphaNumeric();
const systemConfig = {
...randomAsyncSystemConfig(asyncSystemConfigOptions, unitConfigOptions),
id: systemId,
};
asyncSystem = new AsyncSystem(systemConfig);
const {queryUnit, dataUnit, errorUnit, pendingUnit} = asyncSystem;
expect(queryUnit.config.id).toBe(systemId + '_QUERY');
expect(dataUnit.config.id).toBe(systemId + '_DATA');
expect(errorUnit.config.id).toBe(systemId + '_ERROR');
expect(pendingUnit.config.id).toBe(systemId + '_PENDING');
});
it('auto-id should not override inline unit id', () => {
const systemId = randomBoolean() ? Faker.random.alphaNumeric() : undefined;
const systemConfig: any = {
...randomAsyncSystemConfig(asyncSystemConfigOptions, unitConfigOptions),
id: systemId,
};
if (randomBoolean()) {
// tslint:disable:no-unused-expression
systemConfig.queryUnit && (systemConfig.queryUnit.id = Faker.random.alphaNumeric());
systemConfig.dataUnit && (systemConfig.dataUnit.id = Faker.random.alphaNumeric());
systemConfig.errorUnit && (systemConfig.errorUnit.id = Faker.random.alphaNumeric());
systemConfig.pendingUnit && (systemConfig.pendingUnit.id = Faker.random.alphaNumeric());
// tslint:disable:no-unused-expression
}
asyncSystem = new AsyncSystem(systemConfig);
const {queryUnit, dataUnit, errorUnit, pendingUnit} = asyncSystem;
if (isValidId(systemId)) {
expect(queryUnit.config.id).toBe(systemConfig.queryUnit?.id ?? systemId + '_QUERY');
expect(dataUnit.config.id).toBe(systemConfig.dataUnit?.id ?? systemId + '_DATA');
expect(errorUnit.config.id).toBe(systemConfig.errorUnit?.id ?? systemId + '_ERROR');
expect(pendingUnit.config.id).toBe(systemConfig.pendingUnit?.id ?? systemId + '_PENDING');
} else {
expect(queryUnit.config.id).toBe(systemConfig.queryUnit?.id);
expect(dataUnit.config.id).toBe(systemConfig.dataUnit?.id);
expect(errorUnit.config.id).toBe(systemConfig.errorUnit?.id);
expect(pendingUnit.config.id).toBe(systemConfig.pendingUnit?.id);
}
});
});
describe('relationships', () => {
let asyncSystem: AsyncSystem<any, any, any>;
let queryUnit: GenericUnit<any>;
let dataUnit: GenericUnit<any>;
let errorUnit: GenericUnit<any>;
let pendingUnit: BoolUnit;
let systemEmitCount: number;
let queryUnitEmitCount: number;
let dataUnitEmitCount: number;
let errorUnitEmitCount: number;
let pendingUnitEmitCount: number;
const dispatchRandomValues = (): number => {
const someUnits = randomSelectMultiple([queryUnit, dataUnit, errorUnit, pendingUnit]);
return someUnits
.map(unit => {
const shouldDispatchDuplicate = randomBoolean();
return unit.dispatch(shouldDispatchDuplicate ? unit.value() : randomValidValue(unit), {
bypassDebounce: true,
});
})
.filter(didDispatch => didDispatch).length;
};
beforeEach(() => {
Configuration.reset();
asyncSystem = new AsyncSystem<any, any, any>(
randomAsyncSystemConfig(asyncSystemConfigOptions, unitConfigOptions)
);
queryUnit = asyncSystem.queryUnit;
dataUnit = asyncSystem.dataUnit;
errorUnit = asyncSystem.errorUnit;
pendingUnit = asyncSystem.pendingUnit;
if (randomBoolean()) {
dispatchRandomValues();
}
systemEmitCount = asyncSystem.emitCount;
queryUnitEmitCount = queryUnit.emitCount;
dataUnitEmitCount = dataUnit.emitCount;
errorUnitEmitCount = errorUnit.emitCount;
pendingUnitEmitCount = pendingUnit.emitCount;
});
it('should emit when member Units emit', () => {
const successfulUnitDispatchCount = dispatchRandomValues();
expect(asyncSystem.emitCount).toBe(systemEmitCount + successfulUnitDispatchCount);
});
it('should have combined derived value of units', () => {
expect(asyncSystem.value()).toEqual({
query: queryUnit.value(),
data: dataUnit.value(),
error: errorUnit.value(),
pending: pendingUnit.value(),
});
});
it('should auto-toggle pendingUnit', () => {
// choose a random unit
const primaryUnit: GenericUnit<any> = selectRandom([queryUnit, dataUnit, errorUnit]);
// true for query, false for data and error
const nextPendingValue: boolean = primaryUnit === queryUnit;
const isAutoToggleOn = asyncSystem.config.autoUpdatePendingValue !== false;
const wouldPendingUnitDispatch =
isAutoToggleOn && pendingUnit.wouldDispatch(nextPendingValue);
const primaryDispatchWorked = primaryUnit.dispatch(randomValue(), {bypassDebounce: true});
if (primaryDispatchWorked) {
if (wouldPendingUnitDispatch) {
expect(pendingUnit.value()).toBe(nextPendingValue);
expect(pendingUnit.emitCount).toBe(pendingUnitEmitCount + 1);
} else {
expect(pendingUnit.emitCount).toBe(pendingUnitEmitCount);
}
expect(asyncSystem.emitCount).toBe(systemEmitCount + 1);
} else {
expect(pendingUnit.emitCount).toBe(pendingUnitEmitCount);
expect(asyncSystem.emitCount).toBe(systemEmitCount);
}
});
it('should auto-clear error', () => {
const primaryUnit: GenericUnit<any> = randomBoolean() ? queryUnit : dataUnit;
const isAutoClearOn =
primaryUnit === queryUnit
? asyncSystem.config.clearErrorOnQuery === true
: asyncSystem.config.clearErrorOnQuery !== true &&
asyncSystem.config.clearErrorOnData !== false;
const wouldErrorUnitEmit = isAutoClearOn && !errorUnit.isEmpty;
const primaryDispatchWorked = primaryUnit.dispatch(randomValue(), {bypassDebounce: true});
if (primaryDispatchWorked) {
if (isAutoClearOn) {
expect(errorUnit.value()).toBe(undefined);
expect(errorUnit.emitCount).toBe(errorUnitEmitCount + (wouldErrorUnitEmit ? 1 : 0));
} else {
expect(errorUnit.emitCount).toBe(errorUnitEmitCount);
}
expect(asyncSystem.emitCount).toBe(systemEmitCount + 1);
} else {
expect(errorUnit.emitCount).toBe(errorUnitEmitCount);
expect(asyncSystem.emitCount).toBe(systemEmitCount);
}
});
it('should auto-clear data', () => {
const primaryUnit: GenericUnit<any> = randomBoolean() ? queryUnit : errorUnit;
const isAutoClearOn =
primaryUnit === queryUnit
? asyncSystem.config.clearDataOnQuery === true
: asyncSystem.config.clearDataOnQuery !== true &&
asyncSystem.config.clearDataOnError === true;
const wouldDataUnitEmit = isAutoClearOn && !dataUnit.isEmpty;
const primaryDispatchWorked = primaryUnit.dispatch(randomValue(), {bypassDebounce: true});
if (primaryDispatchWorked) {
if (isAutoClearOn) {
expect(dataUnit.value()).toBe(undefined);
expect(dataUnit.emitCount).toBe(dataUnitEmitCount + (wouldDataUnitEmit ? 1 : 0));
} else {
expect(dataUnit.emitCount).toBe(dataUnitEmitCount);
}
expect(asyncSystem.emitCount).toBe(systemEmitCount + 1);
} else {
expect(dataUnit.emitCount).toBe(dataUnitEmitCount);
expect(asyncSystem.emitCount).toBe(systemEmitCount);
}
});
it('should auto-clear query', () => {
const primaryUnit: GenericUnit<any> = randomBoolean() ? dataUnit : errorUnit;
const isAutoClearOn =
(!queryUnit.isFrozen || asyncSystem.config.autoUpdatePendingValue !== false) &&
(primaryUnit === dataUnit
? asyncSystem.config.clearQueryOnData === true
: asyncSystem.config.clearQueryOnError === true);
const wouldQueryUnitEmit = isAutoClearOn && !queryUnit.isEmpty;
const primaryDispatchWorked = primaryUnit.dispatch(randomValue(), {bypassDebounce: true});
if (primaryDispatchWorked) {
if (isAutoClearOn) {
expect(queryUnit.value()).toBe(undefined);
expect(queryUnit.emitCount).toBe(queryUnitEmitCount + (wouldQueryUnitEmit ? 1 : 0));
} else {
expect(queryUnit.emitCount).toBe(queryUnitEmitCount);
}
expect(asyncSystem.emitCount).toBe(systemEmitCount + 1);
} else {
expect(queryUnit.emitCount).toBe(queryUnitEmitCount);
expect(asyncSystem.emitCount).toBe(systemEmitCount);
}
});
it('should toggle-freeze query on pending', () => {
if (randomBoolean()) {
queryUnit.freeze();
}
const originalFrozenState = queryUnit.isFrozen;
const randomUnit: UnitBase<any> = selectRandom([
queryUnit,
dataUnit,
errorUnit,
pendingUnit,
]);
randomUnit.dispatch(randomValidValue(randomUnit), {
bypassDebounce: true,
});
const pendingUnitEmitted = pendingUnit.emitCount > pendingUnitEmitCount;
if (asyncSystem.config.freezeQueryWhilePending === true && pendingUnitEmitted) {
expect(queryUnit.isFrozen).toBe(pendingUnit.value());
} else {
expect(queryUnit.isFrozen).toBe(originalFrozenState);
}
});
it('should createStream', () => {
const operatorSpy = createSpy('operatorSpy');
const observableProducer = createSpy<AsyncSystemStreamObservableProducer<any, any, any>>(
'observableProducer'
).and.callFake((qU, dU, eU, pU) => {
return qU.pipe(tap(v => operatorSpy(v)));
});
const stream = asyncSystem.createStream(observableProducer);
expect(stream).toBeInstanceOf(Stream);
expect(observableProducer).toHaveBeenCalledWith(
queryUnit,
dataUnit,
errorUnit,
pendingUnit
);
if (queryUnit.config.replay === false) {
expect(operatorSpy).not.toHaveBeenCalled();
} else {
expect(operatorSpy).toHaveBeenCalledWith(queryUnit.value());
}
operatorSpy.calls.reset();
if (queryUnit.dispatch(randomValue(1), {bypassDebounce: true})) {
expect(operatorSpy).toHaveBeenCalledWith(queryUnit.value());
} else {
expect(operatorSpy).not.toHaveBeenCalled();
}
});
it('should pause relationships', () => {
if (randomBoolean()) {
queryUnit.freeze();
}
asyncSystem.pauseRelationships();
expect(asyncSystem.relationshipsWorking).toBe(false);
asyncSystem.pauseRelationships(); // this should have no effect
const wasQueryUnitFrozen = queryUnit.isFrozen;
dispatchRandomValues();
expect(queryUnit.isFrozen).toBe(wasQueryUnitFrozen);
expect(asyncSystem.emitCount).toBe(systemEmitCount);
expect(asyncSystem.relationshipsWorking).toBe(false);
});
it('should resume relationships', () => {
asyncSystem.pauseRelationships();
expect(asyncSystem.relationshipsWorking).toBe(false);
const someDidDispatch: boolean = dispatchRandomValues() !== 0;
asyncSystem.resumeRelationships();
expect(asyncSystem.relationshipsWorking).toBe(true);
asyncSystem.resumeRelationships(); // this should have no effect
if (someDidDispatch) {
expect(asyncSystem.emitCount).toBe(systemEmitCount + 1);
} else {
expect(asyncSystem.emitCount).toBe(systemEmitCount);
}
});
});
})
); | the_stack |
import {
MalVal,
isMap,
MalFunc,
keywordFor as K,
MalMap,
MalNode,
isVector,
MalJSFunc,
isSeq,
keywordFor,
getMeta,
MalSeq,
getType,
isSymbol,
MalSymbol,
symbolFor as S,
createList as L,
isNode,
M_OUTER,
isList,
M_OUTER_INDEX,
MalType,
isFunc,
getEvaluated,
isSymbolFor,
cloneExp,
MalNodeMap,
M_DELIMITERS,
getOuter,
} from '@/mal/types'
import ConsoleScope from '@/scopes/console'
import {mat2d} from 'gl-matrix'
import {reconstructTree} from './reader'
export function getStructType(exp: MalVal): StructTypes | undefined {
if (isVector(exp)) {
if (exp[0] === K('path')) {
return 'path'
}
if (exp.length <= 6) {
const isAllNumber =
exp instanceof Float32Array || exp.every(v => typeof v === 'number')
if (isAllNumber) {
switch (exp.length) {
case 2:
return 'vec2'
case 4:
return 'rect2d'
case 6:
return 'mat2d'
}
}
}
}
return undefined
}
type WatchOnReplacedCallback = (newExp: MalVal) => any
const ExpWatcher = new WeakMap<MalNode, Set<WatchOnReplacedCallback>>()
export function watchExpOnReplace(
exp: MalNode,
callback: WatchOnReplacedCallback
) {
const callbacks = ExpWatcher.get(exp) || new Set()
callbacks.add(callback)
ExpWatcher.set(exp, callbacks)
}
export function unwatchExpOnReplace(
exp: MalNode,
callback: WatchOnReplacedCallback
) {
const callbacks = ExpWatcher.get(exp)
if (callbacks) {
callbacks.delete(callback)
if (callbacks.size === 0) {
ExpWatcher.delete(exp)
}
}
}
export function getExpByPath(root: MalNode, path: string): MalVal {
const keys = path
.split('/')
.filter(k => k !== '')
.map(k => parseInt(k))
return find(root, keys)
function find(exp: MalVal, keys: number[]): MalVal {
const [index, ...rest] = keys
const expBody = getUIBodyExp(exp)
if (keys.length === 0) {
return expBody
}
if (isSeq(expBody)) {
return find(expBody[index], rest)
} else if (isMap(expBody)) {
const keys = Object.keys(expBody as MalNodeMap)
return find(expBody[keys[index]], rest)
} else {
return expBody
}
}
}
export function generateExpAbsPath(exp: MalNode) {
return seek(exp, '')
function seek(exp: MalNode, path: string): string {
const outer = getOuter(exp)
if (outer) {
if (isList(outer) && isSymbolFor(outer[0], 'ui-annotate')) {
return seek(outer, path)
} else {
const index = exp[M_OUTER_INDEX]
return seek(outer, index + '/' + path)
}
} else {
return '/' + path
}
}
}
export function getUIOuterInfo(
_exp: MalVal | undefined
): [MalNode | null, number] {
if (!isNode(_exp)) {
return [null, -1]
}
let exp = _exp
let outer = getOuter(exp)
if (isList(outer) && isSymbolFor(outer[0], 'ui-annotate')) {
exp = outer
outer = getOuter(exp)
}
return outer ? [outer, exp[M_OUTER_INDEX]] : [null, -1]
}
/**
* Cached Tree-shaking
*/
export function replaceExp(original: MalNode, replaced: MalVal) {
// Execute a callback if necessary
if (ExpWatcher.has(original)) {
const callbacks = ExpWatcher.get(original) as Set<WatchOnReplacedCallback>
ExpWatcher.delete(original)
for (const cb of callbacks) {
cb(replaced)
}
}
const outer = original[M_OUTER]
const index = original[M_OUTER_INDEX]
if (index === undefined || !isNode(outer)) {
// Is the root exp
return
}
const newOuter = cloneExp(outer)
// Set replaced as new child
if (isSeq(newOuter)) {
// Sequence
newOuter[index] = replaced
for (let i = 0; i < newOuter.length; i++) {
if (isNode(newOuter[i])) {
;(newOuter[i] as MalNode)[M_OUTER] = newOuter
;(newOuter[i] as MalNode)[M_OUTER_INDEX] = i
}
}
} else {
// Hash map
const keys = Object.keys(outer as MalNodeMap)
const key = keys[index]
newOuter[key] = replaced
for (let i = 0; i < keys.length; i++) {
if (isNode(newOuter[i])) {
;(newOuter[i] as MalNode)[M_OUTER] = newOuter
;(newOuter[i] as MalNode)[M_OUTER_INDEX] = i
}
}
}
newOuter[M_DELIMITERS] = outer[M_DELIMITERS]
replaceExp(outer, newOuter)
}
export function getUIAnnotationExp(exp: MalNode) {
const outer = getOuter(exp)
return isList(outer) && isSymbolFor(outer[0], 'ui-annotate') ? outer : exp
}
export function getUIBodyExp(exp: MalVal) {
return isList(exp) && isSymbolFor(exp[0], 'ui-annotate') ? exp[2] : exp
}
export function deleteExp(exp: MalNode) {
const outer = exp[M_OUTER]
const index = exp[M_OUTER_INDEX]
if (!outer) {
return false
}
const newOuter = cloneExp(outer)
if (isSeq(newOuter)) {
newOuter.splice(index, 1)
} else {
const key = Object.keys(newOuter)[index]
delete newOuter[key]
}
copyDelimiters(newOuter, outer)
reconstructTree(newOuter)
replaceExp(outer, newOuter)
return true
}
export function getMapValue(
exp: MalVal | undefined,
path: string,
type?: MalType,
defaultValue?: MalVal
): MalVal {
if (exp === undefined) {
return defaultValue !== undefined ? defaultValue : null
}
const keys = path.split('/').map(k => (/^[0-9]+$/.test(k) ? parseInt(k) : k))
while (keys.length > 0) {
const key = keys[0]
if (typeof key === 'number') {
if (!isSeq(exp) || exp[key] === undefined) {
return defaultValue !== undefined ? defaultValue : null
}
exp = exp[key]
} else {
// map key
const kw = keywordFor(key)
if (!isMap(exp) || !(kw in exp)) {
return defaultValue !== undefined ? defaultValue : null
}
exp = exp[kw]
}
keys.shift()
}
// Type checking
if (type && getType(exp) !== type) {
return defaultValue !== undefined ? defaultValue : null
}
return exp
}
type StructTypes = 'vec2' | 'rect2d' | 'mat2d' | 'path'
export interface FnInfoType {
fn: MalFunc | MalJSFunc
meta?: MalVal
aliasFor?: string
structType?: StructTypes
}
export function getFnInfo(exp: MalVal): FnInfoType | undefined {
let fn = isFunc(exp) ? exp : getFn(exp)
let meta = undefined
let aliasFor = undefined
let structType: StructTypes | undefined = undefined
// Check if the exp is struct
if (!fn) {
structType = getStructType(getEvaluated(exp))
if (structType) {
fn = ConsoleScope.var(structType) as MalFunc
}
}
if (!fn) {
return undefined
}
meta = getMeta(fn)
if (isMap(meta)) {
aliasFor = getMapValue(meta, 'alias-for', MalType.String) as string
}
return {fn, meta, aliasFor, structType}
}
export function reverseEval(
exp: MalVal,
original: MalVal,
forceOverwrite = false
) {
// const meta = getMeta(original)
switch (getType(original)) {
case MalType.List: {
// Check if the list is wrapped within const
if (isSymbolFor((original as MalSeq)[0], 'const')) {
return original
} else {
// find Inverse function
const info = getFnInfo(original as MalSeq)
if (!info) break
const inverseFn = getMapValue(info.meta, 'inverse')
if (!isFunc(inverseFn)) break
const fnName = (original as MalSeq)[0]
const originalParams = (original as MalSeq).slice(1)
const evaluatedParams = originalParams.map(e => getEvaluated(e))
// Compute the original parameter
const result = inverseFn({
[K('return')]: exp,
[K('params')]: evaluatedParams,
})
if (!isVector(result) && !isMap(result)) {
return null
}
// Parse the result
let newParams: MalVal[]
let updatedIndices: number[] | undefined = undefined
if (isMap(result)) {
const params = result[K('params')]
const replace = result[K('replace')]
if (isVector(params)) {
newParams = params
} else if (isVector(replace)) {
newParams = [...originalParams]
const pairs = (typeof replace[0] === 'number'
? [(replace as any) as [number, MalVal]]
: ((replace as any) as [number, MalVal][])
).map(
([si, e]) =>
[si < 0 ? newParams.length + si : si, e] as [number, MalVal]
)
for (const [i, value] of pairs) {
newParams[i] = value
}
updatedIndices = pairs.map(([i]) => i)
} else {
return null
}
} else {
newParams = result
}
if (!updatedIndices) {
updatedIndices = Array(newParams.length)
.fill(0)
.map((_, i) => i)
}
for (const i of updatedIndices) {
newParams[i] = reverseEval(
newParams[i],
originalParams[i],
forceOverwrite
)
}
const newExp = L(fnName, ...newParams)
return newExp
}
break
}
case MalType.Vector: {
if (isVector(exp) && exp.length === (original as MalSeq).length) {
const newExp = exp.map((e, i) =>
reverseEval(e, (original as MalSeq)[i], forceOverwrite)
) as MalVal[]
return newExp
}
break
}
case MalType.Map: {
if (isMap(exp)) {
const newExp = {...exp} as MalMap
Object.entries(original as MalMap).forEach(([key, value]) => {
if (key in exp) {
newExp[key] = reverseEval(exp[key], value, forceOverwrite)
} else {
newExp[key] = value
}
})
return newExp
}
break
}
case MalType.Symbol: {
const def = (original as MalSymbol).def
if (def && !isSymbol(exp)) {
// NOTE: Making side-effects on the below line
const newDefBody = reverseEval(exp, def[2], forceOverwrite)
replaceExp(def, L(S('defvar'), original, newDefBody))
return cloneExp(original)
}
break
}
case MalType.Number:
case MalType.String:
case MalType.Keyword:
case MalType.Boolean:
return exp
}
return forceOverwrite ? exp : original
}
export function computeExpTransform(exp: MalVal): mat2d {
if (!isNode(exp)) {
return mat2d.create()
}
// Collect ancestors with index
const ancestors: [MalNode, number][] = []
for (let _exp: MalNode = exp; _exp[M_OUTER]; _exp = _exp[M_OUTER]) {
ancestors.unshift([_exp[M_OUTER], _exp[M_OUTER_INDEX]])
}
const xform = mat2d.create()
for (const [node, index] of ancestors) {
if (!isList(node)) {
continue
}
const meta = getMeta(getEvaluated(node[0]))
const viewportFn = getMapValue(meta, 'viewport-transform')
if (!isFunc(viewportFn)) {
continue
}
// Execute the viewport transform function
const evaluatedParams = node.slice(1).map(x => getEvaluated(x))
const paramXforms = viewportFn(...evaluatedParams) as MalVal
if (!isVector(paramXforms) || !paramXforms[index - 1]) {
continue
}
mat2d.mul(xform, xform, paramXforms[index - 1] as mat2d)
}
return xform
}
const K_PARAMS = K('params')
const K_REPLACE = K('replace')
export function applyParamModifier(modifier: MalVal, originalParams: MalVal[]) {
if (!isVector(modifier) && !isMap(modifier)) {
return null
}
// Parse the modifier
let newParams: MalVal[]
let updatedIndices: number[] | undefined = undefined
if (isMap(modifier)) {
const params = modifier[K_PARAMS]
const replace = modifier[K_REPLACE]
if (isVector(params)) {
newParams = [...params]
} else if (isVector(replace)) {
newParams = [...originalParams]
const pairs = (typeof replace[0] === 'number'
? [(replace as any) as [number, MalVal]]
: ((replace as any) as [number, MalVal][])
).map(
([si, e]) =>
[si < 0 ? newParams.length + si : si, e] as [number, MalVal]
)
for (const [i, value] of pairs) {
newParams[i] = value
}
updatedIndices = pairs.map(([i]) => i)
} else {
return null
}
// if (isVector(changeId)) {
// const newId = newParams[1]
// data.draggingIndex = data.handles.findIndex(h => h.id === newId)
// }
} else {
newParams = modifier
}
if (!updatedIndices) {
updatedIndices = Array(newParams.length)
.fill(0)
.map((_, i) => i)
}
// Execute the backward evaluation
for (const i of updatedIndices) {
let newValue = newParams[i]
const unevaluated = originalParams[i]
// if (malEquals(newValue, this.params[i])) {
// newValue = unevaluated
// }
newValue = reverseEval(newValue, unevaluated)
newParams[i] = newValue
}
return newParams
}
export function getFn(exp: MalVal) {
if (!isList(exp)) {
//throw new MalError(`${printExp(exp)} is not a function application`)
return undefined
}
const first = getEvaluated(exp[0])
if (!isFunc(first)) {
// throw new Error(`${printExp(exp[0])} is not a function`)
return undefined
}
return first
}
export function copyDelimiters(target: MalVal, original: MalVal) {
if (isSeq(target) && isSeq(original) && M_DELIMITERS in original) {
const delimiters = [...original[M_DELIMITERS]]
const lengthDiff = target.length - original.length
if (lengthDiff < 0) {
if (original.length === 1) {
delimiters.pop()
} else {
delimiters.splice(delimiters.length - 1 + lengthDiff, -lengthDiff)
}
} else if (lengthDiff > 0) {
if (original.length === 0) {
delimiters.push('')
} else {
const filler = delimiters[delimiters.length - 2] || ' '
const newDelimiters = Array(lengthDiff).fill(filler)
delimiters.splice(delimiters.length - 1, 0, ...newDelimiters)
}
}
target[M_DELIMITERS] = delimiters
}
} | the_stack |
import React from 'react';
import Button from '@material-ui/core/Button';
import InputLabel from '@material-ui/core/InputLabel';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Pagination from '@material-ui/lab/Pagination';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import ButtonGroup from '@material-ui/core/ButtonGroup';
import EditIcon from '@material-ui/icons/Edit';
import PlayArrowIcon from '@material-ui/icons/PlayArrow';
import PauseIcon from '@material-ui/icons/Pause';
import DeleteForeverIcon from '@material-ui/icons/DeleteForever';
import FormControl from '@material-ui/core/FormControl';
import TextField from '@material-ui/core/TextField';
import Snackbar from '@material-ui/core/Snackbar';
import './index.less';
import { get, post } from '../../service/Request';
import Utils from '../../service/Utils';
import { TagError, TagSuccess, TagInfo, TagRem, TagBlu } from '../../plugin/Tag';
interface IState {
[key: string]: any;
channel_list: any[];
list: any[];
count: number;
channel: string;
key: string;
state: number | string;
status: number | string;
open: boolean;
message: string;
}
export default class App extends React.Component<any, IState> {
constructor(props: any) {
super(props);
this.state = {
channel_list: [],
list: [],
count: 0,
channel: '',
key: '',
state: '',
status: '',
open: false,
message: '',
};
}
render() {
return (
<div id="configs">
<div className="top-box">
<FormControl className="item">
<InputLabel id="label-channel">频道</InputLabel>
<Select labelId="label-channel" value={this.state.channel} onChange={(e) => this.onSearchChange(e, 'channel')} className="channel">
<MenuItem value={''}>
<span className="project-item">所有</span>
</MenuItem>
{this.state.channel_list.map((item, index) => (
<MenuItem value={item.key} key={index}>
<span className="project-item">
{item.title} {item.key}
</span>
</MenuItem>
))}
</Select>
</FormControl>
<TextField className="item" label="字段名" value={this.state.key} onChange={(e) => this.onSearchChange(e, 'key')} />
<FormControl className="item">
<InputLabel id="label-type">类型</InputLabel>
<Select labelId="label-type" value={this.state.state} onChange={(e) => this.onSearchChange(e, 'state')} className="channel">
<MenuItem value={''}>
<span className="project-item">所有</span>
</MenuItem>
<MenuItem value={0}>
<span className="project-item">普通</span>
</MenuItem>
<MenuItem value={1}>
<span className="project-item">定时</span>
</MenuItem>
</Select>
</FormControl>
<FormControl className="item">
<InputLabel id="label-status">状态</InputLabel>
<Select labelId="label-status" value={this.state.status} onChange={(e) => this.onSearchChange(e, 'status')} className="channel">
<MenuItem value={''}>
<span className="project-item">所有</span>
</MenuItem>
<MenuItem value={0}>
<span className="project-item">暂停</span>
</MenuItem>
<MenuItem value={1}>
<span className="project-item">启用</span>
</MenuItem>
</Select>
</FormControl>
<FormControl className="item">
<Button className="btn-search" variant="contained" color="primary" onClick={() => this.getList(1)}>
查询
</Button>
</FormControl>
</div>
<TableContainer>
<Table stickyHeader className="table-list">
<TableHead>
<TableRow>
<TableCell align="center">频道</TableCell>
<TableCell>标题和key</TableCell>
<TableCell align="center">内容</TableCell>
<TableCell>类型</TableCell>
<TableCell>状态</TableCell>
<TableCell align="center">操作人</TableCell>
<TableCell align="center">操作</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.list.map((item, index) => (
<TableRow key={index}>
<TableCell>{item.channel_title}</TableCell>
<TableCell>
<p>{item.title}</p>
<small>{item.key}</small>
</TableCell>
<TableCell>
<div className="item-val">
{item.key_type === 'image' && <img className="img" src={item.val} alt="" />}
{item.key_type !== 'image' && <span className="txts">{item.val}</span>}
</div>
</TableCell>
<TableCell>
{item.state === 0 && <TagInfo val="普通任务" />}
{item.state === 1 && <TagRem val={'定时任务'} />}
{item.state === 2 && <TagBlu val={'灰度' + item.proption + '%'} />}
</TableCell>
<TableCell>
{item.status === 1 ? <TagSuccess val="生效" /> : <TagError val="暂停" />}
<a className="linkto" href={'/api_config/configs/preview/' + item.id} target="_blank" rel="noopener noreferrer">
预览
</a>
</TableCell>
<TableCell>
<p>{item.nickname}</p>
<small>{Utils.DateFormartString(item.updatedAt, 'yyyy.MM.dd hh:mm')}</small>
</TableCell>
<TableCell>
<ButtonGroup size="small" aria-label="">
<Button color="primary" onClick={() => this.goEdit(item.id)}>
<EditIcon />
</Button>
{item.status === 0 && (
<Button color="primary" onClick={() => this.goPublish(item.id)}>
<PlayArrowIcon />
</Button>
)}
{item.status === 1 && (
<Button color="primary" onClick={() => this.goPause(item.id)}>
<PauseIcon />
</Button>
)}
<Button color="secondary" disabled={item.status !== 0} onClick={() => this.goDelete(item.id)}>
<DeleteForeverIcon />
</Button>
</ButtonGroup>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<div className="table-footer">
<Pagination className="pagination" count={this.state.count} shape="rounded" />
</div>
<Snackbar open={this.state.open} anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} message={this.state.message} onClose={this.onMessageClose} />
</div>
);
}
componentDidMount() {
this.getAllChannel();
this.getList();
}
/**
* 获取所有的频道列表
*/
async getAllChannel() {
try {
const channel_list = await get('/channel/all');
this.setState({ channel_list });
} catch (error) {
console.log(error);
}
}
limit = 1;
/**
* 获取页面列表
* @param pageIndex 页码
*/
async getList(pageIndex?: number) {
if (pageIndex) {
this.limit = pageIndex;
}
let opts: any = {
limit: this.limit,
};
if (this.state.channel) {
opts.channel = this.state.channel;
}
if (this.state.key) {
opts.key = this.state.key;
}
if (this.state.state !== '') {
opts.state = this.state.state;
}
if (this.state.status !== '') {
opts.status = this.state.status;
}
try {
const data = await get('/configs', opts);
this.setState({
list: data.rows,
count: Math.ceil(data.count / 20),
});
} catch (error) {
console.log(error);
}
}
/**
* 通用更新键值
* @param elem 来源
* @param keyName 键名
*/
onSearchChange = (elem: React.ChangeEvent<{ value: unknown }>, keyName: string) => {
const data = {
[keyName]: elem.target.value,
};
this.setState(data);
};
goEdit(id: number) {
this.props.history.push('/detail?id=' + id);
}
/**
* 发布
* @param id id
*/
async goPublish(id: number) {
try {
const data = await post('/configs/publish/' + id);
console.log(data);
this.getList();
this.showMessage('已启动');
} catch (error) {
console.log(error);
this.showMessage(error.message);
}
}
/**
* 暂停
* @param id id
*/
async goPause(id: number) {
try {
const data = await post('/configs/pause/' + id);
console.log(data);
this.getList();
this.showMessage('已暂停');
} catch (error) {
console.log(error);
this.showMessage(error.message);
}
}
async goDelete(id: number) {
try {
const data = await post('/configs/del/' + id);
console.log(data);
this.getList();
this.showMessage('已删除');
} catch (error) {
console.log(error);
this.showMessage(error.message);
}
}
/**
* 展示消息
* @param msg 消息内容
*/
showMessage(msg: string) {
this.setState({
message: msg,
open: true,
});
}
/**
* 关闭消息
*/
onMessageClose = () => {
this.setState({
message: '',
open: false,
});
};
test(id: number) {
console.log(id);
}
} | the_stack |
require('module-alias/register');
import * as _ from 'lodash';
import * as ABIDecoder from 'abi-decoder';
import * as chai from 'chai';
import * as setProtocolUtils from 'set-protocol-utils';
import { Address } from 'set-protocol-utils';
import { BigNumber } from 'bignumber.js';
import ChaiSetup from '@utils/chaiSetup';
import { BigNumberSetup } from '@utils/bigNumberSetup';
import {
UpdatableOracleMockContract
} from 'set-protocol-oracles';
import {
CoreMockContract,
FixedFeeCalculatorContract,
LinearAuctionLiquidatorContract,
OracleWhiteListContract,
SetTokenContract,
RebalanceAuctionModuleContract,
RebalancingSetTokenV2Contract,
RebalancingSetTokenV2FactoryContract,
SetTokenFactoryContract,
StandardTokenMockContract,
TransferProxyContract,
VaultContract,
WhiteListContract,
} from '@utils/contracts';
import { Blockchain } from '@utils/blockchain';
import { ether, gWei } from '@utils/units';
import {
DEFAULT_GAS,
EMPTY_BYTESTRING,
ONE_DAY_IN_SECONDS,
} from '@utils/constants';
import { expectRevertError } from '@utils/tokenAssertions';
import { getWeb3 } from '@utils/web3Helper';
import { CoreHelper } from '@utils/helpers/coreHelper';
import { ERC20Helper } from '@utils/helpers/erc20Helper';
import { FeeCalculatorHelper } from '@utils/helpers/feeCalculatorHelper';
import { LiquidatorHelper } from '@utils/helpers/liquidatorHelper';
import { OracleHelper } from 'set-protocol-oracles';
import { RebalancingSetV2Helper } from '@utils/helpers/rebalancingSetV2Helper';
import { ValuationHelper } from '@utils/helpers/valuationHelper';
BigNumberSetup.configure();
ChaiSetup.configure();
const web3 = getWeb3();
const { SetProtocolUtils: SetUtils } = setProtocolUtils;
const { expect } = chai;
const blockchain = new Blockchain(web3);
contract('RebalancingSetV2 - LinearAuctionLiquidator', accounts => {
const [
deployerAccount,
managerAccount,
otherAccount,
fakeTokenAccount,
feeRecipient,
] = accounts;
let rebalancingSetToken: RebalancingSetTokenV2Contract;
let coreMock: CoreMockContract;
let transferProxy: TransferProxyContract;
let vault: VaultContract;
let setTokenFactory: SetTokenFactoryContract;
let rebalanceAuctionModule: RebalanceAuctionModuleContract;
let rebalancingFactory: RebalancingSetTokenV2FactoryContract;
let rebalancingComponentWhiteList: WhiteListContract;
let liquidatorWhitelist: WhiteListContract;
let liquidator: LinearAuctionLiquidatorContract;
let fixedFeeCalculator: FixedFeeCalculatorContract;
let feeCalculatorWhitelist: WhiteListContract;
let name: string;
let auctionPeriod: BigNumber;
let rangeStart: BigNumber;
let rangeEnd: BigNumber;
let oracleWhiteList: OracleWhiteListContract;
let component1: StandardTokenMockContract;
let component2: StandardTokenMockContract;
let component3: StandardTokenMockContract;
let component1Price: BigNumber;
let component2Price: BigNumber;
let component3Price: BigNumber;
let set1: SetTokenContract;
let set2: SetTokenContract;
let set1Components: Address[];
let set2Components: Address[];
let set1Units: BigNumber[];
let set2Units: BigNumber[];
let set1NaturalUnit: BigNumber;
let set2NaturalUnit: BigNumber;
let customSet1NaturalUnit: BigNumber;
let customSet2NaturalUnit: BigNumber;
let component1Oracle: UpdatableOracleMockContract;
let component2Oracle: UpdatableOracleMockContract;
let component3Oracle: UpdatableOracleMockContract;
const coreHelper = new CoreHelper(deployerAccount, deployerAccount);
const erc20Helper = new ERC20Helper(deployerAccount);
const rebalancingHelper = new RebalancingSetV2Helper(
deployerAccount,
coreHelper,
erc20Helper,
blockchain
);
const oracleHelper = new OracleHelper(deployerAccount);
const valuationHelper = new ValuationHelper(deployerAccount, coreHelper, erc20Helper, oracleHelper);
const liquidatorHelper = new LiquidatorHelper(deployerAccount, erc20Helper, valuationHelper);
const feeCalculatorHelper = new FeeCalculatorHelper(deployerAccount);
before(async () => {
ABIDecoder.addABI(CoreMockContract.getAbi());
});
after(async () => {
ABIDecoder.removeABI(CoreMockContract.getAbi());
});
beforeEach(async () => {
blockchain.saveSnapshotAsync();
transferProxy = await coreHelper.deployTransferProxyAsync();
vault = await coreHelper.deployVaultAsync();
coreMock = await coreHelper.deployCoreMockAsync(transferProxy, vault);
rebalanceAuctionModule = await coreHelper.deployRebalanceAuctionModuleAsync(coreMock, vault);
await coreHelper.addModuleAsync(coreMock, rebalanceAuctionModule.address);
setTokenFactory = await coreHelper.deploySetTokenFactoryAsync(coreMock.address);
rebalancingComponentWhiteList = await coreHelper.deployWhiteListAsync();
liquidatorWhitelist = await coreHelper.deployWhiteListAsync();
feeCalculatorWhitelist = await coreHelper.deployWhiteListAsync();
rebalancingFactory = await coreHelper.deployRebalancingSetTokenV2FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.setDefaultStateAndAuthorizationsAsync(coreMock, vault, transferProxy, setTokenFactory);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactory);
component1 = await erc20Helper.deployTokenAsync(deployerAccount);
component2 = await erc20Helper.deployTokenAsync(deployerAccount);
component3 = await erc20Helper.deployTokenAsync(deployerAccount);
await coreHelper.addTokensToWhiteList(
[component1.address, component2.address, component3.address],
rebalancingComponentWhiteList,
);
await erc20Helper.approveTransfersAsync(
[component1, component2, component3],
transferProxy.address
);
set1Components = [component1.address, component2.address];
set1Units = [gWei(1), gWei(1)];
set1NaturalUnit = customSet1NaturalUnit || gWei(1);
set1 = await coreHelper.createSetTokenAsync(
coreMock,
setTokenFactory.address,
set1Components,
set1Units,
set1NaturalUnit,
);
set2Components = [component1.address, component2.address];
set2Units = [gWei(1), gWei(2)];
set2NaturalUnit = customSet2NaturalUnit || gWei(2);
set2 = await coreHelper.createSetTokenAsync(
coreMock,
setTokenFactory.address,
set2Components,
set2Units,
set2NaturalUnit,
);
component1Price = ether(1);
component2Price = ether(2);
component3Price = ether(1);
component1Oracle = await oracleHelper.deployUpdatableOracleMockAsync(component1Price);
component2Oracle = await oracleHelper.deployUpdatableOracleMockAsync(component2Price);
component3Oracle = await oracleHelper.deployUpdatableOracleMockAsync(component3Price);
oracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[component1.address, component2.address, component3.address],
[component1Oracle.address, component2Oracle.address, component3Oracle.address],
);
auctionPeriod = ONE_DAY_IN_SECONDS;
rangeStart = new BigNumber(10); // 10% above fair value
rangeEnd = new BigNumber(10); // 10% below fair value
name = 'liquidator';
liquidator = await liquidatorHelper.deployLinearAuctionLiquidatorAsync(
coreMock.address,
oracleWhiteList.address,
auctionPeriod,
rangeStart,
rangeEnd,
name,
);
await coreHelper.addAddressToWhiteList(liquidator.address, liquidatorWhitelist);
fixedFeeCalculator = await feeCalculatorHelper.deployFixedFeeCalculatorAsync();
await coreHelper.addAddressToWhiteList(fixedFeeCalculator.address, feeCalculatorWhitelist);
});
afterEach(async () => {
blockchain.revertAsync();
});
describe('#startRebalance', async () => {
let subjectCaller: Address;
let subjectNextSet: Address;
let subjectLiquidatorData: string;
let subjectTimeFastForward: BigNumber;
let failPeriod: BigNumber;
let currentSetToken: SetTokenContract;
let nextSetToken: SetTokenContract;
let rebalancingSetQuantityToIssue: BigNumber;
beforeEach(async () => {
currentSetToken = set1;
nextSetToken = set2;
failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp: lastRebalanceTimestamp } = await web3.eth.getBlock('latest');
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactory.address,
managerAccount,
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
currentSetToken.address,
failPeriod,
lastRebalanceTimestamp,
);
await coreMock.issue.sendTransactionAsync(
currentSetToken.address,
ether(8),
{from: deployerAccount}
);
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetQuantityToIssue);
subjectCaller = managerAccount;
subjectNextSet = nextSetToken.address;
subjectLiquidatorData = EMPTY_BYTESTRING;
subjectTimeFastForward = ONE_DAY_IN_SECONDS.add(1);
});
async function subject(): Promise<string> {
await blockchain.increaseTimeAsync(subjectTimeFastForward);
return rebalancingSetToken.startRebalance.sendTransactionAsync(
subjectNextSet,
subjectLiquidatorData,
{ from: subjectCaller, gas: DEFAULT_GAS}
);
}
describe('when startRebalance is called from Default State', async () => {
it('updates the rebalanceState to Rebalance', async () => {
await subject();
const newRebalanceState = await rebalancingSetToken.rebalanceState.callAsync();
expect(newRebalanceState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.REBALANCE);
});
it('updates the rebalanceStartTime to the latest timestamp', async () => {
await subject();
const { timestamp } = await web3.eth.getBlock('latest');
const rebalanceStartTime = await rebalancingSetToken.rebalanceStartTime.callAsync();
expect(rebalanceStartTime).to.be.bignumber.equal(timestamp);
});
it('redeemsInVault the currentSet', async () => {
const supply = await vault.getOwnerBalance.callAsync(currentSetToken.address, rebalancingSetToken.address);
const currentSetNaturalUnit = await currentSetToken.naturalUnit.callAsync();
const currentSetTokenBalance = await vault.balances.callAsync(
currentSetToken.address,
rebalancingSetToken.address
);
await subject();
const expectedRedeemableCurrentSets = supply.div(currentSetNaturalUnit).round(0, 3).mul(currentSetNaturalUnit);
const expectedCurrentSetTokenBalance = currentSetTokenBalance.sub(expectedRedeemableCurrentSets);
const actualCurrentSetTokenBalance = await vault.balances.callAsync(
currentSetToken.address,
rebalancingSetToken.address
);
expect(actualCurrentSetTokenBalance).to.be.bignumber.equal(expectedCurrentSetTokenBalance);
});
it('increments the balances of the currentSet components back to the rebalancingSetToken', async () => {
const components = await currentSetToken.getComponents.callAsync();
const naturalUnit = await currentSetToken.naturalUnit.callAsync();
const componentUnits = await currentSetToken.getUnits.callAsync();
const existingVaultBalancePromises = _.map(components, component =>
vault.balances.callAsync(component, rebalancingSetToken.address),
);
const existingVaultBalances = await Promise.all(existingVaultBalancePromises);
await subject();
const actualStartingCurrentSetAmount = await liquidator.startingCurrentSets.callAsync(
rebalancingSetToken.address
);
const expectedVaultBalances = _.map(components, (component, idx) => {
const requiredQuantityToRedeem = actualStartingCurrentSetAmount.div(naturalUnit).mul(componentUnits[idx]);
return existingVaultBalances[idx].add(requiredQuantityToRedeem);
});
const newVaultBalancesPromises = _.map(components, component =>
vault.balances.callAsync(component, rebalancingSetToken.address),
);
const newVaultBalances = await Promise.all(newVaultBalancesPromises);
_.map(components, (component, idx) =>
expect(newVaultBalances[idx]).to.be.bignumber.equal(expectedVaultBalances[idx]),
);
});
describe('when one of the components in the next set is not on the whitelist', async () => {
beforeEach(async () => {
const nextSetComponents = await nextSetToken.getComponents.callAsync();
await rebalancingComponentWhiteList.removeAddress.sendTransactionAsync(
nextSetComponents[0],
{ from: deployerAccount }
);
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
describe('when the union of currentSet and nextSet is not 2 components', async () => {
beforeEach(async () => {
const set3Components = [component1.address, component3.address];
const set3Units = [gWei(1), gWei(1)];
const set3NaturalUnit = customSet1NaturalUnit || gWei(1);
const set3 = await coreHelper.createSetTokenAsync(
coreMock,
setTokenFactory.address,
set3Components,
set3Units,
set3NaturalUnit,
);
subjectNextSet = set3.address;
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
describe('when the rebalance interval has not elapsed', async () => {
beforeEach(async () => {
subjectTimeFastForward = ONE_DAY_IN_SECONDS.sub(10);
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
describe('when not by the token manager', async () => {
beforeEach(async () => {
subjectCaller = otherAccount;
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
describe('when the nextSet is not approved by Core', async () => {
beforeEach(async () => {
subjectNextSet = fakeTokenAccount;
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
describe("when the new set's natural unit is not a multiple of the current set", async () => {
before(async () => {
// a setToken with natural unit ether(.003) and setToken with natural unit ether(.002) are being used
customSet1NaturalUnit = ether(.002);
customSet2NaturalUnit = ether(.003);
});
after(async () => {
customSet1NaturalUnit = undefined;
customSet2NaturalUnit = undefined;
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
});
describe('when startRebalance is called from Rebalance state', async () => {
beforeEach(async () => {
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(8), {from: deployerAccount});
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetQuantityToIssue);
await rebalancingHelper.transitionToRebalanceV2Async(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
set2,
managerAccount
);
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
});
describe('#settleRebalance', async () => {
let subjectCaller: Address;
let nextSetToken: SetTokenContract;
let currentSetToken: SetTokenContract;
let rebalancingSetQuantityToIssue: BigNumber;
let currentSetIssueQuantity: BigNumber;
beforeEach(async () => {
currentSetToken = set1;
nextSetToken = set2;
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp: lastRebalanceTimestamp } = await web3.eth.getBlock('latest');
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactory.address,
managerAccount,
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
currentSetToken.address,
failPeriod,
lastRebalanceTimestamp,
);
// Issue currentSetToken
currentSetIssueQuantity = ether(8);
await coreMock.issue.sendTransactionAsync(
currentSetToken.address,
currentSetIssueQuantity,
{from: deployerAccount}
);
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetQuantityToIssue);
subjectCaller = managerAccount;
});
async function subject(): Promise<string> {
return rebalancingSetToken.settleRebalance.sendTransactionAsync(
{ from: subjectCaller, gas: DEFAULT_GAS}
);
}
describe('when settleRebalance is called from Rebalance State and all currentSets are rebalanced', async () => {
beforeEach(async () => {
await rebalancingHelper.transitionToRebalanceV2Async(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
nextSetToken,
managerAccount
);
const bidQuantity = rebalancingSetQuantityToIssue;
await rebalancingHelper.placeBidAsync(
rebalanceAuctionModule,
rebalancingSetToken.address,
bidQuantity,
);
});
it('updates the rebalanceState to Default', async () => {
await subject();
const newRebalanceState = await rebalancingSetToken.rebalanceState.callAsync();
expect(newRebalanceState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.DEFAULT);
});
it('updates the lastRebalanceTimestamp to the latest blocktimestamp', async () => {
await subject();
const { timestamp } = await web3.eth.getBlock('latest');
const lastRebalanceTimestamp = await rebalancingSetToken.lastRebalanceTimestamp.callAsync();
expect(lastRebalanceTimestamp).to.be.bignumber.equal(timestamp);
});
it('updates the hasBidded state to false', async () => {
await subject();
const hasBidded = await rebalancingSetToken.hasBidded.callAsync();
expect(hasBidded).to.equal(false);
});
it('increments the rebalanceIndex', async () => {
const previousRebalanceIndex = await rebalancingSetToken.rebalanceIndex.callAsync();
await subject();
const newRebalanceIndex = previousRebalanceIndex.plus(1);
const rebalanceIndex = await rebalancingSetToken.rebalanceIndex.callAsync();
expect(rebalanceIndex).to.bignumber.equal(newRebalanceIndex);
});
it('updates the currentSet to rebalancing set', async () => {
await subject();
const newCurrentSet = await rebalancingSetToken.currentSet.callAsync();
expect(newCurrentSet).to.equal(nextSetToken.address);
});
it('issues the nextSet to the rebalancingSetToken', async () => {
const existingBalance = await vault.balances.callAsync(
nextSetToken.address,
rebalancingSetToken.address
);
const settlementAmounts = await rebalancingHelper.getExpectedUnitSharesAndIssueAmount(
coreMock,
rebalancingSetToken,
nextSetToken,
vault
);
await subject();
const expectedBalance = existingBalance.add(settlementAmounts['issueAmount']);
const newBalance = await vault.balances.callAsync(nextSetToken.address, rebalancingSetToken.address);
expect(newBalance).to.be.bignumber.equal(expectedBalance);
});
it('decrements component balance for the rebalancingSetToken by the correct amount', async () => {
const componentAddresses = await nextSetToken.getComponents.callAsync();
const setNaturalUnit = await nextSetToken.naturalUnit.callAsync();
const setComponentUnits = await nextSetToken.getUnits.callAsync();
const existingVaultBalances = await coreHelper.getVaultBalancesForTokensForOwner(
componentAddresses,
vault,
rebalancingSetToken.address
);
const settlementAmounts = await rebalancingHelper.getExpectedUnitSharesAndIssueAmount(
coreMock,
rebalancingSetToken,
nextSetToken,
vault
);
await subject();
const quantityToIssue = settlementAmounts['issueAmount'];
const expectedVaultBalances: BigNumber[] = [];
setComponentUnits.forEach((component, idx) => {
const requiredQuantityToIssue = quantityToIssue.div(setNaturalUnit).mul(component);
expectedVaultBalances.push(existingVaultBalances[idx].sub(requiredQuantityToIssue));
});
const newVaultBalances = await coreHelper.getVaultBalancesForTokensForOwner(
componentAddresses,
vault,
rebalancingSetToken.address
);
expect(JSON.stringify(newVaultBalances)).to.equal(JSON.stringify(expectedVaultBalances));
});
it('updates the unitShares amount correctly', async () => {
const settlementAmounts = await rebalancingHelper.getExpectedUnitSharesAndIssueAmount(
coreMock,
rebalancingSetToken,
nextSetToken,
vault
);
await subject();
const newUnitShares = await rebalancingSetToken.unitShares.callAsync();
expect(newUnitShares).to.be.bignumber.equal(settlementAmounts['unitShares']);
});
it('clears the nextSet variable', async () => {
await subject();
const nextSet = await rebalancingSetToken.nextSet.callAsync();
const expectedNextSet = 0;
expect(nextSet).to.be.bignumber.equal(expectedNextSet);
});
});
describe('when settleRebalance is called but no bids are made', async () => {
beforeEach(async () => {
await rebalancingHelper.transitionToRebalanceV2Async(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
nextSetToken,
managerAccount
);
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
});
describe('#failRebalance', async () => {
let subjectCaller: Address;
let nextSetToken: SetTokenContract;
let currentSetToken: SetTokenContract;
let rebalancingSetQuantityToIssue: BigNumber = ether(7);
let currentSetIssueQuantity: BigNumber;
let failPeriod: BigNumber;
beforeEach(async () => {
currentSetToken = set1;
nextSetToken = set2;
failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp: lastRebalanceTimestamp } = await web3.eth.getBlock('latest');
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactory.address,
managerAccount,
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
currentSetToken.address,
failPeriod,
lastRebalanceTimestamp,
);
// Issue currentSetToken
currentSetIssueQuantity = ether(8);
await coreMock.issue.sendTransactionAsync(
currentSetToken.address,
currentSetIssueQuantity,
{from: deployerAccount}
);
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetQuantityToIssue);
subjectCaller = managerAccount;
});
async function subject(): Promise<string> {
return rebalancingSetToken.endFailedRebalance.sendTransactionAsync(
{ from: subjectCaller, gas: DEFAULT_GAS}
);
}
describe('when endFailedAuction is called from Rebalance State', async () => {
beforeEach(async () => {
await rebalancingHelper.transitionToRebalanceV2Async(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
nextSetToken,
managerAccount
);
});
describe('when the failAuctionTime has been breached', async () => {
describe('and no bids have been placed', async () => {
beforeEach(async () => {
const failRebalancePeriod = new BigNumber(100000);
await blockchain.increaseTimeAsync(failRebalancePeriod.add(1));
});
it('updates the rebalanceState to Default', async () => {
await subject();
const newRebalanceState = await rebalancingSetToken.rebalanceState.callAsync();
expect(newRebalanceState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.DEFAULT);
});
it('reissues the currentSet to the rebalancingSetToken', async () => {
const existingBalance = await vault.balances.callAsync(
currentSetToken.address,
rebalancingSetToken.address
);
const nextSetIssueQuantity = await rebalancingHelper.getSetIssueQuantity(
currentSetToken,
rebalancingSetToken,
vault,
);
await subject();
const expectedBalance = existingBalance.add(nextSetIssueQuantity);
const newBalance = await vault.balances.callAsync(currentSetToken.address, rebalancingSetToken.address);
expect(newBalance).to.be.bignumber.equal(expectedBalance);
});
it('sets lastRebalanceTimestamp to block timestamp', async () => {
const txHash = await subject();
const txReceipt = await web3.eth.getTransactionReceipt(txHash);
const blockData = await web3.eth.getBlock(txReceipt.blockHash);
const newLastRebalanceTimestamp = await rebalancingSetToken.lastRebalanceTimestamp.callAsync();
expect(newLastRebalanceTimestamp).to.be.bignumber.equal(blockData.timestamp);
});
it('clears the nextSet variable', async () => {
await subject();
const nextSet = await rebalancingSetToken.nextSet.callAsync();
const expectedNextSet = 0;
expect(nextSet).to.be.bignumber.equal(expectedNextSet);
});
it('clears the hasBidded variable', async () => {
await subject();
const hasBidded = await rebalancingSetToken.hasBidded.callAsync();
expect(hasBidded).to.equal(false);
});
it('increments the rebalanceIndex variable', async () => {
const previousRebalanceIndex = await rebalancingSetToken.rebalanceIndex.callAsync();
await subject();
const expectedRebalanceIndex = previousRebalanceIndex.plus(1);
const rebalanceIndex = await rebalancingSetToken.rebalanceIndex.callAsync();
expect(rebalanceIndex).to.bignumber.equal(expectedRebalanceIndex);
});
});
describe('and bids have been placed', async () => {
beforeEach(async () => {
const failPeriod = new BigNumber(100000);
await blockchain.increaseTimeAsync(failPeriod.add(1));
const minimumBid = await liquidator.minimumBid.callAsync(rebalancingSetToken.address);
await rebalancingHelper.placeBidAsync(
rebalanceAuctionModule,
rebalancingSetToken.address,
minimumBid,
);
});
it('updates the rebalanceState to Drawdown', async () => {
await subject();
const newRebalanceState = await rebalancingSetToken.rebalanceState.callAsync();
expect(newRebalanceState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.DRAWDOWN);
});
it('clears the nextSet variable', async () => {
await subject();
const nextSet = await rebalancingSetToken.nextSet.callAsync();
const expectedNextSet = 0;
expect(nextSet).to.be.bignumber.equal(expectedNextSet);
});
it('updates the failedRebalanceComponents property', async () => {
const currentSetComponents = await currentSetToken.getComponents.callAsync();
const nextSetComponents = await nextSetToken.getComponents.callAsync();
const expectedWithdrawComponents = _.union(currentSetComponents, nextSetComponents);
await subject();
const withdrawComponents = await rebalancingSetToken.getFailedAuctionWithdrawComponents.callAsync();
expect(withdrawComponents).to.deep.equal(expectedWithdrawComponents);
});
});
});
describe('when auctionFailPoint has not been reached and auction has not failed', async () => {
it('should revert', async () => {
await expectRevertError(subject());
});
});
});
});
}); | the_stack |
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { UsersService } from '../accounts/services/users.service'
import { AccountsService } from '../accounts/services/accounts.service'
import { RequestUser, ValidUser } from './interfaces/user.interface'
import { JwtService } from '@nestjs/jwt'
import { parseDomain, ParseResultType } from 'parse-domain'
import { UserCredentialsService } from '../accounts/services/userCredentials.service'
import { UserEntity } from '../accounts/entities/user.entity'
import { AccountEntity } from '../accounts/entities/account.entity'
import { SettingsService } from '../settings/settings.service'
import { PaymentsService } from '../payments/services/payments.service'
import { PlansService } from '../payments/services/plans.service'
import { UserError } from '../utilities/common.model'
import { UserCredentialsEntity } from 'src/accounts/entities/userCredentials.entity'
export class UnauthorizedWithRedirectException extends UnauthorizedException {
public redirect: string
constructor (url: string) {
super()
this.redirect = url
}
}
@Injectable()
export class AuthService {
constructor (
private readonly usersService: UsersService,
private readonly jwtService: JwtService,
private readonly accountsService: AccountsService,
private readonly userCredentialsService: UserCredentialsService,
private readonly settingsService: SettingsService,
private readonly paymentsService: PaymentsService,
private readonly plansService: PlansService
) {}
async getUserInfo (email): Promise<ValidUser | null> {
if (email == null) {
return null
}
const credential = await this.userCredentialsService.findUserCredentialByEmail(email)
if (credential == null) {
console.error('auth.service - getUserInfo - credentials not valid', email)
return null
}
const user = await this.usersService.findById(credential.userId)
if (user == null) {
console.error('auth.service - getUserInfo - userInfo not found', email)
return null
}
const account = await this.accountsService.findByUserId(user.id)
if (account == null) {
console.error('auth.service - getUserInfo - account not found', user)
return null
}
return { user, credential, account }
}
async getOrgSSORedirectUrl (accountWithOrg: AccountEntity): Promise<string> {
const org = accountWithOrg?.data?.org ?? {}
const { provider, domain } = org
switch (provider) {
case 'google':
return '/auth/google'
case 'azure':
return '/auth/azure'
case 'okta':
return `/auth/okta?iss=https%3A%2F%2F${domain as string}`
}
return '/login'
}
async validateUser (email: string, inputPassword: string): Promise<ValidUser | null> {
if (email == null) {
return null
}
const validUser = await this.getUserInfo(email)
if (validUser == null) {
console.error('auth.service - validateUser - cannon get valid user info', email)
return null
}
// [org] extract account from email domain, if any
const accountWithOrg = await this.getAccountWithOrgByEmail(email)
const forceProvider = accountWithOrg?.data?.org?.provider ?? null
if (accountWithOrg != null && forceProvider != null && forceProvider !== 'password') {
console.error('AuthService - validateUser - org required, invalid provider')
const url = await this.getOrgSSORedirectUrl(accountWithOrg)
throw new UnauthorizedWithRedirectException(url)
}
// [org] validate that org's account and actual account are the same
if (accountWithOrg != null && accountWithOrg.id !== validUser.account.id) {
console.error('AuthService - validateUser - org required, invalid account id')
return null
}
if (inputPassword == null) {
return null
}
const isRegistered = await this.userCredentialsService.isRegistered(validUser.credential, inputPassword)
if (!isRegistered) {
console.error('auth.service - validateUser - credentials not registered', email)
return null
}
if (validUser.account.email_verification_required === true) {
if (validUser.user.emailConfirmed !== true) {
console.error('auth.service - validateUser - email not confirmed, but confirmation is required', email)
return null
}
}
return validUser
}
// TODO: move into AccountEntity
async isPaymentMethodOK (account: AccountEntity): Promise<Boolean> {
// when not set, it's false - e.g. in tests
const paymentsConfig = await this.paymentsService.getPaymentsConfig()
const payment = account.data.payment
const configSignupForcePayment = (paymentsConfig.signup_force_payment === true)
const isExternal = payment?.plan?.provider === 'external'
const hasPaymentMethods = payment?.methods != null && payment.methods.length > 0
const accountIsActive =
// signup requires payment and account has payments
(configSignupForcePayment && hasPaymentMethods) ||
// signup doesn't require payment
!configSignupForcePayment ||
// enterprise are alwasy active
isExternal
// TODO not banned/blocked account
return accountIsActive
}
// TODO: move into SubscriptionEntity
async isSubscriptionPaid (payment): Promise<Boolean> {
// when not set, it's false - e.g. in tests
const paymentsConfig = await this.paymentsService.getPaymentsConfig()
const configPaymentProcessorEnabled = (paymentsConfig.payment_processor_enabled === true)
const subscription = payment?.sub
const plan = payment?.plan
if (subscription == null && plan == null) {
return true
}
const subsIsActive =
// no subs, but payment processor disabled
(subscription?.status == null && !configPaymentProcessorEnabled) ||
// no subs, e.g. enterprise or not yet added
// (subscription?.status === undefined) || // this should never happen unless something was broken in subscription creation
// valid subs in any of these states: disabled, external, active, trialing
['disabled', 'external', 'active', 'trialing'].includes(subscription?.status)
return subsIsActive
}
// TODO: move into UserEntity
async isUserActive (user: UserEntity): Promise<Boolean> {
return user.isActive
}
async getTokenPayloadStatus (validUser: ValidUser): Promise<string> {
const userIsActive = (await this.isUserActive(validUser.user) === true)
const paymentMethodIsOK = (await this.isPaymentMethodOK(validUser.account) === true)
const subsIsPaid = (await this.isSubscriptionPaid(validUser.account.data.payment) === true)
if (userIsActive && paymentMethodIsOK && subsIsPaid) {
return 'active'
} else {
if (!paymentMethodIsOK) {
return 'no_payment_method'
}
if (!subsIsPaid) {
return 'unpaid'
}
if (!userIsActive) {
return 'inactive_user'
}
}
return 'invalid'
}
getTokenPayloadSubscripionData (payment): any {
// const payment = validUser.account.data.payment
const subscriptionData: any = {}
// subs_name
if (payment?.plan?.name != null) {
subscriptionData.subs_name = payment.plan.name
}
// subs_status
if (payment?.sub?.status != null) {
subscriptionData.subs_status = payment.sub.status
}
// subs_exp
if (payment?.sub?.current_period_end != null) {
subscriptionData.subs_exp = payment.sub.current_period_end
}
return subscriptionData
}
async getTokenPayloadFromUserModel (validUser: ValidUser, updateActiveSubscription: boolean = true): Promise<RequestUser | null> {
if (validUser == null) {
return null
}
// TODO cleanup
const { allowedKeys } = await this.settingsService.getUserSettings()
const userData = validUser.user.data.profile != null
? allowedKeys.filter((key) => !(['email', 'username']).includes(key)).reduce((acc, key: string) => {
acc[`user_${key}`] = validUser.user.data.profile[key] ?? '' // using user_${key} to flatten the jwt data
return acc
}, {})
: {}
const subscriptionData = this.getTokenPayloadSubscripionData(validUser.account.data.payment)
const status = await this.getTokenPayloadStatus(validUser)
return {
nonce: '', // TODO
id: validUser.user.id,
account_id: validUser.account?.id,
account_name: validUser.account?.data.name ?? '',
status: status,
email: validUser.user.email,
email_verified: validUser.user?.data.emailConfirmed ?? false,
staff: validUser.user?.isAdmin ?? false,
username: validUser.user.username ?? null,
...userData,
...subscriptionData
}
}
getJwtCookieDomain (requestHostname: string, primaryDomain: string): string {
let cookieDomain
// if the request is from localhost or mysaasform.com, use the request's hostname
if (requestHostname.endsWith('.localhost') || requestHostname.endsWith('.mysaasform.com')) { // TODO: remove hard coded value
cookieDomain = requestHostname
} else {
// else use the primary domain set in admin/developers
// to build the second level domain (e.g., beta.beautifulsaas.com -> beautifulsaas.com)
const parseResult = parseDomain(primaryDomain)
if (parseResult.type === ParseResultType.Listed) {
const { domain, topLevelDomains } = parseResult
cookieDomain = `${domain as string}.${topLevelDomains.join('.')}`
} else {
// if improperly set, fall back to the request's hostname
cookieDomain = requestHostname
}
}
return cookieDomain
}
async getJwtCookieOptions (request): Promise<any> {
const settings = await this.settingsService.getWebsiteSettings()
const cookieDomain = this.getJwtCookieDomain(request.hostname, settings.domain_primary)
let options = { secure: true, httpOnly: true, domain: cookieDomain }
if (process.env.NODE_ENV === 'development') { // TODO: better check for development mode
options = { secure: false, httpOnly: false, domain: cookieDomain }
}
return options
}
async setJwtCookie (request, response, requestUser: RequestUser): Promise<string> {
const jwt = await this.jwtService.sign(requestUser)
const options = await this.getJwtCookieOptions(request)
response.cookie('__session', jwt, options) // TODO: make cookie name parametric
return jwt
}
async getUserIdentity (email: string): Promise<UserEntity | null> {
const user = await this.usersService.findByEmail(email)
return email != null ? user : null
}
async getAccountWithOrgByEmail (email: string): Promise<any> {
const domain = email.split('@')[1]
const account = await this.accountsService.getAccountByDomain(domain)
return account
}
async getOrgByDomain (domain: string): Promise<any> {
const account = await this.accountsService.getAccountByDomain(domain)
const org = account?.data?.org ?? null
return org
}
async createNewUser (newUser: any): Promise<ValidUser | UserError | null> {
const { email } = newUser
if (email == null) {
console.error('auth.service - createNewUser - missing parameters', email)
return null
}
const { password, _csrf, accountEmail, ...data } = newUser
const user = await this.usersService.addUser({ email, password, data })
if (user instanceof UserError || user == null) {
console.error('auth.service - createNewUser - error while creating user', email, accountEmail, user)
return user
}
const credential = await this.userCredentialsService.findUserCredentialByEmail(email)
if (credential == null) {
console.error('auth.service - createNewUser - error while finding user credential', email)
return null
}
return { user, credential, account: null }
}
async registerUser (req: any): Promise<ValidUser | UserError | null> {
const userData = req.body
const chosenPlan = req?.cookies?.plan
const newUser = await this.createNewUser(userData)
if (newUser instanceof UserError || newUser == null) {
console.error('auth.service - registerUser - error while creating user')
return newUser
}
const { user, credential } = newUser
const { email, accountEmail } = userData
// We create a new acount for this user and add this as owner
const account = await this.accountsService.addOrAttach({ data: { name: accountEmail ?? email }, user, chosenPlan })
if (account == null) {
console.error('auth.service - registerUser - error while creating account', email, accountEmail)
return null
}
return { user, credential, account }
}
async userFind (email): Promise<ValidUser | null> {
return await this.getUserInfo(email)
}
async userCreate (req, data): Promise<ValidUser | null> {
const { provider, email } = data
const chosenPlan = req?.cookies?.plan
if (email == null) {
console.error('auth.service - userCreate - missing parameters', email)
return null
}
const userData = {
emailConfirmed: data.email_verified
}
const user = await this.usersService.addUser({ email, password: null, data: userData })
if (user instanceof UserError || user == null) {
console.error('auth.service - userCreate - error while creating user', email, user)
return null
}
const credential = await this.userCredentialsService.findUserCredentialByEmail(email)
if (credential == null) {
console.error('auth.service - userCreate - error while creating user credential', email, user)
return null
}
credential.setProviderData(provider, data.subject, data.extra)
const { id, ...cred } = credential
await this.userCredentialsService.updateOne(id, cred)
// We create a new acount for this user and add this as owner
const accountEmail = email
const account = await this.accountsService.addOrAttach({ data: { name: accountEmail ?? email }, user, chosenPlan })
if (account == null) {
console.error('auth.service - userCreate - error while creating account', email, accountEmail)
return null
}
return { user, credential, account }
}
/*
req - request
data:
- provider: string w/ provider name, stored in the credentials
- subject: the user id within the social, used for validation
- email: to fetch the user
- email_verified: to allow/deny autoconnect
- extra: data from the provider, stored at creation or connect
*/
async userFindOrCreate (req, data): Promise<RequestUser | null> {
const { email, provider } = data
// [org] extract account from email domain, if any
const accountWithOrg = await this.getAccountWithOrgByEmail(email)
const forceProvider = accountWithOrg?.data?.org?.provider ?? null
if (accountWithOrg != null && forceProvider != null && forceProvider !== provider) {
console.error('AuthService - userFindOrCreate - org required, invalid provider')
return null
}
// userFind
let validUser = await this.userFind(email)
// ...orCreate
if (validUser == null) {
const newUser = await this.userCreate(req, data)
if (newUser == null) {
console.error('AuthService - userFindOrCreate - error creating new user')
return null
}
validUser = newUser
}
// add IdP data to user
await this.usersService.updateUserProfile(data.idpData, validUser.user.id)
// [org] validate that org's account and actual account are the same
if (accountWithOrg != null && accountWithOrg.id !== validUser.account.id) {
console.error('AuthService - userFindOrCreate - org required, invalid account id')
return null
}
// prepare to validate credentials
let expectedSubject = validUser.credential.getProviderData(provider).sub
// autoconnect social if it wasn't connected AND email is verified
if (expectedSubject == null && validUser.user?.emailConfirmed === true && data.email_verified === true) {
validUser.credential.setProviderData(provider, data.subject, data.extra)
const { id, ...cred } = validUser.credential
await this.userCredentialsService.updateOne(id, cred)
console.log('AuthService - userFindOrCreate - autoconnect social')
expectedSubject = data.subject
}
// validate credentials
// for social logins we validate that the subject (user id in the social) is the expected one
if (data.subject !== expectedSubject) {
console.error('AuthService - userFindOrCreate - invalid subject')
return null
}
// store/update oauth tokens
(validUser.credential as UserCredentialsEntity).setProviderTokens(data.provider, data.tokens)
const { id, ...cred } = validUser.credential
await this.userCredentialsService.updateOne(id, cred)
// gather additional info: account, subscription, ...
const requestUser = await this.getTokenPayloadFromUserModel(validUser)
if (requestUser == null) {
console.error('AuthService - userFindOrCreate - error while creating token')
}
return requestUser
}
async authGoogle (req, profile, accessToken, refreshToken): Promise<RequestUser | null> {
/*
profile = {
iss: 'accounts.google.com',
azp: '627822000951-53a8ms2qfooaah8gnree5p1a8smsou36.apps.googleusercontent.com',
aud: '627822000951-53a8ms2qfooaah8gnree5p1a8smsou36.apps.googleusercontent.com',
sub: '113712275836931755074',
email: 'emanuele.cesena@gmail.com',
email_verified: true,
at_hash: 'nPTrt2UohVAGAPxzNsIZ-A',
name: 'Emanuele Cesena',
picture: 'https://lh3.googleusercontent.com/a-/AOh14GjUMOcLy8nS3ztxcrB0RfD430Frlgu00QNPbyV8Kw=s96-c',
given_name: 'Emanuele',
family_name: 'Cesena',
locale: 'en',
iat: 1622282004,
exp: 1622285604,
jti: '8fd2715a4320b7f8680c4c1390d905ef5b61a099'
}
*/
const data = profile ?? {}
const idpData = {
email: data.email ?? null,
name: data.name ?? null,
given_name: data.given_name ?? null,
family_name: data.family_mane ?? null,
picture: data.picture ?? null
}
return await this.userFindOrCreate(req, {
provider: 'google',
email: data.email,
email_verified: data.email_verified,
subject: data.sub,
extra: data,
idpData,
tokens: { access_token: accessToken, refresh_token: refreshToken }
})
}
async authAzureAd (req, profile, accessToken, refreshToken): Promise<RequestUser | null> {
/*
profile = {
sub: 'N8_aXBiWPKx74LKf2z28LbG14UEuRyOX1t8IkVMVVKA',
oid: 'bffd1826-68f1-4f5c-9966-8b4283512054',
upn: undefined,
displayName: 'ec@saasform.dev Cesena',
name: {
familyName: undefined,
givenName: undefined,
middleName: undefined
},
emails: undefined,
_raw: '{"aud":"becd9aa0-431b-4140-a0b5-d05952426ebc","iss":"https://login.microsoftonline.com/13f01d05-aaf9-49d8-94ce-32ee372992e7/v2.0","iat":1622108856,"nbf":1622108856,"exp":1622112756,"aio":"AWQAm/8TAAAAFMbu7nMRi5DHdBhMxDsvuyRl0owAsOcTbh8HPEoaRN1SM4F88/qKz1R1/4ZGtot3b5XAEeSUmPY++SGNly1wzO9ubIADJ9frDc2YdX7KQfFAonCMMmqOwIHXksJJ/zNw","email":"ec@saasform.dev","idp":"https://sts.windows.net/9188040d-6c67-4c5b-b112-36a304b66dad/","name":"ec@saasform.dev Cesena","nonce":"_aAugJ0JmMiHMKNN6C3s-SV2E8-wA7mI","oid":"bffd1826-68f1-4f5c-9966-8b4283512054","preferred_username":"ec@saasform.dev","prov_data":[{"at":true,"prov":"github.com","altsecid":"1491992"}],"rh":"0.AXwABR3wE_mq2EmUzjLuNymS56Cazb4bQ0BBoLXQWVJCbrx8AEw.","sub":"N8_aXBiWPKx74LKf2z28LbG14UEuRyOX1t8IkVMVVKA","tid":"13f01d05-aaf9-49d8-94ce-32ee372992e7","uti":"LaEsxTASU0O0Qs40_CBAAw","ver":"2.0"}',
_json: {
aud: 'becd9aa0-431b-4140-a0b5-d05952426ebc',
iss: 'https://login.microsoftonline.com/13f01d05-aaf9-49d8-94ce-32ee372992e7/v2.0',
iat: 1622108856,
nbf: 1622108856,
exp: 1622112756,
aio: 'AWQAm/8TAAAAFMbu7nMRi5DHdBhMxDsvuyRl0owAsOcTbh8HPEoaRN1SM4F88/qKz1R1/4ZGtot3b5XAEeSUmPY++SGNly1wzO9ubIADJ9frDc2YdX7KQfFAonCMMmqOwIHXksJJ/zNw',
email: 'ec@saasform.dev',
idp: 'https://sts.windows.net/9188040d-6c67-4c5b-b112-36a304b66dad/',
name: 'ec@saasform.dev Cesena',
nonce: '_aAugJ0JmMiHMKNN6C3s-SV2E8-wA7mI',
oid: 'bffd1826-68f1-4f5c-9966-8b4283512054',
preferred_username: 'ec@saasform.dev',
prov_data: [ [Object] ],
rh: '0.AXwABR3wE_mq2EmUzjLuNymS56Cazb4bQ0BBoLXQWVJCbrx8AEw.',
sub: 'N8_aXBiWPKx74LKf2z28LbG14UEuRyOX1t8IkVMVVKA',
tid: '13f01d05-aaf9-49d8-94ce-32ee372992e7',
uti: 'LaEsxTASU0O0Qs40_CBAAw',
ver: '2.0'
}
}
*/
const data = profile?._json ?? {}
const idpData = {
email: profile?._json?.email ?? null,
name: profile?._json?.name ?? null,
given_name: profile?.name?.givenName ?? null,
middle_name: profile?.name?.middleName ?? null,
family_name: profile?.name?.undefined ?? null,
picture: '' // todo: find the right value
}
return await this.userFindOrCreate(req, {
provider: 'azure',
email: data.email,
email_verified: true, // Azure AD doesn't return it - TODO: validate that it's always true
subject: data.sub,
extra: data,
idpData,
tokens: { access_token: accessToken, refresh_token: refreshToken }
})
}
async authMiracl (req, profile, accessToken, refreshToken): Promise<RequestUser | null> {
/*
profile = {
id: 'ec@saasform.dev',
displayName: undefined,
name: {
familyName: undefined,
givenName: undefined,
middleName: undefined
},
_raw: '{"sub":"ec@saasform.dev","email":"ec@saasform.dev","email_verified":true}',
_json: {
sub: 'ec@saasform.dev',
email: 'ec@saasform.dev',
email_verified: true
}
}
*/
const data = profile?._json ?? {}
const { _raw, ...extra } = profile
return await this.userFindOrCreate(req, {
provider: 'miracl',
email: data.email,
email_verified: data.email_verified ?? false,
subject: profile.id,
extra,
tokens: { access_token: accessToken, refresh_token: refreshToken }
})
}
async authOkta (req, profile, accessToken, refreshToken): Promise<RequestUser | null> {
/*
profile = {
id: '00uc4l9dEVFyEGY9F695',
displayName: 'Emanuele Due',
name: { familyName: 'Due', givenName: 'Emanuele', middleName: undefined },
_raw: '{"sub":"00uc4l9dEVFyEGY9F695","name":"Emanuele Due","locale":"en-US","email":"ec@saasform.dev","preferred_username":"ec@saasform.dev","given_name":"Emanuele","family_name":"Due","zoneinfo":"America/Los_Angeles","updated_at":1626335424,"email_verified":true}',
_json: {
sub: '00uc4l9dEVFyEGY9F695',
name: 'Emanuele Due',
locale: 'en-US',
email: 'ec@saasform.dev',
preferred_username: 'ec@saasform.dev',
given_name: 'Emanuele',
family_name: 'Due',
zoneinfo: 'America/Los_Angeles',
updated_at: 1626335424,
email_verified: true
}
*/
const data = profile?._json ?? {}
const { _raw, ...extra } = profile
return await this.userFindOrCreate(req, {
provider: 'okta',
email: data.email,
email_verified: data.email_verified ?? false,
subject: profile.id,
extra,
tokens: { access_token: accessToken, refresh_token: refreshToken }
})
}
} | the_stack |
import * as FontMeasure from "./font-measure";
const GRAPHICS_MINIMUM_SIZE = 10;
const MINIMUM_FONT_SIZE_PX = 8.0 * 96.0 / 72.0;
type Style = {
fontSize: number,
fontFamily: string,
fontMetric: { middle: number, baseline: number },
lineHeight: number
};
let boxMutations : (() => any)[] = [];
const clearBoxMutations = () => {
for (const mutation of boxMutations) {
mutation();
}
boxMutations.length = 0;
};
export const handleBoxes = (root: HTMLElement) => {
const baseStyle = {
fontFamily: "'Consolas', 'wlsupplement'",
fontSize: 14.0,
lineHeight: 1.1,
fontMetric: FontMeasure.getFontMetric("Consolas")
};
try {
const element = root.querySelector(".wexpr > :first-child");
if (element) {
handleBox(element as HTMLElement, baseStyle);
clearBoxMutations();
}
} catch (e) {
console.warn(e);
}
};
const handleBox = (elem: HTMLElement, style: Style) => {
const handlerTable:
{ [key: string]: (elem: HTMLElement, style: Style) => number[] } = {
/* eslint-disable */
"W": handleStringBox,
"WROW": handleRowBox,
"WSUP": handleSuperscriptBox,
"WSUB": handleSubscriptBox,
"WSUBSUP": handleSubsuperscriptBox,
"WOVER": handleOverscriptBox,
"WUNDER": handleUnderscriptBox,
"WUNDEROVER": handleUnderoverscriptBox,
"WFRAC": handleFractionBox,
"WSQRT": handleSqrtBox,
"WGRID": handleGridBox,
"WFRAME": handleFrameBox,
"WPANE": handlePaneBox,
"WGRAPH": handleGraphicsBox
/* eslint-enable */
};
if (handlerTable[elem.tagName] === undefined) {
return [0, 0];
} else {
const span = handlerTable[elem.tagName](elem, style);
if (span.length === 2 &&
(-Infinity < span[0] && span[0] < Infinity) &&
(-Infinity < span[1] && span[1] < Infinity)) {
return span;
} else {
return [0, 0];
}
}
};
const elementSpanMerge = (a: number[], b: number[]) => [Math.max(a[0], b[0]), Math.max(a[1], b[1])];
const elementSpanAdd = (span: number[], offset: number) => [span[0] + offset, span[1] - offset];
const elementSpanToString = (span: number[]) => `${span[0].toFixed(2)} ${span[1].toFixed(2)}`;
const parseCssLength = (value: string, reference = NaN) => {
if (value === "") {
return NaN;
} else if (value[value.length - 1] === "%") {
return reference * (0.01 * parseFloat(value.substring(0, value.length - 1)));
} else if (value.substring(value.length - 2) === "pt") {
return parseFloat(value.substring(0, value.length - 2)) * (96.0 / 72.0);
} else {
return parseFloat(value);
}
};
const bracketRenderScheme: { [key: string]: string[][] } = {
"(": [[""], [""], ["", "", ""]],
")": [[""], [""], ["", "", ""]],
"[": [[""], [""], ["", "", ""]],
"]": [[""], [""], ["", "", ""]],
"{": [[""], [""], [""], [""], ["", "", "", ""]],
"}": [[""], [""], [""], [""], ["", "", "", ""]],
"\u2308": [[""], [""], ["", "", ""]], // LeftCeiling
"\u2309": [[""], [""], ["", "", ""]], // RightCeiling
"\u230a": [[""], [""], ["", "", ""]], // LeftFloor
"\u230b": [[""], [""], ["", "", ""]], // RightFloor
"\u301a": [[""], [""], ["", "", ""]], // LeftDoubleBracket
"\u301b": [[""], [""], ["", "", ""]], // RightDoubleBracket
"\u2329": [[""], [""], ["", ""]], // LeftAngleBracket
"\u232a": [[""], [""], ["", ""]], // RightAngleBracket
"\uf113": [[""], [""], ["", ""]], // LeftAssociation
"\uf114": [[""], [""], ["", ""]], // RightAssociation
"\uf603": [[""], [""], [""], [""], ["", "", "", ""]], // LeftBracketingBar
"\uf604": [[""], [""], [""], [""], ["", "", "", ""]], // RightBracketingBar
"\uf605": [[""], [""], [""], [""], ["", "", "", ""]], // LeftDoubleBracketingBar
"\uf606": [[""], [""], [""], [""], ["", "", "", ""]], // RightDoubleBracketingBar
"\uf3d3": [[""], [""], ["", "", ""]], // Conditioned
"\uf432": [[""], [""], ["", "", ""]], // VerticalSeparator
"\uf361": [[""], [""], [""], [""], ["", "", "", ""]], // Piecewise
};
const handleBracket = (elem: HTMLElement, style: Style, span: number[]) => {
let ch = elem.getAttribute("ch");
const em = Math.floor(style.fontSize);
if (ch === null) {
// the bracket has never been rendered
ch = elem.innerHTML;
elem.setAttribute("ch", ch);
elem.style.lineHeight = `${em}px`;
}
const previousHeightCat = parseInt(elem.getAttribute("height") || "-1");
const middle = (style.fontMetric.baseline - 0.5) * style.fontSize;
const spanMax = Math.max(span[0] - middle - 0.05 * em, span[1] + middle - 0.05 * em);
const bracketMaxHeight = "()\u2308\u2309\u230a\u230b\uf603\uf604\uf605\uf606\uf361".includes(ch) ? 100 * em : 2 * em;
const containerApproxHeight = Math.min(2 * Math.max(0.45 * em, spanMax), bracketMaxHeight);
const bracketHeightCat = Math.max(Math.round(((containerApproxHeight / em) + 0.1) * 2) - 2, 0);
const containerHeight = (1.0 + 0.5 * bracketHeightCat) * em;
if (previousHeightCat !== bracketHeightCat) {
const schemeSet = (bracketRenderScheme[ch] || []);
const scheme = bracketHeightCat < schemeSet.length ?
schemeSet[bracketHeightCat] : schemeSet[schemeSet.length - 1];
boxMutations.push(() => {
if (scheme !== undefined) {
if (scheme.length === 1) {
elem.innerHTML = `<w><div>${scheme[0]}</div></w>`;
} else if (scheme.length === 2) {
const transform = `transform:scaleY(${0.25 * bracketHeightCat + 0.5});`;
elem.innerHTML = `<w><div style="${transform}transform-origin:50% 100%">${scheme[0]}</div><div style="${transform}transform-origin:50% 0%">${scheme[1]}</div></w>`;
} else if (scheme.length === 3) {
const spacing = 0.5 * bracketHeightCat - 1;
const spacingElement = `<w style="height:${spacing}em;">${("<w>" + scheme[2] + "</w>").repeat(Math.ceil(spacing))}</w>`;
elem.innerHTML = `<w><w>${scheme[0]}</w>${spacingElement}<w>${scheme[1]}</w></w>`;
} else if (scheme.length === 4) {
const spacing = 0.5 * (0.5 * bracketHeightCat - 2);
const spacingElement = `<w style="height:${spacing}em;">${("<w>" + scheme[3] + "</w>").repeat(Math.ceil(spacing))}</w>`;
elem.innerHTML = `<w><w>${scheme[0]}</w>${spacingElement}<w>${scheme[1]}</w>${spacingElement}<w>${scheme[2]}</w></w>`;
}
}
elem.style.height = `${(containerHeight).toFixed(2)}px`;
elem.setAttribute("height", String(bracketHeightCat));
});
}
return [0.5 * containerHeight + middle, 0.5 * containerHeight - middle];
};
const handleStringBox = (elem: HTMLElement | null, style: Style) => {
const lineHeight = style.lineHeight + (!(elem) ? 0.0 :
elem.classList.contains("large-symbol") ? 0.5 :
elem.classList.contains("small-symbol") ? -0.5 : 0.0
);
const padding = 0.5 * (lineHeight - 1.0) * style.fontSize;
return [
style.fontSize * style.fontMetric.baseline + padding,
style.fontSize * (1.0 - style.fontMetric.baseline) + padding
];
};
const handleRowBox = (elem: HTMLElement, style: Style, styleHandled = false) : number[] => {
if (!styleHandled && (elem.style.fontFamily || elem.style.fontSize)) {
let newFontFamily = elem.style.fontFamily || style.fontFamily;
let newFontSize = parseCssLength(elem.style.fontSize);
if (!(newFontSize >= 0)) {
newFontSize = style.fontSize;
}
return handleRowBox(elem, {
fontFamily: newFontFamily,
fontSize: newFontSize,
lineHeight: style.lineHeight,
fontMetric: (newFontFamily === style.fontFamily) ? style.fontMetric : FontMeasure.getFontMetric(newFontFamily)
}, true);
} else {
let span = handleStringBox(elem.children[0] as HTMLElement, style);
let brackets = [];
for (const child of elem.children as any) {
if (child.tagName === "W") {
} else if (child.tagName === "WB") {
brackets.push(child);
} else {
const childSpan = handleBox(child, style);
span = elementSpanMerge(span, childSpan);
}
}
if (brackets.length > 0) {
let bracketSpan = [-Infinity, -Infinity];
for (const bracket of brackets) {
bracketSpan = elementSpanMerge(bracketSpan, handleBracket(bracket, style, span));
}
span = elementSpanMerge(span, bracketSpan);
}
elem.setAttribute("span", elementSpanToString(span));
return span;
}
};
const getScriptStyle = (style: Style) => {
return {
...style,
fontSize: Math.max(style.fontSize * 0.71, MINIMUM_FONT_SIZE_PX)
};
};
const getLineWidth = (style: Style) => Math.max(0.08 * style.fontSize, 1.0);
const getAlignments = (span: number[], style: Style) => {
const supFactor = 0.37;
const subFactor = 1.05;
const fontSize = style.fontSize;
const topFactor = -0.5 * (style.lineHeight - 1.0);
const bottomFactor = 1.0 - topFactor;
const baselineFactor = style.fontMetric.baseline;
const middleFactor = style.fontMetric.middle;
return {
sup: span[0] + (topFactor - supFactor) * fontSize,
sub: -span[1] + (bottomFactor - subFactor) * fontSize,
middle: (baselineFactor - middleFactor) * fontSize,
x: (2.0 * (baselineFactor - middleFactor)) * fontSize,
ascend: (baselineFactor - 0.0) * fontSize,
descend: (baselineFactor - 1.0) * fontSize,
top: span[0] + (topFactor - 0.0) * fontSize,
bottom: -span[1] + (bottomFactor - 1.0) * fontSize,
};
};
const handleSubscriptBoxImpl = (elem: HTMLElement, style: Style, isSubscript: boolean) => {
const base = elem.children[1] as HTMLElement;
const script = elem.children[2] as HTMLElement;
const scriptStyle = getScriptStyle(style);
const baseSpan = handleBox(base, style);
const scriptSpan = handleBox(script.firstChild as HTMLElement, scriptStyle);
const baseAlign = getAlignments(baseSpan, style);
const scriptAlign = getAlignments(scriptSpan, scriptStyle);
const valign = isSubscript ?
Math.min(baseAlign.sub, baseAlign.ascend - scriptAlign.top) :
Math.max(baseAlign.sup, baseAlign.descend - scriptAlign.bottom);
boxMutations.push(() => {
script.style.verticalAlign = `${valign}px`;
});
const span = elementSpanMerge(baseSpan, elementSpanAdd(scriptSpan, valign));
elem.setAttribute("span", elementSpanToString(span));
return span;
};
const handleSuperscriptBox = (elem: HTMLElement, style: Style) => handleSubscriptBoxImpl(elem, style, false);
const handleSubscriptBox = (elem: HTMLElement, style: Style) => handleSubscriptBoxImpl(elem, style, true);
const handleSubsuperscriptBox = (elem: HTMLElement, style: Style) => {
const base = elem.children[1] as HTMLElement;
const scripts = elem.children[2] as HTMLElement;
const sup = scripts.children[0] as HTMLElement;
const space = scripts.children[1] as HTMLElement;
const sub = scripts.children[2] as HTMLElement;
const scriptStyle = getScriptStyle(style);
const baseSpan = handleBox(base, style);
const subSpan = handleBox(sub, scriptStyle);
const supSpan = handleBox(sup, scriptStyle);
const baseAlign = getAlignments(baseSpan, style);
const subValign = Math.min(baseAlign.sub, baseAlign.middle - subSpan[0]);
const supValign = Math.max(baseAlign.sup, baseAlign.middle + supSpan[1]);
const spaceHeight = Math.max(0.0, (supValign - supSpan[1]) - (subValign + subSpan[0]));
const valign = subValign - subSpan[1];
boxMutations.push(() => {
space.style.height = `${spaceHeight}px`;
scripts.style.verticalAlign = `${valign}px`;
});
return [Math.max(baseSpan[0], supSpan[0] + supValign), Math.max(baseSpan[1], subSpan[1] - subValign)];
};
const handleUnderscriptBoxImpl = (elem: HTMLElement, style: Style, isUnderscript: boolean) => {
const base = elem.children[isUnderscript ? 0 : 1] as HTMLElement;
const script = elem.children[isUnderscript ? 1 : 0] as HTMLElement;
const scriptStyle = getScriptStyle(style);
const baseSpan = handleBox(base, style);
const scriptSpan = handleBox(script.firstChild as HTMLElement, scriptStyle);
const span = isUnderscript ?
[baseSpan[0], baseSpan[1] + scriptSpan[0] + scriptSpan[1]] :
[baseSpan[0] + scriptSpan[0] + scriptSpan[1], baseSpan[1]];
elem.setAttribute("span", elementSpanToString(span));
return span;
};
const handleOverscriptBox = (elem: HTMLElement, style: Style) => handleUnderscriptBoxImpl(elem, style, false);
const handleUnderscriptBox = (elem: HTMLElement, style: Style) => handleUnderscriptBoxImpl(elem, style, true);
const handleUnderoverscriptBox = (elem: HTMLElement, style: Style) => {
const base = elem.children[1].firstChild as HTMLElement;
const over = elem.children[0] as HTMLElement;
const under = elem.children[1].children[1] as HTMLElement;
const scriptStyle = getScriptStyle(style);
const baseSpan = handleBox(base, style);
const overSpan = handleBox(over.firstChild as HTMLElement, scriptStyle);
const underSpan = handleBox(under.firstChild as HTMLElement, scriptStyle);
const span = [baseSpan[0] + overSpan[0] + overSpan[1], baseSpan[1] + underSpan[0] + underSpan[1]];
elem.setAttribute("span", elementSpanToString(span));
return span;
};
const sqrtSignRenderScheme = [
["", ""],
["", ""],
["", ""],
["", ""],
["", ""]
];
const handleSqrtBox = (elem: HTMLElement, style: Style) => {
const base = elem.children[2] as HTMLElement;
const script = elem.children[0].children[1] as HTMLElement;
const scriptStyle = getScriptStyle(style);
const lineWidth = getLineWidth(style);
const baseSpan = elementSpanMerge(handleStringBox(null, style), handleBox(base.firstChild as HTMLElement, style));
const scriptSpan = script ? handleBox(script.firstChild as HTMLElement, scriptStyle) : [0.0, 0.0];
const signRightHeight = (baseSpan[0] + baseSpan[1] + lineWidth) / style.fontSize;
const signLeftHeight = Math.min(0.25 * (signRightHeight + 1.0), 1.0);
const heightCat = Math.min(Math.max(Math.round(2.0 * (signRightHeight - 1.0)), 0), 4);
const [signLeftChar, signRightChar] = sqrtSignRenderScheme[heightCat];
const scaleFactorRight = (signRightHeight / (0.5 * heightCat + 1.0)).toFixed(3);
const scaleFactorLeft = (signLeftHeight / (0.125 * heightCat + 0.5)).toFixed(3);
const scriptExtraHeight = (signLeftHeight + 0.2 - signRightHeight) + (scriptSpan[0] + scriptSpan[1]) / style.fontSize;
boxMutations.push(() => {
elem.children[1].innerHTML = `<w style="transform:scaleY(${scaleFactorRight})">${signRightChar}</w>`;
elem.children[0].children[0].innerHTML = `<w style="transform:scaleY(${scaleFactorLeft})">${signLeftChar}</w>`;
(elem.children[0].children[0] as HTMLElement).style.height = `${signLeftHeight.toFixed(3)}em`;
elem.style.marginTop = `${Math.max(scriptExtraHeight, 0.1).toFixed(3)}em`;
});
return [baseSpan[0] + lineWidth, baseSpan[1]];
};
const handleFractionBox = (elem: HTMLElement, style: Style) => {
const up = elem.children[0];
const down = elem.children[1].children[1];
const scriptStyle = elem.classList.contains("script") ? getScriptStyle(style) : style;
const upSpan = handleBox(up.firstChild as HTMLElement, scriptStyle);
const downSpan = handleBox(down.firstChild as HTMLElement, scriptStyle);
const lineWidth = getLineWidth(style);
const offset = getAlignments([0., 0.], style).middle;
const span = elementSpanAdd([upSpan[0] + upSpan[1] + 0.5 * lineWidth, downSpan[0] + downSpan[1] + 0.5 * lineWidth], offset);
elem.setAttribute("span", elementSpanToString(span));
return span;
};
const handleGridBox = (elem: HTMLElement, style: Style) => {
const childrenSpans = Array.from(elem.children).map(child => handleBox(child.firstChild as HTMLElement, style));
clearBoxMutations();
const height = elem.offsetHeight;
const middle = (style.fontMetric.baseline - style.fontMetric.middle) * style.fontSize;
const margin = 0.1 * style.fontSize;
const span = [0.5 * height + middle + margin, 0.5 * height - middle + margin];
elem.setAttribute("span", elementSpanToString(span));
return span;
};
const handleFrameBox = (elem: HTMLElement, style: Style) => {
const defaultPadding = getLineWidth(style);
const orDefault = (value: number) => (value >= 0 ? value : defaultPadding);
const paddings = [orDefault(parseCssLength(elem.style.paddingTop)), orDefault(parseCssLength(elem.style.paddingBottom))];
const margins = [parseCssLength(elem.style.marginTop) || 0, parseCssLength(elem.style.marginBottom) || 0];
const lineWidth = Math.max(1.0, 0.05 * style.fontSize);
const contentSpan = handleBox(elem.firstChild as HTMLElement, style);
const span = [contentSpan[0] + paddings[0] + margins[0] + lineWidth, contentSpan[1] + paddings[1] + margins[1] + lineWidth];
elem.setAttribute("span", elementSpanToString(span));
return span;
};
const handlePaneBox = (elem: HTMLElement, style: Style) => {
return handleStringBox(elem, style);
};
const handleGraphicsBox = (elem: HTMLElement, style: Style) => {
const height = elem.offsetHeight;
const middle = (style.fontMetric.baseline - style.fontMetric.middle) * style.fontSize;
const margin = 0.1 * style.fontSize + 1.0;
const span = [0.5 * height + middle + margin, 0.5 * height - middle + margin];
elem.setAttribute("span", elementSpanToString(span));
return span;
};
const preventDefault = (e: any) => {
e.preventDefault();
};
const addPreventDragStart = (elem: HTMLElement) => {
elem.addEventListener("dragstart", preventDefault);
};
const removePreventDragStart = (elem: HTMLElement) => {
elem.removeEventListener("dragstart", preventDefault);
};
export const addResizeWidget = (root: HTMLElement) => {
const graphs = root.querySelectorAll("wgraph.resizable");
for (let i = graphs.length - 1; i >= 0; --i) {
const graph = graphs[i] as HTMLElement;
addPreventDragStart(graph);
if (graph.childElementCount > 0) {
addPreventDragStart(graph.children[0] as HTMLElement);
}
graph.appendChild(document.createElement("div"));
const widget = graph.lastChild as HTMLElement;
widget.className = "resize-widget";
widget.style.zIndex = "1000";
widget.onpointerdown = (e: PointerEvent) => {
const initialX = e.clientX;
const initialWidth = (e.target as HTMLElement).parentElement?.offsetWidth || 0;
widget.onpointermove = e => {
const parent = widget.parentElement as HTMLElement;
const aspectRatio = parent ? parseFloat(parent.getAttribute("aspect-ratio") || "") : NaN;
if (!(aspectRatio > 0)) {
return;
}
let newWidth = e.clientX - initialX + initialWidth;
if (aspectRatio <= 1.0 && newWidth < GRAPHICS_MINIMUM_SIZE) {
newWidth = GRAPHICS_MINIMUM_SIZE;
} else if (aspectRatio > 1.0 && newWidth * aspectRatio < GRAPHICS_MINIMUM_SIZE) {
newWidth = GRAPHICS_MINIMUM_SIZE / aspectRatio;
}
parent.style.width = `${newWidth}px`;
parent.style.height = `${newWidth * aspectRatio}px`;
};
widget.setPointerCapture(e.pointerId);
};
widget.onpointerup = e => {
widget.onpointermove = null;
widget.releasePointerCapture(e.pointerId);
};
}
};
export const removeResizeWidget = (root: HTMLElement) => {
const widgets = root.querySelectorAll(".resize-widget");
for (let i = widgets.length - 1; i >= 0; --i) {
const widget = widgets[i];
const parent = widget.parentElement;
if (parent) {
parent.removeChild(widget);
if (parent.childElementCount > 0) {
removePreventDragStart(parent.children[0] as HTMLElement);
}
removePreventDragStart(parent);
}
}
}; | the_stack |
import * as React from "react";
import * as ReactDom from "react-dom";
import { Version } from "@microsoft/sp-core-library";
import {
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneChoiceGroup,
PropertyPaneToggle,
PropertyPaneDropdown,
IPropertyPaneDropdownOption,
PropertyPaneSlider,
PropertyPaneHorizontalRule,
PropertyPaneLabel
} from "@microsoft/sp-property-pane";
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import * as lodash from "lodash";
import * as strings from "NewsWebPartStrings";
import News from "../components/News";
import { INewsProps } from "../components/INewsProps";
import dataservices from "../../services/dataservices";
import { DisplayMode } from "@microsoft/sp-core-library";
import * as $ from "jquery";
import { loadTheme, IDropdownOption } from "office-ui-fabric-react";
import { PropertyFieldMultiSelect } from "@pnp/spfx-property-controls/lib/PropertyFieldMultiSelect";
import { ISourcesResults } from "../../services/ISourcesResults";
import { ISource } from "../../services/ISource";
import { ThemeProvider, ThemeChangedEventArgs, IReadonlyTheme } from '@microsoft/sp-component-base';
const languages: IPropertyPaneDropdownOption[] = [
{ key: "all", text: "All Languages" },
{ key: "ar", text: "Arabic" },
{ key: "de", text: "German" },
{ key: "en", text: "English" },
{ key: "es", text: "Castilian" },
{ key: "fr", text: "French" },
{ key: "he", text: "Hebrew" },
{ key: "it", text: "Italian" },
{ key: "nl", text: "Dutch" },
{ key: "no", text: "Norwegian" },
{ key: "pt", text: "Portuguese" },
{ key: "ru", text: "Russian" },
{ key: "se", text: "Northern Sami" },
{ key: "zh", text: "Chinese" }
];
const countries: IPropertyPaneDropdownOption[] = [
{ key: "ALL", text: "All Countries" },
{ key: "AE", text: "United Arab Emirates" },
{ key: "AR", text: "Argentina" },
{ key: "AT", text: "Austria" },
{ key: "AU", text: "Australia" },
{ key: "BE", text: "Belgium" },
{ key: "BG", text: "Bulgaria" },
{ key: "BR", text: "Brazil" },
{ key: "CA", text: "Canada" },
{ key: "CH", text: "Switzerland" },
{ key: "CN", text: "China" },
{ key: "CO", text: "Colombia" },
{ key: "CU", text: "Cuba" },
{ key: "CZ", text: "Czech Republic" },
{ key: "DE", text: "Germany" },
{ key: "EG", text: "Egypt" },
{ key: "FR", text: "France" },
{ key: "GB", text: "United Kingdom" },
{ key: "GR", text: "Greece" },
{ key: "HK", text: "Hong Kong" },
{ key: "HU", text: "Hungary" },
{ key: "ID", text: "Indonesia" },
{ key: "IE", text: "Ireland" },
{ key: "IL", text: "Israel" },
{ key: "IN", text: "India" },
{ key: "IT", text: "Italy" },
{ key: "JP", text: "Japan" },
{ key: "KR", text: "Korea, Republic of" },
{ key: "LT", text: "Lithuania" },
{ key: "LV", text: "Latvia" },
{ key: "MA", text: "Morocco" },
{ key: "MX", text: "Mexico" },
{ key: "MY", text: "Malaysia" },
{ key: "NG", text: "Nigeria" },
{ key: "NL", text: "Netherlands" },
{ key: "NO", text: "Norway" },
{ key: "NZ", text: "New Zealand" },
{ key: "PH", text: "Philippines" },
{ key: "PL", text: "Poland" },
{ key: "PT", text: "Portugal" },
{ key: "RO", text: "Romania" },
{ key: "RS", text: "Serbia" },
{ key: "RU", text: "Russian Federation" },
{ key: "SA", text: "Saudi Arabia" },
{ key: "SE", text: "Sweden" },
{ key: "SG", text: "Singapore" },
{ key: "SI", text: "Slovenia" },
{ key: "SK", text: "Slovakia" },
{ key: "TH", text: "Thailand" },
{ key: "TR", text: "Turkey" },
{ key: "TW", text: "Taiwan, Province of China" },
{ key: "UA", text: "Ukraine" },
{ key: "US", text: "United States" },
{ key: "VE", text: "Venezuela, Bolivarian Republic of" },
{ key: "ZA", text: "South Africa" }
];
const categories: IPropertyPaneDropdownOption[] = [
{ key: "business", text: "business" },
{ key: "entertainment", text: "entertainment" },
{ key: "general", text: "general" },
{ key: "health", text: "health" },
{ key: "science", text: "science" },
{ key: "sports", text: "sports" },
{ key: "technology", text: "technology" }
];
const teamsDefaultTheme = require("../../common/TeamsDefaultTheme.json");
const teamsDarkTheme = require("../../common/TeamsDarkTheme.json");
const teamsContrastTheme = require("../../common/TeamsContrastTheme.json");
export interface INewsWebPartProps {
title: string;
newsUrl: string;
apiKey: string;
endpoint: number;
queryTitleOnly: boolean;
domains: string;
excludeDomains: string;
language: string;
country: string;
category: string;
query: string;
pagesize: number;
viewOption: string;
sources: string[];
}
export default class NewsWebPart extends BaseClientSideWebPart<
INewsWebPartProps
> {
private _sourcesOptions: IDropdownOption[] = [];
private _themeProvider: ThemeProvider;
private _themeVariant: IReadonlyTheme | undefined;
protected async onInit<T>(): Promise<T> {
await dataservices.init(this.context);
this._themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey);
// If it exists, get the theme variant
this._themeVariant = this._themeProvider.tryGetTheme();
// Register a handler to be notified if the theme variant changes
this._themeProvider.themeChangedEvent.add(this, this._handleThemeChangedEvent);
// test if is teams context
if (this.context.sdks.microsoftTeams) {
// in teams ?
const context = this.context.sdks.microsoftTeams!.context;
this._applyTheme(context.theme || "default");
this.context.sdks.microsoftTeams.teamsJs.registerOnThemeChangeHandler(
this._applyTheme
);
}
return Promise.resolve();
}
/**
* Update the current theme variant reference and re-render.
*
* @param args The new theme
*/
private _handleThemeChangedEvent(args: ThemeChangedEventArgs): void {
this._themeVariant = args.theme;
this.render();
}
// Apply Teams Context
private _applyTheme = (theme: string): void => {
this.context.domElement.setAttribute("data-theme", theme);
document.body.setAttribute("data-theme", theme);
if (theme == "dark") {
loadTheme({
palette: teamsDarkTheme
});
}
if (theme == "default") {
loadTheme({
palette: teamsDefaultTheme
});
}
if (theme == "contrast") {
loadTheme({
palette: teamsContrastTheme
});
}
}
private _validateNewsUrl = (value: string): string => {
try {
let _url = new URL(value);
return "";
} catch (error) {
return "news Url is not valid, please specify valid url";
}
}
public updateProperty = (value: string) => {
this.properties.title = value;
}
private _getSources = async (apiKey: string) => {
let _resultSources: ISourcesResults = await dataservices.getSources(apiKey);
try {
if (_resultSources && _resultSources.sources.length > 0) {
for (const source of _resultSources.sources) {
this._sourcesOptions.push({ key: source.id, text: source.name });
}
return;
}
} catch (error) {
console.log("Error loading Sources", error);
return;
}
}
// Render WebPart
public render(): void {
const element: React.ReactElement<INewsProps> = React.createElement(
News,
{
newsUrl: this.properties.newsUrl,
apiKey: this.properties.apiKey,
context: this.context,
title: this.properties.title,
updateProperty: this.updateProperty,
displayMode: this.displayMode,
viewOption: this.properties.viewOption,
pageSize: this.properties.pagesize,
themeVariant: this._themeVariant,
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get disableReactivePropertyChanges(): boolean {
return true;
}
protected get dataVersion(): Version {
return Version.parse("1.0");
}
protected async onPropertyPaneConfigurationStart() {
await this._getSources(this.properties.apiKey);
this.context.propertyPane.refresh();
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
let _showPropertyQueryTitle: any = "";
let _showPropertyDomains: any = "";
let _showPropertyexcludeDomains: any = "";
let _showPropertyLanguage: any = "";
let _showPropertyCountry: any = "";
let _showPropertyCategory: any = "";
let _viewOption: string = undefined;
if (!this.properties.viewOption || this.properties.viewOption === "list") {
_viewOption = "list";
} else {
_viewOption = "tiles";
}
if (!this.properties.newsUrl) {
this.properties.newsUrl =
"https://newsapi.org/v2/top-headlines?category=general&sortBy=publishedAt";
}
if (!this.properties.endpoint) {
this.properties.endpoint = 1;
}
if (!this.properties.category) {
this.properties.category = "general";
}
// teste if All News or TOP Headding news
switch (this.properties.endpoint) {
case 2:
this.properties.country = "";
this.properties.category = "";
_showPropertyCountry = "";
_showPropertyCategory = "";
_showPropertyQueryTitle = PropertyPaneToggle("queryTitleOnly", {
label: "Search on Article Title Only",
onText: "On",
offText: "Off",
checked: this.properties.queryTitleOnly
});
_showPropertyDomains = PropertyPaneTextField("domains", {
label: "Selected Domains",
value: this.properties.domains,
description:
"comma-seperated (eg bbc.co.uk, techcrunch.com, engadget.com)"
});
_showPropertyexcludeDomains = PropertyPaneTextField("excludeDomains", {
label: "Exclude Domains",
value: this.properties.excludeDomains,
description:
"comma-seperated (eg bbc.co.uk, techcrunch.com, engadget.com)"
});
// Create a news URL API
this.properties.newsUrl = `https://newsapi.org/v2/everything?sortBy=publishedAt`;
// Test Properties
// Query on Article Title
if (this.properties.queryTitleOnly) {
if (
this.properties.query &&
this.properties.query.trim().length > 0
) {
let _query: string = encodeURIComponent(this.properties.query);
this.properties.newsUrl = `${this.properties.newsUrl}&qInTitle=${_query}`;
} else {
this.properties.newsUrl = `${this.properties.newsUrl}&qInTitle=*`;
}
}
// Domains
if (this.properties.domains) {
this.properties.newsUrl = `${this.properties.newsUrl}&domains=${this.properties.domains}`;
}
// Excluded Domains
if (this.properties.excludeDomains) {
this.properties.newsUrl = `${this.properties.newsUrl}&excludeDomains=${this.properties.excludeDomains}`;
}
// Language
if (this.properties.language && this.properties.language !== "all") {
this.properties.newsUrl = `${this.properties.newsUrl}&language=${this.properties.language}`;
}
// Query Title Only
if (!this.properties.queryTitleOnly) {
if (
this.properties.query &&
this.properties.query.trim().length > 0
) {
let _query: string = encodeURIComponent(this.properties.query);
this.properties.newsUrl = `${this.properties.newsUrl}&q=${_query}`;
} else {
this.properties.newsUrl = `${this.properties.newsUrl}&q=*`;
}
}
if (this.properties.pagesize) {
this.properties.newsUrl = `${this.properties.newsUrl}&pageSize=${this.properties.pagesize}`;
}
if (this.properties.sources && this.properties.sources.length > 0) {
if (this.properties.sources.length < 20) {
this.properties.newsUrl = `${
this.properties.newsUrl
}&sources=${this.properties.sources.join()}`;
} else {
this.properties.newsUrl = `${
this.properties.newsUrl
}&sources=${this.properties.sources.slice(0, 19).join()}`;
}
}
_showPropertyLanguage = PropertyPaneDropdown("language", {
label: "Show Articles in this language",
options: lodash.sortBy(languages, ["key"]),
selectedKey: this.properties.language || "all"
});
break;
// Top Heading
case 1:
// Reset Properties Vars
this.properties.queryTitleOnly = false;
this.properties.domains = "";
this.properties.excludeDomains = "";
this.properties.language = "";
_showPropertyQueryTitle = "";
_showPropertyDomains = "";
_showPropertyexcludeDomains = "";
_showPropertyLanguage = "";
this.properties.newsUrl = `https://newsapi.org/v2/top-headlines?sortBy=publishedAt`;
if (this.properties.query && this.properties.query.trim().length > 0) {
let _query: string = encodeURIComponent(this.properties.query);
this.properties.newsUrl = `${this.properties.newsUrl}&q=${_query}`;
}
if (this.properties.pagesize) {
this.properties.newsUrl = `${this.properties.newsUrl}&pageSize=${this.properties.pagesize}`;
}
// Has sources ? add parameter to newsURl disable country and Category
if (this.properties.sources && this.properties.sources.length > 0) {
if (this.properties.sources.length < 20) {
// only the first 20 sources selectd limited by API
this.properties.newsUrl = `${
this.properties.newsUrl
}&sources=${this.properties.sources.join()}`;
} else {
this.properties.newsUrl = `${
this.properties.newsUrl
}&sources=${this.properties.sources.slice(0, 19).join()}`;
}
} else {
// Show Category and Country if sources is not specified
if (this.properties.category) {
this.properties.newsUrl = `${this.properties.newsUrl}&category=${this.properties.category}`;
}
if (this.properties.country && this.properties.country !== "ALL") {
this.properties.newsUrl = `${this.properties.newsUrl}&country=${this.properties.country}`;
}
_showPropertyCountry = PropertyPaneDropdown("country", {
label: "Country",
options: lodash.sortBy(countries, ["text"]),
selectedKey: this.properties.country || "ALL"
});
_showPropertyCategory = PropertyPaneDropdown("category", {
label: "Category",
options: lodash.sortBy(categories, ["key"]),
selectedKey: this.properties.category || "general"
});
}
break;
default:
break;
}
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField("title", {
label: strings.Title,
value: this.properties.title
}),
PropertyPaneTextField("query", {
label: "Search Keyword or Phrase",
value: this.properties.query
}),
PropertyFieldMultiSelect("sources", {
key: "sources",
label: "Sources",
disabled: false,
options: this._sourcesOptions,
selectedKeys: this.properties.sources
}),
PropertyPaneChoiceGroup("endpoint", {
label: "Show Articles from:",
options: [
{ text: "Top Headlines", key: 1 },
{ text: "All News", key: 2 }
]
}),
_showPropertyCountry,
_showPropertyCategory,
_showPropertyQueryTitle,
_showPropertyDomains,
_showPropertyexcludeDomains,
_showPropertyLanguage
]
}
]
},
{
header: {
description: strings.ViewSettings
},
groups: [
{
groupFields: [
PropertyPaneChoiceGroup("viewOption", {
label: strings.ViewOption,
options: [
{
text: "List View",
key: "list",
checked: _viewOption === "list" ? true : false,
iconProps: { officeFabricIconFontName: "list" }
},
{
text: "Tiles View",
key: "tiles",
checked: _viewOption === "ltiles" ? true : false,
iconProps: { officeFabricIconFontName: "Tiles" }
}
]
}),
PropertyPaneLabel("", { text: "" }),
PropertyPaneSlider("pagesize", {
label: strings.PageSizeLabel,
max: 100,
min: 3,
step: 1,
showValue: true,
value: this.properties.pagesize
}),
PropertyPaneLabel("", { text: strings.APILabelText }),
PropertyPaneTextField("apiKey", {
label: strings.ApiKey,
value: this.properties.apiKey,
validateOnFocusOut: true,
onGetErrorMessage: value => {
if (!value) {
return "ApiKey is Required";
} else {
return "";
}
}
})
]
}
]
}
]
};
}
} | the_stack |
import { promisify } from "util";
import * as async from "async";
import { assert } from "node-opcua-assert";
import { DataValue } from "node-opcua-data-value";
import { make_errorLog } from "node-opcua-debug";
import { NodeId, resolveNodeId, NodeIdType } from "node-opcua-nodeid";
import {
ArgumentDefinition,
BrowseDescriptionLike,
CallMethodRequestLike,
getArgumentDefinitionHelper,
IBasicSession,
MethodId,
ResponseCallback
} from "node-opcua-pseudo-session";
import { BrowseDescription, BrowseResult } from "node-opcua-service-browse";
import { CallMethodRequest, CallMethodResult, CallMethodResultOptions } from "node-opcua-service-call";
import { BrowsePath, BrowsePathResult } from "node-opcua-service-translate-browse-path";
import { StatusCodes, StatusCode } from "node-opcua-status-code";
import { NodeClass, AttributeIds } from "node-opcua-data-model";
import { WriteValueOptions, ReadValueIdOptions, BrowseDescriptionOptions } from "node-opcua-types";
import { randomGuid } from "node-opcua-basic-types";
import { IAddressSpace, UAVariable, ISessionContext, ContinuationPoint } from "node-opcua-address-space-base";
import { ContinuationPointManager } from "./continuation_points/continuation_point_manager";
import { callMethodHelper } from "./helpers/call_helpers";
import { SessionContext } from "./session_context";
const errorLog = make_errorLog("PseudoSession");
/**
* Pseudo session is an helper object that exposes the same async methods
* than the ClientSession. It can be used on a server address space.
*
* Code reused !
* The primary benefit of this object is that its makes advanced OPCUA
* operations that uses browse, translate, read, write etc similar
* whether we work inside a server or through a client session.
*
*/
export class PseudoSession implements IBasicSession {
public requestedMaxReferencesPerNode = 0;
private _sessionId: NodeId = new NodeId(NodeIdType.GUID, randomGuid());
private readonly addressSpace: IAddressSpace;
private readonly continuationPointManager: ContinuationPointManager;
private readonly context: ISessionContext;
constructor(addressSpace: IAddressSpace, context?: ISessionContext) {
this.addressSpace = addressSpace;
this.context = context || SessionContext.defaultContext;
this.continuationPointManager = new ContinuationPointManager();
}
public getSessionId(): NodeId {
return this._sessionId;
}
public browse(nodeToBrowse: BrowseDescriptionLike, callback: ResponseCallback<BrowseResult>): void;
public browse(nodesToBrowse: BrowseDescriptionLike[], callback: ResponseCallback<BrowseResult[]>): void;
public browse(nodeToBrowse: BrowseDescriptionLike): Promise<BrowseResult>;
public browse(nodesToBrowse: BrowseDescriptionLike[]): Promise<BrowseResult[]>;
public browse(nodesToBrowse: BrowseDescriptionLike | BrowseDescriptionLike[], callback?: ResponseCallback<any>): any {
setImmediate(() => {
const isArray = Array.isArray(nodesToBrowse);
if (!isArray) {
nodesToBrowse = [nodesToBrowse as BrowseDescriptionLike];
}
let results: BrowseResult[] = [];
for (const browseDescription of nodesToBrowse as BrowseDescriptionOptions[]) {
browseDescription.referenceTypeId = resolveNodeId(browseDescription.referenceTypeId!);
const _browseDescription =
browseDescription instanceof BrowseDescription ? browseDescription : new BrowseDescription(browseDescription);
const nodeId = resolveNodeId(_browseDescription.nodeId);
const r = this.addressSpace.browseSingleNode(nodeId, _browseDescription, this.context);
results.push(r);
}
// handle continuation points
results = results.map((result: BrowseResult, index) => {
assert(!result.continuationPoint);
const r = this.continuationPointManager.registerReferences(
this.requestedMaxReferencesPerNode,
result.references || [],
{ continuationPoint: null, index }
);
let { statusCode } = r;
const { continuationPoint, values } = r;
assert(statusCode === StatusCodes.Good || statusCode === StatusCodes.GoodNoData);
statusCode = result.statusCode;
return new BrowseResult({
statusCode,
continuationPoint,
references: values
});
});
callback!(null, isArray ? results : results[0]);
});
}
public read(nodeToRead: ReadValueIdOptions, callback: ResponseCallback<DataValue>): void;
public read(nodesToRead: ReadValueIdOptions[], callback: ResponseCallback<DataValue[]>): void;
public read(nodeToRead: ReadValueIdOptions): Promise<DataValue>;
public read(nodesToRead: ReadValueIdOptions[]): Promise<DataValue[]>;
public read(nodesToRead: ReadValueIdOptions[] | ReadValueIdOptions, callback?: ResponseCallback<any>): any {
const isArray = Array.isArray(nodesToRead);
if (!isArray) {
nodesToRead = [nodesToRead as ReadValueIdOptions];
}
const _nodesToRead = nodesToRead as ReadValueIdOptions[];
const context = this.context;
setImmediate(() => {
async.map(
_nodesToRead,
(nodeToRead: ReadValueIdOptions, innerCallback: any) => {
const obj = this.addressSpace.findNode(nodeToRead.nodeId!);
if (!obj || obj.nodeClass !== NodeClass.Variable || nodeToRead.attributeId !== AttributeIds.Value) {
return innerCallback();
}
(obj as UAVariable).readValueAsync(context, innerCallback);
},
(err) => {
const dataValues = _nodesToRead.map((nodeToRead: ReadValueIdOptions) => {
assert(!!nodeToRead.nodeId, "expecting a nodeId");
assert(!!nodeToRead.attributeId, "expecting a attributeId");
const nodeId = nodeToRead.nodeId!;
const attributeId = nodeToRead.attributeId!;
const indexRange = nodeToRead.indexRange;
const dataEncoding = nodeToRead.dataEncoding;
const obj = this.addressSpace.findNode(nodeId);
if (!obj) {
return new DataValue({ statusCode: StatusCodes.BadNodeIdUnknown });
}
const context = this.context;
const dataValue = obj.readAttribute(context, attributeId, indexRange, dataEncoding);
return dataValue;
});
callback!(null, isArray ? dataValues : dataValues[0]);
}
);
});
}
public browseNext(
continuationPoint: Buffer,
releaseContinuationPoints: boolean,
callback: ResponseCallback<BrowseResult>
): void;
public browseNext(
continuationPoints: Buffer[],
releaseContinuationPoints: boolean,
callback: ResponseCallback<BrowseResult[]>
): void;
public browseNext(continuationPoint: Buffer, releaseContinuationPoints: boolean): Promise<BrowseResult>;
public browseNext(continuationPoints: Buffer[], releaseContinuationPoints: boolean): Promise<BrowseResult[]>;
public browseNext(
continuationPoints: Buffer | Buffer[],
releaseContinuationPoints: boolean,
callback?: ResponseCallback<any>
): any {
setImmediate(() => {
if (continuationPoints instanceof Buffer) {
return this.browseNext([continuationPoints], releaseContinuationPoints, (err, _results) => {
if (err) {
return callback!(err);
}
callback!(null, _results![0]);
});
}
const results = continuationPoints
.map((continuationPoint: ContinuationPoint, index: number) => {
return this.continuationPointManager.getNextReferences(0, {
continuationPoint,
index,
releaseContinuationPoints
});
})
.map(
(r) =>
new BrowseResult({
statusCode: r.statusCode,
continuationPoint: r.continuationPoint,
references: r.values
})
);
callback!(null, results);
});
}
// call service ----------------------------------------------------------------------------------------------------
public call(methodToCall: CallMethodRequestLike, callback: ResponseCallback<CallMethodResult>): void;
public call(methodsToCall: CallMethodRequestLike[], callback: ResponseCallback<CallMethodResult[]>): void;
public call(methodToCall: CallMethodRequestLike): Promise<CallMethodResult>;
public call(methodsToCall: CallMethodRequestLike[]): Promise<CallMethodResult[]>;
public call(methodsToCall: CallMethodRequestLike | CallMethodRequestLike[], callback?: ResponseCallback<any>): any {
const isArray = Array.isArray(methodsToCall);
if (!isArray) {
methodsToCall = [methodsToCall as CallMethodRequestLike];
}
async.map(
methodsToCall as CallMethodRequestLike[],
(methodToCall, innerCallback: (err: Error | null, result?: CallMethodResult) => void) => {
const callMethodRequest = new CallMethodRequest(methodToCall);
callMethodHelper(
this.context,
this.addressSpace,
callMethodRequest,
(err: Error | null, result?: CallMethodResultOptions) => {
let callMethodResult: CallMethodResult;
if (err) {
errorLog("Internal Error = ", err);
callMethodResult = new CallMethodResult({
statusCode: StatusCodes.BadInternalError
});
} else {
callMethodResult = new CallMethodResult(result);
}
innerCallback(null, callMethodResult);
}
);
},
(err?: Error | null, callMethodResults?: any) => {
callback!(null, isArray ? callMethodResults! : callMethodResults![0]);
}
);
}
public getArgumentDefinition(methodId: MethodId): Promise<ArgumentDefinition>;
public getArgumentDefinition(methodId: MethodId, callback: ResponseCallback<ArgumentDefinition>): void;
public getArgumentDefinition(methodId: MethodId, callback?: ResponseCallback<ArgumentDefinition>): any {
return getArgumentDefinitionHelper(this, methodId, callback!);
}
public translateBrowsePath(browsePaths: BrowsePath[], callback: ResponseCallback<BrowsePathResult[]>): void;
public translateBrowsePath(browsePath: BrowsePath, callback: ResponseCallback<BrowsePathResult>): void;
public translateBrowsePath(browsePath: BrowsePath): Promise<BrowsePathResult>;
public translateBrowsePath(browsePaths: BrowsePath[]): Promise<BrowsePathResult[]>;
public translateBrowsePath(browsePaths: BrowsePath[] | BrowsePath, callback?: ResponseCallback<any>): any {
const isArray = Array.isArray(browsePaths);
if (!isArray) {
browsePaths = [browsePaths as BrowsePath];
}
const browsePathResults = (browsePaths as BrowsePath[]).map((browsePath: BrowsePath) => {
return this.addressSpace.browsePath(browsePath);
});
callback!(null, isArray ? browsePathResults : browsePathResults[0]);
}
public write(nodeToWrite: WriteValueOptions, callback: ResponseCallback<StatusCode>): void;
public write(nodesToWrite: WriteValueOptions[], callback: ResponseCallback<StatusCode[]>): void;
public write(nodeToWrite: WriteValueOptions): Promise<StatusCode>;
public write(nodesToWrite: WriteValueOptions[]): Promise<StatusCode[]>;
public write(nodesToWrite: WriteValueOptions[] | WriteValueOptions, callback?: ResponseCallback<any>): any {
const isArray = nodesToWrite instanceof Array;
const _nodesToWrite: WriteValueOptions[] = !isArray ? [nodesToWrite] : nodesToWrite;
const context = this.context;
setImmediate(() => {
const statusCodesPromises = _nodesToWrite.map((nodeToWrite: WriteValueOptions) => {
assert(!!nodeToWrite.nodeId, "expecting a nodeId");
assert(!!nodeToWrite.attributeId, "expecting a attributeId");
const nodeId = nodeToWrite.nodeId!;
const obj = this.addressSpace.findNode(nodeId);
if (!obj) {
return StatusCodes.BadNodeIdUnknown;
}
return promisify(obj.writeAttribute).call(obj, context, nodeToWrite);
});
Promise.all(statusCodesPromises).then((statusCodes) => {
callback!(null, isArray ? statusCodes : statusCodes[0]);
});
});
}
}
// tslint:disable:no-var-requires
// tslint:disable:max-line-length
const thenify = require("thenify");
PseudoSession.prototype.read = thenify.withCallback(PseudoSession.prototype.read);
PseudoSession.prototype.write = thenify.withCallback(PseudoSession.prototype.write);
PseudoSession.prototype.browse = thenify.withCallback(PseudoSession.prototype.browse);
PseudoSession.prototype.browseNext = thenify.withCallback(PseudoSession.prototype.browseNext);
PseudoSession.prototype.getArgumentDefinition = thenify.withCallback(PseudoSession.prototype.getArgumentDefinition);
PseudoSession.prototype.call = thenify.withCallback(PseudoSession.prototype.call);
PseudoSession.prototype.translateBrowsePath = thenify.withCallback(PseudoSession.prototype.translateBrowsePath); | the_stack |
import { isNotNull, isPascalCase } from '@vuedx/shared'
import {
findTemplateNodeAt,
isElementNode,
isInterpolationNode,
isSimpleExpressionNode,
SearchResult,
} from '@vuedx/template-ast-types'
import type {
TextDocument,
VueBlockDocument,
VueSFCDocument,
} from '@vuedx/vue-virtual-textdocument'
import { inject, injectable } from 'inversify'
import type Typescript from 'typescript/lib/tsserverlibrary'
import { INJECTABLE_TS_SERVICE } from '../constants'
import type { TSLanguageService } from '../contracts/Typescript'
import { FilesystemService } from '../services/FilesystemService'
import { LoggerService } from '../services/LoggerService'
interface TSCompletionsInVueFile {
blockFile: VueBlockDocument
vueFile: VueSFCDocument
tsFile: TextDocument
fileName: string
cursor: {
original: number
generated: number
template: SearchResult | undefined
setup: number | undefined
}
completions: {
getTs(): Typescript.WithMetadata<Typescript.CompletionInfo> | undefined
getTsx(): Typescript.WithMetadata<Typescript.CompletionInfo> | undefined
getOffset(): Typescript.WithMetadata<Typescript.CompletionInfo> | undefined
getSetup(): Typescript.WithMetadata<Typescript.CompletionInfo> | undefined
}
}
@injectable()
export class CompletionsService {
private readonly logger = LoggerService.getLogger('Completions')
constructor(
@inject(FilesystemService)
private readonly fs: FilesystemService,
@inject(INJECTABLE_TS_SERVICE)
private readonly service: TSLanguageService,
) {}
private readonly ignoreList = new Set('arguments'.split(','))
private getTSCompletionsAtPositionInVueFile(
fileName: string,
position: number,
options: Typescript.GetCompletionsAtPositionOptions | undefined,
): undefined | TSCompletionsInVueFile {
const vueFile = this.fs.getVueFile(fileName)
if (vueFile == null) return
const blockFile = vueFile.getDocAt(position)
if (blockFile == null) return
const tsFile = blockFile.generated
const tsFileName = blockFile.tsFileName
if (tsFile == null || tsFileName == null) return
const offset = blockFile.generatedOffetAt(position)
const template =
blockFile.block.type === 'template' && vueFile.templateAST != null
? findTemplateNodeAt(
vueFile.templateAST,
position - blockFile.block.loc.start.offset,
)
: undefined
const completions = {
getTs: () => {
if (blockFile.tsCompletionsOffset == null) return
this.logger.debug('Loading TS completions')
return this.service.getCompletionsAtPosition(
tsFileName,
blockFile.tsCompletionsOffset,
this.getContextCompletionOptions(options),
)
},
getTsx: () => {
if (blockFile.tsxCompletionsOffset == null) return
this.logger.debug(
'Loading TSX completions: ' +
tsFile
.getText()
.substring(
blockFile.tsxCompletionsOffset - 1,
blockFile.tsxCompletionsOffset + 4,
),
)
return this.service.getCompletionsAtPosition(
tsFileName,
blockFile.tsxCompletionsOffset,
this.getTsxCompletionOptions(options),
)
},
getOffset: () => {
this.logger.debug('Loading offset completions')
return this.service.getCompletionsAtPosition(
tsFileName,
offset,
options,
)
},
getSetup: () => {
this.logger.debug('Loading setup completions')
return this.getScriptSetupCompletions(fileName)
},
} as const
return {
vueFile,
blockFile,
tsFile,
fileName: tsFileName,
cursor: {
original: position - blockFile.block.loc.start.offset,
generated: offset,
template,
setup:
vueFile.descriptor.scriptSetup != null
? (vueFile
.getDoc(vueFile.descriptor.scriptSetup)
?.generated?.getText().length ?? 1) - 1
: undefined,
},
completions,
}
}
private getScriptSetupCompletions(
fileName: string,
): Typescript.WithMetadata<Typescript.CompletionInfo> | undefined {
const vueFile = this.fs.getVueFile(fileName)
if (vueFile == null) return
const scriptSetup = vueFile.descriptor.scriptSetup
if (scriptSetup != null) {
const file = vueFile.getDoc(scriptSetup)
if (file?.tsFileName != null && file.generated != null) {
const position = file.generated.getText().length - 1
return this.service.getCompletionsAtPosition(
file.tsFileName,
position,
{
/* TODO: Put some options */
},
)
}
}
return undefined
}
private getTsxCompletionOptions(
options: Typescript.GetCompletionsAtPositionOptions | undefined,
): Typescript.GetCompletionsAtPositionOptions {
return {
...options,
allowTextChangesInNewFiles: false,
disableSuggestions: false,
includeAutomaticOptionalChainCompletions: true,
includeCompletionsForImportStatements: true,
includeCompletionsForModuleExports: true,
includePackageJsonAutoImports: 'off',
includeCompletionsWithInsertText: true,
includeCompletionsWithSnippetText: true,
providePrefixAndSuffixTextForRename: true,
provideRefactorNotApplicableReason: true,
quotePreference: 'double',
triggerCharacter: '<',
}
}
private getContextCompletionOptions(
options: Typescript.GetCompletionsAtPositionOptions | undefined,
): Typescript.GetCompletionsAtPositionOptions {
return {
...options,
allowTextChangesInNewFiles: false,
disableSuggestions: true,
includeAutomaticOptionalChainCompletions: true,
includeCompletionsForImportStatements: false,
includeCompletionsForModuleExports: false,
includePackageJsonAutoImports: 'off',
triggerCharacter: '.',
}
}
public getCompletionsAtPosition(
fileName: string,
position: number,
options: Typescript.GetCompletionsAtPositionOptions | undefined,
): Typescript.WithMetadata<Typescript.CompletionInfo> | undefined {
this.logger.debug(`Find completions at ${position} in ${fileName}`)
if (this.fs.isVueFile(fileName)) {
const result = this.getTSCompletionsAtPositionInVueFile(
fileName,
position,
options,
)
if (result == null) return
const { cursor, completions } = result
if (cursor.template != null) {
const { node } = cursor.template
if (isSimpleExpressionNode(node) || isInterpolationNode(node)) {
return this.combine(
[
completions.getTs(),
completions.getOffset(),
completions.getSetup(),
].map((info) => this.filterCompletionsInExpression(info)),
)
} else if (isElementNode(node)) {
if (cursor.original <= node.loc.start.offset + node.tag.length + 1) {
return this.combine(
[completions.getTsx()].map((info) =>
this.filterCompletionsInElementTag(info),
),
)
} else {
// Possibly attribute completion
return this.combine(
[completions.getOffset()].map((info) =>
this.filterCompletionsInElementTag(info),
),
)
}
}
const content = result.vueFile.getText()
const charAtCursor = content.substr(position - 1, 1)
const lastTag = content.substring(
content.substr(0, position).lastIndexOf('<'),
position,
)
if (charAtCursor === '<' || /^<[a-z0-9-]+$/i.test(lastTag)) {
return this.combine(
[completions.getTsx()].map((info) =>
this.filterCompletionsInElementTag(info),
),
)
}
return undefined
} else {
return this.combine([completions.getOffset()])
}
} else {
return this.combine([
this.service.getCompletionsAtPosition(fileName, position, options),
])
}
}
public getCompletionEntryDetails(
fileName: string,
position: number,
entryName: string,
formatOptions:
| Typescript.FormatCodeOptions
| Typescript.FormatCodeSettings
| undefined,
source: string | undefined,
preferences: Typescript.UserPreferences | undefined,
data: Typescript.CompletionEntryData | undefined,
): Typescript.CompletionEntryDetails | undefined {
if (this.fs.isVueFile(fileName)) {
this.logger.debug(`Find details: "${entryName}" of "${source ?? ''}"`)
const result = this.getTSCompletionsAtPositionInVueFile(
fileName,
position,
undefined,
)
if (result == null) return
const { blockFile, completions } = result
const fromTS = completions
.getTs()
?.entries.find((entry) =>
this.testCompletionEntry(entry, entryName, source),
)
if (fromTS != null && blockFile.tsCompletionsOffset != null) {
return this.service.getCompletionEntryDetails(
result.fileName,
blockFile.tsCompletionsOffset,
entryName,
formatOptions,
fromTS.source,
preferences,
data,
)
}
const fromTSX = completions
.getTsx()
?.entries.find((entry) =>
this.testCompletionEntry(entry, entryName, source),
)
if (fromTSX != null && blockFile.tsxCompletionsOffset != null) {
return this.service.getCompletionEntryDetails(
result.fileName,
blockFile.tsxCompletionsOffset,
entryName,
formatOptions,
fromTSX.source,
preferences,
data,
)
}
const fromOffset = completions
.getOffset()
?.entries.find((entry) =>
this.testCompletionEntry(entry, entryName, source),
)
if (fromOffset != null) {
return this.service.getCompletionEntryDetails(
result.fileName,
result.cursor.generated,
entryName,
formatOptions,
fromOffset.source,
preferences,
data,
)
}
const fromSetup = completions
.getSetup()
?.entries.find((entry) =>
this.testCompletionEntry(entry, entryName, source),
)
if (
fromSetup != null &&
result.cursor.setup != null &&
result.vueFile.descriptor.scriptSetup != null
) {
const id = result.vueFile.getBlockId(
result.vueFile.descriptor.scriptSetup,
)
return this.service.getCompletionEntryDetails(
id,
result.cursor.setup,
entryName,
formatOptions,
fromSetup.source,
preferences,
data,
)
}
return undefined
} else {
return this.service.getCompletionEntryDetails(
fileName,
position,
entryName,
formatOptions,
source,
preferences,
data,
)
}
}
private testCompletionEntry(
entry: Typescript.CompletionEntry,
entryName: string,
source: string | undefined,
): boolean {
if (entry.name !== entryName) return false
const a = source ?? ''
const b = entry.source ?? ''
return a === b || a === this.fs.getRealFileName(b)
}
private filterCompletionsInExpression(
info: Typescript.WithMetadata<Typescript.CompletionInfo> | undefined,
): Typescript.WithMetadata<Typescript.CompletionInfo> | undefined {
if (info == null) return
info.entries = info.entries.filter((entry) => {
if (entry.name.startsWith('_') || entry.name === '$') return false // Internal properties
if (entry.source == null) {
if (this.ignoreList.has(entry.name)) return false // Global ignore list
}
// Move dollar properties at the bottom
if (entry.name.startsWith('$')) {
entry.sortText = '9:' + entry.sortText
}
return true
})
return info
}
private filterCompletionsInElementTag(
info: Typescript.WithMetadata<Typescript.CompletionInfo> | undefined,
): Typescript.WithMetadata<Typescript.CompletionInfo> | undefined {
if (info == null) return
info.entries = info.entries.filter((entry) => {
if (!isPascalCase(entry.name)) return false
if (entry.source != null) {
if (this.fs.isVueTsFile(entry.source)) {
entry.source = this.fs.getRealFileName(entry.source)
}
if (this.fs.isVueFile(entry.source)) {
entry.sortText = '0:' + entry.sortText
}
}
return true
})
return info
}
private combine(
completions: Array<
Typescript.WithMetadata<Typescript.CompletionInfo> | undefined
>,
): Typescript.WithMetadata<Typescript.CompletionInfo> | undefined {
const onlyValid = completions.filter(isNotNull)
if (onlyValid[0] == null) return
const completion = onlyValid[0]
onlyValid.slice(1).forEach((result) => {
completion.entries.push(...result.entries)
})
const ids = new Set<string>()
completion.entries = completion.entries.filter((entry) => {
// Check virtuals.
if (entry.source != null) {
if (this.fs.isVueVirtualFile(entry.source)) {
return false
}
}
// Check duplicates.
const id = this.getCompletionEntryId(entry)
if (ids.has(id)) return false
ids.add(id)
return true
})
completion.entries.forEach((entry) => {
if (entry.source != null) {
if (
this.fs.isVueVirtualFile(entry.source) ||
this.fs.isVueTsFile(entry.source)
) {
entry.source = this.fs.getRealFileName(entry.source)
}
}
})
return completion
}
private getCompletionEntryId(entry: Typescript.CompletionEntry): string {
return JSON.stringify({
source: entry.source,
name: entry.name,
})
}
} | the_stack |
import { LitElement, css, html, TemplateResult } from 'lit';
import { customElement, state } from 'lit/decorators.js';
import { localeStrings } from '../../locales';
import '../components/app-header';
import '../components/app-file-input';
import { FileInputDetails, Lazy } from '../utils/interfaces';
import {
fastButtonCss,
fastCheckboxCss,
fastNumberFieldCss,
fastRadioCss,
} from '../utils/css/fast-elements';
interface PlatformInformation {
label: string;
value: string;
}
interface ImageGeneratorServicePostResponse {
Message: string;
Uri: string;
}
interface ImageGenerateServiceGetResponse {
Message: string;
}
type ColorRadioValues = 'best guess' | 'transparent' | 'custom';
const loc = localeStrings.imageGenerator;
const platformsData: Array<PlatformInformation> = [
{ label: loc.windows11, value: 'windows11' },
{ label: loc.android, value: 'android' },
{ label: loc.ios, value: 'ios' }
];
const baseUrl = 'https://appimagegenerator-prod.azurewebsites.net';
function boolListHasChanged<T>(value: T, unknownValue: T): boolean {
if (!value || !unknownValue) {
return false;
}
return (value as Object).toString() === (unknownValue as Object).toString();
}
@customElement('image-generator')
export class ImageGenerator extends LitElement {
@state({ hasChanged: boolListHasChanged })
platformSelected: Array<boolean> = platformsData.map(() => true);
@state() files: Lazy<FileList>;
@state() padding = 0.3;
@state() colorOption: ColorRadioValues = 'transparent';
// hex color
@state() color: string = '#ffffff';
@state() selectAllState = false;
@state() generating = false;
@state() generateEnabled = false;
@state() error: Lazy<string>;
static get styles() {
return [
fastButtonCss,
fastCheckboxCss,
fastRadioCss,
fastNumberFieldCss,
css`
:host {
--loader-size: 1.8em;
}
h1 {
font-size: var(--xlarge-font-size);
line-height: 48px;
letter-spacing: -0.015em;
margin: 0;
}
h2 {
font-size: var(--large-font-size);
}
h3 {
font-size: var(--medium-font-size);
}
p {
font-size: var(--font-size);
}
small {
display: block;
font-size: 10px;
}
fast-card {
--background-color: var(--secondary-color);
padding: 16px;
}
fast-button {
height: 24px;
padding: 8px 0;
}
fast-progress-ring {
height: var(--loader-size);
width: var(--loader-size);
--accent-foreground-rest: var(--secondary-color);
--accent-foreground-rest: var(--primary-color);
--neutral-fill-rest: white;
--neutral-fill-active: white;
--neutral-fill-hover: white;
}
fast-button::part(content) {
margin: 0 16px;
}
#submit {
margin-top: 8px;
}
fast-button#generateButton,
fast-button#downloadButton {
--neutral-foreground-rest: var(--secondary-color);
--button-font-color: var(--secondary-color);
}
.background {
background-color: var(--primary-color);
color: var(--primary-color);
}
.main {
padding: 32px;
}
`,
];
}
constructor() {
super();
}
render() {
return html`
<div>
<app-header></app-header>
<main id="main" role="presentation" class="main background">
<fast-card>
<h1>${loc.image_generator}</h1>
<p>${loc.image_generator_text}</p>
<form id="imageFileInputForm" enctype="multipart/form-data" role="form" class="form">
<section class="form-left">
<div class="image-section">
<h3>${loc.input_image}</h3>
<p>${loc.input_image_help}</p>
<app-file-input @input-change=${this.handleInputChange}></app-file-input>
</div>
<div class="padding-section">
<h3>${loc.padding}</h3>
<fast-number-field name="padding" max="1" min="0" step="0.1" .value=${this.padding}
@change=${this.handlePaddingChange} required></fast-number-field>
<small>${loc.padding_text}</small>
</div>
<div class="color-section">
<h3>${loc.background_color}</h3>
<div class="color-radio">
<fast-radio-group orientation="vertical" .value=${this.colorOption}
@change=${this.handleBackgroundRadioChange}>
<fast-radio name="colorOption" value="best guess">
${loc.best_guess}
</fast-radio>
<fast-radio name="colorOption" value="transparent">
${loc.transparent}
</fast-radio>
<fast-radio name="colorOption" value="custom">
${loc.custom_color}
</fast-radio>
</fast-radio-group>
</div>
${this.renderColorPicker()}
</div>
</section>
<section class="form-right platforms-section">
<h4>${loc.platforms}</h4>
<p>${loc.platforms_text}</p>
<div role="group" class="platform-list">
${this.renderPlatformList()}
</div>
</section>
<section id="submit" class="form-bottom">
<fast-button id="generateButton" class="primary" ?disabled=${!this.generateEnabled || this.generating}
@click=${this.generateZip}>
${this.generating
? html`<fast-progress-ring></fast-progress-ring>`
: localeStrings.button.generate}
</fast-button>
${this.renderError()}
</section>
</form>
</fast-card>
</main>
</div>
`;
}
renderPlatformList() {
return platformsData.map(
(platform, i) => html`
<fast-checkbox type="checkbox" name="platform" value="${platform.value}" ?checked=${this.platformSelected[i]}
@change=${this.handleCheckbox} data-index=${i}>
${platform.label}
</fast-checkbox>
`
);
}
renderColorPicker() {
if (this.colorOption === 'custom') {
return html`<div class="custom-color-block">
<label for="theme-custom-color">${localeStrings.values.custom}</label>
<input type="color" id="theme-custom-color" name="color" .value=${this.color}
@change=${this.handleThemeColorInputChange} />
</div>`;
}
return undefined;
}
renderError(): TemplateResult {
if (this.error) {
return html`<p style="font-size: 16px; color: red;">${this.error}</p>`;
}
return html``;
}
handleInputChange(event: CustomEvent<FileInputDetails>) {
const input = event.detail.input;
if (input.files) {
this.files = input.files;
}
this.checkGenerateEnabled();
}
handlePaddingChange(event: Event) {
const input = event.target as HTMLInputElement;
this.padding = Number(input.value);
}
handleCheckbox(event: Event) {
const input = event.target as HTMLInputElement;
const index = input.dataset['index'];
this.platformSelected[index as any] = input.checked;
this.checkGenerateEnabled();
}
handleBackgroundRadioChange(event: CustomEvent) {
const value: ColorRadioValues = (<HTMLInputElement>event.target)
.value as ColorRadioValues;
this.colorOption = value;
this.checkGenerateEnabled();
}
handleThemeColorInputChange(event: Event) {
const input = event.target as HTMLInputElement;
this.color = input.value;
this.checkGenerateEnabled();
}
async generateZip() {
const file = this.files ? this.files[0] : null;
if (!file) {
const errorMessage = 'No file available to generate zip';
console.error(errorMessage);
this.error = errorMessage;
return;
}
try {
this.generateEnabled = false;
this.generating = true;
const form = new FormData();
const colorValue =
this.colorOption === 'custom' ? this.color : // custom? Then send in the chosen color
this.colorOption === 'best guess' ? '' : // best guess? Then send in an empty string, which the API interprets as best guess
'transparent'; // otherwise, it must be transparent
form.append('fileName', file as Blob);
form.append('padding', String(this.padding));
form.append('color', colorValue);
platformsData
.filter((_, index) => this.platformSelected[index])
.forEach(data => form.append('platform', data.value));
const res = await fetch(`${baseUrl}/api/image`, {
method: 'POST',
body: form,
});
const postRes =
(await res.json()) as unknown as ImageGeneratorServicePostResponse;
if (postRes.Message) {
throw new Error('Error from service: ' + postRes.Message);
}
this.downloadZip(`${baseUrl}${postRes.Uri}`);
} catch (e) {
console.error(e);
this.error = (e as Error).message;
} finally {
this.generating = false;
this.generateEnabled = true;
}
}
downloadZip(zipUrl: string) {
const hyperlink = document.createElement("a");
hyperlink.href = zipUrl;
hyperlink.download = "";
hyperlink.click();
}
checkGenerateEnabled() {
this.generateEnabled =
this.files !== undefined &&
this.platformSelected.reduce((a, b) => a || b);
return this.generateEnabled;
}
} | the_stack |
import * as React from 'react';
import { RateTableGrpc, RateTableHttp } from '../../components/SummaryPanel/RateTable';
import { RequestChart, StreamChart } from '../../components/SummaryPanel/RpsChart';
import { ResponseTimeChart, ResponseTimeUnit } from '../../components/SummaryPanel/ResponseTimeChart';
import {
GraphType,
NodeType,
Protocol,
SummaryPanelPropType,
DecoratedGraphNodeData,
UNKNOWN,
TrafficRate
} from '../../types/Graph';
import { renderBadgedLink } from './SummaryLink';
import {
shouldRefreshData,
getDatapoints,
getNodeMetrics,
getNodeMetricType,
hr,
renderNoTraffic,
NodeMetricType,
summaryHeader,
summaryBodyTabs,
summaryPanel,
summaryFont
} from './SummaryPanelCommon';
import { Metric, Datapoint, IstioMetricsMap, Labels } from '../../types/Metrics';
import { Response } from '../../services/Api';
import { CancelablePromise, makeCancelablePromise } from '../../utils/CancelablePromises';
import { decoratedEdgeData, decoratedNodeData } from '../../components/CytoscapeGraph/CytoscapeGraphUtils';
import { ResponseFlagsTable } from 'components/SummaryPanel/ResponseFlagsTable';
import { ResponseHostsTable } from 'components/SummaryPanel/ResponseHostsTable';
import { KialiIcon } from 'config/KialiIcon';
import { Tab, Tooltip } from '@patternfly/react-core';
import SimpleTabs from 'components/Tab/SimpleTabs';
import { Direction } from 'types/MetricsOptions';
import { style } from 'typestyle';
type SummaryPanelEdgeMetricsState = {
rates: Datapoint[];
errRates: Datapoint[];
rtAvg: Datapoint[];
rtMed: Datapoint[];
rt95: Datapoint[];
rt99: Datapoint[];
sent: Datapoint[];
received: Datapoint[];
unit: ResponseTimeUnit;
};
type SummaryPanelEdgeState = SummaryPanelEdgeMetricsState & {
edge: any;
loading: boolean;
metricsLoadError: string | null;
};
const defaultMetricsState: SummaryPanelEdgeMetricsState = {
rates: [],
errRates: [],
rtAvg: [],
rtMed: [],
rt95: [],
rt99: [],
sent: [],
received: [],
unit: 'ms'
};
const defaultState: SummaryPanelEdgeState = {
edge: null,
loading: false,
metricsLoadError: null,
...defaultMetricsState
};
const principalStyle = style({
display: 'inline-block',
overflow: 'hidden',
textOverflow: 'ellipsis',
width: '100%',
whiteSpace: 'nowrap'
});
export default class SummaryPanelEdge extends React.Component<SummaryPanelPropType, SummaryPanelEdgeState> {
private metricsPromise?: CancelablePromise<Response<IstioMetricsMap>>;
private readonly mainDivRef: React.RefObject<HTMLDivElement>;
constructor(props: SummaryPanelPropType) {
super(props);
this.state = { ...defaultState };
this.mainDivRef = React.createRef<HTMLDivElement>();
}
static getDerivedStateFromProps(props: SummaryPanelPropType, state: SummaryPanelEdgeState) {
// if the summaryTarget (i.e. selected edge) has changed, then init the state and set to loading. The loading
// will actually be kicked off after the render (in componentDidMount/Update).
return props.data.summaryTarget !== state.edge
? { edge: props.data.summaryTarget, loading: true, ...defaultMetricsState }
: null;
}
componentDidMount() {
this.updateCharts(this.props);
}
componentDidUpdate(prevProps: SummaryPanelPropType) {
if (prevProps.data.summaryTarget !== this.props.data.summaryTarget) {
if (this.mainDivRef.current) {
this.mainDivRef.current.scrollTop = 0;
}
}
if (shouldRefreshData(prevProps, this.props)) {
this.updateCharts(this.props);
}
}
componentWillUnmount() {
if (this.metricsPromise) {
this.metricsPromise.cancel();
}
}
render() {
const target = this.props.data.summaryTarget;
const source = decoratedNodeData(target.source());
const dest = decoratedNodeData(target.target());
const edge = decoratedEdgeData(target);
const mTLSPercentage = edge.isMTLS;
const isMtls = mTLSPercentage && mTLSPercentage > 0;
const hasPrincipals = !!edge.sourcePrincipal || !!edge.destPrincipal;
const hasSecurity = isMtls || hasPrincipals;
const protocol = edge.protocol;
const isGrpc = protocol === Protocol.GRPC;
const isHttp = protocol === Protocol.HTTP;
const isTcp = protocol === Protocol.TCP;
const isRequests = isHttp || (isGrpc && this.props.trafficRates.includes(TrafficRate.GRPC_REQUEST));
const SecurityBlock = () => {
return (
<div className="panel-heading" style={summaryHeader}>
{isMtls && this.renderMTLSSummary(mTLSPercentage)}
{hasPrincipals && (
<>
<div style={{ padding: '5px 0 2px 0' }}>
<strong>Principals:</strong>
</div>
<Tooltip key="tt_src_ppl" position="top" content={`Source principal: ${edge.sourcePrincipal}`}>
<span className={principalStyle}>{edge.sourcePrincipal || 'unknown'}</span>
</Tooltip>
<Tooltip key="tt_src_ppl" position="top" content={`Destination principal: ${edge.destPrincipal}`}>
<span className={principalStyle}>{edge.destPrincipal || 'unknown'}</span>
</Tooltip>
</>
)}
</div>
);
};
return (
<div ref={this.mainDivRef} className={`panel panel-default ${summaryPanel}`}>
<div className="panel-heading" style={summaryHeader}>
{renderBadgedLink(source, undefined, 'From: ')}
{renderBadgedLink(dest, undefined, 'To: ')}
</div>
{hasSecurity && <SecurityBlock />}
{(isHttp || isGrpc) && (
<div className={summaryBodyTabs}>
<SimpleTabs id="edge_summary_rate_tabs" defaultTab={0} style={{ paddingBottom: '10px' }}>
<Tab style={summaryFont} title="Traffic" eventKey={0}>
<div style={summaryFont}>
{isGrpc && (
<>
<RateTableGrpc
isRequests={isRequests}
rate={this.safeRate(edge.grpc)}
rateGrpcErr={this.safeRate(edge.grpcErr)}
rateNR={this.safeRate(edge.grpcNoResponse)}
/>
</>
)}
{isHttp && (
<>
<RateTableHttp
title="HTTP requests per second:"
rate={this.safeRate(edge.http)}
rate3xx={this.safeRate(edge.http3xx)}
rate4xx={this.safeRate(edge.http4xx)}
rate5xx={this.safeRate(edge.http5xx)}
rateNR={this.safeRate(edge.httpNoResponse)}
/>
</>
)}
</div>
</Tab>
{isRequests && (
<Tab style={summaryFont} title="Flags" eventKey={1}>
<div style={summaryFont}>
<ResponseFlagsTable
title={'Response flags by ' + (isGrpc ? 'GRPC code:' : 'HTTP code:')}
responses={edge.responses}
/>
</div>
</Tab>
)}
<Tab style={summaryFont} title="Hosts" eventKey={2}>
<div style={summaryFont}>
<ResponseHostsTable
title={'Hosts by ' + (isGrpc ? 'GRPC code:' : 'HTTP code:')}
responses={edge.responses}
/>
</div>
</Tab>
</SimpleTabs>
{hr()}
{this.renderCharts(target, isGrpc, isHttp, isTcp, isRequests)}
</div>
)}
{isTcp && (
<div className={summaryBodyTabs}>
<SimpleTabs id="edge_summary_flag_hosts_tabs" defaultTab={0} style={{ paddingBottom: '10px' }}>
<Tab style={summaryFont} eventKey={0} title="Flags">
<div style={summaryFont}>
<ResponseFlagsTable title="Response flags by code:" responses={edge.responses} />
</div>
</Tab>
<Tab style={summaryFont} eventKey={1} title="Hosts">
<div style={summaryFont}>
<ResponseHostsTable title="Hosts by code:" responses={edge.responses} />
</div>
</Tab>
</SimpleTabs>
{hr()}
{this.renderCharts(target, isGrpc, isHttp, isTcp, isRequests)}
</div>
)}
{!isGrpc && !isHttp && !isTcp && <div className="panel-body">{renderNoTraffic()}</div>}
</div>
);
}
private getByLabels = (sourceMetricType: NodeMetricType, destMetricType: NodeMetricType) => {
let label: string;
switch (sourceMetricType) {
case NodeMetricType.AGGREGATE:
switch (destMetricType) {
case NodeMetricType.APP:
label = 'destination_app';
break;
case NodeMetricType.SERVICE:
label = 'destination_service_name';
break;
case NodeMetricType.WORKLOAD:
// fall through, workload is default
default:
label = 'destination_workload';
break;
}
break;
case NodeMetricType.APP:
label = 'source_app';
break;
case NodeMetricType.SERVICE:
label = 'destination_service_name';
break;
case NodeMetricType.WORKLOAD:
// fall through, workload is default
default:
label = 'source_workload';
break;
}
// For special service dest nodes we want to narrow the data to only TS with 'unknown' workloads (see the related
// comparator in getNodeDatapoints).
return this.isSpecialServiceDest(destMetricType) ? [label, 'destination_workload'] : [label];
};
private getNodeDataPoints = (
m: Metric[] | undefined,
sourceMetricType: NodeMetricType,
destMetricType: NodeMetricType,
data: DecoratedGraphNodeData,
isServiceEntry: boolean
) => {
if (isServiceEntry) {
// For service entries, metrics are grouped by destination_service_name and we need to match it per "data.destServices"
return getDatapoints(m, (labels: Labels) => {
return data.destServices
? data.destServices.some(svc => svc.name === labels['destination_service_name'])
: false;
});
}
let label: string;
let value: string | undefined;
switch (sourceMetricType) {
case NodeMetricType.AGGREGATE:
switch (destMetricType) {
case NodeMetricType.APP:
label = 'destination_app';
value = data.app;
break;
case NodeMetricType.SERVICE:
label = 'destination_service_name';
value = data.service;
break;
case NodeMetricType.WORKLOAD:
// fall through, workload is default
default:
label = 'destination_workload';
value = data.workload;
break;
}
break;
case NodeMetricType.APP:
label = 'source_app';
value = data.app;
break;
case NodeMetricType.SERVICE:
label = 'destination_service_name';
value = data.service;
break;
case NodeMetricType.WORKLOAD:
// fall through, use workload as the default
default:
label = 'source_workload';
value = data.workload;
}
const comparator = this.isSpecialServiceDest(destMetricType)
? (labels: Labels) => labels[label] === value && labels.destination_workload === UNKNOWN
: (labels: Labels) => labels[label] === value;
return getDatapoints(m, comparator);
};
private updateCharts = (props: SummaryPanelPropType) => {
const edge = props.data.summaryTarget;
const edgeData = decoratedEdgeData(edge);
const sourceData = decoratedNodeData(edge.source());
const destData = decoratedNodeData(edge.target());
const sourceMetricType = getNodeMetricType(sourceData);
const destMetricType = getNodeMetricType(destData);
const protocol = edgeData.protocol;
const isGrpc = protocol === Protocol.GRPC;
const isHttp = protocol === Protocol.HTTP;
const isTcp = protocol === Protocol.TCP;
const isRequests = isHttp || (isGrpc && this.props.trafficRates.includes(TrafficRate.GRPC_REQUEST));
if (this.metricsPromise) {
this.metricsPromise.cancel();
this.metricsPromise = undefined;
}
// Just return if the metric types are unset, there is no data, destination node is "unknown" or charts are unsupported
if (
!destMetricType ||
!sourceMetricType ||
!this.hasSupportedCharts(edge) ||
(!isGrpc && !isHttp && !isTcp) ||
destData.isInaccessible
) {
this.setState({
loading: false
});
return;
}
// use dest node metrics unless dest is a serviceEntry or source is an aggregate
const isSourceAggregate = sourceData.nodeType === NodeType.AGGREGATE;
const isDestServiceEntry = !!destData.isServiceEntry;
const useDestMetrics = isDestServiceEntry || isSourceAggregate ? false : true;
const metricsNode = useDestMetrics ? edge.target() : edge.source();
const metricsNodeData = useDestMetrics ? destData : sourceData;
const direction: Direction = useDestMetrics || isSourceAggregate ? 'inbound' : 'outbound';
const metricType = useDestMetrics ? destMetricType : sourceMetricType;
const byLabels = isDestServiceEntry
? ['destination_service_name']
: this.getByLabels(sourceMetricType, destMetricType);
const otherEndData = useDestMetrics ? sourceData : destData;
const quantiles = ['0.5', '0.95', '0.99'];
let promiseRequests, promiseStream;
if (isHttp || (isGrpc && isRequests)) {
const reporterRps =
[NodeType.SERVICE, NodeType.UNKNOWN].includes(sourceData.nodeType) ||
NodeType.AGGREGATE === metricsNodeData.nodeType ||
edge.source().isIstio ||
edge.target().isIstio
? 'destination'
: 'source';
const filtersRps = ['request_count', 'request_duration_millis', 'request_error_count'];
promiseRequests = getNodeMetrics(
metricType,
metricsNode,
props,
filtersRps,
direction,
reporterRps,
protocol,
quantiles,
byLabels
);
} else if (isGrpc) {
// gRPC messages uses slightly different reporting
const reporter =
[NodeType.AGGREGATE, NodeType.UNKNOWN].includes(sourceData.nodeType) || sourceData.isIstio
? 'destination'
: 'source';
const filters = ['grpc_sent', 'grpc_received'];
promiseStream = getNodeMetrics(
metricType,
metricsNode,
props,
filters,
direction,
reporter,
undefined, // streams (tcp, grpc-messages) use dedicated metrics (i.e. no request_protocol label)
quantiles,
byLabels
);
} else {
// TCP uses slightly different reporting
const reporterTCP =
[NodeType.AGGREGATE, NodeType.UNKNOWN].includes(sourceData.nodeType) || sourceData.isIstio
? 'destination'
: 'source';
const filtersTCP = ['tcp_sent', 'tcp_received'];
promiseStream = getNodeMetrics(
metricType,
metricsNode,
props,
filtersTCP,
direction,
reporterTCP,
undefined, // streams (tcp, grpc-messages) use dedicated metrics (i.e. no request_protocol label)
quantiles,
byLabels
);
}
this.metricsPromise = makeCancelablePromise(promiseRequests ? promiseRequests : promiseStream);
this.metricsPromise.promise
.then(response => {
const metrics = response.data;
let { rates: reqRates, errRates, rtAvg, rtMed, rt95, rt99, sent, received, unit } = defaultMetricsState;
if (isHttp || (isGrpc && isRequests)) {
reqRates = this.getNodeDataPoints(
metrics.request_count,
sourceMetricType,
destMetricType,
otherEndData,
isDestServiceEntry
);
errRates = this.getNodeDataPoints(
metrics.request_error_count,
sourceMetricType,
destMetricType,
otherEndData,
isDestServiceEntry
);
const duration = metrics.request_duration_millis || [];
rtAvg = this.getNodeDataPoints(
duration.filter(m => m.stat === 'avg'),
sourceMetricType,
destMetricType,
otherEndData,
isDestServiceEntry
);
rtMed = this.getNodeDataPoints(
duration.filter(m => m.stat === '0.5'),
sourceMetricType,
destMetricType,
otherEndData,
isDestServiceEntry
);
rt95 = this.getNodeDataPoints(
duration.filter(m => m.stat === '0.95'),
sourceMetricType,
destMetricType,
otherEndData,
isDestServiceEntry
);
rt99 = this.getNodeDataPoints(
duration.filter(m => m.stat === '0.99'),
sourceMetricType,
destMetricType,
otherEndData,
isDestServiceEntry
);
} else {
// TCP or gRPC stream
sent = this.getNodeDataPoints(
isTcp ? metrics.tcp_sent : metrics.grpc_sent,
sourceMetricType,
destMetricType,
otherEndData,
isDestServiceEntry
);
received = this.getNodeDataPoints(
isTcp ? metrics.tcp_received : metrics.grpc_received,
sourceMetricType,
destMetricType,
otherEndData,
isDestServiceEntry
);
}
this.setState({
loading: false,
rates: reqRates,
errRates: errRates,
rtAvg: rtAvg,
rtMed: rtMed,
rt95: rt95,
rt99: rt99,
sent: sent,
received: received,
unit: unit
});
})
.catch(error => {
if (error.isCanceled) {
console.debug('SummaryPanelEdge: Ignore fetch error (canceled).');
return;
}
const errorMsg = error.response && error.response.data.error ? error.response.data.error : error.message;
this.setState({
loading: false,
metricsLoadError: errorMsg,
...defaultMetricsState
});
});
this.setState({ loading: true, metricsLoadError: null });
};
private safeRate = (s: any) => {
return isNaN(s) ? 0.0 : Number(s);
};
private renderCharts = (edge, isGrpc, isHttp, isTcp, isRequests) => {
if (!this.hasSupportedCharts(edge)) {
return isGrpc || isHttp ? (
<>
<KialiIcon.Info /> Service graphs do not support service-to-service aggregate sparklines. See the chart above
for aggregate traffic or use the workload graph type to observe individual workload-to-service edge
sparklines.
</>
) : (
<>
<KialiIcon.Info /> Service graphs do not support service-to-service aggregate sparklines. Use the workload
graph type to observe individual workload-to-service edge sparklines.
</>
);
}
const target = decoratedNodeData(edge.target());
if (target.isInaccessible) {
return (
<>
<KialiIcon.Info /> Sparkline charts cannot be shown because the destination is inaccessible.
</>
);
}
if (this.state.loading) {
return <strong>Loading charts...</strong>;
}
if (this.state.metricsLoadError) {
return (
<div>
<KialiIcon.Warning /> <strong>Error loading metrics: </strong>
{this.state.metricsLoadError}
</div>
);
}
let requestChart, streamChart;
if (isGrpc || isHttp) {
if (isRequests) {
const labelRps = isGrpc ? 'gRPC Request Traffic' : 'HTTP Request Traffic';
const labelRt = isGrpc ? 'gRPC Request Response Time (ms)' : 'HTTP Request Response Time (ms)';
requestChart = (
<>
<RequestChart label={labelRps} dataRps={this.state.rates!} dataErrors={this.state.errRates} />
{hr()}
<ResponseTimeChart
label={labelRt}
rtAvg={this.state.rtAvg}
rtMed={this.state.rtMed}
rt95={this.state.rt95}
rt99={this.state.rt99}
unit={this.state.unit}
/>
</>
);
} else {
// assume gRPC messages, it's the only option other than requests
requestChart = (
<>
<StreamChart
label="gRPC Message Traffic"
sentRates={this.state.sent!}
receivedRates={this.state.received}
unit="messages"
/>
</>
);
}
} else if (isTcp) {
streamChart = (
<StreamChart label="TCP Traffic" sentRates={this.state.sent} receivedRates={this.state.received} unit="bytes" />
);
}
return (
<>
{requestChart}
{streamChart}
</>
);
};
private hasSupportedCharts = edge => {
const sourceData = decoratedNodeData(edge.source());
const destData = decoratedNodeData(edge.target());
const sourceMetricType = getNodeMetricType(sourceData);
const destMetricType = getNodeMetricType(destData);
// service-to-service edges are unsupported because they represent aggregations (of multiple workload to service edges)
const chartsSupported = sourceMetricType !== NodeMetricType.SERVICE || destMetricType !== NodeMetricType.SERVICE;
return chartsSupported;
};
// We need to handle the special case of a dest service node showing client failures. These service nodes show up in
// non-service graphs, even when not injecting service nodes.
private isSpecialServiceDest(destMetricType: NodeMetricType) {
return (
destMetricType === NodeMetricType.SERVICE &&
!this.props.injectServiceNodes &&
this.props.graphType !== GraphType.SERVICE
);
}
private renderMTLSSummary = (mTLSPercentage: number) => {
let mtls = 'mTLS Enabled';
const isMtls = mTLSPercentage > 0;
if (isMtls && mTLSPercentage < 100.0) {
mtls = `${mtls} [${mTLSPercentage}% of request traffic]`;
}
return (
<>
{isMtls && (
<div>
<KialiIcon.MtlsLock />
<span style={{ paddingLeft: '6px' }}>{mtls}</span>
</div>
)}
</>
);
};
} | the_stack |
import crypto from 'crypto'
import fs from 'fs'
import Bot from '../lib'
import config from './tests.config'
import {timeout} from '../lib/utils'
import {pollFor} from './test-utils'
import {promisify} from 'util'
import {TopicType, ChatChannel, MsgSummary, BotCommandsAdvertisementTyp} from '../lib/types/chat1'
import {OnMessage, ReadResult} from '../lib/chat-client'
// HACK:
// typescript does not believe certain scenarios could be mutated
// see for example: https://github.com/Microsoft/TypeScript/issues/12176
// This is easy solution for the timeout check
const coerceMsgSummary = (m: MsgSummary | null): MsgSummary => (m as unknown) as MsgSummary
test('Chat methods with an uninitialized bot', (): void => {
const alice1 = new Bot()
const channel = {name: `${config.bots.alice1.username},${config.bots.bob1.username}`}
const message = {body: 'Testing!'}
// @ts-ignore because it intentionally has bad arguments
expect(alice1.chat.list()).rejects.toThrowError()
// @ts-ignore because it intentionally has bad arguments
expect(alice1.chat.read()).rejects.toThrowError()
// @ts-ignore because it intentionally has bad arguments
expect(alice1.chat.send(channel, message)).rejects.toThrowError()
// @ts-ignore because it intentionally has bad arguments
expect(alice1.chat.delete(channel, 314)).rejects.toThrowError()
})
describe('Chat Methods', (): void => {
const alice1 = new Bot()
const alice2 = new Bot()
const bob = new Bot()
const channel: ChatChannel = {name: `${config.bots.alice1.username},${config.bots.bob1.username}`}
const teamChannel: ChatChannel = {
name: config.teams.acme.teamname,
public: false,
topicType: 'chat',
membersType: 'team',
topicName: 'general',
}
const message = {body: 'Test message!'}
const invalidChannel = {name: 'kbot,'}
const invalidMessage = {bdy: 'blah'}
const channelMatcher = expect.objectContaining({
name: expect.any(String),
membersType: expect.any(String),
})
const conversationMatcher = expect.objectContaining({
id: expect.any(String),
channel: channelMatcher,
unread: expect.any(Boolean),
activeAt: expect.any(Number),
activeAtMs: expect.any(Number),
memberStatus: expect.any(String),
})
const messageMatcher = expect.objectContaining({
id: expect.any(Number),
channel: channelMatcher,
sender: expect.objectContaining({
deviceId: expect.any(String),
uid: expect.any(String),
}),
sentAt: expect.any(Number),
sentAtMs: expect.any(Number),
content: expect.objectContaining({
type: expect.any(String),
}),
unread: expect.any(Boolean),
})
beforeAll(
async (): Promise<void> => {
await alice1.init(config.bots.alice1.username, config.bots.alice1.paperkey)
await alice2.init(config.bots.alice2.username, config.bots.alice2.paperkey)
await bob.init(config.bots.bob1.username, config.bots.bob1.paperkey)
}
)
afterAll(
async (): Promise<void> => {
await alice1.deinit()
await alice2.deinit()
await bob.deinit()
}
)
it('watchForNewConversation', async (): Promise<void> => {
try {
await alice1.team.removeMember({team: config.teams.alicesPlayground.teamname, username: config.bots.bob1.username})
} catch (err) {
console.log('Caught err on removing existing membership')
} finally {
// We seem to need to track this because otherwise it'll pick up ones in later tests
let seenOneYet = false
const toWait = new Promise(async (resolve, reject) => {
await bob.chat.watchForNewConversation(
conv => {
if (!seenOneYet) {
seenOneYet = true
expect(conv.channel.name).toBe(config.teams.alicesPlayground.teamname)
expect(conv.channel.topicName).toBe('general')
resolve()
}
},
err => reject(err)
)
})
await alice1.team.addMembers({
team: config.teams.alicesPlayground.teamname,
usernames: [{username: config.bots.bob1.username, role: 'writer'}],
})
await toWait
}
})
describe('Chat list', (): void => {
it('Returns all chat conversations in an array', async (): Promise<void> => {
const conversations = await alice1.chat.list()
expect(Array.isArray(conversations)).toBe(true)
for (const conversation of conversations) {
expect(conversation).toEqual(conversationMatcher)
}
})
it('Lists only unread conversations if given the option', async (): Promise<void> => {
await bob.chat.send(channel, message)
await timeout(500)
const conversations = await alice1.chat.list({unreadOnly: true})
for (const conversation of conversations) {
expect(conversation).toHaveProperty('unread', true)
}
})
it('Shows only messages of a specific topic type if given the option', async (): Promise<void> => {
const conversations = await alice1.chat.list({topicType: TopicType.DEV})
for (const conversation of conversations) {
expect(conversation.channel).toHaveProperty('topicType', 'dev')
}
})
})
describe('Chat read', (): void => {
it('Retrieves all messages in a conversation', async (): Promise<void> => {
const result = await alice1.chat.read(channel)
expect(Array.isArray(result.messages)).toBe(true)
for (const message of result.messages) {
expect(message).toEqual(messageMatcher)
}
})
it('Shows only unread messages if given the option', async (): Promise<void> => {
await bob.chat.send(channel, message)
const result = await alice1.chat.read(channel, {unreadOnly: true})
expect(Array.isArray(result.messages)).toBe(true)
for (const message of result.messages) {
expect(message).toHaveProperty('unread', true)
}
})
it("Doesn't mark messages read on peek", async (): Promise<void> => {
// No peeking: message should be unread on first read, and read on subsequent reads
let result = await alice1.chat.read(channel)
await bob.chat.send(channel, message)
result = await alice1.chat.read(channel)
expect(result.messages[0]).toHaveProperty('unread', true)
result = await alice1.chat.read(channel)
expect(result.messages[0]).toHaveProperty('unread', false)
// Now let's peek. Messages should remain unread on subsequent reads.
await bob.chat.send(channel, message)
result = await alice1.chat.read(channel, {peek: true})
expect(result.messages[0]).toHaveProperty('unread', true)
result = await alice1.chat.read(channel)
expect(result.messages[0]).toHaveProperty('unread', true)
})
it('Allows a user to properly paginate over the messages', async (): Promise<void> => {
// Mark all messages as read
await alice1.chat.read(channel)
// Prepare some new messages
const expectedCount = 10
for (let i = 0; i < expectedCount; i++) {
await bob.chat.send(channel, message)
}
// Run the pagination with peek and unreadOnly enabled, expecting 10 msgs
let totalCount = 0
let lastPagination
while (true) {
const result: ReadResult = await alice1.chat.read(channel, {
peek: true,
unreadOnly: true,
pagination: {
num: 1,
next: lastPagination ? lastPagination.next : undefined,
},
})
totalCount += result.messages.length
if (totalCount >= expectedCount) {
break
}
lastPagination = result.pagination
}
expect(totalCount).toEqual(10)
})
it('Throws an error if given an invalid channel', async (): Promise<void> => {
expect(alice1.chat.read(invalidChannel)).rejects.toThrowError()
})
})
describe('Chat send', (): void => {
it('Sends a message to a certain channel and returns an empty promise', async (): Promise<void> => {
await alice1.chat.send(channel, message)
const result = await alice1.chat.read(channel, {peek: true})
expect(result.messages[0].sender.username).toEqual(alice1.myInfo()?.username)
if (result.messages[0].content.type === 'text') {
expect(result.messages[0].content.text?.body).toEqual(message.body)
} else {
expect(false).toBe(true)
}
})
it('Throws an error if given an invalid channel', async (): Promise<void> => {
expect(alice1.chat.send(invalidChannel, message)).rejects.toThrowError()
})
it('Throws an error if given an invalid message', async (): Promise<void> => {
// @ts-ignore intentionally bad formatted message
expect(alice1.chat.send(channel, invalidMessage)).rejects.toThrowError()
})
})
describe('Gets messages in correct channels', (): void => {
it(`Can act read/post in different channels concurrently`, async (): Promise<void> => {
const channels: ChatChannel[] = [
{
name: config.teams.acme.teamname,
topicName: 'general',
membersType: 'team',
},
{
name: config.teams.acme.teamname,
topicName: 'singularitarians',
membersType: 'team',
},
{name: `${config.bots.alice1.username},${config.bots.bob1.username}`},
]
const okChecks: boolean[] = []
for (const channel of channels) {
if (channel.topicName && channel.topicName !== 'general') {
try {
await alice1.chat.createChannel(channel)
} catch (err) {
/* may already be made */
}
await bob.chat.joinChannel(channel)
}
}
await timeout(1000)
// concurrently watch and send to all of them
for (const i in channels) {
const channel = channels[i]
bob.chat.watchChannelForNewMessages(channel, (message): void => {
if (message.content.type !== 'text') {
throw new Error('Expected text type')
}
if (message.content.text?.body === `c${i} test`) {
if (okChecks[i]) {
throw new Error('Uh oh, duplicate! ' + JSON.stringify(message))
}
okChecks[i] = true
} else {
throw new Error('Got bad message: ' + JSON.stringify(message))
}
})
alice1.chat.send(channel, {body: `c${i} test`})
}
const allChecksOk = (): boolean => {
for (const i in channels) {
if (!okChecks[i]) {
return false
}
}
return true
}
await pollFor(allChecksOk)
expect(allChecksOk()).toBe(true)
})
it(`Can read and post even if own username missing from a DM channel name`, async (): Promise<void> => {
const channelAlice = {name: config.bots.bob1.username}
const channelBob = {name: config.bots.alice1.username}
const body = 'Dearest Bob, how are you?'
let incoming: MsgSummary | null = null
const watcher: OnMessage = (message: MsgSummary): void => {
incoming = message
}
bob.chat.watchChannelForNewMessages(channelBob, watcher)
await timeout(500)
await alice1.chat.send(channelAlice, {body})
await timeout(500)
const inc = coerceMsgSummary(incoming)
if (inc.content?.type !== 'text') {
throw new Error('got a bad message')
} else {
expect(inc.content?.text?.body).toBe(body)
}
})
it(`Can read and post with usernames in any order`, async (): Promise<void> => {
const channel1 = {name: `${config.bots.alice1.username},${config.bots.bob1.username}`}
const channel2 = {name: `${config.bots.bob1.username},${config.bots.alice1.username}`}
const channel3 = {name: `${channel2.name},${config.bots.charlie1.username}`}
const body = 'Total protonic reversal. That would be bad.'
let receipts = 0
const bobOnMessage = (message: MsgSummary): void => {
if (message.content.type === 'text' && message.content.text?.body === body) {
receipts++
}
}
bob.chat.watchChannelForNewMessages(channel1, bobOnMessage)
bob.chat.watchChannelForNewMessages(channel2, bobOnMessage)
await timeout(500)
await alice1.chat.send(channel1, {body})
await timeout(500)
expect(receipts).toBe(2)
await alice1.chat.send(channel2, {body})
await timeout(500)
expect(receipts).toBe(4)
// channel 3 should not be included by bob since it's not watched
await alice1.chat.send(channel3, {body})
await timeout(500)
expect(receipts).toBe(4)
})
})
describe('Chat createChannel, joinChannel, watchChannel, and leaveChannel', (): void => {
it('Successfully performs the complete flow', async (): Promise<void> => {
const teamChannel: ChatChannel = {
name: config.teams.acme.teamname,
public: false,
topicType: 'chat',
membersType: 'team',
topicName: `sub-${Date.now()}`,
}
const generalChannel: ChatChannel = {
name: config.teams.acme.teamname,
public: false,
topicType: 'chat',
membersType: 'team',
topicName: 'general',
}
const message = {body: `And she's buuuuuuy..ing a stairway....to heav-un.`}
await alice1.chat.createChannel(teamChannel)
await bob.chat.joinChannel(teamChannel)
const read1 = await alice1.chat.read(teamChannel, {
pagination: {
num: 1,
},
})
expect(read1.messages[0].content.type).toEqual('join')
expect(read1.messages[0].sender.username).toEqual(config.bots.bob1.username)
let bobMessageCount = 0
const bobOnMessage = async (): Promise<void> => {
bobMessageCount++
}
bob.chat.watchChannelForNewMessages(teamChannel, bobOnMessage)
bob.chat.watchChannelForNewMessages(generalChannel, bobOnMessage)
await timeout(500)
await alice1.chat.send(generalChannel, message)
await timeout(500)
expect(bobMessageCount).toBe(1) /* only one of the watchers should've picked this up */
await alice1.chat.send(teamChannel, message)
await timeout(500)
expect(bobMessageCount).toBe(2)
await bob.chat.leaveChannel(teamChannel)
const read2 = await alice1.chat.read(teamChannel, {
pagination: {
num: 1,
},
})
expect(read2.messages[0].content.type).toEqual('leave')
expect(read2.messages[0].sender.username).toEqual(config.bots.bob1.username)
await timeout(500)
await alice1.chat.send(teamChannel, message)
await timeout(500)
expect(bobMessageCount).toBe(2) /* confirm bob is no longer listening */
})
})
describe('Chat react', (): void => {
it('Allows a user to react to a valid message', async (): Promise<void> => {
await alice1.chat.send(channel, message)
let result = await alice1.chat.read(channel, {peek: true})
const messageToReactTo = result.messages[0]
await bob.chat.react(channel, messageToReactTo.id, ':poop:')
result = await alice1.chat.read(channel, {peek: true})
const reaction = result.messages[0]
expect(reaction.id).toBe(messageToReactTo.id + 1)
expect(reaction.content.type).toBe('reaction')
expect(result.messages[1]?.reactions?.reactions?.poop?.users).toHaveProperty(config.bots.bob1.username)
})
// it('Throws an error if given an invalid emoji', async () => {
// await alice1.chat.send(channel, message)
// const result = await alice1.chat.read(channel, {peek: true})
// const messageToReactTo = result.messages[0]
// expect(bob.chat.react(channel, messageToReactTo.id, 'blah')).rejects.toThrowError()
// })
// it("Throws an error if it cannot react to a message (e.g., it's not a reactable message type")
})
describe('Chat attach', (): void => {
const attachmentLocation = '/tmp/kb-attachment.txt'
beforeAll(
async (): Promise<void> => {
await promisify(fs.writeFile)(attachmentLocation, 'This is a test file!')
}
)
afterAll(
async (): Promise<void> => {
await promisify(fs.unlink)(attachmentLocation)
}
)
it('Attaches and sends a file on the filesystem', async (): Promise<void> => {
await alice1.chat.attach(channel, attachmentLocation)
const result = await alice1.chat.read(channel)
expect(result.messages[0].sender.username).toEqual(alice1.myInfo()?.username)
expect(result.messages[0].content.type).toBe('attachment')
expect(result.messages[0].content).toHaveProperty('attachment')
})
it('Throws an error if given an invalid channel', async () => {
expect(alice1.chat.attach(invalidChannel, attachmentLocation)).rejects.toThrowError()
})
it('Throws an error if the file does not exist', async () => {
expect(alice1.chat.attach(channel, '/fake-attachment.png')).rejects.toThrowError()
})
})
describe('Chat download', (): void => {
const downloadLocation = '/tmp/kb-downloaded-file'
it('Downloads a file and saves it on the filesystem', async (): Promise<void> => {
// Send a file
const attachmentLocation = '/tmp/kb-attachment.txt'
const attachmentContent = 'Test attachment file'
await promisify(fs.writeFile)(attachmentLocation, attachmentContent)
await alice1.chat.attach(channel, attachmentLocation)
// Read the file
const result = await alice1.chat.read(channel)
await alice1.chat.download(channel, result.messages[0].id, downloadLocation)
const downloadContents = await promisify(fs.readFile)(downloadLocation)
expect(downloadContents.toString()).toBe(attachmentContent)
// Delete the created files
await promisify(fs.unlink)(attachmentLocation)
await promisify(fs.unlink)(downloadLocation)
})
it('Throws an error if given an invalid channel', async (): Promise<void> => {
const result = await alice1.chat.read(channel)
const attachments = result.messages.filter(message => message.content.type === 'attachment')
expect(alice1.chat.download(invalidChannel, attachments[0].id, downloadLocation)).rejects.toThrowError()
})
it('Throws an error if given a non-attachment message', async (): Promise<void> => {
await alice1.chat.send(channel, message)
const result = await alice1.chat.read(channel)
expect(alice1.chat.download(channel, result.messages[0].id, '/tmp/attachment')).rejects.toThrowError()
})
})
describe('Chat delete', (): void => {
it('Deletes a message to a certain channel and returns an empty promise', async (): Promise<void> => {
await alice1.chat.send(channel, message)
// Send a message
const result = await alice1.chat.read(channel, {
peek: true,
})
expect(result.messages[0].sender.username).toEqual(alice1.myInfo()?.username)
if (result.messages[0].content.type !== 'text') {
throw new Error('Expected text type but got something else')
} else {
expect(result.messages[0].content.text?.body).toEqual(message.body)
}
const {id} = result.messages[0]
await alice1.chat.delete(channel, id)
// Send a message
const newResult = await alice1.chat.read(channel, {
peek: true,
})
expect(newResult.messages[0].id).toEqual(id + 1)
if (newResult.messages[0].content.type !== 'delete') {
throw new Error('expected delete message type')
} else {
expect(newResult.messages[0].content.delete?.messageIDs).toContain(id)
expect(newResult.messages[0].content.delete?.messageIDs).toHaveLength(1)
}
expect(newResult.messages[1].id).toEqual(id - 1)
})
it('Throws an error if given an invalid channel', async (): Promise<void> => {
await alice1.chat.send(channel, message)
const result = await alice1.chat.read(channel, {
peek: true,
})
const {id} = result.messages[0]
expect(alice1.chat.delete(invalidChannel, id)).rejects.toThrowError()
})
it('Throws an error if given an invalid id', async (): Promise<void> => {
expect(alice1.chat.delete(channel, -1)).rejects.toThrowError()
})
/*
TODO: currently in DM's both parties are considered admins of the chat and technically have the power
to delete messages from either side, a feature which isn't currently exposed in the GUI. we will likely
turn this off in the form of access control on the server, and then this test will pass.
it('Throws an error if it cannot delete the message (e.g., someone else wrote it)', async () => {
await bob.chat.send(channel, message)
const result = await alice1.chat.read(channel, {
peek: true,
})
const {id} = result.messages[0]
expect(alice1.chat.delete(channel, id)).rejects.toThrowError()
})
*/
})
describe('Command advertisements', (): void => {
it('Should be able to clear, publish and then lookup', async (): Promise<void> => {
await alice1.chat.clearCommands()
await alice1.chat.advertiseCommands({
advertisements: [
{
type: BotCommandsAdvertisementTyp.PUBLIC,
commands: [
{
name: '!helloworld',
description: 'sample description',
usage: 'test',
},
],
},
],
})
const listBeforeClear = await bob.chat.listCommands({
channel: channel,
})
expect(listBeforeClear.commands).toContainEqual({
name: '!helloworld',
description: 'sample description',
usage: 'test',
username: alice1.myInfo()?.username,
})
await alice1.chat.clearCommands()
const listAfterClear = await bob.chat.listCommands({
channel: channel,
})
expect(listAfterClear.commands.length).toBe(0)
})
})
describe('watchChannelForNewMessages', (): void => {
it('Can have bots say hello to each other in a team', async (): Promise<void> => {
let ALICE_IS_SATISFIED = false
let BOB_IS_SATISFIED = false
alice1.chat.watchChannelForNewMessages(teamChannel, (message): void => {
if (message.content.type === 'text' && message.content.text?.body === 'hello alice1') {
ALICE_IS_SATISFIED = true
}
})
bob.chat.watchChannelForNewMessages(teamChannel, (message): void => {
if (message.content.type === 'text' && message.content.text?.body === 'hello bob') {
BOB_IS_SATISFIED = true
}
})
await alice1.chat.send(teamChannel, {body: 'hello bob'})
await bob.chat.send(teamChannel, {body: 'hello alice1'})
await pollFor((): boolean => ALICE_IS_SATISFIED && BOB_IS_SATISFIED)
expect(ALICE_IS_SATISFIED).toBe(true)
expect(BOB_IS_SATISFIED).toBe(true)
})
it("Doesn't pick up its own messages from the same device", async (): Promise<void> => {
const messageText = 'Ever thus to deadbeats, Lebowski'
let noticedMessages = 0
alice1.chat.watchChannelForNewMessages(teamChannel, (message): void => {
if (message.content.type === 'text' && message.content.text?.body === messageText) {
noticedMessages++
}
})
await alice1.chat.send(teamChannel, {body: messageText})
await timeout(3000)
expect(noticedMessages).toBe(0)
})
})
describe('watchAllChannelsForNewMessages', (): void => {
const testTwoBotsCounting = async (bot1: Bot, bot2: Bot): Promise<void> => {
const stopAt = 10
const convoCode = crypto.randomBytes(8).toString('hex')
const directChannel = {name: `${bot1.myInfo()?.username},${bot2.myInfo()?.username}`}
let totalMessagesSeen = 0
let highestReached = 0
const onMessageForBot = (bot: Bot): OnMessage => {
const onMessage = async (message: MsgSummary): Promise<void> => {
if (message.content.type === 'text') {
const body = message.content.text?.body ?? ''
if (body.indexOf(convoCode) !== -1) {
totalMessagesSeen++
const num = parseInt(body.replace(convoCode, '').trim())
highestReached = Math.max(num, highestReached)
if (num < stopAt) {
const reply = {body: `${convoCode} ${num + 1}`}
await bot.chat.send(message.channel, reply)
}
}
}
}
return onMessage
}
bot1.chat.watchAllChannelsForNewMessages(onMessageForBot(bot1))
bot2.chat.watchAllChannelsForNewMessages(onMessageForBot(bot2))
const message = {body: `${convoCode} 1`}
await bot1.chat.send(directChannel, message)
await pollFor((): boolean => highestReached === stopAt)
expect(totalMessagesSeen).toBe(stopAt)
}
it('can have 2 users count together', async (): Promise<void> => testTwoBotsCounting(alice1, bob))
it('can have 1 user count across 2 devices', async (): Promise<void> => testTwoBotsCounting(alice1, alice2))
})
}) | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/proactiveDetectionConfigurationsMappers";
import * as Parameters from "../models/parameters";
import { ApplicationInsightsManagementClientContext } from "../applicationInsightsManagementClientContext";
/** Class representing a ProactiveDetectionConfigurations. */
export class ProactiveDetectionConfigurations {
private readonly client: ApplicationInsightsManagementClientContext;
/**
* Create a ProactiveDetectionConfigurations.
* @param {ApplicationInsightsManagementClientContext} client Reference to the service client.
*/
constructor(client: ApplicationInsightsManagementClientContext) {
this.client = client;
}
/**
* Gets a list of ProactiveDetection configurations of an Application Insights component.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param [options] The optional parameters
* @returns Promise<Models.ProactiveDetectionConfigurationsListResponse>
*/
list(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProactiveDetectionConfigurationsListResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param callback The callback
*/
list(resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration[]>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param options The optional parameters
* @param callback The callback
*/
list(resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration[]>): void;
list(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration[]>, callback?: msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration[]>): Promise<Models.ProactiveDetectionConfigurationsListResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceName,
options
},
listOperationSpec,
callback) as Promise<Models.ProactiveDetectionConfigurationsListResponse>;
}
/**
* Get the ProactiveDetection configuration for this configuration id.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param configurationId The ProactiveDetection configuration ID. This is unique within a
* Application Insights component.
* @param [options] The optional parameters
* @returns Promise<Models.ProactiveDetectionConfigurationsGetResponse>
*/
get(resourceGroupName: string, resourceName: string, configurationId: string, options?: msRest.RequestOptionsBase): Promise<Models.ProactiveDetectionConfigurationsGetResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param configurationId The ProactiveDetection configuration ID. This is unique within a
* Application Insights component.
* @param callback The callback
*/
get(resourceGroupName: string, resourceName: string, configurationId: string, callback: msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param configurationId The ProactiveDetection configuration ID. This is unique within a
* Application Insights component.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, resourceName: string, configurationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration>): void;
get(resourceGroupName: string, resourceName: string, configurationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration>, callback?: msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration>): Promise<Models.ProactiveDetectionConfigurationsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceName,
configurationId,
options
},
getOperationSpec,
callback) as Promise<Models.ProactiveDetectionConfigurationsGetResponse>;
}
/**
* Update the ProactiveDetection configuration for this configuration id.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param configurationId The ProactiveDetection configuration ID. This is unique within a
* Application Insights component.
* @param proactiveDetectionProperties Properties that need to be specified to update the
* ProactiveDetection configuration.
* @param [options] The optional parameters
* @returns Promise<Models.ProactiveDetectionConfigurationsUpdateResponse>
*/
update(resourceGroupName: string, resourceName: string, configurationId: string, proactiveDetectionProperties: Models.ApplicationInsightsComponentProactiveDetectionConfiguration, options?: msRest.RequestOptionsBase): Promise<Models.ProactiveDetectionConfigurationsUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param configurationId The ProactiveDetection configuration ID. This is unique within a
* Application Insights component.
* @param proactiveDetectionProperties Properties that need to be specified to update the
* ProactiveDetection configuration.
* @param callback The callback
*/
update(resourceGroupName: string, resourceName: string, configurationId: string, proactiveDetectionProperties: Models.ApplicationInsightsComponentProactiveDetectionConfiguration, callback: msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param configurationId The ProactiveDetection configuration ID. This is unique within a
* Application Insights component.
* @param proactiveDetectionProperties Properties that need to be specified to update the
* ProactiveDetection configuration.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, resourceName: string, configurationId: string, proactiveDetectionProperties: Models.ApplicationInsightsComponentProactiveDetectionConfiguration, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration>): void;
update(resourceGroupName: string, resourceName: string, configurationId: string, proactiveDetectionProperties: Models.ApplicationInsightsComponentProactiveDetectionConfiguration, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration>, callback?: msRest.ServiceCallback<Models.ApplicationInsightsComponentProactiveDetectionConfiguration>): Promise<Models.ProactiveDetectionConfigurationsUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceName,
configurationId,
proactiveDetectionProperties,
options
},
updateOperationSpec,
callback) as Promise<Models.ProactiveDetectionConfigurationsUpdateResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/ProactiveDetectionConfigs",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.resourceName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ApplicationInsightsComponentProactiveDetectionConfiguration"
}
}
}
}
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/ProactiveDetectionConfigs/{ConfigurationId}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.resourceName,
Parameters.configurationId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ApplicationInsightsComponentProactiveDetectionConfiguration
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/ProactiveDetectionConfigs/{ConfigurationId}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.resourceName,
Parameters.configurationId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "proactiveDetectionProperties",
mapper: {
...Mappers.ApplicationInsightsComponentProactiveDetectionConfiguration,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.ApplicationInsightsComponentProactiveDetectionConfiguration
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import { FileStreamRotator } from '../src/fileStreamRotator';
import * as crypto from 'crypto';
import { writeFileSync, remove, ensureFile, lstat, readdirSync } from 'fs-extra';
import { join } from 'path';
import { createChildProcess, sleep } from './util';
describe('/test/stream-rotate.test.ts', () => {
beforeEach(async () => {
await remove(join(__dirname, 'logs'));
});
it('test every second', async () => {
const rotator = new FileStreamRotator();
const rotatingLogStream = rotator.getStream({
filename: 'logs/1s/testlog-%DATE%.log',
frequency: 'custom',
date_format: 'YYYY-MM-DD.HH.mm',
size: '50k',
max_logs: '5',
audit_file: '/tmp/audit-1s.json',
end_stream: false,
utc: true,
extension: '.logs',
});
rotatingLogStream.on('error', function (err) {
console.log(Date.now(), Date(), 'stream error', err)
process.exit()
});
rotatingLogStream.on('close', function () {
console.log(Date.now(), Date(), 'stream closed')
});
rotatingLogStream.on('finish', function () {
console.log(Date.now(), Date(), 'stream finished')
});
rotatingLogStream.on('rotate', function (oldFile, newFile) {
console.log(Date.now(), Date(), 'stream rotated', oldFile, newFile);
});
rotatingLogStream.on('open', function (fd) {
console.log(Date.now(), Date(), 'stream open', fd);
});
rotatingLogStream.on('new', function (newFile) {
console.log(Date.now(), Date(), 'stream new', newFile);
});
await new Promise<void>(resolve => {
let counter = 0;
const i = setInterval( () => {
counter++;
// rotatingLogStream.write(Date() + "\ttesting 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890\n")
rotatingLogStream.write(Date() + 'ニューバランスの100年を超える長い歴史\n')
// if(counter == 2000){
if (counter == 400) {
clearInterval(i);
console.log(Date() + '\tEND STREAM');
rotatingLogStream.end('end\n');
resolve();
return;
}
rotatingLogStream.write(Date() + '\t');
for (let y = 0; y < 400; y++) {
// console.log(i + " ")
// rotatingLogStream.write(y + ": " + Date.now() + " >> ");
rotatingLogStream.write('適: ' + Date.now() + ' >> ');
}
rotatingLogStream.write('\n');
}, 10);
})
})
it('test minute-test', async () => {
const rotator = new FileStreamRotator();
const rotatingLogStream = rotator.getStream({
filename: "logs/1m/testlog-%DATE%",
frequency: "1m",
date_format: "YYYY-MM-DD.HH.mm",
size: "500k",
max_logs: "10",
audit_file: "/tmp/audit.json",
end_stream: false,
utc: true,
extension: ".log",
create_symlink: true,
symlink_name: "tail.log"
});
rotatingLogStream.on("error", function () {
console.log(Date.now(), Date(), "stream error", arguments)
})
rotatingLogStream.on("close", function () {
console.log(Date.now(), Date(), "stream closed")
})
rotatingLogStream.on("finish", function () {
console.log(Date.now(), Date(), "stream finished")
})
rotatingLogStream.on("rotate", function (oldFile, newFile) {
console.log(Date.now(), Date(), "stream rotated", oldFile, newFile);
})
rotatingLogStream.on("open", function (fd) {
console.log(Date.now(), Date(), "stream open", fd);
})
rotatingLogStream.on("new", function (newFile) {
console.log(Date.now(), Date(), "stream new", newFile);
})
rotatingLogStream.on("logRemoved", function (newFile) {
console.log(Date.now(), Date(), "stream logRemoved", newFile);
})
await new Promise<void>(resolve => {
var counter = 0;
var i = setInterval(function () {
counter++;
rotatingLogStream.write(Date() + "\t" + "testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890\n")
// rotatingLogStream1.write(Date() + "\t" + "testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890-testing 1234567890\n")
if (counter == 5000) {
clearInterval(i);
rotatingLogStream.end("end\n");
// rotatingLogStream1.end("end\n");
resolve();
}
}, 10);
});
});
it('should test large', async () => {
const buffer: Buffer = await new Promise(resolve => {
crypto.randomBytes(1048, (err, buffer) => {
resolve(buffer);
});
});
const token = buffer.toString('hex');
const rotator = new FileStreamRotator();
const logStream = rotator.getStream({
filename: './logs/application-%DATE%',
frequency: 'custom',
// size: '50k',
max_logs: 4,
end_stream: true,
extension: ".log",
create_symlink: true
});
let count = 0;
const i = setInterval(() => {
// console.log("count: ", count)
if (count > 300) {
return clear()
}
count++;
for (let i = 0; i < 1; i++) {
logStream.write(token + "\n");
}
},10);
function clear(){
console.log("clearing interval")
clearInterval(i)
logStream.end("end");
}
});
it('should test rotate log when file has limit size', async () => {
// 测试当没有日志切割规则只有大小规则,初始化文件达到限制大小,是否能正确切割
const buffer: Buffer = await new Promise(resolve => {
crypto.randomBytes(1048, (err, buffer) => {
resolve(buffer);
});
});
const logFile = join(__dirname, 'logs/test.log');
const newLogFile = join(__dirname, 'logs/test.log.1');
const token = buffer.toString('hex');
await ensureFile(logFile);
writeFileSync(logFile, token);
const rotator = new FileStreamRotator();
const logStream = rotator.getStream({
filename: logFile,
size: '2k',
end_stream: true,
});
let i = 100;
while(i-- >= 0) {
logStream.write('hello world\n');
}
logStream.end();
await sleep();
expect((await lstat(logFile)).size).toEqual(2096);
expect((await lstat(newLogFile)).size).toEqual(1212);
});
it('should test rotate log when file has limit size2', async () => {
// 测试当没有日志切割规则只有大小规则,初始化文件未达到限制大小,再写一点看是否能正确切割
const buffer: Buffer = await new Promise(resolve => {
crypto.randomBytes(1000, (err, buffer) => {
resolve(buffer);
});
});
const logFile = join(__dirname, 'logs/test.log');
const newLogFile = join(__dirname, 'logs/test.log.1');
const token = buffer.toString('hex');
await ensureFile(logFile);
writeFileSync(logFile, token);
const rotator = new FileStreamRotator();
const logStream = rotator.getStream({
filename: logFile,
size: '2k',
end_stream: true,
});
let i = 100;
while(i-- >= 0) {
logStream.write('hello world\n');
}
logStream.end();
await sleep();
expect((await lstat(logFile)).size).toEqual(2060);
expect((await lstat(newLogFile)).size).toEqual(1152);
});
it('should test write big data over limit', async () => {
const buffer: Buffer = await new Promise(resolve => {
crypto.randomBytes(400, (err, buffer) => {
resolve(buffer);
});
});
const logFile = join(__dirname, 'logs/test.log');
const newLogFile = join(__dirname, 'logs/test.log.1');
const token = buffer.toString('hex');
await ensureFile(logFile);
const rotator = new FileStreamRotator();
const logStream = rotator.getStream({
filename: logFile,
size: '1k',
end_stream: true,
});
// 第一次写入 800k
logStream.write(token);
// 第二次写入 800k,这个时候应该都在第一个文件
logStream.write(token);
// 第三次写入 800k,超过第一个文件的大小,写入第二个文件
logStream.write(token);
logStream.end();
await sleep();
expect((await lstat(logFile)).size).toEqual(1600);
expect((await lstat(newLogFile)).size).toEqual(800);
});
it('should test rotate log when frequency set ', async () => {
const logFile = join(__dirname, 'logs/test.log');
const rotator = new FileStreamRotator();
const logStream = rotator.getStream({
filename: logFile,
frequency: '5s',
date_format: 'YYYY-MM-DD-HHmmss',
end_stream: true,
});
for (let i = 0; i < 10; i++) {
logStream.write('hello world\n');
await sleep();
}
logStream.end();
const files = readdirSync(join(__dirname, 'logs'))
expect(files.length).toBeGreaterThanOrEqual(2);
});
it('should rotate log by size in cluster', async () => {
// const logFile = join(__dirname, 'logs/test.log');
const clusterFile = join(__dirname, 'fixtures/cluster-rotate.ts');
const child = createChildProcess(clusterFile);
await new Promise<any>(resolve => {
child.on('message', pidList => {
resolve(pidList);
});
});
await new Promise<void>(resolve => {
child.on('exit', () => {
// 等进程退出
resolve();
});
});
const files = readdirSync(join(__dirname, 'logs'))
expect(files.length).toBeGreaterThanOrEqual(10);
});
}) | the_stack |
import BigNumber from '../../dependencies/src/bignumber.js-9.0.0/bignumber'
import {
isArray,
isDate,
isInteger,
isNumber,
isObject,
isString,
validate,
validators
} from '../../dependencies/src/validate.js-0.13.1/validate'
import { EthereumProtocol } from '../../protocols/ethereum/EthereumProtocol'
import { KusamaProtocol } from '../../protocols/substrate/kusama/KusamaProtocol'
import bs64check from '../../utils/base64Check'
import { SignedEthereumTransaction } from '../schemas/definitions/signed-transaction-ethereum'
import { SignedSubstrateTransaction } from '../schemas/definitions/signed-transaction-substrate'
import { SignedTezosTransaction } from '../schemas/definitions/signed-transaction-tezos'
import { UnsignedTezosTransaction } from '../schemas/definitions/unsigned-transaction-tezos'
import { RawTezosTransaction } from '../types'
import { AeternityProtocol } from './../../protocols/aeternity/AeternityProtocol'
import { BitcoinProtocol } from './../../protocols/bitcoin/BitcoinProtocol'
import { TezosProtocol } from './../../protocols/tezos/TezosProtocol'
validators.type = (value, options, key, attributes) => {
// allow empty values by default (needs to be checked by "presence" check)
if (value === null || typeof value === 'undefined') {
return null
}
// allow defining object of any type using their constructor. --> options = {clazz: ClassName}
/*
if (typeof options === 'object' && options.clazz) {
return value instanceof options.clazz ? null : 'is not of type "' + options.clazz.name + '"'
}
*/
if (!validators.type.checks[options]) {
throw new Error(`Could not find validator for type ${options}`)
}
return validators.type.checks[options](value) ? null : `is not of type "${options}"`
}
validators.type.checks = {
Object(value: unknown) {
return isObject(value) && !isArray(value)
},
Array: isArray,
Integer: isInteger,
Number: isNumber,
String: isString,
Date: isDate,
Boolean(value: unknown) {
return typeof value === 'boolean'
},
BigNumber(value: unknown) {
return BigNumber.isBigNumber(value)
}
}
validators.isHexStringWithPrefix = (value: unknown) => {
if (typeof value !== 'string') {
return 'is not hex string'
}
if (!value.startsWith('0x')) {
return 'is not hex string'
}
const hexWithoutPrefix = value.substr(2)
if (hexWithoutPrefix.length === 0) {
// For ethereum, "0x" is valid
return null
}
return /[0-9A-F]/gi.test(hexWithoutPrefix) ? null : 'is not hex string'
}
validators.isPublicKey = (value: unknown) => {
if (typeof value !== 'string') {
return 'is not a valid public key: should be of type string'
}
if (value.length !== 64) {
return 'is not a valid public key: wrong length'
}
return /[0-9A-F]/gi.test(value) ? null : 'is not a valid public key: invalid characters'
}
// ETHEREUM
validators.isValidEthereumTransactionString = (transaction: string) => {
// console.log(binaryTransaction)
return new Promise<void>(async (resolve, reject) => {
if (transaction === null || typeof transaction === 'undefined') {
reject('not a valid Ethereum transaction')
}
const signedTx: SignedEthereumTransaction = {
accountIdentifier: '',
transaction
}
const protocol = new EthereumProtocol()
// allow empty values by default (needs to be checked by "presence" check)
if (transaction === null || typeof transaction === 'undefined') {
reject()
}
try {
await protocol.getTransactionDetailsFromSigned(signedTx)
resolve()
} catch (error) {
// console.log(error)
reject('not a valid Ethereum transaction')
}
})
}
// BITCOIN
validators.isValidBitcoinInput = (ins: unknown) => {
// if (!Array.isArray(ins)) {
// ins = [ins]
// }
if (!Array.isArray(ins)) {
return 'not an array'
}
for (let i: number = 0; i < ins.length; i++) {
const value = ins[i]
if (!value.hasOwnProperty('txId')) {
return "doesn't have property txId "
} else {
const pattern = RegExp('^[a-fA-F0-9]{64}$')
if (!pattern.test(value.txId)) {
return 'not a valid txId'
}
}
if (!value.hasOwnProperty('value')) {
return "doesn't have property value "
} else {
if (!BigNumber.isBigNumber(value.value)) {
return 'value not a valid BigNumber'
}
}
if (!value.hasOwnProperty('vout')) {
return "doesn't have property vout"
} else {
if (typeof value.vout !== 'number') {
return 'vout is not a number'
} else if (value.vout < 0) {
return 'vout is not a positive value'
}
}
if (!value.hasOwnProperty('address')) {
return "doesn't have property address "
} else {
const pattern = RegExp(new BitcoinProtocol().addressValidationPattern)
if (!pattern.test(value.address)) {
return 'not a valid bitcoin address'
}
}
if (!value.hasOwnProperty('derivationPath')) {
return "doesn't have property derivationPath"
} else {
const protocol = new BitcoinProtocol()
try {
const mnemonic = 'spell device they juice trial skirt amazing boat badge steak usage february virus art survey'
protocol.getPublicKeyFromMnemonic(mnemonic, value.derivationPath)
} catch (error) {
return 'invalid derivation path'
}
}
}
return null
}
validators.isValidBitcoinOutput = (outs: unknown) => {
// console.log(outs)
// if (!Array.isArray(outs)) {
// outs = [outs]
// }
if (!Array.isArray(outs)) {
return 'not an array'
}
for (let i: number = 0; i < outs.length; i++) {
const value = outs[i]
if (!value.hasOwnProperty('recipient')) {
return "doesn't have property recipient"
} else {
const pattern = RegExp(new BitcoinProtocol().addressValidationPattern)
if (!pattern.test(value.recipient)) {
return 'invalid Bitcoin address'
}
}
if (!value.hasOwnProperty('isChange')) {
return "doesn't have property isChange "
} else {
if (typeof value.isChange !== 'boolean') {
return 'change is not a boolean'
}
}
if (!value.hasOwnProperty('value')) {
return "doesn't have property value "
} else {
if (!BigNumber.isBigNumber(value.value)) {
return 'value is not BigNumber'
}
}
}
return null
}
validators.isValidBitcoinFromArray = (array: unknown) => {
if (!Array.isArray(array)) {
return 'not an array of Bitcoin addresses'
}
for (let i = 0; i < array.length; i++) {
const address: string = array[i]
// const testpattern = RegExp(new BitcoinTestnetProtocol().addressValidationPattern) // TODO maybe don't use the testnetprotocol
const pattern = RegExp(new BitcoinProtocol().addressValidationPattern) // TODO maybe don't use the testnetprotocol
if (!pattern.test(address)) {
return 'not a valid bitcoin address'
}
}
return null
}
validators.isBitcoinAccount = (accountIdentifier: string) => {
if (accountIdentifier === null || typeof accountIdentifier === 'undefined') {
return null
}
try {
const protocol = new BitcoinProtocol()
protocol.getAddressFromExtendedPublicKey(accountIdentifier, 0, 0)
return null
} catch (error) {
return 'not a valid Bitcoin account'
}
}
validators.isValidBitcoinTxString = (transaction: string) => {
// allow empty values by default (needs to be checked by "presence" check)
if (transaction === null || typeof transaction === 'undefined') {
return null
}
try {
const protocol = new BitcoinProtocol()
const bitcoinJSLib = protocol.options.config.bitcoinJSLib
bitcoinJSLib.Transaction.fromHex(transaction)
return null
} catch (error) {
return 'is not a valid hex encoded Bitcoin transaction'
}
}
// AETERNITY
validators.isMainNet = (value: unknown) => {
// allow empty values by default (needs to be checked by "presence" check)
if (value === null || typeof value === 'undefined') {
return null
}
if (value !== 'ae_mainnet') {
return 'is not on mainnet'
}
return null
}
validators.isValidAeternityTx = (transaction: unknown) => {
// allow empty values by default (needs to be checked by "presence" check)
if (transaction === null || typeof transaction === 'undefined') {
return null
}
if (typeof transaction === 'string' && !transaction.startsWith('tx_')) {
return 'invalid tx format'
} else if (typeof transaction === 'string') {
try {
bs64check.decode(transaction.replace('tx_', ''))
return null
} catch (error) {
return "isn't base64 encoded"
}
} else {
return "isn't a string"
}
}
validators.isValidAeternityAccount = (accountIdentifier: string) => {
return new Promise<void>(async (resolve, reject) => {
if (accountIdentifier === null || typeof accountIdentifier === 'undefined') {
reject()
}
try {
const protocol = new AeternityProtocol()
await protocol.getTransactionsFromPublicKey(accountIdentifier, 1)
resolve()
} catch (error) {
reject('not a valid Aeternity account')
}
})
}
// TEZOS
validators.isValidTezosUnsignedTransaction = (binaryTx: string) => {
const rawTx: RawTezosTransaction = { binaryTransaction: binaryTx }
const unsignedTx: UnsignedTezosTransaction = {
transaction: rawTx,
publicKey: '',
callbackURL: ''
}
return new Promise<void>(async (resolve, reject) => {
if (binaryTx === null || typeof binaryTx === 'undefined') {
reject('not a valid Tezos transaction')
}
const protocol = new TezosProtocol()
// allow empty values by default (needs to be checked by "presence" check)
if (binaryTx === null || typeof binaryTx === 'undefined') {
reject()
}
try {
await protocol.getTransactionDetails(unsignedTx)
resolve()
} catch (error) {
// console.log(error)
reject('not a valid Tezos transaction')
}
})
}
validators.isValidTezosSignedTransaction = (signedTransaction: string) => {
const signedTx: SignedTezosTransaction = {
accountIdentifier: '',
transaction: signedTransaction
}
return new Promise<void>(async (resolve, reject) => {
if (signedTransaction === null || typeof signedTransaction === 'undefined') {
reject('not a valid Tezos transaction')
}
const protocol = new TezosProtocol()
// allow empty values by default (needs to be checked by "presence" check)
if (signedTransaction === null || typeof signedTransaction === 'undefined') {
reject()
}
try {
await protocol.getTransactionDetailsFromSigned(signedTx)
resolve()
} catch (error) {
// console.log(error)
reject('not a valid Tezos transaction')
}
})
}
// SUBSTRATE
validators.isValidSubstrateUnsignedTransaction = (encoded: string) => {
const unsignedTx = {
transaction: { encoded },
publicKey: '',
callbackURL: ''
}
return new Promise<void>(async (resolve, reject) => {
if (encoded === null || typeof encoded === 'undefined') {
reject('not a valid Substrate transaction')
}
const protocol = new KusamaProtocol()
try {
await protocol.getTransactionDetails(unsignedTx)
resolve()
} catch (error) {
reject('not a valid Substrate transaction')
}
})
}
validators.isValidSubstrateSignedTransaction = (transaction: string) => {
const signedTx: SignedSubstrateTransaction = {
accountIdentifier: '',
transaction
}
return new Promise<void>(async (resolve, reject) => {
if (transaction === null || typeof transaction === 'undefined') {
reject('not a valid Substrate transaction')
}
const protocol = new KusamaProtocol()
try {
await protocol.getTransactionDetailsFromSigned(signedTx)
resolve()
} catch (error) {
reject('not a valid Substrate transaction')
}
})
}
export async function validateSyncScheme(syncScheme: unknown) {
const constraints = {
version: {
presence: { allowEmpty: false },
numericality: { noStrings: true, onlyInteger: true, greaterThanOrEqualTo: 0 }
},
type: {
presence: { allowEmpty: false },
numericality: { noStrings: true, onlyInteger: true, greaterThanOrEqualTo: 0 }
},
protocol: {
presence: { allowEmpty: false },
type: 'String',
length: {
minimum: 1
}
},
payload: {
presence: { allowEmpty: false },
type: 'Array'
}
}
return validate(syncScheme, constraints)
}
// tslint:disable-next-line
/*
function validateSerializationInput(from: string, fee: BigNumber, amount: BigNumber, publicKey: string, transaction: any) {
const constraints = {
from: {
presence: { allowEmpty: false },
type: 'String'
},
fee: {
presence: { allowEmpty: false },
type: 'BigNumber'
},
amount: {
presence: { allowEmpty: false },
type: 'BigNumber'
},
publicKey: {
presence: { allowEmpty: false },
type: 'String'
},
transaction: {
presence: { allowEmpty: false },
type: 'Array'
}
}
let test = validate(
{
from,
fee,
amount,
publicKey,
transaction
},
constraints
)
return test
}
*/ | the_stack |
* @module QuantityFormatting
*/
import {
BadUnit, BasicUnit, UnitConversion, UnitProps, UnitsProvider,
} from "@itwin/core-quantity";
import { UnitNameKey } from "./QuantityFormatter";
import { UNIT_EXTRA_DATA } from "./UnitsData";
// cSpell:ignore ussurvey USCUSTOM
/** Units provider that provides a limited number of UnitDefinitions that are needed to support basic tools.
* @internal
*/
export class BasicUnitsProvider implements UnitsProvider {
/** Find a unit given the unitLabel. */
public async findUnit(unitLabel: string, schemaName?: string, phenomenon?: string, unitSystem?: string): Promise<UnitProps> {
const labelToFind = unitLabel.toLowerCase();
const unitFamilyToFind = phenomenon ? phenomenon.toLowerCase() : undefined;
const unitSystemToFind = unitSystem ? unitSystem.toLowerCase() : undefined;
for (const entry of UNIT_DATA) {
if (schemaName && schemaName !== "Units")
continue;
if (phenomenon && entry.phenomenon.toLowerCase() !== unitFamilyToFind)
continue;
if (unitSystemToFind && entry.system.toLowerCase() !== unitSystemToFind)
continue;
if (entry.displayLabel.toLowerCase() === labelToFind || entry.name.toLowerCase() === labelToFind) {
const unitProps = new BasicUnit(entry.name, entry.displayLabel, entry.phenomenon, entry.system);
return unitProps;
}
if (entry.altDisplayLabels && entry.altDisplayLabels.length > 0) {
if (entry.altDisplayLabels.findIndex((ref) => ref.toLowerCase() === labelToFind) !== -1) {
const unitProps = new BasicUnit(entry.name, entry.displayLabel, entry.phenomenon, entry.system);
return unitProps;
}
}
}
return new BadUnit();
}
/** Find all units given phenomenon */
public async getUnitsByFamily(phenomenon: string): Promise<UnitProps[]> {
const units: UnitProps[] = [];
for (const entry of UNIT_DATA) {
if (entry.phenomenon !== phenomenon)
continue;
units.push(new BasicUnit(entry.name, entry.displayLabel, entry.phenomenon, entry.system));
}
return units;
}
protected findUnitDefinition(name: string): UnitDefinition | undefined {
for (const entry of UNIT_DATA) {
if (entry.name === name)
return entry;
}
return undefined;
}
/** Find a unit given the unit's unique name. */
public async findUnitByName(unitName: string): Promise<UnitProps> {
const unitDataEntry = this.findUnitDefinition(unitName);
if (unitDataEntry) {
return new BasicUnit(unitDataEntry.name, unitDataEntry.displayLabel, unitDataEntry.phenomenon, unitDataEntry.system);
}
return new BadUnit();
}
/** Return the information needed to convert a value between two different units. The units should be from the same phenomenon. */
public async getConversion(fromUnit: UnitProps, toUnit: UnitProps): Promise<UnitConversion> {
const fromUnitData = this.findUnitDefinition(fromUnit.name);
const toUnitData = this.findUnitDefinition(toUnit.name);
if (fromUnitData && toUnitData) {
const deltaOffset = toUnitData.conversion.offset - fromUnitData.conversion.offset;
const deltaNumerator = toUnitData.conversion.numerator * fromUnitData.conversion.denominator;
const deltaDenominator = toUnitData.conversion.denominator * fromUnitData.conversion.numerator;
const conversionData = new ConversionData();
conversionData.factor = deltaNumerator / deltaDenominator;
conversionData.offset = deltaOffset;
return conversionData;
}
return new ConversionData();
}
}
/** Class that implements the minimum UnitConversion interface to provide information needed to convert unit values.
* @alpha
*/
class ConversionData implements UnitConversion {
public factor: number = 1.0;
public offset: number = 0.0;
public error: boolean = false;
}
/** interface use to define unit conversions to a base used for a phenomenon */
interface ConversionDef {
numerator: number;
denominator: number;
offset: number;
}
// Temporary interface use to define structure of the unit definitions in this example.
interface UnitDefinition {
readonly name: string;
readonly phenomenon: string;
readonly displayLabel: string;
readonly altDisplayLabels?: string[];
readonly conversion: ConversionDef;
readonly system: string;
}
/** Function to generate default set of alternate unit labels
* @internal
*/
export function getDefaultAlternateUnitLabels() {
const altDisplayLabelsMap = new Map<UnitNameKey, Set<string>>();
for (const entry of UNIT_EXTRA_DATA) {
if (entry.altDisplayLabels && entry.altDisplayLabels.length > 0) {
altDisplayLabelsMap.set(entry.name, new Set<string>(entry.altDisplayLabels));
}
}
if (altDisplayLabelsMap.size)
return altDisplayLabelsMap;
return undefined;
}
// ========================================================================================================================================
// Minimum set of UNITs to be removed when official UnitsProvider is available
// ========================================================================================================================================
// cSpell:ignore MILLIINCH, MICROINCH, MILLIFOOT
// Set of supported units - this information will come from Schema-based units once the EC package is ready to provide this information.
const UNIT_DATA: UnitDefinition[] = [
// Angles ( base unit radian )
{ name: "Units.RAD", phenomenon: "Units.ANGLE", system: "Units.SI", conversion: { numerator: 1.0, denominator: 1.0, offset: 0.0 }, displayLabel: "rad" },
// 1 rad = 180.0/PI °
{ name: "Units.ARC_DEG", phenomenon: "Units.ANGLE", system: "Units.METRIC", conversion: { numerator: 180.0, denominator: 3.1415926535897932384626433832795, offset: 0.0 }, displayLabel: "°" },
{ name: "Units.ARC_MINUTE", phenomenon: "Units.ANGLE", system: "Units.METRIC", conversion: { numerator: 10800.0, denominator: 3.14159265358979323846264338327950, offset: 0.0 }, displayLabel: "'" },
{ name: "Units.ARC_SECOND", phenomenon: "Units.ANGLE", system: "Units.METRIC", conversion: { numerator: 648000.0, denominator: 3.1415926535897932384626433832795, offset: 0.0 }, displayLabel: '"' },
{ name: "Units.GRAD", phenomenon: "Units.ANGLE", system: "Units.METRIC", conversion: { numerator: 200, denominator: 3.1415926535897932384626433832795, offset: 0.0 }, displayLabel: "grad" },
// Time ( base unit second )
{ name: "Units.S", phenomenon: "Units.TIME", system: "Units.SI", conversion: { numerator: 1.0, denominator: 1.0, offset: 0.0 }, displayLabel: "s" },
{ name: "Units.MIN", phenomenon: "Units.TIME", system: "Units.INTERNATIONAL", conversion: { numerator: 1.0, denominator: 60.0, offset: 0.0 }, displayLabel: "min" },
{ name: "Units.HR", phenomenon: "Units.TIME", system: "Units.INTERNATIONAL", conversion: { numerator: 1.0, denominator: 3600.0, offset: 0.0 }, displayLabel: "h"},
{ name: "Units.DAY", phenomenon: "Units.TIME", system: "Units.INTERNATIONAL", conversion: { numerator: 1.0, denominator: 86400.0, offset: 0.0 }, displayLabel: "days" },
{ name: "Units.WEEK", phenomenon: "Units.TIME", system: "Units.INTERNATIONAL", conversion: { numerator: 1.0, denominator: 604800.0, offset: 0.0 }, displayLabel: "weeks" },
// 1 sec = 1/31536000.0 yr
{ name: "Units.YR", phenomenon: "Units.TIME", system: "Units.INTERNATIONAL", conversion: { numerator: 1.0, denominator: 31536000.0, offset: 0.0 }, displayLabel: "years" },
// conversion => specified unit to base unit of m
{ name: "Units.M", phenomenon: "Units.LENGTH", system: "Units.SI", conversion: { numerator: 1.0, denominator: 1.0, offset: 0.0 }, displayLabel: "m" },
{ name: "Units.MM", phenomenon: "Units.LENGTH", system: "Units.METRIC", conversion: { numerator: 1000.0, denominator: 1.0, offset: 0.0 }, displayLabel: "mm" },
{ name: "Units.CM", phenomenon: "Units.LENGTH", system: "Units.METRIC", conversion: { numerator: 100.0, denominator: 1.0, offset: 0.0 }, displayLabel: "cm" },
{ name: "Units.DM", phenomenon: "Units.LENGTH", system: "Units.METRIC", conversion: { numerator: 10.0, denominator: 1.0, offset: 0.0 }, displayLabel: "dm" },
{ name: "Units.KM", phenomenon: "Units.LENGTH", system: "Units.METRIC", conversion: { numerator: 1.0, denominator: 1000.0, offset: 0.0 }, displayLabel: "km" },
{ name: "Units.UM", phenomenon: "Units.LENGTH", system: "Units.METRIC", conversion: { numerator: 1000000.0, denominator: 1.0, offset: 0.0 }, displayLabel: "µm" },
{ name: "Units.MILLIINCH", phenomenon: "Units.LENGTH", system: "Units.USCUSTOM", conversion: { numerator: 1000.0, denominator: 0.0254, offset: 0.0 }, displayLabel: "mil" },
{ name: "Units.MICROINCH", phenomenon: "Units.LENGTH", system: "Units.USCUSTOM", conversion: { numerator: 1000000.0, denominator: 0.0254, offset: 0.0 }, displayLabel: "µin" },
{ name: "Units.MILLIFOOT", phenomenon: "Units.LENGTH", system: "Units.USCUSTOM", conversion: { numerator: 1000.0, denominator: 0.3048, offset: 0.0 }, displayLabel: "mft" },
{ name: "Units.IN", phenomenon: "Units.LENGTH", system: "Units.USCUSTOM", conversion: { numerator: 1.0, denominator: 0.0254, offset: 0.0 }, displayLabel: "in" },
{ name: "Units.FT", phenomenon: "Units.LENGTH", system: "Units.USCUSTOM", conversion: { numerator: 1.0, denominator: 0.3048, offset: 0.0 }, displayLabel: "ft" },
{ name: "Units.CHAIN", phenomenon: "Units.LENGTH", system: "Units.USCUSTOM", conversion: { numerator: 1.0, denominator: 66.0 * 0.3048, offset: 0.0 }, displayLabel: "chain" },
{ name: "Units.YRD", phenomenon: "Units.LENGTH", system: "Units.USCUSTOM", conversion: { numerator: 1.0, denominator: 0.9144, offset: 0.0 }, displayLabel: "yd" },
{ name: "Units.MILE", phenomenon: "Units.LENGTH", system: "Units.USCUSTOM", conversion: { numerator: 1.0, denominator: 1609.344, offset: 0.0 }, displayLabel: "mi" },
{ name: "Units.US_SURVEY_FT", phenomenon: "Units.LENGTH", system: "Units.USSURVEY", conversion: { numerator: 3937.0, denominator: 1200.0, offset: 0.0 }, displayLabel: "ft (US Survey)" },
{ name: "Units.US_SURVEY_YRD", phenomenon: "Units.LENGTH", system: "Units.USSURVEY", conversion: { numerator: 3937.0, denominator: 3.0 * 1200.0, offset: 0.0 }, displayLabel: "yrd (US Survey)" },
{ name: "Units.US_SURVEY_IN", phenomenon: "Units.LENGTH", system: "Units.USSURVEY", conversion: { numerator: 3937.0, denominator: 100.0, offset: 0.0 }, displayLabel: "in (US Survey)" },
{ name: "Units.US_SURVEY_MILE", phenomenon: "Units.LENGTH", system: "Units.USSURVEY", conversion: { numerator: 3937.0, denominator: 5280.0 * 1200.0, offset: 0.0 }, displayLabel: "mi (US Survey)" },
{ name: "Units.US_SURVEY_CHAIN", phenomenon: "Units.LENGTH", system: "Units.USSURVEY", conversion: { numerator: 1.0, denominator: 20.11684, offset: 0.0 }, displayLabel: "chain (US Survey)" },
// conversion => specified unit to base unit of m²
{ name: "Units.SQ_FT", phenomenon: "Units.AREA", system: "Units.USCUSTOM", conversion: { numerator: 1.0, denominator: .09290304, offset: 0.0 }, displayLabel: "ft²" },
{ name: "Units.SQ_US_SURVEY_FT", phenomenon: "Units.AREA", system: "Units.USCUSTOM", conversion: { numerator: 15499969.0, denominator: 1440000, offset: 0.0 }, displayLabel: "ft² (US Survey)" },
{ name: "Units.SQ_M", phenomenon: "Units.AREA", system: "Units.SI", conversion: { numerator: 1.0, denominator: 1.0, offset: 0.0 }, displayLabel: "m²" },
// conversion => specified unit to base unit m³
{ name: "Units.CUB_FT", phenomenon: "Units.VOLUME", system: "Units.USCUSTOM", conversion: { numerator: 1.0, denominator: 0.028316847, offset: 0.0 }, displayLabel: "ft³" },
{ name: "Units.CUB_US_SURVEY_FT", phenomenon: "Units.VOLUME", system: "Units.USSURVEY", conversion: { numerator: 1, denominator: 0.0283170164937591, offset: 0.0 }, displayLabel: "ft³" },
{ name: "Units.CUB_YRD", phenomenon: "Units.VOLUME", system: "Units.USCUSTOM", conversion: { numerator: 1.0, denominator: 0.76455486, offset: 0.0 }, displayLabel: "yd³" },
{ name: "Units.CUB_M", phenomenon: "Units.VOLUME", system: "Units.SI", conversion: { numerator: 1.0, denominator: 1.0, offset: 0.0 }, displayLabel: "m³" },
]; | the_stack |
import {
getRandStr,
TFrontendDependency,
TModuleConfig,
TPackageCromwellConfig,
TPackageJson,
TPagesMetaInfo,
TPluginConfig,
TRollupConfig,
TScriptMetaInfo,
} from '@cromwell/core';
import {
buildDirName,
getLogger,
getMetaInfoPath,
getModuleStaticDir,
getPluginBackendPath,
getPublicPluginsDir,
getPublicThemesDir,
getThemePagesMetaPath,
getThemePagesVirtualPath,
getThemeTempRollupBuildDir,
isExternalForm,
pluginAdminBundlePath,
pluginFrontendBundlePath,
pluginFrontendCjsPath,
} from '@cromwell/core-backend';
import { babel } from '@rollup/plugin-babel';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import virtual from '@rollup/plugin-virtual';
import chokidar from 'chokidar';
import cryptoRandomString from 'crypto-random-string';
import { walk } from 'estree-walker';
import fs from 'fs-extra';
import glob from 'glob';
import isPromise from 'is-promise';
import normalizePath from 'normalize-path';
import { dirname, isAbsolute, join, resolve } from 'path';
import { OutputOptions, Plugin, RollupOptions } from 'rollup';
import {
collectFrontendDependencies,
collectPackagesInfo,
cromwellStoreModulesPath,
getDepVersion,
getNodeModuleVersion,
globPackages,
interopDefaultContent,
parseFrontendDeps,
} from '../shared';
import externalGlobals from './rollup-globals';
const logger = getLogger(false);
const resolveExternal = (source: string, frontendDeps?: TFrontendDependency[]): boolean => {
// Mark all as external for backend bundle and only include in frontendDeps for frontend bundle
if (isExternalForm(source)) {
if (frontendDeps) {
// Frontend
if (frontendDeps.some(dep => dep.name === source)) {
return true;
} else {
return false;
}
} else {
// Backend
return true;
}
}
return false;
}
export const rollupConfigWrapper = async (moduleInfo: TPackageCromwellConfig, moduleConfig?: TModuleConfig, watch?: boolean): Promise<RollupOptions[]> => {
if (!moduleInfo) throw new Error(`CromwellPlugin Error. Provide config as second argument to the wrapper function`);
if (!moduleInfo?.type) throw new Error(`CromwellPlugin Error. Provide one of types to the CromwellConfig: 'plugin', 'theme'`);
try {
const pckg: TPackageJson = require(resolve(process.cwd(), 'package.json'));
if (pckg?.name) moduleInfo.name = pckg.name;
} catch (e) {
logger.error('Failed to find package.json in project root');
logger.error(e);
}
if (!moduleInfo.name) throw new Error(`CromwellPlugin Error. Failed to find name of the package in working directory`);
const strippedName = moduleInfo.name.replace(/\W/g, '_');
const packagePaths = await globPackages(process.cwd());
const packages = collectPackagesInfo(packagePaths);
const frontendDeps = await collectFrontendDependencies(packages, false);
let specifiedOptions: TRollupConfig | undefined = moduleConfig?.rollupConfig?.() as any;
if (isPromise(specifiedOptions)) specifiedOptions = await specifiedOptions as any;
const inputOptions = specifiedOptions?.main;
const outOptions: RollupOptions[] = [];
const resolveFileExtension = (basePath: string): string | undefined => {
const globStr = `${normalizePath(resolve(process.cwd(), basePath))}.+(ts|tsx|js|jsx)`;
const files = glob.sync(globStr);
return files[0]
}
if (moduleInfo.type === 'plugin') {
const pluginConfig = moduleConfig as TPluginConfig | undefined;
let frontendInputFile = pluginConfig?.frontendInputFile;
if (!frontendInputFile) {
frontendInputFile = resolveFileExtension('src/frontend/index');
}
if (frontendInputFile) {
// Plugin frontend
const options: RollupOptions = (Object.assign({}, specifiedOptions?.frontend ?? inputOptions));
const inputPath = isAbsolute(frontendInputFile) ? normalizePath(frontendInputFile) :
normalizePath(resolve(process.cwd(), frontendInputFile));
const optionsInput = '$$' + moduleInfo.name + '/' + frontendInputFile;
options.input = optionsInput;
options.output = Object.assign({}, options.output, {
file: resolve(process.cwd(), buildDirName, pluginFrontendBundlePath),
format: "iife",
exports: 'default',
name: strippedName,
banner: '(function() {',
footer: `return ${strippedName};})();`
} as OutputOptions);
options.plugins = [...(options.plugins ?? [])];
options.plugins.push(virtual({
[optionsInput]: `
import defaultComp from '${inputPath}';
export default defaultComp;
`
}))
options.plugins.push(await rollupPluginCromwellFrontend({
moduleInfo,
moduleConfig,
frontendDeps,
}));
outOptions.push(options);
// Plugin frontend cjs (for getStaticPaths at server)
const cjsOptions = Object.assign({}, specifiedOptions?.frontendCjs ?? inputOptions);
cjsOptions.input = optionsInput;
cjsOptions.output = Object.assign({}, cjsOptions.output, {
file: resolve(process.cwd(), buildDirName, pluginFrontendCjsPath),
format: "cjs",
name: moduleInfo.name,
exports: "auto"
} as OutputOptions)
cjsOptions.plugins = [...(cjsOptions.plugins ?? [])];
cjsOptions.plugins.push(virtual({
[optionsInput]: `
import * as allExports from '${inputPath}';
export default allExports;
`
}))
cjsOptions.plugins.push(await rollupPluginCromwellFrontend({
generateMeta: false,
moduleInfo,
moduleConfig,
}));
outOptions.push(cjsOptions);
}
// Plugin admin panel
let adminInputFile = pluginConfig?.adminInputFile;
if (!adminInputFile) {
adminInputFile = resolveFileExtension('src/admin/index');
}
if (adminInputFile) {
const options = (Object.assign({}, specifiedOptions?.frontend ?? inputOptions));
const inputPath = isAbsolute(adminInputFile) ? normalizePath(adminInputFile) :
normalizePath(resolve(process.cwd(), adminInputFile));
const optionsInput = '$$' + moduleInfo.name + '/' + adminInputFile;
options.input = optionsInput;
options.output = Object.assign({}, options.output, {
file: resolve(process.cwd(), buildDirName, pluginAdminBundlePath),
format: "iife",
name: strippedName,
} as OutputOptions);
options.plugins = [...(options.plugins ?? [])];
options.plugins.push(virtual({
[optionsInput]: `
import '${inputPath}';
`
}))
options.plugins.push(await rollupPluginCromwellFrontend({
moduleInfo,
moduleConfig,
frontendDeps,
}));
outOptions.push(options);
}
// Plugin backend
const backendInputFile = resolveFileExtension(pluginConfig?.backend ?? 'src/backend/index');
if (backendInputFile) {
const cjsOptions = Object.assign({}, specifiedOptions?.backend ?? inputOptions);
cjsOptions.input = backendInputFile;
cjsOptions.output = Object.assign({}, cjsOptions.output, {
file: getPluginBackendPath(resolve(process.cwd(), buildDirName)),
format: "cjs",
name: moduleInfo.name,
exports: "auto"
} as OutputOptions)
cjsOptions.plugins = [...(cjsOptions.plugins ?? [])];
cjsOptions.external = isExternalForm;
outOptions.push(cjsOptions);
}
// Copy static into public
if (watch) {
startStaticWatcher(moduleInfo.name, 'plugin');
} else {
const pluginStaticDir = await getModuleStaticDir(moduleInfo.name)
if (pluginStaticDir && await fs.pathExists(pluginStaticDir)) {
try {
const publicPluginsDir = getPublicPluginsDir();
await fs.ensureDir(publicPluginsDir);
await fs.copy(pluginStaticDir, resolve(publicPluginsDir, moduleInfo.name));
} catch (e) { logger.log(e) }
}
}
}
if (moduleInfo.type === 'theme') {
const buildDir = normalizePath(getThemeTempRollupBuildDir());
if (!buildDir) throw new Error(`CromwellPlugin Error. Failed to find package directory of ` + moduleInfo.name);
let srcDir = process.cwd();
let pagesDirChunk = 'pages';
let pagesDir = resolve(srcDir, pagesDirChunk);
if (!fs.existsSync(pagesDir)) {
srcDir = resolve(process.cwd(), 'src');
pagesDir = resolve(srcDir, 'pages');
pagesDirChunk = 'src/pages';
}
if (!fs.pathExistsSync(pagesDir)) {
throw new Error('Pages directory was not found')
}
// Theme frontend
const options: RollupOptions = (Object.assign({}, specifiedOptions?.themePages ? specifiedOptions.themePages : inputOptions));
const globStr = `${pagesDir}/**/*.+(ts|tsx|js|jsx)`;
const pageFiles = glob.sync(globStr);
const pagesMetaInfo = await collectPages({
buildDir,
pagesDir,
});
const dependencyOptions: RollupOptions[] = [];
if (pageFiles && pageFiles.length > 0) {
options.plugins = [...(options.plugins ?? [])];
options.input = getThemePagesVirtualPath(buildDir);
options.output = Object.assign({}, options.output, {
dir: buildDir,
format: "esm",
preserveModules: true
} as OutputOptions);
options.plugins.push(scssExternalPlugin());
if (!options.plugins.find(plugin => typeof plugin === 'object' && plugin?.name === '@rollup/plugin-babel' ||
typeof plugin === 'object' && plugin?.name === 'babel'))
options.plugins.push(babel({
extensions: ['.js', '.jsx', '.ts', '.tsx'],
babelHelpers: 'bundled',
presets: ['@babel/preset-react']
}));
options.plugins.push(await rollupPluginCromwellFrontend({
pagesMetaInfo, buildDir, srcDir, moduleInfo,
moduleConfig, watch,
generatePagesMeta: true,
frontendDeps, dependencyOptions,
type: 'themePages',
pagesDir,
}));
if (!options.plugins.find(plugin => typeof plugin === 'object' && plugin?.name === '@rollup/plugin-node-resolve'
|| typeof plugin === 'object' && plugin?.name === 'node-resolve'))
options.plugins.push(nodeResolve({
extensions: ['.js', '.jsx', '.ts', '.tsx'],
}));
outOptions.push(options);
if (watch) {
startPagesWatcher(buildDir, pagesDir);
}
} else {
throw new Error('CromwellPlugin Error. No pages found at: ' + pagesDir);
}
// Copy static into public
if (watch) {
startStaticWatcher(moduleInfo.name, 'theme');
} else {
const themeStaticDir = await getModuleStaticDir(moduleInfo.name);
if (themeStaticDir && await fs.pathExists(themeStaticDir)) {
try {
const publicThemesDir = getPublicThemesDir();
await fs.ensureDir(publicThemesDir);
await fs.copy(themeStaticDir, resolve(publicThemesDir, moduleInfo.name), {
overwrite: false,
});
} catch (e) { logger.log(e) }
}
}
// Theme admin panel page-controller
const adminPanelDirChunk = 'admin-panel';
const adminPanelDir = resolve(srcDir, adminPanelDirChunk);
if (!watch && fs.pathExistsSync(adminPanelDir)) {
const adminOptions: RollupOptions = (Object.assign({}, specifiedOptions?.themePages ? specifiedOptions.themePages : inputOptions));
adminOptions.plugins = [...(adminOptions.plugins ?? [])];
const optionsInput = '$$' + moduleInfo.name + '/' + adminPanelDirChunk;
adminOptions.plugins.push(virtual({
[optionsInput]: `import settings from '${normalizePath(adminPanelDir)}'; export default settings`
}));
adminOptions.input = optionsInput;
adminOptions.output = Object.assign({}, adminOptions.output, {
dir: resolve(buildDir, 'admin', '_settings'),
format: "iife",
} as OutputOptions);
adminOptions.plugins.push(await rollupPluginCromwellFrontend({
pagesMetaInfo, buildDir, srcDir,
moduleInfo, moduleConfig, frontendDeps,
pagesDir,
}));
outOptions.push(adminOptions);
}
}
return outOptions;
}
const scssExternalPlugin = (): Plugin => {
return {
name: 'cromwell-scssExternalPlugin',
resolveId(source) {
if (/\.s?css$/.test(source)) {
return { id: source, external: true };
}
}
}
}
export const rollupPluginCromwellFrontend = async (settings?: {
packageJsonPath?: string;
generateMeta?: boolean;
generatePagesMeta?: boolean;
pagesMetaInfo?: TPagesMetaInfo;
buildDir?: string;
srcDir?: string;
pagesDir?: string;
watch?: boolean;
moduleInfo?: TPackageCromwellConfig;
moduleConfig?: TModuleConfig;
frontendDeps?: TFrontendDependency[];
dependencyOptions?: RollupOptions[];
type?: 'themePages' | 'themeAdminPanel';
}): Promise<Plugin> => {
const scriptsInfo: Record<string, TScriptMetaInfo> = {};
const importsInfo: Record<string, {
externals: Record<string, string[]>;
internals: string[];
}> = {};
if (settings?.frontendDeps) settings.frontendDeps = await parseFrontendDeps(settings.frontendDeps);
// Defer stylesheetsLoader until compile info available. Look for: stylesheetsLoaderStarter()
let stylesheetsLoaderStarter;
if (settings?.srcDir && settings?.buildDir) {
(async () => {
await new Promise(resolve => {
stylesheetsLoaderStarter = resolve;
})
if (settings?.srcDir && settings?.buildDir)
initStylesheetsLoader(settings?.srcDir, settings?.buildDir, settings?.pagesMetaInfo?.basePath, settings?.watch);
})();
}
const packageJson: TPackageJson = require(resolve(process.cwd(), 'package.json'));
const plugin: Plugin = {
name: 'cromwell-frontend',
options(options: RollupOptions) {
if (!options.plugins) options.plugins = [];
options.plugins.push(externalGlobals((id: string) => {
if (settings?.moduleInfo?.type === 'theme' && settings?.pagesMetaInfo?.paths) {
// Disable for Theme pages
return;
}
const extStr = `${cromwellStoreModulesPath}["${id}"]`;
if (id.startsWith('next/')) {
return extStr;
}
const isExt = resolveExternal(id, settings?.frontendDeps);
if (isExt) return extStr;
}, {
include: '**/*.+(ts|tsx|js|jsx)',
createVars: true,
}));
return options;
},
resolveId(source) {
if (settings?.moduleInfo?.type === 'theme' && settings?.pagesMetaInfo?.paths) {
// If bundle frontend pages mark css as external to leave it to Next.js Webpack
if (/\.s?css$/.test(source)) {
return { id: source, external: true };
}
// All node_modules are external to leave them to next.js
if (isExternalForm(source)) {
return { id: source, external: true };
}
}
if (resolveExternal(source, settings?.frontendDeps)) {
// Mark external frontendDependencies from package.json
return { id: source, external: true };
}
if (isExternalForm(source)) {
// Other node_modules...
if (source.startsWith('next/')) {
// Leave Next.js modules external for the next step
return { id: source, external: true };
}
if (/\.s?css$/.test(source)) {
// Bundle css with AdminPanel pages
return { id: require.resolve(source), external: false };
}
// Bundled by Rollup by for Themes and Plugins
return { id: require.resolve(source), external: false };
}
return null;
},
};
if (settings?.generateMeta !== false) {
plugin.transform = function (code, id): string | null {
id = normalizePath(id).replace('\x00', '');
if (!/\.(m?jsx?|tsx?)$/.test(id)) return null;
const ast = this.parse(code);
walk(ast, {
enter(node: any) {
if (node.type === 'ImportDeclaration') {
if (!node.specifiers || !node.source) return;
const source = node.source.value.replace('\x00', '');
if (!importsInfo[id]) importsInfo[id] = {
externals: {},
internals: []
};
if (!isExternalForm(source)) {
const absolutePath = resolve(dirname(id), source);
const globStr = `${absolutePath}.+(ts|tsx|js|jsx)`;
const targetFiles = glob.sync(globStr);
if (targetFiles[0]) importsInfo[id].internals.push(targetFiles[0]);
return;
}
// Add external
if (resolveExternal(source, settings?.frontendDeps)) {
if (!importsInfo[id].externals[source]) importsInfo[id].externals[source] = [];
node.specifiers.forEach(spec => {
if (spec.type === 'ImportDefaultSpecifier' || spec.type === 'ImportNamespaceSpecifier') {
importsInfo[id].externals[source].push('default')
}
if (spec.type === 'ImportSpecifier' && spec.imported) {
importsInfo[id].externals[source].push(spec.imported.name)
}
})
}
}
}
});
return null;
};
plugin.generateBundle = async function (options, bundle) {
if (settings?.pagesMetaInfo && settings.buildDir && settings.pagesDir) {
settings.pagesMetaInfo = await collectPages({
buildDir: settings.buildDir,
pagesDir: settings.pagesDir,
});
}
Object.values(bundle).forEach((info: any) => {
const mergeBindings = (bindings1, bindings2): Record<string, string[]> => {
const mergedBindings = Object.assign({}, bindings1);
Object.keys(bindings2).forEach(modDep => {
if (mergedBindings[modDep]) {
mergedBindings[modDep] = [...mergedBindings[modDep], ...bindings2[modDep]];
mergedBindings[modDep] = Array.from(new Set(mergedBindings[modDep]));
}
else mergedBindings[modDep] = bindings2[modDep];
})
return mergedBindings;
}
const importBindingsCache: Record<string, Record<string, string[]>> = {}
const getImportBingingsForModule = (modId: string): Record<string, string[]> => {
modId = normalizePath(modId);
if (importBindingsCache[modId]) return importBindingsCache[modId];
let importedBindings = {};
importBindingsCache[modId] = {};
if (importsInfo[modId]) {
Object.keys(importsInfo[modId].externals).forEach(libName => {
if (!isExternalForm(libName)) return;
const importsSpecs = importsInfo[modId].externals[libName];
importsSpecs?.forEach(spec => {
if (!importedBindings[libName]) importedBindings[libName] = [];
if (!importedBindings[libName].includes(spec)) {
importedBindings[libName].push(spec);
}
});
});
importsInfo[modId].internals.forEach(internal => {
const internalBinds = getImportBingingsForModule(internal);
importedBindings = mergeBindings(importedBindings, internalBinds);
})
}
importBindingsCache[modId] = importedBindings;
return importedBindings;
}
let totalImportedBindings = {};
if (info.modules) {
Object.keys(info.modules).forEach(modId => {
const modBindings = getImportBingingsForModule(modId);
totalImportedBindings = mergeBindings(totalImportedBindings, modBindings);
})
}
const versionedImportedBindings = {};
Object.keys(totalImportedBindings).forEach(dep => {
let ver = getNodeModuleVersion(dep, process.cwd());
if (!ver) {
ver = getDepVersion(packageJson, dep);
}
if (ver) {
if (totalImportedBindings[dep].includes('default')) totalImportedBindings[dep] = ['default'];
versionedImportedBindings[`${dep}@${ver}`] = totalImportedBindings[dep];
}
})
const metaInfo: TScriptMetaInfo = {
name: settings?.moduleInfo?.name + '/' + info.fileName + '_' + cryptoRandomString({ length: 8 }),
externalDependencies: versionedImportedBindings,
// importsInfo
// info
};
scriptsInfo[info.fileName] = metaInfo;
this.emitFile({
type: 'asset',
fileName: getMetaInfoPath(info.fileName),
source: JSON.stringify(metaInfo, null, 2)
});
if (settings?.pagesMetaInfo?.paths && settings.buildDir && settings.generatePagesMeta) {
settings.pagesMetaInfo.paths = settings.pagesMetaInfo.paths.map(paths => {
if (info.fileName && paths.srcFullPath === normalizePath(info.facadeModuleId)) {
paths.localPath = info.fileName;
// Get base path chunk that appended in build dir relatively src dir.
// Since we use preserveModules: true, node_modules can appear in build dir.
// That will relatively move rollup's options.output.dir on a prefix
// We don't know this prefix (basePath) before compile, so we calc it here:
if (!settings?.pagesMetaInfo?.basePath && settings?.srcDir && info.facadeModuleId) {
let baseFileName: any = normalizePath(info.facadeModuleId).replace(normalizePath(settings.srcDir), '').split('.');
baseFileName.length > 1 ? baseFileName = baseFileName.slice(0, -1).join('.') : baseFileName.join('.');
let basePath: any = normalizePath(info.fileName).split('.');
basePath.length > 1 ? basePath = basePath.slice(0, -1).join('.') : basePath.join('.');
if ((basePath as string).startsWith('/')) basePath = (basePath as string).substring(1);
if ((baseFileName as string).startsWith('/')) baseFileName = (baseFileName as string).substring(1);
basePath = normalizePath(basePath).replace(baseFileName, '');
if (settings?.pagesMetaInfo) {
settings.pagesMetaInfo.basePath = basePath;
if (stylesheetsLoaderStarter) {
stylesheetsLoaderStarter();
stylesheetsLoaderStarter = null;
}
}
}
delete paths.srcFullPath;
}
return paths;
})
}
});
if (settings?.pagesMetaInfo?.paths && settings.srcDir && settings.buildDir && settings.generatePagesMeta) {
await generatePagesMeta(settings.pagesMetaInfo, settings.buildDir)
}
}
plugin.writeBundle = function () {
if (hasToRunRendererGenerator) {
hasToRunRendererGenerator = false;
const { generator } = require('@cromwell/renderer/build/generator');
generator({
scriptName: "build",
targetThemeName: settings?.moduleInfo?.name,
});
}
}
}
return plugin;
}
let hasToRunRendererGenerator = false;
const generatePagesMeta = async (pagesMetaInfo: TPagesMetaInfo, buildDir: string) => {
// Generate lists of frontend node_modules
// that are going to be bundled in one chunk by Next.js to load
// on first page open when a client has no cached modules.
// By default frontend modules are requested by separate requests from client
// So this optimization basically cuts hundreds of requests on first load.
// List mapped from package.json's cromwell.firstLoadedDependencies
// Beware! For now this feature works in a way that
// modules are going to be bundled entirely without any tree-shaking
// We definitely don't want @mui/icons-material in this list!
const packageJson: TPackageJson = require(resolve(process.cwd(), 'package.json'));
for (const pagePath of pagesMetaInfo.paths) {
if (pagePath?.localPath && packageJson.cromwell?.firstLoadedDependencies) {
packageJson.cromwell.firstLoadedDependencies = Array.from(new Set(packageJson.cromwell.firstLoadedDependencies));
let importsStr = `${interopDefaultContent}\n`;
importsStr += `
import { getModuleImporter } from '@cromwell/core-frontend';
const importer = getModuleImporter();\n`;
for (const depName of packageJson.cromwell.firstLoadedDependencies) {
const strippedDepName = depName.replace(/\W/g, '_') + '_' + getRandStr(4);
importsStr += `
import * as ${strippedDepName} from '${depName}';
importer.modules['${depName}'] = interopDefault(${strippedDepName}, 'default');
importer.importStatuses['${depName}'] = 'default';
`;
}
const generatedFileName = normalizePath(resolve(buildDir, 'dependencies', pagePath.pageName + '.generated.js'));
fs.outputFileSync(generatedFileName, importsStr);
pagePath.localDepsBundle = generatedFileName
.replace(buildDir, '').replace(/^\//, '');
// Code below generates lists with actually used keys of modules (very useful feature)
// But currently it doesn't work, bcs if Importer in browser will try to load additional
// key, we'll have two instances of a module. In case with material-ui or react it will
// crash everything. But code can be reused later if we'll decide to make it work.
// const meta = scriptsInfo[pagePath.localPath];
// if (meta?.externalDependencies) {
// let importsStr = `${interopDefaultContent}\n`;
// for (const usedModule of Object.keys(meta.externalDependencies)) {
// const usedkeys = meta.externalDependencies[usedModule];
// let usedModuleName: string[] | string = usedModule.split('@');
// usedModuleName.pop();
// usedModuleName = usedModuleName.join('@');
// if (rendererDefaultDeps.includes(usedModuleName) ||
// usedModuleName.startsWith('next/')) continue;
// if (!packageJson.cromwell?.firstLoadedDependencies ||
// !packageJson.cromwell?.firstLoadedDependencies.includes(usedModuleName)) continue;
// const strippedusedModuleName = usedModuleName.replace(/\W/g, '_') + '_' + getRandStr(4);
// // if (usedkeys.includes('default')) {
// importsStr += `
// import * as ${strippedusedModuleName} from '${usedModuleName}';
// ${getGlobalModuleStr(usedModuleName)} = interopDefault(${strippedusedModuleName}, 'default');
// ${getGlobalModuleStr(usedModuleName)}.didDefaultImport = true;
// `
// // } else {
// // let importKeysStr = '';
// // let exportKeysStr = '';
// // usedkeys.forEach((key, index) => {
// // const keyAs = key + '_' + getRandStr(4);
// // importKeysStr += `${key} as ${keyAs}`;
// // exportKeysStr += `${key}: ${keyAs}`;
// // if (index < usedkeys.length - 1) {
// // importKeysStr += ', ';
// // exportKeysStr += ', ';
// // }
// // })
// // importsStr += `
// // import { ${importKeysStr} } from '${resolvedModuleName}';
// // ${getGlobalModuleStr(usedModuleName)} = { ${exportKeysStr} };
// // `
// // }
// }
// const generatedFileName = normalizePath(resolve(settings.buildDir, 'dependencies', pagePath.pageName + '.generated.js'));
// fs.outputFileSync(generatedFileName, importsStr);
// pagePath.localDepsBundle = generatedFileName
// .replace(settings.buildDir!, '').replace(/^\//, '');
// }
}
}
delete pagesMetaInfo.buildDir;
fs.outputFileSync(getThemePagesMetaPath(buildDir), JSON.stringify(pagesMetaInfo, null, 2));
}
const stylesheetsLoaderDirs: string[] = [];
const initStylesheetsLoader = (srcDir: string, buildDir: string, basePath?: string, watch?: boolean) => {
if (stylesheetsLoaderDirs.includes(srcDir)) return;
stylesheetsLoaderDirs.push(srcDir);
const globStr = `${normalizePath(srcDir)}/**/*.+(css|scss|sass)`;
const getBuildPath = (styleSheetPath: string) => {
const finalBuildDir = basePath ? join(buildDir, basePath) : buildDir;
return normalizePath(styleSheetPath).replace(normalizePath(srcDir),
normalizePath(finalBuildDir));
}
const copyFile = async (styleSheetPath: string) => {
const styleSheetBuildPath = getBuildPath(styleSheetPath);
await fs.ensureDir(dirname(styleSheetBuildPath));
await fs.copyFile(styleSheetPath, styleSheetBuildPath);
}
const removeFile = async (styleSheetPath: string) => {
const styleSheetBuildPath = getBuildPath(styleSheetPath);
await fs.remove(styleSheetBuildPath);
}
if (!watch) {
const targetFiles = glob.sync(globStr);
targetFiles.forEach(copyFile);
return;
}
const watcher = chokidar.watch(globStr, {
ignored: /(^|[/\\])\../, // ignore dotfiles
persistent: true
});
watcher
.on('add', copyFile)
.on('change', copyFile)
.on('unlink', removeFile);
}
const collectPages = async (settings: {
buildDir: string;
pagesDir: string;
}): Promise<TPagesMetaInfo> => {
const { pagesDir, buildDir } = settings;
const globStr = `${pagesDir}/**/*.+(ts|tsx|js|jsx)`;
const pageFiles = glob.sync(globStr);
const pagesMetaInfo: TPagesMetaInfo = {
paths: [],
buildDir,
}
let pageImports = '';
for (let fileName of pageFiles) {
fileName = normalizePath(fileName);
const pageName = fileName.replace(normalizePath(pagesDir) + '/', '').replace(/\.(m?jsx?|tsx?)$/, '');
pagesMetaInfo.paths.push({
srcFullPath: fileName,
pageName
});
pageImports += `export * as Page_${pageName.replace(/\W/g, '_')} from '${fileName}';\n`;
}
const importsFilePath = getThemePagesVirtualPath(buildDir);
const prevImports = await fs.pathExists(importsFilePath) ? (await fs.readFile(importsFilePath)).toString() : undefined;
if (prevImports !== pageImports) {
await fs.outputFile(importsFilePath, pageImports);
}
return pagesMetaInfo;
}
let pagesWatcherActive = false;
const startPagesWatcher = (buildDir: string, pagesDir: string) => {
if (pagesWatcherActive) return;
pagesWatcherActive = true;
pagesDir = normalizePath(pagesDir);
const globStr = `${pagesDir}/**/*.+(ts|tsx|js|jsx)`;
const updatePagesInfo = async () => {
await collectPages({
buildDir,
pagesDir,
});
hasToRunRendererGenerator = true;
}
const watcher = chokidar.watch(globStr, {
ignored: /(^|[/\\])\../, // ignore dotfiles
persistent: true
});
watcher
.on('add', updatePagesInfo)
.on('unlink', updatePagesInfo);
}
let staticWatcherActive = false;
const startStaticWatcher = async (moduleName: string, type: 'theme' | 'plugin') => {
if (staticWatcherActive) return;
staticWatcherActive = true;
const staticDir = normalizePath((await getModuleStaticDir(process.cwd())) ?? '');
await fs.ensureDir(staticDir);
const publicDir = type === 'theme' ? getPublicThemesDir() : getPublicPluginsDir();
const globStr = `${staticDir}/**`;
const copyFile = async (filePath: string) => {
const pathChunk = normalizePath(filePath).replace(staticDir, '');
const publicPath = join(publicDir, moduleName, pathChunk);
try {
await fs.ensureDir(dirname(publicPath));
await fs.copyFile(filePath, publicPath);
} catch (error) {
console.error(error);
}
}
const watcher = chokidar.watch(globStr, {
persistent: true
});
watcher
.on('change', copyFile)
.on('add', copyFile)
} | the_stack |
import * as util from 'util';
import * as assert from 'assert';
import {BaseMemory} from './basememory';
import {Memory, MemAttribute} from './memory';
import {NumberType} from './numbertype'
import {Format} from './format';
/// Classifies opcodes.
export enum OpcodeFlag {
NONE = 0,
BRANCH_ADDRESS = 0x01, ///< contains a branch address, e.g. jp, jp cc, jr, jr cc, call, call cc.
CALL = 0x02, ///< is a subroutine call, e.g. call, call cc or rst
STOP = 0x04, ///< is a stop-code. E.g. ret, reti, jp or jr. Disassembly procedure stops here.
RET = 0x08, ///< is a RETURN from a subroutine
CONDITIONAL = 0x10, ///< is a conditional opcode, e.g. JP NZ, RET Z, CALL P etc.
LOAD_STACK_TOP = 0x20, ///< value is the stack top value.
COPY, ///< Is a copy instruction (used for "used registers")
}
/**
* Class for Opcodes.
* Contains the name, formatting, type and possibly a value.
*/
export class Opcode {
/// The code (byte value) of the opcode
public code: number; /// Used to test if all codes are in the right place.
/// The name of the opcode, e.g. "LD A,%d"
public name: string;
/// An optional comment, e.g. "; ZX Next opcode"
protected comment: string;
/// Opcode flags: branch-address, call, stop
public flags: OpcodeFlag;
/// The additional value in the opcode, e.g. nn or n
public valueType: NumberType;
/// The length of the opcode + value
public length: number;
/// The value (if any) used in the opcode, e.g. nn in "LD HL,nn"
/// Is only a temporary value, decoded for the current instruction.
public value: number;
/// For custom opcodes further bytes to decode can be added.
public appendValues: Array<number>;
/// For custom opcodes further bytes to decode can be added.
public appendValueTypes: Array<NumberType>;
/**
* Sets the handler to convert a number into a label string.
* If handler is undefined then value will not be converted, i.e. it remains
* a hex value.
* @param handler Gets the value and should return a string with the label.
* If label string does not exist it can return undefinde and the value will be converted into a hex string.
*/
public static setConvertToLabelHandler(handler: (value: number) => string) {
Opcode.convertToLabelHandler = handler;
}
/// The static member that holds the label converter handler.
protected static convertToLabelHandler: (value: number) => string;
/// Converts a value to a label or a hex string.
protected static convertToLabel(value: number): string {
let valueString;
if (Opcode.convertToLabelHandler)
valueString = Opcode.convertToLabelHandler(value);
if (!valueString) {
valueString = Format.getHexString(value) + 'h';
}
return valueString;
}
/// Call this to use lower case or upper case opcodes.
public static makeLowerCase() {
for (let oc of Opcodes)
oc.name = oc.name.toLowerCase();
for (let oc of OpcodesCB)
oc.name = oc.name.toLowerCase();
for (let oc of OpcodesDD)
oc.name = oc.name.toLowerCase();
for (let oc of OpcodesED)
oc.name = oc.name.toLowerCase();
for (let oc of OpcodesFD)
oc.name = oc.name.toLowerCase();
for (let oc of OpcodesDDCB)
oc.name = oc.name.toLowerCase();
for (let oc of OpcodesFDCB)
oc.name = oc.name.toLowerCase();
}
/// If true comments might be added to the opcode.
/// I.e. the hex, decimal etc. conversion of value.
public static enableComments = true;
/**
* Constructor.
* @param code The opcode number equivalent.
* @param name The mnemonic.
*/
constructor(code?: number, name = '') {
if (code == undefined)
return; // Ignore the rest because values wil be copied anyway.
name = name.trim();
this.code = code;
this.comment = '';
this.flags = OpcodeFlag.NONE;
this.valueType = NumberType.NONE;
this.value = 0;
this.length = 1; // default
// Retrieve valueType and opcode flags from name
let k;
if ((k = name.indexOf('#n')) > 0) {
if (name.substr(k + 2, 1) == 'n') { // i.e. '#nn'
// Word
this.length = 3;
// substitute formatting
name = name.substr(0, k) + '%s' + name.substr(k + 3);
// store type
const indirect = name.substr(k - 1, 1);
if (indirect == '(') {
// Enclosed in brackets ? E.g. "(20fe)" -> indirect (this is no call or jp)
this.valueType = NumberType.DATA_LBL;
}
else {
// now check for opcode flags
if (name.startsWith("CALL")) {
this.flags |= OpcodeFlag.CALL | OpcodeFlag.BRANCH_ADDRESS;
this.valueType = NumberType.CODE_SUB;
// Check if conditional
if (name.indexOf(',') >= 0)
this.flags |= OpcodeFlag.CONDITIONAL;
}
else if (name.startsWith("JP")) {
this.flags |= OpcodeFlag.BRANCH_ADDRESS;
this.valueType = NumberType.CODE_LBL;
// Now check if it is conditional, i.e. if there is a ',' in the opcode
// Check if conditional or stop code
this.flags |= (name.indexOf(',') >= 0) ? OpcodeFlag.CONDITIONAL : OpcodeFlag.STOP;
}
else if (name.startsWith("LD SP,")) {
// The stack pointer is loaded, so this is the top of the stack.
this.valueType = NumberType.DATA_LBL;
this.flags |= OpcodeFlag.LOAD_STACK_TOP;
this.comment = 'top of stack';
}
else {
// Either call nor jp
this.valueType = NumberType.NUMBER_WORD;
}
}
}
else {
// Byte
this.length = 2;
// substitute formatting
name = name.substr(0, k) + '%s' + name.substr(k + 2);
// store type
this.valueType = NumberType.NUMBER_BYTE;
// now check for opcode flags
if (name.startsWith("DJNZ")) {
//this.valueType = NumberType.CODE_LOCAL_LOOP;
this.valueType = NumberType.CODE_LOCAL_LBL; // Becomes a loop because it jumps backwards.
this.flags |= OpcodeFlag.BRANCH_ADDRESS | OpcodeFlag.CONDITIONAL;
}
if (name.startsWith("JR")) {
this.valueType = NumberType.CODE_LOCAL_LBL;
this.flags |= OpcodeFlag.BRANCH_ADDRESS;
// Check if conditional or stop code
this.flags |= (name.indexOf(',') >= 0) ? OpcodeFlag.CONDITIONAL : OpcodeFlag.STOP;
}
else if (name.startsWith("IN") || name.startsWith("OUT")) {
// a port
this.valueType = NumberType.PORT_LBL;
}
}
}
else if (name.startsWith("RET")) { // "RETN", "RETI", "RET" with or without condition
this.flags |= OpcodeFlag.RET;
// Check if conditional or stop code
this.flags |= (name.indexOf(' ') >= 0) ? OpcodeFlag.CONDITIONAL : OpcodeFlag.STOP;
}
else if (name.startsWith("RST")) { // "RST"
// Use like a CALL
this.valueType = NumberType.CODE_RST;
this.flags |= OpcodeFlag.BRANCH_ADDRESS | OpcodeFlag.CALL;
// Get jump value
const jumpAddress = this.code & 0b00111000;
this.value = jumpAddress;
}
else if (name.startsWith("JP")) { // "JP (HL)", "JP (IXY)" or "JP (C)"
// Note: we don't set a branch address because we don't know where it jumps to: this.flags |= OpcodeFlag.BRANCH_ADDRESS;
// But it is a stop code.
this.flags |= OpcodeFlag.STOP;
}
// Store
this.name = name;
}
/**
* Creates a copy object,
* @returns A new object with same values.
*/
public clone(): Opcode {
// Create empty object
const clone = Object.create(
Object.getPrototypeOf(this),
Object.getOwnPropertyDescriptors(this)
);
// Copy properties
clone.code = this.code;
clone.comment = this.comment;
clone.name = this.name;
clone.flags = this.flags;
clone.valueType = this.valueType;
clone.length = this.length;
clone.value = this.value;
clone.appendValues = this.appendValues;
clone.appendValueTypes = this.appendValueTypes;
return clone;
}
/**
* Returns the Opcode at address.
* @param address The address to retrieve.
* @returns It's opcode.
*/
public static getOpcodeAt(memory: BaseMemory, address: number, opcodes = Opcodes): Opcode {
const memValue = memory.getValueAt(address);
const opcode = opcodes[memValue];
const realOpcode = opcode.getOpcodeAt(memory, address);
return realOpcode;
}
/**
* For custom opcodes like the extension to RST.
* E.g. for a byte that follows a RST use the following appendName:
* "#n"
* This will result in e.g. the name "RST 16,#n" which will decode the
* #n as a byte in the disassembly.
* @param appendName A string that is appended to the opcode name which includes also
* further bytes to decode, e.g. "#n" or "#nn" or even "#n,#nn,#nn"
*/
public appendToOpcode(appendName: string) {
if (!appendName || appendName.length == 0)
return;
this.appendValues = new Array<number>();
this.appendValueTypes = new Array<NumberType>();
// Calculate length and convert #n to %s
let k = 0;
let text = appendName + ' ';
let len = 0;
while ((k = text.indexOf("#n", k)) >= 0) {
// Increment
len++;
// Check for word
if (text[k + 2] == "n") {
k++;
len++;
this.appendValueTypes.push(NumberType.NUMBER_WORD);
}
else {
this.appendValueTypes.push(NumberType.NUMBER_BYTE);
}
// Next
k += 2;
}
this.length += len;
// Substitute formatting
this.name += appendName.replace(/#nn?/g, "%s");
// Comment
this.comment = 'Custom opcode';
}
/**
* The 1 byte opcodes just return self (this).
* @param memory The memory area to get the opcode from.
* @param address The address of the opcode.
* @returns this
*/
public getOpcodeAt(memory: BaseMemory, address: number): Opcode {
// Get value (if any)
let offs = 0;
switch (this.valueType) {
case NumberType.CODE_RST:
case NumberType.NONE:
// no value
break;
case NumberType.CODE_LBL:
case NumberType.CODE_SUB:
case NumberType.CODE_SUB:
case NumberType.DATA_LBL:
case NumberType.NUMBER_WORD:
// word value
this.value = memory.getWordValueAt(address + 1);
offs = 2;
break;
case NumberType.NUMBER_WORD_BIG_ENDIAN:
// e.g. for PUSH $nnnn
this.value = memory.getBigEndianWordValueAt(address + 1);
offs = 2;
break;
case NumberType.RELATIVE_INDEX:
case NumberType.CODE_LOCAL_LBL:
case NumberType.CODE_LOCAL_LOOP:
// byte value
this.value = memory.getValueAt(address + 1);
offs = 1;
if (this.value >= 0x80)
this.value -= 0x100;
// Change relative jump address to absolute
if (this.valueType == NumberType.CODE_LOCAL_LBL || this.valueType == NumberType.CODE_LOCAL_LOOP)
this.value += address + 2;
break;
case NumberType.NUMBER_BYTE:
// byte value
this.value = memory.getValueAt(address + 1);
offs = 1;
break;
case NumberType.PORT_LBL:
// TODO: need to be implemented differently
this.value = memory.getValueAt(address + 1);
offs = 1;
break;
default:
assert(false, 'getOpcodeAt');
break;
}
// Check for custom code
if (this.appendValueTypes) {
this.appendValues.length = 0;
let addr = address + 1 + offs;
for (const vType of this.appendValueTypes) {
let val;
if (vType == NumberType.NUMBER_BYTE) {
val = memory.getValueAt(addr);
addr++;
}
else {
val = memory.getWordValueAt(addr);
addr += 2;
}
this.appendValues.push(val);
}
}
return this;
}
/**
* Disassembles one opcode together with a referenced label (if there
* is one).
* @returns A string that contains the disassembly, e.g. "LD A,(DATA_LBL1)"
* or "JR Z,.sub1_lbl3".
* @param memory The memory area. Used to distinguish if the access is maybe wrong.
* If this is not required (comment) the parameter can be omitted.
*/
public disassemble(memory?: Memory): {mnemonic: string, comment: string} {
// optional comment
let comment = '';
// Check if there is any value
if (this.valueType == NumberType.NONE) {
return {mnemonic: this.name, comment: this.comment};
}
// Get referenced label name
let valueName = '';
if (this.valueType == NumberType.CODE_LBL
|| this.valueType == NumberType.CODE_LOCAL_LBL
|| this.valueType == NumberType.CODE_LOCAL_LOOP
|| this.valueType == NumberType.CODE_SUB) {
const val = this.value;
valueName = Opcode.convertToLabel(val);
comment = Format.getConversionForAddress(val);
// Check if branching into the middle of an opcode
if (memory) {
const memAttr = memory.getAttributeAt(val);
if (memAttr & MemAttribute.ASSIGNED) {
if (!(memAttr & MemAttribute.CODE_FIRST)) {
// Yes, it jumps into the middle of an opcode.
comment += ', WARNING: Branches into the middle of an opcode!';
}
}
}
}
else if (this.valueType == NumberType.DATA_LBL) {
const val = this.value;
valueName = Opcode.convertToLabel(val);
comment = Format.getConversionForAddress(val);
// Check if accessing code area
if (memory) {
const memAttr = memory.getAttributeAt(val);
if (memAttr & MemAttribute.ASSIGNED) {
if (memAttr & MemAttribute.CODE) {
// Yes, code is accessed
comment += ', WARNING: Instruction accesses code!';
}
}
}
}
else if (this.valueType == NumberType.RELATIVE_INDEX) {
// E.g. in 'LD (IX+n),a'
let val = this.value;
valueName = (val >= 0) ? '+' : '';
valueName += val.toString();
}
else if (this.valueType == NumberType.CODE_RST) {
// Use value instead of label (looks better)
valueName = Format.getHexString(this.value, 2) + 'h';
}
else {
// Use direct value
const val = this.value;
// Add comment
if (this.valueType == NumberType.NUMBER_BYTE) {
// byte
valueName = Format.getHexString(val, 2) + 'h';
comment = Format.getVariousConversionsForByte(val);
}
else {
// word
valueName = Format.getHexString(val, 4) + 'h';
comment = Format.getVariousConversionsForWord(val);
}
}
// Disassemble
let opCodeString;
if (!this.appendValueTypes) {
// Nomal disassembly
opCodeString = util.format(this.name, valueName);
}
else {
// Custom opcode with appended bytes.
const len = this.appendValueTypes.length;
const vals = new Array<string>();
for (let k = 0; k < len; k++) {
const vType = this.appendValueTypes[k];
const val = this.appendValues[k];
let valName = (vType == NumberType.NUMBER_BYTE) ? Format.getHexString(val, 2) : Format.getHexString(val, 4);
valName += 'h';
vals.push(valName);
}
opCodeString = util.format(this.name, valueName, ...vals);
}
// Comments
if (Opcode.enableComments) {
if (this.comment) {
if (comment.length > 0)
comment += ', '
comment += this.comment;
}
}
else {
// no comment
comment = '';
}
return {mnemonic: opCodeString, comment: comment};
}
}
/// Opcode with a number index.
/// E.g. 0xDD 0x74 0x03 = ld (ix+3),h
class OpcodeIndex extends Opcode {
/**
* Constructor.
* Set type to relative index.
* @param code The opcode number equivalent.
* @param name The mnemonic.
*/
constructor(code?: number, name = '') {
super(code, name);
this.valueType = NumberType.RELATIVE_INDEX;
this.length++;
}
}
/// Opcode that has a number index before the opcode (DDCB).
/// E.g. 0xDD 0xCB 0x03 0x01 = ld (ix+3),c
class OpcodePrevIndex extends OpcodeIndex {
/**
* Constructor.
* Set type to relative index.
* @param code The opcode number equivalent.
* @param name The mnemonic.
*/
constructor(code?: number, name = '') {
super(code, name);
this.length++;
}
/**
* Gets the value from the byte which is PREVIOUS to the opcode.
* @param memory
* @param address
* @returns this
*/
public getOpcodeAt(memory: BaseMemory, address: number): Opcode {
this.value = memory.getValueAt(address - 1);
if (this.value >= 0x80)
this.value -= 0x100;
return this;
}
}
/// Opcode that has a number index and an immediate value.
/// E.g. 0xDD 0x36 0x03 0x08 = ld (ix+3),8
class OpcodeIndexImmediate extends Opcode {
// The second value (the immediate value, i.e. 8 in the example above.
protected secondValue: number;
/**
* Constructor.
*/
constructor(code?: number, name = '') {
super(code, name);
this.length = 3; // Is afterwards corrected to 4
this.valueType = NumberType.RELATIVE_INDEX;
}
/**
* Creates a copy object,
* @returns A new object with same values.
*/
public clone(): Opcode {
const clone = super.clone() as OpcodeIndexImmediate;
clone.secondValue = this.secondValue;
return clone;
}
/**
* Gets the value from the byte which is PREVIOUS to the opcode.
* @param memory
* @param address
* @returns this
*/
public getOpcodeAt(memory: BaseMemory, address: number): Opcode {
this.value = memory.getValueAt(address + 1);
if (this.value >= 0x80)
this.value -= 0x100;
this.secondValue = memory.getValueAt(address + 2);
return this;
}
/**
* Disassembles the opcode.
* @returns A string that contains the disassembly, e.g. "LD (IX+6),4"
* @param memory The memory area. Used to distinguish if the access is maybe wrong.
* If this is not required (comment) the parameter can be omitted.
*/
public disassemble(memory?: Memory): {mnemonic: string, comment: string} {
const dasm = super.disassemble(memory);
// Results e.g. in "LD (IX+6),%s"
const valueName = Format.getHexString(this.secondValue, 2) + 'h';
const comment = Format.getVariousConversionsForByte(this.secondValue);
const dasm2 = util.format(dasm.mnemonic, valueName);
return {mnemonic: dasm2, comment};
}
}
class OpcodeExtended extends Opcode {
/// Array that holds the sub opcodes for this opcode.
public opcodes;
/**
* On construction the array is passed which holds the opcodes for this extended opcode.
* @param code The code, e.g. 0xCD or 0xDD
* @param opcodes The array with opcodes.
*/
constructor(code: number, opcodes: Array<Opcode>) {
super(code);
this.opcodes = opcodes;
this.length += 1; // one more
}
/// Clone not supported.
public clone(): Opcode {
throw Error("Cloning of OpcodeExtended not supported.");
}
/**
* The extended opcodes must return the next byte.
* @param memory Unused
* @param address Unused
* @returns The opcode from the address after the current one.
*/
public getOpcodeAt(memory: BaseMemory, address: number): Opcode {
return Opcode.getOpcodeAt(memory, address + 1, this.opcodes);
}
}
/// 3 (4) byte opcode
class OpcodeExtended2 extends OpcodeExtended {
/// Pass also the opcode array.
constructor(code: number, opcodes: Array<Opcode>) {
super(code, opcodes);
this.length += 1; // one more
}
/**
* This is a 3 byte opcode.
* The first 2 bytes are DDCB followed by a value (for the index),
* followed by the rest of the opcode.
*/
public getOpcodeAt(memory: BaseMemory, address: number): Opcode {
return Opcode.getOpcodeAt(memory, address + 2, this.opcodes);
}
}
/// Special opcode that works as a NOP.
/// E.g. 2 0xDD after each other: Then the first 0xDD is like a nop.
class OpcodeNOP extends Opcode {
constructor(code: number) {
super(code, '');
this.name = '[NOP]\t; because of following 0x' + Format.getHexString(code, 2);
this.length--; // Does not anything to the length (but is afterwards increased)
}
}
/// Special opcode for an invalid instruction.
/// E.g. 2 0xDD after each other: Then the first 0xDD is like a nop.
class OpcodeInvalid extends Opcode {
constructor(code: number) {
super(code, '');
this.name = 'INVALID INSTRUCTION\t; mostly equivalent to NOP.';
}
}
/// Special opcodes for the ZX Spectrum next
class OpcodeNext extends Opcode {
// Constructor.
constructor(code: number, name: string) {
super(code, name);
this.comment = 'ZX Next opcode'
}
/// Clone not supported.
public clone(): Opcode {
throw Error("Cloning of OpcodeExtended not supported.");
}
}
/// Push nn must be derived because the nn is big endian.
class OpcodeNextPush extends OpcodeNext {
constructor(code: number, name: string) {
super(code, name);
this.valueType = NumberType.NUMBER_WORD_BIG_ENDIAN;
}
}
/**
* Special opcode to decode the next register
*/
class OpcodeNext_nextreg_n_a extends OpcodeNext {
/// Disassemble the next register.
/// (1 byte value)
public disassemble(): {mnemonic: string, comment: string} {
const regname = OpcodeNext_nextreg_n_a.getRegisterName(this.value);
const opCodeString = util.format(this.name, regname);
return {mnemonic: opCodeString, comment: this.comment};
}
/**
* Returns the corresponding next feature register name.
* @param regId The id of the register
* @returns The register name, e.g. "REG_VIDEO_TIMING"
*/
protected static getRegisterName(regId: number): string {
let regname;
switch (regId) {
case 0: regname = "REG_MACHINE_ID"; break;
case 1: regname = "REG_VERSION"; break;
case 2: regname = "REG_RESET"; break;
case 3: regname = "REG_MACHINE_TYPE"; break;
case 4: regname = "REG_RAM_PAGE"; break;
case 5: regname = "REG_PERIPHERAL_1"; break;
case 6: regname = "REG_PERIPHERAL_2"; break;
case 7: regname = "REG_TURBO_MODE"; break;
case 8: regname = "REG_PERIPHERAL_3"; break;
case 14: regname = "REG_SUB_VERSION"; break;
case 15: regname = "REG_VIDEO_PARAM"; break;
case 16: regname = "REG_ANTI_BRICK"; break;
case 17: regname = "REG_VIDEO_TIMING"; break;
case 18: regname = "REG_LAYER_2_RAM_PAGE"; break;
case 19: regname = "REG_LAYER_2_SHADOW_RAM_PAGE"; break;
case 20: regname = "REG_GLOBAL_TRANSPARENCY_COLOR"; break;
case 21: regname = "REG_SPRITE_LAYER_SYSTEM"; break;
case 22: regname = "REG_LAYER_2_OFFSET_X"; break;
case 23: regname = "REG_LAYER_2_OFFSET_Y"; break;
case 24: regname = "REG_CLIP_WINDOW_LAYER_2"; break;
case 25: regname = "REG_CLIP_WINDOW_SPRITES"; break;
case 26: regname = "REG_CLIP_WINDOW_ULA"; break;
case 28: regname = "REG_CLIP_WINDOW_CONTROL"; break;
case 30: regname = "REG_ACTIVE_VIDEO_LINE_H"; break;
case 31: regname = "REG_ACTIVE_VIDEO_LINE_L"; break;
case 34: regname = "REG_LINE_INTERRUPT_CONTROL"; break;
case 35: regname = "REG_LINE_INTERRUPT_VALUE_L"; break;
case 40: regname = "REG_KEYMAP_ADDRESS_H"; break;
case 41: regname = "REG_KEYMAP_ADDRESS_L"; break;
case 42: regname = "REG_KEYMAP_DATA_H"; break;
case 43: regname = "REG_KEYMAP_DATA_L"; break;
case 45: regname = "REG_DAC_MONO"; break;
case 50: regname = "REG_LORES_OFFSET_X"; break;
case 51: regname = "REG_LORES_OFFSET_Y"; break;
case 64: regname = "REG_PALETTE_INDEX"; break;
case 65: regname = "REG_PALETTE_VALUE_8"; break;
case 66: regname = "REG_ULANEXT_PALETTE_FORMAT"; break;
case 67: regname = "REG_PALETTE_CONTROL"; break;
case 68: regname = "REG_PALETTE_VALUE_16"; break;
case 74: regname = "REG_FALLBACK_COLOR"; break;
case 80: regname = "REG_MMU0"; break;
case 81: regname = "REG_MMU1"; break;
case 82: regname = "REG_MMU2"; break;
case 83: regname = "REG_MMU3"; break;
case 84: regname = "REG_MMU4"; break;
case 85: regname = "REG_MMU5"; break;
case 86: regname = "REG_MMU6"; break;
case 87: regname = "REG_MMU7"; break;
case 96: regname = "REG_COPPER_DATA"; break;
case 97: regname = "REG_COPPER_CONTROL_L"; break;
case 98: regname = "REG_COPPER_CONTROL_H"; break;
case 255: regname = "REG_DEBUG"; break;
default:
// unknown
regname = Format.getHexString(regId, 2) + 'h';
break;
}
return regname;
}
}
/**
* Special opcode to decode the 2 values.
*/
class OpcodeNext_nextreg_n_n extends OpcodeNext_nextreg_n_a {
// The 2nd value.
public value2: number;
/// Constructor.
constructor(code: number, name: string) {
super(code, name);
// There is still an '#n' to convert
this.name = this.name.replace('#n', '%s');
this.length++;
}
/// Collects the 2 values.
public getOpcodeAt(memory: BaseMemory, address: number): Opcode {
this.value = memory.getValueAt(address + 1);
this.value2 = memory.getValueAt(address + 2);
return this;
}
/// Disassemble the 2 values.
/// Both are #n (1 byte values)
public disassemble(): {mnemonic: string, comment: string} {
const regId = this.value;
const regValue = this.value2;
const regname = OpcodeNext_nextreg_n_a.getRegisterName(regId);
const valuename = OpcodeNext_nextreg_n_n.getRegisterValueName(regId, regValue);
const opCodeString = util.format(this.name, regname, valuename);
return {mnemonic: opCodeString, comment: this.comment};
}
/**
* Returns the corresponding value name for a value for a next feature register name.
* @param regId The id of the register. e.g. "REG_PERIPHERAL_1"
* @param regValue The value for the register, e.g. 0x40
* @returns E.g. "RP1_JOY1_KEMPSTON"
*/
protected static getRegisterValueName(regId: number, regValue: number): string {
let valuename;
let arr;
switch (regId) {
case 0: // REG_MACHINE_ID
switch (regValue) {
case 0: valuename = "REG_MACHINE_ID"; break;
case 1: valuename = "RMI_DE1A"; break;
case 2: valuename = "RMI_DE2A"; break;
case 5: valuename = "RMI_FBLABS"; break;
case 6: valuename = "RMI_VTRUCCO"; break;
case 7: valuename = "RMI_WXEDA"; break;
case 8: valuename = "RMI_EMULATORS"; break;
case 10: valuename = "RMI_ZXNEXT"; break; // ZX Spectrum Next
case 11: valuename = "RMI_MULTICORE"; break;
case 250: valuename = "RMI_ZXNEXT_AB"; break; // ZX Spectrum Next Anti-brick
}
break;
case 1: // REG_VERSION
valuename = Format.getHexString(regValue, 2) + 'h (v' + (regValue >>> 4) + '.' + (regValue & 0x0f) + ')';
break;
case 2: // REG_RESET
valuename = Format.getHexString(regValue, 2) + 'h';
arr = new Array<string>();
if (regValue & 0x04)
arr.push("RR_POWER_ON_RESET");
if (regValue & 0x02)
arr.push("RR_HARD_RESET");
if (regValue & 0x01)
arr.push("RR_SOFT_RESET");
if (arr.length > 0)
valuename += ' (' + arr.join('|') + ')';
break;
case 3: // REG_MACHINE_TYPE
valuename = Format.getHexString(regValue, 2) + 'h';
arr = new Array<string>();
if (regValue & 0x80)
arr.push("lock timing");
switch ((regValue >>> 4) & 0x07) {
case 0b000:
case 0b001: arr.push("Timing:ZX 48K"); break;
case 0b010: arr.push("Timing:ZX 128K"); break;
case 0b011: arr.push("Timing:ZX +2/+3e"); break;
case 0b100: arr.push("Timing:Pentagon 128K"); break;
}
switch (regValue & 0x07) {
case 0b000: arr.push("Machine:Config mode"); break;
case 0b001: arr.push("Machine:ZX 48K"); break;
case 0b010: arr.push("Machine:ZX 128K"); break;
case 0b011: arr.push("Machine:ZX +2/+3e"); break;
case 0b100: arr.push("Machine:Pentagon 128K"); break;
}
if (arr.length > 0)
valuename += ' (' + arr.join('|') + ')';
break;
case 4: // REG_RAM_PAGE
switch (regValue) {
case 0x08: valuename = "RRP_RAM_DIVMMC"; break; // 0x00
case 0x04: valuename = "RRP_ROM_DIVMMC"; break; // 0x18
case 0x05: valuename = "RRP_ROM_MF"; break; // 0x19
case 0x00: valuename = "RRP_ROM_SPECTRUM"; break; // 0x1c
}
break;
case 5: // REG_PERIPHERAL_1
switch (regValue) {
case 0x00: valuename = "RP1_JOY1_SINCLAIR"; break;
case 0x40: valuename = "RP1_JOY1_KEMPSTON"; break;
case 0x80: valuename = "RP1_JOY1_CURSOR"; break;
case 0x00: valuename = "RP1_JOY2_SINCLAIR"; break;
case 0x10: valuename = "RP1_JOY2_KEMPSTON"; break;
case 0x20: valuename = "RP1_JOY2_CURSOR"; break;
case 0x00: valuename = "RP1_RATE_50"; break;
case 0x04: valuename = "RP1_RATE_60"; break;
case 0x02: valuename = "RP1_ENABLE_SCANLINES"; break;
case 0x01: valuename = "RP1_ENABLE_SCANDOUBLER"; break;
}
break;
case 6: // REG_PERIPHERAL_2
break;
case 7: // REG_TURBO_MODE
switch (regValue) {
case 0x00: valuename = "RTM_3MHZ"; break;
case 0x01: valuename = "RTM_7MHZ"; break;
case 0x02: valuename = "RTM_14MHZ"; break;
case 0x03: valuename = "RTM_28MHZ"; break;
}
break;
case 8: // REG_PERIPHERAL_3
break;
case 14: // REG_SUB_VERSION
break;
case 15: // REG_VIDEO_PARAM
break;
case 16: // REG_ANTI_BRICK
break;
case 17: // REG_VIDEO_TIMING
break;
case 18: // REG_LAYER_2_RAM_PAGE
switch (regValue) {
case 0x3f: valuename = "RL2RP_MASK"; break;
}
break;
case 19: // REG_LAYER_2_SHADOW_RAM_PAGE
switch (regValue) {
case 0x3f: valuename = "RL2RP_MASK"; break;
}
break;
case 20: // REG_GLOBAL_TRANSPARENCY_COLOR
break;
case 21: // REG_SPRITE_LAYER_SYSTEM
switch (regValue) {
case 0x80: valuename = "RSLS_ENABLE_LORES"; break;
case 0x00: valuename = "RSLS_LAYER_PRIORITY_SLU"; break;
case 0x04: valuename = "RSLS_LAYER_PRIORITY_LSU"; break;
case 0x08: valuename = "RSLS_LAYER_PRIORITY_SUL"; break;
case 0x0c: valuename = "RSLS_LAYER_PRIORITY_LUS"; break;
case 0x10: valuename = "RSLS_LAYER_PRIORITY_USL"; break;
case 0x14: valuename = "RSLS_LAYER_PRIORITY_ULS"; break;
case 0x02: valuename = "RSLS_SPRITES_OVER_BORDER"; break;
case 0x01: valuename = "RSLS_SPRITES_VISIBLE"; break;
}
break;
case 22: // REG_LAYER_2_OFFSET_X
break;
case 23: // REG_LAYER_2_OFFSET_Y
break;
case 24: // REG_CLIP_WINDOW_LAYER_2
break;
case 25: // REG_CLIP_WINDOW_SPRITES
break;
case 26: // REG_CLIP_WINDOW_ULA
break;
case 28: // REG_CLIP_WINDOW_CONTROL
switch (regValue) {
case 0x04: valuename = "RCWC_RESET_ULA_CLIP_INDEX"; break;
case 0x02: valuename = "RCWC_RESET_SPRITE_CLIP_INDEX"; break;
case 0x01: valuename = "RCWC_RESET_LAYER_2_CLIP_INDEX"; break;
}
break;
case 30: // REG_ACTIVE_VIDEO_LINE_H
break;
case 31: // REG_ACTIVE_VIDEO_LINE_L
break;
case 34: // REG_LINE_INTERRUPT_CONTROL
switch (regValue) {
case 0x80: valuename = "RLIC_INTERRUPT_FLAG"; break;
case 0x04: valuename = "RLIC_DISABLE_ULA_INTERRUPT"; break;
case 0x02: valuename = "RLIC_ENABLE_LINE_INTERRUPT"; break;
case 0x01: valuename = "RLIC_LINE_INTERRUPT_VALUE_H"; break;
}
break;
case 35: // REG_LINE_INTERRUPT_VALUE_L
break;
case 40: // REG_KEYMAP_ADDRESS_H
break;
case 41: // REG_KEYMAP_ADDRESS_L
break;
case 42: // REG_KEYMAP_DATA_H
break;
case 43: // REG_KEYMAP_DATA_L
break;
case 45: // REG_DAC_MONO
break;
case 50: // REG_LORES_OFFSET_X
break;
case 51: // REG_LORES_OFFSET_Y
break;
case 64: // REG_PALETTE_INDEX
break;
case 65: // REG_PALETTE_VALUE_8
break;
case 66: // REG_ULANEXT_PALETTE_FORMAT
break;
case 67: // REG_PALETTE_CONTROL
switch (regValue) {
case 0x80: valuename = "RPC_DISABLE_AUTOINC"; break;
case 0x00: valuename = "RPC_SELECT_ULA_PALETTE_0"; break;
case 0x40: valuename = "RPC_SELECT_ULA_PALETTE_1"; break;
case 0x10: valuename = "RPC_SELECT_LAYER_2_PALETTE_0"; break;
case 0x50: valuename = "RPC_SELECT_LAYER_2_PALETTE_1"; break;
case 0x20: valuename = "RPC_SELECT_SPRITES_PALETTE_0"; break;
case 0x60: valuename = "RPC_SELECT_SPRITES_PALETTE_1"; break;
case 0x00: valuename = "RPC_ENABLE_SPRITES_PALETTE_0"; break;
case 0x08: valuename = "RPC_ENABLE_SPRITES_PALETTE_1"; break;
case 0x00: valuename = "RPC_ENABLE_LAYER_2_PALETTE_0"; break;
case 0x04: valuename = "RPC_ENABLE_LAYER_2_PALETTE_1"; break;
case 0x00: valuename = "RPC_ENABLE_ULA_PALETTE_0"; break;
case 0x02: valuename = "RPC_ENABLE_ULA_PALETTE_1"; break;
case 0x01: valuename = "RPC_ENABLE_ULANEXT"; break;
}
break;
case 68: // REG_PALETTE_VALUE_16
break;
case 74: // REG_FALLBACK_COLOR
break;
case 80: // REG_MMU0
break;
case 81: // REG_MMU1
break;
case 82: // REG_MMU2
break;
case 83: // REG_MMU3
break;
case 84: // REG_MMU4
break;
case 85: // REG_MMU5
break;
case 86: // REG_MMU6
break;
case 87: // REG_MMU7
break;
case 96: // REG_COPPER_DATA
break;
case 97: // REG_COPPER_CONTROL_L
break;
case 98: // REG_COPPER_CONTROL_H
switch (regValue) {
case 0x00: valuename = "RCCH_COPPER_STOP"; break;
case 0x40: valuename = "RCCH_COPPER_RUN_LOOP_RESET"; break;
case 0x80: valuename = "RCCH_COPPER_RUN_LOOP"; break;
case 0xc0: valuename = "RCCH_COPPER_RUN_VBI"; break;
}
break;
case 255: // REG_DEBUG
break;
}
// Check if undefined
if (!valuename)
valuename = Format.getHexString(regValue, 2) + 'h';
return valuename;
}
}
/// Opcodes that start with 0xED.
export const OpcodesED: Array<Opcode> = [
...Array<number>(0x23).fill(0).map((value, index) => new OpcodeInvalid(index)),
new OpcodeNext(0x23, "SWAPNIB"), // ZX Spectrum Next
new OpcodeNext(0x24, "MIRROR"), // ZX Spectrum Next
...Array<number>(0x02).fill(0).map((value, index) => new OpcodeInvalid(0x25 + index)),
new OpcodeNext(0x27, "TEST #n"), // ZX Spectrum Next
new OpcodeNext(0x28, "BSLA DE,B"), // ZX Spectrum Next
new OpcodeNext(0x29, "BSRA DE,B"), // ZX Spectrum Next
new OpcodeNext(0x2A, "BSRL DE,B"), // ZX Spectrum Next
new OpcodeNext(0x2B, "BSRF DE,B"), // ZX Spectrum Next
new OpcodeNext(0x2C, "BRLC DE,B"), // ZX Spectrum Next
...Array<number>(0x03).fill(0).map((value, index) => new OpcodeInvalid(0x2D + index)),
new OpcodeNext(0x30, "MUL D,E"), // ZX Spectrum Next
new OpcodeNext(0x31, "ADD HL,A"), // ZX Spectrum Next
new OpcodeNext(0x32, "ADD DE,A"), // ZX Spectrum Next
new OpcodeNext(0x33, "ADD BC,A"), // ZX Spectrum Next
new OpcodeNext(0x34, "ADD HL,#nn"), // ZX Spectrum Next
new OpcodeNext(0x35, "ADD DE,#nn"), // ZX Spectrum Next
new OpcodeNext(0x36, "ADD BC,#nn"), // ZX Spectrum Next
...Array<number>(0x09).fill(0).map((value, index) => new OpcodeInvalid(0x37 + index)),
new Opcode(0x40, "IN B,(C)"),
new Opcode(0x41, "OUT (C),B"),
new Opcode(0x42, "SBC HL,BC"),
new Opcode(0x43, "LD (#nn),BC"),
new Opcode(0x44, "NEG"),
new Opcode(0x45, "RETN"),
new Opcode(0x46, "IM 0"),
new Opcode(0x47, "LD I,A"),
new Opcode(0x48, "IN C,(C)"),
new Opcode(0x49, "OUT (C),C"),
new Opcode(0x4A, "ADC HL,BC"),
new Opcode(0x4B, "LD BC,(#nn)"),
new Opcode(0x4C, "[neg]"),
new Opcode(0x4D, "RETI"),
new Opcode(0x4E, "[im0]"),
new Opcode(0x4F, "LD R,A"),
new Opcode(0x50, "IN D,(C)"),
new Opcode(0x51, "OUT (C),D"),
new Opcode(0x52, "SBC HL,DE"),
new Opcode(0x53, "LD (#nn),DE"),
new Opcode(0x54, "[neg]"),
new Opcode(0x55, "[retn]"),
new Opcode(0x56, "IM 1"),
new Opcode(0x57, "LD A,I"),
new Opcode(0x58, "IN E,(C)"),
new Opcode(0x59, "OUT (C),E"),
new Opcode(0x5A, "ADC HL,DE"),
new Opcode(0x5B, "LD DE,(#nn)"),
new Opcode(0x5C, "[neg]"),
new Opcode(0x5D, "[reti]"),
new Opcode(0x5E, "IM 2"),
new Opcode(0x5F, "LD A,R"),
new Opcode(0x60, "IN H,(C)"),
new Opcode(0x61, "OUT (C),H"),
new Opcode(0x62, "SBC HL,HL"),
new Opcode(0x63, "LD (#nn),HL"),
new Opcode(0x64, "[neg]"),
new Opcode(0x65, "[retn]"),
new Opcode(0x66, "[im0]"),
new Opcode(0x67, "RRD"),
new Opcode(0x68, "IN L,(C)"),
new Opcode(0x69, "OUT (C),L"),
new Opcode(0x6A, "ADC HL,HL"),
new Opcode(0x6B, "LD HL,(#nn)"),
new Opcode(0x6C, "[neg]"),
new Opcode(0x6D, "[reti]"),
new Opcode(0x6E, "[im0]"),
new Opcode(0x6F, "RLD"),
new Opcode(0x70, "IN F,(C)"),
new Opcode(0x71, "OUT (C),F"),
new Opcode(0x72, "SBC HL,SP"),
new Opcode(0x73, "LD (#nn),SP"),
new Opcode(0x74, "[neg]"),
new Opcode(0x75, "[retn]"),
new Opcode(0x76, "[im1]"),
new Opcode(0x77, "[ld i,i?]"),
new Opcode(0x78, "IN A,(C)"),
new Opcode(0x79, "OUT (C),A"),
new Opcode(0x7A, "ADC HL,SP"),
new Opcode(0x7B, "LD SP,(#nn)"),
new Opcode(0x7C, "[neg]"),
new Opcode(0x7D, "[reti]"),
new Opcode(0x7E, "[im2]"),
new Opcode(0x7F, "[ld r,r?]"),
...Array<number>(0x0A).fill(0).map((value, index) => new OpcodeInvalid(0x80 + index)),
new OpcodeNextPush(0x8A, "PUSH #nn"), // ZX Spectrum Next
...Array<number>(0x06).fill(0).map((value, index) => new OpcodeInvalid(0x8B + index)),
new OpcodeNext_nextreg_n_n(0x91, "NEXTREG #n,#n"), // ZX Spectrum Next
new OpcodeNext_nextreg_n_a(0x92, "NEXTREG #n,A"), // ZX Spectrum Next
new OpcodeNext(0x93, "PIXELDN"), // ZX Spectrum Next
new OpcodeNext(0x94, "PIXELAD"), // ZX Spectrum Next
new OpcodeNext(0x95, "SETAE"), // ZX Spectrum Next
...Array<number>(0x02).fill(0).map((value, index) => new OpcodeInvalid(0x96 + index)),
new OpcodeNext(0x98, "JP (C)"), // ZX Spectrum Next
...Array<number>(0x07).fill(0).map((value, index) => new OpcodeInvalid(0x99 + index)),
new Opcode(0xA0, "LDI"),
new Opcode(0xA1, "CPI"),
new Opcode(0xA2, "INI"),
new Opcode(0xA3, "OUTI"),
new OpcodeNext(0xA4, "LDIX"), // ZX Spectrum Next
new OpcodeNext(0xA5, "LDWS"), // ZX Spectrum Next
...Array<number>(0x02).fill(0).map((value, index) => new OpcodeInvalid(0xA6 + index)),
new Opcode(0xA8, "LDD"),
new Opcode(0xA9, "CPD"),
new Opcode(0xAA, "IND"),
new Opcode(0xAB, "OUTD"),
new OpcodeNext(0xAC, "LDDX"), // ZX Spectrum Next
...Array<number>(0x03).fill(0).map((value, index) => new OpcodeInvalid(0xAD + index)),
new Opcode(0xB0, "LDIR"),
new Opcode(0xB1, "CPIR"),
new Opcode(0xB2, "INIR"),
new Opcode(0xB3, "OUTIR"),
new OpcodeNext(0xB4, "LDIRX"), // ZX Spectrum Next
new OpcodeInvalid(0xB5),
new OpcodeNext(0xB6, "LDIRSCALE"), // ZX Spectrum Next
new OpcodeNext(0xB7, "LDPIRX"), // ZX Spectrum Next
new Opcode(0xB8, "LDDR"),
new Opcode(0xB9, "CPDR"),
new Opcode(0xBA, "INDR"),
new Opcode(0xBB, "OUTDR"),
new OpcodeNext(0xBC, "LDDRX"), // ZX Spectrum Next
...Array<number>(0x100 - 0xBC - 1).fill(0).map((value, index) => new OpcodeInvalid(0xBD + index))
];
// Fix length (2)
OpcodesED.forEach(opcode => {
opcode.length++;
});
/// Opcodes that start with 0xCB.
export const OpcodesCB: Array<Opcode> = [
new Opcode(0x00, "RLC B"),
new Opcode(0x01, "RLC C"),
new Opcode(0x02, "RLC D"),
new Opcode(0x03, "RLC E"),
new Opcode(0x04, "RLC H"),
new Opcode(0x05, "RLC L"),
new Opcode(0x06, "RLC (HL)"),
new Opcode(0x07, "RLC A"),
new Opcode(0x08, "RRC B"),
new Opcode(0x09, "RRC C"),
new Opcode(0x0A, "RRC D"),
new Opcode(0x0B, "RRC E"),
new Opcode(0x0C, "RRC H"),
new Opcode(0x0D, "RRC L"),
new Opcode(0x0E, "RRC (HL)"),
new Opcode(0x0F, "RRC A"),
new Opcode(0x10, "RL B"),
new Opcode(0x11, "RL C"),
new Opcode(0x12, "RL D"),
new Opcode(0x13, "RL E"),
new Opcode(0x14, "RL H"),
new Opcode(0x15, "RL L"),
new Opcode(0x16, "RL (HL)"),
new Opcode(0x17, "RL A"),
new Opcode(0x18, "RR B"),
new Opcode(0x19, "RR C"),
new Opcode(0x1A, "RR D"),
new Opcode(0x1B, "RR E"),
new Opcode(0x1C, "RR H"),
new Opcode(0x1D, "RR L"),
new Opcode(0x1E, "RR (HL)"),
new Opcode(0x1F, "RR A"),
new Opcode(0x20, "SLA B"),
new Opcode(0x21, "SLA C"),
new Opcode(0x22, "SLA D"),
new Opcode(0x23, "SLA E"),
new Opcode(0x24, "SLA H"),
new Opcode(0x25, "SLA L"),
new Opcode(0x26, "SLA (HL)"),
new Opcode(0x27, "SLA A"),
new Opcode(0x28, "SRA B"),
new Opcode(0x29, "SRA C"),
new Opcode(0x2A, "SRA D"),
new Opcode(0x2B, "SRA E"),
new Opcode(0x2C, "SRA H"),
new Opcode(0x2D, "SRA L"),
new Opcode(0x2E, "SRA (HL)"),
new Opcode(0x2F, "SRA A"),
new Opcode(0x30, "SLL B"),
new Opcode(0x31, "SLL C"),
new Opcode(0x32, "SLL D"),
new Opcode(0x33, "SLL E"),
new Opcode(0x34, "SLL H"),
new Opcode(0x35, "SLL L"),
new Opcode(0x36, "SLL (HL)"),
new Opcode(0x37, "SLL A"),
new Opcode(0x38, "SRL B"),
new Opcode(0x39, "SRL C"),
new Opcode(0x3A, "SRL D"),
new Opcode(0x3B, "SRL E"),
new Opcode(0x3C, "SRL H"),
new Opcode(0x3D, "SRL L"),
new Opcode(0x3E, "SRL (HL)"),
new Opcode(0x3F, "SRL A"),
new Opcode(0x40, "BIT 0,B"),
new Opcode(0x41, "BIT 0,C"),
new Opcode(0x42, "BIT 0,D"),
new Opcode(0x43, "BIT 0,E"),
new Opcode(0x44, "BIT 0,H"),
new Opcode(0x45, "BIT 0,L"),
new Opcode(0x46, "BIT 0,(HL)"),
new Opcode(0x47, "BIT 0,A"),
new Opcode(0x48, "BIT 1,B"),
new Opcode(0x49, "BIT 1,C"),
new Opcode(0x4A, "BIT 1,D"),
new Opcode(0x4B, "BIT 1,E"),
new Opcode(0x4C, "BIT 1,H"),
new Opcode(0x4D, "BIT 1,L"),
new Opcode(0x4E, "BIT 1,(HL)"),
new Opcode(0x4F, "BIT 1,A"),
new Opcode(0x50, "BIT 2,B"),
new Opcode(0x51, "BIT 2,C"),
new Opcode(0x52, "BIT 2,D"),
new Opcode(0x53, "BIT 2,E"),
new Opcode(0x54, "BIT 2,H"),
new Opcode(0x55, "BIT 2,L"),
new Opcode(0x56, "BIT 2,(HL)"),
new Opcode(0x57, "BIT 2,A"),
new Opcode(0x58, "BIT 3,B"),
new Opcode(0x59, "BIT 3,C"),
new Opcode(0x5A, "BIT 3,D"),
new Opcode(0x5B, "BIT 3,E"),
new Opcode(0x5C, "BIT 3,H"),
new Opcode(0x5D, "BIT 3,L"),
new Opcode(0x5E, "BIT 3,(HL)"),
new Opcode(0x5F, "BIT 3,A"),
new Opcode(0x60, "BIT 4,B"),
new Opcode(0x61, "BIT 4,C"),
new Opcode(0x62, "BIT 4,D"),
new Opcode(0x63, "BIT 4,E"),
new Opcode(0x64, "BIT 4,H"),
new Opcode(0x65, "BIT 4,L"),
new Opcode(0x66, "BIT 4,(HL)"),
new Opcode(0x67, "BIT 4,A"),
new Opcode(0x68, "BIT 5,B"),
new Opcode(0x69, "BIT 5,C"),
new Opcode(0x6A, "BIT 5,D"),
new Opcode(0x6B, "BIT 5,E"),
new Opcode(0x6C, "BIT 5,H"),
new Opcode(0x6D, "BIT 5,L"),
new Opcode(0x6E, "BIT 5,(HL)"),
new Opcode(0x6F, "BIT 5,A"),
new Opcode(0x70, "BIT 6,B"),
new Opcode(0x71, "BIT 6,C"),
new Opcode(0x72, "BIT 6,D"),
new Opcode(0x73, "BIT 6,E"),
new Opcode(0x74, "BIT 6,H"),
new Opcode(0x75, "BIT 6,L"),
new Opcode(0x76, "BIT 6,(HL)"),
new Opcode(0x77, "BIT 6,A"),
new Opcode(0x78, "BIT 7,B"),
new Opcode(0x79, "BIT 7,C"),
new Opcode(0x7A, "BIT 7,D"),
new Opcode(0x7B, "BIT 7,E"),
new Opcode(0x7C, "BIT 7,H"),
new Opcode(0x7D, "BIT 7,L"),
new Opcode(0x7E, "BIT 7,(HL)"),
new Opcode(0x7F, "BIT 7,A"),
new Opcode(0x80, "RES 0,B"),
new Opcode(0x81, "RES 0,C"),
new Opcode(0x82, "RES 0,D"),
new Opcode(0x83, "RES 0,E"),
new Opcode(0x84, "RES 0,H"),
new Opcode(0x85, "RES 0,L"),
new Opcode(0x86, "RES 0,(HL)"),
new Opcode(0x87, "RES 0,A"),
new Opcode(0x88, "RES 1,B"),
new Opcode(0x89, "RES 1,C"),
new Opcode(0x8A, "RES 1,D"),
new Opcode(0x8B, "RES 1,E"),
new Opcode(0x8C, "RES 1,H"),
new Opcode(0x8D, "RES 1,L"),
new Opcode(0x8E, "RES 1,(HL)"),
new Opcode(0x8F, "RES 1,A"),
new Opcode(0x90, "RES 2,B"),
new Opcode(0x91, "RES 2,C"),
new Opcode(0x92, "RES 2,D"),
new Opcode(0x93, "RES 2,E"),
new Opcode(0x94, "RES 2,H"),
new Opcode(0x95, "RES 2,L"),
new Opcode(0x96, "RES 2,(HL)"),
new Opcode(0x97, "RES 2,A"),
new Opcode(0x98, "RES 3,B"),
new Opcode(0x99, "RES 3,C"),
new Opcode(0x9A, "RES 3,D"),
new Opcode(0x9B, "RES 3,E"),
new Opcode(0x9C, "RES 3,H"),
new Opcode(0x9D, "RES 3,L"),
new Opcode(0x9E, "RES 3,(HL)"),
new Opcode(0x9F, "RES 3,A"),
new Opcode(0xA0, "RES 4,B"),
new Opcode(0xA1, "RES 4,C"),
new Opcode(0xA2, "RES 4,D"),
new Opcode(0xA3, "RES 4,E"),
new Opcode(0xA4, "RES 4,H"),
new Opcode(0xA5, "RES 4,L"),
new Opcode(0xA6, "RES 4,(HL)"),
new Opcode(0xA7, "RES 4,A"),
new Opcode(0xA8, "RES 5,B"),
new Opcode(0xA9, "RES 5,C"),
new Opcode(0xAA, "RES 5,D"),
new Opcode(0xAB, "RES 5,E"),
new Opcode(0xAC, "RES 5,H"),
new Opcode(0xAD, "RES 5,L"),
new Opcode(0xAE, "RES 5,(HL)"),
new Opcode(0xAF, "RES 5,A"),
new Opcode(0xB0, "RES 6,B"),
new Opcode(0xB1, "RES 6,C"),
new Opcode(0xB2, "RES 6,D"),
new Opcode(0xB3, "RES 6,E"),
new Opcode(0xB4, "RES 6,H"),
new Opcode(0xB5, "RES 6,L"),
new Opcode(0xB6, "RES 6,(HL)"),
new Opcode(0xB7, "RES 6,A"),
new Opcode(0xB8, "RES 7,B"),
new Opcode(0xB9, "RES 7,C"),
new Opcode(0xBA, "RES 7,D"),
new Opcode(0xBB, "RES 7,E"),
new Opcode(0xBC, "RES 7,H"),
new Opcode(0xBD, "RES 7,L"),
new Opcode(0xBE, "RES 7,(HL)"),
new Opcode(0xBF, "RES 7,A"),
new Opcode(0xC0, "SET 0,B"),
new Opcode(0xC1, "SET 0,C"),
new Opcode(0xC2, "SET 0,D"),
new Opcode(0xC3, "SET 0,E"),
new Opcode(0xC4, "SET 0,H"),
new Opcode(0xC5, "SET 0,L"),
new Opcode(0xC6, "SET 0,(HL)"),
new Opcode(0xC7, "SET 0,A"),
new Opcode(0xC8, "SET 1,B"),
new Opcode(0xC9, "SET 1,C"),
new Opcode(0xCA, "SET 1,D"),
new Opcode(0xCB, "SET 1,E"),
new Opcode(0xCC, "SET 1,H"),
new Opcode(0xCD, "SET 1,L"),
new Opcode(0xCE, "SET 1,(HL)"),
new Opcode(0xCF, "SET 1,A"),
new Opcode(0xD0, "SET 2,B"),
new Opcode(0xD1, "SET 2,C"),
new Opcode(0xD2, "SET 2,D"),
new Opcode(0xD3, "SET 2,E"),
new Opcode(0xD4, "SET 2,H"),
new Opcode(0xD5, "SET 2,L"),
new Opcode(0xD6, "SET 2,(HL)"),
new Opcode(0xD7, "SET 2,A"),
new Opcode(0xD8, "SET 3,B"),
new Opcode(0xD9, "SET 3,C"),
new Opcode(0xDA, "SET 3,D"),
new Opcode(0xDB, "SET 3,E"),
new Opcode(0xDC, "SET 3,H"),
new Opcode(0xDD, "SET 3,L"),
new Opcode(0xDE, "SET 3,(HL)"),
new Opcode(0xDF, "SET 3,A"),
new Opcode(0xE0, "SET 4,B"),
new Opcode(0xE1, "SET 4,C"),
new Opcode(0xE2, "SET 4,D"),
new Opcode(0xE3, "SET 4,E"),
new Opcode(0xE4, "SET 4,H"),
new Opcode(0xE5, "SET 4,L"),
new Opcode(0xE6, "SET 4,(HL)"),
new Opcode(0xE7, "SET 4,A"),
new Opcode(0xE8, "SET 5,B"),
new Opcode(0xE9, "SET 5,C"),
new Opcode(0xEA, "SET 5,D"),
new Opcode(0xEB, "SET 5,E"),
new Opcode(0xEC, "SET 5,H"),
new Opcode(0xED, "SET 5,L"),
new Opcode(0xEE, "SET 5,(HL)"),
new Opcode(0xEF, "SET 5,A"),
new Opcode(0xF0, "SET 6,B"),
new Opcode(0xF1, "SET 6,C"),
new Opcode(0xF2, "SET 6,D"),
new Opcode(0xF3, "SET 6,E"),
new Opcode(0xF4, "SET 6,H"),
new Opcode(0xF5, "SET 6,L"),
new Opcode(0xF6, "SET 6,(HL)"),
new Opcode(0xF7, "SET 6,A"),
new Opcode(0xF8, "SET 7,B"),
new Opcode(0xF9, "SET 7,C"),
new Opcode(0xFA, "SET 7,D"),
new Opcode(0xFB, "SET 7,E"),
new Opcode(0xFC, "SET 7,H"),
new Opcode(0xFD, "SET 7,L"),
new Opcode(0xFE, "SET 7,(HL)"),
new Opcode(0xFF, "SET 7,A")
];
// Fix length (2)
OpcodesCB.forEach(opcode => {
opcode.length++;
});
/// Opcodes that start with 0xDDCB.
export const OpcodesDDCB: Array<Opcode> = [
new OpcodePrevIndex(0x00, "RLC (IX%s),B"),
new OpcodePrevIndex(0x01, "RLC (IX%s),C"),
new OpcodePrevIndex(0x02, "RLC (IX%s),D"),
new OpcodePrevIndex(0x03, "RLC (IX%s),E"),
new OpcodePrevIndex(0x04, "RLC (IX%s),H"),
new OpcodePrevIndex(0x05, "RLC (IX%s),L"),
new OpcodePrevIndex(0x06, "RLC (IX%s)"),
new OpcodePrevIndex(0x07, "RLC (IX%s),A"),
new OpcodePrevIndex(0x08, "RRC (IX%s),B"),
new OpcodePrevIndex(0x09, "RRC (IX%s),C"),
new OpcodePrevIndex(0x0A, "RRC (IX%s),D"),
new OpcodePrevIndex(0x0B, "RRC (IX%s),E"),
new OpcodePrevIndex(0x0C, "RRC (IX%s),H"),
new OpcodePrevIndex(0x0D, "RRC (IX%s),L"),
new OpcodePrevIndex(0x0E, "RRC (IX%s)"),
new OpcodePrevIndex(0x0F, "RRC (IX%s),A"),
new OpcodePrevIndex(0x10, "RL (IX%s),B"),
new OpcodePrevIndex(0x11, "RL (IX%s),C"),
new OpcodePrevIndex(0x12, "RL (IX%s),D"),
new OpcodePrevIndex(0x13, "RL (IX%s),E"),
new OpcodePrevIndex(0x14, "RL (IX%s),H"),
new OpcodePrevIndex(0x15, "RL (IX%s),L"),
new OpcodePrevIndex(0x16, "RL (IX%s)"),
new OpcodePrevIndex(0x17, "RL (IX%s),A"),
new OpcodePrevIndex(0x18, "RR (IX%s),B"),
new OpcodePrevIndex(0x19, "RR (IX%s),C"),
new OpcodePrevIndex(0x1A, "RR (IX%s),D"),
new OpcodePrevIndex(0x1B, "RR (IX%s),E"),
new OpcodePrevIndex(0x1C, "RR (IX%s),H"),
new OpcodePrevIndex(0x1D, "RR (IX%s),L"),
new OpcodePrevIndex(0x1E, "RR (IX%s)"),
new OpcodePrevIndex(0x1F, "RR (IX%s),A"),
new OpcodePrevIndex(0x20, "SLA (IX%s),B"),
new OpcodePrevIndex(0x21, "SLA (IX%s),C"),
new OpcodePrevIndex(0x22, "SLA (IX%s),D"),
new OpcodePrevIndex(0x23, "SLA (IX%s),E"),
new OpcodePrevIndex(0x24, "SLA (IX%s),H"),
new OpcodePrevIndex(0x25, "SLA (IX%s),L"),
new OpcodePrevIndex(0x26, "SLA (IX%s)"),
new OpcodePrevIndex(0x27, "SLA (IX%s),A"),
new OpcodePrevIndex(0x28, "SRA (IX%s),B"),
new OpcodePrevIndex(0x29, "SRA (IX%s),C"),
new OpcodePrevIndex(0x2A, "SRA (IX%s),D"),
new OpcodePrevIndex(0x2B, "SRA (IX%s),E"),
new OpcodePrevIndex(0x2C, "SRA (IX%s),H"),
new OpcodePrevIndex(0x2D, "SRA (IX%s),L"),
new OpcodePrevIndex(0x2E, "SRA (IX%s)"),
new OpcodePrevIndex(0x2F, "SRA (IX%s),A"),
new OpcodePrevIndex(0x30, "SLL (IX%s),B"),
new OpcodePrevIndex(0x31, "SLL (IX%s),C"),
new OpcodePrevIndex(0x32, "SLL (IX%s),D"),
new OpcodePrevIndex(0x33, "SLL (IX%s),E"),
new OpcodePrevIndex(0x34, "SLL (IX%s),H"),
new OpcodePrevIndex(0x35, "SLL (IX%s),L"),
new OpcodePrevIndex(0x36, "SLL (IX%s)"),
new OpcodePrevIndex(0x37, "SLL (IX%s),A"),
new OpcodePrevIndex(0x38, "SRL (IX%s),B"),
new OpcodePrevIndex(0x39, "SRL (IX%s),C"),
new OpcodePrevIndex(0x3A, "SRL (IX%s),D"),
new OpcodePrevIndex(0x3B, "SRL (IX%s),E"),
new OpcodePrevIndex(0x3C, "SRL (IX%s),H"),
new OpcodePrevIndex(0x3D, "SRL (IX%s),L"),
new OpcodePrevIndex(0x3E, "SRL (IX%s)"),
new OpcodePrevIndex(0x3F, "SRL (IX%s),A"),
new OpcodePrevIndex(0x40, "BIT 0,(IX%s)"),
new OpcodePrevIndex(0x41, "BIT 0,(IX%s)"),
new OpcodePrevIndex(0x42, "BIT 0,(IX%s)"),
new OpcodePrevIndex(0x43, "BIT 0,(IX%s)"),
new OpcodePrevIndex(0x44, "BIT 0,(IX%s)"),
new OpcodePrevIndex(0x45, "BIT 0,(IX%s)"),
new OpcodePrevIndex(0x46, "BIT 0,(IX%s)"),
new OpcodePrevIndex(0x47, "BIT 0,(IX%s)"),
new OpcodePrevIndex(0x48, "BIT 1,(IX%s)"),
new OpcodePrevIndex(0x49, "BIT 1,(IX%s)"),
new OpcodePrevIndex(0x4A, "BIT 1,(IX%s)"),
new OpcodePrevIndex(0x4B, "BIT 1,(IX%s)"),
new OpcodePrevIndex(0x4C, "BIT 1,(IX%s)"),
new OpcodePrevIndex(0x4D, "BIT 1,(IX%s)"),
new OpcodePrevIndex(0x4E, "BIT 1,(IX%s)"),
new OpcodePrevIndex(0x4F, "BIT 1,(IX%s)"),
new OpcodePrevIndex(0x50, "BIT 2,(IX%s)"),
new OpcodePrevIndex(0x51, "BIT 2,(IX%s)"),
new OpcodePrevIndex(0x52, "BIT 2,(IX%s)"),
new OpcodePrevIndex(0x53, "BIT 2,(IX%s)"),
new OpcodePrevIndex(0x54, "BIT 2,(IX%s)"),
new OpcodePrevIndex(0x55, "BIT 2,(IX%s)"),
new OpcodePrevIndex(0x56, "BIT 2,(IX%s)"),
new OpcodePrevIndex(0x57, "BIT 2,(IX%s)"),
new OpcodePrevIndex(0x58, "BIT 3,(IX%s)"),
new OpcodePrevIndex(0x59, "BIT 3,(IX%s)"),
new OpcodePrevIndex(0x5A, "BIT 3,(IX%s)"),
new OpcodePrevIndex(0x5B, "BIT 3,(IX%s)"),
new OpcodePrevIndex(0x5C, "BIT 3,(IX%s)"),
new OpcodePrevIndex(0x5D, "BIT 3,(IX%s)"),
new OpcodePrevIndex(0x5E, "BIT 3,(IX%s)"),
new OpcodePrevIndex(0x5F, "BIT 3,(IX%s)"),
new OpcodePrevIndex(0x60, "BIT 4,(IX%s)"),
new OpcodePrevIndex(0x61, "BIT 4,(IX%s)"),
new OpcodePrevIndex(0x62, "BIT 4,(IX%s)"),
new OpcodePrevIndex(0x63, "BIT 4,(IX%s)"),
new OpcodePrevIndex(0x64, "BIT 4,(IX%s)"),
new OpcodePrevIndex(0x65, "BIT 4,(IX%s)"),
new OpcodePrevIndex(0x66, "BIT 4,(IX%s)"),
new OpcodePrevIndex(0x67, "BIT 4,(IX%s)"),
new OpcodePrevIndex(0x68, "BIT 5,(IX%s)"),
new OpcodePrevIndex(0x69, "BIT 5,(IX%s)"),
new OpcodePrevIndex(0x6A, "BIT 5,(IX%s)"),
new OpcodePrevIndex(0x6B, "BIT 5,(IX%s)"),
new OpcodePrevIndex(0x6C, "BIT 5,(IX%s)"),
new OpcodePrevIndex(0x6D, "BIT 5,(IX%s)"),
new OpcodePrevIndex(0x6E, "BIT 5,(IX%s)"),
new OpcodePrevIndex(0x6F, "BIT 5,(IX%s)"),
new OpcodePrevIndex(0x70, "BIT 6,(IX%s)"),
new OpcodePrevIndex(0x71, "BIT 6,(IX%s)"),
new OpcodePrevIndex(0x72, "BIT 6,(IX%s)"),
new OpcodePrevIndex(0x73, "BIT 6,(IX%s)"),
new OpcodePrevIndex(0x74, "BIT 6,(IX%s)"),
new OpcodePrevIndex(0x75, "BIT 6,(IX%s)"),
new OpcodePrevIndex(0x76, "BIT 6,(IX%s)"),
new OpcodePrevIndex(0x77, "BIT 6,(IX%s)"),
new OpcodePrevIndex(0x78, "BIT 7,(IX%s)"),
new OpcodePrevIndex(0x79, "BIT 7,(IX%s)"),
new OpcodePrevIndex(0x7A, "BIT 7,(IX%s)"),
new OpcodePrevIndex(0x7B, "BIT 7,(IX%s)"),
new OpcodePrevIndex(0x7C, "BIT 7,(IX%s)"),
new OpcodePrevIndex(0x7D, "BIT 7,(IX%s)"),
new OpcodePrevIndex(0x7E, "BIT 7,(IX%s)"),
new OpcodePrevIndex(0x7F, "BIT 7,(IX%s)"),
new OpcodePrevIndex(0x80, "RES 0,(IX%s),B"),
new OpcodePrevIndex(0x81, "RES 0,(IX%s),C"),
new OpcodePrevIndex(0x82, "RES 0,(IX%s),D"),
new OpcodePrevIndex(0x83, "RES 0,(IX%s),E"),
new OpcodePrevIndex(0x84, "RES 0,(IX%s),H"),
new OpcodePrevIndex(0x85, "RES 0,(IX%s),L"),
new OpcodePrevIndex(0x86, "RES 0,(IX%s)"),
new OpcodePrevIndex(0x87, "RES 0,(IX%s),A"),
new OpcodePrevIndex(0x88, "RES 1,(IX%s),B"),
new OpcodePrevIndex(0x89, "RES 1,(IX%s),C"),
new OpcodePrevIndex(0x8A, "RES 1,(IX%s),D"),
new OpcodePrevIndex(0x8B, "RES 1,(IX%s),E"),
new OpcodePrevIndex(0x8C, "RES 1,(IX%s),H"),
new OpcodePrevIndex(0x8D, "RES 1,(IX%s),L"),
new OpcodePrevIndex(0x8E, "RES 1,(IX%s)"),
new OpcodePrevIndex(0x8F, "RES 1,(IX%s),A"),
new OpcodePrevIndex(0x90, "RES 2,(IX%s),B"),
new OpcodePrevIndex(0x91, "RES 2,(IX%s),C"),
new OpcodePrevIndex(0x92, "RES 2,(IX%s),D"),
new OpcodePrevIndex(0x93, "RES 2,(IX%s),E"),
new OpcodePrevIndex(0x94, "RES 2,(IX%s),H"),
new OpcodePrevIndex(0x95, "RES 2,(IX%s),L"),
new OpcodePrevIndex(0x96, "RES 2,(IX%s)"),
new OpcodePrevIndex(0x97, "RES 2,(IX%s),A"),
new OpcodePrevIndex(0x98, "RES 3,(IX%s),B"),
new OpcodePrevIndex(0x99, "RES 3,(IX%s),C"),
new OpcodePrevIndex(0x9A, "RES 3,(IX%s),D"),
new OpcodePrevIndex(0x9B, "RES 3,(IX%s),E"),
new OpcodePrevIndex(0x9C, "RES 3,(IX%s),H"),
new OpcodePrevIndex(0x9D, "RES 3,(IX%s),L"),
new OpcodePrevIndex(0x9E, "RES 3,(IX%s)"),
new OpcodePrevIndex(0x9F, "RES 3,(IX%s),A"),
new OpcodePrevIndex(0xA0, "RES 4,(IX%s),B"),
new OpcodePrevIndex(0xA1, "RES 4,(IX%s),C"),
new OpcodePrevIndex(0xA2, "RES 4,(IX%s),D"),
new OpcodePrevIndex(0xA3, "RES 4,(IX%s),E"),
new OpcodePrevIndex(0xA4, "RES 4,(IX%s),H"),
new OpcodePrevIndex(0xA5, "RES 4,(IX%s),L"),
new OpcodePrevIndex(0xA6, "RES 4,(IX%s)"),
new OpcodePrevIndex(0xA7, "RES 4,(IX%s),A"),
new OpcodePrevIndex(0xA8, "RES 5,(IX%s),B"),
new OpcodePrevIndex(0xA9, "RES 5,(IX%s),C"),
new OpcodePrevIndex(0xAA, "RES 5,(IX%s),D"),
new OpcodePrevIndex(0xAB, "RES 5,(IX%s),E"),
new OpcodePrevIndex(0xAC, "RES 5,(IX%s),H"),
new OpcodePrevIndex(0xAD, "RES 5,(IX%s),L"),
new OpcodePrevIndex(0xAE, "RES 5,(IX%s)"),
new OpcodePrevIndex(0xAF, "RES 5,(IX%s),A"),
new OpcodePrevIndex(0xB0, "RES 6,(IX%s),B"),
new OpcodePrevIndex(0xB1, "RES 6,(IX%s),C"),
new OpcodePrevIndex(0xB2, "RES 6,(IX%s),D"),
new OpcodePrevIndex(0xB3, "RES 6,(IX%s),E"),
new OpcodePrevIndex(0xB4, "RES 6,(IX%s),H"),
new OpcodePrevIndex(0xB5, "RES 6,(IX%s),L"),
new OpcodePrevIndex(0xB6, "RES 6,(IX%s)"),
new OpcodePrevIndex(0xB7, "RES 6,(IX%s),A"),
new OpcodePrevIndex(0xB8, "RES 7,(IX%s),B"),
new OpcodePrevIndex(0xB9, "RES 7,(IX%s),C"),
new OpcodePrevIndex(0xBA, "RES 7,(IX%s),D"),
new OpcodePrevIndex(0xBB, "RES 7,(IX%s),E"),
new OpcodePrevIndex(0xBC, "RES 7,(IX%s),H"),
new OpcodePrevIndex(0xBD, "RES 7,(IX%s),L"),
new OpcodePrevIndex(0xBE, "RES 7,(IX%s)"),
new OpcodePrevIndex(0xBF, "RES 7,(IX%s),A"),
new OpcodePrevIndex(0xC0, "SET 0,(IX%s),B"),
new OpcodePrevIndex(0xC1, "SET 0,(IX%s),C"),
new OpcodePrevIndex(0xC2, "SET 0,(IX%s),D"),
new OpcodePrevIndex(0xC3, "SET 0,(IX%s),E"),
new OpcodePrevIndex(0xC4, "SET 0,(IX%s),H"),
new OpcodePrevIndex(0xC5, "SET 0,(IX%s),L"),
new OpcodePrevIndex(0xC6, "SET 0,(IX%s)"),
new OpcodePrevIndex(0xC7, "SET 0,(IX%s),A"),
new OpcodePrevIndex(0xC8, "SET 1,(IX%s),B"),
new OpcodePrevIndex(0xC9, "SET 1,(IX%s),C"),
new OpcodePrevIndex(0xCA, "SET 1,(IX%s),D"),
new OpcodePrevIndex(0xCB, "SET 1,(IX%s),E"),
new OpcodePrevIndex(0xCC, "SET 1,(IX%s),H"),
new OpcodePrevIndex(0xCD, "SET 1,(IX%s),L"),
new OpcodePrevIndex(0xCE, "SET 1,(IX%s)"),
new OpcodePrevIndex(0xCF, "SET 1,(IX%s),A"),
new OpcodePrevIndex(0xD0, "SET 2,(IX%s),B"),
new OpcodePrevIndex(0xD1, "SET 2,(IX%s),C"),
new OpcodePrevIndex(0xD2, "SET 2,(IX%s),D"),
new OpcodePrevIndex(0xD3, "SET 2,(IX%s),E"),
new OpcodePrevIndex(0xD4, "SET 2,(IX%s),H"),
new OpcodePrevIndex(0xD5, "SET 2,(IX%s),L"),
new OpcodePrevIndex(0xD6, "SET 2,(IX%s)"),
new OpcodePrevIndex(0xD7, "SET 2,(IX%s),A"),
new OpcodePrevIndex(0xD8, "SET 3,(IX%s),B"),
new OpcodePrevIndex(0xD9, "SET 3,(IX%s),C"),
new OpcodePrevIndex(0xDA, "SET 3,(IX%s),D"),
new OpcodePrevIndex(0xDB, "SET 3,(IX%s),E"),
new OpcodePrevIndex(0xDC, "SET 3,(IX%s),H"),
new OpcodePrevIndex(0xDD, "SET 3,(IX%s),L"),
new OpcodePrevIndex(0xDE, "SET 3,(IX%s)"),
new OpcodePrevIndex(0xDF, "SET 3,(IX%s),A"),
new OpcodePrevIndex(0xE0, "SET 4,(IX%s),B"),
new OpcodePrevIndex(0xE1, "SET 4,(IX%s),C"),
new OpcodePrevIndex(0xE2, "SET 4,(IX%s),D"),
new OpcodePrevIndex(0xE3, "SET 4,(IX%s),E"),
new OpcodePrevIndex(0xE4, "SET 4,(IX%s),H"),
new OpcodePrevIndex(0xE5, "SET 4,(IX%s),L"),
new OpcodePrevIndex(0xE6, "SET 4,(IX%s)"),
new OpcodePrevIndex(0xE7, "SET 4,(IX%s),A"),
new OpcodePrevIndex(0xE8, "SET 5,(IX%s),B"),
new OpcodePrevIndex(0xE9, "SET 5,(IX%s),C"),
new OpcodePrevIndex(0xEA, "SET 5,(IX%s),D"),
new OpcodePrevIndex(0xEB, "SET 5,(IX%s),E"),
new OpcodePrevIndex(0xEC, "SET 5,(IX%s),H"),
new OpcodePrevIndex(0xED, "SET 5,(IX%s),L"),
new OpcodePrevIndex(0xEE, "SET 5,(IX%s)"),
new OpcodePrevIndex(0xEF, "SET 5,(IX%s),A"),
new OpcodePrevIndex(0xF0, "SET 6,(IX%s),B"),
new OpcodePrevIndex(0xF1, "SET 6,(IX%s),C"),
new OpcodePrevIndex(0xF2, "SET 6,(IX%s),D"),
new OpcodePrevIndex(0xF3, "SET 6,(IX%s),E"),
new OpcodePrevIndex(0xF4, "SET 6,(IX%s),H"),
new OpcodePrevIndex(0xF5, "SET 6,(IX%s),L"),
new OpcodePrevIndex(0xF6, "SET 6,(IX%s)"),
new OpcodePrevIndex(0xF7, "SET 6,(IX%s),A"),
new OpcodePrevIndex(0xF8, "SET 7,(IX%s),B"),
new OpcodePrevIndex(0xF9, "SET 7,(IX%s),C"),
new OpcodePrevIndex(0xFA, "SET 7,(IX%s),D"),
new OpcodePrevIndex(0xFB, "SET 7,(IX%s),E"),
new OpcodePrevIndex(0xFC, "SET 7,(IX%s),H"),
new OpcodePrevIndex(0xFD, "SET 7,(IX%s),L"),
new OpcodePrevIndex(0xFE, "SET 7,(IX%s)"),
new OpcodePrevIndex(0xFF, "SET 7,(IX%s),A")
];
// Fix length (4)
OpcodesDDCB.forEach(opcode => {
opcode.length += 1;
});
/// Opcodes that start with 0xFDCB.
/// Create FDCB (use IY instead of IX)
export const OpcodesFDCB = OpcodesDDCB.map(opcode => {
const opcodeFDCB = opcode.clone();
const name = opcode.name.replace('IX', 'IY');
opcodeFDCB.name = name;
return opcodeFDCB;
});
/// Opcodes that start with 0xDD.
export const OpcodesDD: Array<Opcode> = [
new OpcodeInvalid(0x00),
new OpcodeInvalid(0x01),
new OpcodeInvalid(0x02),
new OpcodeInvalid(0x03),
new OpcodeInvalid(0x04),
new OpcodeInvalid(0x05),
new OpcodeInvalid(0x06),
new OpcodeInvalid(0x07),
new OpcodeInvalid(0x08),
new Opcode(0x09, "ADD IX,BC"),
new OpcodeInvalid(0x0A),
new OpcodeInvalid(0x0B),
new OpcodeInvalid(0x0C),
new OpcodeInvalid(0x0D),
new OpcodeInvalid(0x0E),
new OpcodeInvalid(0x0F),
new OpcodeInvalid(0x10),
new OpcodeInvalid(0x11),
new OpcodeInvalid(0x12),
new OpcodeInvalid(0x13),
new OpcodeInvalid(0x14),
new OpcodeInvalid(0x15),
new OpcodeInvalid(0x16),
new OpcodeInvalid(0x17),
new OpcodeInvalid(0x18),
new Opcode(0x19, "ADD IX,DE"),
new OpcodeInvalid(0x1A),
new OpcodeInvalid(0x1B),
new OpcodeInvalid(0x1C),
new OpcodeInvalid(0x1D),
new OpcodeInvalid(0x1E),
new OpcodeInvalid(0x1F),
new OpcodeInvalid(0x20),
new Opcode(0x21, "LD IX,#nn"),
new Opcode(0x22, "LD (#nn),IX"),
new Opcode(0x23, "INC IX"),
new Opcode(0x24, "INC IXH"),
new Opcode(0x25, "DEC IXH"),
new Opcode(0x26, "LD IXH,#n"),
new OpcodeInvalid(0x27),
new OpcodeInvalid(0x28),
new Opcode(0x29, "ADD IX,IX"),
new Opcode(0x2A, "LD IX,(#nn)"),
new Opcode(0x2B, "DEC IX"),
new Opcode(0x2C, "INC IXL"),
new Opcode(0x2D, "DEC IXL"),
new Opcode(0x2E, "LD IXL,#n"),
new OpcodeInvalid(0x2F),
new OpcodeInvalid(0x30),
new OpcodeInvalid(0x31),
new OpcodeInvalid(0x32),
new OpcodeInvalid(0x33),
new Opcode(0x34, "INC (IX)"),
new Opcode(0x35, "DEC (IX)"),
new OpcodeIndexImmediate(0x36, 'LD (IX%s),%s'),
new OpcodeInvalid(0x37),
new OpcodeInvalid(0x38),
new Opcode(0x39, "ADD IX,SP"),
new OpcodeInvalid(0x3A),
new OpcodeInvalid(0x3B),
new OpcodeInvalid(0x3C),
new OpcodeInvalid(0x3D),
new OpcodeInvalid(0x3E),
new OpcodeInvalid(0x3F),
new OpcodeInvalid(0x40),
new OpcodeInvalid(0x41),
new OpcodeInvalid(0x42),
new OpcodeInvalid(0x43),
new Opcode(0x44, "LD B,IXH"),
new Opcode(0x45, "LD B,IXL"),
new OpcodeIndex(0x46, "LD B,(IX%s)"),
new OpcodeInvalid(0x47),
new OpcodeInvalid(0x48),
new OpcodeInvalid(0x49),
new OpcodeInvalid(0x4A),
new OpcodeInvalid(0x4B),
new Opcode(0x4C, "LD C,IXH"),
new Opcode(0x4D, "LD C,IXL"),
new OpcodeIndex(0x4E, "LD C,(IX%s)"),
new OpcodeInvalid(0x4F),
new OpcodeInvalid(0x50),
new OpcodeInvalid(0x51),
new OpcodeInvalid(0x52),
new OpcodeInvalid(0x53),
new Opcode(0x54, "LD D,IXH"),
new Opcode(0x55, "LD D,IXL"),
new OpcodeIndex(0x56, "LD D,(IX%s)"),
new OpcodeInvalid(0x57),
new OpcodeInvalid(0x58),
new OpcodeInvalid(0x59),
new OpcodeInvalid(0x5A),
new OpcodeInvalid(0x5B),
new Opcode(0x5C, "LD E,IXH"),
new Opcode(0x5D, "LD E,IXL"),
new OpcodeIndex(0x5E, "LD E,(IX%s)"),
new OpcodeInvalid(0x5F),
new Opcode(0x60, "LD IXH,B"),
new Opcode(0x61, "LD IXH,C"),
new Opcode(0x62, "LD IXH,D"),
new Opcode(0x63, "LD IXH,E"),
new Opcode(0x64, "LD IXH,IXH"),
new Opcode(0x65, "LD IXH,IXL"),
new OpcodeIndex(0x66, "LD H,(IX%s)"),
new Opcode(0x67, "LD IXH,A"),
new Opcode(0x68, "LD IXL,B"),
new Opcode(0x69, "LD IXL,C"),
new Opcode(0x6A, "LD IXL,D"),
new Opcode(0x6B, "LD IXL,E"),
new Opcode(0x6C, "LD IXL,IXH"),
new Opcode(0x6D, "LD IXL,IXL"),
new OpcodeIndex(0x6E, "LD L,(IX%s)"),
new Opcode(0x6F, "LD IXL,A"),
new OpcodeIndex(0x70, "LD (IX%s),B"),
new OpcodeIndex(0x71, "LD (IX%s),C"),
new OpcodeIndex(0x72, "LD (IX%s),D"),
new OpcodeIndex(0x73, "LD (IX%s),E"),
new OpcodeIndex(0x74, "LD (IX%s),H"),
new OpcodeIndex(0x75, "LD (IX%s),L"),
new OpcodeInvalid(0x76),
new OpcodeIndex(0x77, "LD (IX%s),A"),
new OpcodeInvalid(0x78),
new OpcodeInvalid(0x79),
new OpcodeInvalid(0x7A),
new OpcodeInvalid(0x7B),
new Opcode(0x7C, "LD A,IXH"),
new Opcode(0x7D, "LD A,IXL"),
new OpcodeIndex(0x7E, "LD A,(IX%s)"),
new OpcodeInvalid(0x7F),
new OpcodeInvalid(0x80),
new OpcodeInvalid(0x81),
new OpcodeInvalid(0x82),
new OpcodeInvalid(0x83),
new Opcode(0x84, "ADD A,IXH"),
new Opcode(0x85, "ADD A,IXL"),
new OpcodeIndex(0x86, "ADD A,(IX%s)"),
new OpcodeInvalid(0x87),
new OpcodeInvalid(0x88),
new OpcodeInvalid(0x89),
new OpcodeInvalid(0x8A),
new OpcodeInvalid(0x8B),
new Opcode(0x8C, "ADC A,IXH"),
new Opcode(0x8D, "ADC A,IXL"),
new OpcodeIndex(0x8E, "ADC A,(IX%s)"),
new OpcodeInvalid(0x8F),
new OpcodeInvalid(0x90),
new OpcodeInvalid(0x91),
new OpcodeInvalid(0x92),
new OpcodeInvalid(0x93),
new Opcode(0x94, "SUB IXH"),
new Opcode(0x95, "SUB IXL"),
new OpcodeIndex(0x96, "SUB (IX%s)"),
new OpcodeInvalid(0x97),
new OpcodeInvalid(0x98),
new OpcodeInvalid(0x99),
new OpcodeInvalid(0x9A),
new OpcodeInvalid(0x9B),
new Opcode(0x9C, "SBC A,IXH"),
new Opcode(0x9D, "SBC A,IXL"),
new OpcodeIndex(0x9E, "SBC A,(IX%s)"),
new OpcodeInvalid(0x9F),
new OpcodeInvalid(0xA0),
new OpcodeInvalid(0xA1),
new OpcodeInvalid(0xA2),
new OpcodeInvalid(0xA3),
new Opcode(0xA4, "AND IXH"),
new Opcode(0xA5, "AND IXL"),
new OpcodeIndex(0xA6, "AND (IX%s)"),
new OpcodeInvalid(0xA7),
new OpcodeInvalid(0xA8),
new OpcodeInvalid(0xA9),
new OpcodeInvalid(0xAA),
new OpcodeInvalid(0xAB),
new Opcode(0xAC, "XOR IXH"),
new Opcode(0xAD, "XOR IXL"),
new OpcodeIndex(0xAE, "XOR (IX%s)"),
new OpcodeInvalid(0xAF),
new OpcodeInvalid(0xB0),
new OpcodeInvalid(0xB1),
new OpcodeInvalid(0xB2),
new OpcodeInvalid(0xB3),
new Opcode(0xB4, "OR IXH"),
new Opcode(0xB5, "OR IXL"),
new OpcodeIndex(0xB6, "OR (IX%s)"),
new OpcodeInvalid(0xB7),
new OpcodeInvalid(0xB8),
new OpcodeInvalid(0xB9),
new OpcodeInvalid(0xBA),
new OpcodeInvalid(0xBB),
new Opcode(0xBC, "CP IXH"),
new Opcode(0xBD, "CP IXL"),
new OpcodeIndex(0xBE, "CP (IX%s)"),
new OpcodeInvalid(0xBF),
new OpcodeInvalid(0xC0),
new OpcodeInvalid(0xC1),
new OpcodeInvalid(0xC2),
new OpcodeInvalid(0xC3),
new OpcodeInvalid(0xC4),
new OpcodeInvalid(0xC5),
new OpcodeInvalid(0xC6),
new OpcodeInvalid(0xC7),
new OpcodeInvalid(0xC8),
new OpcodeInvalid(0xC9),
new OpcodeInvalid(0xCA),
new OpcodeExtended2(0xCB, OpcodesDDCB),
new OpcodeInvalid(0xCC),
new OpcodeInvalid(0xCD),
new OpcodeInvalid(0xCE),
new OpcodeInvalid(0xCF),
new OpcodeInvalid(0xD0),
new OpcodeInvalid(0xD1),
new OpcodeInvalid(0xD2),
new OpcodeInvalid(0xD3),
new OpcodeInvalid(0xD4),
new OpcodeInvalid(0xD5),
new OpcodeInvalid(0xD6),
new OpcodeInvalid(0xD7),
new OpcodeInvalid(0xD8),
new OpcodeInvalid(0xD9),
new OpcodeInvalid(0xDA),
new OpcodeInvalid(0xDB),
new OpcodeInvalid(0xDC),
new OpcodeNOP(0xDD),
new OpcodeInvalid(0xDE),
new OpcodeInvalid(0xDF),
new OpcodeInvalid(0xE0),
new Opcode(0xE1, "POP IX"),
new OpcodeInvalid(0xE2),
new Opcode(0xE3, "EX (SP),IX"),
new OpcodeInvalid(0xE4),
new Opcode(0xE5, "PUSH IX"),
new OpcodeInvalid(0xE6),
new OpcodeInvalid(0xE7),
new OpcodeInvalid(0xE8),
new Opcode(0xE9, "JP (IX)"),
new OpcodeInvalid(0xEA),
new OpcodeInvalid(0xEB),
new OpcodeInvalid(0xEC),
new OpcodeNOP(0xED),
new OpcodeInvalid(0xEE),
new OpcodeInvalid(0xEF),
new OpcodeInvalid(0xF0),
new OpcodeInvalid(0xF1),
new OpcodeInvalid(0xF2),
new OpcodeInvalid(0xF3),
new OpcodeInvalid(0xF4),
new OpcodeInvalid(0xF5),
new OpcodeInvalid(0xF6),
new OpcodeInvalid(0xF7),
new OpcodeInvalid(0xF8),
new Opcode(0xF9, "LD SP,IX"),
new OpcodeInvalid(0xFA),
new OpcodeInvalid(0xFB),
new OpcodeInvalid(0xFC),
new OpcodeNOP(0xFD),
new OpcodeInvalid(0xFE),
new OpcodeInvalid(0xFF),
];
// Fix length (2)
OpcodesDD.forEach(opcode => {
opcode.length++;
});
/// Opcodes that start with 0xFD.
/// Create FD (use IY instead of IX)
export const OpcodesFD = OpcodesDD.map(opcode => {
let opcodeFD;
// Check for extended opcode
if (opcode.code == 0xCB) {
opcodeFD = new OpcodeExtended2(0xCB, OpcodesFDCB);
}
else {
// Simple copy
opcodeFD = opcode.clone();
opcodeFD.name = opcode.name.replace(/IX/g, 'IY');
}
return opcodeFD;
});
// Normal Opcodes
export const Opcodes: Array<Opcode> = [
new Opcode(0x00, "NOP"),
new Opcode(0x01, "LD BC,#nn"),
new Opcode(0x02, "LD (BC),A"),
new Opcode(0x03, "INC BC"),
new Opcode(0x04, "INC B"),
new Opcode(0x05, "DEC B"),
new Opcode(0x06, "LD B,#n"),
new Opcode(0x07, "RLCA"),
new Opcode(0x08, "EX AF,AF'"),
new Opcode(0x09, "ADD HL,BC"),
new Opcode(0x0A, "LD A,(BC)"),
new Opcode(0x0B, "DEC BC"),
new Opcode(0x0C, "INC C"),
new Opcode(0x0D, "DEC C"),
new Opcode(0x0E, "LD C,#n"),
new Opcode(0x0F, "RRCA"),
new Opcode(0x10, "DJNZ #n"),
new Opcode(0x11, "LD DE,#nn"),
new Opcode(0x12, "LD (DE),A"),
new Opcode(0x13, "INC DE"),
new Opcode(0x14, "INC D"),
new Opcode(0x15, "DEC D"),
new Opcode(0x16, "LD D,#n"),
new Opcode(0x17, "RLA"),
new Opcode(0x18, "JR #n"),
new Opcode(0x19, "ADD HL,DE"),
new Opcode(0x1A, "LD A,(DE)"),
new Opcode(0x1B, "DEC DE"),
new Opcode(0x1C, "INC E"),
new Opcode(0x1D, "DEC E"),
new Opcode(0x1E, "LD E,#n"),
new Opcode(0x1F, "RRA"),
new Opcode(0x20, "JR NZ,#n"),
new Opcode(0x21, "LD HL,#nn"),
new Opcode(0x22, "LD (#nn),HL"),
new Opcode(0x23, "INC HL"),
new Opcode(0x24, "INC H"),
new Opcode(0x25, "DEC H"),
new Opcode(0x26, "LD H,#n"),
new Opcode(0x27, "DAA"),
new Opcode(0x28, "JR Z,#n"),
new Opcode(0x29, "ADD HL,HL"),
new Opcode(0x2A, "LD HL,(#nn)"),
new Opcode(0x2B, "DEC HL"),
new Opcode(0x2C, "INC L"),
new Opcode(0x2D, "DEC L"),
new Opcode(0x2E, "LD L,#n"),
new Opcode(0x2F, "CPL"),
new Opcode(0x30, "JR NC,#n"),
new Opcode(0x31, "LD SP,#nn"),
new Opcode(0x32, "LD (#nn),A"),
new Opcode(0x33, "INC SP"),
new Opcode(0x34, "INC (HL)"),
new Opcode(0x35, "DEC (HL)"),
new Opcode(0x36, "LD (HL),#n"),
new Opcode(0x37, "SCF"),
new Opcode(0x38, "JR C,#n"),
new Opcode(0x39, "ADD HL,SP"),
new Opcode(0x3A, "LD A,(#nn)"),
new Opcode(0x3B, "DEC SP"),
new Opcode(0x3C, "INC A"),
new Opcode(0x3D, "DEC A"),
new Opcode(0x3E, "LD A,#n"),
new Opcode(0x3F, "CCF"),
new Opcode(0x40, "LD B,B"),
new Opcode(0x41, "LD B,C"),
new Opcode(0x42, "LD B,D"),
new Opcode(0x43, "LD B,E"),
new Opcode(0x44, "LD B,H"),
new Opcode(0x45, "LD B,L"),
new Opcode(0x46, "LD B,(HL)"),
new Opcode(0x47, "LD B,A"),
new Opcode(0x48, "LD C,B"),
new Opcode(0x49, "LD C,C"),
new Opcode(0x4A, "LD C,D"),
new Opcode(0x4B, "LD C,E"),
new Opcode(0x4C, "LD C,H"),
new Opcode(0x4D, "LD C,L"),
new Opcode(0x4E, "LD C,(HL)"),
new Opcode(0x4F, "LD C,A"),
new Opcode(0x50, "LD D,B"),
new Opcode(0x51, "LD D,C"),
new Opcode(0x52, "LD D,D"),
new Opcode(0x53, "LD D,E"),
new Opcode(0x54, "LD D,H"),
new Opcode(0x55, "LD D,L"),
new Opcode(0x56, "LD D,(HL)"),
new Opcode(0x57, "LD D,A"),
new Opcode(0x58, "LD E,B"),
new Opcode(0x59, "LD E,C"),
new Opcode(0x5A, "LD E,D"),
new Opcode(0x5B, "LD E,E"),
new Opcode(0x5C, "LD E,H"),
new Opcode(0x5D, "LD E,L"),
new Opcode(0x5E, "LD E,(HL)"),
new Opcode(0x5F, "LD E,A"),
new Opcode(0x60, "LD H,B"),
new Opcode(0x61, "LD H,C"),
new Opcode(0x62, "LD H,D"),
new Opcode(0x63, "LD H,E"),
new Opcode(0x64, "LD H,H"),
new Opcode(0x65, "LD H,L"),
new Opcode(0x66, "LD H,(HL)"),
new Opcode(0x67, "LD H,A"),
new Opcode(0x68, "LD L,B"),
new Opcode(0x69, "LD L,C"),
new Opcode(0x6A, "LD L,D"),
new Opcode(0x6B, "LD L,E"),
new Opcode(0x6C, "LD L,H"),
new Opcode(0x6D, "LD L,L"),
new Opcode(0x6E, "LD L,(HL)"),
new Opcode(0x6F, "LD L,A"),
new Opcode(0x70, "LD (HL),B"),
new Opcode(0x71, "LD (HL),C"),
new Opcode(0x72, "LD (HL),D"),
new Opcode(0x73, "LD (HL),E"),
new Opcode(0x74, "LD (HL),H"),
new Opcode(0x75, "LD (HL),L"),
new Opcode(0x76, "HALT"),
new Opcode(0x77, "LD (HL),A"),
new Opcode(0x78, "LD A,B"),
new Opcode(0x79, "LD A,C"),
new Opcode(0x7A, "LD A,D"),
new Opcode(0x7B, "LD A,E"),
new Opcode(0x7C, "LD A,H"),
new Opcode(0x7D, "LD A,L"),
new Opcode(0x7E, "LD A,(HL)"),
new Opcode(0x7F, "LD A,A"),
new Opcode(0x80, "ADD A,B"),
new Opcode(0x81, "ADD A,C"),
new Opcode(0x82, "ADD A,D"),
new Opcode(0x83, "ADD A,E"),
new Opcode(0x84, "ADD A,H"),
new Opcode(0x85, "ADD A,L"),
new Opcode(0x86, "ADD A,(HL)"),
new Opcode(0x87, "ADD A,A"),
new Opcode(0x88, "ADC A,B"),
new Opcode(0x89, "ADC A,C"),
new Opcode(0x8A, "ADC A,D"),
new Opcode(0x8B, "ADC A,E"),
new Opcode(0x8C, "ADC A,H"),
new Opcode(0x8D, "ADC A,L"),
new Opcode(0x8E, "ADC A,(HL)"),
new Opcode(0x8F, "ADC A,A"),
new Opcode(0x90, "SUB B"),
new Opcode(0x91, "SUB C"),
new Opcode(0x92, "SUB D"),
new Opcode(0x93, "SUB E"),
new Opcode(0x94, "SUB H"),
new Opcode(0x95, "SUB L"),
new Opcode(0x96, "SUB (HL)"),
new Opcode(0x97, "SUB A"),
new Opcode(0x98, "SBC A,B"),
new Opcode(0x99, "SBC A,C"),
new Opcode(0x9A, "SBC A,D"),
new Opcode(0x9B, "SBC A,E"),
new Opcode(0x9C, "SBC A,H"),
new Opcode(0x9D, "SBC A,L"),
new Opcode(0x9E, "SBC A,(HL)"),
new Opcode(0x9F, "SBC A,A"),
new Opcode(0xA0, "AND B"),
new Opcode(0xA1, "AND C"),
new Opcode(0xA2, "AND D"),
new Opcode(0xA3, "AND E"),
new Opcode(0xA4, "AND H"),
new Opcode(0xA5, "AND L"),
new Opcode(0xA6, "AND (HL)"),
new Opcode(0xA7, "AND A"),
new Opcode(0xA8, "XOR B"),
new Opcode(0xA9, "XOR C"),
new Opcode(0xAA, "XOR D"),
new Opcode(0xAB, "XOR E"),
new Opcode(0xAC, "XOR H"),
new Opcode(0xAD, "XOR L"),
new Opcode(0xAE, "XOR (HL)"),
new Opcode(0xAF, "XOR A"),
new Opcode(0xB0, "OR B"),
new Opcode(0xB1, "OR C"),
new Opcode(0xB2, "OR D"),
new Opcode(0xB3, "OR E"),
new Opcode(0xB4, "OR H"),
new Opcode(0xB5, "OR L"),
new Opcode(0xB6, "OR (HL)"),
new Opcode(0xB7, "OR A"),
new Opcode(0xB8, "CP B"),
new Opcode(0xB9, "CP C"),
new Opcode(0xBA, "CP D"),
new Opcode(0xBB, "CP E"),
new Opcode(0xBC, "CP H"),
new Opcode(0xBD, "CP L"),
new Opcode(0xBE, "CP (HL)"),
new Opcode(0xBF, "CP A"),
new Opcode(0xC0, "RET NZ"),
new Opcode(0xC1, "POP BC"),
new Opcode(0xC2, "JP NZ,#nn"),
new Opcode(0xC3, "JP #nn"),
new Opcode(0xC4, "CALL NZ,#nn"),
new Opcode(0xC5, "PUSH BC"),
new Opcode(0xC6, "ADD A,#n"),
new Opcode(0xC7, "RST %s"),
new Opcode(0xC8, "RET Z"),
new Opcode(0xC9, "RET"),
new Opcode(0xCA, "JP Z,#nn"),
new OpcodeExtended(0xCB, OpcodesCB),
new Opcode(0xCC, "CALL Z,#nn"),
new Opcode(0xCD, "CALL #nn"),
new Opcode(0xCE, "ADC A,#n"),
new Opcode(0xCF, "RST %s"),
new Opcode(0xD0, "RET NC"),
new Opcode(0xD1, "POP DE"),
new Opcode(0xD2, "JP NC,#nn"),
new Opcode(0xD3, "OUT (#n),A"),
new Opcode(0xD4, "CALL NC,#nn"),
new Opcode(0xD5, "PUSH DE"),
new Opcode(0xD6, "SUB #n"),
new Opcode(0xD7, "RST %s"),
new Opcode(0xD8, "RET C"),
new Opcode(0xD9, "EXX"),
new Opcode(0xDA, "JP C,#nn"),
new Opcode(0xDB, "IN A,(#n)"),
new Opcode(0xDC, "CALL C,#nn"),
new OpcodeExtended(0xDD, OpcodesDD),
new Opcode(0xDE, "SBC A,#n"),
new Opcode(0xDF, "RST %s"),
new Opcode(0xE0, "RET PO"),
new Opcode(0xE1, "POP HL"),
new Opcode(0xE2, "JP PO,#nn"),
new Opcode(0xE3, "EX (SP),HL"),
new Opcode(0xE4, "CALL PO,#nn"),
new Opcode(0xE5, "PUSH HL"),
new Opcode(0xE6, "AND #n"),
new Opcode(0xE7, "RST %s"),
new Opcode(0xE8, "RET PE"),
new Opcode(0xE9, "JP (HL)"),
new Opcode(0xEA, "JP PE,#nn"),
new Opcode(0xEB, "EX DE,HL"),
new Opcode(0xEC, "CALL PE,#nn"),
new OpcodeExtended(0xED, OpcodesED),
new Opcode(0xEE, "XOR #n"),
new Opcode(0xEF, "RST %s"),
new Opcode(0xF0, "RET P"),
new Opcode(0xF1, "POP AF"),
new Opcode(0xF2, "JP P,#nn"),
new Opcode(0xF3, "DI"),
new Opcode(0xF4, "CALL P,#nn"),
new Opcode(0xF5, "PUSH AF"),
new Opcode(0xF6, "OR #n"),
new Opcode(0xF7, "RST %s"),
new Opcode(0xF8, "RET M"),
new Opcode(0xF9, "LD SP,HL"),
new Opcode(0xFA, "JP M,#nn"),
new Opcode(0xFB, "EI"),
new Opcode(0xFC, "CALL M,#nn"),
new OpcodeExtended(0xFD, OpcodesFD),
new Opcode(0xFE, "CP #n"),
new Opcode(0xFF, "RST %s")
]; | the_stack |
module TDev.RT {
//? A contact
//@ walltap cap(contacts)
export class Contact
extends RTValue
{
private _id : string = undefined;
private _first_name : string = undefined;
private _last_name : string = undefined;
private _nick_name : string = undefined;
private _middle_name : string = undefined;
private _title : string = undefined;
private _suffix : string = undefined;
private _company : string = undefined;
private _job_title : string = undefined;
private _office : string = undefined;
private _work_address : string = undefined;
private _home_address : string = undefined;
private _source : string = undefined;
private _birthday : DateTime = undefined;
private _pictureUrl: string = undefined;
private _picture : Picture = undefined;
private _email : string = undefined;
private _work_email : string = undefined;
private _personal_email : string = undefined;
private _phone_number : string = undefined;
private _home_phone : string = undefined;
private _work_phone : string = undefined;
private _mobile_phone : string = undefined;
private _web_site : string = undefined;
static mkFake(firstName : string, middleName : string, lastName : string, email : string, phoneNumber : string, pictureUrl : string): Contact {
var c = new Contact();
c._first_name = firstName;
c._middle_name = middleName;
c._last_name = lastName;
c._email = email;
c._phone_number = phoneNumber;
c._pictureUrl = Cloud.getServiceUrl() + '/doc/contacts/' + encodeURIComponent(pictureUrl);
c._source = "AdventureWorks";
return c;
}
constructor() {
super()
}
public clone(): Contact {
var c = new Contact();
c._id = this._id;
c._first_name = this._first_name;
c._last_name = this._last_name;
c._nick_name = this._nick_name;
c._middle_name = this._middle_name;
c._title = this._title;
c._suffix = this._suffix;
c._company = this._company;
c._job_title = this._job_title;
c._office = this._office;
c._work_address = this._work_address;
c._home_address = this._home_address;
c._source = this._source;
c._birthday = this._birthday;
c._pictureUrl = this._pictureUrl;
c._picture = this._picture;
c._email = this._email;
c._work_email = this._work_email;
c._personal_email = this._personal_email;
c._phone_number = this._phone_number;
c._home_phone = this._home_phone;
c._work_phone = this._work_phone;
c._mobile_phone = this._mobile_phone;
c._web_site = this._web_site;
return c;
}
static mk(nickname: string, email : string = null): Contact
{
var c = new Contact();
c._nick_name = nickname;
c._email = email;
return c;
}
public toString(): string
{
return this.name();
}
public toFullString(): string {
var r = this.name();
if (this._title != null)
r += '\ntitle: ' + this._title;
if (this._company != null)
r += '\ncompany: ' + this._company;
if (this._job_title != null)
r += '\njob title: ' + this._job_title;
if (this._office != null)
r += '\noffice: ' + this._office;
if (this._work_address != null)
r += '\nwork address: ' + this._work_address;
if (this._home_address != null)
r += '\nhome address: ' + this._home_address;
if (this._birthday != null)
r += '\nbirthday: ' + this._birthday;
if (this._email != null)
r += '\nemail: ' + this._email;
if (this._work_email != null)
r += '\nwork email: ' + this._work_email;
if (this._personal_email != null)
r += '\npersonal email: ' + this._personal_email;
if (this._phone_number != null)
r += '\nphone number: ' + this._phone_number;
if (this._home_phone != null)
r += '\nhome phone: ' + this._home_phone;
if (this._work_phone != null)
r += '\nwork phone: ' + this._work_phone;
if (this._mobile_phone != null)
r += '\nmobile phone: ' + this._mobile_phone;
if (this._web_site != null)
r += '\nweb site: ' + this._web_site;
return r;
}
//? Gets the user id if any
//@ readsMutable
public id() : string {
return this._id;
}
//? Sets the user id
//@ writesMutable
public set_id(id : string) {
this._id = id;
}
//? Gets the display name (not used when saving contact)
//@ readsMutable
public name() : string
{
if (this._nick_name) return this._nick_name;
else
return [this._first_name, this._middle_name, this._last_name]
.filter(s => !!s)
.join(" ");
}
//? Gets the first name if any.
//@ readsMutable
public first_name() : string { return this._first_name || ''; }
//? Sets the first name
//@ writesMutable
public set_first_name(first_name:string) : void { this._first_name = first_name; }
//? Gets the last name if any.
//@ readsMutable
public last_name() : string { return this._last_name; }
//? Sets the last name
//@ writesMutable
public set_last_name(last_name:string) : void { this._last_name = last_name; }
//? Gets the nickname if any.
//@ readsMutable
public nick_name() : string { return this._nick_name; }
//? Sets the middle name
//@ writesMutable
public set_nick_name(nick_name:string) : void { this._nick_name = nick_name; }
//? Gets the middle name if any.
//@ readsMutable
public middle_name() : string { return this._middle_name; }
//? Sets the middle name
//@ writesMutable
public set_middle_name(middle_name:string) : void { this._middle_name = middle_name; }
//? Gets the name title if any.
//@ readsMutable
public title() : string { return this._title; }
//? Sets the title
//@ writesMutable
public set_title(title:string) : void { this._title = title; }
//? Gets the name suffix if any.
//@ readsMutable
public suffix() : string { return this._suffix; }
//? Sets the suffix
//@ writesMutable
public set_suffix(suffix:string) : void { this._suffix = suffix; }
//? Gets the company name if any.
//@ readsMutable
public company() : string { return this._company; }
//? Sets the company
//@ writesMutable
public set_company(company:string) : void { this._company = company; }
//? Gets the job title at the company if any.
//@ readsMutable
public job_title() : string { return this._title; }
//? Sets the job title
//@ writesMutable
public set_job_title(job_title:string) : void { this._job_title = job_title; }
//? Gets the office location at the company if any.
//@ readsMutable
public office() : string { return this._office; }
//? Sets the office location at the company
//@ writesMutable
public set_office(office:string) : void { this._office = office; }
//? Gets the home address if any
//@ readsMutable
public work_address() : string { return this._work_address; }
//? Sets the work address
//@ writesMutable
public set_work_address(work_address:string) : void { this._work_address = work_address; }
//? Gets the work address if any
//@ readsMutable
public home_address() : string { return this._home_address; }
//? Sets the home address
//@ writesMutable
public set_home_address(home_address:string) : void { this._home_address = home_address; }
//? Gets the source of this contact (phone, etc...)
//@ readsMutable
public source() : string { return this._source; }
//? Sets the source
//@ writesMutable
public set_source(source:string) : void { this._source = source; }
//? Gets the birth date if any.
//@ readsMutable
public birthday() : DateTime { return this._birthday; }
//? Sets the birthday
//@ writesMutable
public set_birthday(birthday:DateTime) : void { this._birthday = birthday; }
//? Gets the picture of the contact if any.
//@ returns(Picture) readsMutable picAsync
public picture(r : ResumeCtx) // : Picture
{
if (!this._picture && this._pictureUrl) {
Picture.fromUrl(this._pictureUrl, true)
.then((pic) => {
this._picture = pic;
r.resumeVal(pic);
})
.done();
}
r.resumeVal(this._picture);
}
//? Sets the picture
//@ writesMutable [picture].readsMutable
public set_picture(picture: Picture): void {
this._pictureUrl = undefined;
this._picture = picture;
}
//? Sets the picture url
//@ writesMutable
public setPicture_url(url: string) {
this._pictureUrl = url;
this._picture = null;
}
public getViewCore(s: IStackFrame, b: BoxBase): HTMLElement {
var d = div("item");
if (this._picture)
d.appendChild(div("item-image contact-image", this._picture.getViewCore(s, b)));
else if (this._pictureUrl) {
var img = HTML.mkImg(this._pictureUrl);
img.className = "item-image contact-image";
d.appendChild(img);
}
var dc = div("item-info");
d.appendChild(dc);
var n = this.name();
if (n)
dc.appendChild(div("item-title", n));
var t = this.title() || this._email || this._work_email || this._personal_email;
if (t)
dc.appendChild(div("item-subtitle", t));
if (this.company() || this.job_title())
dc.appendChild(div("item-description", this.job_title() + ' ' + this.company()));
var ss = this.source();
if (ss)
dc.appendChild(div("item-subtle", ss));
return d;
}
//? Gets the work or personal email if any
//@ readsMutable
public email() : Link { return this._email ? Link.mk(this._email, LinkKind.email) : undefined; }
//? Sets the work or personal email
//@ writesMutable
public set_email(email:string) : void { this._email = email; }
//? Gets the work email if any
//@ readsMutable
public work_email() : Link { return this._work_email ? Link.mk(this._work_email, LinkKind.email) : undefined; }
//? Sets the work email
//@ writesMutable
public set_work_email(work_email:string) : void { this._work_email = work_email; }
//? Gets the personal email if any
//@ readsMutable
public personal_email() : Link { return this._personal_email ? Link.mk(this._personal_email, LinkKind.email) : undefined; }
//? Sets the personal email
//@ writesMutable
public set_personal_email(personal_email:string) : void { this._personal_email = personal_email; }
//? Gets the cell or work or home phone number if any
//@ readsMutable
public phone_number() : Link { return this._phone_number ? Link.mk(this._phone_number, LinkKind.phoneNumber) : undefined; }
//? Sets the cell or work or home phone number if any
//@ writesMutable
public set_phone_number(phone_number:string) : void { this._phone_number = phone_number; }
//? Gets the home phone number if any
//@ readsMutable
public home_phone() : Link { return this._home_phone ? Link.mk(this._home_phone, LinkKind.phoneNumber) : undefined; }
//? Sets the home phone
//@ writesMutable
public set_home_phone(home_phone:string) : void { this._home_phone = home_phone; }
//? Gets the work phone number if any
//@ readsMutable
public work_phone() : Link { return this._work_phone ? Link.mk(this._work_phone, LinkKind.phoneNumber) : undefined; }
//? Sets the work phone
//@ writesMutable
public set_work_phone(work_phone:string) : void { this._work_phone = work_phone; }
//? Gets the cell phone number if any
//@ readsMutable
public mobile_phone() : Link { return this._mobile_phone ? Link.mk(this._mobile_phone, LinkKind.phoneNumber) : undefined; }
//? Sets the mobile phone
//@ writesMutable
public set_mobile_phone(mobile_phone:string) : void { this._mobile_phone = mobile_phone; }
//? Gets the web site if any
//@ readsMutable
public web_site() : Link { return this._web_site ? Link.mk(this._web_site, LinkKind.hyperlink) : undefined; }
//? Sets the web site
//@ writesMutable
public set_web_site(web_site:string) : void { this._web_site = web_site; }
public set_nickname(value:string) : void
{
this.set_nickname(value);
}
public set_website(value:string) : void
{
this.set_web_site(value);
}
//? Posts the contact to the wall
//@ cap(none)
public post_to_wall(s:IStackFrame) : void { super.post_to_wall(s) }
}
} | the_stack |
* @packageDocumentation
* @hidden
*/
import { EDITOR, TEST } from 'internal:constants';
import { Asset } from '../assets';
import { legacyCC } from '../global-exports';
import { js } from '../utils/js';
import Cache from './cache';
import { decodeUuid, normalize } from './helper';
import { AssetType } from './shared';
export interface IConfigOption {
importBase: string;
nativeBase: string;
base: string;
name: string;
deps: string[];
uuids: string[];
paths: Record<string, any[]>;
scenes: Record<string, string>;
packs: Record<string, string[]>;
versions: { import: string[], native: string[] };
redirect: string[];
debug: boolean;
types: string[];
extensionMap: Record<string, string[]>;
}
export interface IAssetInfo {
uuid: string;
packs?: IPackInfo[];
redirect?: string;
ver?: string;
nativeVer?: string;
extension?: string;
}
export interface IPackInfo extends IAssetInfo {
packedUuids: string[];
ext: string;
}
export interface IAddressableInfo extends IAssetInfo {
path: string;
ctor: AssetType;
}
export interface ISceneInfo extends IAssetInfo {
url: string;
}
const isMatchByWord = (path: string, test: string): boolean => {
if (path.length > test.length) {
const nextAscii = path.charCodeAt(test.length);
return nextAscii === 47; // '/'
}
return true;
};
const processOptions = (options: IConfigOption) => {
if (EDITOR || TEST) { return; }
let uuids = options.uuids;
const paths = options.paths;
const types = options.types;
const bundles = options.deps;
const realEntries = options.paths = Object.create(null);
if (options.debug === false) {
for (let i = 0, l = uuids.length; i < l; i++) {
uuids[i] = decodeUuid(uuids[i]);
}
for (const id in paths) {
const entry = paths[id];
const type = entry[1];
entry[1] = types[type];
}
} else {
const out = Object.create(null);
for (let i = 0, l = uuids.length; i < l; i++) {
const uuid = uuids[i];
uuids[i] = out[uuid] = decodeUuid(uuid);
}
uuids = out;
}
for (const id in paths) {
const entry = paths[id];
realEntries[uuids[id]] = entry;
}
const scenes = options.scenes;
for (const name in scenes) {
const uuid = scenes[name];
scenes[name] = uuids[uuid];
}
const packs = options.packs;
for (const packId in packs) {
const packedIds = packs[packId];
for (let j = 0; j < packedIds.length; ++j) {
packedIds[j] = uuids[packedIds[j]];
}
}
const versions = options.versions;
if (versions) {
for (const folder in versions) {
const entries = versions[folder];
for (let i = 0; i < entries.length; i += 2) {
const uuid = entries[i];
entries[i] = uuids[uuid] || uuid;
}
}
}
const redirect = options.redirect;
if (redirect) {
for (let i = 0; i < redirect.length; i += 2) {
redirect[i] = uuids[redirect[i]];
redirect[i + 1] = bundles[redirect[i + 1]];
}
}
const extensionMap = options.extensionMap;
if (extensionMap) {
for (const ext in options.extensionMap) {
if (!Object.prototype.hasOwnProperty.call(options.extensionMap, ext)) {
continue;
}
options.extensionMap[ext].forEach((uuid, index) => {
options.extensionMap[ext][index] = uuids[uuid] || uuid;
});
}
}
};
export default class Config {
public name = '';
public base = '';
public importBase = '';
public nativeBase = '';
public deps: string[] | null = null;
public assetInfos = new Cache<IAssetInfo>();
public scenes = new Cache<ISceneInfo>();
public paths = new Cache<IAddressableInfo[]>();
public init (options: IConfigOption) {
processOptions(options);
this.importBase = options.importBase || '';
this.nativeBase = options.nativeBase || '';
this.base = options.base || '';
this.name = options.name || '';
this.deps = options.deps || [];
// init
this._initUuid(options.uuids);
this._initPath(options.paths);
this._initScene(options.scenes);
this._initPackage(options.packs);
this._initVersion(options.versions);
this._initRedirect(options.redirect);
for (const ext in options.extensionMap) {
if (!Object.prototype.hasOwnProperty.call(options.extensionMap, ext)) {
continue;
}
options.extensionMap[ext].forEach((uuid) => {
const assetInfo = this.assetInfos.get(uuid);
if (assetInfo) {
assetInfo.extension = ext;
}
});
}
}
public getInfoWithPath (path: string, type?: AssetType | null): IAddressableInfo | null {
if (!path) {
return null;
}
path = normalize(path);
const items = this.paths.get(path);
if (items) {
if (type) {
for (let i = 0, l = items.length; i < l; i++) {
const assetInfo = items[i];
if (js.isChildClassOf(assetInfo.ctor, type)) {
return assetInfo;
}
}
} else {
return items[0];
}
}
return null;
}
public getDirWithPath (path: string, type?: AssetType | null, out?: IAddressableInfo[]): IAddressableInfo[] {
path = normalize(path);
if (path[path.length - 1] === '/') {
path = path.slice(0, -1);
}
const infos = out || [];
this.paths.forEach((items, p) => {
if ((p.startsWith(path) && isMatchByWord(p, path)) || !path) {
for (let i = 0, l = items.length; i < l; i++) {
const entry = items[i];
if (!type || js.isChildClassOf(entry.ctor, type)) {
infos.push(entry);
}
}
}
});
return infos;
}
public getAssetInfo (uuid: string): IAssetInfo | null {
return this.assetInfos.get(uuid) || null;
}
public getSceneInfo (name: string): ISceneInfo | null {
if (!name.endsWith('.scene')) {
name += '.scene';
}
if (name[0] !== '/' && !name.startsWith('db://')) {
name = `/${name}`;
}
// search scene
const info = this.scenes.find((val, key) => key.endsWith(name));
return info;
}
public destroy () {
this.paths.destroy();
this.scenes.destroy();
this.assetInfos.destroy();
}
private _initUuid (uuidList: string[]) {
if (!uuidList) {
return;
}
this.assetInfos.clear();
for (let i = 0, l = uuidList.length; i < l; i++) {
const uuid = uuidList[i];
this.assetInfos.add(uuid, { uuid });
}
}
private _initPath (pathList: Record<string, string[]>) {
if (!pathList) { return; }
const paths = this.paths;
paths.clear();
for (const uuid in pathList) {
const info = pathList[uuid];
const path = info[0];
const type = info[1];
const isSubAsset = info.length === 3;
const assetInfo = this.assetInfos.get(uuid) as IAddressableInfo;
assetInfo.path = path;
assetInfo.ctor = js._getClassById(type) as Constructor<Asset>;
if (paths.has(path)) {
if (isSubAsset) {
paths.get(path)!.push(assetInfo);
} else {
paths.get(path)!.unshift(assetInfo);
}
} else {
paths.add(path, [assetInfo]);
}
}
}
private _initScene (sceneList: Record<string, string>) {
if (!sceneList) { return; }
const scenes = this.scenes;
scenes.clear();
const assetInfos = this.assetInfos;
for (const sceneName in sceneList) {
const uuid = sceneList[sceneName];
const assetInfo = assetInfos.get(uuid) as ISceneInfo;
assetInfo.url = sceneName;
scenes.add(sceneName, assetInfo);
}
}
private _initPackage (packageList: Record<string, string[]>) {
if (!packageList) { return; }
const assetInfos = this.assetInfos;
for (const packUuid in packageList) {
const uuids = packageList[packUuid];
const pack = { uuid: packUuid, packedUuids: uuids, ext: '.json' };
assetInfos.add(packUuid, pack);
for (let i = 0, l = uuids.length; i < l; i++) {
const uuid = uuids[i];
const assetInfo = assetInfos.get(uuid)!;
const assetPacks = assetInfo.packs;
if (assetPacks) {
if (l === 1) {
assetPacks.unshift(pack);
} else {
assetPacks.push(pack);
}
} else {
assetInfo.packs = [pack];
}
}
}
}
private _initVersion (versions: { import?: string[], native?: string[] }) {
if (!versions) { return; }
const assetInfos = this.assetInfos;
let entries = versions.import;
if (entries) {
for (let i = 0, l = entries.length; i < l; i += 2) {
const uuid = entries[i];
const assetInfo = assetInfos.get(uuid)!;
assetInfo.ver = entries[i + 1];
}
}
entries = versions.native;
if (entries) {
for (let i = 0, l = entries.length; i < l; i += 2) {
const uuid = entries[i];
const assetInfo = assetInfos.get(uuid)!;
assetInfo.nativeVer = entries[i + 1];
}
}
}
private _initRedirect (redirect: string[]) {
if (!redirect) { return; }
const assetInfos = this.assetInfos;
for (let i = 0, l = redirect.length; i < l; i += 2) {
const uuid = redirect[i];
const assetInfo = assetInfos.get(uuid)!;
assetInfo.redirect = redirect[i + 1];
}
}
}
if (TEST) {
legacyCC._Test.Config = Config;
} | the_stack |
import * as path from "path";
import * as _ from "lodash";
import * as crypto from "crypto";
import { IDictionary, IErrors, IFileSystem } from "../../common/declarations";
import { IInjector } from "../../common/definitions/yok";
import { injector } from "../../common/yok";
const PROTOCOL_VERSION_LENGTH_SIZE = 1;
const PROTOCOL_OPERATION_LENGTH_SIZE = 1;
const SIZE_BYTE_LENGTH = 1;
const REPORT_LENGTH = 1;
const DO_REFRESH_LENGTH = 1;
const SYNC_OPERATION_TIMEOUT = 60000;
const TRY_CONNECT_TIMEOUT = 60000;
const DEFAULT_LOCAL_HOST_ADDRESS = "127.0.0.1";
export class AndroidLivesyncTool implements IAndroidLivesyncTool {
public static DELETE_FILE_OPERATION = 7;
public static CREATE_FILE_OPERATION = 8;
public static DO_SYNC_OPERATION = 9;
public static ERROR_REPORT = 1;
public static OPERATION_END_REPORT = 2;
public static OPERATION_END_NO_REFRESH_REPORT_CODE = 3;
public static DO_REFRESH = 1;
public static SKIP_REFRESH = 0;
public static APP_IDENTIFIER_MISSING_ERROR =
'You need to provide "appIdentifier" as a configuration property!';
public static APP_PLATFORMS_PATH_MISSING_ERROR =
'You need to provide "appPlatformsPath" as a configuration property!';
public static SOCKET_CONNECTION_ALREADY_EXISTS_ERROR =
"Socket connection already exists.";
public static SOCKET_CONNECTION_TIMED_OUT_ERROR =
"Socket connection timed out.";
public static NO_SOCKET_CONNECTION_AVAILABLE_ERROR =
"No socket connection available.";
public protocolVersion: string;
private operationPromises: IDictionary<any>;
private socketError: string | Error;
private socketConnection: ILiveSyncSocket;
private configuration: IAndroidLivesyncToolConfiguration;
private pendingConnectionData: {
connectionTimer?: NodeJS.Timer;
socketTimer?: NodeJS.Timer;
rejectHandler?: Function;
socket?: INetSocket;
} = null;
constructor(
private $androidProcessService: Mobile.IAndroidProcessService,
private $errors: IErrors,
private $fs: IFileSystem,
private $logger: ILogger,
private $mobileHelper: Mobile.IMobileHelper,
private $injector: IInjector
) {
this.operationPromises = Object.create(null);
this.socketError = null;
this.socketConnection = null;
}
public async connect(
configuration: IAndroidLivesyncToolConfiguration
): Promise<void> {
if (!configuration.appIdentifier) {
this.$errors.fail(AndroidLivesyncTool.APP_IDENTIFIER_MISSING_ERROR);
}
if (!configuration.appPlatformsPath) {
this.$errors.fail(AndroidLivesyncTool.APP_PLATFORMS_PATH_MISSING_ERROR);
}
if (this.socketConnection) {
this.$errors.fail(
AndroidLivesyncTool.SOCKET_CONNECTION_ALREADY_EXISTS_ERROR
);
}
if (!configuration.localHostAddress) {
configuration.localHostAddress =
process.env.NATIVESCRIPT_LIVESYNC_ADDRESS || DEFAULT_LOCAL_HOST_ADDRESS;
}
const connectTimeout = configuration.connectTimeout || TRY_CONNECT_TIMEOUT;
this.configuration = configuration;
this.socketError = null;
const port = await this.$androidProcessService.forwardFreeTcpToAbstractPort(
{
deviceIdentifier: configuration.deviceIdentifier,
appIdentifier: configuration.appIdentifier,
abstractPort: `localabstract:${configuration.appIdentifier}-livesync`,
}
);
const connectionResult = await this.connectEventuallyUntilTimeout(
this.createSocket.bind(this, port),
connectTimeout,
configuration
);
this.handleConnection(connectionResult);
}
public async sendFile(filePath: string): Promise<void> {
await this.sendFileHeader(filePath);
await this.sendFileContent(filePath);
}
public async sendFiles(filePaths: string[]) {
for (const filePath of filePaths) {
if (this.$fs.getLsStats(filePath).isFile()) {
if (!this.$fs.exists(filePath)) {
this.$errors.fail(`${filePath} doesn't exist.`);
}
await this.sendFile(filePath);
}
}
}
public sendDirectory(directoryPath: string) {
const list = this.$fs.enumerateFilesInDirectorySync(directoryPath);
return this.sendFiles(list);
}
public async removeFile(filePath: string): Promise<void> {
this.verifyActiveConnection();
const filePathData = this.getFilePathData(filePath);
const headerBuffer = Buffer.alloc(
PROTOCOL_OPERATION_LENGTH_SIZE +
SIZE_BYTE_LENGTH +
filePathData.filePathLengthSize +
filePathData.filePathLengthBytes
);
let offset = 0;
offset += headerBuffer.write(
AndroidLivesyncTool.DELETE_FILE_OPERATION.toString(),
offset,
PROTOCOL_OPERATION_LENGTH_SIZE
);
offset = headerBuffer.writeInt8(filePathData.filePathLengthSize, offset);
offset += headerBuffer.write(
filePathData.filePathLengthString,
offset,
filePathData.filePathLengthSize
);
headerBuffer.write(
filePathData.relativeFilePath,
offset,
filePathData.filePathLengthBytes
);
const hash = crypto.createHash("md5").update(headerBuffer).digest();
await this.writeToSocket(headerBuffer);
await this.writeToSocket(hash);
}
public async removeFiles(files: string[]): Promise<void> {
for (const file of files) {
await this.removeFile(file);
}
}
public generateOperationIdentifier(): string {
return crypto.randomBytes(16).toString("hex");
}
public isOperationInProgress(operationId: string): boolean {
return !!this.operationPromises[operationId];
}
public sendDoSyncOperation(
options?: IDoSyncOperationOptions
): Promise<IAndroidLivesyncSyncOperationResult> {
options = _.assign(
{ doRefresh: true, timeout: SYNC_OPERATION_TIMEOUT },
options
);
const { doRefresh, timeout, operationId } = options;
const id = operationId || this.generateOperationIdentifier();
const operationPromise: Promise<IAndroidLivesyncSyncOperationResult> = new Promise(
(resolve, reject) => {
if (!this.verifyActiveConnection(reject)) {
return;
}
const message = `${AndroidLivesyncTool.DO_SYNC_OPERATION}${id}`;
const headerBuffer = Buffer.alloc(
Buffer.byteLength(message) + DO_REFRESH_LENGTH
);
const socketId = this.socketConnection.uid;
const doRefreshCode = doRefresh
? AndroidLivesyncTool.DO_REFRESH
: AndroidLivesyncTool.SKIP_REFRESH;
const offset = headerBuffer.write(message);
headerBuffer.writeUInt8(doRefreshCode, offset);
const hash = crypto.createHash("md5").update(headerBuffer).digest();
this.writeToSocket(headerBuffer)
.then(() => {
this.writeToSocket(hash).catch(reject);
})
.catch(reject);
const timeoutId = setTimeout(() => {
if (this.isOperationInProgress(id)) {
this.handleSocketError(
socketId,
"Sync operation is taking too long"
);
}
}, timeout);
this.operationPromises[id] = {
resolve,
reject,
socketId,
timeoutId,
};
}
);
return operationPromise;
}
public end(error?: Error) {
if (this.socketConnection) {
const socketUid = this.socketConnection.uid;
const socket = this.socketConnection;
error =
error ||
this.getErrorWithMessage(
"Socket connection ended before sync operation is complete."
);
//remove listeners and delete this.socketConnection
this.cleanState(socketUid);
//call end of the connection (close and error callbacks won't be called - listeners removed)
socket.end();
socket.destroy();
//reject all pending sync requests and clear timeouts
this.rejectPendingSyncOperations(socketUid, error);
}
}
public hasConnection(): boolean {
return !!this.socketConnection;
}
private async sendFileHeader(filePath: string): Promise<void> {
this.verifyActiveConnection();
const filePathData = this.getFilePathData(filePath);
const stats = this.$fs.getFsStats(filePathData.filePath);
const fileContentLengthBytes = stats.size;
const fileContentLengthString = fileContentLengthBytes.toString();
const fileContentLengthSize = Buffer.byteLength(fileContentLengthString);
const headerBuffer = Buffer.alloc(
PROTOCOL_OPERATION_LENGTH_SIZE +
SIZE_BYTE_LENGTH +
filePathData.filePathLengthSize +
filePathData.filePathLengthBytes +
SIZE_BYTE_LENGTH +
fileContentLengthSize
);
if (filePathData.filePathLengthSize > 255) {
this.$errors.fail("File name size is longer that 255 digits.");
} else if (fileContentLengthSize > 255) {
this.$errors.fail("File name size is longer that 255 digits.");
}
let offset = 0;
offset += headerBuffer.write(
AndroidLivesyncTool.CREATE_FILE_OPERATION.toString(),
offset,
PROTOCOL_OPERATION_LENGTH_SIZE
);
offset = headerBuffer.writeUInt8(filePathData.filePathLengthSize, offset);
offset += headerBuffer.write(
filePathData.filePathLengthString,
offset,
filePathData.filePathLengthSize
);
offset += headerBuffer.write(
filePathData.relativeFilePath,
offset,
filePathData.filePathLengthBytes
);
offset = headerBuffer.writeUInt8(fileContentLengthSize, offset);
headerBuffer.write(fileContentLengthString, offset, fileContentLengthSize);
const hash = crypto.createHash("md5").update(headerBuffer).digest();
await this.writeToSocket(headerBuffer);
await this.writeToSocket(hash);
}
private sendFileContent(filePath: string): Promise<boolean> {
return new Promise((resolve, reject) => {
if (!this.verifyActiveConnection(reject)) {
return;
}
const fileStream = this.$fs.createReadStream(filePath);
const fileHash = crypto.createHash("md5");
fileStream
.on("data", (chunk: Buffer) => {
fileHash.update(chunk);
this.writeToSocket(chunk).catch(reject);
})
.on("end", () => {
this.writeToSocket(fileHash.digest())
.then(() => resolve())
.catch(reject);
})
.on("error", (error: Error) => {
reject(error);
});
});
}
private createSocket(port: number): ILiveSyncSocket {
const socket = this.$injector.resolve("LiveSyncSocket");
socket.connect(port, this.configuration.localHostAddress);
return socket;
}
private checkConnectionStatus() {
if (this.socketConnection === null) {
const defaultError = this.getErrorWithMessage(
AndroidLivesyncTool.NO_SOCKET_CONNECTION_AVAILABLE_ERROR
);
const error = this.socketError || defaultError;
return error;
}
}
private verifyActiveConnection(rejectHandler?: any) {
const error = this.checkConnectionStatus();
if (error && rejectHandler) {
rejectHandler(error);
return false;
}
if (error && !rejectHandler) {
this.$errors.fail(error.toString());
}
return true;
}
private handleConnection({
socket,
data,
}: {
socket: ILiveSyncSocket;
data: Buffer | string;
}) {
this.socketConnection = socket;
this.socketConnection.uid = this.generateOperationIdentifier();
const versionLength = (<Buffer>data).readUInt8(0);
const versionBuffer = data.slice(
PROTOCOL_VERSION_LENGTH_SIZE,
versionLength + PROTOCOL_VERSION_LENGTH_SIZE
);
const appIdentifierBuffer = data.slice(
versionLength + PROTOCOL_VERSION_LENGTH_SIZE,
data.length
);
const protocolVersion = versionBuffer.toString();
const appIdentifier = appIdentifierBuffer.toString();
this.$logger.trace(
`Handle socket connection for app identifier: ${appIdentifier} with protocol version: ${protocolVersion}.`
);
this.protocolVersion = protocolVersion;
this.socketConnection.on("data", (connectionData: Buffer) =>
this.handleData(socket.uid, connectionData)
);
this.socketConnection.on("close", (hasError: boolean) =>
this.handleSocketClose(socket.uid, hasError)
);
this.socketConnection.on("error", (err: Error) => {
const error = new Error(`Socket Error:\n${err}`);
if (this.configuration.errorHandler) {
this.configuration.errorHandler(error);
} else {
this.handleSocketError(socket.uid, error.message);
}
});
}
private connectEventuallyUntilTimeout(
factory: () => ILiveSyncSocket,
timeout: number,
configuration: IAndroidLivesyncToolConfiguration
): Promise<{ socket: ILiveSyncSocket; data: Buffer | string }> {
return new Promise((resolve, reject) => {
let lastKnownError: Error | string,
isConnected = false;
const connectionTimer = setTimeout(async () => {
if (!isConnected) {
isConnected = true;
if (
this.pendingConnectionData &&
this.pendingConnectionData.socketTimer
) {
clearTimeout(this.pendingConnectionData.socketTimer);
}
const applicationPid = await this.$androidProcessService.getAppProcessId(
configuration.deviceIdentifier,
configuration.appIdentifier
);
if (!applicationPid) {
this.$logger.trace(
"In Android LiveSync tool, lastKnownError is: ",
lastKnownError
);
this.$logger.info(
`Application ${configuration.appIdentifier} is not running on device ${configuration.deviceIdentifier}.`
.yellow
);
this.$logger.info(
`This issue may be caused by:
* crash at startup (try \`tns debug android --debug-brk\` to check why it crashes)
* different application identifier in your package.json and in your gradle files (check your identifier in \`package.json\` and in all *.gradle files in your App_Resources directory)
* device is locked
* manual closing of the application`.cyan
);
reject(
new Error(
`Application ${configuration.appIdentifier} is not running`
)
);
} else {
reject(
lastKnownError ||
new Error(AndroidLivesyncTool.SOCKET_CONNECTION_TIMED_OUT_ERROR)
);
}
this.pendingConnectionData = null;
}
}, timeout);
this.pendingConnectionData = {
connectionTimer,
rejectHandler: reject,
};
const tryConnect = () => {
const socket = factory();
const tryConnectAfterTimeout = (error: Error) => {
if (isConnected) {
this.pendingConnectionData = null;
return;
}
if (typeof error === "boolean" && error) {
error = new Error("Socket closed due to error");
}
lastKnownError = error;
socket.removeAllListeners();
this.pendingConnectionData.socketTimer = setTimeout(tryConnect, 1000);
};
this.pendingConnectionData.socket = socket;
socket.once("data", (data) => {
socket.removeListener("close", tryConnectAfterTimeout);
socket.removeListener("error", tryConnectAfterTimeout);
isConnected = true;
clearTimeout(connectionTimer);
resolve({ socket, data });
});
socket.on("close", tryConnectAfterTimeout);
socket.on("error", tryConnectAfterTimeout);
};
tryConnect();
});
}
private handleData(socketId: string, data: any) {
const reportType = data.readUInt8();
const infoBuffer = data.slice(REPORT_LENGTH, data.length);
if (reportType === AndroidLivesyncTool.ERROR_REPORT) {
const errorMessage = infoBuffer.toString();
this.handleSocketError(socketId, errorMessage);
} else if (reportType === AndroidLivesyncTool.OPERATION_END_REPORT) {
this.handleSyncEnd({ data: infoBuffer, didRefresh: true });
} else if (
reportType === AndroidLivesyncTool.OPERATION_END_NO_REFRESH_REPORT_CODE
) {
this.handleSyncEnd({ data: infoBuffer, didRefresh: false });
}
}
private handleSyncEnd({
data,
didRefresh,
}: {
data: any;
didRefresh: boolean;
}) {
const operationId = data.toString();
const promiseHandler = this.operationPromises[operationId];
if (promiseHandler) {
clearTimeout(promiseHandler.timeoutId);
promiseHandler.resolve({ operationId, didRefresh });
delete this.operationPromises[operationId];
}
}
private handleSocketClose(socketId: string, hasError: boolean) {
const errorMessage = "Socket closed from server before operation end.";
this.handleSocketError(socketId, errorMessage);
}
private handleSocketError(socketId: string, errorMessage: string) {
const error = this.getErrorWithMessage(errorMessage);
if (this.socketConnection && this.socketConnection.uid === socketId) {
this.socketError = error;
this.end(error);
} else {
this.rejectPendingSyncOperations(socketId, error);
}
}
private cleanState(socketId: string) {
if (this.socketConnection && this.socketConnection.uid === socketId) {
this.socketConnection.removeAllListeners();
this.socketConnection = null;
}
}
private rejectPendingSyncOperations(socketId: string, error: Error) {
_.keys(this.operationPromises).forEach((operationId) => {
const operationPromise = this.operationPromises[operationId];
if (operationPromise.socketId === socketId) {
clearTimeout(operationPromise.timeoutId);
operationPromise.reject(error);
delete this.operationPromises[operationId];
}
});
}
private getErrorWithMessage(errorMessage: string) {
const error = new Error(errorMessage);
error.message = errorMessage;
return error;
}
private getFilePathData(
filePath: string
): {
relativeFilePath: string;
filePathLengthBytes: number;
filePathLengthString: string;
filePathLengthSize: number;
filePath: string;
} {
const relativeFilePath = this.resolveRelativePath(filePath);
const filePathLengthBytes = Buffer.byteLength(relativeFilePath);
const filePathLengthString = filePathLengthBytes.toString();
const filePathLengthSize = Buffer.byteLength(filePathLengthString);
return {
relativeFilePath,
filePathLengthBytes,
filePathLengthString,
filePathLengthSize,
filePath,
};
}
private resolveRelativePath(filePath: string): string {
const relativeFilePath = path.relative(
this.configuration.appPlatformsPath,
filePath
);
return this.$mobileHelper.buildDevicePath(relativeFilePath);
}
private async writeToSocket(data: Buffer): Promise<Boolean> {
this.verifyActiveConnection();
const result = await this.socketConnection.writeAsync(data);
return result;
}
}
injector.register("androidLivesyncTool", AndroidLivesyncTool); | the_stack |
import {PortableSerializer} from './PortableSerializer';
import {DataOutput, PositionalDataOutput} from '../Data';
import {ClassDefinition, FieldDefinition} from './ClassDefinition';
import {BitsUtil} from '../../util/BitsUtil';
import {Portable, FieldType, PortableWriter} from '../Portable';
import * as Long from 'long';
import {
BigDecimal,
HazelcastSerializationError,
LocalDate,
LocalDateTime,
LocalTime,
OffsetDateTime
} from '../../core';
import {IOUtil} from '../../util/IOUtil';
import {PortableUtil} from '../../util/PortableUtil';
/** @internal */
export class DefaultPortableWriter implements PortableWriter {
private serializer: PortableSerializer;
private readonly output: PositionalDataOutput;
private classDefinition: ClassDefinition;
private readonly offset: number;
private readonly begin: number;
private readonly writtenFields: Set<string>;
constructor(serializer: PortableSerializer, output: PositionalDataOutput, classDefinition: ClassDefinition) {
this.serializer = serializer;
this.output = output;
this.classDefinition = classDefinition;
this.writtenFields = new Set<string>();
this.begin = this.output.position();
this.output.writeZeroBytes(4);
this.output.writeInt(this.classDefinition.getFieldCount());
this.offset = this.output.position();
const fieldIndexesLength: number = (this.classDefinition.getFieldCount() + 1) * BitsUtil.INT_SIZE_IN_BYTES;
this.output.writeZeroBytes(fieldIndexesLength);
}
writeInt(fieldName: string, value: number): void {
this.setPosition(fieldName, FieldType.INT);
this.output.writeInt(value);
}
writeLong(fieldName: string, long: Long): void {
this.setPosition(fieldName, FieldType.LONG);
this.output.writeLong(long);
}
writeUTF(fieldName: string, str: string | null): void {
this.writeString(fieldName, str);
}
writeString(fieldName: string, str: string | null): void {
this.setPosition(fieldName, FieldType.STRING);
this.output.writeString(str);
}
writeBoolean(fieldName: string, value: boolean): void {
this.setPosition(fieldName, FieldType.BOOLEAN);
this.output.writeBoolean(value);
}
writeByte(fieldName: string, value: number): void {
this.setPosition(fieldName, FieldType.BYTE);
this.output.writeByte(value);
}
writeChar(fieldName: string, char: string): void {
this.setPosition(fieldName, FieldType.CHAR);
this.output.writeChar(char);
}
writeDouble(fieldName: string, double: number): void {
this.setPosition(fieldName, FieldType.DOUBLE);
this.output.writeDouble(double);
}
writeFloat(fieldName: string, float: number): void {
this.setPosition(fieldName, FieldType.FLOAT);
this.output.writeFloat(float);
}
writeShort(fieldName: string, value: number): void {
this.setPosition(fieldName, FieldType.SHORT);
this.output.writeShort(value);
}
writePortable(fieldName: string, portable: Portable | null): void {
const fieldDefinition = this.setPosition(fieldName, FieldType.PORTABLE);
const isNullPortable = (portable == null);
this.output.writeBoolean(isNullPortable);
this.output.writeInt(fieldDefinition.getFactoryId());
this.output.writeInt(fieldDefinition.getClassId());
if (!isNullPortable) {
this.serializer.writeObject(this.output, portable);
}
}
writeNullPortable(fieldName: string, factoryId: number, classId: number): void {
this.setPosition(fieldName, FieldType.PORTABLE);
this.output.writeBoolean(true);
this.output.writeInt(factoryId);
this.output.writeInt(classId);
}
writeDecimal(fieldName: string, value: BigDecimal | null): void {
this.writeNullable(fieldName, FieldType.DECIMAL, value, IOUtil.writeDecimal);
}
writeTime(fieldName: string, value: LocalTime | null): void {
this.writeNullable(fieldName, FieldType.TIME, value, IOUtil.writeLocalTime);
}
writeDate(fieldName: string, value: LocalDate | null): void {
this.writeNullable(fieldName, FieldType.DATE, value, PortableUtil.writeLocalDate);
}
writeTimestamp(fieldName: string, value: LocalDateTime | null): void {
this.writeNullable(fieldName, FieldType.TIMESTAMP, value, PortableUtil.writeLocalDateTime);
}
writeTimestampWithTimezone(fieldName: string, value: OffsetDateTime | null): void {
this.writeNullable(fieldName, FieldType.TIMESTAMP_WITH_TIMEZONE, value, PortableUtil.writeOffsetDateTime);
}
writeNullable<T>(fieldName: string, fieldType: FieldType, value: T | null, writeFn: (out: DataOutput, value: T) => void) {
this.setPosition(fieldName, fieldType);
const isNull = value === null;
this.output.writeBoolean(isNull);
if (!isNull) {
writeFn(this.output, value);
}
}
writeByteArray(fieldName: string, bytes: Buffer | null): void {
this.setPosition(fieldName, FieldType.BYTE_ARRAY);
this.output.writeByteArray(bytes);
}
writeBooleanArray(fieldName: string, booleans: boolean[] | null): void {
this.setPosition(fieldName, FieldType.BOOLEAN_ARRAY);
this.output.writeBooleanArray(booleans);
}
writeCharArray(fieldName: string, chars: string[] | null): void {
this.setPosition(fieldName, FieldType.CHAR_ARRAY);
this.output.writeCharArray(chars);
}
writeIntArray(fieldName: string, ints: number[] | null): void {
this.setPosition(fieldName, FieldType.INT_ARRAY);
this.output.writeIntArray(ints);
}
writeLongArray(fieldName: string, longs: Long[] | null): void {
this.setPosition(fieldName, FieldType.LONG_ARRAY);
this.output.writeLongArray(longs);
}
writeDoubleArray(fieldName: string, doubles: number[] | null): void {
this.setPosition(fieldName, FieldType.DOUBLE_ARRAY);
this.output.writeDoubleArray(doubles);
}
writeFloatArray(fieldName: string, floats: number[] | null): void {
this.setPosition(fieldName, FieldType.FLOAT_ARRAY);
this.output.writeFloatArray(floats);
}
writeShortArray(fieldName: string, shorts: number[] | null): void {
this.setPosition(fieldName, FieldType.SHORT_ARRAY);
this.output.writeShortArray(shorts);
}
writeUTFArray(fieldName: string, val: string[] | null): void {
this.writeStringArray(fieldName, val);
}
writeStringArray(fieldName: string, val: string[] | null): void {
this.setPosition(fieldName, FieldType.STRING_ARRAY);
this.output.writeStringArray(val);
}
writePortableArray(fieldName: string, portables: Portable[] | null): void {
let innerOffset: number;
let sample: Portable;
let i: number;
const fieldDefinition = this.setPosition(fieldName, FieldType.PORTABLE_ARRAY);
const len = (portables == null) ? BitsUtil.NULL_ARRAY_LENGTH : portables.length;
this.output.writeInt(len);
this.output.writeInt(fieldDefinition.getFactoryId());
this.output.writeInt(fieldDefinition.getClassId());
if (len > 0) {
innerOffset = this.output.position();
this.output.writeZeroBytes(len * 4);
for (i = 0; i < len; i++) {
sample = portables[i];
const posVal = this.output.position();
this.output.pwriteInt(innerOffset + i * BitsUtil.INT_SIZE_IN_BYTES, posVal);
this.serializer.writeObject(this.output, sample);
}
}
}
writeDecimalArray(fieldName: string, values: BigDecimal[] | null): void {
this.writeObjectArrayField(fieldName, FieldType.DECIMAL_ARRAY, values, IOUtil.writeDecimal)
}
writeTimeArray(fieldName: string, values: LocalTime[] | null): void {
this.writeObjectArrayField(fieldName, FieldType.TIME_ARRAY, values, IOUtil.writeLocalTime)
}
writeDateArray(fieldName: string, values: LocalDate[] | null): void {
this.writeObjectArrayField(fieldName, FieldType.DATE_ARRAY, values, PortableUtil.writeLocalDate)
}
writeTimestampArray(fieldName: string, values: LocalDateTime[] | null): void {
this.writeObjectArrayField(fieldName, FieldType.TIMESTAMP_ARRAY, values, PortableUtil.writeLocalDateTime)
}
writeTimestampWithTimezoneArray(fieldName: string, values: OffsetDateTime[] | null): void {
this.writeObjectArrayField(
fieldName, FieldType.TIMESTAMP_WITH_TIMEZONE_ARRAY, values, PortableUtil.writeOffsetDateTime
);
}
writeObjectArrayField<T>(
fieldName: string, fieldType: FieldType, values: T[] | null, writeFn: (out: DataOutput, value: T) => void
) {
this.setPosition(fieldName, fieldType);
const len = values === null ? BitsUtil.NULL_ARRAY_LENGTH : values.length;
this.output.writeInt(len);
if (len > 0) {
const offset = this.output.position();
this.output.writeZeroBytes(len * BitsUtil.INT_SIZE_IN_BYTES);
for (let i = 0; i < len; i++) {
const position = this.output.position();
if (values[i] === null) {
throw new HazelcastSerializationError('Array items cannot be null');
}
this.output.pwriteInt(offset + i * BitsUtil.INT_SIZE_IN_BYTES, position);
writeFn(this.output, values[i]);
}
}
}
end(): void {
const position = this.output.position();
this.output.pwriteInt(this.begin, position);
}
private setPosition(fieldName: string, fieldType: FieldType): FieldDefinition {
const field: FieldDefinition = this.classDefinition.getField(fieldName);
if (field === null) {
throw new HazelcastSerializationError(`Invalid field name: '${fieldName}' for ClassDefinition`
+ `{id: ${this.classDefinition.getClassId()}, version: ${this.classDefinition.getVersion()}}`);
}
if (this.writtenFields.has(fieldName)) {
throw new HazelcastSerializationError(`Field ${fieldName} has already been written!`);
}
this.writtenFields.add(fieldName);
const pos: number = this.output.position();
const index: number = field.getIndex();
this.output.pwriteInt(this.offset + index * BitsUtil.INT_SIZE_IN_BYTES, pos);
this.output.writeShort(fieldName.length);
this.output.write(Buffer.from(fieldName));
this.output.writeByte(fieldType);
return field;
}
} | the_stack |
import { ChangeDetectorRef, Component, ElementRef, OnDestroy, Renderer2, ViewChild } from '@angular/core';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { BasePickerResults } from '../base-picker-results/BasePickerResults';
import { Helpers } from '../../../../utils/Helpers';
import { NovoLabelService } from '../../../../services/novo-label-service';
import { NovoListElement } from '../../../list/List';
import { Subject, fromEvent, Subscription } from 'rxjs';
export interface IMixedMultiPickerOption {
value: string;
label: string;
secondaryOptions?: {
value: string,
label: string,
filterValue?: any,
}[];
getSecondaryOptionsAsync?(): Promise<{value: string, label: string}[]>;
// TODO: Refactor to prevent the need for a behaviorSubject to allow primaryOption's secondaryOptions to be cleared
// Currently secondaryOptions cannot be cleared via FieldInteraction API and must use a behavior subject - this includes modifyPickerConfig
clearSecondaryOptions?: Subject<any>;
showSearchOnSecondaryOptions?: boolean;
}
@Component({
selector: 'mixed-multi-picker-results',
template: `
<div class="mixed-multi-picker-groups">
<novo-list direction="vertical">
<novo-list-item
*ngFor="let option of options"
(click)="selectPrimaryOption(option, $event)"
[class.active]="selectedPrimaryOption?.value === option.value"
[attr.data-automation-id]="option.label"
[class.disabled]="isLoading">
<item-content>
<i *ngIf="option.iconClass" [class]="option.iconClass"></i>
<span data-automation-id="label">{{ option.label }}</span>
</item-content>
<item-end *ngIf="optionHasSecondaryOptions(option)">
<i class="bhi-next"></i>
</item-end>
</novo-list-item>
</novo-list>
</div>
<div class="mixed-multi-picker-matches" [hidden]="!optionHasSecondaryOptions(selectedPrimaryOption)">
<div class="mixed-multi-picker-input-container" [hidden]="!shouldShowSearchBox(selectedPrimaryOption)" data-automation-id="input-container">
<input autofocus #input [(ngModel)]="searchTerm" [disabled]="isLoading" data-automation-id="input" [placeholder]="placeholder"/>
<i class="bhi-search" *ngIf="!searchTerm" [class.disabled]="isLoading" data-automation-id="seach-icon"></i>
<i class="bhi-times" *ngIf="searchTerm" (click)="clearSearchTerm($event)" [class.disabled]="isLoading" data-automation-id="remove-icon"></i>
</div>
<div class="mixed-multi-picker-list-container">
<novo-list direction="vertical" #list>
<novo-list-item
*ngFor="let match of matches"
(click)="selectMatch($event)"
[class.active]="match === activeMatch"
(mouseenter)="selectActive(match)"
[class.disabled]="preselected(match) || isLoading"
[attr.data-automation-id]="match.label">
<item-content>
<span>{{ match.label }}</span>
</item-content>
</novo-list-item>
</novo-list>
<div class="mixed-multi-picker-no-results" *ngIf="matches.length === 0 && !isLoading && selectedPrimaryOption" data-automation-id="empty-message">
{{ config.emptyOptionsLabel ? config.emptyOptionsLabel : labels.groupedMultiPickerEmpty }}
</div>
<div class="mixed-multi-picker-loading" *ngIf="isLoading" data-automation-id="loading-message">
<novo-loading theme="line"></novo-loading>
</div>
</div>
</div>`,
})
export class MixedMultiPickerResults extends BasePickerResults implements OnDestroy {
@ViewChild('input', { static: true })
private inputElement: ElementRef;
@ViewChild('list')
private listElement: NovoListElement;
public selectedPrimaryOption: IMixedMultiPickerOption;
public searchTerm: string;
public placeholder: string = '';
public emptyOptionsLabel: string = '';
private keyboardSubscription: Subscription;
private internalMap: Map<string, { value: string; label: string; items: { value: string; label: string }[] }> = new Map<
string,
{ value: string; label: string; items: { value: string; label: string }[] }
>();
set term(value) {
if (this.config.placeholder) {
this.placeholder = this.config.placeholder;
}
// Focus
setTimeout(() => {
this.inputElement.nativeElement.focus();
});
}
get options() {
return this.config.options || [];
}
constructor(element: ElementRef, private renderer: Renderer2, public labels: NovoLabelService, ref: ChangeDetectorRef) {
super(element, ref);
}
public ngOnDestroy() {
// Cleanup
if (this.keyboardSubscription) {
this.keyboardSubscription.unsubscribe();
}
if (this.config.options) {
this.config.options.forEach(option => {
if (option.clearSecondaryOptions) {
option.clearSecondaryOptions.unsubscribe();
}
});
}
}
public selectPrimaryOption(primaryOption: IMixedMultiPickerOption, event?: MouseEvent): void {
if (this.keyboardSubscription) {
this.keyboardSubscription.unsubscribe();
}
// Scroll to top
this.renderer.setProperty(this.listElement.element.nativeElement, 'scrollTop', 0);
// Set focus
this.inputElement.nativeElement.focus();
// Find new items
const key: string = primaryOption.value;
this.selectedPrimaryOption = primaryOption;
// Clear
this.matches = [];
this.ref.markForCheck();
// New matches
if (this.optionHasSecondaryOptions(primaryOption)) {
// Subscribe to keyboard events and debounce
this.keyboardSubscription = fromEvent(this.inputElement.nativeElement, 'keyup')
.pipe(
debounceTime(350),
distinctUntilChanged(),
).subscribe((keyEvent: KeyboardEvent) => {
this.searchTerm = keyEvent.target['value'];
this.matches = this.filterData();
this.ref.markForCheck();
});
this.getNewMatches(primaryOption);
} else {
this.selectActive(primaryOption);
this.selectMatch(event);
}
}
public selectMatch(event?: MouseEvent): boolean {
// Set focus
this.inputElement.nativeElement.focus();
return super.selectMatch(event);
}
public clearSearchTerm(event: MouseEvent) {
Helpers.swallowEvent(event);
this.searchTerm = '';
this.selectPrimaryOption({ value: this.selectedPrimaryOption.value, label: this.selectedPrimaryOption.label });
this.ref.markForCheck();
}
public optionHasSecondaryOptions(primaryOption: IMixedMultiPickerOption) {
return !!(primaryOption && (primaryOption.secondaryOptions || primaryOption.getSecondaryOptionsAsync));
}
public shouldShowSearchBox(primaryOption: IMixedMultiPickerOption) {
return !!(primaryOption && primaryOption.showSearchOnSecondaryOptions);
}
public clearPrimaryOption(primaryOption: IMixedMultiPickerOption) {
if (this.internalMap.get(primaryOption.value)) {
if (primaryOption.value === this.selectedPrimaryOption?.value) {
this.activeMatch = null;
this.matches = [];
this.selectedPrimaryOption = null;
}
this.internalMap.delete(primaryOption.value);
this.ref.markForCheck();
}
}
filterData(): { value: string; label: string }[] {
if (this.selectedPrimaryOption) {
if (this.selectedPrimaryOption.secondaryOptions) {
return this.filter(this.selectedPrimaryOption.secondaryOptions);
} else {
return this.filter(this.internalMap.get(this.selectedPrimaryOption.value).items);
}
}
return [];
}
private filter(
array: { value: string; label: string; filterValue?: any }[]
): { value: string; label: string }[] {
let matches: { value: string; label: string; filterValue?: any }[] = array;
if (this.searchTerm && this.searchTerm.length !== 0 && this.selectedPrimaryOption) {
matches = matches.filter((match) => {
const searchTerm = this.searchTerm.toLowerCase();
return match.label.toLowerCase().indexOf(searchTerm) > -1 || match.value.toLowerCase().indexOf(searchTerm) > -1;
});
}
return matches;
}
private getNewMatches(primaryOption: IMixedMultiPickerOption): void {
// Get new matches
if (primaryOption.secondaryOptions) {
this.matches = this.filter(primaryOption.secondaryOptions);
this.ref.markForCheck();
} else {
if (!primaryOption.getSecondaryOptionsAsync) {
throw new Error(
'An option needs to have either an array of secondaryOptions or a function getSecondaryOptionsAsync',
);
}
if (!this.internalMap.get(primaryOption.value)) {
this.isLoading = true;
primaryOption.getSecondaryOptionsAsync().then((items: { value: string; label: string }[]) => {
this.internalMap.set(primaryOption.value, { value: primaryOption.value, label: primaryOption.label, items });
this.matches = this.filter(items);
this.isLoading = false;
this.ref.markForCheck();
setTimeout(() => {
this.inputElement.nativeElement.focus();
});
});
if (primaryOption.clearSecondaryOptions) {
primaryOption.clearSecondaryOptions.subscribe(() => {
this.clearPrimaryOption(primaryOption);
});
}
} else {
this.matches = this.filter(this.internalMap.get(primaryOption.value).items);
this.ref.markForCheck();
}
}
}
} | the_stack |
import { pipe, SK } from '../src/function'
import * as O from '../src/Option'
import * as RA from '../src/ReadonlyArray'
import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray'
import * as T from '../src/Task'
import * as TE from '../src/TaskEither'
import * as _ from '../src/TaskOption'
import * as U from './util'
describe('TaskOption', () => {
// -------------------------------------------------------------------------------------
// type class members
// -------------------------------------------------------------------------------------
it('map', async () => {
U.deepStrictEqual(await pipe(_.some(1), _.map(U.double))(), O.some(2))
})
it('ap', async () => {
U.deepStrictEqual(await pipe(_.some(U.double), _.ap(_.some(2)))(), O.some(4))
U.deepStrictEqual(await pipe(_.some(U.double), _.ap(_.none))(), O.none)
U.deepStrictEqual(await pipe(_.none, _.ap(_.some(2)))(), O.none)
U.deepStrictEqual(await pipe(_.none, _.ap(_.none))(), O.none)
})
it('chain', async () => {
const f = (n: number) => _.some(n * 2)
const g = () => _.none
U.deepStrictEqual(await pipe(_.some(1), _.chain(f))(), O.some(2))
U.deepStrictEqual(await pipe(_.none, _.chain(f))(), O.none)
U.deepStrictEqual(await pipe(_.some(1), _.chain(g))(), O.none)
U.deepStrictEqual(await pipe(_.none, _.chain(g))(), O.none)
})
it('alt', async () => {
U.deepStrictEqual(
await pipe(
_.some(1),
_.alt(() => _.some(2))
)(),
O.some(1)
)
U.deepStrictEqual(
await pipe(
_.some(2),
_.alt(() => _.none as _.TaskOption<number>)
)(),
O.some(2)
)
U.deepStrictEqual(
await pipe(
_.none,
_.alt(() => _.some(1))
)(),
O.some(1)
)
U.deepStrictEqual(
await pipe(
_.none,
_.alt(() => _.none)
)(),
O.none
)
})
it('zero', async () => {
U.deepStrictEqual(await _.zero()(), O.none)
})
it('fromIO', async () => {
U.deepStrictEqual(await _.fromIO(() => 1)(), O.some(1))
})
// -------------------------------------------------------------------------------------
// instances
// -------------------------------------------------------------------------------------
it('ApplicativeSeq', async () => {
await U.assertSeq(_.ApplySeq, _.FromTask, (fa) => fa())
await U.assertSeq(_.ApplicativeSeq, _.FromTask, (fa) => fa())
})
it('ApplicativePar', async () => {
await U.assertPar(_.ApplyPar, _.FromTask, (fa) => fa())
await U.assertPar(_.ApplicativePar, _.FromTask, (fa) => fa())
})
// -------------------------------------------------------------------------------------
// constructors
// -------------------------------------------------------------------------------------
it('tryCatch', async () => {
U.deepStrictEqual(await _.tryCatch(() => Promise.resolve(1))(), O.some(1))
U.deepStrictEqual(await _.tryCatch(() => Promise.reject())(), O.none)
})
it('fromNullable', async () => {
U.deepStrictEqual(await _.fromNullable(1)(), O.some(1))
U.deepStrictEqual(await _.fromNullable(null)(), O.none)
U.deepStrictEqual(await _.fromNullable(undefined)(), O.none)
})
it('fromNullableK', async () => {
const f = _.fromNullableK((n: number) => (n > 0 ? n : n === 0 ? null : undefined))
U.deepStrictEqual(await f(1)(), O.some(1))
U.deepStrictEqual(await f(0)(), O.none)
U.deepStrictEqual(await f(-1)(), O.none)
})
it('chainNullableK', async () => {
const f = _.chainNullableK((n: number) => (n > 0 ? n : n === 0 ? null : undefined))
U.deepStrictEqual(await f(_.of(1))(), O.some(1))
U.deepStrictEqual(await f(_.of(0))(), O.none)
U.deepStrictEqual(await f(_.of(-1))(), O.none)
})
it('fromPredicate', async () => {
const p = (n: number): boolean => n > 2
const f = _.fromPredicate(p)
U.deepStrictEqual(await f(1)(), O.none)
U.deepStrictEqual(await f(3)(), O.some(3))
})
it('fromTaskEither', async () => {
const pl = TE.left('a')
const pr = TE.right('a')
const fl = _.fromTaskEither(pl)
const fr = _.fromTaskEither(pr)
U.deepStrictEqual(await fl(), O.none)
U.deepStrictEqual(await fr(), O.some('a'))
})
// -------------------------------------------------------------------------------------
// destructors
// -------------------------------------------------------------------------------------
it('fold', async () => {
const f = _.fold(
() => T.of('none'),
(a) => T.of(`some(${a})`)
)
U.deepStrictEqual(await pipe(_.some(1), f)(), 'some(1)')
U.deepStrictEqual(await pipe(_.none, f)(), 'none')
})
it('getOrElse', async () => {
U.deepStrictEqual(
await pipe(
_.some(1),
_.getOrElse(() => T.of(2))
)(),
1
)
U.deepStrictEqual(
await pipe(
_.none,
_.getOrElse(() => T.of(2))
)(),
2
)
})
// -------------------------------------------------------------------------------------
// combinators
// -------------------------------------------------------------------------------------
it('fromOptionK', async () => {
const f = _.fromOptionK((n: number) => (n > 0 ? O.some(n) : O.none))
U.deepStrictEqual(await f(1)(), O.some(1))
U.deepStrictEqual(await f(-1)(), O.none)
})
it('chainOptionK', async () => {
const f = _.chainOptionK((n: number) => (n > 0 ? O.some(n) : O.none))
U.deepStrictEqual(await f(_.some(1))(), O.some(1))
U.deepStrictEqual(await f(_.some(-1))(), O.none)
U.deepStrictEqual(await f(_.none)(), O.none)
})
describe('array utils', () => {
const input: ReadonlyNonEmptyArray<string> = ['a', 'b']
it('traverseReadonlyArrayWithIndex', async () => {
const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.some(a + i) : _.none))
U.deepStrictEqual(await pipe(RA.empty, f)(), O.some(RA.empty))
U.deepStrictEqual(await pipe(input, f)(), O.some(['a0', 'b1']))
U.deepStrictEqual(await pipe(['a', ''], f)(), O.none)
})
it('traverseReadonlyArrayWithIndexSeq', async () => {
const f = _.traverseReadonlyArrayWithIndexSeq((i, a: string) => (a.length > 0 ? _.some(a + i) : _.none))
U.deepStrictEqual(await pipe(RA.empty, f)(), O.some(RA.empty))
U.deepStrictEqual(await pipe(input, f)(), O.some(['a0', 'b1']))
U.deepStrictEqual(await pipe(['a', ''], f)(), O.none)
})
it('sequenceReadonlyArray', async () => {
const log: Array<number | string> = []
const some = (n: number): _.TaskOption<number> =>
_.fromIO(() => {
log.push(n)
return n
})
const none = (s: string): _.TaskOption<number> =>
pipe(
T.fromIO(() => {
log.push(s)
return s
}),
T.map(() => O.none)
)
U.deepStrictEqual(await pipe([some(1), some(2)], _.traverseReadonlyArrayWithIndex(SK))(), O.some([1, 2]))
U.deepStrictEqual(await pipe([some(3), none('a')], _.traverseReadonlyArrayWithIndex(SK))(), O.none)
U.deepStrictEqual(await pipe([none('b'), some(4)], _.traverseReadonlyArrayWithIndex(SK))(), O.none)
U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4])
})
it('sequenceReadonlyArraySeq', async () => {
const log: Array<number | string> = []
const some = (n: number): _.TaskOption<number> =>
_.fromIO(() => {
log.push(n)
return n
})
const none = (s: string): _.TaskOption<number> =>
pipe(
T.fromIO(() => {
log.push(s)
return s
}),
T.map(() => O.none)
)
U.deepStrictEqual(await pipe([some(1), some(2)], _.traverseReadonlyArrayWithIndexSeq(SK))(), O.some([1, 2]))
U.deepStrictEqual(await pipe([some(3), none('a')], _.traverseReadonlyArrayWithIndexSeq(SK))(), O.none)
U.deepStrictEqual(await pipe([none('b'), some(4)], _.traverseReadonlyArrayWithIndexSeq(SK))(), O.none)
U.deepStrictEqual(log, [1, 2, 3, 'a', 'b'])
})
// old
it('sequenceArray', async () => {
// tslint:disable-next-line: readonly-array
const log: Array<number | string> = []
const some = (n: number): _.TaskOption<number> =>
_.fromIO(() => {
log.push(n)
return n
})
const none = (s: string): _.TaskOption<number> =>
pipe(
T.fromIO(() => {
log.push(s)
return s
}),
T.map(() => O.none)
)
// tslint:disable-next-line: deprecation
U.deepStrictEqual(await pipe([some(1), some(2)], _.sequenceArray)(), O.some([1, 2]))
// tslint:disable-next-line: deprecation
U.deepStrictEqual(await pipe([some(3), none('a')], _.sequenceArray)(), O.none)
// tslint:disable-next-line: deprecation
U.deepStrictEqual(await pipe([none('b'), some(4)], _.sequenceArray)(), O.none)
U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4])
})
it('sequenceSeqArray', async () => {
// tslint:disable-next-line: readonly-array
const log: Array<number | string> = []
const some = (n: number): _.TaskOption<number> =>
_.fromIO(() => {
log.push(n)
return n
})
const none = (s: string): _.TaskOption<number> =>
pipe(
T.fromIO(() => {
log.push(s)
return s
}),
T.map(() => O.none)
)
// tslint:disable-next-line: deprecation
U.deepStrictEqual(await pipe([some(1), some(2)], _.sequenceSeqArray)(), O.some([1, 2]))
// tslint:disable-next-line: deprecation
U.deepStrictEqual(await pipe([some(3), none('a')], _.sequenceSeqArray)(), O.none)
// tslint:disable-next-line: deprecation
U.deepStrictEqual(await pipe([none('b'), some(4)], _.sequenceSeqArray)(), O.none)
U.deepStrictEqual(log, [1, 2, 3, 'a', 'b'])
})
})
it('tryCatchK', async () => {
const f = (n: number) => (n > 0 ? Promise.resolve(n) : Promise.reject(n))
const g = _.tryCatchK(f)
U.deepStrictEqual(await g(1)(), O.some(1))
U.deepStrictEqual(await g(-1)(), O.none)
})
it('match', async () => {
const f = _.match(
() => 'none',
(a) => `some(${a})`
)
U.deepStrictEqual(await pipe(_.some(1), f)(), 'some(1)')
U.deepStrictEqual(await pipe(_.none, f)(), 'none')
})
it('matchE', async () => {
const f = _.matchE(
() => T.of('none'),
(a) => T.of(`some(${a})`)
)
U.deepStrictEqual(await pipe(_.some(1), f)(), 'some(1)')
U.deepStrictEqual(await pipe(_.none, f)(), 'none')
})
}) | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
IntegrationRuntimeResource,
IntegrationRuntimesListByFactoryOptionalParams,
IntegrationRuntimesCreateOrUpdateOptionalParams,
IntegrationRuntimesCreateOrUpdateResponse,
IntegrationRuntimesGetOptionalParams,
IntegrationRuntimesGetResponse,
UpdateIntegrationRuntimeRequest,
IntegrationRuntimesUpdateOptionalParams,
IntegrationRuntimesUpdateResponse,
IntegrationRuntimesDeleteOptionalParams,
IntegrationRuntimesGetStatusOptionalParams,
IntegrationRuntimesGetStatusResponse,
IntegrationRuntimesListOutboundNetworkDependenciesEndpointsOptionalParams,
IntegrationRuntimesListOutboundNetworkDependenciesEndpointsResponse,
IntegrationRuntimesGetConnectionInfoOptionalParams,
IntegrationRuntimesGetConnectionInfoResponse,
IntegrationRuntimeRegenerateKeyParameters,
IntegrationRuntimesRegenerateAuthKeyOptionalParams,
IntegrationRuntimesRegenerateAuthKeyResponse,
IntegrationRuntimesListAuthKeysOptionalParams,
IntegrationRuntimesListAuthKeysResponse,
IntegrationRuntimesStartOptionalParams,
IntegrationRuntimesStartResponse,
IntegrationRuntimesStopOptionalParams,
IntegrationRuntimesSyncCredentialsOptionalParams,
IntegrationRuntimesGetMonitoringDataOptionalParams,
IntegrationRuntimesGetMonitoringDataResponse,
IntegrationRuntimesUpgradeOptionalParams,
LinkedIntegrationRuntimeRequest,
IntegrationRuntimesRemoveLinksOptionalParams,
CreateLinkedIntegrationRuntimeRequest,
IntegrationRuntimesCreateLinkedIntegrationRuntimeOptionalParams,
IntegrationRuntimesCreateLinkedIntegrationRuntimeResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a IntegrationRuntimes. */
export interface IntegrationRuntimes {
/**
* Lists integration runtimes.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param options The options parameters.
*/
listByFactory(
resourceGroupName: string,
factoryName: string,
options?: IntegrationRuntimesListByFactoryOptionalParams
): PagedAsyncIterableIterator<IntegrationRuntimeResource>;
/**
* Creates or updates an integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param integrationRuntime Integration runtime resource definition.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
integrationRuntime: IntegrationRuntimeResource,
options?: IntegrationRuntimesCreateOrUpdateOptionalParams
): Promise<IntegrationRuntimesCreateOrUpdateResponse>;
/**
* Gets an integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesGetOptionalParams
): Promise<IntegrationRuntimesGetResponse>;
/**
* Updates an integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param updateIntegrationRuntimeRequest The parameters for updating an integration runtime.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
updateIntegrationRuntimeRequest: UpdateIntegrationRuntimeRequest,
options?: IntegrationRuntimesUpdateOptionalParams
): Promise<IntegrationRuntimesUpdateResponse>;
/**
* Deletes an integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesDeleteOptionalParams
): Promise<void>;
/**
* Gets detailed status information for an integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
getStatus(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesGetStatusOptionalParams
): Promise<IntegrationRuntimesGetStatusResponse>;
/**
* Gets the list of outbound network dependencies for a given Azure-SSIS integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
listOutboundNetworkDependenciesEndpoints(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesListOutboundNetworkDependenciesEndpointsOptionalParams
): Promise<
IntegrationRuntimesListOutboundNetworkDependenciesEndpointsResponse
>;
/**
* Gets the on-premises integration runtime connection information for encrypting the on-premises data
* source credentials.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
getConnectionInfo(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesGetConnectionInfoOptionalParams
): Promise<IntegrationRuntimesGetConnectionInfoResponse>;
/**
* Regenerates the authentication key for an integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param regenerateKeyParameters The parameters for regenerating integration runtime authentication
* key.
* @param options The options parameters.
*/
regenerateAuthKey(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
regenerateKeyParameters: IntegrationRuntimeRegenerateKeyParameters,
options?: IntegrationRuntimesRegenerateAuthKeyOptionalParams
): Promise<IntegrationRuntimesRegenerateAuthKeyResponse>;
/**
* Retrieves the authentication keys for an integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
listAuthKeys(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesListAuthKeysOptionalParams
): Promise<IntegrationRuntimesListAuthKeysResponse>;
/**
* Starts a ManagedReserved type integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
beginStart(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesStartOptionalParams
): Promise<
PollerLike<
PollOperationState<IntegrationRuntimesStartResponse>,
IntegrationRuntimesStartResponse
>
>;
/**
* Starts a ManagedReserved type integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
beginStartAndWait(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesStartOptionalParams
): Promise<IntegrationRuntimesStartResponse>;
/**
* Stops a ManagedReserved type integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
beginStop(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesStopOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Stops a ManagedReserved type integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
beginStopAndWait(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesStopOptionalParams
): Promise<void>;
/**
* Force the integration runtime to synchronize credentials across integration runtime nodes, and this
* will override the credentials across all worker nodes with those available on the dispatcher node.
* If you already have the latest credential backup file, you should manually import it (preferred) on
* any self-hosted integration runtime node than using this API directly.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
syncCredentials(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesSyncCredentialsOptionalParams
): Promise<void>;
/**
* Get the integration runtime monitoring data, which includes the monitor data for all the nodes under
* this integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
getMonitoringData(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesGetMonitoringDataOptionalParams
): Promise<IntegrationRuntimesGetMonitoringDataResponse>;
/**
* Upgrade self-hosted integration runtime to latest version if availability.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param options The options parameters.
*/
upgrade(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
options?: IntegrationRuntimesUpgradeOptionalParams
): Promise<void>;
/**
* Remove all linked integration runtimes under specific data factory in a self-hosted integration
* runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param linkedIntegrationRuntimeRequest The data factory name for the linked integration runtime.
* @param options The options parameters.
*/
removeLinks(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
linkedIntegrationRuntimeRequest: LinkedIntegrationRuntimeRequest,
options?: IntegrationRuntimesRemoveLinksOptionalParams
): Promise<void>;
/**
* Create a linked integration runtime entry in a shared integration runtime.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param integrationRuntimeName The integration runtime name.
* @param createLinkedIntegrationRuntimeRequest The linked integration runtime properties.
* @param options The options parameters.
*/
createLinkedIntegrationRuntime(
resourceGroupName: string,
factoryName: string,
integrationRuntimeName: string,
createLinkedIntegrationRuntimeRequest: CreateLinkedIntegrationRuntimeRequest,
options?: IntegrationRuntimesCreateLinkedIntegrationRuntimeOptionalParams
): Promise<IntegrationRuntimesCreateLinkedIntegrationRuntimeResponse>;
} | the_stack |
import connect = require('connect');
import { createServer } from 'http';
import * as swaggerTools from 'swagger-tools';
const app = connect();
const serverPort = 3000;
// swaggerRouter configuration
const options = {
controllers: './controllers',
useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode)
};
const swaggerUiOptions = {
apiDocs: 'apiDocs',
swaggerUi: 'swaggerUi',
};
// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
// tslint:disable-next-line no-var-requires
const swaggerDoc20 = require('./api/swagger.json');
// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc20, middleware => {
// Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
app.use(middleware.swaggerMetadata());
// Validate Swagger requests
app.use(middleware.swaggerValidator());
// Route validated requests to appropriate controller
app.use(middleware.swaggerRouter(options));
// Test passing in the handlers directly
app.use(middleware.swaggerRouter({
controllers: {
// These tests are based on tests here:
// https://github.com/apigee-127/swagger-tools/blob/0cea535b122265c6d01546e199e2e8fda4c0f5da/test/2.0/test-middleware-swagger-metadata.js#L102-L138
foo_bar: (req, res, next) => {
req.swagger.swaggerVersion = '2.0';
req.swagger.apiPath = '/pets/{id}';
req.swagger.operation = {
security: [
{
oauth2: ["read"]
}
],
tags: [ "Pet Operations" ],
operationId: "getPetById",
summary: "Finds the pet by id",
responses: {
200: {
description: "Pet response",
schema: {
$ref: "#/definitions/Pet"
}
},
default: {
description: "Unexpected error",
schema: {
$ref: "#/definitions/Error"
}
}
},
parameters: [
{
in: 'query',
name: 'mock',
description: 'Mock mode',
required: false,
type: 'boolean'
}
]
};
req.swagger.operationParameters = [
{
path: ['paths', '/pets/{id}', 'get', 'parameters', '0'],
schema: {
in: 'query',
name: 'mock',
description: 'Mock mode',
required: false,
type: 'boolean'
},
},
{
path: ['paths', '/pets/{id}', 'parameters', '0'],
schema: {
name: "id",
in: "path",
description: "ID of pet",
required: true,
type: "integer",
format: "int64"
}
}
];
req.swagger.operationPath = ['paths', '/pets/{id}', 'get'];
req.swagger.security = [
{
oauth2: [ 'read' ]
}
];
req.swagger.params = {
id: {
path: ['paths', '/pets/{id}', 'parameters', '0'],
schema: {
name: "id",
in: "path",
description: "ID of pet",
required: true,
type: "integer",
format: "int64"
},
originalValue: '1',
value: 1
},
mock: {
path: ['paths', '/pets/{id}', 'get', 'parameters', '0'],
schema: {
in: 'query',
name: 'mock',
description: 'Mock mode',
required: false,
type: 'boolean'
},
originalValue: 'false',
value: false
}
};
res.setHeader('Content-Type', 'application/json');
res.end([ 'foo', 0 ]);
},
}
}));
// Serve the Swagger documents and Swagger UI
app.use(middleware.swaggerUi(swaggerUiOptions));
app.use(middleware.swaggerUi());
// Start the server
createServer(app).listen(serverPort, () => {
console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
});
});
// 1.2 examples from https://github.com/apigee-127/swagger-tools/blob/master/examples/1.2/index.js
// The Swagger Resource Listing Document (require it, build it programmatically, fetch it from a URL, ...)
// tslint:disable-next-line no-var-requires
const apiDoc12 = require('./api/api-doc.json');
// The Swagger API Declaration Documents (require them, build them programmatically, fetch them from a URL, ...)
const apiDeclarations = [
// tslint:disable-next-line no-var-requires
require('./api/weather.json')
];
// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(apiDoc12, apiDeclarations, middleware => {
// Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
app.use(middleware.swaggerMetadata());
// Validate Swagger requests
app.use(middleware.swaggerValidator());
// Route validated requests to appropriate controller
app.use(middleware.swaggerRouter(options));
// Test passing in the handlers directly
app.use(middleware.swaggerRouter({
controllers: {
// These tests are based on tests here:
// https://github.com/apigee-127/swagger-tools/blob/0cea535b122265c6d01546e199e2e8fda4c0f5da/test/1.2/test-middleware-swagger-metadata.js#L72-L89
foo_bar: (req, res, next) => {
req.swagger.swaggerVersion = '1.2';
req.swagger.api = {
operations: [
{
authorizations: {},
method: "GET",
nickname: "getPetById",
notes: "Returns a pet based on ID",
parameters: [
{
allowMultiple: false,
description: "ID of pet that needs to be fetched",
format: "int64",
maximum: "100000.0",
minimum: "1.0",
name: "petId",
paramType: "path",
required: true,
type: "integer"
}
],
responseMessages: [
{
code: 400,
message: "Invalid ID supplied"
},
{
code: 404,
message: "Pet not found"
}
],
summary: "Find pet by ID",
type: "Pet"
},
{
authorizations: {
oauth2: [
{
description: "modify pets in your account",
scope: "write:pets"
}
]
},
method: "DELETE",
nickname: "deletePet",
notes: "",
parameters: [
{
allowMultiple: false,
description: "Pet id to delete",
name: "petId",
paramType: "path",
required: true,
type: "string"
}
],
responseMessages: [
{
code: 400,
message: "Invalid pet value"
}
],
summary: "Deletes a pet",
type: "void"
},
],
path: "/pet/{petId}"
};
req.swagger.apiDeclaration = {};
req.swagger.apiIndex = 0;
req.swagger.authorizations = {
oauth2: [
{
description: "modify pets in your account",
scope: "write:pets"
}
]
};
req.swagger.operation = {
authorizations: {},
method: "GET",
nickname: "getPetById",
notes: "Returns a pet based on ID",
parameters: [
{
allowMultiple: false,
description: "ID of pet that needs to be fetched",
format: "int64",
maximum: "100000.0",
minimum: "1.0",
name: "petId",
paramType: "path",
required: true,
type: "integer"
}
],
responseMessages: [
{
code: 400,
message: "Invalid ID supplied"
},
{
code: 404,
message: "Pet not found"
}
],
summary: "Find pet by ID",
type: "Pet"
};
req.swagger.operationPath = ['apis', '0', 'operations', '0'];
req.swagger.params = {
petId: {
path: ['apis', '0', 'operations', '0', 'parameters', '0'],
schema: {
allowMultiple: false,
description: "ID of pet that needs to be fetched",
format: "int64",
maximum: "100000.0",
minimum: "1.0",
name: "petId",
paramType: "path",
required: true,
type: "integer"
},
originalValue: '1',
value: 1
}
};
res.setHeader('Content-Type', 'application/json');
res.end([ 'foo', 0 ]);
},
}
}));
// Serve the Swagger documents and Swagger UI
app.use(middleware.swaggerUi({
'/weather': apiDeclarations[0]
}));
// Start the server
createServer(app).listen(serverPort, () => {
console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
});
});
// Testing that handler functions can type the incoming request
type TypedRequest = swaggerTools.Swagger20Request<{
foo: swaggerTools.SwaggerRequestParameter<number>;
bar?: swaggerTools.SwaggerRequestParameter<string> | undefined;
}>;
swaggerTools.initializeMiddleware(swaggerDoc20, middleware => {
app.use(middleware.swaggerRouter({
controllers: {
foo_bar: (req: TypedRequest, res, next) => {
req.swagger.params.foo.value + 2;
req.swagger.params.bar && req.swagger.params.bar.value.replace('a', 'b');
},
}
}));
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.