text stringlengths 2.5k 6.39M | kind stringclasses 3 values |
|---|---|
import React from 'react'
import { store } from '../../../store'
import { StoreContext } from 'storeon/react'
import { object, withKnobs, select, boolean, text } from '@storybook/addon-knobs'
import uiManagmentApi from '../../../api/uiManagment/uiManagmentApi'
import stylesApi from '../../../api/styles/stylesApi'
// import { darkTheme, lightTheme } from '../../../configs/styles'
// import { ru, en } from '../../../configs/languages'
import languagesApi from '../../../api/languages/languagesApi'
// import { settings } from '../../../configs/settings'
import settingsApi from '../../../api/settings/settingsApi'
import Rate from '../Rate'
import { withInfo } from '@storybook/addon-info'
import info from './RateInfo.md'
import '../../../styles/storyBookContainer.css'
import { iconsList } from '../../../configs/icons'
export default {
title: 'Rate',
decorators: [withKnobs, withInfo],
parameters: {
info: {
text: info,
source: false,
propTables: false,
},
},
}
const groupUIManagment = 'UIManagment'
const groupStyles = 'Styles'
const groupLanguages = 'Languages'
const groupSettings = 'Settings'
// const storyDarkStyles = {
// mainContainer: {
// display: 'flex',
// flexWrap: 'wrap',
// backgroundColor: '#373737',
// padding: '8px',
// borderRadius: '10px',
// },
// titleContainer: {
// width: '100%',
// textAlign: 'center',
// color: 'white',
// },
// negativeRateButton: {
// fontSize: '16px',
// width: '50%',
// marginTop: '10px',
// marginBottom: '10px',
// border: 'none',
// backgroundColor: 'transparent',
// outline: 'none',
// display: 'flex',
// flexDirection: 'column',
// alignItems: 'center',
// color: '#fa4caa',
// },
// positiveRateButton: {
// fontSize: '16px',
// width: '50%',
// marginTop: '10px',
// marginBottom: '10px',
// border: 'none',
// backgroundColor: 'transparent',
// outline: 'none',
// display: 'flex',
// flexDirection: 'column',
// alignItems: 'center',
// color: '#fa4caa',
// },
// ratingElement: {
// marginTop: '5px',
// width: '60%',
// color: '#5271fe',
// listStyleType: 'none',
// },
// ratingListContainer: {
// display: 'flex',
// marginTop: '20px',
// marginBottom: '20px',
// flexDirection: 'column',
// alignItems: 'center',
// width: '100%',
// },
// }
// const storyLightStyles = {
// mainContainer: {
// display: 'flex',
// flexWrap: 'wrap',
// backgroundColor: '#edf0f5',
// padding: '8px',
// borderRadius: '10px',
// },
// titleContainer: {
// width: '100%',
// textAlign: 'center',
// color: '#575757',
// },
// negativeRateButton: {
// fontSize: '16px',
// width: '50%',
// marginTop: '10px',
// marginBottom: '10px',
// border: 'none',
// backgroundColor: 'transparent',
// outline: 'none',
// display: 'flex',
// flexDirection: 'column',
// alignItems: 'center',
// color: '#fa4caa',
// },
// positiveRateButton: {
// fontSize: '16px',
// width: '50%',
// marginTop: '10px',
// marginBottom: '10px',
// border: 'none',
// backgroundColor: 'transparent',
// outline: 'none',
// display: 'flex',
// flexDirection: 'column',
// alignItems: 'center',
// color: '#fa4caa',
// },
// ratingElement: {
// marginTop: '5px',
// width: '60%',
// color: '#5271fe',
// listStyleType: 'none',
// },
// ratingListContainer: {
// display: 'flex',
// marginTop: '20px',
// marginBottom: '20px',
// flexDirection: 'column',
// alignItems: 'center',
// width: '100%',
// },
// }
// stylesApi.styles('changeRate', { themeName: 'darkTheme', data: storyDarkStyles })
// stylesApi.styles('changeRate', { themeName: 'lightTheme', data: storyLightStyles })
// export const RateComponent = () => {
// const negativeRateIcon = object('negativeRateIcon', settings.media.icons.negativeRateIcon, groupSettings)
// settingsApi.settings('changeIcon', { iconName: 'negativeRateIcon', iconData: negativeRateIcon })
// const positiveRateIcon = object('positiveRateIcon', settings.media.icons.positiveRateIcon, groupSettings)
// settingsApi.settings('changeIcon', { iconName: 'positiveRateIcon', iconData: positiveRateIcon })
// const negativeRateButton = object('negativeRateButton', uiManagmentRate.negativeRate, groupUIManagment)
// const positiveRateButton = object('settingsButton', uiManagmentRate.positiveRate, groupUIManagment)
// uiManagmentApi.uiManagment('setUpRate', { negativeRate: negativeRateButton, positiveRate: positiveRateButton })
// const activeLanguage = select('active', { en: 'en', ru: 'ru' }, 'en', groupLanguages)
// languagesApi.languages('changeLanguage', activeLanguage)
// const russian = object('Russian', ru.packet.Rate, groupLanguages)
// languagesApi.languages('changeRate', { language: 'ru', data: russian })
// const english = object('English', en.packet.Rate, groupLanguages)
// languagesApi.languages('changeRate', { language: 'en', data: english })
// const activeTheme = select('active', { darkTheme: 'darkTheme', lightTheme: 'lightTheme' }, 'darkTheme', groupStyles)
// stylesApi.styles('switchTheme', activeTheme)
// const stylesDarkTheme = object('darkTheme', darkTheme.data.Rate, groupStyles)
// stylesApi.styles('changeRate', { themeName: 'darkTheme', data: stylesDarkTheme })
// const stylesLightTheme = object('lightTheme', lightTheme.data.Rate, groupStyles)
// stylesApi.styles('changeRate', { themeName: 'lightTheme', data: stylesLightTheme })
// return (
// <StoreContext.Provider value={store}>
// <Rate />
// </StoreContext.Provider>
// )
// }
const languagePacket = {
title: (language: string, title: string) => text(`${language}/title`, title, groupLanguages),
positive: (language: string, title: string) => text(`${language}/positive`, title, groupLanguages),
negative: (language: string, title: string) => text(`${language}/negative`, title, groupLanguages),
raitingOne: (language: string, title: string) => text(`${language}/raiting 1`, title, groupLanguages),
raitingTwo: (language: string, title: string) => text(`${language}/raiting 2`, title, groupLanguages),
raitingThree: (language: string, title: string) => text(`${language}/raiting 3`, title, groupLanguages),
}
const stylesPacket = {
mainContainer: (themeName: string, data: any) => object(`${themeName}/mainContainer`, data, groupStyles),
titleContainer: (themeName: string, data: any) => object(`${themeName}/titleContainer`, data, groupStyles),
positiveRateButton: (themeName: string, data: any) => object(`${themeName}/positiveRateButton`, data, groupStyles),
negativeRateButton: (themeName: string, data: any) => object(`${themeName}/negativeRateButton`, data, groupStyles),
ratingListContainer: (themeName: string, data: any) => object(`${themeName}/ratingListContainer`, data, groupStyles),
ratingElement: (themeName: string, data: any) => object(`${themeName}/ratingElement`, data, groupStyles),
}
export const RateComponent = () => {
//settings start
const negativeRateIcon = select('negativeRateIcon', iconsList, 'far thumbs-down', groupSettings)
settingsApi.settings('changeIcon', { iconName: 'negativeRateIcon', iconData: { icon: negativeRateIcon.split(' ') } })
const positiveRateIcon = select('positiveRateIcon', iconsList, 'fas thumbs-up', groupSettings)
settingsApi.settings('changeIcon', { iconName: 'positiveRateIcon', iconData: { icon: positiveRateIcon.split(' ') } })
// settings end
//ui managment start
const uiManagmentRate = store.get().managment.getIn(['components', 'Rate'])
const negativeRateButton = boolean(
'negativeRateButton enabled',
uiManagmentRate.negativeRate.enabled,
groupUIManagment
)
const titleNegativeRate = boolean('show negativeRateTitle', uiManagmentRate.negativeRate.withTitle, groupUIManagment)
const iconNegativeRate = boolean('show negativeRateIcon', uiManagmentRate.negativeRate.withIcon, groupUIManagment)
const positiveRateButton = boolean(
'positiveRateButton enabled',
uiManagmentRate.positiveRate.enabled,
groupUIManagment
)
const titlePositiveRateButton = boolean(
'show positiveRateButtonTitle',
uiManagmentRate.positiveRate.withTitle,
groupUIManagment
)
const iconPositiveRateButton = boolean(
'show positiveRateButtonIcon',
uiManagmentRate.positiveRate.withIcon,
groupUIManagment
)
uiManagmentApi.uiManagment('setUpRate', {
positiveRate: { enabled: positiveRateButton, withTitle: titlePositiveRateButton, withIcon: iconPositiveRateButton },
negativeRate: { enabled: negativeRateButton, withTitle: titleNegativeRate, withIcon: iconNegativeRate },
})
// ui managment end
// languages start
const language = select('language', { en: 'en', ru: 'ru' }, 'en', groupLanguages)
languagesApi.languages('changeLanguage', language)
const activeLanguagePacket = store.get().languages.getIn(['stack', language, 'Rate'])
const title = languagePacket.title(language, activeLanguagePacket.title)
const negative = languagePacket.negative(language, activeLanguagePacket.negative)
const positive = languagePacket.positive(language, activeLanguagePacket.positive)
const raitingOne = languagePacket.raitingOne(language, activeLanguagePacket.ratingList[2])
const raitingTwo = languagePacket.raitingTwo(language, activeLanguagePacket.ratingList[1])
const raitingThree = languagePacket.raitingThree(language, activeLanguagePacket.ratingList[0])
languagesApi.languages('changeRate', {
language: language,
data: { title, negative, positive, ratingList: [raitingThree, raitingTwo, raitingOne] },
})
// languages end
//styles start
const themeName = select(
'theme',
{ sovaDark: 'sovaDark', sovaLight: 'sovaLight', sovaGray: 'sovaGray' },
'sovaLight',
groupStyles
)
stylesApi.styles('switchTheme', themeName)
const activeThemePacket = store.get().styles.getIn(['stack', themeName, 'Rate'])
const mainContainer = stylesPacket.mainContainer(themeName, activeThemePacket.mainContainer)
const titleContainer = stylesPacket.titleContainer(themeName, activeThemePacket.titleContainer)
const negativeRate = stylesPacket.negativeRateButton(themeName, activeThemePacket.negativeRateButton)
const positiveRate = stylesPacket.positiveRateButton(themeName, activeThemePacket.positiveRateButton)
const ratingElement = stylesPacket.ratingElement(themeName, activeThemePacket.ratingElement)
const ratingListContainer = stylesPacket.ratingListContainer(themeName, activeThemePacket.ratingListContainer)
stylesApi.styles('changeRate', {
themeName: themeName,
data: {
mainContainer,
ratingElement,
positiveRateButton: positiveRate,
negativeRateButton: negativeRate,
titleContainer,
ratingListContainer,
},
})
//styles end
return (
<StoreContext.Provider value={store}>
<div className="sova-ck-main">
<div className="sova-ck-chat">
<Rate />
</div>
</div>
</StoreContext.Provider>
)
} | the_stack |
import sinon from "sinon";
import Api from "../src";
import KintoClientBase, { KintoClientOptions } from "../src/base";
import { EventEmitter } from "events";
import KintoServer from "kinto-node-test-server";
import { delayedPromise, Stub, btoa, expectAsyncError } from "./test_utils";
import Bucket from "../src/bucket";
import Collection from "../src/collection";
import {
PermissionData,
OperationResponse,
KintoObject,
Attachment,
KintoResponse,
Group,
} from "../src/types";
import { AggregateResponse } from "../src/batch";
interface TitleRecord extends KintoObject {
title: string;
}
const { expect } = intern.getPlugin("chai");
intern.getPlugin("chai").should();
const { describe, it, before, after, beforeEach, afterEach } =
intern.getPlugin("interface.bdd");
const skipLocalServer = !!process.env.TEST_KINTO_SERVER;
const TEST_KINTO_SERVER =
process.env.TEST_KINTO_SERVER || "http://0.0.0.0:8888/v1";
const KINTO_PROXY_SERVER = process.env.KINTO_PROXY_SERVER || TEST_KINTO_SERVER;
async function startServer(
server: KintoServer,
options: { [key: string]: string } = {}
) {
if (!skipLocalServer) {
await server.start(options);
}
}
async function stopServer(server: KintoServer) {
if (!skipLocalServer) {
await server.stop();
}
}
describe("Integration tests", function (__test) {
let sandbox: sinon.SinonSandbox, server: KintoServer, api: Api;
// Disabling test timeouts until pserve gets decent startup time.
__test.timeout = 0;
before(async () => {
if (skipLocalServer) {
return;
}
let kintoConfigPath = __dirname + "/kinto.ini";
if (process.env.SERVER && process.env.SERVER !== "master") {
kintoConfigPath = `${__dirname}/kinto-${process.env.SERVER}.ini`;
}
server = new KintoServer(KINTO_PROXY_SERVER, {
maxAttempts: 200,
kintoConfigPath,
});
await server.loadConfig(kintoConfigPath);
});
after(() => {
if (skipLocalServer) {
return;
}
const logLines = server.logs.toString().split("\n");
const serverDidCrash = logLines.some((l) => l.startsWith("Traceback"));
if (serverDidCrash) {
// Server errors have been encountered, raise to break the build
const trace = logLines.join("\n");
throw new Error(
`Kinto server crashed while running the test suite.\n\n${trace}`
);
}
return server.killAll();
});
function createClient(options: Partial<KintoClientOptions> = {}) {
return new Api(TEST_KINTO_SERVER, options);
}
beforeEach((__test) => {
__test.timeout = 12500;
sandbox = sinon.createSandbox();
const events = new EventEmitter();
api = createClient({
events,
headers: { Authorization: "Basic " + btoa("user:pass") },
});
});
afterEach(() => sandbox.restore());
describe("Default server configuration", () => {
before(async () => {
await startServer(server);
});
after(async () => {
await stopServer(server);
});
beforeEach(async () => {
await server.flush();
});
// XXX move this to batch tests
describe("new batch", () => {
it("should support root batch", async function () {
await api.batch((batch: KintoClientBase) => {
const bucket = batch.bucket("default");
bucket.createCollection("posts");
const coll = bucket.collection("posts");
coll.createRecord({ a: 1 });
coll.createRecord({ a: 2 });
});
const res = await api
.bucket("default")
.collection("posts")
.listRecords();
res.data.should.have.lengthOf(2);
});
it("should support bucket batch", async function () {
await api.bucket("default").batch((batch) => {
batch.createCollection("posts");
const coll = batch.collection("posts");
coll.createRecord({ a: 1 });
coll.createRecord({ a: 2 });
});
const res = await api
.bucket("default")
.collection("posts")
.listRecords();
res.data.should.have.lengthOf(2);
});
});
describe("Server properties", () => {
it("should retrieve server settings", async () => {
(await api.fetchServerSettings()).should.have
.property("batch_max_requests")
.eql(25);
});
it("should retrieve server capabilities", async () => {
const capabilities = await api.fetchServerCapabilities();
expect(capabilities).to.be.an("object");
// Kinto protocol 1.4 exposes capability descriptions
Object.keys(capabilities).forEach((capability) => {
const capabilityObj = capabilities[capability];
expect(capabilityObj).to.include.keys("url", "description");
});
});
it("should retrieve user information", async () => {
const user = await api.fetchUser();
expect(user!.id).to.match(/^basicauth:/);
expect(user!.bucket).to.have.lengthOf(36);
});
it("should retrieve current API version", async () => {
(await api.fetchHTTPApiVersion()).should.match(/^\d\.\d+$/);
});
});
describe("#createBucket", () => {
let result: KintoResponse;
describe("Default options", () => {
describe("Autogenerated id", () => {
beforeEach(async () => {
const res = await api.createBucket(null);
return (result = res as KintoResponse);
});
it("should create a bucket", () => {
expect(result)
.to.have.property("data")
.to.have.property("id")
.to.be.a("string");
});
});
describe("Custom id", () => {
beforeEach(async () => {
const res = await api.createBucket("foo");
return (result = res as KintoResponse);
});
it("should create a bucket with the passed id", () => {
expect(result)
.to.have.property("data")
.to.have.property("id")
.eql("foo");
});
it("should create a bucket having a list of write permissions", () => {
expect(result)
.to.have.property("permissions")
.to.have.property("write")
.to.be.a("array");
});
describe("data option", () => {
it("should create bucket data", async () => {
(await api.createBucket("foo", { data: { a: 1 } })).should.have
.property("data")
.to.have.property("a")
.eql(1);
});
});
describe("Safe option", () => {
it("should not override existing bucket", async () => {
await expectAsyncError(
() => api.createBucket("foo", { safe: true }),
/412 Precondition Failed/
);
});
});
});
});
describe("permissions option", () => {
beforeEach(async () => {
const res = await api.createBucket("foo", {
permissions: { read: ["github:n1k0"] },
});
return (result = res as KintoResponse);
});
it("should create a bucket having a list of write permissions", () => {
expect(result)
.to.have.property("permissions")
.to.have.property("read")
.to.eql(["github:n1k0"]);
});
});
});
describe("#deleteBucket()", () => {
let last_modified: number;
beforeEach(async () => {
const res = await api.createBucket("foo");
return (last_modified = (res as KintoResponse).data.last_modified);
});
it("should delete a bucket", async () => {
await api.deleteBucket("foo");
const { data } = await api.listBuckets();
data.map((bucket) => bucket.id).should.not.include("foo");
});
describe("Safe option", () => {
it("should raise a conflict error when resource has changed", async () => {
await expectAsyncError(
() =>
api.deleteBucket("foo", {
last_modified: last_modified - 1000,
safe: true,
}),
/412 Precondition Failed/
);
});
});
});
describe("#deleteBuckets()", () => {
beforeEach(() => {
return api.batch((batch: KintoClientBase) => {
batch.createBucket("b1");
batch.createBucket("b2");
});
});
it("should delete all buckets", async () => {
await api.deleteBuckets();
await delayedPromise(50);
const { data } = await api.listBuckets();
data.should.deep.equal([]);
});
});
describe("#listPermissions", () => {
// FIXME: this feature was introduced between 8.2 and 8.3, and
// these tests run against master as well as an older Kinto
// version (see .travis.yml). If we ever bump the older version
// up to one where it also has bucket:create, we can clean this
// up.
const shouldHaveCreatePermission =
// People developing don't always set SERVER. Let's assume
// that means "master".
!process.env.SERVER ||
// "master" is greater than 8.3 but let's just be explicit here.
process.env.SERVER == "master" ||
process.env.SERVER > "8.3" ||
(process.env.SERVER > "8.2" && process.env.SERVER.includes("dev"));
describe("Single page of permissions", () => {
beforeEach(() => {
return api.batch((batch: KintoClientBase) => {
batch.createBucket("b1");
batch.bucket("b1").createCollection("c1");
});
});
it("should retrieve the list of permissions", async () => {
let { data } = await api.listPermissions();
if (shouldHaveCreatePermission) {
// One element is for the root element which has
// `bucket:create` as well as `account:create`. Remove
// it.
const isBucketCreate = (p_1: PermissionData) =>
p_1.permissions.includes("bucket:create");
const bucketCreate = data.filter(isBucketCreate);
expect(bucketCreate.length).eql(1);
data = data.filter((p_2) => !isBucketCreate(p_2));
}
expect(data).to.have.lengthOf(2);
expect(data.map((p_3) => p_3.id).sort()).eql(["b1", "c1"]);
});
});
describe("Paginated list of permissions", () => {
beforeEach(() => {
return api.batch((batch: KintoClientBase) => {
for (let i = 1; i <= 15; i++) {
batch.createBucket("b" + i);
}
});
});
it("should retrieve the list of permissions", async () => {
const results = await api.listPermissions({ pages: Infinity });
let expectedRecords = 15;
if (shouldHaveCreatePermission) {
expectedRecords++;
}
expect(results.data).to.have.lengthOf(expectedRecords);
});
});
});
describe("#listBuckets", () => {
beforeEach(() => {
return api.batch((batch: KintoClientBase) => {
batch.createBucket("b1", { data: { size: 24 } });
batch.createBucket("b2", { data: { size: 13 } });
batch.createBucket("b3", { data: { size: 38 } });
batch.createBucket("b4", { data: { size: -4 } });
});
});
it("should retrieve the list of buckets", async () => {
const { data } = await api.listBuckets();
data
.map((bucket) => bucket.id)
.sort()
.should.deep.equal(["b1", "b2", "b3", "b4"]);
});
it("should order buckets by field", async () => {
const { data } = await api.listBuckets({ sort: "-size" });
data
.map((bucket) => bucket.id)
.should.deep.equal(["b3", "b1", "b2", "b4"]);
});
describe("Filtering", () => {
it("should filter buckets", async () => {
const { data } = await api.listBuckets({
sort: "size",
filters: { min_size: 20 },
});
data.map((bucket) => bucket.id).should.deep.equal(["b1", "b3"]);
});
it("should resolve with buckets last_modified value", async () => {
(await api.listBuckets()).should.have
.property("last_modified")
.to.be.a("string");
});
it("should retrieve only buckets after provided timestamp", async () => {
const timestamp = (await api.listBuckets()).last_modified!;
await api.createBucket("b5");
(await api.listBuckets({ since: timestamp })).should.have
.property("data")
.to.have.lengthOf(1);
});
});
describe("Pagination", () => {
it("should not paginate by default", async () => {
const { data } = await api.listBuckets();
data
.map((bucket) => bucket.id)
.should.deep.equal(["b4", "b3", "b2", "b1"]);
});
it("should paginate by chunks", async () => {
const { data } = await api.listBuckets({ limit: 2 });
data.map((bucket) => bucket.id).should.deep.equal(["b4", "b3"]);
});
it("should expose a hasNextPage boolean prop", async () => {
(await api.listBuckets({ limit: 2 })).should.have
.property("hasNextPage")
.eql(true);
});
it("should provide a next method to load next page", async () => {
const res = await api.listBuckets({ limit: 2 });
const { data } = await res.next();
data.map((bucket) => bucket.id).should.deep.equal(["b2", "b1"]);
});
});
});
describe("#createAccount", () => {
it("should create an account", async () => {
await api.createAccount("testuser", "testpw");
const user = await createClient({
headers: { Authorization: "Basic " + btoa("testuser:testpw") },
}).fetchUser();
expect(user!.id).equal("account:testuser");
});
});
describe("#batch", () => {
describe("No chunked requests", () => {
it("should allow batching operations", async () => {
await api.batch((batch: KintoClientBase) => {
batch.createBucket("custom");
const bucket = batch.bucket("custom");
bucket.createCollection("blog");
const coll = bucket.collection("blog");
coll.createRecord({ title: "art1" });
coll.createRecord({ title: "art2" });
});
const { data } = await api
.bucket("custom")
.collection("blog")
.listRecords<TitleRecord>();
data
.map((record) => record.title)
.should.deep.equal(["art2", "art1"]);
});
});
describe("Chunked requests", () => {
it("should allow batching by chunks", async () => {
// Note: kinto server configuration has kinto.paginated_by set to 10.
await api.batch((batch: KintoClientBase) => {
batch.createBucket("custom");
const bucket = batch.bucket("custom");
bucket.createCollection("blog");
const coll = bucket.collection("blog");
for (let i = 1; i <= 27; i++) {
coll.createRecord({ title: "art" + i });
}
});
(
await api.bucket("custom").collection("blog").listRecords()
).should.have
.property("data")
.to.have.lengthOf(10);
});
});
describe("aggregate option", () => {
describe("Succesful publication", () => {
describe("No chunking", () => {
let results: AggregateResponse;
beforeEach(async () => {
const _results = await api.batch(
(batch: KintoClientBase) => {
batch.createBucket("custom");
const bucket = batch.bucket("custom");
bucket.createCollection("blog");
const coll = bucket.collection("blog");
coll.createRecord({ title: "art1" });
coll.createRecord({ title: "art2" });
},
{ aggregate: true }
);
return (results = _results as AggregateResponse);
});
it("should return an aggregated result object", () => {
expect(results).to.include.keys([
"errors",
"conflicts",
"published",
"skipped",
]);
});
it("should contain the list of succesful publications", () => {
expect(
results.published.map((body) => body.data)
).to.have.lengthOf(4);
});
});
describe("Chunked response", () => {
let results: AggregateResponse;
beforeEach(async () => {
const _results = await api
.bucket("default")
.collection("blog")
.batch(
(batch) => {
for (let i = 1; i <= 26; i++) {
batch.createRecord({ title: "art" + i });
}
},
{ aggregate: true }
);
return (results = _results as AggregateResponse);
});
it("should return an aggregated result object", () => {
expect(results).to.include.keys([
"errors",
"conflicts",
"published",
"skipped",
]);
});
it("should contain the list of succesful publications", () => {
expect(results.published).to.have.lengthOf(26);
});
});
});
});
});
});
describe("Backed off server", () => {
const backoffSeconds = 10;
before(async () => {
await startServer(server, { KINTO_BACKOFF: backoffSeconds.toString() });
});
after(async () => {
await stopServer(server);
});
beforeEach(async () => {
await server.flush();
});
it("should appropriately populate the backoff property", async () => {
// Issuing a first api call to retrieve backoff information
await api.listBuckets();
return expect(Math.round(api.backoff / 1000)).eql(backoffSeconds);
});
});
describe("Deprecated protocol version", () => {
beforeEach(async () => {
await server.flush();
});
describe("Soft EOL", () => {
let consoleWarnStub: Stub<typeof console.warn>;
before(() => {
const tomorrow = new Date(new Date().getTime() + 86400000)
.toJSON()
.slice(0, 10);
return startServer(server, {
KINTO_EOS: `"${tomorrow}"`,
KINTO_EOS_URL: "http://www.perdu.com",
KINTO_EOS_MESSAGE: "Boom",
});
});
after(async () => {
await stopServer(server);
});
beforeEach(() => {
consoleWarnStub = sandbox.stub(console, "warn");
});
it("should warn when the server sends a deprecation Alert header", async () => {
await api.fetchServerSettings();
sinon.assert.calledWithExactly(
consoleWarnStub,
"Boom",
"http://www.perdu.com"
);
});
});
describe("Hard EOL", () => {
before(() => {
const lastWeek = new Date(new Date().getTime() - 7 * 86400000)
.toJSON()
.slice(0, 10);
return startServer(server, {
KINTO_EOS: `"${lastWeek}"`,
KINTO_EOS_URL: "http://www.perdu.com",
KINTO_EOS_MESSAGE: "Boom",
});
});
after(() => stopServer(server));
beforeEach(() => {
sandbox.stub(console, "warn");
});
it("should reject with a 410 Gone when hard EOL is received", async () => {
// As of Kinto 13.6.2, EOL responses don't contain CORS headers, so we
// can only assert than an error is throw.
await expectAsyncError(
() => api.fetchServerSettings()
// /HTTP 410 Gone: Service deprecated/,
// ServerResponse
);
});
});
});
describe("Limited pagination", () => {
before(() => {
return startServer(server, { KINTO_PAGINATE_BY: "1" });
});
after(() => stopServer(server));
beforeEach(() => server.flush());
describe("Limited configured server pagination", () => {
let collection: Collection;
beforeEach(() => {
collection = api.bucket("default").collection("posts");
return collection.batch((batch) => {
batch.createRecord({ n: 1 });
batch.createRecord({ n: 2 });
});
});
it("should fetch one results page", async () => {
const { data } = await collection.listRecords();
data.map((record) => record.id).should.have.lengthOf(1);
});
it("should fetch all available pages", async () => {
const { data } = await collection.listRecords({ pages: Infinity });
data.map((record) => record.id).should.have.lengthOf(2);
});
});
});
describe("Chainable API", () => {
before(() => startServer(server));
after(() => stopServer(server));
beforeEach(() => server.flush());
describe(".bucket()", () => {
let bucket: Bucket;
beforeEach(async () => {
bucket = api.bucket("custom");
await api.createBucket("custom");
return await bucket.batch((batch) => {
batch.createCollection("c1", { data: { size: 24 } });
batch.createCollection("c2", { data: { size: 13 } });
batch.createCollection("c3", { data: { size: 38 } });
batch.createCollection("c4", { data: { size: -4 } });
batch.createGroup("g1", [], { data: { size: 24 } });
batch.createGroup("g2", [], { data: { size: 13 } });
batch.createGroup("g3", [], { data: { size: 38 } });
batch.createGroup("g4", [], { data: { size: -4 } });
});
});
describe(".getData()", () => {
let result: KintoObject;
beforeEach(async () => {
const res = await bucket.getData<KintoObject>();
return (result = res);
});
it("should retrieve the bucket identifier", () => {
expect(result).to.have.property("id").eql("custom");
});
it("should retrieve bucket last_modified value", () => {
expect(result).to.have.property("last_modified").to.be.gt(1);
});
});
describe(".setData()", () => {
beforeEach(() => {
return bucket.setPermissions({ read: ["github:jon"] });
});
it("should post data to the bucket", async () => {
const res = await bucket.setData({ a: 1 });
expect((res as KintoResponse).data.a).eql(1);
expect((res as KintoResponse).permissions.read).to.include(
"github:jon"
);
});
it("should patch existing data for the bucket", async () => {
await bucket.setData({ a: 1 });
const res = await bucket.setData({ b: 2 }, { patch: true });
expect((res as KintoResponse).data.a).eql(1);
expect((res as KintoResponse).data.b).eql(2);
expect((res as KintoResponse).permissions.read).to.include(
"github:jon"
);
});
it("should post data to the default bucket", async () => {
const { data } = await api.bucket("default").setData({ a: 1 });
data.should.have.property("a").eql(1);
});
});
describe(".getPermissions()", () => {
it("should retrieve bucket permissions", async () => {
(await bucket.getPermissions()).should.have
.property("write")
.to.have.lengthOf(1);
});
});
describe(".setPermissions()", () => {
beforeEach(() => {
return bucket.setData({ a: 1 });
});
it("should set bucket permissions", async () => {
const res = await bucket.setPermissions({ read: ["github:n1k0"] });
expect((res as KintoResponse).data.a).eql(1);
expect((res as KintoResponse).permissions.read).eql(["github:n1k0"]);
});
describe("Safe option", () => {
it("should check for concurrency", async () => {
await expectAsyncError(
() =>
bucket.setPermissions(
{ read: ["github:n1k0"] },
{ safe: true, last_modified: 1 }
),
/412 Precondition Failed/
);
});
});
});
describe(".addPermissions()", () => {
beforeEach(async () => {
await bucket.setPermissions({ read: ["github:n1k0"] });
return await bucket.setData({ a: 1 });
});
it("should append bucket permissions", async () => {
const res = await bucket.addPermissions({ read: ["accounts:gabi"] });
expect((res as KintoResponse).data.a).eql(1);
expect((res as KintoResponse).permissions.read!.sort()).eql([
"accounts:gabi",
"github:n1k0",
]);
});
});
describe(".removePermissions()", () => {
beforeEach(async () => {
await bucket.setPermissions({ read: ["github:n1k0"] });
return await bucket.setData({ a: 1 });
});
it("should pop bucket permissions", async () => {
const res = await bucket.removePermissions({ read: ["github:n1k0"] });
expect((res as KintoResponse).data.a).eql(1);
expect((res as KintoResponse).permissions.read).eql(undefined);
});
});
describe(".listHistory()", () => {
it("should retrieve the list of history entries", async () => {
const { data } = await bucket.listHistory();
data
.map((entry) => entry.target.data.id)
.should.deep.equal([
"g4",
"g3",
"g2",
"g1",
"c4",
"c3",
"c2",
"c1",
"custom",
]);
});
it("should order entries by field", async () => {
const { data } = await bucket.listHistory({ sort: "last_modified" });
data
.map((entry) => entry.target.data.id)
.should.deep.equal([
"custom",
"c1",
"c2",
"c3",
"c4",
"g1",
"g2",
"g3",
"g4",
]);
});
describe("Filtering", () => {
it("should filter entries by top-level attributes", async () => {
const { data } = await bucket.listHistory({
filters: { resource_name: "bucket" },
});
data
.map((entry) => entry.target.data.id)
.should.deep.equal(["custom"]);
});
it("should filter entries by target attributes", async () => {
const { data } = await bucket.listHistory({
filters: { "target.data.id": "custom" },
});
data
.map((entry) => entry.target.data.id)
.should.deep.equal(["custom"]);
});
it("should resolve with entries last_modified value", async () => {
(await bucket.listHistory()).should.have
.property("last_modified")
.to.be.a("string");
});
it("should retrieve only entries after provided timestamp", async () => {
const timestamp = (await bucket.listHistory()).last_modified!;
await bucket.createCollection("c5");
(await bucket.listHistory({ since: timestamp })).should.have
.property("data")
.to.have.lengthOf(1);
});
});
describe("Pagination", () => {
it("should not paginate by default", async () => {
const { data } = await bucket.listHistory();
data.map((entry) => entry.target.data.id).should.have.lengthOf(9);
});
it("should paginate by chunks", async () => {
const { data } = await bucket.listHistory({ limit: 2 });
data
.map((entry) => entry.target.data.id)
.should.deep.equal(["g4", "g3"]);
});
it("should provide a next method to load next page", async () => {
const res = await bucket.listHistory({ limit: 2 });
const { data } = await res.next();
data
.map((entry) => entry.target.data.id)
.should.deep.equal(["g2", "g1"]);
});
});
});
describe(".listCollections()", () => {
it("should retrieve the list of collections", async () => {
const { data } = await bucket.listCollections();
data
.map((collection) => collection.id)
.sort()
.should.deep.equal(["c1", "c2", "c3", "c4"]);
});
it("should order collections by field", async () => {
const { data } = await bucket.listCollections({ sort: "-size" });
data
.map((collection) => collection.id)
.should.deep.equal(["c3", "c1", "c2", "c4"]);
});
it("should work in a batch", async () => {
const res = (await api.batch((batch: KintoClientBase) => {
batch.bucket("custom").listCollections();
})) as unknown as OperationResponse<KintoObject[]>[];
res[0].body.data
.map((r) => r.id)
.should.deep.equal(["c4", "c3", "c2", "c1"]);
});
describe("Filtering", () => {
it("should filter collections", async () => {
const { data } = await bucket.listCollections({
sort: "size",
filters: { min_size: 20 },
});
data
.map((collection) => collection.id)
.should.deep.equal(["c1", "c3"]);
});
it("should resolve with collections last_modified value", async () => {
(await bucket.listCollections()).should.have
.property("last_modified")
.to.be.a("string");
});
it("should retrieve only collections after provided timestamp", async () => {
const timestamp = (await bucket.listCollections()).last_modified!;
await bucket.createCollection("c5");
(await bucket.listCollections({ since: timestamp })).should.have
.property("data")
.to.have.lengthOf(1);
});
});
describe("Pagination", () => {
it("should not paginate by default", async () => {
const { data } = await bucket.listCollections();
data
.map((collection) => collection.id)
.should.deep.equal(["c4", "c3", "c2", "c1"]);
});
it("should paginate by chunks", async () => {
const { data } = await bucket.listCollections({ limit: 2 });
data
.map((collection) => collection.id)
.should.deep.equal(["c4", "c3"]);
});
it("should provide a next method to load next page", async () => {
const res = await bucket.listCollections({ limit: 2 });
const { data } = await res.next();
data
.map((collection) => collection.id)
.should.deep.equal(["c2", "c1"]);
});
});
});
describe(".createCollection()", () => {
it("should create a named collection", async () => {
await bucket.createCollection("foo");
const { data } = await bucket.listCollections();
data.map((coll) => coll.id).should.include("foo");
});
it("should create an automatically named collection", async () => {
const res = await bucket.createCollection();
const generated = (res as KintoResponse).data.id;
const { data } = await bucket.listCollections();
return expect(data.some((x) => x.id === generated)).eql(true);
});
describe("Safe option", () => {
it("should not override existing collection", async () => {
await bucket.createCollection("posts");
await expectAsyncError(
() => bucket.createCollection("posts", { safe: true }),
/412 Precondition Failed/
);
});
});
describe("Permissions option", () => {
let result: KintoResponse;
beforeEach(async () => {
const res = await bucket.createCollection("posts", {
permissions: {
read: ["github:n1k0"],
},
});
return (result = res as KintoResponse);
});
it("should create a collection having a list of write permissions", () => {
expect(result)
.to.have.property("permissions")
.to.have.property("read")
.to.eql(["github:n1k0"]);
});
});
describe("Data option", () => {
let result: KintoResponse;
beforeEach(async () => {
const res = await bucket.createCollection("posts", {
data: { foo: "bar" },
});
return (result = res as KintoResponse);
});
it("should create a collection having the expected data attached", () => {
expect(result)
.to.have.property("data")
.to.have.property("foo")
.eql("bar");
});
});
});
describe(".deleteCollection()", () => {
it("should delete a collection", async () => {
await bucket.createCollection("foo");
await bucket.deleteCollection("foo");
const { data } = await bucket.listCollections();
data.map((coll) => coll.id).should.not.include("foo");
});
describe("Safe option", () => {
it("should check for concurrency", async () => {
const res = await bucket.createCollection("posts");
expectAsyncError(
() =>
bucket.deleteCollection("posts", {
safe: true,
last_modified: res.data.last_modified - 1000,
}),
/412 Precondition Failed/
);
});
});
});
describe(".listGroups()", () => {
it("should retrieve the list of groups", async () => {
const { data } = await bucket.listGroups();
data
.map((group) => group.id)
.sort()
.should.deep.equal(["g1", "g2", "g3", "g4"]);
});
it("should order groups by field", async () => {
const { data } = await bucket.listGroups({ sort: "-size" });
data
.map((group) => group.id)
.should.deep.equal(["g3", "g1", "g2", "g4"]);
});
describe("Filtering", () => {
it("should filter groups", async () => {
const { data } = await bucket.listGroups({
sort: "size",
filters: { min_size: 20 },
});
data.map((group) => group.id).should.deep.equal(["g1", "g3"]);
});
it("should resolve with groups last_modified value", async () => {
(await bucket.listGroups()).should.have
.property("last_modified")
.to.be.a("string");
});
it("should retrieve only groups after provided timestamp", async () => {
const timestamp = (await bucket.listGroups()).last_modified!;
await bucket.createGroup("g5", []);
(await bucket.listGroups({ since: timestamp })).should.have
.property("data")
.to.have.lengthOf(1);
});
});
describe("Pagination", () => {
it("should not paginate by default", async () => {
const { data } = await bucket.listGroups();
data
.map((group) => group.id)
.should.deep.equal(["g4", "g3", "g2", "g1"]);
});
it("should paginate by chunks", async () => {
const { data } = await bucket.listGroups({ limit: 2 });
data.map((group) => group.id).should.deep.equal(["g4", "g3"]);
});
it("should provide a next method to load next page", async () => {
const res = await bucket.listGroups({ limit: 2 });
const { data } = await res.next();
data.map((group) => group.id).should.deep.equal(["g2", "g1"]);
});
});
});
describe(".createGroup()", () => {
it("should create a named group", async () => {
await bucket.createGroup("foo");
const { data } = await bucket.listGroups();
data.map((group) => group.id).should.include("foo");
});
it("should create an automatically named group", async () => {
const res = await bucket.createGroup();
const generated = (res as KintoResponse<Group>).data.id;
const { data } = await bucket.listGroups();
return expect(data.some((x) => x.id === generated)).eql(true);
});
describe("Safe option", () => {
it("should not override existing group", async () => {
await bucket.createGroup("admins");
await expectAsyncError(
() => bucket.createGroup("admins", [], { safe: true }),
/412 Precondition Failed/
);
});
});
describe("Permissions option", () => {
let result: KintoResponse<Group>;
beforeEach(async () => {
const res = await bucket.createGroup(
"admins",
["twitter:leplatrem"],
{
permissions: {
read: ["github:n1k0"],
},
}
);
return (result = res as KintoResponse<Group>);
});
it("should create a collection having a list of write permissions", () => {
expect(result)
.to.have.property("permissions")
.to.have.property("read")
.to.eql(["github:n1k0"]);
expect(result.data.members).to.include("twitter:leplatrem");
});
});
describe("Data option", () => {
let result: KintoResponse<Group>;
beforeEach(async () => {
const res = await bucket.createGroup(
"admins",
["twitter:leplatrem"],
{
data: { foo: "bar" },
}
);
return (result = res as KintoResponse<Group>);
});
it("should create a collection having the expected data attached", () => {
expect(result)
.to.have.property("data")
.to.have.property("foo")
.eql("bar");
expect(result.data.members).to.include("twitter:leplatrem");
});
});
});
describe(".getGroup()", () => {
it("should get a group", async () => {
await bucket.createGroup("foo");
const res = await bucket.getGroup("foo");
expect((res as KintoResponse<Group>).data.id).eql("foo");
expect((res as KintoResponse<Group>).data.members).eql([]);
expect(
(res as KintoResponse<Group>).permissions.write
).to.have.lengthOf(1);
});
});
describe(".updateGroup()", () => {
it("should update a group", async () => {
const res = await bucket.createGroup("foo");
await bucket.updateGroup({ ...res.data, title: "mod" });
const { data } = await bucket.listGroups();
// type Group doesn't have a title property, so we create an
// intersection type that does
const firstGroup = data[0] as Group & { title: string };
firstGroup.title.should.equal("mod");
});
it("should patch a group", async () => {
const res = await bucket.createGroup("foo", ["github:me"], {
data: { title: "foo", blah: 42 },
});
await bucket.updateGroup(
{ id: (res as KintoResponse<Group>).data.id, blah: 43 },
{ patch: true }
);
const { data } = await bucket.listGroups();
expect(data[0].title).eql("foo");
expect(data[0].members).eql(["github:me"]);
expect(data[0].blah).eql(43);
});
describe("Safe option", () => {
const id = "2dcd0e65-468c-4655-8015-30c8b3a1c8f8";
it("should perform concurrency checks with last_modified", async () => {
const { data } = await bucket.createGroup("foo");
await expectAsyncError(
() =>
bucket.updateGroup(
{
id: data.id,
members: ["github:me"],
title: "foo",
last_modified: 1,
},
{ safe: true }
),
/412 Precondition Failed/
);
});
it("should create a non-existent resource when safe is true", async () => {
(
await bucket.updateGroup({ id, members: ["all"] }, { safe: true })
).should.have
.property("data")
.to.have.property("members")
.eql(["all"]);
});
it("should not override existing data with no last_modified", async () => {
const { data } = await bucket.createGroup("foo");
await expectAsyncError(
() =>
bucket.updateGroup(
{ id: data.id, members: [], title: "foo" },
{ safe: true }
),
/412 Precondition Failed/
);
});
});
});
describe(".deleteGroup()", () => {
it("should delete a group", async () => {
await bucket.createGroup("foo");
await bucket.deleteGroup("foo");
const { data } = await bucket.listGroups();
data.map((coll) => coll.id).should.not.include("foo");
});
describe("Safe option", () => {
it("should check for concurrency", async () => {
const { data } = await bucket.createGroup("posts");
await expectAsyncError(
() =>
bucket.deleteGroup("posts", {
safe: true,
last_modified: data.last_modified - 1000,
}),
/412 Precondition Failed/
);
});
});
});
describe(".batch()", () => {
it("should allow batching operations for current bucket", async () => {
await bucket.batch((batch) => {
batch.createCollection("comments");
const coll = batch.collection("comments");
coll.createRecord({ content: "plop" });
coll.createRecord({ content: "yo" });
});
const { data } = await bucket.collection("comments").listRecords();
data
.map((comment) => comment.content)
.sort()
.should.deep.equal(["plop", "yo"]);
});
describe("Safe option", () => {
it("should allow batching operations for current bucket", async () => {
(
await bucket.batch(
(batch) => {
batch.createCollection("comments");
batch.createCollection("comments");
},
{ safe: true, aggregate: true }
)
).should.have
.property("conflicts")
.to.have.lengthOf(1);
});
});
});
});
describe(".collection()", () => {
function runSuite(label: string, collPromise: () => Promise<Collection>) {
describe(label, () => {
let coll: Collection;
beforeEach(async () => {
const _coll = await collPromise();
return (coll = _coll);
});
describe(".getTotalRecords()", () => {
it("should retrieve the initial total number of records", async () => {
(await coll.getTotalRecords()).should.equal(0);
});
it("should retrieve the updated total number of records", async () => {
await coll.batch((batch) => {
batch.createRecord({ a: 1 });
batch.createRecord({ a: 2 });
});
(await coll.getTotalRecords()).should.equal(2);
});
});
describe(".getPermissions()", () => {
it("should retrieve permissions", async () => {
(await coll.getPermissions()).should.have
.property("write")
.to.have.lengthOf(1);
});
});
describe(".setPermissions()", () => {
beforeEach(() => {
return coll.setData({ a: 1 });
});
it("should set typed permissions", async () => {
const res = await coll.setPermissions({ read: ["github:n1k0"] });
expect((res as KintoResponse).data.a).eql(1);
expect((res as KintoResponse).permissions.read).eql([
"github:n1k0",
]);
});
describe("Safe option", () => {
it("should perform concurrency checks", async () => {
await expectAsyncError(
() =>
coll.setPermissions(
{ read: ["github:n1k0"] },
{ safe: true, last_modified: 1 }
),
/412 Precondition Failed/
);
});
});
});
describe(".addPermissions()", () => {
beforeEach(async () => {
await coll.setPermissions({ read: ["github:n1k0"] });
return await coll.setData({ a: 1 });
});
it("should append collection permissions", async () => {
const res = await coll.addPermissions({
read: ["accounts:gabi"],
});
expect((res as KintoResponse).data.a).eql(1);
expect((res as KintoResponse).permissions.read!.sort()).eql([
"accounts:gabi",
"github:n1k0",
]);
});
});
describe(".removePermissions()", () => {
beforeEach(async () => {
await coll.setPermissions({ read: ["github:n1k0"] });
return await coll.setData({ a: 1 });
});
it("should pop collection permissions", async () => {
const res = await coll.removePermissions({
read: ["github:n1k0"],
});
expect((res as KintoResponse).data.a).eql(1);
expect((res as KintoResponse).permissions.read).eql(undefined);
});
});
describe(".getData()", () => {
it("should retrieve collection data", async () => {
await coll.setData({ signed: true });
const data = (await coll.getData()) as { signed: boolean };
data.should.have.property("signed").eql(true);
});
});
describe(".setData()", () => {
beforeEach(() => {
return coll.setPermissions({ read: ["github:n1k0"] });
});
it("should set collection data", async () => {
const res = await coll.setData({ signed: true });
expect((res as KintoResponse).data.signed).eql(true);
expect((res as KintoResponse).permissions.read).to.include(
"github:n1k0"
);
});
describe("Safe option", () => {
it("should perform concurrency checks", async () => {
await expectAsyncError(
() =>
coll.setData(
{ signed: true },
{ safe: true, last_modified: 1 }
),
/412 Precondition Failed/
);
});
});
});
describe(".createRecord()", () => {
describe("No record id provided", () => {
it("should create a record", async () => {
(await coll.createRecord({ title: "foo" })).should.have
.property("data")
.to.have.property("title")
.eql("foo");
});
describe("Safe option", () => {
it("should check for existing record", async () => {
const { data } = await coll.createRecord({ title: "foo" });
await expectAsyncError(
() =>
coll.createRecord(
{ id: data.id, title: "foo" },
{ safe: true }
),
/412 Precondition Failed/
);
});
});
});
describe("Record id provided", () => {
const record = {
id: "37f727ed-c8c4-461b-80ac-de874992165c",
title: "foo",
};
it("should create a record", async () => {
(await coll.createRecord(record)).should.have
.property("data")
.to.have.property("title")
.eql("foo");
});
});
});
describe(".updateRecord()", () => {
it("should update a record", async () => {
const res = await coll.createRecord({ title: "foo" });
await coll.updateRecord({ ...res.data, title: "mod" });
const { data } = await coll.listRecords();
// type KintoObject doesn't have a title property, so we create
// an intersection type that does
const record = data[0] as KintoObject & { title: string };
record.title.should.equal("mod");
});
it("should patch a record", async () => {
const res = await coll.createRecord({ title: "foo", blah: 42 });
await coll.updateRecord(
{ id: (res as KintoResponse).data.id, blah: 43 },
{ patch: true }
);
const { data } = await coll.listRecords();
expect(data[0].title).eql("foo");
expect(data[0].blah).eql(43);
});
it("should create the record if it doesn't exist yet", async () => {
const id = "2dcd0e65-468c-4655-8015-30c8b3a1c8f8";
const { data } = await coll.updateRecord({ id, title: "blah" });
(await coll.getRecord(data.id)).should.have
.property("data")
.to.have.property("title")
.eql("blah");
});
describe("Safe option", () => {
const id = "2dcd0e65-468c-4655-8015-30c8b3a1c8f8";
it("should perform concurrency checks with last_modified", async () => {
const { data } = await coll.createRecord({ title: "foo" });
await expectAsyncError(
() =>
coll.updateRecord(
{ id: data.id, title: "foo", last_modified: 1 },
{ safe: true }
),
/412 Precondition Failed/
);
});
it("should create a non-existent resource when safe is true", async () => {
(
await coll.updateRecord({ id, title: "foo" }, { safe: true })
).should.have
.property("data")
.to.have.property("title")
.eql("foo");
});
it("should not override existing data with no last_modified", async () => {
const { data } = await coll.createRecord({ title: "foo" });
await expectAsyncError(
() =>
coll.updateRecord(
{ id: data.id, title: "foo" },
{ safe: true }
),
/412 Precondition Failed/
);
});
});
});
describe(".deleteRecord()", () => {
it("should delete a record", async () => {
const { data } = await coll.createRecord({ title: "foo" });
await coll.deleteRecord(data.id);
(await coll.listRecords()).should.have
.property("data")
.deep.equals([]);
});
describe("Safe option", () => {
it("should perform concurrency checks", async () => {
const { data } = await coll.createRecord({ title: "foo" });
await expectAsyncError(
() =>
coll.deleteRecord(data.id, {
last_modified: 1,
safe: true,
}),
/412 Precondition Failed/
);
});
});
});
describe(".addAttachment()", () => {
describe("With filename", () => {
const input = "test";
const dataURL =
"data:text/plain;name=test.txt;base64," + btoa(input);
let result: KintoResponse<{ attachment: Attachment }>;
beforeEach(async () => {
const res = await coll.addAttachment(
dataURL,
{ foo: "bar" },
{ permissions: { write: ["github:n1k0"] } }
);
return (result = res as KintoResponse<{
attachment: Attachment;
}>);
});
it("should create a record with an attachment", () => {
expect(result)
.to.have.property("data")
.to.have.property("attachment")
.to.have.property("size")
.eql(input.length);
});
it("should create a record with provided record data", () => {
expect(result)
.to.have.property("data")
.to.have.property("foo")
.eql("bar");
});
it("should create a record with provided permissions", () => {
expect(result)
.to.have.property("permissions")
.to.have.property("write")
.contains("github:n1k0");
});
});
describe("Without filename", () => {
const dataURL = "data:text/plain;base64," + btoa("blah");
it("should default filename to 'untitled' if not specified", async () => {
(await coll.addAttachment(dataURL)).should.have
.property("data")
.have.property("attachment")
.have.property("filename")
.eql("untitled");
});
it("should allow to specify safe in options", async () => {
(
await coll.addAttachment(dataURL, undefined, { safe: true })
).should.to.have
.property("data")
.to.have.property("attachment")
.to.have.property("size")
.eql(4);
});
it("should allow to specify a filename in options", async () => {
(
await coll.addAttachment(dataURL, undefined, {
filename: "MYFILE.DAT",
})
).should.have
.property("data")
.have.property("attachment")
.have.property("filename")
.eql("MYFILE.DAT");
});
});
});
describe(".removeAttachment()", () => {
const input = "test";
const dataURL =
"data:text/plain;name=test.txt;base64," + btoa(input);
let recordId: string;
beforeEach(async () => {
const res = await coll.addAttachment(dataURL);
return (recordId = (
res as KintoResponse<{
attachment: Attachment;
}>
).data.id);
});
it("should remove an attachment from a record", async () => {
await coll.removeAttachment(recordId);
(await coll.getRecord(recordId)).should.have
.property("data")
.to.have.property("attachment")
.eql(null);
});
});
describe(".getRecord()", () => {
it("should retrieve a record by its id", async () => {
const { data } = await coll.createRecord({ title: "blah" });
(await coll.getRecord(data.id)).should.have
.property("data")
.to.have.property("title")
.eql("blah");
});
});
describe(".listRecords()", () => {
it("should list records", async () => {
await coll.createRecord({ title: "foo" });
const { data } = await coll.listRecords();
data.map((record) => record.title).should.deep.equal(["foo"]);
});
it("should order records by field", async () => {
await Promise.all(
["art3", "art1", "art2"].map((title) => {
return coll.createRecord({ title });
})
);
const { data } = await coll.listRecords({ sort: "title" });
data
.map((record) => record.title)
.should.deep.equal(["art1", "art2", "art3"]);
});
describe("Filtering", () => {
beforeEach(() => {
return coll.batch((batch) => {
batch.createRecord({ name: "paul", age: 28 });
batch.createRecord({ name: "jess", age: 54 });
batch.createRecord({ name: "john", age: 33 });
batch.createRecord({ name: "rené", age: 24 });
});
});
it("should filter records", async () => {
const { data } = await coll.listRecords({
sort: "age",
filters: { min_age: 30 },
});
data
.map((record) => record.name)
.should.deep.equal(["john", "jess"]);
});
it("should properly escape unicode filters", async () => {
const { data } = await coll.listRecords({
filters: { name: "rené" },
});
data.map((record) => record.name).should.deep.equal(["rené"]);
});
it("should resolve with collection last_modified value", async () => {
(await coll.listRecords()).should.have
.property("last_modified")
.to.be.a("string");
});
});
describe("since", () => {
let ts1: string, ts2: string;
beforeEach(async () => {
ts1 = (await coll.listRecords()).last_modified!;
await coll.createRecord({ n: 1 });
ts2 = (await coll.listRecords()).last_modified!;
return await coll.createRecord({ n: 2 });
});
it("should retrieve all records modified since provided timestamp", async () => {
(await coll.listRecords({ since: ts1 })).should.have
.property("data")
.to.have.lengthOf(2);
});
it("should only list changes made after the provided timestamp", async () => {
(await coll.listRecords({ since: ts2 })).should.have
.property("data")
.to.have.lengthOf(1);
});
});
describe("'at' retrieves a snapshot at a given timestamp", () => {
let rec1: KintoObject, rec2: KintoObject, rec3: KintoObject;
beforeEach(async () => {
const resp = await coll.createRecord({ n: 1 });
rec1 = (resp as KintoResponse).data;
const res = await coll.createRecord({ n: 2 });
rec2 = (res as KintoResponse).data;
const res_1 = await coll.createRecord({ n: 3 });
return (rec3 = (res_1 as KintoResponse).data);
});
it("should resolve with a regular list result object", async () => {
const result = await coll.listRecords({
at: rec3.last_modified,
});
const expectedSnapshot = [rec3, rec2, rec1];
expect(result.data).to.eql(expectedSnapshot);
expect(result.last_modified).eql(String(rec3.last_modified));
expect(result.hasNextPage).eql(false);
expect(result.totalRecords).eql(expectedSnapshot.length);
expect(() => result.next()).to.Throw(Error, /pagination/);
});
it("should handle creations", async () => {
(await coll.listRecords({ at: rec1.last_modified })).should.have
.property("data")
.eql([rec1]);
});
it("should handle updates", async () => {
const res = await coll.updateRecord({ ...rec2, n: 42 });
const updatedRec2 = (res as KintoResponse).data;
const { data } = await coll.listRecords({
at: updatedRec2.last_modified,
});
expect(data).eql([updatedRec2, rec3, rec1]);
});
it("should handle deletions", async () => {
const res = await coll.deleteRecord(rec1.id);
const { data } = await coll.listRecords({
at: (res as KintoResponse).data.last_modified,
});
expect(data).eql([rec3, rec2]);
});
it("should handle re-creations", async () => {
await coll.deleteRecord(rec1.id);
await coll.createRecord({ id: rec1.id, n: 1 });
const { data } = await coll.listRecords({
at: rec3.last_modified,
});
expect(data).eql([rec3, rec2, rec1]);
});
it("should handle plural delete before timestamp", async () => {
await coll.createRecord({ n: 3 });
await coll.deleteRecords({
filters: {
eq_n: 3,
},
});
const { data: rec4 } = await coll.createRecord({ n: 4 });
const { data } = await coll.listRecords({
at: rec4.last_modified,
});
expect(data).eql([rec4, rec2, rec1]);
});
it("should handle plural delete after timestamp", async () => {
const { data: rec33 } = await coll.createRecord({ n: 3 });
await coll.createRecord({ n: 4 });
await coll.deleteRecords({
filters: {
eq_n: 3,
},
});
const { data } = await coll.listRecords({
at: rec33.last_modified,
});
expect(data).eql([rec33, rec3, rec2, rec1]);
});
it("should handle long list of changes", async () => {
const res = await coll.batch((batch) => {
for (let n = 4; n <= 100; n++) {
batch.createRecord({ n });
}
});
const at = (res as OperationResponse[])[50].body.data
.last_modified;
(await coll.listRecords({ at })).should.have
.property("data")
.to.lengthOf(54);
});
describe("Mixed CRUD operations", () => {
let rec4: KintoObject;
let s1: KintoObject[] = [],
s2: KintoObject[] = [],
s3: KintoObject[] = [],
s4: KintoObject[] = [];
let rec1up: KintoObject;
beforeEach(async () => {
const responses = await coll.batch((batch) => {
batch.deleteRecord(rec2.id);
batch.updateRecord({
...rec1,
foo: "bar",
});
batch.createRecord({ n: 4 });
});
rec1up = (responses as OperationResponse[])[1].body.data;
rec4 = (responses as OperationResponse[])[
(responses as OperationResponse[]).length - 1
].body.data;
const results = await Promise.all([
coll.listRecords({ at: rec1.last_modified }),
coll.listRecords({ at: rec2.last_modified }),
coll.listRecords({ at: rec3.last_modified }),
coll.listRecords({ at: rec4.last_modified }),
]);
const snapshots = results.map(({ data }) => data);
s1 = snapshots[0];
s2 = snapshots[1];
s3 = snapshots[2];
s4 = snapshots[3];
});
it("should compute snapshot1 as expected", () => {
expect(s1).eql([rec1]);
});
it("should compute snapshot2 as expected", () => {
expect(s2).eql([rec2, rec1]);
});
it("should compute snapshot3 as expected", () => {
expect(s3).eql([rec3, rec2, rec1]);
});
it("should compute snapshot4 as expected", () => {
expect(s4).eql([rec4, rec1up, rec3]);
});
});
});
describe("Pagination", () => {
beforeEach(() => {
return coll.batch((batch) => {
for (let i = 1; i <= 3; i++) {
batch.createRecord({ n: i });
}
});
});
it("should not paginate by default", async () => {
const { data } = await coll.listRecords();
data.map((record) => record.n).should.deep.equal([3, 2, 1]);
});
it("should paginate by chunks", async () => {
const { data } = await coll.listRecords({ limit: 2 });
data.map((record) => record.n).should.deep.equal([3, 2]);
});
it("should provide a next method to load next page", async () => {
const res = await coll.listRecords({ limit: 2 });
const { data } = await res.next();
data.map((record) => record.n).should.deep.equal([1]);
});
it("should resolve with an empty array on exhausted pagination", async () => {
const res1 = await coll.listRecords({ limit: 2 });
const res2 = await res1.next();
await expectAsyncError(
() => res2.next(),
/Pagination exhausted./
);
});
it("should retrieve all pages", async () => {
// Note: Server has no limit by default, so here we get all the
// records.
const { data } = await coll.listRecords();
data.map((record) => record.n).should.deep.equal([3, 2, 1]);
});
it("should retrieve specified number of pages", async () => {
const { data } = await coll.listRecords({ limit: 1, pages: 2 });
data.map((record) => record.n).should.deep.equal([3, 2]);
});
it("should allow fetching next page after last page if any", async () => {
const { next } = await coll.listRecords({ limit: 1, pages: 1 });
const { data } = await next();
data.map((record) => record.n).should.deep.equal([3, 2]);
});
it("should should retrieve all existing pages", async () => {
const { data } = await coll.listRecords({
limit: 1,
pages: Infinity,
});
data.map((record) => record.n).should.deep.equal([3, 2, 1]);
});
});
});
describe(".batch()", () => {
it("should allow batching operations in the current collection", async () => {
await coll.batch((batch) => {
batch.createRecord({ title: "a" });
batch.createRecord({ title: "b" });
});
const { data } = await coll.listRecords({ sort: "title" });
data.map((record) => record.title).should.deep.equal(["a", "b"]);
});
});
});
}
runSuite("default bucket", async () => {
await api.bucket("default").createCollection("plop");
return api.bucket("default").collection("plop");
});
runSuite("custom bucket", async () => {
await api.createBucket("custom");
await api.bucket("custom").createCollection("plop");
return api.bucket("custom").collection("plop");
});
});
});
}); | the_stack |
'use strict';
import * as _ from 'lodash';
import { expect } from 'chai';
import * as sinon from 'sinon';
import * as mocks from '../../resources/mocks';
import { FirebaseApp } from '../../../src/app/firebase-app';
import { Database, DatabaseService } from '../../../src/database/database';
import { ServiceAccountCredential } from '../../../src/app/credential-internal';
import * as utils from '../utils';
import { HttpClient, HttpRequestConfig } from '../../../src/utils/api-request';
describe('Database', () => {
let mockApp: FirebaseApp;
let database: DatabaseService;
beforeEach(() => {
mockApp = mocks.app();
database = new DatabaseService(mockApp);
});
afterEach(() => {
return database.delete().then(() => {
return mockApp.delete();
});
});
describe('Constructor', () => {
const invalidApps = [null, NaN, 0, 1, true, false, '', 'a', [], [1, 'a'], {}, { a: 1 }, _.noop];
invalidApps.forEach((invalidApp) => {
it(`should throw given invalid app: ${JSON.stringify(invalidApp)}`, () => {
expect(() => {
const databaseAny: any = DatabaseService;
return new databaseAny(invalidApp);
}).to.throw('First argument passed to admin.database() must be a valid Firebase app instance.');
});
});
it('should throw given no app', () => {
expect(() => {
const databaseAny: any = DatabaseService;
return new databaseAny();
}).to.throw('First argument passed to admin.database() must be a valid Firebase app instance.');
});
it('should not throw given a valid app', () => {
expect(() => {
return new DatabaseService(mockApp);
}).not.to.throw();
});
});
describe('app', () => {
it('returns the app from the constructor', () => {
// We expect referential equality here
expect(database.app).to.equal(mockApp);
});
it('is read-only', () => {
expect(() => {
(database as any).app = mockApp;
}).to.throw('Cannot set property app of #<DatabaseService> which has only a getter');
});
});
describe('getDatabase', () => {
it('should return the default Database namespace', () => {
const db: Database = database.getDatabase();
expect(db.ref().toString()).to.be.equal('https://databasename.firebaseio.com/');
});
it('should return the Database namespace', () => {
const db: Database = database.getDatabase(mockApp.options.databaseURL);
expect(db.ref().toString()).to.be.equal('https://databasename.firebaseio.com/');
});
it('should return a cached version of Database on subsequent calls', () => {
const db1: Database = database.getDatabase(mockApp.options.databaseURL);
const db2: Database = database.getDatabase(mockApp.options.databaseURL);
expect(db1).to.equal(db2);
expect(db1.ref().toString()).to.equal('https://databasename.firebaseio.com/');
});
it('should return a Database instance for the specified URL', () => {
const db1: Database = database.getDatabase(mockApp.options.databaseURL);
const db2: Database = database.getDatabase('https://other-database.firebaseio.com');
expect(db1.ref().toString()).to.equal('https://databasename.firebaseio.com/');
expect(db2.ref().toString()).to.equal('https://other-database.firebaseio.com/');
});
const invalidArgs = [null, NaN, 0, 1, true, false, '', [], [1, 'a'], {}, { a: 1 }, _.noop];
invalidArgs.forEach((url) => {
it(`should throw given invalid URL argument: ${JSON.stringify(url)}`, () => {
expect(() => {
(database as any).getDatabase(url);
}).to.throw('Database URL must be a valid, non-empty URL string.');
});
});
});
describe('Token refresh', () => {
const MINUTE_IN_MILLIS = 60 * 1000;
let clock: sinon.SinonFakeTimers;
let getTokenStub: sinon.SinonStub;
beforeEach(() => {
getTokenStub = stubCredentials();
clock = sinon.useFakeTimers(1000);
});
afterEach(() => {
getTokenStub.restore();
clock.restore();
});
function stubCredentials(options?: {
accessToken?: string;
expiresIn?: number;
err?: any;
}): sinon.SinonStub {
if (options?.err) {
return sinon.stub(ServiceAccountCredential.prototype, 'getAccessToken')
.rejects(options.err);
}
return sinon.stub(ServiceAccountCredential.prototype, 'getAccessToken')
.resolves({
access_token: options?.accessToken || 'mock-access-token', // eslint-disable-line @typescript-eslint/camelcase
expires_in: options?.expiresIn || 3600, // eslint-disable-line @typescript-eslint/camelcase
});
}
it('should refresh the token 5 minutes before expiration', () => {
database.getDatabase();
expect(getTokenStub).to.have.not.been.called;
return mockApp.INTERNAL.getToken()
.then((token) => {
expect(getTokenStub).to.have.been.calledOnce;
const expiryInMillis = token.expirationTime - Date.now();
clock.tick(expiryInMillis - (5 * MINUTE_IN_MILLIS) - 1000);
expect(getTokenStub).to.have.been.calledOnce;
clock.tick(1000);
expect(getTokenStub).to.have.been.calledTwice;
});
});
it('should not start multiple token refresher tasks', () => {
database.getDatabase();
database.getDatabase('https://other-database.firebaseio.com');
expect(getTokenStub).to.have.not.been.called;
return mockApp.INTERNAL.getToken()
.then((token) => {
expect(getTokenStub).to.have.been.calledOnce;
const expiryInMillis = token.expirationTime - Date.now();
clock.tick(expiryInMillis - (5 * MINUTE_IN_MILLIS));
expect(getTokenStub).to.have.been.calledTwice;
});
});
it('should reschedule the token refresher when the underlying token changes', () => {
database.getDatabase();
return mockApp.INTERNAL.getToken()
.then((token1) => {
expect(getTokenStub).to.have.been.calledOnce;
// Forward the clock to 30 minutes before expiry.
const expiryInMillis = token1.expirationTime - Date.now();
clock.tick(expiryInMillis - (30 * MINUTE_IN_MILLIS));
// Force a token refresh
return mockApp.INTERNAL.getToken(true)
.then((token2) => {
expect(getTokenStub).to.have.been.calledTwice;
// Forward the clock to 5 minutes before old expiry time.
clock.tick(25 * MINUTE_IN_MILLIS);
expect(getTokenStub).to.have.been.calledTwice;
// Forward the clock 1 second past old expiry time.
clock.tick(5 * MINUTE_IN_MILLIS + 1000);
expect(getTokenStub).to.have.been.calledTwice;
const newExpiryTimeInMillis = token2.expirationTime - Date.now();
clock.tick(newExpiryTimeInMillis - (5 * MINUTE_IN_MILLIS));
expect(getTokenStub).to.have.been.calledThrice;
});
});
});
it('should not reschedule when the token is about to expire in 5 minutes', () => {
database.getDatabase();
return mockApp.INTERNAL.getToken()
.then((token1) => {
expect(getTokenStub).to.have.been.calledOnce;
// Forward the clock to 30 minutes before expiry.
const expiryInMillis = token1.expirationTime - Date.now();
clock.tick(expiryInMillis - (30 * MINUTE_IN_MILLIS));
getTokenStub.restore();
getTokenStub = stubCredentials({ expiresIn: 5 * 60 });
// Force a token refresh
return mockApp.INTERNAL.getToken(true);
})
.then((token2) => {
expect(getTokenStub).to.have.been.calledOnce;
const newExpiryTimeInMillis = token2.expirationTime - Date.now();
clock.tick(newExpiryTimeInMillis);
expect(getTokenStub).to.have.been.calledOnce;
getTokenStub.restore();
getTokenStub = stubCredentials({ expiresIn: 60 * 60 });
// Force a token refresh
return mockApp.INTERNAL.getToken(true);
})
.then((token3) => {
expect(getTokenStub).to.have.been.calledOnce;
const newExpiryTimeInMillis = token3.expirationTime - Date.now();
clock.tick(newExpiryTimeInMillis - (5 * MINUTE_IN_MILLIS));
expect(getTokenStub).to.have.been.calledTwice;
});
});
it('should gracefully handle errors during token refresh', () => {
database.getDatabase();
return mockApp.INTERNAL.getToken()
.then((token1) => {
expect(getTokenStub).to.have.been.calledOnce;
getTokenStub.restore();
getTokenStub = stubCredentials({ err: new Error('Test error') });
expect(getTokenStub).to.have.not.been.called;
const expiryInMillis = token1.expirationTime - Date.now();
clock.tick(expiryInMillis);
expect(getTokenStub).to.have.been.calledOnce;
getTokenStub.restore();
getTokenStub = stubCredentials();
expect(getTokenStub).to.have.not.been.called;
// Force a token refresh
return mockApp.INTERNAL.getToken(true);
})
.then((token2) => {
expect(getTokenStub).to.have.been.calledOnce;
const newExpiryTimeInMillis = token2.expirationTime - Date.now();
clock.tick(newExpiryTimeInMillis - (5 * MINUTE_IN_MILLIS));
expect(getTokenStub).to.have.been.calledTwice;
});
});
it('should stop the token refresher task at delete', () => {
database.getDatabase();
return mockApp.INTERNAL.getToken()
.then((token) => {
expect(getTokenStub).to.have.been.calledOnce;
return database.delete()
.then(() => {
// Forward the clock to five minutes before expiry.
const expiryInMillis = token.expirationTime - Date.now();
clock.tick(expiryInMillis - (5 * MINUTE_IN_MILLIS));
expect(getTokenStub).to.have.been.calledOnce;
});
});
});
});
describe('Rules', () => {
const mockAccessToken: string = utils.generateRandomAccessToken();
let getTokenStub: sinon.SinonStub;
let stubs: sinon.SinonStub[] = [];
before(() => {
getTokenStub = utils.stubGetAccessToken(mockAccessToken);
});
after(() => {
getTokenStub.restore();
});
beforeEach(() => {
return mockApp.INTERNAL.getToken();
});
afterEach(() => {
_.forEach(stubs, (stub) => stub.restore());
stubs = [];
});
const rules = {
rules: {
'.read': true,
},
};
const rulesString = JSON.stringify(rules);
const rulesWithComments = `{
// Some comments
rules: {
'.read': true,
},
}`;
const rulesPath = '.settings/rules.json';
function callParamsForGet(options?: { strict?: boolean; url?: string }): HttpRequestConfig {
const url = options?.url || `https://databasename.firebaseio.com/${rulesPath}`;
const params: HttpRequestConfig = {
method: 'GET',
url,
headers: {
Authorization: 'Bearer ' + mockAccessToken,
},
};
if (options?.strict) {
params.data = { format: 'strict' };
}
return params;
}
function stubSuccessfulResponse(payload: string | object): sinon.SinonStub {
const expectedResult = utils.responseFrom(payload);
const stub = sinon.stub(HttpClient.prototype, 'send').resolves(expectedResult);
stubs.push(stub);
return stub;
}
function stubErrorResponse(payload: string | object): sinon.SinonStub {
const expectedResult = utils.errorFrom(payload);
const stub = sinon.stub(HttpClient.prototype, 'send').rejects(expectedResult);
stubs.push(stub);
return stub;
}
describe('getRules', () => {
it('should return the rules fetched from the database', () => {
const db: Database = database.getDatabase();
const stub = stubSuccessfulResponse(rules);
return db.getRules().then((result) => {
expect(result).to.equal(rulesString);
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForGet());
});
});
it('should return the rules fetched from the database including comments', () => {
const db: Database = database.getDatabase();
const stub = stubSuccessfulResponse(rulesWithComments);
return db.getRules().then((result) => {
expect(result).to.equal(rulesWithComments);
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForGet());
});
});
it('should return the rules fetched from the explicitly specified database', () => {
const db: Database = database.getDatabase('https://custom.firebaseio.com');
const stub = stubSuccessfulResponse(rules);
return db.getRules().then((result) => {
expect(result).to.equal(rulesString);
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForGet({ url: `https://custom.firebaseio.com/${rulesPath}` }));
});
});
it('should return the rules fetched from the custom URL with query params', () => {
const db: Database = database.getDatabase('http://localhost:9000?ns=foo');
const stub = stubSuccessfulResponse(rules);
return db.getRules().then((result) => {
expect(result).to.equal(rulesString);
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForGet({ url: `http://localhost:9000/${rulesPath}?ns=foo` }));
});
});
it('should throw if the server responds with a well-formed error', () => {
const db: Database = database.getDatabase();
stubErrorResponse({ error: 'test error' });
return db.getRules().should.eventually.be.rejectedWith(
'Error while accessing security rules: test error');
});
it('should throw if the server responds with an error', () => {
const db: Database = database.getDatabase();
stubErrorResponse('error text');
return db.getRules().should.eventually.be.rejectedWith(
'Error while accessing security rules: error text');
});
it('should throw in the event of an I/O error', () => {
const db: Database = database.getDatabase();
const stub = sinon.stub(HttpClient.prototype, 'send').rejects(
new Error('network error'));
stubs.push(stub);
return db.getRules().should.eventually.be.rejectedWith('network error');
});
});
describe('getRulesWithJSON', () => {
it('should return the rules fetched from the database', () => {
const db: Database = database.getDatabase();
const stub = stubSuccessfulResponse(rules);
return db.getRulesJSON().then((result) => {
expect(result).to.deep.equal(rules);
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForGet({ strict: true }));
});
});
it('should return the rules fetched from the explicitly specified database', () => {
const db: Database = database.getDatabase('https://custom.firebaseio.com');
const stub = stubSuccessfulResponse(rules);
return db.getRulesJSON().then((result) => {
expect(result).to.deep.equal(rules);
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForGet({ strict: true, url: `https://custom.firebaseio.com/${rulesPath}` }));
});
});
it('should return the rules fetched from the custom URL with query params', () => {
const db: Database = database.getDatabase('http://localhost:9000?ns=foo');
const stub = stubSuccessfulResponse(rules);
return db.getRulesJSON().then((result) => {
expect(result).to.deep.equal(rules);
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForGet({ strict: true, url: `http://localhost:9000/${rulesPath}?ns=foo` }));
});
});
it('should throw if the server responds with a well-formed error', () => {
const db: Database = database.getDatabase();
stubErrorResponse({ error: 'test error' });
return db.getRulesJSON().should.eventually.be.rejectedWith(
'Error while accessing security rules: test error');
});
it('should throw if the server responds with an error', () => {
const db: Database = database.getDatabase();
stubErrorResponse('error text');
return db.getRulesJSON().should.eventually.be.rejectedWith(
'Error while accessing security rules: error text');
});
it('should throw in the event of an I/O error', () => {
const db: Database = database.getDatabase();
const stub = sinon.stub(HttpClient.prototype, 'send').rejects(
new Error('network error'));
stubs.push(stub);
return db.getRulesJSON().should.eventually.be.rejectedWith('network error');
});
});
function callParamsForPut(
data: string | Buffer | object,
url = `https://databasename.firebaseio.com/${rulesPath}`,
): HttpRequestConfig {
return {
method: 'PUT',
url,
headers: {
'Authorization': 'Bearer ' + mockAccessToken,
'content-type': 'application/json; charset=utf-8',
},
data,
};
}
describe('setRules', () => {
it('should set the rules when specified as a string', () => {
const db: Database = database.getDatabase();
const stub = stubSuccessfulResponse({});
return db.setRules(rulesString).then(() => {
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForPut(rulesString));
});
});
it('should set the rules when specified as a Buffer', () => {
const db: Database = database.getDatabase();
const stub = stubSuccessfulResponse({});
const buffer = Buffer.from(rulesString);
return db.setRules(buffer).then(() => {
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForPut(buffer));
});
});
it('should set the rules when specified as an object', () => {
const db: Database = database.getDatabase();
const stub = stubSuccessfulResponse({});
return db.setRules(rules).then(() => {
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForPut(rules));
});
});
it('should set the rules with comments when specified as a string', () => {
const db: Database = database.getDatabase();
const stub = stubSuccessfulResponse({});
return db.setRules(rulesWithComments).then(() => {
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForPut(rulesWithComments));
});
});
it('should set the rules in the explicitly specified database', () => {
const db: Database = database.getDatabase('https://custom.firebaseio.com');
const stub = stubSuccessfulResponse({});
return db.setRules(rulesString).then(() => {
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForPut(rulesString, `https://custom.firebaseio.com/${rulesPath}`));
});
});
it('should set the rules using the custom URL with query params', () => {
const db: Database = database.getDatabase('http://localhost:9000?ns=foo');
const stub = stubSuccessfulResponse({});
return db.setRules(rulesString).then(() => {
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForPut(rulesString, `http://localhost:9000/${rulesPath}?ns=foo`));
});
});
const invalidSources: any[] = [null, '', undefined, true, false, 1];
invalidSources.forEach((invalidSource) => {
it(`should throw if the source is ${JSON.stringify(invalidSource)}`, () => {
const db: Database = database.getDatabase();
return db.setRules(invalidSource).should.eventually.be.rejectedWith(
'Source must be a non-empty string, Buffer or an object.');
});
});
it('should throw if the server responds with a well-formed error', () => {
const db: Database = database.getDatabase();
stubErrorResponse({ error: 'test error' });
return db.setRules(rules).should.eventually.be.rejectedWith(
'Error while accessing security rules: test error');
});
it('should throw if the server responds with an error', () => {
const db: Database = database.getDatabase();
stubErrorResponse('error text');
return db.setRules(rules).should.eventually.be.rejectedWith(
'Error while accessing security rules: error text');
});
it('should throw in the event of an I/O error', () => {
const db: Database = database.getDatabase();
const stub = sinon.stub(HttpClient.prototype, 'send').rejects(
new Error('network error'));
stubs.push(stub);
return db.setRules(rules).should.eventually.be.rejectedWith('network error');
});
});
describe('emulator mode', () => {
interface EmulatorTestConfig {
name: string;
setUp: () => FirebaseApp;
tearDown?: () => void;
url: string;
}
const configs: EmulatorTestConfig[] = [
{
name: 'with environment variable',
setUp: () => {
process.env.FIREBASE_DATABASE_EMULATOR_HOST = 'localhost:9090';
return mocks.app();
},
tearDown: () => {
delete process.env.FIREBASE_DATABASE_EMULATOR_HOST;
},
url: `http://localhost:9090/${rulesPath}?ns=databasename`,
},
{
name: 'with app options',
setUp: () => {
return mocks.appWithOptions({
databaseURL: 'http://localhost:9091?ns=databasename',
});
},
url: `http://localhost:9091/${rulesPath}?ns=databasename`,
},
{
name: 'with environment variable overriding app options',
setUp: () => {
process.env.FIREBASE_DATABASE_EMULATOR_HOST = 'localhost:9090';
return mocks.appWithOptions({
databaseURL: 'http://localhost:9091?ns=databasename',
});
},
tearDown: () => {
delete process.env.FIREBASE_DATABASE_EMULATOR_HOST;
},
url: `http://localhost:9090/${rulesPath}?ns=databasename`,
},
];
configs.forEach((config) => {
describe(config.name, () => {
let emulatorApp: FirebaseApp;
let emulatorDatabase: DatabaseService;
before(() => {
emulatorApp = config.setUp();
emulatorDatabase = new DatabaseService(emulatorApp);
});
after(() => {
if (config.tearDown) {
config.tearDown();
}
return emulatorDatabase.delete().then(() => {
return emulatorApp.delete();
});
});
it('getRules should connect to the emulator', () => {
const db: Database = emulatorDatabase.getDatabase();
const stub = stubSuccessfulResponse(rules);
return db.getRules().then((result) => {
expect(result).to.equal(rulesString);
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForGet({ url: config.url }));
});
});
it('getRulesJSON should connect to the emulator', () => {
const db: Database = emulatorDatabase.getDatabase();
const stub = stubSuccessfulResponse(rules);
return db.getRulesJSON().then((result) => {
expect(result).to.equal(rules);
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForGet({ strict: true, url: config.url }));
});
});
it('setRules should connect to the emulator', () => {
const db: Database = emulatorDatabase.getDatabase();
const stub = stubSuccessfulResponse({});
return db.setRules(rulesString).then(() => {
return expect(stub).to.have.been.calledOnce.and.calledWith(
callParamsForPut(rulesString, config.url));
});
});
});
});
});
});
}); | the_stack |
import autobind from 'autobind-decorator';
import * as posenet from '@tensorflow-models/posenet';
import { backgroundColor } from './styles';
import { computeStyleResult, cssColorToArray } from './../utils';
import { vec2, copy, add, sub, scale } from './../vec2';
import { scaleToFill, clamp, setBooleanAttribute } from './../utils';
import { InputType, Animitter } from './types';
import { html } from '@polymer/lit-element';
import { ACCInputEvent, InputEventDetails } from '../events/input-event';
import { AbstractInputElement } from './abstract-input';
import { WebcamCanvas } from '../webcam';
import { scalemap } from '../utils';
import { property } from './decorators';
import { MobileNetMultiplier } from '@tensorflow-models/posenet/dist/mobilenet';
import './tutorial';
const animitter = require('animitter');
interface KeypointMap {
[name: string]: vec2;
}
/**
* used in order to focus on calibration panel header without strict casting
* @param c
*/
const canFocusHeader = (c:any): c is { focusHeader: ()=>void } =>
typeof c.focusHeader === 'function';
/**
* is an element that has width and height attributes like canvas or image
* @param v
*/
const isPixelResolutionElement = (v: any): v is { width: number, height: number } =>
typeof v.width === 'number' && v.height === 'number';
/**
* Get the dimensions of the provided element
* @param element an Element to get the dimensions of
* @param result optionally provide an array to fill as a vector to reduce garbage
*/
const getElementDimensions = (element: Element, result: vec2 = [0, 0]): vec2 => {
if (isPixelResolutionElement(element)) {
result[0] = element.width;
result[1] = element.height;
return result;
}
if (Math.min(element.clientWidth, element.clientHeight) > 0) {
result[0] = element.clientWidth;
result[1] = element.clientHeight;
return result;
}
const bcr = element.getBoundingClientRect();
if(Math.min(bcr.width, bcr.height) > 0) {
result[0] = bcr.width;
result[1] = bcr.height;
return result;
}
return result;
}
const _tmpVec2: vec2 = [NaN, NaN];
const _tmpScaleBounds = {};
/**
* mutate the provided points to be scaled and offset to the destination canvas
* @param {*} canvas
* @param {Array<[number,number]>} nestedPoints
* @param {*} result
*/
export const transformCameraPoints = (
inWidth: number, inHeight: number,
outWidth: number, outHeight: number,
nestedPoints: vec2[]) => {
const { scale, left, top } = scaleToFill(inWidth, inHeight, outWidth, outHeight, 0, _tmpScaleBounds);
for(let i=0; i<nestedPoints.length; i++){
const point = nestedPoints[i];
let [x, y] = point;
x *= scale;
y *= scale;
x += left;
y += top;
point[0] = x;
point[1] = y;
}
return nestedPoints;
};
const keypointPartsMap: any = {
'nose': 'Nose',
'leftEye': 'Right Eye',
'rightEye': 'Left Eye',
'leftEar': 'Right Ear',
'rightEar': 'Left Ear',
'leftShoulder': 'Right Shoulder',
'rightShoulder': 'Left Shoulder',
'leftElbow': 'Right Elbow',
'rightElbow': 'Left Elbow',
'leftWrist': 'Right Wrist',
'rightWrist':'Left Wrist',
'leftHip': 'Right Hip',
'rightHip': 'Left Hip',
'leftKnee': 'Right Knee',
'rightKnee': 'Left Knee',
'leftAnkle': 'Right Ankle',
'rightAnkle': 'Left Ankle'
};
//pre-defined parts that come with posenet
export const keypointParts = [
'nose',
'leftEye',
'rightEye',
'leftEar',
'rightEar',
'leftShoulder',
'rightShoulder',
'leftElbow',
'rightElbow',
'leftWrist',
'rightWrist',
'leftHip',
'rightHip',
'leftKnee',
'rightKnee',
'leftAnkle',
'rightAnkle'
];
const selectableParts = [
'nose',
'leftWrist',
'rightWrist',
'leftElbow',
'rightElbow',
'leftKnee',
'rightKnee',
'leftAnkle',
'rightAnkle'
];
const selectablePartsDisplay = selectableParts.map(key=> keypointPartsMap[key]);
//all parts
export const parts = keypointParts;
export interface PoseInputEventDetails extends InputEventDetails {
pose:posenet.Pose;
bodyPart:string;
}
type PoseInputEventInit = CustomEventInit<PoseInputEventDetails>;
export class ACCPoseInputEvent extends ACCInputEvent {
constructor(type:string, eventInit:PoseInputEventInit){
super(type, eventInit);
}
}
// let constraints = {
// audio: false,
// video: {
// advanced: [
// { width: { exact: 400 } },
// { height: { exact: 400 } },
// ]
// }
// }
const _tmpContentDims: [number, number] = [NaN, NaN];
/**
* `<acc-pose-input>` element easily adds PoseNet based tracking for controlling
* the cursor position on a webpage with a chosen body part of the user.
* For example with a couple lines of code, a user's nose can be used to control
* a webpage.
*
* @example ```html
*
* <acc-pose-input amplification="2" smoothing="0.5" bodyPart="nose"></acc-pose-input>
* ```
*/
export class PoseInputElement extends AbstractInputElement {
@property({ type: String })
public label:string = 'Body';
public inputType:InputType = 'pose';
public pose:posenet.Pose;
public preamplifiedTargetPosition: vec2 = [0, 0];
@property({ type: Number })
public amplification:number = 1;
@property({ type: String })
public bodyPart:string = 'nose';
@property({ type: String })
public target:string = '';
@property({ type: Number })
public multiplier:MobileNetMultiplier = 1.01;//0.75;
@property({ type: Number })
public imageScaleFactor:number = 0.33;
/**
* show the help modal, has priority over controls
*/
@property({ type: Boolean })
public help: boolean = false;
@property({ type: Number })
public keypointEase: number = 0.5;
/**
* this input has a cointrols panel
*/
public get hasControls() {
return true;
}
protected _estimating:boolean;
protected _webcamCanvas:WebcamCanvas = new WebcamCanvas();
protected _loop:Animitter = animitter();
protected _input:posenet.PoseNet;
public sourceCenter: vec2;
private __estimating: boolean;
/**
* holds a dictionary of all tracked keypoints, in source (webcam) coordinates
* points are all eased by keypointEase
*/
private __easedKeypointMap: KeypointMap = {};
private __lastSourcePosition: vec2 = [0, 0];
constructor(){
super();
this._loop.on('update', this._handleNewFrame);
this._loop.on('start', this._dispatchReady);
this._loop.on('stop', this._handleStop);
}
/**
* overriding AbstractInputElement#_createEvent to provide extra details
* @param type
* @param bubbles
* @param composed
*/
protected _createEvent(type:string, bubbles:boolean=true, composed:boolean=true){
const eventInit:PoseInputEventInit = {
detail: {
inputType: this.inputType,
position: this.position,
bodyPart: this.bodyPart,
pose:this.pose,
},
bubbles,
//send outside of shadow to parent element
composed
};
return new ACCInputEvent(type, eventInit);
}
computePartPosition(part:string, result: vec2=[NaN,NaN]): vec2 {
if(!this.pose || !this.pose.keypoints){
result[0] = result[1] = NaN;
return result;
}
let x: number;
let y: number;
if(part === 'sternum'){
const leftSh = this.pose.keypoints[5].position;
const rightSh = this.pose.keypoints[6].position;
x = (leftSh.x - rightSh.x) * 0.5 + rightSh.x;
y = (leftSh.y - rightSh.y) * 0.5 + rightSh.y;
} else {
const p = this.pose.keypoints[keypointParts.indexOf(part)].position;
x = p.x;
y = p.y;
}
result[0] = x;
result[1] = y;
return result;
}
getPartPosition(part: string, result: vec2= [NaN, NaN]): vec2 {
//return this.computePartPosition(part, result);
const src = this.__easedKeypointMap[part];
if(src) {
result[0] = src[0];
result[1] = src[1];
}
return result;
}
getPartPositionNormalized(part:string, result: vec2=[NaN, NaN]): vec2 {
const pos = this.getPartPosition(part, result);
const x = scalemap(pos[0], 0, this.canvas.width, -1, 1);// * this.amplification;
const y = scalemap(pos[1], 0, this.canvas.height, -1, 1);// * this.amplification;
result[0] = x;
result[1] = y;
return result;
}
/**
* Get the position of the body part projected into the coordinate space of the target element
* @param part the body part key to receive the position of
* @param targetElement optionally provide an Element if you wish to use one other than the target
*/
getPartPositionProjected(part: string, targetElement:Element= this.contentElement): vec2 {
return this.projectPosition(this.getPartPosition(part), targetElement);
}
/**
* Project (mutate) a position from source (webcam) coordinates to an elements coordinates
* @param position a vector in source (webcam) coordinates
* @param targetElement optionally provide an Element to project to other than target element
*/
projectPosition(position: vec2, targetElement: Element= this.contentElement): vec2 {
const [ width, height ] = getElementDimensions(targetElement);
return transformCameraPoints(this.canvas.width, this.canvas.height, width, height, [position])[0];
}
get canvas(){
return this._webcamCanvas.domElement;
}
async initialize(){
this._dispatchInitializing();
if(/(iPad|iPhone|Crios)/g.test(navigator.userAgent)) {
const err = new Error('Body tracking is not supported on iOS.');
this._dispatchError(err);
throw err;
}
if (!this._input) {
this._input = await posenet.load(this.multiplier);
}
try {
await this._webcamCanvas.initialize();
} catch(e) {
this._dispatchError(new Error(e)); //'Error initializing camera. Please ensure you have one and haven\'t denied access.');
throw e;
}
if(!this.sourceCenter) {
this.resetCenter();
}
this._loop.setFPS(this._webcamCanvas.getFrameRate());
this._loop.start();
}
@autobind
protected _handleStop(){
//when the input stops, shut down the camera and undo all initialization
this._dispatchStop();
this._webcamCanvas.stop();
}
@autobind
protected _handleNewFrame(){
//if a new frame occurs while still estimating the last pose
//skip this frame
if(this.__estimating){
return;
}
this._updatePose();
}
public _propertiesChanged(props: any, changed: any, prev: any) {
super._propertiesChanged(props, changed, prev);
if(changed && changed.hasOwnProperty('help')) {
setBooleanAttribute(this, 'help', props.help);
this._dispatchChange();
}
}
protected async _updatePose(){
const outputStride = 16;
const flipHorizontal = false;
const maxPoseDetections = 1;
this._estimating = true;
this._webcamCanvas.update();
const poses = await this._input.estimateMultiplePoses(this._webcamCanvas.domElement, this.imageScaleFactor, flipHorizontal, outputStride, maxPoseDetections);
const pose = poses[0];
this._estimating = false;
this.pose = pose;
if(this.pose){
const _tmp: vec2 = [NaN, NaN];
//update all keypoints positions, and ease them by parameter
for (let i= 0; i<keypointParts.length; i++) {
const key: string = keypointParts[i];
const position = this.computePartPosition(key);
const lastPosition = this.__easedKeypointMap[key];
if (lastPosition && !isNaN(lastPosition[0]) && !isNaN(lastPosition[1])) {
const easedDifference = scale(sub(position, lastPosition, _tmp), this.keypointEase, _tmp);
add(lastPosition, easedDifference, lastPosition);
} else {
this.__easedKeypointMap[key] = position;
}
}
if(this.contentElement){
//the source coordinate from webcam (likely 640x480)
const partPosition = this.getPartPosition(this.bodyPart);
//calculate the position projected to the target,
//but before any amplification has been computed
copy(partPosition, this.preamplifiedTargetPosition);
this.projectPosition(this.preamplifiedTargetPosition);
const distanceFromCenter = sub(partPosition, this.sourceCenter);
const amplifiedDistance = scale(distanceFromCenter, this.amplification);
//update partPosition to being the amplified position still in source coordinates
add(this.sourceCenter, amplifiedDistance, this.__lastSourcePosition);
add(this.sourceCenter, amplifiedDistance, this._lastFoundTargetPosition);
//set the projected position
this.projectPosition(this._lastFoundTargetPosition);
if (!this.disableClamp) {
const dims = getElementDimensions(this.contentElement, _tmpContentDims)
this._lastFoundTargetPosition[0] = clamp(this._lastFoundTargetPosition[0], 0, dims[0]);
this._lastFoundTargetPosition[1] = clamp(this._lastFoundTargetPosition[1], 0, dims[1]);
}
}
this._lastFoundPosition = this.getPartPositionNormalized(this.bodyPart);
}
this._dispatchTick();
}
/**
* Returns an object of the project positions for every part
* @param keypoints optionally provide a list of bodyPart keys to project, defaults to all
* @param targetElement optionally project an Element to project coordinates too, defaults to target
*/
public getAllPositionsProjected(keypoints: string[]= keypointParts, targetElement: Element= this.contentElement) {
const [ width, height ] = getElementDimensions(targetElement);
return keypoints.reduce((mem: any, part: string) => {
if(!mem[part]) {
mem[part] = transformCameraPoints(640, 480, width, height, [this.getPartPosition(part)])[0];
}
return mem;
}, {});
}
/**
* render a crosshair of the input's center calibration point
* @param ctx
* @param style
* @param lineWidth
* @param radius
* @param crossLength
*/
public renderCenter(ctx: CanvasRenderingContext2D, style: string= 'black', lineWidth: number= 3, radius: number= 16, crossLength: number= 8) {
if(!this.isReady) {
return;
}
copy(this.sourceCenter, _tmpVec2);
const center = this.projectPosition(_tmpVec2, ctx.canvas);
let x = 0;
let y = 0;
ctx.strokeStyle = style;
ctx.lineWidth = lineWidth;
// cross-hair scope design
// ctx.beginPath();
// ctx.arc(center[0], center[1], radius, 0, Math.PI * 2);
// x = center[0] + radius;
// y = center[1];
// ctx.moveTo(x, y);
// ctx.lineTo(x + crossLength, y);
// x = center[0] - radius;
// ctx.moveTo(x - crossLength, y);
// ctx.lineTo(x, y);
// x = center[0];
// y = center[1] - radius;
// ctx.moveTo(x, y);
// ctx.lineTo(x, y - crossLength);
// y = center[1] + radius;
// ctx.moveTo(x, y);
// ctx.lineTo(x, y + crossLength);
ctx.beginPath();
ctx.moveTo(center[0] - radius, center[1]);
ctx.lineTo(center[0] + radius, center[1]);
ctx.moveTo(center[0], center[1] - radius);
ctx.lineTo(center[0], center[1] + radius);
ctx.stroke();
}
public renderCursor(ctx: CanvasRenderingContext2D, style='blue') {
if (!this.isReady) {
return;
}
const { __lastSourcePosition:source } = this;
const [x1, y1] = this.projectPosition(this.getPartPosition(this.bodyPart), ctx.canvas);
const [x2, y2] = this.projectPosition(source, ctx.canvas);
ctx.strokeStyle = ctx.fillStyle = style;
//line connecting source dot to amplified dot
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
//circle representing cursor
ctx.beginPath();
ctx.arc(x2, y2, 16, 0, Math.PI * 2);
ctx.fill();
}
/**
* render the pose data to a canvas to show current tracked skeleton
* @param ctx
* @param style
* @param radius
*/
public renderInputData(ctx: CanvasRenderingContext2D, style: string= 'rgba(96,96,96, 0.85)', radius: number= 4) {
if (!this.isReady) {
return;
}
const segments: string[][] = [
['nose'],
['leftShoulder', 'rightShoulder', 'rightHip', 'leftHip', 'leftShoulder'],
['leftShoulder', 'leftElbow', 'leftWrist'],
['rightShoulder', 'rightElbow', 'rightWrist']
];
ctx.strokeStyle = ctx.fillStyle = style;
const currentPosition: vec2 = [NaN, NaN];
const partsRendered: string[] = [];
segments.forEach((segment: string[]) => {
if(segment.length > 1){
ctx.beginPath();
segment.forEach((bodyPart: string, i: number) => {
this.getPartPosition(bodyPart, currentPosition);
this.projectPosition(currentPosition, ctx.canvas);
if (i === 0) {
ctx.moveTo(currentPosition[0], currentPosition[1]);
} else {
ctx.lineTo(currentPosition[0], currentPosition[1]);
}
});
ctx.stroke();
}
segment.forEach((bodyPart: string) => {
if(partsRendered.indexOf(bodyPart) !== -1){
return;
}
this.getPartPosition(bodyPart, currentPosition);
this.projectPosition(currentPosition, ctx.canvas);
ctx.beginPath();
ctx.arc(currentPosition[0], currentPosition[1], radius, 0, Math.PI * 2);
ctx.fill();
partsRendered.push(bodyPart);
});
});
}
resetCenter() {
this.sourceCenter = [
this.canvas.width / 2,
this.canvas.height / 2
];
}
setCenterToCurrentPosition() {
this.sourceCenter = this.getPartPosition(this.bodyPart);
}
stop(){
this._loop.stop();
}
_didRender(props: any, changed: any, prev: any) {
if(changed && changed.hasOwnProperty('controls') && changed.controls) {
setTimeout(()=> {
const controls = this.shadowRoot.querySelector('acc-pose-input-calibration');
if(controls && canFocusHeader(controls)) {
controls.focusHeader();
}
}, 16);
}
return super._didRender(props, changed, prev);
}
_render({ amplification, controls, help, imageScaleFactor, part, smoothing }:any){
let isDark = false;
//calculate if a dark background is set by computing the color and seeing if its average color is more than half way
const computed = computeStyleResult(this.shadowRoot, 'color', backgroundColor);
if(computed) {
const color = cssColorToArray(computed);
if(color) {
isDark = ((color[0] + color[1] + color[2]) / 3) < 128;
}
}
const postFix = isDark ? '-dark' : '';
return html`
<style>
</style>
<acc-pose-input-calibration
closable
tabIndex="0"
on-center=${()=> this.setCenterToCurrentPosition()}
on-resetcenter=${()=> this.resetCenter()}
amplification="${amplification}"
imageScaleFactor="${imageScaleFactor}"
smoothing="${smoothing}"
parts="${selectablePartsDisplay}"
part="${keypointPartsMap[part]}"
open?=${controls}
fullscreen
on-change=${(evt:any)=>{
const findPartId = () => {
for(let prop in keypointPartsMap) {
if(keypointPartsMap[prop] === evt.detail.part) {
return prop;
}
}
}
this.amplification = evt.detail.amplification;
this.bodyPart = findPartId(); //evt.detail.part;
this.imageScaleFactor = evt.detail.imageScaleFactor;
this.smoothing = evt.detail.smoothing;
this._dispatchChange();
}}
on-help=${()=> this.help = true}
on-close=${()=>{ console.log("POSE INPUT CONTROLS ON CLOSE"); this.controls = false; }}
on-close-click=${()=>this.controls = false}>
</acc-pose-input-calibration>
<acc-tutorial
dark?=${isDark}
closebutton="Back to settings"
aria-live="polite"
aria-atomic="true"
on-close=${() => this.help = false}
open?=${help}>
<acc-slide
video="//storage.googleapis.com/acc-components/camera-tutorial-01${postFix}.mp4"
alt="Animation demonstrating moving your nose to control the cursor."
caption="Here's how to use your camera. A blue dot will follow the position of your nose."></acc-slide>
<acc-slide
video="//storage.googleapis.com/acc-components/camera-tutorial-02${postFix}.mp4"
alt="Animation showing how to use the slider to amplify your cursors movement."
caption="Use the slider to help reach all parts of the screen. This works best if you're centered."></acc-slide>
<acc-slide
video="//storage.googleapis.com/acc-components/camera-tutorial-03${postFix}.mp4"
alt="Animation demonstrating how the centerpoint works and how to move it."
caption="Or, you can move the centerpoint to you."></acc-slide>
<acc-slide
video="//storage.googleapis.com/acc-components/camera-tutorial-04${postFix}.mp4"
alt="Animation of using the pop up button to select a different body part to track."
caption="You can also track different parts of your body, like your wrist or shoulder."></acc-slide>
</acc-tutorial>
`;
}
// _shouldRender(props: any, changed: any, prev: any) {
// if(changed && (changed.part || changed.amplification)) {
// return false;
// }
// return super._shouldRender(props, changed, prev);
// }
}
customElements.define('acc-pose-input', PoseInputElement); | the_stack |
import {
EVENT_ACTION,
PRESENCE_ACTION,
RECORD_ACTION,
RPC_ACTION,
TOPIC,
Message,
ALL_ACTIONS,
ACTIONS
} from '../constants'
import * as Ajv from 'ajv'
import {
getUid,
reverseMap,
deepFreeze,
} from '../utils/utils'
import { jifSchema } from './jif-schema'
import { JifMessage, DeepstreamServices, EVENT } from '@deepstream/types'
const ajv = new Ajv()
const validateJIF: any = ajv.compile(jifSchema)
type JifInMessage = any
// jif -> message lookup table
function getJifToMsg () {
const JIF_TO_MSG: any = {}
JIF_TO_MSG.event = {}
JIF_TO_MSG.event.emit = (msg: JifInMessage) => ({
done: true,
message: {
topic: TOPIC.EVENT,
action: EVENT_ACTION.EMIT,
name: msg.eventName,
parsedData: msg.data,
},
})
JIF_TO_MSG.rpc = {}
JIF_TO_MSG.rpc.make = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.RPC,
action: RPC_ACTION.REQUEST,
name: msg.rpcName,
correlationId: getUid(),
parsedData: msg.data,
},
})
JIF_TO_MSG.record = {}
JIF_TO_MSG.record.read = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.RECORD,
action: RECORD_ACTION.READ,
name: msg.recordName,
},
})
JIF_TO_MSG.record.write = (msg: JifInMessage) => (
msg.path ? JIF_TO_MSG.record.patch(msg) : JIF_TO_MSG.record.update(msg)
)
JIF_TO_MSG.record.patch = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.RECORD,
action: RECORD_ACTION.CREATEANDPATCH,
name: msg.recordName,
version: msg.version || -1,
path: msg.path,
parsedData: msg.data,
isWriteAck: true,
correlationId: 0
},
})
JIF_TO_MSG.record.update = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.RECORD,
action: RECORD_ACTION.CREATEANDUPDATE,
name: msg.recordName,
version: msg.version || -1,
parsedData: msg.data,
isWriteAck: true,
correlationId: 0
},
})
JIF_TO_MSG.record.head = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.RECORD,
action: RECORD_ACTION.HEAD,
name: msg.recordName,
},
})
JIF_TO_MSG.record.delete = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.RECORD,
action: RECORD_ACTION.DELETE,
name: msg.recordName,
},
}),
JIF_TO_MSG.record.notify = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.RECORD,
action: RECORD_ACTION.NOTIFY,
names: msg.recordNames
},
})
JIF_TO_MSG.list = {}
JIF_TO_MSG.list.read = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.RECORD,
action: RECORD_ACTION.READ,
name: msg.listName,
},
})
JIF_TO_MSG.list.write = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.RECORD,
action: RECORD_ACTION.CREATEANDUPDATE,
name: msg.listName,
version: msg.version || -1,
parsedData: msg.data,
isWriteAck: true,
correlationId: 0
},
})
JIF_TO_MSG.list.delete = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.RECORD,
action: RECORD_ACTION.DELETE,
name: msg.listName,
},
})
JIF_TO_MSG.presence = {}
JIF_TO_MSG.presence.query = (msg: JifInMessage) => (
msg.names ? JIF_TO_MSG.presence.queryUsers(msg) : JIF_TO_MSG.presence.queryAll(msg)
)
JIF_TO_MSG.presence.queryAll = () => ({
done: false,
message: {
topic: TOPIC.PRESENCE,
action: PRESENCE_ACTION.QUERY_ALL,
},
})
JIF_TO_MSG.presence.queryUsers = (msg: JifInMessage) => ({
done: false,
message: {
topic: TOPIC.PRESENCE,
action: PRESENCE_ACTION.QUERY,
names: msg.names,
},
})
return deepFreeze(JIF_TO_MSG)
}
// message type enumeration
const TYPE = { ACK: 'A', NORMAL: 'N' }
function getMsgToJif () {
// message -> jif lookup table
const MSG_TO_JIF: any = {}
MSG_TO_JIF[TOPIC.RPC] = {}
MSG_TO_JIF[TOPIC.RPC][RPC_ACTION.RESPONSE] = {}
MSG_TO_JIF[TOPIC.RPC][RPC_ACTION.RESPONSE][TYPE.NORMAL] = (message: Message) => ({
done: true,
message: {
data: message.parsedData,
success: true,
},
})
MSG_TO_JIF[TOPIC.RPC][RPC_ACTION.REQUEST_ERROR] = {}
MSG_TO_JIF[TOPIC.RPC][RPC_ACTION.REQUEST_ERROR][TYPE.NORMAL] = (message: Message) => ({
done: true,
message: {
errorTopic: 'rpc',
error: message.parsedData,
success: false,
},
})
MSG_TO_JIF[TOPIC.RPC][RPC_ACTION.ACCEPT] = {}
MSG_TO_JIF[TOPIC.RPC][RPC_ACTION.ACCEPT][TYPE.NORMAL] = () => ({ done: false })
MSG_TO_JIF[TOPIC.RPC][RPC_ACTION.REQUEST] = {}
MSG_TO_JIF[TOPIC.RPC][RPC_ACTION.REQUEST][TYPE.ACK] = () => ({ done: false })
MSG_TO_JIF[TOPIC.RECORD] = {}
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.READ_RESPONSE] = {}
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.READ_RESPONSE][TYPE.NORMAL] = (message: Message) => ({
done: true,
message: {
version: message.version,
data: message.parsedData,
success: true,
},
})
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.WRITE_ACKNOWLEDGEMENT] = {}
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.WRITE_ACKNOWLEDGEMENT][TYPE.NORMAL] = (message: Message) => ({
done: true,
message: {
success: true,
},
})
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.DELETE] = {}
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.DELETE][TYPE.NORMAL] = () => ({
done: true,
message: {
success: true,
},
})
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.DELETE_SUCCESS] = {}
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.DELETE_SUCCESS][TYPE.NORMAL] = () => ({
done: true,
message: {
success: true,
},
})
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.NOTIFY] = {}
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.NOTIFY][TYPE.ACK] = (message: Message) => ({
done: true,
message: {
success: true,
},
})
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.HEAD_RESPONSE] = {}
MSG_TO_JIF[TOPIC.RECORD][RECORD_ACTION.HEAD_RESPONSE][TYPE.NORMAL] = (message: Message) => ({
done: true,
message: {
version: message.version,
success: true,
},
})
MSG_TO_JIF[TOPIC.PRESENCE] = {}
MSG_TO_JIF[TOPIC.PRESENCE][PRESENCE_ACTION.QUERY_ALL_RESPONSE] = {}
MSG_TO_JIF[TOPIC.PRESENCE][PRESENCE_ACTION.QUERY_ALL_RESPONSE][TYPE.NORMAL] = (message: Message) => ({
done: true,
message: {
users: message.names,
success: true,
},
})
MSG_TO_JIF[TOPIC.PRESENCE][PRESENCE_ACTION.QUERY_RESPONSE] = {}
MSG_TO_JIF[TOPIC.PRESENCE][PRESENCE_ACTION.QUERY_RESPONSE][TYPE.NORMAL] = (message: Message) => ({
done: true,
message: {
users: message.parsedData,
success: true,
},
})
return deepFreeze(MSG_TO_JIF)
}
export default class JIFHandler {
private JIF_TO_MSG = getJifToMsg()
private MSG_TO_JIF = getMsgToJif()
private topicToKey = reverseMap(TOPIC)
constructor (private services: DeepstreamServices) {}
/*
* Validate and convert a JIF message to a deepstream message
*/
public fromJIF (jifMessage: JifInMessage) {
if (!validateJIF(jifMessage)) {
let error = validateJIF.errors[0]
switch (error.keyword) {
// case 'additionalProperties':
// error = `property '${error.params.additionalProperty}'
// not permitted for topic '${jifMessage.topic}'`
// break
case 'required':
error = `property '${error.params.missingProperty}' is required for topic '${jifMessage.topic}'`
break
case 'type':
case 'minLength':
error = `property '${error.dataPath}' ${error.message}`
break
// case 'const':
// error = `value for property '${error.dataPath}' not valid for topic '${jifMessage.topic}'`
// break
default:
error = null
}
return {
success: false,
error,
done: true,
}
}
const result = this.JIF_TO_MSG[jifMessage.topic][jifMessage.action](jifMessage)
result.success = true
return result
}
/*
* Convert a deepstream response/ack message to a JIF message response
* @param {Object} message deepstream message
*
* @returns {Object} {
* {Object} message jif message
* {Boolean} done false iff message should await another result/acknowledgement
* }
*/
public toJIF (message: Message): JifMessage {
let type
if (message.isAck) {
type = TYPE.ACK
} else {
type = TYPE.NORMAL
}
if (message.isError) {
return this.errorToJIF(message, message.action)
}
return this.MSG_TO_JIF[message.topic][message.action][type](message)
}
/*
* Convert a deepstream error message to a JIF message response
*/
public errorToJIF (message: Message, event: ALL_ACTIONS | string) {
// convert topic enum to human-readable key
const topicKey = this.topicToKey[message.topic]
const result: any = {
errorTopic: topicKey && topicKey.toLowerCase(),
errorEvent: event,
success: false,
}
if (event === ACTIONS[message.topic].MESSAGE_DENIED) {
result.action = message.originalAction as number
result.error = `Message denied. Action "${ACTIONS[message.topic][message.originalAction!]}" is not permitted.`
} else if (message.topic === TOPIC.RECORD && event === RECORD_ACTION.VERSION_EXISTS) {
result.error = `Record update failed. Version ${message.version} exists for record "${message.name}".`
result.currentVersion = message.version
result.currentData = message.parsedData
} else if (message.topic === TOPIC.RECORD && event === RECORD_ACTION.INVALID_VERSION) {
result.error = `Record update failed. Version ${message.version} is not valid for record "${message.name}".`
result.currentVersion = message.version
result.currentData = message.parsedData
} else if (message.topic === TOPIC.RECORD && event === RECORD_ACTION.RECORD_NOT_FOUND) {
result.error = `Record read failed. Record "${message.name}" could not be found.`
result.errorEvent = message.action
} else if (message.topic === TOPIC.RPC && event === RPC_ACTION.NO_RPC_PROVIDER) {
result.error = `No provider was available to handle the RPC "${message.name}".`
// message.correlationId = data[1]
} else if (message.topic === TOPIC.RPC && message.action === RPC_ACTION.RESPONSE_TIMEOUT) {
result.error = 'The RPC response timeout was exceeded by the provider.'
} else {
this.services.logger.warn(
EVENT.INFO,
`Unhandled request error occurred: ${TOPIC[message.topic]} ${event} ${JSON.stringify(message)}`,
{ message }
)
result.error = `An error occurred: ${RPC_ACTION[event as number]}.`
result.errorParams = message.name
}
return {
message: result,
done: true,
}
}
} | the_stack |
import { StateParams } from '@uirouter/core';
import _ = require('lodash');
import { ApiService } from '../../services/api.service';
import ApiHeaderService from '../../services/apiHeader.service';
import CategoryService from '../../services/category.service';
import ClientRegistrationProviderService from '../../services/clientRegistrationProvider.service';
import ConsoleSettingsService from '../../services/consoleSettings.service';
import CustomUserFieldsService from '../../services/custom-user-fields.service';
import DashboardService from '../../services/dashboard.service';
import DictionaryService from '../../services/dictionary.service';
import { DocumentationQuery, DocumentationService } from '../../services/documentation.service';
import EnvironmentService from '../../services/environment.service';
import FetcherService from '../../services/fetcher.service';
import GroupService from '../../services/group.service';
import IdentityProviderService from '../../services/identityProvider.service';
import MetadataService from '../../services/metadata.service';
import PortalSettingsService from '../../services/portalSettings.service';
import QualityRuleService from '../../services/qualityRule.service';
import RoleService from '../../services/role.service';
import TagService from '../../services/tag.service';
import TopApiService from '../../services/top-api.service';
export default configurationRouterConfig;
function configurationRouterConfig($stateProvider) {
'ngInject';
$stateProvider
.state('management.settings', {
url: '/settings',
component: 'settings',
data: {
menu: {
label: 'Settings',
icon: 'settings',
firstLevel: true,
order: 50,
},
perms: {
only: [
// hack only read permissions is necessary but READ is also allowed for API_PUBLISHER
'environment-category-r',
'environment-metadata-r',
'environment-top_apis-r',
'environment-group-r',
'environment-tag-c',
'environment-tenant-c',
'environment-group-c',
'environment-documentation-c',
'environment-tag-u',
'environment-tenant-u',
'environment-group-u',
'environment-documentation-u',
'environment-tag-d',
'environment-tenant-d',
'environment-group-d',
'environment-documentation-d',
'environment-api_header-r',
],
},
},
})
.state('management.settings.categories', {
url: '/categories',
component: 'categories',
resolve: {
categories: (CategoryService: CategoryService) => CategoryService.list().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-categories',
},
perms: {
only: ['environment-category-r'],
},
},
})
.state('management.settings.categorynew', {
url: '/categories/new',
component: 'category',
resolve: {
pages: (DocumentationService: DocumentationService) => {
const q = new DocumentationQuery();
q.type = 'MARKDOWN';
q.published = true;
return DocumentationService.search(q).then((response) => response.data);
},
},
data: {
menu: null,
docs: {
page: 'management-configuration-categories',
},
perms: {
only: ['environment-category-c'],
},
},
})
.state('management.settings.category', {
url: '/categories/:categoryId',
component: 'category',
resolve: {
category: (CategoryService: CategoryService, $stateParams) =>
CategoryService.get($stateParams.categoryId).then((response) => response.data),
categoryApis: (ApiService: ApiService, $stateParams) => ApiService.list($stateParams.categoryId).then((response) => response.data),
pages: (DocumentationService: DocumentationService) => {
const q = new DocumentationQuery();
q.type = 'MARKDOWN';
q.published = true;
return DocumentationService.search(q).then((response) => response.data);
},
},
data: {
menu: null,
docs: {
page: 'management-configuration-categories',
},
perms: {
only: ['environment-category-u', 'environment-category-d'],
},
},
})
.state('management.settings.tags', {
url: '/tags',
component: 'moved',
resolve: {
destinationName: () => 'Organization settings > Tags',
permissions: () => ['organization-tag-r'],
goTo: () => 'organization.settings.tags',
destinationIcon: () => 'settings_applications',
},
data: {
menu: null,
docs: {
page: 'management-configuration-sharding-tags',
},
perms: {
only: ['environment-tag-r'],
},
},
})
.state('management.settings.tenants', {
url: '/tenants',
component: 'moved',
resolve: {
destinationName: () => 'Organization settings > Tenants',
permissions: () => ['organization-tenant-r'],
goTo: () => 'organization.settings.tenants',
destinationIcon: () => 'settings_applications',
},
data: {
menu: null,
docs: {
page: 'management-configuration-tenants',
},
perms: {
only: ['environment-tenant-r'],
},
},
})
.state('management.settings.groups', {
abstract: true,
url: '/groups',
})
.state('management.settings.groups.list', {
url: '/',
component: 'groups',
resolve: {
groups: (GroupService: GroupService) => GroupService.list().then((response) => _.filter(response.data, 'manageable')),
},
data: {
menu: null,
docs: {
page: 'management-configuration-groups',
},
perms: {
only: ['environment-group-r'],
},
},
})
.state('management.settings.groups.create', {
url: '/new',
component: 'group',
resolve: {
tags: (TagService: TagService) => TagService.list().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-group',
},
perms: {
only: ['environment-group-r'],
},
},
})
.state('management.settings.groups.group', {
url: '/:groupId',
component: 'group',
resolve: {
group: (GroupService: GroupService, $stateParams) => GroupService.get($stateParams.groupId).then((response) => response.data),
apiRoles: (RoleService: RoleService) =>
RoleService.list('API').then((roles) => [{ scope: 'API', name: '', system: false }].concat(roles)),
applicationRoles: (RoleService: RoleService) =>
RoleService.list('APPLICATION').then((roles) => [{ scope: 'APPLICATION', name: '', system: false }].concat(roles)),
invitations: (GroupService: GroupService, $stateParams) =>
GroupService.getInvitations($stateParams.groupId).then((response) => response.data),
tags: (TagService: TagService) => TagService.list().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-group',
},
perms: {
only: ['environment-group-r'],
},
},
})
.state('management.settings.documentation', {
url: '/pages?:parent',
component: 'documentationManagement',
resolve: {
pages: (DocumentationService: DocumentationService, $stateParams: StateParams) => {
const q = new DocumentationQuery();
if ($stateParams.parent && '' !== $stateParams.parent) {
q.parent = $stateParams.parent;
} else {
q.root = true;
}
return DocumentationService.search(q).then((response) => response.data);
},
folders: (DocumentationService: DocumentationService) => {
const q = new DocumentationQuery();
q.type = 'FOLDER';
return DocumentationService.search(q).then((response) => response.data);
},
systemFolders: (DocumentationService: DocumentationService) => {
const q = new DocumentationQuery();
q.type = 'SYSTEM_FOLDER';
return DocumentationService.search(q).then((response) => response.data);
},
},
data: {
menu: null,
docs: {
page: 'management-configuration-portal-pages',
},
perms: {
only: ['environment-documentation-r'],
},
},
params: {
parent: {
type: 'string',
value: '',
squash: false,
},
},
})
.state('management.settings.newdocumentation', {
url: '/pages/new?type&:parent',
component: 'newPage',
resolve: {
resolvedFetchers: (FetcherService: FetcherService) => {
return FetcherService.list().then((response) => {
return response.data;
});
},
pagesToLink: (DocumentationService: DocumentationService, $stateParams: StateParams) => {
if ($stateParams.type === 'MARKDOWN' || $stateParams.type === 'MARKDOWN_TEMPLATE') {
const q = new DocumentationQuery();
q.homepage = false;
q.published = true;
return DocumentationService.search(q).then((response) =>
response.data.filter(
(page) =>
page.type.toUpperCase() === 'MARKDOWN' ||
page.type.toUpperCase() === 'SWAGGER' ||
page.type.toUpperCase() === 'ASCIIDOC' ||
page.type.toUpperCase() === 'ASYNCAPI',
),
);
}
},
folders: (DocumentationService: DocumentationService) => {
const q = new DocumentationQuery();
q.type = 'FOLDER';
return DocumentationService.search(q).then((response) => response.data);
},
systemFolders: (DocumentationService: DocumentationService) => {
const q = new DocumentationQuery();
q.type = 'SYSTEM_FOLDER';
return DocumentationService.search(q).then((response) => response.data);
},
pageResources: (DocumentationService: DocumentationService, $stateParams: StateParams) => {
if ($stateParams.type === 'LINK') {
const q = new DocumentationQuery();
return DocumentationService.search(q).then((response) => response.data);
}
},
categoryResources: (CategoryService: CategoryService, $stateParams: StateParams) => {
if ($stateParams.type === 'LINK') {
return CategoryService.list().then((response) => response.data);
}
},
},
data: {
menu: null,
docs: {
page: 'management-configuration-portal-pages',
},
perms: {
only: ['environment-documentation-c'],
},
},
params: {
type: {
type: 'string',
value: '',
squash: false,
},
parent: {
type: 'string',
value: '',
squash: false,
},
},
})
.state('management.settings.importdocumentation', {
url: '/pages/import',
component: 'importPages',
resolve: {
resolvedFetchers: (FetcherService: FetcherService) => {
return FetcherService.list(true).then((response) => {
return response.data;
});
},
resolvedRootPage: (DocumentationService: DocumentationService) => {
const q = new DocumentationQuery();
q.type = 'ROOT';
return DocumentationService.search(q).then((response) => (response.data && response.data.length > 0 ? response.data[0] : null));
},
},
data: {
menu: null,
docs: {
page: 'management-configuration-portal-pages',
},
perms: {
only: ['environment-documentation-c'],
},
},
})
.state('management.settings.editdocumentation', {
url: '/pages/:pageId?:tab&type',
component: 'editPage',
resolve: {
resolvedPage: (DocumentationService: DocumentationService, $stateParams: StateParams) =>
DocumentationService.get(null, $stateParams.pageId).then((response) => response.data),
resolvedGroups: (GroupService: GroupService) => {
return GroupService.list().then((response) => {
return response.data;
});
},
resolvedFetchers: (FetcherService: FetcherService) => {
return FetcherService.list().then((response) => {
return response.data;
});
},
pagesToLink: (DocumentationService: DocumentationService, $stateParams: StateParams) => {
if ($stateParams.type === 'MARKDOWN' || $stateParams.type === 'MARKDOWN_TEMPLATE') {
const q = new DocumentationQuery();
q.homepage = false;
q.published = true;
return DocumentationService.search(q).then((response) =>
response.data.filter(
(page) =>
(page.type.toUpperCase() === 'MARKDOWN' ||
page.type.toUpperCase() === 'SWAGGER' ||
page.type.toUpperCase() === 'ASCIIDOC' ||
page.type.toUpperCase() === 'ASYNCAPI') &&
page.id !== $stateParams.pageId,
),
);
}
},
folders: (DocumentationService: DocumentationService) => {
const q = new DocumentationQuery();
q.type = 'FOLDER';
return DocumentationService.search(q).then((response) => response.data);
},
systemFolders: (DocumentationService: DocumentationService) => {
const q = new DocumentationQuery();
q.type = 'SYSTEM_FOLDER';
return DocumentationService.search(q).then((response) => response.data);
},
pageResources: (DocumentationService: DocumentationService, $stateParams: StateParams) => {
if ($stateParams.type === 'LINK') {
const q = new DocumentationQuery();
return DocumentationService.search(q).then((response) => response.data);
}
},
categoryResources: (CategoryService: CategoryService, $stateParams: StateParams) => {
if ($stateParams.type === 'LINK') {
return CategoryService.list().then((response) => response.data);
}
},
attachedResources: (DocumentationService: DocumentationService, $stateParams: StateParams) => {
if ($stateParams.type === 'MARKDOWN' || $stateParams.type === 'ASCIIDOC' || $stateParams.type === 'ASYNCAPI') {
return DocumentationService.getMedia($stateParams.pageId, null).then((response) => response.data);
}
},
},
data: {
menu: null,
docs: {
page: 'management-configuration-portal-pages',
},
perms: {
only: ['environment-documentation-u'],
},
},
params: {
pageId: {
type: 'string',
value: '',
squash: false,
},
},
})
.state('management.settings.metadata', {
url: '/metadata',
component: 'metadata',
resolve: {
metadata: (MetadataService: MetadataService) => MetadataService.list().then((response) => response.data),
metadataFormats: (MetadataService: MetadataService) => MetadataService.listFormats(),
},
data: {
menu: null,
docs: {
page: 'management-configuration-metadata',
},
perms: {
only: ['environment-metadata-r'],
},
},
})
.state('management.settings.customUserFields', {
url: '/custom-user-fields',
component: 'customUserFields',
resolve: {
fields: (CustomUserFieldsService: CustomUserFieldsService) => CustomUserFieldsService.list().then((response) => response.data),
fieldFormats: (CustomUserFieldsService: CustomUserFieldsService) => CustomUserFieldsService.listFormats(),
predefinedKeys: (CustomUserFieldsService: CustomUserFieldsService) => CustomUserFieldsService.listPredefinedKeys(),
},
data: {
menu: null,
docs: {
page: 'management-configuration-custom-user-fields',
},
perms: {
only: ['organization-custom_user_fields-r'],
},
},
})
.state('management.settings.theme', {
url: '/theme',
component: 'theme',
resolve: {},
data: {
menu: null,
docs: {
page: 'management-configuration-portal-theme',
},
perms: {
only: ['environment-theme-r'],
},
},
})
.state('management.settings.top-apis', {
url: '/top-apis',
component: 'topApis',
resolve: {
topApis: (TopApiService: TopApiService) => TopApiService.list().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-top_apis',
},
perms: {
only: ['environment-top_apis-r'],
},
},
})
.state('management.settings.portal', {
url: '/portal',
component: 'portalSettings',
resolve: {
tags: (TagService: TagService) => TagService.list().then((response) => response.data),
settings: (PortalSettingsService: PortalSettingsService) => PortalSettingsService.get().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-portal',
},
perms: {
only: ['environment-settings-r'],
},
},
})
.state('management.settings.dictionaries', {
abstract: true,
url: '/dictionaries',
})
.state('management.settings.dictionaries.list', {
url: '/',
component: 'dictionaries',
resolve: {
dictionaries: (DictionaryService: DictionaryService) => DictionaryService.list().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-dictionaries',
},
perms: {
only: ['environment-dictionary-r'],
},
},
})
.state('management.settings.dictionaries.new', {
url: '/new',
component: 'dictionary',
data: {
menu: null,
docs: {
page: 'management-configuration-dictionary',
},
perms: {
only: ['environment-dictionary-c'],
},
},
})
.state('management.settings.dictionaries.dictionary', {
url: '/:dictionaryId',
component: 'dictionary',
resolve: {
dictionary: (DictionaryService: DictionaryService, $stateParams) =>
DictionaryService.get($stateParams.dictionaryId).then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-dictionary',
},
perms: {
only: ['environment-dictionary-c', 'environment-dictionary-r', 'environment-dictionary-u', 'environment-dictionary-d'],
},
},
})
.state('management.settings.analytics', {
url: '/analytics',
component: 'analyticsSettings',
resolve: {
dashboardsPlatform: (DashboardService: DashboardService) => DashboardService.list('PLATFORM').then((response) => response.data),
dashboardsApi: (DashboardService: DashboardService) => DashboardService.list('API').then((response) => response.data),
dashboardsApplication: (DashboardService: DashboardService) =>
DashboardService.list('APPLICATION').then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-analytics',
},
perms: {
only: ['environment-settings-r'],
},
},
})
.state('management.settings.dashboardnew', {
url: '/analytics/dashboard/:type/new',
component: 'dashboard',
data: {
menu: null,
docs: {
page: 'management-configuration-dashboard',
},
perms: {
only: ['environment-dashboard-c'],
},
},
})
.state('management.settings.dashboard', {
url: '/analytics/dashboard/:type/:dashboardId',
component: 'dashboard',
resolve: {
dashboard: (DashboardService: DashboardService, $stateParams) =>
DashboardService.get($stateParams.dashboardId).then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-dashboard',
},
perms: {
only: ['environment-dashboard-u'],
},
},
})
.state('management.settings.apiPortalHeader', {
url: '/apiportalheader',
component: 'configApiPortalHeader',
resolve: {
apiPortalHeaders: (ApiHeaderService: ApiHeaderService) => ApiHeaderService.list().then((response) => response.data),
settings: (PortalSettingsService: PortalSettingsService) => PortalSettingsService.get().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-apiportalheader',
},
perms: {
only: ['environment-api_header-r'],
},
},
})
.state('management.settings.apiQuality', {
url: '/apiquality',
component: 'configApiQuality',
resolve: {
qualityRules: (QualityRuleService: QualityRuleService) => QualityRuleService.list().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-apiquality',
},
perms: {
only: ['environment-settings-r'],
},
},
})
.state('management.settings.qualityRulenew', {
url: '/apiquality/new',
component: 'qualityRule',
data: {
menu: null,
docs: {
page: 'management-configuration-apiquality',
},
perms: {
only: ['environment-quality_rule-c'],
},
},
})
.state('management.settings.qualityRule', {
url: '/apiquality/:qualityRuleId',
component: 'qualityRule',
resolve: {
qualityRule: (QualityRuleService: QualityRuleService, $stateParams) =>
QualityRuleService.get($stateParams.qualityRuleId).then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-apiquality',
},
perms: {
only: ['environment-quality_rule-u'],
},
},
})
.state('management.settings.environment', {
abstract: true,
url: '/environment',
})
.state('management.settings.environment.identityproviders', {
url: '/identity-providers',
component: 'identityProviders',
resolve: {
target: () => 'ENVIRONMENT',
targetId: (Constants) => Constants.org.currentEnv.id,
identityProviders: (IdentityProviderService: IdentityProviderService) =>
IdentityProviderService.list().then((response) => response),
identities: (EnvironmentService: EnvironmentService, Constants) =>
EnvironmentService.listEnvironmentIdentities(Constants.org.currentEnv.id).then((response) => response.data),
settings: (PortalSettingsService: PortalSettingsService) => PortalSettingsService.get().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-identityproviders',
},
perms: {
only: ['environment-identity_provider_activation-r'],
},
},
})
.state('management.settings.api_logging', {
url: '/api_logging',
component: 'apiLogging',
resolve: {
settings: (ConsoleSettingsService: ConsoleSettingsService) => ConsoleSettingsService.get().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-apilogging',
},
perms: {
only: ['organization-settings-r'],
},
},
})
.state('management.settings.clientregistrationproviders', {
abstract: true,
url: '/client-registration',
})
.state('management.settings.clientregistrationproviders.list', {
url: '/',
component: 'clientRegistrationProviders',
resolve: {
clientRegistrationProviders: (ClientRegistrationProviderService: ClientRegistrationProviderService) =>
ClientRegistrationProviderService.list().then((response) => response),
settings: (PortalSettingsService: PortalSettingsService) => PortalSettingsService.get().then((response) => response.data),
},
data: {
menu: null,
docs: {
page: 'management-configuration-client-registration-providers',
},
perms: {
only: ['environment-client_registration_provider-r'],
},
},
})
.state('management.settings.clientregistrationproviders.create', {
url: '/new',
component: 'clientRegistrationProvider',
data: {
menu: null,
docs: {
page: 'management-configuration-client-registration-provider',
},
perms: {
only: ['environment-client_registration_provider-c'],
},
},
})
.state('management.settings.clientregistrationproviders.clientregistrationprovider', {
url: '/:id',
component: 'clientRegistrationProvider',
resolve: {
clientRegistrationProvider: (ClientRegistrationProviderService: ClientRegistrationProviderService, $stateParams) =>
ClientRegistrationProviderService.get($stateParams.id).then((response) => response),
},
data: {
menu: null,
docs: {
page: 'management-configuration-client-registration-provider',
},
perms: {
only: [
'environment-client_registration_provider-r',
'environment-client_registration_provider-u',
'environment-client_registration_provider-d',
],
},
},
});
} | the_stack |
import { fetchAddr, trackMro } from './backUtils';
import { ConstraintSet } from './constraintSet';
import { Constraint, ConstraintType } from './constraintType';
import { Context } from './context';
import { Fraction } from './fraction';
import { ShEnv, ShHeap } from './sharpEnvironments';
import { CodeSource, ShValue, SVAddr, SVType } from './sharpValues';
import {
BoolOpType,
ExpBool,
ExpNum,
ExpNumBop,
ExpNumConst,
ExpShape,
ExpString,
NumBopType,
NumOpType,
NumUopType,
SEType,
ShapeOpType,
StringOpType,
SymbolType,
SymExp,
} from './symExpressions';
// expression with coefficient
export interface CoExpNum<T extends ExpNum> {
exp: T;
coeff: Fraction;
}
// normalized sum of indivisible expressions
export interface NormalExp {
list: CoExpNum<ExpNum>[];
constant: Fraction;
}
function emptyNormalExp(exp: ExpNum): NormalExp {
return {
list: [{ exp, coeff: new Fraction(1, 1) }],
constant: new Fraction(0, 1),
};
}
function mergeCoExpList<T extends ExpNum>(list1: CoExpNum<T>[], list2: CoExpNum<T>[]): CoExpNum<T>[] {
const [mainList, subList] = list1.length >= list2.length ? [list1, list2] : [list2, list1];
const newList = mainList.map((cexp) => ({ ...cexp }));
const leftLen = newList.length;
for (const right of subList) {
let found = false;
for (let i = 0; i < leftLen; i++) {
const left = newList[i];
if (isStructuallyEq(left.exp, right.exp)) {
left.coeff = left.coeff.add(right.coeff);
found = true;
break;
}
}
if (!found) newList.push({ ...right });
}
return newList.filter((n) => n.coeff.up !== 0);
}
// make NormalExp
export function normalizeExpNum(exp: ExpNum): NormalExp {
switch (exp.opType) {
case NumOpType.Const:
return {
list: [],
constant: new Fraction(exp.value, 1),
};
case NumOpType.Symbol:
return emptyNormalExp(exp);
case NumOpType.Uop:
if (exp.uopType === NumUopType.Neg) {
const norm = normalizeExpNum(exp.baseValue);
return {
list: norm.list.map((n) => ({ exp: n.exp, coeff: n.coeff.neg() })),
constant: norm.constant.neg(),
};
}
return emptyNormalExp(exp);
case NumOpType.Bop: {
const left = normalizeExpNum(exp.left);
let right = normalizeExpNum(exp.right);
switch (exp.bopType) {
case NumBopType.Sub:
right = {
list: right.list.map((n) => ({ exp: n.exp, coeff: n.coeff.neg() })),
constant: right.constant.neg(),
};
// eslint-disable-next-line no-fallthrough
case NumBopType.Add:
return {
list: mergeCoExpList(left.list, right.list),
constant: left.constant.add(right.constant),
};
case NumBopType.Mul: {
let newList: CoExpNum<ExpNum>[] = [];
for (const lexp of left.list) {
const tempList = right.list.map((rexp) => ({
exp: ExpNum.bop(NumBopType.Mul, lexp.exp, rexp.exp, exp.source),
coeff: lexp.coeff.mul(rexp.coeff),
}));
newList = mergeCoExpList(newList, tempList);
}
let isZero = true;
if (right.constant.up !== 0) {
const tempList = left.list.map((lexp) => ({
exp: lexp.exp,
coeff: lexp.coeff.mul(right.constant),
}));
newList = mergeCoExpList(newList, tempList);
isZero = false;
}
if (left.constant.up !== 0) {
const tempList = right.list.map((rexp) => ({
exp: rexp.exp,
coeff: rexp.coeff.mul(left.constant),
}));
newList = mergeCoExpList(newList, tempList);
isZero = false;
}
return {
list: newList,
constant: isZero ? new Fraction(0, 1) : left.constant.mul(right.constant),
};
}
case NumBopType.Mod:
if (left.list.length === 0 && right.list.length === 0) {
return {
list: [],
constant: new Fraction(left.constant.toNum() % right.constant.toNum(), 1),
};
}
return emptyNormalExp(
ExpNum.bop(NumBopType.Mod, denormalizeExpNum(left), denormalizeExpNum(right), exp.source)
);
case NumBopType.FloorDiv:
if (left.list.length === 0 && right.list.length === 0 && right.constant.up !== 0) {
return { list: [], constant: left.constant.div(right.constant).floor() };
}
return emptyNormalExp(
ExpNum.bop(NumBopType.FloorDiv, denormalizeExpNum(left), denormalizeExpNum(right), exp.source)
);
case NumBopType.TrueDiv:
if (right.list.length === 0 && right.constant.up !== 0) {
return {
list: left.list.map((c) => ({ exp: c.exp, coeff: c.coeff.div(right.constant) })),
constant: left.constant.div(right.constant),
};
}
return emptyNormalExp(
ExpNum.bop(NumBopType.TrueDiv, denormalizeExpNum(left), denormalizeExpNum(right), exp.source)
);
}
break;
}
default:
return emptyNormalExp(exp);
}
}
export function denormalizeExpNum(nexp: NormalExp): ExpNum {
let left: ExpNum | undefined;
for (const cexp of nexp.list) {
const coeff = cexp.coeff.norm();
if (coeff.down === 1) {
if (coeff.up === 1) {
left = left ? ExpNum.bop(NumBopType.Add, left, cexp.exp, cexp.exp.source) : cexp.exp;
} else {
const right = ExpNum.bop(NumBopType.Mul, cexp.exp, coeff.up, cexp.exp.source);
left = left ? ExpNum.bop(NumBopType.Add, left, right, left.source) : right;
}
} else {
let right: ExpNum;
if (coeff.up === 1) {
right = ExpNum.bop(NumBopType.TrueDiv, cexp.exp, coeff.down, cexp.exp.source);
} else {
right = ExpNum.bop(
NumBopType.TrueDiv,
ExpNum.bop(NumBopType.Mul, cexp.exp, coeff.up, cexp.exp.source),
coeff.down,
cexp.exp.source
);
}
left = left ? ExpNum.bop(NumBopType.Add, left, right, left.source) : right;
}
}
const ncst = nexp.constant.norm();
if (ncst.up === 0) {
return left ? left : ExpNum.fromConst(0, undefined);
}
const cstExp =
ncst.down === 1
? ExpNum.fromConst(ncst.up, undefined)
: ExpNum.bop(NumBopType.TrueDiv, ExpNum.fromConst(ncst.up, undefined), ncst.down, undefined);
return left ? ExpNum.bop(NumBopType.Add, left, cstExp, left.source) : cstExp;
}
export function simplifyString(ctrSet: ConstraintSet, exp: ExpString): ExpString {
switch (exp.opType) {
case StringOpType.Concat: {
const left = simplifyString(ctrSet, exp.left);
const right = simplifyString(ctrSet, exp.right);
if (left.opType === StringOpType.Const && right.opType === StringOpType.Const) {
return ExpString.fromConst(left.value + right.value, exp.source);
}
return ExpString.concat(left, right, exp.source);
}
case StringOpType.Slice: {
const base = simplifyString(ctrSet, exp.baseString);
const start = exp.start ? simplifyNum(ctrSet, exp.start) : undefined;
const end = exp.end ? simplifyNum(ctrSet, exp.end) : undefined;
if (
base.opType === StringOpType.Const &&
(!start || start.opType === NumOpType.Const) &&
(!end || end.opType === NumOpType.Const)
) {
const len = base.value.length;
const startId = start ? (start.value < 0 ? len - start.value : start.value) : 0;
const endId = end ? (end.value < 0 ? len - end.value : end.value) : len;
if (startId <= endId) return ExpString.fromConst(base.value.substring(startId, endId), exp.source);
}
return ExpString.slice(base, start, end, exp.source);
}
case StringOpType.Const:
case StringOpType.Symbol:
return exp;
}
}
export function simplifyBool(ctrSet: ConstraintSet, exp: ExpBool): ExpBool {
switch (exp.opType) {
case BoolOpType.And: {
const left = simplifyBool(ctrSet, exp.left);
const right = simplifyBool(ctrSet, exp.right);
if (left.opType === BoolOpType.Const) {
return left.value ? right : left;
} else if (right.opType === BoolOpType.Const) {
return right.value ? left : right;
}
// do not check immediate. that's not simplifier's job.
return ExpBool.and(left, right, exp.source);
}
case BoolOpType.Or: {
const left = simplifyBool(ctrSet, exp.left);
const right = simplifyBool(ctrSet, exp.right);
if (left.opType === BoolOpType.Const) {
return left.value ? left : right;
} else if (right.opType === BoolOpType.Const) {
return right.value ? right : left;
}
// do not check immediate. that's not simplifier's job.
return ExpBool.or(left, right, exp.source);
}
case BoolOpType.Equal:
case BoolOpType.NotEqual: {
const left = simplifyExp(ctrSet, exp.left);
const right = simplifyExp(ctrSet, exp.right);
if (left.expType === SEType.Num && right.expType === SEType.Num) {
if (left.opType === NumOpType.Const && right.opType === NumOpType.Const) {
return exp.opType === BoolOpType.Equal
? ExpBool.fromConst(left.value === right.value, exp.source)
: ExpBool.fromConst(left.value !== right.value, exp.source);
}
} else if (left.expType === SEType.Bool && right.expType === SEType.Bool) {
if (left.opType === BoolOpType.Const && right.opType === BoolOpType.Const) {
return exp.opType === BoolOpType.Equal
? ExpBool.fromConst(left.value === right.value, exp.source)
: ExpBool.fromConst(left.value !== right.value, exp.source);
}
} else if (left.expType === SEType.String && right.expType === SEType.String) {
if (left.opType === StringOpType.Const && right.opType === StringOpType.Const) {
return exp.opType === BoolOpType.Equal
? ExpBool.fromConst(left.value === right.value, exp.source)
: ExpBool.fromConst(left.value !== right.value, exp.source);
}
}
// do not check immediate. that's not simplifier's job.
return exp.opType === BoolOpType.Equal
? ExpBool.eq(left, right, exp.source)
: ExpBool.neq(left, right, exp.source);
}
case BoolOpType.LessThan:
case BoolOpType.LessThanOrEqual: {
const left = simplifyNum(ctrSet, exp.left);
const right = simplifyNum(ctrSet, exp.right);
if (left.opType === NumOpType.Const && right.opType === NumOpType.Const) {
return exp.opType === BoolOpType.LessThan
? ExpBool.fromConst(left.value < right.value, exp.source)
: ExpBool.fromConst(left.value <= right.value, exp.source);
}
// do not check immediate. that's not simplifier's job.
return exp.opType === BoolOpType.LessThan
? ExpBool.lt(left, right, exp.source)
: ExpBool.lte(left, right, exp.source);
}
case BoolOpType.Not: {
const base = simplifyBool(ctrSet, exp.baseBool);
switch (base.opType) {
case BoolOpType.Equal:
return ExpBool.neq(base.left, base.right, exp.source);
case BoolOpType.NotEqual:
return ExpBool.eq(base.left, base.right, exp.source);
case BoolOpType.Const:
return ExpBool.fromConst(!base.value, exp.source);
case BoolOpType.LessThan:
return ExpBool.lte(base.right, base.left, exp.source);
case BoolOpType.LessThanOrEqual:
return ExpBool.lt(base.right, base.left, exp.source);
case BoolOpType.Not:
return base.baseBool;
default:
return ExpBool.not(base, exp.source);
}
}
case BoolOpType.Symbol: {
const rng = ctrSet.getSymbolRange(exp.symbol);
if (rng && rng.isConst()) {
return ExpBool.fromConst(rng.start !== 0, exp.symbol.source);
}
return exp;
}
default:
return exp;
}
}
export function simplifyNum(ctrSet: ConstraintSet, exp: ExpNum): ExpNum {
switch (exp.opType) {
case NumOpType.Uop: {
const baseValue = simplifyNum(ctrSet, exp.baseValue);
switch (baseValue.opType) {
case NumOpType.Const:
switch (exp.uopType) {
case NumUopType.Neg:
return ExpNum.fromConst(-baseValue.value, exp.source);
case NumUopType.Floor:
return ExpNum.fromConst(Math.floor(baseValue.value), exp.source);
case NumUopType.Ceil:
return ExpNum.fromConst(Math.ceil(baseValue.value), exp.source);
case NumUopType.Abs:
return ExpNum.fromConst(Math.abs(baseValue.value), exp.source);
}
break;
case NumOpType.Uop:
switch (exp.uopType) {
case NumUopType.Ceil:
case NumUopType.Floor:
// if inner value is structually integer, remove ceil and floor
if (isStructuallyInt(baseValue)) {
return baseValue;
}
break;
case NumUopType.Neg:
// double negation
if (baseValue.uopType === NumUopType.Neg) {
return baseValue.baseValue;
}
break;
case NumUopType.Abs:
// cancel double abs
if (baseValue.uopType === NumUopType.Abs) {
return baseValue;
}
break;
}
break;
default:
break;
}
const rng = ctrSet.getCachedRange(baseValue);
if (rng) {
if (rng.isConst()) {
const base = rng.start;
switch (exp.uopType) {
case NumUopType.Neg:
return ExpNum.fromConst(-base, exp.source);
case NumUopType.Floor:
return ExpNum.fromConst(Math.floor(base), exp.source);
case NumUopType.Ceil:
return ExpNum.fromConst(Math.ceil(base), exp.source);
case NumUopType.Abs:
return ExpNum.fromConst(Math.abs(base), exp.source);
}
}
if (exp.uopType === NumUopType.Abs) {
if (rng.gte(0)) {
return baseValue;
} else if (rng.lte(0)) {
return simplifyNum(ctrSet, ExpNum.uop(NumUopType.Neg, baseValue, exp.source));
}
}
}
return ExpNum.uop(exp.uopType, baseValue, exp.source);
}
case NumOpType.Bop: {
const left = simplifyNum(ctrSet, exp.left);
const right = simplifyNum(ctrSet, exp.right);
if (left.opType === NumOpType.Const) {
const leftVal = left.value;
if (leftVal === 0) {
switch (exp.bopType) {
case NumBopType.Add:
return right;
case NumBopType.FloorDiv:
case NumBopType.TrueDiv:
case NumBopType.Mod:
case NumBopType.Mul:
return ExpNum.fromConst(0, exp.source);
case NumBopType.Sub:
break;
}
} else if (leftVal === 1 && exp.bopType === NumBopType.Mul) {
return right;
}
if (right.opType === NumOpType.Const) {
switch (exp.bopType) {
case NumBopType.Add:
return ExpNum.fromConst(leftVal + right.value, exp.source);
case NumBopType.FloorDiv:
return ExpNum.fromConst(Math.floor(leftVal / right.value), exp.source);
case NumBopType.Mod:
return ExpNum.fromConst(leftVal % right.value, exp.source);
case NumBopType.Mul:
return ExpNum.fromConst(leftVal * right.value, exp.source);
case NumBopType.Sub:
return ExpNum.fromConst(leftVal - right.value, exp.source);
case NumBopType.TrueDiv:
return ExpNum.fromConst(leftVal / right.value, exp.source);
}
} else if (right.opType === NumOpType.Bop) {
const rl = right.left;
const rr = right.right;
switch (right.bopType) {
case NumBopType.Add:
if (rl.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Add) {
return ExpNum.bop(NumBopType.Add, leftVal + rl.value, rr, exp.source);
} else if (exp.bopType === NumBopType.Sub) {
return ExpNum.bop(NumBopType.Sub, leftVal - rl.value, rr, exp.source);
} else if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(
NumBopType.Add,
leftVal * rl.value,
ExpNum.bop(NumBopType.Mul, leftVal, rr, exp.source),
exp.source
);
}
}
if (rr.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Add) {
return ExpNum.bop(NumBopType.Add, leftVal + rr.value, rl, exp.source);
} else if (exp.bopType === NumBopType.Sub) {
return ExpNum.bop(NumBopType.Sub, leftVal - rr.value, rl, exp.source);
} else if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(
NumBopType.Add,
ExpNum.bop(NumBopType.Mul, leftVal, rl, exp.source),
leftVal * rr.value,
exp.source
);
}
}
break;
case NumBopType.Sub:
if (rl.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Add) {
return ExpNum.bop(NumBopType.Sub, leftVal + rl.value, rr, exp.source);
} else if (exp.bopType === NumBopType.Sub) {
return ExpNum.bop(NumBopType.Add, leftVal - rl.value, rr, exp.source);
} else if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(
NumBopType.Sub,
leftVal * rl.value,
ExpNum.bop(NumBopType.Mul, leftVal, rr, exp.source),
exp.source
);
}
}
if (rr.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Add) {
return ExpNum.bop(NumBopType.Add, leftVal - rr.value, rl, exp.source);
} else if (exp.bopType === NumBopType.Sub) {
return ExpNum.bop(NumBopType.Sub, leftVal + rr.value, rl, exp.source);
} else if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(
NumBopType.Add,
ExpNum.bop(NumBopType.Mul, leftVal, rl, exp.source),
leftVal * rr.value,
exp.source
);
}
}
break;
case NumBopType.Mul:
if (rl.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(NumBopType.Mul, leftVal * rl.value, rr, exp.source);
} else if (exp.bopType === NumBopType.TrueDiv && rl.value !== 0) {
return ExpNum.bop(NumBopType.TrueDiv, leftVal / rl.value, rr, exp.source);
}
}
if (rr.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(NumBopType.Mul, leftVal * rr.value, rl, exp.source);
} else if (exp.bopType === NumBopType.TrueDiv && rr.value !== 0) {
return ExpNum.bop(NumBopType.TrueDiv, leftVal / rr.value, rl, exp.source);
}
}
break;
case NumBopType.TrueDiv:
if (rl.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(NumBopType.TrueDiv, leftVal * rl.value, rr, exp.source);
}
}
break;
}
}
} else if (right.opType === NumOpType.Const) {
const rightVal = right.value;
if (rightVal === 0) {
switch (exp.bopType) {
case NumBopType.Add:
case NumBopType.Sub:
return left;
case NumBopType.Mul:
return ExpNum.fromConst(0, exp.source);
default:
break;
}
} else if (rightVal === 1) {
switch (exp.bopType) {
case NumBopType.TrueDiv:
return left;
case NumBopType.FloorDiv:
if (isStructuallyInt(left)) {
return left;
}
break;
default:
break;
}
}
if (left.opType === NumOpType.Bop) {
const ll = left.left;
const lr = left.right;
switch (left.bopType) {
case NumBopType.Add:
if (ll.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Add) {
return ExpNum.bop(NumBopType.Add, lr, ll.value + rightVal, exp.source);
} else if (exp.bopType === NumBopType.Sub) {
return ExpNum.bop(NumBopType.Add, lr, ll.value - rightVal, exp.source);
} else if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(
NumBopType.Add,
ll.value * rightVal,
ExpNum.bop(NumBopType.Mul, lr, rightVal, exp.source),
exp.source
);
}
}
if (lr.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Add) {
return ExpNum.bop(NumBopType.Add, ll, lr.value + rightVal, exp.source);
} else if (exp.bopType === NumBopType.Sub) {
return ExpNum.bop(NumBopType.Add, ll, lr.value - rightVal, exp.source);
} else if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(
NumBopType.Add,
ExpNum.bop(NumBopType.Mul, ll, rightVal, exp.source),
lr.value * rightVal,
exp.source
);
}
}
break;
case NumBopType.Sub:
if (ll.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Add) {
return ExpNum.bop(NumBopType.Sub, ll.value + rightVal, lr, exp.source);
} else if (exp.bopType === NumBopType.Sub) {
return ExpNum.bop(NumBopType.Sub, ll.value - rightVal, lr, exp.source);
} else if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(
NumBopType.Sub,
ll.value * rightVal,
ExpNum.bop(NumBopType.Mul, lr, rightVal, exp.source),
exp.source
);
}
}
if (lr.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Add) {
return ExpNum.bop(NumBopType.Add, ll, rightVal - lr.value, exp.source);
} else if (exp.bopType === NumBopType.Sub) {
return ExpNum.bop(NumBopType.Add, ll, -lr.value - rightVal, exp.source);
} else if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(
NumBopType.Sub,
ExpNum.bop(NumBopType.Mul, ll, rightVal, exp.source),
lr.value * rightVal,
exp.source
);
}
}
break;
case NumBopType.Mul:
if (ll.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(NumBopType.Mul, ll.value * rightVal, lr, exp.source);
} else if (exp.bopType === NumBopType.TrueDiv && rightVal !== 0) {
return ExpNum.bop(NumBopType.Mul, ll.value / rightVal, lr, exp.source);
}
}
if (lr.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(NumBopType.Mul, ll, lr.value * rightVal, exp.source);
} else if (exp.bopType === NumBopType.TrueDiv && rightVal !== 0) {
return ExpNum.bop(NumBopType.Mul, ll, lr.value / rightVal, exp.source);
}
}
break;
case NumBopType.TrueDiv:
if (ll.opType === NumOpType.Const) {
if (exp.bopType === NumBopType.Mul) {
return ExpNum.bop(NumBopType.TrueDiv, ll.value * rightVal, lr, exp.source);
}
}
break;
}
}
}
return ExpNum.bop(exp.bopType, left, right, exp.source);
}
case NumOpType.Const:
return exp;
case NumOpType.Index: {
let base = simplifyShape(ctrSet, exp.baseShape);
const idx = simplifyNum(ctrSet, exp.index);
if (idx.opType === NumOpType.Const) {
let doBreak = false;
let index = idx.value;
if (Math.floor(index) !== index) {
return ExpNum.index(base, idx, exp.source);
}
while (!doBreak) {
switch (base.opType) {
case ShapeOpType.Const:
if (0 <= index && index < base.dims.length) {
return simplifyNum(ctrSet, base.dims[index]);
} else {
doBreak = true;
}
break;
case ShapeOpType.Concat:
{
const firstRank = ExpShape.getRank(base.left);
const rankRng = ctrSet.getCachedRange(firstRank);
if (rankRng?.lte(index)) {
// take second
base = base.right;
if (rankRng.isConst()) {
index -= rankRng.start;
} else {
return ExpNum.index(
base,
ExpNum.bop(NumBopType.Sub, idx, firstRank, idx.source),
exp.source
);
}
} else if (rankRng?.gte(index + 1)) {
// take first
base = base.left;
} else {
doBreak = true;
}
}
break;
case ShapeOpType.Set:
{
const axisRng = ctrSet.getCachedRange(base.axis);
if (axisRng) {
if (axisRng.isConst()) {
if (axisRng.start === index) {
return { ...base.dim, source: exp.source };
} else {
base = base.baseShape;
}
} else if (axisRng.contains(index)) {
doBreak = true;
} else {
base = base.baseShape;
}
}
doBreak = true;
}
break;
case ShapeOpType.Slice:
case ShapeOpType.Broadcast:
case ShapeOpType.Symbol:
// TODO: implement it.
doBreak = true;
break;
}
}
}
return ExpNum.index(base, idx, exp.source);
}
case NumOpType.Max: {
const values = exp.values.map((v) => simplifyNum(ctrSet, v));
if (values.length > 0 && values.every((v) => v.opType === NumOpType.Const)) {
let maxVal = (values[0] as ExpNumConst).value;
values.forEach((v) => {
const currVal = (v as ExpNumConst).value;
if (maxVal < currVal) maxVal = currVal;
});
return ExpNum.fromConst(maxVal, exp.source);
}
return ExpNum.max(values, exp.source);
}
case NumOpType.Min: {
const values = exp.values.map((v) => simplifyNum(ctrSet, v));
if (values.length > 0 && values.every((v) => v.opType === NumOpType.Const)) {
let minVal = (values[0] as ExpNumConst).value;
values.forEach((v) => {
const currVal = (v as ExpNumConst).value;
if (minVal > currVal) minVal = currVal;
});
return ExpNum.fromConst(minVal, exp.source);
}
return ExpNum.min(values, exp.source);
}
case NumOpType.Numel: {
const base = simplifyShape(ctrSet, exp.shape);
if (base.opType === ShapeOpType.Const) {
let numel: ExpNum | undefined;
base.dims.forEach((v) => {
if (numel) {
numel = ExpNum.bop(NumBopType.Mul, numel, v, exp.source);
} else {
numel = v;
}
});
// TODO: potential inifinity loop?
if (numel) {
return simplifyNum(ctrSet, numel);
} else {
return ExpNum.fromConst(0, exp.source);
}
} else if (base.opType === ShapeOpType.Concat) {
return simplifyNum(
ctrSet,
ExpNum.bop(
NumBopType.Add,
ExpNum.numel(base.left, exp.source),
ExpNum.numel(base.right, exp.source),
exp.source
)
);
}
return ExpNum.numel(base, exp.source);
}
case NumOpType.Symbol: {
const rng = ctrSet.getSymbolRange(exp.symbol);
if (rng && rng.isConst()) {
return ExpNum.fromConst(rng.start, exp.source);
}
return exp;
}
}
}
export function simplifyShape(ctrSet: ConstraintSet, exp: ExpShape): ExpShape {
switch (exp.opType) {
case ShapeOpType.Broadcast: {
// TODO: implement it.
const left = simplifyShape(ctrSet, exp.left);
const right = simplifyShape(ctrSet, exp.right);
if (left.opType === ShapeOpType.Const && right.opType === ShapeOpType.Const) {
// baseShape has larger rank.
const [baseShape, rightShape] = left.rank < right.rank ? [right, left] : [left, right];
const dims: ExpNum[] = [];
let isSimple = true;
const rankdiff = baseShape.dims.length - rightShape.dims.length;
for (let i = 0; i < baseShape.dims.length; i++) {
if (i < rankdiff) {
dims.push(baseShape.dims[i]);
continue;
}
const dim = ctrSet.selectBroadcastable(baseShape.dims[i], rightShape.dims[i - rankdiff]);
if (!dim) {
isSimple = false;
break;
}
dims.push(dim);
}
if (isSimple) {
return ExpShape.fromConst(baseShape.rank, dims, exp.source);
}
}
return ExpShape.broadcast(left, right, exp.source);
}
case ShapeOpType.Concat: {
const left = simplifyShape(ctrSet, exp.left);
const right = simplifyShape(ctrSet, exp.right);
if (left.opType === ShapeOpType.Const && right.opType === ShapeOpType.Const) {
return ExpShape.fromConst(left.rank + right.rank, [...left.dims, ...right.dims], exp.source);
}
return ExpShape.concat(left, right, exp.source);
}
case ShapeOpType.Set: {
const base = simplifyShape(ctrSet, exp.baseShape);
const axis = simplifyNum(ctrSet, exp.axis);
const dim = simplifyNum(ctrSet, exp.dim);
if (base.opType === ShapeOpType.Const && axis.opType === NumOpType.Const) {
const idx = axis.value;
if (0 <= idx && idx < base.rank) {
const newDims = [...base.dims];
newDims[idx] = dim;
return ExpShape.fromConst(base.rank, newDims, exp.source);
}
}
return ExpShape.setDim(base, axis, dim, exp.source);
}
case ShapeOpType.Slice: {
const base = simplifyShape(ctrSet, exp.baseShape);
const start = exp.start !== undefined ? simplifyNum(ctrSet, exp.start) : undefined;
const end = exp.end !== undefined ? simplifyNum(ctrSet, exp.end) : undefined;
if (base.opType === ShapeOpType.Const) {
const startPos = start === undefined ? 0 : start.opType === NumOpType.Const ? start.value : -1;
const endPos = end === undefined ? base.rank : end.opType === NumOpType.Const ? end.value : -1;
if (
startPos >= 0 &&
endPos >= 0 &&
Math.floor(startPos) === startPos &&
Math.floor(endPos) === endPos
) {
const newDims = base.dims.slice(startPos, endPos);
return ExpShape.fromConst(newDims.length, newDims, exp.source);
}
}
return ExpShape.slice(base, start, end, exp.source);
}
case ShapeOpType.Const: {
const dims = exp.dims.map((num) => simplifyNum(ctrSet, num));
return ExpShape.fromConst(exp.rank, dims, exp.source);
}
case ShapeOpType.Symbol: {
const dims = ctrSet.getCachedShape(exp);
if (dims) return ExpShape.fromConst(dims.length, dims, exp.source);
return exp;
}
}
}
export function simplifyExp(ctrSet: ConstraintSet, exp: SymExp): SymExp {
switch (exp.expType) {
case SEType.String:
return simplifyString(ctrSet, exp);
case SEType.Bool:
return simplifyBool(ctrSet, exp);
case SEType.Num:
return simplifyNum(ctrSet, exp);
case SEType.Shape:
return simplifyShape(ctrSet, exp);
}
}
export function simplifyConstraint(ctrSet: ConstraintSet, ctr: Constraint): Constraint {
switch (ctr.type) {
case ConstraintType.And:
case ConstraintType.Or:
return { ...ctr, left: simplifyConstraint(ctrSet, ctr.left), right: simplifyConstraint(ctrSet, ctr.right) };
case ConstraintType.Equal:
case ConstraintType.NotEqual:
return { ...ctr, left: simplifyExp(ctrSet, ctr.left), right: simplifyExp(ctrSet, ctr.right) };
case ConstraintType.LessThan:
case ConstraintType.LessThanOrEqual:
return { ...ctr, left: simplifyNum(ctrSet, ctr.left), right: simplifyNum(ctrSet, ctr.right) };
case ConstraintType.ExpBool:
return { ...ctr, exp: simplifyBool(ctrSet, ctr.exp) };
case ConstraintType.Broadcastable:
return { ...ctr, left: simplifyShape(ctrSet, ctr.left), right: simplifyShape(ctrSet, ctr.right) };
case ConstraintType.Forall:
return {
...ctr,
range: [simplifyNum(ctrSet, ctr.range[0]), simplifyNum(ctrSet, ctr.range[1])],
constraint: simplifyConstraint(ctrSet, ctr),
};
case ConstraintType.Not:
return { ...ctr, constraint: simplifyConstraint(ctrSet, ctr.constraint) };
default:
return ctr;
}
}
export function ceilDiv(left: ExpNum | number, right: ExpNum | number, source: CodeSource | undefined): ExpNumBop {
if (typeof left === 'number') {
left = ExpNum.fromConst(left, source);
}
if (typeof right === 'number') {
right = ExpNum.fromConst(right, source);
}
const exp1 = ExpNum.bop(NumBopType.Sub, right, 1, source);
const exp2 = ExpNum.bop(NumBopType.Add, left, exp1, source);
return ExpNum.bop(NumBopType.FloorDiv, exp2, right, source);
}
// if exp can be recognized as integer structually, return true
export function isStructuallyInt(exp: ExpNum): boolean {
switch (exp.opType) {
case NumOpType.Bop:
if (exp.bopType === NumBopType.TrueDiv) return false;
return isStructuallyInt(exp.left) && isStructuallyInt(exp.right);
case NumOpType.Const:
return Number.isInteger(exp.value);
case NumOpType.Max:
case NumOpType.Min:
return exp.values.every((e) => isStructuallyInt(e));
case NumOpType.Symbol:
return exp.symbol.type === SymbolType.Int;
case NumOpType.Numel:
case NumOpType.Index:
return true;
case NumOpType.Uop:
if (exp.uopType === NumUopType.Floor || exp.uopType === NumUopType.Ceil) return true;
return isStructuallyInt(exp.baseValue);
}
}
// simple structural equality checker.
export function isStructuallyEq(left?: SymExp, right?: SymExp): boolean {
if (!left) return !right;
if (!right) return false;
if (left.expType !== right.expType || left.opType !== right.opType) return false;
switch (left.expType) {
case SEType.Bool:
switch (left.opType) {
case BoolOpType.And: {
const re = right as typeof left;
return isStructuallyEq(left.left, re.left) && isStructuallyEq(left.right, re.right);
}
case BoolOpType.Const: {
const re = right as typeof left;
return left.value === re.value;
}
case BoolOpType.Equal: {
const re = right as typeof left;
return isStructuallyEq(left.left, re.left) && isStructuallyEq(left.right, re.right);
}
case BoolOpType.LessThan: {
const re = right as typeof left;
return isStructuallyEq(left.left, re.left) && isStructuallyEq(left.right, re.right);
}
case BoolOpType.LessThanOrEqual: {
const re = right as typeof left;
return isStructuallyEq(left.left, re.left) && isStructuallyEq(left.right, re.right);
}
case BoolOpType.Not: {
const re = right as typeof left;
return isStructuallyEq(left.baseBool, re.baseBool);
}
case BoolOpType.NotEqual: {
const re = right as typeof left;
return isStructuallyEq(left.left, re.left) && isStructuallyEq(left.right, re.right);
}
case BoolOpType.Or: {
const re = right as typeof left;
return isStructuallyEq(left.left, re.left) && isStructuallyEq(left.right, re.right);
}
case BoolOpType.Symbol: {
const re = right as typeof left;
return left.symbol.id === re.symbol.id;
}
}
break;
case SEType.Num:
switch (left.opType) {
case NumOpType.Uop: {
const re = right as typeof left;
return left.uopType === re.uopType && isStructuallyEq(left.baseValue, re.baseValue);
}
case NumOpType.Bop: {
const re = right as typeof left;
return (
left.bopType === re.bopType &&
isStructuallyEq(left.left, re.left) &&
isStructuallyEq(left.right, re.right)
);
}
case NumOpType.Const: {
const re = right as typeof left;
return left.value === re.value;
}
case NumOpType.Index: {
const re = right as typeof left;
return isStructuallyEq(left.index, re.index) && isStructuallyEq(left.baseShape, re.baseShape);
}
case NumOpType.Max:
case NumOpType.Min: {
const re = right as typeof left;
return (
left.opType === right.opType &&
left.values.length === re.values.length &&
left.values.every((v, i) => isStructuallyEq(v, re.values[i]))
);
}
case NumOpType.Numel: {
const re = right as typeof left;
return isStructuallyEq(left.shape, re.shape);
}
case NumOpType.Symbol: {
const re = right as typeof left;
return left.symbol.id === re.symbol.id;
}
}
break;
case SEType.Shape:
switch (left.opType) {
case ShapeOpType.Broadcast: {
const re = right as typeof left;
return isStructuallyEq(left.left, re.left) && isStructuallyEq(left.right, re.right);
}
case ShapeOpType.Concat: {
const re = right as typeof left;
return isStructuallyEq(left.left, re.left) && isStructuallyEq(left.right, re.right);
}
case ShapeOpType.Const: {
const re = right as typeof left;
return (
left.rank === re.rank &&
left.dims.length === re.dims.length &&
left.dims.every((v, i) => isStructuallyEq(v, re.dims[i]))
);
}
case ShapeOpType.Set: {
const re = right as typeof left;
return (
isStructuallyEq(left.axis, re.axis) &&
isStructuallyEq(left.dim, re.dim) &&
isStructuallyEq(left.baseShape, re.baseShape)
);
}
case ShapeOpType.Slice: {
const re = right as typeof left;
return (
isStructuallyEq(left.start, re.start) &&
isStructuallyEq(left.end, re.end) &&
isStructuallyEq(left.baseShape, re.baseShape)
);
}
case ShapeOpType.Symbol: {
const re = right as typeof left;
return left.symbol.id === re.symbol.id;
}
}
break;
case SEType.String:
switch (left.opType) {
case StringOpType.Concat: {
const re = right as typeof left;
return isStructuallyEq(left.left, re.left) && isStructuallyEq(left.right, re.right);
}
case StringOpType.Const: {
const re = right as typeof left;
return left.value === re.value;
}
case StringOpType.Slice: {
const re = right as typeof left;
return (
isStructuallyEq(left.start, re.start) &&
isStructuallyEq(left.end, re.end) &&
isStructuallyEq(left.baseString, re.baseString)
);
}
case StringOpType.Symbol: {
const re = right as typeof left;
return left.symbol.id === re.symbol.id;
}
}
}
}
// return symbolic length of str
export function strLen(
ctx: Context<any>,
str: string | ExpString,
source: CodeSource | undefined
): number | ExpNum | Context<ExpNum> {
if (typeof str === 'string') {
return str.length;
}
switch (str.opType) {
case StringOpType.Const:
return str.value.length;
case StringOpType.Concat: {
let leftIsCtx = false;
let left = strLen(ctx, str.left, source);
if (left instanceof Context) {
ctx = left;
left = left.retVal;
leftIsCtx = true;
}
const right = strLen(ctx, str.right, source);
if (right instanceof Context) {
const exp = simplifyNum(right.ctrSet, ExpNum.bop(NumBopType.Add, left, right.retVal, source));
return right.setRetVal(exp);
} else {
const exp = simplifyNum(ctx.ctrSet, ExpNum.bop(NumBopType.Add, left, right, source));
return leftIsCtx ? ctx.setRetVal(exp) : exp;
}
}
case StringOpType.Slice:
if (str.end === undefined) {
const baseLen = strLen(ctx, str.baseString, source);
if (baseLen instanceof Context) {
return baseLen.setRetVal(ExpNum.bop(NumBopType.Sub, baseLen.retVal, str.start ?? 0, source));
}
return simplifyNum(ctx.ctrSet, ExpNum.bop(NumBopType.Sub, baseLen, str.start ?? 0, source));
}
return simplifyNum(ctx.ctrSet, ExpNum.bop(NumBopType.Sub, str.end, str.start ?? 0, source));
case StringOpType.Symbol:
// TODO: cache length of symbolic string
return ctx.genIntGte(`${str.symbol.name}_${str.symbol.id}_len`, 0, source);
}
}
// return closed expression of normalized index of list. (e.g. a[-1] with length 5 => 4)
// if it cannot determine that index is neg or pos,
// return i + r * (1 - (1 // (abs(i) - i + 1))) for safety
// this is equivalent to i if i >= 0 else r - i
export function absExpIndexByLen(
index: number | ExpNum,
rank: number | ExpNum,
source: CodeSource | undefined,
ctrSet?: ConstraintSet
): number | ExpNum {
if (typeof index === 'number') {
if (index >= 0) return index;
else if (typeof rank === 'number') return rank + index;
const r = ctrSet ? simplifyNum(ctrSet, rank) : rank;
if (r.opType === NumOpType.Const) return r.value + index;
return ExpNum.bop(NumBopType.Add, r, index, source);
}
const i = ctrSet ? simplifyNum(ctrSet, index) : index;
if (i.opType === NumOpType.Const) {
index = i.value;
if (index >= 0) return index;
else if (typeof rank === 'number') return rank + index;
const r = ctrSet ? simplifyNum(ctrSet, rank) : rank;
if (r.opType === NumOpType.Const) return r.value + index;
return ExpNum.bop(NumBopType.Add, r, index, source);
} else if (ctrSet) {
const idxRange = ctrSet.getCachedRange(i);
if (idxRange?.gte(0)) {
return i;
}
}
// don't know sign of i
// return i + r * (1 - (1 // (abs(i) - i + 1)))
const r = typeof rank === 'number' ? ExpNum.fromConst(rank, source) : ctrSet ? simplifyNum(ctrSet, rank) : rank;
const result = ExpNum.bop(
NumBopType.Add,
i,
ExpNum.bop(
NumBopType.Mul,
r,
ExpNum.bop(
NumBopType.Sub,
1,
ExpNum.bop(
NumBopType.FloorDiv,
1,
ExpNum.bop(
NumBopType.Sub,
ExpNum.bop(NumBopType.Sub, ExpNum.uop(NumUopType.Abs, i, source), i, source),
1,
source
),
source
),
source
),
source
),
source
);
return result;
}
// return closed expression of length of a:b
// return b >= a ? b - a : 0
// that is, ((b - a) + |b - a|) // 2
export function reluLen(
a: number | ExpNum,
b: number | ExpNum,
source: CodeSource | undefined,
ctrSet?: ConstraintSet
): number | ExpNum {
if (typeof a === 'number' && typeof b === 'number') return b - a >= 0 ? b - a : 0;
const bma = ExpNum.bop(NumBopType.Sub, b, a, source);
const result = ExpNum.bop(
NumBopType.FloorDiv,
ExpNum.bop(NumBopType.Add, bma, ExpNum.uop(NumUopType.Abs, bma, source), source),
2,
source
);
return ctrSet ? simplifyNum(ctrSet, result) : result;
}
// return undefined if inputVal points undefined value. else, return isinstance(inputVal, classVal)
export function isInstanceOf(inputVal: ShValue, classVal: ShValue, env: ShEnv, heap: ShHeap): boolean | undefined {
const input = fetchAddr(inputVal, heap);
if (!input) return;
const mroList = trackMro(inputVal, heap, env);
if (classVal.type !== SVType.Addr) {
// direct comparison between int / float type function
return (
mroList.findIndex((v) => {
if (v === undefined) return false;
return fetchAddr(heap.getVal(v), heap) === classVal;
}) >= 0
);
}
let classPoint: SVAddr = classVal;
while (true) {
const next = heap.getVal(classPoint);
if (next?.type !== SVType.Addr) {
break;
}
classPoint = next;
}
return mroList.findIndex((v) => v === classPoint.addr) >= 0;
} | the_stack |
import * as React from 'react';
import { StackItem, Tooltip } from '@patternfly/react-core';
import { ExternalLinkAltIcon } from '@patternfly/react-icons';
import cn from 'classnames';
import * as copy from 'copy-to-clipboard';
import i18next from 'i18next';
import { Trans, useTranslation } from 'react-i18next';
import { Action } from '@console/dynamic-plugin-sdk';
import { confirmModal } from '@console/internal/components/modals';
import { asAccessReview, Kebab, KebabOption } from '@console/internal/components/utils';
import {
K8sKind,
K8sResourceKind,
PersistentVolumeClaimKind,
PodKind,
} from '@console/internal/module/k8s';
import { YellowExclamationTriangleIcon } from '@console/shared';
import { StatusGroup } from '../../constants/status-group';
import { VMStatus } from '../../constants/vm/vm-status';
import useSSHCommand from '../../hooks/use-ssh-command';
import useSSHService from '../../hooks/use-ssh-service';
import { restartVM, startVM, stopVM } from '../../k8s/requests/vm';
import { startVMIMigration } from '../../k8s/requests/vmi';
import { pauseVMI, unpauseVMI } from '../../k8s/requests/vmi/actions';
import { cancelMigration } from '../../k8s/requests/vmim';
import { cancelVMImport } from '../../k8s/requests/vmimport';
import { VMImportWrappper } from '../../k8s/wrapper/vm-import/vm-import-wrapper';
import { VirtualMachineImportModel, VirtualMachineInstanceMigrationModel } from '../../models';
import { getName, getNamespace } from '../../selectors';
import {
getAutoRemovedOrPersistentDiskName,
getHotplugDiskNames,
} from '../../selectors/disks/hotplug';
import {
isVMCreated,
isVMExpectedRunning,
isVMRunningOrExpectedRunning,
} from '../../selectors/vm/selectors';
import { isVMIPaused } from '../../selectors/vmi';
import { getMigrationVMIName } from '../../selectors/vmi-migration';
import { VMStatusBundle } from '../../statuses/vm/types';
import { getVMStatus } from '../../statuses/vm/vm-status';
import { V1alpha1DataVolume } from '../../types/api';
import { VMIKind, VMKind } from '../../types/vm';
import { VMImportKind } from '../../types/vm-import/ovirt/vm-import';
import { cloneVMModal } from '../modals/clone-vm-modal';
import { confirmVMIModal } from '../modals/menu-actions-modals/confirm-vmi-modal';
import { deleteVMModal } from '../modals/menu-actions-modals/delete-vm-modal';
import { deleteVMIModal } from '../modals/menu-actions-modals/delete-vmi-modal';
import { RemovalDiskAlert } from '../vm-disks/RemovalDiskAlert';
import { ActionMessage } from './ActionMessage';
import './menu-actions.scss';
type ActionArgs = {
vmi?: VMIKind;
vmStatusBundle?: VMStatusBundle;
sshServices?: any;
command?: any;
};
/**
* @deprecated migrated to new action extensions, use VmImportActionFactory
*/
export const menuActionDeleteVMImport = (
kindObj: K8sKind,
vmimport: VMImportKind,
actionArgs?: ActionArgs,
innerArgs?: { vm?: VMKind },
): KebabOption => {
const vmName = new VMImportWrappper(vmimport).getResolvedVMTargetName();
const DeleteVMImportTitle: React.FC = () => {
const { t } = useTranslation();
return (
<>
<YellowExclamationTriangleIcon className="co-icon-space-r" />{' '}
{t('kubevirt-plugin~Cancel Import?')}
</>
);
};
const vmElem = <strong className="co-break-word">{vmName}</strong>;
const vmImportElem = <strong className="co-break-word">{getName(vmimport)}</strong>;
const nsElem = <strong className="co-break-word">{getNamespace(vmimport)}</strong>;
const DeleteVMImportMessage: React.FC = () => {
const { t } = useTranslation();
return innerArgs?.vm ? (
<>
{t(
'kubevirt-plugin~Are you sure you want to cancel importing {{vmImportElem}}? It will also delete the newly created {{vmElem}} in the {{nsElem}} namespace?',
{ vmImportElem, vmElem, nsElem },
)}
</>
) : (
<>
{t(
'kubevirt-plugin~Are you sure you want to cancel importing {{vmImportElem}} in the {{nsElem}} namespace?',
{ vmImportElem, nsElem },
)}
</>
);
};
return {
// t('kubevirt-plugin~Cancel Import')
labelKey: 'kubevirt-plugin~Cancel Import',
callback: () =>
confirmModal({
title: <DeleteVMImportTitle />,
message: <DeleteVMImportMessage />,
submitDanger: true,
// t('kubevirt-plugin~Cancel Import')
btnTextKey: 'kubevirt-plugin~Cancel Import',
executeFn: () => cancelVMImport(vmimport, innerArgs?.vm),
}),
accessReview: asAccessReview(kindObj, vmimport, 'delete'),
};
};
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
export const menuActionStart = (
kindObj: K8sKind,
vm: VMKind,
{ vmi, vmStatusBundle }: ActionArgs,
): KebabOption => {
const StartMessage: React.FC = () => {
const name = getName(vm);
const namespace = getNamespace(vm);
return (
<Trans ns="kubevirt-plugin">
<p>
This virtual machine will start as soon as the import has been completed. If you proceed
you will not be able to change this option.
</p>
Are you sure you want to start <strong>{name}</strong> in namespace{' '}
<strong>{namespace}</strong> after it has imported?
</Trans>
);
};
return {
hidden: vmStatusBundle?.status?.isMigrating() || isVMRunningOrExpectedRunning(vm, vmi),
labelKey: i18next.t('kubevirt-plugin~Start Virtual Machine'),
callback: () => {
if (!vmStatusBundle?.status?.isImporting()) {
startVM(vm);
} else {
confirmModal({
titleKey: i18next.t('kubevirt-plugin~ Start Virtual Machine'),
message: <StartMessage />,
btnTextKey: i18next.t('kubevirt-plugin~Start'),
executeFn: () => startVM(vm),
});
}
},
accessReview: asAccessReview(kindObj, vm, 'patch'),
};
};
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
const menuActionStop = (
kindObj: K8sKind,
vm: VMKind,
{ vmi, vmStatusBundle }: ActionArgs,
): KebabOption => {
const isImporting = vmStatusBundle?.status?.isImporting();
const isPending = vmStatusBundle?.status?.isPending();
return {
isDisabled: isImporting,
hidden: isPending || (!isImporting && !isVMExpectedRunning(vm, vmi)),
// t('kubevirt-plugin~Stop Virtual Machine')
labelKey: 'kubevirt-plugin~Stop Virtual Machine',
callback: () =>
confirmVMIModal({
vmi,
// t('kubevirt-plugin~Stop Virtual Machine')
titleKey: 'kubevirt-plugin~Stop Virtual Machine',
// t('kubevirt-plugin~Stop Virtual Machine alert')
alertTitleKey: 'kubevirt-plugin~Stop Virtual Machine alert',
// t('kubevirt-plugin~stop')
message: (
<ActionMessage obj={vm} actionKey="kubevirt-plugin~stop">
<StackItem>
<RemovalDiskAlert
hotplugDiskNames={getAutoRemovedOrPersistentDiskName(
vm,
getHotplugDiskNames(vmi),
true,
)}
/>
</StackItem>
</ActionMessage>
),
// t('kubevirt-plugin~Stop')
btnTextKey: 'kubevirt-plugin~Stop',
executeFn: () => stopVM(vm),
}),
accessReview: asAccessReview(kindObj, vm, 'patch'),
};
};
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
const menuActionRestart = (
kindObj: K8sKind,
vm: VMKind,
{ vmi, vmStatusBundle }: ActionArgs,
): KebabOption => {
return {
hidden:
vmStatusBundle?.status?.isImporting() ||
vmStatusBundle?.status?.isMigrating() ||
!isVMExpectedRunning(vm, vmi) ||
!isVMCreated(vm),
// t('kubevirt-plugin~Restart Virtual Machine')
labelKey: 'kubevirt-plugin~Restart Virtual Machine',
callback: () =>
confirmVMIModal({
vmi,
// t('kubevirt-plugin~Restart Virtual Machine')
titleKey: 'kubevirt-plugin~Restart Virtual Machine',
// t('kubevirt-plugin~Restart Virtual Machine alert')
alertTitleKey: 'kubevirt-plugin~Restart Virtual Machine alert',
// t('kubevirt-plugin~restart')
message: (
<ActionMessage obj={vm} actionKey="kubevirt-plugin~restart">
<StackItem>
<RemovalDiskAlert
hotplugDiskNames={getAutoRemovedOrPersistentDiskName(
vm,
getHotplugDiskNames(vmi),
true,
)}
/>
</StackItem>
</ActionMessage>
),
// t('kubevirt-plugin~Restart')
btnTextKey: 'kubevirt-plugin~Restart',
executeFn: () => restartVM(vm),
}),
accessReview: asAccessReview(kindObj, vm, 'patch'),
};
};
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
const menuActionUnpause = (kindObj: K8sKind, vm: VMKind, { vmi }: ActionArgs): KebabOption => {
return {
hidden: !isVMIPaused(vmi),
// t('kubevirt-plugin~Unpause Virtual Machine')
labelKey: 'kubevirt-plugin~Unpause Virtual Machine',
callback: () =>
confirmModal({
// t('kubevirt-plugin~Unpause Virtual Machine')
titleKey: 'kubevirt-plugin~Unpause Virtual Machine',
// t('kubevirt-plugin~unpause')
message: <ActionMessage obj={vmi} actionKey="kubevirt-plugin~unpause" />,
// t('kubevirt-plugin~Unpause')
btnTextKey: 'kubevirt-plugin~Unpause',
executeFn: () => unpauseVMI(vmi),
}),
};
};
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
const menuActionPause = (kindObj: K8sKind, vm: VMKind, { vmi }: ActionArgs): KebabOption => {
return {
hidden: isVMIPaused(vmi),
// t('kubevirt-plugin~Pause Virtual Machine')
labelKey: 'kubevirt-plugin~Pause Virtual Machine',
callback: () =>
confirmModal({
// t('kubevirt-plugin~Pause Virtual Machine')
titleKey: 'kubevirt-plugin~Pause Virtual Machine',
// t('kubevirt-plugin~pause')
message: <ActionMessage obj={vmi} actionKey="kubevirt-plugin~pause" />,
// t('kubevirt-plugin~Pause')
btnTextKey: 'kubevirt-plugin~Pause',
executeFn: () => pauseVMI(vmi),
}),
};
};
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
const menuActionMigrate = (
kindObj: K8sKind,
vm: VMKind,
{ vmStatusBundle, vmi }: ActionArgs,
): KebabOption => {
const MigrateMessage: React.FC = () => {
const name = getName(vmi);
return (
<Trans ns="kubevirt-plugin">
Do you wish to migrate <strong>{name}</strong> vmi to another node?
</Trans>
);
};
return {
hidden:
vmStatusBundle?.status?.isMigrating() ||
vmStatusBundle?.status?.isError() ||
vmStatusBundle?.status?.isInProgress() ||
!isVMRunningOrExpectedRunning(vm, vmi),
// t('kubevirt-plugin~Migrate Virtual Machine')
labelKey: 'kubevirt-plugin~Migrate Virtual Machine',
callback: () =>
confirmModal({
// t('kubevirt-plugin~Migrate Virtual Machine')
titleKey: 'kubevirt-plugin~Migrate Virtual Machine',
message: <MigrateMessage />,
// t('kubevirt-plugin~Migrate')
btnTextKey: 'kubevirt-plugin~Migrate',
executeFn: () => startVMIMigration(vmi),
}),
};
};
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
const menuActionCancelMigration = (
kindObj: K8sKind,
vm: VMKind,
{ vmStatusBundle }: ActionArgs,
): KebabOption => {
const migration = vmStatusBundle?.migration;
const CancelMigrationMessage: React.FC = () => {
const name = getMigrationVMIName(migration);
const namespace = getNamespace(migration);
return (
<Trans ns="kubevirt-plugin">
Are you sure you want to cancel <strong>{name}</strong> migration in{' '}
<strong>{namespace}</strong> namespace?
</Trans>
);
};
return {
hidden: !vmStatusBundle?.status?.isMigrating(),
// t('kubevirt-plugin~Cancel Virtual Machine Migration')
labelKey: 'kubevirt-plugin~Cancel Virtual Machine Migration',
callback: () =>
confirmModal({
// t('kubevirt-plugin~Cancel Virtual Machine Migration')
titleKey: 'kubevirt-plugin~Cancel Virtual Machine Migration',
message: <CancelMigrationMessage />,
// t('kubevirt-plugin~Cancel Migration')
btnTextKey: 'kubevirt-plugin~Cancel Migration',
executeFn: () => cancelMigration(migration),
}),
accessReview:
migration && asAccessReview(VirtualMachineInstanceMigrationModel, migration, 'delete'),
};
};
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
const menuActionClone = (
kindObj: K8sKind,
vm: VMKind,
{ vmi, vmStatusBundle }: ActionArgs,
): KebabOption => {
return {
hidden: vmStatusBundle?.status?.isImporting(),
// t('kubevirt-plugin~Clone Virtual Machine')
labelKey: 'kubevirt-plugin~Clone Virtual Machine',
callback: () => cloneVMModal({ vm, vmi }),
accessReview: asAccessReview(kindObj, vm, 'patch'),
};
};
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
export const menuActionDeleteVM = (kindObj: K8sKind, vm: VMKind, vmi: VMIKind): KebabOption => ({
// t('kubevirt-plugin~Delete Virtual Machine')
labelKey: 'kubevirt-plugin~Delete Virtual Machine',
callback: () =>
deleteVMModal({
vm,
vmi,
}),
accessReview: asAccessReview(kindObj, vm, 'delete'),
});
export const menuActionDeleteVMorCancelImport = (
kindObj: K8sKind,
vm: VMKind,
actionArgs: ActionArgs,
): KebabOption => {
const { status, vmImport } = actionArgs.vmStatusBundle;
if (status?.getGroup() === StatusGroup.VMIMPORT && !status?.isCompleted() && vmImport) {
return menuActionDeleteVMImport(VirtualMachineImportModel, vmImport, actionArgs, {
vm,
});
}
return menuActionDeleteVM(kindObj, vm, actionArgs?.vmi);
};
/**
* @deprecated migrated to new action extensions, use VmiActionFactory
*/
export const menuActionDeleteVMI = (kindObj: K8sKind, vmi: VMIKind): KebabOption => ({
// t('kubevirt-plugin~Delete Virtual Machine Instance')
labelKey: 'kubevirt-plugin~Delete Virtual Machine Instance',
callback: () =>
deleteVMIModal({
vmi,
}),
accessReview: asAccessReview(kindObj, vmi, 'delete'),
});
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
export const menuActionOpenConsole = (kindObj: K8sKind, vmi: VMIKind): KebabOption => {
const OpenConsoleLabel: React.FC = () => {
const { t } = useTranslation();
return (
<>
{t('kubevirt-plugin~Open Console')}
<span className="kubevirt-menu-actions__icon-spacer">
<ExternalLinkAltIcon />
</span>
</>
);
};
return {
label: <OpenConsoleLabel />,
callback: () =>
window.open(
`/k8s/ns/${getNamespace(vmi)}/virtualmachineinstances/${getName(vmi)}/standaloneconsole`,
`${getName(vmi)}-console}`,
'modal=yes,alwaysRaised=yes,location=yes,width=1024,height=768',
),
};
};
/**
* @deprecated migrated to new action extensions, use VmActionFactory
*/
export const menuActionCopySSHCommand = (
kindObj: K8sKind,
vm: VMIKind,
{ vmStatusBundle },
): KebabOption => {
let sshCommand = '';
let isDisabled = false;
const CopySSHCommand: React.FC = () => {
const { sshServices } = useSSHService(vm);
const { command } = useSSHCommand(vm);
const [showTooltip, setShowToolTip] = React.useState(false);
const { t } = useTranslation();
sshCommand = command;
isDisabled = !sshServices?.running || !(vmStatusBundle?.status === VMStatus.RUNNING);
return (
<div
id="SSHMenuLabel"
onMouseEnter={() => setShowToolTip(true)}
onMouseLeave={() => setShowToolTip(false)}
className={cn({ 'CopySSHCommand-disabled': isDisabled })}
>
{t('kubevirt-plugin~Copy SSH Command')}
{isDisabled && (
<Tooltip
reference={() => document.getElementById('SSHMenuLabel')}
position="left"
trigger="manual"
isVisible={showTooltip}
content={t('kubevirt-plugin~Manage SSH access in the virtual machine details page')}
/>
)}
<div className="kubevirt-menu-actions__secondary-title">
{isDisabled
? t('kubevirt-plugin~Requires SSH Service')
: t('kubevirt-plugin~copy to clipboard')}
</div>
</div>
);
};
return {
label: <CopySSHCommand />,
callback: () => !isDisabled && copy(sshCommand),
isDisabled,
};
};
export const VmActionFactory = {
Start: (kindObj: K8sKind, vm: VMKind, { vmi, vmStatusBundle }: ActionArgs): Action => {
const StartMessage: React.FC = () => {
const name = getName(vm);
const namespace = getNamespace(vm);
return (
<Trans ns="kubevirt-plugin">
<p>
This virtual machine will start as soon as the import has been completed. If you proceed
you will not be able to change this option.
</p>
Are you sure you want to start <strong>{name}</strong> in namespace{' '}
<strong>{namespace}</strong> after it has imported?
</Trans>
);
};
return {
id: 'vm-action-start',
disabled: vmStatusBundle?.status?.isMigrating() || isVMRunningOrExpectedRunning(vm, vmi),
label: i18next.t('kubevirt-plugin~Start Virtual Machine'),
cta: () => {
if (!vmStatusBundle?.status?.isImporting()) {
startVM(vm);
} else {
confirmModal({
title: i18next.t('kubevirt-plugin~ Start Virtual Machine'),
message: <StartMessage />,
btnText: i18next.t('kubevirt-plugin~Start'),
executeFn: () => startVM(vm),
});
}
},
accessReview: asAccessReview(kindObj, vm, 'patch'),
};
},
Stop: (kindObj: K8sKind, vm: VMKind, { vmi, vmStatusBundle }: ActionArgs): Action => {
const isImporting = vmStatusBundle?.status?.isImporting();
return {
id: 'vm-action-stop',
disabled: isImporting,
label: i18next.t('kubevirt-plugin~Stop Virtual Machine'),
cta: () =>
confirmVMIModal({
vmi,
title: i18next.t('kubevirt-plugin~Stop Virtual Machine'),
alertTitle: i18next.t('kubevirt-plugin~Stop Virtual Machine alert'),
message: (
<ActionMessage obj={vm} action={i18next.t('kubevirt-plugin~stop')}>
<StackItem>
<RemovalDiskAlert
hotplugDiskNames={getAutoRemovedOrPersistentDiskName(
vm,
getHotplugDiskNames(vmi),
true,
)}
/>
</StackItem>
</ActionMessage>
),
btnTextKey: i18next.t('kubevirt-plugin~Stop'),
executeFn: () => stopVM(vm),
}),
accessReview: asAccessReview(kindObj, vm, 'patch'),
};
},
Restart: (kindObj: K8sKind, vm: VMKind, { vmi }: ActionArgs): Action => {
return {
id: 'vm-action-restart',
label: i18next.t('kubevirt-plugin~Restart Virtual Machine'),
cta: () =>
confirmVMIModal({
vmi,
title: i18next.t('kubevirt-plugin~Restart Virtual Machine'),
alertTitle: i18next.t('kubevirt-plugin~Restart Virtual Machine alert'),
message: (
<ActionMessage obj={vm} action={i18next.t('kubevirt-plugin~restart')}>
<StackItem>
<RemovalDiskAlert
hotplugDiskNames={getAutoRemovedOrPersistentDiskName(
vm,
getHotplugDiskNames(vmi),
true,
)}
/>
</StackItem>
</ActionMessage>
),
btnText: i18next.t('kubevirt-plugin~Restart'),
executeFn: () => restartVM(vm),
}),
accessReview: asAccessReview(kindObj, vm, 'patch'),
};
},
Unpause: (vmi: VMIKind): Action => {
return {
id: 'vm-action-unpause',
label: i18next.t('kubevirt-plugin~Unpause Virtual Machine'),
cta: () =>
confirmModal({
title: i18next.t('kubevirt-plugin~Unpause Virtual Machine'),
message: <ActionMessage obj={vmi} action={i18next.t('kubevirt-plugin~unpause')} />,
btnText: i18next.t('kubevirt-plugin~Unpause'),
executeFn: () => unpauseVMI(vmi),
}),
};
},
Pause: (vmi: VMIKind): Action => {
return {
id: 'vm-action-pause',
label: i18next.t('kubevirt-plugin~Pause Virtual Machine'),
cta: () =>
confirmModal({
title: i18next.t('kubevirt-plugin~Pause Virtual Machine'),
message: <ActionMessage obj={vmi} action={i18next.t('kubevirt-plugin~pause')} />,
btnText: i18next.t('kubevirt-plugin~Pause'),
executeFn: () => pauseVMI(vmi),
}),
};
},
Migrate: (vmi: VMIKind): Action => {
const MigrateMessage: React.FC = () => {
const name = getName(vmi);
return (
<Trans ns="kubevirt-plugin">
Do you wish to migrate <strong>{name}</strong> vmi to another node?
</Trans>
);
};
return {
id: 'vm-action-migrate',
label: i18next.t('kubevirt-plugin~Migrate Virtual Machine'),
cta: () =>
confirmModal({
title: i18next.t('kubevirt-plugin~Migrate Virtual Machine'),
message: <MigrateMessage />,
btnText: i18next.t('kubevirt-plugin~Migrate'),
executeFn: () => startVMIMigration(vmi),
}),
};
},
CancelMigration: (vmStatusBundle: VMStatusBundle): Action => {
const migration = vmStatusBundle?.migration;
const CancelMigrationMessage: React.FC = () => {
const name = getMigrationVMIName(migration);
const namespace = getNamespace(migration);
return (
<Trans ns="kubevirt-plugin">
Are you sure you want to cancel <strong>{name}</strong> migration in{' '}
<strong>{namespace}</strong> namespace?
</Trans>
);
};
return {
id: 'vm-action-cancel-migration',
label: i18next.t('kubevirt-plugin~Cancel Virtual Machine Migration'),
cta: () =>
confirmModal({
title: i18next.t('kubevirt-plugin~Cancel Virtual Machine Migration'),
message: <CancelMigrationMessage />,
btnText: i18next.t('kubevirt-plugin~Cancel Migration'),
executeFn: () => cancelMigration(migration),
}),
accessReview:
migration && asAccessReview(VirtualMachineInstanceMigrationModel, migration, 'delete'),
};
},
Clone: (kindObj: K8sKind, vm: VMKind, { vmi }: ActionArgs): Action => {
return {
id: 'vm-action-clone',
label: i18next.t('kubevirt-plugin~Clone Virtual Machine'),
cta: () => cloneVMModal({ vm, vmi }),
accessReview: asAccessReview(kindObj, vm, 'patch'),
};
},
OpenConsole: (vmi: VMIKind): Action => {
const OpenConsoleLabel: React.FC = () => {
const { t } = useTranslation();
return (
<>
{t('kubevirt-plugin~Open Console')}
<span className="kubevirt-menu-actions__icon-spacer">
<ExternalLinkAltIcon />
</span>
</>
);
};
return {
id: 'vm-action-open-console',
label: <OpenConsoleLabel />,
cta: () =>
window.open(
`/k8s/ns/${getNamespace(vmi)}/virtualmachineinstances/${getName(vmi)}/standaloneconsole`,
`${getName(vmi)}-console}`,
'modal=yes,alwaysRaised=yes,location=yes,width=1024,height=768',
),
};
},
CopySSHCommand: (vm: VMKind, vmStatusBundle: VMStatusBundle): Action => {
let sshCommand = '';
let isDisabled = false;
const CopySSHCommand: React.FC = () => {
const { sshServices } = useSSHService(vm);
const { command } = useSSHCommand(vm);
const [showTooltip, setShowToolTip] = React.useState(false);
const { t } = useTranslation();
sshCommand = command;
isDisabled = !sshServices?.running || !(vmStatusBundle?.status === VMStatus.RUNNING);
return (
<div
id="SSHMenuLabel"
onMouseEnter={() => setShowToolTip(true)}
onMouseLeave={() => setShowToolTip(false)}
className={cn({ 'CopySSHCommand-disabled': isDisabled })}
>
{t('kubevirt-plugin~Copy SSH Command')}
{isDisabled && (
<Tooltip
reference={() => document.getElementById('SSHMenuLabel')}
position="left"
trigger="manual"
isVisible={showTooltip}
content={t('kubevirt-plugin~Manage SSH access in the virtual machine details page')}
/>
)}
<div className="kubevirt-menu-actions__secondary-title">
{isDisabled
? t('kubevirt-plugin~Requires SSH Service')
: t('kubevirt-plugin~copy to clipboard')}
</div>
</div>
);
};
return {
id: 'vm-action-copy-ssh-command',
label: <CopySSHCommand />,
cta: () => !isDisabled && copy(sshCommand),
disabled: isDisabled,
};
},
Delete: (kindObj: K8sKind, vm: VMKind, vmi: VMIKind): Action => ({
id: 'vm-action-delete',
label: i18next.t('kubevirt-plugin~Delete Virtual Machine'),
cta: () =>
deleteVMModal({
vm,
vmi,
}),
accessReview: asAccessReview(kindObj, vm, 'delete'),
}),
};
export const VmiActionFactory = {
Delete: (kindObj: K8sKind, vmi: VMIKind): Action => ({
id: 'vmi-action-delete',
label: i18next.t('kubevirt-plugin~Delete Virtual Machine Instance'),
cta: () =>
deleteVMIModal({
vmi,
}),
accessReview: asAccessReview(kindObj, vmi, 'delete'),
}),
};
export const VmImportActionFactory = {
Delete: (kindObj: K8sKind, vmimport: VMImportKind, innerArgs?: { vm?: VMKind }): Action => {
const vmName = new VMImportWrappper(vmimport).getResolvedVMTargetName();
const DeleteVMImportTitle: React.FC = () => {
const { t } = useTranslation();
return (
<>
<YellowExclamationTriangleIcon className="co-icon-space-r" />{' '}
{t('kubevirt-plugin~Cancel Import?')}
</>
);
};
const vmElem = <strong className="co-break-word">{vmName}</strong>;
const vmImportElem = <strong className="co-break-word">{getName(vmimport)}</strong>;
const nsElem = <strong className="co-break-word">{getNamespace(vmimport)}</strong>;
const DeleteVMImportMessage: React.FC = () => {
const { t } = useTranslation();
return innerArgs?.vm ? (
<>
{t(
'kubevirt-plugin~Are you sure you want to cancel importing {{vmImportElem}}? It will also delete the newly created {{vmElem}} in the {{nsElem}} namespace?',
{ vmImportElem, vmElem, nsElem },
)}
</>
) : (
<>
{t(
'kubevirt-plugin~Are you sure you want to cancel importing {{vmImportElem}} in the {{nsElem}} namespace?',
{ vmImportElem, nsElem },
)}
</>
);
};
return {
id: 'vm-import-action-delete',
label: i18next.t('kubevirt-plugin~Cancel Import'),
cta: () =>
confirmModal({
title: <DeleteVMImportTitle />,
message: <DeleteVMImportMessage />,
submitDanger: true,
btnText: i18next.t('kubevirt-plugin~Cancel Import'),
executeFn: () => cancelVMImport(vmimport, innerArgs?.vm),
}),
accessReview: asAccessReview(kindObj, vmimport, 'delete'),
};
},
};
export const vmMenuActions = [
menuActionStart,
menuActionStop,
menuActionRestart,
menuActionUnpause,
menuActionPause,
menuActionMigrate,
menuActionCancelMigration,
menuActionClone,
menuActionOpenConsole,
menuActionCopySSHCommand,
Kebab.factory.ModifyLabels,
Kebab.factory.ModifyAnnotations,
menuActionDeleteVMorCancelImport,
];
export const vmiMenuActions = [
Kebab.factory.ModifyLabels,
Kebab.factory.ModifyAnnotations,
menuActionDeleteVMI,
];
export const vmImportMenuActions = [
Kebab.factory.ModifyLabels,
Kebab.factory.ModifyAnnotations,
menuActionDeleteVMImport,
];
export type ExtraResources = {
vmis: VMIKind[];
pods: PodKind[];
migrations: K8sResourceKind[];
pvcs?: PersistentVolumeClaimKind[];
dataVolumes: V1alpha1DataVolume[];
vmImports: VMImportKind[];
};
export const vmMenuActionsCreator = (
kindObj: K8sKind,
vm: VMKind,
{ vmis, pods, migrations, vmImports, pvcs, dataVolumes }: ExtraResources,
) => {
const vmi = vmis && vmis[0];
const vmStatusBundle = getVMStatus({ vm, vmi, pods, migrations, pvcs, dataVolumes, vmImports });
return vmMenuActions.map((action) => {
return action(kindObj, vm, { vmi, vmStatusBundle });
});
};
export const vmiMenuActionsCreator = (kindObj: K8sKind, vmi: VMIKind) => {
return vmiMenuActions.map((action) => {
return action(kindObj, vmi);
});
}; | the_stack |
import initTrace from "debug";
import { DEFAULT_TRAVERSE_LIMIT, DEFAULT_BUFFER_SIZE } from "../constants";
import {
MSG_INVALID_FRAME_HEADER,
MSG_SEGMENT_OUT_OF_BOUNDS,
MSG_SEGMENT_TOO_SMALL,
MSG_NO_SEGMENTS_IN_ARENA,
} from "../errors";
import { dumpBuffer, format, padToWord } from "../util";
import { AnyArena, Arena, MultiSegmentArena, SingleSegmentArena, ArenaKind } from "./arena";
import { pack, unpack } from "./packing";
import { Pointer, StructCtor, PointerType, Struct } from "./pointers";
import { Segment } from "./segment";
import { getTargetStructSize, validate } from "./pointers/pointer";
import { resize, initStruct } from "./pointers/struct";
const trace = initTrace("capnp:message");
trace("load");
export interface _Message {
readonly arena: AnyArena;
segments: Segment[];
traversalLimit: number;
}
export class Message {
static readonly allocateSegment = allocateSegment;
static readonly dump = dump;
static readonly getRoot = getRoot;
static readonly getSegment = getSegment;
static readonly initRoot = initRoot;
static readonly readRawPointer = readRawPointer;
static readonly toArrayBuffer = toArrayBuffer;
static readonly toPackedArrayBuffer = toPackedArrayBuffer;
readonly _capnp: _Message;
/**
* A Cap'n Proto message.
*
* SECURITY WARNING: In nodejs do not pass a Buffer's internal array buffer into this constructor. Pass the buffer
* directly and everything will be fine. If not, your message will potentially be initialized with random memory
* contents!
*
* The constructor method creates a new Message, optionally using a provided arena for segment allocation, or a buffer
* to read from.
*
* @constructor {Message}
*
* @param {AnyArena|ArrayBufferView|ArrayBuffer} [src] The source for the message.
* A value of `undefined` will cause the message to initialize with a single segment arena only big enough for the
* root pointer; it will expand as you go. This is a reasonable choice for most messages.
*
* Passing an arena will cause the message to use that arena for its segment allocation. Contents will be accepted
* as-is.
*
* Passing an array buffer view (like `DataView`, `Uint8Array` or `Buffer`) will create a **copy** of the source
* buffer; beware of the potential performance cost!
*
* @param {boolean} [packed] Whether or not the message is packed. If `true` (the default), the message will be
* unpacked.
*
* @param {boolean} [singleSegment] If true, `src` will be treated as a message consisting of a single segment without
* a framing header.
*
*/
constructor(src?: AnyArena | ArrayBufferView | ArrayBuffer, packed = true, singleSegment = false) {
this._capnp = initMessage(src, packed, singleSegment);
if (src && !isAnyArena(src)) preallocateSegments(this);
trace("new %s", this);
}
allocateSegment(byteLength: number): Segment {
return allocateSegment(byteLength, this);
}
/**
* Create a pretty-printed string dump of this message; incredibly useful for debugging.
*
* WARNING: Do not call this method on large messages!
*
* @returns {string} A big steaming pile of pretty hex digits.
*/
dump(): string {
return dump(this);
}
/**
* Get a struct pointer for the root of this message. This is primarily used when reading a message; it will not
* overwrite existing data.
*
* @template T
* @param {StructCtor<T>} RootStruct The struct type to use as the root.
* @returns {T} A struct representing the root of the message.
*/
getRoot<T extends Struct>(RootStruct: StructCtor<T>): T {
return getRoot(RootStruct, this);
}
/**
* Get a segment by its id.
*
* This will lazily allocate the first segment if it doesn't already exist.
*
* @param {number} id The segment id.
* @returns {Segment} The requested segment.
*/
getSegment(id: number): Segment {
return getSegment(id, this);
}
/**
* Initialize a new message using the provided struct type as the root.
*
* @template T
* @param {StructCtor<T>} RootStruct The struct type to use as the root.
* @returns {T} An initialized struct pointing to the root of the message.
*/
initRoot<T extends Struct>(RootStruct: StructCtor<T>): T {
return initRoot(RootStruct, this);
}
/**
* Set the root of the message to a copy of the given pointer. Used internally
* to make copies of pointers for default values.
*
* @param {Pointer} src The source pointer to copy.
* @returns {void}
*/
setRoot(src: Pointer): void {
setRoot(src, this);
}
/**
* Combine the contents of this message's segments into a single array buffer and prepend a stream framing header
* containing information about the following segment data.
*
* @returns {ArrayBuffer} An ArrayBuffer with the contents of this message.
*/
toArrayBuffer(): ArrayBuffer {
return toArrayBuffer(this);
}
/**
* Like `toArrayBuffer()`, but also applies the packing algorithm to the output. This is typically what you want to
* use if you're sending the message over a network link or other slow I/O interface where size matters.
*
* @returns {ArrayBuffer} A packed message.
*/
toPackedArrayBuffer(): ArrayBuffer {
return toPackedArrayBuffer(this);
}
toString(): string {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return `Message_arena:${this._capnp.arena}`;
}
}
export interface CreateMessageOptions {
packed?: boolean;
singleSegment?: boolean;
}
export function initMessage(
src?: AnyArena | ArrayBufferView | ArrayBuffer,
packed = true,
singleSegment = false
): _Message {
if (src === undefined) {
return {
arena: new SingleSegmentArena(),
segments: [],
traversalLimit: DEFAULT_TRAVERSE_LIMIT,
};
}
if (isAnyArena(src)) {
return { arena: src, segments: [], traversalLimit: DEFAULT_TRAVERSE_LIMIT };
}
let buf: ArrayBuffer = src as ArrayBuffer;
if (isArrayBufferView(buf)) {
buf = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
}
if (packed) buf = unpack(buf);
if (singleSegment) {
return {
arena: new SingleSegmentArena(buf),
segments: [],
traversalLimit: DEFAULT_TRAVERSE_LIMIT,
};
}
return {
arena: new MultiSegmentArena(getFramedSegments(buf)),
segments: [],
traversalLimit: DEFAULT_TRAVERSE_LIMIT,
};
}
/**
* Given an _unpacked_ message with a segment framing header, this will generate an ArrayBuffer for each segment in
* the message.
*
* This method is not typically called directly, but can be useful in certain cases.
*
* @static
* @param {ArrayBuffer} message An unpacked message with a framing header.
* @returns {ArrayBuffer[]} An array of buffers containing the segment data.
*/
export function getFramedSegments(message: ArrayBuffer): ArrayBuffer[] {
const dv = new DataView(message);
const segmentCount = dv.getUint32(0, true) + 1;
const segments = new Array(segmentCount) as ArrayBuffer[];
trace("reading %d framed segments from stream", segmentCount);
let byteOffset = 4 + segmentCount * 4;
byteOffset += byteOffset % 8;
if (byteOffset + segmentCount * 4 > message.byteLength) {
throw new Error(MSG_INVALID_FRAME_HEADER);
}
for (let i = 0; i < segmentCount; i++) {
const byteLength = dv.getUint32(4 + i * 4, true) * 8;
if (byteOffset + byteLength > message.byteLength) {
throw new Error(MSG_INVALID_FRAME_HEADER);
}
segments[i] = message.slice(byteOffset, byteOffset + byteLength);
byteOffset += byteLength;
}
return segments;
}
/**
* This method is called on messages that were constructed with existing data to prepopulate the segments array with
* everything we can find in the arena. Each segment will have it's `byteLength` set to the size of its buffer.
*
* Technically speaking, the message's segments will be "full" after calling this function. Calling this on your own
* may void your warranty.
*
* @param {Message} m The message to allocate.
* @returns {void}
*/
export function preallocateSegments(m: Message): void {
const numSegments = Arena.getNumSegments(m._capnp.arena);
if (numSegments < 1) throw new Error(MSG_NO_SEGMENTS_IN_ARENA);
m._capnp.segments = new Array(numSegments) as Segment[];
for (let i = 0; i < numSegments; i++) {
// Set up each segment so that they're fully allocated to the extents of the existing buffers.
const buffer = Arena.getBuffer(i, m._capnp.arena);
const segment = new Segment(i, m, buffer, buffer.byteLength);
m._capnp.segments[i] = segment;
}
}
function isArrayBufferView(src: ArrayBuffer | ArrayBufferView): src is ArrayBufferView {
return (src as { byteOffset?: number }).byteOffset !== undefined;
}
function isAnyArena(o: unknown): o is AnyArena {
return (o as { kind?: ArenaKind }).kind !== undefined;
}
export function allocateSegment(byteLength: number, m: Message): Segment {
trace("allocating %x bytes for %s", byteLength, m);
const res = Arena.allocate(byteLength, m._capnp.segments, m._capnp.arena);
let s: Segment;
if (res.id === m._capnp.segments.length) {
// Note how we're only allowing new segments in if they're exactly the next one in the array. There is no logical
// reason for segments to be created out of order.
s = new Segment(res.id, m, res.buffer);
trace("adding new segment %s", s);
m._capnp.segments.push(s);
} else if (res.id < 0 || res.id > m._capnp.segments.length) {
throw new Error(format(MSG_SEGMENT_OUT_OF_BOUNDS, res.id, m));
} else {
s = m._capnp.segments[res.id];
trace("replacing segment %s with buffer (len:%d)", s, res.buffer.byteLength);
s.replaceBuffer(res.buffer);
}
return s;
}
export function dump(m: Message): string {
let r = "";
if (m._capnp.segments.length === 0) {
return "================\nNo Segments\n================\n";
}
for (let i = 0; i < m._capnp.segments.length; i++) {
r += `================\nSegment #${i}\n================\n`;
const { buffer, byteLength } = m._capnp.segments[i];
const b = new Uint8Array(buffer, 0, byteLength);
r += dumpBuffer(b);
}
return r;
}
export function getRoot<T extends Struct>(RootStruct: StructCtor<T>, m: Message): T {
const root = new RootStruct(m.getSegment(0), 0);
validate(PointerType.STRUCT, root);
const ts = getTargetStructSize(root);
// Make sure the underlying pointer is actually big enough to hold the data and pointers as specified in the schema.
// If not a shallow copy of the struct contents needs to be made before returning.
if (
ts.dataByteLength < RootStruct._capnp.size.dataByteLength ||
ts.pointerLength < RootStruct._capnp.size.pointerLength
) {
trace("need to resize root struct %s", root);
resize(RootStruct._capnp.size, root);
}
return root;
}
export function getSegment(id: number, m: Message): Segment {
const segmentLength = m._capnp.segments.length;
if (id === 0 && segmentLength === 0) {
// Segment zero is special. If we have no segments in the arena we'll want to allocate a new one and leave room
// for the root pointer.
const arenaSegments = Arena.getNumSegments(m._capnp.arena);
if (arenaSegments === 0) {
allocateSegment(DEFAULT_BUFFER_SIZE, m);
} else {
// Okay, the arena already has a buffer we can use. This is totally fine.
m._capnp.segments[0] = new Segment(0, m, Arena.getBuffer(0, m._capnp.arena));
}
if (!m._capnp.segments[0].hasCapacity(8)) {
throw new Error(MSG_SEGMENT_TOO_SMALL);
}
// This will leave room for the root pointer.
m._capnp.segments[0].allocate(8);
return m._capnp.segments[0];
}
if (id < 0 || id >= segmentLength) {
throw new Error(format(MSG_SEGMENT_OUT_OF_BOUNDS, id, m));
}
return m._capnp.segments[id];
}
export function initRoot<T extends Struct>(RootStruct: StructCtor<T>, m: Message): T {
const root = new RootStruct(m.getSegment(0), 0);
initStruct(RootStruct._capnp.size, root);
trace("Initialized root pointer %s for %s.", root, m);
return root;
}
/**
* Read a pointer in raw form (a packed message with framing headers). Does not
* care or attempt to validate the input beyond parsing the message
* segments.
*
* This is typically used by the compiler to load default values, but can be
* useful to work with messages with an unknown schema.
*
* @param {ArrayBuffer} data The raw data to read.
* @returns {Pointer} A root pointer.
*/
export function readRawPointer(data: ArrayBuffer): Pointer {
return new Pointer(new Message(data).getSegment(0), 0);
}
export function setRoot(src: Pointer, m: Message): void {
Pointer.copyFrom(src, new Pointer(m.getSegment(0), 0));
}
export function toArrayBuffer(m: Message): ArrayBuffer {
const streamFrame = getStreamFrame(m);
// Make sure the first segment is allocated.
if (m._capnp.segments.length === 0) getSegment(0, m);
const segments = m._capnp.segments;
// Add space for the stream framing.
const totalLength = streamFrame.byteLength + segments.reduce((l, s) => l + padToWord(s.byteLength), 0);
const out = new Uint8Array(new ArrayBuffer(totalLength));
let o = streamFrame.byteLength;
out.set(new Uint8Array(streamFrame));
segments.forEach((s) => {
const segmentLength = padToWord(s.byteLength);
out.set(new Uint8Array(s.buffer, 0, segmentLength), o);
o += segmentLength;
});
return out.buffer;
}
export function toPackedArrayBuffer(m: Message): ArrayBuffer {
const streamFrame = pack(getStreamFrame(m));
// Make sure the first segment is allocated.
if (m._capnp.segments.length === 0) m.getSegment(0);
// NOTE: A copy operation can be avoided here if we capture the intermediate array and use that directly in the copy
// loop below, rather than have `pack()` copy it to an ArrayBuffer just to have to copy it again later. If the
// intermediate array can be avoided altogether that's even better!
const segments = m._capnp.segments.map((s) => pack(s.buffer, 0, padToWord(s.byteLength)));
const totalLength = streamFrame.byteLength + segments.reduce((l, s) => l + s.byteLength, 0);
const out = new Uint8Array(new ArrayBuffer(totalLength));
let o = streamFrame.byteLength;
out.set(new Uint8Array(streamFrame));
segments.forEach((s) => {
out.set(new Uint8Array(s), o);
o += s.byteLength;
});
return out.buffer;
}
export function getStreamFrame(m: Message): ArrayBuffer {
const length = m._capnp.segments.length;
if (length === 0) {
// Don't bother allocating the first segment, just return a single zero word for the frame header.
return new Float64Array(1).buffer;
}
const frameLength = 4 + length * 4 + (1 - (length % 2)) * 4;
const out = new DataView(new ArrayBuffer(frameLength));
trace("Writing message stream frame with segment count: %d.", length);
out.setUint32(0, length - 1, true);
m._capnp.segments.forEach((s, i) => {
trace("Message segment %d word count: %d.", s.id, s.byteLength / 8);
out.setUint32(i * 4 + 4, s.byteLength / 8, true);
});
return out.buffer;
} | the_stack |
import { inject, injectable } from 'inversify'
import {
AlertEvent,
IdAlert,
IdRevision,
ResponseKind,
applyDelta
} from 'unofficial-grammarly-api'
import {
CodeAction,
CodeActionKind,
Connection,
Diagnostic,
DiagnosticRelatedInformation,
DiagnosticSeverity,
DiagnosticTag,
Disposable,
MarkedString,
ServerCapabilities
} from 'vscode-languageserver'
import { Position, Range, TextDocument } from 'vscode-languageserver-textdocument'
import { CONNECTION, SERVER } from '../constants'
import { DevLogger } from '../DevLogger'
import { GrammarlyDocument } from '../GrammarlyDocument'
import { Registerable } from '../interfaces'
import { isNumber } from '../is'
import { GrammarlyLanguageServer } from '../protocol'
import { watch, watchEffect } from '../watch'
import { ConfigurationService } from './ConfigurationService'
import { DocumentService } from './DocumentService'
interface DiagnosticWithPosition extends Diagnostic {
id: IdAlert
rev: IdRevision
start: number
end: number
}
const SOURCE = 'Grammarly'
@injectable()
export class GrammarlyDiagnosticsService implements Registerable {
private LOGGER = new DevLogger(GrammarlyDiagnosticsService.name)
private diagnostics = new Map<string, Map<IdAlert, DiagnosticWithPosition[]>>()
constructor (
@inject(CONNECTION)
private readonly connection: Connection,
@inject(SERVER)
private readonly capabilities: ServerCapabilities,
private readonly documents: DocumentService,
private readonly config: ConfigurationService,
) { }
public register() {
this.capabilities.hoverProvider = true
this.capabilities.codeActionProvider = true
this.connection.onRequest(GrammarlyLanguageServer.Feature.checkGrammar, (ref) => {
this.LOGGER.trace(`${GrammarlyLanguageServer.Feature.checkGrammar}(${JSON.stringify(ref, null, 2)})`)
this.check(ref.uri)
})
this.connection.onRequest(GrammarlyLanguageServer.Feature.stop, (ref) => {
this.LOGGER.trace(`${GrammarlyLanguageServer.Feature.stop}(${JSON.stringify(ref, null, 2)})`)
const document = this.documents.get(ref.uri)
if (document != null) {
this.clearDiagnostics(document)
this.connection.sendRequest(GrammarlyLanguageServer.Client.Feature.updateDocumentState, { uri: document.uri })
document.detachHost()
}
})
this.connection.onRequest(GrammarlyLanguageServer.Feature.getDocumentState, (ref) => {
this.LOGGER.trace(`${GrammarlyLanguageServer.Feature.checkGrammar}(${JSON.stringify(ref, null, 2)})`)
const document = this.documents.get(ref.uri)
if (document?.host) {
return this.getDocumentState(document)
}
return null
})
this.connection.onRequest(GrammarlyLanguageServer.Feature.acceptAlert, (options) => {
this.LOGGER.trace(`${GrammarlyLanguageServer.Feature.acceptAlert}(${JSON.stringify(options, null, 2)})`)
const document = this.documents.get(options.uri)
this.diagnostics.get(options.uri)?.delete(options.id)
if (document?.host) {
document.host.acceptAlert(options.id, options.text)
this.sendDiagnostics(document)
}
})
this.connection.onRequest(GrammarlyLanguageServer.Feature.dismissAlert, (options) => {
this.LOGGER.trace(`${GrammarlyLanguageServer.Feature.dismissAlert}(${JSON.stringify(options, null, 2)})`)
const document = this.documents.get(options.uri)
this.diagnostics.get(options.uri)?.delete(options.id)
if (document?.host) {
document.host.dismissAlert(options.id)
this.sendDiagnostics(document)
}
})
this.documents.onDidOpen((document) => {
if (document.host) {
this.LOGGER.trace(`Listening Grammarly alerts for ${document.uri}`)
this.setupDiagnostics(document)
}
})
this.documents.onDidClose((document) => {
this.LOGGER.trace(`Stopping Grammarly alerts for ${document.uri}`)
this.clearDiagnostics(document)
})
this.connection.onHover(({ position, textDocument }) => {
this.LOGGER.trace('Hover', `Incoming request for ${textDocument.uri} at`, position)
const diagnostics = this.findDiagnosticsAt(textDocument.uri, position)
this.LOGGER.trace('Hover', 'Active diagnostics at', diagnostics)
const document = this.documents.get(textDocument.uri)!
if (!diagnostics.length) return null
const range = document.rangeAt(
Math.min(...diagnostics.map((diagnostic) => diagnostic.start)),
Math.max(...diagnostics.map((diagnostic) => diagnostic.end)),
)
const hover = {
range: range,
contents: [] as MarkedString[],
}
const config = {
isDebugMode: this.config.settings.debug,
showDetails: this.config.settings.showExplanation,
showExamples: this.config.settings.showExamples,
cta: document.host!.user.value.isAnonymous
? '> 👉 [Login](https://www.grammarly.com/signin) to get automated fix for this issue.'
: document.host!.user.value.isPremium
? ''
: '> ⏫ [Upgrade](https://www.grammarly.com/upgrade) to get automated fix for this issue.',
}
unique(diagnostics.map((diagnostic) => diagnostic.id))
.map((id) => document.host!.getAlert(id))
.forEach((alert, index) => {
if (!alert) return
if (alert.title) {
const hasFixes = alert.replacements.length
hover.contents.push(
toMarkdown(
`#### ${alert.title}`,
index === 0 ? (hasFixes ? `` : config.cta) : '',
alert.explanation,
config.showDetails && !alert.hidden ? alert.details : '',
config.showExamples && !alert.hidden ? alert.examples : '',
),
)
} else if (alert.subalerts?.length) {
const hasFixes = alert.subalerts.every((alert) => !!alert.transformJson.alternatives)
const count = alert.subalerts.length
hover.contents.push(
toMarkdown(
`### ${alert.cardLayout.outcome}`,
index === 0 ? (hasFixes ? `` : config.cta) : '',
alert.cardLayout.outcomeDescription,
'<p></p>',
`*There ${count > 1 ? 'are' : 'is'} ${count} such ${count > 1 ? 'issues' : 'issue'} in this document.*`,
),
)
} else {
const hasFixes = alert.replacements.length
hover.contents.push(
toMarkdown(
`### ${alert.cardLayout.outcome}`,
index === 0 ? (hasFixes ? `` : config.cta) : '',
alert.cardLayout.outcomeDescription,
),
)
}
if (config.isDebugMode) {
hover.contents.push({ value: JSON.stringify(alert, null, 2), language: 'json' })
}
})
this.LOGGER.trace('Hover', 'Sending', hover)
return hover
})
this.connection.onCodeAction(async ({ textDocument, context }) => {
const document = this.documents.get(textDocument.uri)
const diagnostics = context.diagnostics.filter((diagnostic) => diagnostic.source === SOURCE)
this.LOGGER.trace(`CodeAction in ${textDocument.uri}`, diagnostics)
const actions: CodeAction[] = []
const showDeletedText = this.config.settings.showDeletedTextInQuickFix
if (diagnostics.length >= 1 && document?.host) {
const diagnostic = diagnostics[0]
const alert = document.host.getAlert(diagnostic.code as IdAlert)
if (alert) {
if (isNumber(alert.begin) && alert.replacements.length > 0) {
const replacementRange = document.rangeAt(alert.begin, alert.end)
alert.replacements.forEach((newText, index) => {
actions.push({
title: `${alert.minicardTitle}${showDeletedText ? `: "${document.getText(replacementRange)}"` : ''} -> "${newText}"`,
kind: CodeActionKind.QuickFix,
diagnostics: diagnostics,
isPreferred: index === 0,
command: {
command: 'grammarly.callback',
title: '',
arguments: [
{
method: GrammarlyLanguageServer.Feature.acceptAlert,
params: { id: alert.id, text: newText, uri: textDocument.uri },
},
],
},
edit: {
changes: {
[textDocument.uri]: [
{
range: replacementRange,
newText: newText,
},
],
},
},
})
})
} else if (alert.subalerts != null) {
const len = Math.min(...alert.subalerts.map(subalert => subalert.transformJson.alternatives.length))
const subAlerts = alert.subalerts.slice()
subAlerts.sort((a, b) => b.transformJson.context.s - a.transformJson.context.s)
for (let i = 0; i < len; ++i) {
const { label, highlightText } = alert.subalerts[i]
actions.push({
title: `REPLACE ALL: ${alert.minicardTitle}${label === highlightText ? '' : ` (${label})`} -> "${highlightText}"`,
kind: CodeActionKind.QuickFix,
diagnostics: diagnostics,
command: {
command: 'grammarly.callback',
title: '',
arguments: [
{
method: GrammarlyLanguageServer.Feature.acceptAlert,
params: { id: alert.id, uri: textDocument.uri },
},
],
},
edit: {
changes: {
[textDocument.uri]: subAlerts.map(subAlert => {
const range = document.rangeAt(subAlert.transformJson.context.s, subAlert.transformJson.context.e)
const oldText = document.getText(range)
const newText = applyDelta(oldText, subAlert.transformJson.alternatives[i])
console.log({ oldText, newText })
return { range, newText }
}),
},
},
})
}
}
actions.push({
title: `Ignore Grammarly issue`,
kind: CodeActionKind.QuickFix,
diagnostics: diagnostics,
command: {
command: 'grammarly.callback',
title: 'Grammarly: Dismiss Alert',
arguments: [
{
method: GrammarlyLanguageServer.Feature.dismissAlert,
params: { id: alert.id, uri: textDocument.uri },
},
],
},
})
}
}
if (__DEV__) this.LOGGER.trace('Providing code actions', actions)
return actions
})
this.LOGGER.trace('Registering diagnostics service for Grammarly')
return Disposable.create(() => { })
}
private findDiagnosticsAt(uri: string, position: Position) {
const document = this.documents.get(uri)
const diagnostics = this.diagnostics.get(uri)
if (!document || !document.host || !diagnostics) {
return []
}
const offset = document.offsetAt(position)
return Array.from(diagnostics.values())
.flat()
.filter((diagnostic) => diagnostic.start <= offset && offset <= diagnostic.end)
}
private async check(uri: string) {
const document = this.documents.get(uri)
if (document) {
// When host is attached onDidOpen callback would be called.
await this.documents.attachHost(document, true)
}
}
private setupDiagnostics(document: GrammarlyDocument) {
this.diagnostics.set(document.uri, new Map())
const diagnostics = this.diagnostics.get(document.uri)!
document.host!.onDispose(
watch(document.host!.alerts, (alerts) => {
diagnostics.clear()
alerts.forEach((alert) => {
diagnostics.set(
alert.id,
this.toDiagnostics(alert, document)
)
})
this.sendDiagnostics(document, true)
}),
)
document.host!.onDispose(watchEffect(() => this.sendDocumentState(document)))
document.host!.on(ResponseKind.FINISHED, () => {
this.sendDiagnostics(document)
})
this.sendDiagnostics(document)
}
private sendDocumentState(document: GrammarlyDocument): void {
this.connection.sendRequest(
GrammarlyLanguageServer.Client.Feature.updateDocumentState,
this.getDocumentState(document),
)
}
private getDocumentState(document: GrammarlyDocument): GrammarlyLanguageServer.DocumentState {
let additionalFixableErrors = 0
let premiumErrors = 0
document.host!.alerts.value.forEach((error) => {
if (!error.free) ++premiumErrors
else if (error.hidden) ++additionalFixableErrors
})
return {
uri: document.uri,
score: document.host!.score.value,
status: document.host!.status.value,
scores: document.host!.scores.value,
emotions: document.host!.emotions.value,
textInfo: document.host!.textInfo.value,
totalAlertsCount: document.host!.alerts.value.size,
additionalFixableAlertsCount: additionalFixableErrors,
premiumAlertsCount: premiumErrors,
user: document.host!.user.value,
}
}
private toDiagnostics(alert: AlertEvent, document: GrammarlyDocument): DiagnosticWithPosition[] {
const diagnostics: DiagnosticWithPosition[] = []
if (this.config.settings.hideUnavailablePremiumAlerts && alert.hidden) {
return []
}
const severity = getAlertSeverity(alert)
if (isNumber(alert.begin) && isNumber(alert.end)) {
if (!alert.title) {
this.LOGGER.warn('toDiagnostics', `Missing title`, alert)
}
diagnostics.push({
id: alert.id,
code: alert.id,
message: toText(alert.title || alert.categoryHuman),
range: document.rangeAt(alert.highlightBegin, alert.highlightEnd),
source: SOURCE,
severity: severity,
tags: severity === DiagnosticSeverity.Hint ? [DiagnosticTag.Unnecessary] : [],
rev: alert.rev,
start: alert.highlightBegin,
end: alert.highlightEnd,
})
} else if (alert.subalerts) {
const relatedInformation: DiagnosticRelatedInformation[] = []
alert.subalerts.forEach((subalert, i) => {
const { s: start } = subalert.transformJson.context
let highlightBegin: number = 0
let highlightEnd: number = 0
let range: Range = {} as any
subalert.transformJson.highlights.forEach((highlight, j) => {
const s = start + highlight.s
const e = start + highlight.e
const r = document.rangeAt(s, e)
if (j <= i) {
highlightBegin = s
highlightEnd = e
range = r
}
relatedInformation.push({ location: { uri: document.uri, range: r }, message: subalert.highlightText })
})
diagnostics.push({
id: alert.id,
code: alert.id,
message: toText(alert.title || alert.categoryHuman),
range: range,
source: SOURCE,
severity: severity,
relatedInformation,
rev: alert.rev,
start: highlightBegin,
end: highlightEnd,
})
})
} else {
this.LOGGER.warn('toDiagnostics', `Unhandled alert`, alert)
}
return diagnostics
}
private clearDiagnostics(document: GrammarlyDocument) {
this.connection.sendDiagnostics({ uri: document.uri, version: document.version, diagnostics: [] })
}
private sendDiagnostics(document: GrammarlyDocument, ignoreVersion = false) {
const diagnostics = Array.from(this.diagnostics.get(document.uri)?.values() || []).flat()
this.LOGGER.trace(`Diagnostics: Sending ${diagnostics.length} alerts`, diagnostics)
if (ignoreVersion) {
this.connection.sendDiagnostics({ uri: document.uri, diagnostics: diagnostics })
} else {
this.connection.sendDiagnostics({ uri: document.uri, version: document.version, diagnostics: diagnostics })
}
}
}
function toText(...html: string[]) {
return html
.filter((value) => typeof value === 'string')
.join('\n\n')
.replace(/<p>(.*?)<\/p>/gi, '$1\n\n')
.replace(/<p>/gi, '\n\n') // Explanation has unclosed <p> tag.)
.replace(/<br\/>/gi, ' \n')
.replace(/<[a-z][^/>]*?\/?>/gi, '')
.replace(/<\/[a-z][^>]*?>/gi, '')
.replace(/\n{3,}/g, '\n\n') // Remove unnecessary empty lines.
.trim()
}
function toMarkdown(...html: string[]) {
return html
.filter((value) => typeof value === 'string')
.join('\n\n')
.replace(/<b>(.*?)<\/b>/gi, '**$1**')
.replace(/<i>(.*?)<\/i>/gi, '*$1*')
.replace(/<p>(.*?)<\/p>/gi, '$1\n\n')
.replace(/<p>/gi, '\n\n') // Explanation has unclosed <p> tag.)
.replace(/<br\/>/gi, ' \n')
.replace(/<span class="red">/gi, '❌ <span style="color:#FF0000">')
.replace(/<span class="green">/gi, '✅ <span style="color:#00FF00">')
.replace(/\n{3,}/g, '\n\n') // Remove unnecessary empty lines.
.trim()
}
function unique<T>(items: T[]): T[] {
return Array.from(new Set(items))
}
function getAlertSeverity(alert: AlertEvent): DiagnosticSeverity {
if (alert.impact === 'critical') return DiagnosticSeverity.Error
switch (alert.cardLayout.outcome.toLowerCase()) {
case 'clarity':
case 'engagement':
return DiagnosticSeverity.Information
case 'tone':
return DiagnosticSeverity.Warning
case 'vox':
return DiagnosticSeverity.Hint
case 'correctness':
case 'other':
default:
return DiagnosticSeverity.Error
}
} | the_stack |
import { Template } from '@aws-cdk/assertions';
import * as notifications from '@aws-cdk/aws-codestarnotifications';
import * as iam from '@aws-cdk/aws-iam';
import * as kms from '@aws-cdk/aws-kms';
import * as cdk from '@aws-cdk/core';
import * as sns from '../lib';
/* eslint-disable quote-props */
describe('Topic', () => {
describe('topic tests', () => {
test('all defaults', () => {
const stack = new cdk.Stack();
new sns.Topic(stack, 'MyTopic');
Template.fromStack(stack).resourceCountIs('AWS::SNS::Topic', 1);
});
test('specify topicName', () => {
const stack = new cdk.Stack();
new sns.Topic(stack, 'MyTopic', {
topicName: 'topicName',
});
Template.fromStack(stack).hasResourceProperties('AWS::SNS::Topic', {
'TopicName': 'topicName',
});
});
test('specify displayName', () => {
const stack = new cdk.Stack();
new sns.Topic(stack, 'MyTopic', {
displayName: 'displayName',
});
Template.fromStack(stack).hasResourceProperties('AWS::SNS::Topic', {
'DisplayName': 'displayName',
});
});
test('specify kmsMasterKey', () => {
const stack = new cdk.Stack();
const key = new kms.Key(stack, 'CustomKey');
new sns.Topic(stack, 'MyTopic', {
masterKey: key,
});
Template.fromStack(stack).hasResourceProperties('AWS::SNS::Topic', {
'KmsMasterKeyId': { 'Fn::GetAtt': ['CustomKey1E6D0D07', 'Arn'] },
});
});
test('specify displayName and topicName', () => {
const stack = new cdk.Stack();
new sns.Topic(stack, 'MyTopic', {
topicName: 'topicName',
displayName: 'displayName',
});
Template.fromStack(stack).hasResourceProperties('AWS::SNS::Topic', {
'DisplayName': 'displayName',
'TopicName': 'topicName',
});
});
// NOTE: This test case should be invalid when CloudFormation problem reported in CDK issue 12386 is resolved
// see https://github.com/aws/aws-cdk/issues/12386
test('throw with missing topicName on fifo topic', () => {
const stack = new cdk.Stack();
expect(() => new sns.Topic(stack, 'MyTopic', {
fifo: true,
})).toThrow(/FIFO SNS topics must be given a topic name./);
});
test('specify fifo without .fifo suffix in topicName', () => {
const stack = new cdk.Stack();
new sns.Topic(stack, 'MyTopic', {
fifo: true,
topicName: 'topicName',
});
Template.fromStack(stack).hasResourceProperties('AWS::SNS::Topic', {
'FifoTopic': true,
'TopicName': 'topicName.fifo',
});
});
test('specify fifo with .fifo suffix in topicName', () => {
const stack = new cdk.Stack();
new sns.Topic(stack, 'MyTopic', {
fifo: true,
topicName: 'topicName.fifo',
});
Template.fromStack(stack).hasResourceProperties('AWS::SNS::Topic', {
'FifoTopic': true,
'TopicName': 'topicName.fifo',
});
});
test('specify fifo without contentBasedDeduplication', () => {
const stack = new cdk.Stack();
new sns.Topic(stack, 'MyTopic', {
fifo: true,
topicName: 'topicName',
});
Template.fromStack(stack).hasResourceProperties('AWS::SNS::Topic', {
'FifoTopic': true,
'TopicName': 'topicName.fifo',
});
});
test('specify fifo with contentBasedDeduplication', () => {
const stack = new cdk.Stack();
new sns.Topic(stack, 'MyTopic', {
contentBasedDeduplication: true,
fifo: true,
topicName: 'topicName',
});
Template.fromStack(stack).hasResourceProperties('AWS::SNS::Topic', {
'ContentBasedDeduplication': true,
'FifoTopic': true,
'TopicName': 'topicName.fifo',
});
});
test('throw with contentBasedDeduplication on non-fifo topic', () => {
const stack = new cdk.Stack();
expect(() => new sns.Topic(stack, 'MyTopic', {
contentBasedDeduplication: true,
})).toThrow(/Content based deduplication can only be enabled for FIFO SNS topics./);
});
});
test('can add a policy to the topic', () => {
// GIVEN
const stack = new cdk.Stack();
const topic = new sns.Topic(stack, 'Topic');
// WHEN
topic.addToResourcePolicy(new iam.PolicyStatement({
resources: ['*'],
actions: ['sns:*'],
principals: [new iam.ArnPrincipal('arn')],
}));
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::SNS::TopicPolicy', {
PolicyDocument: {
Version: '2012-10-17',
Statement: [{
'Sid': '0',
'Action': 'sns:*',
'Effect': 'Allow',
'Principal': { 'AWS': 'arn' },
'Resource': '*',
}],
},
});
});
test('give publishing permissions', () => {
// GIVEN
const stack = new cdk.Stack();
const topic = new sns.Topic(stack, 'Topic');
const user = new iam.User(stack, 'User');
// WHEN
topic.grantPublish(user);
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::IAM::Policy', {
'PolicyDocument': {
Version: '2012-10-17',
'Statement': [
{
'Action': 'sns:Publish',
'Effect': 'Allow',
'Resource': stack.resolve(topic.topicArn),
},
],
},
});
});
test('TopicPolicy passed document', () => {
// GIVEN
const stack = new cdk.Stack();
const topic = new sns.Topic(stack, 'MyTopic');
const ps = new iam.PolicyStatement({
actions: ['service:statement0'],
principals: [new iam.ArnPrincipal('arn')],
});
// WHEN
new sns.TopicPolicy(stack, 'topicpolicy', { topics: [topic], policyDocument: new iam.PolicyDocument({ assignSids: true, statements: [ps] }) });
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::SNS::TopicPolicy', {
'PolicyDocument': {
'Statement': [
{
'Action': 'service:statement0',
'Effect': 'Allow',
'Principal': { 'AWS': 'arn' },
'Sid': '0',
},
],
'Version': '2012-10-17',
},
'Topics': [
{
'Ref': 'MyTopic86869434',
},
],
});
});
test('Add statements to policy', () => {
// GIVEN
const stack = new cdk.Stack();
const topic = new sns.Topic(stack, 'MyTopic');
// WHEN
const topicPolicy = new sns.TopicPolicy(stack, 'TopicPolicy', {
topics: [topic],
});
topicPolicy.document.addStatements(new iam.PolicyStatement({
actions: ['service:statement0'],
principals: [new iam.ArnPrincipal('arn')],
}));
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::SNS::TopicPolicy', {
'PolicyDocument': {
'Statement': [
{
'Action': 'service:statement0',
'Effect': 'Allow',
'Principal': { 'AWS': 'arn' },
'Sid': '0',
},
],
'Version': '2012-10-17',
},
'Topics': [
{
'Ref': 'MyTopic86869434',
},
],
});
});
test('topic resource policy includes unique SIDs', () => {
const stack = new cdk.Stack();
const topic = new sns.Topic(stack, 'MyTopic');
topic.addToResourcePolicy(new iam.PolicyStatement({
actions: ['service:statement0'],
principals: [new iam.ArnPrincipal('arn')],
}));
topic.addToResourcePolicy(new iam.PolicyStatement({
actions: ['service:statement1'],
principals: [new iam.ArnPrincipal('arn')],
}));
Template.fromStack(stack).hasResourceProperties('AWS::SNS::TopicPolicy', {
'PolicyDocument': {
'Statement': [
{
'Action': 'service:statement0',
'Effect': 'Allow',
'Principal': { 'AWS': 'arn' },
'Sid': '0',
},
{
'Action': 'service:statement1',
'Effect': 'Allow',
'Principal': { 'AWS': 'arn' },
'Sid': '1',
},
],
'Version': '2012-10-17',
},
'Topics': [
{
'Ref': 'MyTopic86869434',
},
],
});
});
test('fromTopicArn', () => {
// GIVEN
const stack2 = new cdk.Stack();
// WHEN
const imported = sns.Topic.fromTopicArn(stack2, 'Imported', 'arn:aws:sns:*:123456789012:my_corporate_topic');
// THEN
expect(imported.topicName).toEqual('my_corporate_topic');
expect(imported.topicArn).toEqual('arn:aws:sns:*:123456789012:my_corporate_topic');
});
test('test metrics', () => {
// GIVEN
const stack = new cdk.Stack();
const topic = new sns.Topic(stack, 'Topic');
// THEN
expect(stack.resolve(topic.metricNumberOfMessagesPublished())).toEqual({
dimensions: { TopicName: { 'Fn::GetAtt': ['TopicBFC7AF6E', 'TopicName'] } },
namespace: 'AWS/SNS',
metricName: 'NumberOfMessagesPublished',
period: cdk.Duration.minutes(5),
statistic: 'Sum',
});
expect(stack.resolve(topic.metricPublishSize())).toEqual({
dimensions: { TopicName: { 'Fn::GetAtt': ['TopicBFC7AF6E', 'TopicName'] } },
namespace: 'AWS/SNS',
metricName: 'PublishSize',
period: cdk.Duration.minutes(5),
statistic: 'Average',
});
});
test('subscription is created under the topic scope by default', () => {
// GIVEN
const stack = new cdk.Stack();
const topic = new sns.Topic(stack, 'Topic');
// WHEN
topic.addSubscription({
bind: () => ({
protocol: sns.SubscriptionProtocol.HTTP,
endpoint: 'http://foo/bar',
subscriberId: 'my-subscription',
}),
});
// THEN
Template.fromStack(stack).resourceCountIs('AWS::SNS::Subscription', 1);
});
test('if "scope" is defined, subscription will be created under that scope', () => {
// GIVEN
const app = new cdk.App();
const stack = new cdk.Stack(app, 'A');
const stack2 = new cdk.Stack(app, 'B');
const topic = new sns.Topic(stack, 'Topic');
// WHEN
topic.addSubscription({
bind: () => ({
protocol: sns.SubscriptionProtocol.HTTP,
endpoint: 'http://foo/bar',
subscriberScope: stack2,
subscriberId: 'subscriberId',
}),
});
// THEN
Template.fromStack(stack).resourceCountIs('AWS::SNS::Subscription', 0);
Template.fromStack(stack2).resourceCountIs('AWS::SNS::Subscription', 1);
});
test('fails if topic policy has no actions', () => {
// GIVEN
const app = new cdk.App();
const stack = new cdk.Stack(app, 'my-stack');
const topic = new sns.Topic(stack, 'Topic');
// WHEN
topic.addToResourcePolicy(new iam.PolicyStatement({
resources: ['*'],
principals: [new iam.ArnPrincipal('arn')],
}));
// THEN
expect(() => app.synth()).toThrow(/A PolicyStatement must specify at least one \'action\' or \'notAction\'/);
});
test('fails if topic policy has no IAM principals', () => {
// GIVEN
const app = new cdk.App();
const stack = new cdk.Stack(app, 'my-stack');
const topic = new sns.Topic(stack, 'Topic');
// WHEN
topic.addToResourcePolicy(new iam.PolicyStatement({
resources: ['*'],
actions: ['sns:*'],
}));
// THEN
expect(() => app.synth()).toThrow(/A PolicyStatement used in a resource-based policy must specify at least one IAM principal/);
});
test('topic policy should be set if topic as a notifications rule target', () => {
const app = new cdk.App();
const stack = new cdk.Stack(app, 'my-stack');
const topic = new sns.Topic(stack, 'Topic');
const rule = new notifications.NotificationRule(stack, 'MyNotificationRule', {
source: {
bindAsNotificationRuleSource: () => ({
sourceArn: 'ARN',
}),
},
events: ['codebuild-project-build-state-succeeded'],
});
rule.addTarget(topic);
Template.fromStack(stack).hasResourceProperties('AWS::SNS::TopicPolicy', {
PolicyDocument: {
Version: '2012-10-17',
Statement: [{
'Sid': '0',
'Action': 'sns:Publish',
'Effect': 'Allow',
'Principal': { 'Service': 'codestar-notifications.amazonaws.com' },
'Resource': { 'Ref': 'TopicBFC7AF6E' },
}],
},
Topics: [{
Ref: 'TopicBFC7AF6E',
}],
});
});
}); | the_stack |
import {
INodeProperties,
} from 'n8n-workflow';
export const playlistOperations: INodeProperties[] = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
displayOptions: {
show: {
resource: [
'playlist',
],
},
},
options: [
{
name: 'Create',
value: 'create',
description: 'Create a playlist',
},
{
name: 'Delete',
value: 'delete',
description: 'Delete a playlist',
},
{
name: 'Get',
value: 'get',
description: 'Get a playlist',
},
{
name: 'Get All',
value: 'getAll',
description: 'Retrieve all playlists',
},
{
name: 'Update',
value: 'update',
description: 'Update a playlist',
},
],
default: 'getAll',
description: 'The operation to perform.',
},
];
export const playlistFields: INodeProperties[] = [
/* -------------------------------------------------------------------------- */
/* playlist:create */
/* -------------------------------------------------------------------------- */
{
displayName: 'Title',
name: 'title',
type: 'string',
required: true,
displayOptions: {
show: {
operation: [
'create',
],
resource: [
'playlist',
],
},
},
default: '',
description: `The playlist's title.`,
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
show: {
operation: [
'create',
],
resource: [
'playlist',
],
},
},
options: [
{
displayName: 'Description',
name: 'description',
type: 'string',
default: '',
description: `The playlist's description.`,
},
{
displayName: 'Privacy Status',
name: 'privacyStatus',
type: 'options',
options: [
{
name: 'Private',
value: 'private',
},
{
name: 'Public',
value: 'public',
},
{
name: 'Unlisted',
value: 'unlisted',
},
],
default: '',
description: `The playlist's privacy status.`,
},
{
displayName: 'Tags',
name: 'tags',
type: 'string',
default: '',
description: `Keyword tags associated with the playlist. Mulplie can be defined separated by comma`,
},
{
displayName: 'Default Language',
name: 'defaultLanguage',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getLanguages',
},
default: '',
description: `The language of the text in the playlist resource's title and description properties.`,
},
{
displayName: 'On Behalf Of Content Owner Channel',
name: 'onBehalfOfContentOwnerChannel',
type: 'string',
default: '',
description: `The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter.`,
},
{
displayName: 'On Behalf Of Content Owner',
name: 'onBehalfOfContentOwner',
type: 'string',
default: '',
description: `The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value`,
},
],
},
/* -------------------------------------------------------------------------- */
/* playlist:get */
/* -------------------------------------------------------------------------- */
{
displayName: 'Playlist ID',
name: 'playlistId',
type: 'string',
required: true,
displayOptions: {
show: {
operation: [
'get',
],
resource: [
'playlist',
],
},
},
default: '',
},
{
displayName: 'Fields',
name: 'part',
type: 'multiOptions',
options: [
{
name: '*',
value: '*',
},
{
name: 'Content Details',
value: 'contentDetails',
},
{
name: 'ID',
value: 'id',
},
{
name: 'Localizations',
value: 'localizations',
},
{
name: 'Player',
value: 'player',
},
{
name: 'Snippet',
value: 'snippet',
},
{
name: 'Status',
value: 'status',
},
],
required: true,
displayOptions: {
show: {
operation: [
'get',
],
resource: [
'playlist',
],
},
},
description: 'The fields parameter specifies a comma-separated list of one or more playlist resource properties that the API response will include.',
default: ['*'],
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
show: {
operation: [
'get',
],
resource: [
'playlist',
],
},
},
options: [
{
displayName: 'On Behalf Of Content Owner',
name: 'onBehalfOfContentOwner',
type: 'string',
default: '',
description: `The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value`,
},
{
displayName: 'On Behalf Of Content Owner Channel',
name: 'onBehalfOfContentOwnerChannel',
type: 'string',
default: '',
description: `The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added`,
},
],
},
/* -------------------------------------------------------------------------- */
/* playlist:delete */
/* -------------------------------------------------------------------------- */
{
displayName: 'Playlist ID',
name: 'playlistId',
type: 'string',
required: true,
displayOptions: {
show: {
operation: [
'delete',
],
resource: [
'playlist',
],
},
},
default: '',
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
show: {
operation: [
'delete',
],
resource: [
'playlist',
],
},
},
options: [
{
displayName: 'On Behalf Of Content Owner',
name: 'onBehalfOfContentOwner',
type: 'string',
default: '',
description: `The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value`,
},
],
},
/* -------------------------------------------------------------------------- */
/* playlist:getAll */
/* -------------------------------------------------------------------------- */
{
displayName: 'Fields',
name: 'part',
type: 'multiOptions',
options: [
{
name: '*',
value: '*',
},
{
name: 'Content Details',
value: 'contentDetails',
},
{
name: 'ID',
value: 'id',
},
{
name: 'Localizations',
value: 'localizations',
},
{
name: 'Player',
value: 'player',
},
{
name: 'Snippet',
value: 'snippet',
},
{
name: 'Status',
value: 'status',
},
],
required: true,
displayOptions: {
show: {
operation: [
'getAll',
],
resource: [
'playlist',
],
},
},
description: 'The fields parameter specifies a comma-separated list of one or more playlist resource properties that the API response will include.',
default: ['*'],
},
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
operation: [
'getAll',
],
resource: [
'playlist',
],
},
},
default: false,
description: 'If all results should be returned or only up to a given limit.',
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
displayOptions: {
show: {
operation: [
'getAll',
],
resource: [
'playlist',
],
returnAll: [
false,
],
},
},
typeOptions: {
minValue: 1,
maxValue: 50,
},
default: 25,
description: 'How many results to return.',
},
{
displayName: 'Filters',
name: 'filters',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
show: {
operation: [
'getAll',
],
resource: [
'playlist',
],
},
},
options: [
{
displayName: 'Channel ID',
name: 'channelId',
type: 'string',
default: '',
description: `This value indicates that the API should only return the specified channel's playlists.`,
},
{
displayName: 'ID',
name: 'id',
type: 'string',
default: '',
description: `The id parameter specifies a comma-separated list of the YouTube playlist ID(s) for the resource(s) that are being retrieved. In a playlist resource, the id property specifies the playlist's YouTube playlist ID.`,
},
],
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
show: {
operation: [
'getAll',
],
resource: [
'playlist',
],
},
},
options: [
{
displayName: 'On Behalf Of Content Owner Channel',
name: 'onBehalfOfContentOwnerChannel',
type: 'string',
default: '',
description: `The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter.`,
},
{
displayName: 'On Behalf Of Content Owner',
name: 'onBehalfOfContentOwner',
type: 'string',
default: '',
description: `The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value`,
},
],
},
/* -------------------------------------------------------------------------- */
/* playlist:update */
/* -------------------------------------------------------------------------- */
{
displayName: 'Playlist ID',
name: 'playlistId',
type: 'string',
required: true,
displayOptions: {
show: {
operation: [
'update',
],
resource: [
'playlist',
],
},
},
default: '',
description: `The playlist's title.`,
},
{
displayName: 'Title',
name: 'title',
type: 'string',
required: true,
displayOptions: {
show: {
operation: [
'update',
],
resource: [
'playlist',
],
},
},
default: '',
description: `The playlist's title.`,
},
{
displayName: 'Update Fields',
name: 'updateFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
operation: [
'update',
],
resource: [
'playlist',
],
},
},
options: [
{
displayName: 'Default Language',
name: 'defaultLanguage',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getLanguages',
},
default: '',
description: `The language of the text in the playlist resource's title and description properties.`,
},
{
displayName: 'Description',
name: 'description',
type: 'string',
default: '',
description: `The playlist's description.`,
},
{
displayName: 'On Behalf Of Content Owner',
name: 'onBehalfOfContentOwner',
type: 'string',
default: '',
description: `The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value`,
},
{
displayName: 'Privacy Status',
name: 'privacyStatus',
type: 'options',
options: [
{
name: 'Private',
value: 'private',
},
{
name: 'Public',
value: 'public',
},
{
name: 'Unlisted',
value: 'unlisted',
},
],
default: '',
description: `The playlist's privacy status.`,
},
{
displayName: 'Tags',
name: 'tags',
type: 'string',
default: '',
description: `Keyword tags associated with the playlist. Mulplie can be defined separated by comma`,
},
],
},
]; | the_stack |
* ExportBashEvents请求参数结构体
*/
export interface ExportBashEventsRequest {
/**
* 过滤参数
*/
Filters?: Array<Filters>
}
/**
* DescribeSearchTemplates返回参数结构体
*/
export interface DescribeSearchTemplatesResponse {
/**
* 总数
*/
TotalCount: number
/**
* 模板列表
*/
List: Array<SearchTemplate>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportReverseShellEvents返回参数结构体
*/
export interface ExportReverseShellEventsResponse {
/**
* 导出文件下载链接地址。
*/
DownloadUrl: string
/**
* 任务id
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBaselineTop返回参数结构体
*/
export interface DescribeBaselineTopResponse {
/**
* 检测项Top列表
注意:此字段可能返回 null,表示取不到有效值。
*/
RuleTopList: Array<BaselineRuleTopInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetWebServiceInfoList返回参数结构体
*/
export interface DescribeAssetWebServiceInfoListResponse {
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
WebServices: Array<AssetWebServiceBaseInfo>
/**
* 总数量
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetAppProcessList返回参数结构体
*/
export interface DescribeAssetAppProcessListResponse {
/**
* 进程列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Process: Array<AssetAppProcessInfo>
/**
* 分区总数
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ScanVulAgain请求参数结构体
*/
export interface ScanVulAgainRequest {
/**
* 漏洞事件id串,多个用英文逗号分隔
*/
EventIds: string
/**
* 重新检查的机器uuid,多个逗号分隔
*/
Uuids?: string
}
/**
* DeleteBaselineStrategy返回参数结构体
*/
export interface DeleteBaselineStrategyResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportWebPageEventList返回参数结构体
*/
export interface ExportWebPageEventListResponse {
/**
* 任务id 可通过 ExportTasks接口下载
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* InquiryPriceOpenProVersionPrepaid请求参数结构体
*/
export interface InquiryPriceOpenProVersionPrepaidRequest {
/**
* 预付费模式(包年包月)参数设置。
*/
ChargePrepaid: ChargePrepaid
/**
* 需要开通专业版机器列表数组。
*/
Machines: Array<ProVersionMachine>
}
/**
* DescribeUndoVulCounts返回参数结构体
*/
export interface DescribeUndoVulCountsResponse {
/**
* 未处理的漏洞数
注意:此字段可能返回 null,表示取不到有效值。
*/
UndoVulCount: number
/**
* 未处理的主机数
注意:此字段可能返回 null,表示取不到有效值。
*/
UndoHostCount: number
/**
* 普通版主机数
注意:此字段可能返回 null,表示取不到有效值。
*/
NotProfessionCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBaselineScanSchedule返回参数结构体
*/
export interface DescribeBaselineScanScheduleResponse {
/**
* 检测进度(百分比)
注意:此字段可能返回 null,表示取不到有效值。
*/
Schedule: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 恶意请求白名单列表信息
*/
export interface MaliciousRequestWhiteListInfo {
/**
* 白名单id
*/
Id: number
/**
* 域名
*/
Domain: string
/**
* 备注
*/
Mark: string
/**
* 创建时间
*/
CreateTime: string
/**
* 更新时间
*/
ModifyTime: string
}
/**
* DeleteBashEvents返回参数结构体
*/
export interface DeleteBashEventsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetProcessInfoList请求参数结构体
*/
export interface DescribeAssetProcessInfoListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Name - String - 是否必填:否 - 进程名</li>
<li>User - String - 是否必填:否 - 进程用户</li>
<li>Group - String - 是否必填:否 - 进程用户组</li>
<li>Pid - uint64 - 是否必填:否 - 进程ID</li>
<li>Ppid - uint64 - 是否必填:否 - 父进程ID</li>
<li>OsType - uint64 - 是否必填:否 - windows/linux</li>
<li>Status - string - 是否必填:否 - 进程状态:
1:R 可执行
2:S 可中断
3:D 不可中断
4:T 暂停状态或跟踪状态
5:Z 僵尸状态
6:X 将被销毁</li>
<li>RunTimeStart - String - 是否必填:否 - 运行开始时间</li>
<li>RunTimeEnd - String - 是否必填:否 - 运行结束时间</li>
<li>InstallByPackage - uint64 - 是否必填:否 - 是否包安装:0否,1是</li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )</li>
*/
Filters?: Array<Filter>
/**
* 查询指定Quuid主机的信息
*/
Quuid?: string
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 排序方式:StartTime
*/
By?: string
}
/**
* ExportWebPageEventList请求参数结构体
*/
export interface ExportWebPageEventListRequest {
/**
* 过滤条件
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>EventType - String - 是否必填:否 - 事件类型</li>
<li>EventStatus - String - 是否必填:否 - 事件状态</li>
*/
Filters?: Array<AssetFilters>
/**
* 排序方式:CreateTime 或 RestoreTime,默认为CreateTime
*/
By?: string
/**
* 排序方式,0降序,1升序,默认为0
*/
Order?: number
}
/**
* 资产管理网卡信息
*/
export interface AssetNetworkCardInfo {
/**
* 网卡名称
*/
Name: string
/**
* Ipv4对应IP
*/
Ip: string
/**
* 网关
*/
GateWay: string
/**
* MAC地址
*/
Mac: string
/**
* Ipv6对应IP
*/
Ipv6: string
/**
* DNS服务器
*/
DnsServer: string
}
/**
* DescribeAssetWebFrameList请求参数结构体
*/
export interface DescribeAssetWebFrameListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Name - String - 是否必填:否 - 框架名</li>
<li>NameStrict - String - 是否必填:否 - 框架名(严格匹配)</li>
<li>Lang - String - 是否必填:否 - 框架语言:java/python</li>
<li>Type - String - 是否必填:否 - 服务类型:
0:全部
1:Tomcat
2:Apache
3:Nginx
4:WebLogic
5:Websphere
6:JBoss
7:WildFly
8:Jetty
9:IHS
10:Tengine</li>
<li>OsType - String - 是否必填:否 - windows/linux</li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )</li>
*/
Filters?: Array<Filter>
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 可选排序:JarCount
*/
By?: string
/**
* 查询指定Quuid主机的信息
*/
Quuid?: string
}
/**
* DescribeMonthInspectionReport返回参数结构体
*/
export interface DescribeMonthInspectionReportResponse {
/**
* 总条数
*/
TotalCount: number
/**
* 巡检报告列表
*/
List: Array<MonthInspectionReport>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeSaveOrUpdateWarnings返回参数结构体
*/
export interface DescribeSaveOrUpdateWarningsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBaselineHostTop返回参数结构体
*/
export interface DescribeBaselineHostTopResponse {
/**
* 主机基线策略事件Top
注意:此字段可能返回 null,表示取不到有效值。
*/
BaselineHostTopList: Array<BaselineHostTopList>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteBashRules返回参数结构体
*/
export interface DeleteBashRulesResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportVulList返回参数结构体
*/
export interface ExportVulListResponse {
/**
* 导出的文件下载url(已弃用!)
注意:此字段可能返回 null,表示取不到有效值。
*/
DownloadUrl: string
/**
* 导出文件Id 可通过ExportTasks接口下载
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeHistoryService返回参数结构体
*/
export interface DescribeHistoryServiceResponse {
/**
* 1 可购买 2 只能升降配 3 只能跳到续费管理页
*/
BuyStatus: number
/**
* 用户已购容量 单位 G
*/
InquireNum: number
/**
* 到期时间
*/
EndTime: string
/**
* 是否自动续费,0 初始值, 1 开通 2 没开通
*/
IsAutoOpenRenew: number
/**
* 资源ID
*/
ResourceId: string
/**
* 0 没开通 1 正常 2隔离 3销毁
*/
Status: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 基线影响主机信息
*/
export interface BaselineEffectHost {
/**
* 通过项
注意:此字段可能返回 null,表示取不到有效值。
*/
PassCount: number
/**
* 风险项
注意:此字段可能返回 null,表示取不到有效值。
*/
FailCount: number
/**
* 首次检测事件
注意:此字段可能返回 null,表示取不到有效值。
*/
FirstScanTime: string
/**
* 最后检测时间
注意:此字段可能返回 null,表示取不到有效值。
*/
LastScanTime: string
/**
* 处理状态
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: number
/**
* 主机Quuid
注意:此字段可能返回 null,表示取不到有效值。
*/
Quuid: string
/**
* 主机IP
注意:此字段可能返回 null,表示取不到有效值。
*/
HostIp: string
/**
* 主机别名
注意:此字段可能返回 null,表示取不到有效值。
*/
AliasName: string
/**
* 主机Uuid
注意:此字段可能返回 null,表示取不到有效值。
*/
Uuid: string
/**
* 检测中状态
注意:此字段可能返回 null,表示取不到有效值。
*/
MaxStatus: number
}
/**
* ModifyWebPageProtectSetting返回参数结构体
*/
export interface ModifyWebPageProtectSettingResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeVulInfoCvss返回参数结构体
*/
export interface DescribeVulInfoCvssResponse {
/**
* 漏洞id
注意:此字段可能返回 null,表示取不到有效值。
*/
VulId: number
/**
* 漏洞名称
注意:此字段可能返回 null,表示取不到有效值。
*/
VulName: string
/**
* 危害等级:1-低危;2-中危;3-高危;4-严重
注意:此字段可能返回 null,表示取不到有效值。
*/
VulLevel: number
/**
* 漏洞分类 1: web应用漏洞 2:系统组件漏洞
注意:此字段可能返回 null,表示取不到有效值。
*/
VulType: number
/**
* 漏洞描述信息
注意:此字段可能返回 null,表示取不到有效值。
*/
Description: string
/**
* 修复方案
注意:此字段可能返回 null,表示取不到有效值。
*/
RepairPlan: string
/**
* 漏洞CVEID
注意:此字段可能返回 null,表示取不到有效值。
*/
CveId: string
/**
* 参考链接
注意:此字段可能返回 null,表示取不到有效值。
*/
Reference: string
/**
* CVSS信息,wiki:http://tapd.oa.com/Teneyes/markdown_wikis/view/#1010131751011792303
注意:此字段可能返回 null,表示取不到有效值。
*/
CVSS: string
/**
* 发布时间
注意:此字段可能返回 null,表示取不到有效值。
*/
PublicDate: string
/**
* Cvss分数
注意:此字段可能返回 null,表示取不到有效值。
*/
CvssScore: number
/**
* cvss详情
注意:此字段可能返回 null,表示取不到有效值。
*/
CveInfo: string
/**
* cvss 分数 浮点型
注意:此字段可能返回 null,表示取不到有效值。
*/
CvssScoreFloat: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBaselineStrategyDetail请求参数结构体
*/
export interface DescribeBaselineStrategyDetailRequest {
/**
* 用户基线策略id
*/
StrategyId: number
}
/**
* 木马列表集合
*/
export interface MalWareList {
/**
* 服务器ip
*/
HostIp: string
/**
* 唯一UUID
*/
Uuid: string
/**
* 路径
*/
FilePath: string
/**
* 描述
*/
VirusName: string
/**
* 状态;4-:待处理,5-已信任,6-已隔离
*/
Status: number
/**
* 唯一ID
注意:此字段可能返回 null,表示取不到有效值。
*/
Id: number
/**
* 主机别名
*/
Alias: string
/**
* 特性标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tags: Array<string>
/**
* 首次运行时间
注意:此字段可能返回 null,表示取不到有效值。
*/
FileCreateTime: string
/**
* 最近运行时间
注意:此字段可能返回 null,表示取不到有效值。
*/
FileModifierTime: string
/**
* 创建时间
*/
CreateTime: string
/**
* 最近扫描时间
*/
LatestScanTime: string
}
/**
* DescribeAssetUserInfo返回参数结构体
*/
export interface DescribeAssetUserInfoResponse {
/**
* 用户详细信息
*/
User: AssetUserDetail
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 标签信息
*/
export interface Tag {
/**
* 标签ID
*/
Id: number
/**
* 标签名
*/
Name: string
/**
* 服务器数
*/
Count: number
}
/**
* ExportAttackLogs返回参数结构体
*/
export interface ExportAttackLogsResponse {
/**
* 已废弃
*/
DownloadUrl: string
/**
* 导出任务ID 可通过ExportTasks接口下载
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBaselineEffectHostList返回参数结构体
*/
export interface DescribeBaselineEffectHostListResponse {
/**
* 记录总数
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalCount: number
/**
* 影响服务器列表
注意:此字段可能返回 null,表示取不到有效值。
*/
EffectHostList: Array<BaselineEffectHost>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* TrustMalwares请求参数结构体
*/
export interface TrustMalwaresRequest {
/**
* 木马ID数组(单次不超过的最大条数:100)
*/
Ids: Array<number>
}
/**
* ExportVulEffectHostList请求参数结构体
*/
export interface ExportVulEffectHostListRequest {
/**
* 漏洞id
*/
VulId: number
/**
* 过滤条件。
<li>AliasName - String - 主机名筛选</li>
*/
Filters?: Array<Filter>
}
/**
* DescribeBaselineBasicInfo请求参数结构体
*/
export interface DescribeBaselineBasicInfoRequest {
/**
* 基线名称
*/
BaselineName?: string
}
/**
* DescribeProVersionInfo请求参数结构体
*/
export type DescribeProVersionInfoRequest = null
/**
* DescribeVulCountByDates请求参数结构体
*/
export interface DescribeVulCountByDatesRequest {
/**
* 需要查询最近几天的数据,需要都 -1后传入
*/
LastDays?: Array<number>
/**
* 漏洞的分类,最小值为1最大值为5
*/
VulCategory?: number
/**
* 是否为应急漏洞筛选 是: yes
*/
IfEmergency?: string
}
/**
* DescribeBaselineStrategyList返回参数结构体
*/
export interface DescribeBaselineStrategyListResponse {
/**
* 分页查询记录的总数
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalCount: number
/**
* 用户策略信息列表
注意:此字段可能返回 null,表示取不到有效值。
*/
StrategyList: Array<Strategy>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 网络攻击日志
*/
export interface DefendAttackLog {
/**
* 日志ID
*/
Id: number
/**
* 客户端ID
*/
Uuid: string
/**
* 来源IP
*/
SrcIp: string
/**
* 来源端口
*/
SrcPort: number
/**
* 攻击方式
*/
HttpMethod: string
/**
* 攻击描述
*/
HttpCgi: string
/**
* 攻击参数
*/
HttpParam: string
/**
* 威胁类型
*/
VulType: string
/**
* 攻击时间
*/
CreatedAt: string
/**
* 目标服务器IP
*/
MachineIp: string
/**
* 目标服务器名称
*/
MachineName: string
/**
* 目标IP
*/
DstIp: string
/**
* 目标端口
*/
DstPort: number
/**
* 攻击内容
*/
HttpContent: string
}
/**
* DescribeAssetEnvList返回参数结构体
*/
export interface DescribeAssetEnvListResponse {
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Envs: Array<AssetEnvBaseInfo>
/**
* 总数量
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAttackLogInfo返回参数结构体
*/
export interface DescribeAttackLogInfoResponse {
/**
* 日志ID
*/
Id: number
/**
* 主机ID
*/
Quuid: string
/**
* 攻击来源端口
*/
SrcPort: number
/**
* 攻击来源IP
*/
SrcIp: string
/**
* 攻击目标端口
*/
DstPort: number
/**
* 攻击目标IP
*/
DstIp: string
/**
* 攻击方法
*/
HttpMethod: string
/**
* 攻击目标主机
*/
HttpHost: string
/**
* 攻击头信息
*/
HttpHead: string
/**
* 攻击者浏览器标识
*/
HttpUserAgent: string
/**
* 请求源
*/
HttpReferer: string
/**
* 威胁类型
*/
VulType: string
/**
* 攻击路径
*/
HttpCgi: string
/**
* 攻击参数
*/
HttpParam: string
/**
* 攻击时间
*/
CreatedAt: string
/**
* 攻击内容
*/
HttpContent: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribePrivilegeEvents返回参数结构体
*/
export interface DescribePrivilegeEventsResponse {
/**
* 数据列表
*/
List: Array<PrivilegeEscalationProcess>
/**
* 总条数
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeOverviewStatistics返回参数结构体
*/
export interface DescribeOverviewStatisticsResponse {
/**
* 服务器在线数。
*/
OnlineMachineNum: number
/**
* 专业服务器数。
*/
ProVersionMachineNum: number
/**
* 木马文件数。
*/
MalwareNum: number
/**
* 异地登录数。
*/
NonlocalLoginNum: number
/**
* 暴力破解成功数。
*/
BruteAttackSuccessNum: number
/**
* 漏洞数。
*/
VulNum: number
/**
* 安全基线数。
*/
BaseLineNum: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeMonthInspectionReport请求参数结构体
*/
export interface DescribeMonthInspectionReportRequest {
/**
* 分页大小
*/
Limit: number
/**
* 分页步长
*/
Offset: number
}
/**
* 专家服务-旗舰护网信息
*/
export interface ProtectNetInfo {
/**
* 任务id
*/
TaskId: string
/**
* 护网天数
*/
ProtectDays: number
/**
* 护网状态 0未启动,1护网中,2已完成
*/
Status: number
/**
* 护网启动时间
*/
StartTime: string
/**
* 护网完成时间
*/
EndTime: string
/**
* 报告下载地址
*/
ReportPath: string
}
/**
* 反弹Shell规则
*/
export interface ReverseShellRule {
/**
* 规则ID
*/
Id: number
/**
* 客户端ID
*/
Uuid: string
/**
* 进程名称
*/
ProcessName: string
/**
* 目标IP
*/
DestIp: string
/**
* 目标端口
*/
DestPort: string
/**
* 操作人
*/
Operator: string
/**
* 是否全局规则
*/
IsGlobal: number
/**
* 状态 (0: 有效 1: 无效)
*/
Status: number
/**
* 创建时间
*/
CreateTime: string
/**
* 修改时间
*/
ModifyTime: string
/**
* 主机IP
*/
Hostip: string
}
/**
* DescribeBashRules返回参数结构体
*/
export interface DescribeBashRulesResponse {
/**
* 列表内容
*/
List: Array<BashRule>
/**
* 总条数
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAvailableExpertServiceDetail返回参数结构体
*/
export interface DescribeAvailableExpertServiceDetailResponse {
/**
* 安全管家订单
*/
ExpertService: Array<ExpertServiceOrderInfo>
/**
* 应急响应可用次数
*/
EmergencyResponse: number
/**
* 旗舰护网可用次数
*/
ProtectNet: number
/**
* 是否购买过安全管家
*/
ExpertServiceBuy: boolean
/**
* 是否购买过应急响应
*/
EmergencyResponseBuy: boolean
/**
* 是否哦购买过旗舰护网
*/
ProtectNetBuy: boolean
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ChangeRuleEventsIgnoreStatus请求参数结构体
*/
export interface ChangeRuleEventsIgnoreStatusRequest {
/**
* 忽略状态 0:取消忽略 ; 1:忽略
*/
IgnoreStatus: number
/**
* 检测项id数组
*/
RuleIdList?: Array<number>
/**
* 事件id数组
*/
EventIdList?: Array<number>
}
/**
* DescribeWebPageEventList请求参数结构体
*/
export interface DescribeWebPageEventListRequest {
/**
* 过滤条件
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>EventType - String - 是否必填:否 - 事件类型</li>
<li>EventStatus - String - 是否必填:否 - 事件状态</li>
*/
Filters?: Array<AssetFilters>
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 排序方式:CreateTime 或 RestoreTime,默认为CreateTime
*/
By?: string
/**
* 排序方式,0降序,1升序,默认为0
*/
Order?: number
}
/**
* ExportAssetCoreModuleList请求参数结构体
*/
export interface ExportAssetCoreModuleListRequest {
/**
* 过滤条件。
<li>Name- string - 是否必填:否 - 包名</li>
<li>User- string - 是否必填:否 - 用户</li>
*/
Filters?: Array<AssetFilters>
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 排序依据:Size,ProcessCount,ModuleCount
*/
By?: string
/**
* 服务器Uuid
*/
Uuid?: string
/**
* 服务器Quuid
*/
Quuid?: string
}
/**
* DescribeComponentStatistics返回参数结构体
*/
export interface DescribeComponentStatisticsResponse {
/**
* 组件统计列表记录总数。
*/
TotalCount: number
/**
* 组件统计列表数据数组。
*/
ComponentStatistics: Array<ComponentStatistics>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeMachineRegions请求参数结构体
*/
export type DescribeMachineRegionsRequest = null
/**
* DescribeSearchExportList返回参数结构体
*/
export interface DescribeSearchExportListResponse {
/**
* 导出的任务号
*/
TaskId: number
/**
* 下载地址
*/
DownloadUrl: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 标准阻断模式规则
*/
export interface BruteAttackRule {
/**
* 爆破事件发生的时间范围,单位:秒
*/
TimeRange: number
/**
* 爆破事件失败次数
*/
LoginFailTimes: number
}
/**
* DescribeAvailableExpertServiceDetail请求参数结构体
*/
export type DescribeAvailableExpertServiceDetailRequest = null
/**
* DescribeServerRelatedDirInfo返回参数结构体
*/
export interface DescribeServerRelatedDirInfoResponse {
/**
* 服务器名称
*/
HostName: string
/**
* 服务器IP
*/
HostIp: string
/**
* 防护目录数量
*/
ProtectDirNum: number
/**
* 防护文件数量
*/
ProtectFileNum: number
/**
* 防篡改数量
*/
ProtectTamperNum: number
/**
* 防护软链数量
*/
ProtectLinkNum: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CloseProVersion请求参数结构体
*/
export interface CloseProVersionRequest {
/**
* 主机唯一标识Uuid数组。
黑石的InstanceId,CVM的Uuid ,边缘计算的Uuid , 轻量应用服务器的Uuid ,混合云机器的Quuid 。 当前参数最大长度限制20
*/
Quuid?: string
}
/**
* DescribeUsualLoginPlaces返回参数结构体
*/
export interface DescribeUsualLoginPlacesResponse {
/**
* 常用登录地数组
*/
UsualLoginPlaces: Array<UsualPlace>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 忽略的基线检测项信息
*/
export interface IgnoreBaselineRule {
/**
* 基线检测项名称
注意:此字段可能返回 null,表示取不到有效值。
*/
RuleName: string
/**
* 基线检测项id
注意:此字段可能返回 null,表示取不到有效值。
*/
RuleId: number
/**
* 更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
ModifyTime: string
/**
* 修复建议
注意:此字段可能返回 null,表示取不到有效值。
*/
Fix: string
/**
* 影响主机数
注意:此字段可能返回 null,表示取不到有效值。
*/
EffectHostCount: number
}
/**
* DescribeBaselineBasicInfo返回参数结构体
*/
export interface DescribeBaselineBasicInfoResponse {
/**
* 基线基础信息列表
注意:此字段可能返回 null,表示取不到有效值。
*/
BaselineBasicInfoList: Array<BaselineBasicInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* EditBashRules返回参数结构体
*/
export interface EditBashRulesResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 异地登录白名单
*/
export interface LoginWhiteLists {
/**
* 记录ID
*/
Id: number
/**
* 云镜客户端ID
*/
Uuid: string
/**
* 白名单地域
*/
Places: Array<Place>
/**
* 白名单用户(多个用户逗号隔开)
*/
UserName: string
/**
* 白名单IP(多个IP逗号隔开)
*/
SrcIp: string
/**
* 是否为全局规则
*/
IsGlobal: boolean
/**
* 创建白名单时间
*/
CreateTime: string
/**
* 修改白名单时间
*/
ModifyTime: string
/**
* 机器名
*/
MachineName: string
/**
* 机器IP
*/
HostIp: string
/**
* 起始时间
*/
StartTime: string
/**
* 结束时间
*/
EndTime: string
}
/**
* ScanVul返回参数结构体
*/
export interface ScanVulResponse {
/**
* 任务id
注意:此字段可能返回 null,表示取不到有效值。
*/
TaskId: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeOverviewStatistics请求参数结构体
*/
export type DescribeOverviewStatisticsRequest = null
/**
* 操作系统名称
*/
export interface OsName {
/**
* 系统名称
*/
Name: string
/**
* 操作系统类型枚举值
*/
MachineOSType: number
}
/**
* DescribeTagMachines请求参数结构体
*/
export interface DescribeTagMachinesRequest {
/**
* 标签ID
*/
Id: number
}
/**
* key-val类型的通用数据结构
*/
export interface AssetKeyVal {
/**
* 标签
*/
Key: string
/**
* 数量
*/
Value: number
/**
* 描述信息
注意:此字段可能返回 null,表示取不到有效值。
*/
Desc: string
}
/**
* ModifyAutoOpenProVersionConfig请求参数结构体
*/
export interface ModifyAutoOpenProVersionConfigRequest {
/**
* 设置自动开通状态。
<li>CLOSE:关闭</li>
<li>OPEN:打开</li>
*/
Status: string
}
/**
* DeletePrivilegeEvents请求参数结构体
*/
export interface DeletePrivilegeEventsRequest {
/**
* ID数组. (最大100条)
*/
Ids: Array<number>
}
/**
* ExportAttackLogs请求参数结构体
*/
export interface ExportAttackLogsRequest {
/**
* 过滤条件。
<li>HttpMethod - String - 是否必填:否 - 攻击方法(POST|GET)</li>
<li>DateRange - String - 是否必填:否 - 时间范围(存储最近3个月的数据),如最近一个月["2019-11-17", "2019-12-17"]</li>
<li>VulType - String 威胁类型 - 是否必填: 否</li>
<li>SrcIp - String 攻击源IP - 是否必填: 否</li>
<li>DstIp - String 攻击目标IP - 是否必填: 否</li>
<li>SrcPort - String 攻击源端口 - 是否必填: 否</li>
<li>DstPort - String 攻击目标端口 - 是否必填: 否</li>
*/
Filters?: Array<Filters>
/**
* 主机安全客户端ID
*/
Uuid?: string
/**
* 云主机机器ID
*/
Quuid?: string
}
/**
* 忽略检测项影响主机信息
*/
export interface IgnoreRuleEffectHostInfo {
/**
* 主机名称
注意:此字段可能返回 null,表示取不到有效值。
*/
HostName: string
/**
* 危害等级
注意:此字段可能返回 null,表示取不到有效值。
*/
Level: number
/**
* 主机标签数组
注意:此字段可能返回 null,表示取不到有效值。
*/
TagList: Array<string>
/**
* 状态
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: number
/**
* 最后检测事件
注意:此字段可能返回 null,表示取不到有效值。
*/
LastScanTime: string
/**
* 事件id
注意:此字段可能返回 null,表示取不到有效值。
*/
EventId: number
/**
* 主机quuid
注意:此字段可能返回 null,表示取不到有效值。
*/
Quuid: string
}
/**
* DescribeBanMode请求参数结构体
*/
export type DescribeBanModeRequest = null
/**
* DeleteSearchTemplate请求参数结构体
*/
export interface DeleteSearchTemplateRequest {
/**
* 模板ID
*/
Id: number
}
/**
* 应急漏洞信息
*/
export interface EmergencyVul {
/**
* 漏洞id
*/
VulId: number
/**
* 漏洞级别
*/
Level: number
/**
* 漏洞名称
*/
VulName: string
/**
* 发布日期
*/
PublishDate: string
/**
* 漏洞分类
*/
Category: number
/**
* 漏洞状态 0未检测 1有风险 ,2无风险 ,3 检查中展示progress
*/
Status: number
/**
* 最后扫描时间
*/
LastScanTime: string
/**
* 扫描进度
*/
Progress: number
}
/**
* ExportReverseShellEvents请求参数结构体
*/
export interface ExportReverseShellEventsRequest {
/**
* 过滤参数
*/
Filters?: Array<Filters>
}
/**
* DeleteLoginWhiteList返回参数结构体
*/
export interface DeleteLoginWhiteListResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAttackLogs返回参数结构体
*/
export interface DescribeAttackLogsResponse {
/**
* 日志列表
注意:此字段可能返回 null,表示取不到有效值。
*/
AttackLogs: Array<DefendAttackLog>
/**
* 总条数
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteMalwares返回参数结构体
*/
export interface DeleteMalwaresResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetInitServiceList请求参数结构体
*/
export interface DescribeAssetInitServiceListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Name- string - 是否必填:否 - 包名</li>
<li>User- string - 是否必填:否 - 用户</li>
<li>Status- string - 是否必填:否 - 默认启用状态:0未启用, 1启用 仅linux</li>
<li>Type- string - 是否必填:否 - 类型:类型 仅windows:
1:编码器
2:IE插件
3:网络提供者
4:镜像劫持
5:LSA提供者
6:KnownDLLs
7:启动执行
8:WMI
9:计划任务
10:Winsock提供者
11:打印监控器
12:资源管理器
13:驱动服务
14:登录</li>
*/
Filters?: Array<AssetFilters>
/**
* 服务器Uuid
*/
Uuid?: string
/**
* 服务器Quuid
*/
Quuid?: string
}
/**
* ScanVulAgain返回参数结构体
*/
export interface ScanVulAgainResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 漏洞top统计实体
*/
export interface VulTopInfo {
/**
* 漏洞 名
注意:此字段可能返回 null,表示取不到有效值。
*/
VulName: string
/**
* 危害等级:1-低危;2-中危;3-高危;4-严重
注意:此字段可能返回 null,表示取不到有效值。
*/
VulLevel: number
/**
* 漏洞数量
注意:此字段可能返回 null,表示取不到有效值。
*/
VulCount: number
/**
* 漏洞id
注意:此字段可能返回 null,表示取不到有效值。
*/
VulId: number
}
/**
* SeparateMalwares返回参数结构体
*/
export interface SeparateMalwaresResponse {
/**
* 隔离成功的id数组,若无则返回空数组
*/
SuccessIds: Array<number>
/**
* 隔离失败的id数组,若无则返回空数组
*/
FailedIds: Array<number>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeTags请求参数结构体
*/
export interface DescribeTagsRequest {
/**
* 云主机类型。
<li>CVM:表示云服务器</li>
<li>BM: 表示黑石物理机</li>
<li>ECM: 表示边缘计算服务器</li>
<li>LH: 表示轻量应用服务器</li>
<li>Other: 表示混合云服务器</li>
*/
MachineType?: string
/**
* 机器所属地域。如:ap-guangzhou
*/
MachineRegion?: string
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 查询关键字(机器名称/机器IP </li>
<li>Status - String - 是否必填:否 - 客户端在线状态(OFFLINE: 离线 | ONLINE: 在线 | UNINSTALLED:未安装 | SHUTDOWN 已关机)</li>
<li>Version - String 是否必填:否 - 当前防护版本( PRO_VERSION:专业版 | BASIC_VERSION:基础版)</li>
<li>Risk - String 是否必填: 否 - 风险主机( yes ) </li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )
每个过滤条件只支持一个值,暂不支持多个值“或”关系查询
*/
Filters?: Array<Filters>
}
/**
* DescribeRiskDnsList请求参数结构体
*/
export interface DescribeRiskDnsListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Url - String - 是否必填:否 - Url筛选</li>
<li>Status - String - 是否必填:否 - 状态筛选0:待处理;2:信任;3:不信任</li>
<li>MergeBeginTime - String - 是否必填:否 - 最近访问开始时间</li>
<li>MergeEndTime - String - 是否必填:否 - 最近访问结束时间</li>
*/
Filters?: Array<Filter>
/**
* 排序方式:根据请求次数排序:asc-升序/desc-降序
*/
Order?: string
/**
* 排序字段:AccessCount-请求次数
*/
By?: string
}
/**
* DescribeStrategyExist请求参数结构体
*/
export interface DescribeStrategyExistRequest {
/**
* 策略名
*/
StrategyName: string
}
/**
* DescribeSecurityDynamics请求参数结构体
*/
export interface DescribeSecurityDynamicsRequest {
/**
* 返回数量,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
}
/**
* CheckBashRuleParams请求参数结构体
*/
export interface CheckBashRuleParamsRequest {
/**
* 校验内容 Name或Rule ,两个都要校验时逗号分割
*/
CheckField: string
/**
* 在事件列表中新增白名时需要提交事件ID
*/
EventId?: number
/**
* 填入的规则名称
*/
Name?: string
/**
* 用户填入的正则表达式:"正则表达式" 需与 "提交EventId对应的命令内容" 相匹配
*/
Rule?: string
/**
* 编辑时传的规则id
*/
Id?: number
}
/**
* DescribeIgnoreBaselineRule请求参数结构体
*/
export interface DescribeIgnoreBaselineRuleRequest {
/**
* 分页参数 最大100条
*/
Limit: number
/**
* 分页参数
*/
Offset: number
/**
* 检测项名称
*/
RuleName?: string
}
/**
* ExportNonlocalLoginPlaces返回参数结构体
*/
export interface ExportNonlocalLoginPlacesResponse {
/**
* 导出文件下载链接地址。
*/
DownloadUrl: string
/**
* 导出任务ID
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetJarList返回参数结构体
*/
export interface DescribeAssetJarListResponse {
/**
* 应用列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Jars: Array<AssetJarBaseInfo>
/**
* 总数量
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportMaliciousRequests请求参数结构体
*/
export interface ExportMaliciousRequestsRequest {
/**
* 过滤参数
*/
Filters?: Array<Filters>
}
/**
* 登录审计列表实体
*/
export interface HostLoginList {
/**
* 记录Id
*/
Id: number
/**
* Uuid串
注意:此字段可能返回 null,表示取不到有效值。
*/
Uuid: string
/**
* 主机ip
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineIp: string
/**
* 主机名
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineName: string
/**
* 用户名
注意:此字段可能返回 null,表示取不到有效值。
*/
UserName: string
/**
* 来源ip
注意:此字段可能返回 null,表示取不到有效值。
*/
SrcIp: string
/**
* 1:正常登录;2异地登录; 5已加白
*/
Status: number
/**
* 国家id
注意:此字段可能返回 null,表示取不到有效值。
*/
Country: number
/**
* 城市id
注意:此字段可能返回 null,表示取不到有效值。
*/
City: number
/**
* 省份id
注意:此字段可能返回 null,表示取不到有效值。
*/
Province: number
/**
* 登录时间
注意:此字段可能返回 null,表示取不到有效值。
*/
LoginTime: string
/**
* 修改时间
注意:此字段可能返回 null,表示取不到有效值。
*/
ModifyTime: string
/**
* 是否命中异地登录异常 1表示命中此类异常, 0表示未命中
注意:此字段可能返回 null,表示取不到有效值。
*/
IsRiskArea: number
/**
* 是否命中异常用户异常 1表示命中此类异常, 0表示未命中
注意:此字段可能返回 null,表示取不到有效值。
*/
IsRiskUser: number
/**
* 是否命中异常时间异常 1表示命中此类异常, 0表示未命中
注意:此字段可能返回 null,表示取不到有效值。
*/
IsRiskTime: number
/**
* 是否命中异常IP异常 1表示命中此类异常, 0表示未命中
注意:此字段可能返回 null,表示取不到有效值。
*/
IsRiskSrcIp: number
/**
* 危险等级:
0 高危
1 可疑
注意:此字段可能返回 null,表示取不到有效值。
*/
RiskLevel: number
/**
* 位置名称
注意:此字段可能返回 null,表示取不到有效值。
*/
Location: string
}
/**
* DescribeWebPageProtectStat请求参数结构体
*/
export type DescribeWebPageProtectStatRequest = null
/**
* 资产管理jar包详情
*/
export interface AssetJarDetail {
/**
* 名称
*/
Name: string
/**
* 类型:1应用程序,2系统类库,3Web服务自带库,8:其他,
*/
Type: number
/**
* 是否可执行:0未知,1是,2否
*/
Status: number
/**
* 版本
*/
Version: string
/**
* 路径
*/
Path: string
/**
* 服务器IP
*/
MachineIp: string
/**
* 服务器名称
*/
MachineName: string
/**
* 操作系统
*/
OsInfo: string
/**
* 引用进程列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Process: Array<AssetAppProcessInfo>
/**
* Jar包Md5
注意:此字段可能返回 null,表示取不到有效值。
*/
Md5: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* ExportVulDetectionReport请求参数结构体
*/
export interface ExportVulDetectionReportRequest {
/**
* 漏洞扫描任务id(不同于出参的导出检测报告的任务Id)
*/
TaskId: number
/**
* 过滤参数
*/
Filters?: Array<Filters>
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
}
/**
* ExportMalwares返回参数结构体
*/
export interface ExportMalwaresResponse {
/**
* 导出文件下载链接地址。
*/
DownloadUrl: string
/**
* 任务id
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeScanVulSetting请求参数结构体
*/
export type DescribeScanVulSettingRequest = null
/**
* DescribeESHits请求参数结构体
*/
export interface DescribeESHitsRequest {
/**
* ES查询条件JSON
*/
Query: string
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 返回数量,最大值为100。
*/
Limit?: number
}
/**
* DescribeAssetPlanTaskList返回参数结构体
*/
export interface DescribeAssetPlanTaskListResponse {
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Tasks: Array<AssetPlanTask>
/**
* 总数量
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBaselineRule请求参数结构体
*/
export interface DescribeBaselineRuleRequest {
/**
* 基线id
*/
BaselineId: number
/**
* 分页参数 最大100条
*/
Limit: number
/**
* 分页参数
*/
Offset: number
/**
* 危害等级
*/
Level?: Array<number>
/**
* 状态
*/
Status?: number
/**
* 主机quuid
*/
Quuid?: string
/**
* 主机uuid
*/
Uuid?: string
}
/**
* DescribeHistoryAccounts请求参数结构体
*/
export interface DescribeHistoryAccountsRequest {
/**
* 云镜客户端唯一Uuid。
*/
Uuid: string
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Username - String - 是否必填:否 - 帐号名</li>
*/
Filters?: Array<Filter>
}
/**
* DescribeAssetMachineDetail请求参数结构体
*/
export interface DescribeAssetMachineDetailRequest {
/**
* 服务器Quuid
*/
Quuid: string
/**
* 服务器Uuid
*/
Uuid: string
}
/**
* CancelIgnoreVul返回参数结构体
*/
export interface CancelIgnoreVulResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* IgnoreImpactedHosts返回参数结构体
*/
export interface IgnoreImpactedHostsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* RescanImpactedHost返回参数结构体
*/
export interface RescanImpactedHostResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetMachineDetail返回参数结构体
*/
export interface DescribeAssetMachineDetailResponse {
/**
* 主机详情
*/
MachineDetail: AssetMachineDetail
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeStrategyExist返回参数结构体
*/
export interface DescribeStrategyExistResponse {
/**
* 策略是否存在, 1是 0否
注意:此字段可能返回 null,表示取不到有效值。
*/
IfExist: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteReverseShellEvents请求参数结构体
*/
export interface DeleteReverseShellEventsRequest {
/**
* ID数组. (最大100条)
*/
Ids: Array<number>
}
/**
* DescribeBanRegions请求参数结构体
*/
export interface DescribeBanRegionsRequest {
/**
* 阻断模式,STANDARD_MODE:标准阻断,DEEP_MODE:深度阻断
*/
Mode: string
}
/**
* DescribeServersAndRiskAndFirstInfo请求参数结构体
*/
export type DescribeServersAndRiskAndFirstInfoRequest = null
/**
* DescribeAssetWebServiceProcessList返回参数结构体
*/
export interface DescribeAssetWebServiceProcessListResponse {
/**
* 进程列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Process: Array<AssetAppProcessInfo>
/**
* 总数
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* IgnoreImpactedHosts请求参数结构体
*/
export interface IgnoreImpactedHostsRequest {
/**
* 漏洞ID数组。
*/
Ids: Array<number>
}
/**
* 资源管理账号基本信息
*/
export interface AssetUserDetail {
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机名称
*/
MachineName: string
/**
* 主机Uuid
*/
Uuid: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 账号UID
*/
Uid: string
/**
* 账号GID
*/
Gid: string
/**
* 账号状态:0-禁用;1-启用
*/
Status: number
/**
* 是否有root权限:0-否;1是,999为空: 仅linux
*/
IsRoot: number
/**
* 上次登录时间
*/
LastLoginTime: string
/**
* 账号名称
*/
Name: string
/**
* 账号类型:0访客用户,1标准用户,2管理员用户 ,999为空,仅windows
*/
UserType: number
/**
* 是否域账号:0否, 1是, 999为空 仅windows
*/
IsDomain: number
/**
* 是否允许ssh登录,1是,0否, 999为空, 仅linux
*/
IsSshLogin: number
/**
* Home目录
*/
HomePath: string
/**
* Shell路径 仅linux
*/
Shell: string
/**
* 是否shell登录性,0不是;1是 仅linux
*/
ShellLoginStatus: number
/**
* 密码修改时间
*/
PasswordChangeTime: string
/**
* 密码过期时间 仅linux
*/
PasswordDueTime: string
/**
* 密码锁定时间:单位天, -1为永不锁定 999为空,仅linux
*/
PasswordLockDays: number
/**
* 备注
*/
Remark: string
/**
* 用户组名
*/
GroupName: string
/**
* 账号到期时间
*/
DisableTime: string
/**
* 最近登录终端
*/
LastLoginTerminal: string
/**
* 最近登录位置
*/
LastLoginLoc: string
/**
* 最近登录IP
*/
LastLoginIp: string
/**
* 密码过期提醒:单位天
*/
PasswordWarnDays: number
/**
* 密码修改设置:0-不可修改,1-可修改
*/
PasswordChangeType: number
/**
* 用户公钥列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Keys: Array<AssetUserKeyInfo>
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribeMachines请求参数结构体
*/
export interface DescribeMachinesRequest {
/**
* 机器所属专区类型
CVM 云服务器
BM 黑石
ECM 边缘计算
LH 轻量应用服务器
Other 混合云专区
*/
MachineType: string
/**
* 机器所属地域。如:ap-guangzhou,ap-shanghai
*/
MachineRegion: string
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 查询关键字 </li>
<li>Status - String - 是否必填:否 - 客户端在线状态(OFFLINE: 离线/关机 | ONLINE: 在线 | UNINSTALLED:未安装 | AGENT_OFFLINE 离线| AGENT_SHUTDOWN 已关机)</li>
<li>Version - String 是否必填:否 - 当前防护版本( PRO_VERSION:专业版 | BASIC_VERSION:基础版)</li>
<li>Risk - String 是否必填: 否 - 风险主机( yes ) </li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )
每个过滤条件只支持一个值,暂不支持多个值“或”关系查询
*/
Filters?: Array<Filter>
/**
* 机器所属业务ID列表
*/
ProjectIds?: Array<number>
}
/**
* 资产管理Web应用插件详情
*/
export interface AssetWebAppPluginInfo {
/**
* 名称
*/
Name: string
/**
* 描述
*/
Desc: string
/**
* 版本
*/
Version: string
/**
* 链接
*/
Link: string
}
/**
* DeletePrivilegeRules请求参数结构体
*/
export interface DeletePrivilegeRulesRequest {
/**
* ID数组,最大100条。
*/
Ids: Array<number>
}
/**
* DescribeMalwareInfo请求参数结构体
*/
export interface DescribeMalwareInfoRequest {
/**
* 唯一ID
*/
Id: number
}
/**
* DescribeVersionStatistics请求参数结构体
*/
export type DescribeVersionStatisticsRequest = null
/**
* ExportPrivilegeEvents返回参数结构体
*/
export interface ExportPrivilegeEventsResponse {
/**
* 导出文件下载链接地址。
*/
DownloadUrl: string
/**
* 导出任务ID
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 常用登录地
*/
export interface UsualPlace {
/**
* ID。
*/
Id: number
/**
* 云镜客户端唯一标识UUID。
*/
Uuid: string
/**
* 国家 ID。
*/
CountryId: number
/**
* 省份 ID。
*/
ProvinceId: number
/**
* 城市 ID。
*/
CityId: number
}
/**
* DescribeReverseShellEvents请求参数结构体
*/
export interface DescribeReverseShellEventsRequest {
/**
* 返回数量,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 关键字(主机内网IP|进程名)</li>
*/
Filters?: Array<Filter>
}
/**
* 反弹Shell数据
*/
export interface ReverseShell {
/**
* ID 主键
*/
Id: number
/**
* 云镜UUID
*/
Uuid: string
/**
* 主机ID
*/
Quuid: string
/**
* 主机内网IP
*/
Hostip: string
/**
* 目标IP
*/
DstIp: string
/**
* 目标端口
*/
DstPort: number
/**
* 进程名
*/
ProcessName: string
/**
* 进程路径
*/
FullPath: string
/**
* 命令详情
*/
CmdLine: string
/**
* 执行用户
*/
UserName: string
/**
* 执行用户组
*/
UserGroup: string
/**
* 父进程名
*/
ParentProcName: string
/**
* 父进程用户
*/
ParentProcUser: string
/**
* 父进程用户组
*/
ParentProcGroup: string
/**
* 父进程路径
*/
ParentProcPath: string
/**
* 处理状态:0-待处理 2-白名单
*/
Status: number
/**
* 产生时间
*/
CreateTime: string
/**
* 主机名
*/
MachineName: string
/**
* 进程树
*/
ProcTree: string
/**
* 检测方法
*/
DetectBy: number
}
/**
* DescribeAttackVulTypeList请求参数结构体
*/
export type DescribeAttackVulTypeListRequest = null
/**
* DescribeLogStorageStatistic请求参数结构体
*/
export type DescribeLogStorageStatisticRequest = null
/**
* DescribeAssetRecentMachineInfo请求参数结构体
*/
export interface DescribeAssetRecentMachineInfoRequest {
/**
* 开始时间,如:2020-09-22
*/
BeginDate: string
/**
* 结束时间,如:2020-09-22
*/
EndDate: string
}
/**
* CheckBashRuleParams返回参数结构体
*/
export interface CheckBashRuleParamsResponse {
/**
* 0=校验通过 1=规则名称校验不通过 2=正则表达式校验不通过
*/
ErrCode: number
/**
* 校验信息
*/
ErrMsg: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportBaselineList请求参数结构体
*/
export interface ExportBaselineListRequest {
/**
* 过滤条件:
<li>StrategyId- Uint64 - 基线策略id</li>
<li>Status - Uint64 - 事件状态:0-未通过,1-忽略,3-通过,5-检测中</li>
<li>BaselineName - String - 基线名称</li>
<li>AliasName- String - 服务器名称/服务器ip</li>
<li>Uuid- String - 主机uuid</li>
*/
Filters?: Array<Filters>
/**
* 已废弃
*/
IfDetail?: number
}
/**
* DeleteProtectDir请求参数结构体
*/
export interface DeleteProtectDirRequest {
/**
* 删除的目录ID 最大100条
*/
Ids: Array<string>
}
/**
* ExportIgnoreBaselineRule返回参数结构体
*/
export interface ExportIgnoreBaselineRuleResponse {
/**
* 文件下载地址
*/
DownloadUrl: string
/**
* 导出任务Id , 可通过ExportTasks 接口下载
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 暴力破解判定规则列表
*/
export interface BruteAttackRuleList {
/**
* 爆破事件发生的时间范围,单位:秒
*/
TimeRange: number
/**
* 爆破事件失败次数
*/
LoginFailTimes: number
/**
* 规则是否为空,为空则填充默认规则
*/
Enable: boolean
/**
* 爆破事件发生的时间范围,单位:秒(默认规则)
*/
TimeRangeDefault: number
/**
* 爆破事件失败次数(默认规则)
*/
LoginFailTimesDefault: number
}
/**
* DescribeBanStatus返回参数结构体
*/
export interface DescribeBanStatusResponse {
/**
* 阻断开关状态 0:关闭 1:开启
*/
Status: number
/**
* 是否弹窗提示信息 false: 关闭,true: 开启
*/
ShowTips: boolean
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 漏洞详细信息
*/
export interface VulDetailInfo {
/**
* 漏洞ID
*/
VulId: number
/**
* 漏洞级别
*/
Level: number
/**
* 漏洞名称
*/
Name: string
/**
* cve编号
*/
CveId: string
/**
* 漏洞分类
*/
VulCategory: number
/**
* 漏洞描述
*/
Descript: string
/**
* 修复建议
*/
Fix: string
/**
* 参考链接
*/
Reference: string
/**
* CVSS评分
*/
CvssScore: number
/**
* CVSS详情
*/
Cvss: string
/**
* 发布时间
*/
PublishTime: string
}
/**
* DescribeServersAndRiskAndFirstInfo返回参数结构体
*/
export interface DescribeServersAndRiskAndFirstInfoResponse {
/**
* 风险文件数
*/
RiskFileCount: number
/**
* 今日新增风险文件数
*/
AddRiskFileCount: number
/**
* 受影响服务器台数
*/
ServersCount: number
/**
* 是否试用:true-是,false-否
*/
IsFirstCheck: boolean
/**
* 木马最近检测时间
*/
ScanTime: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 资源管理进程基本信息
*/
export interface AssetAppBaseInfo {
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* 操作系统信息
*/
OsInfo: string
/**
* 主机业务组ID
*/
ProjectId: number
/**
* 主机标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tag: Array<MachineTag>
/**
* 应用名称
*/
Name: string
/**
* 应用类型
1: 运维
2 : 数据库
3 : 安全
4 : 可疑应用
5 : 系统架构
6 : 系统应用
7 : WEB服务
99: 其他
*/
Type: number
/**
* 二进制路径
*/
BinPath: string
/**
* 配置文件路径
*/
ConfigPath: string
/**
* 关联进程数
*/
ProcessCount: number
/**
* 应用描述
*/
Desc: string
/**
* 版本号
*/
Version: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribePrivilegeRules请求参数结构体
*/
export interface DescribePrivilegeRulesRequest {
/**
* 返回数量,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 关键字(进程名称)</li>
*/
Filters?: Array<Filter>
}
/**
* 专家服务-月巡检报告
*/
export interface MonthInspectionReport {
/**
* 巡检报告名称
*/
ReportName: string
/**
* 巡检报告下载地址
*/
ReportPath: string
/**
* 巡检报告更新时间
*/
ModifyTime: string
}
/**
* DescribeAssetSystemPackageList返回参数结构体
*/
export interface DescribeAssetSystemPackageListResponse {
/**
* 记录总数
*/
Total: number
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Packages: Array<AssetSystemPackageInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetMachineList返回参数结构体
*/
export interface DescribeAssetMachineListResponse {
/**
* 总数
*/
Total: number
/**
* 记录列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Machines: Array<AssetMachineBaseInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeWebPageGeneralize请求参数结构体
*/
export type DescribeWebPageGeneralizeRequest = null
/**
* DescribeBaselineDetail请求参数结构体
*/
export interface DescribeBaselineDetailRequest {
/**
* 基线id
*/
BaselineId: number
}
/**
* ModifyWarningSetting请求参数结构体
*/
export interface ModifyWarningSettingRequest {
/**
* 告警设置的修改内容
*/
WarningObjects: Array<WarningObject>
}
/**
* DescribeMalwareRiskWarning请求参数结构体
*/
export type DescribeMalwareRiskWarningRequest = null
/**
* DescribeAssetInfo请求参数结构体
*/
export type DescribeAssetInfoRequest = null
/**
* DescribeVulTop返回参数结构体
*/
export interface DescribeVulTopResponse {
/**
* 漏洞top列表
注意:此字段可能返回 null,表示取不到有效值。
*/
VulTopList: Array<VulTopInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* UntrustMalwares请求参数结构体
*/
export interface UntrustMalwaresRequest {
/**
* 木马ID数组 (最大100条)
*/
Ids: Array<number>
}
/**
* DescribeAssetAppList请求参数结构体
*/
export interface DescribeAssetAppListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>AppName- string - 是否必填:否 - 应用名搜索</li>
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Type - int - 是否必填:否 - 类型 : 仅linux
0: 全部
1: 运维
2 : 数据库
3 : 安全
4 : 可疑应用
5 : 系统架构
6 : 系统应用
7 : WEB服务
99:其他</li>
<li>OsType - uint64 - 是否必填:否 - windows/linux</li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )</li>
*/
Filters?: Array<AssetFilters>
/**
* 排序方式:ProcessCount
*/
By?: string
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 查询指定Quuid主机的信息
*/
Quuid?: string
}
/**
* UntrustMalwares返回参数结构体
*/
export interface UntrustMalwaresResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeExpertServiceList返回参数结构体
*/
export interface DescribeExpertServiceListResponse {
/**
* 总条数
*/
TotalCount: number
/**
* 安全管家数据
*/
List: Array<SecurityButlerInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAccountStatistics返回参数结构体
*/
export interface DescribeAccountStatisticsResponse {
/**
* 帐号统计列表记录总数。
*/
TotalCount: number
/**
* 帐号统计列表。
*/
AccountStatistics: Array<AccountStatistics>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeSearchExportList请求参数结构体
*/
export interface DescribeSearchExportListRequest {
/**
* ES查询条件JSON
*/
Query: string
}
/**
* ScanAsset请求参数结构体
*/
export interface ScanAssetRequest {
/**
* 资产指纹类型id列表
*/
AssetTypeIds?: Array<number>
/**
* Quuid列表
*/
Quuids?: Array<string>
}
/**
* DescribeBaselineRule返回参数结构体
*/
export interface DescribeBaselineRuleResponse {
/**
* 分页查询记录总数
*/
TotalCount: number
/**
* 基线检测项列表
注意:此字段可能返回 null,表示取不到有效值。
*/
BaselineRuleList: Array<BaselineRuleInfo>
/**
* 是否显示说明列:true-是,false-否
注意:此字段可能返回 null,表示取不到有效值。
*/
ShowRuleRemark: boolean
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteMaliciousRequests返回参数结构体
*/
export interface DeleteMaliciousRequestsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeESHits返回参数结构体
*/
export interface DescribeESHitsResponse {
/**
* ES查询结果JSON
*/
Data: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 防护目录关联服务器列表信息
*/
export interface ProtectDirRelatedServer {
/**
* 唯一ID
*/
Id: string
/**
* 服务器名称
*/
HostName: string
/**
* 服务器IP
*/
HostIp: string
/**
* 服务器系统
*/
MachineOs: string
/**
* 关联目录数
*/
RelateDirNum: number
/**
* 防护状态
*/
ProtectStatus: number
/**
* 防护开关
*/
ProtectSwitch: number
/**
* 自动恢复开关
*/
AutoRestoreSwitchStatus: number
/**
* 服务器唯一ID
*/
Quuid: string
/**
* 是否已经授权
*/
Authorization: boolean
/**
* 异常状态
*/
Exception: number
/**
* 过渡进度
*/
Progress: number
/**
* 异常信息
*/
ExceptionMessage: string
}
/**
* ExportBruteAttacks请求参数结构体
*/
export interface ExportBruteAttacksRequest {
/**
* 过滤参数
*/
Filters?: Array<Filters>
}
/**
* DeleteMachine返回参数结构体
*/
export interface DeleteMachineResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ScanVul请求参数结构体
*/
export interface ScanVulRequest {
/**
* 漏洞类型:1: web应用漏洞 2:系统组件漏洞 (多选英文;分隔)
*/
VulCategories: string
/**
* 危害等级:1-低危;2-中危;3-高危;4-严重 (多选英文;分隔)
*/
VulLevels: string
/**
* 服务器分类:1:专业版服务器;2:自选服务器
*/
HostType: number
/**
* 自选服务器时生效,主机quuid的string数组
*/
QuuidList?: Array<string>
/**
* 是否是应急漏洞 0 否 1 是
*/
VulEmergency?: number
/**
* 超时时长 单位秒 默认 3600 秒
*/
TimeoutPeriod?: number
/**
* 需要扫描的漏洞id
*/
VulIds?: Array<number>
}
/**
* RecoverMalwares请求参数结构体
*/
export interface RecoverMalwaresRequest {
/**
* 木马Id数组(最大100条)
*/
Ids: Array<number>
}
/**
* 标签相关服务器信息
*/
export interface TagMachine {
/**
* ID
*/
Id: string
/**
* 主机ID
*/
Quuid: string
/**
* 主机名称
*/
MachineName: string
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 主机区域
*/
MachineRegion: string
/**
* 主机区域类型
*/
MachineType: string
}
/**
* DescribeAssetCoreModuleInfo返回参数结构体
*/
export interface DescribeAssetCoreModuleInfoResponse {
/**
* 内核模块详情
*/
Module: AssetCoreModuleDetail
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetEnvList请求参数结构体
*/
export interface DescribeAssetEnvListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 类型:
0
*/
Type?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Name- string - 是否必填:否 - 环境变量名</li>
<li>Type- int - 是否必填:否 - 类型:0用户变量,1系统变量</li>
*/
Filters?: Array<AssetFilters>
/**
* 服务器Uuid
*/
Uuid?: string
/**
* 服务器Quuid
*/
Quuid?: string
}
/**
* StopNoticeBanTips请求参数结构体
*/
export type StopNoticeBanTipsRequest = null
/**
* DescribeScanMalwareSchedule请求参数结构体
*/
export type DescribeScanMalwareScheduleRequest = null
/**
* 资产指纹中服务器列表的基本信息
*/
export interface AssetMachineBaseInfo {
/**
* 服务器Quuid
*/
Quuid: string
/**
* 服务器uuid
*/
Uuid: string
/**
* 服务器内网IP
*/
MachineIp: string
/**
* 服务器名称
*/
MachineName: string
/**
* 操作系统名称
*/
OsInfo: string
/**
* CPU信息
*/
Cpu: string
/**
* 内存容量:单位G
*/
MemSize: number
/**
* 内存使用率百分比
*/
MemLoad: string
/**
* 硬盘容量:单位G
*/
DiskSize: number
/**
* 硬盘使用率百分比
*/
DiskLoad: string
/**
* 分区数
*/
PartitionCount: number
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 业务组ID
*/
ProjectId: number
/**
* Cpu数量
*/
CpuSize: number
/**
* Cpu使用率百分比
*/
CpuLoad: string
/**
* 标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tag: Array<MachineTag>
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribeBashEvents返回参数结构体
*/
export interface DescribeBashEventsResponse {
/**
* 总条数
*/
TotalCount: number
/**
* 高危命令事件列表
*/
List: Array<BashEvent>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* UpdateMachineTags返回参数结构体
*/
export interface UpdateMachineTagsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBashEvents请求参数结构体
*/
export interface DescribeBashEventsRequest {
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 关键词(主机内网IP)</li>
*/
Filters?: Array<Filter>
}
/**
* DeleteMachine请求参数结构体
*/
export interface DeleteMachineRequest {
/**
* 云镜客户端Uuid。
*/
Uuid: string
}
/**
* DescribeAssetWebLocationList返回参数结构体
*/
export interface DescribeAssetWebLocationListResponse {
/**
* 记录总数
*/
Total: number
/**
* 站点列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Locations: Array<AssetWebLocationBaseInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 告警更新或插入的参数
*/
export interface WarningObject {
/**
* 事件告警类型;1:离线,2:木马,3:异常登录,4:爆破,5:漏洞(已拆分为9-12四种类型)6:高位命令,7:反弹sell,8:本地提权,9:系统组件漏洞,10:web应用漏洞,11:应急漏洞,12:安全基线
*/
Type?: number
/**
* 1: 关闭告警 0: 开启告警
*/
DisablePhoneWarning?: number
/**
* 开始时间,格式: HH:mm
*/
BeginTime?: string
/**
* 结束时间,格式: HH:mm
*/
EndTime?: string
/**
* 漏洞等级控制位二进制,每一位对应页面漏洞等级的开启关闭:低中高(0:关闭;1:开启),例如:101 → 同时勾选低+高;01→(登录审计)疑似不告警,高危告警
*/
ControlBits?: string
}
/**
* DescribeAssetJarList请求参数结构体
*/
export interface DescribeAssetJarListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Name- string - 是否必填:否 - 包名</li>
<li>Type- uint - 是否必填:否 - 类型
1: 应用程序
2 : 系统类库
3 : Web服务自带库
4 : 其他依赖包</li>
<li>Status- string - 是否必填:否 - 是否可执行:0否,1是</li>
*/
Filters?: Array<AssetFilters>
/**
* 服务器Uuid
*/
Uuid?: string
/**
* 服务器Quuid
*/
Quuid?: string
}
/**
* 本地提权数据
*/
export interface PrivilegeEscalationProcess {
/**
* 数据ID
*/
Id: number
/**
* 云镜ID
*/
Uuid: string
/**
* 主机ID
*/
Quuid: string
/**
* 主机内网IP
*/
Hostip: string
/**
* 进程名
*/
ProcessName: string
/**
* 进程路径
*/
FullPath: string
/**
* 执行命令
*/
CmdLine: string
/**
* 用户名
*/
UserName: string
/**
* 用户组
*/
UserGroup: string
/**
* 进程文件权限
*/
ProcFilePrivilege: string
/**
* 父进程名
*/
ParentProcName: string
/**
* 父进程用户名
*/
ParentProcUser: string
/**
* 父进程用户组
*/
ParentProcGroup: string
/**
* 父进程路径
*/
ParentProcPath: string
/**
* 进程树
*/
ProcTree: string
/**
* 处理状态:0-待处理 2-白名单
*/
Status: number
/**
* 发生时间
*/
CreateTime: string
/**
* 机器名
*/
MachineName: string
}
/**
* DescribeProtectNetList返回参数结构体
*/
export interface DescribeProtectNetListResponse {
/**
* 总条数
*/
TotalCount: number
/**
* 安全管家数据
*/
List: Array<ProtectNetInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeESAggregations返回参数结构体
*/
export interface DescribeESAggregationsResponse {
/**
* ES聚合结果JSON
*/
Data: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 资产管理Web站点列表信息
*/
export interface AssetWebLocationInfo {
/**
* 域名
*/
Name: string
/**
* 站点端口
*/
Port: string
/**
* 站点协议
*/
Proto: string
/**
* 服务类型
*/
ServiceType: string
/**
* 安全模块状态:0未启用,1启用,999空,仅nginx
*/
SafeStatus: number
/**
* 运行用户
*/
User: string
/**
* 主目录
*/
MainPath: string
/**
* 启动命令
*/
Command: string
/**
* 绑定IP
*/
Ip: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* ChangeRuleEventsIgnoreStatus返回参数结构体
*/
export interface ChangeRuleEventsIgnoreStatusResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 资产指纹中服务器列表的基本信息
*/
export interface AssetMachineDetail {
/**
* 服务器Quuid
*/
Quuid: string
/**
* 服务器uuid
*/
Uuid: string
/**
* 服务器内网IP
*/
MachineIp: string
/**
* 服务器名称
*/
MachineName: string
/**
* 操作系统名称
*/
OsInfo: string
/**
* CPU信息
*/
Cpu: string
/**
* 内存容量:单位G
*/
MemSize: number
/**
* 内存使用率百分比
*/
MemLoad: string
/**
* 硬盘容量:单位G
*/
DiskSize: number
/**
* 硬盘使用率百分比
*/
DiskLoad: string
/**
* 分区数
*/
PartitionCount: number
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* Cpu数量
*/
CpuSize: number
/**
* Cpu使用率百分比
*/
CpuLoad: string
/**
* 防护级别:0基础版,1专业版
*/
ProtectLevel: number
/**
* 风险状态:UNKNOW-未知,RISK-风险,SAFT-安全
*/
RiskStatus: string
/**
* 已防护天数
*/
ProtectDays: number
/**
* 专业版开通时间
*/
BuyTime: string
/**
* 专业版到期时间
*/
EndTime: string
/**
* 内核版本
*/
CoreVersion: string
/**
* linux/windows
*/
OsType: string
/**
* agent版本
*/
AgentVersion: string
/**
* 安装时间
*/
InstallTime: string
/**
* 系统启动时间
*/
BootTime: string
/**
* 最后上线时间
*/
LastLiveTime: string
/**
* 生产商
*/
Producer: string
/**
* 序列号
*/
SerialNumber: string
/**
* 网卡
*/
NetCards: Array<AssetNetworkCardInfo>
/**
* 分区
*/
Disks: Array<AssetDiskPartitionInfo>
/**
* 0在线,1已离线
*/
Status: number
/**
* 业务组ID
*/
ProjectId: number
/**
* 设备型号
*/
DeviceVersion: string
/**
* 离线时间
注意:此字段可能返回 null,表示取不到有效值。
*/
OfflineTime: string
/**
* 主机ID
注意:此字段可能返回 null,表示取不到有效值。
*/
InstanceId: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* 资源管理数据库列表信息
*/
export interface AssetDatabaseBaseInfo {
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* 操作系统信息
*/
OsInfo: string
/**
* 主机业务组ID
*/
ProjectId: number
/**
* 主机标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tag: Array<MachineTag>
/**
* 数据库名
*/
Name: string
/**
* 版本
*/
Version: string
/**
* 监听端口
*/
Port: string
/**
* 协议
*/
Proto: string
/**
* 运行用户
*/
User: string
/**
* 绑定IP
*/
Ip: string
/**
* 配置文件路径
*/
ConfigPath: string
/**
* 日志文件路径
*/
LogPath: string
/**
* 数据路径
*/
DataPath: string
/**
* 运行权限
*/
Permission: string
/**
* 错误日志路径
*/
ErrorLogPath: string
/**
* 插件路径
*/
PlugInPath: string
/**
* 二进制路径
*/
BinPath: string
/**
* 启动参数
*/
Param: string
/**
* 数据库ID
*/
Id: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DeletePrivilegeRules返回参数结构体
*/
export interface DeletePrivilegeRulesResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateProtectServer请求参数结构体
*/
export interface CreateProtectServerRequest {
/**
* 防护目录地址
*/
ProtectDir: string
/**
* 防护机器 信息
*/
ProtectHostConfig: Array<ProtectHostConfig>
}
/**
* DescribeMachineList请求参数结构体
*/
export interface DescribeMachineListRequest {
/**
* 云主机类型。
<li>CVM:表示虚拟主机</li>
<li>BM: 表示黑石物理机</li>
<li>ECM: 表示边缘计算服务器</li>
<li>LH: 表示轻量应用服务器</li>
<li>Other: 表示混合云机器</li>
*/
MachineType: string
/**
* 机器所属地域。如:ap-guangzhou,ap-shanghai
*/
MachineRegion: string
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 查询关键字 </li>
<li>Status - String - 是否必填:否 - 客户端在线状态(OFFLINE: 离线 | ONLINE: 在线 | UNINSTALLED:未安装)</li>
<li>Version - String 是否必填:否 - 当前防护版本( PRO_VERSION:专业版 | BASIC_VERSION:基础版)</li>
每个过滤条件只支持一个值,暂不支持多个值“或”关系查询
*/
Filters?: Array<AssetFilters>
}
/**
* CreateEmergencyVulScan返回参数结构体
*/
export interface CreateEmergencyVulScanResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetCoreModuleInfo请求参数结构体
*/
export interface DescribeAssetCoreModuleInfoRequest {
/**
* 服务器Quuid
*/
Quuid: string
/**
* 服务器Uuid
*/
Uuid: string
/**
* 内核模块ID
*/
Id: string
}
/**
* DescribeIndexList返回参数结构体
*/
export interface DescribeIndexListResponse {
/**
* ES 索引信息
*/
Data: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyWebPageProtectDir请求参数结构体
*/
export interface ModifyWebPageProtectDirRequest {
/**
* 网站防护目录地址
*/
ProtectDirAddr: string
/**
* 网站防护目录名称
*/
ProtectDirName: string
/**
* 防护文件类型,分号分割 ;
*/
ProtectFileType: string
/**
* 防护机器列表信息
*/
HostConfig: Array<ProtectHostConfig>
}
/**
* DescribeWebPageGeneralize返回参数结构体
*/
export interface DescribeWebPageGeneralizeResponse {
/**
* 防护监测 0 未开启 1 已开启 2 异常
*/
ProtectMonitor: number
/**
* 防护目录数
*/
ProtectDirNum: number
/**
* 防护文件数
*/
ProtectFileNum: number
/**
* 篡改文件数
*/
TamperFileNum: number
/**
* 篡改数
*/
TamperNum: number
/**
* 今日防护数
*/
ProtectToday: number
/**
* 防护主机数
*/
ProtectHostNum: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBanWhiteList返回参数结构体
*/
export interface DescribeBanWhiteListResponse {
/**
* 总记录数
*/
TotalCount: number
/**
* 白名单列表
*/
WhiteList: Array<BanWhiteListDetail>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 专家服务-应急响应信息
*/
export interface EmergencyResponseInfo {
/**
* 任务id
*/
TaskId: string
/**
* 主机个数
*/
HostNum: number
/**
* 服务状态 0未启动,·响应中,2响应完成
*/
Status: number
/**
* 服务开始时间
*/
StartTime: string
/**
* 服务结束时间
*/
EndTime: string
/**
* 报告下载地址
*/
ReportPath: string
}
/**
* DescribeOpenPortStatistics返回参数结构体
*/
export interface DescribeOpenPortStatisticsResponse {
/**
* 端口统计列表总数
*/
TotalCount: number
/**
* 端口统计数据列表
*/
OpenPortStatistics: Array<OpenPortStatistics>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteAttackLogs返回参数结构体
*/
export interface DeleteAttackLogsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 安全事件消息数据。
*/
export interface SecurityDynamic {
/**
* 云镜客户端UUID。
*/
Uuid: string
/**
* 安全事件发生时间。
*/
EventTime: string
/**
* 安全事件类型。
<li>MALWARE:木马事件</li>
<li>NON_LOCAL_LOGIN:异地登录</li>
<li>BRUTEATTACK_SUCCESS:密码破解成功</li>
<li>VUL:漏洞</li>
<li>BASELINE:安全基线</li>
*/
EventType: string
/**
* 安全事件消息。
*/
Message: string
/**
* 安全事件等级。
<li>RISK: 严重</li>
<li>HIGH: 高危</li>
<li>NORMAL: 中危</li>
<li>LOW: 低危</li>
*/
SecurityLevel: string
}
/**
* OpenProVersionPrepaid请求参数结构体
*/
export interface OpenProVersionPrepaidRequest {
/**
* 购买相关参数。
*/
ChargePrepaid: ChargePrepaid
/**
* 需要开通专业版主机信息数组。
*/
Machines: Array<ProVersionMachine>
}
/**
* DescribeMalWareList请求参数结构体
*/
export interface DescribeMalWareListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>FilePath - String - 是否必填:否 - 路径筛选</li>
<li>VirusName - String - 是否必填:否 - 描述筛选</li>
<li>CreateBeginTime - String - 是否必填:否 - 创建时间筛选-开始时间</li>
<li>CreateEndTime - String - 是否必填:否 - 创建时间筛选-结束时间</li>
<li>Status - String - 是否必填:否 - 状态筛选 4待处理,5信任沃尔玛可哦啊吗,6已隔离,10隔离中,11恢复隔离中</li>
*/
Filters?: Array<Filter>
/**
* 检测排序 CreateTime
*/
By?: string
/**
* 排序方式 ASC,DESC
*/
Order?: string
}
/**
* DescribeProVersionInfo返回参数结构体
*/
export interface DescribeProVersionInfoResponse {
/**
* 后付费昨日扣费
*/
PostPayCost: number
/**
* 新增主机是否自动开通专业版
*/
IsAutoOpenProVersion: boolean
/**
* 开通专业版主机数
*/
ProVersionNum: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteTags返回参数结构体
*/
export interface DeleteTagsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeSecurityEventsCnt请求参数结构体
*/
export type DescribeSecurityEventsCntRequest = null
/**
* 资源管理账号基本信息
*/
export interface AssetUserBaseInfo {
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 主机名称
*/
MachineName: string
/**
* 操作系统信息
*/
OsInfo: string
/**
* 主机Uuid
*/
Uuid: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 账号UID
*/
Uid: string
/**
* 账号GID
*/
Gid: string
/**
* 账号状态:0-禁用;1-启用
*/
Status: number
/**
* 是否有root权限:0-否;1是,999为空: 仅linux
*/
IsRoot: number
/**
* 登录方式:0-不可登录;1-只允许key登录;2只允许密码登录;3-允许key和密码,999为空,仅linux
*/
LoginType: number
/**
* 上次登录时间
*/
LastLoginTime: string
/**
* 账号名称
*/
Name: string
/**
* 主机业务组ID
*/
ProjectId: number
/**
* 账号类型:0访客用户,1标准用户,2管理员用户 ,999为空,仅windows
*/
UserType: number
/**
* 是否域账号:0否, 1是,2否, 999为空 仅windows
*/
IsDomain: number
/**
* 是否有sudo权限,1是,0否, 999为空, 仅linux
*/
IsSudo: number
/**
* 是否允许ssh登录,1是,0否, 999为空, 仅linux
*/
IsSshLogin: number
/**
* Home目录
*/
HomePath: string
/**
* Shell路径 仅linux
*/
Shell: string
/**
* 是否shell登录性,0不是;1是 仅linux
*/
ShellLoginStatus: number
/**
* 密码修改时间
*/
PasswordChangeTime: string
/**
* 密码过期时间 仅linux
*/
PasswordDueTime: string
/**
* 密码锁定时间:单位天, -1为永不锁定 999为空,仅linux
*/
PasswordLockDays: number
/**
* 密码状态:1正常 2即将过期 3已过期 4已锁定 999为空 仅linux
*/
PasswordStatus: number
/**
* 更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribeMachineOsList返回参数结构体
*/
export interface DescribeMachineOsListResponse {
/**
* 操作系统列表
*/
List: Array<OsName>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportMaliciousRequests返回参数结构体
*/
export interface ExportMaliciousRequestsResponse {
/**
* 导出文件下载链接地址。
*/
DownloadUrl: string
/**
* 导出任务Id , 可通过ExportTasks 接口下载
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 批量导入机器信息.
*/
export interface EffectiveMachineInfo {
/**
* 机器名称
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineName: string
/**
* 机器公网ip
注意:此字段可能返回 null,表示取不到有效值。
*/
MachinePublicIp: string
/**
* 机器内网ip
注意:此字段可能返回 null,表示取不到有效值。
*/
MachinePrivateIp: string
/**
* 机器标签
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineTag: Array<MachineTag>
/**
* 机器Quuid
注意:此字段可能返回 null,表示取不到有效值。
*/
Quuid: string
/**
* 云镜Uuid
注意:此字段可能返回 null,表示取不到有效值。
*/
Uuid: string
}
/**
* DescribeVulCountByDates返回参数结构体
*/
export interface DescribeVulCountByDatesResponse {
/**
* 批量获得对应天数的漏洞数量
注意:此字段可能返回 null,表示取不到有效值。
*/
VulCount: Array<number>
/**
* 批量获得对应天数的主机数量
*/
HostCount: Array<number>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeTagMachines返回参数结构体
*/
export interface DescribeTagMachinesResponse {
/**
* 列表数据
*/
List: Array<TagMachine>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeIndexList请求参数结构体
*/
export type DescribeIndexListRequest = null
/**
* 防护目录列表集
*/
export interface ProtectDirInfo {
/**
* 网站名称
*/
DirName: string
/**
* 网站防护目录地址
*/
DirPath: string
/**
* 关联服务器数
*/
RelatedServerNum: number
/**
* 防护服务器数
*/
ProtectServerNum: number
/**
* 未防护服务器数
*/
NoProtectServerNum: number
/**
* 唯一ID
*/
Id: string
/**
* 防护状态
*/
ProtectStatus: number
/**
* 防护异常
*/
ProtectException: number
/**
* 自动恢复开关 (Filters 过滤Quuid 时 返回) 默认0
*/
AutoRestoreSwitchStatus: number
}
/**
* DeleteBashRules请求参数结构体
*/
export interface DeleteBashRulesRequest {
/**
* ID数组,最大100条。
*/
Ids: Array<number>
}
/**
* CreateProtectServer返回参数结构体
*/
export interface CreateProtectServerResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* OpenProVersion返回参数结构体
*/
export interface OpenProVersionResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeExpertServiceList请求参数结构体
*/
export interface DescribeExpertServiceListRequest {
/**
* 过滤条件。
<li>Keyword- String - 是否必填:否 - 关键词过滤,</li>
<li>Uuids - String - 是否必填:否 - 主机id过滤</li>
*/
Filters?: Array<Filters>
/**
* 需要返回的数量,最大值为100
*/
Limit?: number
/**
* 排序步长
*/
Offset?: number
/**
* 排序方法
*/
Order?: string
/**
* 排序字段 StartTime,EndTime
*/
By?: string
}
/**
* DescribeBaselineHostTop请求参数结构体
*/
export interface DescribeBaselineHostTopRequest {
/**
* 动态top值
*/
Top: number
/**
* 策略id
*/
StrategyId: number
}
/**
* ExportBaselineEffectHostList返回参数结构体
*/
export interface ExportBaselineEffectHostListResponse {
/**
* 下载地址
注意:此字段可能返回 null,表示取不到有效值。
*/
DownloadUrl: string
/**
* 导出任务id 可通过 ExportTasks接口下载
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeVulHostTop返回参数结构体
*/
export interface DescribeVulHostTopResponse {
/**
* 服务器风险top列表
注意:此字段可能返回 null,表示取不到有效值。
*/
VulHostTopList: Array<VulHostTopInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* TrustMalwares返回参数结构体
*/
export interface TrustMalwaresResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeHistoryService请求参数结构体
*/
export type DescribeHistoryServiceRequest = null
/**
* DescribeWarningList请求参数结构体
*/
export type DescribeWarningListRequest = null
/**
* ModifyProVersionRenewFlag请求参数结构体
*/
export interface ModifyProVersionRenewFlagRequest {
/**
* 自动续费标识。取值范围:
<li>NOTIFY_AND_AUTO_RENEW:通知过期且自动续费</li>
<li>NOTIFY_AND_MANUAL_RENEW:通知过期不自动续费</li>
<li>DISABLE_NOTIFY_AND_MANUAL_RENEW:不通知过期不自动续费</li>
*/
RenewFlag: string
/**
* 主机唯一ID,对应CVM的uuid、BM的instanceId。
*/
Quuid: string
}
/**
* DescribeServerRelatedDirInfo请求参数结构体
*/
export interface DescribeServerRelatedDirInfoRequest {
/**
* 唯一ID
*/
Id: number
}
/**
* DescribeESAggregations请求参数结构体
*/
export interface DescribeESAggregationsRequest {
/**
* ES聚合条件JSON
*/
Query: string
}
/**
* 基线影响服务器列表数据
*/
export interface BaselineHostTopList {
/**
* 事件等级与次数列表
注意:此字段可能返回 null,表示取不到有效值。
*/
EventLevelList: Array<BaselineEventLevelInfo>
/**
* 主机名称
注意:此字段可能返回 null,表示取不到有效值。
*/
HostName: string
/**
* 主机Quuid
注意:此字段可能返回 null,表示取不到有效值。
*/
Quuid: string
/**
* 计算权重的分数
注意:此字段可能返回 null,表示取不到有效值。
*/
Score: number
}
/**
* DescribeReverseShellRules返回参数结构体
*/
export interface DescribeReverseShellRulesResponse {
/**
* 列表内容
*/
List: Array<ReverseShellRule>
/**
* 总条数
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBruteAttackList请求参数结构体
*/
export interface DescribeBruteAttackListRequest {
/**
* 需要返回的数量,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Uuid - String - 是否必填:否 - 云镜唯一Uuid</li>
<li>Status - String - 是否必填:否 - 状态筛选:失败:FAILED 成功:SUCCESS</li>
<li>UserName - String - 是否必填:否 - UserName筛选</li>
<li>SrcIp - String - 是否必填:否 - 来源ip筛选</li>
<li>CreateBeginTime - String - 是否必填:否 - 首次攻击时间筛选,开始时间</li>
<li>CreateEndTime - String - 是否必填:否 - 首次攻击时间筛选,结束时间</li>
<li>ModifyBeginTime - String - 是否必填:否 - 最近攻击时间筛选,开始时间</li>
<li>ModifyEndTime - String - 是否必填:否 - 最近攻击时间筛选,结束时间</li>
<li>Banned - String - 是否必填:否 - 阻断状态筛选,多个用","分割:0-未阻断(全局ZK开关关闭),82-未阻断(非专业版),83-未阻断(已加白名单),1-已阻断,2-未阻断-程序异常,3-未阻断-内网攻击暂不支持阻断,4-未阻断-安平暂不支持阻断</li>
*/
Filters?: Array<Filter>
}
/**
* DescribeUndoVulCounts请求参数结构体
*/
export interface DescribeUndoVulCountsRequest {
/**
* 漏洞分类,最小值为1,最大值为5
*/
VulCategory?: number
/**
* 是否应急漏洞筛选, 是 : yes
*/
IfEmergency?: string
}
/**
* ScanAsset返回参数结构体
*/
export interface ScanAssetResponse {
/**
* 任务id
注意:此字段可能返回 null,表示取不到有效值。
*/
TaskId: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyProVersionRenewFlag返回参数结构体
*/
export interface ModifyProVersionRenewFlagResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 主机列表
*/
export interface Machine {
/**
* 主机名称。
*/
MachineName: string
/**
* 主机系统。
*/
MachineOs: string
/**
* 主机状态。
<li>OFFLINE: 离线 </li>
<li>ONLINE: 在线</li>
<li>SHUTDOWN: 已关机</li>
*/
MachineStatus: string
/**
* 云镜客户端唯一Uuid,若客户端长时间不在线将返回空字符。
*/
Uuid: string
/**
* CVM或BM机器唯一Uuid。
*/
Quuid: string
/**
* 漏洞数。
*/
VulNum: number
/**
* 主机IP。
*/
MachineIp: string
/**
* 是否是专业版。
<li>true: 是</li>
<li>false:否</li>
*/
IsProVersion: boolean
/**
* 主机外网IP。
*/
MachineWanIp: string
/**
* 主机状态。
<li>POSTPAY: 表示后付费,即按量计费 </li>
<li>PREPAY: 表示预付费,即包年包月</li>
*/
PayMode: string
/**
* 木马数。
*/
MalwareNum: number
/**
* 标签信息
*/
Tag: Array<MachineTag>
/**
* 基线风险数。
*/
BaselineNum: number
/**
* 网络风险数。
*/
CyberAttackNum: number
/**
* 风险状态。
<li>SAFE:安全</li>
<li>RISK:风险</li>
<li>UNKNOWN:未知</li>
*/
SecurityStatus: string
/**
* 入侵事件数
*/
InvasionNum: number
/**
* 地域信息
*/
RegionInfo: RegionInfo
/**
* 实例状态 TERMINATED_PRO_VERSION 已销毁
*/
InstanceState: string
/**
* 防篡改 授权状态 1 授权 0 未授权
*/
LicenseStatus: number
/**
* 项目ID
*/
ProjectId: number
/**
* 是否有资产扫描接口,0无,1有
*/
HasAssetScan: number
/**
* 机器所属专区类型 CVM 云服务器, BM 黑石, ECM 边缘计算, LH 轻量应用服务器 ,Other 混合云专区
*/
MachineType: string
}
/**
* 授权机器信息
*/
export interface ProtectMachineInfo {
/**
* 机器名称
*/
HostName: string
/**
* 机器IP
*/
HostIp: string
/**
* 开通时间
*/
CreateTime: string
/**
* 到期时间
*/
ExpireTime: string
}
/**
* DescribeMalwareFile请求参数结构体
*/
export interface DescribeMalwareFileRequest {
/**
* 木马记录ID
*/
Id: number
}
/**
* DeleteMaliciousRequests请求参数结构体
*/
export interface DeleteMaliciousRequestsRequest {
/**
* 恶意请求记录ID数组,(最大100条)
*/
Ids: Array<number>
}
/**
* DescribeBanWhiteList请求参数结构体
*/
export interface DescribeBanWhiteListRequest {
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 返回数量,最大值为100。
*/
Limit?: number
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 查询关键字 </li>
*/
Filters?: Array<Filter>
}
/**
* DescribeWebPageServiceInfo返回参数结构体
*/
export interface DescribeWebPageServiceInfoResponse {
/**
* 是否已购服务:true-是,false-否
*/
Status: boolean
/**
* 已使用授权数
*/
UsedNum: number
/**
* 剩余授权数
*/
ResidueNum: number
/**
* 已购授权数
*/
BuyNum: number
/**
* 临近到期数量
*/
ExpireNum: number
/**
* 所有授权机器信息
*/
AllAuthorizedMachines: Array<ProtectMachineInfo>
/**
* 临近到期授权机器信息
*/
ExpireAuthorizedMachines: Array<ProtectMachine>
/**
* 已过期授权数
*/
ExpiredNum: number
/**
* 防护目录数
*/
ProtectDirNum: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeUsualLoginPlaces请求参数结构体
*/
export interface DescribeUsualLoginPlacesRequest {
/**
* 云镜客户端UUID
*/
Uuid: string
}
/**
* 防护事件列表信息
*/
export interface ProtectEventLists {
/**
* 服务器名称
*/
HostName: string
/**
* 服务器ip
*/
HostIp: string
/**
* 事件地址
*/
EventDir: string
/**
* 事件类型 0-内容被修改恢复;1-权限被修改恢复;2-归属被修改恢复;3-被删除恢复;4-新增删除
*/
EventType: number
/**
* 事件状态 1 已恢复 0 未恢复
*/
EventStatus: number
/**
* 发现时间
*/
CreateTime: string
/**
* 恢复时间
*/
RestoreTime: string
/**
* 唯一ID
*/
Id: number
/**
* 文件类型 0-常规文件;1-目录;2-软链
*/
FileType: number
}
/**
* SwitchBashRules请求参数结构体
*/
export interface SwitchBashRulesRequest {
/**
* 规则ID
*/
Id: number
/**
* 是否禁用
*/
Disabled: number
}
/**
* DescribeProcessStatistics请求参数结构体
*/
export interface DescribeProcessStatisticsRequest {
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>ProcessName - String - 是否必填:否 - 进程名</li>
*/
Filters?: Array<Filter>
}
/**
* DescribeAssetInfo返回参数结构体
*/
export interface DescribeAssetInfoResponse {
/**
* 主机数
*/
MachineCount: number
/**
* 账号数
*/
AccountCount: number
/**
* 端口数
*/
PortCount: number
/**
* 进程数
*/
ProcessCount: number
/**
* 软件数
*/
SoftwareCount: number
/**
* 数据库数
*/
DatabaseCount: number
/**
* Web应用数
*/
WebAppCount: number
/**
* Web框架数
*/
WebFrameCount: number
/**
* Web服务数
*/
WebServiceCount: number
/**
* Web站点数
*/
WebLocationCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 恶意文件风险提示列表信息
*/
export interface MalwareRisk {
/**
* 机器IP
*/
MachineIp: string
/**
* 病毒名
*/
VirusName: string
/**
* 发现时间
*/
CreateTime: string
/**
* 唯一ID
*/
Id: number
}
/**
* ExportProtectDirList返回参数结构体
*/
export interface ExportProtectDirListResponse {
/**
* 任务ID
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 资源管理Web应用列表信息
*/
export interface AssetWebFrameBaseInfo {
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* 操作系统信息
*/
OsInfo: string
/**
* 主机业务组ID
*/
ProjectId: number
/**
* 主机标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tag: Array<MachineTag>
/**
* 数据库名
*/
Name: string
/**
* 版本
*/
Version: string
/**
* 语言
*/
Lang: string
/**
* 服务类型
*/
ServiceType: string
/**
* 主机名称
*/
MachineName: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* ExportTasks请求参数结构体
*/
export interface ExportTasksRequest {
/**
* 任务ID
*/
TaskId: string
}
/**
* DescribeAssetWebLocationInfo返回参数结构体
*/
export interface DescribeAssetWebLocationInfoResponse {
/**
* 站点信息
注意:此字段可能返回 null,表示取不到有效值。
*/
WebLocation: AssetWebLocationInfo
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyBruteAttackRules请求参数结构体
*/
export interface ModifyBruteAttackRulesRequest {
/**
* 暴力破解判断规则
*/
Rules: Array<BruteAttackRule>
}
/**
* ExportVulList请求参数结构体
*/
export interface ExportVulListRequest {
/**
* 过滤条件。
<li>VulCategory - int - 是否必填:否 - 漏洞分类筛选 1: web应用漏洞 2:系统组件漏洞 3:安全基线</li>
<li>IfEmergency - String - 是否必填:否 - 是否为应急漏洞,查询应急漏洞传:yes</li>
<li>Status - String - 是否必填:是 - 漏洞状态筛选,0: 待处理 1:忽略 3:已修复 5:检测中, 控制台仅处理0,1,3,5四种状态</li>
<li>Level - String - 是否必填:否 - 漏洞等级筛选 1:低 2:中 3:高 4:提示</li>
<li>VulName- String - 是否必填:否 - 漏洞名称搜索</li>
*/
Filters?: Array<Filter>
/**
* 是否导出详情,1是 0不是
*/
IfDetail?: number
}
/**
* DescribeAccounts返回参数结构体
*/
export interface DescribeAccountsResponse {
/**
* 帐号列表记录总数。
*/
TotalCount?: number
/**
* 帐号数据列表。
*/
Accounts?: Array<Account>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBaselineScanSchedule请求参数结构体
*/
export interface DescribeBaselineScanScheduleRequest {
/**
* 任务id
*/
TaskId: number
}
/**
* DescribeEmergencyVulList返回参数结构体
*/
export interface DescribeEmergencyVulListResponse {
/**
* 漏洞列表
注意:此字段可能返回 null,表示取不到有效值。
*/
List: Array<EmergencyVul>
/**
* 漏洞总条数
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalCount: number
/**
* 是否存在风险
注意:此字段可能返回 null,表示取不到有效值。
*/
ExistsRisk: boolean
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetUserList返回参数结构体
*/
export interface DescribeAssetUserListResponse {
/**
* 记录总数
*/
Total: number
/**
* 账号列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Users: Array<AssetUserBaseInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 标准模式阻断配置
*/
export interface StandardModeConfig {
/**
* 阻断时长,单位:秒
*/
Ttl: number
}
/**
* 高危命令数据
*/
export interface BashEvent {
/**
* 数据ID
*/
Id: number
/**
* 云镜ID
*/
Uuid: string
/**
* 主机ID
*/
Quuid: string
/**
* 主机内网IP
*/
Hostip: string
/**
* 执行用户名
*/
User: string
/**
* 平台类型
*/
Platform: number
/**
* 执行命令
*/
BashCmd: string
/**
* 规则ID
*/
RuleId: number
/**
* 规则名称
*/
RuleName: string
/**
* 规则等级:1-高 2-中 3-低
*/
RuleLevel: number
/**
* 处理状态: 0 = 待处理 1= 已处理, 2 = 已加白
*/
Status: number
/**
* 发生时间
*/
CreateTime: string
/**
* 主机名
*/
MachineName: string
/**
* 0: bash日志 1: 实时监控(雷霆版)
注意:此字段可能返回 null,表示取不到有效值。
*/
DetectBy: number
/**
* 进程id
注意:此字段可能返回 null,表示取不到有效值。
*/
Pid: string
/**
* 进程名称
注意:此字段可能返回 null,表示取不到有效值。
*/
Exe: string
/**
* 处理时间
注意:此字段可能返回 null,表示取不到有效值。
*/
ModifyTime: string
/**
* 规则类别 0=系统规则,1=用户规则
注意:此字段可能返回 null,表示取不到有效值。
*/
RuleCategory: number
/**
* 自动生成的正则表达式
注意:此字段可能返回 null,表示取不到有效值。
*/
RegexBashCmd: string
}
/**
* DeleteMalwares请求参数结构体
*/
export interface DeleteMalwaresRequest {
/**
* 木马记录ID数组 (最大100条)
*/
Ids: Array<number>
}
/**
* RecoverMalwares返回参数结构体
*/
export interface RecoverMalwaresResponse {
/**
* 恢复成功id数组,若无则返回空数组
*/
SuccessIds: Array<number>
/**
* 恢复失败id数组,若无则返回空数组
*/
FailedIds: Array<number>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 地域信息
*/
export interface RegionSet {
/**
* 地域名称
*/
RegionName: string
/**
* 可用区信息
*/
ZoneSet: Array<ZoneInfo>
}
/**
* DescribeReverseShellRules请求参数结构体
*/
export interface DescribeReverseShellRulesRequest {
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 关键字(进程名称)</li>
*/
Filters?: Array<Filter>
}
/**
* DescribeScanVulSetting返回参数结构体
*/
export interface DescribeScanVulSettingResponse {
/**
* 漏洞类型:1: web应用漏洞 2:系统组件漏洞 (多选英文逗号分隔)
*/
VulCategories: string
/**
* 危害等级:1-低危;2-中危;3-高危;4-严重 (多选英文逗号分隔)
*/
VulLevels: string
/**
* 定期检测间隔时间(天)
*/
TimerInterval: number
/**
* 定期检测时间,如:00:00
*/
TimerTime: string
/**
* 是否紧急漏洞:0-否 1-是
*/
VulEmergency: number
/**
* 开始时间
*/
StartTime: string
/**
* 是否开启
*/
EnableScan: number
/**
* 结束时间
*/
EndTime: string
/**
* 一键扫描超时时长,如:1800秒(s)
*/
ClickTimeout: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 容器安全
描述键值对过滤器,用于条件过滤查询。例如过滤ID、名称、状态等
若存在多个Filter时,Filter间的关系为逻辑与(AND)关系。
若同一个Filter存在多个Values,同一Filter下Values间的关系为逻辑或(OR)关系。
*/
export interface AssetFilters {
/**
* 过滤键的名称。
*/
Name: string
/**
* 一个或者多个过滤值。
*/
Values: Array<string>
/**
* 是否模糊查询
*/
ExactMatch?: boolean
}
/**
* DescribeAssetDatabaseInfo返回参数结构体
*/
export interface DescribeAssetDatabaseInfoResponse {
/**
* 数据库详情
*/
Database: AssetDatabaseDetail
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* SetBashEventsStatus请求参数结构体
*/
export interface SetBashEventsStatusRequest {
/**
* ID数组,最大100条。
*/
Ids: Array<number>
/**
* 新状态(0-待处理 1-高危 2-正常)
*/
Status: number
}
/**
* DescribeAccounts请求参数结构体
*/
export interface DescribeAccountsRequest {
/**
* 云镜客户端唯一Uuid。Username和Uuid必填其一,使用Uuid表示,查询该主机下列表信息。
*/
Uuid?: string
/**
* 云镜客户端唯一Uuid。Username和Uuid必填其一,使用Username表示,查询该用户名下列表信息。
*/
Username?: string
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Username - String - 是否必填:否 - 帐号名</li>
<li>Privilege - String - 是否必填:否 - 帐号类型(ORDINARY: 普通帐号 | SUPPER: 超级管理员帐号)</li>
<li>MachineIp - String - 是否必填:否 - 主机内网IP</li>
*/
Filters?: Array<Filter>
}
/**
* 软件应用关联进程信息
*/
export interface AssetAppProcessInfo {
/**
* 名称
*/
Name: string
/**
* 进程状态
*/
Status: string
/**
* 进程版本
*/
Version: string
/**
* 路径
*/
Path: string
/**
* 用户
*/
User: string
/**
* 启动时间
*/
StartTime: string
}
/**
* DescribeBaselineStrategyList请求参数结构体
*/
export interface DescribeBaselineStrategyListRequest {
/**
* 分页参数 最大100
*/
Limit: number
/**
* 分页参数
*/
Offset: number
/**
* 规则开关,1:打开 0:关闭 2:全部
*/
Enabled: number
}
/**
* 地域信息
*/
export interface RegionInfo {
/**
* 地域标志,如 ap-guangzhou,ap-shanghai,ap-beijing
*/
Region: string
/**
* 地域中文名,如华南地区(广州),华东地区(上海金融),华北地区(北京)
*/
RegionName: string
/**
* 地域ID
*/
RegionId: number
/**
* 地域代码,如 gz,sh,bj
*/
RegionCode: string
/**
* 地域英文名
*/
RegionNameEn: string
}
/**
* DescribeAttackLogs请求参数结构体
*/
export interface DescribeAttackLogsRequest {
/**
* 返回数量,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>HttpMethod - String - 是否必填:否 - 攻击方法(POST|GET)</li>
<li>DateRange - String - 是否必填:否 - 时间范围(存储最近3个月的数据),如最近一个月["2019-11-17", "2019-12-17"]</li>
<li>VulType - String 威胁类型 - 是否必填: 否</li>
<li>SrcIp - String 攻击源IP - 是否必填: 否</li>
<li>DstIp - String 攻击目标IP - 是否必填: 否</li>
<li>SrcPort - String 攻击源端口 - 是否必填: 否</li>
<li>DstPort - String 攻击目标端口 - 是否必填: 否</li>
*/
Filters?: Array<Filter>
/**
* 主机安全客户端ID
*/
Uuid?: string
/**
* 云主机机器ID
*/
Quuid?: string
}
/**
* 组件统计数据。
*/
export interface ComponentStatistics {
/**
* 组件ID。
*/
Id: number
/**
* 主机数量。
*/
MachineNum: number
/**
* 组件名称。
*/
ComponentName: string
/**
* 组件类型。
<li>WEB:Web组件</li>
<li>SYSTEM:系统组件</li>
*/
ComponentType: string
/**
* 组件描述。
*/
Description: string
}
/**
* ExportAssetWebServiceInfoList请求参数结构体
*/
export interface ExportAssetWebServiceInfoListRequest {
/**
* 过滤条件。
<li>User- string - 是否必填:否 - 运行用户</li>
<li>Name- string - 是否必填:否 - Web服务名:
1:Tomcat
2:Apache
3:Nginx
4:WebLogic
5:Websphere
6:JBoss
7:WildFly
8:Jetty
9:IHS
10:Tengine</li>
<li>OsType- string - 是否必填:否 - Windows/linux</li>
*/
Filters?: Array<AssetFilters>
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 可选排序:ProcessCount
*/
By?: string
/**
* 查询指定Quuid主机的信息
*/
Quuid?: string
}
/**
* SetBashEventsStatus返回参数结构体
*/
export interface SetBashEventsStatusResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 机器授权到期信息
*/
export interface ProtectMachine {
/**
* 机器名称
*/
HostName: string
/**
* 机器IP
*/
HostIp: string
/**
* 防护目录数
*/
SafeguardDirNum: number
}
/**
* DescribeAssetUserInfo请求参数结构体
*/
export interface DescribeAssetUserInfoRequest {
/**
* 服务器Quuid
*/
Quuid: string
/**
* 服务器Uuid
*/
Uuid: string
/**
* 账户名
*/
Name: string
}
/**
* DescribeProtectDirList请求参数结构体
*/
export interface DescribeProtectDirListRequest {
/**
* 分页条数 最大100条
*/
Limit: number
/**
* 偏移量
*/
Offset: number
/**
* DirName 网站名称
DirPath 网站防护目录地址
*/
Filters?: Array<AssetFilters>
/**
* asc:升序/desc:降序
*/
Order?: string
/**
* 排序字段
*/
By?: string
}
/**
* ExportPrivilegeEvents请求参数结构体
*/
export interface ExportPrivilegeEventsRequest {
/**
* 过滤参数
*/
Filters?: Array<Filters>
}
/**
* 帐号列表信息数据。
*/
export interface Account {
/**
* 唯一ID。
*/
Id: number
/**
* 云镜客户端唯一Uuid
*/
Uuid: string
/**
* 主机内网IP。
*/
MachineIp: string
/**
* 主机名称。
*/
MachineName: string
/**
* 帐号名。
*/
Username: string
/**
* 帐号所属组。
*/
Groups: string
/**
* 帐号类型。
<li>ORDINARY:普通帐号</li>
<li>SUPPER:超级管理员帐号</li>
*/
Privilege: string
/**
* 帐号创建时间。
*/
AccountCreateTime: string
/**
* 帐号最后登录时间。
*/
LastLoginTime: string
}
/**
* DescribeMalwareFile返回参数结构体
*/
export interface DescribeMalwareFileResponse {
/**
* 木马文件下载地址
*/
FileUrl: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 任务扫描状态列表
*/
export interface TaskStatus {
/**
* 扫描中(包含初始化)
*/
Scanning: string
/**
* 扫描终止(包含终止中)
*/
Ok: string
/**
* 扫描失败
*/
Fail: string
/**
* 扫描失败(提示具体原因:扫描超时、客户端版本低、客户端离线)
注意:此字段可能返回 null,表示取不到有效值。
*/
Stop: string
}
/**
* DescribeRiskDnsList返回参数结构体
*/
export interface DescribeRiskDnsListResponse {
/**
* 恶意请求列表数组
注意:此字段可能返回 null,表示取不到有效值。
*/
RiskDnsList: Array<RiskDnsList>
/**
* 总数量
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetWebAppList返回参数结构体
*/
export interface DescribeAssetWebAppListResponse {
/**
* 记录总数
*/
Total: number
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
WebApps: Array<AssetWebAppBaseInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 扫描任务详情列表信息
*/
export interface ScanTaskDetails {
/**
* 服务器IP
*/
HostIp: string
/**
* 服务器名称
*/
HostName: string
/**
* 操作系统
*/
OsName: string
/**
* 风险数量
*/
RiskNum: number
/**
* 扫描开始时间
*/
ScanBeginTime: string
/**
* 扫描结束时间
*/
ScanEndTime: string
/**
* 唯一Uuid
*/
Uuid: string
/**
* 唯一Quuid
*/
Quuid: string
/**
* 状态码
*/
Status: string
/**
* 描述
*/
Description: string
/**
* id唯一
*/
Id: number
/**
* 失败详情
*/
FailType: number
}
/**
* 资源管理数据库列表信息
*/
export interface AssetDatabaseDetail {
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* 操作系统信息
*/
OsInfo: string
/**
* 数据库名
*/
Name: string
/**
* 版本
*/
Version: string
/**
* 监听端口
*/
Port: string
/**
* 协议
*/
Proto: string
/**
* 运行用户
*/
User: string
/**
* 绑定IP
*/
Ip: string
/**
* 配置文件路径
*/
ConfigPath: string
/**
* 日志文件路径
*/
LogPath: string
/**
* 数据路径
*/
DataPath: string
/**
* 运行权限
*/
Permission: string
/**
* 错误日志路径
*/
ErrorLogPath: string
/**
* 插件路径
*/
PlugInPath: string
/**
* 二进制路径
*/
BinPath: string
/**
* 启动参数
*/
Param: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribeScanTaskStatus请求参数结构体
*/
export interface DescribeScanTaskStatusRequest {
/**
* 模块类型 当前提供 Malware 木马 , Vul 漏洞 , Baseline 基线
*/
ModuleType: string
}
/**
* ExportIgnoreBaselineRule请求参数结构体
*/
export interface ExportIgnoreBaselineRuleRequest {
/**
* 检测项名称
*/
RuleName?: string
}
/**
* DeleteMachineTag请求参数结构体
*/
export interface DeleteMachineTagRequest {
/**
* 关联的标签ID
*/
Rid: number
}
/**
* 资产管理磁盘分区信息
*/
export interface AssetDiskPartitionInfo {
/**
* 分区名
*/
Name: string
/**
* 分区大小:单位G
*/
Size: number
/**
* 分区使用率
*/
Percent: number
/**
* 文件系统类型
*/
Type: string
/**
* 挂载目录
*/
Path: string
/**
* 已使用空间:单位G
*/
Used: number
}
/**
* 可用区信息
*/
export interface ZoneInfo {
/**
* 可用区名称
*/
ZoneName: string
}
/**
* 基线检测信息
*/
export interface BaselineRuleInfo {
/**
* 检测项名称
*/
RuleName: string
/**
* 检测项描述
*/
Description: string
/**
* 修复建议
*/
FixMessage: string
/**
* 危害等级
*/
Level: number
/**
* 状态
*/
Status: number
/**
* 检测项id
*/
RuleId: number
/**
* 最后检测时间
*/
LastScanAt: string
/**
* 具体原因说明
*/
RuleRemark: string
/**
* 唯一Uuid
*/
Uuid: string
/**
* 唯一事件ID
*/
EventId: number
}
/**
* DescribeExportMachines返回参数结构体
*/
export interface DescribeExportMachinesResponse {
/**
* 任务id
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeScanTaskStatus返回参数结构体
*/
export interface DescribeScanTaskStatusResponse {
/**
* 任务扫描状态列表
*/
State: TaskStatus
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeProtectNetList请求参数结构体
*/
export interface DescribeProtectNetListRequest {
/**
* 过滤条件。
<li>Keyword- String - 是否必填:否 - 关键词过滤,</li>
<li>Uuids - String - 是否必填:否 - 主机id过滤</li>
*/
Filters?: Array<Filters>
/**
* 需要返回的数量,最大值为100
*/
Limit?: number
/**
* 排序步长
*/
Offset?: number
/**
* 排序方法
*/
Order?: string
/**
* 排序字段 StartTime,EndTime
*/
By?: string
}
/**
* DescribeWebPageEventList返回参数结构体
*/
export interface DescribeWebPageEventListResponse {
/**
* 防护事件列表信息
*/
List: Array<ProtectEventLists>
/**
* 总数
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteProtectDir返回参数结构体
*/
export interface DeleteProtectDirResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyBanStatus请求参数结构体
*/
export interface ModifyBanStatusRequest {
/**
* 阻断状态 0:关闭 1:开启
*/
Status: number
}
/**
* DescribeWebPageServiceInfo请求参数结构体
*/
export type DescribeWebPageServiceInfoRequest = null
/**
* SyncAssetScan请求参数结构体
*/
export interface SyncAssetScanRequest {
/**
* 是否同步:true-是 false-否;默认false
*/
Sync: boolean
}
/**
* DescribeLogStorageStatistic返回参数结构体
*/
export interface DescribeLogStorageStatisticResponse {
/**
* 总容量(单位:GB)
*/
TotalSize: number
/**
* 已使用容量(单位:GB)
*/
UsedSize: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeEmergencyResponseList请求参数结构体
*/
export interface DescribeEmergencyResponseListRequest {
/**
* 过滤条件。
<li>Keyword- String - 是否必填:否 - 关键词过滤,</li>
<li>Uuids - String - 是否必填:否 - 主机id过滤</li>
*/
Filters?: Array<Filters>
/**
* 需要返回的数量,最大值为100
*/
Limit?: number
/**
* 排序步长
*/
Offset?: number
/**
* 排序方法
*/
Order?: string
/**
* 排序字段 StartTime,EndTime
*/
By?: string
}
/**
* DescribeScanState返回参数结构体
*/
export interface DescribeScanStateResponse {
/**
* 0 从未扫描过、 1 扫描中、 2扫描完成、 3停止中、 4停止完成
*/
ScanState: number
/**
* 扫描进度
*/
Schedule: number
/**
* 任务Id
*/
TaskId: number
/**
* 任务扫描的漏洞id
*/
VulId: Array<number>
/**
* 0一键检测 1定时检测
*/
Type: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* EditTags请求参数结构体
*/
export interface EditTagsRequest {
/**
* 标签名
*/
Name: string
/**
* 标签ID
*/
Id?: number
/**
* Quuid
*/
Quuids?: Array<string>
}
/**
* DeleteReverseShellRules请求参数结构体
*/
export interface DeleteReverseShellRulesRequest {
/**
* ID数组. (最大100条)
*/
Ids: Array<number>
}
/**
* DescribeBaselineEffectHostList请求参数结构体
*/
export interface DescribeBaselineEffectHostListRequest {
/**
* 分页参数 最大100条
*/
Limit: number
/**
* 分页参数
*/
Offset: number
/**
* 基线id
*/
BaselineId: number
/**
* 过滤条件。
<li>AliasName- String- 主机别名</li>
<li>Status- Uint- 1已通过 0未通过 5检测中</li>
*/
Filters?: Array<Filters>
/**
* 策略id
*/
StrategyId?: number
/**
* 主机uuid数组
*/
UuidList?: Array<string>
}
/**
* ExportSecurityTrends请求参数结构体
*/
export interface ExportSecurityTrendsRequest {
/**
* 开始时间。
*/
BeginDate: string
/**
* 结束时间。
*/
EndDate: string
}
/**
* DescribeAssetDatabaseInfo请求参数结构体
*/
export interface DescribeAssetDatabaseInfoRequest {
/**
* 服务器Quuid
*/
Quuid: string
/**
* 服务器Uuid
*/
Uuid: string
/**
* 数据库ID
*/
Id: string
}
/**
* DescribeOpenPortStatistics请求参数结构体
*/
export interface DescribeOpenPortStatisticsRequest {
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Port - Uint64 - 是否必填:否 - 端口号</li>
*/
Filters?: Array<Filter>
}
/**
* ExportAssetWebServiceInfoList返回参数结构体
*/
export interface ExportAssetWebServiceInfoListResponse {
/**
* 异步下载任务ID,需要配合ExportTasks接口使用
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportSecurityTrends返回参数结构体
*/
export interface ExportSecurityTrendsResponse {
/**
* 导出文件下载链接地址。
*/
DownloadUrl: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyMalwareTimingScanSettings返回参数结构体
*/
export interface ModifyMalwareTimingScanSettingsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteNonlocalLoginPlaces返回参数结构体
*/
export interface DeleteNonlocalLoginPlacesResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyWebPageProtectSetting请求参数结构体
*/
export interface ModifyWebPageProtectSettingRequest {
/**
* 需要操作的类型1 目录名称 2 防护文件类型
*/
ModifyType: number
/**
* 提交值
*/
Value: string
/**
* 配置对应的protect_path
*/
Id: string
}
/**
* DeleteMalwareScanTask返回参数结构体
*/
export interface DeleteMalwareScanTaskResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBaselineDetail返回参数结构体
*/
export interface DescribeBaselineDetailResponse {
/**
* 基线详情
注意:此字段可能返回 null,表示取不到有效值。
*/
BaselineDetail: BaselineDetail
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportIgnoreRuleEffectHostList返回参数结构体
*/
export interface ExportIgnoreRuleEffectHostListResponse {
/**
* 导出文件下载地址
*/
DownloadUrl: string
/**
* 导出任务Id , 可通过ExportTasks 接口下载
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetWebAppPluginList请求参数结构体
*/
export interface DescribeAssetWebAppPluginListRequest {
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* Web应用ID
*/
Id: string
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
}
/**
* DeletePrivilegeEvents返回参数结构体
*/
export interface DeletePrivilegeEventsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeMachineInfo返回参数结构体
*/
export interface DescribeMachineInfoResponse {
/**
* 机器ip。
*/
MachineIp: string
/**
* 受云镜保护天数。
*/
ProtectDays: number
/**
* 操作系统。
*/
MachineOs: string
/**
* 主机名称。
*/
MachineName: string
/**
* 在线状态。
<li>ONLINE: 在线</li>
<li>OFFLINE:离线</li>
*/
MachineStatus: string
/**
* CVM或BM主机唯一标识。
*/
InstanceId: string
/**
* 主机外网IP。
*/
MachineWanIp: string
/**
* CVM或BM主机唯一Uuid。
*/
Quuid: string
/**
* 云镜客户端唯一Uuid。
*/
Uuid: string
/**
* 是否开通专业版。
<li>true:是</li>
<li>false:否</li>
*/
IsProVersion: boolean
/**
* 专业版开通时间。
*/
ProVersionOpenDate: string
/**
* 云主机类型。
<li>CVM: 腾讯云服务器</li>
<li>BM: 黑石物理机</li>
<li>ECM: 边缘计算服务器</li>
<li>LH: 轻量应用服务器</li>
<li>Other: 混合云机器</li>
*/
MachineType: string
/**
* 机器所属地域。如:ap-guangzhou,ap-shanghai
*/
MachineRegion: string
/**
* 主机状态。
<li>POSTPAY: 表示后付费,即按量计费 </li>
<li>PREPAY: 表示预付费,即包年包月</li>
*/
PayMode: string
/**
* 免费木马剩余检测数量。
*/
FreeMalwaresLeft: number
/**
* 免费漏洞剩余检测数量。
*/
FreeVulsLeft: number
/**
* agent版本号
*/
AgentVersion: string
/**
* 专业版到期时间(仅预付费)
*/
ProVersionDeadline: string
/**
* 是否有资产扫描记录,0无,1有
*/
HasAssetScan: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 服务器风险top5实体
*/
export interface VulHostTopInfo {
/**
* 主机名
注意:此字段可能返回 null,表示取不到有效值。
*/
HostName: string
/**
* 漏洞等级与数量统计列表
注意:此字段可能返回 null,表示取不到有效值。
*/
VulLevelList: Array<VulLevelCountInfo>
/**
* 主机Quuid
注意:此字段可能返回 null,表示取不到有效值。
*/
Quuid: string
/**
* top评分
注意:此字段可能返回 null,表示取不到有效值。
*/
Score: number
}
/**
* DescribeImportMachineInfo请求参数结构体
*/
export interface DescribeImportMachineInfoRequest {
/**
* 服务器内网IP(默认)/ 服务器名称 / 服务器ID 数组 (最大 1000条)
*/
MachineList: Array<string>
/**
* 批量导入的数据类型:Ip、Name、Id 三选一
*/
ImportType: string
/**
* 是否仅支持专业版机器的查询(true:仅专业版 false:专业版+基础版)
*/
IsQueryProMachine?: boolean
}
/**
* 漏洞数量按等级分布统计结果实体
*/
export interface VulLevelInfo {
/**
* // 危害等级:1-低危;2-中危;3-高危;4-严重
*/
VulLevel: number
/**
* 数量
*/
Count: number
}
/**
* 防护信息统计
*/
export interface ProtectStat {
/**
* 名称
*/
Name: string
/**
* 数量
*/
Num: number
}
/**
* SwitchBashRules返回参数结构体
*/
export interface SwitchBashRulesResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeSearchLogs请求参数结构体
*/
export type DescribeSearchLogsRequest = null
/**
* DescribeAttackLogInfo请求参数结构体
*/
export interface DescribeAttackLogInfoRequest {
/**
* 日志ID
*/
Id: number
}
/**
* ScanVulSetting返回参数结构体
*/
export interface ScanVulSettingResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetJarInfo返回参数结构体
*/
export interface DescribeAssetJarInfoResponse {
/**
* Jar包详情
*/
Jar: AssetJarDetail
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeVulInfoCvss请求参数结构体
*/
export interface DescribeVulInfoCvssRequest {
/**
* 漏洞id
*/
VulId: number
}
/**
* DescribeComponentStatistics请求参数结构体
*/
export interface DescribeComponentStatisticsRequest {
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
ComponentName - String - 是否必填:否 - 组件名称
*/
Filters?: Array<Filter>
}
/**
* RescanImpactedHost请求参数结构体
*/
export interface RescanImpactedHostRequest {
/**
* 漏洞ID。
*/
Id: number
}
/**
* DescribeMaliciousRequestWhiteList请求参数结构体
*/
export interface DescribeMaliciousRequestWhiteListRequest {
/**
* 分页参数
*/
Limit: number
/**
* 分页参数
*/
Offset: number
/**
* 过滤条件。
<li>Domain - String - 基线名称</li>
*/
Filters?: Array<Filters>
}
/**
* ModifyBanStatus返回参数结构体
*/
export interface ModifyBanStatusResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeLoginWhiteList返回参数结构体
*/
export interface DescribeLoginWhiteListResponse {
/**
* 记录总数
*/
TotalCount: number
/**
* 异地登录白名单数组
*/
LoginWhiteLists: Array<LoginWhiteLists>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* StopNoticeBanTips返回参数结构体
*/
export interface StopNoticeBanTipsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeScanMalwareSchedule返回参数结构体
*/
export interface DescribeScanMalwareScheduleResponse {
/**
* 扫描进度(单位:%)
*/
Schedule: number
/**
* 风险文件数,当进度满了以后才有该值
*/
RiskFileNumber: number
/**
* 是否正在扫描中
*/
IsSchedule: boolean
/**
* 0 从未扫描过、 1 扫描中、 2扫描完成、 3停止中、 4停止完成
*/
ScanStatus: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 资产管理Web站点列表信息
*/
export interface AssetWebLocationBaseInfo {
/**
* 主机Uuid
*/
Uuid: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 内网IP
*/
MachineIp: string
/**
* 外网IP
*/
MachineWanIp: string
/**
* 主机名称
*/
MachineName: string
/**
* 操作系统
*/
OsInfo: string
/**
* 域名
*/
Name: string
/**
* 站点端口
*/
Port: string
/**
* 站点协议
*/
Proto: string
/**
* 服务类型
*/
ServiceType: string
/**
* 站点路经数
*/
PathCount: number
/**
* 运行用户
*/
User: string
/**
* 主目录
*/
MainPath: string
/**
* 主目录所有者
*/
MainPathOwner: string
/**
* 拥有者权限
*/
Permission: string
/**
* 主机业务组ID
*/
ProjectId: number
/**
* 主机标签
*/
Tag: Array<MachineTag>
/**
* Web站点Id
*/
Id: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribeMalwareTimingScanSetting请求参数结构体
*/
export type DescribeMalwareTimingScanSettingRequest = null
/**
* 高危命令规则
*/
export interface BashRule {
/**
* 规则ID
*/
Id: number
/**
* 客户端ID
*/
Uuid: string
/**
* 规则名称
*/
Name: string
/**
* 危险等级(0 :无 1: 高危 2:中危 3: 低危)
*/
Level: number
/**
* 正则表达式
*/
Rule: string
/**
* 规则描述
*/
Decription: string
/**
* 操作人
*/
Operator: string
/**
* 是否全局规则
*/
IsGlobal: number
/**
* 状态 (0: 有效 1: 无效)
*/
Status: number
/**
* 创建时间
*/
CreateTime: string
/**
* 修改时间
*/
ModifyTime: string
/**
* 主机IP
*/
Hostip: string
/**
* 生效服务器的uuid数组
注意:此字段可能返回 null,表示取不到有效值。
*/
Uuids: Array<string>
/**
* 0=黑名单 1=白名单
注意:此字段可能返回 null,表示取不到有效值。
*/
White: number
/**
* 是否处理之前的事件 0: 不处理 1:处理
注意:此字段可能返回 null,表示取不到有效值。
*/
DealOldEvents: number
}
/**
* RenewProVersion返回参数结构体
*/
export interface RenewProVersionResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateSearchLog返回参数结构体
*/
export interface CreateSearchLogResponse {
/**
* 0:成功,非0:失败
*/
Status: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeSecurityTrends返回参数结构体
*/
export interface DescribeSecurityTrendsResponse {
/**
* 木马事件统计数据数组。
*/
Malwares: Array<SecurityTrend>
/**
* 异地登录事件统计数据数组。
*/
NonLocalLoginPlaces: Array<SecurityTrend>
/**
* 密码破解事件统计数据数组。
*/
BruteAttacks: Array<SecurityTrend>
/**
* 漏洞统计数据数组。
*/
Vuls: Array<SecurityTrend>
/**
* 基线统计数据数组。
*/
BaseLines: Array<SecurityTrend>
/**
* 恶意请求统计数据数组。
*/
MaliciousRequests: Array<SecurityTrend>
/**
* 高危命令统计数据数组。
*/
HighRiskBashs: Array<SecurityTrend>
/**
* 反弹shell统计数据数组。
*/
ReverseShells: Array<SecurityTrend>
/**
* 本地提权统计数据数组。
*/
PrivilegeEscalations: Array<SecurityTrend>
/**
* 网络攻击统计数据数组。
*/
CyberAttacks: Array<SecurityTrend>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 资源管理系统安装包列表信息
*/
export interface AssetSystemPackageInfo {
/**
* 数据库名
*/
Name: string
/**
* 描述
*/
Desc: string
/**
* 版本
*/
Version: string
/**
* 安装时间
*/
InstallTime: string
/**
* 类型
*/
Type: string
/**
* 主机名称
*/
MachineName: string
/**
* 主机IP
*/
MachineIp: string
/**
* 操作系统
*/
OsInfo: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribeEmergencyVulList请求参数结构体
*/
export interface DescribeEmergencyVulListRequest {
/**
* 返回数量,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Status - String - 是否必填:是 - 漏洞状态筛选,0//未检测 1有风险 ,2无风险 ,3 检查中展示progress</li>
<li>Level - String - 是否必填:否 - 漏洞等级筛选 1:低 2:中 3:高 4:提示</li>
<li>VulName- String - 是否必填:否 - 漏洞名称搜索</li>
<li>Uuids- String - 是否必填:否 - 主机uuid</li>
*/
Filters?: Array<Filters>
/**
* 排序方式 desc , asc
*/
Order?: string
/**
* 排序字段 PublishDate
*/
By?: string
}
/**
* DescribeSecurityDynamics返回参数结构体
*/
export interface DescribeSecurityDynamicsResponse {
/**
* 安全事件消息数组。
*/
SecurityDynamics: Array<SecurityDynamic>
/**
* 记录总数。
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteReverseShellEvents返回参数结构体
*/
export interface DeleteReverseShellEventsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 资源管理Web服务列表信息
*/
export interface AssetWebServiceBaseInfo {
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* 操作系统信息
*/
OsInfo: string
/**
* 主机业务组ID
*/
ProjectId: number
/**
* 主机标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tag: Array<MachineTag>
/**
* 数据库名
*/
Name: string
/**
* 版本
*/
Version: string
/**
* 二进制路径
*/
BinPath: string
/**
* 启动用户
*/
User: string
/**
* 安装路径
*/
InstallPath: string
/**
* 配置路径
*/
ConfigPath: string
/**
* 关联进程数
*/
ProcessCount: number
/**
* Web服务ID
*/
Id: string
/**
* 主机名称
*/
MachineName: string
/**
* 描述
*/
Desc: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribeProVersionStatus返回参数结构体
*/
export interface DescribeProVersionStatusResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeScanTaskDetails返回参数结构体
*/
export interface DescribeScanTaskDetailsResponse {
/**
* 扫描任务信息列表
*/
ScanTaskDetailList: Array<ScanTaskDetails>
/**
* 总数
*/
TotalCount: number
/**
* 扫描机器总数
*/
ScanMachineCount: number
/**
* 发现风险机器数
*/
RiskMachineCount: number
/**
* 扫描开始时间
*/
ScanBeginTime: string
/**
* 扫描结束时间
*/
ScanEndTime: string
/**
* 检测时间
*/
ScanTime: number
/**
* 扫描进度
*/
ScanProgress: number
/**
* 扫描剩余时间
*/
ScanLeftTime: number
/**
* 扫描内容
*/
ScanContent: Array<string>
/**
* 漏洞信息
注意:此字段可能返回 null,表示取不到有效值。
*/
VulInfo: Array<VulDetailInfo>
/**
* 风险事件个数
注意:此字段可能返回 null,表示取不到有效值。
*/
RiskEventCount: number
/**
* 0一键检测 1定时检测
注意:此字段可能返回 null,表示取不到有效值。
*/
Type: number
/**
* 任务是否全部正在被停止 ture是
注意:此字段可能返回 null,表示取不到有效值。
*/
StoppingAll: boolean
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeGeneralStat请求参数结构体
*/
export interface DescribeGeneralStatRequest {
/**
* 云主机类型。
<li>CVM:表示腾讯云服务器</li>
<li>BM: 表示黑石物理机</li>
<li>ECM: 表示边缘计算服务器</li>
<li>LH: 表示轻量应用服务器</li>
<li>Other: 表示混合云机器</li>
*/
MachineType?: string
/**
* 机器所属地域。如:ap-guangzhou,ap-shanghai
*/
MachineRegion?: string
}
/**
* UpdateBaselineStrategy返回参数结构体
*/
export interface UpdateBaselineStrategyResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 资产管理启动服务列表
*/
export interface AssetInitServiceBaseInfo {
/**
* 名称
*/
Name: string
/**
* 类型:
1:编码器
2:IE插件
3:网络提供者
4:镜像劫持
5:LSA提供者
6:KnownDLLs
7:启动执行
8:WMI
9:计划任务
10:Winsock提供者
11:打印监控器
12:资源管理器
13:驱动服务
14:登录
*/
Type: number
/**
* 默认启用状态:0未启用,1启用
*/
Status: number
/**
* 启动用户
*/
User: string
/**
* 路径
*/
Path: string
/**
* 服务器IP
*/
MachineIp: string
/**
* 服务器名称
*/
MachineName: string
/**
* 操作系统
*/
OsInfo: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机uuid
*/
Uuid: string
/**
* 数据更新时间
*/
UpdateTime: string
}
/**
* DescribeVulHostTop请求参数结构体
*/
export interface DescribeVulHostTopRequest {
/**
* 获取top值,1-100
*/
Top: number
/**
* 1: web应用漏洞 2=系统组件漏洞3:安全基线 4: Linux系统漏洞 5: windows补丁 6:应急漏洞
*/
VulCategory?: number
}
/**
* DescribeIgnoreRuleEffectHostList请求参数结构体
*/
export interface DescribeIgnoreRuleEffectHostListRequest {
/**
* 分页参数 最大100条
*/
Limit: number
/**
* 分页参数
*/
Offset: number
/**
* 检测项id
*/
RuleId: number
/**
* 过滤条件。
<li>AliasName- String- 主机别名</li>
*/
Filters?: Array<Filters>
/**
* 主机标签名
*/
TagNames?: Array<string>
}
/**
* ModifyWarningSetting返回参数结构体
*/
export interface ModifyWarningSettingResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 异地登录合并后白名单
*/
export interface LoginWhiteCombinedInfo {
/**
* 白名单地域
注意:此字段可能返回 null,表示取不到有效值。
*/
Places: Array<Place>
/**
* 白名单用户(多个用户逗号隔开)
*/
UserName: string
/**
* 白名单IP(多个IP逗号隔开)
*/
SrcIp: string
/**
* 地域字符串
*/
Locale: string
/**
* 备注
*/
Remark: string
/**
* 开始时间
*/
StartTime: string
/**
* 结束时间
*/
EndTime: string
/**
* 是否对全局生效, 1:全局有效 0: 对指定主机列表生效'
*/
IsGlobal: number
/**
* 白名单名字:IsLocal=1时固定为:全部服务器;单台机器时为机器内网IP,多台服务器时为服务器数量,如:11台
*/
Name: string
/**
* 仅在单台服务器时,返回服务器名称
*/
Desc: string
/**
* 白名单ID
*/
Id: number
/**
* 创建时间
*/
CreateTime: string
/**
* 最近修改时间
*/
ModifyTime: string
/**
* 服务器Uuid
*/
Uuid: string
}
/**
* OpenProVersionPrepaid返回参数结构体
*/
export interface OpenProVersionPrepaidResponse {
/**
* 订单ID列表。
*/
DealIds: Array<string>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeMalwareInfo返回参数结构体
*/
export interface DescribeMalwareInfoResponse {
/**
* 恶意文件详情信息
*/
MalwareInfo: MalwareInfo
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetJarInfo请求参数结构体
*/
export interface DescribeAssetJarInfoRequest {
/**
* 服务器Quuid
*/
Quuid: string
/**
* 服务器Uuid
*/
Uuid: string
/**
* Jar包ID
*/
Id: string
}
/**
* DescribePrivilegeEvents请求参数结构体
*/
export interface DescribePrivilegeEventsRequest {
/**
* 返回数量,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 关键词(主机IP)</li>
*/
Filters?: Array<Filter>
}
/**
* 基线信息
*/
export interface BaselineInfo {
/**
* 基线名
注意:此字段可能返回 null,表示取不到有效值。
*/
Name: string
/**
* 危害等级:1-低危;2-中危;3-高危;4-严重
注意:此字段可能返回 null,表示取不到有效值。
*/
Level: number
/**
* 检测项数量
注意:此字段可能返回 null,表示取不到有效值。
*/
RuleCount: number
/**
* 影响服务器数量
注意:此字段可能返回 null,表示取不到有效值。
*/
HostCount: number
/**
* 通过状态:0:未通过,1:已通过
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: number
/**
* 基线id
注意:此字段可能返回 null,表示取不到有效值。
*/
CategoryId: number
/**
* 最后检测时间
注意:此字段可能返回 null,表示取不到有效值。
*/
LastScanTime: string
/**
* 检测中状态: 5
注意:此字段可能返回 null,表示取不到有效值。
*/
MaxStatus: number
/**
* 基线风险项
注意:此字段可能返回 null,表示取不到有效值。
*/
BaselineFailCount: number
}
/**
* DescribeVulHostCountScanTime请求参数结构体
*/
export type DescribeVulHostCountScanTimeRequest = null
/**
* ExportScanTaskDetails返回参数结构体
*/
export interface ExportScanTaskDetailsResponse {
/**
* 导出本次检测Excel的任务Id(不同于入参的本次检测任务id)
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportBashEvents返回参数结构体
*/
export interface ExportBashEventsResponse {
/**
* 导出文件下载链接地址。
*/
DownloadUrl: string
/**
* 导出任务ID
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteLoginWhiteList请求参数结构体
*/
export interface DeleteLoginWhiteListRequest {
/**
* 白名单ID (最大 100 条)
*/
Ids: Array<number>
}
/**
* DeleteWebPageEventLog返回参数结构体
*/
export interface DeleteWebPageEventLogResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeVulLevelCount返回参数结构体
*/
export interface DescribeVulLevelCountResponse {
/**
* 统计结果
注意:此字段可能返回 null,表示取不到有效值。
*/
VulLevelList: Array<VulLevelInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeVersionStatistics返回参数结构体
*/
export interface DescribeVersionStatisticsResponse {
/**
* 基础版数量
*/
BasicVersionNum: number
/**
* 专业版数量
*/
ProVersionNum: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBruteAttackRules请求参数结构体
*/
export type DescribeBruteAttackRulesRequest = null
/**
* DescribeProcessStatistics返回参数结构体
*/
export interface DescribeProcessStatisticsResponse {
/**
* 进程统计列表记录总数。
*/
TotalCount: number
/**
* 进程统计列表数据数组。
*/
ProcessStatistics: Array<ProcessStatistics>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyBruteAttackRules返回参数结构体
*/
export interface ModifyBruteAttackRulesResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteNonlocalLoginPlaces请求参数结构体
*/
export interface DeleteNonlocalLoginPlacesRequest {
/**
* 删除异地登录事件的方式,可选值:"Ids"、"Ip"、"All",默认为Ids
*/
DelType?: string
/**
* 异地登录事件ID数组。DelType为Ids或DelType未填时此项必填
*/
Ids?: Array<number>
/**
* 异地登录事件的Ip。DelType为Ip时必填
*/
Ip?: Array<string>
/**
* 主机Uuid
*/
Uuid?: string
}
/**
* DescribeAssetWebAppPluginList返回参数结构体
*/
export interface DescribeAssetWebAppPluginListResponse {
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Plugins: Array<AssetWebAppPluginInfo>
/**
* 分区总数
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeTags返回参数结构体
*/
export interface DescribeTagsResponse {
/**
* 列表信息
*/
List: Array<Tag>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 服务器风险Top的主机信息
*/
export interface BaselineEventLevelInfo {
/**
* 危害等级:1-低危;2-中危;3-高危;4-严重
注意:此字段可能返回 null,表示取不到有效值。
*/
EventLevel: number
/**
* 漏洞数量
注意:此字段可能返回 null,表示取不到有效值。
*/
EventCount: number
}
/**
* DescribeLoginWhiteCombinedList请求参数结构体
*/
export interface DescribeLoginWhiteCombinedListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>UserName - String - 是否必填:否 - 用户名筛选</li>
<li>ModifyBeginTime - String - 是否必填:否 - 按照修改时间段筛选,开始时间</li>
<li>ModifyEndTime - String - 是否必填:否 - 按照修改时间段筛选,结束时间</li>
*/
Filters?: Array<Filter>
}
/**
* 基线安全用户策略信息
*/
export interface Strategy {
/**
* 策略名
注意:此字段可能返回 null,表示取不到有效值。
*/
StrategyName: string
/**
* 策略id
注意:此字段可能返回 null,表示取不到有效值。
*/
StrategyId: number
/**
* 基线检测项总数
注意:此字段可能返回 null,表示取不到有效值。
*/
RuleCount: number
/**
* 主机数量
注意:此字段可能返回 null,表示取不到有效值。
*/
HostCount: number
/**
* 扫描周期
注意:此字段可能返回 null,表示取不到有效值。
*/
ScanCycle: number
/**
* 扫描时间
注意:此字段可能返回 null,表示取不到有效值。
*/
ScanAt: string
/**
* 是否可用
注意:此字段可能返回 null,表示取不到有效值。
*/
Enabled: number
/**
* 通过率
注意:此字段可能返回 null,表示取不到有效值。
*/
PassRate: number
/**
* 基线id
注意:此字段可能返回 null,表示取不到有效值。
*/
CategoryIds: string
/**
* 是否默认策略
注意:此字段可能返回 null,表示取不到有效值。
*/
IsDefault: number
}
/**
* DeleteSearchTemplate返回参数结构体
*/
export interface DeleteSearchTemplateResponse {
/**
* 0:成功,非0:失败
*/
Status: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBanRegions返回参数结构体
*/
export interface DescribeBanRegionsResponse {
/**
* 地域信息列表
*/
RegionSet: Array<RegionSet>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeEmergencyResponseList返回参数结构体
*/
export interface DescribeEmergencyResponseListResponse {
/**
* 总条数
*/
TotalCount: number
/**
* 应急响应列表
*/
List: Array<EmergencyResponseInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 防护机器信息
*/
export interface ProtectHostConfig {
/**
* 机器唯一ID
*/
Quuid: string
/**
* 防护开关 0 关闭 1开启
*/
ProtectSwitch: number
/**
* 自动恢复开关 0 关闭 1开启
*/
AutoRecovery: number
}
/**
* 资产管理计划任务列表
*/
export interface AssetPlanTask {
/**
* 默认启用状态:1启用,2未启用
*/
Status: number
/**
* 执行周期
*/
Cycle: string
/**
* 执行命令或脚本
*/
Command: string
/**
* 启动用户
*/
User: string
/**
* 配置文件路径
*/
ConfigPath: string
/**
* 服务器IP
*/
MachineIp: string
/**
* 服务器名称
*/
MachineName: string
/**
* 操作系统
*/
OsInfo: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机uuid
*/
Uuid: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* 账号变更历史数据。
*/
export interface HistoryAccount {
/**
* 唯一ID。
*/
Id: number
/**
* 云镜客户端唯一Uuid。
*/
Uuid: string
/**
* 主机内网IP。
*/
MachineIp: string
/**
* 主机名。
*/
MachineName: string
/**
* 帐号名。
*/
Username: string
/**
* 帐号变更类型。
<li>CREATE:表示新增帐号</li>
<li>MODIFY:表示修改帐号</li>
<li>DELETE:表示删除帐号</li>
*/
ModifyType: string
/**
* 变更时间。
*/
ModifyTime: string
}
/**
* DescribeAssetAppList返回参数结构体
*/
export interface DescribeAssetAppListResponse {
/**
* 应用列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Apps: Array<AssetAppBaseInfo>
/**
* 总数量
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyWebPageProtectSwitch请求参数结构体
*/
export interface ModifyWebPageProtectSwitchRequest {
/**
* 开关类型 1 防护开关 2 自动恢复开关 3 移除防护目录
*/
SwitchType: number
/**
* 需要操作开关的网站 最大100条
*/
Ids: Array<string>
/**
* 1 开启 0 关闭 SwitchType 为 1 | 2 必填;
*/
Status?: number
}
/**
* CreateScanMalwareSetting请求参数结构体
*/
export interface CreateScanMalwareSettingRequest {
/**
* 扫描模式 0 全盘扫描, 1 快速扫描
*/
ScanPattern: number
/**
* 服务器分类:1:专业版服务器;2:自选服务器
*/
HostType: number
/**
* 自选服务器时生效,主机quuid的string数组
*/
QuuidList?: Array<string>
/**
* 超时时间单位 秒 默认3600 秒
*/
TimeoutPeriod?: number
}
/**
* DescribeMalwareTimingScanSetting返回参数结构体
*/
export interface DescribeMalwareTimingScanSettingResponse {
/**
* 检测模式 0 全盘检测 1快速检测
*/
CheckPattern: number
/**
* 检测周期 开始时间
*/
StartTime: string
/**
* 检测周期 超时结束时间
*/
EndTime: string
/**
* 是否全部服务器 1 全部 2 自选
*/
IsGlobal: number
/**
* 自选服务器时必须 主机quuid的string数组
注意:此字段可能返回 null,表示取不到有效值。
*/
QuuidList: Array<string>
/**
* 监控模式 0 标准 1深度
*/
MonitoringPattern: number
/**
* 周期 1每天
*/
Cycle: number
/**
* 定时检测开关 0 关闭1 开启
*/
EnableScan: number
/**
* 唯一ID
*/
Id: number
/**
* 实时监控0 关闭 1开启
*/
RealTimeMonitoring: number
/**
* 是否自动隔离:1-是,0-否
*/
AutoIsolation: number
/**
* 一键扫描超时时长,如:1800秒(s)
*/
ClickTimeout: number
/**
* 是否杀掉进程 1杀掉 0不杀掉 只有开启自动隔离才生效
*/
KillProcess: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeHostLoginList请求参数结构体
*/
export interface DescribeHostLoginListRequest {
/**
* 需要返回的数量,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Uuid - String - 是否必填:否 - 云镜唯一Uuid</li>
<li>UserName - String - 是否必填:否 - 用户名筛选</li>
<li>LoginTimeBegin - String - 是否必填:否 - 按照修改时间段筛选,开始时间</li>
<li>LoginTimeEnd - String - 是否必填:否 - 按照修改时间段筛选,结束时间</li>
<li>SrcIp - String - 是否必填:否 - 来源ip筛选</li>
<li>Status - int - 是否必填:否 - 状态筛选1:正常登录;5:已加白</li>
<li>RiskLevel - int - 是否必填:否 - 状态筛选0:高危;1:可疑</li>
*/
Filters?: Array<Filter>
}
/**
* 安全趋势统计数据。
*/
export interface SecurityTrend {
/**
* 事件时间。
*/
Date: string
/**
* 事件数量。
*/
EventNum: number
}
/**
* DescribeAssetWebServiceProcessList请求参数结构体
*/
export interface DescribeAssetWebServiceProcessListRequest {
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* Web服务ID
*/
Id: string
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
}
/**
* 本地提权规则
*/
export interface PrivilegeRule {
/**
* 规则ID
*/
Id: number
/**
* 客户端ID
*/
Uuid: string
/**
* 进程名
*/
ProcessName: string
/**
* 是否S权限
*/
SMode: number
/**
* 操作人
*/
Operator: string
/**
* 是否全局规则
*/
IsGlobal: number
/**
* 状态(0: 有效 1: 无效)
*/
Status: number
/**
* 创建时间
*/
CreateTime: string
/**
* 修改时间
*/
ModifyTime: string
/**
* 主机IP
*/
Hostip: string
}
/**
* ExportVulDetectionExcel请求参数结构体
*/
export interface ExportVulDetectionExcelRequest {
/**
* 本次漏洞检测任务id(不同于出参的导出本次漏洞检测Excel的任务Id)
*/
TaskId: number
}
/**
* CreateEmergencyVulScan请求参数结构体
*/
export interface CreateEmergencyVulScanRequest {
/**
* 漏洞id
*/
VulId: number
/**
* 自选服务器时生效,主机uuid的string数组
*/
Uuids?: Array<string>
}
/**
* DescribeProtectDirRelatedServer返回参数结构体
*/
export interface DescribeProtectDirRelatedServerResponse {
/**
* 网站关联服务器列表信息
*/
List: Array<ProtectDirRelatedServer>
/**
* 总数
*/
TotalCount: number
/**
* 已开启防护总数
*/
ProtectServerCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyAutoOpenProVersionConfig返回参数结构体
*/
export interface ModifyAutoOpenProVersionConfigResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportBaselineEffectHostList请求参数结构体
*/
export interface ExportBaselineEffectHostListRequest {
/**
* 基线id
*/
BaselineId: number
/**
* 筛选条件
<li>AliasName- String- 主机别名</li>
*/
Filters?: Array<Filters>
/**
* 策略id
*/
StrategyId?: number
/**
* 主机uuid数组
*/
UuidList?: Array<string>
/**
* 基线名称
*/
BaselineName?: string
}
/**
* 资产管理内核模块详情
*/
export interface AssetCoreModuleDetail {
/**
* 名称
*/
Name: string
/**
* 描述
*/
Desc: string
/**
* 路径
*/
Path: string
/**
* 版本
*/
Version: string
/**
* 大小
*/
Size: number
/**
* 依赖进程
*/
Processes: string
/**
* 被依赖模块
*/
Modules: string
/**
* 参数信息
注意:此字段可能返回 null,表示取不到有效值。
*/
Params: Array<AssetCoreModuleParam>
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribeBanStatus请求参数结构体
*/
export type DescribeBanStatusRequest = null
/**
* DescribeAssetRecentMachineInfo返回参数结构体
*/
export interface DescribeAssetRecentMachineInfoResponse {
/**
* 总数量列表
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalList: Array<AssetKeyVal>
/**
* 在线数量列表
注意:此字段可能返回 null,表示取不到有效值。
*/
LiveList: Array<AssetKeyVal>
/**
* 离线数量列表
注意:此字段可能返回 null,表示取不到有效值。
*/
OfflineList: Array<AssetKeyVal>
/**
* 风险数量列表
注意:此字段可能返回 null,表示取不到有效值。
*/
RiskList: Array<AssetKeyVal>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeMalWareList返回参数结构体
*/
export interface DescribeMalWareListResponse {
/**
* 木马列表
注意:此字段可能返回 null,表示取不到有效值。
*/
MalWareList: Array<MalWareList>
/**
* 总数量
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetPortInfoList返回参数结构体
*/
export interface DescribeAssetPortInfoListResponse {
/**
* 记录总数
*/
Total: number
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Ports: Array<AssetPortBaseInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeProtectDirList返回参数结构体
*/
export interface DescribeProtectDirListResponse {
/**
* 总数
*/
TotalCount: number
/**
* 防护目录列表信息
*/
List: Array<ProtectDirInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeMaliciousRequestWhiteList返回参数结构体
*/
export interface DescribeMaliciousRequestWhiteListResponse {
/**
* 白名单信息列表
注意:此字段可能返回 null,表示取不到有效值。
*/
List: Array<MaliciousRequestWhiteListInfo>
/**
* 分页查询记录总数
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteBruteAttacks返回参数结构体
*/
export interface DeleteBruteAttacksResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportTasks返回参数结构体
*/
export interface ExportTasksResponse {
/**
* PENDING:正在生成下载链接,FINISHED:下载链接已生成,ERROR:网络异常等异常情况
*/
Status: string
/**
* 下载链接
*/
DownloadUrl: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeIgnoreBaselineRule返回参数结构体
*/
export interface DescribeIgnoreBaselineRuleResponse {
/**
* 忽略基线检测项列表信息
注意:此字段可能返回 null,表示取不到有效值。
*/
IgnoreBaselineRuleList: Array<IgnoreBaselineRule>
/**
* 分页查询记录总数
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeMachineOsList请求参数结构体
*/
export type DescribeMachineOsListRequest = null
/**
* DescribeMalwareRiskWarning返回参数结构体
*/
export interface DescribeMalwareRiskWarningResponse {
/**
* 是否开启自动扫描:true-开启,false-未开启
*/
IsCheckRisk: boolean
/**
* 风险文件列表信息
注意:此字段可能返回 null,表示取不到有效值。
*/
List: Array<MalwareRisk>
/**
* 是否弹出提示 true 弹出, false不弹
*/
IsPop: boolean
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBashRules请求参数结构体
*/
export interface DescribeBashRulesRequest {
/**
* 0-系统规则; 1-用户规则
*/
Type: number
/**
* 返回数量,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 关键字(规则名称)</li>
*/
Filters?: Array<Filter>
}
/**
* 基线基础信息
*/
export interface BaselineBasicInfo {
/**
* 基线名称
注意:此字段可能返回 null,表示取不到有效值。
*/
Name: string
/**
* 基线id
注意:此字段可能返回 null,表示取不到有效值。
*/
BaselineId: number
/**
* 父级id
注意:此字段可能返回 null,表示取不到有效值。
*/
ParentId: number
}
/**
* DescribeBanMode返回参数结构体
*/
export interface DescribeBanModeResponse {
/**
* 阻断模式,STANDARD_MODE:标准阻断,DEEP_MODE:深度阻断
*/
Mode: string
/**
* 标准阻断模式的配置
*/
StandardModeConfig: StandardModeConfig
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeImportMachineInfo返回参数结构体
*/
export interface DescribeImportMachineInfoResponse {
/**
* 有效的机器信息列表:机器名称、机器公网/内网ip、机器标签
注意:此字段可能返回 null,表示取不到有效值。
*/
EffectiveMachineInfoList: Array<EffectiveMachineInfo>
/**
* 用户批量导入失败的机器列表(比如机器不存在等...)
注意:此字段可能返回 null,表示取不到有效值。
*/
InvalidMachineList: Array<string>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetDatabaseList请求参数结构体
*/
export interface DescribeAssetDatabaseListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>User- string - 是否必填:否 - 运行用户</li>
<li>Ip - String - 是否必填:否 - 绑定IP</li>
<li>Port - Int - 是否必填:否 - 端口</li>
<li>Name - Int - 是否必填:否 - 数据库名称
0:全部
1:MySQL
2:Redis
3:Oracle
4:MongoDB
5:MemCache
6:PostgreSQL
7:HBase
8:DB2
9:Sybase
10:TiDB</li>
<li>Proto - String - 是否必填:否 - 协议:1:TCP, 2:UDP, 3:未知</li>
<li>OsType - String - 是否必填:否 - 操作系统: linux/windows</li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )</li>
*/
Filters?: Array<AssetFilters>
/**
* 查询指定Quuid主机的信息
*/
Quuid?: string
}
/**
* ModifyWebPageProtectSwitch返回参数结构体
*/
export interface ModifyWebPageProtectSwitchResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetMachineList请求参数结构体
*/
export interface DescribeAssetMachineListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>OsType - String - 是否必填:否 - windows或linux</li>
<li>CpuLoad - Int - 是否必填:否 -
0: 未知 1: 低负载
2: 中负载 3: 高负载</li>
<li>DiskLoad - Int - 是否必填:否 -
0: 0%或未知 1: 0%~20%
2: 20%~50% 3: 50%~80%
4: 80%~100%</li>
<li>MemLoad - Int - 是否必填:否 -
0: 0%或未知 1: 0%~20%
2: 20%~50% 3: 50%~80%
4: 80%~100%</li>
<li>Quuid:主机Quuid</li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )</li>
*/
Filters?: Array<Filter>
/**
* 可选排序:PartitionCount
*/
By?: string
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
}
/**
* CreateSearchTemplate返回参数结构体
*/
export interface CreateSearchTemplateResponse {
/**
* 0:成功,非0:失败
*/
Status: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetDatabaseList返回参数结构体
*/
export interface DescribeAssetDatabaseListResponse {
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Databases: Array<AssetDatabaseBaseInfo>
/**
* 总数量
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportMalwares请求参数结构体
*/
export interface ExportMalwaresRequest {
/**
* 限制条数,默认10
*/
Limit?: number
/**
* 偏移量 默认0
*/
Offset?: number
/**
* 过滤参数。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>FilePath - String - 是否必填:否 - 路径筛选</li>
<li>VirusName - String - 是否必填:否 - 描述筛选</li>
<li>CreateBeginTime - String - 是否必填:否 - 创建时间筛选-开始时间</li>
<li>CreateEndTime - String - 是否必填:否 - 创建时间筛选-结束时间</li>
<li>Status - String - 是否必填:否 - 状态筛选</li>
*/
Filters?: Array<Filters>
/**
* 排序值 CreateTime
*/
By?: string
/**
* 排序 方式 ,ASC,DESC
*/
Order?: string
}
/**
* ExportNonlocalLoginPlaces请求参数结构体
*/
export interface ExportNonlocalLoginPlacesRequest {
/**
* <li>Status - int - 是否必填:否 - 状态筛选1:正常登录;2:异地登录</li>
*/
Filters?: Array<Filter>
}
/**
* SyncAssetScan返回参数结构体
*/
export interface SyncAssetScanResponse {
/**
* 枚举值有(大写):NOTASK(没有同步任务),SYNCING(同步中),FINISHED(同步完成)
*/
State: string
/**
* 最新开始同步时间
*/
LatestStartTime: string
/**
* 最新结束同步时间
*/
LatestEndTime: string
/**
* 任务ID
注意:此字段可能返回 null,表示取不到有效值。
*/
TaskId: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 资产管理内核模块列表
*/
export interface AssetCoreModuleBaseInfo {
/**
* 名称
*/
Name: string
/**
* 描述
*/
Desc: string
/**
* 路径
*/
Path: string
/**
* 版本
*/
Version: string
/**
* 服务器IP
*/
MachineIp: string
/**
* 服务器名称
*/
MachineName: string
/**
* 操作系统
*/
OsInfo: string
/**
* 模块大小
*/
Size: number
/**
* 依赖进程数
*/
ProcessCount: number
/**
* 依赖模块数
*/
ModuleCount: number
/**
* 模块ID
*/
Id: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机uuid
*/
Uuid: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* CreateBaselineStrategy请求参数结构体
*/
export interface CreateBaselineStrategyRequest {
/**
* 策略名称
*/
StrategyName: string
/**
* 检测周期, 表示每隔多少天进行检测.示例: 2, 表示每2天进行检测一次.
*/
ScanCycle: number
/**
* 定期检测时间,该时间下发扫描. 示例:“22:00”, 表示在22:00下发检测
*/
ScanAt: string
/**
* 该策略下选择的基线id数组. 示例: [1,3,5,7]
*/
CategoryIds: Array<number>
/**
* 扫描范围是否全部服务器, 1:是 0:否, 为1则为全部专业版主机
*/
IsGlobal: number
/**
* 云主机类型:
CVM:虚拟主机
BM:裸金属
ECM:边缘计算主机
LH:轻量应用服务器
Other:混合云机器
*/
MachineType: string
/**
* 主机地域. 示例: "ap-guangzhou"
*/
RegionCode: string
/**
* 主机id数组. 示例: ["quuid1","quuid2"]
*/
Quuids?: Array<string>
}
/**
* DescribeSecurityTrends请求参数结构体
*/
export interface DescribeSecurityTrendsRequest {
/**
* 开始时间,如:2021-07-10
*/
BeginDate: string
/**
* 结束时间,如:2021-07-10
*/
EndDate: string
}
/**
* DescribeAttackVulTypeList返回参数结构体
*/
export interface DescribeAttackVulTypeListResponse {
/**
* 威胁类型列表
*/
List: Array<string>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribePrivilegeRules返回参数结构体
*/
export interface DescribePrivilegeRulesResponse {
/**
* 列表内容
*/
List: Array<PrivilegeRule>
/**
* 总条数
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeReverseShellEvents返回参数结构体
*/
export interface DescribeReverseShellEventsResponse {
/**
* 列表内容
*/
List: Array<ReverseShell>
/**
* 总条数
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 密码破解列表实体
*/
export interface BruteAttackInfo {
/**
* 唯一Id
*/
Id: number
/**
* 云镜客户端唯一标识UUID
注意:此字段可能返回 null,表示取不到有效值。
*/
Uuid: string
/**
* 主机ip
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineIp: string
/**
* 主机名
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineName: string
/**
* 用户名
注意:此字段可能返回 null,表示取不到有效值。
*/
UserName: string
/**
* 来源ip
注意:此字段可能返回 null,表示取不到有效值。
*/
SrcIp: string
/**
* SUCCESS:破解成功;FAILED:破解失败
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: string
/**
* 国家id
注意:此字段可能返回 null,表示取不到有效值。
*/
Country: number
/**
* 城市id
注意:此字段可能返回 null,表示取不到有效值。
*/
City: number
/**
* 省份id
注意:此字段可能返回 null,表示取不到有效值。
*/
Province: number
/**
* 创建时间
注意:此字段可能返回 null,表示取不到有效值。
*/
CreateTime: string
/**
* 阻断状态:1-阻断成功;非1-阻断失败
注意:此字段可能返回 null,表示取不到有效值。
*/
BanStatus: number
/**
* 事件类型:200-暴力破解事件,300-暴力破解成功事件(页面展示),400-暴力破解不存在的帐号事件
注意:此字段可能返回 null,表示取不到有效值。
*/
EventType: number
/**
* 发生次数
注意:此字段可能返回 null,表示取不到有效值。
*/
Count: number
/**
* 机器UUID
注意:此字段可能返回 null,表示取不到有效值。
*/
Quuid: string
/**
* 是否为专业版(true/false)
注意:此字段可能返回 null,表示取不到有效值。
*/
IsProVersion: boolean
/**
* 被攻击的服务的用户名
注意:此字段可能返回 null,表示取不到有效值。
*/
Protocol: string
/**
* 端口
注意:此字段可能返回 null,表示取不到有效值。
*/
Port: number
/**
* 最近攻击时间
注意:此字段可能返回 null,表示取不到有效值。
*/
ModifyTime: string
/**
* 实例ID
注意:此字段可能返回 null,表示取不到有效值。
*/
InstanceId: string
}
/**
* DescribeWebPageProtectStat返回参数结构体
*/
export interface DescribeWebPageProtectStatResponse {
/**
* 文件篡改信息
*/
FileTamperNum: Array<ProtectStat>
/**
* 防护文件分类信息
*/
ProtectFileType: Array<ProtectStat>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetPortInfoList请求参数结构体
*/
export interface DescribeAssetPortInfoListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Port - uint64 - 是否必填:否 - 端口</li>
<li>Ip - String - 是否必填:否 - 绑定IP</li>
<li>ProcessName - String - 是否必填:否 - 监听进程</li>
<li>Pid - uint64 - 是否必填:否 - PID</li>
<li>User - String - 是否必填:否 - 运行用户</li>
<li>Group - String - 是否必填:否 - 所属用户组</li>
<li>Ppid - uint64 - 是否必填:否 - PPID</li>
<li>Proto - string - 是否必填:否 - tcp/udp或“”(空字符串筛选未知状态)</li>
<li>OsType - uint64 - 是否必填:否 - windows/linux</li>
<li>RunTimeStart - String - 是否必填:否 - 运行开始时间</li>
<li>RunTimeEnd - String - 是否必填:否 - 运行结束时间</li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )</li>
*/
Filters?: Array<Filter>
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 排序方式:StartTime
*/
By?: string
/**
* 查询指定Quuid主机的信息
*/
Quuid?: string
}
/**
* 漏洞等级数量实体
*/
export interface VulLevelCountInfo {
/**
* 漏洞等级
*/
VulLevel: number
/**
* 漏洞数量
*/
VulCount: number
}
/**
* DescribeExportMachines请求参数结构体
*/
export interface DescribeExportMachinesRequest {
/**
* 云主机类型。
<li>CVM:表示虚拟主机</li>
<li>BM: 表示黑石物理机</li>
*/
MachineType: string
/**
* 机器所属地域。如:ap-guangzhou,ap-shanghai
*/
MachineRegion: string
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Keywords - String - 是否必填:否 - 查询关键字 </li>
<li>Status - String - 是否必填:否 - 客户端在线状态(OFFLINE: 离线 | ONLINE: 在线 | UNINSTALLED:未安装)</li>
<li>Version - String 是否必填:否 - 当前防护版本( PRO_VERSION:专业版 | BASIC_VERSION:基础版)</li>
每个过滤条件只支持一个值,暂不支持多个值“或”关系查询
*/
Filters?: Array<Filter>
/**
* 机器所属业务ID列表
*/
ProjectIds?: Array<number>
}
/**
* CreateScanMalwareSetting返回参数结构体
*/
export interface CreateScanMalwareSettingResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* RenewProVersion请求参数结构体
*/
export interface RenewProVersionRequest {
/**
* 购买相关参数。
*/
ChargePrepaid: ChargePrepaid
/**
* 主机唯一ID,对应CVM的uuid、BM的InstanceId。
*/
Quuid: string
}
/**
* 恶意请求列表
*/
export interface RiskDnsList {
/**
* 对外访问域名
*/
Url: string
/**
* 访问次数
*/
AccessCount: number
/**
* 进程名
*/
ProcessName: string
/**
* 进程MD5
*/
ProcessMd5: string
/**
* 是否为全局规则,0否,1是
*/
GlobalRuleId: number
/**
* 用户规则id
*/
UserRuleId: number
/**
* 状态;0-待处理,2-已加白,3-非信任状态
*/
Status: number
/**
* 首次访问时间
*/
CreateTime: string
/**
* 最近访问时间
*/
MergeTime: string
/**
* 唯一 Quuid
*/
Quuid: string
/**
* 主机ip
*/
HostIp: string
/**
* 别名
*/
Alias: string
/**
* 描述
*/
Description: string
/**
* 唯一ID
*/
Id: number
/**
* 参考
*/
Reference: string
/**
* 命令行
*/
CmdLine: string
/**
* 进程号
*/
Pid: number
/**
* 唯一UUID
*/
Uuid: string
/**
* 建议方案
*/
SuggestScheme: string
/**
* 标签特性
*/
Tags: Array<string>
/**
* 外网ip
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineWanIp: string
/**
* 主机在线状态 OFFLINE ONLINE
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineStatus: string
}
/**
* DeleteMalwareScanTask请求参数结构体
*/
export type DeleteMalwareScanTaskRequest = null
/**
* DescribeIgnoreRuleEffectHostList返回参数结构体
*/
export interface DescribeIgnoreRuleEffectHostListResponse {
/**
* 忽略检测项影响主机列表
注意:此字段可能返回 null,表示取不到有效值。
*/
IgnoreRuleEffectHostList: Array<IgnoreRuleEffectHostInfo>
/**
* 分页查询记录总数
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportProtectDirList请求参数结构体
*/
export interface ExportProtectDirListRequest {
/**
* DirName 网站名称
DirPath 网站防护目录地址
*/
Filters?: Array<AssetFilters>
/**
* asc:升序/desc:降序
*/
Order?: string
/**
* 排序字段
*/
By?: string
}
/**
* CreateBaselineStrategy返回参数结构体
*/
export interface CreateBaselineStrategyResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportAssetCoreModuleList返回参数结构体
*/
export interface ExportAssetCoreModuleListResponse {
/**
* 异步下载任务ID,需要配合ExportTasks接口使用
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeHistoryAccounts返回参数结构体
*/
export interface DescribeHistoryAccountsResponse {
/**
* 帐号变更历史列表记录总数。
*/
TotalCount: number
/**
* 帐号变更历史数据数组。
*/
HistoryAccounts: Array<HistoryAccount>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeLoginWhiteList请求参数结构体
*/
export interface DescribeLoginWhiteListRequest {
/**
* 返回数量,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 查询关键字 </li>
<li>UserName - String - 是否必填:否 - 用户名筛选 </li>
<li>ModifyBeginTime - String - 是否必填:否 - 按照修改时间段筛选,开始时间 </li>
<li>ModifyEndTime - String - 是否必填:否 - 按照修改时间段筛选,结束时间 </li>
*/
Filters?: Array<Filter>
}
/**
* 端口统计列表
*/
export interface OpenPortStatistics {
/**
* 端口号
*/
Port: number
/**
* 主机数量
*/
MachineNum: number
}
/**
* ExportVulDetectionReport返回参数结构体
*/
export interface ExportVulDetectionReportResponse {
/**
* 导出文件下载链接地址
*/
DownloadUrl: string
/**
* 导出检测报告的任务Id(不同于入参的漏洞扫描任务id)
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeScanSchedule请求参数结构体
*/
export interface DescribeScanScheduleRequest {
/**
* 任务id
*/
TaskId: number
}
/**
* EditBashRules请求参数结构体
*/
export interface EditBashRulesRequest {
/**
* 规则ID(新增时不填)
*/
Id?: number
/**
* 客户端ID数组
*/
Uuids?: Array<string>
/**
* 主机IP
*/
HostIp?: string
/**
* 规则名称,编辑时不可修改规则名称
*/
Name?: string
/**
* 危险等级(0:无,1: 高危 2:中危 3: 低危)
*/
Level?: number
/**
* 正则表达式 ,编辑时不可修改正则表达式,需要对内容QueryEscape后再base64
*/
Rule?: string
/**
* 是否全局规则(默认否):1-全局,0-非全局
*/
IsGlobal?: number
/**
* 0=黑名单, 1=白名单
*/
White?: number
/**
* 事件列表点击“加入白名单”时,需要传EventId 事件的id
*/
EventId?: number
/**
* 是否处理旧事件为白名单 0=不处理 1=处理
*/
DealOldEvents?: number
}
/**
* DescribeBruteAttackList返回参数结构体
*/
export interface DescribeBruteAttackListResponse {
/**
* 总数
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalCount: number
/**
* 密码破解列表
注意:此字段可能返回 null,表示取不到有效值。
*/
BruteAttackList: Array<BruteAttackInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ScanVulSetting请求参数结构体
*/
export interface ScanVulSettingRequest {
/**
* 定期检测间隔时间(天)
*/
TimerInterval: number
/**
* 漏洞类型:1: web应用漏洞 2:系统组件漏洞, 以数组方式传参[1,2]
*/
VulCategories?: Array<number>
/**
* 危害等级:1-低危;2-中危;3-高危;4-严重,以数组方式传参[1,2,3]
*/
VulLevels?: Array<number>
/**
* 定期检测时间,如:02:10:50
*/
TimerTime?: string
/**
* 是否是应急漏洞 0 否 1 是
*/
VulEmergency?: number
/**
* 扫描开始时间,如:00:00
*/
StartTime?: string
/**
* 扫描结束时间,如:08:00
*/
EndTime?: string
/**
* 是否开启扫描 1开启 0不开启
*/
EnableScan?: number
}
/**
* ExportScanTaskDetails请求参数结构体
*/
export interface ExportScanTaskDetailsRequest {
/**
* 本次检测的任务id(不同于出参的导出本次检测Excel的任务Id)
*/
TaskId: number
/**
* 模块类型,当前提供:Malware 木马 , Vul 漏洞 , Baseline 基线
*/
ModuleType: string
/**
* 过滤参数:ipOrAlias(服务器名/ip)
*/
Filters?: Array<Filters>
}
/**
* ExportBaselineList返回参数结构体
*/
export interface ExportBaselineListResponse {
/**
* 导出文件下载地址(已弃用)
注意:此字段可能返回 null,表示取不到有效值。
*/
DownloadUrl: string
/**
* 导出文件Id 可通过ExportTasks接口下载
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBruteAttackRules返回参数结构体
*/
export interface DescribeBruteAttackRulesResponse {
/**
* 爆破阻断规则列表
*/
Rules: Array<BruteAttackRuleList>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyBanMode返回参数结构体
*/
export interface ModifyBanModeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 基线检测项TOP信息
*/
export interface BaselineRuleTopInfo {
/**
* 基线检测项名
注意:此字段可能返回 null,表示取不到有效值。
*/
RuleName: string
/**
* 检测项危害等级
注意:此字段可能返回 null,表示取不到有效值。
*/
Level: number
/**
* 事件总数
注意:此字段可能返回 null,表示取不到有效值。
*/
EventCount: number
/**
* 检测项id
注意:此字段可能返回 null,表示取不到有效值。
*/
RuleId: number
}
/**
* 资源管理进程基本信息
*/
export interface AssetProcessBaseInfo {
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* 操作系统信息
*/
OsInfo: string
/**
* 主机业务组ID
*/
ProjectId: number
/**
* 主机标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tag: Array<MachineTag>
/**
* 进程名称
*/
Name: string
/**
* 进程说明
*/
Desc: string
/**
* 进程路径
*/
Path: string
/**
* 进程ID
*/
Pid: string
/**
* 运行用户
*/
User: string
/**
* 启动时间
*/
StartTime: string
/**
* 启动参数
*/
Param: string
/**
* 进程TTY
*/
Tty: string
/**
* 进程版本
*/
Version: string
/**
* 进程用户组
*/
GroupName: string
/**
* 进程MD5
*/
Md5: string
/**
* 父进程ID
*/
Ppid: string
/**
* 父进程名称
*/
ParentProcessName: string
/**
* 进程状态
*/
Status: string
/**
* 数字签名:0无,1有, 999 空,仅windows
*/
HasSign: number
/**
* 是否通过安装包安装::0否,1是, 999 空,仅linux
*/
InstallByPackage: number
/**
* 软件包名
*/
PackageName: string
/**
* 主机名称
*/
MachineName: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DeleteBruteAttacks请求参数结构体
*/
export interface DeleteBruteAttacksRequest {
/**
* 暴力破解事件Id数组。(最大 100条)
*/
Ids: Array<number>
}
/**
* DescribeAssetCoreModuleList返回参数结构体
*/
export interface DescribeAssetCoreModuleListResponse {
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Modules: Array<AssetCoreModuleBaseInfo>
/**
* 总数量
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeLoginWhiteCombinedList返回参数结构体
*/
export interface DescribeLoginWhiteCombinedListResponse {
/**
* 总数量
*/
TotalCount: number
/**
* 合并后的白名单列表
注意:此字段可能返回 null,表示取不到有效值。
*/
LoginWhiteCombinedInfos: Array<LoginWhiteCombinedInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ExportVulDetectionExcel返回参数结构体
*/
export interface ExportVulDetectionExcelResponse {
/**
* 导出文件下载链接地址
*/
DownloadUrl: string
/**
* 导出本次漏洞检测Excel的任务Id(不同于入参的本次漏洞检测任务id)
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeWarningList返回参数结构体
*/
export interface DescribeWarningListResponse {
/**
* 获取告警列表
*/
WarningInfoList: Array<WarningInfoObj>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateSearchTemplate请求参数结构体
*/
export interface CreateSearchTemplateRequest {
/**
* 搜索模板
*/
SearchTemplate: SearchTemplate
}
/**
* DeleteTags请求参数结构体
*/
export interface DeleteTagsRequest {
/**
* 标签ID (最大100 条)
*/
Ids: Array<number>
}
/**
* DescribeScanState请求参数结构体
*/
export interface DescribeScanStateRequest {
/**
* 模块类型 当前提供 Malware 木马 , Vul 漏洞 , Baseline 基线
*/
ModuleType: string
/**
* 过滤参数;
<li>StrategyId 基线策略ID ,仅ModuleType 为 Baseline 时需要<li/>
*/
Filters?: Array<Filters>
}
/**
* ModifyMalwareTimingScanSettings请求参数结构体
*/
export interface ModifyMalwareTimingScanSettingsRequest {
/**
* 检测模式 0 全盘检测 1快速检测
*/
CheckPattern: number
/**
* 检测周期 开始时间,如:02:00:00
*/
StartTime: string
/**
* 检测周期 超时结束时间,如:04:00:00
*/
EndTime: string
/**
* 是否全部服务器 1 全部 2 自选
*/
IsGlobal: number
/**
* 定时检测开关 0 关闭 1开启
*/
EnableScan: number
/**
* 监控模式 0 标准 1深度
*/
MonitoringPattern: number
/**
* 扫描周期 默认每天 1
*/
Cycle: number
/**
* 实时监控 0 关闭 1开启
*/
RealTimeMonitoring: number
/**
* 自选服务器时必须 主机quuid的string数组
*/
QuuidList?: Array<string>
/**
* 是否自动隔离 1隔离 0 不隔离
*/
AutoIsolation?: number
/**
* 是否杀掉进程 1杀掉 0不杀掉
*/
KillProcess?: number
}
/**
* 资产管理环境变量列表
*/
export interface AssetEnvBaseInfo {
/**
* 名称
*/
Name: string
/**
* 类型:
0:用户变量
1:系统变量
*/
Type: number
/**
* 启动用户
*/
User: string
/**
* 环境变量值
*/
Value: string
/**
* 服务器IP
*/
MachineIp: string
/**
* 服务器名称
*/
MachineName: string
/**
* 操作系统
*/
OsInfo: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机uuid
*/
Uuid: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribeMachineList返回参数结构体
*/
export interface DescribeMachineListResponse {
/**
* 主机列表
*/
Machines: Array<Machine>
/**
* 主机数量
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 恶意文件详情
*/
export interface MalwareInfo {
/**
* 病毒名称
*/
VirusName: string
/**
* 文件大小
*/
FileSize: number
/**
* 文件MD5
*/
MD5: string
/**
* 文件地址
*/
FilePath: string
/**
* 首次运行时间
*/
FileCreateTime: string
/**
* 最近一次运行时间
*/
FileModifierTime: string
/**
* 危害描述
*/
HarmDescribe: string
/**
* 建议方案
*/
SuggestScheme: string
/**
* 服务器名称
*/
ServersName: string
/**
* 服务器IP
*/
HostIp: string
/**
* 进程名称
*/
ProcessName: string
/**
* 进程ID
*/
ProcessID: string
/**
* 标签特性
*/
Tags: Array<string>
/**
* 影响广度 // 暂时不提供
注意:此字段可能返回 null,表示取不到有效值。
*/
Breadth: string
/**
* 查询热度 // 暂时不提供
注意:此字段可能返回 null,表示取不到有效值。
*/
Heat: string
/**
* 唯一ID
*/
Id: number
/**
* 文件名称
*/
FileName: string
/**
* 首次发现时间
*/
CreateTime: string
/**
* 最近扫描时间
*/
LatestScanTime: string
/**
* 参考链接
*/
Reference: string
/**
* 外网ip
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineWanIp: string
/**
* 进程树 json pid:进程id,exe:文件路径 ,account:进程所属用组和用户 ,cmdline:执行命令,ssh_service: SSH服务ip, ssh_soure:登录源
注意:此字段可能返回 null,表示取不到有效值。
*/
PsTree: string
/**
* 主机在线状态 OFFLINE ONLINE
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineStatus: string
/**
* 状态;4-:待处理,5-已信任,6-已隔离
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: number
}
/**
* 登录地信息
*/
export interface Place {
/**
* 城市 ID。
*/
CityId: number
/**
* 省份 ID。
*/
ProvinceId: number
/**
* 国家ID,暂只支持国内:1。
*/
CountryId: number
/**
* 位置名称
*/
Location?: string
}
/**
* DescribeExpertServiceOrderList返回参数结构体
*/
export interface DescribeExpertServiceOrderListResponse {
/**
* 总条数
*/
TotalCount: number
/**
* 订单列表
*/
List: Array<ExpertServiceOrderInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteReverseShellRules返回参数结构体
*/
export interface DeleteReverseShellRulesResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetPlanTaskList请求参数结构体
*/
export interface DescribeAssetPlanTaskListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>User- string - 是否必填:否 - 用户</li>
<li>Status- int - 是否必填:否 - 默认启用状态:0未启用, 1启用 </li>
*/
Filters?: Array<AssetFilters>
/**
* 服务器Uuid
*/
Uuid?: string
/**
* 服务器Quuid
*/
Quuid?: string
}
/**
* DescribeScanTaskDetails请求参数结构体
*/
export interface DescribeScanTaskDetailsRequest {
/**
* 模块类型 当前提供 Malware 木马 , Vul 漏洞 , Baseline 基线
*/
ModuleType: string
/**
* 任务ID
*/
TaskId: number
/**
* 过滤参数
*/
Filters?: Array<Filters>
/**
* 需要返回的数量,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
}
/**
* DescribeProtectDirRelatedServer请求参数结构体
*/
export interface DescribeProtectDirRelatedServerRequest {
/**
* 唯一ID
*/
Id: string
/**
* 分页条数 最大100条
*/
Limit: number
/**
* 偏移量
*/
Offset: number
/**
* 过滤参数 ProtectStatus
*/
Filters?: Array<Filter>
/**
* 排序方式
*/
Order?: string
/**
* 排序值
*/
By?: string
}
/**
* InquiryPriceOpenProVersionPrepaid返回参数结构体
*/
export interface InquiryPriceOpenProVersionPrepaidResponse {
/**
* 预支费用的原价,单位:元。
*/
OriginalPrice: number
/**
* 预支费用的折扣价,单位:元。
*/
DiscountPrice: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeSearchLogs返回参数结构体
*/
export interface DescribeSearchLogsResponse {
/**
* 历史搜索记录 保留最新的10条
*/
Data: Array<string>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 安全事件统计列表
*/
export interface SecurityEventInfo {
/**
* 安全事件数
*/
EventCnt: number
/**
* 受影响机器数
*/
UuidCnt: number
}
/**
* DescribeBaselineAnalysisData返回参数结构体
*/
export interface DescribeBaselineAnalysisDataResponse {
/**
* 最后检测时间
注意:此字段可能返回 null,表示取不到有效值。
*/
LatestScanTime: string
/**
* 是否全部服务器
注意:此字段可能返回 null,表示取不到有效值。
*/
IsGlobal: number
/**
* 服务器总数
注意:此字段可能返回 null,表示取不到有效值。
*/
ScanHostCount: number
/**
* 检测项总数
注意:此字段可能返回 null,表示取不到有效值。
*/
ScanRuleCount: number
/**
* 是否是第一次检测 1是 0不是
注意:此字段可能返回 null,表示取不到有效值。
*/
IfFirstScan: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyBanMode请求参数结构体
*/
export interface ModifyBanModeRequest {
/**
* 阻断模式,STANDARD_MODE:标准阻断,DEEP_MODE:深度阻断
*/
Mode: string
/**
* 阻断时间,用于标准阻断模式
*/
Ttl?: number
}
/**
* 阻断白名单展示列表,包含了机器的信息
*/
export interface BanWhiteListDetail {
/**
* 白名单ID
*/
Id: string
/**
* 白名单别名
*/
Remark: string
/**
* 阻断来源IP
*/
SrcIp: string
/**
* 修改白名单时间
*/
ModifyTime: string
/**
* 创建白名单时间
*/
CreateTime: string
/**
* 白名单是否全局
*/
IsGlobal: boolean
/**
* 机器的UUID
*/
Quuid: string
/**
* 主机安全程序的UUID
*/
Uuid: string
/**
* 机器IP
*/
MachineIp: string
/**
* 机器名称
*/
MachineName: string
}
/**
* DescribeMachineRegions返回参数结构体
*/
export interface DescribeMachineRegionsResponse {
/**
* CVM 云服务器地域列表
*/
CVM: Array<RegionInfo>
/**
* BM 黑石机器地域列表
*/
BM: Array<RegionInfo>
/**
* LH 轻量应用服务器地域列表
*/
LH: Array<RegionInfo>
/**
* ECM 边缘计算服务器地域列表
*/
ECM: Array<RegionInfo>
/**
* Other 混合云地域列表
*/
Other: Array<RegionInfo>
/**
* 所有地域列表(包含以上所有地域)
*/
ALL: Array<RegionInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 资源管理Web应用列表信息
*/
export interface AssetWebAppBaseInfo {
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* 操作系统信息
*/
OsInfo: string
/**
* 主机业务组ID
*/
ProjectId: number
/**
* 主机标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tag: Array<MachineTag>
/**
* 应用名
*/
Name: string
/**
* 版本
*/
Version: string
/**
* 根路径
*/
RootPath: string
/**
* 服务类型
*/
ServiceType: string
/**
* 站点域名
*/
Domain: string
/**
* 虚拟路径
*/
VirtualPath: string
/**
* 插件数
*/
PluginCount: number
/**
* 应用ID
*/
Id: string
/**
* 应用描述
*/
Desc: string
/**
* 主机名称
*/
MachineName: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* 资产管理内核模块参数
*/
export interface AssetCoreModuleParam {
/**
* 名称
*/
Name: string
/**
* 数据
*/
Data: string
}
/**
* DeleteBashEvents请求参数结构体
*/
export interface DeleteBashEventsRequest {
/**
* ID数组,最大100条。
*/
Ids: Array<number>
}
/**
* 资产管理jar包列表
*/
export interface AssetJarBaseInfo {
/**
* 名称
*/
Name: string
/**
* 类型:1应用程序,2系统类库,3Web服务自带库,8:其他,
*/
Type: number
/**
* 是否可执行:0未知,1是,2否
*/
Status: number
/**
* 版本
*/
Version: string
/**
* 路径
*/
Path: string
/**
* 服务器IP
*/
MachineIp: string
/**
* 服务器名称
*/
MachineName: string
/**
* 操作系统
*/
OsInfo: string
/**
* Jar包ID
*/
Id: string
/**
* Jar包Md5
*/
Md5: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机uuid
*/
Uuid: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* SeparateMalwares请求参数结构体
*/
export interface SeparateMalwaresRequest {
/**
* 木马事件ID数组。(最大100条)
*/
Ids: Array<number>
/**
* 是否杀掉进程
*/
KillProcess?: boolean
}
/**
* ExportIgnoreRuleEffectHostList请求参数结构体
*/
export interface ExportIgnoreRuleEffectHostListRequest {
/**
* 检测项id
*/
RuleId: number
/**
* 过滤条件。
<li>AliasName- String- 主机别名</li>
*/
Filters?: Array<Filters>
}
/**
* 需要开通专业版机器信息。
*/
export interface ProVersionMachine {
/**
* 主机类型。
<li>CVM: 云服务器</li>
<li>BM: 黑石物理机</li>
<li>ECM: 边缘计算服务器</li>
<li>LH: 轻量应用服务器</li>
<li>Other: 混合云机器</li>
*/
MachineType: string
/**
* 主机所在地域。
如:ap-guangzhou、ap-beijing
*/
MachineRegion: string
/**
* 主机唯一标识Uuid数组。
黑石的InstanceId,CVM的Uuid ,边缘计算的Uuid , 轻量应用服务器的Uuid ,混合云机器的Quuid 。 当前参数最大长度限制20
*/
Quuid: string
}
/**
* DescribeVulHostCountScanTime返回参数结构体
*/
export interface DescribeVulHostCountScanTimeResponse {
/**
* 总漏洞数
*/
TotalVulCount: number
/**
* 漏洞影响主机数
*/
VulHostCount: number
/**
* 扫描时间
*/
ScanTime: string
/**
* 是否第一次检测
*/
IfFirstScan: boolean
/**
* 运行中的任务号, 没有任务则为0
*/
TaskId: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetCoreModuleList请求参数结构体
*/
export interface DescribeAssetCoreModuleListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Name- string - 是否必填:否 - 包名</li>
<li>User- string - 是否必填:否 - 用户</li>
*/
Filters?: Array<AssetFilters>
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 排序依据:Size,ProcessCount,ModuleCount
*/
By?: string
/**
* 服务器Uuid
*/
Uuid?: string
/**
* 服务器Quuid
*/
Quuid?: string
}
/**
* CloseProVersion返回参数结构体
*/
export interface CloseProVersionResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteAttackLogs请求参数结构体
*/
export interface DeleteAttackLogsRequest {
/**
* 日志ID数组,最大100条。
*/
Ids: Array<number>
}
/**
* DescribeBaselineStrategyDetail返回参数结构体
*/
export interface DescribeBaselineStrategyDetailResponse {
/**
* 策略扫描通过率
注意:此字段可能返回 null,表示取不到有效值。
*/
PassRate: number
/**
* 策略名
注意:此字段可能返回 null,表示取不到有效值。
*/
StrategyName: string
/**
* 策略扫描周期(天)
注意:此字段可能返回 null,表示取不到有效值。
*/
ScanCycle: string
/**
* 定期检测时间, 该时间下发扫描
注意:此字段可能返回 null,表示取不到有效值。
*/
ScanAt: string
/**
* 扫描范围是否全部服务器, 1:是 0:否, 为1则为全部专业版主机
注意:此字段可能返回 null,表示取不到有效值。
*/
IsGlobal: number
/**
* 云服务器类型:
cvm:腾讯云服务器
bm:裸金属
ecm:边缘计算主机
lh: 轻量应用服务器
ohter: 混合云机器
注意:此字段可能返回 null,表示取不到有效值。
*/
MachineType: string
/**
* 主机地域
注意:此字段可能返回 null,表示取不到有效值。
*/
Region: string
/**
* 用户该策略下的所有主机id
注意:此字段可能返回 null,表示取不到有效值。
*/
Quuids: Array<string>
/**
* 用户该策略下所有的基线id
注意:此字段可能返回 null,表示取不到有效值。
*/
CategoryIds: Array<string>
/**
* 1 表示扫描过, 0没扫描过
注意:此字段可能返回 null,表示取不到有效值。
*/
IfScanned: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBaselineList请求参数结构体
*/
export interface DescribeBaselineListRequest {
/**
* 分页参数 最大100条
*/
Limit: number
/**
* 分页参数
*/
Offset: number
/**
* 过滤条件。
<li>StrategyId- Uint64 - 基线策略id</li>
<li>Status - Uint64 - 处理状态1已通过 0未通过</li>
<li>Level - Uint64[] - 处理状态1已通过 0未通过</li>BaselineName
<li>BaselineName - String - 基线名称</li>
<li>Quuid- String - 主机quuid</li>
<li>Uuid- String - 主机uuid</li>
*/
Filters?: Array<Filters>
}
/**
* DescribeBaselineTop请求参数结构体
*/
export interface DescribeBaselineTopRequest {
/**
* 动态top值
*/
Top: number
/**
* 策略id
*/
StrategyId: number
}
/**
* DescribeAssetAppProcessList请求参数结构体
*/
export interface DescribeAssetAppProcessListRequest {
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* App名
*/
Name: string
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
}
/**
* 描述键值对过滤器,用于条件过滤查询。例如过滤ID、名称、状态等
若存在多个Filter时,Filter间的关系为逻辑与(AND)关系。
若同一个Filter存在多个Values,同一Filter下Values间的关系为逻辑或(OR)关系。
* 最多只能有5个Filter
* 同一个Filter存在多个Values,Values值数量最多不能超过5个。
*/
export interface Filter {
/**
* 过滤键的名称。
*/
Name: string
/**
* 一个或者多个过滤值。
*/
Values: Array<string>
/**
* 模糊搜索
*/
ExactMatch?: boolean
}
/**
* DescribeAccountStatistics请求参数结构体
*/
export interface DescribeAccountStatisticsRequest {
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Username - String - 是否必填:否 - 帐号用户名</li>
*/
Filters?: Array<Filter>
}
/**
* ExportBruteAttacks返回参数结构体
*/
export interface ExportBruteAttacksResponse {
/**
* 导出文件下载链接地址。
*/
DownloadUrl: string
/**
* 导出任务ID
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 安全管家列表信息
*/
export interface SecurityButlerInfo {
/**
* 数据id
*/
Id: number
/**
* 订单id
*/
OrderId: number
/**
* cvm id
*/
Quuid: string
/**
* 服务状态 0-服务中,1-已到期 2已销毁
*/
Status: number
/**
* 服务开始时间
*/
StartTime: string
/**
* 服务结束时间
*/
EndTime: string
/**
* 主机名称
*/
HostName: string
/**
* 主机Ip
*/
HostIp: string
/**
* 主机 uuid
*/
Uuid: string
/**
* 主机风险数
*/
RiskCount: number
}
/**
* DescribeSaveOrUpdateWarnings请求参数结构体
*/
export interface DescribeSaveOrUpdateWarningsRequest {
/**
* 告警设置的修改内容
*/
WarningObjects?: Array<WarningObject>
}
/**
* 预付费模式,即包年包月相关参数设置。通过该参数可以指定包年包月实例的购买时长、是否设置自动续费等属性。
*/
export interface ChargePrepaid {
/**
* 购买实例的时长,单位:月。取值范围:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 24, 36。
*/
Period: number
/**
* 自动续费标识。取值范围:
<li>NOTIFY_AND_AUTO_RENEW:通知过期且自动续费</li>
<li>NOTIFY_AND_MANUAL_RENEW:通知过期不自动续费</li>
<li>DISABLE_NOTIFY_AND_MANUAL_RENEW:不通知过期不自动续费</li>
默认取值:NOTIFY_AND_MANUAL_RENEW。若该参数指定为NOTIFY_AND_AUTO_RENEW,在账户余额充足的情况下,实例到期后将按月自动续费。
*/
RenewFlag?: string
}
/**
* DescribeAssetProcessInfoList返回参数结构体
*/
export interface DescribeAssetProcessInfoListResponse {
/**
* 记录总数
*/
Total: number
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Process: Array<AssetProcessBaseInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 进程数据统计数据。
*/
export interface ProcessStatistics {
/**
* 进程名。
*/
ProcessName: string
/**
* 主机数量。
*/
MachineNum: number
}
/**
* DescribeScanSchedule返回参数结构体
*/
export interface DescribeScanScheduleResponse {
/**
* 检测进度
注意:此字段可能返回 null,表示取不到有效值。
*/
Schedule: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 基线详情
*/
export interface BaselineDetail {
/**
* 基线描述
注意:此字段可能返回 null,表示取不到有效值。
*/
Description: string
/**
* 危害等级
注意:此字段可能返回 null,表示取不到有效值。
*/
Level: number
/**
* package名
注意:此字段可能返回 null,表示取不到有效值。
*/
PackageName: string
/**
* 父级id
注意:此字段可能返回 null,表示取不到有效值。
*/
ParentId: number
/**
* 基线名
注意:此字段可能返回 null,表示取不到有效值。
*/
Name: string
}
/**
* ModifyWebPageProtectDir返回参数结构体
*/
export interface ModifyWebPageProtectDirResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetWebAppList请求参数结构体
*/
export interface DescribeAssetWebAppListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Name - String - 是否必填:否 - 应用名</li>
<li>Domain - String - 是否必填:否 - 站点域名</li>
<li>Type - int - 是否必填:否 - 服务类型:
0:全部
1:Tomcat
2:Apache
3:Nginx
4:WebLogic
5:Websphere
6:JBoss
7:Jetty
8:IHS
9:Tengine</li>
<li>OsType - String - 是否必填:否 - windows/linux</li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )</li>
*/
Filters?: Array<Filter>
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 可选排序:PluginCount
*/
By?: string
/**
* 查询指定Quuid主机的信息
*/
Quuid?: string
}
/**
* 专家服务订单信息
*/
export interface ExpertServiceOrderInfo {
/**
* 订单id
*/
OrderId: number
/**
* 订单类型 1应急 2 旗舰护网 3 安全管家
*/
InquireType: number
/**
* 服务数量
*/
InquireNum: number
/**
* 服务开始时间
*/
BeginTime: string
/**
* 服务结束时间
*/
EndTime: string
/**
* 服务时长几个月
*/
ServiceTime: number
/**
* 订单状态 0 未启动 1 服务中 2已过期 3完成,4退费销毁
*/
Status: number
}
/**
* 帐号统计数据。
*/
export interface AccountStatistics {
/**
* 用户名。
*/
Username: string
/**
* 主机数量。
*/
MachineNum: number
}
/**
* 资产管理账号key详情
*/
export interface AssetUserKeyInfo {
/**
* 公钥值
*/
Value: string
/**
* 公钥备注
*/
Comment: string
/**
* 加密方式
*/
EncryptType: string
}
/**
* DescribeMachines返回参数结构体
*/
export interface DescribeMachinesResponse {
/**
* 主机列表
*/
Machines: Array<Machine>
/**
* 主机数量
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetWebLocationList请求参数结构体
*/
export interface DescribeAssetWebLocationListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Name - String - 是否必填:否 - 域名</li>
<li>User - String - 是否必填:否 - 运行用户</li>
<li>Port - uint64 - 是否必填:否 - 站点端口</li>
<li>Proto - uint64 - 是否必填:否 - 站点协议:1:HTTP,2:HTTPS</li>
<li>ServiceType - uint64 - 是否必填:否 - 服务类型:
1:Tomcat
2:Apache
3:Nginx
4:WebLogic
5:Websphere
6:JBoss
7:WildFly
8:Jetty
9:IHS
10:Tengine</li>
<li>OsType - String - 是否必填:否 - windows/linux</li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )</li>
*/
Filters?: Array<Filter>
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 可选排序:PathCount
*/
By?: string
/**
* 查询指定Quuid主机的信息
*/
Quuid?: string
}
/**
* DescribeVulLevelCount请求参数结构体
*/
export type DescribeVulLevelCountRequest = null
/**
* DeleteWebPageEventLog请求参数结构体
*/
export type DeleteWebPageEventLogRequest = null
/**
* DescribeProVersionStatus请求参数结构体
*/
export interface DescribeProVersionStatusRequest {
/**
* 云镜客户端UUID、填写"all"表示所有主机。
*/
Uuid: string
}
/**
* DescribeBaselineList返回参数结构体
*/
export interface DescribeBaselineListResponse {
/**
* 基线信息列表
注意:此字段可能返回 null,表示取不到有效值。
*/
BaselineList: Array<BaselineInfo>
/**
* 分页查询记录总数
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeExpertServiceOrderList请求参数结构体
*/
export interface DescribeExpertServiceOrderListRequest {
/**
* <li>InquireType- String - 是否必填:否 - 订单类型过滤,</li>
*/
Filters?: Array<Filters>
/**
* 分页条数 最大100条
*/
Limit?: number
/**
* 分页步长
*/
Offset?: number
}
/**
* ExportVulEffectHostList返回参数结构体
*/
export interface ExportVulEffectHostListResponse {
/**
* 已废弃
注意:此字段可能返回 null,表示取不到有效值。
*/
DownloadUrl: string
/**
* 导出任务Id , 可通过ExportTasks 接口下载
*/
TaskId: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeVulTop请求参数结构体
*/
export interface DescribeVulTopRequest {
/**
* 漏洞风险服务器top,1-100
*/
Top: number
/**
* 1: web应用漏洞 2=系统组件漏洞3:安全基线 4: Linux系统漏洞 5: windows补丁,传0的时候表示查应急漏洞
*/
VulCategory?: number
}
/**
* DescribeMachineInfo请求参数结构体
*/
export interface DescribeMachineInfoRequest {
/**
* 云镜客户端唯一Uuid。
*/
Uuid?: string
/**
* Quuid , Uuid 必填一项
*/
Quuid?: string
}
/**
* 快速搜索模板
*/
export interface SearchTemplate {
/**
* 检索名称
*/
Name: string
/**
* 检索索引类型
*/
LogType: string
/**
* 检索语句
*/
Condition: string
/**
* 时间范围
*/
TimeRange: string
/**
* 转换的检索语句内容
*/
Query: string
/**
* 检索方式。输入框检索:standard,过滤,检索:simple
*/
Flag: string
/**
* 展示数据
*/
DisplayData: string
/**
* 规则ID
*/
Id?: number
}
/**
* DescribeGeneralStat返回参数结构体
*/
export interface DescribeGeneralStatResponse {
/**
* 云主机总数
*/
MachinesAll: number
/**
* 云主机没有安装主机安全客户端的总数
*/
MachinesUninstalled: number
/**
* 主机安全客户端总数的总数
*/
AgentsAll: number
/**
* 主机安全客户端在线的总数
*/
AgentsOnline: number
/**
* 主机安全客户端 离线+关机 的总数
*/
AgentsOffline: number
/**
* 主机安全客户端专业版的总数
*/
AgentsPro: number
/**
* 主机安全客户端基础版的总数
*/
AgentsBasic: number
/**
* 7天内到期的预付费专业版总数
*/
AgentsProExpireWithInSevenDays: number
/**
* 风险主机总数
*/
RiskMachine: number
/**
* 已关机总数
*/
Shutdown: number
/**
* 已离线总数
*/
Offline: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* EditTags返回参数结构体
*/
export interface EditTagsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteMachineTag返回参数结构体
*/
export interface DeleteMachineTagResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeSecurityEventsCnt返回参数结构体
*/
export interface DescribeSecurityEventsCntResponse {
/**
* 木马文件相关风险事件
*/
Malware: SecurityEventInfo
/**
* 登录审计相关风险事件
*/
HostLogin: SecurityEventInfo
/**
* 密码破解相关风险事件
*/
BruteAttack: SecurityEventInfo
/**
* 恶意请求相关风险事件
*/
RiskDns: SecurityEventInfo
/**
* 高危命令相关风险事件
*/
Bash: SecurityEventInfo
/**
* 本地提权相关风险事件
*/
PrivilegeRules: SecurityEventInfo
/**
* 反弹Shell相关风险事件
*/
ReverseShell: SecurityEventInfo
/**
* 系统组件相关风险事件
*/
SysVul: SecurityEventInfo
/**
* Web应用漏洞相关风险事件
*/
WebVul: SecurityEventInfo
/**
* 应急漏洞相关风险事件
*/
EmergencyVul: SecurityEventInfo
/**
* 安全基线相关风险事件
*/
BaseLine: SecurityEventInfo
/**
* 攻击检测相关风险事件
*/
AttackLogs: SecurityEventInfo
/**
* 受影响机器数
*/
EffectMachineCount: number
/**
* 所有事件总数
*/
EventsCount: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 告警设置列表
*/
export interface WarningInfoObj {
/**
* 事件告警类型;1:离线,2:木马,3:异常登录,4:爆破,5:漏洞(已拆分为9-12四种类型)6:高危命令,7:反弹sell,8:本地提权,9:系统组件漏洞,10:wen应用漏洞,11:应急漏洞,12:安全基线 ,13: 防篡改
*/
Type: number
/**
* 1: 关闭告警 0: 开启告警
*/
DisablePhoneWarning: number
/**
* 开始时间,格式: HH:mm
*/
BeginTime: string
/**
* 结束时间,格式: HH:mm
*/
EndTime: string
/**
* 时区信息
*/
TimeZone: string
/**
* 漏洞等级控制位(对应DB的十进制存储)
*/
ControlBit: number
/**
* 漏洞等级控制位二进制,每一位对应页面漏洞等级的开启关闭:低中高(0:关闭;1:开启),例如:101 → 同时勾选低+高
*/
ControlBits: string
}
/**
* OpenProVersion请求参数结构体
*/
export interface OpenProVersionRequest {
/**
* 云主机类型。(当前参数已作废,可以留空值 )
*/
MachineType: string
/**
* 机器所属地域。(当前参数已作废,可以留空值 )
*/
MachineRegion: string
/**
* 主机唯一标识Uuid数组。
黑石的InstanceId,CVM的Uuid ,边缘计算的Uuid , 轻量应用服务器的Uuid ,混合云机器的Quuid 。 当前参数最大长度限制20
*/
Quuids: Array<string>
/**
* 活动ID。
*/
ActivityId?: number
}
/**
* UpdateMachineTags请求参数结构体
*/
export interface UpdateMachineTagsRequest {
/**
* 机器 Quuid
*/
Quuid: string
/**
* 服务器地区 如: ap-guangzhou
*/
MachineRegion: string
/**
* 服务器类型(CVM|BM|ECM|LH|Other)
*/
MachineArea: string
/**
* 标签ID,该操作会覆盖原有的标签列表
*/
TagIds?: Array<number>
}
/**
* UpdateBaselineStrategy请求参数结构体
*/
export interface UpdateBaselineStrategyRequest {
/**
* 策略id
*/
StrategyId: number
/**
* 策略名称
*/
StrategyName: string
/**
* 检测周期
*/
ScanCycle: number
/**
* 定期检测时间,该时间下发扫描
*/
ScanAt: string
/**
* 该策略下选择的基线id数组
*/
CategoryIds: Array<string>
/**
* 扫描范围是否全部服务器, 1:是 0:否, 为1则为全部专业版主机
*/
IsGlobal: number
/**
* 云主机类型:
cvm:腾讯云服务器
bm:裸金属
ecm:边缘计算主机
lh:轻量应用服务器
other:混合云机器
*/
MachineType: string
/**
* 主机地域 ap-guangzhou
*/
RegionCode: string
/**
* 主机id数组
*/
Quuids: Array<string>
}
/**
* DescribeHostLoginList返回参数结构体
*/
export interface DescribeHostLoginListResponse {
/**
* 总数
*/
TotalCount: number
/**
* 登录审计列表
注意:此字段可能返回 null,表示取不到有效值。
*/
HostLoginList: Array<HostLoginList>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeBaselineAnalysisData请求参数结构体
*/
export interface DescribeBaselineAnalysisDataRequest {
/**
* 基线策略id
*/
StrategyId: number
}
/**
* 资源管理账号基本信息
*/
export interface AssetPortBaseInfo {
/**
* 主机内网IP
*/
MachineIp: string
/**
* 主机外网IP
*/
MachineWanIp: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 主机Uuid
*/
Uuid: string
/**
* 操作系统信息
*/
OsInfo: string
/**
* 主机业务组ID
*/
ProjectId: number
/**
* 主机标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tag: Array<MachineTag>
/**
* 进程名称
*/
ProcessName: string
/**
* 进程版本
*/
ProcessVersion: string
/**
* 进程路径
*/
ProcessPath: string
/**
* 进程ID
*/
Pid: string
/**
* 运行用户
*/
User: string
/**
* 启动时间
*/
StartTime: string
/**
* 启动参数
*/
Param: string
/**
* 进程TTY
*/
Teletype: string
/**
* 端口
*/
Port: string
/**
* 所属用户组
*/
GroupName: string
/**
* 进程MD5
*/
Md5: string
/**
* 父进程ID
*/
Ppid: string
/**
* 父进程名称
*/
ParentProcessName: string
/**
* 端口协议
*/
Proto: string
/**
* 绑定IP
*/
BindIp: string
/**
* 主机名称
*/
MachineName: string
/**
* 数据更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdateTime: string
}
/**
* DescribeAssetWebLocationInfo请求参数结构体
*/
export interface DescribeAssetWebLocationInfoRequest {
/**
* 服务器Quuid
*/
Quuid: string
/**
* 服务器Uuid
*/
Uuid: string
/**
* 站点Id
*/
Id: string
}
/**
* DescribeAssetInitServiceList返回参数结构体
*/
export interface DescribeAssetInitServiceListResponse {
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Services: Array<AssetInitServiceBaseInfo>
/**
* 总数量
*/
Total: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetWebFrameList返回参数结构体
*/
export interface DescribeAssetWebFrameListResponse {
/**
* 记录总数
*/
Total: number
/**
* 列表
注意:此字段可能返回 null,表示取不到有效值。
*/
WebFrames: Array<AssetWebFrameBaseInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAssetUserList请求参数结构体
*/
export interface DescribeAssetUserListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
<li>Name - String - 是否必填:否 - 账户名(模糊匹配)</li>
<li>NameStrict - String - 是否必填:否 - 账户名(严格匹配)</li>
<li>Uid - uint64 - 是否必填:否 - Uid</li>
<li>Guid - uint64 - 是否必填:否 - Guid</li>
<li>LoginTimeStart - String - 是否必填:否 - 开始时间,如:2021-01-11</li>
<li>LoginTimeEnd - String - 是否必填:否 - 结束时间,如:2021-01-11</li>
<li>LoginType - uint64 - 是否必填:否 - 0-不可登录;1-只允许key登录;2只允许密码登录;3-允许key和密码 仅linux</li>
<li>OsType - String - 是否必填:否 - windows或linux</li>
<li>Status - uint64 - 是否必填:否 - 账号状态:0-禁用;1-启用</li>
<li>UserType - uint64 - 是否必填:否 - 账号类型:0访客用户,1标准用户,2管理员用户 仅windows</li>
<li>IsDomain - uint64 - 是否必填:否 - 是否域账号:0 不是,1是 仅windows
<li>IsRoot - uint64 - 是否必填:否 - 是否Root权限:0 不是,1是 仅linux
<li>IsSudo - uint64 - 是否必填:否 - 是否Sudo权限:0 不是,1是 仅linux</li>
<li>IsSshLogin - uint64 - 是否必填:否 - 是否ssh登录:0 不是,1是 仅linux</li>
<li>ShellLoginStatus - uint64 - 是否必填:否 - 是否shell登录性,0不是;1是 仅linux</li>
<li>PasswordStatus - uint64 - 是否必填:否 - 密码状态:1正常 2即将过期 3已过期 4已锁定 仅linux</li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )</li>
*/
Filters?: Array<Filter>
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 可选排序:
LoginTime
PasswordChangeTime
PasswordDuaTime
PasswordLockDays
*/
By?: string
/**
* 查询指定Quuid主机的信息
*/
Quuid?: string
}
/**
* DeleteBaselineStrategy请求参数结构体
*/
export interface DeleteBaselineStrategyRequest {
/**
* 基线策略id
*/
StrategyId: number
}
/**
* DescribeAssetSystemPackageList请求参数结构体
*/
export interface DescribeAssetSystemPackageListRequest {
/**
* 主机Uuid
*/
Uuid: string
/**
* 主机Quuid
*/
Quuid: string
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 过滤条件。
<li>Name - String - 是否必填:否 - 包 名</li>
<li>StartTime - String - 是否必填:否 - 安装开始时间</li>
<li>EndTime - String - 是否必填:否 - 安装开始时间</li>
<li>Type - int - 是否必填:否 - 安装包类型:
1:rmp
2:dpkg
3:java
4:system</li>
*/
Filters?: Array<Filter>
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 排序方式可选:InstallTime 安装时间
*/
By?: string
}
/**
* 服务器标签信息
*/
export interface MachineTag {
/**
* 关联标签ID
*/
Rid: number
/**
* 标签名
*/
Name: string
/**
* 标签ID
*/
TagId: number
}
/**
* 描述键值对过滤器,用于条件过滤查询。例如过滤ID、名称、状态等
若存在多个Filter时,Filter间的关系为逻辑与(AND)关系。
若同一个Filter存在多个Values,同一Filter下Values间的关系为逻辑或(OR)关系。
*/
export interface Filters {
/**
* 过滤键的名称。
*/
Name: string
/**
* 一个或者多个过滤值。
*/
Values: Array<string>
/**
* 是否模糊匹配,前端框架会带上,可以不管
*/
ExactMatch?: boolean
}
/**
* DescribeAssetWebServiceInfoList请求参数结构体
*/
export interface DescribeAssetWebServiceInfoListRequest {
/**
* 需要返回的数量,默认为10,最大值为100
*/
Limit?: number
/**
* 偏移量,默认为0。
<li>IpOrAlias - String - 是否必填:否 - 主机ip或别名筛选</li>
*/
Offset?: number
/**
* 过滤条件。
<li>User- string - 是否必填:否 - 运行用户</li>
<li>Name- string - 是否必填:否 - Web服务名:
1:Tomcat
2:Apache
3:Nginx
4:WebLogic
5:Websphere
6:JBoss
7:WildFly
8:Jetty
9:IHS
10:Tengine</li>
<li>OsType- string - 是否必填:否 - Windows/linux</li>
<li>Os -String 是否必填: 否 - 操作系统( DescribeMachineOsList 接口 值 )</li>
*/
Filters?: Array<AssetFilters>
/**
* 排序方式,asc升序 或 desc降序
*/
Order?: string
/**
* 可选排序:ProcessCount
*/
By?: string
/**
* 查询指定Quuid主机的信息
*/
Quuid?: string
}
/**
* CreateSearchLog请求参数结构体
*/
export interface CreateSearchLogRequest {
/**
* 搜索内容
*/
SearchContent: string
}
/**
* DescribeSearchTemplates请求参数结构体
*/
export interface DescribeSearchTemplatesRequest {
/**
* 偏移量,默认为0。
*/
Offset?: number
/**
* 返回数量,默认为10,最大值为100。
*/
Limit?: number
}
/**
* CancelIgnoreVul请求参数结构体
*/
export interface CancelIgnoreVulRequest {
/**
* 漏洞事件id串,多个用英文逗号分隔
*/
EventIds: string
} | the_stack |
import * as std from "tstl";
import { Entity } from "../../protocol/entity/Entity";
import { IProtocol } from "../../protocol/invoke/IProtocol";
import { DistributedSystemArray } from "./DistributedSystemArray";
import { DistributedSystem } from "./DistributedSystem";
import { DSInvokeHistory } from "./DSInvokeHistory";
import { Invoke } from "../../protocol/invoke/Invoke";
import { InvokeParameter } from "../../protocol/invoke/InvokeParameter";
/**
* A process of Distributed Processing System.
*
* The {@link DistributedProcess} is an abstract class who represents a **process**, *SOMETHING TO DISTRIBUTE* in a Distributed
* Processing System. Overrides the {@link DistributedProcess} and defines the *SOMETHING TO DISTRIBUTE*.
*
* Relationship between {@link DistributedSystem} and {@link DistributedProcess} objects are **M: N Associative**.
* Unlike {@link ExternalSystemRole}, the {@link DistributedProcess} objects are not belonged to a specific
* {@link DistributedSystem} object. The {@link DistributedProcess} objects are belonged to the
* {@link DistributedSystemArrayMediator} directly.
*
* When you need the **distributed process**, then call {@link sendData sendData()}. The {@link sendData} will find
* the most idle {@link DistributedSystem slave system} considering not only number of processes on progress, but also
* {@link DistributedSystem.getPerformance performance index} of each {@link DistributedSystem} object and
* {@link getResource resource index} of this {@link DistributedProcess} object. The {@link Invoke} message
* requesting the **distributed process** will be sent to the most idle {@link DistributedSystem slave system}.
*
* Those {@link DistributedSystem.getPerformance performance index} and {@link getResource resource index} are
* revaluated whenever the **distributed process** has completed basis on the execution time.
*
* <a href="http://samchon.github.io/framework/images/design/ts_class_diagram/templates_distributed_system.png"
* target="_blank">
* <img src="http://samchon.github.io/framework/images/design/ts_class_diagram/templates_distributed_system.png"
* style="max-width: 100%" />
* </a>
*
* @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System)
* @author Jeongho Nam <http://samchon.org>
*/
export abstract class DistributedProcess
extends Entity
implements IProtocol
{
/**
* @hidden
*/
private system_array_: DistributedSystemArray<DistributedSystem>;
/**
* A name, represents and identifies this {@link DistributedProcess process}.
*
* This {@link name} is an identifier represents this {@link DistributedProcess process}. This {@link name} is
* used in {@link DistributedSystemArray.getProcess} and {@link DistributedSystemArray.getProcess}, as a key elements.
* Thus, this {@link name} should be unique in its parent {@link DistributedSystemArray} object.
*/
protected name: string;
/**
* @hidden
*/
private progress_list_: std.HashMap<number, DSInvokeHistory>;
/**
* @hidden
*/
private history_list_: std.HashMap<number, DSInvokeHistory>;
/**
* @hidden
*/
private resource: number;
/**
* @hidden
*/
private enforced_: boolean;
/* ---------------------------------------------------------
CONSTRUCTORS
--------------------------------------------------------- */
/**
* Constrct from parent {@link DistributedSystemArray} object.
*
* @param systemArray The parent {@link DistributedSystemArray} object.
*/
public constructor(systemArray: DistributedSystemArray<DistributedSystem>)
{
super();
this.system_array_ = systemArray;
this.name = "";
// PERFORMANCE INDEX
this.resource = 1.0;
this.progress_list_ = new std.HashMap<number, DSInvokeHistory>();
this.history_list_ = new std.HashMap<number, DSInvokeHistory>();
}
/* ---------------------------------------------------------
ACCESSORS
--------------------------------------------------------- */
/**
* Identifier of {@link ParallelProcess} is its {@link name}.
*/
public key(): string
{
return this.name;
}
/**
* Get parent {@link DistributedSystemArray} object.
*
* @return The parent {@link DistributedSystemArray} object.
*/
public getSystemArray(): DistributedSystemArray<DistributedSystem>;
/**
* Get parent {@link DistributedSystemArray} object.
*
* @return The parent {@link DistributedSystemArray} object.
*/
public getSystemArray<SystemArray extends DistributedSystemArray<DistributedSystem>>(): SystemArray;
public getSystemArray(): DistributedSystemArray<DistributedSystem>
{
return this.system_array_;
}
/**
* Get name, who represents and identifies this process.
*/
public getName(): string
{
return this.name;
}
/**
* Get resource index.
*
* Get *resource index* that indicates how much this {@link DistributedProcess process} is heavy.
*
* If this {@link DistributedProcess process} does not have any {@link Invoke} message had handled, then the
* *resource index* will be ```1.0```, which means default and average value between all
* {@link DistributedProcess} instances (that are belonged to a same {@link DistributedSystemArray} object).
*
* You can specify the *resource index* by yourself, but notice that, if the *resource index* is higher than
* other {@link DistributedProcess} objects, then this {@link DistributedProcess process} will be ordered to
* handle less processes than other {@link DistributedProcess} objects. Otherwise, the *resource index* is
* lower than others, of course, much processes will be requested.
*
* - {@link setResource setResource()}
* - {@link enforceResource enforceResource()}
*
* Unless {@link enforceResource enforceResource()} is called, This *resource index* is **revaluated** whenever
* {@link sendData sendData()} is called.
*
* @return Resource index.
*/
public getResource(): number
{
return this.resource;
}
/**
* Set resource index.
*
* Set *resource index* that indicates how much this {@link DistributedProcess process} is heavy. This
* *resource index* can be **revaulated**.
*
* Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the
* *resource index* is higher than other {@link DistributedProcess} objects, then this
* {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess}
* objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested.
*
* Unlike {@link enforceResource}, configuring *resource index* by this {@link setResource} allows the
* **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the
* *resource index*. The {@link DistributedProcess process} is much heavier than any other, but you estimated it
* to the lightest one. It looks like a terrible case that causes
* {@link DistributedSystemArray entire distributed processing system} to be slower, however, don't mind. The
* {@link DistributedProcess process} will the direct to the *propriate resource index* eventually with the
* **revaluation**.
*
* - The **revaluation** is caused by the {@link sendData sendData()} method.
*
* @param val New resource index, but can be revaluated.
*/
public setResource(val: number): void
{
this.resource = val;
this.enforced_ = false;
}
/**
* Enforce resource index.
*
* Enforce *resource index* that indicates how much heavy the {@link DistributedProcess process is}. The
* *resource index* will be fixed, never be **revaluated**.
*
* Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the
* *resource index* is higher than other {@link DistributedProcess} objects, then this
* {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess}
* objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested.
*
* The difference between {@link setResource} and this {@link enforceResource} is allowing **revaluation** or not.
* This {@link enforceResource} does not allow the **revaluation**. The *resource index* is clearly fixed and
* never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the **mis-valuation**
* with this {@link enforceResource}.
*
* For example, there's a {@link DistributedProcess process} much heavier than any other, but you
* **mis-estimated** it to the lightest. In that case, there's no way. The
* {@link DistributedSystemArray entire distributed processing system} will be slower by the **mis-valuation**.
* By the reason, using {@link enforceResource}, it's recommended only when you can clearly certain the
* *resource index*. If you can't certain the *resource index* but want to recommend, then use {@link setResource}
* instead.
*
* @param val New resource index to be fixed.
*/
public enforceResource(val: number): void
{
this.resource = val;
this.enforced_ = true;
}
/**
* @hidden
*/
private _Compute_average_elapsed_time(): number
{
let sum: number = 0;
for (let it = this.history_list_.begin(); !it.equals(this.history_list_.end()); it = it.next())
{
let history: DSInvokeHistory = it.second;
let elapsed_time: number = history.computeElapsedTime() / history.getWeight();
// THE SYSTEM'S PERFORMANCE IS 5. THE SYSTEM CAN HANDLE A PROCESS VERY QUICKLY
// AND ELAPSED TIME OF THE PROCESS IS 3 SECONDS
// THEN I CONSIDER THE ELAPSED TIME AS 15 SECONDS.
sum += elapsed_time * history.getSystem().getPerformance();
}
return sum / this.history_list_.size();
}
/* ---------------------------------------------------------
INVOKE MESSAGE CHAIN
--------------------------------------------------------- */
/**
* @inheritdoc
*/
public abstract replyData(invoke: Invoke): void;
/**
* Send an {@link Invoke} message.
*
* Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent
* to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle
* {@link DistributedSystem} object will be returned.
*
* When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate
* {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this
* {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time.
*
* @param invoke An {@link Invoke} message requesting distributed process.
* @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message.
*/
public sendData(invoke: Invoke): DistributedSystem;
/**
* Send an {@link Invoke} message.
*
* Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent
* to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle
* {@link DistributedSystem} object will be returned.
*
* When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate
* {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this
* {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time.
*
* @param invoke An {@link Invoke} message requesting distributed process.
* @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1.
*
* @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message.
*/
public sendData(invoke: Invoke, weight: number): DistributedSystem;
public sendData(invoke: Invoke, weight: number = 1.0): DistributedSystem
{
if (this.system_array_.empty() == true)
return null;
// ADD UID FOR ARCHIVING HISTORY
let uid: number;
if (invoke.has("_History_uid") == false)
{
// ISSUE UID AND ATTACH IT TO INVOKE'S LAST PARAMETER
uid = ++this.system_array_["history_sequence_"];
invoke.push_back(new InvokeParameter("_History_uid", uid));
}
else
{
// INVOKE MESSAGE ALREADY HAS ITS OWN UNIQUE ID
// - system_array_ IS A TYPE OF DistributedSystemArrayMediator. THE MESSAGE HAS COME FROM ITS MASTER
// - A Distributed HAS DISCONNECTED. THE SYSTEM SHIFTED ITS CHAIN TO ANOTHER SLAVE.
uid = invoke.get("_History_uid").getValue();
// FOR CASE 1. UPDATE HISTORY_SEQUENCE TO MAXIMUM
this.system_array_["history_sequence_"] = uid;
// FOR CASE 2. ERASE ORDINARY PROGRESSIVE HISTORY FROM THE DISCONNECTED
this.progress_list_.erase(uid);
}
// ADD PROCESS NAME AND WEIGHT FOR MEDIATOR
if (invoke.has("_Process_name") == false)
invoke.push_back(new InvokeParameter("_Process_name", this.name));
if (invoke.has("_Process_weight") == false)
invoke.push_back(new InvokeParameter("_Process_weight", weight));
else
weight = invoke.get("_Process_name").getValue();
// FIND THE MOST IDLE SYSTEM
let idle_system: DistributedSystem = null;
for (let i: number = 0; i < this.system_array_.size(); i++)
{
let system: DistributedSystem = this.system_array_.at(i) as DistributedSystem;
if (system["exclude_"] == true)
continue; // BEING REMOVED SYSTEM
if (idle_system == null || // NO IDLE SYSTEM YET
(system["progress_list_"].empty() && system["history_list_"].empty()) || // NOTHING HAS REQUESTED
system["progress_list_"].size() < idle_system["progress_list_"].size() || // LESS NUMBER OF PROGRESS
(
system["progress_list_"].size() == idle_system["progress_list_"].size() &&
system.getPerformance() > idle_system.getPerformance() // GREATER PERFORMANCE
) ||
(
system["progress_list_"].size() == idle_system["progress_list_"].size() &&
system.getPerformance() == idle_system.getPerformance() &&
system["history_list_"].size() < idle_system["history_list_"].size()) // LESS HISTORY
)
idle_system = system;
}
if (idle_system == null)
throw new std.OutOfRange("No remote system to send data exists.");
// ARCHIVE HISTORY ON PROGRESS_LIST (IN SYSTEM AND ROLE AT THE SAME TIME)
let history: DSInvokeHistory = new DSInvokeHistory(idle_system, this, invoke, weight);
this.progress_list_.emplace(uid, history);
idle_system["progress_list_"].emplace(uid, std.make_pair(invoke, history));
// SEND DATA
idle_system.sendData(invoke);
// RETURN THE IDLE SYSTEM, WHO SENT THE INVOKE MESSAGE.
return idle_system;
}
/**
* @hidden
*/
private _Complete_history(history: DSInvokeHistory): void
{
// ERASE FROM ORDINARY PROGRESS AND MIGRATE TO THE HISTORY
this.progress_list_.erase(history.getUID());
this.history_list_.emplace(history.getUID(), history);
}
/* ---------------------------------------------------------
EXPORTERS
--------------------------------------------------------- */
/**
* @inheritdoc
*/
public TAG(): string
{
return "process";
}
} | the_stack |
declare namespace WechatMiniprogram {
namespace Component {
type Instance<
TData extends DataOption,
TProperty extends PropertyOption,
TMethod extends Partial<MethodOption>
> = InstanceProperties &
InstanceMethods<TData> &
TMethod & {
/** 组件数据,**包括内部数据和属性值** */
data: TData & PropertyOptionToData<TProperty>
/** 组件数据,**包括内部数据和属性值**(与 `data` 一致) */
properties: TData & PropertyOptionToData<TProperty>,
}
type TrivialInstance = Instance<IAnyObject, IAnyObject, IAnyObject>
type TrivialOption = Options<IAnyObject, IAnyObject, IAnyObject>
type Options<
TData extends DataOption,
TProperty extends PropertyOption,
TMethod extends MethodOption
> = Partial<Data<TData>> &
Partial<Property<TProperty>> &
Partial<Method<TMethod>> &
Partial<OtherOption> &
Partial<Lifetimes> &
ThisType<Instance<TData, TProperty, TMethod>>
interface Constructor {
<
TData extends DataOption,
TProperty extends PropertyOption,
TMethod extends MethodOption
>(
options: Options<TData, TProperty, TMethod>,
): string
}
type DataOption = Record<string, any>
type PropertyOption = Record<string, AllProperty>
type MethodOption = Record<string, (...args: any[]) => any>
interface Data<D extends DataOption> {
/** 组件的内部数据,和 `properties` 一同用于组件的模板渲染 */
data?: D
}
interface Property<P extends PropertyOption> {
/** 组件的对外属性,是属性名到属性设置的映射表 */
properties: P
}
interface Method<M extends MethodOption> {
/** 组件的方法,包括事件响应函数和任意的自定义方法,关于事件响应函数的使用,参见 [组件间通信与事件](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/events.html) */
methods: M
}
type PropertyType =
| StringConstructor
| NumberConstructor
| BooleanConstructor
| ArrayConstructor
| ObjectConstructor
| null
type ValueType<T extends PropertyType> = T extends StringConstructor
? string
: T extends NumberConstructor
? number
: T extends BooleanConstructor
? boolean
: T extends ArrayConstructor
? any[]
: T extends ObjectConstructor ? IAnyObject : any
interface FullProperty<T extends PropertyType> {
/** 属性类型 */
type: T
/** 属性初始值 */
value?: ValueType<T>
/** 属性值被更改时的响应函数 */
observer?:
| string
| ((
newVal: ValueType<T>,
oldVal: ValueType<T>,
changedPath: Array<string | number>,
) => void)
/** 属性的类型(可以指定多个) */
optionalTypes?: ShortProperty[]
}
type AllFullProperty =
| FullProperty<StringConstructor>
| FullProperty<NumberConstructor>
| FullProperty<BooleanConstructor>
| FullProperty<ArrayConstructor>
| FullProperty<ObjectConstructor>
| FullProperty<null>
type ShortProperty =
| StringConstructor
| NumberConstructor
| BooleanConstructor
| ArrayConstructor
| ObjectConstructor
| null
type AllProperty = AllFullProperty | ShortProperty
type PropertyToData<T extends AllProperty> = T extends ShortProperty
? ValueType<T>
: FullPropertyToData<Exclude<T, ShortProperty>>
type FullPropertyToData<T extends AllFullProperty> = ValueType<
T['type']
>
type PropertyOptionToData<P extends PropertyOption> = {
[name in keyof P]: PropertyToData<P[name]>
}
interface InstanceProperties {
/** 组件的文件路径 */
is: string
/** 节点id */
id: string
/** 节点dataset */
dataset: Record<string, string>
}
interface InstanceMethods<D extends DataOption> {
/** `setData` 函数用于将数据从逻辑层发送到视图层
*(异步),同时改变对应的 `this.data` 的值(同步)。
*
* **注意:**
*
* 1. **直接修改 this.data 而不调用 this.setData 是无法改变页面的状态的,还会造成数据不一致**。
* 1. 仅支持设置可 JSON 化的数据。
* 1. 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据。
* 1. 请不要把 data 中任何一项的 value 设为 `undefined` ,否则这一项将不被设置并可能遗留一些潜在问题。
*/
setData(
/** 这次要改变的数据
*
* 以 `key: value` 的形式表示,将 `this.data` 中的 `key` 对应的值改变成 `value`。
*
* 其中 `key` 可以以数据路径的形式给出,支持改变数组中的某一项或对象的某个属性,如 `array[2].message`,`a.b.c.d`,并且不需要在 this.data 中预先定义。
*/
data: Partial<D> & IAnyObject,
/** setData引起的界面更新渲染完毕后的回调函数,最低基础库: `1.5.0` */
callback?: () => void,
): void
/** 检查组件是否具有 `behavior` (检查时会递归检查被直接或间接引入的所有behavior) */
hasBehavior(behavior: object): void
/** 触发事件,参见组件事件 */
triggerEvent(
name: string,
detail?: object,
options?: TriggerEventOption,
): void
/** 创建一个 SelectorQuery 对象,选择器选取范围为这个组件实例内 */
createSelectorQuery(): SelectorQuery
/** 创建一个 IntersectionObserver 对象,选择器选取范围为这个组件实例内 */
createIntersectionObserver(
options: CreateIntersectionObserverOption,
): IntersectionObserver
/** 使用选择器选择组件实例节点,返回匹配到的第一个组件实例对象(会被 `wx://component-export` 影响) */
selectComponent(selector: string): TrivialInstance
/** 使用选择器选择组件实例节点,返回匹配到的全部组件实例对象组成的数组 */
selectAllComponents(selector: string): TrivialInstance[]
/**
* 选取当前组件节点所在的组件实例(即组件的引用者),返回它的组件实例对象(会被 `wx://component-export` 影响)
*
* 最低基础库版本:[`2.8.2`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
selectOwnerComponent(): TrivialInstance
/** 获取这个关系所对应的所有关联节点,参见 组件间关系 */
getRelationNodes(relationKey: string): TrivialInstance[]
/**
* 立刻执行 callback ,其中的多个 setData 之间不会触发界面绘制(只有某些特殊场景中需要,如用于在不同组件同时 setData 时进行界面绘制同步)
*
* 最低基础库版本:[`2.4.0`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
groupSetData(callback?: () => void): void
/**
* 返回当前页面的 custom-tab-bar 的组件实例
*
* 最低基础库版本:[`2.6.2`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
getTabBar(): TrivialInstance
/**
* 返回页面标识符(一个字符串),可以用来判断几个自定义组件实例是不是在同一个页面内
*
* 最低基础库版本:[`2.7.1`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
getPageId(): string
/**
* 执行关键帧动画,详见[动画](https://developers.weixin.qq.com/miniprogram/dev/framework/view/animation.html)
*
* 最低基础库版本:[`2.9.0`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
animate(
selector: string,
keyFrames: KeyFrame[],
duration: number,
callback: () => void,
): void
/**
* 执行关键帧动画,详见[动画](https://developers.weixin.qq.com/miniprogram/dev/framework/view/animation.html)
*
* 最低基础库版本:[`2.9.0`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
animate(
selector: string,
keyFrames: ScrollTimelineKeyframe[],
duration: number,
scrollTimeline: ScrollTimelineOption,
): void
/**
* 清除关键帧动画,详见[动画](https://developers.weixin.qq.com/miniprogram/dev/framework/view/animation.html)
*
* 最低基础库版本:[`2.9.0`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
clearAnimation(selector: string, callback: () => void): void
/**
* 清除关键帧动画,详见[动画](https://developers.weixin.qq.com/miniprogram/dev/framework/view/animation.html)
*
* 最低基础库版本:[`2.9.0`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
clearAnimation(
selector: string,
options: ClearAnimationOptions,
callback: () => void,
): void
}
interface ComponentOptions {
/**
* [启用多slot支持](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html#组件wxml的slot)
*/
multipleSlots?: boolean
/**
* [组件样式隔离](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html#组件样式隔离)
*/
addGlobalClass?: boolean
/**
* [组件样式隔离](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html#组件样式隔离)
*/
styleIsolation?:
| 'isolated'
| 'apply-shared'
| 'shared'
| 'page-isolated'
| 'page-apply-shared'
| 'page-shared'
/**
* [纯数据字段](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/pure-data.html) 是一些不用于界面渲染的 data 字段,可以用于提升页面更新性能。从小程序基础库版本 2.8.2 开始支持。
*/
pureDataPattern?: RegExp
}
interface TriggerEventOption {
/** 事件是否冒泡
*
* 默认值: `false`
*/
bubbles?: boolean
/** 事件是否可以穿越组件边界,为false时,事件将只能在引用组件的节点树上触发,不进入其他任何组件内部
*
* 默认值: `false`
*/
composed?: boolean
/** 事件是否拥有捕获阶段
*
* 默认值: `false`
*/
capturePhase?: boolean
}
interface RelationOption {
/** 目标组件的相对关系 */
type: 'parent' | 'child' | 'ancestor' | 'descendant'
/** 关系生命周期函数,当关系被建立在页面节点树中时触发,触发时机在组件attached生命周期之后 */
linked?(target: TrivialInstance): void
/** 关系生命周期函数,当关系在页面节点树中发生改变时触发,触发时机在组件moved生命周期之后 */
linkChanged?(target: TrivialInstance): void
/** 关系生命周期函数,当关系脱离页面节点树时触发,触发时机在组件detached生命周期之后 */
unlinked?(target: TrivialInstance): void
/** 如果这一项被设置,则它表示关联的目标节点所应具有的behavior,所有拥有这一behavior的组件节点都会被关联 */
target?: string
}
interface PageLifetimes {
/** 页面生命周期回调—监听页面显示
*
* 页面显示/切入前台时触发。
*/
show(): void
/** 页面生命周期回调—监听页面隐藏
*
* 页面隐藏/切入后台时触发。 如 `navigateTo` 或底部 `tab` 切换到其他页面,小程序切入后台等。
*/
hide(): void
/** 页面生命周期回调—监听页面尺寸变化
*
* 所在页面尺寸变化时执行
*/
resize(size: Page.IResizeOption): void
}
type DefinitionFilter = <T extends TrivialOption>(
/** 使用该 behavior 的 component/behavior 的定义对象 */
defFields: T,
/** 该 behavior 所使用的 behavior 的 definitionFilter 函数列表 */
definitionFilterArr?: DefinitionFilter[],
) => void
interface Lifetimes {
/** 组件生命周期声明对象,组件的生命周期:`created`、`attached`、`ready`、`moved`、`detached` 将收归到 `lifetimes` 字段内进行声明,原有声明方式仍旧有效,如同时存在两种声明方式,则 `lifetimes` 字段内声明方式优先级最高
*
* 最低基础库: `2.2.3` */
lifetimes: Partial<{
/**
* 在组件实例刚刚被创建时执行,注意此时不能调用 `setData`
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
created(): void
/**
* 在组件实例进入页面节点树时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
attached(): void
/**
* 在组件在视图层布局完成后执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
ready(): void
/**
* 在组件实例被移动到节点树另一个位置时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
moved(): void
/**
* 在组件实例被从页面节点树移除时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
detached(): void
/**
* 每当组件方法抛出错误时执行
*
* 最低基础库版本:[`2.4.1`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
error(err: Error): void,
}>
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 在组件实例刚刚被创建时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
created(): void
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 在组件实例进入页面节点树时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
attached(): void
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 在组件在视图层布局完成后执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
ready(): void
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 在组件实例被移动到节点树另一个位置时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
moved(): void
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 在组件实例被从页面节点树移除时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
detached(): void
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 每当组件方法抛出错误时执行
*
* 最低基础库版本:[`2.4.1`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
error(err: Error): void
}
interface OtherOption {
/** 类似于mixins和traits的组件间代码复用机制,参见 [behaviors](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/behaviors.html) */
behaviors: string[]
/**
* 组件数据字段监听器,用于监听 properties 和 data 的变化,参见 [数据监听器](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/observer.html)
*
* 最低基础库版本:[`2.6.1`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
observers: Record<string, (...args: any[]) => any>
/** 组件间关系定义,参见 [组件间关系](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/lifetimes.html) */
relations: {
[componentName: string]: RelationOption,
}
/** 组件接受的外部样式类,参见 [外部样式类](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html) */
externalClasses?: string[]
/** 组件所在页面的生命周期声明对象,参见 [组件生命周期](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/lifetimes.html)
*
* 最低基础库版本: [`2.2.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html) */
pageLifetimes?: Partial<PageLifetimes>
/** 一些选项(文档中介绍相关特性时会涉及具体的选项设置,这里暂不列举) */
options: ComponentOptions
/** 定义段过滤器,用于自定义组件扩展,参见 [自定义组件扩展](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/extend.html)
*
* 最低基础库版本: [`2.2.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html) */
definitionFilter?: DefinitionFilter
}
interface KeyFrame {
/** 关键帧的偏移,范围[0-1] */
offset?: number
/** 动画缓动函数 */
ease?: string
/** 基点位置,即 CSS transform-origin */
transformOrigin?: string
/** 背景颜色,即 CSS background-color */
backgroundColor?: string
/** 底边位置,即 CSS bottom */
bottom?: number | string
/** 高度,即 CSS height */
height?: number | string
/** 左边位置,即 CSS left */
left?: number | string
/** 宽度,即 CSS width */
width?: number | string
/** 不透明度,即 CSS opacity */
opacity?: number | string
/** 右边位置,即 CSS right */
right?: number | string
/** 顶边位置,即 CSS top */
top?: number | string
/** 变换矩阵,即 CSS transform matrix */
matrix?: number[]
/** 三维变换矩阵,即 CSS transform matrix3d */
matrix3d?: number[]
/** 旋转,即 CSS transform rotate */
rotate?: number
/** 三维旋转,即 CSS transform rotate3d */
rotate3d?: number[]
/** X 方向旋转,即 CSS transform rotateX */
rotateX?: number
/** Y 方向旋转,即 CSS transform rotateY */
rotateY?: number
/** Z 方向旋转,即 CSS transform rotateZ */
rotateZ?: number
/** 缩放,即 CSS transform scale */
scale?: number[]
/** 三维缩放,即 CSS transform scale3d */
scale3d?: number[]
/** X 方向缩放,即 CSS transform scaleX */
scaleX?: number
/** Y 方向缩放,即 CSS transform scaleY */
scaleY?: number
/** Z 方向缩放,即 CSS transform scaleZ */
scaleZ?: number
/** 倾斜,即 CSS transform skew */
skew?: number[]
/** X 方向倾斜,即 CSS transform skewX */
skewX?: number
/** Y 方向倾斜,即 CSS transform skewY */
skewY?: number
/** 位移,即 CSS transform translate */
translate?: Array<number | string>
/** 三维位移,即 CSS transform translate3d */
translate3d?: Array<number | string>
/** X 方向位移,即 CSS transform translateX */
translateX?: number | string
/** Y 方向位移,即 CSS transform translateY */
translateY?: number | string
/** Z 方向位移,即 CSS transform translateZ */
translateZ?: number | string
}
interface ClearAnimationOptions {
/** 基点位置,即 CSS transform-origin */
transformOrigin?: boolean
/** 背景颜色,即 CSS background-color */
backgroundColor?: boolean
/** 底边位置,即 CSS bottom */
bottom?: boolean
/** 高度,即 CSS height */
height?: boolean
/** 左边位置,即 CSS left */
left?: boolean
/** 宽度,即 CSS width */
width?: boolean
/** 不透明度,即 CSS opacity */
opacity?: boolean
/** 右边位置,即 CSS right */
right?: boolean
/** 顶边位置,即 CSS top */
top?: boolean
/** 变换矩阵,即 CSS transform matrix */
matrix?: boolean
/** 三维变换矩阵,即 CSS transform matrix3d */
matrix3d?: boolean
/** 旋转,即 CSS transform rotate */
rotate?: boolean
/** 三维旋转,即 CSS transform rotate3d */
rotate3d?: boolean
/** X 方向旋转,即 CSS transform rotateX */
rotateX?: boolean
/** Y 方向旋转,即 CSS transform rotateY */
rotateY?: boolean
/** Z 方向旋转,即 CSS transform rotateZ */
rotateZ?: boolean
/** 缩放,即 CSS transform scale */
scale?: boolean
/** 三维缩放,即 CSS transform scale3d */
scale3d?: boolean
/** X 方向缩放,即 CSS transform scaleX */
scaleX?: boolean
/** Y 方向缩放,即 CSS transform scaleY */
scaleY?: boolean
/** Z 方向缩放,即 CSS transform scaleZ */
scaleZ?: boolean
/** 倾斜,即 CSS transform skew */
skew?: boolean
/** X 方向倾斜,即 CSS transform skewX */
skewX?: boolean
/** Y 方向倾斜,即 CSS transform skewY */
skewY?: boolean
/** 位移,即 CSS transform translate */
translate?: boolean
/** 三维位移,即 CSS transform translate3d */
translate3d?: boolean
/** X 方向位移,即 CSS transform translateX */
translateX?: boolean
/** Y 方向位移,即 CSS transform translateY */
translateY?: boolean
/** Z 方向位移,即 CSS transform translateZ */
translateZ?: boolean
}
interface ScrollTimelineKeyframe {
composite?: 'replace' | 'add' | 'accumulate' | 'auto'
easing?: string
offset?: number | null
[property: string]: string | number | null | undefined
}
interface ScrollTimelineOption {
/** 指定滚动元素的选择器(只支持 scroll-view),该元素滚动时会驱动动画的进度 */
scrollSource: string
/** 指定滚动的方向。有效值为 horizontal 或 vertical */
orientation?: string
/** 指定开始驱动动画进度的滚动偏移量,单位 px */
startScrollOffset: number
/** 指定停止驱动动画进度的滚动偏移量,单位 px */
endScrollOffset: number
/** 起始和结束的滚动范围映射的时间长度,该时间可用于与关键帧动画里的时间 (duration) 相匹配,单位 ms */
timeRange: number
}
}
}
/** Component构造器可用于定义组件,调用Component构造器时可以指定组件的属性、数据、方法等。
*
* * 使用 `this.data` 可以获取内部数据和属性值,但不要直接修改它们,应使用 `setData` 修改。
* * 生命周期函数无法在组件方法中通过 `this` 访问到。
* * 属性名应避免以 data 开头,即不要命名成 `dataXyz` 这样的形式,因为在 WXML 中, `data-xyz=""` 会被作为节点 dataset 来处理,而不是组件属性。
* * 在一个组件的定义和使用时,组件的属性名和 data 字段相互间都不能冲突(尽管它们位于不同的定义段中)。
* * 从基础库 `2.0.9` 开始,对象类型的属性和 data 字段中可以包含函数类型的子字段,即可以通过对象类型的属性字段来传递函数。低于这一版本的基础库不支持这一特性。
* * `bug` : 对于 type 为 Object 或 Array 的属性,如果通过该组件自身的 `this.setData` 来改变属性值的一个子字段,则依旧会触发属性 observer ,且 observer 接收到的 `newVal` 是变化的那个子字段的值, `oldVal` 为空, `changedPath` 包含子字段的字段名相关信息。
*/
declare let Component: WechatMiniprogram.Component.Constructor | the_stack |
import * as FSE from 'fs-extra'
import * as path from 'path'
import { Repository } from '../../../src/models/repository'
import { setupEmptyRepository } from '../../helpers/repositories'
import { GitProcess } from '@shiftkey/dugite'
import {
createDesktopStashMessage,
createDesktopStashEntry,
getLastDesktopStashEntryForBranch,
dropDesktopStashEntry,
popStashEntry,
getStashes,
} from '../../../src/lib/git/stash'
import { getStatusOrThrow } from '../../helpers/status'
import { AppFileStatusKind } from '../../../src/models/status'
import {
IStashEntry,
StashedChangesLoadStates,
} from '../../../src/models/stash-entry'
import { generateString } from '../../helpers/random-data'
describe('git/stash', () => {
describe('getStash', () => {
let repository: Repository
let readme: string
beforeEach(async () => {
repository = await setupEmptyRepository()
readme = path.join(repository.path, 'README.md')
await FSE.writeFile(readme, '')
await GitProcess.exec(['add', 'README.md'], repository.path)
await GitProcess.exec(['commit', '-m', 'initial commit'], repository.path)
})
it('handles unborn repo by returning empty list', async () => {
const repo = await setupEmptyRepository()
const stash = await getStashes(repo)
expect(stash.desktopEntries).toHaveLength(0)
})
it('returns an empty list when no stash entries have been created', async () => {
const stash = await getStashes(repository)
expect(stash.desktopEntries).toHaveLength(0)
})
it('returns all stash entries created by Desktop', async () => {
await generateTestStashEntry(repository, 'master', false)
await generateTestStashEntry(repository, 'master', false)
await generateTestStashEntry(repository, 'master', true)
const stash = await getStashes(repository)
const entries = stash.desktopEntries
expect(entries).toHaveLength(1)
expect(entries[0].branchName).toBe('master')
expect(entries[0].name).toBe('refs/stash@{0}')
})
})
describe('createDesktopStashEntry', () => {
let repository: Repository
let readme: string
beforeEach(async () => {
repository = await setupEmptyRepository()
readme = path.join(repository.path, 'README.md')
await FSE.writeFile(readme, '')
await GitProcess.exec(['add', 'README.md'], repository.path)
await GitProcess.exec(['commit', '-m', 'initial commit'], repository.path)
})
it('creates a stash entry when repo is not unborn or in any kind of conflict or rebase state', async () => {
await FSE.appendFile(readme, 'just testing stuff')
await createDesktopStashEntry(repository, 'master', [])
const stash = await getStashes(repository)
const entries = stash.desktopEntries
expect(entries).toHaveLength(1)
expect(entries[0].branchName).toBe('master')
})
it('stashes untracked files and removes them from the working directory', async () => {
const untrackedFile = path.join(repository.path, 'not-tracked.txt')
FSE.writeFile(untrackedFile, 'some untracked file')
let status = await getStatusOrThrow(repository)
let files = status.workingDirectory.files
expect(files).toHaveLength(1)
expect(files[0].status.kind).toBe(AppFileStatusKind.Untracked)
const untrackedFiles = status.workingDirectory.files.filter(
f => f.status.kind === AppFileStatusKind.Untracked
)
await createDesktopStashEntry(repository, 'master', untrackedFiles)
status = await getStatusOrThrow(repository)
files = status.workingDirectory.files
expect(files).toHaveLength(0)
})
})
describe('getLastDesktopStashEntryForBranch', () => {
let repository: Repository
let readme: string
beforeEach(async () => {
repository = await setupEmptyRepository()
readme = path.join(repository.path, 'README.md')
await FSE.writeFile(readme, '')
await GitProcess.exec(['add', 'README.md'], repository.path)
await GitProcess.exec(['commit', '-m', 'initial commit'], repository.path)
})
it('returns null when no stash entries exist for branch', async () => {
await generateTestStashEntry(repository, 'some-other-branch', true)
const entry = await getLastDesktopStashEntryForBranch(
repository,
'master'
)
expect(entry).toBeNull()
})
it('returns last entry made for branch', async () => {
const branchName = 'master'
await generateTestStashEntry(repository, branchName, true)
await generateTestStashEntry(repository, branchName, true)
const stash = await getStashes(repository)
// entries are returned in LIFO order
const lastEntry = stash.desktopEntries[0]
const actual = await getLastDesktopStashEntryForBranch(
repository,
branchName
)
expect(actual).not.toBeNull()
expect(actual!.stashSha).toBe(lastEntry.stashSha)
})
})
describe('createDesktopStashMessage', () => {
it('creates message that matches Desktop stash entry format', () => {
const branchName = 'master'
const message = createDesktopStashMessage(branchName)
expect(message).toBe('!!GitHub_Desktop<master>')
})
})
describe('dropDesktopStashEntry', () => {
let repository: Repository
let readme: string
beforeEach(async () => {
repository = await setupEmptyRepository()
readme = path.join(repository.path, 'README.md')
await FSE.writeFile(readme, '')
await GitProcess.exec(['add', 'README.md'], repository.path)
await GitProcess.exec(['commit', '-m', 'initial commit'], repository.path)
})
it('removes the entry identified by `stashSha`', async () => {
await generateTestStashEntry(repository, 'master', true)
await generateTestStashEntry(repository, 'master', true)
let stash = await getStashes(repository)
let entries = stash.desktopEntries
expect(entries.length).toBe(2)
const stashToDelete = entries[1]
await dropDesktopStashEntry(repository, stashToDelete.stashSha)
// using this function to get stashSha since it parses
// the output from git into easy to use objects
stash = await getStashes(repository)
entries = stash.desktopEntries
expect(entries.length).toBe(1)
expect(entries[0].stashSha).not.toEqual(stashToDelete)
})
it('does not fail when attempting to delete when stash is empty', async () => {
let didFail = false
const doesNotExist: IStashEntry = {
name: 'refs/stash@{0}',
branchName: 'master',
stashSha: 'xyz',
files: { kind: StashedChangesLoadStates.NotLoaded },
}
try {
await dropDesktopStashEntry(repository, doesNotExist.stashSha)
} catch {
didFail = true
}
expect(didFail).toBe(false)
})
it("does not fail when attempting to delete stash entry that doesn't exist", async () => {
let didFail = false
const doesNotExist: IStashEntry = {
name: 'refs/stash@{4}',
branchName: 'master',
stashSha: 'xyz',
files: { kind: StashedChangesLoadStates.NotLoaded },
}
await generateTestStashEntry(repository, 'master', true)
await generateTestStashEntry(repository, 'master', true)
await generateTestStashEntry(repository, 'master', true)
try {
await dropDesktopStashEntry(repository, doesNotExist.stashSha)
} catch {
didFail = true
}
expect(didFail).toBe(false)
})
})
describe('popStashEntry', () => {
let repository: Repository
let readme: string
beforeEach(async () => {
repository = await setupEmptyRepository()
readme = path.join(repository.path, 'README.md')
await FSE.writeFile(readme, '')
await GitProcess.exec(['add', 'README.md'], repository.path)
await GitProcess.exec(['commit', '-m', 'initial commit'], repository.path)
})
describe('without any conflicts', () => {
it('restores changes back to the working directory', async () => {
await generateTestStashEntry(repository, 'master', true)
const stash = await getStashes(repository)
const { desktopEntries } = stash
expect(desktopEntries.length).toBe(1)
let status = await getStatusOrThrow(repository)
let files = status.workingDirectory.files
expect(files).toHaveLength(0)
const entryToApply = desktopEntries[0]
await popStashEntry(repository, entryToApply.stashSha)
status = await getStatusOrThrow(repository)
files = status.workingDirectory.files
expect(files).toHaveLength(1)
})
})
describe('when there are (resolvable) conflicts', () => {
it('restores changes and drops stash', async () => {
await generateTestStashEntry(repository, 'master', true)
const stash = await getStashes(repository)
const { desktopEntries } = stash
expect(desktopEntries.length).toBe(1)
const readme = path.join(repository.path, 'README.md')
await FSE.appendFile(readme, generateString())
await GitProcess.exec(
['commit', '-am', 'later commit'],
repository.path
)
let status = await getStatusOrThrow(repository)
let files = status.workingDirectory.files
expect(files).toHaveLength(0)
const entryToApply = desktopEntries[0]
await popStashEntry(repository, entryToApply.stashSha)
status = await getStatusOrThrow(repository)
files = status.workingDirectory.files
expect(files).toHaveLength(1)
const stashAfter = await getStashes(repository)
expect(stashAfter.desktopEntries).not.toContain(entryToApply)
})
})
describe('when there are unresolvable conflicts', () => {
it('throws an error', async () => {
await generateTestStashEntry(repository, 'master', true)
const stash = await getStashes(repository)
const { desktopEntries } = stash
expect(desktopEntries.length).toBe(1)
const readme = path.join(repository.path, 'README.md')
await FSE.writeFile(readme, generateString())
const entryToApply = desktopEntries[0]
await expect(
popStashEntry(repository, entryToApply.stashSha)
).rejects.toThrowError()
})
})
})
})
/**
* Creates a stash entry using `git stash push` to allow for simulating
* entries created via the CLI and Desktop
*
* @param repository the repository to create the stash entry for
* @param message passing null will similate a Desktop created stash entry
*/
async function stash(
repository: Repository,
branchName: string,
message: string | null
): Promise<void> {
const result = await GitProcess.exec(
['stash', 'push', '-m', message || createDesktopStashMessage(branchName)],
repository.path
)
if (result.exitCode !== 0) {
throw new Error(result.stderr)
}
}
async function generateTestStashEntry(
repository: Repository,
branchName: string,
simulateDesktopEntry: boolean
): Promise<void> {
const message = simulateDesktopEntry ? null : 'Should get filtered'
const readme = path.join(repository.path, 'README.md')
await FSE.appendFile(readme, generateString())
await stash(repository, branchName, message)
} | the_stack |
import {Receiver} from "../rpc";
import {
Groups,
kindIsString, RangeFilterArrayDescription,
RemoteObjectId
} from "../javaBridge";
import {FullPage, PageTitle} from "../ui/fullPage";
import {BaseReceiver, TableTargetAPI} from "../modules";
import {
add, assert, assertNever,
Converters, Exporter,
ICancellable, makeInterval,
PartialResult,
percentString, prefixSum, Two,
} from "../util";
import {AxisData, AxisKind} from "./axisData";
import {IViewSerialization, TrellisHistogramSerialization} from "../datasetView";
import {IDataView} from "../ui/dataview";
import {D3SvgElement, DragEventKind, HtmlString, Resolution} from "../ui/ui";
import {HistogramPlot} from "../ui/histogramPlot";
import {SubMenu, TopMenu} from "../ui/menu";
import {CDFPlot} from "../ui/cdfPlot";
import {
NewTargetReceiver,
DataRangesReceiver,
TrellisShape,
TrellisLayoutComputation
} from "./dataRangesReceiver";
import {BucketDialog} from "./histogramViewBase";
import {TextOverlay} from "../ui/textOverlay";
import {TrellisChartView} from "./trellisChartView";
import {event as d3event, mouse as d3mouse} from "d3-selection";
import {Dialog, saveAs} from "../ui/dialog";
import {PlottingSurface} from "../ui/plottingSurface";
import {TableMeta} from "../ui/receiver";
export class TrellisHistogramView extends TrellisChartView<Two<Groups<Groups<number>>>> {
protected hps: HistogramPlot[];
protected cdfs: CDFPlot[];
protected bucketCount: number;
protected xAxisData: AxisData;
protected cdfDot: D3SvgElement;
private readonly defaultProvenance: string = "Trellis histograms";
public constructor(
remoteObjectId: RemoteObjectId,
meta: TableMeta,
protected shape: TrellisShape,
protected samplingRate: number,
page: FullPage) {
super(remoteObjectId, meta, shape, page, "TrellisHistogram");
this.hps = [];
this.cdfs = [];
this.menu = new TopMenu( [this.exportMenu(),
{ text: "View", help: "Change the way the data is displayed.",
subMenu: new SubMenu([
{ text: "refresh",
action: () => { this.refresh(); },
help: "Redraw this view.",
},
{ text: "table",
action: () => this.showTable(
[this.xAxisData.description, this.groupByAxisData.description], this.defaultProvenance),
help: "Show the data underlying view using a table view.",
},
{ text: "exact",
action: () => this.exactHistogram(),
help: "Draw this data without making any approximations.",
},
{ text: "# buckets...",
action: () => this.chooseBuckets(),
help: "Change the number of buckets used to draw the histograms. ",
}, { text: "# groups",
action: () => this.changeGroups(),
help: "Change the number of groups."
}, { text: "correlate...",
action: () => this.chooseSecondColumn(),
help: "Draw a Trellis plot of 2-dimensional histogram using this data and another column.",
},
]) },
this.dataset.combineMenu(this, page.pageId),
]);
this.page.setMenu(this.menu);
this.createDiv("chart");
this.createDiv("summary");
}
protected createNewSurfaces(): void {
if (this.surface != null)
this.surface.destroy();
this.hps = [];
this.cdfs = [];
this.createAllSurfaces((surface) => {
const hp = new HistogramPlot(surface);
this.hps.push(hp);
const cdfp = new CDFPlot(surface);
this.cdfs.push(cdfp);
});
}
public setAxes(xAxisData: AxisData, groupByAxisData: AxisData): void {
this.xAxisData = xAxisData;
this.groupByAxisData = groupByAxisData;
}
protected doChangeGroups(groupCount: number): void {
if (groupCount == null) {
this.page.reportError("Illegal group count");
return;
}
if (groupCount === 1) {
const cds = [this.xAxisData.description!];
const rr = this.createDataQuantilesRequest(cds, this.page, "Histogram");
rr.invoke(new DataRangesReceiver(this, this.page, rr, this.meta,
[0], cds, null, "change groups",{
reusePage: true, relative: false,
chartKind: "Histogram", exact: this.samplingRate >= 1, pieChart: false
}));
} else {
const cds = [this.xAxisData.description!, this.groupByAxisData.description!];
const rr = this.createDataQuantilesRequest(cds, this.page, "TrellisHistogram");
rr.invoke(new DataRangesReceiver(this, this.page, rr, this.meta,
[0, groupCount], cds, null, "change groups", {
reusePage: true, relative: false,
chartKind: "TrellisHistogram", exact: this.samplingRate >= 1
}));
}
}
protected exactHistogram(): void {
const cds = [this.xAxisData.description!, this.groupByAxisData.description!];
const rr = this.createDataQuantilesRequest(cds, this.page, "TrellisHistogram");
rr.invoke(new DataRangesReceiver(this, this.page, rr, this.meta,
[this.bucketCount, this.shape.windowCount], cds, null, "exact counts",{
reusePage: true, relative: false,
chartKind: "TrellisHistogram", exact: true
}));
}
protected chooseBuckets(): void {
const bucketDialog = new BucketDialog(
this.bucketCount, Resolution.maxBuckets(this.page.getWidthInPixels()));
bucketDialog.setAction(() => {
const ct = bucketDialog.getBucketCount();
if (ct != null)
this.updateView(this.data, ct);
});
bucketDialog.show();
}
public chooseSecondColumn(): void {
const columns: string[] = [];
for (let i = 0; i < this.getSchema().length; i++) {
const col = this.getSchema().get(i);
if (col.name === this.xAxisData.description!.name ||
col.name === this.groupByAxisData.description!.name)
continue;
columns.push(col.name);
}
if (columns.length === 0) {
this.page.reportError("No other acceptable columns found");
return;
}
const dialog = new Dialog("Choose column",
"Select a second column to use for displaying a Trellis plot of 2D histograms.");
dialog.addColumnSelectField("column", "column", columns, null,
"The second column that will be used in addition to the one displayed here " +
"for drawing a Trellis plot of two-dimensional histogram.");
dialog.setAction(() => this.showSecondColumn(dialog.getColumnName("column")));
dialog.show();
}
protected showSecondColumn(colName: string): void {
const col = this.getSchema().find(colName)!;
const cds = [this.xAxisData.description, col, this.groupByAxisData.description];
const rr = this.createDataQuantilesRequest(cds, this.page, "Trellis2DHistogram");
rr.invoke(new DataRangesReceiver(this, this.page, rr, this.meta,
[this.bucketCount, 0, this.shape.windowCount], cds, null, this.defaultProvenance,{
reusePage: true, relative: false,
chartKind: "Trellis2DHistogram", exact: this.samplingRate >= 1
}));
}
protected export(): void {
const lines: string[] = Exporter.histogram2DAsCsv(
this.data.first, this.getSchema(), [this.xAxisData, this.groupByAxisData]);
const fileName = "trellis-histogram.csv";
saveAs(fileName, lines.join("\n"));
}
public resize(): void {
const chartSize = PlottingSurface.getDefaultChartSize(this.page.getWidthInPixels());
this.shape = TrellisLayoutComputation.resize(chartSize.width, chartSize.height, this.shape);
this.updateView(this.data, this.bucketCount);
}
public refresh(): void {
const cds = [this.xAxisData.description, this.groupByAxisData.description];
const ranges = [this.xAxisData.dataRange, this.groupByAxisData.dataRange];
const receiver = new DataRangesReceiver(this,
this.page, null, this.meta,
[this.xAxisData.bucketCount, this.groupByAxisData.bucketCount],
cds, this.page.title, null,{
chartKind: "TrellisHistogram", exact: this.samplingRate >= 1,
relative: false, reusePage: true
});
receiver.run(ranges);
receiver.finished();
}
public serialize(): IViewSerialization {
// noinspection UnnecessaryLocalVariableJS
const ser: TrellisHistogramSerialization = {
...super.serialize(),
...this.shape,
gRange: this.groupByAxisData.dataRange,
isPie: false,
bucketCount: this.bucketCount,
samplingRate: this.samplingRate,
columnDescription: this.xAxisData.description,
groupByColumn: this.groupByAxisData.description,
range: this.xAxisData.dataRange
};
return ser;
}
public static reconstruct(ser: TrellisHistogramSerialization, page: FullPage): IDataView | null {
if (ser.remoteObjectId == null || ser.rowCount == null || ser.xWindows == null ||
ser.yWindows == null || ser.windowCount === null || ser.gRange === null ||
ser.samplingRate == null || ser.schema == null || ser.range == null)
return null;
const args = this.validateSerialization(ser);
const shape = TrellisChartView.deserializeShape(ser, page);
if (args == null || shape == null)
return null;
const view = new TrellisHistogramView(ser.remoteObjectId, args, shape, ser.samplingRate, page);
view.setAxes(new AxisData(ser.columnDescription, ser.range, ser.bucketCount),
new AxisData(ser.groupByColumn, ser.gRange, ser.windowCount));
return view;
}
private static coarsen(cdf: Groups<number>, bucketCount: number): Groups<number> {
const cdfBucketCount = cdf.perBucket.length;
if (bucketCount === cdfBucketCount)
return cdf;
const buckets = [];
const bucketWidth = cdfBucketCount / bucketCount;
for (let i = 0; i < bucketCount; i++) {
let sum = 0;
const leftBoundary = i * bucketWidth - .5;
const rightBoundary = leftBoundary + bucketWidth;
for (let j = Math.ceil(leftBoundary); j < rightBoundary; j++) {
console.assert(j < cdf.perBucket.length);
sum += cdf.perBucket[j];
}
buckets.push(Math.max(sum, 0));
}
// noinspection UnnecessaryLocalVariableJS
const hist: Groups<number> = {
perBucket: buckets,
perMissing: cdf.perMissing };
return hist;
}
public updateView(data: Two<Groups<Groups<number>>>, bucketCount: number): void {
if (data == null || data.first === null || data.first.perBucket == null)
return;
const histos = data.first;
const confidences = data.second;
this.createNewSurfaces();
if (this.isPrivate()) {
const cols = [this.xAxisData.description.name, this.groupByAxisData.description.name];
const eps = this.dataset.getEpsilon(cols);
this.page.setEpsilon(eps, cols);
}
if (bucketCount !== 0)
this.bucketCount = bucketCount;
else
this.bucketCount = Math.min(Math.round(this.shape.size.width / Resolution.minBarWidth),
histos.perBucket[0].perBucket.length);
this.data = data;
const coarsened: Groups<number>[] = [];
let max = 0;
const discrete = kindIsString(this.xAxisData.description.kind) ||
this.xAxisData.description.kind === "Integer";
for (let i = 0; i < histos.perBucket.length; i++) {
const bucketData = histos.perBucket[i];
const cdfp = this.cdfs[i];
cdfp.setData(prefixSum(bucketData.perBucket.map((b) => Math.max(0, b))), discrete);
const coarse = TrellisHistogramView.coarsen(bucketData, this.bucketCount);
max = Math.max(max, Math.max(...coarse.perBucket));
coarsened.push(coarse);
}
if (histos.perMissing.perBucket.reduce(add) > 0) {
const bucketData = histos.perMissing;
const cdfp = this.cdfs[histos.perBucket.length];
cdfp.setData(prefixSum(bucketData.perBucket.map((b) => Math.max(0, b))), discrete);
const coarse = TrellisHistogramView.coarsen(bucketData, this.bucketCount);
max = Math.max(max, Math.max(...coarse.perBucket));
coarsened.push(coarse);
}
for (let i = 0; i < coarsened.length; i++) {
const plot = this.hps[i];
const confidence: Groups<number> | null =
confidences == null ? null : {
perBucket: confidences.perBucket[i].perBucket,
perMissing: confidences.perBucket[i].perMissing
};
plot.setHistogram({ first: coarsened[i], second: confidence }, this.samplingRate,
this.xAxisData,
max, this.page.dataset!.isPrivate(), this.meta.rowCount);
plot.displayAxes = false;
plot.draw();
plot.border(1);
this.cdfs[i].draw();
}
// We draw the axes after drawing the data
this.xAxisData.setResolution(this.shape.size.width, AxisKind.Bottom, PlottingSurface.bottomMargin);
// This axis is only created when the surface is drawn
const yAxis = this.hps[0].getYAxis();
this.drawAxes(this.xAxisData.axis!, yAxis);
assert(this.surface != null);
this.setupMouse();
this.pointDescription = new TextOverlay(this.surface.getCanvas(),
this.surface.getActualChartSize(),
[this.xAxisData.getName()!,
this.groupByAxisData.getName()!,
"count", "cdf"], 40);
this.cdfDot = this.surface.getChart()
.append("circle")
.attr("r", Resolution.mouseDotRadius)
.attr("fill", "blue");
this.summary!.set("rows", this.meta.rowCount, this.isPrivate());
this.summary!.setString("bar width", new HtmlString(this.xAxisData.barWidth()));
this.summary!.display();
}
protected onMouseMove(): void {
const mousePosition = this.checkMouseBounds();
if (mousePosition == null || mousePosition.plotIndex == null)
return;
assert(this.surface != null);
this.pointDescription!.show(true);
const plot = this.hps[mousePosition.plotIndex];
const xs = this.xAxisData.invert(mousePosition.x);
const value = plot.get(mousePosition.x);
const group = this.groupByAxisData.bucketDescription(mousePosition.plotIndex, 40);
const cdfPlot = this.cdfs[mousePosition.plotIndex];
// The point description is a child of the canvas, so we use canvas coordinates
const position = d3mouse(this.surface.getCanvas().node());
const cdfPos = cdfPlot.getY(mousePosition.x);
this.cdfDot.attr("cx", position[0] - this.surface.leftMargin);
this.cdfDot.attr("cy", (1 - cdfPos) * cdfPlot.getChartHeight() + this.shape.headerHeight +
mousePosition.plotYIndex * (this.shape.size.height + this.shape.headerHeight));
const perc = percentString(cdfPos);
this.pointDescription!.update([xs, group, makeInterval(value), perc], position[0], position[1]);
}
public getAxisData(event: DragEventKind): AxisData | null {
switch (event) {
case "Title":
case "GAxis":
return this.groupByAxisData;
case "XAxis":
return this.xAxisData;
case "YAxis":
// TODO
return null;
default:
assertNever(event);
}
}
protected dragMove(): boolean {
if (!super.dragMove())
return false;
const index = this.selectionIsLocal();
if (index != null) {
// Adjust the selection rectangle size to cover the whole vertical space
this.selectionRectangle
.attr("height", this.shape.size.height)
.attr("y", this.coordinates[index].y);
}
return true;
}
protected getCombineRenderer(title: PageTitle):
(page: FullPage, operation: ICancellable<RemoteObjectId>) => BaseReceiver {
return (page: FullPage, operation: ICancellable<RemoteObjectId>) => {
return new NewTargetReceiver(title, [this.xAxisData.description, this.groupByAxisData.description],
this.meta, [0, 0], page, operation, this.dataset, {
chartKind: "TrellisHistogram", relative: false,
reusePage: false, exact: this.samplingRate >= 1
});
};
}
protected filter(filter: RangeFilterArrayDescription) {
const rr = this.createFilterRequest(filter);
const title = new PageTitle(this.page.title.format, Converters.filterArrayDescription(filter));
const renderer = new NewTargetReceiver(title, [this.xAxisData.description, this.groupByAxisData.description],
this.meta, [0, 0], this.page, rr, this.dataset, {
chartKind: "TrellisHistogram", relative: false,
reusePage: false, exact: this.samplingRate >= 1
});
rr.invoke(renderer);
}
protected selectionCompleted(): void {
const local = this.selectionIsLocal();
let filter: RangeFilterArrayDescription | null;
if (local != null) {
const origin = this.canvasToChart(this.selectionOrigin!);
const left = this.position(origin.x, origin.y)!;
const end = this.canvasToChart(this.selectionEnd!);
const right = this.position(end.x, end.y)!;
filter = {
filters: [this.xAxisData.getFilter(left.x, right.x)],
complement: d3event.sourceEvent.ctrlKey,
};
} else {
filter = this.getGroupBySelectionFilter();
}
if (filter == null)
return;
this.filter(filter);
}
}
/**
* Renders a Trellis plot of 1D histograms
*/
export class TrellisHistogramReceiver extends Receiver<Two<Groups<Groups<number>>>> {
protected trellisView: TrellisHistogramView;
constructor(title: PageTitle,
page: FullPage,
remoteTable: TableTargetAPI,
protected meta: TableMeta,
protected axes: AxisData[],
protected bucketCount: number,
protected samplingRate: number,
protected shape: TrellisShape,
operation: ICancellable<Two<Groups<Groups<number>>>>,
protected reusePage: boolean) {
super(reusePage ? page : page.dataset!.newPage(title, page), operation, "histogram");
this.trellisView = new TrellisHistogramView(
remoteTable.getRemoteObjectId()!, meta,
this.shape, this.samplingRate, this.page);
this.trellisView.setAxes(axes[0], axes[1]);
}
public onNext(value: PartialResult<Two<Groups<Groups<number>>>>): void {
super.onNext(value);
if (value == null || value.data == null) {
return;
}
this.trellisView.updateView(value.data, this.bucketCount);
}
public onCompleted(): void {
super.onCompleted();
this.trellisView.updateCompleted(this.elapsedMilliseconds());
}
} | the_stack |
import { OidcClientSettingsStore } from "./OidcClientSettings";
import type { StateStore } from "./StateStore";
describe("OidcClientSettings", () => {
describe("client_id", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
});
// assert
expect(subject.client_id).toEqual("client");
});
});
describe("client_secret", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
client_secret: "secret",
});
// assert
expect(subject.client_secret).toEqual("secret");
});
});
describe("response_type", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
response_type: "foo",
});
// assert
expect(subject.response_type).toEqual("foo");
});
it("should use default value", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
});
// assert
expect(subject.response_type).toEqual("code");
});
});
describe("scope", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
scope: "foo",
});
// assert
expect(subject.scope).toEqual("foo");
});
it("should use default value", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
});
// assert
expect(subject.scope).toEqual("openid");
});
});
describe("redirect_uri", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "http://app",
});
// assert
expect(subject.redirect_uri).toEqual("http://app");
});
});
describe("post_logout_redirect_uri", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
post_logout_redirect_uri: "http://app/loggedout",
});
// assert
expect(subject.post_logout_redirect_uri).toEqual("http://app/loggedout");
});
});
describe("prompt", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
prompt: "foo",
});
// assert
expect(subject.prompt).toEqual("foo");
});
});
describe("display", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
display: "foo",
});
// assert
expect(subject.display).toEqual("foo");
});
});
describe("max_age", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
max_age: 22,
});
// assert
expect(subject.max_age).toEqual(22);
});
});
describe("ui_locales", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
ui_locales: "foo",
});
// assert
expect(subject.ui_locales).toEqual("foo");
});
});
describe("acr_values", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
acr_values: "foo",
});
// assert
expect(subject.acr_values).toEqual("foo");
});
});
describe("resource", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
resource: "foo",
});
// assert
expect(subject.resource).toEqual("foo");
});
});
describe("response_mode", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
response_mode: "query",
});
// assert
expect(subject.response_mode).toEqual("query");
});
});
describe("authority", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
client_id: "client",
redirect_uri: "redirect",
authority: "http://sts",
});
// assert
expect(subject.authority).toEqual("http://sts");
});
});
describe("metadataUrl", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
metadataUrl: "http://sts/metadata",
});
// assert
expect(subject.metadataUrl).toEqual("http://sts/metadata");
});
});
describe("metadata", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
metadata: { issuer: "test" },
});
// assert
expect(subject.metadata).toEqual({ issuer: "test" });
});
});
describe("signingKeys", () => {
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
signingKeys: [{ kid: "test" }],
});
// assert
expect(subject.signingKeys).toEqual([{ kid: "test" }]);
});
});
describe("filterProtocolClaims", () => {
it("should use default value", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
});
// assert
expect(subject.filterProtocolClaims).toEqual(true);
});
it("should return value from initial settings", () => {
// act
let subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
filterProtocolClaims: true,
});
// assert
expect(subject.filterProtocolClaims).toEqual(true);
// act
subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
filterProtocolClaims: false,
});
// assert
expect(subject.filterProtocolClaims).toEqual(false);
});
});
describe("loadUserInfo", () => {
it("should use default value", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
});
// assert
expect(subject.loadUserInfo).toEqual(false);
});
it("should return value from initial settings", () => {
// act
let subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
loadUserInfo: true,
});
// assert
expect(subject.loadUserInfo).toEqual(true);
// act
subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
loadUserInfo: false,
});
// assert
expect(subject.loadUserInfo).toEqual(false);
});
});
describe("staleStateAge", () => {
it("should use default value", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
});
// assert
expect(subject.staleStateAgeInSeconds).toEqual(900);
});
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
staleStateAgeInSeconds: 100,
});
// assert
expect(subject.staleStateAgeInSeconds).toEqual(100);
});
});
describe("clockSkew", () => {
it("should use default value", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
});
// assert
expect(subject.clockSkewInSeconds).toEqual(5 * 60); // 5 mins
});
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
clockSkewInSeconds: 10,
});
// assert
expect(subject.clockSkewInSeconds).toEqual(10);
});
});
describe("stateStore", () => {
it("should return value from initial settings", () => {
// arrange
const temp = {} as StateStore;
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
stateStore: temp,
});
// assert
expect(subject.stateStore).toEqual(temp);
});
});
describe("stateStore", () => {
it("should return value from initial settings", () => {
// arrange
const temp = {} as StateStore;
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
stateStore: temp,
});
// assert
expect(subject.stateStore).toEqual(temp);
});
});
describe("extraQueryParams", () => {
it("should use default value", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
});
// assert
expect(subject.extraQueryParams).toEqual({});
});
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
extraQueryParams: {
"hd": "domain.com",
},
});
// assert
expect(subject.extraQueryParams).toEqual({ "hd": "domain.com" });
});
});
describe("extraTokenParams", () => {
it("should use default value", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
});
// assert
expect(subject.extraTokenParams).toEqual({});
});
it("should return value from initial settings", () => {
// act
const subject = new OidcClientSettingsStore({
authority: "authority",
client_id: "client",
redirect_uri: "redirect",
extraTokenParams: {
"resourceServer": "abc",
},
});
// assert
expect(subject.extraTokenParams).toEqual({ "resourceServer": "abc" });
});
});
}); | the_stack |
import Page = require('../../../base/Page');
import Response = require('../../../http/response');
import V1 = require('../V1');
import { SerializableClass } from '../../../interfaces';
type SmsCommandDirection = 'to_sim'|'from_sim';
type SmsCommandStatus = 'queued'|'sent'|'delivered'|'received'|'failed';
/**
* Initialize the SmsCommandList
*
* PLEASE NOTE that this class contains beta products that are subject to change.
* Use them with caution.
*
* @param version - Version of the resource
*/
declare function SmsCommandList(version: V1): SmsCommandListInstance;
interface SmsCommandListInstance {
/**
* @param sid - sid of instance
*/
(sid: string): SmsCommandContext;
/**
* create a SmsCommandInstance
*
* @param opts - Options for request
* @param callback - Callback to handle processed record
*/
create(opts: SmsCommandListInstanceCreateOptions, callback?: (error: Error | null, item: SmsCommandInstance) => any): Promise<SmsCommandInstance>;
/**
* Streams SmsCommandInstance records from the API.
*
* This operation lazily loads records as efficiently as possible until the limit
* is reached.
*
* The results are passed into the callback function, so this operation is memory
* efficient.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Function to process each record
*/
each(callback?: (item: SmsCommandInstance, done: (err?: Error) => void) => void): void;
/**
* Streams SmsCommandInstance records from the API.
*
* This operation lazily loads records as efficiently as possible until the limit
* is reached.
*
* The results are passed into the callback function, so this operation is memory
* efficient.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Function to process each record
*/
each(opts?: SmsCommandListInstanceEachOptions, callback?: (item: SmsCommandInstance, done: (err?: Error) => void) => void): void;
/**
* Constructs a sms_command
*
* @param sid - The SID that identifies the resource to fetch
*/
get(sid: string): SmsCommandContext;
/**
* Retrieve a single target page of SmsCommandInstance records from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
getPage(callback?: (error: Error | null, items: SmsCommandPage) => any): Promise<SmsCommandPage>;
/**
* Retrieve a single target page of SmsCommandInstance records from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param targetUrl - API-generated URL for the requested results page
* @param callback - Callback to handle list of records
*/
getPage(targetUrl?: string, callback?: (error: Error | null, items: SmsCommandPage) => any): Promise<SmsCommandPage>;
/**
* Lists SmsCommandInstance records from the API as a list.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
list(callback?: (error: Error | null, items: SmsCommandInstance[]) => any): Promise<SmsCommandInstance[]>;
/**
* Lists SmsCommandInstance records from the API as a list.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Callback to handle list of records
*/
list(opts?: SmsCommandListInstanceOptions, callback?: (error: Error | null, items: SmsCommandInstance[]) => any): Promise<SmsCommandInstance[]>;
/**
* Retrieve a single page of SmsCommandInstance records from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
page(callback?: (error: Error | null, items: SmsCommandPage) => any): Promise<SmsCommandPage>;
/**
* Retrieve a single page of SmsCommandInstance records from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Callback to handle list of records
*/
page(opts?: SmsCommandListInstancePageOptions, callback?: (error: Error | null, items: SmsCommandPage) => any): Promise<SmsCommandPage>;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
/**
* Options to pass to create
*
* @property callbackMethod - The HTTP method we should use to call callback_url
* @property callbackUrl - The URL we should call after we have sent the command
* @property payload - The message body of the SMS Command
* @property sim - The sid or unique_name of the SIM to send the SMS Command to
*/
interface SmsCommandListInstanceCreateOptions {
callbackMethod?: string;
callbackUrl?: string;
payload: string;
sim: string;
}
/**
* Options to pass to each
*
* @property callback -
* Function to process each record. If this and a positional
* callback are passed, this one will be used
* @property direction - The direction of the SMS Command
* @property done - Function to be called upon completion of streaming
* @property limit -
* Upper limit for the number of records to return.
* each() guarantees never to return more than limit.
* Default is no limit
* @property pageSize -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no pageSize is defined but a limit is defined,
* each() will attempt to read the limit with the most efficient
* page size, i.e. min(limit, 1000)
* @property sim - The SID or unique name of the Sim resource that SMS Command was sent to or from.
* @property status - The status of the SMS Command
*/
interface SmsCommandListInstanceEachOptions {
callback?: (item: SmsCommandInstance, done: (err?: Error) => void) => void;
direction?: SmsCommandDirection;
done?: Function;
limit?: number;
pageSize?: number;
sim?: string;
status?: SmsCommandStatus;
}
/**
* Options to pass to list
*
* @property direction - The direction of the SMS Command
* @property limit -
* Upper limit for the number of records to return.
* list() guarantees never to return more than limit.
* Default is no limit
* @property pageSize -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no page_size is defined but a limit is defined,
* list() will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @property sim - The SID or unique name of the Sim resource that SMS Command was sent to or from.
* @property status - The status of the SMS Command
*/
interface SmsCommandListInstanceOptions {
direction?: SmsCommandDirection;
limit?: number;
pageSize?: number;
sim?: string;
status?: SmsCommandStatus;
}
/**
* Options to pass to page
*
* @property direction - The direction of the SMS Command
* @property pageNumber - Page Number, this value is simply for client state
* @property pageSize - Number of records to return, defaults to 50
* @property pageToken - PageToken provided by the API
* @property sim - The SID or unique name of the Sim resource that SMS Command was sent to or from.
* @property status - The status of the SMS Command
*/
interface SmsCommandListInstancePageOptions {
direction?: SmsCommandDirection;
pageNumber?: number;
pageSize?: number;
pageToken?: string;
sim?: string;
status?: SmsCommandStatus;
}
interface SmsCommandPayload extends SmsCommandResource, Page.TwilioResponsePayload {
}
interface SmsCommandResource {
account_sid: string;
date_created: Date;
date_updated: Date;
direction: SmsCommandDirection;
payload: string;
sid: string;
sim_sid: string;
status: SmsCommandStatus;
url: string;
}
interface SmsCommandSolution {
}
declare class SmsCommandContext {
/**
* Initialize the SmsCommandContext
*
* PLEASE NOTE that this class contains beta products that are subject to change.
* Use them with caution.
*
* @param version - Version of the resource
* @param sid - The SID that identifies the resource to fetch
*/
constructor(version: V1, sid: string);
/**
* fetch a SmsCommandInstance
*
* @param callback - Callback to handle processed record
*/
fetch(callback?: (error: Error | null, items: SmsCommandInstance) => any): Promise<SmsCommandInstance>;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
declare class SmsCommandInstance extends SerializableClass {
/**
* Initialize the SmsCommandContext
*
* PLEASE NOTE that this class contains beta products that are subject to change.
* Use them with caution.
*
* @param version - Version of the resource
* @param payload - The instance payload
* @param sid - The SID that identifies the resource to fetch
*/
constructor(version: V1, payload: SmsCommandPayload, sid: string);
private _proxy: SmsCommandContext;
accountSid: string;
dateCreated: Date;
dateUpdated: Date;
direction: SmsCommandDirection;
/**
* fetch a SmsCommandInstance
*
* @param callback - Callback to handle processed record
*/
fetch(callback?: (error: Error | null, items: SmsCommandInstance) => any): Promise<SmsCommandInstance>;
payload: string;
sid: string;
simSid: string;
status: SmsCommandStatus;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
url: string;
}
declare class SmsCommandPage extends Page<V1, SmsCommandPayload, SmsCommandResource, SmsCommandInstance> {
/**
* Initialize the SmsCommandPage
*
* PLEASE NOTE that this class contains beta products that are subject to change.
* Use them with caution.
*
* @param version - Version of the resource
* @param response - Response from the API
* @param solution - Path solution
*/
constructor(version: V1, response: Response<string>, solution: SmsCommandSolution);
/**
* Build an instance of SmsCommandInstance
*
* @param payload - Payload response from the API
*/
getInstance(payload: SmsCommandPayload): SmsCommandInstance;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
export { SmsCommandContext, SmsCommandDirection, SmsCommandInstance, SmsCommandList, SmsCommandListInstance, SmsCommandListInstanceCreateOptions, SmsCommandListInstanceEachOptions, SmsCommandListInstanceOptions, SmsCommandListInstancePageOptions, SmsCommandPage, SmsCommandPayload, SmsCommandResource, SmsCommandSolution, SmsCommandStatus } | the_stack |
import {
DeflateWorker,
DeflateWorkerAction,
DeflateWorkerListener,
} from '../src/domain/segmentCollection/deflateWorker'
import {
IncrementalSource,
MutationPayload,
MutationData,
ElementNode,
NodeType,
SerializedNode,
SerializedNodeWithId,
TextNode,
} from '../src/domain/record/types'
import { FullSnapshotRecord, IncrementalSnapshotRecord, MetaRecord, RecordType, Segment } from '../src/types'
export class MockWorker implements DeflateWorker {
readonly pendingMessages: DeflateWorkerAction[] = []
private rawSize = 0
private deflatedData: Uint8Array[] = []
private listeners: {
message: DeflateWorkerListener[]
error: Array<(error: unknown) => void>
} = { message: [], error: [] }
addEventListener(eventName: 'message', listener: DeflateWorkerListener): void
addEventListener(eventName: 'error', listener: (error: ErrorEvent) => void): void
addEventListener(eventName: 'message' | 'error', listener: any): void {
const index = this.listeners[eventName].indexOf(listener)
if (index < 0) {
this.listeners[eventName].push(listener)
}
}
removeEventListener(eventName: 'message', listener: DeflateWorkerListener): void
removeEventListener(eventName: 'error', listener: (error: ErrorEvent) => void): void
removeEventListener(eventName: 'message' | 'error', listener: any): void {
const index = this.listeners[eventName].indexOf(listener)
if (index >= 0) {
this.listeners[eventName].splice(index, 1)
}
}
postMessage(message: DeflateWorkerAction): void {
this.pendingMessages.push(message)
}
terminate(): void {
// do nothing
}
get pendingData() {
return this.pendingMessages.map((message) => ('data' in message ? message.data : '')).join('')
}
get messageListenersCount() {
return this.listeners.message.length
}
processAllMessages(): void {
while (this.pendingMessages.length) {
this.processNextMessage()
}
}
dropNextMessage(): void {
this.pendingMessages.shift()
}
processNextMessage(): void {
const message = this.pendingMessages.shift()
if (message) {
switch (message.action) {
case 'init':
this.listeners.message.forEach((listener) =>
listener({
data: {
type: 'initialized',
},
})
)
break
case 'write':
{
const additionalRawSize = this.pushData(message.data)
this.listeners.message.forEach((listener) =>
listener({
data: {
type: 'wrote',
id: message.id,
compressedSize: uint8ArraysSize(this.deflatedData),
additionalRawSize,
},
})
)
}
break
case 'flush':
{
const additionalRawSize = this.pushData(message.data)
this.listeners.message.forEach((listener) =>
listener({
data: {
type: 'flushed',
id: message.id,
result: mergeUint8Arrays(this.deflatedData),
rawSize: this.rawSize,
additionalRawSize,
},
})
)
this.deflatedData.length = 0
this.rawSize = 0
}
break
}
}
}
dispatchErrorEvent() {
const error = new ErrorEvent('worker')
this.listeners.error.forEach((listener) => listener(error))
}
dispatchErrorMessage(error: Error | string) {
this.listeners.message.forEach((listener) => listener({ data: { type: 'errored', error } }))
}
private pushData(data?: string) {
const encodedData = new TextEncoder().encode(data)
this.rawSize += encodedData.length
// In the mock worker, for simplicity, we'll just use the UTF-8 encoded string instead of deflating it.
this.deflatedData.push(encodedData)
return encodedData.length
}
}
function uint8ArraysSize(arrays: Uint8Array[]) {
return arrays.reduce((sum, bytes) => sum + bytes.length, 0)
}
function mergeUint8Arrays(arrays: Uint8Array[]) {
const result = new Uint8Array(uint8ArraysSize(arrays))
let offset = 0
for (const bytes of arrays) {
result.set(bytes, offset)
offset += bytes.byteLength
}
return result
}
export function parseSegment(bytes: Uint8Array) {
return JSON.parse(new TextDecoder().decode(bytes)) as Segment
}
export function collectAsyncCalls<F extends jasmine.Func>(spy: jasmine.Spy<F>) {
return {
waitAsyncCalls: (expectedCallsCount: number, callback: (calls: jasmine.Calls<F>) => void) => {
if (spy.calls.count() === expectedCallsCount) {
callback(spy.calls)
} else if (spy.calls.count() > expectedCallsCount) {
fail('Unexpected extra call')
} else {
spy.and.callFake((() => {
if (spy.calls.count() === expectedCallsCount) {
callback(spy.calls)
}
}) as F)
}
},
expectNoExtraAsyncCall: (done: () => void) => {
spy.and.callFake((() => {
fail('Unexpected extra call')
}) as F)
setTimeout(done, 300)
},
}
}
// Returns the first MetaRecord in a Segment, if any.
export function findMeta(segment: Segment): MetaRecord | null {
return segment.records.find((record) => record.type === RecordType.Meta) as MetaRecord
}
// Returns the first FullSnapshotRecord in a Segment, if any.
export function findFullSnapshot(segment: Segment): FullSnapshotRecord | null {
return segment.records.find((record) => record.type === RecordType.FullSnapshot) as FullSnapshotRecord
}
// Returns the first IncrementalSnapshotRecord of a given source in a Segment, if any.
export function findIncrementalSnapshot(segment: Segment, source: IncrementalSource): IncrementalSnapshotRecord | null {
return segment.records.find(
(record) => record.type === RecordType.IncrementalSnapshot && record.data.source === source
) as IncrementalSnapshotRecord
}
// Returns all the IncrementalSnapshotRecord of a given source in a Segment, if any.
export function findAllIncrementalSnapshots(segment: Segment, source: IncrementalSource): IncrementalSnapshotRecord[] {
return segment.records.filter(
(record) => record.type === RecordType.IncrementalSnapshot && record.data.source === source
) as IncrementalSnapshotRecord[]
}
// Returns the textContent of a ElementNode, if any.
export function findTextContent(elem: ElementNode): string | null {
const text = elem.childNodes.find((child) => child.type === NodeType.Text) as TextNode
return text ? text.textContent : null
}
// Returns the first ElementNode with the given ID attribute contained in a node, if any.
export function findElementWithIdAttribute(root: SerializedNodeWithId, id: string) {
return findElement(root, (node) => node.attributes.id === id)
}
// Returns the first ElementNode with the given tag name contained in a node, if any.
export function findElementWithTagName(root: SerializedNodeWithId, tagName: string) {
return findElement(root, (node) => node.tagName === tagName)
}
// Returns the first TextNode with the given content contained in a node, if any.
export function findTextNode(root: SerializedNodeWithId, textContent: string) {
return findNode(root, (node) => isTextNode(node) && node.textContent === textContent) as
| (TextNode & { id: number })
| null
}
// Returns the first ElementNode matching the predicate
export function findElement(root: SerializedNodeWithId, predicate: (node: ElementNode) => boolean) {
return findNode(root, (node) => isElementNode(node) && predicate(node)) as (ElementNode & { id: number }) | null
}
// Returns the first SerializedNodeWithId matching the predicate
export function findNode(
node: SerializedNodeWithId,
predicate: (node: SerializedNodeWithId) => boolean
): SerializedNodeWithId | null {
if (predicate(node)) {
return node
}
if ('childNodes' in node) {
for (const child of node.childNodes) {
const node = findNode(child, predicate)
if (node !== null) {
return node
}
}
}
return null
}
function isElementNode(node: SerializedNode): node is ElementNode {
return node.type === NodeType.Element
}
function isTextNode(node: SerializedNode): node is TextNode {
return node.type === NodeType.Text
}
interface NodeSelector {
// Select the first node with the given tag name from the initial full snapshot
tag?: string
// Select the first node with the given id attribute from the initial full snapshot
idAttribute?: string
// Select the first node with the given text content from the initial full snapshot
text?: string
}
interface ExpectedTextMutation {
// Reference to the node where the mutation happens
node: ExpectedNode
// New text value
value: string
}
interface ExpectedAttributeMutation {
// Reference to the node where the mutation happens
node: ExpectedNode
// Updated attributes
attributes: {
[key: string]: string | null
}
}
interface ExpectedRemoveMutation {
// Reference to the removed node
node: ExpectedNode
// Reference to the parent of the removed node
parent: ExpectedNode
}
interface ExpectedAddMutation {
// Partially check for the added node properties.
node: ExpectedNode
// Reference to the parent of the added node
parent: ExpectedNode
// Reference to the sibling of the added node
next?: ExpectedNode
}
interface ExpectedMutationsPayload {
texts?: ExpectedTextMutation[]
attributes?: ExpectedAttributeMutation[]
removes?: ExpectedRemoveMutation[]
adds?: ExpectedAddMutation[]
}
/**
* ExpectedNode is a helper class to build a serialized Node tree to be used to validate mutations.
* For now, its purpose is limited to specifying child nodes.
*/
class ExpectedNode {
constructor(private node: Omit<SerializedNodeWithId, 'childNodes'> & { childNodes?: ExpectedNode[] }) {}
withChildren(...childNodes: ExpectedNode[]): ExpectedNode {
return new ExpectedNode({ ...this.node, childNodes })
}
getId() {
return this.node.id
}
toSerializedNodeWithId() {
const { childNodes, ...result } = this.node
if (childNodes) {
;(result as any).childNodes = childNodes.map((node) => node.toSerializedNodeWithId())
}
return result as SerializedNodeWithId
}
}
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>
/**
* Based on an serialized initial document, it returns:
*
* * a set of utilities functions to expect nodes by selecting initial nodes from the initial
* document (expectInitialNode) or creating new nodes (expectNewNode)
*
* * a 'validate' function to actually validate a mutation payload against an expected mutation
* object.
*/
export function createMutationPayloadValidator(initialDocument: SerializedNodeWithId) {
let maxNodeId = findMaxNodeId(initialDocument)
/**
* Creates a new node based on input parameter, with sensible default properties, and an
* automatically computed 'id' attribute based on the previously created nodes.
*/
function expectNewNode(node: Optional<ElementNode, 'childNodes' | 'attributes'>): ExpectedNode
function expectNewNode(node: TextNode): ExpectedNode
function expectNewNode(node: Partial<SerializedNode>) {
maxNodeId += 1
if (node.type === NodeType.Element) {
node.attributes ||= {}
node.childNodes = []
}
return new ExpectedNode({
...node,
id: maxNodeId,
} as any)
}
return {
/**
* Validates the mutation payload against the expected text, attribute, add and remove mutations.
*/
validate: (payload: MutationPayload, expected: ExpectedMutationsPayload) => {
payload = removeUndefinedValues(payload)
expect(payload.adds).toEqual(
(expected.adds || []).map(({ node, parent, next }) => ({
node: node.toSerializedNodeWithId(),
parentId: parent.getId(),
nextId: next ? next.getId() : null,
}))
)
expect(payload.texts).toEqual((expected.texts || []).map(({ node, value }) => ({ id: node.getId(), value })))
expect(payload.removes).toEqual(
(expected.removes || []).map(({ node, parent }) => ({
id: node.getId(),
parentId: parent.getId(),
}))
)
expect(payload.attributes).toEqual(
(expected.attributes || []).map(({ node, attributes }) => ({
id: node.getId(),
attributes,
}))
)
},
expectNewNode,
/**
* Selects a node from the initially serialized document. Nodes can be selected via their 'tag'
* name, 'id' attribute or 'text' content.
*/
expectInitialNode: (selector: NodeSelector) => {
let node
if (selector.text) {
node = findTextNode(initialDocument, selector.text)
} else if (selector.idAttribute) {
node = findElementWithIdAttribute(initialDocument, selector.idAttribute)
} else if (selector.tag) {
node = findElementWithTagName(initialDocument, selector.tag)
} else {
throw new Error('Empty selector')
}
if (!node) {
throw new Error(`Cannot find node from selector ${JSON.stringify(selector)}`)
}
if ('childNodes' in node) {
node = { ...node, childNodes: [] }
}
return new ExpectedNode(removeUndefinedValues(node))
},
}
function findMaxNodeId(root: SerializedNodeWithId): number {
if ('childNodes' in root) {
return Math.max(root.id, ...root.childNodes.map((child) => findMaxNodeId(child)))
}
return root.id
}
/**
* When serializing a Node, some properties like 'isSVG' may be undefined, and they are not
* sent to the intake.
*
* To be able to validate mutations from E2E and Unit tests, we prefer to keep a single
* format. Thus, we serialize and deserialize objects to drop undefined
* properties, so they don't interferes during unit tests.
*/
function removeUndefinedValues<T>(object: T) {
return JSON.parse(JSON.stringify(object)) as T
}
}
/**
* Validate the first and only mutation record of a segment against the expected text, attribute,
* add and remove mutations.
*/
export function createMutationPayloadValidatorFromSegment(segment: Segment) {
const fullSnapshot = findFullSnapshot(segment)!
expect(fullSnapshot).toBeTruthy()
const mutations = findAllIncrementalSnapshots(segment, IncrementalSource.Mutation) as Array<{
data: MutationData
}>
expect(mutations.length).toBe(1)
const mutationPayloadValidator = createMutationPayloadValidator(fullSnapshot.data.node)
return {
...mutationPayloadValidator,
validate: (expected: ExpectedMutationsPayload) => mutationPayloadValidator.validate(mutations[0].data, expected),
}
} | the_stack |
import * as monaco from "monaco-editor";
import * as markdownit from "markdown-it";
import * as ACDesigner from "adaptivecards-designer";
import * as ACTemplating from "adaptivecards-templating";
import "adaptivecards-designer/src/adaptivecards-designer.css";
import "./app.css";
// Uncomment below if you plan to use an empty hostContainers array
// import "adaptivecards-designer/dist/adaptivecards-defaulthost.css";
window.onload = function () {
ACTemplating.GlobalSettings.getUndefinedFieldValueSubstitutionString = (path: string) => { return "<" + path + " is undefined>" };
ACDesigner.GlobalSettings.showVersionPicker = true;
ACDesigner.GlobalSettings.enableDataBindingSupport = true;
ACDesigner.GlobalSettings.showDataStructureToolbox = false;
ACDesigner.GlobalSettings.showSampleDataEditorToolbox = true;
// Uncomment to configure default toolbox titles
/*
ACDesigner.Strings.toolboxes.cardEditor.title = "Custom title";
ACDesigner.Strings.toolboxes.cardStructure.title = "Custom title";
ACDesigner.Strings.toolboxes.dataStructure.title = "Custom title";
ACDesigner.Strings.toolboxes.propertySheet.title = "Custom title";
ACDesigner.Strings.toolboxes.sampleDataEditor.title = "Custom title";
ACDesigner.Strings.toolboxes.toolPalette.title = "Custom title";
*/
// Uncomment to configure pic2card service
/*
ACDesigner.Pic2Card.pic2cardService = "https://<<your-pic2Card-service-endpoint>>";
*/
// To Configure path for pic2card image usage policy
/*
ACDesigner.Pic2Card.privacyLink = "../myPath/privacy";
*/
ACDesigner.CardDesigner.onProcessMarkdown = (text: string, result: { didProcess: boolean, outputHtml: string }) => {
result.outputHtml = new markdownit().render(text);
result.didProcess = true;
}
if (!ACDesigner.SettingsManager.isLocalStorageAvailable) {
console.log("Local storage is not available.");
}
// Uncomment to disable (de)serialization of a specific property
/*
Adaptive.CardElement.requiresProperty.isSerializationEnabled = false;
*/
// Uncomment to add/remove properties to/from the designer's property sheet
/*
ACDesigner.DesignerPeer.onPopulatePropertySheet = (sender: ACDesigner.DesignerPeer, propertySheet: ACDesigner.PropertySheet) => {
if (sender instanceof ACDesigner.TextBlockPeer) {
propertySheet.remove(ACDesigner.TextBlockPeer.maxLinesProperty);
}
}
*/
let designer = new ACDesigner.CardDesigner(
ACDesigner.defaultMicrosoftHosts,
ACDesigner.defaultMicrosoftDeviceEmulations
);
designer.sampleCatalogueUrl = window.location.origin + "/sample-catalogue.json";
designer.attachTo(document.getElementById("designerRootHost"));
/* Uncomment to test a custom palette item example
let exampleSnippet = new ACDesigner.SnippetPaletteItem("Custom", "Example");
exampleSnippet.snippet = {
type: "ColumnSet",
columns: [
{
width: "auto",
items: [
{
type: "Image",
size: "Small",
style: "Person",
url: "https://matthidinger.com/images/bio-photo.jpg"
}
]
},
{
width: "stretch",
items: [
{
type: "TextBlock",
text: "John Doe",
weight: "Bolder",
wrap: true
},
{
type: "TextBlock",
spacing: "None",
text: "Additional information",
wrap: true
}
]
}
]
};
designer.customPaletteItems = [ exampleSnippet ];
*/
designer.monacoModuleLoaded(monaco);
let sampleData = {
title: "Publish Adaptive Card Schema",
description: "Now that we have defined the main rules and features of the format, we need to produce a schema and publish it to GitHub. The schema will be the starting point of our reference documentation.",
creator: {
name: "Matt Hidinger",
profileImage: "https://matthidinger.com/images/bio-photo.jpg"
},
createdUtc: "2017-02-14T06:08:39Z",
viewUrl: "https://adaptivecards.io",
properties: [
{ key: "Board", value: "Adaptive Cards" },
{ key: "List", value: "Backlog" },
{ key: "Assigned to", value: "Matt Hidinger" },
{ key: "Due date", value: "Not set" }
]
};
let sampleDataStructure: ACDesigner.IData = {
valueType: "Object",
fields: [
{
name: "title",
displayName: "Title",
valueType: "String",
sampleValue: "Publish Adaptive Card Schema"
},
{
name: "description",
displayName: "Description",
valueType: "String",
sampleValue: "Now that we have defined the main rules and features of the format, we need to produce a schema and publish it to GitHub. The schema will be the starting point of our reference documentation."
},
{
name: "creator",
displayName: "Creator",
valueType: "Object",
fields: [
{
name: "name",
displayName: "Name",
valueType: "String",
sampleValue: "Matt Hidinger"
},
{
name: "profileImage",
displayName: "Profile image URL",
valueType: "String",
sampleValue: "https://matthidinger.com/images/bio-photo.jpg"
}
]
},
{
name: "createdUtc",
displayName: "Date created",
valueType: "String",
sampleValue: "2017-02-14T06:08:39Z"
},
{
name: "viewUrl",
displayName: "View URL",
valueType: "String",
sampleValue: "https://adaptivecards.io"
},
{
name: "properties",
displayName: "Properties",
valueType: "Array",
itemType: {
valueType: "Object",
fields: [
{
name: "key",
displayName: "Key",
valueType: "String",
sampleValue: "Sample key"
},
{
name: "value",
displayName: "Value",
valueType: "String",
sampleValue: "Sample value"
}
]
}
}
]
};
/*
let sampleData = {
firstName: "John",
lastName: "Doe",
age: 45,
isMarried: true,
address: {
street: "1234 555th Ave NE",
city: "Redmond",
state: "WA",
countryOrRegion: "USA"
},
children: [
{
firstName: "Jennifer",
lastName: "Doe",
age: 9
},
{
firstName: "James",
lastName: "Doe",
age: 13
}
]
};
let sampleDataStructure: ACDesigner.IData = {
valueType: "Object",
fields: [
{
name: "firstName",
displayName: "First name",
valueType: "String",
sampleValue: "John"
},
{
name: "lastName",
displayName: "Last name",
valueType: "String",
sampleValue: "Doe"
},
{
name: "age",
displayName: "Age",
valueType: "Number",
sampleValue: 36
},
{
name: "isMarried",
displayName: "Married",
valueType: "Boolean",
sampleValue: false
},
{
name: "address",
displayName: "Address",
valueType: "Object",
fields: [
{
name: "street",
displayName: "Street",
valueType: "String",
sampleValue: "1234 555th Ave NE"
},
{
name: "city",
displayName: "City",
valueType: "String",
sampleValue: "Redmond"
},
{
name: "state",
displayName: "State",
valueType: "String",
sampleValue: "WA"
},
{
name: "countryOrRegion",
displayName: "Country/region",
valueType: "String",
sampleValue: "USA"
}
]
},
{
name: "children",
displayName: "Children",
valueType: "Array",
itemType: {
valueType: "Object",
fields: [
{
name: "firstName",
displayName: "First name",
valueType: "String",
sampleValue: "Jennifer"
},
{
name: "lastName",
displayName: "Last name",
valueType: "String",
sampleValue: "Doe"
},
{
name: "age",
displayName: "Age",
valueType: "Number",
sampleValue: 13
}
]
}
}
]
};
*/
designer.dataStructure = ACDesigner.FieldDefinition.parse(sampleDataStructure);
// designer.lockDataStructure = true;
designer.sampleData = sampleData;
designer.bindingPreviewMode = ACDesigner.BindingPreviewMode.SampleData;
} | the_stack |
import { get } from 'svelte/store'
import { getDecimalSeparator } from '../currency'
import { localize } from '../i18n'
import { networkStatus } from '../networkStatus'
import { showAppNotification } from '../notifications'
import { activeProfile } from '../profile'
import { getBestTimeDuration, MILLISECONDS_PER_SECOND, SECONDS_PER_MILESTONE } from '../time'
import type { WalletAccount } from '../typings/wallet'
import { formatUnitBestMatch } from '../units'
import { clamp, delineateNumber } from '../utils'
import { wallet } from '../wallet'
import { ASSEMBLY_EVENT_ID, SHIMMER_EVENT_ID, STAKING_AIRDROP_TOKENS, STAKING_EVENT_IDS } from './constants'
import {
assemblyStakingRemainingTime,
calculateRemainingStakingTime,
partiallyStakedAccounts,
participationEvents,
participationOverview,
shimmerStakingRemainingTime,
stakedAccounts,
stakingEventState,
} from './stores'
import { Participation, ParticipationEvent, ParticipationEventState, StakingAirdrop } from './types'
/**
* Determines whether an account is currently being staked or not.
*
* @method isAccountStaked
*
* @param {string} accountId
*
* @returns {boolean}
*/
export const isAccountStaked = (accountId: string): boolean =>
get(stakedAccounts).find((sa) => sa.id === accountId) !== undefined
const getAirdropEventId = (airdrop: StakingAirdrop): string => {
switch (airdrop) {
case StakingAirdrop.Assembly:
return STAKING_EVENT_IDS[0]
case StakingAirdrop.Shimmer:
return STAKING_EVENT_IDS[1]
default:
return undefined
}
}
/**
* Determines whether an accounts is staked for a particular airdrop.
*
* @method isAccountStakedForAirdrop
*
* @param {string} accountId
* @param {StakingAirdrop} airdrop
*
* @returns {boolean}
*/
export const isAccountStakedForAirdrop = (accountId: string, airdrop: StakingAirdrop): boolean => {
const account = get(stakedAccounts).find((sa) => sa.id === accountId)
if (!account) return false
const accountOverview = get(participationOverview).find((apo) => apo.accountIndex === account?.index)
if (!accountOverview) return false
return accountOverview.participations.find((p) => p.eventId === getAirdropEventId(airdrop)) !== undefined
}
/**
* Determines if an account is partially staked.
*
* @method isAccountPartiallyStaked
*
* @param {string} accountId
* @returns {boolean}
*/
export const isAccountPartiallyStaked = (accountId: string): boolean =>
get(partiallyStakedAccounts).find((psa) => psa.id === accountId) !== undefined
/**
* Determines the staking airdrop from a given participation event ID.
*
* @method getAirdropFromEventId
*
* @param {string} eventId
*
* @returns {StakingAirdrop | undefined}
*/
export const getAirdropFromEventId = (eventId: string): StakingAirdrop | undefined => {
if (!eventId) return undefined
if (!STAKING_EVENT_IDS.includes(eventId)) {
showAppNotification({
type: 'error',
message: localize('error.participation.invalidStakingEventId'),
})
}
return eventId === ASSEMBLY_EVENT_ID ? StakingAirdrop.Assembly : StakingAirdrop.Shimmer
}
/**
* Get the corresponding staking participation event data from its airdrop enumeration.
*
* @method getStakingEventFromAirdrop
*
* @param {StakingAirdrop} airdrop
*
* @returns {ParticipationEvent}
*/
export const getStakingEventFromAirdrop = (airdrop: StakingAirdrop): ParticipationEvent => {
let stakingEventId
switch (airdrop) {
case StakingAirdrop.Assembly:
stakingEventId = ASSEMBLY_EVENT_ID
break
case StakingAirdrop.Shimmer:
stakingEventId = SHIMMER_EVENT_ID
break
default:
break
}
return get(participationEvents).find((pe) => pe.eventId === stakingEventId)
}
/**
* Returns a formatted version of the rewards for a particular airdrop.
*
* CAUTION: The formatting for the ASMB token assumes that the amount passed
* is in microASMB.
*
* @method formatStakingAirdropReward
*
* @param {StakingAirdrop} airdrop
* @param {number} amount
* @param {number} decimalPlaces
*
* @returns {string}
*/
export const formatStakingAirdropReward = (airdrop: StakingAirdrop, amount: number, decimalPlaces: number): string => {
const decimalSeparator = getDecimalSeparator(get(activeProfile)?.settings?.currency)
const thousandthSeparator = decimalSeparator === '.' ? ',' : '.'
let reward
switch (airdrop) {
case StakingAirdrop.Assembly: {
decimalPlaces = clamp(decimalPlaces, 0, 6)
const [integer, float] = (amount / 1_000_000).toFixed(decimalPlaces).split('.')
reward = `${delineateNumber(integer, thousandthSeparator)}${
Number(float) > 0 ? decimalSeparator + float : ''
}`
break
}
case StakingAirdrop.Shimmer: {
reward = delineateNumber(String(Math.floor(amount)), thousandthSeparator)
break
}
default:
reward = '0'
break
}
return `${reward} ${STAKING_AIRDROP_TOKENS[airdrop]}`
}
/**
* Returns a formatted version of the minimum rewards for a particular airdrop.
*
* @method getFormattedMinimumRewards
*
* @param {StakingAirdrop} airdrop
*
* @returns {string}
*/
export const getFormattedMinimumRewards = (airdrop: StakingAirdrop): string =>
formatStakingAirdropReward(
airdrop,
getStakingEventFromAirdrop(airdrop)?.information.payload.requiredMinimumRewards,
airdrop === StakingAirdrop.Assembly ? 6 : 0
)
/**
* The amount of microASMB per 1 Mi received every milestone,
* which is currently 4 microASMB (0.000004 ASMB).
*/
const ASSEMBLY_REWARD_MULTIPLIER = 4.0
/**
* The amount of SMR per 1 Mi received every milestone,
* which is currently 1 SMR.
*/
const SHIMMER_REWARD_MULTIPLIER = 1.0
/**
* Calculates the reward estimate for a particular staking airdrop.
*
* @method estimateStakingAirdropReward
*
* @param {StakingAirdrop} airdrop
* @param {number} amountToStake
* @param {boolean} formatAmount
* @param {number} decimalPlaces
*
* @returns {number | string}
*/
export const estimateStakingAirdropReward = (
airdrop: StakingAirdrop,
amountToStake: number,
formatAmount: boolean = false,
decimalPlaces: number = 6
): number | string => {
const stakingEvent = getStakingEventFromAirdrop(airdrop)
if (!stakingEvent || amountToStake <= 0) {
return formatAmount ? formatStakingAirdropReward(airdrop, 0, decimalPlaces) : 0
}
/**
* NOTE: We can use either of these, however since the network status is polled reguarly
* it will seem more dynamic rather than re-calculating within this function.
*/
const currentMilestone = get(networkStatus)?.currentMilestone || stakingEvent?.status?.milestoneIndex
const beginMilestone =
currentMilestone < stakingEvent?.information?.milestoneIndexStart
? stakingEvent?.information?.milestoneIndexStart
: currentMilestone
const endMilestone = stakingEvent?.information?.milestoneIndexEnd
const multiplier =
airdrop === StakingAirdrop.Assembly
? ASSEMBLY_REWARD_MULTIPLIER
: airdrop === StakingAirdrop.Shimmer
? SHIMMER_REWARD_MULTIPLIER
: 0
const estimation = multiplier * (amountToStake / 1_000_000) * (endMilestone - beginMilestone)
return formatAmount ? formatStakingAirdropReward(airdrop, estimation, decimalPlaces) : estimation
}
/**
* Calculate the staked funds for a particular account.
*
* @method getStakedFunds
*
* @param {WalletAccount} account
*
* @returns {number}
*/
export const getStakedFunds = (account: WalletAccount): number => {
const accountParticipation = get(participationOverview).find((apo) => apo.accountIndex === account?.index)
if (!accountParticipation) return 0
else return Math.max(accountParticipation.assemblyStakedFunds, accountParticipation.shimmerStakedFunds)
}
/**
* Calculate the unstaked funds for a particular account.
*
* @method getUnstakedFunds
*
* @param {WalletAccount} account
*
* @returns {number}
*/
export const getUnstakedFunds = (account: WalletAccount): number => {
const accountParticipation = get(participationOverview).find((apo) => apo.accountIndex === account?.index)
if (!accountParticipation) return 0
else return Math.min(accountParticipation.assemblyUnstakedFunds, accountParticipation.shimmerUnstakedFunds)
}
/**
* Determines if partipations include shimmer event id
*
* @method isStakingForShimmer
*
* @param {Participation[]} participations
*
* @returns {boolean}
*/
export const isStakingForShimmer = (participations: Participation[]): boolean => {
const eventIds = participations.map((participation) => participation.eventId)
return eventIds.includes(SHIMMER_EVENT_ID)
}
/**
* Determines if partipations include assembly event id
*
* @method isStakingForAssembly
*
* @param {Participation[]} participations
*
* @returns {boolean}
*/
export const isStakingForAssembly = (participations: Participation[]): boolean => {
const eventIds = participations.map((participation) => participation.eventId)
return eventIds.includes(ASSEMBLY_EVENT_ID)
}
/**
* Determines whether staking is currently in the pre-stake or holding period
*
* @method isStakingPossible
*
* @param {ParticipationEventState} stakingEventState
*
* @returns {boolean}
*/
export const isStakingPossible = (stakingEventState: ParticipationEventState): boolean =>
stakingEventState === ParticipationEventState.Commencing || stakingEventState === ParticipationEventState.Holding
const getAirdropRewardMultipler = (airdrop: StakingAirdrop): number => {
return airdrop === StakingAirdrop.Assembly
? ASSEMBLY_REWARD_MULTIPLIER
: airdrop === StakingAirdrop.Shimmer
? SHIMMER_REWARD_MULTIPLIER
: 0
}
const calculateNumMilestonesUntilMinimumReward = (
rewardsNeeded: number,
airdrop: StakingAirdrop,
amountStaked: number
): number => {
const result = (rewardsNeeded * 1_000_000) / (amountStaked * getAirdropRewardMultipler(airdrop))
return isNaN(result) ? 0 : result
}
const getMinimumRewardsRequired = (rewards: number, airdrop: StakingAirdrop): number => {
const event = getStakingEventFromAirdrop(airdrop)
if (!event) return 0
const rewardsRequired = event.information.payload.requiredMinimumRewards
if (rewards >= rewardsRequired) return 0
return rewardsRequired - rewards
}
const calculateTimeUntilMinimumReward = (rewards: number, airdrop: StakingAirdrop, amountStaked: number): number => {
const minRewardsRequired = getMinimumRewardsRequired(rewards, airdrop)
const numMilestonesUntilMinimumReward = calculateNumMilestonesUntilMinimumReward(
minRewardsRequired,
airdrop,
amountStaked
)
return numMilestonesUntilMinimumReward * SECONDS_PER_MILESTONE * MILLISECONDS_PER_SECOND
}
/**
* Calculates the remaining time needed to continue staking in order to
* reach the minimum airdrop amount. If called with format = true then returns
* human-readable duration, else returns the amount of time in millis.
*
* @method getTimeUntilMinimumAirdropReward
*
* @param {WalletAccount} account
* @param {StakingAirdrop} airdrop
* @param {boolean} format
*
* @returns {number | string}
*/
export const getTimeUntilMinimumAirdropReward = (
account: WalletAccount,
airdrop: StakingAirdrop,
format: boolean = false
): number | string => {
if (!account) return format ? getBestTimeDuration(0) : 0
const rewards = getCurrentRewardsForAirdrop(account, airdrop)
const amountStaked = account?.rawIotaBalance
const timeRequired = calculateTimeUntilMinimumReward(rewards, airdrop, amountStaked)
return format ? getBestTimeDuration(timeRequired) : timeRequired
}
const getNumRemainingMilestones = (airdrop: StakingAirdrop): number => {
const event = getStakingEventFromAirdrop(airdrop)
if (!event || !isStakingPossible(event?.status?.status)) return 0
// Remaining time is in milliseconds
const timeLeft =
airdrop === StakingAirdrop.Assembly
? get(assemblyStakingRemainingTime)
: airdrop === StakingAirdrop.Shimmer
? get(shimmerStakingRemainingTime)
: 0
const isInHolding = event?.status?.status === ParticipationEventState.Holding
const { milestoneIndexStart, milestoneIndexEnd } = event?.information
return isInHolding
? timeLeft / MILLISECONDS_PER_SECOND / SECONDS_PER_MILESTONE
: milestoneIndexEnd - milestoneIndexStart
}
const calculateIotasUntilMinimumReward = (rewards: number, airdrop: StakingAirdrop): number => {
const minRewardsRequired = getMinimumRewardsRequired(rewards, airdrop)
const numRemainingMilestones = getNumRemainingMilestones(airdrop)
return minRewardsRequired / ((getAirdropRewardMultipler(airdrop) / 1_000_000) * numRemainingMilestones)
}
/**
* Calculates the remaining number of IOTAs needed to reach the minimum airdrop amount.
* If called with format = true then returns best unit match for amount of IOTAs, else
* returns the raw number of IOTAs.
*
* @method getIotasUntilMinimumAirdropReward
*
* @param {WalletAccount} account
* @param {StakingAirdrop} airdrop
* @param {boolean} format
*
* @returns {number | string}
*/
export const getIotasUntilMinimumAirdropReward = (
account: WalletAccount,
airdrop: StakingAirdrop,
format: boolean = false
): number | string => {
if (!account) return format ? formatUnitBestMatch(0) : 0
const currentRewards = getCurrentRewardsForAirdrop(account, airdrop)
const iotasRequired = Math.round(calculateIotasUntilMinimumReward(currentRewards, airdrop))
return format ? formatUnitBestMatch(iotasRequired) : iotasRequired
}
/**
* Determines whether an account will be able to reach rewards minimums
* for both airdrops. This will return false if only one airdrop's minimum
* is able to be reached.
*
* @method canAccountReachMinimumAirdrop
*
* @param {WalletAccount} account
* @param {StakingAirdrop} airdrop
*
* @returns {boolean}
*/
export const canAccountReachMinimumAirdrop = (account: WalletAccount, airdrop: StakingAirdrop): boolean => {
if (!account) return false
const currentRewards = getCurrentRewardsForAirdrop(account, airdrop)
const timeRequired = calculateTimeUntilMinimumReward(currentRewards, airdrop, account.rawIotaBalance)
const stakingEvent = getStakingEventFromAirdrop(airdrop)
const _getTimeLeft = () => {
if (get(stakingEventState) === ParticipationEventState.Commencing)
return calculateRemainingStakingTime(stakingEvent?.information?.milestoneIndexStart, stakingEvent)
return airdrop === StakingAirdrop.Assembly
? get(assemblyStakingRemainingTime)
: airdrop === StakingAirdrop.Shimmer
? get(shimmerStakingRemainingTime)
: 0
}
return timeRequired <= _getTimeLeft()
}
/**
* Returns current rewards for a given airdrop
*
* @method getCurrentRewardsForAirdrop
*
* @param {WalletAccount} account
* @param {StakingAirdrop} airdrop
*
* @returns {number}
*/
export const getCurrentRewardsForAirdrop = (account: WalletAccount, airdrop: StakingAirdrop): number => {
const overview = get(participationOverview).find((apo) => apo.accountIndex === account?.index)
if (!overview) return 0
return airdrop === StakingAirdrop.Assembly
? overview.assemblyRewards + overview.assemblyRewardsBelowMinimum
: overview.shimmerRewards + overview.shimmerRewardsBelowMinimum
}
/**
* Returns current stake for a given airdrop
*
* @method getCurrentStakeForAirdrop
*
* @param {WalletAccount} account
* @param {StakingAirdrop} airdrop
*
* @returns {number}
*/
export const getCurrentStakeForAccount = (account: WalletAccount, airdrop: StakingAirdrop): number => {
const overview = get(participationOverview).find((apo) => apo.accountIndex === account?.index)
if (!overview) return 0
return airdrop === StakingAirdrop.Assembly ? overview.assemblyStakedFunds : overview.shimmerUnstakedFunds
}
/**
* Determines whether a given account has reached the reward minimum
* for either airdrop.
*
* @method hasAccountReachedMinimumAirdrop
*
* @param {WalletAccount} account
*
* @returns {boolean}
*/
export const hasAccountReachedMinimumAirdrop = (account: WalletAccount): boolean => {
if (!account) return false
const overview = get(participationOverview).find((apo) => apo.accountIndex === account?.index)
if (!overview) return false
return overview.assemblyRewards > 0 || overview.shimmerRewards > 0
}
/**
* Determines whether any account has reached the reward minimum
* for either airdrop.
*
* @method hasAnAccountReachedMinimumAirdrop
*
* @returns {boolean}
*/
export const hasAnAccountReachedMinimumAirdrop = (): boolean =>
get(get(wallet).accounts).some((a) => hasAccountReachedMinimumAirdrop(a)) | the_stack |
import {
CdmCorpusDefinition,
CdmEntityAttributeDefinition,
CdmEntityDefinition,
CdmEntityReference,
CdmOperationIncludeAttributes,
CdmProjection,
CdmTypeAttributeDefinition
} from '../../../internal';
import { testHelper } from '../../testHelper';
import { projectionTestUtils } from '../../Utilities/projectionTestUtils';
import { TypeAttributeParam } from './TypeAttributeParam';
import { ProjectionOMTestUtil } from './ProjectionOMTestUtil';
/**
* A test class for testing the IncludeAttributes operation in a projection as well as SelectsSomeTakeNames in a resolution guidance
*/
describe('Cdm/Projection/ProjectionIncludeTest', () => {
/**
* All possible combinations of the different resolution directives
*/
const resOptsCombinations: string[][] = [
[],
['referenceOnly'],
['normalized'],
['structured'],
['referenceOnly', 'normalized'],
['referenceOnly', 'structured'],
['normalized', 'structured'],
['referenceOnly', 'normalized', 'structured']
];
/**
* Path to foundations
*/
const foundationJsonPath: string = 'cdm:/foundations.cdm.json';
/**
* The path between TestDataPath and TestName.
*/
const testsSubpath: string = 'Cdm/Projection/ProjectionIncludeTest';
/**
* Test for entity extends with resolution guidance with a SelectsSomeTakeNames
*/
it('TestExtends', async () => {
const testName: string = 'TestExtends';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for entity extends with projection with an includeAttributes operation
*/
it('TestExtendsProj', async () => {
const testName: string = 'TestExtendsProj';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for entity attribute with resolution guidance with a SelectsSomeTakeNames
*/
it('TestEA', async () => {
const testName: string = 'TestEA';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for entity attribute with projection with an includeAttributes operation
*/
it('TestEAProj', async () => {
const testName: string = 'TestEAProj';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for object model
*/
it('TestEAProjOM', async () => {
const className: string = 'ProjectionIncludeTest';
const testName: string = 'TestEAProjOM';
const entityName_RGB: string = 'RGB';
const attributeParams_RGB: TypeAttributeParam[] = [];
attributeParams_RGB.push(new TypeAttributeParam('Red', 'string', 'hasA'));
attributeParams_RGB.push(new TypeAttributeParam('Green', 'string', 'hasA'));
attributeParams_RGB.push(new TypeAttributeParam('Blue', 'string', 'hasA'));
attributeParams_RGB.push(new TypeAttributeParam('IsGrayscale', 'boolean', 'hasA'));
const entityName_Color: string = 'Color';
const attributeParams_Color: TypeAttributeParam[] = [];
attributeParams_Color.push(new TypeAttributeParam('ColorName', 'string', 'identifiedBy'));
const includeAttributeNames: string[] = [];
includeAttributeNames.push('Red');
includeAttributeNames.push('Green');
includeAttributeNames.push('Blue');
const util: ProjectionOMTestUtil = new ProjectionOMTestUtil(className, testName);
const entity_RGB: CdmEntityDefinition = util.CreateBasicEntity(entityName_RGB, attributeParams_RGB);
util.validateBasicEntity(entity_RGB, entityName_RGB, attributeParams_RGB);
const entity_Color: CdmEntityDefinition = util.CreateBasicEntity(entityName_Color, attributeParams_Color);
util.validateBasicEntity(entity_Color, entityName_Color, attributeParams_Color);
const projection_RGBColor: CdmProjection = util.createProjection(entity_RGB.entityName);
const operation_IncludeAttributes: CdmOperationIncludeAttributes = util.createOperationInputAttribute(projection_RGBColor, includeAttributeNames);
const projectionEntityRef_RGBColor: CdmEntityReference = util.createProjectionInlineEntityReference(projection_RGBColor);
const entityAttribute_RGBColor: CdmEntityAttributeDefinition = util.createEntityAttribute('RGBColor', projectionEntityRef_RGBColor);
entity_Color.attributes.push(entityAttribute_RGBColor);
for (const resOpts of resOptsCombinations) {
await util.getAndValidateResolvedEntity(entity_Color, resOpts);
}
util.defaultManifest.saveAsAsync(util.manifestDocName, true);
});
/**
* Test for leaf level projection
*/
it('TestNested1of3Proj', async () => {
const testName: string = 'TestNested1of3Proj';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for mid level projection
*/
it('TestNested2of3Proj', async () => {
const testName: string = 'TestNested2of3Proj';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for top level projection
*/
it('TestNested3of3Proj', async () => {
const testName: string = 'TestNested3of3Proj';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for Condition = 'false'
*/
it('TestConditionProj', async () => {
const testName: string = 'TestConditionProj';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for SelectsSomeTakeNames by Group Name
*/
it('TestGroupName', async () => {
const testName: string = 'TestGroupName';
const entityName: string = 'Product';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for include attributes operation by Group Name
*/
it('TestGroupNameProj', async () => {
const testName: string = 'TestGroupNameProj';
const entityName: string = 'Product';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for SelectsSomeTakeNames from an Array
*/
it('TestArray', async () => {
const testName: string = 'TestArray';
const entityName: string = 'Sales';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for SelectsSomeTakeNames from a renamed Array
*/
it('TestArrayRename', async () => {
const testName: string = 'TestArrayRename';
const entityName: string = 'Sales';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for Include Attributes from an Array
*/
it('TestArrayProj', async () => {
const testName: string = 'TestArrayProj';
const entityName: string = 'Sales';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for SelectsSomeTakeNames from a Polymorphic Source
*/
it('TestPolymorphic', async () => {
const testName: string = 'TestPolymorphic';
const entityName: string = 'Person';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for Include Attributes from a Polymorphic Source
*/
it('TestPolymorphicProj', async () => {
const testName: string = 'TestPolymorphicProj';
const entityName: string = 'Person';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for Include Attributes from a Polymorphic Source
*/
it('TestReorderProj', async () => {
const testName: string = 'TestReorderProj'
const entityName: string = 'NewPerson'
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, []);
// Original set of attributes: ['name', 'age', 'address', 'phoneNumber', 'email']
// Renamed attribute 'age' with format 'yearsOld' and re-order all attributes removing email
expect(resolvedEntity.attributes.allItems.length)
.toEqual(4);
expect((resolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('address');
expect((resolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('phoneNumber');
expect((resolvedEntity.attributes.allItems[2] as CdmTypeAttributeDefinition).name)
.toEqual('yearsOld');
expect((resolvedEntity.attributes.allItems[3] as CdmTypeAttributeDefinition).name)
.toEqual('name');
});
/**
* Test for entity attribute with resolution guidance with an empty SelectsSomeTakeNames list
*/
it('TestEmpty', async () => {
const testName: string = 'TestEmpty';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for entity attribute with projection with an empty includeAttributes operation list
*/
it('TestEmptyProj', async () => {
const testName: string = 'TestEmptyProj';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for Nested Projections that include then exclude some attributes
*/
it('TestNestedIncludeExcludeProj', async () => {
const testName: string = 'TestNestedIncludeExcludeProj';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
/**
* Test for Projections with include and exclude
*/
it('TestIncludeExcludeProj', async () => {
const testName: string = 'TestIncludeExcludeProj';
const entityName: string = 'Color';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
});
}); | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import { DashboardConstants } from '../../../src/plugins/dashboard/public/dashboard_constants';
export const PIE_CHART_VIS_NAME = 'Visualization PieChart';
export const AREA_CHART_VIS_NAME = 'Visualization漢字 AreaChart';
export const LINE_CHART_VIS_NAME = 'Visualization漢字 LineChart';
import { FtrProviderContext } from '../ftr_provider_context';
export function DashboardPageProvider({ getService, getPageObjects }: FtrProviderContext) {
const log = getService('log');
const find = getService('find');
const retry = getService('retry');
const browser = getService('browser');
const opensearchArchiver = getService('opensearchArchiver');
const opensearchDashboardsServer = getService('opensearchDashboardsServer');
const testSubjects = getService('testSubjects');
const dashboardAddPanel = getService('dashboardAddPanel');
const renderable = getService('renderable');
const listingTable = getService('listingTable');
const PageObjects = getPageObjects(['common', 'header', 'visualize']);
interface SaveDashboardOptions {
waitDialogIsClosed: boolean;
needsConfirm?: boolean;
storeTimeWithDashboard?: boolean;
saveAsNew?: boolean;
}
class DashboardPage {
async initTests({
opensearchDashboardsIndex = 'dashboard/legacy',
defaultIndex = 'logstash-*',
} = {}) {
log.debug('load opensearch-dashboards index with visualizations and log data');
await opensearchArchiver.load(opensearchDashboardsIndex);
await opensearchDashboardsServer.uiSettings.replace({ defaultIndex });
await PageObjects.common.navigateToApp('dashboard');
}
public async preserveCrossAppState() {
const url = await browser.getCurrentUrl();
await browser.get(url, false);
await PageObjects.header.waitUntilLoadingHasFinished();
}
public async clickFullScreenMode() {
log.debug(`clickFullScreenMode`);
await testSubjects.click('dashboardFullScreenMode');
await testSubjects.exists('exitFullScreenModeLogo');
await this.waitForRenderComplete();
}
public async exitFullScreenMode() {
log.debug(`exitFullScreenMode`);
const logoButton = await this.getExitFullScreenLogoButton();
await logoButton.moveMouseTo();
await this.clickExitFullScreenTextButton();
}
public async fullScreenModeMenuItemExists() {
return await testSubjects.exists('dashboardFullScreenMode');
}
public async exitFullScreenTextButtonExists() {
return await testSubjects.exists('exitFullScreenModeText');
}
public async getExitFullScreenTextButton() {
return await testSubjects.find('exitFullScreenModeText');
}
public async exitFullScreenLogoButtonExists() {
return await testSubjects.exists('exitFullScreenModeLogo');
}
public async getExitFullScreenLogoButton() {
return await testSubjects.find('exitFullScreenModeLogo');
}
public async clickExitFullScreenLogoButton() {
await testSubjects.click('exitFullScreenModeLogo');
await this.waitForRenderComplete();
}
public async clickExitFullScreenTextButton() {
await testSubjects.click('exitFullScreenModeText');
await this.waitForRenderComplete();
}
public async getDashboardIdFromCurrentUrl() {
const currentUrl = await browser.getCurrentUrl();
const id = this.getDashboardIdFromUrl(currentUrl);
log.debug(`Dashboard id extracted from ${currentUrl} is ${id}`);
return id;
}
public getDashboardIdFromUrl(url: string) {
const urlSubstring = '#/view/';
const startOfIdIndex = url.indexOf(urlSubstring) + urlSubstring.length;
const endIndex = url.indexOf('?');
const id = url.substring(startOfIdIndex, endIndex < 0 ? url.length : endIndex);
return id;
}
/**
* Returns true if already on the dashboard landing page (that page doesn't have a link to itself).
* @returns {Promise<boolean>}
*/
public async onDashboardLandingPage() {
log.debug(`onDashboardLandingPage`);
return await testSubjects.exists('dashboardLandingPage', {
timeout: 5000,
});
}
public async expectExistsDashboardLandingPage() {
log.debug(`expectExistsDashboardLandingPage`);
await testSubjects.existOrFail('dashboardLandingPage');
}
public async clickDashboardBreadcrumbLink() {
log.debug('clickDashboardBreadcrumbLink');
await find.clickByCssSelector(`a[href="#${DashboardConstants.LANDING_PAGE_PATH}"]`);
await this.expectExistsDashboardLandingPage();
}
public async gotoDashboardLandingPage() {
log.debug('gotoDashboardLandingPage');
const onPage = await this.onDashboardLandingPage();
if (!onPage) {
await this.clickDashboardBreadcrumbLink();
}
}
public async clickClone() {
log.debug('Clicking clone');
await testSubjects.click('dashboardClone');
}
public async getCloneTitle() {
return await testSubjects.getAttribute('clonedDashboardTitle', 'value');
}
public async confirmClone() {
log.debug('Confirming clone');
await testSubjects.click('cloneConfirmButton');
}
public async cancelClone() {
log.debug('Canceling clone');
await testSubjects.click('cloneCancelButton');
}
public async setClonedDashboardTitle(title: string) {
await testSubjects.setValue('clonedDashboardTitle', title);
}
/**
* Asserts that the duplicate title warning is either displayed or not displayed.
* @param { displayed: boolean }
*/
public async expectDuplicateTitleWarningDisplayed({ displayed = true }) {
if (displayed) {
await testSubjects.existOrFail('titleDupicateWarnMsg');
} else {
await testSubjects.missingOrFail('titleDupicateWarnMsg');
}
}
/**
* Asserts that the toolbar pagination (count and arrows) is either displayed or not displayed.
* @param { displayed: boolean }
*/
public async expectToolbarPaginationDisplayed({ displayed = true }) {
const subjects = ['btnPrevPage', 'btnNextPage', 'toolBarPagerText'];
if (displayed) {
await Promise.all(subjects.map(async (subj) => await testSubjects.existOrFail(subj)));
} else {
await Promise.all(subjects.map(async (subj) => await testSubjects.missingOrFail(subj)));
}
}
public async switchToEditMode() {
log.debug('Switching to edit mode');
await testSubjects.click('dashboardEditMode');
// wait until the count of dashboard panels equals the count of toggle menu icons
await retry.waitFor('in edit mode', async () => {
const panels = await testSubjects.findAll('embeddablePanel', 2500);
const menuIcons = await testSubjects.findAll('embeddablePanelToggleMenuIcon', 2500);
return panels.length === menuIcons.length;
});
}
public async getIsInViewMode() {
log.debug('getIsInViewMode');
return await testSubjects.exists('dashboardEditMode');
}
public async clickCancelOutOfEditMode() {
log.debug('clickCancelOutOfEditMode');
await testSubjects.click('dashboardViewOnlyMode');
}
public async clickNewDashboard() {
await listingTable.clickNewButton('createDashboardPromptButton');
// make sure the dashboard page is shown
await this.waitForRenderComplete();
}
public async clickCreateDashboardPrompt() {
await testSubjects.click('createDashboardPromptButton');
}
public async getCreateDashboardPromptExists() {
return await testSubjects.exists('createDashboardPromptButton');
}
public async isOptionsOpen() {
log.debug('isOptionsOpen');
return await testSubjects.exists('dashboardOptionsMenu');
}
public async openOptions() {
log.debug('openOptions');
const isOpen = await this.isOptionsOpen();
if (!isOpen) {
return await testSubjects.click('dashboardOptionsButton');
}
}
// avoids any 'Object with id x not found' errors when switching tests.
public async clearSavedObjectsFromAppLinks() {
await PageObjects.header.clickVisualize();
await PageObjects.visualize.gotoLandingPage();
await PageObjects.header.clickDashboard();
await this.gotoDashboardLandingPage();
}
public async isMarginsOn() {
log.debug('isMarginsOn');
await this.openOptions();
return await testSubjects.getAttribute('dashboardMarginsCheckbox', 'checked');
}
public async useMargins(on = true) {
await this.openOptions();
const isMarginsOn = await this.isMarginsOn();
if (isMarginsOn !== 'on') {
return await testSubjects.click('dashboardMarginsCheckbox');
}
}
public async gotoDashboardEditMode(dashboardName: string) {
await this.loadSavedDashboard(dashboardName);
await this.switchToEditMode();
}
public async renameDashboard(dashboardName: string) {
log.debug(`Naming dashboard ` + dashboardName);
await testSubjects.click('dashboardRenameButton');
await testSubjects.setValue('savedObjectTitle', dashboardName);
}
/**
* Save the current dashboard with the specified name and options and
* verify that the save was successful, close the toast and return the
* toast message
*
* @param dashboardName {String}
* @param saveOptions {{storeTimeWithDashboard: boolean, saveAsNew: boolean, needsConfirm: false, waitDialogIsClosed: boolean }}
*/
public async saveDashboard(
dashboardName: string,
saveOptions: SaveDashboardOptions = { waitDialogIsClosed: true }
) {
await retry.try(async () => {
await this.enterDashboardTitleAndClickSave(dashboardName, saveOptions);
if (saveOptions.needsConfirm) {
await this.ensureDuplicateTitleCallout();
await this.clickSave();
}
// Confirm that the Dashboard has actually been saved
await testSubjects.existOrFail('saveDashboardSuccess');
});
const message = await PageObjects.common.closeToast();
await PageObjects.header.waitUntilLoadingHasFinished();
await PageObjects.common.waitForSaveModalToClose();
return message;
}
public async cancelSave() {
log.debug('Canceling save');
await testSubjects.click('saveCancelButton');
}
public async clickSave() {
log.debug('DashboardPage.clickSave');
await testSubjects.click('confirmSaveSavedObjectButton');
}
/**
*
* @param dashboardTitle {String}
* @param saveOptions {{storeTimeWithDashboard: boolean, saveAsNew: boolean, waitDialogIsClosed: boolean}}
*/
public async enterDashboardTitleAndClickSave(
dashboardTitle: string,
saveOptions: SaveDashboardOptions = { waitDialogIsClosed: true }
) {
await testSubjects.click('dashboardSaveMenuItem');
const modalDialog = await testSubjects.find('savedObjectSaveModal');
log.debug('entering new title');
await testSubjects.setValue('savedObjectTitle', dashboardTitle);
if (saveOptions.storeTimeWithDashboard !== undefined) {
await this.setStoreTimeWithDashboard(saveOptions.storeTimeWithDashboard);
}
if (saveOptions.saveAsNew !== undefined) {
await this.setSaveAsNewCheckBox(saveOptions.saveAsNew);
}
await this.clickSave();
if (saveOptions.waitDialogIsClosed) {
await testSubjects.waitForDeleted(modalDialog);
}
}
public async ensureDuplicateTitleCallout() {
await testSubjects.existOrFail('titleDupicateWarnMsg');
}
/**
* @param dashboardTitle {String}
*/
public async enterDashboardTitleAndPressEnter(dashboardTitle: string) {
await testSubjects.click('dashboardSaveMenuItem');
const modalDialog = await testSubjects.find('savedObjectSaveModal');
log.debug('entering new title');
await testSubjects.setValue('savedObjectTitle', dashboardTitle);
await PageObjects.common.pressEnterKey();
await testSubjects.waitForDeleted(modalDialog);
}
// use the search filter box to narrow the results down to a single
// entry, or at least to a single page of results
public async loadSavedDashboard(dashboardName: string) {
log.debug(`Load Saved Dashboard ${dashboardName}`);
await this.gotoDashboardLandingPage();
await listingTable.searchForItemWithName(dashboardName);
await retry.try(async () => {
await listingTable.clickItemLink('dashboard', dashboardName);
await PageObjects.header.waitUntilLoadingHasFinished();
// check Dashboard landing page is not present
await testSubjects.missingOrFail('dashboardLandingPage', { timeout: 10000 });
});
}
public async getPanelTitles() {
log.debug('in getPanelTitles');
const titleObjects = await testSubjects.findAll('dashboardPanelTitle');
return await Promise.all(titleObjects.map(async (title) => await title.getVisibleText()));
}
public async getPanelDimensions() {
const panels = await find.allByCssSelector('.react-grid-item'); // These are gridster-defined elements and classes
return await Promise.all(
panels.map(async (panel) => {
const size = await panel.getSize();
return {
width: size.width,
height: size.height,
};
})
);
}
public async getPanelCount() {
log.debug('getPanelCount');
const panels = await testSubjects.findAll('embeddablePanel');
return panels.length;
}
public getTestVisualizations() {
return [
{ name: PIE_CHART_VIS_NAME, description: 'PieChart' },
{ name: 'Visualization☺ VerticalBarChart', description: 'VerticalBarChart' },
{ name: AREA_CHART_VIS_NAME, description: 'AreaChart' },
{ name: 'Visualization☺漢字 DataTable', description: 'DataTable' },
{ name: LINE_CHART_VIS_NAME, description: 'LineChart' },
{ name: 'Visualization TileMap', description: 'TileMap' },
{ name: 'Visualization MetricChart', description: 'MetricChart' },
];
}
public getTestVisualizationNames() {
return this.getTestVisualizations().map((visualization) => visualization.name);
}
public getTestVisualizationDescriptions() {
return this.getTestVisualizations().map((visualization) => visualization.description);
}
public async getDashboardPanels() {
return await testSubjects.findAll('embeddablePanel');
}
public async addVisualizations(visualizations: string[]) {
await dashboardAddPanel.addVisualizations(visualizations);
}
public async setSaveAsNewCheckBox(checked: boolean) {
log.debug('saveAsNewCheckbox: ' + checked);
let saveAsNewCheckbox = await testSubjects.find('saveAsNewCheckbox');
const isAlreadyChecked = (await saveAsNewCheckbox.getAttribute('aria-checked')) === 'true';
if (isAlreadyChecked !== checked) {
log.debug('Flipping save as new checkbox');
saveAsNewCheckbox = await testSubjects.find('saveAsNewCheckbox');
await retry.try(() => saveAsNewCheckbox.click());
}
}
public async setStoreTimeWithDashboard(checked: boolean) {
log.debug('Storing time with dashboard: ' + checked);
let storeTimeCheckbox = await testSubjects.find('storeTimeWithDashboard');
const isAlreadyChecked = (await storeTimeCheckbox.getAttribute('aria-checked')) === 'true';
if (isAlreadyChecked !== checked) {
log.debug('Flipping store time checkbox');
storeTimeCheckbox = await testSubjects.find('storeTimeWithDashboard');
await retry.try(() => storeTimeCheckbox.click());
}
}
public async getSharedItemsCount() {
log.debug('in getSharedItemsCount');
const attributeName = 'data-shared-items-count';
const element = await find.byCssSelector(`[${attributeName}]`);
if (element) {
return await element.getAttribute(attributeName);
}
throw new Error('no element');
}
public async waitForRenderComplete() {
log.debug('waitForRenderComplete');
const count = await this.getSharedItemsCount();
// eslint-disable-next-line radix
await renderable.waitForRender(parseInt(count));
}
public async getSharedContainerData() {
log.debug('getSharedContainerData');
const sharedContainer = await find.byCssSelector('[data-shared-items-container]');
return {
title: await sharedContainer.getAttribute('data-title'),
description: await sharedContainer.getAttribute('data-description'),
count: await sharedContainer.getAttribute('data-shared-items-count'),
};
}
public async getPanelSharedItemData() {
log.debug('in getPanelSharedItemData');
const sharedItemscontainer = await find.byCssSelector('[data-shared-items-count]');
const $ = await sharedItemscontainer.parseDomContent();
return $('[data-shared-item]')
.toArray()
.map((item) => {
return {
title: $(item).attr('data-title'),
description: $(item).attr('data-description'),
};
});
}
public async checkHideTitle() {
log.debug('ensure that you can click on hide title checkbox');
await this.openOptions();
return await testSubjects.click('dashboardPanelTitlesCheckbox');
}
public async expectMissingSaveOption() {
await testSubjects.missingOrFail('dashboardSaveMenuItem');
}
public async getNotLoadedVisualizations(vizList: string[]) {
const checkList = [];
for (const name of vizList) {
const isPresent = await testSubjects.exists(
`embeddablePanelHeading-${name.replace(/\s+/g, '')}`,
{ timeout: 10000 }
);
checkList.push({ name, isPresent });
}
return checkList.filter((viz) => viz.isPresent === false).map((viz) => viz.name);
}
public async getPanelDrilldownCount(panelIndex = 0): Promise<number> {
log.debug('getPanelDrilldownCount');
const panel = (await this.getDashboardPanels())[panelIndex];
try {
const count = await panel.findByTestSubject(
'embeddablePanelNotification-ACTION_PANEL_NOTIFICATIONS'
);
return Number.parseInt(await count.getVisibleText(), 10);
} catch (e) {
// if not found then this is 0 (we don't show badge with 0)
return 0;
}
}
}
return new DashboardPage();
} | the_stack |
import * as $protobuf from "protobufjs";
/** Properties of a ServerClientMessage. */
export interface IServerClientMessage {
/** ServerClientMessage compression */
compression?: (Compression|null);
/** ServerClientMessage uncompressedSize */
uncompressedSize?: (number|null);
/** ServerClientMessage compressedData */
compressedData?: (Uint8Array|null);
/** ServerClientMessage data */
data?: (IServerClient|null);
}
/** Represents a ServerClientMessage. */
export class ServerClientMessage implements IServerClientMessage {
/**
* Constructs a new ServerClientMessage.
* @param [properties] Properties to set
*/
constructor(properties?: IServerClientMessage);
/** ServerClientMessage compression. */
public compression: Compression;
/** ServerClientMessage uncompressedSize. */
public uncompressedSize: number;
/** ServerClientMessage compressedData. */
public compressedData: Uint8Array;
/** ServerClientMessage data. */
public data?: (IServerClient|null);
/** ServerClientMessage message. */
public message?: ("compressedData"|"data");
/**
* Creates a new ServerClientMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns ServerClientMessage instance
*/
public static create(properties?: IServerClientMessage): ServerClientMessage;
/**
* Encodes the specified ServerClientMessage message. Does not implicitly {@link ServerClientMessage.verify|verify} messages.
* @param message ServerClientMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IServerClientMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ServerClientMessage message, length delimited. Does not implicitly {@link ServerClientMessage.verify|verify} messages.
* @param message ServerClientMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IServerClientMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ServerClientMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ServerClientMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ServerClientMessage;
/**
* Decodes a ServerClientMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ServerClientMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ServerClientMessage;
/**
* Verifies a ServerClientMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ServerClientMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ServerClientMessage
*/
public static fromObject(object: { [k: string]: any }): ServerClientMessage;
/**
* Creates a plain object from a ServerClientMessage message. Also converts values to other types if specified.
* @param message ServerClientMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ServerClientMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ServerClientMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ServerClient. */
export interface IServerClient {
/** ServerClient messageType */
messageType?: (ServerClient.MessageType|null);
/** ServerClient handshake */
handshake?: (IServerHandshake|null);
/** ServerClient ping */
ping?: (IPing|null);
/** ServerClient serverMessage */
serverMessage?: (IServerMessage|null);
/** ServerClient playerListUpdate */
playerListUpdate?: (IPlayerListUpdate|null);
/** ServerClient playerUpdate */
playerUpdate?: (IPlayerUpdate|null);
/** ServerClient playerData */
playerData?: (IPlayerData|null);
/** ServerClient metaData */
metaData?: (IMetaData|null);
/** ServerClient chat */
chat?: (IChat|null);
}
/** Represents a ServerClient. */
export class ServerClient implements IServerClient {
/**
* Constructs a new ServerClient.
* @param [properties] Properties to set
*/
constructor(properties?: IServerClient);
/** ServerClient messageType. */
public messageType: ServerClient.MessageType;
/** ServerClient handshake. */
public handshake?: (IServerHandshake|null);
/** ServerClient ping. */
public ping?: (IPing|null);
/** ServerClient serverMessage. */
public serverMessage?: (IServerMessage|null);
/** ServerClient playerListUpdate. */
public playerListUpdate?: (IPlayerListUpdate|null);
/** ServerClient playerUpdate. */
public playerUpdate?: (IPlayerUpdate|null);
/** ServerClient playerData. */
public playerData?: (IPlayerData|null);
/** ServerClient metaData. */
public metaData?: (IMetaData|null);
/** ServerClient chat. */
public chat?: (IChat|null);
/** ServerClient message. */
public message?: ("handshake"|"ping"|"serverMessage"|"playerListUpdate"|"playerUpdate"|"playerData"|"metaData"|"chat");
/**
* Creates a new ServerClient instance using the specified properties.
* @param [properties] Properties to set
* @returns ServerClient instance
*/
public static create(properties?: IServerClient): ServerClient;
/**
* Encodes the specified ServerClient message. Does not implicitly {@link ServerClient.verify|verify} messages.
* @param message ServerClient message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IServerClient, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ServerClient message, length delimited. Does not implicitly {@link ServerClient.verify|verify} messages.
* @param message ServerClient message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IServerClient, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ServerClient message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ServerClient
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ServerClient;
/**
* Decodes a ServerClient message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ServerClient
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ServerClient;
/**
* Verifies a ServerClient message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ServerClient message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ServerClient
*/
public static fromObject(object: { [k: string]: any }): ServerClient;
/**
* Creates a plain object from a ServerClient message. Also converts values to other types if specified.
* @param message ServerClient
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ServerClient, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ServerClient to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ServerClient {
/** MessageType enum. */
enum MessageType {
UNKNOWN = 0,
HANDSHAKE = 2,
PING = 3,
SERVER_MESSAGE = 4,
PLAYER_LIST_UPDATE = 5,
PLAYER_UPDATE = 6,
PLAYER_DATA = 128,
META_DATA = 129,
CHAT = 130
}
}
/** Properties of a ServerHandshake. */
export interface IServerHandshake {
/** ServerHandshake playerId */
playerId?: (number|null);
/** ServerHandshake ip */
ip?: (string|null);
/** ServerHandshake port */
port?: (number|null);
/** ServerHandshake domain */
domain?: (string|null);
/** ServerHandshake name */
name?: (string|null);
/** ServerHandshake description */
description?: (string|null);
/** ServerHandshake playerList */
playerList?: (IPlayerListUpdate|null);
/** ServerHandshake countryCode */
countryCode?: (string|null);
/** ServerHandshake gameMode */
gameMode?: (GameModeType|null);
/** ServerHandshake passwordRequired */
passwordRequired?: (boolean|null);
}
/** Represents a ServerHandshake. */
export class ServerHandshake implements IServerHandshake {
/**
* Constructs a new ServerHandshake.
* @param [properties] Properties to set
*/
constructor(properties?: IServerHandshake);
/** ServerHandshake playerId. */
public playerId: number;
/** ServerHandshake ip. */
public ip: string;
/** ServerHandshake port. */
public port: number;
/** ServerHandshake domain. */
public domain: string;
/** ServerHandshake name. */
public name: string;
/** ServerHandshake description. */
public description: string;
/** ServerHandshake playerList. */
public playerList?: (IPlayerListUpdate|null);
/** ServerHandshake countryCode. */
public countryCode: string;
/** ServerHandshake gameMode. */
public gameMode: GameModeType;
/** ServerHandshake passwordRequired. */
public passwordRequired: boolean;
/**
* Creates a new ServerHandshake instance using the specified properties.
* @param [properties] Properties to set
* @returns ServerHandshake instance
*/
public static create(properties?: IServerHandshake): ServerHandshake;
/**
* Encodes the specified ServerHandshake message. Does not implicitly {@link ServerHandshake.verify|verify} messages.
* @param message ServerHandshake message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IServerHandshake, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ServerHandshake message, length delimited. Does not implicitly {@link ServerHandshake.verify|verify} messages.
* @param message ServerHandshake message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IServerHandshake, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ServerHandshake message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ServerHandshake
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ServerHandshake;
/**
* Decodes a ServerHandshake message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ServerHandshake
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ServerHandshake;
/**
* Verifies a ServerHandshake message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ServerHandshake message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ServerHandshake
*/
public static fromObject(object: { [k: string]: any }): ServerHandshake;
/**
* Creates a plain object from a ServerHandshake message. Also converts values to other types if specified.
* @param message ServerHandshake
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ServerHandshake, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ServerHandshake to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GameMode. */
export interface IGameMode {
/** GameMode gameMode */
gameMode?: (GameModeType|null);
}
/** Represents a GameMode. */
export class GameMode implements IGameMode {
/**
* Constructs a new GameMode.
* @param [properties] Properties to set
*/
constructor(properties?: IGameMode);
/** GameMode gameMode. */
public gameMode: GameModeType;
/**
* Creates a new GameMode instance using the specified properties.
* @param [properties] Properties to set
* @returns GameMode instance
*/
public static create(properties?: IGameMode): GameMode;
/**
* Encodes the specified GameMode message. Does not implicitly {@link GameMode.verify|verify} messages.
* @param message GameMode message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGameMode, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GameMode message, length delimited. Does not implicitly {@link GameMode.verify|verify} messages.
* @param message GameMode message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IGameMode, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GameMode message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GameMode
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): GameMode;
/**
* Decodes a GameMode message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GameMode
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): GameMode;
/**
* Verifies a GameMode message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a GameMode message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GameMode
*/
public static fromObject(object: { [k: string]: any }): GameMode;
/**
* Creates a plain object from a GameMode message. Also converts values to other types if specified.
* @param message GameMode
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: GameMode, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GameMode to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** GameModeType enum. */
export enum GameModeType {
NONE = 0,
DEFAULT = 1,
THIRD_PERSON_SHOOTER = 2,
INTERACTIONLESS = 3,
PROP_HUNT = 4,
BOSS_RUSH = 5,
TAG = 6,
WARIO_WARE = 8
}
/** Properties of a PlayerUpdate. */
export interface IPlayerUpdate {
/** PlayerUpdate playerId */
playerId?: (number|null);
/** PlayerUpdate player */
player?: (IPlayer|null);
}
/** Represents a PlayerUpdate. */
export class PlayerUpdate implements IPlayerUpdate {
/**
* Constructs a new PlayerUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: IPlayerUpdate);
/** PlayerUpdate playerId. */
public playerId: number;
/** PlayerUpdate player. */
public player?: (IPlayer|null);
/**
* Creates a new PlayerUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns PlayerUpdate instance
*/
public static create(properties?: IPlayerUpdate): PlayerUpdate;
/**
* Encodes the specified PlayerUpdate message. Does not implicitly {@link PlayerUpdate.verify|verify} messages.
* @param message PlayerUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPlayerUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PlayerUpdate message, length delimited. Does not implicitly {@link PlayerUpdate.verify|verify} messages.
* @param message PlayerUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPlayerUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PlayerUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PlayerUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PlayerUpdate;
/**
* Decodes a PlayerUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PlayerUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PlayerUpdate;
/**
* Verifies a PlayerUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PlayerUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PlayerUpdate
*/
public static fromObject(object: { [k: string]: any }): PlayerUpdate;
/**
* Creates a plain object from a PlayerUpdate message. Also converts values to other types if specified.
* @param message PlayerUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: PlayerUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PlayerUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PlayerListUpdate. */
export interface IPlayerListUpdate {
/** PlayerListUpdate playerUpdates */
playerUpdates?: (IPlayerUpdate[]|null);
}
/** Represents a PlayerListUpdate. */
export class PlayerListUpdate implements IPlayerListUpdate {
/**
* Constructs a new PlayerListUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: IPlayerListUpdate);
/** PlayerListUpdate playerUpdates. */
public playerUpdates: IPlayerUpdate[];
/**
* Creates a new PlayerListUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns PlayerListUpdate instance
*/
public static create(properties?: IPlayerListUpdate): PlayerListUpdate;
/**
* Encodes the specified PlayerListUpdate message. Does not implicitly {@link PlayerListUpdate.verify|verify} messages.
* @param message PlayerListUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPlayerListUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PlayerListUpdate message, length delimited. Does not implicitly {@link PlayerListUpdate.verify|verify} messages.
* @param message PlayerListUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPlayerListUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PlayerListUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PlayerListUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PlayerListUpdate;
/**
* Decodes a PlayerListUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PlayerListUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PlayerListUpdate;
/**
* Verifies a PlayerListUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PlayerListUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PlayerListUpdate
*/
public static fromObject(object: { [k: string]: any }): PlayerListUpdate;
/**
* Creates a plain object from a PlayerListUpdate message. Also converts values to other types if specified.
* @param message PlayerListUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: PlayerListUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PlayerListUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Player. */
export interface IPlayer {
/** Player username */
username?: (string|null);
/** Player characterId */
characterId?: (number|null);
}
/** Represents a Player. */
export class Player implements IPlayer {
/**
* Constructs a new Player.
* @param [properties] Properties to set
*/
constructor(properties?: IPlayer);
/** Player username. */
public username: string;
/** Player characterId. */
public characterId: number;
/**
* Creates a new Player instance using the specified properties.
* @param [properties] Properties to set
* @returns Player instance
*/
public static create(properties?: IPlayer): Player;
/**
* Encodes the specified Player message. Does not implicitly {@link Player.verify|verify} messages.
* @param message Player message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPlayer, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Player message, length delimited. Does not implicitly {@link Player.verify|verify} messages.
* @param message Player message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPlayer, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Player message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Player
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Player;
/**
* Decodes a Player message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Player
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Player;
/**
* Verifies a Player message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Player message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Player
*/
public static fromObject(object: { [k: string]: any }): Player;
/**
* Creates a plain object from a Player message. Also converts values to other types if specified.
* @param message Player
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Player, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Player to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Ping. */
export interface IPing {
}
/** Represents a Ping. */
export class Ping implements IPing {
/**
* Constructs a new Ping.
* @param [properties] Properties to set
*/
constructor(properties?: IPing);
/**
* Creates a new Ping instance using the specified properties.
* @param [properties] Properties to set
* @returns Ping instance
*/
public static create(properties?: IPing): Ping;
/**
* Encodes the specified Ping message. Does not implicitly {@link Ping.verify|verify} messages.
* @param message Ping message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPing, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Ping message, length delimited. Does not implicitly {@link Ping.verify|verify} messages.
* @param message Ping message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPing, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Ping message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Ping
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Ping;
/**
* Decodes a Ping message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Ping
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Ping;
/**
* Verifies a Ping message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Ping message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Ping
*/
public static fromObject(object: { [k: string]: any }): Ping;
/**
* Creates a plain object from a Ping message. Also converts values to other types if specified.
* @param message Ping
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Ping, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Ping to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ServerMessage. */
export interface IServerMessage {
/** ServerMessage messageType */
messageType?: (ServerMessage.MessageType|null);
/** ServerMessage connectionDenied */
connectionDenied?: (IConnectionDenied|null);
/** ServerMessage gameMode */
gameMode?: (IGameMode|null);
/** ServerMessage playerReorder */
playerReorder?: (IPlayerReorder|null);
/** ServerMessage error */
error?: (IError|null);
/** ServerMessage authentication */
authentication?: (IAuthentication|null);
}
/** Represents a ServerMessage. */
export class ServerMessage implements IServerMessage {
/**
* Constructs a new ServerMessage.
* @param [properties] Properties to set
*/
constructor(properties?: IServerMessage);
/** ServerMessage messageType. */
public messageType: ServerMessage.MessageType;
/** ServerMessage connectionDenied. */
public connectionDenied?: (IConnectionDenied|null);
/** ServerMessage gameMode. */
public gameMode?: (IGameMode|null);
/** ServerMessage playerReorder. */
public playerReorder?: (IPlayerReorder|null);
/** ServerMessage error. */
public error?: (IError|null);
/** ServerMessage authentication. */
public authentication?: (IAuthentication|null);
/** ServerMessage message. */
public message?: ("connectionDenied"|"gameMode"|"playerReorder"|"error"|"authentication");
/**
* Creates a new ServerMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns ServerMessage instance
*/
public static create(properties?: IServerMessage): ServerMessage;
/**
* Encodes the specified ServerMessage message. Does not implicitly {@link ServerMessage.verify|verify} messages.
* @param message ServerMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IServerMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ServerMessage message, length delimited. Does not implicitly {@link ServerMessage.verify|verify} messages.
* @param message ServerMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IServerMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ServerMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ServerMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ServerMessage;
/**
* Decodes a ServerMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ServerMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ServerMessage;
/**
* Verifies a ServerMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ServerMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ServerMessage
*/
public static fromObject(object: { [k: string]: any }): ServerMessage;
/**
* Creates a plain object from a ServerMessage message. Also converts values to other types if specified.
* @param message ServerMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ServerMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ServerMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ServerMessage {
/** MessageType enum. */
enum MessageType {
CONNECTION_DENIED = 0,
GAME_MODE = 1,
PLAYER_REORDER = 2,
ERROR = 3,
AUTHENTICATION = 4
}
}
/** Properties of a PlayerReorder. */
export interface IPlayerReorder {
/** PlayerReorder grantToken */
grantToken?: (boolean|null);
/** PlayerReorder playerId */
playerId?: (number|null);
}
/** Represents a PlayerReorder. */
export class PlayerReorder implements IPlayerReorder {
/**
* Constructs a new PlayerReorder.
* @param [properties] Properties to set
*/
constructor(properties?: IPlayerReorder);
/** PlayerReorder grantToken. */
public grantToken: boolean;
/** PlayerReorder playerId. */
public playerId: number;
/**
* Creates a new PlayerReorder instance using the specified properties.
* @param [properties] Properties to set
* @returns PlayerReorder instance
*/
public static create(properties?: IPlayerReorder): PlayerReorder;
/**
* Encodes the specified PlayerReorder message. Does not implicitly {@link PlayerReorder.verify|verify} messages.
* @param message PlayerReorder message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPlayerReorder, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PlayerReorder message, length delimited. Does not implicitly {@link PlayerReorder.verify|verify} messages.
* @param message PlayerReorder message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPlayerReorder, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PlayerReorder message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PlayerReorder
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PlayerReorder;
/**
* Decodes a PlayerReorder message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PlayerReorder
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PlayerReorder;
/**
* Verifies a PlayerReorder message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PlayerReorder message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PlayerReorder
*/
public static fromObject(object: { [k: string]: any }): PlayerReorder;
/**
* Creates a plain object from a PlayerReorder message. Also converts values to other types if specified.
* @param message PlayerReorder
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: PlayerReorder, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PlayerReorder to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an Error. */
export interface IError {
/** Error errorType */
errorType?: (Error.ErrorType|null);
/** Error message */
message?: (string|null);
}
/** Represents an Error. */
export class Error implements IError {
/**
* Constructs a new Error.
* @param [properties] Properties to set
*/
constructor(properties?: IError);
/** Error errorType. */
public errorType: Error.ErrorType;
/** Error message. */
public message: string;
/**
* Creates a new Error instance using the specified properties.
* @param [properties] Properties to set
* @returns Error instance
*/
public static create(properties?: IError): Error;
/**
* Encodes the specified Error message. Does not implicitly {@link Error.verify|verify} messages.
* @param message Error message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IError, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Error message, length delimited. Does not implicitly {@link Error.verify|verify} messages.
* @param message Error message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IError, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Error message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Error
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Error;
/**
* Decodes an Error message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Error
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Error;
/**
* Verifies an Error message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Error message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Error
*/
public static fromObject(object: { [k: string]: any }): Error;
/**
* Creates a plain object from an Error message. Also converts values to other types if specified.
* @param message Error
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Error, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Error to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace Error {
/** ErrorType enum. */
enum ErrorType {
UNKNOWN = 0,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
TOO_MANY_REQUESTS = 429,
INTERNAL_SERVER_ERROR = 500
}
}
/** Properties of an Authentication. */
export interface IAuthentication {
/** Authentication status */
status?: (Authentication.Status|null);
/** Authentication throttle */
throttle?: (number|null);
}
/** Represents an Authentication. */
export class Authentication implements IAuthentication {
/**
* Constructs a new Authentication.
* @param [properties] Properties to set
*/
constructor(properties?: IAuthentication);
/** Authentication status. */
public status: Authentication.Status;
/** Authentication throttle. */
public throttle: number;
/**
* Creates a new Authentication instance using the specified properties.
* @param [properties] Properties to set
* @returns Authentication instance
*/
public static create(properties?: IAuthentication): Authentication;
/**
* Encodes the specified Authentication message. Does not implicitly {@link Authentication.verify|verify} messages.
* @param message Authentication message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IAuthentication, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Authentication message, length delimited. Does not implicitly {@link Authentication.verify|verify} messages.
* @param message Authentication message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IAuthentication, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Authentication message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Authentication
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Authentication;
/**
* Decodes an Authentication message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Authentication
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Authentication;
/**
* Verifies an Authentication message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Authentication message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Authentication
*/
public static fromObject(object: { [k: string]: any }): Authentication;
/**
* Creates a plain object from an Authentication message. Also converts values to other types if specified.
* @param message Authentication
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Authentication, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Authentication to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace Authentication {
/** Status enum. */
enum Status {
ACCEPTED = 0,
DENIED = 1
}
}
/** Properties of a ConnectionDenied. */
export interface IConnectionDenied {
/** ConnectionDenied reason */
reason?: (ConnectionDenied.Reason|null);
/** ConnectionDenied serverFull */
serverFull?: (IServerFull|null);
/** ConnectionDenied wrongVersion */
wrongVersion?: (IWrongVersion|null);
}
/** Represents a ConnectionDenied. */
export class ConnectionDenied implements IConnectionDenied {
/**
* Constructs a new ConnectionDenied.
* @param [properties] Properties to set
*/
constructor(properties?: IConnectionDenied);
/** ConnectionDenied reason. */
public reason: ConnectionDenied.Reason;
/** ConnectionDenied serverFull. */
public serverFull?: (IServerFull|null);
/** ConnectionDenied wrongVersion. */
public wrongVersion?: (IWrongVersion|null);
/** ConnectionDenied message. */
public message?: ("serverFull"|"wrongVersion");
/**
* Creates a new ConnectionDenied instance using the specified properties.
* @param [properties] Properties to set
* @returns ConnectionDenied instance
*/
public static create(properties?: IConnectionDenied): ConnectionDenied;
/**
* Encodes the specified ConnectionDenied message. Does not implicitly {@link ConnectionDenied.verify|verify} messages.
* @param message ConnectionDenied message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConnectionDenied, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConnectionDenied message, length delimited. Does not implicitly {@link ConnectionDenied.verify|verify} messages.
* @param message ConnectionDenied message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConnectionDenied, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConnectionDenied message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConnectionDenied
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ConnectionDenied;
/**
* Decodes a ConnectionDenied message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConnectionDenied
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ConnectionDenied;
/**
* Verifies a ConnectionDenied message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ConnectionDenied message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConnectionDenied
*/
public static fromObject(object: { [k: string]: any }): ConnectionDenied;
/**
* Creates a plain object from a ConnectionDenied message. Also converts values to other types if specified.
* @param message ConnectionDenied
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ConnectionDenied, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ConnectionDenied to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConnectionDenied {
/** Reason enum. */
enum Reason {
SERVER_FULL = 0,
WRONG_VERSION = 1
}
}
/** Properties of a ServerFull. */
export interface IServerFull {
/** ServerFull maxPlayers */
maxPlayers?: (number|null);
}
/** Represents a ServerFull. */
export class ServerFull implements IServerFull {
/**
* Constructs a new ServerFull.
* @param [properties] Properties to set
*/
constructor(properties?: IServerFull);
/** ServerFull maxPlayers. */
public maxPlayers: number;
/**
* Creates a new ServerFull instance using the specified properties.
* @param [properties] Properties to set
* @returns ServerFull instance
*/
public static create(properties?: IServerFull): ServerFull;
/**
* Encodes the specified ServerFull message. Does not implicitly {@link ServerFull.verify|verify} messages.
* @param message ServerFull message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IServerFull, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ServerFull message, length delimited. Does not implicitly {@link ServerFull.verify|verify} messages.
* @param message ServerFull message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IServerFull, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ServerFull message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ServerFull
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ServerFull;
/**
* Decodes a ServerFull message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ServerFull
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ServerFull;
/**
* Verifies a ServerFull message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ServerFull message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ServerFull
*/
public static fromObject(object: { [k: string]: any }): ServerFull;
/**
* Creates a plain object from a ServerFull message. Also converts values to other types if specified.
* @param message ServerFull
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ServerFull, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ServerFull to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a WrongVersion. */
export interface IWrongVersion {
/** WrongVersion majorVersion */
majorVersion?: (number|null);
/** WrongVersion minorVersion */
minorVersion?: (number|null);
}
/** Represents a WrongVersion. */
export class WrongVersion implements IWrongVersion {
/**
* Constructs a new WrongVersion.
* @param [properties] Properties to set
*/
constructor(properties?: IWrongVersion);
/** WrongVersion majorVersion. */
public majorVersion: number;
/** WrongVersion minorVersion. */
public minorVersion: number;
/**
* Creates a new WrongVersion instance using the specified properties.
* @param [properties] Properties to set
* @returns WrongVersion instance
*/
public static create(properties?: IWrongVersion): WrongVersion;
/**
* Encodes the specified WrongVersion message. Does not implicitly {@link WrongVersion.verify|verify} messages.
* @param message WrongVersion message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IWrongVersion, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified WrongVersion message, length delimited. Does not implicitly {@link WrongVersion.verify|verify} messages.
* @param message WrongVersion message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IWrongVersion, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a WrongVersion message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns WrongVersion
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): WrongVersion;
/**
* Decodes a WrongVersion message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns WrongVersion
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): WrongVersion;
/**
* Verifies a WrongVersion message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a WrongVersion message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns WrongVersion
*/
public static fromObject(object: { [k: string]: any }): WrongVersion;
/**
* Creates a plain object from a WrongVersion message. Also converts values to other types if specified.
* @param message WrongVersion
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: WrongVersion, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this WrongVersion to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PlayerData. */
export interface IPlayerData {
/** PlayerData dataLength */
dataLength?: (number|null);
/** PlayerData playerBytes */
playerBytes?: (IPlayerBytes[]|null);
}
/** Represents a PlayerData. */
export class PlayerData implements IPlayerData {
/**
* Constructs a new PlayerData.
* @param [properties] Properties to set
*/
constructor(properties?: IPlayerData);
/** PlayerData dataLength. */
public dataLength: number;
/** PlayerData playerBytes. */
public playerBytes: IPlayerBytes[];
/**
* Creates a new PlayerData instance using the specified properties.
* @param [properties] Properties to set
* @returns PlayerData instance
*/
public static create(properties?: IPlayerData): PlayerData;
/**
* Encodes the specified PlayerData message. Does not implicitly {@link PlayerData.verify|verify} messages.
* @param message PlayerData message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPlayerData, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PlayerData message, length delimited. Does not implicitly {@link PlayerData.verify|verify} messages.
* @param message PlayerData message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPlayerData, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PlayerData message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PlayerData
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PlayerData;
/**
* Decodes a PlayerData message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PlayerData
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PlayerData;
/**
* Verifies a PlayerData message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PlayerData message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PlayerData
*/
public static fromObject(object: { [k: string]: any }): PlayerData;
/**
* Creates a plain object from a PlayerData message. Also converts values to other types if specified.
* @param message PlayerData
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: PlayerData, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PlayerData to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PlayerBytes. */
export interface IPlayerBytes {
/** PlayerBytes playerId */
playerId?: (number|null);
/** PlayerBytes playerData */
playerData?: (Uint8Array|null);
}
/** Represents a PlayerBytes. */
export class PlayerBytes implements IPlayerBytes {
/**
* Constructs a new PlayerBytes.
* @param [properties] Properties to set
*/
constructor(properties?: IPlayerBytes);
/** PlayerBytes playerId. */
public playerId: number;
/** PlayerBytes playerData. */
public playerData: Uint8Array;
/**
* Creates a new PlayerBytes instance using the specified properties.
* @param [properties] Properties to set
* @returns PlayerBytes instance
*/
public static create(properties?: IPlayerBytes): PlayerBytes;
/**
* Encodes the specified PlayerBytes message. Does not implicitly {@link PlayerBytes.verify|verify} messages.
* @param message PlayerBytes message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPlayerBytes, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PlayerBytes message, length delimited. Does not implicitly {@link PlayerBytes.verify|verify} messages.
* @param message PlayerBytes message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPlayerBytes, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PlayerBytes message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PlayerBytes
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PlayerBytes;
/**
* Decodes a PlayerBytes message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PlayerBytes
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PlayerBytes;
/**
* Verifies a PlayerBytes message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PlayerBytes message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PlayerBytes
*/
public static fromObject(object: { [k: string]: any }): PlayerBytes;
/**
* Creates a plain object from a PlayerBytes message. Also converts values to other types if specified.
* @param message PlayerBytes
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: PlayerBytes, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PlayerBytes to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Meta. */
export interface IMeta {
/** Meta length */
length?: (number|null);
/** Meta address */
address?: (number|null);
/** Meta data */
data?: (Uint8Array|null);
}
/** Represents a Meta. */
export class Meta implements IMeta {
/**
* Constructs a new Meta.
* @param [properties] Properties to set
*/
constructor(properties?: IMeta);
/** Meta length. */
public length: number;
/** Meta address. */
public address: number;
/** Meta data. */
public data: Uint8Array;
/**
* Creates a new Meta instance using the specified properties.
* @param [properties] Properties to set
* @returns Meta instance
*/
public static create(properties?: IMeta): Meta;
/**
* Encodes the specified Meta message. Does not implicitly {@link Meta.verify|verify} messages.
* @param message Meta message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IMeta, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Meta message, length delimited. Does not implicitly {@link Meta.verify|verify} messages.
* @param message Meta message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IMeta, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Meta message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Meta
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Meta;
/**
* Decodes a Meta message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Meta
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Meta;
/**
* Verifies a Meta message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Meta message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Meta
*/
public static fromObject(object: { [k: string]: any }): Meta;
/**
* Creates a plain object from a Meta message. Also converts values to other types if specified.
* @param message Meta
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Meta, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Meta to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a MetaData. */
export interface IMetaData {
/** MetaData metaData */
metaData?: (IMeta[]|null);
}
/** Represents a MetaData. */
export class MetaData implements IMetaData {
/**
* Constructs a new MetaData.
* @param [properties] Properties to set
*/
constructor(properties?: IMetaData);
/** MetaData metaData. */
public metaData: IMeta[];
/**
* Creates a new MetaData instance using the specified properties.
* @param [properties] Properties to set
* @returns MetaData instance
*/
public static create(properties?: IMetaData): MetaData;
/**
* Encodes the specified MetaData message. Does not implicitly {@link MetaData.verify|verify} messages.
* @param message MetaData message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IMetaData, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MetaData message, length delimited. Does not implicitly {@link MetaData.verify|verify} messages.
* @param message MetaData message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IMetaData, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MetaData message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MetaData
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): MetaData;
/**
* Decodes a MetaData message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MetaData
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): MetaData;
/**
* Verifies a MetaData message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a MetaData message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MetaData
*/
public static fromObject(object: { [k: string]: any }): MetaData;
/**
* Creates a plain object from a MetaData message. Also converts values to other types if specified.
* @param message MetaData
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: MetaData, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MetaData to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Chat. */
export interface IChat {
/** Chat chatType */
chatType?: (Chat.ChatType|null);
/** Chat senderId */
senderId?: (number|null);
/** Chat message */
message?: (string|null);
/** Chat global */
global?: (IChatGlobal|null);
/** Chat private */
"private"?: (IChatPrivate|null);
/** Chat command */
command?: (IChatCommand|null);
}
/** Represents a Chat. */
export class Chat implements IChat {
/**
* Constructs a new Chat.
* @param [properties] Properties to set
*/
constructor(properties?: IChat);
/** Chat chatType. */
public chatType: Chat.ChatType;
/** Chat senderId. */
public senderId: number;
/** Chat message. */
public message: string;
/** Chat global. */
public global?: (IChatGlobal|null);
/** Chat private. */
public private?: (IChatPrivate|null);
/** Chat command. */
public command?: (IChatCommand|null);
/** Chat messageType. */
public messageType?: ("global"|"private"|"command");
/**
* Creates a new Chat instance using the specified properties.
* @param [properties] Properties to set
* @returns Chat instance
*/
public static create(properties?: IChat): Chat;
/**
* Encodes the specified Chat message. Does not implicitly {@link Chat.verify|verify} messages.
* @param message Chat message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IChat, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Chat message, length delimited. Does not implicitly {@link Chat.verify|verify} messages.
* @param message Chat message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IChat, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Chat message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Chat
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Chat;
/**
* Decodes a Chat message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Chat
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Chat;
/**
* Verifies a Chat message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Chat message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Chat
*/
public static fromObject(object: { [k: string]: any }): Chat;
/**
* Creates a plain object from a Chat message. Also converts values to other types if specified.
* @param message Chat
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Chat, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Chat to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace Chat {
/** ChatType enum. */
enum ChatType {
GLOBAL = 0,
PRIVATE = 1,
COMMAND = 255
}
}
/** Properties of a ChatGlobal. */
export interface IChatGlobal {
}
/** Represents a ChatGlobal. */
export class ChatGlobal implements IChatGlobal {
/**
* Constructs a new ChatGlobal.
* @param [properties] Properties to set
*/
constructor(properties?: IChatGlobal);
/**
* Creates a new ChatGlobal instance using the specified properties.
* @param [properties] Properties to set
* @returns ChatGlobal instance
*/
public static create(properties?: IChatGlobal): ChatGlobal;
/**
* Encodes the specified ChatGlobal message. Does not implicitly {@link ChatGlobal.verify|verify} messages.
* @param message ChatGlobal message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IChatGlobal, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ChatGlobal message, length delimited. Does not implicitly {@link ChatGlobal.verify|verify} messages.
* @param message ChatGlobal message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IChatGlobal, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ChatGlobal message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ChatGlobal
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ChatGlobal;
/**
* Decodes a ChatGlobal message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ChatGlobal
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ChatGlobal;
/**
* Verifies a ChatGlobal message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ChatGlobal message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ChatGlobal
*/
public static fromObject(object: { [k: string]: any }): ChatGlobal;
/**
* Creates a plain object from a ChatGlobal message. Also converts values to other types if specified.
* @param message ChatGlobal
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ChatGlobal, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ChatGlobal to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ChatPrivate. */
export interface IChatPrivate {
/** ChatPrivate receiverId */
receiverId?: (number|null);
}
/** Represents a ChatPrivate. */
export class ChatPrivate implements IChatPrivate {
/**
* Constructs a new ChatPrivate.
* @param [properties] Properties to set
*/
constructor(properties?: IChatPrivate);
/** ChatPrivate receiverId. */
public receiverId: number;
/**
* Creates a new ChatPrivate instance using the specified properties.
* @param [properties] Properties to set
* @returns ChatPrivate instance
*/
public static create(properties?: IChatPrivate): ChatPrivate;
/**
* Encodes the specified ChatPrivate message. Does not implicitly {@link ChatPrivate.verify|verify} messages.
* @param message ChatPrivate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IChatPrivate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ChatPrivate message, length delimited. Does not implicitly {@link ChatPrivate.verify|verify} messages.
* @param message ChatPrivate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IChatPrivate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ChatPrivate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ChatPrivate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ChatPrivate;
/**
* Decodes a ChatPrivate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ChatPrivate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ChatPrivate;
/**
* Verifies a ChatPrivate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ChatPrivate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ChatPrivate
*/
public static fromObject(object: { [k: string]: any }): ChatPrivate;
/**
* Creates a plain object from a ChatPrivate message. Also converts values to other types if specified.
* @param message ChatPrivate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ChatPrivate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ChatPrivate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ChatCommand. */
export interface IChatCommand {
/** ChatCommand arguments */
"arguments"?: (string[]|null);
}
/** Represents a ChatCommand. */
export class ChatCommand implements IChatCommand {
/**
* Constructs a new ChatCommand.
* @param [properties] Properties to set
*/
constructor(properties?: IChatCommand);
/** ChatCommand arguments. */
public arguments: string[];
/**
* Creates a new ChatCommand instance using the specified properties.
* @param [properties] Properties to set
* @returns ChatCommand instance
*/
public static create(properties?: IChatCommand): ChatCommand;
/**
* Encodes the specified ChatCommand message. Does not implicitly {@link ChatCommand.verify|verify} messages.
* @param message ChatCommand message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IChatCommand, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ChatCommand message, length delimited. Does not implicitly {@link ChatCommand.verify|verify} messages.
* @param message ChatCommand message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IChatCommand, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ChatCommand message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ChatCommand
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ChatCommand;
/**
* Decodes a ChatCommand message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ChatCommand
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ChatCommand;
/**
* Verifies a ChatCommand message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ChatCommand message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ChatCommand
*/
public static fromObject(object: { [k: string]: any }): ChatCommand;
/**
* Creates a plain object from a ChatCommand message. Also converts values to other types if specified.
* @param message ChatCommand
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ChatCommand, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ChatCommand to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Compression enum. */
export enum Compression {
NONE = 0,
ZSTD = 1,
GZIP = 2
} | the_stack |
import { TextAlign, TextVerticalAlign, ImageLike, Dictionary, MapToType } from '../core/types';
import { parseRichText, parsePlainText } from './helper/parseText';
import TSpan, { TSpanStyleProps } from './TSpan';
import { retrieve2, each, normalizeCssArray, trim, retrieve3, extend, keys, defaults } from '../core/util';
import { DEFAULT_FONT, adjustTextX, adjustTextY } from '../contain/text';
import ZRImage from './Image';
import Rect from './shape/Rect';
import BoundingRect from '../core/BoundingRect';
import { MatrixArray } from '../core/matrix';
import Displayable, {
DisplayableStatePropNames,
DisplayableProps,
DEFAULT_COMMON_ANIMATION_PROPS
} from './Displayable';
import { ZRenderType } from '../zrender';
import Animator from '../animation/Animator';
import Transformable from '../core/Transformable';
import { ElementCommonState } from '../Element';
import { GroupLike } from './Group';
type TextContentBlock = ReturnType<typeof parseRichText>
type TextLine = TextContentBlock['lines'][0]
type TextToken = TextLine['tokens'][0]
// TODO Default value?
export interface TextStylePropsPart {
// TODO Text is assigned inside zrender
text?: string
fill?: string
stroke?: string
opacity?: number
fillOpacity?: number
strokeOpacity?: number
/**
* textStroke may be set as some color as a default
* value in upper applicaion, where the default value
* of lineWidth should be 0 to make sure that
* user can choose to do not use text stroke.
*/
lineWidth?: number
lineDash?: false | number[]
lineDashOffset?: number
borderDash?: false | number[]
borderDashOffset?: number
/**
* If `fontSize` or `fontFamily` exists, `font` will be reset by
* `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
* So do not visit it directly in upper application (like echarts),
* but use `contain/text#makeFont` instead.
*/
font?: string
/**
* The same as font. Use font please.
* @deprecated
*/
textFont?: string
/**
* It helps merging respectively, rather than parsing an entire font string.
*/
fontStyle?: 'normal' | 'italic' | 'oblique'
/**
* It helps merging respectively, rather than parsing an entire font string.
*/
fontWeight?: 'normal' | 'bold' | 'bolder' | 'lighter' | number
/**
* It helps merging respectively, rather than parsing an entire font string.
*/
fontFamily?: string
/**
* It helps merging respectively, rather than parsing an entire font string.
* Should be 12 but not '12px'.
*/
fontSize?: number | string
align?: TextAlign
verticalAlign?: TextVerticalAlign
/**
* Line height. Default to be text height of '国'
*/
lineHeight?: number
/**
* Width of text block. Not include padding
* Used for background, truncate, wrap
*/
width?: number | string
/**
* Height of text block. Not include padding
* Used for background, truncate
*/
height?: number
/**
* Reserved for special functinality, like 'hr'.
*/
tag?: string
textShadowColor?: string
textShadowBlur?: number
textShadowOffsetX?: number
textShadowOffsetY?: number
// Shadow, background, border of text box.
backgroundColor?: string | {
image: ImageLike | string
}
/**
* Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
*/
padding?: number | number[]
/**
* Margin of label. Used when layouting the label.
*/
margin?: number
borderColor?: string
borderWidth?: number
borderRadius?: number | number[]
/**
* Shadow color for background box.
*/
shadowColor?: string
/**
* Shadow blur for background box.
*/
shadowBlur?: number
/**
* Shadow offset x for background box.
*/
shadowOffsetX?: number
/**
* Shadow offset y for background box.
*/
shadowOffsetY?: number
}
export interface TextStyleProps extends TextStylePropsPart {
text?: string
x?: number
y?: number
/**
* Only support number in the top block.
*/
width?: number
/**
* Text styles for rich text.
*/
rich?: Dictionary<TextStylePropsPart>
/**
* Strategy when calculated text width exceeds textWidth.
* break: break by word
* break: will break inside the word
* truncate: truncate the text and show ellipsis
* Do nothing if not set
*/
overflow?: 'break' | 'breakAll' | 'truncate' | 'none'
/**
* Strategy when text lines exceeds textHeight.
* Do nothing if not set
*/
lineOverflow?: 'truncate'
/**
* Epllipsis used if text is truncated
*/
ellipsis?: string
/**
* Placeholder used if text is truncated to empty
*/
placeholder?: string
/**
* Min characters for truncating
*/
truncateMinChar?: number
}
export interface TextProps extends DisplayableProps {
style?: TextStyleProps
zlevel?: number
z?: number
z2?: number
culling?: boolean
cursor?: string
}
export type TextState = Pick<TextProps, DisplayableStatePropNames> & ElementCommonState
export type DefaultTextStyle = Pick<TextStyleProps, 'fill' | 'stroke' | 'align' | 'verticalAlign'> & {
autoStroke?: boolean
};
const DEFAULT_RICH_TEXT_COLOR = {
fill: '#000'
};
const DEFAULT_STROKE_LINE_WIDTH = 2;
// const DEFAULT_TEXT_STYLE: TextStyleProps = {
// x: 0,
// y: 0,
// fill: '#000',
// stroke: null,
// opacity: 0,
// fillOpacity:
// }
export const DEFAULT_TEXT_ANIMATION_PROPS: MapToType<TextProps, boolean> = {
style: defaults<MapToType<TextStyleProps, boolean>, MapToType<TextStyleProps, boolean>>({
fill: true,
stroke: true,
fillOpacity: true,
strokeOpacity: true,
lineWidth: true,
fontSize: true,
lineHeight: true,
width: true,
height: true,
textShadowColor: true,
textShadowBlur: true,
textShadowOffsetX: true,
textShadowOffsetY: true,
backgroundColor: true,
padding: true, // TODO needs normalize padding before animate
borderColor: true,
borderWidth: true,
borderRadius: true // TODO needs normalize radius before animate
}, DEFAULT_COMMON_ANIMATION_PROPS.style)
};
interface ZRText {
animate(key?: '', loop?: boolean): Animator<this>
animate(key: 'style', loop?: boolean): Animator<this['style']>
getState(stateName: string): TextState
ensureState(stateName: string): TextState
states: Dictionary<TextState>
stateProxy: (stateName: string) => TextState
}
class ZRText extends Displayable<TextProps> implements GroupLike {
type = 'text'
style: TextStyleProps
/**
* How to handling label overlap
*
* hidden:
*/
overlap: 'hidden' | 'show' | 'blur'
/**
* Will use this to calculate transform matrix
* instead of Element itseelf if it's give.
* Not exposed to developers
*/
innerTransformable: Transformable
private _children: (ZRImage | Rect | TSpan)[] = []
private _childCursor: 0
private _defaultStyle: DefaultTextStyle = DEFAULT_RICH_TEXT_COLOR
constructor(opts?: TextProps) {
super();
this.attr(opts);
}
childrenRef() {
return this._children;
}
update() {
super.update();
// Update children
if (this.styleChanged()) {
this._updateSubTexts();
}
for (let i = 0; i < this._children.length; i++) {
const child = this._children[i];
// Set common properties.
child.zlevel = this.zlevel;
child.z = this.z;
child.z2 = this.z2;
child.culling = this.culling;
child.cursor = this.cursor;
child.invisible = this.invisible;
}
}
updateTransform() {
const innerTransformable = this.innerTransformable;
if (innerTransformable) {
innerTransformable.updateTransform();
if (innerTransformable.transform) {
this.transform = innerTransformable.transform;
}
}
else {
super.updateTransform();
}
}
getLocalTransform(m?: MatrixArray): MatrixArray {
const innerTransformable = this.innerTransformable;
return innerTransformable
? innerTransformable.getLocalTransform(m)
: super.getLocalTransform(m);
}
// TODO override setLocalTransform?
getComputedTransform() {
if (this.__hostTarget) {
// Update host target transform
this.__hostTarget.getComputedTransform();
// Update text position.
this.__hostTarget.updateInnerText(true);
}
return super.getComputedTransform();
}
private _updateSubTexts() {
// Reset child visit cursor
this._childCursor = 0;
normalizeTextStyle(this.style);
this.style.rich
? this._updateRichTexts()
: this._updatePlainTexts();
this._children.length = this._childCursor;
this.styleUpdated();
}
addSelfToZr(zr: ZRenderType) {
super.addSelfToZr(zr);
for (let i = 0; i < this._children.length; i++) {
// Also need mount __zr for case like hover detection.
// The case: hover on a label (position: 'top') causes host el
// scaled and label Y position lifts a bit so that out of the
// pointer, then mouse move should be able to trigger "mouseout".
this._children[i].__zr = zr;
}
}
removeSelfFromZr(zr: ZRenderType) {
super.removeSelfFromZr(zr);
for (let i = 0; i < this._children.length; i++) {
this._children[i].__zr = null;
}
}
getBoundingRect(): BoundingRect {
if (this.styleChanged()) {
this._updateSubTexts();
}
if (!this._rect) {
// TODO: Optimize when using width and overflow: wrap/truncate
const tmpRect = new BoundingRect(0, 0, 0, 0);
const children = this._children;
const tmpMat: MatrixArray = [];
let rect = null;
for (let i = 0; i < children.length; i++) {
const child = children[i];
const childRect = child.getBoundingRect();
const transform = child.getLocalTransform(tmpMat);
if (transform) {
tmpRect.copy(childRect);
tmpRect.applyTransform(transform);
rect = rect || tmpRect.clone();
rect.union(tmpRect);
}
else {
rect = rect || childRect.clone();
rect.union(childRect);
}
}
this._rect = rect || tmpRect;
}
return this._rect;
}
// Can be set in Element. To calculate text fill automatically when textContent is inside element
setDefaultTextStyle(defaultTextStyle: DefaultTextStyle) {
// Use builtin if defaultTextStyle is not given.
this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
}
setTextContent(textContent: never) {
throw new Error('Can\'t attach text on another text');
}
// getDefaultStyleValue<T extends keyof TextStyleProps>(key: T): TextStyleProps[T] {
// // Default value is on the prototype.
// return this.style.prototype[key];
// }
protected _mergeStyle(targetStyle: TextStyleProps, sourceStyle: TextStyleProps) {
if (!sourceStyle) {
return targetStyle;
}
// DO deep merge on rich configurations.
const sourceRich = sourceStyle.rich;
const targetRich = targetStyle.rich || (sourceRich && {}); // Create a new one if source have rich but target don't
extend(targetStyle, sourceStyle);
if (sourceRich && targetRich) {
// merge rich and assign rich again.
this._mergeRich(targetRich, sourceRich);
targetStyle.rich = targetRich;
}
else if (targetRich) {
// If source rich not exists. DON'T override the target rich
targetStyle.rich = targetRich;
}
return targetStyle;
}
private _mergeRich(targetRich: TextStyleProps['rich'], sourceRich: TextStyleProps['rich']) {
const richNames = keys(sourceRich);
// Merge by rich names.
for (let i = 0; i < richNames.length; i++) {
const richName = richNames[i];
targetRich[richName] = targetRich[richName] || {};
extend(targetRich[richName], sourceRich[richName]);
}
}
getAnimationStyleProps() {
return DEFAULT_TEXT_ANIMATION_PROPS;
}
private _getOrCreateChild(Ctor: {new(): TSpan}): TSpan
private _getOrCreateChild(Ctor: {new(): ZRImage}): ZRImage
private _getOrCreateChild(Ctor: {new(): Rect}): Rect
private _getOrCreateChild(Ctor: {new(): TSpan | Rect | ZRImage}): TSpan | Rect | ZRImage {
let child = this._children[this._childCursor];
if (!child || !(child instanceof Ctor)) {
child = new Ctor();
}
this._children[this._childCursor++] = child;
child.__zr = this.__zr;
// TODO to users parent can only be group.
child.parent = this as any;
return child;
}
private _updatePlainTexts() {
const style = this.style;
const textFont = style.font || DEFAULT_FONT;
const textPadding = style.padding as number[];
const text = getStyleText(style);
const contentBlock = parsePlainText(text, style);
const needDrawBg = needDrawBackground(style);
const bgColorDrawn = !!(style.backgroundColor);
let outerHeight = contentBlock.outerHeight;
const textLines = contentBlock.lines;
const lineHeight = contentBlock.lineHeight;
const defaultStyle = this._defaultStyle;
const baseX = style.x || 0;
const baseY = style.y || 0;
const textAlign = style.align || defaultStyle.align || 'left';
const verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
let textX = baseX;
let textY = adjustTextY(baseY, contentBlock.contentHeight, verticalAlign);
if (needDrawBg || textPadding) {
// Consider performance, do not call getTextWidth util necessary.
let outerWidth = contentBlock.width;
textPadding && (outerWidth += textPadding[1] + textPadding[3]);
const boxX = adjustTextX(baseX, outerWidth, textAlign);
const boxY = adjustTextY(baseY, outerHeight, verticalAlign);
needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
}
// `textBaseline` is set as 'middle'.
textY += lineHeight / 2;
if (textPadding) {
textX = getTextXForPadding(baseX, textAlign, textPadding);
if (verticalAlign === 'top') {
textY += textPadding[0];
}
else if (verticalAlign === 'bottom') {
textY -= textPadding[2];
}
}
let defaultLineWidth = 0;
let useDefaultFill = false;
const textFill = getFill(
'fill' in style
? style.fill
: (useDefaultFill = true, defaultStyle.fill)
);
const textStroke = getStroke(
'stroke' in style
? style.stroke
: (!bgColorDrawn
// If we use "auto lineWidth" widely, it probably bring about some bad case.
// So the current strategy is:
// If `style.fill` is specified (i.e., `useDefaultFill` is `false`)
// (A) And if `textConfig.insideStroke/outsideStroke` is not specified as a color
// (i.e., `defaultStyle.autoStroke` is `true`), we do not actually display
// the auto stroke because we can not make sure wether the stoke is approperiate to
// the given `fill`.
// (B) But if `textConfig.insideStroke/outsideStroke` is specified as a color,
// we give the auto lineWidth to display the given stoke color.
&& (!defaultStyle.autoStroke || useDefaultFill)
)
? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
: null
);
const hasShadow = style.textShadowBlur > 0;
const fixedBoundingRect = style.width != null
&& (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
const calculatedLineHeight = contentBlock.calculatedLineHeight;
for (let i = 0; i < textLines.length; i++) {
const el = this._getOrCreateChild(TSpan);
// Always create new style.
const subElStyle: TSpanStyleProps = el.createStyle();
el.useStyle(subElStyle);
subElStyle.text = textLines[i];
subElStyle.x = textX;
subElStyle.y = textY;
// Always set textAlign and textBase line, because it is difficute to calculate
// textAlign from prevEl, and we dont sure whether textAlign will be reset if
// font set happened.
if (textAlign) {
subElStyle.textAlign = textAlign;
}
// Force baseline to be "middle". Otherwise, if using "top", the
// text will offset downward a little bit in font "Microsoft YaHei".
subElStyle.textBaseline = 'middle';
subElStyle.opacity = style.opacity;
// Fill after stroke so the outline will not cover the main part.
subElStyle.strokeFirst = true;
if (hasShadow) {
subElStyle.shadowBlur = style.textShadowBlur || 0;
subElStyle.shadowColor = style.textShadowColor || 'transparent';
subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
}
if (textStroke) {
subElStyle.stroke = textStroke as string;
subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
subElStyle.lineDash = style.lineDash;
subElStyle.lineDashOffset = style.lineDashOffset || 0;
}
if (textFill) {
subElStyle.fill = textFill as string;
}
subElStyle.font = textFont;
textY += lineHeight;
if (fixedBoundingRect) {
el.setBoundingRect(new BoundingRect(
adjustTextX(subElStyle.x, style.width, subElStyle.textAlign as TextAlign),
adjustTextY(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline as TextVerticalAlign),
style.width,
calculatedLineHeight
));
}
}
}
private _updateRichTexts() {
const style = this.style;
// TODO Only parse when text changed?
const text = getStyleText(style);
const contentBlock = parseRichText(text, style);
const contentWidth = contentBlock.width;
const outerWidth = contentBlock.outerWidth;
const outerHeight = contentBlock.outerHeight;
const textPadding = style.padding as number[];
const baseX = style.x || 0;
const baseY = style.y || 0;
const defaultStyle = this._defaultStyle;
const textAlign = style.align || defaultStyle.align;
const verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
const boxX = adjustTextX(baseX, outerWidth, textAlign);
const boxY = adjustTextY(baseY, outerHeight, verticalAlign);
let xLeft = boxX;
let lineTop = boxY;
if (textPadding) {
xLeft += textPadding[3];
lineTop += textPadding[0];
}
let xRight = xLeft + contentWidth;
if (needDrawBackground(style)) {
this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
}
const bgColorDrawn = !!(style.backgroundColor);
for (let i = 0; i < contentBlock.lines.length; i++) {
const line = contentBlock.lines[i];
const tokens = line.tokens;
const tokenCount = tokens.length;
const lineHeight = line.lineHeight;
let remainedWidth = line.width;
let leftIndex = 0;
let lineXLeft = xLeft;
let lineXRight = xRight;
let rightIndex = tokenCount - 1;
let token;
while (
leftIndex < tokenCount
&& (token = tokens[leftIndex], !token.align || token.align === 'left')
) {
this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
remainedWidth -= token.width;
lineXLeft += token.width;
leftIndex++;
}
while (
rightIndex >= 0
&& (token = tokens[rightIndex], token.align === 'right')
) {
this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
remainedWidth -= token.width;
lineXRight -= token.width;
rightIndex--;
}
// The other tokens are placed as textAlign 'center' if there is enough space.
lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
while (leftIndex <= rightIndex) {
token = tokens[leftIndex];
// Consider width specified by user, use 'center' rather than 'left'.
this._placeToken(
token, style, lineHeight, lineTop,
lineXLeft + token.width / 2, 'center', bgColorDrawn
);
lineXLeft += token.width;
leftIndex++;
}
lineTop += lineHeight;
}
}
private _placeToken(
token: TextToken,
style: TextStyleProps,
lineHeight: number,
lineTop: number,
x: number,
textAlign: string,
parentBgColorDrawn: boolean
) {
const tokenStyle = style.rich[token.styleName] || {};
tokenStyle.text = token.text;
// 'ctx.textBaseline' is always set as 'middle', for sake of
// the bias of "Microsoft YaHei".
const verticalAlign = token.verticalAlign;
let y = lineTop + lineHeight / 2;
if (verticalAlign === 'top') {
y = lineTop + token.height / 2;
}
else if (verticalAlign === 'bottom') {
y = lineTop + lineHeight - token.height / 2;
}
const needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
needDrawBg && this._renderBackground(
tokenStyle,
style,
textAlign === 'right'
? x - token.width
: textAlign === 'center'
? x - token.width / 2
: x,
y - token.height / 2,
token.width,
token.height
);
const bgColorDrawn = !!tokenStyle.backgroundColor;
const textPadding = token.textPadding;
if (textPadding) {
x = getTextXForPadding(x, textAlign, textPadding);
y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
}
const el = this._getOrCreateChild(TSpan);
const subElStyle: TSpanStyleProps = el.createStyle();
// Always create new style.
el.useStyle(subElStyle);
const defaultStyle = this._defaultStyle;
let useDefaultFill = false;
let defaultLineWidth = 0;
const textFill = getFill(
'fill' in tokenStyle ? tokenStyle.fill
: 'fill' in style ? style.fill
: (useDefaultFill = true, defaultStyle.fill)
);
const textStroke = getStroke(
'stroke' in tokenStyle ? tokenStyle.stroke
: 'stroke' in style ? style.stroke
: (
!bgColorDrawn
&& !parentBgColorDrawn
// See the strategy explained above.
&& (!defaultStyle.autoStroke || useDefaultFill)
) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
: null
);
const hasShadow = tokenStyle.textShadowBlur > 0
|| style.textShadowBlur > 0;
subElStyle.text = token.text;
subElStyle.x = x;
subElStyle.y = y;
if (hasShadow) {
subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
}
subElStyle.textAlign = textAlign as CanvasTextAlign;
// Force baseline to be "middle". Otherwise, if using "top", the
// text will offset downward a little bit in font "Microsoft YaHei".
subElStyle.textBaseline = 'middle';
subElStyle.font = token.font || DEFAULT_FONT;
subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
if (textStroke) {
subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
subElStyle.lineDashOffset = style.lineDashOffset || 0;
subElStyle.stroke = textStroke;
}
if (textFill) {
subElStyle.fill = textFill;
}
const textWidth = token.contentWidth;
const textHeight = token.contentHeight;
// NOTE: Should not call dirtyStyle after setBoundingRect. Or it will be cleared.
el.setBoundingRect(new BoundingRect(
adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign as TextAlign),
adjustTextY(subElStyle.y, textHeight, subElStyle.textBaseline as TextVerticalAlign),
textWidth,
textHeight
));
}
private _renderBackground(
style: TextStylePropsPart,
topStyle: TextStylePropsPart,
x: number,
y: number,
width: number,
height: number
) {
const textBackgroundColor = style.backgroundColor;
const textBorderWidth = style.borderWidth;
const textBorderColor = style.borderColor;
const isImageBg = textBackgroundColor && (textBackgroundColor as {image: ImageLike}).image;
const isPlainOrGradientBg = textBackgroundColor && !isImageBg;
const textBorderRadius = style.borderRadius;
const self = this;
let rectEl: Rect;
let imgEl: ZRImage;
if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
// Background is color
rectEl = this._getOrCreateChild(Rect);
rectEl.useStyle(rectEl.createStyle()); // Create an empty style.
rectEl.style.fill = null;
const rectShape = rectEl.shape;
rectShape.x = x;
rectShape.y = y;
rectShape.width = width;
rectShape.height = height;
rectShape.r = textBorderRadius;
rectEl.dirtyShape();
}
if (isPlainOrGradientBg) {
const rectStyle = rectEl.style;
rectStyle.fill = textBackgroundColor as string || null;
rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
}
else if (isImageBg) {
imgEl = this._getOrCreateChild(ZRImage);
imgEl.onload = function () {
// Refresh and relayout after image loaded.
self.dirtyStyle();
};
const imgStyle = imgEl.style;
imgStyle.image = (textBackgroundColor as {image: ImageLike}).image;
imgStyle.x = x;
imgStyle.y = y;
imgStyle.width = width;
imgStyle.height = height;
}
if (textBorderWidth && textBorderColor) {
const rectStyle = rectEl.style;
rectStyle.lineWidth = textBorderWidth;
rectStyle.stroke = textBorderColor;
rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
rectStyle.lineDash = style.borderDash;
rectStyle.lineDashOffset = style.borderDashOffset || 0;
rectEl.strokeContainThreshold = 0;
// Making shadow looks better.
if (rectEl.hasFill() && rectEl.hasStroke()) {
rectStyle.strokeFirst = true;
rectStyle.lineWidth *= 2;
}
}
const commonStyle = (rectEl || imgEl).style;
commonStyle.shadowBlur = style.shadowBlur || 0;
commonStyle.shadowColor = style.shadowColor || 'transparent';
commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
}
static makeFont(style: TextStylePropsPart): string {
// FIXME in node-canvas fontWeight is before fontStyle
// Use `fontSize` `fontFamily` to check whether font properties are defined.
let font = '';
if (style.fontSize || style.fontFamily || style.fontWeight) {
let fontSize = '';
if (
typeof style.fontSize === 'string'
&& (
style.fontSize.indexOf('px') !== -1
|| style.fontSize.indexOf('rem') !== -1
|| style.fontSize.indexOf('em') !== -1
)
) {
fontSize = style.fontSize;
}
else if (!isNaN(+style.fontSize)) {
fontSize = style.fontSize + 'px';
}
else {
fontSize = '12px';
}
font = [
style.fontStyle,
style.fontWeight,
fontSize,
// If font properties are defined, `fontFamily` should not be ignored.
style.fontFamily || 'sans-serif'
].join(' ');
}
return font && trim(font) || style.textFont || style.font;
}
}
const VALID_TEXT_ALIGN = {left: true, right: 1, center: 1};
const VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
export function normalizeTextStyle(style: TextStyleProps): TextStyleProps {
normalizeStyle(style);
each(style.rich, normalizeStyle);
return style;
}
function normalizeStyle(style: TextStylePropsPart) {
if (style) {
style.font = ZRText.makeFont(style);
let textAlign = style.align;
// 'middle' is invalid, convert it to 'center'
(textAlign as string) === 'middle' && (textAlign = 'center');
style.align = (
textAlign == null || VALID_TEXT_ALIGN[textAlign]
) ? textAlign : 'left';
// Compatible with textBaseline.
let verticalAlign = style.verticalAlign;
(verticalAlign as string) === 'center' && (verticalAlign = 'middle');
style.verticalAlign = (
verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]
) ? verticalAlign : 'top';
// TODO Should not change the orignal value.
const textPadding = style.padding;
if (textPadding) {
style.padding = normalizeCssArray(style.padding);
}
}
}
/**
* @param stroke If specified, do not check style.textStroke.
* @param lineWidth If specified, do not check style.textStroke.
*/
function getStroke(
stroke?: TextStylePropsPart['stroke'],
lineWidth?: number
) {
return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
? null
: ((stroke as any).image || (stroke as any).colorStops)
? '#000'
: stroke;
}
function getFill(
fill?: TextStylePropsPart['fill']
) {
return (fill == null || fill === 'none')
? null
// TODO pattern and gradient?
: ((fill as any).image || (fill as any).colorStops)
? '#000'
: fill;
}
function getTextXForPadding(x: number, textAlign: string, textPadding: number[]): number {
return textAlign === 'right'
? (x - textPadding[1])
: textAlign === 'center'
? (x + textPadding[3] / 2 - textPadding[1] / 2)
: (x + textPadding[3]);
}
function getStyleText(style: TextStylePropsPart): string {
// Compat: set number to text is supported.
// set null/undefined to text is supported.
let text = style.text;
text != null && (text += '');
return text;
}
/**
* If needs draw background
* @param style Style of element
*/
function needDrawBackground(style: TextStylePropsPart): boolean {
return !!(
style.backgroundColor
|| style.lineHeight
|| (style.borderWidth && style.borderColor)
);
}
export default ZRText; | the_stack |
import { SitePaging } from '@alfresco/js-api';
/* We are using functions instead of constants here to pass a new instance of the object each time */
export function getFakeSitePaging(): SitePaging {
return {
'list': {
'pagination': {
'count': 2,
'hasMoreItems': true,
'totalItems': 2,
'skipCount': 0,
'maxItems': 100
},
'entries': [
{
'entry': {
'role': 'SiteManager',
'visibility': 'PUBLIC',
'guid': 'fake-1',
'description': 'fake-test-site',
'id': 'fake-test-site',
'preset': 'site-dashboard',
'title': 'fake-test-site'
}
},
{
'entry': {
'role': 'SiteManager',
'visibility': 'PUBLIC',
'guid': 'fake-2',
'description': 'This is a Sample Alfresco Team site.',
'id': 'swsdp',
'preset': 'site-dashboard',
'title': 'fake-test-2'
}
}
]
}
};
}
export function getFakeSitePagingNoMoreItems(): SitePaging {
return {
'list': {
'pagination': {
'count': 2,
'hasMoreItems': false,
'totalItems': 2,
'skipCount': 0,
'maxItems': 100
},
'entries': [
{
'entry': {
'role': 'SiteManager',
'visibility': 'PUBLIC',
'guid': 'fake-1',
'description': 'fake-test-site',
'id': 'fake-test-site',
'preset': 'site-dashboard',
'title': 'fake-test-site'
}
},
{
'entry': {
'role': 'SiteManager',
'visibility': 'PUBLIC',
'guid': 'fake-2',
'description': 'This is a Sample Alfresco Team site.',
'id': 'swsdp',
'preset': 'site-dashboard',
'title': 'fake-test-2'
}
}
]
}
};
}
export function getFakeSitePagingFirstPage(): SitePaging {
return {
'list': {
'pagination': {
'count': 2,
'hasMoreItems': true,
'totalItems': 2,
'skipCount': 0,
'maxItems': 4
},
'entries': [
{
'entry': {
'role': 'SiteManager',
'visibility': 'PUBLIC',
'guid': 'fake-1',
'description': 'fake-test-site',
'id': 'fake-test-site',
'preset': 'site-dashboard',
'title': 'fake-test-site'
}
},
{
'entry': {
'role': 'SiteManager',
'visibility': 'PUBLIC',
'guid': 'fake-2',
'description': 'This is a Sample Alfresco Team site.',
'id': 'swsdp',
'preset': 'site-dashboard',
'title': 'fake-test-2'
}
}
]
}
};
}
export function getFakeSitePagingLastPage(): SitePaging {
return {
'list': {
'pagination': {
'count': 4,
'hasMoreItems': false,
'totalItems': 2,
'skipCount': 2,
'maxItems': 4
},
'entries': [
{
'entry': {
'role': 'SiteManager',
'visibility': 'PUBLIC',
'guid': 'fake-3',
'description': 'fake-test-3',
'id': 'fake-test-3',
'preset': 'site-dashboard',
'title': 'fake-test-3'
}
},
{
'entry': {
'role': 'SiteManager',
'visibility': 'PUBLIC',
'guid': 'fake-test-4',
'description': 'This is a Sample Alfresco Team site.',
'id': 'fake-test-4',
'preset': 'site-dashboard',
'title': 'fake-test-4'
}
}
]
}
};
}
export function getFakeSitePagingWithMembers() {
return new SitePaging({
'list': {
'entries': [{
'entry': {
'visibility': 'MODERATED',
'guid': 'b4cff62a-664d-4d45-9302-98723eac1319',
'description': 'This is a Sample Alfresco Team site.',
'id': 'MODERATED-SITE',
'preset': 'site-dashboard',
'title': 'FAKE-MODERATED-SITE'
},
'relations': {
'members': {
'list': {
'pagination': {
'count': 3,
'hasMoreItems': false,
'skipCount': 0,
'maxItems': 100
},
'entries': [
{
'entry': {
'role': 'SiteManager',
'person': {
'firstName': 'Administrator',
'emailNotificationsEnabled': true,
'company': {},
'id': 'admin',
'enabled': true,
'email': 'admin@alfresco.com'
},
'id': 'admin'
}
},
{
'entry': {
'role': 'SiteCollaborator',
'person': {
'lastName': 'Beecher',
'userStatus': 'Helping to design the look and feel of the new web site',
'jobTitle': 'Graphic Designer',
'statusUpdatedAt': '2011-02-15T20:20:13.432+0000',
'mobile': '0112211001100',
'emailNotificationsEnabled': true,
'description': 'Alice is a demo user for the sample Alfresco Team site.',
'telephone': '0112211001100',
'enabled': false,
'firstName': 'Alice',
'skypeId': 'abeecher',
'avatarId': '198500fc-1e99-4f5f-8926-248cea433366',
'location': 'Tilbury, UK',
'company': {
'organization': 'Moresby, Garland and Wedge',
'address1': '200 Butterwick Street',
'address2': 'Tilbury',
'address3': 'UK',
'postcode': 'ALF1 SAM1'
},
'id': 'abeecher',
'email': 'abeecher@example.com'
},
'id': 'abeecher'
}
}
]
}
}
}
}, {
'entry': {
'visibility': 'PUBLIC',
'guid': 'b4cff62a-664d-4d45-9302-98723eac1319',
'description': 'This is a Sample Alfresco Team site.',
'id': 'PUBLIC-SITE',
'preset': 'site-dashboard',
'title': 'FAKE-SITE-PUBLIC'
}
}, {
'entry': {
'visibility': 'PRIVATE',
'guid': 'b4cff62a-664d-4d45-9302-98723eac1319',
'description': 'This is a Sample Alfresco Team site.',
'id': 'MEMBER-SITE',
'preset': 'site-dashboard',
'title': 'FAKE-PRIVATE-SITE-MEMBER'
},
'relations': {
'members': {
'list': {
'pagination': {
'count': 3,
'hasMoreItems': false,
'skipCount': 0,
'maxItems': 100
},
'entries': [
{
'entry': {
'role': 'SiteManager',
'person': {
'firstName': 'Administrator',
'emailNotificationsEnabled': true,
'company': {},
'id': 'admin',
'enabled': true,
'email': 'admin@alfresco.com'
},
'id': 'test'
}
}
]
}
}
}
}
]
}
});
} | the_stack |
import { createApiService,
ApplicationsUtil,
BrowserActions,
BrowserVisibility,
LocalStorageUtil,
LoginPage, ModelsActions,
StringUtil,
UserModel,
UsersActions
} from '@alfresco/adf-testing';
import { AppDefinitionRepresentation } from '@alfresco/js-api';
import { browser, by, element } from 'protractor';
import { NavigationBarPage } from '../../core/pages/navigation-bar.page';
import { TasksPage } from './../pages/tasks.page';
import { ProcessServiceTabBarPage } from './../pages/process-service-tab-bar.page';
import { ProcessFiltersPage } from './../pages/process-filters.page';
import { infoDrawerConfiguration } from './../config/task.config';
import CONSTANTS = require('../../util/constants');
import moment = require('moment');
describe('Info Drawer', () => {
const app = browser.params.resources.Files.SIMPLE_APP_WITH_USER_FORM;
const loginPage = new LoginPage();
const navigationBarPage = new NavigationBarPage();
const taskPage = new TasksPage();
const processServiceTabBarPage = new ProcessServiceTabBarPage();
const processFiltersPage = new ProcessFiltersPage();
const apiService = createApiService();
const applicationsService = new ApplicationsUtil(apiService);
const modelsActions = new ModelsActions(apiService);
const usersActions = new UsersActions(apiService);
const firstComment = 'comm1';
const date = {
form: '12/08/2017',
header: 'Aug 12, 2017',
dateFormat: 'll'
};
const taskDetails = {
description: 'I am your Description',
dueDate: date.form,
status: 'Running',
priority: '0',
category: 'No category',
parentName: 'No parent',
dateFormat: 'll'
};
let processUserModelFullName: string;
let assigneeUserModelFullName: string;
let appCreated: AppDefinitionRepresentation;
let processUserModel;
beforeAll(async () => {
await apiService.loginWithProfile('admin');
const assigneeUserModel = await usersActions.createUser();
assigneeUserModelFullName = assigneeUserModel.firstName + ' ' + assigneeUserModel.lastName;
processUserModel = await usersActions.createUser(new UserModel({ tenantId: assigneeUserModel.tenantId }));
processUserModelFullName = processUserModel.firstName + ' ' + processUserModel.lastName;
await apiService.login(processUserModel.username, processUserModel.password);
appCreated = await applicationsService.importPublishDeployApp(app.file_path);
await loginPage.login(processUserModel.username, processUserModel.password);
});
afterAll(async () => {
await modelsActions.deleteModel(appCreated.id);
await apiService.loginWithProfile('admin');
await usersActions.deleteTenant(processUserModel.tenantId);
});
beforeEach(async () => {
await (await navigationBarPage.navigateToProcessServicesPage()).goToTaskApp();
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.MY_TASKS);
});
it('[C260319] New Task - displayed details', async () => {
const name = StringUtil.generateRandomString(5);
await taskPage.createTask({ ...taskDetails, formName: app.formName, name });
await taskPage.tasksListPage().getDataTable().waitTillContentLoaded();
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.INV_TASKS);
await taskPage.tasksListPage().checkContentIsDisplayed(name);
await taskPage.tasksListPage().selectRow(name);
await taskPage.checkTaskTitle(name);
await expect(await taskPage.taskDetails().isAssigneeClickable()).toBeTruthy();
await shouldHaveInfoDrawerDetails({
...taskDetails,
dueDate: date.header,
fullName: processUserModelFullName,
formName: app.formName
});
await taskPage.taskDetails().selectActivityTab();
await taskPage.taskDetails().checkIsEmptyCommentListDisplayed();
await taskPage.taskDetails().addComment(firstComment);
await taskPage.taskDetails().checkCommentIsDisplayed(firstComment);
await taskPage.taskDetails().clickCompleteFormTask();
});
it('[C260323] Priority - Editing field', async () => {
const name = StringUtil.generateRandomString(5);
await taskPage.createTask({ ...taskDetails, formName: app.formName, name });
await taskPage.tasksListPage().getDataTable().waitTillContentLoaded();
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.INV_TASKS);
await taskPage.tasksListPage().checkContentIsDisplayed(name);
await taskPage.tasksListPage().selectRow(name);
await taskPage.checkTaskTitle(name);
await expect(await taskPage.taskDetails().getPriority()).toEqual(taskDetails.priority);
await taskPage.taskDetails().updatePriority('40');
await taskPage.taskDetails().checkTaskDetailsDisplayed();
await expect(await taskPage.taskDetails().getPriority()).toEqual('40');
await taskPage.taskDetails().updatePriority();
await taskPage.taskDetails().checkTaskDetailsDisplayed();
await expect(await taskPage.taskDetails().getPriority()).toEqual('');
await taskPage.taskDetails().clickCompleteFormTask();
});
it('[C260325] Due Date - Changing', async () => {
const name = StringUtil.generateRandomString(5);
await taskPage.createTask({ ...taskDetails, formName: app.formName, name });
await taskPage.tasksListPage().getDataTable().waitTillContentLoaded();
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.INV_TASKS);
await taskPage.tasksListPage().checkContentIsDisplayed(name);
await taskPage.tasksListPage().selectRow(name);
await taskPage.checkTaskTitle(name);
await expect(await taskPage.taskDetails().isAssigneeClickable()).toBeTruthy();
await shouldHaveInfoDrawerDetails({
...taskDetails,
dueDate: date.header,
fullName: processUserModelFullName,
formName: app.formName
});
await taskPage.taskDetails().updateDueDate();
await expect(await taskPage.taskDetails().getDueDate()).toEqual(moment('Aug 1, 2017').format(taskDetails.dateFormat));
await taskPage.taskDetails().clickCompleteFormTask();
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.MY_TASKS);
await taskPage.tasksListPage().checkContentIsNotDisplayed(name);
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.INV_TASKS);
await taskPage.tasksListPage().checkContentIsNotDisplayed(name);
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.COMPLETED_TASKS);
await taskPage.tasksListPage().checkContentIsDisplayed(name);
await taskPage.tasksListPage().selectRow(name);
await taskPage.checkTaskTitle(name);
await shouldHaveInfoDrawerDetails({
...taskDetails,
dueDate: 'Aug 1, 2017',
status: 'Completed',
fullName: processUserModelFullName,
formName: app.formName
});
});
it('[C260329] Task with no form', async () => {
const name = StringUtil.generateRandomString(5);
await taskPage.createTask(<any> { ...taskDetails, formName: '', name });
await taskPage.tasksListPage().getDataTable().waitTillContentLoaded();
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.INV_TASKS);
await taskPage.tasksListPage().checkContentIsDisplayed(name);
await taskPage.tasksListPage().selectRow(name);
await shouldHaveInfoDrawerDetails({
...taskDetails,
dueDate: date.header,
fullName: processUserModelFullName,
formName: 'No form'
});
await taskPage.completeTaskNoForm();
});
it('[C260320] Assign user to the task', async () => {
const name = StringUtil.generateRandomString(5);
await taskPage.createTask(<any> { ...taskDetails, formName: app.formName, name });
await taskPage.tasksListPage().getDataTable().waitTillContentLoaded();
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.MY_TASKS);
await taskPage.tasksListPage().checkContentIsDisplayed(name);
await taskPage.tasksListPage().selectRow(name);
await taskPage.checkTaskTitle(name);
await shouldHaveInfoDrawerDetails({
...taskDetails,
dueDate: date.header,
fullName: processUserModelFullName,
formName: app.formName
});
await expect(await taskPage.taskDetails().isAssigneeClickable()).toBeTruthy();
await BrowserActions.click(taskPage.taskDetails().assigneeButton);
const cancelSearch = element(by.css('button[id="close-people-search"]'));
await BrowserVisibility.waitUntilElementIsPresent(cancelSearch);
await BrowserActions.click(cancelSearch);
await shouldHaveInfoDrawerDetails({
...taskDetails,
dueDate: date.header,
fullName: processUserModelFullName,
formName: app.formName
});
await expect(await taskPage.taskDetails().isAssigneeClickable()).toBeTruthy();
await BrowserActions.click(taskPage.taskDetails().assigneeButton);
const addPeople = element(by.css('button[id="add-people"]'));
await BrowserVisibility.waitUntilElementIsPresent(addPeople);
await BrowserActions.click(addPeople);
await shouldHaveInfoDrawerDetails({
...taskDetails,
dueDate: date.header,
fullName: processUserModelFullName,
formName: app.formName
});
await taskPage.taskDetails().updateAssignee(assigneeUserModelFullName);
await taskPage.tasksListPage().getDataTable().waitTillContentLoaded();
await taskPage.tasksListPage().checkContentIsNotDisplayed(app.taskName);
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.INV_TASKS);
await taskPage.tasksListPage().checkTaskListIsLoaded();
await taskPage.taskDetails().checkTaskDetailsDisplayed();
await browser.sleep(2000);
await shouldHaveInfoDrawerDetails({
...taskDetails,
dueDate: date.header,
fullName: assigneeUserModelFullName,
formName: app.formName
});
});
it('[C260326] Process with a task included', async () => {
await processServiceTabBarPage.clickProcessButton();
const startProcess = await processFiltersPage.startProcess();
await startProcess.enterProcessName('My process');
await startProcess.selectFromProcessDropdown(app.processName);
await startProcess.clickStartProcessButton();
await processServiceTabBarPage.clickTasksButton();
await taskPage.tasksListPage().getDataTable().waitTillContentLoaded();
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.INV_TASKS);
await taskPage.tasksListPage().checkContentIsDisplayed(app.taskName);
await taskPage.tasksListPage().selectRow(app.taskName);
await taskPage.checkTaskTitle(app.taskName);
await taskPage.taskDetails().checkTaskDetailsDisplayed();
await browser.sleep(2000);
await shouldHaveInfoDrawerDetails({
...taskDetails,
dueDate: 'No date',
description: 'No description',
parentName: app.processName,
fullName: processUserModelFullName,
formName: app.formName
});
await taskPage.taskDetails().clickCompleteFormTask();
});
it('[C260328] Description - Editing field', async () => {
const name = StringUtil.generateRandomString(5);
await taskPage.createTask({ ...taskDetails, formName: app.formName, name });
await taskPage.tasksListPage().getDataTable().waitTillContentLoaded();
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.INV_TASKS);
await taskPage.tasksListPage().checkContentIsDisplayed(name);
await taskPage.tasksListPage().selectRow(name);
await taskPage.checkTaskTitle(name);
await taskPage.taskDetails().checkTaskDetailsDisplayed();
await browser.sleep(2000);
await expect(await taskPage.taskDetails().isAssigneeClickable()).toBeTruthy();
await shouldHaveInfoDrawerDetails({
...taskDetails,
dueDate: 'Aug 12, 2017',
fullName: processUserModelFullName,
formName: app.formName
});
await taskPage.taskDetails().updateDescription('');
await expect(await taskPage.taskDetails().getDescriptionPlaceholder()).toEqual('No description');
await taskPage.taskDetails().updateDescription('Good Bye');
await expect(await taskPage.taskDetails().getDescription()).toEqual('Good Bye');
await taskPage.taskDetails().clickCompleteFormTask();
});
it('[C260505] Should be possible customised Task Header changing the adf-task-header field in the app.config.json', async () => {
await LocalStorageUtil.setConfigField('adf-task-header', JSON.stringify(infoDrawerConfiguration));
const name = StringUtil.generateRandomString(5);
await taskPage.createTask({ ...taskDetails, formName: app.formName, name });
await taskPage.tasksListPage().getDataTable().waitTillContentLoaded();
await taskPage.filtersPage().goToFilter(CONSTANTS.TASK_FILTERS.MY_TASKS);
await taskPage.tasksListPage().checkContentIsDisplayed(name);
await taskPage.tasksListPage().selectRow(name);
await taskPage.checkTaskTitle(name);
await expect(await taskPage.taskDetails().getAssignee()).toEqual(processUserModelFullName);
await expect(await taskPage.taskDetails().getStatus()).toEqual(taskDetails.status);
await expect(await taskPage.taskDetails().getPriority()).toEqual(taskDetails.priority);
await expect(await taskPage.taskDetails().getParentName()).toEqual(taskDetails.parentName);
await taskPage.taskDetails().checkDueDatePickerButtonIsNotDisplayed();
await taskPage.taskDetails().clickCompleteFormTask();
});
async function shouldHaveInfoDrawerDetails({ description, status, priority, category, parentName, dateFormat, formName, fullName, dueDate }) {
await expect(await taskPage.taskDetails().getAssignee()).toEqual(fullName);
await expect(await taskPage.taskDetails().getDescription()).toEqual(description);
await expect(await taskPage.taskDetails().getStatus()).toEqual(status);
await expect(await taskPage.taskDetails().getPriority()).toEqual(priority);
await expect(await taskPage.taskDetails().getDueDate()).toEqual(dueDate !== 'No date' ? moment(dueDate).format(dateFormat) : 'No date');
await expect(await taskPage.taskDetails().getCategory()).toEqual(category);
await expect(await taskPage.taskDetails().getParentName()).toEqual(parentName);
await expect(await taskPage.taskDetails().getCreated()).toEqual(moment(Date.now()).format(dateFormat));
await taskPage.taskDetails().waitFormNameEqual(formName);
}
}); | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import { DataProvider } from '../ojdataprovider';
import { editableValue, editableValueEventMap, editableValueSettableProperties } from '../ojeditablevalue';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojCheckboxset<K, D, V = any> extends editableValue<V[], ojCheckboxsetSettableProperties<K, D, V>> {
disabled: boolean;
displayOptions?: {
converterHint?: 'display' | 'none';
helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none';
messages?: 'display' | 'none';
validatorHint?: 'display' | 'none';
};
labelledBy: string | null;
optionRenderer?: ((param0: ojCheckboxset.OptionContext<D>) => Element) | null;
options: DataProvider<K, D> | null;
optionsKeys?: ojCheckboxset.OptionsKeys;
readonly: boolean | null;
required: boolean;
value: V[] | null;
translations: {
readonlyNoValue?: string;
required?: {
hint?: string;
messageDetail?: string;
messageSummary?: string;
};
};
addEventListener<T extends keyof ojCheckboxsetEventMap<K, D, V>>(type: T, listener: (this: HTMLElement, ev: ojCheckboxsetEventMap<K, D, V>[T]) => any, options?: (boolean |
AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojCheckboxsetSettableProperties<K, D, V>>(property: T): ojCheckboxset<K, D, V>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojCheckboxsetSettableProperties<K, D, V>>(property: T, value: ojCheckboxsetSettableProperties<K, D, V>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojCheckboxsetSettableProperties<K, D, V>>): void;
setProperties(properties: ojCheckboxsetSettablePropertiesLenient<K, D, V>): void;
refresh(): void;
validate(): Promise<string>;
}
export namespace ojCheckboxset {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type disabledChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["disabled"]>;
// tslint:disable-next-line interface-over-type-literal
type displayOptionsChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["displayOptions"]>;
// tslint:disable-next-line interface-over-type-literal
type labelledByChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["labelledBy"]>;
// tslint:disable-next-line interface-over-type-literal
type optionRendererChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["optionRenderer"]>;
// tslint:disable-next-line interface-over-type-literal
type optionsChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["options"]>;
// tslint:disable-next-line interface-over-type-literal
type optionsKeysChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["optionsKeys"]>;
// tslint:disable-next-line interface-over-type-literal
type readonlyChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["readonly"]>;
// tslint:disable-next-line interface-over-type-literal
type requiredChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["required"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["value"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type describedByChanged<K, D, V = any> = editableValue.describedByChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type helpChanged<K, D, V = any> = editableValue.helpChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type helpHintsChanged<K, D, V = any> = editableValue.helpHintsChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type labelEdgeChanged<K, D, V = any> = editableValue.labelEdgeChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type labelHintChanged<K, D, V = any> = editableValue.labelHintChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type messagesCustomChanged<K, D, V = any> = editableValue.messagesCustomChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type userAssistanceDensityChanged<K, D, V = any> = editableValue.userAssistanceDensityChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type validChanged<K, D, V = any> = editableValue.validChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type Option = {
disabled?: boolean;
label?: string;
value: any;
};
// tslint:disable-next-line interface-over-type-literal
type OptionContext<D> = {
component: Element;
data: D;
index: number;
};
// tslint:disable-next-line interface-over-type-literal
type OptionsKeys = {
label?: string;
value?: string;
};
}
export interface ojCheckboxsetEventMap<K, D, V = any> extends editableValueEventMap<V[], ojCheckboxsetSettableProperties<K, D, V>> {
'ojAnimateEnd': ojCheckboxset.ojAnimateEnd;
'ojAnimateStart': ojCheckboxset.ojAnimateStart;
'disabledChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["disabled"]>;
'displayOptionsChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["displayOptions"]>;
'labelledByChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["labelledBy"]>;
'optionRendererChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["optionRenderer"]>;
'optionsChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["options"]>;
'optionsKeysChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["optionsKeys"]>;
'readonlyChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["readonly"]>;
'requiredChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["required"]>;
'valueChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["value"]>;
'describedByChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["describedBy"]>;
'helpChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["help"]>;
'helpHintsChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["helpHints"]>;
'labelEdgeChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["labelEdge"]>;
'labelHintChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["labelHint"]>;
'messagesCustomChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["messagesCustom"]>;
'userAssistanceDensityChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["userAssistanceDensity"]>;
'validChanged': JetElementCustomEvent<ojCheckboxset<K, D, V>["valid"]>;
}
export interface ojCheckboxsetSettableProperties<K, D, V> extends editableValueSettableProperties<V[]> {
disabled: boolean;
displayOptions?: {
converterHint?: 'display' | 'none';
helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none';
messages?: 'display' | 'none';
validatorHint?: 'display' | 'none';
};
labelledBy: string | null;
optionRenderer?: ((param0: ojCheckboxset.OptionContext<D>) => Element) | null;
options: DataProvider<K, D> | null;
optionsKeys?: ojCheckboxset.OptionsKeys;
readonly: boolean | null;
required: boolean;
value: V[] | null;
translations: {
readonlyNoValue?: string;
required?: {
hint?: string;
messageDetail?: string;
messageSummary?: string;
};
};
}
export interface ojCheckboxsetSettablePropertiesLenient<K, D, V> extends Partial<ojCheckboxsetSettableProperties<K, D, V>> {
[key: string]: any;
}
export type CheckboxsetElement<K, D, V = any> = ojCheckboxset<K, D, V>;
export namespace CheckboxsetElement {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type disabledChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["disabled"]>;
// tslint:disable-next-line interface-over-type-literal
type displayOptionsChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["displayOptions"]>;
// tslint:disable-next-line interface-over-type-literal
type labelledByChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["labelledBy"]>;
// tslint:disable-next-line interface-over-type-literal
type optionRendererChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["optionRenderer"]>;
// tslint:disable-next-line interface-over-type-literal
type optionsChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["options"]>;
// tslint:disable-next-line interface-over-type-literal
type optionsKeysChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["optionsKeys"]>;
// tslint:disable-next-line interface-over-type-literal
type readonlyChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["readonly"]>;
// tslint:disable-next-line interface-over-type-literal
type requiredChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["required"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged<K, D, V = any> = JetElementCustomEvent<ojCheckboxset<K, D, V>["value"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type describedByChanged<K, D, V = any> = editableValue.describedByChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type helpChanged<K, D, V = any> = editableValue.helpChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type helpHintsChanged<K, D, V = any> = editableValue.helpHintsChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type labelEdgeChanged<K, D, V = any> = editableValue.labelEdgeChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type labelHintChanged<K, D, V = any> = editableValue.labelHintChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type messagesCustomChanged<K, D, V = any> = editableValue.messagesCustomChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type userAssistanceDensityChanged<K, D, V = any> = editableValue.userAssistanceDensityChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type validChanged<K, D, V = any> = editableValue.validChanged<V[], ojCheckboxsetSettableProperties<K, D, V>>;
// tslint:disable-next-line interface-over-type-literal
type Option = {
disabled?: boolean;
label?: string;
value: any;
};
// tslint:disable-next-line interface-over-type-literal
type OptionsKeys = {
label?: string;
value?: string;
};
}
export interface CheckboxsetIntrinsicProps extends Partial<Readonly<ojCheckboxsetSettableProperties<any, any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onojAnimateEnd?: (value: ojCheckboxsetEventMap<any, any, any>['ojAnimateEnd']) => void;
onojAnimateStart?: (value: ojCheckboxsetEventMap<any, any, any>['ojAnimateStart']) => void;
ondisabledChanged?: (value: ojCheckboxsetEventMap<any, any, any>['disabledChanged']) => void;
ondisplayOptionsChanged?: (value: ojCheckboxsetEventMap<any, any, any>['displayOptionsChanged']) => void;
onlabelledByChanged?: (value: ojCheckboxsetEventMap<any, any, any>['labelledByChanged']) => void;
onoptionRendererChanged?: (value: ojCheckboxsetEventMap<any, any, any>['optionRendererChanged']) => void;
onoptionsChanged?: (value: ojCheckboxsetEventMap<any, any, any>['optionsChanged']) => void;
onoptionsKeysChanged?: (value: ojCheckboxsetEventMap<any, any, any>['optionsKeysChanged']) => void;
onreadonlyChanged?: (value: ojCheckboxsetEventMap<any, any, any>['readonlyChanged']) => void;
onrequiredChanged?: (value: ojCheckboxsetEventMap<any, any, any>['requiredChanged']) => void;
onvalueChanged?: (value: ojCheckboxsetEventMap<any, any, any>['valueChanged']) => void;
ondescribedByChanged?: (value: ojCheckboxsetEventMap<any, any, any>['describedByChanged']) => void;
onhelpChanged?: (value: ojCheckboxsetEventMap<any, any, any>['helpChanged']) => void;
onhelpHintsChanged?: (value: ojCheckboxsetEventMap<any, any, any>['helpHintsChanged']) => void;
onlabelEdgeChanged?: (value: ojCheckboxsetEventMap<any, any, any>['labelEdgeChanged']) => void;
onlabelHintChanged?: (value: ojCheckboxsetEventMap<any, any, any>['labelHintChanged']) => void;
onmessagesCustomChanged?: (value: ojCheckboxsetEventMap<any, any, any>['messagesCustomChanged']) => void;
onuserAssistanceDensityChanged?: (value: ojCheckboxsetEventMap<any, any, any>['userAssistanceDensityChanged']) => void;
onvalidChanged?: (value: ojCheckboxsetEventMap<any, any, any>['validChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-checkboxset": CheckboxsetIntrinsicProps;
}
}
} | the_stack |
import _ from 'lodash'
//import x509 from 'x509'
import {ActionGroupSpec, ActionContextType, ActionOutputStyle, ActionOutput, ActionContextOrder} from '../actions/actionSpec'
import K8sFunctions from '../k8s/k8sFunctions'
import IstioFunctions from '../k8s/istioFunctions'
import ChoiceManager, {ItemSelection} from '../actions/choiceManager'
import { ContainerInfo, PodDetails, ServiceDetails, Cluster } from '../k8s/k8sObjectTypes';
import { K8sClient } from '../k8s/k8sClient';
import {outputIngressVirtualServicesAndGatewaysForService} from './analyzeIstioIngress'
const plugin : ActionGroupSpec = {
context: ActionContextType.Istio,
title: "Analysis Recipes",
order: ActionContextOrder.Analysis,
actions: [
{
name: "Analyze Service Details and Routing",
order: 1,
loadingMessage: "Loading Services...",
choose: ChoiceManager.chooseService.bind(ChoiceManager, 1, 1),
async act(actionContext) {
const selections: ItemSelection[] = await ChoiceManager.getServiceSelections(actionContext)
if(selections.length < 1) {
this.onOutput && this.onOutput([["No service selected"]], ActionOutputStyle.Text)
return
}
this.showOutputLoading && this.showOutputLoading(true)
const service = selections[0].item
const namespace = selections[0].namespace
const cluster = actionContext.getClusters()
.filter(c => c.name === selections[0].cluster)[0]
this.onOutput && this.onOutput([["Service Analysis for: " + service.name
+ ", Namespace: " + namespace + ", Cluster: " + cluster.name]], ActionOutputStyle.Table)
this.onStreamOutput && this.onStreamOutput([[">Service Details"], [service.yaml]])
const podsAndContainers = await K8sFunctions.getPodsAndContainersForService(service, cluster.k8sClient, true)
this.outputPodsAndContainers(podsAndContainers)
if(cluster.hasIstio) {
const serviceEntries = await this.outputServiceEntries(service, cluster.k8sClient)
const sidecarConfigs = await this.outputSidecarConfigs(service, cluster.k8sClient)
const vsGateways = await this.outputVirtualServicesAndGateways(service, cluster.k8sClient)
const ingressPods = await IstioFunctions.getIngressGatewayPods(cluster.k8sClient, true)
if(Object.keys(vsGateways.ingressCerts).length > 0) {
await this.outputCertsStatus(vsGateways.ingressCerts, ingressPods, cluster.k8sClient)
}
await this.outputPolicies(service, cluster.k8sClient)
await this.outputDestinationRules(service, cluster.k8sClient)
this.showOutputLoading && this.showOutputLoading(true)
await this.outputRoutingAnalysis(service, podsAndContainers, vsGateways, ingressPods,
sidecarConfigs, cluster)
this.showOutputLoading && this.showOutputLoading(true)
await this.outputIngressGatewayConfigs(service, cluster.k8sClient)
} else {
this.onStreamOutput && this.onStreamOutput([[">>Istio not installed"]])
}
this.showOutputLoading && this.showOutputLoading(false)
},
refresh(actionContext) {
this.act(actionContext)
},
async outputPodsAndContainers(podsAndContainers) {
const containers = (podsAndContainers.containers as ContainerInfo[]) || []
const isSidecarPresent = containers.filter(c => c.name === "istio-proxy").length === 1
this.onStreamOutput && this.onStreamOutput([[">Envoy Sidecar Status"],
[isSidecarPresent ? "Sidecar Proxy Present" : "Sidecar Proxy Not Deployed"]])
this.onStreamOutput && this.onStreamOutput([[">Service Containers"]])
if(containers.length > 0) {
containers.map(c => this.onStreamOutput && this.onStreamOutput([[">>"+c.name],[c]]))
} else {
this.onStreamOutput && this.onStreamOutput([["No containers"]])
}
const pods = podsAndContainers.pods as PodDetails[]
this.onStreamOutput && this.onStreamOutput([[">Service Pods"]])
if(pods && pods.length > 0) {
pods.forEach(pod => this.onStreamOutput && this.onStreamOutput([
[">>"+pod.name],
[{
creationTimestamp: pod.creationTimestamp,
labels: pod.labels,
annotations: pod.annotations,
nodeName: pod.nodeName,
podIP: pod.podIP,
hostIP: pod.hostIP,
phase: pod.phase,
startTime: pod.startTime,
conditions: pod.conditions,
containerStatuses: pod.containerStatuses,
initContainerStatuses: pod.initContainerStatuses,
}]
]))
} else {
this.onStreamOutput && this.onStreamOutput([["No pods"]])
}
return podsAndContainers
},
async outputVirtualServicesAndGateways(service: ServiceDetails, k8sClient: K8sClient) {
const output: ActionOutput = []
const result = await outputIngressVirtualServicesAndGatewaysForService(service.name, service.namespace, k8sClient, output, true)
this.onStreamOutput && this.onStreamOutput(output)
return result
},
async outputDNSCheck(service: ServiceDetails, cluster: Cluster, output: ActionOutput) {
let clientPodForDNSLookup, container
if(cluster.hasIstio) {
clientPodForDNSLookup = await IstioFunctions.getAnyIngressGatewayPod(cluster.k8sClient)
container = "istio-proxy"
} else {
clientPodForDNSLookup = await K8sFunctions.getAnyKubeAPIServerPod(cluster.k8sClient)
container = "kube-apiserver"
}
const shortFqdn = service.name+"."+service.namespace
const fullFqdn = shortFqdn+".svc.cluster.local"
let result = await K8sFunctions.lookupDNSForFqdn(shortFqdn, clientPodForDNSLookup.namespace,
clientPodForDNSLookup.name, container, cluster.k8sClient)
let ipMatched = result && result === service.clusterIP
let succeeded = result && ipMatched
let message = (succeeded ? "" : "[CONFLICT] ") + "DNS Check for Short Fqdn: " + shortFqdn +
(succeeded ? " succeeded, IP: "+result : " failed. ")
result && !ipMatched && (message += "Expected Service IP ["+service.clusterIP+"] but received ["+result+"]")
output.push([message])
result = await K8sFunctions.lookupDNSForFqdn(fullFqdn, clientPodForDNSLookup.namespace,
clientPodForDNSLookup.name, container, cluster.k8sClient)
output.push([(result ? "" : "[CONFLICT] ") + "DNS Check for Full Fqdn: " + fullFqdn + (result ? " succeeded, IP: "+result : " failed")])
},
async outputRoutingAnalysis(service: ServiceDetails, podsAndContainers: any, vsGateways: any, ingressPods: any[],
sidecarConfigs, cluster: Cluster, asSubgroups: boolean = false) {
const output: ActionOutput = []
output.push([(asSubgroups ? ">>" : ">") + "Routing Analysis"])
await this.outputDNSCheck(service, cluster, output)
const hasPods = podsAndContainers.pods && podsAndContainers.pods.length > 0
if(!hasPods) {
output.push(["No pods found for the service."])
} else {
const containerPorts = podsAndContainers.containers ?
_.flatten((podsAndContainers.containers as ContainerInfo[])
.map(c => c.ports ? _.flatten(c.ports.map(p => [p.containerPort, p.name])) : [])) : []
const serviceTargetPorts = service.ports.map(p => p.targetPort)
const invalidServiceTargetPorts = serviceTargetPorts.filter(p => !containerPorts.includes(p))
output.push([
invalidServiceTargetPorts.length > 0 ?
"[CONFLICT] Found service target ports that are mismatched and don't exist as container ports: " + invalidServiceTargetPorts.join(", ")
: "Service target ports correctly match container ports."
])
}
if(vsGateways.virtualServices.length > 0) {
const servicePorts = service.ports.map(p => p.port)
const vsDestinationPorts =
_.flatten(
_.flatten(vsGateways.virtualServices.filter(vs => vs.http).map(vs => vs.http)
.concat(vsGateways.virtualServices.filter(vs => vs.tls).map(vs => vs.tls))
.concat(vsGateways.virtualServices.filter(vs => vs.tcp).map(vs => vs.tcp)))
.filter(routeDetails => routeDetails.route)
.map(routeDetails => routeDetails.route)
)
.filter(route => route.destination && route.destination.port)
.map(route => route.destination.port.number)
const invalidVSDestPorts = vsDestinationPorts.filter(p => !servicePorts.includes(p))
output.push([
invalidVSDestPorts.length > 0 ?
"Found VirtualService destination ports that are mismatched and don't exist as service ports: " + invalidVSDestPorts.join(", ")
: "VirtualService destination ports correctly match service ports."
])
}
const listeners = await IstioFunctions.getIngressGatewayEnvoyListeners(cluster.k8sClient)
const ingressPorts: number[] = []
listeners.forEach(l => ingressPorts.push(l.listener.address.socket_address.port_value))
vsGateways.gateways && vsGateways.gateways.forEach(g =>
g.matchingPorts && g.matchingPorts.forEach(port => {
const found = ingressPorts.includes(port)
output.push([
"Ingress Gateway is " + (found ? "" : "not ")
+ "listening for gateway port " + port + " for gateway " + g.name
])
}))
if(hasPods) {
if(cluster.canPodExec) {
if(ingressPods && ingressPods.length > 0 ) {
try {
const servicePods = podsAndContainers.pods as PodDetails[]
for(const pod of servicePods) {
if(pod.podIP) {
const result = await K8sFunctions.podExec("istio-system", ingressPods[0].name,
"istio-proxy", cluster.k8sClient, ["ping", "-c 2", pod.podIP])
const pingSuccess = result.includes("2 received")
output.push([
"Pod " + pod.name + (pingSuccess ? " is Reachable" : ": is Unreachable") + " from ingress gateway"
])
}
}
} catch(error) {}
}
else {
output.push(["Cannot verify pod reachability as no Ingress Gateway pods available"])
}
} else {
output.push(["Cannot verify pod reachability due to lack of pod command execution privileges"])
}
}
const egressHosts = _.uniqBy(_.flatten(_.flatten(sidecarConfigs.egressSidecarConfigs.map(s => s.egress))
.filter(e => e.hosts).map(e => e.hosts)))
if(egressHosts.length > 0) {
output.push(["Service can only reach out to the following namespace/service destinations: " + egressHosts.join(", ")])
}
const shortFqdn = "/"+service.name+"."+service.namespace
const fullFqdn = "/"+shortFqdn+".svc.cluster.local"
const sidecarsWithInvalidIncomingHosts = {}
sidecarConfigs.incomingSidecarConfigs.forEach(s => {
s.egress && s.egress.forEach(e => {
e.hosts && e.hosts.forEach(h => {
if(h.endsWith(shortFqdn) && ! h.endsWith(fullFqdn)) {
sidecarsWithInvalidIncomingHosts[s.name+"."+s.namespace] = h
}
})
})
})
const invalidSidecarNames = Object.keys(sidecarsWithInvalidIncomingHosts)
if(invalidSidecarNames.length > 0) {
output.push(["Following sidecars have invalid Egress Hosts config (must use full FQDN): " + invalidSidecarNames.join(", ")])
}
this.onStreamOutput && this.onStreamOutput(output)
},
async outputCertsStatus(ingressCerts: any, ingressPods: any[], k8sClient: K8sClient) {
const output: ActionOutput = []
output.push([">Service Ingress Certs"], [ingressCerts])
output.push([">Service Ingress Certs Deployment Status"])
const certPaths: string[] = []
Object.keys(ingressCerts).forEach(key => {
const cert = (ingressCerts[key] || "").trim()
if(cert.length > 0) {
certPaths.push(key)
certPaths.push(cert)
} else {
output.push([key + ": Loaded via SDS"])
}
})
if(certPaths.length > 0) {
if(k8sClient.canPodExec) {
for(const pod of ingressPods) {
output.push([">>Pod: " + pod.name])
try {
const certsLoadedOnIngress = _.flatten((await IstioFunctions.getIngressCertsFromPod(pod.name, k8sClient))
.filter(c => c.cert_chain)
.map(c => c.cert_chain)
.map(certChain => certChain instanceof Array ? certChain : [certChain]))
for(const path of certPaths) {
const result = (await K8sFunctions.podExec("istio-system", pod.name, "istio-proxy", k8sClient, ["ls", path])).trim()
const isPathFound = path === result
const certLoadedInfo = certsLoadedOnIngress.filter(info => (info.path || info).includes(path))[0]
const isPrivateKey = path.indexOf(".key") > 0
output.push([path + (isPathFound ? " is present " : " is NOT present ") + "on the pod filesystem"])
if(!isPrivateKey) {
output.push([path + (certLoadedInfo ? " is loaded on pod >> " +JSON.stringify(certLoadedInfo) : " is NOT loaded on ingress gateway pod")])
}
}
} catch(error) {
output.push(["Failed to check cert status due to error: " + error.message])
}
}
} else {
output.push(["Cannot check cert status due to lack of pod command execution privileges"])
}
}
this.onStreamOutput && this.onStreamOutput(output)
},
async outputPolicies(service: ServiceDetails, k8sClient: K8sClient) {
const policies = await IstioFunctions.getServicePolicies(service, k8sClient)
const output: ActionOutput = []
output.push([">Policies relevant to this service"])
policies.length === 0 && output.push(["No Policies"])
policies.forEach(p => output.push([">>"+p.name+"."+p.namespace],[p]))
this.onStreamOutput && this.onStreamOutput(output)
return policies
},
async outputDestinationRules(service: ServiceDetails, k8sClient: K8sClient) {
const destinationRules = await IstioFunctions.getServiceDestinationRules(service, k8sClient)
const output: ActionOutput = []
output.push([">DestinationRules relevant to this service"])
destinationRules.length === 0 && output.push(["No DestinationRules"])
destinationRules.forEach(dr => output.push([">>"+dr.name+"."+dr.namespace],[dr]))
this.onStreamOutput && this.onStreamOutput(output)
return destinationRules
},
async outputServiceEntries(service: ServiceDetails, k8sClient: K8sClient) {
const serviceEntries = await IstioFunctions.getServiceServiceEntries(service, k8sClient)
const output: ActionOutput = []
output.push([">ServiceEntries relevant to this service"])
serviceEntries.length === 0 && output.push(["No ServiceEntries"])
serviceEntries.forEach(se => output.push([">>"+se.name+"."+se.namespace],[se]))
this.onStreamOutput && this.onStreamOutput(output)
return serviceEntries
},
async outputSidecarConfigs(service: ServiceDetails, k8sClient: K8sClient) {
const egressSidecarConfigs = await IstioFunctions.getServiceEgressSidecarConfigs(service, k8sClient)
const incomingSidecarConfigs = await IstioFunctions.getServiceIncomingSidecarConfigs(service, k8sClient)
const output: ActionOutput = []
output.push([">Sidecar configs relevant to this service"])
output.push([">>Egress Sidecar configs"])
egressSidecarConfigs.length === 0 && output.push(["No Sidecar configs"])
egressSidecarConfigs.forEach(sc => {
delete sc.yaml
output.push([">>>"+sc.name+"."+sc.namespace])
output.push([sc])
})
output.push([">>Incoming Sidecar configs"])
incomingSidecarConfigs.length === 0 && output.push(["No Sidecar configs"])
incomingSidecarConfigs.forEach(sc => {
delete sc.yaml
output.push([">>>"+sc.name+"."+sc.namespace])
output.push([sc])
})
this.onStreamOutput && this.onStreamOutput(output)
return {egressSidecarConfigs, incomingSidecarConfigs}
},
async outputIngressGatewayConfigs(service: ServiceDetails, k8sClient: K8sClient) {
const configsByType = await IstioFunctions.getIngressEnvoyConfigsForService(service, k8sClient)
const output: ActionOutput = []
Object.keys(configsByType).forEach(configType => {
output.push([">IngressGateway " + configType + " configs relevant to this service"])
const configs = configsByType[configType]
configs.length === 0 && output.push(["No " + configType + " configs"])
configs.forEach(c => {
output.push([">>"+c.title])
output.push([c])
})
})
this.onStreamOutput && this.onStreamOutput(output)
},
},
],
}
export default plugin | the_stack |
import {
Injector,
Directive,
ElementRef,
EventEmitter,
forwardRef,
Renderer,
NgZone,
KeyValueDiffers,
IterableDiffers,
DefaultIterableDiffer
} from '@angular/core';
import {FormControlName, NG_VALUE_ACCESSOR} from '@angular/forms';
const Polymer: any = (<any>window).Polymer;
export function PolymerElement(name: string): any[] {
const propertiesWithNotify: Array<any> = [];
const arrayAndObjectProperties: Array<any> = [];
const proto: any = Object.getPrototypeOf(document.createElement(name));
if (proto.is !== name) {
throw new Error(`The Polymer element "${name}" has not been registered. Please check that the element is imported correctly.`);
}
const isFormElement: boolean = Polymer && Polymer.IronFormElementBehavior && proto.behaviors.indexOf(Polymer.IronFormElementBehavior) > -1;
const isCheckedElement: boolean = Polymer && Polymer.IronCheckedElementBehaviorImpl && proto.behaviors.indexOf(Polymer.IronCheckedElementBehaviorImpl) > -1;
proto.behaviors.forEach((behavior: any) => configureProperties(behavior.properties));
configureProperties(proto.properties);
function configureProperties(properties: any) {
if (properties) {
Object.getOwnPropertyNames(properties)
.filter(name => name.indexOf('_') !== 0)
.forEach(name => configureProperty(name, properties));
}
}
function configureProperty(name: string, properties: any) {
let info = properties[name];
if (typeof info === 'function') {
info = {
type: info
};
}
if (info.type && !info.readOnly && (info.type === Object || info.type === Array)) {
arrayAndObjectProperties.push(name);
}
if (info && info.notify) {
propertiesWithNotify.push(name);
}
}
const eventNameForProperty = (property: string) => `${property}Change`;
const changeEventsAdapterDirective = Directive({
selector: name,
outputs: propertiesWithNotify.map(eventNameForProperty),
host: propertiesWithNotify.reduce((hostBindings, property) => {
hostBindings[`(${Polymer.CaseMap.camelToDashCase(property)}-changed)`] = `_emitChangeEvent('${property}', $event);`;
return hostBindings;
}, {})
}).Class({
constructor: function () {
propertiesWithNotify
.forEach(property => this[eventNameForProperty(property)] = new EventEmitter<any>(false));
},
_emitChangeEvent(property: string, event: any) {
// Event is a notification for a sub-property when `path` exists and the
// event.detail.value holds a value for a sub-property.
// For sub-property changes we don't need to explicitly emit events,
// since all interested parties are bound to the same object and Angular
// takes care of updating sub-property bindings on changes.
if (!event.detail.path) {
this[eventNameForProperty(property)].emit(event.detail.value);
}
}
});
const validationDirective = Directive({
selector: name
}).Class({
constructor: [ElementRef, Injector, function (el: ElementRef, injector: Injector) {
this._element = el.nativeElement;
this._injector = injector;
}],
ngDoCheck: function () {
const control = this._injector.get(FormControlName, null);
if (control) {
this._element.invalid = !control.pristine && !control.valid;
}
}
});
const formElementDirective: any = Directive({
selector: name,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => formElementDirective),
multi: true
}
],
host: (isCheckedElement ? {'(checkedChange)': 'onValueChanged($event)'} : {'(valueChange)': 'onValueChanged($event)'})
}).Class({
constructor: [Renderer, ElementRef, function (renderer: Renderer, el: ElementRef) {
this._renderer = renderer;
this._element = el.nativeElement;
this._element.addEventListener('blur', () => this.onTouched(), true);
}],
onChange: (_: any) => {
},
onTouched: () => {
},
writeValue: function (value: any): void {
this._renderer.setElementProperty(this._element, (isCheckedElement ? 'checked' : 'value'), value);
},
registerOnChange: function (fn: (_: any) => void): void {
this.onChange = fn;
},
registerOnTouched: function (fn: () => void): void {
this.onTouched = fn;
},
onValueChanged: function (value: any) {
this.onChange(value);
}
});
const notifyForDiffersDirective = Directive({
selector: name,
inputs: arrayAndObjectProperties,
host: arrayAndObjectProperties.reduce((hostBindings, property) => {
hostBindings[`(${Polymer.CaseMap.camelToDashCase(property)}-changed)`] = `_setValueFromElement('${property}', $event);`;
return hostBindings;
}, {})
}).Class({
constructor: [ElementRef, IterableDiffers, KeyValueDiffers, function (el: ElementRef, iterableDiffers: IterableDiffers, keyValueDiffers: KeyValueDiffers) {
this._element = el.nativeElement;
this._iterableDiffers = iterableDiffers;
this._keyValueDiffers = keyValueDiffers;
this._differs = {};
this._arrayDiffs = {};
}],
ngOnInit() {
let elm = (<any>this)._element;
// In case the element has a default value and the directive doesn't have any value set for a property,
// we need to make sure the element value is set to the directive.
arrayAndObjectProperties.filter(property => elm[property] && !this[property])
.forEach(property => {
this[property] = elm[property];
});
},
_setValueFromElement(property: string, event: Event) {
// Properties in this directive need to be kept synced manually with the element properties.
// Don't use event.detail.value here because it might contain changes for a sub-property.
let target: any = event.target;
if (this[property] !== target[property]) {
this[property] = target[property];
(<any>this)._differs[property] = this._createDiffer(this[property]);
}
},
_createDiffer(value: string) {
let differ = Array.isArray(value) ? (<any>this)._iterableDiffers.find(value).create(null) : (<any>this)._keyValueDiffers.find(value || {}).create(null);
// initial diff with the current value to make sure the differ is synced
// and doesn't report any outdated changes on the next ngDoCheck call.
differ.diff(value);
return differ;
},
_handleArrayDiffs(property: string, diff: any) {
if (diff) {
diff.forEachRemovedItem((item: any) => this._notifyArray(property, item.previousIndex));
diff.forEachAddedItem((item: any) => this._notifyArray(property, item.currentIndex));
diff.forEachMovedItem((item: any) => this._notifyArray(property, item.currentIndex));
}
},
_handleObjectDiffs(property: string, diff: any) {
if (diff) {
let notify = (item: any) => this._notifyPath(property + '.' + item.key, item.currentValue);
diff.forEachRemovedItem(notify);
diff.forEachAddedItem(notify);
diff.forEachChangedItem(notify);
}
},
_notifyArray(property: string, index: number) {
this._notifyPath(property + '.' + index, this[property][index]);
},
_notifyPath(path: string, value: any) {
(<any>this)._element.notifyPath(path, value);
},
ngDoCheck() {
arrayAndObjectProperties.forEach(property => {
let elm = (<any>this)._element;
let _differs = (<any>this)._differs;
if (elm[property] !== this[property]) {
elm[property] = this[property];
_differs[property] = this._createDiffer(this[property]);
} else if (_differs[property]) {
// TODO: these differs won't pickup any changes in need properties like items[0].foo
let diff = _differs[property].diff(this[property]);
if (diff instanceof DefaultIterableDiffer) {
this._handleArrayDiffs(property, diff);
} else {
this._handleObjectDiffs(property, diff);
}
}
});
}
});
const reloadConfigurationDirective = Directive({
selector: name
}).Class({
constructor: [ElementRef, NgZone, function (el: ElementRef, zone: NgZone) {
el.nativeElement.async(() => {
if (el.nativeElement.isInitialized()) {
// Reload outside of Angular to prevent unnecessary ngDoCheck calls
zone.runOutsideAngular(() => {
el.nativeElement.reloadConfiguration();
});
}
});
}],
});
let directives = [changeEventsAdapterDirective, notifyForDiffersDirective];
if (isFormElement) {
directives.push(formElementDirective);
directives.push(validationDirective);
}
// If the element has isInitialized and reloadConfiguration methods (e.g., Charts)
if (typeof proto.isInitialized === 'function' &&
typeof proto.reloadConfiguration === 'function') {
directives.push(reloadConfigurationDirective);
}
return directives;
} | the_stack |
import EventEmitter from "eventemitter3";
import * as React from "react";
import { useState, useEffect } from "react";
import * as ReactDOM from "react-dom";
import {
createTheme,
loadTheme,
Fabric,
Stack,
ActionButton,
Pivot,
PivotItem,
Separator,
Text,
Link,
Icon,
ColorClassNames
} from "@fluentui/react";
import { Client as RPCClient } from "jsonrpc2-ws";
import { JoinParams, NotifyParams } from "../../lib/Mirakurun/rpc.d";
import { EventMessage } from "../../lib/Mirakurun/Event.d";
import { TunerDevice, Service, Status, Program } from "../../api.d";
import ConnectionGuide from "./components/ConnectionGuide";
import UpdateAlert from "./components/UpdateAlert";
import Restart from "./components/Restart";
import StatusView from "./components/StatusView";
import EventsView from "./components/EventsView";
import LogsView from "./components/LogsView";
import ConfigView from "./components/ConfigView";
import HeartView from "./components/HeartView";
import "./index.css";
export interface UIState {
version: string;
statusName: string;
statusIconName: string;
tuners: TunerDevice[];
services: Service[];
status: Status;
}
const uiState: UIState = {
version: "..",
statusName: "Loading",
statusIconName: "offline",
tuners: [],
services: [],
status: null
};
const uiStateEvents = new EventEmitter();
const iconSrcMap = {
normal: "icon.svg",
offline: "icon-gray.svg",
active: "icon-active.svg"
};
let statusRefreshInterval: any;
let servicesRefreshInterval: any;
function idleStatusChecker(): boolean {
let statusName = "Standby";
let statusIconName = "normal";
const isActive = uiState.tuners.some(tuner => tuner.isUsing === true && tuner.users.some(user => user.priority !== -1));
if (isActive) {
statusName = "Active";
statusIconName = "active";
}
if (uiState.statusName === statusName) {
return false;
}
uiState.statusName = statusName;
uiState.statusIconName = statusIconName;
uiStateEvents.emit("update");
return true;
}
uiStateEvents.on("update:tuners", idleStatusChecker);
const rpc = new RPCClient(`ws://${location.host}/rpc`, {
protocols: null
});
rpc.on("connecting", () => {
console.log("rpc:connecting");
uiState.statusName = "Connecting";
uiStateEvents.emit("update");
});
rpc.on("connected", async () => {
console.log("rpc:connected");
status: {
uiState.status = await rpc.call("getStatus");
statusRefreshInterval = setInterval(async () => {
if (document.hidden) {
return;
}
uiState.status = await rpc.call("getStatus");
uiStateEvents.emit("update:status");
}, 1000 * 3);
if (uiState.version !== ".." && uiState.version !== uiState.status.version) {
location.reload();
return;
}
uiState.version = uiState.status.version;
}
services: {
uiState.services = await (await fetch("/api/services")).json();
servicesRefreshInterval = setInterval(async () => {
if (document.hidden) {
return;
}
uiState.services = await (await fetch("/api/services")).json();
uiStateEvents.emit("update:services");
}, 1000 * 60);
}
uiState.tuners = await (await fetch("/api/tuners")).json();
await rpc.call("join", {
rooms: ["events:tuner", "events:service"]
} as JoinParams);
uiStateEvents.emit("update");
uiStateEvents.emit("update:status");
uiStateEvents.emit("update:services");
uiStateEvents.emit("update:tuners");
});
rpc.on("disconnect", () => {
console.log("rpc:disconnected");
clearInterval(statusRefreshInterval);
clearInterval(servicesRefreshInterval);
uiState.statusName = "Disconnected";
uiState.statusIconName = "offline";
uiStateEvents.emit("update");
});
rpc.methods.set("events", async (socket, { array }: NotifyParams<EventMessage>) => {
let reloadServiceRequired = false;
for (const event of array) {
if (event.resource === "service") {
const service: Service = event.data;
reloadServiceRequired = true;
for (const _service of uiState.services) {
if (_service.id === service.id) {
Object.assign(_service, service);
uiStateEvents.emit("update:services");
reloadServiceRequired = false;
break;
}
}
} else if (event.resource === "tuner") {
const tuner: TunerDevice = event.data;
uiState.tuners[uiState.tuners.findIndex(value => value.index === tuner.index)] = tuner;
uiStateEvents.emit("update:tuners");
}
}
if (reloadServiceRequired) {
uiState.services = await (await fetch("/api/services")).json();
uiStateEvents.emit("update:services");
}
uiStateEvents.emit("data:events", array);
});
rpc.methods.set("logs", (socket, { array }: NotifyParams<string> ) => {
uiStateEvents.emit("data:logs", array);
});
const Content = () => {
const [state, setState] = useState<UIState>(uiState);
useEffect(() => {
const title = `${state.statusName} - Mirakurun ${state.version}`;
if (document.title !== title) {
document.title = title;
}
const icon = document.getElementById("icon");
if (icon.getAttribute("href") !== iconSrcMap[state.statusIconName]) {
icon.setAttribute("href", iconSrcMap[state.statusIconName]);
}
const onStateUpdate = () => {
setState({ ...uiState });
};
uiStateEvents.on("update", onStateUpdate);
return () => {
uiStateEvents.removeListener("update", onStateUpdate);
};
});
return (
<Fabric style={{ margin: "16px" }}>
<Stack tokens={{ childrenGap: "8 0" }}>
<UpdateAlert />
<Stack horizontal verticalAlign="center" tokens={{ childrenGap: "0 8" }}>
<img style={{ height: "96px" }} src={iconSrcMap[state.statusIconName]} />
<div className="ms-fontSize-42">Mirakurun</div>
<Text variant="mediumPlus" nowrap block className={ColorClassNames.themePrimary}>{state.status?.version}</Text>
<Text variant="medium" nowrap block className={ColorClassNames.neutralTertiaryAlt}>({state.statusName})</Text>
<Stack.Item grow disableShrink> </Stack.Item>
<ConnectionGuide />
<ActionButton
iconProps={{ iconName: "KnowledgeArticle" }}
text="API Docs"
target="_blank"
href="/api/debug"
/>
<Restart uiStateEvents={uiStateEvents} />
</Stack>
<Pivot>
<PivotItem itemIcon="GroupedList" headerText="Status">
<StatusView uiState={uiState} uiStateEvents={uiStateEvents} />
</PivotItem>
<PivotItem itemIcon="EntitlementRedemption" headerText="Events">
<EventsView uiStateEvents={uiStateEvents} rpc={rpc} />
</PivotItem>
<PivotItem itemIcon="ComplianceAudit" headerText="Logs">
<LogsView uiStateEvents={uiStateEvents} rpc={rpc} />
</PivotItem>
<PivotItem itemIcon="Settings" headerText="Config">
<ConfigView uiState={uiState} uiStateEvents={uiStateEvents} />
</PivotItem>
<PivotItem itemIcon="Heart" headerText="Special Thanks">
<HeartView />
</PivotItem>
</Pivot>
<Stack>
<Separator />
<Text>
<Link href="https://github.com/Chinachu/Mirakurun" target="_blank">Mirakurun</Link> {state.version}
© 2016- <Link href="https://github.com/kanreisa" target="_blank">kanreisa</Link>.
</Text>
<Text>
<Icon iconName="Heart" /> <Link href="https://chinachu.moe/" target="_blank">Chinachu Project</Link>
(<Link href="https://github.com/Chinachu" target="_blank">GitHub</Link>)
</Text>
</Stack>
<Stack>
<Text variant="xSmall" className={ColorClassNames.neutralTertiaryAlt}>
Mirakurun comes with ABSOLUTELY NO WARRANTY. USE AT YOUR OWN RISK.
</Text>
</Stack>
</Stack>
</Fabric>
);
};
ReactDOM.render(
<Content />,
document.getElementById("root")
);
// dark theme
const myTheme = createTheme({
palette: {
themePrimary: '#ffd56c',
themeLighterAlt: '#0a0904',
themeLighter: '#292211',
themeLight: '#4d4020',
themeTertiary: '#998040',
themeSecondary: '#e0bc5e',
themeDarkAlt: '#ffd97a',
themeDark: '#ffdf8f',
themeDarker: '#ffe8ac',
neutralLighterAlt: '#2d2f37',
neutralLighter: '#34363f',
neutralLight: '#40424c',
neutralQuaternaryAlt: '#474a54',
neutralQuaternary: '#4e505b',
neutralTertiaryAlt: '#686b77',
neutralTertiary: '#f1f1f1',
neutralSecondary: '#f4f4f4',
neutralPrimaryAlt: '#f6f6f6',
neutralPrimary: '#ebebeb',
neutralDark: '#fafafa',
black: '#fdfdfd',
white: '#25272e',
}
});
loadTheme(myTheme); | the_stack |
import { expectAssignable, expectError, expectNotAssignable, expectNotType } from 'tsd';
import {
Decimal128,
Double,
Int32,
Long,
ObjectId,
Timestamp,
MongoClient,
Document
} from '../../../../src/index';
import type {
UpdateFilter,
MatchKeysAndValues,
AddToSetOperators,
ArrayOperator,
SetFields,
PushOperator,
PullOperator,
PullAllOperator
} from '../../../../src/mongo_types';
// MatchKeysAndValues - for basic mapping keys to their values, restricts that key types must be the same but optional, and permit dot array notation
expectAssignable<MatchKeysAndValues<{ a: number; b: string }>>({ a: 2, 'dot.notation': true });
expectNotType<MatchKeysAndValues<{ a: number; b: string }>>({ b: 2 });
// AddToSetOperators
expectAssignable<AddToSetOperators<number>>({ $each: [3] });
expectNotType<AddToSetOperators<number>>({ $each: ['hello'] });
// ArrayOperator
expectAssignable<ArrayOperator<number>>({ $each: [2] });
expectAssignable<ArrayOperator<number>>({ $slice: -2 });
expectAssignable<ArrayOperator<number>>({ $position: 1 });
expectAssignable<ArrayOperator<number>>({ $sort: 'asc' });
// SetFields - $addToSet
expectAssignable<SetFields<{ a: number[] }>>({ a: 2 });
// PushOperator - $push
expectAssignable<PushOperator<{ a: string[] }>>({ a: 'hello' });
// PullOperator - $pull
expectAssignable<PullOperator<{ a: string[]; b: number[] }>>({
a: { $in: ['apples', 'oranges'] },
b: 2
});
expectNotType<PullOperator<{ a: string[]; b: number[] }>>({
a: { $in: [2, 3] },
b: 'hello'
});
// PullOperator - $pull
expectAssignable<PullAllOperator<{ a: string[]; b: number[] }>>({ b: [0, 5] });
expectNotType<PullAllOperator<{ a: string[]; b: number[] }>>({ a: [0, 5] });
// Schema-less tests
expectAssignable<UpdateFilter<Document>>({});
expectAssignable<UpdateFilter<Document>>({ $inc: { anyKeyWhatsoever: 2 } });
// We can at least keep type assertions working inside the $inc ensuring provided values are numeric
// But this no longer asserts anything about what the original keys map to
expectNotType<UpdateFilter<Document>>({ $inc: { numberField: '2' } });
// collection.updateX tests
const client = new MongoClient('');
const db = client.db('test');
interface SubTestModel {
_id: ObjectId;
field1: string;
field2?: string;
}
type FruitTypes = 'apple' | 'pear';
// test with collection type
interface TestModel {
stringField: string;
numberField: number;
decimal128Field: Decimal128;
doubleField: Double;
int32Field: Int32;
longField: Long;
optionalNumberField?: number;
dateField: Date;
otherDateField: Date;
oneMoreDateField: Date;
fruitTags: string[];
readonlyFruitTags: ReadonlyArray<string>;
maybeFruitTags?: FruitTypes[];
subInterfaceField: SubTestModel;
subInterfaceArray: SubTestModel[];
timestampField: Timestamp;
}
const collectionTType = db.collection<TestModel>('test.update');
function buildUpdateFilter(updateQuery: UpdateFilter<TestModel>): UpdateFilter<TestModel> {
return updateQuery;
}
const justASample = buildUpdateFilter({ $currentDate: { dateField: true } });
expectAssignable<UpdateFilter<TestModel>>({ $currentDate: { dateField: true } });
expectAssignable<UpdateFilter<TestModel>>({ $currentDate: { otherDateField: { $type: 'date' } } });
expectAssignable<UpdateFilter<TestModel>>({
$currentDate: { otherDateField: { $type: 'timestamp' } }
});
expectAssignable<UpdateFilter<TestModel>>({
$currentDate: { timestampField: { $type: 'timestamp' } }
});
expectAssignable<UpdateFilter<TestModel>>({ $currentDate: { 'dot.notation': true } });
expectAssignable<UpdateFilter<TestModel>>({ $currentDate: { 'subInterfaceArray.$': true } });
expectAssignable<UpdateFilter<TestModel>>({
$currentDate: { 'subInterfaceArray.$[bla]': { $type: 'date' } }
});
expectAssignable<UpdateFilter<TestModel>>({
$currentDate: { 'subInterfaceArray.$[]': { $type: 'timestamp' } }
});
expectNotType<UpdateFilter<TestModel>>({ $currentDate: { stringField: true } }); // stringField is not a date Field
expectAssignable<UpdateFilter<TestModel>>({ $inc: { numberField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({
$inc: { decimal128Field: Decimal128.fromString('1.23') }
});
expectAssignable<UpdateFilter<TestModel>>({ $inc: { doubleField: new Double(1.23) } });
expectAssignable<UpdateFilter<TestModel>>({ $inc: { int32Field: new Int32(10) } });
expectAssignable<UpdateFilter<TestModel>>({ $inc: { longField: Long.fromString('999') } });
expectAssignable<UpdateFilter<TestModel>>({ $inc: { optionalNumberField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $inc: { 'dot.notation': 2 } });
expectAssignable<UpdateFilter<TestModel>>({
$inc: { 'dot.notation': Long.fromBigInt(BigInt(23)) }
});
expectAssignable<UpdateFilter<TestModel>>({ $inc: { 'subInterfaceArray.$': -10 } });
expectAssignable<UpdateFilter<TestModel>>({ $inc: { 'subInterfaceArray.$[bla]': 40 } });
expectAssignable<UpdateFilter<TestModel>>({ $inc: { 'subInterfaceArray.$[]': 1000.2 } });
expectAssignable<UpdateFilter<TestModel>>({ $bit: { numberField: { or: 3 } } });
expectAssignable<UpdateFilter<TestModel>>({ $bit: { numberField: { or: 3, and: 3, xor: 3 } } });
expectNotAssignable<UpdateFilter<TestModel>>({ $bit: { stringField: {} } });
expectAssignable<UpdateFilter<TestModel>>({ $min: { numberField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({
$min: { decimal128Field: Decimal128.fromString('1.23') }
});
expectAssignable<UpdateFilter<TestModel>>({ $min: { doubleField: new Double(1.23) } });
expectAssignable<UpdateFilter<TestModel>>({ $min: { int32Field: new Int32(10) } });
expectAssignable<UpdateFilter<TestModel>>({ $min: { longField: Long.fromString('999') } });
expectAssignable<UpdateFilter<TestModel>>({ $min: { stringField: 'a' } });
expectAssignable<UpdateFilter<TestModel>>({ $min: { 'dot.notation': 2 } });
expectAssignable<UpdateFilter<TestModel>>({ $min: { 'subInterfaceArray.$': 'string' } });
expectAssignable<UpdateFilter<TestModel>>({ $min: { 'subInterfaceArray.$[bla]': 40 } });
expectAssignable<UpdateFilter<TestModel>>({ $min: { 'subInterfaceArray.$[]': 1000.2 } });
expectNotType<UpdateFilter<TestModel>>({ $min: { numberField: 'a' } }); // Matches the type of the keys
expectAssignable<UpdateFilter<TestModel>>({ $max: { numberField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({
$max: { decimal128Field: Decimal128.fromString('1.23') }
});
expectAssignable<UpdateFilter<TestModel>>({ $max: { doubleField: new Double(1.23) } });
expectAssignable<UpdateFilter<TestModel>>({ $max: { int32Field: new Int32(10) } });
expectAssignable<UpdateFilter<TestModel>>({ $max: { longField: Long.fromString('999') } });
expectAssignable<UpdateFilter<TestModel>>({ $max: { stringField: 'a' } });
expectAssignable<UpdateFilter<TestModel>>({ $max: { 'dot.notation': 2 } });
expectAssignable<UpdateFilter<TestModel>>({ $max: { 'subInterfaceArray.$': -10 } });
expectAssignable<UpdateFilter<TestModel>>({ $max: { 'subInterfaceArray.$[bla]': 40 } });
expectAssignable<UpdateFilter<TestModel>>({ $max: { 'subInterfaceArray.$[]': 1000.2 } });
expectNotType<UpdateFilter<TestModel>>({ $min: { numberField: 'a' } }); // Matches the type of the keys
expectAssignable<UpdateFilter<TestModel>>({ $mul: { numberField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({
$mul: { decimal128Field: Decimal128.fromString('1.23') }
});
expectAssignable<UpdateFilter<TestModel>>({ $mul: { doubleField: new Double(1.23) } });
expectAssignable<UpdateFilter<TestModel>>({ $mul: { int32Field: new Int32(10) } });
expectAssignable<UpdateFilter<TestModel>>({ $mul: { longField: Long.fromString('999') } });
expectAssignable<UpdateFilter<TestModel>>({ $mul: { optionalNumberField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $mul: { 'dot.notation': 2 } });
expectAssignable<UpdateFilter<TestModel>>({ $mul: { 'subInterfaceArray.$': -10 } });
expectAssignable<UpdateFilter<TestModel>>({ $mul: { 'subInterfaceArray.$[bla]': 40 } });
expectAssignable<UpdateFilter<TestModel>>({ $mul: { 'subInterfaceArray.$[]': 1000.2 } });
expectAssignable<UpdateFilter<TestModel>>({ $set: { numberField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({
$set: { decimal128Field: Decimal128.fromString('1.23') }
});
expectAssignable<UpdateFilter<TestModel>>({ $set: { doubleField: new Double(1.23) } });
expectAssignable<UpdateFilter<TestModel>>({ $set: { int32Field: new Int32(10) } });
expectAssignable<UpdateFilter<TestModel>>({ $set: { longField: Long.fromString('999') } });
expectAssignable<UpdateFilter<TestModel>>({ $set: { stringField: 'a' } });
expectError(buildUpdateFilter({ $set: { stringField: 123 } }));
expectAssignable<UpdateFilter<TestModel>>({ $set: { 'dot.notation': 2 } });
expectAssignable<UpdateFilter<TestModel>>({ $set: { 'subInterfaceArray.$': -10 } });
expectAssignable<UpdateFilter<TestModel>>({ $set: { 'subInterfaceArray.$[bla]': 40 } });
expectAssignable<UpdateFilter<TestModel>>({ $set: { 'subInterfaceArray.$[]': 1000.2 } });
expectAssignable<UpdateFilter<TestModel>>({ $setOnInsert: { numberField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({
$setOnInsert: { decimal128Field: Decimal128.fromString('1.23') }
});
expectAssignable<UpdateFilter<TestModel>>({ $setOnInsert: { doubleField: new Double(1.23) } });
expectAssignable<UpdateFilter<TestModel>>({ $setOnInsert: { int32Field: new Int32(10) } });
expectAssignable<UpdateFilter<TestModel>>({ $setOnInsert: { longField: Long.fromString('999') } });
expectAssignable<UpdateFilter<TestModel>>({ $setOnInsert: { stringField: 'a' } });
expectError(buildUpdateFilter({ $setOnInsert: { stringField: 123 } }));
expectAssignable<UpdateFilter<TestModel>>({ $setOnInsert: { 'dot.notation': 2 } });
expectAssignable<UpdateFilter<TestModel>>({ $setOnInsert: { 'subInterfaceArray.$': -10 } });
expectAssignable<UpdateFilter<TestModel>>({ $setOnInsert: { 'subInterfaceArray.$[bla]': 40 } });
expectAssignable<UpdateFilter<TestModel>>({ $setOnInsert: { 'subInterfaceArray.$[]': 1000.2 } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { numberField: '' } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { decimal128Field: '' } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { doubleField: '' } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { int32Field: '' } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { longField: '' } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { dateField: '' } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { 'dot.notation': '' } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { 'subInterfaceArray.$': '' } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { 'subInterfaceArray.$[bla]': '' } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { 'subInterfaceArray.$[]': '' } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { numberField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { decimal128Field: 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { doubleField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { int32Field: 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { longField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { dateField: 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { 'dot.notation': 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { 'subInterfaceArray.$': 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { 'subInterfaceArray.$[bla]': 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $unset: { 'subInterfaceArray.$[]': 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $rename: { numberField2: 'stringField' } });
expectAssignable<UpdateFilter<TestModel>>({ $addToSet: { fruitTags: 'stringField' } });
expectError(buildUpdateFilter({ $addToSet: { fruitTags: 123 } }));
expectAssignable<UpdateFilter<TestModel>>({ $addToSet: { fruitTags: { $each: ['stringField'] } } });
expectAssignable<UpdateFilter<TestModel>>({ $addToSet: { readonlyFruitTags: 'apple' } });
expectAssignable<UpdateFilter<TestModel>>({
$addToSet: { readonlyFruitTags: { $each: ['apple'] } }
});
expectAssignable<UpdateFilter<TestModel>>({ $addToSet: { maybeFruitTags: 'apple' } });
expectAssignable<UpdateFilter<TestModel>>({ $addToSet: { 'dot.notation': 'stringField' } });
expectAssignable<UpdateFilter<TestModel>>({
$addToSet: { 'dot.notation': { $each: ['stringfield'] } }
});
expectAssignable<UpdateFilter<TestModel>>({
$addToSet: {
subInterfaceArray: { field1: 'foo' }
}
});
expectAssignable<UpdateFilter<TestModel>>({
$addToSet: {
subInterfaceArray: {
_id: new ObjectId(),
field1: 'foo'
}
}
});
expectAssignable<UpdateFilter<TestModel>>({
$addToSet: {
subInterfaceArray: {
$each: [{ field1: 'foo' }]
}
}
});
expectError(
buildUpdateFilter({
$addToSet: { subInterfaceArray: { field1: 123 } }
})
);
expectAssignable<UpdateFilter<TestModel>>({ $pop: { fruitTags: 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $pop: { fruitTags: -1 } });
expectAssignable<UpdateFilter<TestModel>>({ $pop: { 'dot.notation': 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $pop: { 'subInterfaceArray.$[]': -1 } });
expectAssignable<UpdateFilter<TestModel>>({ $pull: { fruitTags: 'a' } });
expectError(buildUpdateFilter({ $pull: { fruitTags: 123 } }));
expectAssignable<UpdateFilter<TestModel>>({ $pull: { fruitTags: { $in: ['a'] } } });
expectAssignable<UpdateFilter<TestModel>>({ $pull: { maybeFruitTags: 'apple' } });
expectAssignable<UpdateFilter<TestModel>>({ $pull: { 'dot.notation': 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $pull: { 'subInterfaceArray.$[]': { $in: ['a'] } } });
expectAssignable<UpdateFilter<TestModel>>({ $pull: { subInterfaceArray: { field1: 'a' } } });
expectAssignable<UpdateFilter<TestModel>>({
$pull: { subInterfaceArray: { _id: { $in: [new ObjectId()] } } }
});
expectAssignable<UpdateFilter<TestModel>>({
$pull: { subInterfaceArray: { field1: { $in: ['a'] } } }
});
expectAssignable<UpdateFilter<TestModel>>({ $push: { fruitTags: 'a' } });
expectError(buildUpdateFilter({ $push: { fruitTags: 123 } }));
expectAssignable<UpdateFilter<TestModel>>({ $push: { fruitTags: { $each: ['a'] } } });
expectAssignable<UpdateFilter<TestModel>>({ $push: { fruitTags: { $each: ['a'], $slice: 3 } } });
expectAssignable<UpdateFilter<TestModel>>({ $push: { fruitTags: { $each: ['a'], $position: 1 } } });
expectAssignable<UpdateFilter<TestModel>>({ $push: { fruitTags: { $each: ['a'], $sort: 1 } } });
expectAssignable<UpdateFilter<TestModel>>({ $push: { fruitTags: { $each: ['a'], $sort: -1 } } });
expectAssignable<UpdateFilter<TestModel>>({ $push: { fruitTags: { $each: ['stringField'] } } });
expectAssignable<UpdateFilter<TestModel>>({
$push: { fruitTags: { $each: ['a'], $sort: { 'sub.field': -1 } } }
});
expectAssignable<UpdateFilter<TestModel>>({ $push: { maybeFruitTags: 'apple' } });
expectAssignable<UpdateFilter<TestModel>>({
$push: {
subInterfaceArray: { _id: new ObjectId(), field1: 'foo' }
}
});
expectAssignable<UpdateFilter<TestModel>>({
$push: {
subInterfaceArray: {
_id: new ObjectId(),
field1: 'foo'
}
}
});
expectAssignable<UpdateFilter<TestModel>>({
$push: {
subInterfaceArray: {
$each: [
{
_id: new ObjectId(),
field1: 'foo',
field2: 'bar'
}
]
}
}
});
expectError(
buildUpdateFilter({
$push: { subInterfaceArray: { field1: 123 } }
})
);
expectAssignable<UpdateFilter<TestModel>>({ $push: { 'dot.notation': 1 } });
expectAssignable<UpdateFilter<TestModel>>({ $push: { 'subInterfaceArray.$[]': { $in: ['a'] } } });
collectionTType.updateOne({ stringField: 'bla' }, justASample);
collectionTType.updateMany(
{ numberField: 12 },
{
$set: {
stringField: 'Banana'
}
}
);
export async function testPushWithId(): Promise<void> {
interface Model {
_id: ObjectId;
foo: Array<{ _id?: string; name: string }>;
}
const client = new MongoClient('');
const db = client.db('test');
const collection = db.collection<Model>('test');
await collection.updateOne(
{},
{
$push: {
foo: { name: 'Foo' }
}
}
);
await collection.updateOne(
{},
{
$push: {
foo: { _id: 'foo', name: 'Foo' }
}
}
);
} | the_stack |
import '@material/mwc-button';
import '@material/mwc-dialog';
import '@material/mwc-icon';
import { BeforeEnterObserver, PreventAndRedirectCommands, Router, RouterLocation } from '@vaadin/router';
import { css, customElement, html } from 'lit-element';
import merge from 'lodash-es/merge';
import { autorun, computed, observable, reaction, when } from 'mobx';
import '../../components/test_count_indicator';
import '../../components/status_bar';
import '../../components/tab_bar';
import { OPTIONAL_RESOURCE } from '../../common_tags';
import { MiloBaseElement } from '../../components/milo_base';
import { TabDef } from '../../components/tab_bar';
import { AppState, consumeAppState } from '../../context/app_state';
import { BuildState, GetBuildError, provideBuildState } from '../../context/build_state';
import { InvocationState, provideInvocationState, QueryInvocationError } from '../../context/invocation_state';
import { consumeConfigsStore, DEFAULT_USER_CONFIGS, UserConfigs, UserConfigsStore } from '../../context/user_configs';
import { GA_ACTIONS, GA_CATEGORIES, trackEvent } from '../../libs/analytics_utils';
import { getLegacyURLPathForBuild, getURLPathForBuilder, getURLPathForProject } from '../../libs/build_utils';
import {
BUILD_STATUS_CLASS_MAP,
BUILD_STATUS_COLOR_MAP,
BUILD_STATUS_DISPLAY_MAP,
POTENTIALLY_EXPIRED,
} from '../../libs/constants';
import { consumer, provider } from '../../libs/context';
import {
errorHandler,
forwardWithoutMsg,
renderErrorInPre,
reportError,
reportRenderError,
} from '../../libs/error_handler';
import { attachTags, hasTags } from '../../libs/tag';
import { displayDuration, LONG_TIME_FORMAT } from '../../libs/time_utils';
import { LoadTestVariantsError } from '../../models/test_loader';
import { NOT_FOUND_URL, router } from '../../routes';
import { BuilderID, BuildStatus, TEST_PRESENTATION_KEY } from '../../services/buildbucket';
import colorClasses from '../../styles/color_classes.css';
import commonStyle from '../../styles/common_style.css';
const STATUS_FAVICON_MAP = Object.freeze({
[BuildStatus.Scheduled]: 'gray',
[BuildStatus.Started]: 'yellow',
[BuildStatus.Success]: 'green',
[BuildStatus.Failure]: 'red',
[BuildStatus.InfraFailure]: 'purple',
[BuildStatus.Canceled]: 'teal',
});
// An array of [buildTabName, buildTabLabel] tuples.
// Use an array of tuples instead of an Object to ensure order.
const TAB_NAME_LABEL_TUPLES = Object.freeze([
Object.freeze(['build-overview', 'Overview']),
Object.freeze(['build-test-results', 'Test Results']),
Object.freeze(['build-steps', 'Steps & Logs']),
Object.freeze(['build-related-builds', 'Related Builds']),
Object.freeze(['build-timeline', 'Timeline']),
Object.freeze(['build-blamelist', 'Blamelist']),
]);
function retryWithoutComputedInvId(err: ErrorEvent, ele: BuildPageElement) {
let recovered = false;
if (err.error instanceof LoadTestVariantsError) {
// Ignore request using the old invocation ID.
if (!err.error.req.invocations.includes(`invocations/${ele.buildState.invocationId}`)) {
recovered = true;
}
// Old builds don't support computed invocation ID.
// Disable it and try again.
if (ele.buildState.useComputedInvId && !err.error.req.pageToken) {
ele.buildState.useComputedInvId = false;
recovered = true;
}
} else if (err.error instanceof QueryInvocationError) {
// Ignore request using the old invocation ID.
if (err.error.invId !== ele.buildState.invocationId) {
recovered = true;
}
// Old builds don't support computed invocation ID.
// Disable it and try again.
if (ele.buildState.useComputedInvId) {
ele.buildState.useComputedInvId = false;
recovered = true;
}
}
if (recovered) {
err.stopImmediatePropagation();
err.preventDefault();
return false;
}
if (!(err.error instanceof GetBuildError)) {
attachTags(err.error, OPTIONAL_RESOURCE);
}
return forwardWithoutMsg(err, ele);
}
function renderError(err: ErrorEvent, ele: BuildPageElement) {
if (err.error instanceof GetBuildError && hasTags(err.error, POTENTIALLY_EXPIRED)) {
return html`
<div id="build-not-found-error">
Build Not Found: if you are trying to view an old build, it could have been wiped from the server already.
</div>
${renderErrorInPre(err, ele)}
`;
}
return renderErrorInPre(err, ele);
}
/**
* Main build page.
* Reads project, bucket, builder and build from URL params.
* If any of the parameters are not provided, redirects to '/not-found'.
* If build is not a number, shows an error.
*/
@customElement('milo-build-page')
@errorHandler(retryWithoutComputedInvId, renderError)
@provider
@consumer
export class BuildPageElement extends MiloBaseElement implements BeforeEnterObserver {
@observable.ref
@consumeAppState()
appState!: AppState;
@observable.ref
@consumeConfigsStore()
configsStore!: UserConfigsStore;
@observable.ref
@provideBuildState({ global: true })
buildState!: BuildState;
@observable.ref
@provideInvocationState({ global: true })
invocationState!: InvocationState;
@observable private readonly uncommittedConfigs: UserConfigs = merge({}, DEFAULT_USER_CONFIGS);
// The page is visited via a short link.
// The page will be redirected to the long link after the build is fetched.
private isShortLink = false;
private urlSuffix = '';
// builderParam is only set when the page visited via a full link.
@observable.ref private builderIdParam?: BuilderID;
@observable.ref private buildNumOrIdParam = '';
@computed private get buildNumOrId() {
return this.buildState.build?.buildNumOrId || this.buildNumOrIdParam;
}
@computed private get legacyUrl() {
return getLegacyURLPathForBuild(this.builderIdParam!, this.buildNumOrId);
}
onBeforeEnter(location: RouterLocation, cmd: PreventAndRedirectCommands) {
const buildId = location.params['build_id'];
const path = location.params['path'];
if (typeof buildId === 'string' && path instanceof Array) {
this.isShortLink = true;
this.buildNumOrIdParam = ('b' + buildId) as string;
this.urlSuffix = '/' + path.join('/') + location.search + location.hash;
return;
}
this.isShortLink = false;
const project = location.params['project'];
const bucket = location.params['bucket'];
const builder = location.params['builder'];
const buildNumOrId = location.params['build_num_or_id'];
if ([project, bucket, builder, buildNumOrId].some((param) => typeof param !== 'string')) {
return cmd.redirect(NOT_FOUND_URL);
}
this.builderIdParam = {
project: project as string,
bucket: bucket as string,
builder: builder as string,
};
this.buildNumOrIdParam = buildNumOrId as string;
return;
}
@computed private get faviconUrl() {
if (this.buildState.build) {
return `/static/common/favicon/${STATUS_FAVICON_MAP[this.buildState.build.status]}-32.png`;
}
return '/static/common/favicon/milo-32.png';
}
@computed private get documentTitle() {
const status = this.buildState.build?.status;
const statusDisplay = status ? BUILD_STATUS_DISPLAY_MAP[status] : 'loading';
return `${statusDisplay} - ${this.builderIdParam?.builder || ''} ${this.buildNumOrId}`;
}
connectedCallback() {
super.connectedCallback();
if (!this.isShortLink && !window.location.href.includes('javascript:')) {
trackEvent(GA_CATEGORIES.NEW_BUILD_PAGE, GA_ACTIONS.PAGE_VISITED, window.location.href);
trackEvent(GA_CATEGORIES.PROJECT_BUILD_PAGE, GA_ACTIONS.VISITED_NEW, this.builderIdParam!.project);
}
this.appState.hasSettingsDialog++;
this.addDisposer(
reaction(
() => [this.appState],
() => {
this.buildState?.dispose();
this.buildState = new BuildState(this.appState);
this.buildState.builderIdParam = this.builderIdParam;
this.buildState.buildNumOrIdParam = this.buildNumOrIdParam;
// Emulate @property() update.
this.updated(new Map([['buildState', this.buildState]]));
},
{ fireImmediately: true }
)
);
this.addDisposer(() => this.buildState.dispose());
this.addDisposer(
reaction(
() => this.appState,
(appState) => {
this.invocationState?.dispose();
this.invocationState = new InvocationState(appState);
// Emulate @property() update.
this.updated(new Map([['invocationState', this.invocationState]]));
},
{ fireImmediately: true }
)
);
this.addDisposer(() => this.invocationState.dispose());
this.addDisposer(
autorun(() => {
this.invocationState.invocationId = this.buildState.invocationId;
this.invocationState.isComputedInvId = this.buildState.useComputedInvId;
this.invocationState.presentationConfig =
this.buildState.build?.output?.properties?.[TEST_PRESENTATION_KEY] ||
this.buildState.build?.input?.properties?.[TEST_PRESENTATION_KEY] ||
{};
this.invocationState.warning = this.buildState.build?.buildOrStepInfraFailed
? 'Test results displayed here are likely incomplete because some steps have infra failed.'
: '';
})
);
if (this.isShortLink) {
// Redirect to the long link after the build is fetched.
this.addDisposer(
when(
reportError(this, () => this.buildState.build !== null),
() => {
const build = this.buildState.build!;
if (build.number !== undefined) {
this.appState.setBuildId(build.builder, build.number, build.id);
}
const buildUrl = router.urlForName('build', {
project: build.builder.project,
bucket: build.builder.bucket,
builder: build.builder.builder,
build_num_or_id: build.buildNumOrId,
});
const newUrl = buildUrl + this.urlSuffix;
// Prevent the router from pushing the history state.
window.history.replaceState(null, '', newUrl);
Router.go(newUrl);
}
)
);
// Skip rendering-related reactions.
return;
}
this.addDisposer(
reaction(
() => this.faviconUrl,
(faviconUrl) => document.getElementById('favicon')?.setAttribute('href', faviconUrl),
{ fireImmediately: true }
)
);
this.addDisposer(
reaction(
() => this.documentTitle,
(title) => (document.title = title),
{ fireImmediately: true }
)
);
// Sync uncommitted configs with committed configs.
this.addDisposer(
reaction(
() => merge({}, this.configsStore.userConfigs),
(committedConfig) => merge(this.uncommittedConfigs, committedConfig),
{ fireImmediately: true }
)
);
}
disconnectedCallback() {
this.appState.hasSettingsDialog--;
super.disconnectedCallback();
}
@computed get tabDefs(): TabDef[] {
const params = {
project: this.builderIdParam!.project,
bucket: this.builderIdParam!.bucket,
builder: this.builderIdParam!.builder,
build_num_or_id: this.buildNumOrIdParam,
};
return [
{
id: 'overview',
label: 'Overview',
href: router.urlForName('build-overview', params),
},
// TODO(crbug/1128097): display test-results tab unconditionally once
// Foundation team is ready for ResultDB integration with other LUCI
// projects.
...(!this.invocationState.hasInvocation
? []
: [
{
id: 'test-results',
label: 'Test Results',
href: router.urlForName('build-test-results', params),
slotName: 'test-count-indicator',
},
]),
{
id: 'steps',
label: 'Steps & Logs',
href: router.urlForName('build-steps', params),
},
{
id: 'related-builds',
label: 'Related Builds',
href: router.urlForName('build-related-builds', params),
},
{
id: 'timeline',
label: 'Timeline',
href: router.urlForName('build-timeline', params),
},
{
id: 'blamelist',
label: 'Blamelist',
href: router.urlForName('build-blamelist', params),
},
];
}
@computed private get statusBarColor() {
const build = this.buildState.build;
return build ? BUILD_STATUS_COLOR_MAP[build.status] : 'var(--active-color)';
}
private renderBuildStatus() {
const build = this.buildState.build;
if (!build) {
return html``;
}
return html`
<i class="status ${BUILD_STATUS_CLASS_MAP[build.status]}">
${BUILD_STATUS_DISPLAY_MAP[build.status] || 'unknown status'}
</i>
${(() => {
switch (build.status) {
case BuildStatus.Scheduled:
return `since ${build.createTime.toFormat(LONG_TIME_FORMAT)}`;
case BuildStatus.Started:
return `since ${build.startTime!.toFormat(LONG_TIME_FORMAT)}`;
case BuildStatus.Canceled:
return `after ${displayDuration(build.endTime!.diff(build.createTime))} by ${
build.canceledBy || 'unknown'
}`;
case BuildStatus.Failure:
case BuildStatus.InfraFailure:
case BuildStatus.Success:
return `after ${displayDuration(build.endTime!.diff(build.startTime || build.createTime))}`;
default:
return '';
}
})()}
`;
}
protected render = reportRenderError(this, () => {
if (this.isShortLink) {
return html``;
}
return html`
<mwc-dialog
id="settings-dialog"
heading="Settings"
?open=${this.appState.showSettingsDialog}
@closed=${(event: CustomEvent<{ action: string }>) => {
if (event.detail.action === 'save') {
merge(this.configsStore.userConfigs, this.uncommittedConfigs);
}
// Reset uncommitted configs.
merge(this.uncommittedConfigs, this.configsStore.userConfigs);
this.appState.showSettingsDialog = false;
}}
>
<table>
<tr>
<td>Default tab:</td>
<td>
<select
id="default-tab-selector"
@change=${(e: InputEvent) =>
(this.uncommittedConfigs.defaultBuildPageTabName = (e.target as HTMLOptionElement).value)}
>
${TAB_NAME_LABEL_TUPLES.map(
([tabName, label]) => html`
<option value=${tabName} ?selected=${tabName === this.uncommittedConfigs.defaultBuildPageTabName}>
${label}
</option>
`
)}
</select>
</td>
</tr>
<mwc-button slot="primaryAction" dialogAction="save" dense unelevated>Save</mwc-button>
<mwc-button slot="secondaryAction" dialogAction="dismiss">Cancel</mwc-button>
</table>
</mwc-dialog>
<div id="build-summary">
<div id="build-id">
<span id="build-id-label">Build </span>
<a href=${getURLPathForProject(this.builderIdParam!.project)}>${this.builderIdParam!.project}</a>
<span> / </span>
<span>${this.builderIdParam!.bucket}</span>
<span> / </span>
<a href=${getURLPathForBuilder(this.builderIdParam!)}>${this.builderIdParam!.builder}</a>
<span> / </span>
<span>${this.buildNumOrId}</span>
</div>
${this.buildState.customBugLink === null
? html``
: html`
<div class="delimiter"></div>
<a href=${this.buildState.customBugLink} target="_blank">File a bug</a>
`}
${this.appState.redirectSw === null
? html``
: html`
<div class="delimiter"></div>
<a
@click=${(e: MouseEvent) => {
const switchVerTemporarily = e.metaKey || e.shiftKey || e.ctrlKey || e.altKey;
trackEvent(
GA_CATEGORIES.LEGACY_BUILD_PAGE,
switchVerTemporarily ? GA_ACTIONS.SWITCH_VERSION_TEMP : GA_ACTIONS.SWITCH_VERSION,
window.location.href
);
if (switchVerTemporarily) {
return;
}
const expires = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toUTCString();
document.cookie = `showNewBuildPage=false; expires=${expires}; path=/`;
this.appState.redirectSw?.unregister();
}}
href=${this.legacyUrl}
>
Switch to the legacy build page
</a>
`}
<div id="build-status">${this.renderBuildStatus()}</div>
</div>
<milo-status-bar
.components=${[{ color: this.statusBarColor, weight: 1 }]}
.loading=${!this.buildState.build}
></milo-status-bar>
<milo-tab-bar .tabs=${this.tabDefs} .selectedTabId=${this.appState.selectedTabId}>
<milo-test-count-indicator slot="test-count-indicator"></milo-test-count-indicator>
</milo-tab-bar>
<slot></slot>
`;
});
static styles = [
commonStyle,
colorClasses,
css`
#build-summary {
background-color: var(--block-background-color);
padding: 6px 16px;
font-family: 'Google Sans', 'Helvetica Neue', sans-serif;
font-size: 14px;
display: flex;
}
#build-id {
flex: 0 auto;
font-size: 0px;
}
#build-id > * {
font-size: 14px;
}
#build-id-label {
color: var(--light-text-color);
}
#build-status {
margin-left: auto;
flex: 0 auto;
}
.delimiter {
border-left: 1px solid var(--divider-color);
width: 1px;
margin-left: 10px;
margin-right: 10px;
}
#status {
font-weight: 500;
}
milo-tab-bar {
margin: 0 10px;
padding-top: 10px;
}
milo-test-count-indicator {
margin-right: -13px;
}
#settings-dialog {
--mdc-dialog-min-width: 600px;
}
#default-tab-selector {
display: inline-block;
margin-left: 10px;
padding: 0.375rem 0.75rem;
font-size: 1rem;
line-height: 1.5;
background-clip: padding-box;
border: 1px solid var(--divider-color);
border-radius: 0.25rem;
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
#build-not-found-error {
background-color: var(--warning-color);
font-weight: 500;
padding: 5px;
margin: 8px 16px;
}
`,
];
} | the_stack |
import {DEFAULT_FONT_SIZE, DEFAULT_FONT_NAME, DEFAULT_FONT_COLOR} from "../../api/constants";
import {
DEFAULT_STAND_ALONE,
DEFAULT_XML_VERSION,
ENCODING_UTF_8,
EXTENSION_XML,
FILE_STYLES, XMLNS_MAIN, XMLNS_MC, XMLNS_X14AC, XMLNS_X16R2, XMLNS_XR
} from "../../api/Internals";
import {___JSE_XLSX___File, ___JSE_XLSX___Node} from "../../api/xlsx";
import {JSEFont, JSExcel, JSEColor, JSECellBorder, JSEBorderType} from "../../Types";
import {extractFontsFromExcel, hasFontsInExcel, hasBordersInExcel, extractBordersFromExcel} from "../../util/ExcelUtil";
const fileProps: any = {
xml: {
version: DEFAULT_XML_VERSION,
encoding: ENCODING_UTF_8,
standalone: DEFAULT_STAND_ALONE
},
name: FILE_STYLES,
extension: EXTENSION_XML,
nodes: {
styleSheet: "styleSheet",
fonts: "fonts",
font: "font",
sz: "sz",
color: "color",
name: "name",
b: "b",
i: "i",
u: "u",
family: "family",
fills: "fills",
fill: "fill",
patternFill: "patternFill",
fgColor: "fgColor",
bgColor: "bgColor",
borders: "borders",
border: "border",
left: "left",
right: "right",
top: "top",
bottom: "bottom",
diagonal: "diagonal",
cellStyleXfs: "cellStyleXfs",
cellXfs: "cellXfs",
xf: "xf",
alignment: "alignment",
cellStyles: "cellStyles",
cellStyle: "cellStyle",
dxfs: "dxfs",
tableStyles: "tableStyles",
extLst: "extLst",
ext: "ext",
x14SlicerStyles: "x14:slicerStyles",
x15TimelineStyles: "x15:timelineStyles"
},
keys: {
val: "val",
rgb: "rgb",
theme: "theme",
tint: "tint",
count: "count",
patternType: "patternType",
indexed: "indexed",
style: "style",
numFmtId: "numFmtId",
fontId: "fontId",
fillId: "fillId",
borderId: "borderId",
xfId: "xfId",
applyFont: "applyFont",
applyFill: "applyFill",
applyBorder: "applyBorder",
applyAlignment: "applyAlignment",
horizontal: "horizontal",
vertical: "vertical",
name: "name",
builtinId: "builtinId",
defaultTableStyle: "defaultTableStyle",
defaultPivotStyle: "defaultPivotStyle",
uri: "uri",
xmlnsX14: "xmlns:x14",
xmlnsX15: "xmlns:x15",
xmlns: "xmlns",
xmlnsMc: "xmlns:mc",
mcIgnorable: "mc:Ignorable",
xmlnsX14ac: "xmlns:x14ac",
xmlnsX16r2: "xmlns:x16r2",
xmlnsXr: "xmlns:xr",
defaultSlicerStyle: "defaultSlicerStyle",
defaultTimelineStyle: "defaultTimelineStyle"
},
};
export default (excel: JSExcel): ___JSE_XLSX___File => ({
fileName: fileProps.name,
fileExtension: fileProps.extension,
fileContent: {
xml: {...fileProps.xml},
content: {
name: fileProps.nodes.styleSheet,
values: [
{key: fileProps.keys.xmlns, value: XMLNS_MAIN},
{key: fileProps.keys.xmlnsMc, value: XMLNS_MC},
{key: fileProps.keys.mcIgnorable, value: "x14ac x16r2 xr"}, //TODO: Double check
{key: fileProps.keys.xmlnsX14ac, value: XMLNS_X14AC},
{key: fileProps.keys.xmlnsX16r2, value: XMLNS_X16R2},
{key: fileProps.keys.xmlnsXr, value: XMLNS_XR}
],
content: [
getFontsNodes(excel),
// getFillsNodes(excel),
getBorderNodes(excel),
getCellStyleXfsNodes(excel),
getCellXfsNodes(excel),
getCellStylesNodes(excel),
getDXFSNodes(excel),
getTableStylesNodes(excel),
getExtLstNodes(excel)
]
}
}
});
function getFontsNodes(excel: JSExcel): ___JSE_XLSX___Node | undefined {
if (hasFontsInExcel(excel)) {
return {
name: fileProps.nodes.fonts,
content: extractFonts(excel)
};
}
}
function extractFonts(excel: JSExcel): Array<___JSE_XLSX___Node> {
return extractFontsFromExcel(excel).map(getFontNode);
}
function getFontNode(font: JSEFont): ___JSE_XLSX___Node {
const fontCalculatedNodes: Array<___JSE_XLSX___Node | undefined> = [
getFontProperty_Bold(font),
getFontProperty_Italic(font),
getFontProperty_Underline(font),
getFontProperty_Size(font),
getFontProperty_Color(font),
getFontProperty_Name(font),
getFontProperty_Family(font)
];
const fontNodes: Array<___JSE_XLSX___Node> = [];
fontCalculatedNodes.forEach((item: ___JSE_XLSX___Node | undefined) => {
if (item !== null || item !== undefined) {
fontNodes.push(item as ___JSE_XLSX___Node);
}
});
return {
name: fileProps.nodes.font,
content: fontNodes
};
}
function getFontProperty_Bold(font: JSEFont): ___JSE_XLSX___Node | undefined {
if (!font.bold) {
return;
}
return {
name: fileProps.nodes.b
};
}
function getFontProperty_Italic(font: JSEFont): ___JSE_XLSX___Node | undefined {
if (!font.italic) {
return;
}
return {
name: fileProps.nodes.i
};
}
function getFontProperty_Underline(font: JSEFont): ___JSE_XLSX___Node | undefined {
if (!font.underline) {
return;
}
return {
name: fileProps.nodes.u
};
}
function getFontProperty_Size(font: JSEFont): ___JSE_XLSX___Node {
const fontSize: number = !font.size ? DEFAULT_FONT_SIZE : font.size;
return {
name: fileProps.nodes.sz,
values: [{key: fileProps.keys.val, value: fontSize}]
};
}
function getFontProperty_Color(font: JSEFont): ___JSE_XLSX___Node {
let fontColor: string;
let theme: any;
let tint: any;
if (!font.color) {
fontColor = DEFAULT_FONT_COLOR;
}
if (typeof font.color === "string") {
fontColor = font.color;
} else {
const colour: JSEColor = font.color as JSEColor;
fontColor = !colour.rgb ? DEFAULT_FONT_COLOR : colour.rgb;
if (colour.theme) {
theme = {key: fileProps.keys.theme, value: colour.theme};
}
if (colour.tint) {
tint = {key: fileProps.keys.tint, value: colour.tint};
}
}
return {
name: fileProps.nodes.color,
values: [
{key: fileProps.keys.rgb, value: fontColor},
...theme,
...tint
]
};
}
function getFontProperty_Name(font: JSEFont): ___JSE_XLSX___Node {
const fontName: string = !font.name ? DEFAULT_FONT_NAME : font.name;
return {
name: fileProps.nodes.name,
values: [{key: fileProps.keys.val, value: fontName}]
};
}
function getFontProperty_Family(font: JSEFont): ___JSE_XLSX___Node | undefined {
if (!font.family) {
return;
}
return {
name: fileProps.nodes.family,
values: [{key: fileProps.keys.val, value: font.family}]
};
}
/*function getFillsNodes(excel: JSExcel): ___JSE_XLSX___Node {
if (hasFillsInExcel(excel)) {
return {
name: fileProps.nodes.fills,
content: extractFills(excel)
};
}
}*/
function getBorderNodes(excel: JSExcel): ___JSE_XLSX___Node | undefined {
if (hasBordersInExcel(excel)) {
const borders: Array<JSECellBorder> = extractBordersFromExcel(excel);
return {
name: fileProps.nodes.borders,
values: [{key: fileProps.keys.count, value: borders.length}],
content: borders.map(getBorderNode)
};
}
}
function getBorderNode(border: JSECellBorder): ___JSE_XLSX___Node | undefined {
return {
name: fileProps.nodes.border,
content: [
getLeftCellBorder(border),
getRightCellBorder(border),
getTopCellBorder(border),
getBottomCellBorder(border),
getDiagonalCellBorder(border),
]
};
}
function getLeftCellBorder(border: JSECellBorder): ___JSE_XLSX___Node | undefined {
if (!border.left) {
return;
}
const style: JSEBorderType = border.left.type || "thin";
let colorIndex: any;
if (border.left.color) {
colorIndex = {
content: [{
name: fileProps.nodes.color,
values: [
{key: fileProps.keys.indexed, value: border.left.color}
]
}]
};
}
return {
name: fileProps.nodes.left,
values: [
{key: fileProps.keys.style, value: style}
],
...colorIndex
};
}
function getRightCellBorder(border: JSECellBorder): ___JSE_XLSX___Node | undefined {
if (!border.right) {
return;
}
const style: JSEBorderType = border.right.type || "thin";
let colorIndex: any;
if (border.right.color) {
colorIndex = {
content: [{
name: fileProps.nodes.color,
values: [
{key: fileProps.keys.indexed, value: border.right.color}
]
}]
};
}
return {
name: fileProps.nodes.right,
values: [
{key: fileProps.keys.style, value: style}
],
...colorIndex
};
}
function getTopCellBorder(border: JSECellBorder): ___JSE_XLSX___Node | undefined {
if (!border.top) {
return;
}
const style: JSEBorderType = border.top.type || "thin";
let colorIndex: any;
if (border.top.color) {
colorIndex = {
content: [{
name: fileProps.nodes.color,
values: [
{key: fileProps.keys.indexed, value: border.top.color}
]
}]
};
}
return {
name: fileProps.nodes.top,
values: [
{key: fileProps.keys.style, value: style}
],
...colorIndex
};
}
function getBottomCellBorder(border: JSECellBorder): ___JSE_XLSX___Node | undefined {
if (!border.bottom) {
return;
}
const style: JSEBorderType = border.bottom.type || "thin";
let colorIndex: any;
if (border.bottom.color) {
colorIndex = {
content: [{
name: fileProps.nodes.color,
values: [
{key: fileProps.keys.indexed, value: border.bottom.color}
]
}]
};
}
return {
name: fileProps.nodes.bottom,
values: [
{key: fileProps.keys.style, value: style}
],
...colorIndex
};
}
function getDiagonalCellBorder(border: JSECellBorder): ___JSE_XLSX___Node | undefined {
if (!border.diagonal) {
return;
}
const style: JSEBorderType = border.diagonal.type || "thin";
let colorIndex: any;
if (border.diagonal.color) {
colorIndex = {
content: [{
name: fileProps.nodes.color,
values: [
{key: fileProps.keys.indexed, value: border.diagonal.color}
]
}]
};
}
return {
name: fileProps.nodes.diagonal,
values: [
{key: fileProps.keys.style, value: style}
],
...colorIndex
};
}
function getCellStyleXfsNodes(excel: JSExcel): ___JSE_XLSX___Node {
// TODO: complete as with excel sheet -CODE02
return {
name: fileProps.nodes.cellStyleXfs,
values: [
{key: fileProps.keys.count, value: "1"}
],
content: {
name: fileProps.nodes.xf,
values: [
{key: fileProps.keys.numFmtId, value: "0"},
{key: fileProps.keys.fontId, value: "0"},
{key: fileProps.keys.fillId, value: "0"},
{key: fileProps.keys.borderId, value: "0"}
]
}
};
}
function getCellXfsNodes(excel: JSExcel): ___JSE_XLSX___Node {
// TODO: complete as with excel sheet -CODE02
return {
name: fileProps.nodes.cellXfs,
values: [
{key: fileProps.keys.count, value: "1"}
],
content: {
name: fileProps.nodes.xf,
values: [
{key: fileProps.keys.numFmtId, value: "0"},
{key: fileProps.keys.fontId, value: "0"},
{key: fileProps.keys.fillId, value: "0"},
{key: fileProps.keys.borderId, value: "0"},
{key: fileProps.keys.xfId, value: "0"}
]
}
};
}
function getCellStylesNodes(excel: JSExcel): ___JSE_XLSX___Node {
// TODO: complete as with excel sheet -CODE02
return {
name: fileProps.nodes.cellStyles,
values: [
{key: fileProps.keys.count, value: "1"}
],
content: {
name: fileProps.nodes.cellStyle,
values: [
{key: fileProps.keys.name, value: "Standard"},
{key: fileProps.keys.xfId, value: "0"},
{key: fileProps.keys.builtinId, value: "0"}
]
}
};
}
function getDXFSNodes(excel: JSExcel): ___JSE_XLSX___Node {
// TODO: complete as with excel sheet -CODE02
return {
name: fileProps.nodes.dxfs,
values: [
{key: fileProps.keys.count, value: "0"}
]
};
}
function getTableStylesNodes(excel: JSExcel): ___JSE_XLSX___Node {
// TODO: complete as with excel sheet -CODE02
return {
name: fileProps.nodes.tableStyles,
values: [
{key: fileProps.keys.count, value: "0"},
{key: fileProps.keys.defaultTableStyle, value: "TableStyleMedium2"},
{key: fileProps.keys.defaultPivotStyle, value: "PivotStyleMedium9"}
]
};
}
function getExtLstNodes(excel: JSExcel): ___JSE_XLSX___Node {
// TODO: complete as with excel sheet -CODE02
return {
name: fileProps.nodes.extLst,
content: [
{
name: fileProps.nodes.ext,
values: [
{key: fileProps.keys.uri, value: "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"},
{
key: fileProps.keys.xmlnsX14,
value: "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"
}
],
content: {
name: fileProps.nodes.x14SlicerStyles,
values: [
{key: fileProps.keys.defaultSlicerStyle, value: "SlicerStyleLight1"}
]
}
},
{
name: fileProps.nodes.ext,
values: [
{key: fileProps.keys.uri, value: "{9260A510-F301-46a8-8635-F512D64BE5F5}"},
{
key: fileProps.keys.xmlnsX14,
value: "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"
}
],
content: {
name: fileProps.nodes.x15TimelineStyles,
values: [
{key: fileProps.keys.defaultTimelineStyle, value: "SlicerStyleLight1"}
]
}
}
]
};
} | the_stack |
import {
CellEditingStoppedEvent,
ColDef,
ColGroupDef,
ColumnApi,
ColumnMovedEvent,
ColumnResizedEvent,
ColumnVisibleEvent,
GetContextMenuItemsParams,
GridApi,
GridReadyEvent,
RowClickedEvent,
RowDataUpdatedEvent,
RowDoubleClickedEvent,
RowNode,
RowSelectedEvent,
SelectionChangedEvent,
SuppressKeyboardEventParams,
} from '@ag-grid-community/core';
import '@ag-grid-community/core/dist/styles/ag-grid.css';
import '@ag-grid-community/core/dist/styles/ag-theme-balham.css';
import { AgGridReact, AgGridColumn } from '@ag-grid-community/react';
import { AllModules, LicenseManager } from '@ag-grid-enterprise/all-modules';
import { Spin } from 'antd';
import LocaleReceiver from 'antd/lib/locale-provider/LocaleReceiver';
import classnames from 'classnames';
import { findIndex, get, isEmpty, isEqual, isObject } from 'lodash';
import React, { createContext, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { gantGetcontextMenuItems } from './contextMenuItems';
import CustomHeader from './CustomHeader';
import { filterHooks } from './gantFilter';
import GantGridFormToolPanelRenderer from './GantGridFormToolPanelRenderer';
import GridManager from './gridManager';
import { contextHooks, selectedHooks } from './hooks';
import { DataActions, GridPropsPartial, GridVariableRef, RowSelection, Size } from './interface';
import key from './license';
import en from './locale/en-US';
import zh from './locale/zh-CN';
import { getAllComponentsMaps, getGridConfig } from './maps';
import GantPagination from './Pagination';
import SelectedGrid from './SelectedGrid';
import GantDateComponent from './GantDateComponent';
import './style';
import {
checkParentGroupSelectedStatus,
flattenTreeData,
getSizeClassName,
groupNodeSelectedToggle,
mapColumns,
selectedMapColumns,
usePagination,
} from './utils';
export { default as GantGroupCellRenderer } from './GantGroupCellRenderer';
export { default as GantPromiseCellRender } from './GantPromiseCellRender';
export * from './interface';
export { default as GantDateComponent } from './GantDateComponent';
export { setComponentsMaps, setFrameworkComponentsMaps, setGridConfig } from './maps';
LicenseManager.setLicenseKey(key);
const langs = {
en: en,
'zh-cn': zh,
};
export const GridContext = createContext<any>({});
export const defaultProps = {
/**加载状态 */
loading: false,
resizable: true,
/**是否处于编辑状态 */
editable: false,
/**单列的过滤器 */
filter: true,
/**禁止调整列顺序 */
// lockPosition: false,
/**直接在列头下面显示过滤器 */
floatingFilter: false,
/**编辑状态下的尺寸 */
size: Size.small,
/**rowkey */
rowkey: 'key',
width: '100%',
sortable: true,
treeDataChildrenName: 'children',
/** 默认的删除行为 */
/**是否执行treeDataPath计算 */
isCompute: false,
//默认开启编辑校验
openEditSign: true,
};
export const defaultRowSelection: RowSelection = {
type: 'multiple',
// checkboxIndex: 0,
showDefalutCheckbox: true,
// rowMultiSelectWithClick: true,
rowDeselection: true,
};
const Grid = function Grid<T extends any>(gridProps: GridPropsPartial<T>) {
const globalConfig = useMemo(() => {
return getGridConfig();
}, []);
const props = { ...globalConfig, ...gridProps };
const {
dataSource: initDataSource,
onReady,
columns,
editable,
rowSelection: rowSel,
size,
rowkey,
gridKey,
resizable,
filter,
sortable,
width,
height,
treeData,
pagination,
loading,
isServerSideGroup,
getServerSideGroupKey,
frameworkComponents = {},
treeDataChildrenName,
locale: customLocale,
serverGroupExpend,
groupDefaultExpanded = 0,
defaultColDef,
context: propsContext,
components,
serialNumber,
rowClassRules,
isCompute,
getDataPath: orignGetDataPath,
onCellEditChange,
onCellEditingChange,
onCellChanged,
openEditSign = true,
getContextMenuItems,
createConfig,
onRowsCut,
onRowsPaste,
onRowsPasteEnd,
showCut = false,
onContextChangeRender,
defaultExportParams,
defaultJsonParams,
editChangeCallback,
isRowSelectable,
boxColumnIndex,
hideSelectedBox,
hideSelcetedBox,
suppressKeyboardEvent,
onSelectionChanged: propsOnSelectionChanged,
onRowSelected: propsOnRowSelected,
onRowDataUpdated: propOnRowDataUpdated,
onRowDataChanged: propOnRowDataChanged,
groupSelectsChildren,
onColumnMoved,
onColumnResized,
onColumnVisible,
onRowClicked,
drawerMode,
multiLineVerify,
defaultDrawerWidth,
selectedBoxHeight,
selectedBoxWidth = 240,
onRowDoubleClicked,
onFilterModified: handleFilterModified,
doubleClickedExpanded,
customDrawerContent,
visibleDrawer: propVisibleDrawer,
hideMenuItemExport,
hideMenuItemExpand,
hiddenMenuItemNames,
excelStyles = [],
suppressRightClickSelected,
treeDataForcedFilter,
themeClass = 'ag-theme-balham',
gantDateComponent,
autoHeight,
maxAutoHeight,
minAutoHeight = 150,
showCutChild,
...orignProps
} = props;
const apiRef = useRef<GridApi>();
const shiftRef = useRef<boolean>(false);
const selectedChanged = useRef<boolean>(false);
const columnsRef = useRef<ColumnApi>();
const selectedLoadingRef = useRef<boolean>(false);
const gridRef = useRef<any>();
const [visibleDrawer, setVisibleDrawer] = useState(false);
const [clickedEvent, setClickedEvent] = useState<RowClickedEvent>();
const gridVariableRef = useRef<GridVariableRef>({
hasSelectedRows:
typeof rowSel !== 'boolean' && isObject(rowSel) && Reflect.has(rowSel, 'selectedRows'),
hideSelectedBox: hideSelcetedBox || hideSelectedBox,
selectedRows: [],
});
const [innerSelectedRows, setInnerSelectedRows] = useState([]);
const [ready, setReady] = useState(false);
//自定义列头文字
const { ColumnLabelComponent } = frameworkComponents;
const gridManager = useMemo(() => {
return new GridManager();
}, []);
/**默认基本方法 */
const getRowNodeId = useCallback(data => {
if (typeof rowkey === 'string') {
return get(data, rowkey);
}
return rowkey(data);
}, []);
const getDataPath = useCallback(
data => {
if (!treeData) return [];
let dataPath = orignGetDataPath ? orignGetDataPath(data) : isCompute ? data.treeDataPath : [];
return dataPath;
},
[orignGetDataPath, treeData],
);
//自动高度
const gridHeight = useMemo(() => {
if (height) return height;
if (!autoHeight && !height) return 400;
let resHeight: number | string = 0;
if (!treeData || groupDefaultExpanded === -1) {
resHeight = 24 * (initDataSource.length + 1);
} else {
const filterData = initDataSource.filter(itemData => {
const isExpaned = getDataPath(itemData).length <= groupDefaultExpanded + 1;
return isExpaned;
});
resHeight = 24 * (filterData.length + 1);
}
resHeight = maxAutoHeight && resHeight >= maxAutoHeight ? maxAutoHeight : resHeight;
resHeight = minAutoHeight && minAutoHeight >= resHeight ? minAutoHeight : resHeight;
return parseInt(resHeight as any) + 4;
}, [autoHeight, initDataSource, getDataPath, groupDefaultExpanded, height]);
// filter
useEffect(() => {
if (typeof propVisibleDrawer === 'boolean') {
setVisibleDrawer(propVisibleDrawer);
}
}, [propVisibleDrawer]);
// 判断数据分别处理 treeTable 和普通table
const dataSource = useMemo(() => {
if (treeData && isCompute)
return flattenTreeData(initDataSource, getRowNodeId, treeDataChildrenName);
return initDataSource;
}, [initDataSource, treeData, treeDataChildrenName]);
const serverDataRequest = useCallback(
(params, groupKeys, successCallback) => {
if (serverGroupExpend) {
return serverGroupExpend(params, serverDataCallback(groupKeys, successCallback));
}
return successCallback([], 0);
},
[serverGroupExpend],
);
/**fix: 解决保存时候标记状态无法清楚的问题 */
// 分页事件
const computedPagination: any = useMemo(() => usePagination(pagination), [pagination]);
// context
const context = useMemo(() => {
return {
globalEditable: editable && !drawerMode,
serverDataRequest,
isServerSideGroup,
size,
getDataPath: getDataPath,
computedPagination,
treeData,
gridManager,
showCut,
createConfig,
getRowNodeId,
watchEditChange: typeof onCellEditChange === 'function',
onCellEditChange,
onCellEditingChange,
onCellChanged,
...propsContext,
};
}, [
propsContext,
size,
computedPagination,
editable,
drawerMode,
showCut,
onCellEditChange,
onCellEditingChange,
onCellChanged,
getDataPath,
]);
const {
filterDataRef,
onFilterModified,
forcedGridKey,
filterModelRef,
columnIdRef,
} = filterHooks({
treeData,
treeDataForcedFilter,
handleFilterModified,
getRowNodeId,
dataSource,
context,
});
const gridForcedProps = useMemo(() => {
if (!treeDataForcedFilter && forcedGridKey) return {};
return {
key: forcedGridKey,
};
}, [forcedGridKey]);
// 处理selection
const gantSelection: RowSelection = useMemo(() => {
if (rowSel === true) {
return defaultRowSelection;
}
if (rowSel) return { ...defaultRowSelection, ...rowSel };
return {};
}, [rowSel]);
const {
onSelect,
selectedRows,
showDefalutCheckbox,
type: rowSelection,
onSelectedChanged,
defaultSelectionCol,
...selection
} = gantSelection;
// 初始注册配置信息;
useEffect(() => {
gridManager.reset({
getRowNodeId,
createConfig,
treeData,
getDataPath,
isCompute,
treeDataChildrenName,
editChangeCallback,
onRowsPasteEnd,
multiLineVerify,
});
}, []);
useEffect(() => {
gridManager.dataSourceChanged(dataSource);
}, [dataSource, ready]);
const serverDataCallback = useCallback((groupKeys, successCallback) => {
return rows => {
successCallback(rows, rows.length);
gridManager.appendChild(groupKeys, rows);
};
}, []);
const { componentsMaps, frameworkComponentsMaps } = useMemo(() => {
return getAllComponentsMaps();
}, []);
// 获取selected 数据
const getAllSelectedRows = useCallback(selectedRows => {
const dataSource = gridManager.agGridConfig.dataSource;
const currentRows: string[] = [];
const extraRows: any[] = [];
selectedRows.map(itemRow => {
const index = findIndex(dataSource, function(itemData) {
return getRowNodeId(itemData) === getRowNodeId(itemRow);
});
if (
index < 0 &&
!apiRef.current.getRowNode(getRowNodeId(itemRow)) &&
get(itemRow, '_rowType') !== DataActions.add
)
extraRows.push(itemRow);
else {
currentRows.push(itemRow);
}
});
return { extraRows, currentRows };
}, []);
const onBoxSelectionChanged = useCallback(
(keys, rows) => {
if (!gridVariableRef.current.hasSelectedRows) {
const nodes = apiRef.current?.getSelectedNodes();
const innerSelectedRows: any[] = [];
nodes.map(node => {
const nodeId = getRowNodeId(get(node, 'data'));
if (keys.indexOf(nodeId) < 0) return node.setSelected(false);
innerSelectedRows.push(get(node, 'data'));
});
setInnerSelectedRows(innerSelectedRows);
}
onSelect && onSelect(keys, rows);
},
[onSelect],
);
const { selectedChangeRef } = selectedHooks({
gridVariable: gridVariableRef.current,
ready,
apiRef,
dataSource,
getRowNodeId,
selectedRows,
isSingle: rowSelection === 'single',
});
const onSelectionChanged = useCallback(
(event: SelectionChangedEvent) => {
propsOnSelectionChanged && propsOnSelectionChanged(event);
// if (selectedChangeRef.current) return;
if (gridVariableRef.current?.hasSelectedRows && rowSelection === 'multiple') {
const rows = event.api.getSelectedRows();
const { extraRows, currentRows } = getAllSelectedRows(
get(gridVariableRef.current, 'selectedRows', []),
);
if (isEqual(currentRows, rows)) return;
const selectedRows = [...extraRows, ...rows];
return (
onSelect &&
onSelect(
selectedRows.map(item => getRowNodeId(item)),
selectedRows,
)
);
}
const rows = event.api.getSelectedRows();
if (isEqual(gridVariableRef.current?.selectedRows, rows)) return;
onSelect &&
onSelect(
rows.map(item => getRowNodeId(item)),
rows,
);
if (gridVariableRef.current?.hideSelectedBox) return;
gridVariableRef.current.selectedRows = rows;
setInnerSelectedRows(rows);
},
[getAllSelectedRows, propsOnSelectionChanged, rowSelection],
);
const handleRowClicked = useCallback(
(event: RowClickedEvent) => {
if (drawerMode) {
if (typeof propVisibleDrawer !== 'boolean') setVisibleDrawer(true);
setClickedEvent(event);
}
onRowClicked && onRowClicked(event);
},
[onRowClicked, drawerMode, propVisibleDrawer],
);
const handleRowDoubleClicked = useCallback(
(event: RowDoubleClickedEvent) => {
if (onRowDoubleClicked) onRowDoubleClicked(event);
if (!doubleClickedExpanded) return;
const { node } = event;
if (node.childrenAfterGroup.length > 0) node.setExpanded(!node.expanded);
},
[onRowDoubleClicked, doubleClickedExpanded],
);
const onRowSelected = useCallback(
(event: RowSelectedEvent) => {
if (selectedChanged.current) return;
propsOnRowSelected && propsOnRowSelected(event);
if (!groupSelectsChildren || !treeData) return;
const gridSelectedRows = event.api.getSelectedRows();
if (
gridSelectedRows.length === 0 ||
gridManager.getRowData().length === gridSelectedRows.length
)
return;
if (selectedLoadingRef.current) return;
selectedLoadingRef.current = true;
const { node } = event;
const nodeSelected = node.isSelected();
groupNodeSelectedToggle(node, nodeSelected);
checkParentGroupSelectedStatus(node, nodeSelected, event.api);
setTimeout(() => {
selectedLoadingRef.current = false;
event.api.refreshCells({
columns: ['defalutSelection'],
rowNodes: [node],
force: true,
});
}, 200);
},
[propsOnRowSelected],
);
const boxSelectedRows = useMemo(() => {
if (gridVariableRef.current.hasSelectedRows) return selectedRows;
return innerSelectedRows;
}, [innerSelectedRows, selectedRows]);
// 处理selection-end
//columns
const defaultSelection = !isEmpty(gantSelection) && showDefalutCheckbox;
const { columnDefs, validateFields, requireds } = useMemo(() => {
return mapColumns<T>(
columns,
getRowNodeId,
defaultSelection,
defaultSelectionCol,
rowSelection,
serialNumber,
groupSelectsChildren,
);
}, [columns]);
// 选中栏grid columns;
const selectedColumns = useMemo(() => {
return selectedMapColumns(columns, boxColumnIndex);
}, [columns, boxColumnIndex]);
/// 导出 columns
const getExportColmns = useCallback(columns => {
const arr: string[] = [];
columns.map((item: any) => {
if (item.field !== 'defalutSelection' && item.field !== 'g-index') {
item.field && arr.push(item.field);
if (Array.isArray(item.children)) {
const childrenArray = getExportColmns(item.children);
arr.push(...childrenArray);
}
}
});
return arr;
}, []);
const exportColumns = useMemo(() => {
return getExportColmns(columnDefs);
}, [columnDefs]);
// 配置验证规则
useEffect(() => {
gridManager.validateFields = validateFields;
}, [validateFields]);
// 监听columns变换
const onColumnsChange = useCallback(
(event: ColumnMovedEvent | ColumnResizedEvent | ColumnVisibleEvent) => {
switch (event.type) {
case 'columnVisible':
onColumnVisible && onColumnVisible(event as any);
break;
case 'columnResized':
onColumnResized && onColumnResized(event as any);
break;
case 'columnMoved':
onColumnMoved && onColumnMoved(event as any);
break;
}
gridManager.setLocalStorageColumnsState();
},
[onColumnMoved, onColumnResized, onColumnVisible],
);
const localColumnsDefs = useMemo(() => {
return gridManager.getLocalStorageColumns(columnDefs, gridKey);
}, [columnDefs, gridKey]);
// columns-end
const onGridReady = useCallback(
(params: GridReadyEvent) => {
apiRef.current = params.api;
columnsRef.current = params.columnApi;
gridManager.agGridApi = params.api;
gridManager.agGridColumnApi = params.columnApi;
onReady && onReady(params, gridManager);
setReady(true);
// if (filterModelRef.current && treeDataForcedFilter) {
// params.api.setRowData(get(gridManager, 'agGridConfig.dataSource', []));
// params.api.setFilterModel(filterModelRef.current);
// // params.api.ensureColumnVisible(columnIdRef?.current);
// // const {lef} = get(columnIdRef, 'current',{});
// gridRef.current?.eGridDiv
// .querySelector('.ag-center-cols-viewport')
// ?.scrollTo(columnIdRef.current, 0);
// }
// gridManager.dataSourceChanged(dataSource);
},
[onReady, gridKey, dataSource],
);
const onSuppressKeyboardEvent = useCallback((params: SuppressKeyboardEventParams) => {
const { event, colDef, data, api } = params;
if (event.key === 'Shift') {
shiftRef.current = true;
return false;
}
if (event.keyCode == 67 && (event.ctrlKey || event.composed)) {
api.copySelectedRangeToClipboard(false);
return true;
}
return false;
}, []);
const onRowSelectable = useCallback((rowNode: RowNode) => {
const notRemove = get(rowNode, 'data._rowType') !== DataActions.removeTag;
if (isRowSelectable) {
return isRowSelectable(rowNode) && notRemove;
}
return notRemove;
}, []);
// 监听context变换并更新
contextHooks(context, apiRef, onContextChangeRender);
const exportParams = useMemo(() => {
return {
columnKeys: exportColumns,
allColumns: false,
columnGroups: true,
...defaultExportParams,
};
}, [defaultExportParams, exportColumns]);
const hideBox = useMemo(() => {
return hideSelectedBox || rowSelection !== 'multiple' || hideSelcetedBox;
}, [hideSelectedBox, rowSelection, hideSelcetedBox]);
//编辑结束
const onCellEditingStopped = useCallback((params: CellEditingStoppedEvent) => {
const tipDoms = document.querySelectorAll('.gant-cell-tooltip.ag-tooltip-custom');
tipDoms.forEach(itemDom => {
itemDom.remove();
});
}, []);
// 监听数据变化
const onRowDataUpdated = useCallback(
(event: RowDataUpdatedEvent) => {
const { api } = event;
propOnRowDataUpdated && propOnRowDataUpdated(event);
if (isEmpty(selectedRows) || typeof onSelectedChanged !== 'function') return;
const gridSelectedRows = api.getSelectedRows();
let changed = false;
const newSelectedRows = selectedRows.map(item => {
const gridIndex = findIndex(
gridSelectedRows,
gridItem => getRowNodeId(gridItem) === getRowNodeId(item),
);
if (gridIndex >= 0) {
const newSelectedItem = gridSelectedRows[gridIndex];
const diff = !isEqual(newSelectedItem, item);
changed = diff ? diff : changed;
return diff ? newSelectedItem : item;
}
return item;
});
if (changed)
onSelectedChanged(
newSelectedRows.map(item => getRowNodeId(item)),
newSelectedRows,
);
},
[selectedRows, onSelectedChanged],
);
const currentTreeData = useMemo(() => {
if (!treeDataForcedFilter || !treeData) return treeData;
if (isEmpty(filterModelRef.current)) return true;
return false;
}, [forcedGridKey]);
const renderColumns = useCallback((columnDefs: (ColGroupDef | ColDef)[]) => {
return columnDefs.map((item, index) => {
const props: any = { key: (item as any).field || index };
if ((item as ColGroupDef).marryChildren)
return (
<AgGridColumn {...item} {...props} groupId={(item as any).field || index}>
{renderColumns((item as any).children)}
</AgGridColumn>
);
return <AgGridColumn {...item} {...props} />;
});
}, []);
return (
<LocaleReceiver
children={(local, localeCode = 'zh-cn') => {
let lang = langs[localeCode] || langs['zh-cn'];
const locale = { ...lang, ...customLocale };
const contextMenuItems = function(params: GetContextMenuItemsParams) {
return gantGetcontextMenuItems(params, {
downShift: shiftRef.current,
onRowsCut,
onRowsPaste,
locale,
getContextMenuItems,
defaultJsonParams,
hideMenuItemExport,
hideMenuItemExpand,
hiddenMenuItemNames,
suppressRightClickSelected,
showCutChild,
});
};
return (
<Spin spinning={loading || !ready}>
<GridContext.Provider
value={{
serverDataRequest,
isServerSideGroup,
size,
getDataPath: getDataPath,
computedPagination,
treeData: currentTreeData,
...context,
}}
>
<div
style={{ width, height: gridHeight }}
className={classnames(
'gant-grid',
`gant-grid-${getSizeClassName(size)}`,
openEditSign && `gant-grid-edit`,
(editable || (drawerMode && visibleDrawer)) &&
openEditSign &&
'gant-grid-editable',
)}
>
<div
style={{
display: 'flex',
width,
height: computedPagination ? 'calc(100% - 30px)' : '100%',
}}
>
<div
className={classnames(themeClass, 'gant-ag-wrapper', editable && 'no-zebra')}
data-refid={gridKey}
style={{
width: '100%',
height: '100%',
flex: 1,
}}
{...gridForcedProps}
>
{!hideBox && (
<SelectedGrid
apiRef={apiRef}
onChange={onBoxSelectionChanged}
getRowNodeId={getRowNodeId}
columnDefs={selectedColumns as any}
rowData={boxSelectedRows}
selectedBoxHeight={selectedBoxHeight}
selectedBoxWidth={selectedBoxWidth}
/>
)}
<AgGridReact
frameworkComponents={{
agColumnHeader: CustomHeader,
agDateInput: gantDateComponent ? GantDateComponent : null,
...frameworkComponentsMaps,
...frameworkComponents,
}}
components={{
...componentsMaps,
...components,
}}
onRowClicked={handleRowClicked}
onSelectionChanged={onSelectionChanged}
onRowSelected={onRowSelected}
rowSelection={rowSelection}
getRowNodeId={getRowNodeId}
onGridReady={onGridReady}
undoRedoCellEditing
enableFillHandle
headerHeight={24}
floatingFiltersHeight={20}
singleClickEdit
defaultExportParams={exportParams}
context={{
serverDataRequest,
isServerSideGroup,
size,
getDataPath: getDataPath,
computedPagination,
groupSelectsChildren,
...context,
treeData: currentTreeData,
requireds,
}}
onFilterModified={onFilterModified}
suppressCsvExport
stopEditingWhenGridLosesFocus={false}
treeData={currentTreeData}
suppressScrollOnNewData
tooltipShowDelay={0}
tooltipMouseTrack
excludeChildrenWhenTreeDataFiltering
{...selection}
excelStyles={[{ id: 'stringType', dataType: 'String' }, ...excelStyles]}
immutableData
{...orignProps}
rowHeight={size == 'small' ? 24 : 32}
getDataPath={getDataPath}
// columnDefs={localColumnsDefs}
gridOptions={{
...orignProps?.gridOptions,
}}
isRowSelectable={onRowSelectable}
defaultColDef={{
resizable,
sortable,
filter,
minWidth: 30,
tooltipValueGetter: (params: any) => params.value,
headerCheckboxSelectionFilteredOnly: true,
tooltipComponent: 'gantTooltip',
headerComponentParams: {
ColumnLabelComponent,
},
...defaultColDef,
filterParams: {
buttons: ['reset'],
...get(defaultColDef, 'filterParams', {}),
},
}}
onRowDoubleClicked={handleRowDoubleClicked}
groupSelectsChildren={treeData ? false : groupSelectsChildren}
enableCellTextSelection
ensureDomOrder
groupDefaultExpanded={groupDefaultExpanded}
localeText={locale}
rowClassRules={{
'gant-grid-row-isdeleted': params =>
get(params, 'data._rowType') === DataActions.removeTag,
'gant-grid-row-cut': params => get(params, 'data._rowCut'),
...rowClassRules,
}}
getContextMenuItems={contextMenuItems as any}
modules={[...AllModules]}
suppressKeyboardEvent={onSuppressKeyboardEvent}
onCellEditingStopped={onCellEditingStopped}
onRowDataUpdated={onRowDataUpdated}
onColumnMoved={onColumnsChange}
onColumnVisible={onColumnsChange}
onColumnResized={onColumnsChange}
>
{renderColumns(localColumnsDefs)}
</AgGridReact>
</div>
<GantGridFormToolPanelRenderer
columns={columns}
clickedEvent={clickedEvent}
drawerMode={drawerMode}
context={context}
gridManager={gridManager}
visible={visibleDrawer}
closeDrawer={() =>
typeof propVisibleDrawer !== 'boolean' && setVisibleDrawer(false)
}
onCellEditChange={onCellEditChange}
onCellEditingChange={onCellEditingChange}
defaultDrawerWidth={defaultDrawerWidth}
customDrawerContent={customDrawerContent}
/>
</div>
{computedPagination && <GantPagination {...computedPagination} />}
</div>
</GridContext.Provider>
</Spin>
);
}}
></LocaleReceiver>
);
};
Grid.defaultProps = defaultProps;
Grid.LicenseManager = LicenseManager;
export default Grid; | the_stack |
import * as RehypeBuilder from "annotatedtext-rehype";
import * as RemarkBuilder from "annotatedtext-remark";
import * as Fetch from "node-fetch";
import {
CancellationToken,
CodeAction,
CodeActionContext,
CodeActionKind,
CodeActionProvider,
Diagnostic,
DiagnosticCollection,
DiagnosticSeverity,
languages,
Position,
Range,
TextDocument,
Uri,
workspace,
WorkspaceEdit,
} from "vscode";
import * as Constants from "./Constants";
import { ConfigurationManager } from "./ConfigurationManager";
import { FormattingProviderDashes } from "./FormattingProviderDashes";
import { FormattingProviderEllipses } from "./FormattingProviderEllipses";
import { FormattingProviderQuotes } from "./FormattingProviderQuotes";
import {
ILanguageToolMatch,
ILanguageToolReplacement,
ILanguageToolResponse,
} from "./Interfaces";
import { IAnnotatedtext, IAnnotation } from "annotatedtext";
class LTDiagnostic extends Diagnostic {
match?: ILanguageToolMatch;
}
export class Linter implements CodeActionProvider {
// Is the rule a Spelling rule?
// See: https://forum.languagetool.org/t/identify-spelling-rules/4775/3
public static isSpellingRule(ruleId: string): boolean {
return (
ruleId.indexOf("MORFOLOGIK_RULE") !== -1 ||
ruleId.indexOf("SPELLER_RULE") !== -1 ||
ruleId.indexOf("HUNSPELL_NO_SUGGEST_RULE") !== -1 ||
ruleId.indexOf("HUNSPELL_RULE") !== -1 ||
ruleId.indexOf("FR_SPELLING_RULE") !== -1
);
}
public diagnosticCollection: DiagnosticCollection;
public remarkBuilderOptions: RemarkBuilder.IOptions = RemarkBuilder.defaults;
public rehypeBuilderOptions: RehypeBuilder.IOptions = RehypeBuilder.defaults;
private readonly configManager: ConfigurationManager;
private timeoutMap: Map<string, NodeJS.Timeout>;
constructor(configManager: ConfigurationManager) {
this.configManager = configManager;
this.timeoutMap = new Map<string, NodeJS.Timeout>();
this.diagnosticCollection = languages.createDiagnosticCollection(
Constants.EXTENSION_DISPLAY_NAME,
);
this.remarkBuilderOptions.interpretmarkup = this.customMarkdownInterpreter;
}
// Provide CodeActions for thw given Document and Range
public provideCodeActions(
document: TextDocument,
_range: Range,
context: CodeActionContext,
_token: CancellationToken,
): CodeAction[] {
const diagnostics = context.diagnostics || [];
const actions: CodeAction[] = [];
diagnostics
.filter(
(diagnostic) =>
diagnostic.source === Constants.EXTENSION_DIAGNOSTIC_SOURCE,
)
.forEach((diagnostic) => {
const match:
| ILanguageToolMatch
| undefined = (diagnostic as LTDiagnostic).match;
if (match && Linter.isSpellingRule(match.rule.id)) {
const spellingActions: CodeAction[] = this.getSpellingRuleActions(
document,
diagnostic,
);
if (spellingActions.length > 0) {
spellingActions.forEach((action) => {
actions.push(action);
});
}
} else {
this.getRuleActions(document, diagnostic).forEach((action) => {
actions.push(action);
});
}
});
return actions;
}
// Remove diagnostics for a Document URI
public clearDiagnostics(uri: Uri): void {
this.diagnosticCollection.delete(uri);
}
// Request a lint for a document
public requestLint(
document: TextDocument,
timeoutDuration: number = Constants.EXTENSION_TIMEOUT_MS,
): void {
if (this.configManager.isSupportedDocument(document)) {
this.cancelLint(document);
const uriString = document.uri.toString();
const timeout = setTimeout(() => {
this.lintDocument(document);
}, timeoutDuration);
this.timeoutMap.set(uriString, timeout);
}
}
// Force request a lint for a document as plain text regardless of language id
public requestLintAsPlainText(
document: TextDocument,
timeoutDuration: number = Constants.EXTENSION_TIMEOUT_MS,
): void {
this.cancelLint(document);
const uriString = document.uri.toString();
const timeout = setTimeout(() => {
this.lintDocumentAsPlainText(document);
}, timeoutDuration);
this.timeoutMap.set(uriString, timeout);
}
// Cancel lint
public cancelLint(document: TextDocument): void {
const uriString: string = document.uri.toString();
if (this.timeoutMap.has(uriString)) {
if (this.timeoutMap.has(uriString)) {
const timeout: NodeJS.Timeout = this.timeoutMap.get(
uriString,
) as NodeJS.Timeout;
clearTimeout(timeout);
this.timeoutMap.delete(uriString);
}
}
}
// Build annotatedtext from Markdown
public buildAnnotatedMarkdown(text: string): IAnnotatedtext {
return RemarkBuilder.build(text, this.remarkBuilderOptions);
}
// Build annotatedtext from HTML
public buildAnnotatedHTML(text: string): IAnnotatedtext {
return RehypeBuilder.build(text, this.rehypeBuilderOptions);
}
// Build annotatedtext from PLAINTEXT
public buildAnnotatedPlaintext(plainText: string): IAnnotatedtext {
const textAnnotation: IAnnotation = {
text: plainText,
offset: {
start: 0,
end: plainText.length,
},
};
return { annotation: [textAnnotation] };
}
// Abstract annotated text builder
public buildAnnotatedtext(document: TextDocument): IAnnotatedtext {
let annotatedtext: IAnnotatedtext = { annotation: [] };
switch (document.languageId) {
case Constants.LANGUAGE_ID_MARKDOWN:
annotatedtext = this.buildAnnotatedMarkdown(document.getText());
break;
case Constants.LANGUAGE_ID_MDX:
annotatedtext = this.buildAnnotatedMarkdown(document.getText());
break;
case Constants.LANGUAGE_ID_HTML:
annotatedtext = this.buildAnnotatedHTML(document.getText());
break;
default:
annotatedtext = this.buildAnnotatedPlaintext(document.getText());
break;
}
return annotatedtext;
}
// Perform Lint on Document
public lintDocument(document: TextDocument): void {
if (this.configManager.isSupportedDocument(document)) {
if (document.languageId === Constants.LANGUAGE_ID_MARKDOWN) {
const annotatedMarkdown: string = JSON.stringify(
this.buildAnnotatedMarkdown(document.getText()),
);
this.lintAnnotatedText(document, annotatedMarkdown);
} else if (document.languageId === Constants.LANGUAGE_ID_HTML) {
const annotatedHTML: string = JSON.stringify(
this.buildAnnotatedHTML(document.getText()),
);
this.lintAnnotatedText(document, annotatedHTML);
} else {
this.lintDocumentAsPlainText(document);
}
}
}
// Perform Lint on Document As Plain Text
public lintDocumentAsPlainText(document: TextDocument): void {
const annotatedPlaintext: string = JSON.stringify(
this.buildAnnotatedPlaintext(document.getText()),
);
this.lintAnnotatedText(document, annotatedPlaintext);
}
// Lint Annotated Text
public lintAnnotatedText(
document: TextDocument,
annotatedText: string,
): void {
const ltPostDataDict: Record<string, string> = this.getPostDataTemplate();
ltPostDataDict.data = annotatedText;
this.callLanguageTool(document, ltPostDataDict);
}
// Apply smart formatting to annotated text.
public smartFormatAnnotatedtext(annotatedtext: IAnnotatedtext): string {
let newText = "";
// Only run substitutions on text annotations.
annotatedtext.annotation.forEach((annotation) => {
if (annotation.text) {
newText += annotation.text
// Open Double Quotes
.replace(/"(?=[\w'‘])/g, FormattingProviderQuotes.startDoubleQuote)
// Close Double Quotes
.replace(
/([\w.!?%,'’])"/g,
"$1" + FormattingProviderQuotes.endDoubleQuote,
)
// Remaining Double Quotes
.replace(/"/, FormattingProviderQuotes.endDoubleQuote)
// Open Single Quotes
.replace(
/(\W)'(?=[\w"“])/g,
"$1" + FormattingProviderQuotes.startSingleQuote,
)
// Closing Single Quotes
.replace(
/([\w.!?%,"”])'/g,
"$1" + FormattingProviderQuotes.endSingleQuote,
)
// Remaining Single Quotes
.replace(/'/, FormattingProviderQuotes.endSingleQuote)
.replace(/([\w])---(?=[\w])/g, "$1" + FormattingProviderDashes.emDash)
.replace(/([\w])--(?=[\w])/g, "$1" + FormattingProviderDashes.enDash)
.replace(/\.\.\./g, FormattingProviderEllipses.ellipses);
} else if (annotation.markup) {
newText += annotation.markup;
}
});
return newText;
}
// Private instance methods
// Custom markdown interpretation
private customMarkdownInterpreter(text: string): string {
// Default of preserve line breaks
let interpretation = "\n".repeat((text.match(/\n/g) || []).length);
if (text.match(/^(?!\s*`{3})\s*`{1,2}/)) {
// Treat inline code as redacted text
interpretation = "`" + "#".repeat(text.length - 2) + "`";
} else if (text.match(/#\s+$/)) {
// Preserve Headers
interpretation += "# ";
} else if (text.match(/\*\s+$/)) {
// Preserve bullets without leading spaces
interpretation += "* ";
} else if (text.match(/\d+\.\s+$/)) {
// Treat as bullets without leading spaces
interpretation += "** ";
}
return interpretation;
}
// Set ltPostDataTemplate from Configuration
private getPostDataTemplate(): Record<string, string> {
const ltPostDataTemplate: Record<string, string> = {};
this.configManager.getServiceParameters().forEach((value, key) => {
ltPostDataTemplate[key] = value;
});
return ltPostDataTemplate;
}
// Call to LanguageTool Service
private callLanguageTool(
document: TextDocument,
ltPostDataDict: Record<string, string>,
): void {
const url = this.configManager.getUrl();
if (url) {
const formBody = Object.keys(ltPostDataDict)
.map(
(key: string) =>
encodeURIComponent(key) +
"=" +
encodeURIComponent(ltPostDataDict[key]),
)
.join("&");
const options: Fetch.RequestInit = {
body: formBody,
headers: {
"Accepts": "application/json",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
},
method: "POST",
};
Fetch.default(url, options)
.then((res) => res.json())
.then((json) => this.suggest(document, json))
.catch((err) => {
Constants.EXTENSION_OUTPUT_CHANNEL.appendLine(
"Error connecting to " + url,
);
Constants.EXTENSION_OUTPUT_CHANNEL.appendLine(err);
});
} else {
Constants.EXTENSION_OUTPUT_CHANNEL.appendLine(
"No LanguageTool URL provided. Please check your settings and try again.",
);
Constants.EXTENSION_OUTPUT_CHANNEL.show(true);
}
}
// Convert LanguageTool Suggestions into QuickFix CodeActions
private suggest(
document: TextDocument,
response: ILanguageToolResponse,
): void {
const matches = response.matches;
const diagnostics: LTDiagnostic[] = [];
matches.forEach((match: ILanguageToolMatch) => {
const start: Position = document.positionAt(match.offset);
const end: Position = document.positionAt(match.offset + match.length);
const diagnosticSeverity: DiagnosticSeverity = this.configManager.getDiagnosticSeverity();
const diagnosticRange: Range = new Range(start, end);
const diagnosticMessage: string = match.message;
const diagnostic: LTDiagnostic = new LTDiagnostic(
diagnosticRange,
diagnosticMessage,
diagnosticSeverity,
);
diagnostic.source = Constants.EXTENSION_DIAGNOSTIC_SOURCE;
diagnostic.match = match;
if (Linter.isSpellingRule(match.rule.id)) {
if (!this.configManager.isHideRuleIds()) {
diagnostic.code = match.rule.id;
}
} else {
diagnostic.code = {
target: this.configManager.getRuleUrl(match.rule.id),
value: this.configManager.isHideRuleIds()
? Constants.SERVICE_RULE_URL_GENERIC_LABEL
: match.rule.id,
};
}
diagnostics.push(diagnostic);
if (
Linter.isSpellingRule(match.rule.id) &&
this.configManager.isIgnoredWord(document.getText(diagnostic.range)) &&
this.configManager.showIgnoredWordHints()
) {
diagnostic.severity = DiagnosticSeverity.Hint;
}
});
this.diagnosticCollection.set(document.uri, diagnostics);
}
// Get CodeActions for Spelling Rules
private getSpellingRuleActions(
document: TextDocument,
diagnostic: LTDiagnostic,
): CodeAction[] {
const actions: CodeAction[] = [];
const match: ILanguageToolMatch | undefined = diagnostic.match;
const word: string = document.getText(diagnostic.range);
if (this.configManager.isIgnoredWord(word)) {
if (this.configManager.showIgnoredWordHints()) {
if (this.configManager.isGloballyIgnoredWord(word)) {
const actionTitle: string =
"Remove '" + word + "' from always ignored words.";
const action: CodeAction = new CodeAction(
actionTitle,
CodeActionKind.QuickFix,
);
action.command = {
arguments: [word],
command: "languagetoolLinter.removeGloballyIgnoredWord",
title: actionTitle,
};
action.diagnostics = [];
action.diagnostics.push(diagnostic);
actions.push(action);
}
if (this.configManager.isWorkspaceIgnoredWord(word)) {
const actionTitle: string =
"Remove '" + word + "' from Workspace ignored words.";
const action: CodeAction = new CodeAction(
actionTitle,
CodeActionKind.QuickFix,
);
action.command = {
arguments: [word],
command: "languagetoolLinter.removeWorkspaceIgnoredWord",
title: actionTitle,
};
action.diagnostics = [];
action.diagnostics.push(diagnostic);
actions.push(action);
}
}
} else {
const usrIgnoreActionTitle: string = "Always ignore '" + word + "'";
const usrIgnoreAction: CodeAction = new CodeAction(
usrIgnoreActionTitle,
CodeActionKind.QuickFix,
);
usrIgnoreAction.command = {
arguments: [word],
command: "languagetoolLinter.ignoreWordGlobally",
title: usrIgnoreActionTitle,
};
usrIgnoreAction.diagnostics = [];
usrIgnoreAction.diagnostics.push(diagnostic);
actions.push(usrIgnoreAction);
if (workspace !== undefined) {
const wsIgnoreActionTitle: string =
"Ignore '" + word + "' in Workspace";
const wsIgnoreAction: CodeAction = new CodeAction(
wsIgnoreActionTitle,
CodeActionKind.QuickFix,
);
wsIgnoreAction.command = {
arguments: [word],
command: "languagetoolLinter.ignoreWordInWorkspace",
title: wsIgnoreActionTitle,
};
wsIgnoreAction.diagnostics = [];
wsIgnoreAction.diagnostics.push(diagnostic);
actions.push(wsIgnoreAction);
}
if (match) {
this.getReplacementActions(
document,
diagnostic,
match.replacements,
).forEach((action: CodeAction) => {
actions.push(action);
});
}
}
return actions;
}
// Get all Rule CodeActions
private getRuleActions(
document: TextDocument,
diagnostic: LTDiagnostic,
): CodeAction[] {
const match: ILanguageToolMatch | undefined = diagnostic.match;
const actions: CodeAction[] = [];
if (match) {
this.getReplacementActions(
document,
diagnostic,
match.replacements,
).forEach((action: CodeAction) => {
actions.push(action);
});
}
return actions;
}
// Get all edit CodeActions based on Replacements
private getReplacementActions(
document: TextDocument,
diagnostic: Diagnostic,
replacements: ILanguageToolReplacement[],
): CodeAction[] {
const actions: CodeAction[] = [];
replacements.forEach((replacement: ILanguageToolReplacement) => {
const actionTitle: string = "'" + replacement.value + "'";
const action: CodeAction = new CodeAction(
actionTitle,
CodeActionKind.QuickFix,
);
const edit: WorkspaceEdit = new WorkspaceEdit();
edit.replace(document.uri, diagnostic.range, replacement.value);
action.edit = edit;
action.diagnostics = [];
action.diagnostics.push(diagnostic);
actions.push(action);
});
return actions;
}
} | the_stack |
const util = require('util');
import { readdirSync, unlinkSync } from 'fs';
import { normalize, join } from 'path';
import {
forEach,
keys,
indexOf,
has,
some,
lowerFirst,
kebabCase,
snakeCase,
upperFirst,
endsWith,
find,
each,
uniqBy,
uniq,
isNil
} from 'lodash';
import {
log,
readAndCompileTemplateFile,
ensureFolder,
writeFileIfContentsIsChanged,
isInTypesToFilter,
getPathToRoot,
getSortedObjectProperties,
convertNamespaceToPath,
hasTypeFromDescription,
getTypeFromDescription,
getDirectories,
removeFolder,
removeExtension,
logError
} from './utils';
import { GeneratorOptions } from '../bootstrap/options';
import {
Swagger,
SwaggerDefinition,
SwaggerPropertyDefinition,
SwaggerDefinitionProperties
} from '../bootstrap/swagger';
import { prototype } from 'stream';
import { strict } from 'assert';
interface Type {
fileName: string;
typeName: string;
namespace: string;
fullNamespace: string;
fullTypeName: string;
importFile: string;
isSubType: boolean;
hasSubTypeProperty: boolean;
isBaseType: boolean;
baseType: Type;
baseImportFile: string;
path: string;
pathToRoot: string;
properties: TypeProperty[];
}
interface TypeProperty {
name: string;
staticFieldName: string;
type: Type;
typeName: string;
interfaceTypeName: string;
namespace: string;
description: string;
hasValidation: boolean;
isComplexType: boolean;
isImportType: boolean;
isUniqueImportType: boolean;
importType: string;
importFile: string;
isEnum: boolean;
isUniqueImportEnumType: boolean;
importEnumType: string;
isArray: boolean;
isArrayComplexType: boolean;
arrayTypeName: string;
arrayInterfaceTypeName: string;
validators: {
validation: {
required: boolean;
minimum: number;
maximum: number;
enum: string;
minLength: number;
maxLength: number;
pattern: string;
};
validatorArray: string[];
};
enum: string[];
}
interface NamespaceGroups {
[namespace: string]: Type[];
}
const TS_SUFFIX = '.ts';
const MODEL_SUFFIX = '.model';
const MODEL_FILE_SUFFIX = `${MODEL_SUFFIX}${TS_SUFFIX}`;
const ROOT_NAMESPACE = 'root';
// const BASE_TYPE_WAIT_FOR_SECOND_PASS = 'wait-for-second-pass';
export function generateModelTSFiles(swagger: Swagger, options: GeneratorOptions) {
let folder = normalize(options.modelFolder);
// generate fixed file with non-standard validators for validation rules which can be defined in the swagger file
if (options.generateValidatorFile) {
generateTSValidations(folder, options);
}
// generate fixed file with the BaseModel class
generateTSBaseModel(folder, options);
// get type definitions from swagger
let typeCollection = getTypeDefinitions(swagger, options, MODEL_SUFFIX, MODEL_FILE_SUFFIX);
// console.log('typeCollection', util.inspect(typeCollection, false, null, true));
// group types per namespace
let namespaceGroups = getNamespaceGroups(typeCollection, options);
// console.log('namespaceGroups', namespaceGroups);
// generate model files
generateTSModels(namespaceGroups, folder, options);
// generate subTypeFactory
generateSubTypeFactory(namespaceGroups, folder, options);
// generate barrel files (index files to simplify import statements)
if (options.generateBarrelFiles) {
generateBarrelFiles(namespaceGroups, folder, options);
}
}
function generateTSValidations(folder: string, options: GeneratorOptions) {
if (!options.generateClasses) return;
let outputFileName = join(folder, options.validatorsFileName);
let data = {};
let template = readAndCompileTemplateFile(options.templates.validators);
let result = template(data);
ensureFolder(folder);
let isChanged = writeFileIfContentsIsChanged(outputFileName, result);
if (isChanged) {
log(`generated ${outputFileName}`);
}
}
function generateTSBaseModel(folder: string, options: GeneratorOptions) {
if (!options.generateClasses) return;
let outputFileName = join(folder, options.baseModelFileName);
let data = {
subTypePropertyName: options.subTypePropertyName,
generateFormGroups: options.generateFormGroups
};
let template = readAndCompileTemplateFile(options.templates.baseModel);
let result = template(data);
ensureFolder(folder);
let isChanged = writeFileIfContentsIsChanged(outputFileName, result);
if (isChanged) {
log(`generated ${outputFileName}`);
}
}
function getTypeDefinitions(swagger: Swagger, options: GeneratorOptions, suffix: string, fileSuffix: string) {
let typeCollection: Type[] = new Array();
// console.log('typesToFilter', options.typesToFilter);
// // sort the definitions so subTypes are on top
// // console.log('swagger.definitions', swagger.definitions);
// console.log('----------------------------------------------');
// // _(object).toPairs().sortBy(0).fromPairs().value();
// swagger.definitions = _(swagger.definitions).toPairs().sortBy(0, [
// item => {
// console.log(item, 'isSubType', getIsSubType(item))
// return getIsSubType(item)
// }
// ]).fromPairs().value();
// // console.log('sorted swagger.definitions', swagger.definitions);
// console.log('----------------------------------------------');
forEach(swagger.definitions, (item, key) => {
if (!isInTypesToFilter(item, key, options)) {
let type = getTypeDefinition(swagger, typeCollection, item, key, options, suffix, fileSuffix);
if (type) {
typeCollection.push(type);
}
}
});
// second pass: fill baseTypes that are still null
// (if the swagger is generated by SpringFox, the definitions might be sorted by propertyName
// so baseTypes are not on the top. In that case, baseTypes might not have been found when
// finding a subtype)
fillMissingBaseTypes(swagger, typeCollection, options, suffix, fileSuffix);
// fill types of the properties
fillPropertyTypes(swagger, typeCollection, options, suffix, fileSuffix);
// filter on unique types
typeCollection = uniqBy(typeCollection, 'typeName');
return typeCollection;
}
function getTypeDefinition(
swagger: Swagger,
typeCollection: Type[],
item: SwaggerDefinition,
key: string,
options: GeneratorOptions,
suffix: string,
fileSuffix: string
) {
// filter enum types (these are generated by the enumGenerator)
let isEnumType = getIsEnumType(item);
if (isEnumType) {
return undefined;
}
let required = (item.required as string[]) || [];
let namespace = getNamespace(key, options, true);
let fullNamespace = getNamespace(key, options, false);
let typeName = getTypeName(key, options);
if (getIsGenericType(typeName)) {
typeName = convertGenericToGenericT(typeName);
}
let fullTypeName = fullNamespace ? `${fullNamespace}.${typeName}` : typeName;
let pathToRoot = getPathToRoot(namespace);
let importFile = getImportFile(typeName, namespace, pathToRoot, suffix);
let properties = options.sortModelProperties
? (getSortedObjectProperties(item.properties) as SwaggerDefinitionProperties)
: item.properties;
let baseType = undefined;
let baseImportFile = undefined;
let isSubType = getIsSubType(item);
let hasSubTypeProperty = isSubType || getHasSubTypeProperty(properties, options);
if (isSubType) {
baseType = getBaseType(typeName, typeCollection, item, options, false);
// baseType might not be in the typeCollection yet
// in that case, a second pass will be done with method fillMissingBaseTypes
if (baseType) {
// set that the baseType is a baseType
baseType.isBaseType = true;
// determine baseImportFile
baseImportFile = getImportFile(baseType.typeName, baseType.namespace, pathToRoot, suffix);
required = getSubTypeRequired(item);
properties = getSubTypeProperties(item, baseType);
}
}
let type: Type = {
fileName: getFileName(key, options, fileSuffix),
typeName: typeName,
namespace: namespace,
fullNamespace: fullNamespace,
fullTypeName: fullTypeName,
isSubType: isSubType,
hasSubTypeProperty: hasSubTypeProperty,
importFile: importFile,
isBaseType: false, // set elsewhere
baseType: baseType,
baseImportFile: baseImportFile,
path: convertNamespaceToPath(namespace),
pathToRoot: pathToRoot,
properties: []
};
fillTypeProperties(swagger, type, baseType, required, properties, item, key, options, suffix, fileSuffix);
return type;
}
function fillMissingBaseTypes(
swagger: Swagger,
typeCollection: Type[],
options: GeneratorOptions,
suffix: string,
fileSuffix: string
) {
// console.log('-------------------> In fillMissingBaseTypes <---------------------------')
forEach(swagger.definitions, (item, key) => {
let isSubType = getIsSubType(item);
let type = findTypeInTypeCollection(typeCollection, key);
if (isSubType && !type.baseType) {
let namespace = getNamespace(key, options, true);
let pathToRoot = getPathToRoot(namespace);
let baseType = getBaseType(key, typeCollection, item, options, true);
let baseImportFile;
if (baseType) {
// set that the baseType is a baseType
baseType.isBaseType = true;
// determine baseImportFile
baseImportFile = getImportFile(baseType.typeName, baseType.namespace, pathToRoot, suffix);
}
let required = getSubTypeRequired(item);
let properties = getSubTypeProperties(item, baseType);
type.baseType = baseType;
type.baseImportFile = baseImportFile;
fillTypeProperties(swagger, type, baseType, required, properties, item, key, options, suffix, fileSuffix);
}
});
}
function fillPropertyTypes(
swagger: Swagger,
typeCollection: Type[],
options: GeneratorOptions,
suffix: string,
fileSuffix: string
) {
const missingTypes = new Array<string>();
forEach(typeCollection, (type, typeKey) => {
forEach(type.properties, (property, propertyKey) => {
const propertyType = findTypeInTypeCollection(typeCollection, property.typeName);
property.type = propertyType;
if (isNil(propertyType) && !property.isEnum && property.isComplexType) {
let isMissingType = true;
let missingTypeName = property.typeName;
if (property.isArrayComplexType) {
isMissingType = isNil(findTypeInTypeCollection(typeCollection, property.arrayTypeName));
missingTypeName = property.arrayTypeName;
} else if (property.isArray) {
isMissingType = false;
}
if (isMissingType) {
missingTypes.push(missingTypeName);
// console.error(property);
}
}
});
});
for (const missingType of uniq(missingTypes)) {
logError(`type ${missingType} not found`);
}
}
function fillTypeProperties(
swagger: Swagger,
type: Type,
baseType: Type,
required: string[],
properties: SwaggerDefinitionProperties,
item: SwaggerDefinition,
key: string,
options: GeneratorOptions,
suffix: string,
fileSuffix: string
) {
type.properties = [];
forEach(properties, (item, key) => {
let property = getTypePropertyDefinition(
swagger,
type,
baseType,
required,
item,
key,
options,
suffix,
fileSuffix
);
type.properties.push(property);
});
}
function getTypePropertyDefinition(
swagger: Swagger,
type: Type,
baseType: Type,
required: string[],
item: SwaggerPropertyDefinition,
key: string,
options: GeneratorOptions,
suffix: string,
fileSuffix: string
) {
const staticFieldName = `${snakeCase(key).toUpperCase()}_FIELD_NAME`;
let isRefType = !!item.$ref;
let isArray = item.type == 'array';
let isEnum =
(item.type == 'string' && !!item.enum) ||
(isArray && item.items && item.items.type == 'string' && !!item.items.enum) ||
((isRefType || isArray) && getIsEnumRefType(swagger, item, isArray));
// enum ref types are not handles as model types (they are handled in the enumGenerator)
if (isEnum) {
isRefType = false;
}
let propertyType = getPropertyType(item, key, options, isEnum);
let isComplexType = isRefType || isArray; // new this one in constructor
let isImportType = isRefType || (isArray && item.items.$ref && !isEnum);
let importType = isImportType ? getImportType(propertyType.typeName, isArray) : undefined;
let importFile = isImportType
? getImportFile(importType, propertyType.namespace, type.pathToRoot, suffix)
: undefined;
let importTypeIsPropertyType = importType === type.typeName;
let isUniqueImportType =
isImportType && !importTypeIsPropertyType && getIsUniqueImportType(importType, baseType, type.properties); // import this type
let validators = getTypePropertyValidatorDefinitions(required, item, key, propertyType.typeName, isEnum);
let hasValidation = keys(validators.validation).length > 0;
let importEnumType = isEnum ? removeGenericArray(propertyType.typeName, isArray) : undefined;
let isUniqueImportEnumType = isEnum && getIsUniqueImportEnumType(importEnumType, type.properties); // import this enumType
let property = {
name: key,
staticFieldName: staticFieldName,
type: null, // filled elsewhere
typeName: propertyType.typeName,
interfaceTypeName: propertyType.interfaceTypeName,
namespace: propertyType.namespace,
description: item.description,
hasValidation: hasValidation,
isComplexType: isComplexType,
isImportType: isImportType,
isUniqueImportType: isUniqueImportType,
importType: importType,
importFile: importFile,
isEnum: isEnum,
isUniqueImportEnumType: isUniqueImportEnumType,
importEnumType: importEnumType,
isArray: isArray,
isArrayComplexType: propertyType.isArrayComplexType,
arrayTypeName: propertyType.arrayTypeName,
arrayInterfaceTypeName: propertyType.arrayInterfaceTypeName,
validators: validators,
enum: item.enum
};
return property;
}
function getTypePropertyValidatorDefinitions(
required: string[],
item: SwaggerPropertyDefinition,
key: string,
typeName: string,
isEnum: boolean
) {
let isRequired = indexOf(required, key) !== -1;
// console.log('key=', key, 'typeName', typeName, 'item=', item, 'enum=', item.enum);
let validators = {
validation: {} as any,
validatorArray: []
};
if (isRequired) {
validators.validation.required = isRequired;
validators.validatorArray.push('Validators.required');
}
if (has(item, 'minimum')) {
validators.validation.minimum = item.minimum;
validators.validatorArray.push(`minValueValidator(${item.minimum})`);
}
if (has(item, 'maximum')) {
validators.validation.maximum = item.maximum;
validators.validatorArray.push(`maxValueValidator(${item.maximum})`);
}
if (isEnum) {
validators.validation.enum = `'${item.enum}'`;
validators.validatorArray.push(`enumValidator(${typeName})`);
}
if (has(item, 'minLength')) {
validators.validation.minLength = item.minLength;
validators.validatorArray.push(`Validators.minLength(${item.minLength})`);
}
if (has(item, 'maxLength')) {
validators.validation.maxLength = item.maxLength;
validators.validatorArray.push(`Validators.maxLength(${item.maxLength})`);
}
if (has(item, 'pattern')) {
validators.validation.pattern = `'${item.pattern}'`;
validators.validatorArray.push(`Validators.pattern('${item.pattern}')`);
}
return validators;
}
function getIsUniqueImportType(currentTypeName: string, baseType: Type, typeProperties: TypeProperty[]) {
let baseTypeName = baseType ? baseType.typeName : undefined;
if (currentTypeName === baseTypeName) {
return false;
}
return !some(typeProperties, property => {
return property.importType === currentTypeName;
});
}
function getIsUniqueImportEnumType(currentTypeName: string, typeProperties: TypeProperty[]) {
return !some(typeProperties, property => {
return property.importEnumType === currentTypeName;
});
}
function getTypeNameWithoutNamespacePrefixesToRemove(key: string, options: GeneratorOptions) {
if (!options.namespacePrefixesToRemove) {
return key;
}
let namespaces = options.namespacePrefixesToRemove;
namespaces.forEach(item => {
key = key.replace(item, '');
if (key[0] === '.') {
key = key.substring(1);
}
});
return key;
}
function getPropertyType(item: SwaggerPropertyDefinition, name: string, options: GeneratorOptions, isEnum: boolean) {
let result = {
typeName: '',
interfaceTypeName: '',
namespace: '',
fullNamespace: undefined,
isArrayComplexType: false,
arrayTypeName: undefined,
arrayInterfaceTypeName: undefined
};
if (item.type) {
result.typeName = item.type;
if (item.type == 'integer') {
result.typeName = 'number';
}
if (item.type == 'string' && item.format == 'date') {
result.typeName = 'Date';
}
if (item.type == 'string' && item.format == 'date-time') {
result.typeName = 'Date';
}
if (item.type == 'string' && item.enum) {
result.typeName = `${name}`;
}
result.interfaceTypeName = result.typeName;
if (item.type == 'array' && item.items) {
let arrayPropType = getPropertyType(item.items, name, options, isEnum);
result.typeName = `Array<${arrayPropType.typeName}>`;
result.interfaceTypeName = `Array<${arrayPropType.interfaceTypeName}>`;
result.namespace = arrayPropType.namespace;
result.isArrayComplexType = !isEnum ? !!item.items.$ref : false;
result.arrayTypeName = arrayPropType.typeName;
result.arrayInterfaceTypeName = arrayPropType.interfaceTypeName;
}
// description may contain an overrule type for enums, eg /** type CoverType */
if (hasTypeFromDescription(item.description)) {
result.typeName = lowerFirst(getTypeFromDescription(item.description));
// fix enum array with overrule type
if (item.type == 'array' && item.items) {
result.arrayTypeName = result.typeName;
result.typeName = `Array<${result.typeName}>`;
}
}
return result;
}
if (item.$ref) {
let type = removeDefinitionsRef(item.$ref);
result.typeName = getTypeName(type, options);
result.namespace = getNamespace(type, options, true);
result.fullNamespace = getNamespace(type, options, false);
// TODO add more C# primitive types
if (getIsGenericType(result.typeName)) {
let genericTType = getGenericTType(result.typeName);
if (genericTType && genericTType === 'System.DateTime') {
result.typeName = result.typeName.replace(genericTType, 'Date');
}
}
result.interfaceTypeName = isEnum ? result.typeName : `I${result.typeName}`;
return result;
}
}
function removeDefinitionsRef(value: string) {
let result = value.replace('#/definitions/', '');
return result;
}
function getFileName(type: string, options: GeneratorOptions, fileSuffix: string) {
let typeName = removeGenericTType(getTypeName(type, options));
return `${kebabCase(typeName)}${fileSuffix}`;
}
function getTypeName(type: string, options: GeneratorOptions) {
let typeName;
if (getIsGenericType(type)) {
let startGenericT = type.indexOf('[');
let startGenericType = type.lastIndexOf('.', startGenericT) + 1;
typeName = type.substring(startGenericType);
typeName = convertGenericTypeName(typeName);
typeName = getTypeNameWithoutSuffixesToRemove(typeName, options);
} else {
typeName = type.split('.').pop();
typeName = getTypeNameWithoutSuffixesToRemove(typeName, options);
// C# Object affects Typescript Object - fix this
if (typeName === 'Object') {
typeName = 'SystemObject';
}
//classNameSuffixesToRemove
}
return upperFirst(typeName);
}
function getTypeNameWithoutSuffixesToRemove(typeName, options) {
if (!options.typeNameSuffixesToRemove) {
return typeName;
}
let typeNameSuffixesToRemove = options.typeNameSuffixesToRemove;
typeNameSuffixesToRemove.forEach(item => {
if (endsWith(typeName, item)) {
typeName = typeName.slice(0, -item.length);
}
});
return typeName;
}
function getIsGenericType(type: string) {
return type.indexOf('[') !== -1 || type.indexOf('<') !== -1;
}
/**
* NullableOrEmpty<System.Date> -> System.Data
*/
function getGenericTType(type) {
if (getIsGenericType(type)) {
return /\<(.*)\>/.exec(type)[1];
}
return undefined;
}
/**
* NullableOrEmpty<System.Date> -> NullableOrEmpty
*/
function removeGenericTType(type: string) {
if (getIsGenericType(type)) {
type = type.substring(0, type.indexOf('<'));
}
return type;
}
/**
* NullableOrEmpty[System.Date] -> NullableOrEmpty<System.Date>
*/
function convertGenericTypeName(typeName) {
return typeName.replace('[', '<').replace(']', '>');
}
/**
* NullableOrEmpty<System.Date> -> NullableOrEmpty<T>
*/
function convertGenericToGenericT(typeName) {
return typeName.replace(/\<.*\>/, '<T>');
}
function getIsSubType(item: SwaggerDefinition) {
return item.allOf !== undefined;
}
function getHasSubTypeProperty(properties: SwaggerDefinitionProperties, options: GeneratorOptions) {
return has(properties, options.subTypePropertyName);
}
function getBaseType(
subTypeName: string,
typeCollection: Type[],
item: SwaggerDefinition,
options: GeneratorOptions,
logErrorForMissingBaseType: boolean
) {
// TODO how about more than one baseType?
let type = removeDefinitionsRef(item.allOf[0].$ref);
let typeName = getTypeName(type, options);
//let namespace = getNamespace(type, options);
let baseType = findTypeInTypeCollection(typeCollection, typeName);
// console.log('---------------------')
// console.log('getBaseType superTypeName', superTypeName, 'type', type, /*'item', item,*/ 'typeName', typeName, 'baseType', baseType ? baseType.typeName : null, /*'typeCollection', typeCollection*/ )
if (!baseType && logErrorForMissingBaseType) {
logError(`baseType ${typeName} of ${subTypeName} not found`);
}
return baseType;
}
function findTypeInTypeCollection(typeCollection: Type[], typeName: string) {
let result = find(typeCollection, type => {
return type.typeName === typeName;
//return type.typeName === typeName && type.namespace === namespace;
});
return result;
}
function getSubTypeProperties(item: SwaggerDefinition, baseType) {
// TODO strip properties which are defined in the baseType?
let properties = item.allOf[1].properties;
return properties;
}
function getSubTypeRequired(item: SwaggerDefinition) {
let required = (item.allOf[1].required as string[]) || [];
return required;
}
function getIsEnumType(item: SwaggerDefinition) {
return !!(item && item.enum);
}
function getIsEnumRefType(swagger, item, isArray) {
let refItemName;
if (isArray) {
// "perilTypesIncluded": {
// "type": "array",
// "items": {
// "$ref": "#/definitions/PerilTypeIncluded"
// }
// },
if (item.items.$ref) {
refItemName = removeDefinitionsRef(item.items.$ref);
}
} else {
// "riskLocationSupraentity": {
// "$ref": "#/definitions/LocationSupraentity",
// "description": "type LocationSupraentity "
// },
refItemName = removeDefinitionsRef(item.$ref);
}
let refItem = swagger.definitions[refItemName];
return getIsEnumType(refItem);
}
function getNamespace(type: string, options: GeneratorOptions, removePrefix: boolean) {
let typeName = removePrefix ? getTypeNameWithoutNamespacePrefixesToRemove(type, options) : type;
if (getIsGenericType(typeName)) {
let first = typeName.substring(0, typeName.indexOf('['));
typeName = first + first.substring(typeName.indexOf(']'));
}
let parts = typeName.split('.');
parts.pop();
return parts.join('.');
}
function getImportType(type: string, isArray: boolean) {
if (isArray) {
let result = removeGenericArray(type, isArray);
return result;
}
type = removeGenericTType(type);
return type;
}
function removeGenericArray(type: string, isArray: boolean) {
if (isArray) {
let result = type.replace('Array<', '').replace('>', '');
return result;
}
return type;
}
function getImportFile(propTypeName: string, propNamespace: string, pathToRoot: string, suffix: string) {
//return `${_.lowerFirst(type)}${suffix}`;
let importPath = `${kebabCase(propTypeName)}${suffix}`;
if (propNamespace) {
let namespacePath = convertNamespaceToPath(propNamespace);
importPath = `${namespacePath}/${importPath}`;
}
return (pathToRoot + importPath).toLocaleLowerCase();
}
function getNamespaceGroups(typeCollection: Type[], options: GeneratorOptions) {
let namespaces: NamespaceGroups = {
[ROOT_NAMESPACE]: []
};
for (let i = 0; i < typeCollection.length; ++i) {
let type = typeCollection[i];
let namespace = type.namespace || ROOT_NAMESPACE;
if (excludeNamespace(namespace, options.exclude)) {
continue;
}
if (!namespaces[namespace]) {
namespaces[namespace] = [];
}
namespaces[namespace].push(type);
}
return namespaces;
}
function excludeNamespace(namespace: string, excludeOptions: (string | RegExp)[]) {
if (!excludeOptions || !excludeOptions.length) {
return false;
}
for (const excludeCheck of excludeOptions) {
if (
(excludeCheck instanceof RegExp && excludeCheck.test(namespace)) ||
~namespace.indexOf(<string>excludeCheck)
) {
return true;
}
}
return false;
}
function generateTSModels(namespaceGroups: NamespaceGroups, folder: string, options: GeneratorOptions) {
let data = {
generateClasses: options.generateClasses,
generateFormGroups: options.generateFormGroups,
hasComplexType: false,
validatorFileName: removeExtension(options.validatorsFileName),
baseModelFileName: removeExtension(options.baseModelFileName),
subTypeFactoryFileName: removeExtension(options.subTypeFactoryFileName),
moduleName: options.modelModuleName,
enumModuleName: options.enumModuleName,
enumRef: options.enumRef,
subTypePropertyName: options.subTypePropertyName,
subTypePropertyConstantName: snakeCase(options.subTypePropertyName).toUpperCase(),
type: undefined
};
// console.log(data);
let template = readAndCompileTemplateFile(options.templates.models);
ensureFolder(folder);
for (let namespace in namespaceGroups) {
let typeCol = namespaceGroups[namespace];
let firstType =
typeCol[0] ||
<Type>{
namespace: ''
};
let namespacePath = convertNamespaceToPath(firstType.namespace);
let typeFolder = `${folder}${namespacePath}`;
let folderParts = namespacePath.split('/');
let prevParts = folder;
folderParts.forEach(part => {
prevParts += part + '/';
ensureFolder(prevParts);
});
let nrGeneratedFiles = 0;
each(typeCol, type => {
let outputFileName = join(typeFolder, type.fileName);
data.type = type;
data.hasComplexType = type.properties.some(property => property.isComplexType);
let result = template(data);
let isChanged = writeFileIfContentsIsChanged(outputFileName, result);
if (isChanged) {
nrGeneratedFiles++;
}
//fs.writeFileSync(outputFileName, result, { flag: 'w', encoding: utils.ENCODING });
});
log(`generated ${nrGeneratedFiles} type${nrGeneratedFiles === 1 ? '' : 's'} in ${typeFolder}`);
removeFilesOfNonExistingTypes(typeCol, typeFolder, options, MODEL_FILE_SUFFIX);
}
let namespacePaths = Object.keys(namespaceGroups).map(namespace => {
return join(folder, convertNamespaceToPath(namespace));
});
cleanFoldersForObsoleteFiles(folder, namespacePaths);
}
function cleanFoldersForObsoleteFiles(folder: string, namespacePaths: string[]) {
getDirectories(folder).forEach(name => {
let folderPath = join(folder, name);
// TODO bij swagger-zib-v2 wordt de webapi/ZIB folder weggegooid !
let namespacePath = find(namespacePaths, path => {
return path.startsWith(folderPath);
});
if (!namespacePath) {
removeFolder(folderPath);
log(`removed obsolete folder ${name} in ${folder}`);
} else {
cleanFoldersForObsoleteFiles(folderPath, namespacePaths);
}
});
}
function generateSubTypeFactory(namespaceGroups: NamespaceGroups, folder: string, options: GeneratorOptions) {
let data = {
subTypes: undefined,
subTypePropertyName: options.subTypePropertyName,
generateFormGroups: options.generateFormGroups
};
let template = readAndCompileTemplateFile(options.templates.subTypeFactory);
for (let key in namespaceGroups) {
data.subTypes = namespaceGroups[key].filter(type => {
return type.hasSubTypeProperty;
});
let namespacePath = namespaceGroups[key][0] ? namespaceGroups[key][0].path : '';
let outputFileName = join(folder, options.subTypeFactoryFileName);
let result = template(data);
let isChanged = writeFileIfContentsIsChanged(outputFileName, result);
if (isChanged) {
log(`generated ${outputFileName}`);
}
}
}
function generateBarrelFiles(namespaceGroups: NamespaceGroups, folder: string, options: GeneratorOptions) {
let data: { fileNames: string[] } = {
fileNames: undefined
};
let template = readAndCompileTemplateFile(options.templates.barrel);
for (let key in namespaceGroups) {
data.fileNames = namespaceGroups[key].map(type => {
return removeExtension(type.fileName);
});
if (key === ROOT_NAMESPACE) {
addRootFixedFileNames(data.fileNames, options);
}
let namespacePath = namespaceGroups[key][0] ? namespaceGroups[key][0].path : '';
let outputFileName = join(folder + namespacePath, 'index.ts');
let result = template(data);
let isChanged = writeFileIfContentsIsChanged(outputFileName, result);
if (isChanged) {
log(`generated ${outputFileName}`);
}
}
}
function addRootFixedFileNames(fileNames: string[], options: GeneratorOptions) {
let enumOutputFileName = normalize(options.enumTSFile.split('/').pop());
fileNames.splice(0, 0, removeExtension(enumOutputFileName));
if (options.generateClasses) {
let validatorsOutputFileName = normalize(options.validatorsFileName);
fileNames.splice(0, 0, removeExtension(validatorsOutputFileName));
}
}
function removeFilesOfNonExistingTypes(typeCollection, folder: string, options: GeneratorOptions, suffix: string) {
// remove files of types which are no longer defined in typeCollection
let counter = 0;
let files = readdirSync(folder);
each(files, file => {
if (
endsWith(file, suffix) &&
!find(typeCollection, type => {
return type.fileName == file;
})
) {
counter++;
unlinkSync(join(folder, file));
log(`removed ${file} in ${folder}`);
}
});
if (counter > 0) {
log(`removed ${counter} types in ${folder}`);
}
} | the_stack |
import { ProgramCounterInfo } from "@state/AppState";
import { KeyMapping } from "./keyboard";
import { MemoryHelper } from "../wa-interop/memory-helpers";
import {
EXEC_ENGINE_STATE_BUFFER,
EXEC_OPTIONS_BUFFER,
} from "../wa-interop/memory-map";
import {
ExecuteCycleOptions,
MachineCoreState,
MachineCreationOptions,
MachineState,
} from "../../../core/abstractions/vm-core-types";
import { getEngineDependencies } from "./vm-engine-dependencies";
import { MachineApi } from "../wa-interop/wa-api";
import { ICpu } from "@abstractions/abstract-cpu";
import { CodeToInject } from "@abstractions/code-runner-service";
import { IVmEngineService } from "./vm-engine-service";
/**
* Represents the core abstraction of a virtual machine.
*
* Provides all operations that implements the machine execution
* loop.
*/
export abstract class VirtualMachineCoreBase<T extends ICpu = ICpu> {
private _coreState: MachineCoreState;
protected controller: IVmEngineService;
/**
* The WA machine API to use the machine core
*/
public api: MachineApi;
/**
* Gets the CPU of the virtual machine
*/
public abstract get cpu(): T;
/**
* The initial state of the machine after setup
*/
protected initialState: MachineState;
/**
* Instantiates a core with the specified options
* @param options Options to use with machine creation
*/
constructor(public readonly options: MachineCreationOptions) {
this._coreState = MachineCoreState.WaitForSetup;
}
/**
* Attaches this machine core to a controller
* @param controller Controller instance
*/
attachToController(controller: IVmEngineService): void {
this.controller = controller;
}
/**
* Gets the unique model identifier of the machine
*/
abstract get modelId(): string;
/**
* Gets a unique identifier for the particular configuration of the model
*/
abstract get configurationId(): string;
/**
* Friendly name to display
*/
abstract readonly displayName: string;
/**
* The name of the module file with the WA machine engine
*/
abstract readonly waModuleFile: string;
/**
* Optional import properties for the WebAssembly engine
*/
readonly waImportProps: Record<string, any> = {};
/**
* Override this property to apply multiple engine loops before
* Refreshing the UI.
*/
readonly engineLoops: number = 1;
/**
* Width of the screen to display
*/
get screenWidth(): number {
return this.initialState.screenWidth;
}
/**
* Height of the screen to display
*/
get screenHeight(): number {
return this.initialState.screenHeight;
}
/**
* Gets the virtual WA memory address of the beginning of the firmware
*/
getFirmwareBaseAddress(): number {
return 0;
}
/**
* The current state of the machine core
*/
get coreState(): MachineCoreState {
return this._coreState;
}
/**
* Get the type of the keyboard to display
*/
readonly keyboardType: string | null = null;
/**
* Gets the program counter information of the machine
* @param state Current machine state
*/
abstract getProgramCounterInfo(state: MachineState): ProgramCounterInfo;
/**
* Sets up the machine with the specified options
*
* Sets the core state to `Configured`
*/
async setupMachine(): Promise<void> {
// --- Prepare the firmware
let firmware: Uint8Array[] = [];
if (this.options.firmware) {
firmware = this.options.firmware;
} else {
throw new Error("No firmware specified.");
}
// --- Create the webassembly module
const waImportObject = {
imports: {
trace: (arg: number) => console.log(arg),
...this.waImportProps,
},
};
const deps = getEngineDependencies();
this.api = (
await WebAssembly.instantiate(
await deps.waModuleLoader(this.waModuleFile),
waImportObject
)
).instance.exports as unknown as MachineApi;
if (!this.api) {
throw new Error("WebAssembly module initialization failed.");
}
// --- Prepare the machine to run
this.api.setupMachine();
this.configureMachine();
this.initFirmware(firmware);
// --- Obtain the initial screen dimensions
this.initialState = this.getMachineState();
// --- Done.
this._coreState = MachineCoreState.Configured;
}
/**
* Override this method to configure the virtual machine before turning it on
*/
configureMachine(): void {}
/**
* Initializes the specified ROMs
* @param firmware Optional buffers with ROM contents
*/
initFirmware(firmware?: Uint8Array[]): void {
if (!firmware) {
return;
}
const mh = new MemoryHelper(this.api, this.getFirmwareBaseAddress());
for (let i = 0; i < firmware.length; i++) {
const rom = firmware[i];
for (let j = 0; j < rom.length; j++) {
mh.writeByte(0x4000 * i + j, rom[j]);
}
}
}
/**
* Executes the hard reset, as if the nachine has been turned
* off, and then tuned on. Clears volatile memory.
*/
turnOn(): void {
// TODO: Implement this method
}
/**
* Executes soft reset. Uses the hardware's reset signal, generally
* keeps the state of the volatile memory.
*/
reset(): void {
// TODO: Implement this method
}
/**
* Represents the state of the machine, including the CPU, memory, and machine
* devices
*/
getMachineState(): MachineState {
const s: MachineState = {} as MachineState;
// --- Get execution engine state
this.api.getExecutionEngineState();
const mh = new MemoryHelper(this.api, EXEC_ENGINE_STATE_BUFFER);
s.frameCount = mh.readUint32(0);
s.frameCompleted = mh.readBool(4);
s.lastRenderedFrameTact = mh.readUint32(5);
s.executionCompletionReason = mh.readUint32(9);
return s;
}
/**
* Gets the addressable memory contents from the machine
*/
abstract getMemoryContents(): Uint8Array;
/**
* Handles pressing or releasing a physical key on the keyboard
* @param keycode Virtual keycode
* @param isDown Is the key pressed down?
*/
handlePhysicalKey(keycode: string, isDown: boolean): void {
const keyMapping = this.getKeyMapping();
const keySet = keyMapping[keycode];
if (!keySet) {
// --- No mapping for the specified physical key
return;
}
if (typeof keySet === "string") {
// --- Single key
const resolved = this.resolveKeyCode(keySet);
if (resolved !== null) {
this.setKeyStatus(resolved, isDown);
}
} else {
for (const key of keySet) {
const resolved = this.resolveKeyCode(key);
if (resolved !== null) {
this.setKeyStatus(resolved, isDown);
}
}
}
}
/**
* Gets the key mapping used by the machine
*/
getKeyMapping(): KeyMapping {
return {};
}
/**
* Resolves a string key code to a key number
* @param code Key code to resolve
*/
resolveKeyCode(code: string): number | null {
return null;
}
/**
* Sets the status of the specified key on the keyboard
* @param key Code of the key
* @param isDown Pressed/released status of the key
*/
setKeyStatus(key: number, isDown: boolean): void {
this.api.setKeyStatus(key, isDown);
}
/**
* Sets the audio sample rate to use with sound devices
* @param rate Audio sampe rate to use
*/
setAudioSampleRate(rate: number): void {}
/**
* Gets the screen pixels data to display
*/
getScreenData(): Uint32Array {
return new Uint32Array(0);
}
/**
* Override this method to determine the length of the subsequent CPU instruction
* @returns The length of the next instruction
*/
getNextInstructionAddress(): number {
return 0;
}
/**
* Reads a byte from the memory
* @param addr Memory address
*/
abstract readMemory(addr: number): number;
/**
* Writes a byte into the memory
* @param addr Memory address
* @param value Value to write
*/
abstract writeMemory(addr: number, value: number): void;
/**
* The currently set execution options
*/
executionOptions: ExecuteCycleOptions | null;
/**
* Executes a single machine frame
* @param options Execution options
*/
executeFrame(options: ExecuteCycleOptions): void {
this.executionOptions = options;
// --- Copy execution options
const mh = new MemoryHelper(this.api, EXEC_OPTIONS_BUFFER);
mh.writeByte(0, options.emulationMode);
mh.writeByte(1, options.debugStepMode);
mh.writeBool(2, false);
mh.writeByte(3, options.terminationPartition);
mh.writeUint16(4, options.terminationAddress);
mh.writeBool(6, false);
mh.writeBool(7, false);
mh.writeUint32(8, options.stepOverBreakpoint);
this.api.setExecutionOptions();
// --- Run the cycle and retrieve state
this.api.executeMachineLoop();
}
/**
* Executes a machine specific command. Override in a machine to
* respond to those commands
* @param _command Command to execute
* @param _args: Optional command arguments
*/
async executeMachineCommand(
_command: string,
_args?: unknown
): Promise<unknown> {
return;
}
/**
* Override this method to set the clock multiplier
* @param _multiplier Clock multiplier to apply from the next frame
*/
setClockMultiplier(_multiplier: number): void {}
/**
* Indicates if the virtual machine supports code injection for the specified
* machine mode
* @param mode Optional machine mode
* @returns True, if the model supports the code injection
*/
supportsCodeInjection(mode?: string): boolean {
return false;
}
/**
* Initializes the machine with the specified code
* @param runMode Machine run mode
* @param code Intial code
*/
injectCode(
code: number[],
codeAddress = 0x8000,
startAddress = 0x8000
): void {}
/**
* Injects the specified code into the ZX Spectrum machine
* @param codeToInject Code to inject into the machine
*/
abstract injectCodeToRun(codeToInject: CodeToInject): Promise<void>;
/**
* Prepares the engine for code injection
* @param model Model to run in the virtual machine
*/
abstract prepareForInjection(model: string): Promise<number>;
/**
* Injects the specified code into the ZX Spectrum machine and runs it
* @param codeToInject Code to inject into the machine
* @param debug Start in debug mode?
*/
abstract runCode(codeToInject: CodeToInject, debug?: boolean): Promise<void>;
// ==========================================================================
// Lifecycle methods
/**
* Override this method to define actions when the virtual machine is started
* from stopped state
*/
async beforeFirstStart(): Promise<void> {}
/**
* Override this method to define an action before the virtual machine has
* started.
* @param _debugging Is started in debug mode?
*/
async beforeStarted(_debugging: boolean): Promise<void> {}
/**
* Override this method to define an action to run before the injected
* code is started
* @param _codeToInject The injected code
* @param _debug Start in debug mode?
*/
async beforeRunInjected(
_codeToInject: CodeToInject,
_debug?: boolean
): Promise<void> {}
/**
* Override this method to define an action after the virtual machine has
* started.
* @param _debugging Is started in debug mode?
* @param _isFirstStart Is the machine started from stopped state?
*/
async afterStarted(_debugging: boolean): Promise<void> {}
/**
* Override this action to define an action when the virtual machine
* has paused.
* @param _isFirstPause Is the machine paused the first time?
*/
async onPaused(_isFirstPause: boolean): Promise<void> {}
/**
* Override this action to define an action when the virtual machine
* has stopped.
*/
async onStopped(): Promise<void> {}
/**
* Override this action to define an action before the step-into
* operation is executed.
*/
async beforeStepInto(): Promise<void> {}
/**
* Override this action to define an action before the step-over
* operation is executed.
*/
async beforeStepOver(): Promise<void> {}
/**
* Override this action to define an action before the step-out
* operation is executed.
*/
async beforeStepOut(): Promise<void> {}
/**
* Override this method in derived classes to define an action when
* the machine's execution cycle has completed.
* @param _resultState Machine state on loop completion
*/
async onEngineCycleCompletion(_resultState: MachineState): Promise<void> {}
/**
* Override this method in derived classes to define an action when
* the UI loop waits for loop state evaluations (whether to continue the
* cycle of not).
* @param _resultState Machine state on loop completion
*/
async beforeEvalLoopCompletion(_resultState: MachineState): Promise<void> {}
/**
* Override this method to define an action when the execution cycle has
* completed after the loop evaluation.
* @param _resultState Machine state on cycle completion
*/
async onExecutionCycleCompleted(_resultState: MachineState): Promise<void> {}
/**
* Override this method to define an action when an entire frame has been
* completed within the machine execution cycle.
* @param _resultState Machine state on frame completion
* @param _toWait Number of milliseconds to wait for the next frame
*/
async onFrameCompleted(
_resultState: MachineState,
_toWait: number
): Promise<void> {}
} | the_stack |
import produce, { Draft } from 'immer'
import { OfflineSignJSON } from 'services/remote'
import initStates from 'states/init'
import { ConnectionStatus, ErrorCode } from 'utils'
export enum NeuronWalletActions {
InitAppState = 'initAppState',
// wallets
UpdateCurrentWallet = 'updateCurrentWallet',
UpdateWalletList = 'updateWalletList',
UpdateAddressListAndBalance = 'updateAddressListAndBalance',
UpdateAddressDescription = 'updateAddressDescription',
// transactions
UpdateTransactionList = 'updateTransactionList',
UpdateTransactionDescription = 'updateTransactionDescription',
// networks
UpdateNetworkList = 'updateNetworkList',
UpdateCurrentNetworkID = 'updateCurrentNetworkID',
// Connection
UpdateConnectionStatus = 'updateConnectionStatus',
UpdateSyncState = 'updateSyncState',
// dao
UpdateNervosDaoData = 'updateNervosDaoData',
// updater
UpdateAppUpdaterStatus = 'updateAppUpdaterStatus',
}
export enum AppActions {
AddSendOutput = 'addSendOutput',
RemoveSendOutput = 'removeSendOutput',
UpdateSendOutput = 'updateSendOutput',
UpdateSendPrice = 'updateSendPrice',
UpdateSendDescription = 'updateSendDescription',
UpdateGeneratedTx = 'updateGeneratedTx',
ClearSendState = 'clearSendState',
UpdateMessage = 'updateMessage',
SetGlobalDialog = 'setGlobalDialog',
AddNotification = 'addNotification',
DismissNotification = 'dismissNotification',
ClearNotificationsOfCode = 'clearNotificationsOfCode',
ClearNotifications = 'clearNotifications',
CleanTransaction = 'cleanTransaction',
CleanTransactions = 'cleanTransactions',
RequestPassword = 'requestPassword',
DismissPasswordRequest = 'dismissPasswordRequest',
UpdateChainInfo = 'updateChainInfo',
UpdateLoadings = 'updateLoadings',
UpdateAlertDialog = 'updateAlertDialog',
PopIn = 'popIn',
PopOut = 'popOut',
ToggleTopAlertVisibility = 'toggleTopAlertVisibility',
ToggleAllNotificationVisibility = 'toggleAllNotificationVisibility',
ToggleIsAllowedToFetchList = 'toggleIsAllowedToFetchList',
Ignore = 'ignore',
// Experimentals
UpdateExperimentalParams = 'updateExperimentalParams',
// offline sign
UpdateLoadedTransaction = 'updateLoadedTransaction',
}
export type StateAction =
| { type: AppActions.AddSendOutput }
| { type: AppActions.RemoveSendOutput; payload: number }
| { type: AppActions.UpdateSendOutput; payload: { idx: number; item: Partial<State.Output> } }
| { type: AppActions.UpdateSendPrice; payload: string }
| { type: AppActions.UpdateSendDescription; payload: string }
| { type: AppActions.UpdateGeneratedTx; payload: any }
| { type: AppActions.ClearSendState }
| { type: AppActions.UpdateMessage; payload: any }
| { type: AppActions.SetGlobalDialog; payload: State.GlobalDialogType }
| { type: AppActions.AddNotification; payload: State.Message }
| { type: AppActions.DismissNotification; payload: number } // payload: timestamp
| { type: AppActions.ClearNotificationsOfCode; payload: ErrorCode } // payload: code
| { type: AppActions.ClearNotifications }
| { type: AppActions.CleanTransaction }
| { type: AppActions.CleanTransactions }
| { type: AppActions.RequestPassword; payload: Omit<State.PasswordRequest, 'password'> }
| { type: AppActions.DismissPasswordRequest }
| { type: AppActions.UpdateChainInfo; payload: Partial<State.App> }
| { type: AppActions.UpdateLoadings; payload: any }
| { type: AppActions.UpdateAlertDialog; payload: State.AlertDialog }
| { type: AppActions.PopIn; payload: State.Popup }
| { type: AppActions.PopOut }
| { type: AppActions.ToggleTopAlertVisibility; payload?: boolean }
| { type: AppActions.ToggleAllNotificationVisibility; payload?: boolean }
| { type: AppActions.ToggleIsAllowedToFetchList; payload?: boolean }
| { type: AppActions.Ignore; payload?: any }
| { type: AppActions.UpdateExperimentalParams; payload: { tx: any; assetAccount?: any } | null }
| { type: AppActions.UpdateLoadedTransaction; payload: { filePath?: string; json: OfflineSignJSON } }
| { type: NeuronWalletActions.InitAppState; payload: any }
| { type: NeuronWalletActions.UpdateCurrentWallet; payload: Partial<State.Wallet> }
| { type: NeuronWalletActions.UpdateWalletList; payload: State.WalletIdentity[] }
| { type: NeuronWalletActions.UpdateAddressListAndBalance; payload: Partial<State.Wallet> }
| { type: NeuronWalletActions.UpdateAddressDescription; payload: { address: string; description: string } }
| { type: NeuronWalletActions.UpdateTransactionList; payload: any }
| { type: NeuronWalletActions.UpdateTransactionDescription; payload: { hash: string; description: string } }
| { type: NeuronWalletActions.UpdateNetworkList; payload: State.Network[] }
| { type: NeuronWalletActions.UpdateCurrentNetworkID; payload: string }
| { type: NeuronWalletActions.UpdateConnectionStatus; payload: State.ConnectionStatus }
| { type: NeuronWalletActions.UpdateSyncState; payload: State.SyncState }
| { type: NeuronWalletActions.UpdateNervosDaoData; payload: State.NervosDAO }
| { type: NeuronWalletActions.UpdateAppUpdaterStatus; payload: State.AppUpdater }
export type StateDispatch = React.Dispatch<StateAction> // TODO: add type of payload
/* eslint-disable no-param-reassign */
export const reducer = produce((state: Draft<State.AppWithNeuronWallet>, action: StateAction) => {
switch (action.type) {
// Actions of Neuron Wallet
case NeuronWalletActions.InitAppState: {
const {
wallets,
wallet: incomingWallet,
networks,
currentNetworkID: networkID,
transactions,
syncedBlockNumber,
connectionStatus,
} = action.payload
state.wallet = incomingWallet || state.wallet
Object.assign(state.chain, {
networkID,
transactions,
connectionStatus: connectionStatus?.connected ? ConnectionStatus.Online : ConnectionStatus.Connecting,
tipBlockNumber: syncedBlockNumber,
})
Object.assign(state.settings, { networks, wallets })
state.updater = {
checking: false,
downloadProgress: -1,
version: '',
releaseNotes: '',
}
break
}
case NeuronWalletActions.UpdateAddressListAndBalance:
case NeuronWalletActions.UpdateCurrentWallet: {
Object.assign(state.wallet, action.payload)
break
}
case NeuronWalletActions.UpdateWalletList: {
state.settings.wallets = action.payload
break
}
case NeuronWalletActions.UpdateAddressDescription: {
state.wallet.addresses.forEach(addr => {
if (addr.address === action.payload.address) {
addr.description = action.payload.description
}
})
break
}
case NeuronWalletActions.UpdateTransactionList: {
state.chain.transactions = action.payload
break
}
case NeuronWalletActions.UpdateTransactionDescription: {
state.chain.transactions.items.forEach(tx => {
if (tx.hash === action.payload.hash) {
tx.description = action.payload.description
}
})
break
}
case NeuronWalletActions.UpdateNetworkList: {
state.settings.networks = action.payload
break
}
case NeuronWalletActions.UpdateCurrentNetworkID: {
Object.assign(state.app, {
tipBlockNumber: '0',
chain: '',
difficulty: BigInt(0),
epoch: '',
})
state.chain.networkID = action.payload
break
}
case NeuronWalletActions.UpdateConnectionStatus: {
state.chain.connectionStatus = action.payload
break
}
case NeuronWalletActions.UpdateSyncState: {
state.chain.syncState = action.payload
break
}
case NeuronWalletActions.UpdateAppUpdaterStatus: {
state.updater = action.payload
break
}
case NeuronWalletActions.UpdateNervosDaoData: {
state.nervosDAO = action.payload as Draft<typeof initStates.nervosDAO>
break
}
// Actions of App
case AppActions.UpdateChainInfo: {
Object.assign(state.app, action.payload)
break
}
case AppActions.AddSendOutput: {
state.app.send.outputs.push(initStates.app.send.outputs[0])
state.app.messages.send = null
break
}
case AppActions.RemoveSendOutput: {
state.app.send.outputs.splice(action.payload, 1)
state.app.messages.send = null
break
}
case AppActions.UpdateSendOutput: {
/**
* payload:{ idx, item: { address, capacity, date } }
*/
if ('address' in action.payload.item) {
Object.assign(state.app.send.outputs[action.payload.idx], { date: undefined })
}
Object.assign(state.app.send.outputs[action.payload.idx], action.payload.item)
state.app.messages.send = null
break
}
case AppActions.UpdateSendPrice: {
/**
* payload: new price
*/
state.app.send.price = action.payload
break
}
case AppActions.UpdateSendDescription: {
/**
* payload: new description
*/
state.app.send.description = action.payload
break
}
case AppActions.UpdateGeneratedTx: {
state.app.send.generatedTx = action.payload || null
break
}
case AppActions.ClearSendState: {
state.app.send = initStates.app.send as Draft<typeof initStates.app.send>
break
}
case AppActions.RequestPassword: {
state.app.passwordRequest = action.payload
break
}
case AppActions.DismissPasswordRequest: {
state.app.passwordRequest = initStates.app.passwordRequest
break
}
case AppActions.UpdateMessage: {
/**
* payload: {type,content, timestamp}
*/
Object.assign(state.app.messages, action.payload)
break
}
case AppActions.SetGlobalDialog: {
state.app.globalDialog = action.payload
break
}
case AppActions.AddNotification: {
/**
* payload: { type, content }
*/
// NOTICE: for simplicty, only one notification will be displayed
state.app.notifications.push(action.payload)
state.app.showTopAlert = true
break
}
case AppActions.DismissNotification: {
/**
* payload: timstamp
*/
state.app.showTopAlert =
state.app.notifications.findIndex(message => message.timestamp === action.payload) ===
state.app.notifications.length - 1
? false
: state.app.showTopAlert
state.app.notifications = state.app.notifications.filter(({ timestamp }) => timestamp !== action.payload)
state.app.showAllNotifications = state.app.showAllNotifications
? state.app.notifications.length > 0
: state.app.showAllNotifications
break
}
case AppActions.ClearNotificationsOfCode: {
const notifications = state.app.notifications.filter(({ code }) => code !== action.payload)
const showTopAlert =
state.app.showTopAlert &&
notifications.length > 0 &&
!(
state.app.notifications.length > 0 &&
state.app.notifications[state.app.notifications.length - 1].code === action.payload
)
state.app.notifications = notifications
state.app.showTopAlert = showTopAlert
break
}
case AppActions.ClearNotifications: {
state.app.notifications = []
break
}
case AppActions.CleanTransactions: {
state.chain.transactions = initStates.chain.transactions as Draft<typeof initStates.chain.transactions>
break
}
case AppActions.UpdateLoadings: {
Object.assign(state.app.loadings, action.payload)
break
}
case AppActions.UpdateAlertDialog: {
state.app.alertDialog = action.payload
break
}
case AppActions.PopIn: {
state.app.popups.push(action.payload)
break
}
case AppActions.PopOut: {
state.app.popups.shift()
break
}
case AppActions.ToggleTopAlertVisibility: {
state.app.showTopAlert = action.payload === undefined ? !state.app.showTopAlert : action.payload
if (!state.app.showTopAlert) {
state.app.notifications.pop()
}
break
}
case AppActions.ToggleAllNotificationVisibility: {
state.app.showAllNotifications = action.payload === undefined ? !state.app.showAllNotifications : action.payload
break
}
case AppActions.ToggleIsAllowedToFetchList: {
state.app.isAllowedToFetchList = action.payload === undefined ? !state.app.isAllowedToFetchList : action.payload
break
}
case AppActions.UpdateExperimentalParams: {
state.experimental = action.payload
break
}
case AppActions.UpdateLoadedTransaction: {
state.app.loadedTransaction = {
...state.app.loadedTransaction,
...action.payload,
}
break
}
default: {
break
}
}
}) | the_stack |
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodePropertyOptions,
INodeType,
INodeTypeDescription,
NodeOperationError,
} from 'n8n-workflow';
import {
keysToSnakeCase,
shopifyApiRequest,
shopifyApiRequestAllItems,
} from './GenericFunctions';
import {
orderFields,
orderOperations,
} from './OrderDescription';
import {
productFields,
productOperations,
} from './ProductDescription';
import {
IAddress,
IDiscountCode,
ILineItem,
IOrder,
} from './OrderInterface';
import {
IProduct,
} from './ProductInterface';
export class Shopify implements INodeType {
description: INodeTypeDescription = {
displayName: 'Shopify',
name: 'shopify',
icon: 'file:shopify.svg',
group: ['output'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Consume Shopify API',
defaults: {
name: 'Shopify',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'shopifyApi',
required: true,
},
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
options: [
{
name: 'Order',
value: 'order',
},
{
name: 'Product',
value: 'product',
},
],
default: 'order',
description: 'Resource to consume.',
},
// ORDER
...orderOperations,
...orderFields,
// PRODUCTS
...productOperations,
...productFields,
],
};
methods = {
loadOptions: {
// Get all the available products to display them to user so that he can
// select them easily
async getProducts(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const products = await shopifyApiRequestAllItems.call(this, 'products', 'GET', '/products.json', {}, { fields: 'id,title' });
for (const product of products) {
const productName = product.title;
const productId = product.id;
returnData.push({
name: productName,
value: productId,
});
}
return returnData;
},
// Get all the available locations to display them to user so that he can
// select them easily
async getLocations(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const locations = await shopifyApiRequestAllItems.call(this, 'locations', 'GET', '/locations.json', {}, { fields: 'id,name' });
for (const location of locations) {
const locationName = location.name;
const locationId = location.id;
returnData.push({
name: locationName,
value: locationId,
});
}
return returnData;
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
const length = items.length as unknown as number;
let responseData;
const qs: IDataObject = {};
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
for (let i = 0; i < length; i++) {
try {
if (resource === 'order') {
//https://shopify.dev/docs/admin-api/rest/reference/orders/order#create-2020-04
if (operation === 'create') {
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const discount = additionalFields.discountCodesUi as IDataObject;
const billing = additionalFields.billingAddressUi as IDataObject;
const shipping = additionalFields.shippingAddressUi as IDataObject;
const lineItem = (this.getNodeParameter('limeItemsUi', i) as IDataObject).lineItemValues as IDataObject[];
if (lineItem === undefined) {
throw new NodeOperationError(this.getNode(), 'At least one line item has to be added');
}
const body: IOrder = {
test: true,
line_items: keysToSnakeCase(lineItem) as ILineItem[],
};
if (additionalFields.fulfillmentStatus) {
body.fulfillment_status = additionalFields.fulfillmentStatus as string;
}
if (additionalFields.inventoryBehaviour) {
body.inventory_behaviour = additionalFields.inventoryBehaviour as string;
}
if (additionalFields.locationId) {
body.location_id = additionalFields.locationId as number;
}
if (additionalFields.note) {
body.note = additionalFields.note as string;
}
if (additionalFields.sendFulfillmentReceipt) {
body.send_fulfillment_receipt = additionalFields.sendFulfillmentReceipt as boolean;
}
if (additionalFields.sendReceipt) {
body.send_receipt = additionalFields.sendReceipt as boolean;
}
if (additionalFields.sendReceipt) {
body.send_receipt = additionalFields.sendReceipt as boolean;
}
if (additionalFields.sourceName) {
body.source_name = additionalFields.sourceName as string;
}
if (additionalFields.tags) {
body.tags = additionalFields.tags as string;
}
if (additionalFields.test) {
body.test = additionalFields.test as boolean;
}
if (additionalFields.email) {
body.email = additionalFields.email as string;
}
if (discount) {
body.discount_codes = discount.discountCodesValues as IDiscountCode[];
}
if (billing) {
body.billing_address = keysToSnakeCase(billing.billingAddressValues as IDataObject)[0] as IAddress;
}
if (shipping) {
body.shipping_address = keysToSnakeCase(shipping.shippingAddressValues as IDataObject)[0] as IAddress;
}
responseData = await shopifyApiRequest.call(this, 'POST', '/orders.json', { order: body });
responseData = responseData.order;
}
//https://shopify.dev/docs/admin-api/rest/reference/orders/order#destroy-2020-04
if (operation === 'delete') {
const orderId = this.getNodeParameter('orderId', i) as string;
responseData = await shopifyApiRequest.call(this, 'DELETE', `/orders/${orderId}.json`);
responseData = { success: true };
}
//https://shopify.dev/docs/admin-api/rest/reference/orders/order#show-2020-04
if (operation === 'get') {
const orderId = this.getNodeParameter('orderId', i) as string;
const options = this.getNodeParameter('options', i) as IDataObject;
if (options.fields) {
qs.fields = options.fields as string;
}
responseData = await shopifyApiRequest.call(this, 'GET', `/orders/${orderId}.json`, {}, qs);
responseData = responseData.order;
}
//https://shopify.dev/docs/admin-api/rest/reference/orders/order#index-2020-04
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const options = this.getNodeParameter('options', i) as IDataObject;
if (options.fields) {
qs.fields = options.fields as string;
}
if (options.attributionAppId) {
qs.attribution_app_id = options.attributionAppId as string;
}
if (options.createdAtMin) {
qs.created_at_min = options.createdAtMin as string;
}
if (options.createdAtMax) {
qs.created_at_max = options.createdAtMax as string;
}
if (options.updatedAtMax) {
qs.updated_at_max = options.updatedAtMax as string;
}
if (options.updatedAtMin) {
qs.updated_at_min = options.updatedAtMin as string;
}
if (options.processedAtMin) {
qs.processed_at_min = options.processedAtMin as string;
}
if (options.processedAtMax) {
qs.processed_at_max = options.processedAtMax as string;
}
if (options.sinceId) {
qs.since_id = options.sinceId as string;
}
if (options.ids) {
qs.ids = options.ids as string;
}
if (options.status) {
qs.status = options.status as string;
}
if (options.financialStatus) {
qs.financial_status = options.financialStatus as string;
}
if (options.fulfillmentStatus) {
qs.fulfillment_status = options.fulfillmentStatus as string;
}
if (returnAll === true) {
responseData = await shopifyApiRequestAllItems.call(this, 'orders', 'GET', '/orders.json', {}, qs);
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
responseData = await shopifyApiRequest.call(this, 'GET', '/orders.json', {}, qs);
responseData = responseData.orders;
}
}
//https://shopify.dev/docs/admin-api/rest/reference/orders/order#update-2019-10
if (operation === 'update') {
const orderId = this.getNodeParameter('orderId', i) as string;
const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;
const shipping = updateFields.shippingAddressUi as IDataObject;
const body: IOrder = {};
if (updateFields.locationId) {
body.location_id = updateFields.locationId as number;
}
if (updateFields.note) {
body.note = updateFields.note as string;
}
if (updateFields.sourceName) {
body.source_name = updateFields.sourceName as string;
}
if (updateFields.tags) {
body.tags = updateFields.tags as string;
}
if (updateFields.email) {
body.email = updateFields.email as string;
}
if (shipping) {
body.shipping_address = keysToSnakeCase(shipping.shippingAddressValues as IDataObject)[0] as IAddress;
}
responseData = await shopifyApiRequest.call(this, 'PUT', `/orders/${orderId}.json`, { order: body });
responseData = responseData.order;
}
} else if (resource === 'product') {
const productId = this.getNodeParameter('productId', i, '') as string;
let body: IProduct = {};
//https://shopify.dev/docs/admin-api/rest/reference/products/product#create-2020-04
if (operation === 'create') {
const title = this.getNodeParameter('title', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i, {}) as IDataObject;
if (additionalFields.productOptions) {
const metadata = (additionalFields.productOptions as IDataObject).option as IDataObject[];
additionalFields.options = {};
for (const data of metadata) {
//@ts-ignore
additionalFields.options[data.name as string] = data.value;
}
delete additionalFields.productOptions;
}
body = additionalFields;
body.title = title;
responseData = await shopifyApiRequest.call(this, 'POST', '/products.json', { product: body });
responseData = responseData.product;
}
if (operation === 'delete') {
//https://shopify.dev/docs/admin-api/rest/reference/products/product#destroy-2020-04
responseData = await shopifyApiRequest.call(this, 'DELETE', `/products/${productId}.json`);
responseData = { success: true };
}
if (operation === 'get') {
//https://shopify.dev/docs/admin-api/rest/reference/products/product#show-2020-04
const additionalFields = this.getNodeParameter('additionalFields', i, {}) as IDataObject;
Object.assign(qs, additionalFields);
responseData = await shopifyApiRequest.call(this, 'GET', `/products/${productId}.json`, {}, qs);
responseData = responseData.product;
}
if (operation === 'getAll') {
//https://shopify.dev/docs/admin-api/rest/reference/products/product#index-2020-04
const additionalFields = this.getNodeParameter('additionalFields', i, {}) as IDataObject;
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
Object.assign(qs, additionalFields);
if (returnAll === true) {
responseData = await shopifyApiRequestAllItems.call(this, 'products', 'GET', '/products.json', {}, qs);
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
responseData = await shopifyApiRequest.call(this, 'GET', '/products.json', {}, qs);
responseData = responseData.products;
}
}
if (operation === 'update') {
//https://shopify.dev/docs/admin-api/rest/reference/products/product?api[version]=2020-07#update-2020-07
const updateFields = this.getNodeParameter('updateFields', i, {}) as IDataObject;
if (updateFields.productOptions) {
const metadata = (updateFields.productOptions as IDataObject).option as IDataObject[];
updateFields.options = {};
for (const data of metadata) {
//@ts-ignore
updateFields.options[data.name as string] = data.value;
}
delete updateFields.productOptions;
}
body = updateFields;
responseData = await shopifyApiRequest.call(this, 'PUT', `/products/${productId}.json`, { product: body });
responseData = responseData.product;
}
}
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData as IDataObject[]);
} else {
returnData.push(responseData);
}
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
} | the_stack |
import { ChartConfig } from 'app/types/ChartConfig';
import { FONT_FAMILY } from 'styles/StyleConstants';
const config: ChartConfig = {
datas: [
{
label: 'mixed',
key: 'mixed',
required: true,
type: 'mixed',
},
{
label: 'filter',
key: 'filter',
type: 'filter',
disableAggregate: true,
},
],
styles: [
{
label: 'header.title',
key: 'header',
comType: 'group',
rows: [
{
label: 'header.open',
key: 'modal',
comType: 'group',
options: { type: 'modal', modalSize: 'middle' },
rows: [
{
label: 'header.styleAndGroup',
key: 'tableHeaders',
comType: 'tableHeader',
},
],
},
],
},
{
label: 'column.conditionalStyle',
key: 'column',
comType: 'group',
rows: [
{
label: 'column.open',
key: 'modal',
comType: 'group',
options: { type: 'modal', modalSize: 'middle' },
rows: [
{
label: 'column.list',
key: 'list',
comType: 'listTemplate',
rows: [],
options: {
getItems: cols => {
const columns = (cols || [])
.filter(col =>
['aggregate', 'group', 'mixed'].includes(col.type),
)
.reduce((acc, cur) => acc.concat(cur.rows || []), [])
.map(c => ({
key: c.uid,
value: c.uid,
type: c.type,
label:
c.label || c.aggregate
? `${c.aggregate}(${c.colName})`
: c.colName,
}));
return columns;
},
},
template: {
label: 'column.listItem',
key: 'listItem',
comType: 'group',
rows: [
{
label: 'column.columnStyle',
key: 'columnStyle',
comType: 'group',
options: { expand: true },
rows: [
{
label: 'column.useColumnWidth',
key: 'useColumnWidth',
default: false,
comType: 'checkbox',
},
{
label: 'column.columnWidth',
key: 'columnWidth',
default: 100,
options: {
min: 0,
},
watcher: {
deps: ['useColumnWidth'],
action: props => {
return {
disabled: !props.useColumnWidth,
};
},
},
comType: 'inputNumber',
},
{
label: 'style.align',
key: 'align',
default: 'default',
comType: 'fontAlignment',
options: {
translateItemLabel: true,
items: [
{
label: `@global@.style.alignDefault`,
value: 'default',
},
{
label: `viz.common.enum.fontAlignment.left`,
value: 'left',
},
{
label: `viz.common.enum.fontAlignment.center`,
value: 'center',
},
{
label: `viz.common.enum.fontAlignment.right`,
value: 'right',
},
],
},
},
],
},
{
label: 'column.conditionalStyle',
key: 'conditionalStyle',
comType: 'group',
options: { expand: true },
rows: [
{
label: 'column.conditionalStylePanel',
key: 'conditionalStylePanel',
comType: 'conditionalStylePanel',
},
],
},
],
},
},
],
},
],
},
{
label: 'style.title',
key: 'style',
comType: 'group',
rows: [
{
label: 'style.enableFixedHeader',
key: 'enableFixedHeader',
default: true,
comType: 'checkbox',
},
{
label: 'style.enableBorder',
key: 'enableBorder',
default: true,
comType: 'checkbox',
},
{
label: 'style.enableRowNumber',
key: 'enableRowNumber',
default: false,
comType: 'checkbox',
},
{
label: 'style.leftFixedColumns',
key: 'leftFixedColumns',
default: 0,
options: {
min: 0,
},
comType: 'inputNumber',
},
{
label: 'style.rightFixedColumns',
key: 'rightFixedColumns',
default: 0,
options: {
min: 0,
},
comType: 'inputNumber',
},
{
label: 'style.autoMergeFields',
key: 'autoMergeFields',
comType: 'select',
options: {
mode: 'multiple',
getItems: cols => {
const columns = (cols || [])
.filter(col => ['mixed'].includes(col.type))
.reduce((acc, cur) => acc.concat(cur.rows || []), [])
.filter(c => c.type === 'STRING')
.map(c => ({
key: c.uid,
value: c.uid,
label:
c.label || c.aggregate
? `${c.aggregate}(${c.colName})`
: c.colName,
}));
return columns;
},
},
},
{
label: 'style.tableSize',
key: 'tableSize',
default: 'small',
comType: 'select',
options: {
translateItemLabel: true,
items: [
{ label: '@global@.tableSize.default', value: 'default' },
{ label: '@global@.tableSize.middle', value: 'middle' },
{ label: '@global@.tableSize.small', value: 'small' },
],
},
},
],
},
{
label: 'style.tableHeaderStyle',
key: 'tableHeaderStyle',
comType: 'group',
rows: [
{
label: 'common.backgroundColor',
key: 'bgColor',
default: '#f8f9fa',
comType: 'fontColor',
},
{
label: 'style.font',
key: 'font',
comType: 'font',
default: {
fontFamily: FONT_FAMILY,
fontSize: 12,
fontWeight: 'bold',
fontStyle: 'normal',
color: '#495057',
},
},
{
label: 'style.align',
key: 'align',
default: 'left',
comType: 'fontAlignment',
},
],
},
{
label: 'style.tableBodyStyle',
key: 'tableBodyStyle',
comType: 'group',
rows: [
{
label: 'style.oddFontColor',
key: 'oddFontColor',
default: '#000',
comType: 'fontColor',
},
{
label: 'style.oddBgColor',
key: 'oddBgColor',
default: 'rgba(0,0,0,0)',
comType: 'fontColor',
},
{
label: 'style.evenFontColor',
key: 'evenFontColor',
default: '#000',
comType: 'fontColor',
},
{
label: 'style.evenBgColor',
key: 'evenBgColor',
default: 'rgba(0,0,0,0)',
comType: 'fontColor',
},
{
label: 'style.fontSize',
key: 'fontSize',
comType: 'fontSize',
default: 12,
},
{
label: 'style.fontFamily',
key: 'fontFamily',
comType: 'fontFamily',
default: FONT_FAMILY,
},
{
label: 'style.fontWeight',
key: 'fontWeight',
comType: 'fontWeight',
default: 'normal',
},
{
label: 'style.fontStyle',
key: 'fontStyle',
comType: 'fontStyle',
default: 'normal',
},
{
label: 'style.align',
key: 'align',
default: 'default',
comType: 'fontAlignment',
options: {
translateItemLabel: true,
items: [
{
label: `@global@.style.alignDefault`,
value: 'default',
},
{
label: `viz.common.enum.fontAlignment.left`,
value: 'left',
},
{
label: `viz.common.enum.fontAlignment.center`,
value: 'center',
},
{
label: `viz.common.enum.fontAlignment.right`,
value: 'right',
},
],
},
},
],
},
],
settings: [
{
label: 'paging.title',
key: 'paging',
comType: 'group',
rows: [
{
label: 'paging.enablePaging',
key: 'enablePaging',
default: true,
comType: 'checkbox',
options: {
needRefresh: true,
},
},
{
label: 'paging.pageSize',
key: 'pageSize',
default: 100,
comType: 'inputNumber',
options: {
needRefresh: true,
step: 1,
min: 0,
},
watcher: {
deps: ['enablePaging'],
action: props => {
return {
disabled: !props.enablePaging,
};
},
},
},
],
},
{
label: 'summary.title',
key: 'summary',
comType: 'group',
rows: [
{
label: 'summary.aggregateFields',
key: 'aggregateFields',
comType: 'select',
options: {
mode: 'multiple',
getItems: cols => {
const columns = (cols || [])
.filter(col => ['mixed'].includes(col.type))
.reduce((acc, cur) => acc.concat(cur.rows || []), [])
.filter(c => c.type === 'NUMERIC')
.map(c => ({
key: c.uid,
value: c.uid,
label:
c.label || c.aggregate
? `${c.aggregate}(${c.colName})`
: c.colName,
}));
return columns;
},
},
},
{
label: 'common.backgroundColor',
key: 'summaryBcColor',
default: 'rgba(0, 0, 0, 0)',
comType: 'fontColor',
},
{
label: 'viz.palette.style.font',
key: 'summaryFont',
comType: 'font',
default: {
fontFamily: FONT_FAMILY,
fontSize: '14',
fontWeight: 'normal',
fontStyle: 'normal',
color: 'black',
},
},
],
},
],
i18ns: [
{
lang: 'zh-CN',
translation: {
common: { backgroundColor: '背景颜色' },
header: {
title: '表头分组',
open: '打开',
styleAndGroup: '表头分组',
},
column: {
open: '打开样式设置',
list: '字段列表',
sortAndFilter: '排序与过滤',
enableSort: '开启列排序',
basicStyle: '基础样式',
useColumnWidth: '启用固定列宽',
columnWidth: '列宽',
columnStyle: '列样式',
columnStylePanel: '列样式配置器',
conditionalStyle: '条件样式',
conditionalStylePanel: '条件样式配置器',
align: '对齐方式',
enableFixedCol: '开启固定列宽',
fixedColWidth: '固定列宽度设置',
font: '字体与样式',
},
style: {
title: '表格样式',
enableFixedHeader: '固定表头',
enableBorder: '显示边框',
enableRowNumber: '启用行号',
leftFixedColumns: '左侧固定列',
rightFixedColumns: '右侧固定列',
autoMergeFields: '自动合并列内容',
tableSize: '表格大小',
tableHeaderStyle: '表头样式',
tableBodyStyle: '表体样式',
bgColor: '背景颜色',
font: '字体',
align: '对齐方式',
alignDefault: '默认',
fontWeight: '字体粗细',
fontFamily: '字体',
oddBgColor: '奇行背景色',
oddFontColor: '奇行字体色',
evenBgColor: '偶行背景色',
evenFontColor: '偶行字体色',
fontSize: '字体大小',
fontStyle: '字体样式',
},
tableSize: {
default: '默认',
middle: '中',
small: '小',
},
summary: {
title: '数据汇总',
aggregateFields: '汇总列',
},
paging: {
title: '常规',
enablePaging: '启用分页',
pageSize: '每页行数',
},
},
},
{
lang: 'en-US',
translation: {
common: {
backgroundColor: 'Background Color',
},
header: {
title: 'Table Header Group',
open: 'Open',
styleAndGroup: 'Header Group',
},
column: {
open: 'Open Style Setting',
list: 'Field List',
sortAndFilter: 'Sort and Filter',
enableSort: 'Enable Sort',
basicStyle: 'Baisc Style',
useColumnWidth: 'Use Column Width',
columnWidth: 'Column Width',
columnStyle: 'Column Style',
columnStylePanel: 'Column Style Panel',
conditionalStyle: 'Conditional Style',
conditionalStylePanel: 'Conditional Style Panel',
align: 'Align',
enableFixedCol: 'Enable Fixed Column',
fixedColWidth: 'Fixed Column Width',
font: 'Font and Style',
},
style: {
title: 'Table Style',
enableFixedHeader: 'Enable Fixed Header',
enableBorder: 'Show Border',
enableRowNumber: 'Enable Row Number',
leftFixedColumns: 'Left Fixed Columns',
rightFixedColumns: 'Right Fixed Columns',
autoMergeFields: 'Auto Merge Column Content',
tableSize: 'Table Size',
tableHeaderStyle: 'Table Header Style',
tableBodyStyle: 'Table Body Style',
font: 'Font',
align: 'Align',
alignDefault: 'Default',
fontWeight: 'Font Weight',
fontFamily: 'Font Family',
oddBgColor: 'Odd Row Background Color',
evenBgColor: 'Even Row Background Color',
oddFontColor: 'Odd Row Font Color',
evenFontColor: 'Even Row Font Color',
fontSize: 'Font Size',
fontStyle: 'Font Style',
},
tableSize: {
default: 'Default',
middle: 'Middle',
small: 'Small',
},
summary: {
title: 'Summary',
aggregateFields: 'Summary Fields',
},
paging: {
title: 'Paging',
enablePaging: 'Enable Paging',
pageSize: 'Page Size',
},
},
},
],
};
export default config; | the_stack |
import * as d3 from "d3";
import * as C from "../src/constants";
class Snapper {
resizer: Resizer;
sourceExpand: HTMLElement;
sourceCollapse: HTMLElement;
disassemblyExpand: HTMLElement;
disassemblyCollapse: HTMLElement;
rangesExpand: HTMLElement;
rangesCollapse: HTMLElement;
constructor(resizer: Resizer) {
this.resizer = resizer;
this.sourceExpand = document.getElementById(C.SOURCE_EXPAND_ID);
this.sourceCollapse = document.getElementById(C.SOURCE_COLLAPSE_ID);
this.disassemblyExpand = document.getElementById(C.DISASSEMBLY_EXPAND_ID);
this.disassemblyCollapse = document.getElementById(C.DISASSEMBLY_COLLAPSE_ID);
this.rangesExpand = document.getElementById(C.RANGES_EXPAND_ID);
this.rangesCollapse = document.getElementById(C.RANGES_COLLAPSE_ID);
document.getElementById("show-hide-source").addEventListener("click", () => {
this.resizer.resizerLeft.classed("snapped", !this.resizer.resizerLeft.classed("snapped"));
this.setSourceExpanded(!this.sourceExpand.classList.contains("invisible"));
this.resizer.updatePanes();
});
document.getElementById("show-hide-disassembly").addEventListener("click", () => {
this.resizer.resizerRight.classed("snapped", !this.resizer.resizerRight.classed("snapped"));
this.setDisassemblyExpanded(!this.disassemblyExpand.classList.contains("invisible"));
this.resizer.updatePanes();
});
document.getElementById("show-hide-ranges").addEventListener("click", () => {
this.resizer.resizerRanges.classed("snapped", !this.resizer.resizerRanges.classed("snapped"));
this.setRangesExpanded(!this.rangesExpand.classList.contains("invisible"));
this.resizer.updatePanes();
});
}
restoreExpandedState(): void {
this.resizer.resizerLeft.classed("snapped", window.sessionStorage.getItem("expandedState-source") == "false");
this.resizer.resizerRight.classed("snapped", window.sessionStorage.getItem("expandedState-disassembly") == "false");
this.resizer.resizerRanges.classed("snapped", window.sessionStorage.getItem("expandedState-ranges") == "false");
this.setSourceExpanded(this.getLastExpandedState("source", true));
this.setDisassemblyExpanded(this.getLastExpandedState("disassembly", true));
this.setRangesExpanded(this.getLastExpandedState("ranges", true));
}
getLastExpandedState(type: string, defaultState: boolean): boolean {
const state = window.sessionStorage.getItem("expandedState-" + type);
if (state === null) return defaultState;
return state === 'true';
}
sourceUpdate(isSourceExpanded: boolean): void {
window.sessionStorage.setItem("expandedState-source", `${isSourceExpanded}`);
this.sourceExpand.classList.toggle("invisible", isSourceExpanded);
this.sourceCollapse.classList.toggle("invisible", !isSourceExpanded);
document.getElementById("show-hide-ranges").style.marginLeft = isSourceExpanded ? null : "40px";
}
setSourceExpanded(isSourceExpanded: boolean): void {
this.sourceUpdate(isSourceExpanded);
this.resizer.updateLeftWidth();
}
disassemblyUpdate(isDisassemblyExpanded: boolean): void {
window.sessionStorage.setItem("expandedState-disassembly", `${isDisassemblyExpanded}`);
this.disassemblyExpand.classList.toggle("invisible", isDisassemblyExpanded);
this.disassemblyCollapse.classList.toggle("invisible", !isDisassemblyExpanded);
}
setDisassemblyExpanded(isDisassemblyExpanded: boolean): void {
this.disassemblyUpdate(isDisassemblyExpanded);
this.resizer.updateRightWidth();
}
rangesUpdate(isRangesExpanded: boolean): void {
window.sessionStorage.setItem("expandedState-ranges", `${isRangesExpanded}`);
this.rangesExpand.classList.toggle("invisible", isRangesExpanded);
this.rangesCollapse.classList.toggle("invisible", !isRangesExpanded);
}
setRangesExpanded(isRangesExpanded: boolean): void {
this.rangesUpdate(isRangesExpanded);
this.resizer.updateRanges();
}
}
export class Resizer {
snapper: Snapper;
deadWidth: number;
deadHeight: number;
left: HTMLElement;
right: HTMLElement;
ranges: HTMLElement;
middle: HTMLElement;
sepLeft: number;
sepRight: number;
sepRangesHeight: number;
panesUpdatedCallback: () => void;
resizerRight: d3.Selection<HTMLDivElement, any, any, any>;
resizerLeft: d3.Selection<HTMLDivElement, any, any, any>;
resizerRanges: d3.Selection<HTMLDivElement, any, any, any>;
private readonly SOURCE_PANE_DEFAULT_PERCENT = 1 / 4;
private readonly DISASSEMBLY_PANE_DEFAULT_PERCENT = 3 / 4;
private readonly RANGES_PANE_HEIGHT_DEFAULT_PERCENT = 3 / 4;
private readonly RESIZER_RANGES_HEIGHT_BUFFER_PERCENTAGE = 5;
private readonly RESIZER_SIZE = document.getElementById("resizer-ranges").offsetHeight;
constructor(panesUpdatedCallback: () => void, deadWidth: number, deadHeight: number) {
const resizer = this;
resizer.panesUpdatedCallback = panesUpdatedCallback;
resizer.deadWidth = deadWidth;
resizer.deadHeight = deadHeight;
resizer.left = document.getElementById(C.SOURCE_PANE_ID);
resizer.right = document.getElementById(C.GENERATED_PANE_ID);
resizer.ranges = document.getElementById(C.RANGES_PANE_ID);
resizer.middle = document.getElementById("middle");
resizer.resizerLeft = d3.select('#resizer-left');
resizer.resizerRight = d3.select('#resizer-right');
resizer.resizerRanges = d3.select('#resizer-ranges');
// Set default sizes, if they weren't set.
if (window.sessionStorage.getItem("source-pane-percent") === null) {
window.sessionStorage.setItem("source-pane-percent", `${this.SOURCE_PANE_DEFAULT_PERCENT}`);
}
if (window.sessionStorage.getItem("disassembly-pane-percent") === null) {
window.sessionStorage.setItem("disassembly-pane-percent", `${this.DISASSEMBLY_PANE_DEFAULT_PERCENT}`);
}
if (window.sessionStorage.getItem("ranges-pane-height-percent") === null) {
window.sessionStorage.setItem("ranges-pane-height-percent", `${this.RANGES_PANE_HEIGHT_DEFAULT_PERCENT}`);
}
this.updateSizes();
const dragResizeLeft = d3.drag()
.on('drag', function () {
const x = d3.mouse(this.parentElement)[0];
resizer.sepLeft = Math.min(Math.max(0, x), resizer.sepRight);
resizer.updatePanes();
})
.on('start', function () {
resizer.resizerLeft.classed("dragged", true);
})
.on('end', function () {
// If the panel is close enough to the left, treat it as if it was pulled all the way to the lefg.
const x = d3.mouse(this.parentElement)[0];
if (x <= deadWidth) {
resizer.sepLeft = 0;
resizer.updatePanes();
}
// Snap if dragged all the way to the left.
resizer.resizerLeft.classed("snapped", resizer.sepLeft === 0);
if (!resizer.isLeftSnapped()) {
window.sessionStorage.setItem("source-pane-percent", `${resizer.sepLeft / document.body.getBoundingClientRect().width}`);
}
resizer.snapper.setSourceExpanded(!resizer.isLeftSnapped());
resizer.resizerLeft.classed("dragged", false);
});
resizer.resizerLeft.call(dragResizeLeft);
const dragResizeRight = d3.drag()
.on('drag', function () {
const x = d3.mouse(this.parentElement)[0];
resizer.sepRight = Math.max(resizer.sepLeft, Math.min(x, document.body.getBoundingClientRect().width));
resizer.updatePanes();
})
.on('start', function () {
resizer.resizerRight.classed("dragged", true);
})
.on('end', function () {
// If the panel is close enough to the right, treat it as if it was pulled all the way to the right.
const x = d3.mouse(this.parentElement)[0];
const clientWidth = document.body.getBoundingClientRect().width;
if (x >= (clientWidth - deadWidth)) {
resizer.sepRight = clientWidth - 1;
resizer.updatePanes();
}
// Snap if dragged all the way to the right.
resizer.resizerRight.classed("snapped", resizer.sepRight >= clientWidth - 1);
if (!resizer.isRightSnapped()) {
window.sessionStorage.setItem("disassembly-pane-percent", `${resizer.sepRight / clientWidth}`);
}
resizer.snapper.setDisassemblyExpanded(!resizer.isRightSnapped());
resizer.resizerRight.classed("dragged", false);
});
resizer.resizerRight.call(dragResizeRight);
const dragResizeRanges = d3.drag()
.on('drag', function () {
const y = d3.mouse(this.parentElement)[1];
resizer.sepRangesHeight = Math.max(100, Math.min(y, window.innerHeight) - resizer.RESIZER_RANGES_HEIGHT_BUFFER_PERCENTAGE);
resizer.updatePanes();
})
.on('start', function () {
resizer.resizerRanges.classed("dragged", true);
})
.on('end', function () {
// If the panel is close enough to the bottom, treat it as if it was pulled all the way to the bottom.
const y = d3.mouse(this.parentElement)[1];
if (y >= (window.innerHeight - deadHeight)) {
resizer.sepRangesHeight = window.innerHeight;
resizer.updatePanes();
}
// Snap if dragged all the way to the bottom.
resizer.resizerRanges.classed("snapped", resizer.sepRangesHeight >= window.innerHeight - 1);
if (!resizer.isRangesSnapped()) {
window.sessionStorage.setItem("ranges-pane-height-percent", `${resizer.sepRangesHeight / window.innerHeight}`);
}
resizer.snapper.setRangesExpanded(!resizer.isRangesSnapped());
resizer.resizerRanges.classed("dragged", false);
});
resizer.resizerRanges.call(dragResizeRanges);
window.onresize = function () {
resizer.updateSizes();
resizer.updatePanes();
};
resizer.snapper = new Snapper(resizer);
resizer.snapper.restoreExpandedState();
}
isLeftSnapped() {
return this.resizerLeft.classed("snapped");
}
isRightSnapped() {
return this.resizerRight.classed("snapped");
}
isRangesSnapped() {
return this.resizerRanges.classed("snapped");
}
updateRangesPane() {
const clientHeight = window.innerHeight;
const rangesIsHidden = this.ranges.style.visibility == "hidden";
let resizerSize = this.RESIZER_SIZE;
if (rangesIsHidden) {
resizerSize = 0;
this.sepRangesHeight = clientHeight;
}
const rangeHeight = clientHeight - this.sepRangesHeight;
this.ranges.style.height = rangeHeight + 'px';
const panelWidth = this.sepRight - this.sepLeft - (2 * resizerSize);
this.ranges.style.width = panelWidth + 'px';
const multiview = document.getElementById("multiview");
if (multiview && multiview.style) {
multiview.style.height = (this.sepRangesHeight - resizerSize) + 'px';
multiview.style.width = panelWidth + 'px';
}
// Resize the range grid and labels.
const rangeGrid = (this.ranges.getElementsByClassName("range-grid")[0] as HTMLElement);
if (rangeGrid) {
const yAxis = (this.ranges.getElementsByClassName("range-y-axis")[0] as HTMLElement);
const rangeHeader = (this.ranges.getElementsByClassName("range-header")[0] as HTMLElement);
const gridWidth = panelWidth - yAxis.clientWidth;
rangeGrid.style.width = Math.floor(gridWidth - 1) + 'px';
// Take live ranges' right scrollbar into account.
rangeHeader.style.width = (gridWidth - rangeGrid.offsetWidth + rangeGrid.clientWidth - 1) + 'px';
// Set resizer to horizontal.
this.resizerRanges.style('width', panelWidth + 'px');
const rangeTitle = (this.ranges.getElementsByClassName("range-title-div")[0] as HTMLElement);
const rangeHeaderLabel = (this.ranges.getElementsByClassName("range-header-label-x")[0] as HTMLElement);
const gridHeight = rangeHeight - rangeHeader.clientHeight - rangeTitle.clientHeight - rangeHeaderLabel.clientHeight;
rangeGrid.style.height = gridHeight + 'px';
// Take live ranges' bottom scrollbar into account.
yAxis.style.height = (gridHeight - rangeGrid.offsetHeight + rangeGrid.clientHeight) + 'px';
}
this.resizerRanges.style('ranges', this.ranges.style.height);
}
updatePanes() {
this.left.style.width = this.sepLeft + 'px';
this.resizerLeft.style('left', this.sepLeft + 'px');
this.right.style.width = (document.body.getBoundingClientRect().width - this.sepRight) + 'px';
this.resizerRight.style('right', (document.body.getBoundingClientRect().width - this.sepRight - 1) + 'px');
this.updateRangesPane();
this.panesUpdatedCallback();
}
updateRanges() {
if (this.isRangesSnapped()) {
this.sepRangesHeight = window.innerHeight;
} else {
const sepRangesHeight = window.sessionStorage.getItem("ranges-pane-height-percent");
this.sepRangesHeight = window.innerHeight * Number.parseFloat(sepRangesHeight);
}
}
updateLeftWidth() {
if (this.isLeftSnapped()) {
this.sepLeft = 0;
} else {
const sepLeft = window.sessionStorage.getItem("source-pane-percent");
this.sepLeft = document.body.getBoundingClientRect().width * Number.parseFloat(sepLeft);
}
}
updateRightWidth() {
if (this.isRightSnapped()) {
this.sepRight = document.body.getBoundingClientRect().width;
} else {
const sepRight = window.sessionStorage.getItem("disassembly-pane-percent");
this.sepRight = document.body.getBoundingClientRect().width * Number.parseFloat(sepRight);
}
}
updateSizes() {
this.updateLeftWidth();
this.updateRightWidth();
this.updateRanges();
}
} | the_stack |
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as TextUtils from '../../models/text_utils/text_utils.js';
import * as DataGrid from '../../ui/legacy/components/data_grid/data_grid.js';
import * as SourceFrame from '../../ui/legacy/components/source_frame/source_frame.js';
import * as UI from '../../ui/legacy/legacy.js';
import {DOMStorage} from './DOMStorageModel.js';
import {StorageItemsView} from './StorageItemsView.js';
const UIStrings = {
/**
*@description Text in DOMStorage Items View of the Application panel
*/
domStorage: 'DOM Storage',
/**
*@description Text in DOMStorage Items View of the Application panel
*/
key: 'Key',
/**
*@description Text for the value of something
*/
value: 'Value',
/**
*@description Data grid name for DOM Storage Items data grids
*/
domStorageItems: 'DOM Storage Items',
/**
*@description Text in DOMStorage Items View of the Application panel
*/
selectAValueToPreview: 'Select a value to preview',
/**
*@description Text for announcing a DOM Storage key/value item has been deleted
*/
domStorageItemDeleted: 'The storage item was deleted.',
/**
*@description Text for announcing number of entries after filtering
*@example {5} PH1
*/
domStorageNumberEntries: 'Number of entries shown in table: {PH1}',
};
const str_ = i18n.i18n.registerUIStrings('panels/application/DOMStorageItemsView.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
export class DOMStorageItemsView extends StorageItemsView {
private domStorage: DOMStorage;
private dataGrid: DataGrid.DataGrid.DataGridImpl<unknown>;
private readonly splitWidget: UI.SplitWidget.SplitWidget;
private readonly previewPanel: UI.Widget.VBox;
private preview: UI.Widget.Widget|null;
private previewValue: string|null;
private eventListeners: Common.EventTarget.EventDescriptor[];
constructor(domStorage: DOMStorage) {
super(i18nString(UIStrings.domStorage), 'domStoragePanel');
this.domStorage = domStorage;
this.element.classList.add('storage-view', 'table');
const columns = ([
{id: 'key', title: i18nString(UIStrings.key), sortable: false, editable: true, longText: true, weight: 50},
{id: 'value', title: i18nString(UIStrings.value), sortable: false, editable: true, longText: true, weight: 50},
] as DataGrid.DataGrid.ColumnDescriptor[]);
this.dataGrid = new DataGrid.DataGrid.DataGridImpl({
displayName: i18nString(UIStrings.domStorageItems),
columns,
editCallback: this.editingCallback.bind(this),
deleteCallback: this.deleteCallback.bind(this),
refreshCallback: this.refreshItems.bind(this),
});
this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode, event => {
this.previewEntry(event.data);
});
this.dataGrid.addEventListener(DataGrid.DataGrid.Events.DeselectedNode, () => {
this.previewEntry(null);
});
this.dataGrid.setStriped(true);
this.dataGrid.setName('DOMStorageItemsView');
this.splitWidget = new UI.SplitWidget.SplitWidget(
/* isVertical: */ false, /* secondIsSidebar: */ true, 'domStorageSplitViewState');
this.splitWidget.show(this.element);
this.previewPanel = new UI.Widget.VBox();
this.previewPanel.setMinimumSize(0, 50);
const resizer = this.previewPanel.element.createChild('div', 'preview-panel-resizer');
const dataGridWidget = this.dataGrid.asWidget();
dataGridWidget.setMinimumSize(0, 50);
this.splitWidget.setMainWidget(dataGridWidget);
this.splitWidget.setSidebarWidget(this.previewPanel);
this.splitWidget.installResizer(resizer);
this.preview = null;
this.previewValue = null;
this.showPreview(null, null);
this.eventListeners = [];
this.setStorage(domStorage);
}
setStorage(domStorage: DOMStorage): void {
Common.EventTarget.removeEventListeners(this.eventListeners);
this.domStorage = domStorage;
this.eventListeners = [
this.domStorage.addEventListener(DOMStorage.Events.DOMStorageItemsCleared, this.domStorageItemsCleared, this),
this.domStorage.addEventListener(DOMStorage.Events.DOMStorageItemRemoved, this.domStorageItemRemoved, this),
this.domStorage.addEventListener(DOMStorage.Events.DOMStorageItemAdded, this.domStorageItemAdded, this),
this.domStorage.addEventListener(DOMStorage.Events.DOMStorageItemUpdated, this.domStorageItemUpdated, this),
];
this.refreshItems();
}
private domStorageItemsCleared(): void {
if (!this.isShowing() || !this.dataGrid) {
return;
}
this.dataGrid.rootNode().removeChildren();
this.dataGrid.addCreationNode(false);
this.setCanDeleteSelected(false);
}
private domStorageItemRemoved(event: Common.EventTarget.EventTargetEvent<DOMStorage.DOMStorageItemRemovedEvent>):
void {
if (!this.isShowing() || !this.dataGrid) {
return;
}
const storageData = event.data;
const rootNode = this.dataGrid.rootNode();
const children = rootNode.children;
for (let i = 0; i < children.length; ++i) {
const childNode = children[i];
if (childNode.data.key === storageData.key) {
rootNode.removeChild(childNode);
this.setCanDeleteSelected(children.length > 1);
return;
}
}
}
private domStorageItemAdded(event: Common.EventTarget.EventTargetEvent<DOMStorage.DOMStorageItemAddedEvent>): void {
if (!this.isShowing() || !this.dataGrid) {
return;
}
const storageData = event.data;
const rootNode = this.dataGrid.rootNode();
const children = rootNode.children;
for (let i = 0; i < children.length; ++i) {
if (children[i].data.key === storageData.key) {
return;
}
}
const childNode = new DataGrid.DataGrid.DataGridNode({key: storageData.key, value: storageData.value}, false);
rootNode.insertChild(childNode, children.length - 1);
}
private domStorageItemUpdated(event: Common.EventTarget.EventTargetEvent<DOMStorage.DOMStorageItemUpdatedEvent>):
void {
if (!this.isShowing() || !this.dataGrid) {
return;
}
const storageData = event.data;
const childNode = this.dataGrid.rootNode().children.find(
(child: DataGrid.DataGrid.DataGridNode<unknown>) => child.data.key === storageData.key);
if (!childNode || childNode.data.value === storageData.value) {
return;
}
childNode.data.value = storageData.value;
childNode.refresh();
if (!childNode.selected) {
return;
}
this.previewEntry(childNode);
this.setCanDeleteSelected(true);
}
private showDOMStorageItems(items: string[][]): void {
const rootNode = this.dataGrid.rootNode();
let selectedKey: null = null;
for (const node of rootNode.children) {
if (!node.selected) {
continue;
}
selectedKey = node.data.key;
break;
}
rootNode.removeChildren();
let selectedNode: DataGrid.DataGrid.DataGridNode<unknown>|null = null;
const filteredItems = (item: string[]): string => `${item[0]} ${item[1]}`;
const filteredList = this.filter(items, filteredItems);
for (const item of filteredList) {
const key = item[0];
const value = item[1];
const node = new DataGrid.DataGrid.DataGridNode({key: key, value: value}, false);
node.selectable = true;
rootNode.appendChild(node);
if (!selectedNode || key === selectedKey) {
selectedNode = node;
}
}
if (selectedNode) {
selectedNode.selected = true;
}
this.dataGrid.addCreationNode(false);
this.setCanDeleteSelected(Boolean(selectedNode));
UI.ARIAUtils.alert(i18nString(UIStrings.domStorageNumberEntries, {PH1: filteredList.length}));
}
deleteSelectedItem(): void {
if (!this.dataGrid || !this.dataGrid.selectedNode) {
return;
}
this.deleteCallback(this.dataGrid.selectedNode);
}
refreshItems(): void {
this.domStorage.getItems().then(items => items && this.showDOMStorageItems(items));
}
deleteAllItems(): void {
this.domStorage.clear();
// explicitly clear the view because the event won't be fired when it has no items
this.domStorageItemsCleared();
}
private editingCallback(
editingNode: DataGrid.DataGrid.DataGridNode<unknown>, columnIdentifier: string, oldText: string,
newText: string): void {
const domStorage = this.domStorage;
if (columnIdentifier === 'key') {
if (typeof oldText === 'string') {
domStorage.removeItem(oldText);
}
domStorage.setItem(newText, editingNode.data.value || '');
this.removeDupes(editingNode);
} else {
domStorage.setItem(editingNode.data.key || '', newText);
}
}
private removeDupes(masterNode: DataGrid.DataGrid.DataGridNode<unknown>): void {
const rootNode = this.dataGrid.rootNode();
const children = rootNode.children;
for (let i = children.length - 1; i >= 0; --i) {
const childNode = children[i];
if ((childNode.data.key === masterNode.data.key) && (masterNode !== childNode)) {
rootNode.removeChild(childNode);
}
}
}
private deleteCallback(node: DataGrid.DataGrid.DataGridNode<unknown>): void {
if (!node || node.isCreationNode) {
return;
}
if (this.domStorage) {
this.domStorage.removeItem(node.data.key);
}
UI.ARIAUtils.alert(i18nString(UIStrings.domStorageItemDeleted));
}
private showPreview(preview: UI.Widget.Widget|null, value: string|null): void {
if (this.preview && this.previewValue === value) {
return;
}
if (this.preview) {
this.preview.detach();
}
if (!preview) {
preview = new UI.EmptyWidget.EmptyWidget(i18nString(UIStrings.selectAValueToPreview));
}
this.previewValue = value;
this.preview = preview;
preview.show(this.previewPanel.contentElement);
}
private async previewEntry(entry: DataGrid.DataGrid.DataGridNode<unknown>|null): Promise<void> {
const value = entry && entry.data && entry.data.value;
if (entry && entry.data && entry.data.value) {
const protocol = this.domStorage.isLocalStorage ? 'localstorage' : 'sessionstorage';
const url = `${protocol}://${entry.key}`;
const provider = TextUtils.StaticContentProvider.StaticContentProvider.fromString(
url, Common.ResourceType.resourceTypes.XHR, (value as string));
const preview = await SourceFrame.PreviewFactory.PreviewFactory.createPreview(provider, 'text/plain');
// Selection could've changed while the preview was loaded
if (entry.selected) {
this.showPreview(preview, value);
}
} else {
this.showPreview(null, value);
}
}
} | the_stack |
import BigNumber from 'bignumber.js';
import {
Balance,
BalanceStruct,
BaseValue,
CallOptions,
BigNumberable,
Price,
SendOptions,
SignedIntStruct,
TxResult,
address,
bnFromSoliditySignedInt,
bnToSoliditySignedInt,
} from '../../src/lib/types';
import { TestContracts } from './TestContracts';
export class TestLib {
private contracts: TestContracts;
constructor(
contracts: TestContracts,
) {
this.contracts = contracts;
}
public get address(): string {
return this.contracts.testLib.options.address;
}
// ============ BaseMath.sol ============
public async base(
options?: CallOptions,
): Promise<BigNumber> {
const base: string = await this.contracts.call(
this.contracts.testLib.methods.base(),
options,
);
return new BigNumber(base);
}
public async baseMul(
value: BigNumberable,
baseValue: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.baseMul(
new BigNumber(value).toFixed(0),
new BigNumber(baseValue).toFixed(0),
),
options,
);
return new BigNumber(result);
}
public async baseDivMul(
value: BigNumberable,
baseValue: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.baseDivMul(
new BigNumber(value).toFixed(0),
new BigNumber(baseValue).toFixed(0),
),
options,
);
return new BigNumber(result);
}
public async baseMulRoundUp(
value: BigNumberable,
baseValue: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.baseMulRoundUp(
new BigNumber(value).toFixed(0),
new BigNumber(baseValue).toFixed(0),
),
options,
);
return new BigNumber(result);
}
public async baseDiv(
value: BigNumberable,
baseValue: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.baseDiv(
new BigNumber(value).toFixed(0),
new BigNumber(baseValue).toFixed(0),
),
options,
);
return new BigNumber(result);
}
public async baseReciprocal(
baseValue: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.baseReciprocal(
new BigNumber(baseValue).toFixed(0),
),
options,
);
return new BigNumber(result);
}
// ============ Math.sol ============
public async getFraction(
target: BigNumberable,
numerator: BigNumberable,
denominator: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.getFraction(
new BigNumber(target).toFixed(0),
new BigNumber(numerator).toFixed(0),
new BigNumber(denominator).toFixed(0),
),
options,
);
return new BigNumber(result);
}
public async getFractionRoundUp(
target: BigNumberable,
numerator: BigNumberable,
denominator: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.getFractionRoundUp(
new BigNumber(target).toFixed(0),
new BigNumber(numerator).toFixed(0),
new BigNumber(denominator).toFixed(0),
),
options,
);
return new BigNumber(result);
}
public async min(
a: BigNumberable,
b: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.min(
new BigNumber(a).toFixed(0),
new BigNumber(b).toFixed(0),
),
options,
);
return new BigNumber(result);
}
public async max(
a: BigNumberable,
b: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.max(
new BigNumber(a).toFixed(0),
new BigNumber(b).toFixed(0),
),
options,
);
return new BigNumber(result);
}
// ============ Require.sol ============
public async that(
must: boolean,
reason: string,
address: address,
options?: CallOptions,
): Promise<void> {
await this.contracts.call(
this.contracts.testLib.methods.that(
must,
reason,
address,
),
options,
);
}
// ============ SafeCast.sol ============
public async toUint128(
value: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.toUint128(
new BigNumber(value).toFixed(0),
),
options,
);
return new BigNumber(result);
}
public async toUint120(
value: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.toUint120(
new BigNumber(value).toFixed(0),
),
options,
);
return new BigNumber(result);
}
public async toUint32(
value: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.toUint32(
new BigNumber(value).toFixed(0),
),
options,
);
return new BigNumber(result);
}
// ============ SignedMath.sol ============
public async add(
sint: BigNumberable,
value: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: SignedIntStruct = await this.contracts.call(
this.contracts.testLib.methods.add(
bnToSoliditySignedInt(sint),
new BigNumber(value).toFixed(0),
),
options,
);
return bnFromSoliditySignedInt(result);
}
public async sub(
sint: BigNumberable,
value: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: SignedIntStruct = await this.contracts.call(
this.contracts.testLib.methods.sub(
bnToSoliditySignedInt(sint),
new BigNumber(value).toFixed(0),
),
options,
);
return bnFromSoliditySignedInt(result);
}
public async signedAdd(
augend: BigNumberable,
addend: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: SignedIntStruct = await this.contracts.call(
this.contracts.testLib.methods.signedAdd(
bnToSoliditySignedInt(augend),
bnToSoliditySignedInt(addend),
),
options,
);
return bnFromSoliditySignedInt(result);
}
public async signedSub(
minuend: BigNumberable,
subtrahend: BigNumberable,
options?: CallOptions,
): Promise<BigNumber> {
const result: SignedIntStruct = await this.contracts.call(
this.contracts.testLib.methods.signedSub(
bnToSoliditySignedInt(minuend),
bnToSoliditySignedInt(subtrahend),
),
options,
);
return bnFromSoliditySignedInt(result);
}
// ============ Storage.sol ============
public async load(
slot: string,
options?: CallOptions,
): Promise<BigNumber> {
const result = await this.contracts.call(
this.contracts.testLib.methods.load(
slot,
),
options,
);
return new BigNumber(result);
}
public async store(
slot: string,
value: string,
options?: SendOptions,
): Promise<TxResult> {
return this.contracts.send(
this.contracts.testLib.methods.store(
slot,
value,
),
options,
);
}
// ============ TypedSignature.sol ============
public async recover(
hash: string,
typedSignature: string,
options?: CallOptions,
): Promise<address> {
return this.contracts.call(
this.contracts.testLib.methods.recover(
hash,
typedSignature,
),
options,
);
}
// ============ P1BalanceMath.sol ============
public async copy(
balance: Balance,
options?: CallOptions,
): Promise<Balance> {
const result: BalanceStruct = await this.contracts.call(
this.contracts.testLib.methods.copy(
balance.toSolidity(),
),
options,
);
return Balance.fromSolidity(result);
}
public async addToMargin(
balance: Balance,
amount: BigNumberable,
options?: CallOptions,
): Promise<Balance> {
const result: BalanceStruct = await this.contracts.call(
this.contracts.testLib.methods.addToMargin(
balance.toSolidity(),
new BigNumber(amount).toFixed(0),
),
options,
);
return Balance.fromSolidity(result);
}
public async subFromMargin(
balance: Balance,
amount: BigNumberable,
options?: CallOptions,
): Promise<Balance> {
const result: BalanceStruct = await this.contracts.call(
this.contracts.testLib.methods.subFromMargin(
balance.toSolidity(),
new BigNumber(amount).toFixed(0),
),
options,
);
return Balance.fromSolidity(result);
}
public async addToPosition(
balance: Balance,
amount: BigNumberable,
options?: CallOptions,
): Promise<Balance> {
const result: BalanceStruct = await this.contracts.call(
this.contracts.testLib.methods.addToPosition(
balance.toSolidity(),
new BigNumber(amount).toFixed(0),
),
options,
);
return Balance.fromSolidity(result);
}
public async subFromPosition(
balance: Balance,
amount: BigNumberable,
options?: CallOptions,
): Promise<Balance> {
const result: BalanceStruct = await this.contracts.call(
this.contracts.testLib.methods.subFromPosition(
balance.toSolidity(),
new BigNumber(amount).toFixed(0),
),
options,
);
return Balance.fromSolidity(result);
}
public async getPositiveAndNegativeValue(
balance: Balance,
price: Price,
options?: CallOptions,
): Promise<{ positive: BaseValue, negative: BaseValue }> {
const [positive, negative]: [string, string] = await this.contracts.call(
this.contracts.testLib.methods.getPositiveAndNegativeValue(
balance.toSolidity(),
price.toSolidity(),
),
options,
);
return {
positive: BaseValue.fromSolidity(positive),
negative: BaseValue.fromSolidity(negative),
};
}
public async getMargin(
balance: Balance,
options?: CallOptions,
): Promise<BigNumber> {
const result: SignedIntStruct = await this.contracts.call(
this.contracts.testLib.methods.getMargin(
balance.toSolidity(),
),
options,
);
return bnFromSoliditySignedInt(result);
}
public async getPosition(
balance: Balance,
options?: CallOptions,
): Promise<BigNumber> {
const result: SignedIntStruct = await this.contracts.call(
this.contracts.testLib.methods.getPosition(
balance.toSolidity(),
),
options,
);
return bnFromSoliditySignedInt(result);
}
public async setMargin(
balance: Balance,
newMarginSignedInt: BigNumberable,
options?: CallOptions,
): Promise<Balance> {
const result: BalanceStruct = await this.contracts.call(
this.contracts.testLib.methods.setMargin(
balance.toSolidity(),
bnToSoliditySignedInt(newMarginSignedInt),
),
options,
);
return Balance.fromSolidity(result);
}
public async setPosition(
balance: Balance,
newPositionSignedInt: BigNumberable,
options?: CallOptions,
): Promise<Balance> {
const result: BalanceStruct = await this.contracts.call(
this.contracts.testLib.methods.setPosition(
balance.toSolidity(),
bnToSoliditySignedInt(newPositionSignedInt),
),
options,
);
return Balance.fromSolidity(result);
}
// ============ ReentrancyGuard.sol ============
public async nonReentrant1(
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.nonReentrant1(),
options,
);
return new BigNumber(result);
}
public async nonReentrant2(
options?: CallOptions,
): Promise<BigNumber> {
const result: string = await this.contracts.call(
this.contracts.testLib.methods.nonReentrant2(),
options,
);
return new BigNumber(result);
}
} | the_stack |
import { HTTPCodes, HTTPRequestContext, HTTPMethod } from '../WebDAVRequest'
import { ResourceType } from '../../../manager/v2/fileSystem/CommonTypes'
import { Transform } from 'stream'
class RangedStream extends Transform
{
nb : number;
constructor(public min : number, public max : number)
{
super();
this.nb = 0;
}
_transform(chunk : string | Buffer, encoding : string, callback : Function)
{
if(this.nb < this.min)
{
const lastNb = this.nb;
this.nb += chunk.length;
if(this.nb > this.min)
{
const start = this.min - lastNb;
chunk = chunk.slice(start, this.nb > this.max ? this.max - this.min + 1 + start : undefined);
callback(null, chunk);
}
else
callback(null, Buffer.alloc(0));
}
else if(this.nb > this.max)
{
this.nb += chunk.length;
callback(null, Buffer.alloc(0));
}
else
{
this.nb += chunk.length;
if(this.nb > this.max)
chunk = chunk.slice(0, this.max - (this.nb - chunk.length) + 1);
callback(null, chunk);
}
}
}
class MultipleRangedStream extends Transform
{
streams : { stream : RangedStream, range : IRange }[]
onEnded : () => void
constructor(public ranges : IRange[])
{
super();
this.streams = ranges.map((r) => {
return {
stream: new RangedStream(r.min, r.max),
range: r
}
});
}
_transform(chunk : string | Buffer, encoding : string, callback : Function)
{
this.streams.forEach((streamRange) => {
streamRange.stream.write(chunk, encoding);
});
callback(null, Buffer.alloc(0));
}
end(chunk ?: any, encoding?: any, cb?: Function): void
{
if(this.onEnded)
process.nextTick(() => this.onEnded());
super.end(chunk, encoding, cb);
}
}
export interface IRange
{
min : number
max : number
}
export function parseRangeHeader(mimeType : string, size : number, range : string)
{
const separator = Array.apply(null, { length: 20 })
.map(() => String.fromCharCode('a'.charCodeAt(0) + Math.floor(Math.random() * 26)))
.join('');
const createMultipart = (range : IRange) => {
return `--${separator}\r\nContent-Type: ${mimeType}\r\nContent-Range: bytes ${range.min}-${range.max}/*\r\n\r\n`;
};
const endMultipart = () => {
return `\r\n--${separator}--`;
};
const ranges = range
.split(',')
.map((block) => parseRangeBlock(size, block));
const len = ranges.reduce((previous, mm) => mm.max - mm.min + 1 + previous, 0)
+ (ranges.length <= 1 ?
0 : ranges.reduce(
(previous, mm) => createMultipart(mm).length + previous,
endMultipart().length + '\r\n'.length * (ranges.length - 1)
)
);
return {
ranges,
separator,
len,
createMultipart,
endMultipart
}
}
function parseRangeBlock(size : number, block : string) : IRange
{
size -= 1;
const rRange = /([0-9]+)-([0-9]+)/;
let match = rRange.exec(block);
if(match)
return {
min: Math.min(size, parseInt(match[1], 10)),
max: Math.min(size, parseInt(match[2], 10))
};
const rStart = /([0-9]+)-/;
match = rStart.exec(block);
if(match)
return {
min: Math.min(size + 1, parseInt(match[1], 10)),
max: size
};
const rEnd = /-([0-9]+)/;
match = rEnd.exec(block);
if(match)
return {
min: Math.max(0, size - parseInt(match[1], 10) + 1),
max: size
};
throw new Error('Cannot parse the range block');
}
export default class implements HTTPMethod
{
unchunked(ctx : HTTPRequestContext, data : Buffer, callback : () => void) : void
{
ctx.noBodyExpected(() => {
ctx.getResource((e, r) => {
ctx.checkIfHeader(r, () => {
const targetSource = ctx.headers.isSource;
//ctx.requirePrivilegeEx(targetSource ? [ 'canRead', 'canSource', 'canGetMimeType' ] : [ 'canRead', 'canGetMimeType' ], () => {
r.type((e, type) => {
if(e)
{
if(!ctx.setCodeFromError(e))
ctx.setCode(HTTPCodes.InternalServerError)
return callback();
}
if(!type.isFile)
{
ctx.setCode(HTTPCodes.MethodNotAllowed)
return callback();
}
const range = ctx.headers.find('Range');
r.size(targetSource, (e, size) => process.nextTick(() => {
if(e && !range)
{
if(!ctx.setCodeFromError(e))
ctx.setCode(HTTPCodes.InternalServerError)
return callback();
}
r.mimeType(targetSource, (e, mimeType) => process.nextTick(() => {
if(e)
{
if(!ctx.setCodeFromError(e))
ctx.setCode(HTTPCodes.InternalServerError)
return callback();
}
r.openReadStream(targetSource, (e, rstream) => {
if(e)
{
if(!ctx.setCodeFromError(e))
ctx.setCode(HTTPCodes.MethodNotAllowed)
return callback();
}
//ctx.invokeEvent('read', r);
rstream.on('error', (e) => {
if(!ctx.setCodeFromError(e))
ctx.setCode(HTTPCodes.InternalServerError);
return callback();
})
if(range)
{
try
{
const { ranges, separator, len, createMultipart, endMultipart } = parseRangeHeader(mimeType, size, range);
ctx.setCode(HTTPCodes.PartialContent);
ctx.response.setHeader('Accept-Ranges', 'bytes')
ctx.response.setHeader('Content-Length', len.toString())
if(ranges.length <= 1)
{
ctx.response.setHeader('Content-Type', mimeType)
ctx.response.setHeader('Content-Range', `bytes ${ranges[0].min}-${ranges[0].max}/*`)
rstream.on('end', callback);
return rstream.pipe(new RangedStream(ranges[0].min, ranges[0].max)).pipe(ctx.response);
}
ctx.response.setHeader('Content-Type', `multipart/byteranges; boundary=${separator}`)
const multi = new MultipleRangedStream(ranges);
rstream.pipe(multi);
let current = 0;
const dones = {};
const evalNext = () => {
if(current === ranges.length)
{
return ctx.response.end(endMultipart(), () => {
callback();
});
}
const sr = dones[current];
if(sr)
{
if(current > 0)
ctx.response.write('\r\n');
ctx.response.write(createMultipart(sr.range));
sr.stream.on('end', () => {
++current;
evalNext();
});
sr.stream.on('data', (chunk, encoding) => {
ctx.response.write(chunk, encoding);
})
//sr.stream.pipe(ctx.response);
}
}
multi.streams.forEach((sr, index) => {
dones[index] = sr;
})
multi.onEnded = () => {
multi.streams.forEach((sr, index) => {
sr.stream.end();
});
evalNext();
}
}
catch(ex)
{
ctx.setCode(HTTPCodes.BadRequest);
callback();
}
}
else
{
ctx.setCode(HTTPCodes.OK);
ctx.response.setHeader('Accept-Ranges', 'bytes')
ctx.response.setHeader('Content-Type', mimeType);
if(size !== null && size !== undefined && size > -1)
ctx.response.setHeader('Content-Length', size.toString());
rstream.on('end', callback);
rstream.pipe(ctx.response);
}
})
}))
}))
})
//})
})
})
})
}
isValidFor(ctx : HTTPRequestContext, type : ResourceType)
{
return type && type.isFile;
}
} | the_stack |
import { Endpoints } from 'detritus-client-rest';
import { ShardClient } from '../client';
import { BaseCollection, emptyBaseCollection } from '../collections/basecollection';
import { BaseSet } from '../collections/baseset';
import {
ActivityFlags,
ActivityPlatformTypes,
ActivityTypes,
DiscordKeys,
PlatformTypes,
PresenceStatuses,
SpecialUrls,
LOCAL_GUILD_ID,
} from '../constants';
import { addQuery, getFormatFromHash, UrlQuery } from '../utils';
import {
BaseStructure,
BaseStructureData,
} from './basestructure';
import { Application } from './application';
import { Emoji } from './emoji';
import { User } from './user';
export const SpecialApplications = Object.freeze({
XBOX: '438122941302046720',
});
export const SpecialPrefixes = Object.freeze({
SPOTIFY: 'spotify:',
});
export const ImageSizes = Object.freeze({
SMALL: 64,
LARGE: 160,
});
const keysPresence = new BaseSet<string>([
DiscordKeys.ACTIVITIES,
DiscordKeys.CLIENT_STATUS,
DiscordKeys.GAME,
DiscordKeys.GUILD_ID,
DiscordKeys.GUILD_IDS,
DiscordKeys.LAST_MODIFIED,
DiscordKeys.STATUS,
DiscordKeys.USER,
]);
const keysMergePresence = new BaseSet<string>([
DiscordKeys.USER,
DiscordKeys.GUILD_ID,
DiscordKeys.ACTIVITIES,
]);
const keysSkipDifferencePresence = new BaseSet<string>([
DiscordKeys.GUILD_ID,
DiscordKeys.GUILD_IDS,
]);
/**
* Presence Structure, used to detail a user's presence in a guild (or general if you have them added (non-bots only))
* @category Structure
*/
export class Presence extends BaseStructure {
readonly _keys = keysPresence;
readonly _keysMerge = keysMergePresence;
readonly _keysSkipDifference = keysSkipDifferencePresence;
_activities?: BaseCollection<string, PresenceActivity>;
_guildIds: BaseSet<string> | string = '';
clientStatus?: {desktop?: string, mobile?: string, web?: string};
lastGuildId: string = LOCAL_GUILD_ID;
lastModified?: number;
status: string = PresenceStatuses.OFFLINE;
user!: User;
constructor(
client: ShardClient,
data?: BaseStructureData,
isClone?: boolean,
) {
super(client, undefined, isClone);
this.merge(data);
}
get activity(): null | PresenceActivity {
return this.game;
}
get activities(): BaseCollection<string, PresenceActivity> {
if (this._activities) {
return this._activities;
}
return emptyBaseCollection;
}
get game(): null | PresenceActivity {
if (this._activities) {
for (let [activityId, activity] of this._activities) {
if (activity.position === 0) {
return activity;
}
}
return this._activities.first() || null;
}
return null;
}
get guildIds(): BaseSet<string> {
if (typeof(this._guildIds) === 'string') {
const guildIds = new BaseSet<string>();
if (this._guildIds) {
guildIds.add(this._guildIds);
}
return guildIds;
}
return this._guildIds;
}
get isDnd(): boolean {
return this.status === PresenceStatuses.DND;
}
get isIdle(): boolean {
return this.status === PresenceStatuses.IDLE;
}
get isOffline(): boolean {
return this.status === PresenceStatuses.OFFLINE || this.status === PresenceStatuses.INVISIBLE;
}
get isOnline(): boolean {
return this.status === PresenceStatuses.ONLINE;
}
get showMobileIcon(): boolean {
if (this.clientStatus) {
return this.clientStatus.mobile === PresenceStatuses.ONLINE;
}
return false;
}
activityFor(guildId: string): null | PresenceActivity {
if (this._activities) {
const activities = this.activitiesFor(guildId);
for (let [activityId, activity] of activities) {
if (activity.position === 0) {
return activity;
}
}
return activities.first() || null;
}
return null;
}
activitiesFor(guildId: string): BaseCollection<string, PresenceActivity> {
if (this._activities) {
const collection = new BaseCollection<string, PresenceActivity>();
for (let [activityId, activity] of this._activities) {
if (activity._hasGuildId(guildId)) {
collection.set(activity.id, activity);
}
}
return collection;
}
return emptyBaseCollection;
}
get _shouldDelete(): boolean {
return !this._guildIds;
}
_deleteGuildId(guildId: string): void {
if (typeof(this._guildIds) === 'string') {
if (this._guildIds === guildId) {
this._guildIds = '';
if (this._activities) {
this._activities.clear();
this._activities = undefined;
}
}
} else {
this._guildIds.delete(guildId);
if (this._guildIds.length) {
if (this._activities) {
for (let [activityId, activity] of this._activities) {
activity._deleteGuildId(guildId);
if (activity._shouldDelete) {
this._activities.delete(activityId);
}
}
if (!this._activities.length) {
this._activities = undefined;
}
}
if (this._guildIds.length === 1) {
this._guildIds = this._guildIds.first() || '';
}
} else {
this._guildIds = '';
}
}
}
_hasGuildId(guildId: string): boolean {
if (typeof(this._guildIds) === 'string') {
return this._guildIds === guildId;
} else {
return this._guildIds.has(guildId);
}
}
mergeValue(key: string, value: any): void {
if (value !== undefined) {
switch (key) {
case DiscordKeys.ACTIVITIES: {
const guildId = this.lastGuildId;
if (this._activities) {
for (let [activityId, activity] of this._activities) {
activity._deleteGuildId(guildId);
}
}
let isNew = false;
if (value.length) {
if (!this._activities) {
this._activities = new BaseCollection<string, PresenceActivity>();
isNew = true;
}
for (let position = 0; position < value.length; position++) {
const raw = value[position];
raw.position = position;
if (this.isClone) {
const activity = new PresenceActivity(this.user, raw);
this._activities.set(activity.id, activity);
} else {
if (this._activities.has(raw.id)) {
const activity = this._activities.get(raw.id) as PresenceActivity;
activity.merge(raw);
} else {
const activity = new PresenceActivity(this.user, raw);
this._activities.set(activity.id, activity);
}
}
}
}
if (this._activities && !isNew) {
for (let [activityId, activity] of this._activities) {
if (activity._shouldDelete) {
this._activities.delete(activityId);
}
}
if (!this._activities.length) {
this._activities = undefined;
}
}
}; return;
case DiscordKeys.GAME: {
// itll always be in the activities array
}; return;
case DiscordKeys.GUILD_ID: {
value = value || LOCAL_GUILD_ID;
this.lastGuildId = value;
// _guildIds will be a string (if its a single guild) or a set (if the presence is for multiple guilds)
if (typeof(this._guildIds) === 'string') {
if (this._guildIds) {
this._guildIds = new BaseSet<string>([this._guildIds, value]);
} else {
this._guildIds = value;
}
} else {
this._guildIds.add(value);
}
}; return;
case DiscordKeys.GUILD_IDS: {
// we just cloned
if (value.length) {
this._guildIds = new BaseSet<string>(value);
} else {
this._guildIds = '';
}
}; return;
case DiscordKeys.LAST_MODIFIED: {
if (value) {
value = parseInt(value);
}
}; break;
case DiscordKeys.USER: {
let user: User;
if (this.isClone) {
if (this.user) {
user = this.user.clone();
user.merge(value);
} else {
user = new User(this.client, value, this.isClone);
}
} else {
if (this.client.users.has(value.id)) {
user = this.client.users.get(value.id) as User;
user.merge(value);
} else {
if (this.user) {
user = this.user;
user.merge(value);
} else {
user = new User(this.client, value);
this.client.users.insert(user);
}
}
}
value = user;
}; break;
}
super.mergeValue(key, value);
}
}
toString(): string {
return `${this.user} is ${this.status}` + ((this.game) ? ` while ${this.game}` : '');
}
}
const keysPresenceActivity = new BaseSet<string>([
DiscordKeys.APPLICATION_ID,
DiscordKeys.ASSETS,
DiscordKeys.BUTTONS,
DiscordKeys.CREATED_AT,
DiscordKeys.DETAILS,
DiscordKeys.EMOJI,
DiscordKeys.FLAGS,
DiscordKeys.GUILD_ID,
DiscordKeys.GUILD_IDS,
DiscordKeys.ID,
DiscordKeys.INSTANCE,
DiscordKeys.METADATA,
DiscordKeys.NAME,
DiscordKeys.PARTY,
DiscordKeys.PLATFORM,
DiscordKeys.POSITION,
DiscordKeys.SECRETS,
DiscordKeys.SESSION_ID,
DiscordKeys.STATE,
DiscordKeys.SYNC_ID,
DiscordKeys.TIMESTAMPS,
DiscordKeys.TYPE,
DiscordKeys.URL,
]);
const keysMergePresenceActivity = new BaseSet<string>([
DiscordKeys.GUILD_ID,
]);
const keysSkipDifferencePresenceActivity = new BaseSet<string>([
DiscordKeys.GUILD_ID,
DiscordKeys.GUILD_IDS,
]);
/**
* Presence Activity Structure, used in [Presence]
* @category Structure
*/
export class PresenceActivity extends BaseStructure {
readonly _uncloneable = true;
readonly _keys = keysPresenceActivity;
readonly _keysMerge = keysMergePresenceActivity;
readonly _keysSkipDifference = keysSkipDifferencePresenceActivity;
readonly user: User;
_guildIds: BaseSet<string> | string = '';
applicationId?: string;
assets?: PresenceActivityAssets;
buttons?: Array<string>;
createdAt?: number;
details?: string;
emoji?: Emoji;
flags: number = 0;
id: string = '';
instance?: boolean;
metadata?: any;
name: string = '';
party?: {id?: string, size?: [number, number]};
platform?: ActivityPlatformTypes;
position: number = 0;
secrets?: {join?: string, match?: string, spectate?: string};
sessionId?: string;
state?: string;
syncId?: string;
timestamps?: PresenceActivityTimestamps;
type: number = 0;
url?: string;
constructor(user: User, data: BaseStructureData) {
super(user.client, undefined, user._clone);
this.user = user;
this.merge(data);
}
get application(): Application | null {
if (this.applicationId && this.client.applications.has(this.applicationId)) {
return this.client.applications.get(this.applicationId) as Application;
}
if (!this.user.bot && this.name && this.isPlaying) {
for (let [applicationId, application] of this.client.applications) {
if (application.matches(this.name)) {
return application;
}
}
}
return null;
}
get applicationIsXbox(): boolean {
return this.applicationId === SpecialApplications.XBOX;
}
get canInstance(): boolean {
return this.hasFlag(ActivityFlags.INSTANCE);
}
get canJoin(): boolean {
return this.hasFlag(ActivityFlags.JOIN);
}
get canJoinRequest(): boolean {
return this.hasFlag(ActivityFlags.JOIN_REQUEST);
}
get canPlay(): boolean {
return this.hasFlag(ActivityFlags.PLAY);
}
get canSpectate(): boolean {
return this.hasFlag(ActivityFlags.SPECTATE);
}
get canSync(): boolean {
return this.hasFlag(ActivityFlags.SYNC);
}
get group(): BaseCollection<string, User> {
const group = new BaseCollection<string, User>();
if (this.party && this.party.id) {
const me = this.user;
group.set(me.id, me);
for (let [userId, presence] of this.client.presences) {
if (group.has(userId)) {
continue;
}
for (let [activityId, activity] of presence.activities) {
if (activity.party && activity.party.id === this.id) {
group.set(userId, presence.user);
break;
}
}
}
}
return group;
}
get guildIds(): BaseSet<string> {
if (typeof(this._guildIds) === 'string') {
const guildIds = new BaseSet<string>();
if (this._guildIds) {
guildIds.add(this._guildIds);
}
return guildIds;
}
return this._guildIds;
}
get imageUrl(): null | string {
return this.imageUrlFormat();
}
get isCustomStatus(): boolean {
return this.type === ActivityTypes.CUSTOM_STATUS;
}
get isListening(): boolean {
return this.type === ActivityTypes.LISTENING;
}
get isPlaying(): boolean {
return this.type === ActivityTypes.PLAYING;
}
get isStreaming(): boolean {
return this.type === ActivityTypes.STREAMING;
}
get isWatching(): boolean {
return this.type === ActivityTypes.WATCHING;
}
get isOnAndroid(): boolean {
return this.platformType === ActivityPlatformTypes.ANDROID;
}
get isOnIOS(): boolean {
return this.platformType === ActivityPlatformTypes.IOS;
}
get isOnSpotify(): boolean {
return (
this.isListening &&
!!(this.id && this.id.startsWith(SpecialPrefixes.SPOTIFY)) &&
!!(this.partyIsSpotify)
);
}
get isOnSamsung(): boolean {
return this.platformType === ActivityPlatformTypes.SAMSUNG;
}
get isOnXbox(): boolean {
return this.platformType === ActivityPlatformTypes.XBOX;
}
get partyIsFull(): boolean {
if (this.party && this.party.size) {
return this.partySize === this.partyMaxSize;
}
return false;
}
get partyIsSpotify(): boolean {
if (this.party && this.party.id) {
return this.party.id.startsWith(SpecialPrefixes.SPOTIFY);
}
return false;
}
get partyMaxSize(): number | null {
if (this.party && this.party.size) {
return this.party.size[1];
}
return null;
}
get partySize(): number | null {
if (this.party && this.party.size) {
return this.party.size[0];
}
return null;
}
get platformType(): string {
// should we check `isPlaying`? the client returns null if they aren't
if (this.applicationIsXbox) {
return ActivityPlatformTypes.XBOX;
}
if (this.platform) {
return this.platform;
}
return ActivityPlatformTypes.DESKTOP;
}
get platformDiscordUrl(): null | string {
if (this.applicationId) {
// now this might not be on discord
// you need to check if the application exists on discord (by fetching it)
return (
Endpoints.Routes.URL +
Endpoints.Routes.APPLICATION_STORE_LISTING_SKU(this.applicationId)
);
}
return null;
}
get spotifyTrackUrl(): null | string {
if (this.isOnSpotify && this.syncId) {
return SpecialUrls.SPOTIFY_TRACK(this.syncId);
}
return null;
}
get typeText(): string {
switch (this.type) {
case ActivityTypes.PLAYING: return 'Playing';
case ActivityTypes.STREAMING: return 'Streaming';
case ActivityTypes.LISTENING: return 'Listening to';
case ActivityTypes.WATCHING: return 'Watching';
case ActivityTypes.CUSTOM_STATUS: return '';
}
return 'Unknown';
}
hasFlag(flag: number): boolean {
return (this.flags & flag) === flag;
}
imageUrlFormat(format?: null | string, query?: UrlQuery): null | string {
if (this.assets) {
return this.assets.imageUrlFormat(format, query);
}
const application = this.application;
if (application) {
return application.iconUrlFormat(format, query);
}
return null;
}
async fetchApplication(): Promise<Application | null> {
if (this.applicationId) {
return this.client.rest.fetchApplication(this.applicationId);
}
return null;
}
async fetchButtonUrls() {
if (!this.sessionId) {
throw new Error('Activity has no Session Id');
}
if (!this.applicationId) {
throw new Error('Activity has no Application Id');
}
if (!this.buttons) {
throw new Error('Activity has no buttons');
}
return this.client.rest.fetchUserActivityMetadata(
this.user.id,
this.sessionId,
String(this.applicationId),
);
}
async fetchMetadata() {
if (!this.sessionId) {
throw new Error('Activity has no Session Id');
}
return this.client.rest.fetchUserActivityMetadata(
this.user.id,
this.sessionId,
String(this.position),
);
}
get _shouldDelete(): boolean {
return !this._guildIds;
}
_deleteGuildId(guildId: string): void {
if (typeof(this._guildIds) === 'string') {
if (this._guildIds === guildId) {
this._guildIds = '';
}
} else {
this._guildIds.delete(guildId);
if (this._guildIds.length) {
if (this._guildIds.length === 1) {
this._guildIds = this._guildIds.first() || '';
}
} else {
this._guildIds = '';
}
}
}
_hasGuildId(guildId: string): boolean {
if (typeof(this._guildIds) === 'string') {
return this._guildIds === guildId;
} else {
return this._guildIds.has(guildId);
}
}
mergeValue(key: string, value: any): void {
switch (key) {
case DiscordKeys.GUILD_ID: {
value = value || LOCAL_GUILD_ID;
if (typeof(this._guildIds) === 'string') {
if (this._guildIds) {
this._guildIds = new BaseSet<string>([this._guildIds, value]);
} else {
this._guildIds = value;
}
} else {
this._guildIds.add(value);
}
}; return;
case DiscordKeys.GUILD_IDS: {
if (value.length) {
this._guildIds = new BaseSet<string>(value);
} else {
this._guildIds = '';
}
}; return;
}
if (value !== undefined && value !== null) {
// just replace our objects since they're of new values
if (typeof(value) === 'object') {
if (Object.keys(value).length) {
switch (key) {
case DiscordKeys.ASSETS: {
if (this.assets) {
this.assets.merge(value);
} else {
this.assets = new PresenceActivityAssets(this, value);
}
}; return;
case DiscordKeys.EMOJI: {
// reason is that `name` can be spoofed here
if (this.emoji) {
this.emoji.merge(value);
} else {
this.emoji = new Emoji(this.client, value);
}
}; return;
case DiscordKeys.TIMESTAMPS: {
if (this.timestamps) {
this.timestamps.merge(value);
} else {
this.timestamps = new PresenceActivityTimestamps(this, value);
}
}; return;
}
} else {
value = undefined;
}
return this._setFromSnake(key, value);
}
}
return super.mergeValue(key, value);
}
toString(): string {
return `${this.typeText} ${this.name}`;
}
}
const keysPresenceActivityAssets = new BaseSet<string>([
DiscordKeys.LARGE_IMAGE,
DiscordKeys.LARGE_TEXT,
DiscordKeys.SMALL_IMAGE,
DiscordKeys.SMALL_TEXT,
]);
const keysMergePresenceActivityAssets = keysPresenceActivityAssets;
/**
* Presence Activity Assets Structure, used in [PresenceActivity]
* @category Structure
*/
export class PresenceActivityAssets extends BaseStructure {
readonly _uncloneable = true;
readonly _keys = keysPresenceActivityAssets;
readonly _keysMerge = keysMergePresenceActivityAssets;
readonly activity: PresenceActivity;
largeImage?: string;
largeText?: string;
smallImage?: string;
smallText?: string;
constructor(activity: PresenceActivity, data: BaseStructureData) {
super(activity.client, undefined, activity._clone);
this.activity = activity;
this.merge(data);
}
get imageUrl() {
return this.imageUrlFormat();
}
get largeImageUrl() {
return this.largeImageUrlFormat();
}
get smallImageUrl() {
return this.smallImageUrlFormat();
}
imageUrlFormat(
format?: null | string,
query?: UrlQuery,
hash?: null | string,
): null | string {
if (hash === undefined) {
hash = this.largeImage || this.smallImage;
}
if (!hash) {
return null;
}
format = getFormatFromHash(
hash,
format,
this.client.imageFormat,
);
if (hash.includes(':')) {
const [platform, id] = hash.split(':');
switch (platform) {
case PlatformTypes.SPOTIFY: {
return addQuery(
Endpoints.CDN.CUSTOM_SPOTIFY(id),
query,
);
};
case PlatformTypes.TWITCH: {
let height = ImageSizes.LARGE;
let width = ImageSizes.LARGE;
if (query) {
if (query.size !== undefined) {
height = query.size;
width = query.size;
}
}
return addQuery(
Endpoints.CDN.CUSTOM_TWITCH(id, height, width),
query,
);
};
}
} else {
// treat it as a normal hash
return addQuery(
Endpoints.CDN.URL + Endpoints.CDN.APP_ASSET(this.activity.applicationId, hash, format),
query,
);
}
return null;
}
largeImageUrlFormat(format?: null | string, query?: UrlQuery) {
return this.imageUrlFormat(format, query, this.largeImage || null);
}
smallImageUrlFormat(format?: null | string, query?: UrlQuery) {
return this.imageUrlFormat(format, query, this.smallImage || null);
}
mergeValue(key: string, value: any): void {
return this._setFromSnake(key, value);
}
}
const keysPresenceActivityTimestamps = new BaseSet<string>([
DiscordKeys.END,
DiscordKeys.START,
]);
const keysMergePresenceActivityTimestamps = keysPresenceActivityTimestamps;
/**
* Presence Activity Timestamp Structure
* used to describe when they started doing an activity and if they ended it or not
* @category Structure
*/
export class PresenceActivityTimestamps extends BaseStructure {
readonly _uncloneable = true;
readonly _keys = keysPresenceActivityTimestamps;
readonly _keysMerge = keysMergePresenceActivityTimestamps;
readonly activity: PresenceActivity;
end?: number = 0;
start?: number = 0;
constructor(activity: PresenceActivity, data: BaseStructureData) {
super(activity.client, undefined, activity._clone);
this.activity = activity;
this.merge(data);
}
get elapsedTime(): number {
let elapsed: number;
if (this.start) {
elapsed = Math.max(Date.now() - this.start, 0);
} else {
elapsed = Date.now();
}
const total = this.totalTime;
if (total) {
return Math.min(elapsed, total);
}
return elapsed;
}
get totalTime(): number {
if (this.end) {
if (this.start) {
return this.end - this.start;
}
return this.end;
}
return 0;
}
mergeValue(key: string, value: any): void {
return this._setFromSnake(key, value);
}
} | the_stack |
import React from 'react';
import 'jest-styled-components';
import 'jest-axe/extend-expect';
import 'regenerator-runtime/runtime';
import { axe } from 'jest-axe';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Accordion, AccordionPanel, Box, Grommet } from '../..';
const customTheme = {
accordion: {
heading: { level: '3' },
},
};
describe('Accordion', () => {
test('should have no accessibility violations', async () => {
const { container, asFragment } = render(
<Grommet>
<Accordion>
<AccordionPanel>Panel body 1</AccordionPanel>
</Accordion>
</Grommet>,
);
const results = await axe(container);
expect(results).toHaveNoViolations();
expect(asFragment()).toMatchSnapshot();
});
test('no AccordionPanel', () => {
const { asFragment } = render(
<Grommet>
<Accordion />
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
});
test('AccordionPanel', () => {
const { asFragment } = render(
<Grommet>
<Accordion>
<AccordionPanel label="Panel 1">Panel body 1</AccordionPanel>
<AccordionPanel label="Panel 2">Panel body 2</AccordionPanel>
{false && (
<AccordionPanel label="Panel 2">Panel body 2</AccordionPanel>
)}
</Accordion>
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
});
test('complex title', () => {
const { asFragment } = render(
<Grommet>
<Box background="dark-1">
<Accordion>
<AccordionPanel label={<div>Panel 1 complex</div>}>
Panel body 1
</AccordionPanel>
{undefined}
<AccordionPanel label={<div>Panel 2 complex</div>}>
Panel body 2
</AccordionPanel>
</Accordion>
</Box>
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
});
test('complex header', () => {
const { asFragment } = render(
<Grommet>
<Accordion activeIndex={1} animate={false}>
<AccordionPanel header={<div>Panel 1 header</div>}>
Panel body 1
</AccordionPanel>
{undefined}
<AccordionPanel header={<div>Panel 2 header</div>}>
Panel body 2
</AccordionPanel>
</Accordion>
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
});
test('change to second Panel', () => {
jest.useFakeTimers('modern');
const onActive = jest.fn();
const { asFragment } = render(
<Grommet>
<Accordion onActive={onActive}>
<AccordionPanel label="Panel 1">Panel body 1</AccordionPanel>
<AccordionPanel label="Panel 2">Panel body 2</AccordionPanel>
</Accordion>
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
userEvent.click(screen.getByRole('tab', { name: /Panel 2/i }));
expect(onActive).toBeCalled();
expect(asFragment()).toMatchSnapshot();
});
test('change to second Panel without onActive', () => {
const { asFragment } = render(
<Grommet>
<Accordion animate={false}>
<AccordionPanel label="Panel 1">Panel body 1</AccordionPanel>
<AccordionPanel label="Panel 2">Panel body 2</AccordionPanel>
</Accordion>
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
userEvent.click(screen.getByRole('tab', { name: /Panel 2/i }));
expect(asFragment()).toMatchSnapshot();
});
test('multiple panels', () => {
const onActive = jest.fn();
const { asFragment } = render(
<Grommet>
<Accordion animate={false} multiple onActive={onActive}>
<AccordionPanel label="Panel 1">Panel body 1</AccordionPanel>
<AccordionPanel label="Panel 2">Panel body 2</AccordionPanel>
</Accordion>
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
userEvent.click(screen.getByRole('tab', { name: /Panel 2/i }));
expect(onActive).toBeCalledWith([1]);
expect(asFragment()).toMatchSnapshot();
userEvent.click(screen.getByRole('tab', { name: /Panel 1/i }));
expect(onActive).toBeCalledWith([1, 0]);
expect(asFragment()).toMatchSnapshot();
userEvent.click(screen.getByRole('tab', { name: /Panel 2/i }));
expect(onActive).toBeCalledWith([0]);
expect(asFragment()).toMatchSnapshot();
userEvent.click(screen.getByRole('tab', { name: /Panel 1/i }));
expect(onActive).toBeCalledWith([]);
expect(asFragment()).toMatchSnapshot();
});
test('custom accordion', () => {
const { asFragment } = render(
<Grommet theme={customTheme}>
<Accordion>
<AccordionPanel label="Panel 1">Panel body 1</AccordionPanel>
</Accordion>
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
});
test('accordion border', () => {
const { asFragment } = render(
<Grommet
theme={{
accordion: {
border: undefined,
panel: {
border: {
side: 'horizontal',
},
},
},
}}
>
<Accordion>
<AccordionPanel label="Panel 1">Panel body 1</AccordionPanel>
</Accordion>
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
});
test('change active index', () => {
const onActive = jest.fn();
const { asFragment } = render(
<Grommet>
<Accordion animate={false} activeIndex={1} onActive={onActive}>
<AccordionPanel label="Panel 1">Panel body 1</AccordionPanel>
<AccordionPanel label="Panel 2">Panel body 2</AccordionPanel>
</Accordion>
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
userEvent.click(screen.getByRole('tab', { name: /Panel 1/i }));
expect(onActive).toBeCalledWith([0]);
expect(asFragment()).toMatchSnapshot();
});
test('focus and hover styles', () => {
const warnSpy = jest.spyOn(console, 'warn').mockImplementation();
const { asFragment } = render(
<Grommet theme={{ accordion: { hover: { color: 'red' } } }}>
<Accordion>
<AccordionPanel
label="Panel 1"
onMouseOver={() => {}}
onMouseOut={() => {}}
onFocus={() => {}}
onBlur={() => {}}
>
Panel body 1
</AccordionPanel>
</Accordion>
</Grommet>,
);
userEvent.click(screen.getByRole('tab', { name: /Panel 1/i }));
expect(asFragment()).toMatchSnapshot();
expect(warnSpy).toHaveBeenCalled();
warnSpy.mockRestore();
});
test('backward compatibility of hover.color = undefined', () => {
const warnSpy = jest.spyOn(console, 'warn').mockImplementation();
const { asFragment } = render(
<Grommet
theme={{
accordion: {
hover: { color: undefined },
},
}}
>
<Accordion>
<AccordionPanel
label="Panel 1"
onMouseOver={() => {}}
onMouseOut={() => {}}
onFocus={() => {}}
onBlur={() => {}}
>
Panel body 1
</AccordionPanel>
</Accordion>
</Grommet>,
);
userEvent.tab();
// hover color should be undefined
expect(asFragment()).toMatchSnapshot();
expect(warnSpy).toHaveBeenCalled();
warnSpy.mockRestore();
});
test('theme hover of hover.heading.color', () => {
const { asFragment } = render(
<Grommet
theme={{
accordion: {
hover: { heading: { color: 'teal' } },
},
}}
>
<Accordion>
<AccordionPanel
label="Panel 1"
onMouseOver={() => {}}
onMouseOut={() => {}}
onFocus={() => {}}
onBlur={() => {}}
>
Panel body 1
</AccordionPanel>
</Accordion>
</Grommet>,
);
userEvent.tab();
// hover color should be undefined
expect(asFragment()).toMatchSnapshot();
});
test('set on hover', () => {
const onMouseOver1 = jest.fn();
const onMouseOut1 = jest.fn();
const onMouseOver2 = jest.fn();
const onMouseOut2 = jest.fn();
render(
<Grommet>
<Accordion>
<AccordionPanel
label="Panel 1"
onMouseOver={onMouseOver1}
onMouseOut={onMouseOut1}
>
Panel body 1
</AccordionPanel>
<AccordionPanel
label="Panel 2"
onMouseOver={onMouseOver2}
onMouseOut={onMouseOut2}
>
Panel body 2
</AccordionPanel>
</Accordion>
</Grommet>,
);
userEvent.hover(screen.getByRole('tab', { name: /Panel 1/i }));
expect(onMouseOver1).toHaveBeenCalled();
userEvent.unhover(screen.getByRole('tab', { name: /Panel 1/i }));
expect(onMouseOut1).toHaveBeenCalled();
userEvent.hover(screen.getByRole('tab', { name: /Panel 2/i }));
expect(onMouseOver2).toHaveBeenCalled();
userEvent.unhover(screen.getByRole('tab', { name: /Panel 2/i }));
expect(onMouseOver2).toHaveBeenCalled();
});
test('wrapped panel', () => {
const onActive = jest.fn();
const { asFragment } = render(
<Grommet>
<Accordion animate={false} onActive={onActive}>
<AccordionPanel label="Panel 1">Panel body 1</AccordionPanel>
<AccordionPanel label="Panel 2">Panel body 2</AccordionPanel>
</Accordion>
</Grommet>,
);
expect(asFragment()).toMatchSnapshot();
userEvent.click(screen.getByRole('tab', { name: /Panel 1/i }));
expect(onActive).toBeCalledWith([0]);
expect(screen.getByText('Panel body 1')).not.toBeNull();
expect(asFragment()).toMatchSnapshot();
});
test('blur styles', () => {
const onBlur = jest.fn();
const { asFragment } = render(
<Grommet theme={{ accordion: { hover: { heading: { color: 'red' } } } }}>
<Accordion>
<AccordionPanel
label="Panel 1"
onMouseOver={() => {}}
onMouseOut={() => {}}
onFocus={() => {}}
onBlur={onBlur}
>
Panel body 1
</AccordionPanel>
</Accordion>
</Grommet>,
);
// tab to the first accordion panel
userEvent.tab();
expect(asFragment()).toMatchSnapshot();
// tab away from the first accordion panel
userEvent.tab();
expect(onBlur).toHaveBeenCalled();
});
}); | the_stack |
import { Component, ViewChild, ViewChildren, QueryList } from '@angular/core';
import { AlertController } from 'ionic-angular';
import { LoadingService } from '../../../services/loading/loading.service';
import { ToastService } from '../../../services/toast/toast.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
//Components
import { DropdownPopoverComponent } from '../../dropdown-popover/dropdown-popover.component';
import { LoggerXAxisComponent } from '../../logger-xaxis/logger-xaxis.component';
//Services
import { DeviceManagerService, DeviceService } from 'dip-angular2/services';
import { UtilityService } from '../../../services/utility/utility.service';
import { LoggerPlotService } from '../../../services/logger-plot/logger-plot.service';
import { ExportService } from '../../../services/export/export.service';
import { SettingsService } from '../../../services/settings/settings.service';
import { TooltipService } from '../../../services/tooltip/tooltip.service';
//Interfaces
/* import { DataContainer } from '../chart/chart.interface'; */
import { PlotDataContainer } from '../../../services/logger-plot/logger-plot.service';
@Component({
templateUrl: 'openscope-logger.html',
selector: 'openscope-logger-component'
})
export class OpenScopeLoggerComponent {
//@ViewChildren('dropPopOverflow') overflowChildren: QueryList<DropdownPopoverComponent>;
@ViewChildren('dropPopSamples') samplesChildren: QueryList<DropdownPopoverComponent>;
@ViewChildren('dropPopLocation') locationChildren: QueryList<DropdownPopoverComponent>;
@ViewChildren('dropPopLink') linkChildren: QueryList<DropdownPopoverComponent>;
@ViewChild('dropPopProfile') profileChild: DropdownPopoverComponent;
@ViewChild('dropPopMode') modeChild: DropdownPopoverComponent;
@ViewChild('xaxis') xAxis: LoggerXAxisComponent;
private activeDevice: DeviceService;
public showLoggerSettings: boolean = true;
public showAnalogChan: boolean[] = [];
public showDigitalChan: boolean[] = [];
private defaultAnalogParams: AnalogLoggerParams = {
gain: 1,
vOffset: 0,
maxSampleCount: -1,
sampleFreq: 1000,
startDelay: 0,
overflow: 'circular',
storageLocation: 'ram',
uri: '',
startIndex: 0,
count: 0,
state: 'idle',
linked: false,
linkedChan: -1
};
private defaultDigitalParams: DigitalLoggerParams = {
maxSampleCount: -1,
sampleFreq: 1000,
startDelay: 0,
overflow: 'circular',
storageLocation: 'ram',
uri: '',
startIndex: 0,
count: 0,
state: 'idle',
linked: false,
linkedChan: -1,
bitMask: 255 //TODO fix when digital channels exist
};
public analogChans: AnalogLoggerParams[] = [];
public digitalChans: DigitalLoggerParams[] = [];
private analogChanNumbers: number[] = [];
private digitalChanNumbers: number[] = [];
public overflowConditions: ('circular')[] = ['circular'];
public modes: string[] = ['log', 'stream', 'both'];
public samples: ('continuous' | 'finite')[] = ['continuous', 'finite'];
public selectedSamples: 'continuous' | 'finite' = this.samples[0];
public selectedMode: string = this.modes[0];
public storageLocations: string[] = [];
public loggingProfiles: string[] = ['New Profile'];
public selectedLogProfile: string = this.loggingProfiles[0];
private defaultProfileName: string = 'NewProfile';
public profileNameScratch: string = this.defaultProfileName;
public analogLinkOptions: string[][] = [];
public digitalLinkOptions: string[][] = [];
private profileObjectMap: any = {};
public running: boolean = false;
public dataContainers: PlotDataContainer[] = [];
public viewMoved: boolean = false;
private analogChansToRead: number[] = [];
private digitalChansToRead: number[] = [];
private chartPanSubscriptionRef;
private offsetChangeSubscriptionRef;
private filesInStorage: any = {};
private destroyed: boolean = false;
public dataAvailable: boolean = false;
constructor(
private devicemanagerService: DeviceManagerService,
private loadingService: LoadingService,
private toastService: ToastService,
private utilityService: UtilityService,
public loggerPlotService: LoggerPlotService,
private exportService: ExportService,
private alertCtrl: AlertController,
private settingsService: SettingsService,
public tooltipService: TooltipService
) {
this.activeDevice = this.devicemanagerService.devices[this.devicemanagerService.activeDeviceIndex];
console.log(this.activeDevice.instruments.logger);
let loading = this.loadingService.displayLoading('Loading device info...');
this.init();
this.loadDeviceInfo()
.then((data) => {
console.log(data);
loading.dismiss();
if (this.running) {
this.continueStream();
}
})
.catch((e) => {
console.log(e);
this.toastService.createToast('deviceDroppedConnection', true, undefined, 5000);
loading.dismiss();
});
}
ngOnDestroy() {
this.chartPanSubscriptionRef.unsubscribe();
this.offsetChangeSubscriptionRef.unsubscribe();
this.running = false;
this.destroyed = true;
}
private init() {
this.chartPanSubscriptionRef = this.loggerPlotService.chartPan.subscribe(
(data) => {
if (this.running) {
this.viewMoved = true;
}
},
(err) => { },
() => { }
);
this.offsetChangeSubscriptionRef = this.loggerPlotService.offsetChange.subscribe(
(data) => {
if (data.axisNum > this.analogChans.length - 1) {
//Digital
return;
}
else {
this.analogChans[data.axisNum].vOffset = data.offset;
}
},
(err) => { },
() => { }
);
for (let i = 0; i < this.activeDevice.instruments.logger.analog.numChans; i++) {
this.analogChans.push(Object.assign({}, this.defaultAnalogParams));
this.showAnalogChan.push(true);
this.analogLinkOptions[i] = ['no'];
for (let j = 0; j < this.analogLinkOptions.length; j++) {
if (i !== j) {
this.analogLinkOptions[j].push('Ch ' + (i + 1).toString());
this.analogLinkOptions[i].push('Ch ' + (j + 1).toString());
}
}
}
for (let i = 0; i < this.activeDevice.instruments.logger.digital.numChans; i++) {
this.digitalChans.push(Object.assign({}, this.defaultDigitalParams));
this.showDigitalChan.push(i === 0);
this.digitalLinkOptions[i] = ['no'];
for (let j = 0; j < this.digitalLinkOptions.length; j++) {
if (i !== j) {
this.digitalLinkOptions[j].push('Ch ' + (i + 1).toString());
this.digitalLinkOptions[i].push('Ch ' + (j + 1).toString());
}
}
}
for (let i = 0; i < this.analogChans.length; i++) {
this.analogChanNumbers.push(i + 1);
this.dataContainers.push({
data: [],
yaxis: i + 1,
lines: {
show: true
},
points: {
show: false
},
seriesOffset: 0
});
}
for (let i = 0; i < this.digitalChans.length; i++) {
this.digitalChanNumbers.push(i + 1);
this.dataContainers.push({
data: [],
yaxis: i + 1 + this.analogChans.length,
lines: {
show: true
},
points: {
show: false
},
seriesOffset: 0
})
}
}
private loadDeviceInfo(): Promise<any> {
return new Promise((resolve, reject) => {
let analogChanArray = [];
let digitalChanArray = [];
for (let i = 0; i < this.analogChans.length; i++) {
analogChanArray.push(i + 1);
}
for (let i = 0; i < this.digitalChans.length; i++) {
digitalChanArray.push(i + 1);
}
if (analogChanArray.length < 1 && digitalChanArray.length < 1) {
resolve('done');
return;
}
this.getStorageLocations()
.then((data) => {
console.log(data);
if (data && data.device && data.device[0]) {
data.device[0].storageLocations.forEach((el, index, arr) => {
if (el !== 'flash') {
this.storageLocations.unshift(el);
}
});
}
if (this.storageLocations.length < 1) {
this.modes = ['stream'];
this.modeSelect('stream');
return new Promise((resolve, reject) => { resolve(); });
}
else {
return new Promise((resolve, reject) => {
this.storageLocations.reduce((accumulator, currentVal, currentIndex) => {
return accumulator
.then((data) => {
return this.listDir(currentVal, '/');
})
.catch((e) => {
return this.listDir(currentVal, '/');
});
}, Promise.resolve())
.then((data) => {
console.log('DONE READING STORAGE LOCATIONS');
resolve();
})
.catch((e) => {
console.log(e);
resolve();
});
});
}
})
.then((data) => {
console.log(data);
return this.loadProfilesFromDevice();
})
.then((data) => {
console.log(data);
return this.getCurrentState('analog', analogChanArray);
//return this.analogGetMultipleChannelStates(analogChanArray);
})
.catch((e) => {
console.log(e);
return this.getCurrentState('analog', analogChanArray);
//return this.analogGetMultipleChannelStates(analogChanArray);
})
.then((data) => {
console.log(data);
return this.getCurrentState('digital', digitalChanArray);
})
.then((data) => {
console.log(data);
console.log(this.analogChans);
resolve(data);
})
.catch((e) => {
console.log(e);
reject(e);
});
});
}
continueStream() {
if (!this.running) { return; }
//Device was in stream mode and should be ready to stream
this.analogChansToRead = [];
for (let i = 0; i < this.analogChans.length; i++) {
if (this.analogChans[i].state === 'running') {
this.analogChansToRead.push(i + 1);
this.analogChans[i].count = -1000;
this.analogChans[i].startIndex = -1;
}
}
for (let i = 0; i < this.digitalChans.length; i++) {
if (this.digitalChans[i].state === 'running') {
this.digitalChansToRead.push(i + 1);
this.digitalChans[i].count = -1000;
this.digitalChans[i].startIndex = -1;
}
}
if (this.selectedMode === 'log') {
this.bothStartStream();
}
this.readLiveData();
}
fileExists(): Promise<any> {
return new Promise((resolve, reject) => {
this.alertWrapper('File Exists', 'Your log file already exists. Would you like to overwrite or cancel?',
[{
text: 'Cancel',
handler: (data) => {
reject();
}
},
{
text: 'Overwrite',
handler: (data) => {
resolve();
}
}]
);
});
}
private alertWrapper(title: string, subTitle: string, buttons?: { text: string, handler: (data) => void }[]): Promise<any> {
return new Promise((resolve, reject) => {
let alert = this.alertCtrl.create({
title: title,
subTitle: subTitle,
buttons: buttons == undefined ? ['OK'] : <any>buttons
});
alert.onWillDismiss((data) => {
resolve(data);
});
alert.present();
});
}
xAxisValChange(event) {
console.log(event);
this.loggerPlotService.setValPerDivAndUpdate('x', 1, event);
}
yAxisValChange(trueValue, axisNum: number) {
console.log(trueValue);
if (trueValue < this.loggerPlotService.vpdArray[0]) {
trueValue = this.loggerPlotService.vpdArray[0];
}
else if (trueValue > this.loggerPlotService.vpdArray[this.loggerPlotService.vpdArray.length - 1]) {
trueValue = this.loggerPlotService.vpdArray[this.loggerPlotService.vpdArray.length - 1];
}
if (this.loggerPlotService.vpdArray[this.loggerPlotService.vpdIndices[axisNum]] === trueValue) {
console.log('the same');
/* this.chart.timeDivision = trueValue * 10 + 1;
setTimeout(() => {
this.chart.timeDivision = trueValue;
}, 1); */
return;
}
this.loggerPlotService.setValPerDivAndUpdate('y', axisNum + 1, trueValue);
/* this.chart.timeDivision = trueValue;
this.chart.setNearestPresetSecPerDivVal(trueValue);
this.chart.setTimeSettings({
timePerDiv: this.chart.timeDivision,
base: this.chart.base
}, false); */
}
mousewheel(event, instrument: 'analog' | 'digital', axisNum: number, input: 'offset' | 'sampleFreq' | 'samples' | 'vpd') {
if (input === 'offset') {
this.buttonChangeOffset(axisNum, event.deltaY < 0 ? 'increment' : 'decrement');
return;
}
if (event.deltaY < 0) {
input === 'vpd' ? this.decrementVpd(axisNum) : this.incrementFrequency(instrument, axisNum, input);
}
else {
input === 'vpd' ? this.incrementVpd(axisNum) : this.decrementFrequency(instrument, axisNum, input);
}
}
incrementVpd(axisNum: number) {
if (this.loggerPlotService.vpdIndices[axisNum] > this.loggerPlotService.vpdArray.length - 2) { return; }
this.loggerPlotService.setValPerDivAndUpdate('y', axisNum + 1, this.loggerPlotService.vpdArray[this.loggerPlotService.vpdIndices[axisNum] + 1]);
}
decrementVpd(axisNum: number) {
if (this.loggerPlotService.vpdIndices[axisNum] < 1) { return; }
this.loggerPlotService.setValPerDivAndUpdate('y', axisNum + 1, this.loggerPlotService.vpdArray[this.loggerPlotService.vpdIndices[axisNum] - 1]);
}
buttonChangeOffset(axisNum: number, type: 'increment' | 'decrement') {
this.analogChans[axisNum].vOffset += type === 'increment' ? 0.1 : -0.1;
this.loggerPlotService.setPosition('y', axisNum + 1, this.analogChans[axisNum].vOffset, true);
}
incrementFrequency(instrument: 'analog' | 'digital', axisNum: number, type: 'sampleFreq' | 'samples') {
let axisObj = instrument === 'analog' ? this.analogChans[axisNum] : this.digitalChans[axisNum];
let valString = type === 'sampleFreq' ? axisObj.sampleFreq.toString() : axisObj.maxSampleCount.toString();
let valNum = parseFloat(valString);
let pow = 0;
while (valNum * Math.pow(1000, pow) < 1) {
pow++;
}
valString = (valNum * Math.pow(1000, pow)).toString();
let leadingNum = parseInt(valString.charAt(0), 10);
let numberMag = valString.split('.')[0].length - 1;
leadingNum++;
if (leadingNum === 10) {
leadingNum = 1;
numberMag++;
}
let newFreq = (leadingNum * Math.pow(10, numberMag)) / Math.pow(1000, pow);
this.validateAndApply(newFreq, instrument, axisNum, type);
}
private validateAndApply(newVal: number, instrument: 'analog' | 'digital', axisNum: number, type: 'sampleFreq' | 'samples') {
let axisObj = instrument === 'analog' ? this.analogChans[axisNum] : this.digitalChans[axisNum];
if (type === 'sampleFreq') {
let chanObj = this.activeDevice.instruments.logger[instrument].chans[axisNum];
let minFreq = chanObj.sampleFreqMin * chanObj.sampleFreqUnits;
let maxFreq = chanObj.sampleFreqMax * chanObj.sampleFreqUnits;
if (newVal < minFreq) {
newVal = minFreq;
}
else if (newVal > maxFreq) {
newVal = maxFreq;
}
axisObj.sampleFreq = newVal;
}
else if (type === 'samples') {
let chanObj = this.activeDevice.instruments.logger[instrument].chans[axisNum];
let maxSampleSize = axisObj.storageLocation === 'ram' ? chanObj.bufferSizeMax : 2000000000; //2gb fat
if (newVal < 1) {
newVal = 1;
}
else if (newVal > maxSampleSize) {
newVal = maxSampleSize;
}
axisObj.maxSampleCount = newVal;
}
}
decrementFrequency(instrument: 'analog' | 'digital', axisNum: number, type: 'sampleFreq' | 'samples') {
let axisObj = instrument === 'analog' ? this.analogChans[axisNum] : this.digitalChans[axisNum];
let valString = type === 'sampleFreq' ? axisObj.sampleFreq.toString() : axisObj.maxSampleCount.toString();
let valNum = parseFloat(valString);
let pow = 0;
while (valNum * Math.pow(1000, pow) < 1) {
pow++;
}
valString = (valNum * Math.pow(1000, pow)).toString();
let leadingNum = parseInt(valString.charAt(0), 10);
let numberMag = valString.split('.')[0].length - 1;
leadingNum--;
if (leadingNum === 0) {
leadingNum = 9;
numberMag--;
}
let newFreq = (leadingNum * Math.pow(10, numberMag)) / Math.pow(1000, pow);
this.validateAndApply(newFreq, instrument, axisNum, type);
}
setViewToEdge() {
if (this.viewMoved) { return; }
if (this.dataContainers[0].data[0] == undefined || this.dataContainers[0].data[0][0] == undefined) {
//Data was cleared
this.loggerPlotService.setPosition('x', 1, this.loggerPlotService.xAxis.base * 5, true);
return;
}
let rightPos = this.dataContainers[0].data[this.dataContainers[0].data.length - 1][0];
for (let i = 1; i < this.dataContainers.length; i++) {
let tempRightPos = this.dataContainers[i].data[this.dataContainers[i].data.length - 1][0];
rightPos = tempRightPos > rightPos ? tempRightPos : rightPos;
}
let span = this.loggerPlotService.xAxis.base * 10;
let leftPos = rightPos - span;
if (leftPos < 0) { return; }
let newPos = (rightPos + leftPos) / 2;
this.loggerPlotService.setPosition('x', 1, newPos, false);
}
modeSelect(event) {
console.log(event);
if (this.selectedMode === 'stream' && event !== 'stream') {
for (let i = 0; i < this.analogChans.length; i++) {
this.analogChans[i].storageLocation = this.storageLocations[0];
this.setChannelDropdowns(i, {
storageLocation: this.storageLocations[0]
});
}
for (let i = 0; i < this.digitalChans.length; i++) {
this.digitalChans[i].storageLocation = this.storageLocations[0];
//TODO update to support digital in setChannelDropdowns
/* this.setChannelDropdowns(i, {
storageLocation: this.storageLocations[0]
}); */
}
}
if (event === 'stream') {
for (let i = 0; i < this.analogChans.length; i++) {
this.analogChans[i].storageLocation = 'ram';
}
for (let i = 0; i < this.digitalChans.length; i++) {
this.digitalChans[i].storageLocation = 'ram';
}
}
this.selectedMode = event;
}
samplesSelect(event: 'finite' | 'continuous', instrument: 'analog' | 'digital', channel: number) {
console.log(event);
let chanObj = instrument === 'analog' ? this.analogChans[channel] : this.digitalChans[channel];
if (event === 'finite') {
this.analogChans[channel].maxSampleCount = 1000;
}
else {
chanObj.maxSampleCount = -1;
}
this.selectedSamples = event;
}
linkSelect(event, instrument: 'analog' | 'digital', channel: number) {
console.log(event);
if (event === 'no') {
if (this.analogChans[channel].linked) {
let linkedChan = this.analogChans[channel].linkedChan;
this.copyLoggingProfile(instrument, channel, this.analogChans[linkedChan]);
this.setChannelDropdowns(channel, {
storageLocation: this.analogChans[linkedChan].storageLocation,
overflow: this.analogChans[linkedChan].overflow,
linkChan: -1,
samples: this.analogChans[linkedChan].maxSampleCount === -1 ? 'continuous' : 'finite'
});
}
this.analogChans[channel].linked = false;
this.analogChans[channel].linkedChan = -1;
return;
}
let linkChan: number = event.split(' ')[1] - 1;
console.log('linked chan selection: ' + linkChan);
if (instrument === 'analog') {
if (this.analogChans[linkChan].linked) {
//TODO display error
console.log('linked to linked channel');
let id = 'link' + channel;
this.linkChildren.forEach((child) => {
if (id === child.elementRef.nativeElement.id) {
child._applyActiveSelection('no');
}
});
return;
}
this.copyLoggingProfile('analog', channel, this.analogChans[linkChan]);
this.analogChans[channel].linked = true;
this.analogChans[channel].linkedChan = linkChan;
this.setChannelDropdowns(channel, {
storageLocation: this.analogChans[channel].storageLocation,
overflow: this.analogChans[channel].overflow,
linkChan: linkChan,
samples: this.analogChans[channel].maxSampleCount === -1 ? 'continuous' : 'finite'
});
}
else {
}
console.log(this.analogChans);
}
private copyLoggingProfile(instrument: 'analog' | 'digital', channel: number, source: any) {
let instrumentChan = instrument === 'analog' ? this.analogChans : this.digitalChans;
instrumentChan[channel].maxSampleCount = source.maxSampleCount;
instrumentChan[channel].overflow = source.overflow;
instrumentChan[channel].sampleFreq = source.sampleFreq;
instrumentChan[channel].startDelay = source.startDelay;
instrumentChan[channel].storageLocation = source.storageLocation;
if (instrument === 'digital') {
(<DigitalLoggerParams>instrumentChan[channel]).bitMask = source.bitMask;
}
}
private setChannelDropdowns(channel: number, applyOptions: { storageLocation?: string, overflow?: string, linkChan?: number, samples?: string }) {
setTimeout(() => {
if (applyOptions.linkChan != undefined) {
let linkedChanString = applyOptions.linkChan > -1 ? 'Ch ' + (applyOptions.linkChan + 1) : 'no';
let id = 'link' + channel;
this.linkChildren.forEach((child) => {
if (id === child.elementRef.nativeElement.id) {
child._applyActiveSelection(linkedChanString);
}
});
}
if (applyOptions.storageLocation != undefined) {
let id = 'location' + channel;
this.locationChildren.forEach((child) => {
if (id === child.elementRef.nativeElement.id) {
child._applyActiveSelection(applyOptions.storageLocation);
}
});
}
if (applyOptions.samples != undefined) {
let id = 'samples' + channel;
this.samplesChildren.forEach((child) => {
if (id === child.elementRef.nativeElement.id) {
child._applyActiveSelection(applyOptions.samples);
}
});
}
/* if (applyOptions.overflow != undefined) {
let id = 'overflow' + channel;
this.overflowChildren.forEach((child) => {
if (id === child.elementRef.nativeElement.id) {
child._applyActiveSelection(applyOptions.overflow);
}
});
} */
}, 20);
}
overflowSelect(event, instrument: 'analog' | 'digital', channel: number) {
console.log(event);
if (instrument === 'analog') {
this.analogChans[channel].overflow = event;
}
else {
this.digitalChans[channel].overflow = event;
}
}
locationSelect(event, instrument: 'analog' | 'digital', channel: number) {
console.log(event);
if (instrument === 'analog') {
this.analogChans[channel].storageLocation = event;
}
else {
this.digitalChans[channel].storageLocation = event;
}
}
profileSelect(event) {
console.log(event);
let currentLogProfile = this.selectedLogProfile;
this.selectedLogProfile = event;
if (event === this.loggingProfiles[0]) { return; }
if (this.profileObjectMap[event] == undefined) {
this.toastService.createToast('loggerProfileLoadErr', true, undefined, 5000);
console.log('profile not found in profile map');
this.selectedLogProfile = currentLogProfile;
setTimeout(() => {
this.profileChild._applyActiveSelection(this.selectedLogProfile);
}, 20);
return;
}
//Need to copy so further edits do not overwrite profile info
this.parseAndApplyProfileJson(JSON.parse(JSON.stringify(this.profileObjectMap[event])));
}
saveAndSetProfile() {
this.saveProfile(this.profileNameScratch)
.then((data) => {
this.toastService.createToast('loggerSaveSuccess');
})
.catch((e) => {
console.log(e);
this.toastService.createToast('loggerSaveFail');
});
let nameIndex: number = this.loggingProfiles.indexOf(this.profileNameScratch);
if (nameIndex !== -1) {
this.loggingProfiles.splice(nameIndex, 1);
}
this.loggingProfiles.push(this.profileNameScratch);
let profileObj = this.generateProfileJson();
let profileObjCopy = JSON.parse(JSON.stringify(profileObj));
this.profileObjectMap[this.profileNameScratch] = profileObjCopy;
setTimeout(() => {
this.selectedLogProfile = this.profileNameScratch;
this.profileChild._applyActiveSelection(this.selectedLogProfile);
this.profileNameScratch = this.defaultProfileName;
}, 20);
}
loadProfilesFromDevice(): Promise<any> {
return new Promise((resolve, reject) => {
this.listDir('flash', '/')
.then((data) => {
console.log(data);
let profileFileNames = [];
for (let i = 0; i < data.file[0].files.length; i++) {
if (data.file[0].files[i].indexOf(this.settingsService.profileToken) !== -1) {
profileFileNames.push(data.file[0].files[i].replace(this.settingsService.profileToken, ''));
}
}
console.log(profileFileNames);
profileFileNames.reduce((accumulator, currentVal, currentIndex) => {
return accumulator
.then((data) => {
console.log(data);
return this.readProfile(currentVal);
})
.catch((e) => {
console.log(e);
return this.readProfile(currentVal);
});
}, Promise.resolve())
.then((data) => {
console.log(data);
resolve(data);
})
.catch((e) => {
reject(e);
});
})
.catch((e) => {
reject(e);
});
});
}
private readProfile(profileName: string): Promise<any> {
return new Promise((resolve, reject) => {
this.activeDevice.file.read('flash', this.settingsService.profileToken + profileName, 0, -1).subscribe(
(data) => {
console.log(data);
let parsedData;
try {
parsedData = JSON.parse(data.file);
}
catch(e) {
console.log('error parsing json');
resolve(e);
return;
}
let splitArray = profileName.split('.');
if (splitArray.length < 2) {
this.loggingProfiles.push(profileName);
this.profileObjectMap[profileName] = parsedData;
}
else {
splitArray.splice(splitArray.length - 1, 1);
let noExtName = splitArray.join('');
this.loggingProfiles.push(noExtName);
this.profileObjectMap[noExtName] = parsedData;
}
resolve(data);
},
(err) => {
console.log(err);
resolve(err);
},
() => { }
);
});
}
private generateProfileJson() {
let saveObj = {};
if (this.analogChans.length > 0) {
saveObj['analog'] = {};
}
if (this.digitalChans.length > 0) {
saveObj['digital'] = {};
}
for (let i = 0; i < this.analogChans.length; i++) {
saveObj['analog'][i.toString()] = this.analogChans[i];
}
for (let i = 0; i < this.digitalChans.length; i++) {
saveObj['digital'][i.toString()] = this.analogChans[i];
}
return saveObj;
}
private parseAndApplyProfileJson(loadedObj) {
for (let instrument in loadedObj) {
for (let channel in loadedObj[instrument]) {
if (instrument === 'analog') {
let currentState = this.analogChans[parseInt(channel)].state;
let currentLocation = this.analogChans[parseInt(channel)].storageLocation;
this.analogChans[parseInt(channel)] = loadedObj[instrument][channel];
this.analogChans[parseInt(channel)].count = this.defaultAnalogParams.count;
this.analogChans[parseInt(channel)].startIndex = this.defaultAnalogParams.startIndex;
this.analogChans[parseInt(channel)].state = currentState;
this.analogChans[parseInt(channel)].storageLocation = currentLocation
}
else if (instrument === 'digital') {
let currentState = this.digitalChans[parseInt(channel)].state;
let currentLocation = this.digitalChans[parseInt(channel)].storageLocation;
this.digitalChans[parseInt(channel)] = loadedObj[instrument][channel];
this.digitalChans[parseInt(channel)].count = this.defaultAnalogParams.count;
this.digitalChans[parseInt(channel)].startIndex = this.defaultAnalogParams.startIndex;
this.digitalChans[parseInt(channel)].state = currentState;
this.analogChans[parseInt(channel)].storageLocation = currentLocation
}
//Wait for ngFor to execute on the dropPops (~20ms) before we apply the active selections (there has to be a better way)
let dropdownChangeObj = {
overflow: loadedObj[instrument][channel].overflow
};
if (loadedObj[instrument][channel].linked) {
dropdownChangeObj['linkChan'] = loadedObj[instrument][channel].linkedChan;
}
dropdownChangeObj['samples'] = loadedObj[instrument][channel].maxSampleCount === -1 ? 'continuous' : 'finite';
this.setChannelDropdowns(parseInt(channel), dropdownChangeObj);
}
}
}
private saveProfile(profileName: string): Promise<any> {
return new Promise((resolve, reject) => {
for (let i = 0; i < this.analogChans.length; i++) {
if (this.analogChans[i].linked) {
this.copyLoggingProfile('analog', i, this.analogChans[this.analogChans[i].linkedChan]);
}
}
for (let i = 0; i < this.digitalChans.length; i++) {
if (this.digitalChans[i].linked) {
this.copyLoggingProfile('digital', i, this.digitalChans[this.digitalChans[i].linkedChan]);
}
}
let objToSave = this.generateProfileJson();
let str = JSON.stringify(objToSave);
let buf = new ArrayBuffer(str.length);
let bufView = new Uint8Array(buf);
for (let i = 0; i < str.length; i++) {
bufView[i] = str.charCodeAt(i);
}
this.activeDevice.file.write('flash', this.settingsService.profileToken + profileName + '.json', buf).subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
private getStorageLocations(): Promise<any> {
return new Promise((resolve, reject) => {
this.activeDevice.storageGetLocations().subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
setActiveSeries(instrument: 'analog' | 'digital', axisNum: number) {
let convertedNum = instrument === 'analog' ? axisNum + 1 : axisNum + this.analogChans.length + 1;
this.loggerPlotService.setActiveSeries(convertedNum);
}
formatInputAndUpdate(trueValue: number, instrument: 'analog' | 'digital', type: LoggerInputType, channel: number) {
console.log(trueValue);
let chanType = instrument === 'analog' ? this.analogChans[channel] : this.digitalChans[channel];
switch (type) {
case 'delay':
chanType.startDelay = trueValue;
break;
case 'offset':
(<AnalogLoggerParams>chanType).vOffset = trueValue;
this.loggerPlotService.setPosition('y', channel + 1, trueValue, true);
break;
case 'samples':
trueValue = trueValue < 1 ? 1 : trueValue;
chanType.maxSampleCount = trueValue;
break;
case 'sampleFreq':
this.validateAndApply(trueValue, instrument, channel, 'sampleFreq');
break;
default:
break;
}
}
stopLogger() {
this.stop('analog', this.analogChanNumbers)
.then((data) => {
console.log(data);
return this.stop('digital', this.digitalChanNumbers);
})
.then((data) => {
console.log(data);
this.running = false;
})
.catch((e) => {
console.log(e);
});
}
private clearChart() {
for (let i = 0; i < this.dataContainers.length; i++) {
this.dataContainers[i].data = [];
}
this.loggerPlotService.setData(this.dataContainers, this.viewMoved);
this.dataAvailable = false;
}
private parseReadResponseAndDraw(readResponse) {
for (let instrument in readResponse.instruments) {
for (let channel in readResponse.instruments[instrument]) {
let formattedData: number[][] = [];
let channelObj = readResponse.instruments[instrument][channel];
let dt = 1 / (channelObj.actualSampleFreq / 1000000);
let timeVal = channelObj.startIndex * dt;
for (let i = 0; i < channelObj.data.length; i++) {
formattedData.push([timeVal, channelObj.data[i]]);
timeVal += dt;
}
let dataContainerIndex = 0;
if (instrument === 'digital') {
dataContainerIndex += this.analogChans.length;
}
let chanIndex: number = parseInt(channel) - 1;
dataContainerIndex += chanIndex;
this.dataContainers[dataContainerIndex].seriesOffset = channelObj.actualVOffset / 1000;
this.dataContainers[dataContainerIndex].data = this.dataContainers[dataContainerIndex].data.concat(formattedData);
let overflow = 0;
let containerSize = this.analogChans[chanIndex].sampleFreq * this.xAxis.loggerBufferSize;
if ((overflow = this.dataContainers[dataContainerIndex].data.length - containerSize) >= 0) {
this.dataContainers[dataContainerIndex].data = this.dataContainers[dataContainerIndex].data.slice(overflow); // older data is closer to the front of the array, so remove it by the overflow amount
}
}
}
this.setViewToEdge();
this.loggerPlotService.setData(this.dataContainers, this.viewMoved);
this.dataAvailable = true;
}
private existingFileFoundAndValidate(loading): { reason: number } {
let existingFileFound: boolean = false;
let foundChansMap = {};
for (let i = 0; i < this.analogChans.length; i++) {
if (this.analogChans[i].storageLocation !== 'ram' && this.analogChans[i].uri === '') {
loading.dismiss();
this.toastService.createToast('loggerInvalidFileName', true, undefined, 8000);
return { reason: 1 };
}
if (this.analogChans[i].state !== 'idle' && this.analogChans[i].state !== 'stopped') {
loading.dismiss();
this.toastService.createToast('loggerInvalidState', true, undefined, 8000);
return { reason: 1 };
}
if (foundChansMap[this.analogChans[i].uri] != undefined) {
loading.dismiss();
this.toastService.createToast('loggerMatchingFileNames', true, undefined, 8000);
return { reason: 1 };
}
if (this.analogChans[i].storageLocation !== 'ram') {
foundChansMap[this.analogChans[i].uri] = 1;
}
if (this.selectedMode === 'stream') { continue; }
if (this.filesInStorage[this.analogChans[i].storageLocation].indexOf(this.analogChans[i].uri + '.dlog') !== -1) {
//File already exists on device display alert
existingFileFound = true;
}
else {
//TODO fix this so that new uris are only pushed after all channels are processed. Could create a new obj and then deep merge
this.filesInStorage[this.analogChans[i].storageLocation].push(this.analogChans[i].uri + '.dlog');
}
}
return (existingFileFound ? { reason: 2 } : { reason: 0 });
}
startLogger() {
let loading = this.loadingService.displayLoading('Starting data logging...');
this.getCurrentState('analog', this.analogChanNumbers, true)
.then((data) => {
console.log(data);
return this.getCurrentState('digital', this.digitalChanNumbers, true);
})
.then((data) => {
let returnData: { reason: number } = this.existingFileFoundAndValidate(loading);
if (returnData.reason === 2) {
loading.dismiss();
this.fileExists()
.then((data) => {
let loading = this.loadingService.displayLoading('Starting data logging...');
this.setParametersAndRun(loading);
})
.catch((e) => { });
}
else if (returnData.reason === 0) {
this.setParametersAndRun(loading);
}
})
.catch((e) => {
console.log(e);
loading.dismiss();
this.toastService.createToast('loggerUnknownRunError', true, undefined, 8000);
});
}
private setParametersAndRun(loading) {
let analogChanArray = [];
let digitalChanArray = [];
//TODO when each channel invidivdually, loop and check if channel is on before pushing
for (let i = 0; i < this.analogChans.length; i++) {
this.analogChans[i].count = -1000;
this.analogChans[i].startIndex = -1;
if (this.analogChans[i].linked) {
this.copyLoggingProfile('analog', i, this.analogChans[this.analogChans[i].linkedChan]);
}
analogChanArray.push(i + 1);
}
for (let i = 0; i < this.digitalChans.length; i++) {
this.digitalChans[i].count = -1000;
this.digitalChans[i].startIndex = -1;
if (this.digitalChans[i].linked) {
this.copyLoggingProfile('digital', i, this.digitalChans[this.digitalChans[i].linkedChan]);
}
digitalChanArray.push(i + 1);
}
this.clearChart();
this.setViewToEdge();
this.setParameters('analog', analogChanArray)
.then((data) => {
console.log(data);
return this.setParameters('digital', digitalChanArray);
})
.then((data) => {
console.log(data);
return this.run('analog', analogChanArray);
})
.then((data) => {
console.log(data);
return this.run('digital', digitalChanArray);
})
.then((data) => {
console.log(data);
this.running = true;
loading.dismiss();
//TODO load this value from the selected chans assuming individual channel selection is an added feature later
this.analogChansToRead = this.analogChanNumbers.slice();
console.log("ANALOG CHANS TO READ: ");
console.log(this.analogChansToRead);
if (this.selectedMode !== 'log') {
this.readLiveData();
}
else {
this.getLiveState();
}
})
.catch((e) => {
console.log(e);
this.toastService.createToast('loggerUnknownRunError', true, undefined, 8000);
this.running = false;
this.stopLogger();
loading.dismiss();
});
}
private getLiveState() {
this.getCurrentState('analog', this.analogChansToRead.slice())
.then((data) => {
this.parseGetLiveStatePacket('analog', data);
if (this.running) {
setTimeout(() => {
if (this.selectedMode === 'both') {
this.continueStream();
}
else {
this.getLiveState();
}
}, 1000);
}
})
.catch((e) => {
if (this.running) {
setTimeout(() => {
this.getLiveState();
}, 1000);
}
});
}
private parseGetLiveStatePacket(instrument: 'digital' | 'analog', data) {
for (let channel in data.log[instrument]) {
if (data.log[instrument][channel][0].stopReason === 'OVERFLOW') {
console.log('OVERFLOW');
this.toastService.createToast('loggerStorageCouldNotKeepUp', true, undefined, 8000);
// Set running to false beforehand so that another getCurrentState does not occur
this.running = false;
this.stopLogger();
}
else if (data.log[instrument][channel][0].state === 'stopped') {
if (instrument === 'analog') {
this.analogChansToRead.splice(this.analogChansToRead.indexOf(parseInt(channel)), 1);
}
if (this.analogChansToRead.length < 1 && this.digitalChansToRead.length < 1) {
this.toastService.createToast('loggerLogDone');
this.running = false;
}
}
}
}
private readLiveData() {
//Make copies of analogChansToRead so mid-read changes to analogChansToRead don't change the channel array
this.read('analog', this.analogChansToRead.slice())
.then((data) => {
this.parseReadResponseAndDraw(data);
if (this.running) {
if (this.selectedMode !== 'log') {
this.readLiveData();
}
else {
this.getLiveState();
}
}
else {
this.viewMoved = false;
}
})
.catch((e) => {
console.log('error reading live data');
console.log(e);
if (this.destroyed) { return; }
else if (e === 'corrupt transfer') {
this.readLiveData();
return;
}
else if (e.message && e.message === 'Data not ready' && this.running) {
console.log('data not ready');
this.readLiveData();
return;
}
else if (e.message && e.message === 'Could not keep up with device') {
this.toastService.createToast('loggerCouldNotKeepUp', false, undefined, 10000);
this.stop('analog', this.analogChansToRead)
.then((data) => {
console.log(data);
})
.catch((e) => {
console.log(e);
});
}
else {
this.toastService.createToast('loggerUnknownRunError', true, undefined, 8000);
}
this.getCurrentState('analog', this.analogChanNumbers)
.then((data) => {
console.log(data);
return this.getCurrentState('digital', this.digitalChanNumbers);
})
.then((data) => {
console.log(data);
})
.catch((e) => {
console.log(e);
});
this.running = false;
});
}
toggleLoggerSettings() {
this.showLoggerSettings = !this.showLoggerSettings;
}
toggleSeriesSettings(instrument: 'analog' | 'digital', chan: number) {
if (instrument === 'analog') {
this.showAnalogChan[chan] = !this.showAnalogChan[chan];
}
else {
this.showDigitalChan[chan] = !this.showDigitalChan[chan];
}
}
exportCanvasAsPng() {
let flotOverlayRef = document.getElementById('loggerChart').childNodes[1];
this.exportService.exportCanvasAsPng(this.loggerPlotService.chart.getCanvas(), flotOverlayRef);
}
exportCsv(fileName: string) {
let analogChanArray = [];
let digitalChanArray = [];
for (let i = 0; i < this.analogChans.length; i++) {
analogChanArray.push(i);
}
for (let i = analogChanArray.length; i < this.dataContainers.length; i++) {
digitalChanArray.push(i);
}
this.exportService.exportGenericCsv(fileName, this.dataContainers, analogChanArray.concat(digitalChanArray), [{
instrument: 'Analog',
seriesNumberOffset: 0,
xUnit: 's',
yUnit: 'V',
channels: analogChanArray
}, {
instrument: 'Digital',
seriesNumberOffset: this.analogChans.length,
xUnit: 's',
yUnit: 'V',
channels: digitalChanArray
}]);
}
private applyCurrentStateResponse(data: any, onlyCopyState: boolean = false) {
for (let instrument in data.log) {
for (let channel in data.log[instrument]) {
if (instrument === 'analog' || instrument === 'digital') {
this.copyState(<'analog' | 'digital'>instrument, data.log[instrument][channel][0], (parseInt(channel) - 1), onlyCopyState);
}
}
}
}
bothStopStream() {
this.selectedMode = 'log';
this.modeChild._applyActiveSelection('log');
}
bothStartStream() {
this.clearChart();
this.viewMoved = false;
this.setViewToEdge();
this.selectedMode = 'both';
this.modeChild._applyActiveSelection('both');
}
private copyState(instrument: 'analog' | 'digital', respObj, channelInternalIndex: number, onlyCopyState: boolean = false) {
if (respObj.statusCode == undefined || respObj.maxSampleCount == undefined || respObj.actualSampleFreq == undefined) { return; }
let activeChan;
if (instrument === 'analog') {
activeChan = this.analogChans[channelInternalIndex];
if (!onlyCopyState) {
//Perhaps update the window to match gain?
/* activeChan.gain = respObj.actualGain;
activeChan.vOffset = respObj.actualVOffset / 1000; */
}
}
else {
activeChan = this.digitalChans[channelInternalIndex];
if (!onlyCopyState) {
activeChan.bitMask = respObj.bitMask;
}
}
activeChan.state = respObj.state;
if (onlyCopyState) {
return;
}
activeChan.maxSampleCount = respObj.maxSampleCount;
activeChan.sampleFreq = respObj.actualSampleFreq / 1000000;
activeChan.startDelay = respObj.actualStartDelay / Math.pow(10, 12);
activeChan.overflow = 'circular';//respObj.overflow;
let it = 0;
/* this.overflowChildren.forEach((child) => {
if (channelInternalIndex === it) {
child._applyActiveSelection(activeChan.overflow);
}
it++;
}); */
if (this.storageLocations.length < 1) {
//Keith sets default storage location to sd0 even if it doesn't exist.
respObj.storageLocation = 'ram';
}
activeChan.storageLocation = respObj.storageLocation;
if (respObj.storageLocation === 'ram') {
console.log('setting selected mode to stream');
this.selectedMode = 'stream';
this.modeChild._applyActiveSelection('stream');
}
it = 0;
this.locationChildren.forEach((child) => {
if (channelInternalIndex === it) {
child._applyActiveSelection(activeChan.storageLocation);
}
it++;
});
it = 0;
this.samplesChildren.forEach((child) => {
if (channelInternalIndex === it) {
let setting = activeChan.maxSampleCount === -1 ? 'continuous' : 'finite';
child._applyActiveSelection(setting);
}
});
activeChan.uri = respObj.uri;
if (activeChan.uri.indexOf('.dlog') !== -1) {
//Remove .dlog from end of file
activeChan.uri = activeChan.uri.slice(0, activeChan.uri.indexOf('.dlog'));
}
if (activeChan.state === 'running') {
this.running = true;
}
}
private calculateGainFromWindow(channelNum: number): number {
let range = this.loggerPlotService.vpdArray[this.loggerPlotService.vpdIndices[channelNum]] * 10;
let j = 0;
while (range * this.activeDevice.instruments.logger.analog.chans[channelNum].gains[j] > this.activeDevice.instruments.logger.analog.chans[channelNum].adcVpp / 1000 &&
j < this.activeDevice.instruments.logger.analog.chans[channelNum].gains.length
) {
j++;
}
if (j > this.activeDevice.instruments.logger.analog.chans[channelNum].gains.length - 1) {
j--;
}
return this.activeDevice.instruments.logger.analog.chans[channelNum].gains[j];
}
setParameters(instrument: 'analog' | 'digital', chans: number[]): Promise<any> {
return new Promise((resolve, reject) => {
let observable;
let paramObj = {};
if (instrument === 'analog') {
if (this.analogChans.length < 1) {
resolve();
return;
}
let analogParamArray: string[] = ['maxSampleCount', 'gain', 'vOffset', 'sampleFreq', 'startDelay', 'overflow', 'storageLocation', 'uri'];
for (let i = 0; i < chans.length; i++) {
for (let j = 0; j < analogParamArray.length; j++) {
if (paramObj[analogParamArray[j]] == undefined) {
paramObj[analogParamArray[j]] = [];
}
let newIndex = paramObj[analogParamArray[j]].push(this.analogChans[chans[i] - 1][analogParamArray[j]]);
if (analogParamArray[j] === 'uri') {
paramObj[analogParamArray[j]][newIndex - 1] += '.dlog';
}
else if (analogParamArray[j] === 'gain') {
paramObj[analogParamArray[j]][newIndex - 1] = this.calculateGainFromWindow(chans[i] - 1);
}
}
}
console.log(paramObj);
observable = this.activeDevice.instruments.logger.analog.setParameters(
chans,
paramObj[analogParamArray[0]],
paramObj[analogParamArray[1]],
paramObj[analogParamArray[2]],
paramObj[analogParamArray[3]],
paramObj[analogParamArray[4]],
paramObj[analogParamArray[5]],
paramObj[analogParamArray[6]],
paramObj[analogParamArray[7]]
);
}
else {
if (this.digitalChans.length < 1) {
resolve();
return;
}
let digitalParamArray: string[] = ['maxSampleCount', 'sampleFreq', 'startDelay', 'overflow', 'storageLocation', 'uri', 'bitMask'];
for (let i = 0; i < chans.length; i++) {
for (let j = 0; j < digitalParamArray.length; j++) {
if (paramObj[digitalParamArray[j]] == undefined) {
paramObj[digitalParamArray[j]] = [];
}
paramObj[digitalParamArray[j]].push(this.digitalChans[chans[i] - 1][digitalParamArray[j]]);
}
}
console.log(paramObj);
observable = this.activeDevice.instruments.logger.digital.setParameters(
chans,
paramObj[digitalParamArray[0]],
paramObj[digitalParamArray[1]],
paramObj[digitalParamArray[2]],
paramObj[digitalParamArray[3]],
paramObj[digitalParamArray[4]],
paramObj[digitalParamArray[5]],
paramObj[digitalParamArray[6]]
);
}
observable.subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
run(instrument: 'analog' | 'digital', chans: number[]): Promise<any> {
return new Promise((resolve, reject) => {
if (instrument === 'analog' && this.analogChans.length < 1) {
resolve();
return;
}
if (instrument === 'digital' && this.digitalChans.length < 1) {
resolve();
return;
}
/* chans.forEach((el, index, arr) => {
if (instrument === 'analog') {
this.analogChans[el - 1].count = 0;
this.analogChans[el - 1].startIndex = 0;
}
else {
this.digitalChans[el - 1].count = 0;
this.digitalChans[el - 1].startIndex = 0;
}
}); */
this.activeDevice.instruments.logger[instrument].run(instrument, chans).subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
stop(instrument: 'analog' | 'digital', chans: number[]): Promise<any> {
return new Promise((resolve, reject) => {
if (instrument === 'analog' && this.analogChans.length < 1) {
resolve();
return;
}
if (instrument === 'digital' && this.digitalChans.length < 1) {
resolve();
return;
}
this.activeDevice.instruments.logger[instrument].stop(instrument, chans).subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
read(instrument: 'analog' | 'digital', chans: number[]): Promise<any> {
return new Promise((resolve, reject) => {
let startIndices: number[] = [];
let counts: number[] = [];
if (instrument === 'analog') {
if (this.analogChansToRead.length < 1 || this.analogChans.length < 1) {
resolve();
return;
}
for (let i = 0; i < this.analogChansToRead.length; i++) {
startIndices.push(this.analogChans[this.analogChansToRead[i] - 1].startIndex);
counts.push(this.analogChans[this.analogChansToRead[i] - 1].count);
}
}
if (instrument === 'digital') {
if (this.digitalChans.length < 1) {
resolve();
return;
}
for (let i = 0; i < this.digitalChansToRead.length; i++) {
startIndices.push(this.digitalChans[this.digitalChansToRead[i] - 1].startIndex);
counts.push(this.digitalChans[this.digitalChansToRead[i] - 1].count);
}
}
let finalObj = {};
chans.reduce((accumulator, currentVal, currentIndex) => {
return accumulator.flatMap((data) => {
if (currentIndex > 0) {
let chanObj = instrument === 'analog' ? this.analogChans[currentIndex - 1] : this.digitalChans[currentIndex - 1];
if (chanObj.startIndex >= 0 && chanObj.startIndex !== data.instruments[instrument][currentIndex].startIndex) {
return Observable.create((observer) => { observer.error({
message: 'Could not keep up with device',
data: data
}); });
}
this.updateValuesFromRead(data, instrument, chans, currentIndex - 1);
}
this.deepMergeObj(finalObj, data);
return this.activeDevice.instruments.logger[instrument].read(instrument, [chans[currentIndex]], [startIndices[currentIndex]], [counts[currentIndex]]);
});
}, Observable.create((observer) => { observer.next({}); observer.complete(); }))
.subscribe(
(data) => {
let chanObj = instrument === 'analog' ? this.analogChans[chans[chans.length - 1] - 1] : this.digitalChans[chans[chans.length - 1] - 1];
if (chanObj.startIndex >= 0 && chanObj.startIndex !== data.instruments[instrument][chans[chans.length - 1]].startIndex) {
reject({
message: 'Could not keep up with device',
data: data
});
return;
}
this.updateValuesFromRead(data, instrument, chans, chans.length - 1);
this.deepMergeObj(finalObj, data);
resolve(finalObj);
},
(err) => {
console.log(err);
if (err.payload != undefined) {
let jsonString = String.fromCharCode.apply(null, new Uint8Array(err.payload));
let parsedData;
try {
parsedData = JSON.parse(jsonString);
}
catch(e) {
reject(e);
return;
}
//Check if data is not ready
if (parsedData && parsedData.log && parsedData.log[instrument]) {
for (let chan in parsedData.log[instrument]) {
if (parsedData.log[instrument][chan][0].statusCode === 2684354593) {
console.log('data not ready');
reject({
message: 'Data not ready',
data: parsedData
});
return;
}
else if (parsedData.log[instrument][chan][0].statusCode === 2684354595) {
reject({
message: 'Could not keep up with device',
data: parsedData
})
}
}
}
}
reject(err);
},
() => {}
);
});
}
private updateValuesFromRead(data, instrument: 'analog' | 'digital', chans: number[], index: number) {
if (data != undefined && data.instruments != undefined && data.instruments[instrument] != undefined && data.instruments[instrument][chans[index]].statusCode === 0) {
if (instrument === 'analog') {
this.analogChans[chans[index] - 1].startIndex = data.instruments[instrument][chans[index]].startIndex;
this.analogChans[chans[index] - 1].startIndex += data.instruments[instrument][chans[index]].actualCount;
this.analogChans[chans[index] - 1].count = 0;
if (this.analogChans[chans[index] - 1].maxSampleCount > 0 && this.analogChans[chans[index] - 1].startIndex >= this.analogChans[chans[index] - 1].maxSampleCount) {
this.analogChansToRead.splice(this.analogChansToRead.indexOf(chans[index]), 1);
if (this.analogChansToRead.length < 1) {
this.running = false;
}
}
}
else {
this.digitalChans[chans[index] - 1].startIndex += data.instruments[instrument][chans[index]].actualCount;
if (this.digitalChans[chans[index] - 1].maxSampleCount > 0 && this.digitalChans[chans[index] - 1].startIndex >= this.digitalChans[chans[index] - 1].maxSampleCount) {
this.running = false;
}
}
}
}
private deepMergeObj(destObj, sourceObj) {
if (this.isObject(destObj) && this.isObject(sourceObj)) {
Object.keys(sourceObj).forEach((key) => {
if (sourceObj[key].constructor === Array) {
destObj[key] = [];
sourceObj[key].forEach((el, index, arr) => {
if (this.isObject(el)) {
if (destObj[key][index] == undefined) {
destObj[key][index] = {};
}
this.deepMergeObj(destObj[key][index], sourceObj[key][index]);
}
else {
destObj[key][index] = sourceObj[key][index];
}
});
}
else if (this.isObject(sourceObj[key])) {
if (destObj[key] == undefined) {
destObj[key] = {};
}
this.deepMergeObj(destObj[key], sourceObj[key]);
}
else {
destObj[key] = sourceObj[key];
}
});
}
}
private isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
listDir(location: string, path: string): Promise<any> {
return new Promise((resolve, reject) => {
this.activeDevice.file.listDir(location, path).subscribe(
(data) => {
this.filesInStorage[location] = data.file[0].files;
console.log(this.filesInStorage);
resolve(data);
},
(err) => {
reject(err);
},
() => { }
);
});
}
getCurrentState(instrument: 'analog' | 'digital', chans: number[], onlyCopyState: boolean = false): Promise<any> {
return new Promise((resolve, reject) => {
if (instrument === 'analog' && this.analogChans.length < 1) {
resolve();
return;
}
if (instrument === 'digital' && this.digitalChans.length < 1) {
resolve();
return;
}
if (chans.length < 1) {
resolve();
return;
}
this.activeDevice.instruments.logger[instrument].getCurrentState(instrument, chans).subscribe(
(data) => {
if (data.log != undefined && data.log.analog != undefined) {
this.applyCurrentStateResponse(data, onlyCopyState);
}
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
}
export interface LoggerParams {
maxSampleCount: number,
sampleFreq: number,
startDelay: number,
overflow: 'stop' | 'circular',
storageLocation: string,
uri: string,
startIndex: number,
count: number,
state: LoggerChannelState,
linked: boolean,
linkedChan: number
}
export type LoggerChannelState = 'busy' | 'idle' | 'stopped' | 'running';
export interface AnalogLoggerParams extends LoggerParams {
gain: number,
vOffset: number
}
export interface DigitalLoggerParams extends LoggerParams {
bitMask: number
}
export type LoggerInputType = 'delay' | 'offset' | 'samples' | 'sampleFreq'; | the_stack |
import { getRuntimeProxyWindow } from './window_groups_runtime_proxy';
import { GroupWindow } from '../shapes';
import { ExternalWindow } from 'electron';
import { moveFromOpenFinWindow, getEventBounds, getTransactionBounds } from './normalized_rectangle';
import of_events from './of_events';
import route from '../common/route';
import { RectangleBase, Rectangle } from './rectangle';
import { restore } from './api/native_window';
import WindowGroups from './window_groups';
const WindowTransaction = require('electron').windowTransaction;
import { writeToLog } from './log';
import {release} from 'os';
const isWin32 = process.platform === 'win32';
const isWin10 = isWin32 && release().split('.')[0] === '10';
// Use disabled frame bounds changing events for mac os and for external native windows
const usesDisabledFrameEvents = (win: GroupWindow) => win.isExternalWindow || !isWin32;
enum ChangeType {
POSITION = 0,
SIZE = 1,
POSITION_AND_SIZE = 2
}
type MoveAccumulator = { otherWindows: Move[], leader?: Move };
type WinId = string;
const listenerCache: Map<WinId, Array<(...args: any[]) => void>> = new Map();
export interface Move { ofWin: GroupWindow; rect: Rectangle; }
async function raiseEvent(groupWindow: GroupWindow, topic: string, payload: Object) {
const { uuid, name, isProxy, isExternalWindow } = groupWindow;
const identity = { uuid, name };
const eventName = isExternalWindow ? route.externalWindow(topic, uuid, name) : route.window(topic, uuid, name);
const eventArgs = {
...payload,
...identity,
topic,
type: 'window'
};
if (isProxy) {
const rt = await getRuntimeProxyWindow(identity);
const fin = rt.hostRuntime.fin;
await fin.System.executeOnRemote(identity, { action: 'raise-event', payload: { eventName, eventArgs } });
} else {
of_events.emit(eventName, eventArgs);
}
}
function emitChange(topic: string, ofWin: GroupWindow, changeType: ChangeType, reason: string) {
const rect = ofWin.browserWindow.getBounds();
const eventBounds = getEventBounds(rect);
const eventArgs = {
...eventBounds,
changeType,
reason,
deferred: true
};
raiseEvent(ofWin, topic, eventArgs);
}
export function updateGroupedWindowBounds(win: GroupWindow, delta: Partial<RectangleBase>) {
const zeroDelta: RectangleBase = { x: 0, y: 0, height: 0, width: 0 };
const shift = { ...zeroDelta, ...delta };
return handleApiMove(win, shift);
}
function getLeaderDelta(win: GroupWindow, bounds: Partial<RectangleBase>): RectangleBase {
const { rect } = moveFromOpenFinWindow(win);
// Could be partial bounds from an API call
const end = { ...rect, ...bounds };
return rect.delta(end);
}
export function setNewGroupedWindowBounds(win: GroupWindow, partialBounds: Partial<RectangleBase>) {
const delta = getLeaderDelta(win, partialBounds);
return handleApiMove(win, delta);
}
function handleApiMove(win: GroupWindow, delta: RectangleBase) {
const { rect } = moveFromOpenFinWindow(win);
const newBounds = rect.shift(delta);
if (!rect.moved(newBounds)) {
return;
}
const moved = (delta.x && delta.x + delta.width) || (delta.y && delta.y + delta.height);
const resized = delta.width || delta.height;
const changeType = resized
? moved
? ChangeType.POSITION_AND_SIZE
: ChangeType.SIZE
: ChangeType.POSITION;
const moves = generateWindowMoves(win, newBounds, changeType);
const { leader, otherWindows } = moves.reduce((accum: MoveAccumulator, move) => {
move.ofWin === win ? accum.leader = move : accum.otherWindows.push(move);
return accum;
}, <MoveAccumulator>{ otherWindows: [] });
if (!leader || leader.rect.moved(newBounds)) {
//Proposed move differs from requested move
throw new Error('Attempted move violates group constraints');
}
handleBatchedMove(moves);
emitChange('bounds-changed', win, changeType, 'self');
otherWindows.map(({ofWin}) => emitChange('bounds-changed', ofWin, changeType, 'group'));
return leader.rect;
}
function handleBatchedMove(moves: Move[]) {
if (isWin32) {
const { flag: { noZorder, noActivate } } = WindowTransaction;
const flags = noZorder + noActivate;
const wt = new WindowTransaction.Transaction(0);
moves.forEach(({ ofWin, rect }) => {
const hwnd = parseInt(ofWin.browserWindow.nativeId, 16);
let bounds: RectangleBase;
if (isWin10 && ofWin._options.frame) {
bounds = (<any>ExternalWindow).addShadow(ofWin.browserWindow.nativeId, rect);
} else {
bounds = rect;
}
(<any>wt.setWindowPos)(hwnd, { ...getTransactionBounds(bounds), flags, scale: false });
});
wt.commit();
} else {
moves.forEach(({ ofWin, rect }) => {
ofWin.browserWindow.setBounds(rect);
});
}
}
const getInitialPositions = (win: GroupWindow) => WindowGroups.getGroup(win.groupUuid).map(moveFromOpenFinWindow);
const handleMoveOnly = (delta: RectangleBase, initialPositions: Move[]) => {
return initialPositions.map(({ ofWin, rect }) => ({ ofWin, rect: rect.shift(delta)}));
};
function generateWindowMoves(win: GroupWindow, rawBounds: RectangleBase, changeType: ChangeType): Move[] {
const initialPositions: Move[] = getInitialPositions(win);
let moves: Move[];
const delta = getLeaderDelta(win, rawBounds);
switch (changeType) {
case ChangeType.POSITION:
moves = handleMoveOnly(delta, initialPositions);
break;
case ChangeType.SIZE:
moves = handleResizeOnly(win, delta);
break;
case ChangeType.POSITION_AND_SIZE:
const resized = (delta.width || delta.height);
const xShift = delta.x ? delta.x + delta.width : 0;
const yShift = delta.y ? delta.y + delta.height : 0;
const moved = (xShift || yShift);
if (resized) {
const resizeDelta = {x: delta.x - xShift, y: delta.y - yShift, width: delta.width, height: delta.height};
moves = handleResizeOnly(win, resizeDelta);
}
if (moved) {
const shift = { x: xShift, y: yShift, width: 0, height: 0 };
moves = handleMoveOnly(shift, moves);
}
break;
default: {
moves = [];
} break;
}
return moves;
}
function handleResizeOnly(win: GroupWindow, delta: RectangleBase) {
const initialPositions = getInitialPositions(win);
const rects = initialPositions.map(x => x.rect);
const leaderRectIndex = initialPositions.map(x => x.ofWin).indexOf(win);
const start = rects[leaderRectIndex];
const iterMoves = Rectangle.PROPAGATE_MOVE(leaderRectIndex, start, delta, rects);
const allMoves = iterMoves.map((rect, i) => ({
ofWin: initialPositions[i].ofWin,
rect}));
const moves = allMoves.filter((move, i) => initialPositions[i].rect.moved(move.rect));
const endMove = moves.find(({ ofWin }) => ofWin === win);
if (!endMove) {
return [];
}
const final = endMove.rect;
const xChangedWithoutWidth = final.width === start.width && final.x !== start.x;
if (xChangedWithoutWidth) {
return [];
}
const yChangedWithoutHeight = final.height === start.height && final.y !== start.y;
if (yChangedWithoutHeight) {
return [];
}
return moves;
}
export function addWindowToGroup(win: GroupWindow) {
let moved = new Set<GroupWindow>();
let boundsChanging = false;
let interval: any;
let payloadCache: RectangleBase[] = [];
if (usesDisabledFrameEvents(win)) {
win.browserWindow.setUserMovementEnabled(false);
}
const handleEndBoundsChanging = (changeType: ChangeType) => {
// Emit expected events that aren't automatically emitted
moved.forEach((movedWin) => {
const isLeader = movedWin === win;
if (!isLeader || win.isExternalWindow) {
// bounds-changed is emitted for the leader, but not other windows
emitChange('bounds-changed', movedWin, changeType, 'group');
}
});
// Reset map of moved windows and flags for native windows and mac OS
boundsChanging = false;
payloadCache = [];
clearInterval(interval);
interval = null;
moved = new Set<GroupWindow>();
};
const handleBoundsChanging = (e: any, rawPayloadBounds: RectangleBase, changeType: ChangeType) => {
try {
e.preventDefault();
if (isWin32) {
// Use externalWindow static methods to remove the framed offset for Win10 windows
const adjustedBounds: any = (<any>ExternalWindow).removeShadow(win.browserWindow.nativeId, rawPayloadBounds);
rawPayloadBounds = Rectangle.CREATE_FROM_BOUNDS(adjustedBounds);
}
const moves = generateWindowMoves(win, rawPayloadBounds, changeType);
// Keep track of which windows have moved in order to emit events
moves.forEach(({ofWin}) => moved.add(ofWin));
if (!boundsChanging) {
boundsChanging = true;
const endingEvent = isWin32 ? 'end-user-bounds-change' : 'disabled-frame-bounds-changed';
win.browserWindow.once(endingEvent, handleEndBoundsChanging);
WindowGroups.getGroup(win.groupUuid).forEach(win => win.browserWindow.bringToFront());
}
if (moves.length) {
// bounds-changing is not emitted for the leader, but is for the other windows
const leaderMove = moves.find(({ofWin}) => ofWin.uuid === win.uuid && ofWin.name === win.name);
if (leaderMove && typeof leaderMove === 'object') {
// Execute the actual move
handleBatchedMove(moves);
emitChange('bounds-changing', win, changeType, 'self');
}
}
} catch (error) {
writeToLog('error', error);
}
};
const setupInterval = (changeType: ChangeType, raiseBeginEventBounds?: RectangleBase) => {
interval = setInterval(() => {
if (payloadCache.length) {
const bounds = payloadCache.pop();
// tslint:disable-next-line:no-empty - need to mock prevent default
handleBoundsChanging({preventDefault: () => {}}, bounds, changeType);
payloadCache = [];
}
}, 30);
if (raiseBeginEventBounds) {
raiseEvent(win, 'begin-user-bounds-changing', { ...raiseBeginEventBounds, windowState: 'normal' });
}
};
const moveListener = (e: any, rawBounds: RectangleBase) => handleBoundsChanging(e, rawBounds, ChangeType.POSITION);
const resizeListener = (e: any, rawBounds: RectangleBase) => handleBoundsChanging(e, rawBounds, ChangeType.SIZE);
const restoreListener = () => WindowGroups.getGroup(win.groupUuid).forEach(({browserWindow}) => restore(browserWindow));
const disabledFrameListener = (e: any, rawBounds: RectangleBase, changeType: ChangeType) => {
payloadCache.push(rawBounds);
// Setup an interval to get around aero-shake issues in native external windows
if (!interval) {
changeType = changeType !== ChangeType.POSITION_AND_SIZE ? changeType : ChangeType.SIZE;
setupInterval(changeType, rawBounds);
}
};
if (usesDisabledFrameEvents(win)) {
win.browserWindow.on('disabled-frame-bounds-changing', disabledFrameListener);
listenerCache.set(win.browserWindow.nativeId, [disabledFrameListener]);
} else {
win.browserWindow.on('will-move', moveListener);
win.browserWindow.on('will-resize', resizeListener);
win.browserWindow.on('begin-user-bounds-change', restoreListener);
listenerCache.set(win.browserWindow.nativeId, [moveListener, resizeListener, restoreListener]);
}
}
export function removeWindowFromGroup(win: GroupWindow) {
const winId = win.browserWindow.nativeId;
if (!win.browserWindow.isDestroyed()) {
const listeners = listenerCache.get(winId);
if (usesDisabledFrameEvents(win)) {
win.browserWindow.removeListener('disabled-frame-bounds-changing', listeners[0]);
win.browserWindow.setUserMovementEnabled(true);
} else {
win.browserWindow.removeListener('will-move', listeners[0]);
win.browserWindow.removeListener('will-resize', listeners[1]);
win.browserWindow.removeListener('begin-user-bounds-change', listeners[2]);
}
}
listenerCache.delete(winId);
} | the_stack |
import * as ts from "typescript";
import * as lua from "../../LuaAST";
import { assert, getOrUpdate, isNonNull } from "../../utils";
import { TransformationContext } from "../context";
import { getSymbolInfo } from "./symbols";
import { findFirstNodeAbove, getFirstDeclarationInFile } from "./typescript";
export enum ScopeType {
File = 1 << 0,
Function = 1 << 1,
Switch = 1 << 2,
Loop = 1 << 3,
Conditional = 1 << 4,
Block = 1 << 5,
Try = 1 << 6,
Catch = 1 << 7,
}
interface FunctionDefinitionInfo {
referencedSymbols: Map<lua.SymbolId, ts.Node[]>;
definition?: lua.VariableDeclarationStatement | lua.AssignmentStatement;
}
export interface Scope {
type: ScopeType;
id: number;
node?: ts.Node;
referencedSymbols?: Map<lua.SymbolId, ts.Node[]>;
variableDeclarations?: lua.VariableDeclarationStatement[];
functionDefinitions?: Map<lua.SymbolId, FunctionDefinitionInfo>;
importStatements?: lua.Statement[];
loopContinued?: boolean;
functionReturned?: boolean;
}
export interface HoistingResult {
statements: lua.Statement[];
hoistedStatements: lua.Statement[];
hoistedIdentifiers: lua.Identifier[];
}
const scopeStacks = new WeakMap<TransformationContext, Scope[]>();
function getScopeStack(context: TransformationContext): Scope[] {
return getOrUpdate(scopeStacks, context, () => []);
}
export function* walkScopesUp(context: TransformationContext): IterableIterator<Scope> {
const scopeStack = getScopeStack(context);
for (let i = scopeStack.length - 1; i >= 0; --i) {
const scope = scopeStack[i];
yield scope;
}
}
export function markSymbolAsReferencedInCurrentScopes(
context: TransformationContext,
symbolId: lua.SymbolId,
identifier: ts.Identifier
): void {
for (const scope of getScopeStack(context)) {
if (!scope.referencedSymbols) {
scope.referencedSymbols = new Map();
}
const references = getOrUpdate(scope.referencedSymbols, symbolId, () => []);
references.push(identifier);
}
}
export function peekScope(context: TransformationContext): Scope {
const scopeStack = getScopeStack(context);
const scope = scopeStack[scopeStack.length - 1];
assert(scope);
return scope;
}
export function findScope(context: TransformationContext, scopeTypes: ScopeType): Scope | undefined {
return [...getScopeStack(context)].reverse().find(s => scopeTypes & s.type);
}
const scopeIdCounters = new WeakMap<TransformationContext, number>();
export function pushScope(context: TransformationContext, scopeType: ScopeType): Scope {
const nextScopeId = (scopeIdCounters.get(context) ?? 0) + 1;
scopeIdCounters.set(context, nextScopeId);
const scopeStack = getScopeStack(context);
const scope: Scope = { type: scopeType, id: nextScopeId };
scopeStack.push(scope);
return scope;
}
export function popScope(context: TransformationContext): Scope {
const scopeStack = getScopeStack(context);
const scope = scopeStack.pop();
assert(scope);
return scope;
}
function isHoistableFunctionDeclaredInScope(symbol: ts.Symbol, scopeNode: ts.Node) {
return symbol?.declarations?.some(
d => ts.isFunctionDeclaration(d) && findFirstNodeAbove(d, (n): n is ts.Node => n === scopeNode)
);
}
// Checks for references to local functions which haven't been defined yet,
// and thus will be hoisted above the current position.
export function hasReferencedUndefinedLocalFunction(context: TransformationContext, scope: Scope) {
if (!scope.referencedSymbols || !scope.node) {
return false;
}
for (const [symbolId, nodes] of scope.referencedSymbols) {
const type = context.checker.getTypeAtLocation(nodes[0]);
if (
!scope.functionDefinitions?.has(symbolId) &&
type.getCallSignatures().length > 0 &&
isHoistableFunctionDeclaredInScope(type.symbol, scope.node)
) {
return true;
}
}
return false;
}
export function hasReferencedSymbol(context: TransformationContext, scope: Scope, symbol: ts.Symbol) {
if (!scope.referencedSymbols) {
return;
}
for (const nodes of scope.referencedSymbols.values()) {
if (nodes.some(node => context.checker.getSymbolAtLocation(node) === symbol)) {
return true;
}
}
return false;
}
export function isFunctionScopeWithDefinition(scope: Scope): scope is Scope & { node: ts.SignatureDeclaration } {
return scope.node !== undefined && ts.isFunctionLike(scope.node);
}
export function separateHoistedStatements(context: TransformationContext, statements: lua.Statement[]): HoistingResult {
const scope = peekScope(context);
const allHoistedStatments: lua.Statement[] = [];
const allHoistedIdentifiers: lua.Identifier[] = [];
let { unhoistedStatements, hoistedStatements, hoistedIdentifiers } = hoistFunctionDefinitions(
context,
scope,
statements
);
allHoistedStatments.push(...hoistedStatements);
allHoistedIdentifiers.push(...hoistedIdentifiers);
({ unhoistedStatements, hoistedIdentifiers } = hoistVariableDeclarations(context, scope, unhoistedStatements));
allHoistedIdentifiers.push(...hoistedIdentifiers);
({ unhoistedStatements, hoistedStatements } = hoistImportStatements(scope, unhoistedStatements));
allHoistedStatments.unshift(...hoistedStatements);
return {
statements: unhoistedStatements,
hoistedStatements: allHoistedStatments,
hoistedIdentifiers: allHoistedIdentifiers,
};
}
export function performHoisting(context: TransformationContext, statements: lua.Statement[]): lua.Statement[] {
const result = separateHoistedStatements(context, statements);
const modifiedStatements = [...result.hoistedStatements, ...result.statements];
if (result.hoistedIdentifiers.length > 0) {
modifiedStatements.unshift(lua.createVariableDeclarationStatement(result.hoistedIdentifiers));
}
return modifiedStatements;
}
function shouldHoistSymbol(context: TransformationContext, symbolId: lua.SymbolId, scope: Scope): boolean {
// Always hoist in top-level of switch statements
if (scope.type === ScopeType.Switch) {
return true;
}
const symbolInfo = getSymbolInfo(context, symbolId);
if (!symbolInfo) {
return false;
}
const declaration = getFirstDeclarationInFile(symbolInfo.symbol, context.sourceFile);
if (!declaration) {
return false;
}
if (symbolInfo.firstSeenAtPos < declaration.pos) {
return true;
}
if (scope.functionDefinitions) {
for (const [functionSymbolId, functionDefinition] of scope.functionDefinitions) {
assert(functionDefinition.definition);
const { line, column } = lua.getOriginalPos(functionDefinition.definition);
if (line !== undefined && column !== undefined) {
const definitionPos = ts.getPositionOfLineAndCharacter(context.sourceFile, line, column);
if (
functionSymbolId !== symbolId && // Don't recurse into self
declaration.pos < definitionPos && // Ignore functions before symbol declaration
functionDefinition.referencedSymbols.has(symbolId) &&
shouldHoistSymbol(context, functionSymbolId, scope)
) {
return true;
}
}
}
}
return false;
}
function hoistVariableDeclarations(
context: TransformationContext,
scope: Scope,
statements: lua.Statement[]
): { unhoistedStatements: lua.Statement[]; hoistedIdentifiers: lua.Identifier[] } {
if (!scope.variableDeclarations) {
return { unhoistedStatements: statements, hoistedIdentifiers: [] };
}
const unhoistedStatements = [...statements];
const hoistedIdentifiers: lua.Identifier[] = [];
for (const declaration of scope.variableDeclarations) {
const symbols = declaration.left.map(i => i.symbolId).filter(isNonNull);
if (symbols.some(s => shouldHoistSymbol(context, s, scope))) {
const index = unhoistedStatements.indexOf(declaration);
if (index < 0) {
continue; // statements array may not contain all statements in the scope (switch-case)
}
if (declaration.right) {
const assignment = lua.createAssignmentStatement(declaration.left, declaration.right);
lua.setNodePosition(assignment, declaration); // Preserve position info for sourcemap
unhoistedStatements.splice(index, 1, assignment);
} else {
unhoistedStatements.splice(index, 1);
}
hoistedIdentifiers.push(...declaration.left);
}
}
return { unhoistedStatements, hoistedIdentifiers };
}
function hoistFunctionDefinitions(
context: TransformationContext,
scope: Scope,
statements: lua.Statement[]
): { unhoistedStatements: lua.Statement[]; hoistedStatements: lua.Statement[]; hoistedIdentifiers: lua.Identifier[] } {
if (!scope.functionDefinitions) {
return { unhoistedStatements: statements, hoistedStatements: [], hoistedIdentifiers: [] };
}
const unhoistedStatements = [...statements];
const hoistedStatements: lua.Statement[] = [];
const hoistedIdentifiers: lua.Identifier[] = [];
for (const [functionSymbolId, functionDefinition] of scope.functionDefinitions) {
assert(functionDefinition.definition);
if (shouldHoistSymbol(context, functionSymbolId, scope)) {
const index = unhoistedStatements.indexOf(functionDefinition.definition);
if (index < 0) {
continue; // statements array may not contain all statements in the scope (switch-case)
}
unhoistedStatements.splice(index, 1);
if (lua.isVariableDeclarationStatement(functionDefinition.definition)) {
// Separate function definition and variable declaration
assert(functionDefinition.definition.right);
hoistedIdentifiers.push(...functionDefinition.definition.left);
hoistedStatements.push(
lua.createAssignmentStatement(
functionDefinition.definition.left,
functionDefinition.definition.right
)
);
} else {
hoistedStatements.push(functionDefinition.definition);
}
}
}
return { unhoistedStatements, hoistedStatements, hoistedIdentifiers };
}
function hoistImportStatements(
scope: Scope,
statements: lua.Statement[]
): { unhoistedStatements: lua.Statement[]; hoistedStatements: lua.Statement[] } {
return { unhoistedStatements: statements, hoistedStatements: scope.importStatements ?? [] };
} | the_stack |
import test from "ava";
import { anyoneCanPay } from "../src";
import { CellProvider } from "./cell_provider";
import {
TransactionSkeletonType,
TransactionSkeleton,
minimalCellCapacity,
} from "@ckb-lumos/helpers";
import { predefined } from "@ckb-lumos/config-manager";
import { bob, alice } from "./account_info";
import { bobAcpCells, aliceAcpCells } from "./inputs";
import { Cell, values } from "@ckb-lumos/base";
const { AGGRON4 } = predefined;
import { checkLimit } from "../src/anyone_can_pay";
test("withdraw, acp to acp, all", async (t) => {
const cellProvider = new CellProvider([bobAcpCells[0], aliceAcpCells[0]]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
txSkeleton = await anyoneCanPay.withdraw(
txSkeleton,
bobAcpCells[0],
alice.acpTestnetAddress,
BigInt(1000 * 10 ** 8),
{ config: AGGRON4 }
);
// sum of outputs capacity should be equal to sum of inputs capacity
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapacity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfOutputCapacity, sumOfInputCapacity);
t.is(txSkeleton.get("cellDeps").size, 1);
t.is(
txSkeleton.get("cellDeps").get(0)!.out_point.tx_hash,
AGGRON4.SCRIPTS.ANYONE_CAN_PAY!.TX_HASH
);
t.is(txSkeleton.get("headerDeps").size, 0);
t.is(txSkeleton.get("inputs").size, 2);
t.is(txSkeleton.get("outputs").size, 1);
t.deepEqual(
txSkeleton
.get("inputs")
.map((i) => i.cell_output.lock.args)
.toArray(),
[alice.blake160, bob.blake160]
);
t.deepEqual(
txSkeleton
.get("outputs")
.map((o) => o.cell_output.lock.args)
.toArray(),
[alice.blake160]
);
t.is(txSkeleton.get("witnesses").size, 2);
t.is(txSkeleton.get("witnesses").get(0), "0x");
txSkeleton = anyoneCanPay.prepareSigningEntries(txSkeleton, {
config: AGGRON4,
});
t.is(txSkeleton.get("signingEntries").size, 1);
const expectedMessage =
"0xf862243671a339a33e5843877e88e640f848b6f2394a3995bc00b44bf9d19d4e";
t.is(txSkeleton.get("signingEntries").get(0)!.message, expectedMessage);
});
test("withdraw, acp to acp, half", async (t) => {
const cellProvider = new CellProvider([...bobAcpCells, ...aliceAcpCells]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const capacity = BigInt(500 * 10 ** 8);
txSkeleton = await anyoneCanPay.withdraw(
txSkeleton,
bobAcpCells[0],
alice.acpTestnetAddress,
capacity,
{ config: AGGRON4 }
);
// sum of outputs capacity should be equal to sum of inputs capacity
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapacity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfOutputCapacity, sumOfInputCapacity);
t.is(txSkeleton.get("cellDeps").size, 1);
t.is(
txSkeleton.get("cellDeps").get(0)!.out_point.tx_hash,
AGGRON4.SCRIPTS.ANYONE_CAN_PAY!.TX_HASH
);
t.is(txSkeleton.get("headerDeps").size, 0);
t.is(txSkeleton.get("inputs").size, 2);
t.is(txSkeleton.get("outputs").size, 2);
t.deepEqual(
txSkeleton
.get("inputs")
.map((i) => i.cell_output.lock.args)
.toArray(),
[alice.blake160, bob.blake160]
);
t.deepEqual(
txSkeleton
.get("outputs")
.map((o) => o.cell_output.lock.args)
.toArray(),
[alice.blake160, bob.blake160]
);
const aliceReceiveCapacity: bigint =
BigInt(txSkeleton.get("outputs").get(0)!.cell_output.capacity) -
BigInt(txSkeleton.get("inputs").get(0)!.cell_output.capacity);
t.is(aliceReceiveCapacity, capacity);
t.is(txSkeleton.get("witnesses").size, 2);
t.is(txSkeleton.get("witnesses").get(0), "0x");
txSkeleton = anyoneCanPay.prepareSigningEntries(txSkeleton, {
config: AGGRON4,
});
t.is(txSkeleton.get("signingEntries").size, 1);
const expectedMessage =
"0x5acf7d234fc5c9adbc9b01f4938a5efdf6efde2b0a836f4740e6a79f81b64d65";
t.is(txSkeleton.get("signingEntries").get(0)!.message, expectedMessage);
});
test("withdraw, acp to secp, half", async (t) => {
const cellProvider = new CellProvider([...bobAcpCells, ...aliceAcpCells]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const capacity = BigInt(500 * 10 ** 8);
txSkeleton = await anyoneCanPay.withdraw(
txSkeleton,
bobAcpCells[0],
alice.testnetAddress,
capacity,
{ config: AGGRON4 }
);
// sum of outputs capacity should be equal to sum of inputs capacity
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapacity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfOutputCapacity, sumOfInputCapacity);
t.is(txSkeleton.get("cellDeps").size, 1);
t.is(
txSkeleton.get("cellDeps").get(0)!.out_point.tx_hash,
AGGRON4.SCRIPTS.ANYONE_CAN_PAY!.TX_HASH
);
t.is(txSkeleton.get("headerDeps").size, 0);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 2);
t.deepEqual(
txSkeleton
.get("inputs")
.map((i) => i.cell_output.lock.args)
.toArray(),
[bob.blake160]
);
t.deepEqual(
txSkeleton
.get("outputs")
.map((o) => o.cell_output.lock.args)
.toArray(),
[alice.blake160, bob.blake160]
);
const aliceReceiveCapacity: bigint = BigInt(
txSkeleton.get("outputs").get(0)!.cell_output.capacity
);
t.is(aliceReceiveCapacity, capacity);
t.is(txSkeleton.get("witnesses").size, 1);
t.is(
txSkeleton.get("witnesses").get(0),
"0x55000000100000005500000055000000410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
);
txSkeleton = anyoneCanPay.prepareSigningEntries(txSkeleton, {
config: AGGRON4,
});
t.is(txSkeleton.get("signingEntries").size, 1);
const expectedMessage =
"0x554307c4b5858beed7c655b3b7a5537492f532a99ef419df59c94ac7f9347e8e";
t.is(txSkeleton.get("signingEntries").get(0)!.message, expectedMessage);
});
test("withdraw, acp to secp, all", async (t) => {
const cellProvider = new CellProvider([...bobAcpCells, ...aliceAcpCells]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const capacity = BigInt(1000 * 10 ** 8);
txSkeleton = await anyoneCanPay.withdraw(
txSkeleton,
bobAcpCells[0],
alice.testnetAddress,
capacity,
{ config: AGGRON4 }
);
// sum of outputs capacity should be equal to sum of inputs capacity
const sumOfInputCapacity = txSkeleton
.get("inputs")
.map((i) => BigInt(i.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
const sumOfOutputCapacity = txSkeleton
.get("outputs")
.map((o) => BigInt(o.cell_output.capacity))
.reduce((result, c) => result + c, BigInt(0));
t.is(sumOfOutputCapacity, sumOfInputCapacity);
t.is(txSkeleton.get("cellDeps").size, 1);
t.is(
txSkeleton.get("cellDeps").get(0)!.out_point.tx_hash,
AGGRON4.SCRIPTS.ANYONE_CAN_PAY!.TX_HASH
);
t.is(txSkeleton.get("headerDeps").size, 0);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 1);
t.deepEqual(
txSkeleton
.get("inputs")
.map((i) => i.cell_output.lock.args)
.toArray(),
[bob.blake160]
);
t.deepEqual(
txSkeleton
.get("outputs")
.map((o) => o.cell_output.lock.args)
.toArray(),
[alice.blake160]
);
const aliceReceiveCapacity: bigint = BigInt(
txSkeleton.get("outputs").get(0)!.cell_output.capacity
);
t.is(aliceReceiveCapacity, capacity);
t.is(txSkeleton.get("witnesses").size, 1);
t.is(
txSkeleton.get("witnesses").get(0),
"0x55000000100000005500000055000000410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
);
txSkeleton = anyoneCanPay.prepareSigningEntries(txSkeleton, {
config: AGGRON4,
});
t.is(txSkeleton.get("signingEntries").size, 1);
const expectedMessage =
"0x1cb8e323da40058080ddd386ab0f6e62b793abacf68fd3da835273dd0e278c25";
t.is(txSkeleton.get("signingEntries").get(0)!.message, expectedMessage);
});
test("withdraw, acp to secp, greater than capacity - minimal", async (t) => {
const cellProvider = new CellProvider([...bobAcpCells, ...aliceAcpCells]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const bobCell = bobAcpCells[0]!;
const capacity =
BigInt(bobCell.cell_output.capacity) -
minimalCellCapacity(bobCell) +
BigInt(1);
await t.throwsAsync(
async () => {
await anyoneCanPay.withdraw(
txSkeleton,
bobCell,
alice.testnetAddress,
capacity,
{ config: AGGRON4 }
);
},
null,
"capacity must be in [0, 93900000000] or 100000000000 !"
);
});
test("setupInputCell", async (t) => {
const cellProvider = new CellProvider([...bobAcpCells, ...aliceAcpCells]);
let txSkeleton: TransactionSkeletonType = TransactionSkeleton({
cellProvider,
});
const inputCell: Cell = bobAcpCells[0];
txSkeleton = await anyoneCanPay.setupInputCell(
txSkeleton,
inputCell,
bob.testnetAddress,
{
config: AGGRON4,
}
);
t.is(txSkeleton.get("inputs").size, 1);
t.is(txSkeleton.get("outputs").size, 1);
t.is(txSkeleton.get("witnesses").size, 1);
const input: Cell = txSkeleton.get("inputs").get(0)!;
const output: Cell = txSkeleton.get("outputs").get(0)!;
t.is(input.cell_output.capacity, output.cell_output.capacity);
t.is(input.data, output.data);
t.true(
new values.ScriptValue(input.cell_output.lock, { validate: false }).equals(
new values.ScriptValue(output.cell_output.lock, { validate: false })
)
);
t.true(
(!input.cell_output.type && !output.cell_output.type) ||
new values.ScriptValue(input.cell_output.type!, {
validate: false,
}).equals(
new values.ScriptValue(output.cell_output.type!, { validate: false })
)
);
});
test("checkLimit, amount and capacity", (t) => {
const args = bob.blake160 + "01" + "02";
t.throws(() => checkLimit(args, BigInt(0)));
t.throws(() => checkLimit(args, BigInt(10 * 10 ** 8 - 1)));
t.notThrows(() => checkLimit(args, BigInt(10 * 10 ** 8)));
});
test("checkLimit, only capacity", (t) => {
const args = bob.blake160 + "01";
t.throws(() => checkLimit(args, BigInt(0)));
t.throws(() => checkLimit(args, BigInt(10 * 10 ** 8 - 1)));
t.notThrows(() => checkLimit(args, BigInt(10 * 10 ** 8)));
});
test("checkLimit, no limit", (t) => {
const args = bob.blake160;
t.notThrows(() => checkLimit(args, BigInt(0)));
}); | the_stack |
import { LoanMasterNodeRegTestContainer } from './loan_container'
import { GenesisKeys } from '@defichain/testcontainers'
import BigNumber from 'bignumber.js'
import { TestingGroup } from '@defichain/jellyfish-testing'
import { RpcApiError } from '@defichain/jellyfish-api-core'
import { VaultActive } from 'packages/jellyfish-api-core/src/category/loan'
describe('Loan', () => {
const tGroup = TestingGroup.create(3, i => new LoanMasterNodeRegTestContainer(GenesisKeys[i]))
let vaultId1!: string // without loan taken
let vaultId2: string // single collateral, with loan taken, test: loan:collateral ratio
let vaultId3: string // dual collateral, with loan taken, test: liquidated vault, DFI/total collateral ratio
let collateralAddress!: string
let vaultOwner!: string
let oracleId!: string
let oracleTickTimestamp!: number
beforeAll(async () => {
await tGroup.start()
await tGroup.get(0).container.waitForWalletCoinbaseMaturity()
await setup()
})
afterAll(async () => {
await tGroup.stop()
})
async function setup (): Promise<void> {
// token setup
collateralAddress = await tGroup.get(0).container.getNewAddress()
await tGroup.get(0).token.dfi({ address: collateralAddress, amount: 30000 })
await tGroup.get(0).generate(1)
await tGroup.get(0).token.create({ symbol: 'BTC', collateralAddress })
await tGroup.get(0).generate(1)
await tGroup.get(0).token.mint({ symbol: 'BTC', amount: 20000 })
await tGroup.get(0).generate(1)
// oracle setup
const addr = await tGroup.get(0).generateAddress()
const priceFeeds = [
{ token: 'DFI', currency: 'USD' },
{ token: 'BTC', currency: 'USD' },
{ token: 'TSLA', currency: 'USD' }
]
oracleId = await tGroup.get(0).rpc.oracle.appointOracle(addr, priceFeeds, { weightage: 1 })
await tGroup.get(0).generate(1)
oracleTickTimestamp = Math.floor(new Date().getTime() / 1000)
await tGroup.get(0).rpc.oracle.setOracleData(oracleId, oracleTickTimestamp, { prices: [{ tokenAmount: '1@DFI', currency: 'USD' }] })
await tGroup.get(0).rpc.oracle.setOracleData(oracleId, oracleTickTimestamp, { prices: [{ tokenAmount: '10000@BTC', currency: 'USD' }] })
await tGroup.get(0).rpc.oracle.setOracleData(oracleId, oracleTickTimestamp, { prices: [{ tokenAmount: '2@TSLA', currency: 'USD' }] })
await tGroup.get(0).generate(1)
// collateral token
await tGroup.get(0).rpc.loan.setCollateralToken({
token: 'DFI',
factor: new BigNumber(1),
fixedIntervalPriceId: 'DFI/USD'
})
await tGroup.get(0).generate(1)
await tGroup.get(0).rpc.loan.setCollateralToken({
token: 'BTC',
factor: new BigNumber(0.5),
fixedIntervalPriceId: 'BTC/USD'
})
await tGroup.get(0).generate(1)
// loan token
await tGroup.get(0).rpc.loan.setLoanToken({
symbol: 'TSLA',
fixedIntervalPriceId: 'TSLA/USD'
})
await tGroup.get(0).generate(1)
// loan scheme set up
await tGroup.get(0).rpc.loan.createLoanScheme({
minColRatio: 150,
interestRate: new BigNumber(3),
id: 'scheme'
})
await tGroup.get(0).generate(1)
vaultOwner = await tGroup.get(0).generateAddress()
{
// vault1: 2 types of collateral token, no loan taken
vaultId1 = await tGroup.get(0).rpc.loan.createVault({
ownerAddress: vaultOwner,
loanSchemeId: 'scheme'
})
await tGroup.get(0).generate(1)
await tGroup.get(0).rpc.loan.depositToVault({
vaultId: vaultId1, from: collateralAddress, amount: '10000@DFI'
})
await tGroup.get(0).generate(1)
await tGroup.get(0).rpc.loan.depositToVault({
vaultId: vaultId1, from: collateralAddress, amount: '1@BTC'
})
await tGroup.get(0).generate(1)
}
{
// vault2: single collateral token, loan taken, ease ratio control
vaultId2 = await tGroup.get(0).rpc.loan.createVault({
ownerAddress: await tGroup.get(0).generateAddress(),
loanSchemeId: 'scheme'
})
await tGroup.get(0).generate(1)
await tGroup.get(0).rpc.loan.depositToVault({
vaultId: vaultId2, from: collateralAddress, amount: '10000@DFI'
})
await tGroup.get(0).generate(1)
await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '2@TSLA', currency: 'USD' }] })
await tGroup.get(0).rpc.loan.takeLoan({
vaultId: vaultId2,
amounts: '100@TSLA'
})
await tGroup.get(0).generate(1)
}
{
// vault3: 2 types of collateral token, loan taken, to be liquidated
vaultId3 = await tGroup.get(0).rpc.loan.createVault({
ownerAddress: await tGroup.get(0).generateAddress(),
loanSchemeId: 'scheme'
})
await tGroup.get(0).generate(1)
await tGroup.get(0).rpc.loan.depositToVault({
vaultId: vaultId3, from: collateralAddress, amount: '10000@DFI'
})
await tGroup.get(0).generate(1)
await tGroup.get(0).rpc.loan.depositToVault({
vaultId: vaultId3, from: collateralAddress, amount: '1@BTC'
})
await tGroup.get(0).generate(1)
await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '2@TSLA', currency: 'USD' }] })
await tGroup.get(0).rpc.loan.takeLoan({
vaultId: vaultId3,
amounts: '100@TSLA'
})
await tGroup.get(0).generate(1)
}
await tGroup.waitForSync()
}
describe('success cases', () => {
it('should withdrawFromVault', async () => {
const anotherMn = tGroup.get(1)
const destinationAddress = await anotherMn.generateAddress()
{ // before
const accountBalances = await anotherMn.rpc.account.getAccount(destinationAddress)
expect(accountBalances.length).toStrictEqual(0)
const { collateralAmounts } = await tGroup.get(0).rpc.loan.getVault(vaultId1) as VaultActive
expect(collateralAmounts?.length).toStrictEqual(2)
{
const dfiCol = collateralAmounts?.find(c => c.includes('DFI'))
expect(dfiCol).toBeDefined()
const [amount, tokenSymbol] = (dfiCol as string).split('@')
expect(tokenSymbol).toStrictEqual('DFI')
expect(amount).toStrictEqual('10000.00000000')
}
{
const btcCol = collateralAmounts?.find(c => c.includes('BTC'))
expect(btcCol).toBeDefined()
const [amount, tokenSymbol] = (btcCol as string).split('@')
expect(tokenSymbol).toStrictEqual('BTC')
expect(amount).toStrictEqual('1.00000000')
}
}
await tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId1,
to: destinationAddress,
amount: '9.876@DFI'
})
await tGroup.get(0).generate(1)
await tGroup.waitForSync()
{ // after first withdrawal
const accountBalances = await tGroup.get(0).rpc.account.getAccount(destinationAddress)
expect(accountBalances.length).toStrictEqual(1)
expect(accountBalances[0]).toStrictEqual('9.87600000@DFI')
const { collateralAmounts } = await anotherMn.rpc.loan.getVault(vaultId1) as VaultActive
expect(collateralAmounts?.length).toStrictEqual(2)
{
const dfiCol = collateralAmounts?.find(c => c.includes('DFI'))
expect(dfiCol).toBeDefined()
const [amount, tokenSymbol] = (dfiCol as string).split('@')
expect(tokenSymbol).toStrictEqual('DFI')
expect(amount).toStrictEqual('9990.12400000')
}
{ // unchanged
const btcCol = collateralAmounts?.find(c => c.includes('BTC'))
expect(btcCol).toBeDefined()
const [amount, tokenSymbol] = (btcCol as string).split('@')
expect(tokenSymbol).toStrictEqual('BTC')
expect(amount).toStrictEqual('1.00000000')
}
}
await tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId1,
to: destinationAddress,
amount: '0.123@BTC'
})
await tGroup.get(0).generate(1)
await tGroup.waitForSync()
{ // after second withdrawal
const accountBalances = await anotherMn.rpc.account.getAccount(destinationAddress)
expect(accountBalances.length).toStrictEqual(2)
expect(accountBalances[0]).toStrictEqual('9.87600000@DFI')
expect(accountBalances[1]).toStrictEqual('0.12300000@BTC')
const { collateralAmounts } = await anotherMn.rpc.loan.getVault(vaultId1) as VaultActive
expect(collateralAmounts?.length).toStrictEqual(2)
{
const dfiCol = collateralAmounts?.find(c => c.includes('DFI'))
expect(dfiCol).toBeDefined()
const [amount, tokenSymbol] = (dfiCol as string).split('@')
expect(tokenSymbol).toStrictEqual('DFI')
expect(amount).toStrictEqual('9990.12400000')
}
{ // unchanged
const btcCol = collateralAmounts?.find(c => c.includes('BTC'))
expect(btcCol).toBeDefined()
const [amount, tokenSymbol] = (btcCol as string).split('@')
expect(tokenSymbol).toStrictEqual('BTC')
expect(amount).toStrictEqual('0.87700000')
}
}
})
it('should withdrawFromVault using specific utxo', async () => {
const destinationAddress = await tGroup.get(0).generateAddress()
const utxo = await tGroup.get(0).container.fundAddress(vaultOwner, 10)
const txid = await tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId1,
to: destinationAddress,
amount: '2.34567@DFI'
}, [utxo])
const rawtx = await tGroup.get(0).container.call('getrawtransaction', [txid, true])
expect(rawtx.vin[0].txid).toStrictEqual(utxo.txid)
expect(rawtx.vin[0].vout).toStrictEqual(utxo.vout)
await tGroup.get(0).generate(1)
const accountBalances = await tGroup.get(0).rpc.account.getAccount(destinationAddress)
expect(accountBalances.length).toStrictEqual(1)
expect(accountBalances[0]).toStrictEqual('2.34567000@DFI')
})
})
describe('fail cases', () => {
it('should not withdrawFromVault with invalid vaultId', async () => {
const promise = tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: '0'.repeat(64),
to: await tGroup.get(0).generateAddress(),
amount: '9.876@DFI'
})
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow(`Vault <${'0'.repeat(64)}> does not found`)
})
it('should not withdrawFromVault with invalid collateral token', async () => {
const promise = tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId1,
to: await tGroup.get(0).generateAddress(),
amount: '9.876@GOLD'
})
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('amount: Invalid Defi token: GOLD')
})
it('should not withdrawFromVault exceeded total collateral (no loan token)', async () => {
const promise = tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId1,
to: await tGroup.get(0).generateAddress(),
amount: '10000.00000001@DFI'
})
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow(`Collateral for vault <${vaultId1}> not found`)
})
it('should not withdrawFromVault cause DFI less than 50% of total collateral value', async () => {
const promise = tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId3,
to: await tGroup.get(0).generateAddress(),
amount: '6000@DFI' // $4000 of DFI vs $5000 of BTC (tested with 5001, do not work, there are extra margin)
})
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('At least 50% of the vault must be in DFI')
})
it('should not withdrawFromVault when DFI is already less than 50% of total collateral value', async () => {
{
// reduce DFI value to below 50%
await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '0.4999@DFI', currency: 'USD' }] })
await tGroup.get(0).generate(12)
}
const promise = tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId3,
to: await tGroup.get(0).generateAddress(),
amount: '1@DFI' // use small amount, no DFI can be withdrawn when below 50% of total
})
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('At least 50% of the vault must be in DFI')
{
// revert DFI value
await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '1@DFI', currency: 'USD' }] })
await tGroup.get(0).generate(12)
}
})
it('should not withdrawFromVault exceeded minCollateralRatio', async () => {
/**
* collateral = 10000 DFI = 10000 USD
* loan = 100 TSLA = 200 USD
* min collateral = 200 * 150% = 300
*/
const promise = tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId2,
to: await tGroup.get(0).generateAddress(),
amount: '99701@DFI'
})
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow(`Collateral for vault <${vaultId2}> not found`)
})
it('should not withdrawFromVault liquidated vault', async () => {
// trigger liquidation
// min collateral required = (10000 DFI * 1 USD/DFI + 1 BTC * 0.5 (col-factor) * 10000 USD/BTC) / 149.5% = 15000 / 1.495 = 10033.44... USD
await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '100.4@TSLA', currency: 'USD' }] })
await tGroup.get(0).generate(13)
const promise = tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId3,
to: await tGroup.get(0).generateAddress(),
amount: '0.00000001@DFI'
})
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('Cannot withdraw from vault under liquidation')
// stop liq, revert TSLA price to $2
await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '2@TSLA', currency: 'USD' }] })
// wait/ensure auction period to ended, 6 hr * * 60 min * 2 (blocks per min)
await tGroup.get(0).generate(6 * 6 * 2)
// success withdrawal after auction ended
await tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId3,
to: await tGroup.get(0).generateAddress(),
amount: '0.00000001@DFI'
})
})
it('should not withdrawFromVault when price is invalid', async () => {
// trigger liquidation
// min collateral required = (10000 DFI * 1 USD/DFI + 1 BTC * 0.5 (col-factor) * 10000 UDF/BTC) / 149.5% = 15000 / 1.495 = 10033.44... USD
await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), {
prices: [{
tokenAmount: `${2 * 5}@TSLA`, // bump price for 31%
currency: 'USD'
}]
})
await tGroup.get(0).generate(6)
const promise = tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId3,
to: await tGroup.get(0).generateAddress(),
amount: '0.00000001@DFI'
})
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('Cannot withdraw from vault while any of the asset\'s price is invalid')
})
it('should not withdrawFromVault without valid auth', async () => {
const promise = tGroup.get(1).rpc.loan.withdrawFromVault({
vaultId: vaultId1,
to: await tGroup.get(0).generateAddress(),
amount: '9.876@DFI'
})
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow(`Incorrect authorization for ${vaultOwner}`)
})
it('should not withdrawFromVault with not mine utxo', async () => {
const anotherMn = tGroup.get(1)
const utxo = await anotherMn.container.fundAddress(await anotherMn.generateAddress(), 10)
const promise = tGroup.get(0).rpc.loan.withdrawFromVault({
vaultId: vaultId1,
to: await tGroup.get(0).generateAddress(),
amount: '9.876@DFI'
}, [utxo])
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('Insufficient funds')
})
})
}) | the_stack |
import {
ACESFilmicToneMapping,
Camera,
Matrix4,
Object3D,
PCFSoftShadowMap,
PerspectiveCamera,
Quaternion,
Scene,
sRGBEncoding,
Vector3,
WebGLRenderer,
} from "three";
import { getReadObjectBufferView, TripleBufferBackedObjectBufferView } from "../allocator/ObjectBufferView";
import { swapReadBufferFlags, TripleBuffer } from "../allocator/TripleBuffer";
import { renderableSchema } from "../component/renderable.common";
import { clamp } from "../component/transform";
import { worldMatrixObjectBufferSchema } from "../component/transform.common";
import { tickRate } from "../config.common";
import { GLTFResourceLoader } from "../gltf/GLTFResourceLoader";
import { BaseThreadContext, defineModule, getModule, registerMessageHandler, Thread } from "../module/module.common";
import { CameraResourceLoader } from "../resources/CameraResourceLoader";
import { GeometryResourceLoader } from "../resources/GeometryResourceLoader";
import { LightResourceLoader } from "../resources/LightResourceLoader";
import { MaterialResourceLoader } from "../resources/MaterialResourceLoader";
import { MeshResourceLoader } from "../resources/MeshResourceLoader";
import {
createResourceManager,
createResourceManagerBuffer,
onAddResourceRef,
onLoadResource,
onRemoveResourceRef,
registerResourceLoader,
ResourceManager,
ResourceState,
} from "../resources/ResourceManager";
import { SceneResourceLoader } from "../resources/SceneResourceLoader";
import { TextureResourceLoader } from "../resources/TextureResourceLoader";
import { StatsBuffer } from "../stats/stats.common";
import { StatsModule } from "../stats/stats.render";
import {
AddRenderableMessage,
PostMessageTarget,
RemoveRenderableMessage,
RenderableMessages,
RenderWorkerResizeMessage,
SetActiveCameraMessage,
SetActiveSceneMessage,
WorkerMessageType,
} from "../WorkerMessage";
import {
InitializeCanvasMessage,
InitializeRendererTripleBuffersMessage,
RendererMessageType,
rendererModuleName,
} from "./renderer.common";
export interface TransformView {
worldMatrix: Float32Array[];
worldMatrixNeedsUpdate: Uint8Array;
}
export interface RenderableView {
resourceId: Uint32Array;
interpolate: Uint8Array;
visible: Uint8Array;
}
export interface Renderable {
object?: Object3D;
helper?: Object3D;
eid: number;
resourceId: number;
}
export type RenderThreadSystem = (state: RenderThreadState) => void;
export interface IInitialRenderThreadState {
statsBuffer: StatsBuffer;
resourceManagerBuffer: SharedArrayBuffer;
renderableTripleBuffer: TripleBuffer;
gameWorkerMessageTarget: MessagePort;
initialCanvasWidth: number;
initialCanvasHeight: number;
canvasTarget: HTMLElement;
}
export interface RenderThreadState extends BaseThreadContext {
canvas?: HTMLCanvasElement;
elapsed: number;
dt: number;
gameWorkerMessageTarget: PostMessageTarget;
gameToRenderTripleBufferFlags: Uint8Array;
}
interface RendererModuleState {
needsResize: boolean;
canvasWidth: number;
canvasHeight: number;
scene: Object3D;
camera: Camera;
renderer: WebGLRenderer;
resourceManager: ResourceManager;
renderableMessageQueue: RenderableMessages[];
renderables: Renderable[];
objectToEntityMap: Map<Object3D, number>;
renderableIndices: Map<number, number>;
renderableObjectTripleBuffer: TripleBufferBackedObjectBufferView<typeof renderableSchema, ArrayBuffer>;
worldMatrixObjectTripleBuffer: TripleBufferBackedObjectBufferView<typeof worldMatrixObjectBufferSchema, ArrayBuffer>;
}
export const RendererModule = defineModule<RenderThreadState, RendererModuleState>({
name: rendererModuleName,
async create(ctx, { sendMessage, waitForMessage }) {
const { canvasTarget, initialCanvasHeight, initialCanvasWidth } = await waitForMessage<InitializeCanvasMessage>(
Thread.Main,
RendererMessageType.InitializeCanvas
);
const scene = new Scene();
// TODO: initialize playerRig from GameWorker
const camera = new PerspectiveCamera(70, initialCanvasWidth / initialCanvasHeight, 0.1, 1000);
camera.position.y = 1.6;
const resourceManagerBuffer = createResourceManagerBuffer();
sendMessage(Thread.Game, RendererMessageType.InitializeResourceManager, {
resourceManagerBuffer,
});
const resourceManager = createResourceManager(resourceManagerBuffer);
registerResourceLoader(resourceManager, SceneResourceLoader);
registerResourceLoader(resourceManager, GeometryResourceLoader);
registerResourceLoader(resourceManager, TextureResourceLoader);
registerResourceLoader(resourceManager, MaterialResourceLoader);
registerResourceLoader(resourceManager, MeshResourceLoader);
registerResourceLoader(resourceManager, CameraResourceLoader);
registerResourceLoader(resourceManager, LightResourceLoader);
registerResourceLoader(resourceManager, GLTFResourceLoader);
const renderer = new WebGLRenderer({ antialias: true, canvas: canvasTarget || ctx.canvas });
renderer.toneMapping = ACESFilmicToneMapping;
renderer.toneMappingExposure = 1;
renderer.outputEncoding = sRGBEncoding;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = PCFSoftShadowMap;
renderer.setSize(initialCanvasWidth, initialCanvasHeight, false);
const { renderableObjectTripleBuffer, worldMatrixObjectTripleBuffer } =
await waitForMessage<InitializeRendererTripleBuffersMessage>(
Thread.Game,
RendererMessageType.InitializeRendererTripleBuffers
);
return {
scene,
camera,
needsResize: true,
renderer,
resourceManager,
canvasWidth: initialCanvasWidth,
canvasHeight: initialCanvasHeight,
renderableMessageQueue: [],
objectToEntityMap: new Map(),
renderables: [],
renderableIndices: new Map<number, number>(),
renderableObjectTripleBuffer,
worldMatrixObjectTripleBuffer,
};
},
init(ctx) {
registerMessageHandler(ctx, WorkerMessageType.RenderWorkerResize, onResize);
registerMessageHandler(ctx, WorkerMessageType.AddRenderable, onRenderableMessage);
registerMessageHandler(ctx, WorkerMessageType.RemoveRenderable, onRenderableMessage);
registerMessageHandler(ctx, WorkerMessageType.SetActiveCamera, onRenderableMessage);
registerMessageHandler(ctx, WorkerMessageType.SetActiveScene, onRenderableMessage);
registerMessageHandler(ctx, WorkerMessageType.LoadResource, onLoadResource as any);
registerMessageHandler(ctx, WorkerMessageType.AddResourceRef, onAddResourceRef);
registerMessageHandler(ctx, WorkerMessageType.RemoveResourceRef, onRemoveResourceRef);
},
});
export function startRenderLoop(state: RenderThreadState) {
const { renderer } = getModule(state, RendererModule);
renderer.setAnimationLoop(() => onUpdate(state));
}
const tempMatrix4 = new Matrix4();
const tempPosition = new Vector3();
const tempQuaternion = new Quaternion();
const tempScale = new Vector3();
function onUpdate(state: RenderThreadState) {
const bufferSwapped = swapReadBufferFlags(state.gameToRenderTripleBufferFlags);
const renderModule = getModule(state, RendererModule);
const {
needsResize,
renderer,
canvasWidth,
canvasHeight,
renderables,
scene,
camera,
renderableObjectTripleBuffer,
worldMatrixObjectTripleBuffer,
} = renderModule;
processRenderableMessages(state);
const now = performance.now();
const dt = (state.dt = now - state.elapsed);
state.elapsed = now;
const frameRate = 1 / dt;
const lerpAlpha = clamp(tickRate / frameRate, 0, 1);
const Transform = getReadObjectBufferView(worldMatrixObjectTripleBuffer);
const Renderable = getReadObjectBufferView(renderableObjectTripleBuffer);
renderableObjectTripleBuffer.views;
for (let i = 0; i < renderables.length; i++) {
const { object, helper, eid } = renderables[i];
if (!object) {
continue;
}
object.visible = !!Renderable.visible[eid];
if (!Transform.worldMatrixNeedsUpdate[eid]) {
continue;
}
if (Renderable.interpolate[eid]) {
tempMatrix4.fromArray(Transform.worldMatrix[eid]).decompose(tempPosition, tempQuaternion, tempScale);
object.position.lerp(tempPosition, lerpAlpha);
object.quaternion.slerp(tempQuaternion, lerpAlpha);
object.scale.lerp(tempScale, lerpAlpha);
if (helper) {
helper.position.copy(object.position);
helper.quaternion.copy(object.quaternion);
helper.scale.copy(object.scale);
}
} else {
tempMatrix4.fromArray(Transform.worldMatrix[eid]).decompose(object.position, object.quaternion, object.scale);
object.matrix.fromArray(Transform.worldMatrix[eid]);
object.matrixWorld.fromArray(Transform.worldMatrix[eid]);
object.matrixWorldNeedsUpdate = false;
if (helper) {
helper.position.copy(object.position);
helper.quaternion.copy(object.quaternion);
helper.scale.copy(object.scale);
}
}
}
if (needsResize && renderModule.camera.type === "PerspectiveCamera") {
const perspectiveCamera = renderModule.camera as PerspectiveCamera;
perspectiveCamera.aspect = canvasWidth / canvasHeight;
perspectiveCamera.updateProjectionMatrix();
renderer.setSize(canvasWidth, canvasHeight, false);
renderModule.needsResize = false;
}
renderer.render(scene, camera);
for (let i = 0; i < state.systems.length; i++) {
state.systems[i](state);
}
const stats = getModule(state, StatsModule);
if (bufferSwapped) {
if (stats.staleTripleBufferCounter > 1) {
stats.staleFrameCounter++;
}
stats.staleTripleBufferCounter = 0;
} else {
stats.staleTripleBufferCounter++;
}
}
function onResize(state: RenderThreadState, { canvasWidth, canvasHeight }: RenderWorkerResizeMessage) {
const renderer = getModule(state, RendererModule);
renderer.needsResize = true;
renderer.canvasWidth = canvasWidth;
renderer.canvasHeight = canvasHeight;
}
function onRenderableMessage(state: RenderThreadState, message: any) {
const { renderableMessageQueue } = getModule(state, RendererModule);
renderableMessageQueue.push(message);
}
function processRenderableMessages(state: RenderThreadState) {
const { renderableMessageQueue } = getModule(state, RendererModule);
while (renderableMessageQueue.length) {
const message = renderableMessageQueue.shift() as RenderableMessages;
switch (message.type) {
case WorkerMessageType.AddRenderable:
onAddRenderable(state, message);
break;
case WorkerMessageType.RemoveRenderable:
onRemoveRenderable(state, message);
break;
case WorkerMessageType.SetActiveCamera:
onSetActiveCamera(state, message);
break;
case WorkerMessageType.SetActiveScene:
onSetActiveScene(state, message);
break;
}
}
}
function onAddRenderable(state: RenderThreadState, message: AddRenderableMessage) {
const { resourceId, eid } = message;
const { renderableMessageQueue, renderableIndices, renderables, objectToEntityMap, scene, resourceManager } =
getModule(state, RendererModule);
let renderableIndex = renderableIndices.get(eid);
const resourceInfo = resourceManager.store.get(resourceId);
if (!resourceInfo) {
console.warn(`AddRenderable Error: Unknown resourceId ${resourceId} for eid ${eid}`);
return;
}
if (resourceInfo.state === ResourceState.Loaded) {
const object = resourceInfo.resource as Object3D;
if (renderableIndex !== undefined) {
// Replace an existing renderable on an entity if it changed
const removed = renderables.splice(renderableIndex, 1, { object, eid, resourceId });
if (removed.length > 0 && removed[0].object) {
// Remove the renderable object3D only if it exists
scene.remove(removed[0].object);
}
} else {
renderableIndex = renderables.length;
renderableIndices.set(eid, renderables.length);
renderables.push({ object, eid, resourceId });
objectToEntityMap.set(object, eid);
}
scene.add(object);
return;
}
if (resourceInfo.state === ResourceState.Loading) {
if (renderableIndex !== undefined) {
// Update the renderable with the new resource id and remove the old object
const removed = renderables.splice(renderableIndex, 1, { object: undefined, eid, resourceId });
if (removed.length > 0 && removed[0].object) {
// Remove the previous renderable object from the scene if it exists
scene.remove(removed[0].object);
}
} else {
renderableIndex = renderables.length;
renderableIndices.set(eid, renderables.length);
renderables.push({ object: undefined, eid, resourceId });
}
// Resources that are still loading should be re-queued when they finish loading.
resourceInfo.promise.finally(() => {
const index = renderableIndices.get(eid);
if (index === undefined || renderables[index].resourceId !== message.resourceId) {
// The resource was changed since it finished loading so avoid queueing it again
return;
}
renderableMessageQueue.push(message);
});
return;
}
console.warn(
`AddRenderable Error: resourceId ${resourceId} for eid ${eid} could not be loaded: ${resourceInfo.error}`
);
}
function onRemoveRenderable(state: RenderThreadState, { eid }: RemoveRenderableMessage) {
const { renderableIndices, renderables, objectToEntityMap, scene } = getModule(state, RendererModule);
const index = renderableIndices.get(eid);
if (index !== undefined) {
const removed = renderables.splice(index, 1);
renderableIndices.delete(eid);
if (removed.length > 0) {
const { object, helper } = removed[0];
if (object) {
scene.remove(object);
objectToEntityMap.delete(object);
}
if (helper) {
scene.remove(helper);
objectToEntityMap.delete(helper);
}
}
}
}
function onSetActiveScene(state: RenderThreadState, { eid, resourceId }: SetActiveSceneMessage) {
const rendererState = getModule(state, RendererModule);
const resourceInfo = rendererState.resourceManager.store.get(resourceId);
if (!resourceInfo) {
console.error(`SetActiveScene Error: Couldn't find resource ${resourceId} for scene ${eid}`);
return;
}
const setScene = (newScene: Scene) => {
for (const child of rendererState.scene.children) {
newScene.add(child);
}
rendererState.scene = newScene;
};
if (resourceInfo.resource) {
const newScene = resourceInfo.resource as Scene;
setScene(newScene);
} else {
resourceInfo.promise.then(({ resource }) => {
setScene(resource as Scene);
});
}
}
function onSetActiveCamera(state: RenderThreadState, { eid }: SetActiveCameraMessage) {
const renderModule = getModule(state, RendererModule);
const { renderableIndices, renderables } = renderModule;
const index = renderableIndices.get(eid);
if (index !== undefined && renderables[index]) {
const camera = renderables[index].object as Camera;
const perspectiveCamera = camera as PerspectiveCamera;
if (perspectiveCamera.isPerspectiveCamera) {
perspectiveCamera.aspect = renderModule.canvasWidth / renderModule.canvasHeight;
perspectiveCamera.updateProjectionMatrix();
}
renderModule.camera = camera;
}
} | the_stack |
import * as assert from 'assert';
import * as mockery from 'mockery';
import * as mocha from "mocha";
import { Server, SocketIO } from 'mock-socket';
import { LoggerMock } from '../helperMocks';
import { Target } from '../../src/protocols/target';
// As of 0.1.0, the included .d.ts is not in the right format to use the import syntax here
// https://github.com/florinn/typemoq/issues/4
// const typemoq: ITypeMoqStatic = require('typemoq');
import * as TypeMoq from "typemoq";
const MODULE_UNDER_TEST = '../../protocols/target';
function CreateTarget(): Target {
const target: Target = new ((require(MODULE_UNDER_TEST)).Target)();
return target;
}
suite('Proxy/Protocol/Target', () => {
const targetUrl = 'ws://localhost:8080';
const toolsUrl = 'ws://localhost:9090';
let loggerMock: TypeMoq.IMock<LoggerMock>
let targetServer: any;
let toolsServer: any;
let toolSocket: any;
let targetReady: Promise<void>;
let toolsReady: Promise<void>;
function setupTargetAndTools() {
toolSocket = new SocketIO(toolsUrl);
targetReady = new Promise<void>((resolve, reject) => {
targetServer.on('connection', server => {
server.emit('open');
resolve();
});
});
toolsReady = new Promise<void>((resolve, reject) => {
toolSocket.on('connect', () => {
resolve();
});
});
}
setup(() => {
mockery.enable({ useCleanCache: true, warnOnReplace: false, warnOnUnregistered: false });
mockery.registerMock('ws', SocketIO);
// The mock websocket class does not have all the necessary functions to mock.
// SocketIO has most of them minus the OPEN/CLOSED boolean. We only care about OPEN so lets just add this functionality on here.
SocketIO.OPEN = 1;
loggerMock = TypeMoq.Mock.ofType(LoggerMock, TypeMoq.MockBehavior.Loose);
mockery.registerMock('../../shell/logger', { Logger: loggerMock.object });
targetServer = new Server(targetUrl);
toolsServer = new Server(toolsUrl);
toolsServer.on('connection', server => {
server.emit('open');
});
});
teardown(() => {
mockery.deregisterAll();
mockery.disable();
loggerMock.verifyAll();
targetServer.stop();
toolsServer.stop();
});
suite('connectTo()', () => {
test('establishes a connection to the real target websocket', (done) => {
targetServer.on('connection', server => {
done();
});
const target = CreateTarget();
target.connectTo(targetUrl, null);
});
test('buffers messages to target before connect and then sends them on connect', (done) => {
const target = CreateTarget();
const newToolSocket = new SocketIO(toolsUrl);
newToolSocket.on('connect', () => {
target.connectTo(targetUrl, newToolSocket);
let messages = ['test', 'test2'];
let receivedCount = 0;
messages.forEach((i) => {
target.on(`tools::${i}`, () => {
receivedCount++;
if (receivedCount === messages.length) {
done();
}
});
target.forward(JSON.stringify({ method: i }));
});
assert.equal(receivedCount, 0, 'tools should not have received a message before connecting');
// Establish the target connection now
targetServer.on('connection', server => {
server.emit('open');
});
});
});
});
suite('forward()', () => {
setup(() => {
setupTargetAndTools();
});
test('emits message from tools to target', (done) => {
const target = CreateTarget();
Promise.all([targetReady, toolsReady]).then(() => {
let messageEmitted = false;
target.on('tools::test', () => {
messageEmitted = true;
});
targetServer.on('message', () => {
assert.equal(messageEmitted, true, 'message should have been emitted by the target');
done();
});
target.forward(JSON.stringify({ method: 'test' }));
});
target.connectTo(targetUrl, toolSocket);
});
test('emits message from target to tools', (done) => {
const target = CreateTarget();
Promise.all([targetReady, toolsReady]).then(() => {
let messageEmitted = false;
target.on('target::test', () => {
messageEmitted = true;
});
toolsServer.on('message', () => {
assert.equal(messageEmitted, true, 'message should have been emitted by the target');
done();
});
targetServer.emit('message', JSON.stringify({ method: 'test' }));
});
target.connectTo(targetUrl, toolSocket);
});
});
suite('fireEventToTools()', () => {
setup(() => {
setupTargetAndTools();
});
test('sends the correct data format', (done) => {
const target = CreateTarget();
Promise.all([targetReady, toolsReady]).then(() => {
const expectedMethod = 'testEventName';
const expectedParams = { someParam: true, more: { name: 'test', value: 1 } };
toolsServer.on('message', (msg) => {
const data = JSON.parse(msg);
assert.equal(data.method, expectedMethod, 'message.method should match what was fired');
assert.deepEqual(data.params, expectedParams, 'message.params should match what was fired');
done();
});
target.fireEventToTools(expectedMethod, expectedParams);
});
target.connectTo(targetUrl, toolSocket);
});
});
suite('fireResultToTools()', () => {
setup(() => {
setupTargetAndTools();
});
test('sends the correct data format', (done) => {
const target = CreateTarget();
Promise.all([targetReady, toolsReady]).then(() => {
const expectedId = 102;
const expectedResult = { method: 'css.Enable', someParam: true, more: { name: 'test', value: 1 } };
toolsServer.on('message', (msg) => {
const data = JSON.parse(msg);
assert.equal(data.id, expectedId, 'message.id should match what was fired');
assert.deepEqual(data.result, expectedResult, 'message.result should match what was fired');
done();
});
target.fireResultToTools(expectedId, expectedResult);
});
target.connectTo(targetUrl, toolSocket);
});
});
suite('callTarget()', () => {
setup(() => {
setupTargetAndTools();
});
test('sends a request to the target without calling back to the tools', (done) => {
const target = CreateTarget();
toolsServer.on('message', () => {
assert.fail('the adapter calling the target should not have sent a message to the tools', '', '', '');
});
target.on('target::Debugger.Enable', () => {
assert.fail('the adapter calling the target should not have emitted an event, it should resolve the promise instead', '', '', '');
});
Promise.all([targetReady, toolsReady]).then(() => {
const expectedMethod = 'Debugger.Enable';
const expectedParams = { someParam: true, more: { name: 'test', value: 1 } };
const expectedResponse = { id: 0, result: expectedParams };
targetServer.on('message', (msg) => {
const data = JSON.parse(msg);
assert.equal(data.method, expectedMethod, 'message.method should match what was fired');
assert.deepEqual(data.params, expectedParams, 'message.params should match what was fired');
expectedResponse.id = data.id;
targetServer.emit('message', JSON.stringify(expectedResponse));
});
target.callTarget(expectedMethod, expectedParams).then((result) => {
assert.deepEqual(result, expectedParams, 'result should match what was returned from the target server');
done();
});
});
target.connectTo(targetUrl, toolSocket);
});
test('rejects the promise on an error from the target', (done) => {
const target = CreateTarget();
Promise.all([targetReady, toolsReady]).then(() => {
const expectedError = { someErrorProperty: 'yes', moreInfo: { test: 1, pokemon: true } };
const expectedResponse = { id: 0, error: expectedError };
targetServer.on('message', (msg) => {
const data = JSON.parse(msg);
expectedResponse.id = data.id;
targetServer.emit('message', JSON.stringify(expectedResponse));
});
target.callTarget('anything', null).then((result) => {
assert.fail('promise should not have succeeded', '', '', '');
}, (error) => {
assert.deepEqual(error, expectedError, 'error should match what was returned from the target server');
done();
});
});
target.connectTo(targetUrl, toolSocket);
});
});
suite('addMessageFilter()', () => {
setup(() => {
setupTargetAndTools();
});
test('filter is called and modified on message from tools', (done) => {
const target = CreateTarget();
Promise.all([targetReady, toolsReady]).then(() => {
const expectedModifiedMessage = { method: 'CSS.EnableModified', params: { someNewParams: true } };
target.addMessageFilter('tools::CSS.Enable', (msg) => {
return Promise.resolve(expectedModifiedMessage);
});
targetServer.on('message', (msg) => {
const data = JSON.parse(msg);
assert.deepEqual(data, expectedModifiedMessage, 'message should have been modified by the filter before it reached the target');
done();
});
target.forward(JSON.stringify({ method: 'CSS.Enable' }));
});
target.connectTo(targetUrl, toolSocket);
});
test('filter is called and modified on message from target', (done) => {
const target = CreateTarget();
Promise.all([targetReady, toolsReady]).then(() => {
const expectedModifiedMessage = { method: 'Console.newLog', params: { someNewParams: true } };
target.addMessageFilter('target::Console.log', (msg) => {
return Promise.resolve(expectedModifiedMessage);
});
toolsServer.on('message', (msg) => {
const data = JSON.parse(msg);
assert.deepEqual(data, expectedModifiedMessage, 'message should have been modified by the filter before it reached the target');
done();
});
targetServer.emit('message', JSON.stringify({ method: 'Console.log' }));
});
target.connectTo(targetUrl, toolSocket);
});
test('filter is called and modifies the response to a request from tools', (done) => {
const target = CreateTarget();
Promise.all([targetReady, toolsReady]).then(() => {
const expectedResult = { id: 10, result: { sheets: [1, 2, 3] } };
const expectedModifiedResult = { id: 10, result: { sheets: [1, 2, 3, 5, 6, 7, 8, 345, 534], newParam: true } };
target.addMessageFilter('target::CSS.setStyleSheets', (msg) => {
assert.deepEqual(msg, expectedResult);
return Promise.resolve(expectedModifiedResult);
});
targetServer.on('message', (msg) => {
const data = JSON.parse(msg);
expectedResult.id = data.id;
targetServer.emit('message', JSON.stringify(expectedResult));
});
toolsServer.on('message', (msg) => {
const data = JSON.parse(msg);
assert.deepEqual(data, expectedModifiedResult, 'result should have been modified by the filter before it was returned back to the tools');
done();
});
target.forward(JSON.stringify({ id: 101, method: 'CSS.setStyleSheets' }));
});
target.connectTo(targetUrl, toolSocket);
});
});
suite('updateClient()', () => {
setup(() => {
setupTargetAndTools();
});
test('message is sent to new tools', (done) => {
const target = CreateTarget();
const updatedToolSocket = new SocketIO(toolsUrl);
const updatedToolsReady = new Promise<void>((resolve, reject) => {
updatedToolSocket.on('connect', () => {
resolve();
});
});
Promise.all([targetReady, toolsReady, updatedToolsReady]).then(() => {
toolSocket.send = (msg) => {
assert.fail('message should have been sent to the new server', '', '', '');
};
updatedToolSocket.send = (msg) => {
done();
};
target.updateClient(updatedToolSocket);
targetServer.emit('message', JSON.stringify({ method: 'Console.log' }));
});
target.connectTo(targetUrl, toolSocket);
});
});
suite('replyWithEmpty()', () => {
setup(() => {
setupTargetAndTools();
});
test('empty message is sent to tools', (done) => {
const target = CreateTarget();
Promise.all([targetReady, toolsReady]).then(() => {
const expectedId = 101;
let actualId = 0;
target.addMessageFilter('tools::DOM.apithatneedsareply', (msg) => {
actualId = msg.id;
return target.replyWithEmpty(msg);
});
toolsServer.on('message', (msg) => {
const data = JSON.parse(msg);
const expectedEmptyMessage = { id: actualId, result: {} };
assert.deepEqual(data, expectedEmptyMessage, 'message should have been an empty result with the correct id');
done();
});
target.forward(JSON.stringify({ id: expectedId, method: 'DOM.apithatneedsareply' }));
});
target.connectTo(targetUrl, toolSocket);
});
});
}); | the_stack |
import * as assert from 'assert';
import * as fs from 'fs-extra';
import * as path from 'path';
import * as sinon from 'sinon';
import * as uuid from 'uuid';
import * as vscode from 'vscode';
import {
IAzureBlockchainDataManagerApplicationDto,
IAzureBlockchainDataManagerDto,
IAzureBlockchainDataManagerInputDto,
IAzureBlockchainDataManagerOutputDto,
IAzureConsortiumDto,
IAzureTransactionNodeDto,
IEventGridDto,
} from '../src/ARMBlockchain';
import { TruffleCommands } from '../src/commands/TruffleCommands';
import { Constants } from '../src/Constants';
import * as helpers from '../src/helpers';
import { CancellationEvent } from '../src/Models/CancellationEvent';
import { ItemType } from '../src/Models/ItemType';
import {
BlockchainDataManagerInstanceItem,
ConsortiumItem,
EventGridItem,
ResourceGroupItem,
SubscriptionItem,
TransactionNodeItem,
} from '../src/Models/QuickPickItems';
import { BlockchainDataManagerNetworkNode, BlockchainDataManagerProject } from '../src/Models/TreeItems';
import { StorageAccountResourceExplorer } from '../src/resourceExplorers/StorageAccountResourceExplorer';
import { ContractDB, ContractInstanceWithMetadata, ContractService, TreeManager } from '../src/services';
import { Contract } from '../src/services/contract/Contract';
import { AzureAccountHelper } from './testHelpers/AzureAccountHelper';
describe('Blockchain Data Manager Resource Explorer', () => {
const blockchainDataManagerResourceExplorerRequire = require('../src/resourceExplorers/BlockchainDataManagerResourceExplorer');
const blockchainDataManagerResourceExplorer =
blockchainDataManagerResourceExplorerRequire.BlockchainDataManagerResourceExplorer;
afterEach(() => {
sinon.restore();
});
describe('Public methods', () => {
let getOrSelectSubscriptionItemStub: any;
let getOrCreateResourceGroupItemStub: any;
let getBlockchainDataManagerInstanceStub: any;
const subItemTest = {
subscriptionId: uuid.v4(),
} as SubscriptionItem;
const rgItemTest = {
label: uuid.v4(),
} as ResourceGroupItem;
beforeEach(() => {
sinon.stub(vscode.extensions, 'getExtension').returns(AzureAccountHelper.mockExtension);
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'waitForLogin').returns(Promise.resolve(true));
getOrSelectSubscriptionItemStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getOrSelectSubscriptionItem')
.returns(Promise.resolve(subItemTest));
getOrCreateResourceGroupItemStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getOrCreateResourceGroupItem')
.returns(Promise.resolve(rgItemTest));
getBlockchainDataManagerInstanceStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getBlockchainDataManagerInstance');
});
it('selectProject should return blockchain data manager instance', async () => {
// Arrange
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getAzureClient').returns(Promise.resolve());
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getBlockchainDataManagerInstanceItems').resolves([]);
const bdmInstance1 = new BlockchainDataManagerInstanceItem(uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4());
const showQuickPickStub = sinon.stub().returns(bdmInstance1);
sinon.replace(helpers, 'showQuickPick', showQuickPickStub);
// Act
await blockchainDataManagerResourceExplorer.prototype.selectProject();
// Assert
assert.strictEqual(
getOrSelectSubscriptionItemStub.calledOnce,
true,
'getOrSelectSubscriptionItem should be called');
assert.strictEqual(getOrCreateResourceGroupItemStub.calledOnce, true, 'getOrCreateResourceGroupItem should be called');
assert.strictEqual(showQuickPickStub.calledOnce, true, 'showQuickPick should be called');
assert.strictEqual(
getBlockchainDataManagerInstanceStub.calledOnce,
true,
'getBlockchainDataManagerInstance should be called');
assert.strictEqual(
getBlockchainDataManagerInstanceStub.args[0][0],
bdmInstance1,
'getBlockchainDataManagerInstance should be called with correct arguments');
});
it('selectProject should start creating blockchain data manager instance', async () => {
// Arrange
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getAzureClient').returns(Promise.resolve());
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getBlockchainDataManagerInstanceItems').resolves([]);
const createProjectStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'createProject');
const showQuickPickStub = sinon.stub().returns({});
sinon.replace(helpers, 'showQuickPick', showQuickPickStub);
// Act
await blockchainDataManagerResourceExplorer.prototype.selectProject();
// Assert
assert.strictEqual(
getOrSelectSubscriptionItemStub.calledOnce,
true,
'getOrSelectSubscriptionItem should be called');
assert.strictEqual(getOrCreateResourceGroupItemStub.calledOnce, true, 'getOrCreateResourceGroupItem should be called');
assert.strictEqual(showQuickPickStub.calledOnce, true, 'showQuickPick should be called');
assert.strictEqual(
getBlockchainDataManagerInstanceStub.notCalled,
true,
'getBlockchainDataManagerInstance should not called');
assert.strictEqual(createProjectStub.calledOnce, true, 'createProjectStub should called');
});
it('deleteBDMApplication should executed all methods for delete BDM application', async () => {
// Arrange
const azureExplorer = {
bdmResource: { deleteBlockchainDataManagerApplication: async () => Promise.resolve() }};
const deleteBlobsStub =
sinon.stub(StorageAccountResourceExplorer.prototype, 'deleteBlobs').returns(Promise.resolve());
const removeItemStub = sinon.stub(TreeManager, 'removeItem');
const deleteBlockchainDataManagerApplicationSpy = sinon.spy(azureExplorer.bdmResource, 'deleteBlockchainDataManagerApplication');
sinon.stub(ContractService, 'getBuildFolderPath');
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getAzureClient')
.returns(Promise.resolve(azureExplorer));
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getSubscriptionItem').returns(Promise.resolve());
const bdmLabel = uuid.v4();
const fileUrls = [uuid.v4(), uuid.v4()];
const subscriptionId = uuid.v4();
const resourceGroup = uuid.v4();
const application = new BlockchainDataManagerNetworkNode(
uuid.v4(),
uuid.v4(),
subscriptionId,
resourceGroup,
fileUrls,
ItemType.BLOCKCHAIN_DATA_MANAGER_APPLICATION,
uuid.v4());
// Act
await blockchainDataManagerResourceExplorer.prototype
.deleteBDMApplication(bdmLabel, application, new StorageAccountResourceExplorer());
// Assert
assert.strictEqual(deleteBlockchainDataManagerApplicationSpy.calledOnce, true, 'deleteBlockchainDataManagerApplication should be called');
assert.strictEqual(removeItemStub.calledOnce, true, 'removeItem should be called');
assert.strictEqual(deleteBlobsStub.calledOnce, true, 'deleteBlobs should be called');
assert.strictEqual(deleteBlobsStub.calledOnce, true, 'deleteBlobs should be called');
});
describe('createNewBDMApplication', () => {
let getSolidityContractsFolderPathStub: any;
let getDeployedBytecodeByAddressStub: sinon.SinonStub<[string, string], Promise<string>>;
let getBDMApplicationNameStub: sinon.SinonStub<any[], any>;
let getBlobUrlsStub: sinon.SinonStub<any[], any>;
let createBDMApplicationStub: sinon.SinonStub<any[], any> | sinon.SinonStub<unknown[], unknown>;
beforeEach(() => {
sinon.stub(fs, 'statSync').returns({ isDirectory: () => false} as fs.Stats);
sinon.stub(vscode.window, 'showInformationMessage');
getSolidityContractsFolderPathStub = sinon.stub(ContractService, 'getSolidityContractsFolderPath')
.returns(Promise.resolve(''));
getDeployedBytecodeByAddressStub = sinon.stub(ContractService, 'getDeployedBytecodeByAddress')
.returns(Promise.resolve(uuid.v4()));
getBDMApplicationNameStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getBDMApplicationName')
.returns(Promise.resolve(uuid.v4()));
getBlobUrlsStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getBlobUrls')
.returns(Promise.resolve([uuid.v4(), uuid.v4()]));
createBDMApplicationStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'createBDMApplication');
});
afterEach(() => {
sinon.reset();
});
it('should executed all methods for delete BDM application', async () => {
// Arrange
const blockchainDataManagerProject = new BlockchainDataManagerProject(uuid.v4(), uuid.v4(), uuid.v4());
const contractDirectory = ['File1.sol', 'File2.txt', 'File3.sol'];
const testContractFilePath = path.join(__dirname, 'testData', 'enumTestContract.json');
const fileData = fs.readFileSync(testContractFilePath, 'utf-8');
const contract = new Contract(JSON.parse(fileData));
contract.networks.testNetworkKey = { address: uuid.v4() };
const instanceTest =
new ContractInstanceWithMetadata(contract, { id: 'testNetworkKey' }, { host: uuid.v4()});
const expectedSolFiles = 2;
let countSolFiles = 0;
sinon.stub(fs, 'readdirSync').returns(contractDirectory as any[]);
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
countSolFiles = args.length;
return args[0];
});
sinon.stub(ContractDB, 'getContractInstances').returns(Promise.resolve([instanceTest]));
// Act
await blockchainDataManagerResourceExplorer.prototype
.createNewBDMApplication(blockchainDataManagerProject, new StorageAccountResourceExplorer());
// Assert
assert.strictEqual(getSolidityContractsFolderPathStub.calledOnce, true, 'getSolidityContractsFolderPath should be called');
assert.strictEqual(countSolFiles, expectedSolFiles, 'showQuickPick should show only solidity files');
assert.strictEqual(getDeployedBytecodeByAddressStub.calledOnce, true, 'getDeployedBytecodeByAddressStub should be called');
assert.strictEqual(getBDMApplicationNameStub.calledOnce, true, 'getBDMApplicationName should be called');
assert.strictEqual(getBlobUrlsStub.calledOnce, true, 'getBlobUrls should be called');
assert.strictEqual(createBDMApplicationStub.calledOnce, true, 'createBDMApplication should be called');
});
it('throws error when contract directory does not have solidity files', async () => {
// Arrange
const blockchainDataManagerProject = new BlockchainDataManagerProject(uuid.v4(), uuid.v4(), uuid.v4());
const contractDirectory = ['File1.txt', 'File2.txt', 'File3.txt'];
sinon.stub(fs, 'readdirSync').returns(contractDirectory as any[]);
sinon.stub(helpers, 'showQuickPick');
sinon.stub(ContractDB, 'getContractInstances');
try {
// Act
await blockchainDataManagerResourceExplorer.prototype
.createNewBDMApplication(blockchainDataManagerProject, new StorageAccountResourceExplorer());
} catch (error) {
// Assert
assert.strictEqual(error.message, Constants.errorMessageStrings.SolidityContractsNotFound, 'error should be specific');
assert.strictEqual(getSolidityContractsFolderPathStub.calledOnce, true, 'getSolidityContractsFolderPath should be called');
assert.strictEqual(getDeployedBytecodeByAddressStub.calledOnce, false, 'getDeployedBytecodeByAddressStub should not called');
assert.strictEqual(getBDMApplicationNameStub.calledOnce, false, 'getBDMApplicationName should not called');
assert.strictEqual(getBlobUrlsStub.calledOnce, false, 'getBlobUrls should not called');
assert.strictEqual(createBDMApplicationStub.calledOnce, false, 'createBDMApplication should not called');
}
});
it('throws error when contract does not have instance and not to deploy them', async () => {
// Arrange
const blockchainDataManagerProject = new BlockchainDataManagerProject(uuid.v4(), uuid.v4(), uuid.v4());
const contractDirectory = ['File1.sol', 'File2.txt', 'File3.sol'];
const expectedSolFiles = 2;
let countSolFiles = 0;
sinon.stub(fs, 'readdirSync').returns(contractDirectory as any[]);
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
countSolFiles = args.length;
return args[0];
});
sinon.stub(ContractDB, 'getContractInstances').returns(Promise.resolve([]));
const deployContractsStub = sinon.stub(TruffleCommands, 'deployContracts');
sinon.stub(vscode.window, 'showErrorMessage').callsFake((...args: any[]) => {
return args[1];
});
try {
// Act
await blockchainDataManagerResourceExplorer.prototype
.createNewBDMApplication(blockchainDataManagerProject, new StorageAccountResourceExplorer());
} catch (error) {
// Assert
assert.strictEqual(error.name, CancellationEvent.name, 'error should be specific');
assert.strictEqual(countSolFiles, expectedSolFiles, 'showQuickPick should show only solidity files');
assert.strictEqual(getSolidityContractsFolderPathStub.calledOnce, true, 'getSolidityContractsFolderPath should be called');
assert.strictEqual(deployContractsStub.calledOnce, true, 'deployContractsStub should be called');
assert.strictEqual(getDeployedBytecodeByAddressStub.calledOnce, false, 'getDeployedBytecodeByAddressStub should not called');
assert.strictEqual(getBDMApplicationNameStub.calledOnce, false, 'getBDMApplicationName should not called');
assert.strictEqual(getBlobUrlsStub.calledOnce, false, 'getBlobUrls should not called');
assert.strictEqual(createBDMApplicationStub.calledOnce, false, 'createBDMApplication should not called');
}
});
it('throws error when contract does not have instance and deploy them', async () => {
// Arrange
const blockchainDataManagerProject = new BlockchainDataManagerProject(uuid.v4(), uuid.v4(), uuid.v4());
const contractDirectory = ['File1.sol', 'File2.txt', 'File3.sol'];
const expectedSolFiles = 2;
let countSolFiles = 0;
sinon.stub(fs, 'readdirSync').returns(contractDirectory as any[]);
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
countSolFiles = args.length;
return args[0];
});
sinon.stub(ContractDB, 'getContractInstances').returns(Promise.resolve([]));
const deployContractsStub = sinon.stub(TruffleCommands, 'deployContracts');
sinon.stub(vscode.window, 'showErrorMessage').callsFake((...args: any[]) => {
return args[2];
});
try {
// Act
await blockchainDataManagerResourceExplorer.prototype
.createNewBDMApplication(blockchainDataManagerProject, new StorageAccountResourceExplorer());
} catch (error) {
// Assert
assert.strictEqual(error.name, CancellationEvent.name, 'error should be specific');
assert.strictEqual(countSolFiles, expectedSolFiles, 'showQuickPick should show only solidity files');
assert.strictEqual(getSolidityContractsFolderPathStub.calledOnce, true, 'getSolidityContractsFolderPath should be called');
assert.strictEqual(deployContractsStub.calledOnce, false, 'deployContractsStub should not called');
assert.strictEqual(getDeployedBytecodeByAddressStub.calledOnce, false, 'getDeployedBytecodeByAddressStub should not called');
assert.strictEqual(getBDMApplicationNameStub.calledOnce, false, 'getBDMApplicationName should not called');
assert.strictEqual(getBlobUrlsStub.calledOnce, false, 'getBlobUrls should not called');
assert.strictEqual(createBDMApplicationStub.calledOnce, false, 'createBDMApplication should not called');
}
});
it('throws error when contract instance does not have provider', async () => {
// Arrange
const blockchainDataManagerProject = new BlockchainDataManagerProject(uuid.v4(), uuid.v4(), uuid.v4());
const contractDirectory = ['File1.sol', 'File2.txt', 'File3.sol'];
const testContractFilePath = path.join(__dirname, 'testData', 'enumTestContract.json');
const fileData = fs.readFileSync(testContractFilePath, 'utf-8');
const contract = new Contract(JSON.parse(fileData));
contract.networks.testNetworkKey = { address: uuid.v4() };
const instanceTest =
new ContractInstanceWithMetadata(contract, { id: 'testNetworkKey' }, null);
const expectedSolFiles = 2;
let countSolFiles = 0;
sinon.stub(fs, 'readdirSync').returns(contractDirectory as any[]);
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
countSolFiles = args.length;
return args[0];
});
sinon.stub(ContractDB, 'getContractInstances').returns(Promise.resolve([instanceTest]));
try {
// Act
await blockchainDataManagerResourceExplorer.prototype
.createNewBDMApplication(blockchainDataManagerProject, new StorageAccountResourceExplorer());
} catch (error) {
// Assert
assert.strictEqual(error.message, Constants.errorMessageStrings.NetworkIsNotAvailable, 'error should be specific');
assert.strictEqual(countSolFiles, expectedSolFiles, 'showQuickPick should show only solidity files');
assert.strictEqual(getSolidityContractsFolderPathStub.calledOnce, true, 'getSolidityContractsFolderPath should be called');
assert.strictEqual(getDeployedBytecodeByAddressStub.calledOnce, false, 'getDeployedBytecodeByAddressStub should not called');
assert.strictEqual(getBDMApplicationNameStub.calledOnce, false, 'getBDMApplicationName should not called');
assert.strictEqual(getBlobUrlsStub.calledOnce, false, 'getBlobUrls should not called');
assert.strictEqual(createBDMApplicationStub.calledOnce, false, 'createBDMApplication should not called');
}
});
it('throws error when contract instance does not have address', async () => {
// Arrange
const blockchainDataManagerProject = new BlockchainDataManagerProject(uuid.v4(), uuid.v4(), uuid.v4());
const contractDirectory = ['File1.sol', 'File2.txt', 'File3.sol'];
const testContractFilePath = path.join(__dirname, 'testData', 'enumTestContract.json');
const fileData = fs.readFileSync(testContractFilePath, 'utf-8');
const contract = new Contract(JSON.parse(fileData));
const instanceTest =
new ContractInstanceWithMetadata(contract, { id: 'testNetworkKey' }, { host: uuid.v4()});
const expectedSolFiles = 2;
let countSolFiles = 0;
sinon.stub(fs, 'readdirSync').returns(contractDirectory as any[]);
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
countSolFiles = args.length;
return args[0];
});
sinon.stub(ContractDB, 'getContractInstances').returns(Promise.resolve([instanceTest]));
try {
// Act
await blockchainDataManagerResourceExplorer.prototype
.createNewBDMApplication(blockchainDataManagerProject, new StorageAccountResourceExplorer());
} catch (error) {
// Assert
assert.strictEqual(error.message, Constants.errorMessageStrings.NetworkIsNotAvailable, 'error should be specific');
assert.strictEqual(countSolFiles, expectedSolFiles, 'showQuickPick should show only solidity files');
assert.strictEqual(getSolidityContractsFolderPathStub.calledOnce, true, 'getSolidityContractsFolderPath should be called');
assert.strictEqual(getDeployedBytecodeByAddressStub.calledOnce, false, 'getDeployedBytecodeByAddressStub should not called');
assert.strictEqual(getBDMApplicationNameStub.calledOnce, false, 'getBDMApplicationName should not called');
assert.strictEqual(getBlobUrlsStub.calledOnce, false, 'getBlobUrls should not called');
assert.strictEqual(createBDMApplicationStub.calledOnce, false, 'createBDMApplication should not called');
}
});
});
describe('createProject', () => {
const selectedMember = { label: uuid.v4() };
const selectedEventGrid = new EventGridItem(uuid.v4(), uuid.v4());
const transactionName = uuid.v4();
let getSelectedMemberStub: any;
let getSelectedTransactionNodeStub: any;
let getSelectedEventGridStub: any;
let createBlockchainDataManagerInstanceStub: any;
let getEventGridClientStub: any;
let consortiumResourceExplorer: any;
beforeEach(() => {
getEventGridClientStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getEventGridClient');
getSelectedMemberStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getSelectedMember')
.returns(Promise.resolve(selectedMember));
getSelectedTransactionNodeStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getSelectedTransactionNode')
.returns(new TransactionNodeItem(transactionName, uuid.v4(), uuid.v4()));
getSelectedEventGridStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getSelectedEventGrid')
.returns(selectedEventGrid);
createBlockchainDataManagerInstanceStub =
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'createBlockchainDataManagerInstance');
consortiumResourceExplorer = { createAzureConsortium: () => Promise.resolve() };
});
it('all method should be executed for create Blockchain Data Manager', async () => {
// Arrange
const consortiaList = await getConsortiaList();
const memberName = uuid.v4();
const location = uuid.v4();
const selectedConsortium =
new ConsortiumItem(uuid.v4(), uuid.v4(), uuid.v4(), memberName, location, uuid.v4());
const bdmList = await getBlockchainDataManagerList();
const azureExplorer = {
bdmResource: { getBlockchainDataManagerList: async () => bdmList },
consortiumResource: { getConsortiaList: async () => consortiaList }};
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getAzureClient')
.returns(Promise.resolve(azureExplorer));
const getSelectedConsortiumStub =
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getSelectedConsortium')
.returns(selectedConsortium);
const getBlockchainDataManagerListSpy = sinon.spy(azureExplorer.bdmResource, 'getBlockchainDataManagerList');
// Act
await blockchainDataManagerResourceExplorer.prototype.createProject(consortiumResourceExplorer);
// Assert
assert.strictEqual(
getOrSelectSubscriptionItemStub.calledOnce,
true,
'getOrSelectSubscriptionItem should be called');
assert.strictEqual(getOrCreateResourceGroupItemStub.calledOnce, true, 'getOrCreateResourceGroupItem should be called');
assert.strictEqual(getEventGridClientStub.calledOnce, true, 'getEventGridClient should be called');
assert.strictEqual(getSelectedConsortiumStub.calledOnce, true, 'getSelectedConsortium should be called');
assert.strictEqual(getSelectedMemberStub.calledOnce, true, 'getSelectedMember should be called');
assert.strictEqual(getSelectedMemberStub.args[0][2], memberName, 'getSelectedMember should be called with special member name');
assert.strictEqual(getBlockchainDataManagerListSpy.calledOnce, true, 'getBlockchainDataManagerList should be called');
assert.strictEqual(getSelectedTransactionNodeStub.calledOnce, true, 'getSelectedTransactionNode should be called');
assert.strictEqual(getSelectedTransactionNodeStub.args[0][1], bdmList, 'getSelectedTransactionNode should be called with special bdm list');
assert.strictEqual(
getSelectedTransactionNodeStub.args[0][2],
selectedMember.label,
'getSelectedTransactionNode should be called with special member name');
assert.strictEqual(
getSelectedTransactionNodeStub.args[0][3],
location,
'getSelectedTransactionNode should be called with special location');
assert.strictEqual(getSelectedEventGridStub.calledOnce, true, 'getSelectedEventGrid should be called');
assert.strictEqual(
getSelectedEventGridStub.args[0][1],
location,
'getSelectedEventGrid should be called with special location');
assert.strictEqual(createBlockchainDataManagerInstanceStub.calledOnce, true, 'createBlockchainDataManagerInstance should be called');
assert.strictEqual(
createBlockchainDataManagerInstanceStub.args[0][1],
bdmList,
'createBlockchainDataManagerInstanceStub should be called with special bdm list');
assert.strictEqual(
createBlockchainDataManagerInstanceStub.args[0][2],
selectedConsortium.location,
'createBlockchainDataManagerInstanceStub should be called with special location');
assert.strictEqual(
createBlockchainDataManagerInstanceStub.args[0][3],
selectedMember.label,
'createBlockchainDataManagerInstanceStub should be called with selected member');
assert.strictEqual(
createBlockchainDataManagerInstanceStub.args[0][5],
selectedEventGrid.url,
'createBlockchainDataManagerInstanceStub should be called with selected event grid');
});
it('should run the creation of a consortium', async () => {
// Arrange
const consortiaList = await getConsortiaList();
const bdmList = await getBlockchainDataManagerList();
const azureExplorer = {
bdmResource: { getBlockchainDataManagerList: async () => bdmList },
consortiumResource: { getConsortiaList: async () => consortiaList }};
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getAzureClient')
.returns(Promise.resolve(azureExplorer));
const getSelectedConsortiumStub =
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getSelectedConsortium').returns({});
const createAzureConsortiumStub = sinon.stub(consortiumResourceExplorer, 'createAzureConsortium');
const getBlockchainDataManagerListSpy = sinon.spy(azureExplorer.bdmResource, 'getBlockchainDataManagerList');
const createConsortiumCallbackStub = sinon.stub();
try {
// Act
await blockchainDataManagerResourceExplorer.prototype
.createProject(consortiumResourceExplorer, createConsortiumCallbackStub);
} catch (error) {
assert.strictEqual(error.name, new CancellationEvent().name);
} finally {
// Assert
assert.strictEqual(
getOrSelectSubscriptionItemStub.calledOnce,
true,
'getOrSelectSubscriptionItem should be called');
assert
.strictEqual(createConsortiumCallbackStub.calledOnce, true, 'createConsortiumCallback should be called');
assert.strictEqual(createAzureConsortiumStub.calledOnce, true, 'createAzureConsortium should be called');
assert.strictEqual(getOrCreateResourceGroupItemStub.calledOnce, true, 'getOrCreateResourceGroupItem should be called');
assert.strictEqual(getEventGridClientStub.calledOnce, true, 'getEventGridClient should be called');
assert.strictEqual(getSelectedConsortiumStub.calledOnce, true, 'getSelectedConsortium should be called');
assert.strictEqual(getSelectedMemberStub.notCalled, true, 'getSelectedMember should not called');
assert.strictEqual(getBlockchainDataManagerListSpy.notCalled, true, 'getBlockchainDataManagerList should not called');
assert.strictEqual(getSelectedTransactionNodeStub.notCalled, true, 'getSelectedTransactionNode should not called');
assert.strictEqual(getSelectedEventGridStub.notCalled, true, 'getSelectedEventGrid should not called');
assert.strictEqual(createBlockchainDataManagerInstanceStub.notCalled, true, 'createBlockchainDataManagerInstance should not called');
}
});
});
});
describe('Private methods', () => {
it('loadBlockchainDataManagerInstanceItems should return bdm instances', async () => {
// Arrange
const bdmList = await getBlockchainDataManagerList();
const azureExplorer = {
bdmResource: { getBlockchainDataManagerList: async () => bdmList }};
const getBlockchainDataManagerListSpy = sinon.spy(azureExplorer.bdmResource, 'getBlockchainDataManagerList');
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.loadBlockchainDataManagerInstanceItems(azureExplorer, [bdmList[0].name]);
// Assert
assert.strictEqual(result[0].bdmName, bdmList[1].name, 'result should has special bdm instance');
assert.strictEqual(getBlockchainDataManagerListSpy.calledOnce, true, 'getBlockchainDataManagerList should be called');
});
it('getBlockchainDataManagerInstance should return bdm instance', async () => {
// Arrange
const { input, output } = Constants.treeItemData.group.bdm;
const blockchainDataManagerInstanceItem =
new BlockchainDataManagerInstanceItem(uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4());
const applicationList = await getBlockchainDataManagerApplicationList();
const inputList = await getBlockchainDataManagerInputList();
const outputList = await getBlockchainDataManagerOutputList();
const azureExplorer = {
bdmResource: {
getBlockchainDataManagerApplicationList: async () => applicationList,
getBlockchainDataManagerInputList: async () => inputList,
getBlockchainDataManagerOutputList: async () => outputList,
}};
const getBlockchainDataManagerApplicationListSpy =
sinon.spy(azureExplorer.bdmResource, 'getBlockchainDataManagerApplicationList');
const getBlockchainDataManagerInputListSpy =
sinon.spy(azureExplorer.bdmResource, 'getBlockchainDataManagerInputList');
const getBlockchainDataManagerOutputListSpy =
sinon.spy(azureExplorer.bdmResource, 'getBlockchainDataManagerOutputList');
// Act
const bdmProject = await blockchainDataManagerResourceExplorer.prototype
.getBlockchainDataManagerInstance(blockchainDataManagerInstanceItem, azureExplorer);
// Assert
// We should remember that inputs and outputs are in groups, because of it we use + 2
assert.strictEqual(
bdmProject.children.length, applicationList.length + 2, 'result should has special number of children');
assert.strictEqual(
bdmProject.children
.filter((ch: BlockchainDataManagerNetworkNode) => ch.label === input.label)[0].children.length,
inputList.length,
'Input group should has special number of inputs');
assert.strictEqual(
bdmProject.children
.filter((ch: BlockchainDataManagerNetworkNode) => ch.label === output.label)[0].children.length,
outputList.length,
'Output group should has special number of outputs');
assert.strictEqual(
getBlockchainDataManagerApplicationListSpy.calledOnce,
true,
'getBlockchainDataManagerApplicationList should be called');
assert.strictEqual(
getBlockchainDataManagerInputListSpy.calledOnce, true, 'getBlockchainDataManagerInputList should be called');
assert.strictEqual(
getBlockchainDataManagerOutputListSpy.calledOnce, true, 'getBlockchainDataManagerOutputList should be called');
});
it('createBlockchainDataManagerInstance should return bdm instance', async () => {
// Arrange
const expectedNumberChildren = 2;
const bdmItems = await getBlockchainDataManagerList();
const transactionNodeName = uuid.v4();
const selectedBdmName = uuid.v4();
const connectionName = uuid.v4();
const inputList = await getBlockchainDataManagerInputList();
const outputList = await getBlockchainDataManagerOutputList();
const azureExplorer = {
bdmResource: {
createBlockchainDataManager: async (_a: any, _b: any) => bdmItems[0],
createBlockchainDataManagerInput: async (_a: any, _b: any, _c: any) => inputList[0],
createBlockchainDataManagerOutput: async (_a: any, _b: any, _c: any) => outputList[0],
}};
const getBlockchainDataManagerConnectionNameStub =
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getBlockchainDataManagerConnectionName')
.returns(Promise.resolve(connectionName));
const getBlockchainDataManagerNameStub =
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getBlockchainDataManagerName')
.returns(Promise.resolve(selectedBdmName));
const createBlockchainDataManagerSpy = sinon.spy(azureExplorer.bdmResource, 'createBlockchainDataManager');
const createBlockchainDataManagerInputSpy = sinon.spy(azureExplorer.bdmResource, 'createBlockchainDataManagerInput');
const createBlockchainDataManagerOutputSpy = sinon.spy(azureExplorer.bdmResource, 'createBlockchainDataManagerOutput');
const startBlockchainDataManagerStub =
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'startBlockchainDataManager');
const withProgressStub = sinon.stub(vscode.window, 'withProgress').callsFake((...args: any[]) => {
return args[1]();
});
// Act
const bdmProject = await blockchainDataManagerResourceExplorer.prototype.createBlockchainDataManagerInstance(
azureExplorer,
bdmItems,
uuid.v4(),
uuid.v4(),
transactionNodeName,
uuid.v4());
// Assert
assert.strictEqual(bdmProject.children.length, expectedNumberChildren, `result should has only ${expectedNumberChildren} children`);
assert.strictEqual(
getBlockchainDataManagerConnectionNameStub.calledOnce,
true,
'getBlockchainDataManagerConnectionName should be called');
assert.strictEqual(
getBlockchainDataManagerNameStub.calledOnce, true, 'getBlockchainDataManagerName should be called');
assert.strictEqual(withProgressStub.calledOnce, true, 'withProgress should be called');
assert.strictEqual(
createBlockchainDataManagerSpy.calledOnce, true, 'createBlockchainDataManager should be called');
assert.strictEqual(
createBlockchainDataManagerSpy.args[0][0],
selectedBdmName,
'createBlockchainDataManager should be called with special argument');
assert.strictEqual(
createBlockchainDataManagerInputSpy.calledOnce, true, 'createBlockchainDataManagerInput should be called');
assert.strictEqual(createBlockchainDataManagerInputSpy.args[0][0],
selectedBdmName,
'createBlockchainDataManagerInput should be called with special bdm name');
assert.strictEqual(createBlockchainDataManagerInputSpy.args[0][1],
transactionNodeName,
'createBlockchainDataManagerInput should be called with special transaction node name');
assert.strictEqual(
createBlockchainDataManagerOutputSpy.calledOnce, true, 'createBlockchainDataManagerOutput should be called');
assert.strictEqual(createBlockchainDataManagerOutputSpy.args[0][0],
selectedBdmName,
'createBlockchainDataManagerOutput should be called with special bdm name');
assert.strictEqual(createBlockchainDataManagerOutputSpy.args[0][1],
connectionName,
'createBlockchainDataManagerOutput should be called with special connection name');
assert.strictEqual(
startBlockchainDataManagerStub.calledOnce, true, 'startBlockchainDataManager should be called');
assert.strictEqual(startBlockchainDataManagerStub.args[0][1],
bdmItems[0].id,
'startBlockchainDataManager should be called with selected bdm url');
assert.strictEqual(startBlockchainDataManagerStub.args[0][2],
selectedBdmName,
'startBlockchainDataManager should be called with selected bdm name');
assert.strictEqual(
createBlockchainDataManagerInputSpy.calledAfter(createBlockchainDataManagerSpy),
true,
'createBlockchainDataManagerInput should be called after createBlockchainDataManager');
assert.strictEqual(
createBlockchainDataManagerOutputSpy.calledAfter(createBlockchainDataManagerInputSpy),
true,
'createBlockchainDataManagerOutput should be called after createBlockchainDataManagerInput');
assert.strictEqual(
startBlockchainDataManagerStub.calledAfter(createBlockchainDataManagerOutputSpy),
true,
'startBlockchainDataManager should be called after createBlockchainDataManagerOutput');
});
describe('getBlockchainDataManagerConnectionName', () => {
describe('should return error when connection name does not correct', () => {
const incorrectConnectionName = ['', 'A', 'a_a'];
incorrectConnectionName.forEach((name) => {
it(`and equal ${name}`, async () => {
// Arrange
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(name);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getBlockchainDataManagerConnectionName();
// Assert
assert.strictEqual(result, Constants.validationMessages.forbiddenChars.outboundConnectionName, 'result should has error');
});
});
});
describe('should not returns error when connection name correct', () => {
const correctConnectionName = ['1', 'a', '1a'];
correctConnectionName.forEach((name) => {
it(`and equal ${name}`, async () => {
// Arrange
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(name);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getBlockchainDataManagerConnectionName();
// Assert
assert.strictEqual(result, undefined, 'result should not has error');
});
});
});
});
describe('getBlockchainDataManagerName', () => {
describe('should return error when bdm name does not correct', () => {
const incorrectConnectionName = ['', 'A', '!', 'aaaaaaaaaaaaaaaaaaaa1', 'a_1'];
incorrectConnectionName.forEach((name) => {
it(`and equal ${name}`, async () => {
// Arrange
const bdmItems = await getBlockchainDataManagerList();
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(name);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getBlockchainDataManagerName(bdmItems);
// Assert
assert.strictEqual(result, Constants.validationMessages.invalidBlockchainDataManagerName, 'result should has error');
});
});
});
it('should return error when bdm name already exist', async () => {
// Arrange
const bdmItems = await getBlockchainDataManagerList();
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(bdmItems[0].name);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getBlockchainDataManagerName(bdmItems);
// Assert
assert.strictEqual(result, Constants.validationMessages.bdmNameAlreadyExists, 'result should has error');
});
describe('should not returns error when bdm name correct', () => {
const correctConnectionName = ['1', 'a', '1a', 'aaaaaaaaaa1111111111'];
correctConnectionName.forEach((name) => {
it(`and equal ${name}`, async () => {
// Arrange
const bdmItems = await getBlockchainDataManagerList();
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(name);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getBlockchainDataManagerName(bdmItems);
// Assert
assert.strictEqual(result, undefined, 'result should not has error');
});
});
});
});
describe('getTransactionNodeName', () => {
let transactionNodeItems: TransactionNodeItem[];
beforeEach(() => {
transactionNodeItems = [
new TransactionNodeItem('transactionnode1', uuid.v4(), uuid.v4()),
new TransactionNodeItem('transactionnode2', uuid.v4(), uuid.v4()),
];
});
describe('should return error when transaction node name does not correct', () => {
const incorrectConnectionName = ['', 'a', 'aA', 'aaaaaaaaaaaaaaaaaaaa1', 'a_1', '1a'];
incorrectConnectionName.forEach((name) => {
it(`and equal ${name}`, async () => {
// Arrange
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(name);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getTransactionNodeName(transactionNodeItems);
// Assert
assert.strictEqual(result, Constants.validationMessages.invalidAzureName, 'result should has error');
});
});
});
it('should return error when transaction node name already exist', async () => {
// Arrange
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(transactionNodeItems[0].label);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getTransactionNodeName(transactionNodeItems);
// Assert
assert.strictEqual(result, Constants.validationMessages.transactionNodeNameAlreadyExists, 'result should has error');
});
describe('should not returns error when transaction node name correct', () => {
const correctConnectionName = ['aa', 'a1', 'aaaaaaaaaa1111111111'];
correctConnectionName.forEach((name) => {
it(`and equal ${name}`, async () => {
// Arrange
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(name);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getTransactionNodeName(transactionNodeItems);
// Assert
assert.strictEqual(result, undefined, 'result should not has error');
});
});
});
});
describe('getEventGridName', () => {
let eventGridItems: EventGridItem[];
beforeEach(() => {
eventGridItems = [
new EventGridItem('eventgrid1', uuid.v4()),
new EventGridItem('eventgrid2', uuid.v4()),
];
});
describe('should return error when event grid name does not correct', () => {
const incorrectConnectionName = ['', 'aa', 'aA', 'aaaaaaaaaa1111111111aaaaaaaaaa1111111111aaaaaaaaaa1', 'a_1'];
incorrectConnectionName.forEach((name) => {
it(`and equal ${name}`, async () => {
// Arrange
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(name);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getEventGridName(eventGridItems);
// Assert
assert.strictEqual(result, Constants.validationMessages.invalidEventGridName, 'result should has error');
});
});
});
it('should return error when event grid name already exist', async () => {
// Arrange
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(eventGridItems[0].label);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getEventGridName(eventGridItems);
// Assert
assert.strictEqual(result, Constants.validationMessages.eventGridAlreadyExists, 'result should has error');
});
describe('should not returns error when event grid name correct', () => {
const correctConnectionName =
['aaa', '111', 'AAA', 'aA-1', 'aaaaaaaaaa1111111111aaaaaaaaaa1111111111aaaaaaaaaa'];
correctConnectionName.forEach((name) => {
it(`and equal ${name}`, async () => {
// Arrange
sinon.stub(helpers, 'showInputBox').callsFake((...args: any[]) => {
return args[0].validateInput(name);
});
// Act
const result = await blockchainDataManagerResourceExplorer.prototype
.getEventGridName(eventGridItems);
// Assert
assert.strictEqual(result, undefined, 'result should not has error');
});
});
});
});
describe('getSelectedConsortium', () => {
const azureExplorer = {};
const consortiaItemList = getConsortiaItemList();
it('should return quick pick with available consortia', async () => {
// Arrange
const consortiumResourceExplorer = {
loadConsortiumItems: async () => consortiaItemList,
};
let numberQuickPickItems = 0;
const loadConsortiumItemsSpy = sinon.spy(consortiumResourceExplorer, 'loadConsortiumItems');
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
numberQuickPickItems = args[0].length;
return args[0];
});
const expectedNumberConsortia = consortiaItemList
.filter((con) => Constants.availableBlockchainDataManagerLocations.includes(con.location))
.length;
// Act
await blockchainDataManagerResourceExplorer.prototype
.getSelectedConsortium(consortiumResourceExplorer, azureExplorer);
// Assert
assert.strictEqual(loadConsortiumItemsSpy.calledOnce, true, 'loadConsortiumItems should be called');
assert.strictEqual(numberQuickPickItems, expectedNumberConsortia, `QuickPick should has ${expectedNumberConsortia} consortia item`);
});
it('should return quick pick with add button', async () => {
// Arrange
const consortiumResourceExplorer = {
loadConsortiumItems: async () => consortiaItemList
.filter((con) => !Constants.availableBlockchainDataManagerLocations.includes(con.location)),
};
const expectedItem = { label: ''};
const loadConsortiumItemsSpy = sinon.spy(consortiumResourceExplorer, 'loadConsortiumItems');
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
expectedItem.label = args[0][0].label;
return args[0];
});
// Act
await blockchainDataManagerResourceExplorer.prototype
.getSelectedConsortium(consortiumResourceExplorer, azureExplorer);
// Assert
assert.strictEqual(loadConsortiumItemsSpy.calledOnce, true, 'loadConsortiumItems should be called');
assert.strictEqual(expectedItem.label, Constants.uiCommandStrings.createConsortium, 'QuickPick should has add button item');
});
});
describe('getSelectedTransactionNode', () => {
const selectedMemberName = uuid.v4();
const location = uuid.v4();
let bdmInputList: IAzureBlockchainDataManagerInputDto[];
let bdmItems: IAzureBlockchainDataManagerDto[];
let transactionNodeList: IAzureTransactionNodeDto[];
let withProgressStub: any;
let azureExplorer: any;
let expectedQuickPickItems: number;
let getBlockchainDataManagerInputListSpy: sinon.SinonSpy;
let getTransactionNodeListSpy: sinon.SinonSpy;
let getTransactionNodeSpy: sinon.SinonSpy;
beforeEach(() => {
bdmInputList = getBlockchainDataManagerInputList();
bdmItems = getBlockchainDataManagerList();
transactionNodeList = getTransactionNodeList();
withProgressStub = sinon.stub(vscode.window, 'withProgress').callsFake((...args: any[]) => {
return args[1]();
});
let changeOneTransactionNode = false;
transactionNodeList.forEach((tn) => {
if (tn.properties.provisioningState === Constants.provisioningState.succeeded && !changeOneTransactionNode) {
tn.id = bdmInputList[0].properties.dataSource.resourceId;
changeOneTransactionNode = true;
}
});
// We should remember about default transaction node and create button, because of it we use + 2
expectedQuickPickItems = transactionNodeList
.filter((tn) => tn.properties.provisioningState === Constants.provisioningState.succeeded &&
!bdmInputList.some((input) => input.properties.dataSource.resourceId === tn.id)).length + 2;
azureExplorer = {
bdmResource: {
getBlockchainDataManagerInputList: async () => bdmInputList,
},
transactionNodeResource: {
getTransactionNode: async (_a: any, _b: any) => ({
id: uuid.v4(),
location: uuid.v4(),
name: uuid.v4(),
properties: {
dns: uuid.v4(),
password: uuid.v4(),
provisioningState: Constants.provisioningState.succeeded,
publicKey: uuid.v4(),
userName: uuid.v4(),
},
type: uuid.v4(),
}),
getTransactionNodeList: async (_a: any) => transactionNodeList,
},
};
getBlockchainDataManagerInputListSpy
= sinon.spy(azureExplorer.bdmResource, 'getBlockchainDataManagerInputList');
getTransactionNodeListSpy = sinon.spy(azureExplorer.transactionNodeResource, 'getTransactionNodeList');
getTransactionNodeSpy = sinon.spy(azureExplorer.transactionNodeResource, 'getTransactionNode');
});
function assertResponse(numberQuickPickItems: number) {
assert.strictEqual(withProgressStub.calledOnce, true, 'withProgress should be called');
assert.strictEqual(
expectedQuickPickItems,
numberQuickPickItems,
'Quick pick should not has unsuccessful transaction node and transaction node which already use in bdm.');
assert.strictEqual(
getBlockchainDataManagerInputListSpy.callCount,
bdmItems.length,
`getBlockchainDataManagerInputList should be called ${bdmItems.length} time`);
assert.strictEqual(getTransactionNodeListSpy.calledOnce, true, 'getTransactionNodeList should be called');
assert.strictEqual(
getTransactionNodeListSpy.args[0][0],
selectedMemberName,
'getTransactionNodeList should be called with selected member');
assert.strictEqual(getTransactionNodeSpy.calledOnce, true, 'getTransactionNode should be called');
assert.strictEqual(
getTransactionNodeSpy.args[0][0],
selectedMemberName,
'getTransactionNode should be called with selected member');
assert.strictEqual(
getTransactionNodeSpy.args[0][1],
Constants.defaultInputNameInBdm,
'getTransactionNode should be called with default input name');
}
it('should return selected transaction node', async () => {
// Arrange
let numberQuickPickItems = 0;
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
numberQuickPickItems = args[0].length;
return args[0][1];
});
const createdTransactionNodeStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'createdTransactionNode');
// Act
await blockchainDataManagerResourceExplorer.prototype
.getSelectedTransactionNode(azureExplorer, bdmItems, selectedMemberName, location);
// Assert
assertResponse(numberQuickPickItems);
assert.strictEqual(createdTransactionNodeStub.notCalled, true, 'createdTransactionNode should not called');
});
it('should return cancellation event when quick pick return create button', async () => {
// Arrange
let numberQuickPickItems = 0;
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
numberQuickPickItems = args[0].length;
return args[0][0];
});
const createdTransactionNodeStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'createdTransactionNode');
try {
// Act
await blockchainDataManagerResourceExplorer.prototype
.getSelectedTransactionNode(azureExplorer, bdmItems, selectedMemberName, location);
} catch (error) {
assert.strictEqual(error.name, new CancellationEvent().name);
} finally {
// Assert
assertResponse(numberQuickPickItems);
assert.strictEqual(createdTransactionNodeStub.calledOnce, true, 'createdTransactionNode should be called');
}
});
});
describe('getSelectedEventGrid', () => {
let getCreatedEventGridStub: sinon.SinonStub;
let getEventGridListSpy: sinon.SinonSpy;
let expectedQuickPickItems: number;
let eventGridClient: any;
beforeEach(() => {
sinon.stub(vscode.extensions, 'getExtension').returns(AzureAccountHelper.mockExtension);
sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'waitForLogin').returns(Promise.resolve(true));
const eventGridList = getEventGridList();
eventGridClient = {
eventGridResource: {
getEventGridList: async () => eventGridList,
},
};
getCreatedEventGridStub = sinon.stub(blockchainDataManagerResourceExplorer.prototype, 'getCreatedEventGrid');
getEventGridListSpy = sinon.spy(eventGridClient.eventGridResource, 'getEventGridList');
// We should remember about default create button, because of it we use + 1
expectedQuickPickItems = eventGridList
.filter((eg) => eg.properties.provisioningState === Constants.provisioningState.succeeded)
.length + 1;
});
it('should return quick pick with available event grid', async () => {
// Arrange
let numberQuickPickItems = 0;
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
numberQuickPickItems = args[0].length;
return args[0][1];
});
// Act
await blockchainDataManagerResourceExplorer.prototype.getSelectedEventGrid(eventGridClient, uuid.v4());
// Assert
assert.strictEqual(getEventGridListSpy.calledOnce, true, 'getEventGridList should be called');
assert.strictEqual(
numberQuickPickItems,
expectedQuickPickItems,
'Quick pick should not has unsuccessful event grid items');
assert.strictEqual(getCreatedEventGridStub.notCalled, true, 'getCreatedEventGrid should not called');
});
it('should return cancellation event when quick pick return create button', async () => {
// Arrange
let numberQuickPickItems = 0;
sinon.stub(helpers, 'showQuickPick').callsFake((...args: any[]) => {
numberQuickPickItems = args[0].length;
return args[0][0];
});
try {
// Act
await blockchainDataManagerResourceExplorer.prototype.getSelectedEventGrid(eventGridClient, uuid.v4());
} catch (error) {
assert.strictEqual(error.name, new CancellationEvent().name);
} finally {
// Assert
assert.strictEqual(getEventGridListSpy.calledOnce, true, 'getEventGridList should be called');
assert.strictEqual(
numberQuickPickItems,
expectedQuickPickItems,
'Quick pick should not has unsuccessful event grid items');
assert.strictEqual(getCreatedEventGridStub.calledOnce, true, 'getCreatedEventGrid should be called');
}
});
});
});
const consortiumNameList = {
consortium1: 'consortium1',
consortium2: 'consortium2',
consortium3: 'consortium3',
};
function getConsortiaList(): IAzureConsortiumDto[] {
return [{
consortium: consortiumNameList.consortium1,
consortiumManagementAccountAddress: uuid.v4(),
consortiumManagementAccountPassword: uuid.v4(),
dns: uuid.v4(),
location: 'eastus',
password: uuid.v4(),
protocol: uuid.v4(),
provisioningState: uuid.v4(),
publicKey: uuid.v4(),
rootContractAddress: uuid.v4(),
userName: uuid.v4(),
validatorNodesSku: {
capacity: 0,
},
},
{
consortium: consortiumNameList.consortium2,
consortiumManagementAccountAddress: uuid.v4(),
consortiumManagementAccountPassword: uuid.v4(),
dns: uuid.v4(),
location: 'westeurope',
password: uuid.v4(),
protocol: uuid.v4(),
provisioningState: uuid.v4(),
publicKey: uuid.v4(),
rootContractAddress: uuid.v4(),
userName: uuid.v4(),
validatorNodesSku: {
capacity: 0,
},
},
{
consortium: consortiumNameList.consortium3,
consortiumManagementAccountAddress: uuid.v4(),
consortiumManagementAccountPassword: uuid.v4(),
dns: uuid.v4(),
location: uuid.v4(),
password: uuid.v4(),
protocol: uuid.v4(),
provisioningState: uuid.v4(),
publicKey: uuid.v4(),
rootContractAddress: uuid.v4(),
userName: uuid.v4(),
validatorNodesSku: {
capacity: 0,
},
}];
}
const bdmNameList = {
bdm1: 'bdm1',
bdm2: 'bdm2',
};
function getBlockchainDataManagerList(): IAzureBlockchainDataManagerDto[] {
return [{
id: uuid.v4(),
location: uuid.v4(),
name: bdmNameList.bdm1,
properties: {
createdTime: uuid.v4(),
lastUpdatedTime: uuid.v4(),
provisioningState: uuid.v4(),
sku: {
locations: [uuid.v4()],
name: uuid.v4(),
resourceType: uuid.v4(),
tier: uuid.v4(),
},
state: uuid.v4(),
uniqueId: uuid.v4(),
},
tags: {},
type: uuid.v4(),
},
{
id: uuid.v4(),
location: uuid.v4(),
name: bdmNameList.bdm2,
properties: {
createdTime: uuid.v4(),
lastUpdatedTime: uuid.v4(),
provisioningState: uuid.v4(),
sku: {
locations: [uuid.v4()],
name: uuid.v4(),
resourceType: uuid.v4(),
tier: uuid.v4(),
},
state: uuid.v4(),
uniqueId: uuid.v4(),
},
tags: {},
type: uuid.v4(),
}];
}
function getBlockchainDataManagerInputList(): IAzureBlockchainDataManagerInputDto[] {
return [{
id: uuid.v4(),
name: uuid.v4(),
properties: {
dataSource: {
resourceId: uuid.v4(),
},
inputType: uuid.v4(),
},
type: uuid.v4(),
},
{
id: uuid.v4(),
name: uuid.v4(),
properties: {
dataSource: {
resourceId: uuid.v4(),
},
inputType: uuid.v4(),
},
type: uuid.v4(),
}];
}
function getBlockchainDataManagerOutputList(): IAzureBlockchainDataManagerOutputDto[] {
return [{
id: uuid.v4(),
name: uuid.v4(),
properties: {
createdTime: uuid.v4(),
dataSource: {
resourceId: uuid.v4(),
},
lastUpdatedTime: uuid.v4(),
outputType: uuid.v4(),
state: uuid.v4(),
},
type: uuid.v4(),
},
{
id: uuid.v4(),
name: uuid.v4(),
properties: {
createdTime: uuid.v4(),
dataSource: {
resourceId: uuid.v4(),
},
lastUpdatedTime: uuid.v4(),
outputType: uuid.v4(),
state: uuid.v4(),
},
type: uuid.v4(),
}];
}
function getBlockchainDataManagerApplicationList(): IAzureBlockchainDataManagerApplicationDto[] {
return [
{
id: uuid.v4(),
name: uuid.v4(),
properties: {
artifactType: uuid.v4(),
content: {
abiFileUrl: uuid.v4(),
bytecodeFileUrl: uuid.v4(),
queryTargetTypes: [uuid.v4()],
},
createdTime: uuid.v4(),
lastUpdatedTime: uuid.v4(),
provisioningState: uuid.v4(),
state: uuid.v4(),
},
type: uuid.v4(),
},
{
id: uuid.v4(),
name: uuid.v4(),
properties: {
artifactType: uuid.v4(),
content: {
abiFileUrl: uuid.v4(),
bytecodeFileUrl: uuid.v4(),
queryTargetTypes: [uuid.v4()],
},
createdTime: uuid.v4(),
lastUpdatedTime: uuid.v4(),
provisioningState: uuid.v4(),
state: uuid.v4(),
},
type: uuid.v4(),
},
];
}
function getConsortiaItemList(): ConsortiumItem[] {
return [
new ConsortiumItem(uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4(), 'eastus', uuid.v4()),
new ConsortiumItem(uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4(), 'westeurope', uuid.v4()),
new ConsortiumItem(uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4()),
new ConsortiumItem(uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4()),
];
}
function getTransactionNodeList(): IAzureTransactionNodeDto[] {
return [
{
id: uuid.v4(),
location: uuid.v4(),
name: uuid.v4(),
properties: {
dns: uuid.v4(),
password: uuid.v4(),
provisioningState: uuid.v4(),
publicKey: uuid.v4(),
userName: uuid.v4(),
},
type: uuid.v4(),
},
{
id: uuid.v4(),
location: uuid.v4(),
name: uuid.v4(),
properties: {
dns: uuid.v4(),
password: uuid.v4(),
provisioningState: Constants.provisioningState.succeeded,
publicKey: uuid.v4(),
userName: uuid.v4(),
},
type: uuid.v4(),
},
{
id: uuid.v4(),
location: uuid.v4(),
name: uuid.v4(),
properties: {
dns: uuid.v4(),
password: uuid.v4(),
provisioningState: Constants.provisioningState.succeeded,
publicKey: uuid.v4(),
userName: uuid.v4(),
},
type: uuid.v4(),
},
];
}
function getEventGridList(): IEventGridDto[] {
return [
{
id: uuid.v4(),
location: uuid.v4(),
name: uuid.v4(),
properties: {
endpoint: uuid.v4(),
inputSchema: uuid.v4(),
metricResourceId: uuid.v4(),
provisioningState: uuid.v4(),
},
tags: uuid.v4(),
type: uuid.v4(),
},
{
id: uuid.v4(),
location: uuid.v4(),
name: uuid.v4(),
properties: {
endpoint: uuid.v4(),
inputSchema: uuid.v4(),
metricResourceId: uuid.v4(),
provisioningState: Constants.provisioningState.succeeded,
},
tags: uuid.v4(),
type: uuid.v4(),
},
{
id: uuid.v4(),
location: uuid.v4(),
name: uuid.v4(),
properties: {
endpoint: uuid.v4(),
inputSchema: uuid.v4(),
metricResourceId: uuid.v4(),
provisioningState: Constants.provisioningState.succeeded,
},
tags: uuid.v4(),
type: uuid.v4(),
},
];
}
}); | the_stack |
import { core } from './core';
// for docs
// noinspection ES6UnusedImports
import * as el from '../';
// ============================================================================
// Native
/**
* Implements a simple one-pole filter,
* also sometimes called a leaky integrator.
* Expects two children, the first is the pole position,
* the second is the signal to filter.
*
* @param [props]
* props object with optional key
*
* @param polePosition
* the pole position
*
* @param signal
* signal to filter
*
* @returns
* a {@link core.PoleNode} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.PoleNode
*/
export const pole:
core.NodeFactory<'pole',
core.KeyProps,
[
polePosition: core.Child,
signal: core.Child
]>;
/**
* A second order transposed direct-form II filter implementation.
* Expects six children, the first five of which are the raw filter
* coefficients (b0, b1, b2, a1, a2). The final input is the signal to filter.
*
* @param [props]
* props object with optional key
*
* @param b0
* the first coefficient
*
* @param b1
* the second coefficient
*
* @param b2
* the third coefficient
*
* @param a1
* the fourth coefficient
*
* @param a2
* the fifth coefficient
*
* @param signal
* signal to filter
*
* @returns
* a {@link core.BiquadNode} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.BiquadNode
*/
export const biquad:
core.NodeFactory<'biquad',
core.KeyProps,
[
b0: core.Child,
b1: core.Child,
b2: core.Child,
a1: core.Child,
a2: core.Child,
signal: core.Child
]>;
/**
* A convolution node which reads an impulse response from disk and
* convolves it with the input signal.
*
* @param [props]
* {@link core.ConvolveProps} object
*
* @param signal
* signal to convolve
*
* @returns
* a {@link core.ConvolveNode} that convolves the signal
*
* @see el
* @see core.ConvolveProps
* @see core.Child
* @see core.Node
*/
export const convolve:
core.NodeFactory<'convolve',
core.ConvolveProps,
[
signal: core.Child
]>;
// ============================================================================
// Functions
/**
* Implements a simple one-zero filter.
* Expects the b0 coefficient as the first argument,
* the zero position b1 as the second argument,
* and the input to the filter as the third.
*
* @param [props]
* props object with optional key
*
* @param b0
* the first coefficient
*
* @param b1
* the second coefficient
*
* @param signal
* signal to filter
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const zero:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
b0: core.Child,
b1: core.Child,
signal: core.Child
]>;
/**
* Implements a default DC blocking filter with a pole at 0.995 and a zero at 1.
* This filter has a -3dB point near 35Hz at 44.1kHz.
*
* @param [props]
* props object with optional key
*
* @param signal
* signal to filter
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const dcblock:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
signal: core.Child
]>;
/**
* A simple first order pole-zero filter, Direct Form 1.
*
* @param [props]
* props object with optional key
*
* @param b0
* the first coefficient
*
* @param b1
* the second coefficient
*
* @param a1
* the third coefficient
*
* @param signal
* signal to filter
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const df11:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
b0: core.Child,
b1: core.Child,
a1: core.Child,
signal: core.Child
]>;
/**
* Unity gain one-pole smoothing. Commonly used for addressing
* discontinuities in control signals.
* Expects two children, the first is the pole position,
* the second is the signal to filter.
*
* @param [props]
* props object with optional key
*
* @param polePosition
* the pole position
*
* @param signal
* signal to filter
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const smooth:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
polePosition: core.Child,
signal: core.Child
]>;
/**
* A pre-defined smoothing export function with a 20ms decay time equivalent to
* @example
* el.smooth(el.tau2pole(0.02), signal)
*
* @param [props]
* props object with optional key
*
* @param signal
* signal to filter
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const sm:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
signal: core.Child
]>;
/**
* A simple lowpass biquad filter with a cutoff frequency, a Q,
* and which filters the signal.
*
* @param [props]
* props object with optional key
*
* @param cutoff
* the filter cutoff
*
* @param Q
* the filter Q
*
* @param signal
* signal to filter
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const lowpass:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
cutoff: core.Child,
Q: core.Child,
signal: core.Child
]>;
/**
* A simple highpass biquad filter with a cutoff frequency, a Q,
* and which filters the signal.
*
* @param [props]
* props object with optional key
*
* @param cutoff
* the filter cutoff
*
* @param Q
* the filter Q
*
* @param signal
* signal to filter
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const highpass:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
cutoff: core.Child,
Q: core.Child,
signal: core.Child
]>;
/**
* A simple bandpass biquad filter with a cutoff frequency, a Q,
* and which filters the signal.
*
* @param [props]
* props object with optional key
*
* @param cutoff
* the filter cutoff
*
* @param Q
* the filter Q
*
* @param signal
* signal
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const bandpass:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
cutoff: core.Child,
Q: core.Child,
signal: core.Child
]>;
/**
* An allpass biquad filter with a cutoff frequency, a Q,
* and which filters the signal.
*
* @param [props]
* props object with optional key
*
* @param cutoff
* the filter cutoff
*
* @param Q
* the filter Q
*
* @param signal
* signal
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const allpass:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
cutoff: core.Child,
Q: core.Child,
signal: core.Child
]>;
/**
* A notch biquad filter with a cutoff frequency, a Q,
* and which filters the signal.
*
* @param [props]
* props object with optional key
*
* @param cutoff
* the filter cutoff
*
* @param Q
* the filter Q
*
* @param signal
* signal
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const notch:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
cutoff: core.Child,
Q: core.Child,
signal: core.Child
]>;
/**
* A peaking (bell) biquad filter with a cutoff frequency, a Q,
* gain in decibels, and which filters the signal.
*
* @param [props]
* props object with optional key
*
* @param cutoff
* the filter cutoff
*
* @param Q
* the filter Q
*
* @param gain
* the filter gain in decibels
*
* @param signal
* signal
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const peak:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
cutoff: core.Child,
Q: core.Child,
gain: core.Child,
signal: core.Child
]>;
/**
* A lowshelf biquad filter with a cutoff frequency, a Q,
* gain in decibels, and which filters the signal.
*
* @param [props]
* props object with optional key
*
* @param cutoff
* the filter cutoff
*
* @param Q
* the filter Q
*
* @param gain
* the filter gain in decibels
*
* @param signal
* signal
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const lowshelf:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
cutoff: core.Child,
Q: core.Child,
gain: core.Child,
signal: core.Child
]>;
/**
* A highshelf biquad filter with a cutoff frequency, a Q,
* gain in decibels, and which filters the signal.
*
* @param [props]
* props object with optional key
*
* @param cutoff
* the filter cutoff
*
* @param Q
* the filter Q
*
* @param gain
* the filter gain in decibels
*
* @param signal
* signal
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const highshelf:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
cutoff: core.Child,
Q: core.Child,
gain: core.Child,
signal: core.Child
]>;
/**
* A pink noise filter designed to apply a -3dB/octave lowpass to the
* incoming signal.
*
* @param [props]
* props object with optional key
*
* @param signal
* signal to filter
*
* @returns
* a {@link core.Node} that filters the signal
*
* @see el
* @see core.KeyProps
* @see core.Child
* @see core.Node
*/
export const pink:
core.NodeFactory<core.CompositeNodeType,
core.KeyProps,
[
signal: core.Child
]>; | the_stack |
import * as JSDiff from "diff";
import { RenderBaby } from "../jupyter-hooks/render-baby";
import {
Nodey,
NodeyCode,
NodeyMarkdown,
NodeyNotebook,
NodeyOutput,
NodeyRawCell,
} from "../nodey";
import { Sampler, CellMap } from ".";
import { History } from "../history";
import { ChangeType } from "../checkpoint";
export enum DIFF_TYPE {
NO_DIFF,
CHANGE_DIFF,
PRESENT_DIFF,
}
export type DiffCell = {
name: string;
sample: HTMLElement;
status: ChangeType[];
};
const CHANGE_SAME_CLASS = "v-Verdant-sampler-code-same";
const CHANGE_ADDED_CLASS = "v-Verdant-sampler-code-added";
const CHANGE_REMOVED_CLASS = "v-Verdant-sampler-code-removed";
const MARKDOWN_LINEBREAK = "v-Verdant-sampler-markdown-linebreak";
const MAX_WORD_DIFFS = 4;
export class Diff {
private readonly sampler: Sampler;
private readonly history: History;
private readonly renderBaby: RenderBaby;
constructor(sampler: Sampler) {
this.sampler = sampler;
this.history = sampler.history;
this.renderBaby = sampler.renderBaby;
}
async renderNotebook(
notebook_ver: number,
diffKind: DIFF_TYPE
): Promise<DiffCell[]> {
/*
* First set up the basics that we'll need regardless of what kind of
* diff we're doing
*/
let focusedNotebook = this.history.store.getNotebook(notebook_ver);
let relativeToNotebook = notebook_ver;
if (relativeToNotebook < 0) relativeToNotebook = undefined;
let cellMap: { name: string; changes: ChangeType[] }[] = [];
/*
* Based on the diff kind, build a list of cells with changes
*/
if (diffKind === DIFF_TYPE.CHANGE_DIFF) {
let checkpoints = this.history.checkpoints.getForNotebook(
focusedNotebook
);
cellMap = CellMap.build(checkpoints, this.history);
} else if (diffKind === DIFF_TYPE.PRESENT_DIFF) {
let currentNotebook = this.history.store.currentNotebook;
relativeToNotebook = currentNotebook?.version;
cellMap = this.zipNotebooks(focusedNotebook, currentNotebook);
} else if (diffKind === DIFF_TYPE.NO_DIFF) {
cellMap = focusedNotebook.cells.map((name) => {
return { name, changes: [] };
});
}
/*
* For each cell, render line-level diff notation
*/
return Promise.all(
cellMap.map(async (value: { name: string; changes: ChangeType[] }) => {
const name = value.name;
const status = value.changes;
let cell = this.history.store.get(name);
let diff = diffKind;
if (status.includes(ChangeType.REMOVED)) diff = DIFF_TYPE.NO_DIFF;
const sample = await this.renderCell(cell, diff, relativeToNotebook);
return { sample, status, name };
})
);
}
public async renderCell(
nodey: Nodey,
diffKind: DIFF_TYPE = DIFF_TYPE.NO_DIFF,
relativeToNotebook?: number
): Promise<HTMLElement> {
const [sample, elem] = this.sampler.makeSampleDivs(nodey);
if (nodey instanceof NodeyCode) {
this.diffCode(nodey, elem, diffKind, relativeToNotebook);
} else if (nodey instanceof NodeyMarkdown) {
await this.diffMarkdown(nodey, elem, diffKind, relativeToNotebook);
} else if (nodey instanceof NodeyRawCell) {
// raw can be treated the same as code
this.diffCode(nodey, elem, diffKind, relativeToNotebook);
} else if (nodey instanceof NodeyOutput) {
await this.diffOutput(nodey, elem, diffKind, relativeToNotebook);
}
return sample;
}
private getOldNewText(
nodey: Nodey,
diffKind: DIFF_TYPE,
relativeToNotebook?: number
): [string, string, DIFF_TYPE] {
// first get text of the current nodey
let newText = this.sampler.nodeToText(nodey);
// now get text of prior nodey
let [priorNodey, fixedDiffKind] = this.getPrior(
nodey,
diffKind,
relativeToNotebook
);
let oldText = ""; // default to no string if no prior nodey
// otherwise make oldText the value of priorNodey
if (priorNodey) oldText = this.sampler.nodeToText(priorNodey);
return [newText, oldText, fixedDiffKind];
}
private getPrior(
nodey: Nodey,
diffKind: DIFF_TYPE,
relativeToNotebook?: number
): [Nodey | undefined, DIFF_TYPE] {
// now get text of prior nodey
let nodeyHistory = this.history.store?.getHistoryOf(nodey);
let priorNodey = undefined;
let cellParent = undefined;
if (nodey instanceof NodeyOutput) {
cellParent = this.history.store?.get(nodey.parent);
}
if (diffKind === DIFF_TYPE.CHANGE_DIFF) {
priorNodey = nodeyHistory?.getVersion(nodey.version - 1);
/*
* If relative to a checkpoint, check that changes to this nodey occurs
* no earlier than the checkpoint immediately previous so that we
* don't get irrelevant old changes showing up in diffs (ghost book only)
*/
if (relativeToNotebook !== undefined) {
let notebook = this.history?.store.getNotebookOf(nodey);
if (!notebook || notebook?.version < relativeToNotebook) {
priorNodey = undefined;
diffKind = DIFF_TYPE.NO_DIFF;
} else {
if (!priorNodey && cellParent) {
let rel = this.history?.store.getNotebook(relativeToNotebook);
priorNodey = this.history?.store?.getOutputForNotebook(
cellParent,
rel
);
}
}
}
} else if (diffKind === DIFF_TYPE.PRESENT_DIFF) {
if (cellParent) {
// output
let curr = this.history?.store.currentNotebook;
let latestParent = this.history.store.getHistoryOf(cellParent)
?.latest as NodeyCode;
priorNodey = this.history?.store?.getOutputForNotebook(
latestParent,
curr
);
} else priorNodey = nodeyHistory?.latest;
}
return [priorNodey, diffKind];
}
private diffCode(
nodey: Nodey,
elem: HTMLElement,
diffKind: number = DIFF_TYPE.NO_DIFF,
relativeToNotebook?: number
) {
let [newText, oldText, fixedDiffKind] = this.getOldNewText(
nodey,
diffKind,
relativeToNotebook
);
diffKind = fixedDiffKind;
// If no diff necessary, use plain code
if (diffKind === DIFF_TYPE.NO_DIFF) {
return this.sampler.plainCode(elem, newText);
}
if (diffKind === DIFF_TYPE.PRESENT_DIFF) {
// swap old and new, since "old" is actually the present notebook
return this.diffText(newText, oldText, elem);
}
return this.diffText(oldText, newText, elem);
}
diffText(oldText: string, newText: string, elem: HTMLElement) {
// Split new text into lines
let newLines = (newText || "").split("\n");
// Split old text into lines
let oldLines = (oldText || "").split("\n");
// Loop over lines and append diffs to elem
const maxLength = Math.max(newLines.length, oldLines.length);
for (let i = 0; i < maxLength; i++) {
let newLine = newLines[i] || "";
let oldLine = oldLines[i] || "";
elem.appendChild(this.diffLine(oldLine, newLine));
}
return elem;
}
diffLine(oldText: string, newText: string) {
/* Diffs a single line. */
let line = document.createElement("div");
let innerHTML = "";
let diff = JSDiff.diffWords(oldText, newText);
if (diff.length > MAX_WORD_DIFFS) diff = JSDiff.diffLines(oldText, newText);
diff.forEach((part) => {
let partDiv = document.createElement("span");
//log("DIFF", part);
partDiv.textContent = part.value;
if (part.added) {
partDiv.classList.add(CHANGE_ADDED_CLASS);
innerHTML += partDiv.outerHTML;
} else if (part.removed) {
partDiv.classList.add(CHANGE_REMOVED_CLASS);
innerHTML += partDiv.outerHTML;
} else {
innerHTML += part.value;
}
});
line.innerHTML = innerHTML;
return line;
}
async diffMarkdown(
nodey: NodeyMarkdown,
elem: HTMLElement,
diffKind: number = DIFF_TYPE.NO_DIFF,
relativeToNotebook?: number
) {
let [newText, oldText, fixedDiffKind] = this.getOldNewText(
nodey,
diffKind,
relativeToNotebook
);
diffKind = fixedDiffKind;
if (diffKind === DIFF_TYPE.PRESENT_DIFF) {
// swap old and new, since "old" is actually the present notebook
let temp = oldText;
oldText = newText;
newText = temp;
}
// If no diff necessary, use plain markdown
if (diffKind === DIFF_TYPE.NO_DIFF)
await this.renderBaby.renderMarkdown(elem, newText);
else {
let diff = JSDiff.diffWords(oldText, newText);
if (diff.length > MAX_WORD_DIFFS) {
diff = JSDiff.diffLines(oldText, newText, { newlineIsToken: true });
}
const divs = diff.map(async (part) => {
let partDiv: HTMLElement;
if (part.value === "\n") {
partDiv = document.createElement("br");
partDiv.classList.add(MARKDOWN_LINEBREAK);
} else {
partDiv = document.createElement("span");
await this.renderBaby.renderMarkdown(partDiv, part.value);
partDiv.classList.add(CHANGE_SAME_CLASS);
if (part.added) {
partDiv.classList.add(CHANGE_ADDED_CLASS);
} else if (part.removed) {
partDiv.classList.add(CHANGE_REMOVED_CLASS);
}
}
return partDiv;
});
await Promise.all(divs).then((elems) =>
elems.forEach((e) => elem.appendChild(e))
);
}
return elem;
}
async diffOutput(
nodey: NodeyOutput,
elem: HTMLElement,
diffKind: number,
relativeToNotebook?: number
) {
let [priorNodey, fixedDiffType] = this.getPrior(
nodey,
diffKind,
relativeToNotebook
);
if (diffKind === DIFF_TYPE.PRESENT_DIFF) {
// swap old and new, since "old" is actually the present notebook
let temp = priorNodey as NodeyOutput;
priorNodey = nodey;
nodey = temp;
}
if (fixedDiffType === DIFF_TYPE.NO_DIFF || priorNodey?.name === nodey?.name)
await this.sampler.renderOutput(nodey, elem);
else {
// just show side by side
let old = document.createElement("div");
old.classList.add("v-Verdant-output-sideBySide");
old.classList.add(CHANGE_REMOVED_CLASS);
if (priorNodey)
await this.sampler.renderOutput(priorNodey as NodeyOutput, old);
elem.appendChild(old);
let newOut = document.createElement("div");
newOut.classList.add("v-Verdant-output-sideBySide");
newOut.classList.add(CHANGE_ADDED_CLASS);
await this.sampler.renderOutput(nodey, newOut);
elem.appendChild(newOut);
}
return elem;
}
private zipNotebooks(
A: NodeyNotebook,
B: NodeyNotebook
): { name: string; changes: ChangeType[] }[] {
let cellMap: { name: string; changes: ChangeType[] }[] = [];
let cellsInA = A.cells.map((name) => {
return this.history.store.get(name)?.artifactName;
});
let cellsInB = B.cells.map((name) => {
return this.history.store.get(name)?.artifactName;
});
let diff = JSDiff.diffArrays(cellsInA, cellsInB);
let indexA = 0;
let indexB = 0;
diff.map((part) => {
if (part.added) {
// these cells are only in B
part.value.forEach(() => {
let cellB = B.cells[indexB];
cellMap.push({ name: cellB, changes: [ChangeType.ADDED] });
indexB++;
});
} else if (part.removed) {
// these cells are only in A
part.value.forEach(() => {
let cellA = A.cells[indexA];
cellMap.push({ name: cellA, changes: [ChangeType.REMOVED] });
indexA++;
});
} else {
// these cells are in both notebooks
part.value.forEach(() => {
let cellA = A.cells[indexA];
let cellB = B.cells[indexB];
let status = cellA === cellB ? ChangeType.NONE : ChangeType.CHANGED;
// Check has output changed?
if (status === ChangeType.NONE) {
// assuming they're the same version, is this cell code
let nodey = this.history.store.get(cellA);
if (nodey instanceof NodeyCode) {
let outA = this.history.store.getOutputForNotebook(nodey, A);
let outB = this.history.store.getOutputForNotebook(nodey, B);
if (outA && outB && outA !== outB) {
status = ChangeType.OUTPUT_CHANGED;
}
}
}
cellMap.push({ name: cellA, changes: [status] });
indexA++;
indexB++;
});
}
});
//console.log("CURRENT DIFF CELL MAP", cellMap);
return cellMap;
}
} | the_stack |
import {ChunkManager, ChunkSource} from 'neuroglancer/chunk_manager/frontend';
import {IndexedSegmentProperty} from 'neuroglancer/segmentation_display_state/base';
import {Uint64Set} from 'neuroglancer/uint64_set';
import {mergeSequences, TypedArray, TypedArrayConstructor, WritableArrayLike} from 'neuroglancer/util/array';
import {DataType} from 'neuroglancer/util/data_type';
import {Borrowed} from 'neuroglancer/util/disposable';
import {murmurHash3_x86_32Hash64Bits} from 'neuroglancer/util/hash';
import {clampToInterval, dataTypeCompare, DataTypeInterval, dataTypeIntervalEqual, dataTypeValueNextAfter, parseDataTypeValue} from 'neuroglancer/util/lerp';
import {getObjectId} from 'neuroglancer/util/object_id';
import {defaultStringCompare} from 'neuroglancer/util/string';
import {Uint64} from 'neuroglancer/util/uint64';
export type InlineSegmentProperty =
InlineSegmentStringProperty|InlineSegmentTagsProperty|InlineSegmentNumericalProperty;
export interface InlineSegmentStringProperty {
id: string;
type: 'string'|'label'|'description';
description?: string|undefined;
values: string[];
}
export interface InlineSegmentTagsProperty {
id: string;
type: 'tags';
tags: string[];
// Must be the same length as `tags`.
tagDescriptions: string[];
// Each value is a string, where the character code indicates the tag. For example,
// "\u0001\u0010" indicates tags [1, 16]. The character codes must be distinct and sorted.
values: string[];
}
export interface InlineSegmentNumericalProperty {
id: string;
type: 'number';
dataType: DataType;
description: string|undefined;
values: TypedArray;
bounds: DataTypeInterval;
}
export interface InlineSegmentPropertyMap {
// Specifies low/high 32-bit portions of ids.
ids: Uint32Array;
properties: InlineSegmentProperty[];
}
export interface IndexedSegmentPropertyMapOptions {
properties: readonly Readonly<IndexedSegmentProperty>[];
}
export class IndexedSegmentPropertySource extends ChunkSource {
OPTIONS: IndexedSegmentPropertyMapOptions;
properties: readonly Readonly<IndexedSegmentProperty>[];
constructor(chunkManager: Borrowed<ChunkManager>, options: IndexedSegmentPropertyMapOptions) {
super(chunkManager, options);
this.properties = options.properties;
}
static encodeOptions(options: IndexedSegmentPropertyMapOptions): {[key: string]: any} {
return {properties: options.properties};
}
}
function insertIntoLinearChainingTable(table: TypedArray, hashCode: number, value: number) {
const mask = table.length - 1;
while (true) {
hashCode = hashCode & mask;
if (table[hashCode] === 0) {
table[hashCode] = value;
return;
}
++hashCode;
}
}
export type IndicesArray = Uint32Array|Uint16Array|Uint8Array;
function makeIndicesArray(size: number, maxValue: number): IndicesArray {
if (maxValue <= 0xff) {
return new Uint8Array(size);
}
if (maxValue <= 0xffff) {
return new Uint16Array(size);
}
return new Uint32Array(size);
}
function makeUint64PermutationHashMap(values: Uint32Array): IndicesArray {
// Use twice the next power of 2 as the size. This ensures a load factor <= 0.5.
const numEntries = values.length / 2;
const hashCodeBits = Math.ceil(Math.log2(numEntries)) + 1;
const size = 2 ** hashCodeBits;
const table = makeIndicesArray(size, numEntries + 1);
for (let i = 0; i < numEntries; ++i) {
const low = values[2 * i];
const high = values[2 * i + 1];
insertIntoLinearChainingTable(
table, murmurHash3_x86_32Hash64Bits(/*seed=*/ 0, low, high), i + 1);
}
return table;
}
function queryUint64PermutationHashMap(
table: TypedArray, values: Uint32Array, low: number, high: number): number {
let hashCode = murmurHash3_x86_32Hash64Bits(/*seed=*/ 0, low, high);
const mask = table.length - 1;
while (true) {
hashCode = hashCode & mask;
let index = table[hashCode];
if (index === 0) return -1;
--index;
if (values[2 * index] === low && values[2 * index + 1] === high) {
return index;
}
++hashCode;
}
}
export class SegmentPropertyMap {
inlineProperties: InlineSegmentPropertyMap|undefined;
constructor(options: {inlineProperties?: InlineSegmentPropertyMap|undefined}) {
this.inlineProperties = options.inlineProperties;
}
}
export class PreprocessedSegmentPropertyMap {
// Linear-chaining hash table that maps uint64 ids to indices into `inlineProperties.ids`.
inlineIdToIndex: IndicesArray|undefined;
tags: InlineSegmentTagsProperty|undefined;
labels: InlineSegmentStringProperty|undefined;
numericalProperties: InlineSegmentNumericalProperty[];
getSegmentInlineIndex(id: Uint64): number {
const {inlineIdToIndex} = this;
if (inlineIdToIndex === undefined) return -1;
return queryUint64PermutationHashMap(
inlineIdToIndex, this.segmentPropertyMap.inlineProperties!.ids, id.low, id.high);
}
constructor(public segmentPropertyMap: SegmentPropertyMap) {
const {inlineProperties} = segmentPropertyMap;
if (inlineProperties !== undefined) {
this.inlineIdToIndex = makeUint64PermutationHashMap(inlineProperties.ids);
}
this.tags =
inlineProperties?.properties.find(p => p.type === 'tags') as InlineSegmentTagsProperty |
undefined;
this.labels =
inlineProperties?.properties.find(p => p.type === 'label') as InlineSegmentStringProperty |
undefined;
this.numericalProperties = (inlineProperties?.properties.filter(p => p.type === 'number') ??
[]) as InlineSegmentNumericalProperty[];
}
getSegmentLabel(id: Uint64): string|undefined {
const index = this.getSegmentInlineIndex(id);
if (index === -1) return undefined;
const {labels, tags: tagsProperty} = this;
let label = '';
if (labels !== undefined) {
label = labels.values[index];
}
if (tagsProperty !== undefined) {
const {tags, values} = tagsProperty;
let tagIndices = values[index];
for (let i = 0, length = tagIndices.length; i < length; ++i) {
const tag = tags[tagIndices.charCodeAt(i)];
if (label.length > 0) {
label += ' ';
}
label += '#';
label += tag;
}
}
if (label.length === 0) return undefined;
return label;
}
}
function remapArray<T>(input: ArrayLike<T>, output: WritableArrayLike<T>, toMerged: IndicesArray) {
for (let i = 0, length = toMerged.length; i < length; ++i) {
output[toMerged[i]] = input[i];
}
}
function isIdArraySorted(ids: Uint32Array): boolean {
const n = ids.length;
if (n === 0) return true;
let prevLow = ids[0], prevHigh = ids[1];
for (let i = 0; i < n; i += 2) {
const low = ids[i], high = ids[i + 1];
if (((high - prevHigh) || (low - prevLow)) <= 0) return false;
prevLow = low;
prevHigh = high;
}
return true;
}
export function normalizeInlineSegmentPropertyMap(inlineProperties: InlineSegmentPropertyMap):
InlineSegmentPropertyMap {
// Check if ids are already sorted.
const {ids} = inlineProperties;
if (isIdArraySorted(ids)) {
return inlineProperties;
}
const length = ids.length / 2;
const permutation = makeIndicesArray(length, length - 1);
for (let i = 0; i < length; ++i) {
permutation[i] = i;
}
permutation.sort((a, b) => {
const aLow = ids[a * 2], aHigh = ids[a * 2 + 1];
const bLow = ids[b * 2], bHigh = ids[b * 2 + 1];
return (aHigh - bHigh) || (aLow - bLow);
});
const newIds = new Uint32Array(length * 2);
for (let newIndex = 0; newIndex < length; ++newIndex) {
const oldIndex = permutation[newIndex];
newIds[newIndex * 2] = ids[oldIndex * 2];
newIds[newIndex * 2 + 1] = ids[oldIndex * 2 + 1];
}
const properties = inlineProperties.properties.map(property => {
const {values} = property;
const newValues = new (values.constructor as (TypedArrayConstructor | typeof Array))(length);
for (let i = 0; i < length; ++i) {
newValues[i] = values[permutation[i]];
}
return {...property, values: newValues} as InlineSegmentProperty;
});
return {ids: newIds, properties};
}
function remapStringProperty(
property: InlineSegmentStringProperty|InlineSegmentTagsProperty, numMerged: number,
toMerged: Uint32Array): InlineSegmentStringProperty|InlineSegmentTagsProperty {
const values = new Array<string>(numMerged);
values.fill('');
remapArray(property.values, values, toMerged);
return {...property, values};
}
function remapNumericalProperty(
property: InlineSegmentNumericalProperty, numMerged: number,
toMerged: Uint32Array): InlineSegmentNumericalProperty {
const values = new Float32Array(numMerged);
values.fill(Number.NaN);
remapArray(property.values, values, toMerged);
return {...property, values};
}
function remapProperty(property: InlineSegmentProperty, numMerged: number, toMerged: Uint32Array):
InlineSegmentProperty {
const {type} = property;
if (type === 'label' || type === 'description' || type === 'string' || type === 'tags') {
return remapStringProperty(
property as InlineSegmentStringProperty | InlineSegmentTagsProperty, numMerged, toMerged);
}
return remapNumericalProperty(property as InlineSegmentNumericalProperty, numMerged, toMerged);
}
function mergeInlinePropertyMaps(
a: InlineSegmentPropertyMap|undefined,
b: InlineSegmentPropertyMap|undefined): InlineSegmentPropertyMap|undefined {
if (a === undefined) return b;
if (b === undefined) return a;
// Determine number of unique ids and mapping from `a` and `b` indices to joined indices.
let numUnique = 0;
const aCount = a.ids.length / 2;
const bCount = b.ids.length / 2;
const aToMerged = new Uint32Array(aCount), bToMerged = new Uint32Array(bCount);
const aIds = a.ids, bIds = b.ids;
mergeSequences(
aCount, bCount,
(a, b) => {
const aHigh = aIds[2 * a + 1];
const aLow = aIds[2 * a];
const bHigh = bIds[2 * b + 1];
const bLow = bIds[2 * b];
return (aHigh - bHigh) || (aLow - bLow);
},
a => {
aToMerged[a] = numUnique;
++numUnique;
},
b => {
bToMerged[b] = numUnique;
++numUnique;
},
(a, b) => {
aToMerged[a] = numUnique;
bToMerged[b] = numUnique;
++numUnique;
});
let ids: Uint32Array;
if (numUnique === aCount) {
ids = aIds;
} else if (numUnique === bCount) {
ids = bIds;
} else {
ids = new Uint32Array(numUnique * 2);
for (let a = 0; a < aCount; ++a) {
const i = aToMerged[a];
ids[2 * i] = aIds[2 * a];
ids[2 * i + 1] = aIds[2 * a + 1];
}
for (let b = 0; b < bCount; ++b) {
const i = bToMerged[b];
ids[2 * i] = bIds[2 * b];
ids[2 * i + 1] = bIds[2 * b + 1];
}
}
const properties: InlineSegmentProperty[] = [];
if (numUnique === aCount) {
properties.push(...a.properties);
} else {
for (const property of a.properties) {
properties.push(remapProperty(property, numUnique, aToMerged));
}
}
if (numUnique === bCount) {
properties.push(...b.properties);
} else {
for (const property of b.properties) {
properties.push(remapProperty(property, numUnique, bToMerged));
}
}
return {ids, properties};
}
function mergePropertyMaps(a: SegmentPropertyMap, b: SegmentPropertyMap) {
return new SegmentPropertyMap({
inlineProperties: mergeInlinePropertyMaps(a.inlineProperties, b.inlineProperties),
});
}
export function mergeSegmentPropertyMaps(maps: SegmentPropertyMap[]): SegmentPropertyMap|undefined {
while (true) {
if (maps.length === 0) return undefined;
if (maps.length === 1) return maps[0];
const merged: SegmentPropertyMap[] = [];
for (let i = 0, length = maps.length; i < length; i += 2) {
if (i + 1 === length) {
merged.push(maps[i]);
} else {
merged.push(mergePropertyMaps(maps[i], maps[i + 1]));
}
}
maps = merged;
}
}
export function getPreprocessedSegmentPropertyMap(
chunkManager: ChunkManager, maps: SegmentPropertyMap[]): PreprocessedSegmentPropertyMap|
undefined {
return chunkManager.memoize.getUncounted(
{id: 'getPreprocessedSegmentPropertyMap', maps: maps.map(m => getObjectId(m))}, () => {
const merged = mergeSegmentPropertyMaps(maps);
if (merged === undefined) return undefined;
return new PreprocessedSegmentPropertyMap(merged);
});
}
export interface SortBy {
fieldId: string;
order: '<'|'>';
}
export interface ExplicitIdQuery {
ids: Uint64[];
prefix?: undefined;
regexp?: undefined;
includeTags?: undefined;
excludeTags?: undefined;
numericalConstraints?: undefined;
sortBy?: undefined;
includeColumns?: undefined;
errors?: undefined;
}
export interface NumericalPropertyConstraint {
fieldId: string;
bounds: DataTypeInterval;
}
export interface FilterQuery {
ids?: undefined;
prefix: string|undefined, regexp: RegExp|undefined;
includeTags: string[];
excludeTags: string[];
numericalConstraints: NumericalPropertyConstraint[];
sortBy: SortBy[];
includeColumns: string[];
errors?: undefined;
}
export interface QueryParseError {
begin: number;
end: number;
message: string;
}
export interface QueryParseErrors {
errors: QueryParseError[];
ids?: undefined;
prefix?: undefined;
regexp?: undefined;
includeTags?: undefined;
excludeTags?: undefined;
numericalConstraints?: undefined;
sortBy?: undefined;
includeColumns?: undefined;
}
export type QueryParseResult = ExplicitIdQuery|FilterQuery|QueryParseErrors;
const idPattern = /^[,\s]*[0-9]+(?:[,\s]+[0-9]+)*[,\s]*$/;
export function parseSegmentQuery(
db: PreprocessedSegmentPropertyMap|undefined, queryString: string): QueryParseResult {
if (queryString.match(idPattern) !== null) {
const parts = queryString.split(/[\s,]+/);
const ids: Uint64[] = [];
const idSet = new Set<string>();
for (let i = 0, n = parts.length; i < n; ++i) {
const part = parts[i];
if (part === '') continue;
const id = new Uint64();
if (!id.tryParseString(part)) {
continue;
}
const idString = id.toString();
if (idSet.has(idString)) continue;
idSet.add(idString);
ids.push(id);
}
ids.sort(Uint64.compare);
return {ids};
}
const parsed: FilterQuery = {
regexp: undefined,
prefix: undefined,
includeTags: [],
excludeTags: [],
numericalConstraints: [],
sortBy: [],
includeColumns: [],
};
const properties = db?.segmentPropertyMap.inlineProperties?.properties;
const tags = db?.tags;
const tagNames = (tags?.tags || []);
const lowerCaseTags = tagNames.map(x => x.toLowerCase());
const labels = db?.labels;
const errors: QueryParseError[] = [];
let nextStartIndex: number;
for (let startIndex = 0; startIndex < queryString.length; startIndex = nextStartIndex) {
let endIndex = queryString.indexOf(' ', startIndex);
let word: string;
if (endIndex === -1) {
nextStartIndex = endIndex = queryString.length;
} else {
nextStartIndex = endIndex + 1;
}
word = queryString.substring(startIndex, endIndex);
if (word.length === 0) continue;
const checkTag = (tag: string, begin: number) => {
const lowerCaseTag = tag.toLowerCase();
const tagIndex = lowerCaseTags.indexOf(lowerCaseTag);
if (tagIndex === -1) {
errors.push({begin, end: endIndex, message: `Invalid tag: ${tag}`});
return undefined;
}
tag = tagNames[tagIndex];
if (parsed.includeTags.includes(tag) || parsed.excludeTags.includes(tag)) {
errors.push({begin, end: endIndex, message: `Duplicate tag: ${tag}`});
return undefined;
}
return tag;
};
if (word.startsWith('#')) {
const tag = checkTag(word.substring(1), startIndex + 1);
if (tag !== undefined) {
parsed.includeTags.push(tag);
}
continue;
}
if (word.startsWith('-#')) {
const tag = checkTag(word.substring(2), startIndex + 2);
if (tag !== undefined) {
parsed.excludeTags.push(tag);
}
continue;
}
if (word.startsWith('<') || word.startsWith('>')) {
let fieldId = word.substring(1).toLowerCase();
if (fieldId !== 'id' && fieldId !== 'label') {
const property = properties?.find(
p => p.id.toLowerCase() === fieldId &&
(p.type === 'number' || p.type === 'label' || p.type === 'string'));
if (property === undefined) {
errors.push({begin: startIndex + 1, end: endIndex, message: `Invalid field: ${fieldId}`});
continue;
}
fieldId = property.id;
}
if (parsed.sortBy.find(x => x.fieldId === fieldId) !== undefined) {
errors.push(
{begin: startIndex + 1, end: endIndex, message: `Duplicate sort field: ${fieldId}`});
continue;
}
parsed.sortBy.push({order: word[0] as '<' | '>', fieldId});
continue;
}
if (word.startsWith('|')) {
let fieldId = word.substring(1).toLowerCase();
if (fieldId === 'id' || fieldId === 'label') continue;
const property = properties?.find(
p => p.id.toLowerCase() === fieldId && (p.type === 'number' || p.type === 'string'));
if (property === undefined) {
errors.push({begin: startIndex + 1, end: endIndex, message: `Invalid field: ${fieldId}`});
continue;
}
fieldId = property.id;
if (parsed.sortBy.find(x => x.fieldId === fieldId) ||
parsed.includeColumns.find(x => x === fieldId)) {
// Ignore duplicate column.
continue;
}
parsed.includeColumns.push(fieldId);
continue;
}
if (word.startsWith('/')) {
if (parsed.regexp !== undefined) {
errors.push(
{begin: startIndex, end: endIndex, message: 'Only one regular expression allowed'});
continue;
}
if (parsed.prefix !== undefined) {
errors.push({
begin: startIndex,
end: endIndex,
message: 'Prefix cannot be combined with regular expression'
});
continue;
}
if (labels === undefined) {
errors.push({begin: startIndex, end: endIndex, message: 'No label property'});
continue;
}
try {
parsed.regexp = new RegExp(word.substring(1));
} catch (e) {
errors.push(
{begin: startIndex, end: endIndex, message: 'Invalid regular expression syntax'});
}
continue;
}
const constraintMatch = word.match(/^([a-zA-Z][a-zA-Z0-9_]*)(<|<=|=|>=|>)([0-9.].*)$/);
if (constraintMatch !== null) {
let fieldId = constraintMatch[1].toLowerCase();
const op = constraintMatch[2];
const property = db?.numericalProperties.find(p => p.id.toLowerCase() === fieldId);
if (property === undefined) {
errors.push({
begin: startIndex,
end: startIndex + fieldId.length,
message: `Invalid numerical field: ${fieldId}`
});
continue;
}
fieldId = property.id;
let value: number;
try {
value = parseDataTypeValue(property.dataType, constraintMatch[3]) as number;
} catch (e) {
errors.push({
begin: startIndex + constraintMatch[1].length + constraintMatch[2].length,
end: endIndex,
message: e.message,
});
continue;
}
let constraint = parsed.numericalConstraints.find(c => c.fieldId === fieldId);
if (constraint === undefined) {
constraint = {fieldId, bounds: property.bounds};
parsed.numericalConstraints.push(constraint);
}
const origMin = clampToInterval(property.bounds, constraint.bounds[0]),
origMax = clampToInterval(property.bounds, constraint.bounds[1]);
let newMax = origMax, newMin = origMin;
switch (op) {
case '<':
newMax = dataTypeValueNextAfter(property.dataType, value, -1);
break;
case '<=':
newMax = value;
break;
case '=':
newMax = newMin = value;
break;
case '>=':
newMin = value;
break;
case '>':
newMin = dataTypeValueNextAfter(property.dataType, value, +1);
break;
}
newMin = dataTypeCompare(origMin, newMin) > 0 ? origMin : newMin;
newMax = dataTypeCompare(origMax, newMax) < 0 ? origMax : newMax;
if (dataTypeCompare(newMin, newMax) > 0) {
errors.push(
{begin: startIndex, end: endIndex, message: 'Constraint would not match any values'});
continue;
}
constraint.bounds = [newMin, newMax] as DataTypeInterval;
continue;
}
if (parsed.regexp !== undefined) {
errors.push({
begin: startIndex,
end: endIndex,
message: 'Prefix cannot be combined with regular expression'
});
continue;
}
if (labels === undefined) {
errors.push({begin: startIndex, end: endIndex, message: 'No label property'});
continue;
}
if (parsed.prefix !== undefined) {
parsed.prefix += ` ${word}`;
} else {
parsed.prefix = word;
}
}
if (errors.length > 0) {
return {errors};
}
if (parsed.sortBy.length === 0) {
// Add default sort order.
parsed.sortBy.push({fieldId: getDefaultSortField(db), order: '<'});
}
return parsed;
}
export interface TagCount {
tag: string;
tagIndex: number;
count: number;
}
export interface PropertyHistogram {
// Solely serves to indicate whether this histogram is up to date.
queryResult: QueryResult;
window: DataTypeInterval;
histogram: Uint32Array;
}
export interface QueryResult {
query: QueryParseResult;
// Indices into the inline properties table that satisfy all constraints *except* numerical
// constraints. Sorting is also not applied.
intermediateIndices?: IndicesArray|undefined;
// Bitvectors for each index in `intermediateIndices`. Bit `i` is true if constraints on
// numerical property `i` are satisfied. This along with `intermediateIndices` is used to compute
// "marginal" histograms for the numerical properties, for the distribution with all other
// constraints applied, but without constraining the property for which we are computing the
// histogram.
intermediateIndicesMask?: Uint32Array|Uint16Array|Uint8Array|undefined;
// Indices into the inline properties table that satisfy all constraints. Sorting is applied.
indices?: IndicesArray|undefined;
explicitIds?: Uint64[]|undefined;
tags?: TagCount[]|undefined;
count: number;
total: number;
errors?: QueryParseError[]|undefined;
}
function regexpEscapeCharCode(code: number) {
return '\\u' + code.toString(16).padStart(4, '0');
}
export function executeSegmentQuery(
db: PreprocessedSegmentPropertyMap|undefined, query: QueryParseResult): QueryResult {
if (query.errors !== undefined) {
return {query, total: -1, count: 0, errors: query.errors};
}
if (query.ids !== undefined) {
const {ids} = query;
return {query, total: -1, explicitIds: ids, count: ids.length};
}
const inlineProperties = db?.segmentPropertyMap?.inlineProperties;
if (inlineProperties === undefined) {
return {
query,
count: 0,
total: -1,
};
}
const properties = inlineProperties?.properties;
const totalIds = inlineProperties.ids.length / 2;
let indices = makeIndicesArray(totalIds, totalIds);
for (let i = 0; i < totalIds; ++i) {
indices[i] = i;
}
const filterIndices = (predicate: (index: number) => boolean) => {
let length = indices.length;
let outIndex = 0;
for (let i = 0; i < length; ++i) {
const index = indices[i];
if (predicate(index)) {
indices[outIndex] = index;
++outIndex;
}
}
indices = indices.subarray(0, outIndex);
};
// Filter by label
if (query.regexp !== undefined || query.prefix !== undefined) {
const values = db!.labels!.values;
const {regexp, prefix} = query;
if (regexp !== undefined) {
filterIndices(index => values[index].match(regexp) !== null);
}
if (prefix !== undefined) {
filterIndices(index => values[index].startsWith(prefix));
}
}
// Filter by tags
const {includeTags, excludeTags} = query;
const tagsProperty = db!.tags;
if (includeTags.length > 0 || excludeTags.length > 0) {
// Since query was already validated, tags property must exist if tags were specified.
const {values, tags} = tagsProperty!;
const allTags = [];
for (const tag of includeTags) {
allTags.push([tags.indexOf(tag), 1]);
}
for (const tag of excludeTags) {
allTags.push([tags.indexOf(tag), 0]);
}
allTags.sort((a, b) => a[0] - b[0]);
let pattern = '^';
let prevTagIndex = 0;
const addSkipPattern = (endCode: number) => {
if (endCode < prevTagIndex) return;
pattern += `[${regexpEscapeCharCode(prevTagIndex)}-${regexpEscapeCharCode(endCode)}]*`;
};
for (const [tagIndex, sign] of allTags) {
addSkipPattern(tagIndex - 1);
if (sign) {
pattern += regexpEscapeCharCode(tagIndex);
}
prevTagIndex = tagIndex + 1;
}
addSkipPattern(0xffff);
pattern += '$';
const regexp = new RegExp(pattern);
filterIndices(index => values[index].match(regexp) !== null);
}
let intermediateIndicesMask: IndicesArray|undefined;
let intermediateIndices: IndicesArray|undefined;
// Filter by numerical properties.
const {numericalConstraints} = query;
if (numericalConstraints.length > 0) {
const numericalProperties = db!.numericalProperties;
const numNumericalConstraints = numericalConstraints.length;
const fullMask = 2 ** (numNumericalConstraints) - 1;
intermediateIndicesMask = makeIndicesArray(indices.length, fullMask);
for (let constraintIndex = 0; constraintIndex < numNumericalConstraints; ++constraintIndex) {
const constraint = numericalConstraints[constraintIndex];
const property = numericalProperties.find(p => p.id === constraint.fieldId)!;
const {values} = property;
const bit = 2 ** constraintIndex;
const [min, max] = constraint.bounds as [number, number];
for (let i = 0, n = indices.length; i < n; ++i) {
const value = values[indices[i]];
intermediateIndicesMask[i] |= bit * ((value >= min && value <= max) as any);
}
}
intermediateIndices = indices;
indices = intermediateIndices.slice();
let length = indices.length;
let outIndex = 0;
for (let i = 0; i < length; ++i) {
if (intermediateIndicesMask[i] === fullMask) {
indices[outIndex] = indices[i];
++outIndex;
}
}
indices = indices.subarray(0, outIndex);
}
// Compute tag statistics.
let tagStatistics: TagCount[] = [];
if (tagsProperty !== undefined) {
const tagStatisticsInQuery: TagCount[] = [];
const {tags, values} = tagsProperty;
const tagCounts = new Uint32Array(tags.length);
for (let i = 0, n = indices.length; i < n; ++i) {
const value = values[indices[i]];
for (let j = 0, m = value.length; j < m; ++j) {
++tagCounts[value.charCodeAt(j)];
}
}
for (let tagIndex = 0, numTags = tags.length; tagIndex < numTags; ++tagIndex) {
const count = tagCounts[tagIndex];
const tag = tags[tagIndex];
const tagCount = {tag, tagIndex, count: tagCounts[tagIndex]};
if (query.includeTags.includes(tag) || query.excludeTags.includes(tag)) {
tagStatisticsInQuery.push(tagCount);
} else if (count > 0) {
tagStatistics.push(tagCount);
}
}
tagStatisticsInQuery.push(...tagStatistics);
tagStatistics = tagStatisticsInQuery;
}
const sortByProperty = (property: InlineSegmentProperty, orderCoeff: number) => {
if (property.type !== 'number') {
const {values} = property;
indices.sort((a, b) => defaultStringCompare(values[a], values[b]) * orderCoeff);
} else {
const values = property.values as TypedArray;
indices.sort((a, b) => (values[a] - values[b]) * orderCoeff);
}
};
const sortByLabel = (orderCoeff: number) => {
// Sort by tags and then by label.
if (tagsProperty !== undefined) {
sortByProperty(tagsProperty, orderCoeff);
}
const labelsProperty = db?.labels;
if (labelsProperty !== undefined) {
sortByProperty(labelsProperty, orderCoeff);
}
};
// Sort. Apply the sort orders in reverse order to achieve the desired composite ordering, given
// that JavaScript's builtin sort is stable.
const {sortBy} = query;
for (let i = sortBy.length - 1; i >= 0; --i) {
const {fieldId, order} = sortBy[i];
const orderCoeff = order === '<' ? 1 : -1;
if (fieldId === 'id') {
if (i + 1 === sortBy.length) {
if (order === '<') {
// Default order, no need to sort.
continue;
} else {
indices.reverse();
continue;
}
}
indices.sort((a, b) => orderCoeff * (a - b));
continue;
} else if (fieldId === 'label') {
sortByLabel(orderCoeff);
} else {
sortByProperty(properties.find(p => p.id === fieldId)!, orderCoeff);
}
}
return {
query,
intermediateIndices,
intermediateIndicesMask,
indices,
tags: tagStatistics,
count: indices.length,
total: totalIds,
};
}
function updatePropertyHistogram(
queryResult: QueryResult, property: InlineSegmentNumericalProperty,
bounds: DataTypeInterval): PropertyHistogram {
const numBins = 256;
const {values} = property;
const [min, max] = bounds as [number, number];
const multiplier = max <= min ? 0 : (numBins / (max - min));
const histogram = new Uint32Array(numBins + 2);
const {numericalConstraints} = queryResult!.query as FilterQuery;
const constraintIndex = numericalConstraints.findIndex(c => c.fieldId === property.id);
if (constraintIndex === -1) {
// Property is unconstrained, just compute histogram from final result set.
const indices = queryResult.indices!;
for (let i = 0, n = indices.length; i < n; ++i) {
const value = values[indices[i]];
if (!isNaN(value)) {
++histogram[(Math.min(numBins - 1, Math.max(-1, (value - min) * multiplier)) + 1) >>> 0];
}
}
} else {
// Property is constrained, compute histogram from intermediateIndices.
const intermediateIndices = queryResult.intermediateIndices!;
const intermediateIndicesMask = queryResult.intermediateIndicesMask!;
const requiredBits = 2 ** (numericalConstraints.length) - 1 - 2 ** constraintIndex;
for (let i = 0, n = intermediateIndices.length; i < n; ++i) {
const mask = intermediateIndicesMask[i];
if ((mask & requiredBits) == requiredBits) {
const value = values[intermediateIndices[i]];
if (!isNaN(value)) {
++histogram[(Math.min(numBins - 1, Math.max(-1, (value - min) * multiplier)) + 1) >>> 0];
}
}
}
}
return {queryResult, histogram, window: bounds};
}
export function updatePropertyHistograms(
db: PreprocessedSegmentPropertyMap|undefined, queryResult: QueryResult|undefined,
propertyHistograms: PropertyHistogram[], bounds: DataTypeInterval[]) {
if (db === undefined) {
propertyHistograms.length = 0;
bounds.length = 0;
return;
}
const {numericalProperties} = db;
const numProperties = numericalProperties.length;
const indices = queryResult?.indices;
if (indices === undefined) {
propertyHistograms.length = 0;
return;
}
for (let i = 0; i < numProperties; ++i) {
const propertyHistogram = propertyHistograms[i];
const propertyBounds = bounds[i];
const property = numericalProperties[i];
if (propertyHistogram !== undefined && propertyHistogram.queryResult === queryResult &&
dataTypeIntervalEqual(property.dataType, propertyHistogram.window, propertyBounds)) {
continue;
}
propertyHistograms[i] = updatePropertyHistogram(queryResult!, property, propertyBounds);
}
}
function getDefaultSortField(db: PreprocessedSegmentPropertyMap|undefined) {
return db?.tags || db?.labels ? 'label' : 'id';
}
export function unparseSegmentQuery(
db: PreprocessedSegmentPropertyMap|undefined, query: ExplicitIdQuery|FilterQuery): string {
const {ids} = query;
if (ids !== undefined) {
return ids.map(x => x.toString()).join(', ');
}
let queryString = '';
query = query as FilterQuery;
const {prefix, regexp} = query;
if (prefix !== undefined) {
queryString = prefix
} else if (regexp !== undefined) {
queryString = `/${regexp}`;
}
for (const tag of query.includeTags) {
if (queryString.length > 0) queryString += ' ';
queryString += `#${tag}`;
}
for (const tag of query.excludeTags) {
if (queryString.length > 0) queryString += ' ';
queryString += `-#${tag}`;
}
for (const constraint of query.numericalConstraints) {
const {fieldId, bounds} = constraint;
const [min, max] = bounds as [number, number];
const property = db!.numericalProperties.find(p => p.id === fieldId)!;
if (dataTypeIntervalEqual(property.dataType, property.bounds, bounds)) {
continue;
}
if (dataTypeCompare(min, max) === 0) {
if (queryString.length > 0) queryString += ' ';
queryString += `${fieldId}=${min}`;
continue;
}
if (dataTypeCompare(min, property.bounds[0]) > 0) {
if (queryString.length > 0) queryString += ' ';
const beforeMin = dataTypeValueNextAfter(property.dataType, min, -1);
const minString = min.toString();
const beforeMinString = beforeMin.toString();
if (property.dataType !== DataType.FLOAT32 || minString.length <= beforeMinString.length) {
queryString += `${fieldId}>=${minString}`;
} else {
queryString += `${fieldId}>${beforeMinString}`;
}
}
if (dataTypeCompare(max, property.bounds[1]) < 0) {
if (queryString.length > 0) queryString += ' ';
const afterMax = dataTypeValueNextAfter(property.dataType, max, +1);
const maxString = max.toString();
const afterMaxString = afterMax.toString();
if (property.dataType !== DataType.FLOAT32 || maxString.length <= afterMaxString.length) {
queryString += `${fieldId}<=${maxString}`;
} else {
queryString += `${fieldId}<${afterMaxString}`;
}
}
}
let {sortBy} = query;
if (sortBy.length === 1) {
const s = sortBy[0];
if (s.order === '<' && s.fieldId === getDefaultSortField(db)) {
sortBy = [];
}
}
for (const s of sortBy) {
if (queryString.length > 0) queryString += ' ';
queryString += `${s.order}${s.fieldId}`;
}
for (const fieldId of query.includeColumns) {
if (queryString.length > 0) queryString += ' ';
queryString += `|${fieldId}`;
}
return queryString;
}
const tempUint64 = new Uint64();
export function forEachQueryResultSegmentId(
db: PreprocessedSegmentPropertyMap|undefined, queryResult: QueryResult|undefined,
callback: (id: Uint64, index: number) => void) {
if (queryResult === undefined) return;
const {explicitIds} = queryResult;
if (explicitIds !== undefined) {
explicitIds.forEach(callback);
return;
}
const {indices} = queryResult;
if (indices !== undefined) {
const {ids} = db?.segmentPropertyMap.inlineProperties!;
for (let i = 0, count = indices.length; i < count; ++i) {
const propIndex = indices[i];
tempUint64.low = ids[propIndex * 2];
tempUint64.high = ids[propIndex * 2 + 1];
callback(tempUint64, i);
}
}
}
export function findQueryResultIntersectionSize(
db: PreprocessedSegmentPropertyMap|undefined, queryResult: QueryResult|undefined,
segmentSet: Uint64Set): number {
if (segmentSet.size === 0) return 0;
let count = 0;
forEachQueryResultSegmentId(db, queryResult, id => {
if (segmentSet.has(id)) ++count;
});
return count;
}
export function changeTagConstraintInSegmentQuery(
query: FilterQuery, tag: string, include: boolean, value: boolean): FilterQuery {
const includeTags = query.includeTags.filter(x => x !== tag);
const excludeTags = query.excludeTags.filter(x => x !== tag);
if (value === true) {
(include ? includeTags : excludeTags).push(tag);
}
return {...query, includeTags, excludeTags};
}
export function isQueryUnconstrained(query: QueryParseResult) {
if (query.ids !== undefined) return false;
if (query.errors !== undefined) return true;
if (query.numericalConstraints.length > 0) return false;
if (query.includeTags.length > 0) return false;
if (query.excludeTags.length > 0) return false;
if (query.prefix) return false;
if (query.regexp) return false;
return true;
}
export function queryIncludesColumn(query: QueryParseResult|undefined, fieldId: string) {
if (query === undefined) return false;
if (query.ids !== undefined) return false;
if (query.errors !== undefined) return false;
const {sortBy, includeColumns} = query;
return sortBy.find(x => x.fieldId === fieldId) !== undefined || includeColumns.includes(fieldId);
} | the_stack |
import {
cleanValueOfQuotes,
copy,
ExpressionType,
getExpressionType,
getKeyAndValueByExpressionType,
hasOwn,
isEqual,
isNotEqual,
isNotExpression
} from './utility.functions';
import {Injectable} from '@angular/core';
import {isArray, isDefined, isEmpty, isMap, isNumber, isObject, isString} from './validator.functions';
/**
* 'JsonPointer' class
*
* Some utilities for using JSON Pointers with JSON objects
* https://tools.ietf.org/html/rfc6901
*
* get, getCopy, getFirst, set, setCopy, insert, insertCopy, remove, has, dict,
* forEachDeep, forEachDeepCopy, escape, unescape, parse, compile, toKey,
* isJsonPointer, isSubPointer, toIndexedPointer, toGenericPointer,
* toControlPointer, toSchemaPointer, toDataPointer, parseObjectPath
*
* Some functions based on manuelstofer's json-pointer utilities
* https://github.com/manuelstofer/json-pointer
*/
export type Pointer = string | string[];
@Injectable()
export class JsonPointer {
/**
* 'get' function
*
* Uses a JSON Pointer to retrieve a value from an object.
*
* // { object } object - Object to get value from
* // { Pointer } pointer - JSON Pointer (string or array)
* // { number = 0 } startSlice - Zero-based index of first Pointer key to use
* // { number } endSlice - Zero-based index of last Pointer key to use
* // { boolean = false } getBoolean - Return only true or false?
* // { boolean = false } errors - Show error if not found?
* // { object } - Located value (or true or false if getBoolean = true)
*/
static get(
object, pointer, startSlice = 0, endSlice: number = null,
getBoolean = false, errors = false
) {
if (object === null) { return getBoolean ? false : undefined; }
let keyArray: any[] = this.parse(pointer, errors);
if (typeof object === 'object' && keyArray !== null) {
let subObject = object;
if (startSlice >= keyArray.length || endSlice <= -keyArray.length) { return object; }
if (startSlice <= -keyArray.length) { startSlice = 0; }
if (!isDefined(endSlice) || endSlice >= keyArray.length) { endSlice = keyArray.length; }
keyArray = keyArray.slice(startSlice, endSlice);
for (let key of keyArray) {
if (key === '-' && isArray(subObject) && subObject.length) {
key = subObject.length - 1;
}
if (isMap(subObject) && subObject.has(key)) {
subObject = subObject.get(key);
} else if (typeof subObject === 'object' && subObject !== null &&
hasOwn(subObject, key)
) {
subObject = subObject[key];
} else {
const evaluatedExpression = JsonPointer.evaluateExpression(subObject, key);
if (evaluatedExpression.passed) {
subObject = evaluatedExpression.key ? subObject[evaluatedExpression.key] : subObject;
} else {
this.logErrors(errors, key, pointer, object);
return getBoolean ? false : undefined;
}
}
}
return getBoolean ? true : subObject;
}
if (errors && keyArray === null) {
console.error(`get error: Invalid JSON Pointer: ${pointer}`);
}
if (errors && typeof object !== 'object') {
console.error('get error: Invalid object:');
console.error(object);
}
return getBoolean ? false : undefined;
}
private static logErrors(errors, key, pointer, object) {
if (errors) {
console.error(`get error: "${key}" key not found in object.`);
console.error(pointer);
console.error(object);
}
}
/**
* Evaluates conditional expression in form of `model.<property>==<value>` or
* `model.<property>!=<value>` where the first one means that the value must match to be
* shown in a form, while the former shows the property only when the property value is not
* set, or does not equal the given value.
*
* // { subObject } subObject - an object containing the data values of properties
* // { key } key - the key from the for loop in a form of `<property>==<value>`
*
* Returns the object with two properties. The property passed informs whether
* the expression evaluated successfully and the property key returns either the same
* key if it is not contained inside the subObject or the key of the property if it is contained.
*/
static evaluateExpression(subObject: Object, key: any) {
const defaultResult = {passed: false, key: key};
const keysAndExpression = this.parseKeysAndExpression(key, subObject);
if (!keysAndExpression) {
return defaultResult;
}
const ownCheckResult = this.doOwnCheckResult(subObject, keysAndExpression);
if (ownCheckResult) {
return ownCheckResult;
}
const cleanedValue = cleanValueOfQuotes(keysAndExpression.keyAndValue[1]);
const evaluatedResult = this.performExpressionOnValue(keysAndExpression, cleanedValue, subObject);
if (evaluatedResult) {
return evaluatedResult;
}
return defaultResult;
}
/**
* Performs the actual evaluation on the given expression with given values and keys.
* // { cleanedValue } cleanedValue - the given valued cleaned of quotes if it had any
* // { subObject } subObject - the object with properties values
* // { keysAndExpression } keysAndExpression - an object holding the expressions with
*/
private static performExpressionOnValue(keysAndExpression: any, cleanedValue: String, subObject: Object) {
const propertyByKey = subObject[keysAndExpression.keyAndValue[0]];
if (this.doComparisonByExpressionType(keysAndExpression.expressionType, propertyByKey, cleanedValue)) {
return {passed: true, key: keysAndExpression.keyAndValue[0]};
}
return null;
}
private static doComparisonByExpressionType(expressionType: ExpressionType, propertyByKey, cleanedValue: String): Boolean {
if (isEqual(expressionType)) {
return propertyByKey === cleanedValue;
}
if (isNotEqual(expressionType)) {
return propertyByKey !== cleanedValue;
}
return false;
}
/**
* Does the checks when the parsed key is actually no a property inside subObject.
* That would mean that the equal comparison makes no sense and thus the negative result
* is returned, and the not equal comparison is not necessary because it doesn't equal
* obviously. Returns null when the given key is a real property inside the subObject.
* // { subObject } subObject - the object with properties values
* // { keysAndExpression } keysAndExpression - an object holding the expressions with
* the associated keys.
*/
private static doOwnCheckResult(subObject: Object, keysAndExpression) {
let ownCheckResult = null;
if (!hasOwn(subObject, keysAndExpression.keyAndValue[0])) {
if (isEqual(keysAndExpression.expressionType)) {
ownCheckResult = {passed: false, key: null};
}
if (isNotEqual(keysAndExpression.expressionType)) {
ownCheckResult = {passed: true, key: null};
}
}
return ownCheckResult;
}
/**
* Does the basic checks and tries to parse an expression and a pair
* of key and value.
* // { key } key - the original for loop created value containing key and value in one string
* // { subObject } subObject - the object with properties values
*/
private static parseKeysAndExpression(key: string, subObject) {
if (this.keyOrSubObjEmpty(key, subObject)) {
return null;
}
const expressionType = getExpressionType(key.toString());
if (isNotExpression(expressionType)) {
return null;
}
const keyAndValue = getKeyAndValueByExpressionType(expressionType, key);
if (!keyAndValue || !keyAndValue[0] || !keyAndValue[1]) {
return null;
}
return {expressionType: expressionType, keyAndValue: keyAndValue};
}
private static keyOrSubObjEmpty(key: any, subObject: Object) {
return !key || !subObject;
}
/**
* 'getCopy' function
*
* Uses a JSON Pointer to deeply clone a value from an object.
*
* // { object } object - Object to get value from
* // { Pointer } pointer - JSON Pointer (string or array)
* // { number = 0 } startSlice - Zero-based index of first Pointer key to use
* // { number } endSlice - Zero-based index of last Pointer key to use
* // { boolean = false } getBoolean - Return only true or false?
* // { boolean = false } errors - Show error if not found?
* // { object } - Located value (or true or false if getBoolean = true)
*/
static getCopy(
object, pointer, startSlice = 0, endSlice: number = null,
getBoolean = false, errors = false
) {
const objectToCopy =
this.get(object, pointer, startSlice, endSlice, getBoolean, errors);
return this.forEachDeepCopy(objectToCopy);
}
/**
* 'getFirst' function
*
* Takes an array of JSON Pointers and objects,
* checks each object for a value specified by the pointer,
* and returns the first value found.
*
* // { [object, pointer][] } items - Array of objects and pointers to check
* // { any = null } defaultValue - Value to return if nothing found
* // { boolean = false } getCopy - Return a copy instead?
* // - First value found
*/
static getFirst(items, defaultValue: any = null, getCopy = false) {
if (isEmpty(items)) { return; }
if (isArray(items)) {
for (const item of items) {
if (isEmpty(item)) { continue; }
if (isArray(item) && item.length >= 2) {
if (isEmpty(item[0]) || isEmpty(item[1])) { continue; }
const value = getCopy ?
this.getCopy(item[0], item[1]) :
this.get(item[0], item[1]);
if (value) { return value; }
continue;
}
console.error('getFirst error: Input not in correct format.\n' +
'Should be: [ [ object1, pointer1 ], [ object 2, pointer2 ], etc... ]');
return;
}
return defaultValue;
}
if (isMap(items)) {
for (const [object, pointer] of items) {
if (object === null || !this.isJsonPointer(pointer)) { continue; }
const value = getCopy ?
this.getCopy(object, pointer) :
this.get(object, pointer);
if (value) { return value; }
}
return defaultValue;
}
console.error('getFirst error: Input not in correct format.\n' +
'Should be: [ [ object1, pointer1 ], [ object 2, pointer2 ], etc... ]');
return defaultValue;
}
/**
* 'getFirstCopy' function
*
* Similar to getFirst, but always returns a copy.
*
* // { [object, pointer][] } items - Array of objects and pointers to check
* // { any = null } defaultValue - Value to return if nothing found
* // - Copy of first value found
*/
static getFirstCopy(items, defaultValue: any = null) {
const firstCopy = this.getFirst(items, defaultValue, true);
return firstCopy;
}
/**
* 'set' function
*
* Uses a JSON Pointer to set a value on an object.
* Also creates any missing sub objects or arrays to contain that value.
*
* If the optional fourth parameter is TRUE and the inner-most container
* is an array, the function will insert the value as a new item at the
* specified location in the array, rather than overwriting the existing
* value (if any) at that location.
*
* So set([1, 2, 3], '/1', 4) => [1, 4, 3]
* and
* So set([1, 2, 3], '/1', 4, true) => [1, 4, 2, 3]
*
* // { object } object - The object to set value in
* // { Pointer } pointer - The JSON Pointer (string or array)
* // value - The new value to set
* // { boolean } insert - insert value?
* // { object } - The original object, modified with the set value
*/
static set(object, pointer, value, insert = false) {
const keyArray = this.parse(pointer);
if (keyArray !== null && keyArray.length) {
let subObject = object;
for (let i = 0; i < keyArray.length - 1; ++i) {
let key = keyArray[i];
if (key === '-' && isArray(subObject)) {
key = subObject.length;
}
if (isMap(subObject) && subObject.has(key)) {
subObject = subObject.get(key);
} else {
if (!hasOwn(subObject, key)) {
subObject[key] = (keyArray[i + 1].match(/^(\d+|-)$/)) ? [] : {};
}
subObject = subObject[key];
}
}
const lastKey = keyArray[keyArray.length - 1];
if (isArray(subObject) && lastKey === '-') {
subObject.push(value);
} else if (insert && isArray(subObject) && !isNaN(+lastKey)) {
subObject.splice(lastKey, 0, value);
} else if (isMap(subObject)) {
subObject.set(lastKey, value);
} else {
subObject[lastKey] = value;
}
return object;
}
console.error(`set error: Invalid JSON Pointer: ${pointer}`);
return object;
}
/**
* 'setCopy' function
*
* Copies an object and uses a JSON Pointer to set a value on the copy.
* Also creates any missing sub objects or arrays to contain that value.
*
* If the optional fourth parameter is TRUE and the inner-most container
* is an array, the function will insert the value as a new item at the
* specified location in the array, rather than overwriting the existing value.
*
* // { object } object - The object to copy and set value in
* // { Pointer } pointer - The JSON Pointer (string or array)
* // value - The value to set
* // { boolean } insert - insert value?
* // { object } - The new object with the set value
*/
static setCopy(object, pointer, value, insert = false) {
const keyArray = this.parse(pointer);
if (keyArray !== null) {
const newObject = copy(object);
let subObject = newObject;
for (let i = 0; i < keyArray.length - 1; ++i) {
let key = keyArray[i];
if (key === '-' && isArray(subObject)) {
key = subObject.length;
}
if (isMap(subObject) && subObject.has(key)) {
subObject.set(key, copy(subObject.get(key)));
subObject = subObject.get(key);
} else {
if (!hasOwn(subObject, key)) {
subObject[key] = (keyArray[i + 1].match(/^(\d+|-)$/)) ? [] : {};
}
subObject[key] = copy(subObject[key]);
subObject = subObject[key];
}
}
const lastKey = keyArray[keyArray.length - 1];
if (isArray(subObject) && lastKey === '-') {
subObject.push(value);
} else if (insert && isArray(subObject) && !isNaN(+lastKey)) {
subObject.splice(lastKey, 0, value);
} else if (isMap(subObject)) {
subObject.set(lastKey, value);
} else {
subObject[lastKey] = value;
}
return newObject;
}
console.error(`setCopy error: Invalid JSON Pointer: ${pointer}`);
return object;
}
/**
* 'insert' function
*
* Calls 'set' with insert = TRUE
*
* // { object } object - object to insert value in
* // { Pointer } pointer - JSON Pointer (string or array)
* // value - value to insert
* // { object }
*/
static insert(object, pointer, value) {
const updatedObject = this.set(object, pointer, value, true);
return updatedObject;
}
/**
* 'insertCopy' function
*
* Calls 'setCopy' with insert = TRUE
*
* // { object } object - object to insert value in
* // { Pointer } pointer - JSON Pointer (string or array)
* // value - value to insert
* // { object }
*/
static insertCopy(object, pointer, value) {
const updatedObject = this.setCopy(object, pointer, value, true);
return updatedObject;
}
/**
* 'remove' function
*
* Uses a JSON Pointer to remove a key and its attribute from an object
*
* // { object } object - object to delete attribute from
* // { Pointer } pointer - JSON Pointer (string or array)
* // { object }
*/
static remove(object, pointer) {
const keyArray = this.parse(pointer);
if (keyArray !== null && keyArray.length) {
let lastKey = keyArray.pop();
const parentObject = this.get(object, keyArray);
if (isArray(parentObject)) {
if (lastKey === '-') { lastKey = parentObject.length - 1; }
parentObject.splice(lastKey, 1);
} else if (isObject(parentObject)) {
delete parentObject[lastKey];
}
return object;
}
console.error(`remove error: Invalid JSON Pointer: ${pointer}`);
return object;
}
/**
* 'has' function
*
* Tests if an object has a value at the location specified by a JSON Pointer
*
* // { object } object - object to chek for value
* // { Pointer } pointer - JSON Pointer (string or array)
* // { boolean }
*/
static has(object, pointer) {
const hasValue = this.get(object, pointer, 0, null, true);
return hasValue;
}
/**
* 'dict' function
*
* Returns a (pointer -> value) dictionary for an object
*
* // { object } object - The object to create a dictionary from
* // { object } - The resulting dictionary object
*/
static dict(object) {
const results: any = {};
this.forEachDeep(object, (value, pointer) => {
if (typeof value !== 'object') { results[pointer] = value; }
});
return results;
}
/**
* 'forEachDeep' function
*
* Iterates over own enumerable properties of an object or items in an array
* and invokes an iteratee function for each key/value or index/value pair.
* By default, iterates over items within objects and arrays after calling
* the iteratee function on the containing object or array itself.
*
* The iteratee is invoked with three arguments: (value, pointer, rootObject),
* where pointer is a JSON pointer indicating the location of the current
* value within the root object, and rootObject is the root object initially
* submitted to th function.
*
* If a third optional parameter 'bottomUp' is set to TRUE, the iterator
* function will be called on sub-objects and arrays after being
* called on their contents, rather than before, which is the default.
*
* This function can also optionally be called directly on a sub-object by
* including optional 4th and 5th parameterss to specify the initial
* root object and pointer.
*
* // { object } object - the initial object or array
* // { (v: any, p?: string, o?: any) => any } function - iteratee function
* // { boolean = false } bottomUp - optional, set to TRUE to reverse direction
* // { object = object } rootObject - optional, root object or array
* // { string = '' } pointer - optional, JSON Pointer to object within rootObject
* // { object } - The modified object
*/
static forEachDeep(
object, fn: (v: any, p?: string, o?: any) => any = (v) => v,
bottomUp = false, pointer = '', rootObject = object
) {
if (typeof fn !== 'function') {
console.error(`forEachDeep error: Iterator is not a function:`, fn);
return;
}
if (!bottomUp) { fn(object, pointer, rootObject); }
if (isObject(object) || isArray(object)) {
for (const key of Object.keys(object)) {
const newPointer = pointer + '/' + this.escape(key);
this.forEachDeep(object[key], fn, bottomUp, newPointer, rootObject);
}
}
if (bottomUp) { fn(object, pointer, rootObject); }
}
/**
* 'forEachDeepCopy' function
*
* Similar to forEachDeep, but returns a copy of the original object, with
* the same keys and indexes, but with values replaced with the result of
* the iteratee function.
*
* // { object } object - the initial object or array
* // { (v: any, k?: string, o?: any, p?: any) => any } function - iteratee function
* // { boolean = false } bottomUp - optional, set to TRUE to reverse direction
* // { object = object } rootObject - optional, root object or array
* // { string = '' } pointer - optional, JSON Pointer to object within rootObject
* // { object } - The copied object
*/
static forEachDeepCopy(
object, fn: (v: any, p?: string, o?: any) => any = (v) => v,
bottomUp = false, pointer = '', rootObject = object
) {
if (typeof fn !== 'function') {
console.error(`forEachDeepCopy error: Iterator is not a function:`, fn);
return null;
}
if (isObject(object) || isArray(object)) {
let newObject = isArray(object) ? [ ...object ] : { ...object };
if (!bottomUp) { newObject = fn(newObject, pointer, rootObject); }
for (const key of Object.keys(newObject)) {
const newPointer = pointer + '/' + this.escape(key);
newObject[key] = this.forEachDeepCopy(
newObject[key], fn, bottomUp, newPointer, rootObject
);
}
if (bottomUp) { newObject = fn(newObject, pointer, rootObject); }
return newObject;
} else {
return fn(object, pointer, rootObject);
}
}
/**
* 'escape' function
*
* Escapes a string reference key
*
* // { string } key - string key to escape
* // { string } - escaped key
*/
static escape(key) {
const escaped = key.toString().replace(/~/g, '~0').replace(/\//g, '~1');
return escaped;
}
/**
* 'unescape' function
*
* Unescapes a string reference key
*
* // { string } key - string key to unescape
* // { string } - unescaped key
*/
static unescape(key) {
const unescaped = key.toString().replace(/~1/g, '/').replace(/~0/g, '~');
return unescaped;
}
/**
* 'parse' function
*
* Converts a string JSON Pointer into a array of keys
* (if input is already an an array of keys, it is returned unchanged)
*
* // { Pointer } pointer - JSON Pointer (string or array)
* // { boolean = false } errors - Show error if invalid pointer?
* // { string[] } - JSON Pointer array of keys
*/
static parse(pointer, errors = false) {
if (!this.isJsonPointer(pointer)) {
if (errors) { console.error(`parse error: Invalid JSON Pointer: ${pointer}`); }
return null;
}
if (isArray(pointer)) { return <string[]>pointer; }
if (typeof pointer === 'string') {
if ((<string>pointer)[0] === '#') { pointer = pointer.slice(1); }
if (<string>pointer === '' || <string>pointer === '/') { return []; }
return (<string>pointer).slice(1).split('/').map(this.unescape);
}
}
/**
* 'compile' function
*
* Converts an array of keys into a JSON Pointer string
* (if input is already a string, it is normalized and returned)
*
* The optional second parameter is a default which will replace any empty keys.
*
* // { Pointer } pointer - JSON Pointer (string or array)
* // { string | number = '' } defaultValue - Default value
* // { boolean = false } errors - Show error if invalid pointer?
* // { string } - JSON Pointer string
*/
static compile(pointer, defaultValue = '', errors = false) {
if (pointer === '#') { return ''; }
if (!this.isJsonPointer(pointer)) {
if (errors) { console.error(`compile error: Invalid JSON Pointer: ${pointer}`); }
return null;
}
if (isArray(pointer)) {
if ((<string[]>pointer).length === 0) { return ''; }
return '/' + (<string[]>pointer).map(
key => key === '' ? defaultValue : this.escape(key)
).join('/');
}
if (typeof pointer === 'string') {
if (pointer[0] === '#') { pointer = pointer.slice(1); }
return pointer;
}
}
/**
* 'toKey' function
*
* Extracts name of the final key from a JSON Pointer.
*
* // { Pointer } pointer - JSON Pointer (string or array)
* // { boolean = false } errors - Show error if invalid pointer?
* // { string } - the extracted key
*/
static toKey(pointer, errors = false) {
const keyArray = this.parse(pointer, errors);
if (keyArray === null) { return null; }
if (!keyArray.length) { return ''; }
return keyArray[keyArray.length - 1];
}
/**
* 'isJsonPointer' function
*
* Checks a string or array value to determine if it is a valid JSON Pointer.
* Returns true if a string is empty, or starts with '/' or '#/'.
* Returns true if an array contains only string values.
*
* // value - value to check
* // { boolean } - true if value is a valid JSON Pointer, otherwise false
*/
static isJsonPointer(value) {
if (isArray(value)) {
return value.every(key => typeof key === 'string');
} else if (isString(value)) {
if (value === '' || value === '#') { return true; }
if (value[0] === '/' || value.slice(0, 2) === '#/') {
return !/(~[^01]|~$)/g.test(value);
}
}
return false;
}
/**
* 'isSubPointer' function
*
* Checks whether one JSON Pointer is a subset of another.
*
* // { Pointer } shortPointer - potential subset JSON Pointer
* // { Pointer } longPointer - potential superset JSON Pointer
* // { boolean = false } trueIfMatching - return true if pointers match?
* // { boolean = false } errors - Show error if invalid pointer?
* // { boolean } - true if shortPointer is a subset of longPointer, false if not
*/
static isSubPointer(
shortPointer, longPointer, trueIfMatching = false, errors = false
) {
if (!this.isJsonPointer(shortPointer) || !this.isJsonPointer(longPointer)) {
if (errors) {
let invalid = '';
if (!this.isJsonPointer(shortPointer)) { invalid += ` 1: ${shortPointer}`; }
if (!this.isJsonPointer(longPointer)) { invalid += ` 2: ${longPointer}`; }
console.error(`isSubPointer error: Invalid JSON Pointer ${invalid}`);
}
return;
}
shortPointer = this.compile(shortPointer, '', errors);
longPointer = this.compile(longPointer, '', errors);
return shortPointer === longPointer ? trueIfMatching :
`${shortPointer}/` === longPointer.slice(0, shortPointer.length + 1);
}
/**
* 'toIndexedPointer' function
*
* Merges an array of numeric indexes and a generic pointer to create an
* indexed pointer for a specific item.
*
* For example, merging the generic pointer '/foo/-/bar/-/baz' and
* the array [4, 2] would result in the indexed pointer '/foo/4/bar/2/baz'
*
*
* // { Pointer } genericPointer - The generic pointer
* // { number[] } indexArray - The array of numeric indexes
* // { Map<string, number> } arrayMap - An optional array map
* // { string } - The merged pointer with indexes
*/
static toIndexedPointer(
genericPointer, indexArray, arrayMap: Map<string, number> = null
) {
if (this.isJsonPointer(genericPointer) && isArray(indexArray)) {
let indexedPointer = this.compile(genericPointer);
if (isMap(arrayMap)) {
let arrayIndex = 0;
return indexedPointer.replace(/\/\-(?=\/|$)/g, (key, stringIndex) =>
arrayMap.has((<string>indexedPointer).slice(0, stringIndex)) ?
'/' + indexArray[arrayIndex++] : key
);
} else {
for (const pointerIndex of indexArray) {
indexedPointer = indexedPointer.replace('/-', '/' + pointerIndex);
}
return indexedPointer;
}
}
if (!this.isJsonPointer(genericPointer)) {
console.error(`toIndexedPointer error: Invalid JSON Pointer: ${genericPointer}`);
}
if (!isArray(indexArray)) {
console.error(`toIndexedPointer error: Invalid indexArray: ${indexArray}`);
}
}
/**
* 'toGenericPointer' function
*
* Compares an indexed pointer to an array map and removes list array
* indexes (but leaves tuple arrray indexes and all object keys, including
* numeric keys) to create a generic pointer.
*
* For example, using the indexed pointer '/foo/1/bar/2/baz/3' and
* the arrayMap [['/foo', 0], ['/foo/-/bar', 3], ['/foo/-/bar/-/baz', 0]]
* would result in the generic pointer '/foo/-/bar/2/baz/-'
* Using the indexed pointer '/foo/1/bar/4/baz/3' and the same arrayMap
* would result in the generic pointer '/foo/-/bar/-/baz/-'
* (the bar array has 3 tuple items, so index 2 is retained, but 4 is removed)
*
* The structure of the arrayMap is: [['path to array', number of tuple items]...]
*
*
* // { Pointer } indexedPointer - The indexed pointer (array or string)
* // { Map<string, number> } arrayMap - The optional array map (for preserving tuple indexes)
* // { string } - The generic pointer with indexes removed
*/
static toGenericPointer(indexedPointer, arrayMap = new Map<string, number>()) {
if (this.isJsonPointer(indexedPointer) && isMap(arrayMap)) {
const pointerArray = this.parse(indexedPointer);
for (let i = 1; i < pointerArray.length; i++) {
const subPointer = this.compile(pointerArray.slice(0, i));
if (arrayMap.has(subPointer) &&
arrayMap.get(subPointer) <= +pointerArray[i]
) {
pointerArray[i] = '-';
}
}
return this.compile(pointerArray);
}
if (!this.isJsonPointer(indexedPointer)) {
console.error(`toGenericPointer error: invalid JSON Pointer: ${indexedPointer}`);
}
if (!isMap(arrayMap)) {
console.error(`toGenericPointer error: invalid arrayMap: ${arrayMap}`);
}
}
/**
* 'toControlPointer' function
*
* Accepts a JSON Pointer for a data object and returns a JSON Pointer for the
* matching control in an Angular FormGroup.
*
* // { Pointer } dataPointer - JSON Pointer (string or array) to a data object
* // { FormGroup } formGroup - Angular FormGroup to get value from
* // { boolean = false } controlMustExist - Only return if control exists?
* // { Pointer } - JSON Pointer (string) to the formGroup object
*/
static toControlPointer(dataPointer, formGroup, controlMustExist = false) {
const dataPointerArray = this.parse(dataPointer);
const controlPointerArray: string[] = [];
let subGroup = formGroup;
if (dataPointerArray !== null) {
for (const key of dataPointerArray) {
if (hasOwn(subGroup, 'controls')) {
controlPointerArray.push('controls');
subGroup = subGroup.controls;
}
if (isArray(subGroup) && (key === '-')) {
controlPointerArray.push((subGroup.length - 1).toString());
subGroup = subGroup[subGroup.length - 1];
} else if (hasOwn(subGroup, key)) {
controlPointerArray.push(key);
subGroup = subGroup[key];
} else if (controlMustExist) {
console.error(`toControlPointer error: Unable to find "${key}" item in FormGroup.`);
console.error(dataPointer);
console.error(formGroup);
return;
} else {
controlPointerArray.push(key);
subGroup = { controls: {} };
}
}
return this.compile(controlPointerArray);
}
console.error(`toControlPointer error: Invalid JSON Pointer: ${dataPointer}`);
}
/**
* 'toSchemaPointer' function
*
* Accepts a JSON Pointer to a value inside a data object and a JSON schema
* for that object.
*
* Returns a Pointer to the sub-schema for the value inside the object's schema.
*
* // { Pointer } dataPointer - JSON Pointer (string or array) to an object
* // schema - JSON schema for the object
* // { Pointer } - JSON Pointer (string) to the object's schema
*/
static toSchemaPointer(dataPointer, schema) {
if (this.isJsonPointer(dataPointer) && typeof schema === 'object') {
const pointerArray = this.parse(dataPointer);
if (!pointerArray.length) { return ''; }
const firstKey = pointerArray.shift();
if (schema.type === 'object' || schema.properties || schema.additionalProperties) {
if ((schema.properties || {})[firstKey]) {
return `/properties/${this.escape(firstKey)}` +
this.toSchemaPointer(pointerArray, schema.properties[firstKey]);
} else if (schema.additionalProperties) {
return '/additionalProperties' +
this.toSchemaPointer(pointerArray, schema.additionalProperties);
}
}
if ((schema.type === 'array' || schema.items) &&
(isNumber(firstKey) || firstKey === '-' || firstKey === '')
) {
const arrayItem = firstKey === '-' || firstKey === '' ? 0 : +firstKey;
if (isArray(schema.items)) {
if (arrayItem < schema.items.length) {
return '/items/' + arrayItem +
this.toSchemaPointer(pointerArray, schema.items[arrayItem]);
} else if (schema.additionalItems) {
return '/additionalItems' +
this.toSchemaPointer(pointerArray, schema.additionalItems);
}
} else if (isObject(schema.items)) {
return '/items' + this.toSchemaPointer(pointerArray, schema.items);
} else if (isObject(schema.additionalItems)) {
return '/additionalItems' +
this.toSchemaPointer(pointerArray, schema.additionalItems);
}
}
console.error(`toSchemaPointer error: Data pointer ${dataPointer} ` +
`not compatible with schema ${schema}`);
return null;
}
if (!this.isJsonPointer(dataPointer)) {
console.error(`toSchemaPointer error: Invalid JSON Pointer: ${dataPointer}`);
}
if (typeof schema !== 'object') {
console.error(`toSchemaPointer error: Invalid JSON Schema: ${schema}`);
}
return null;
}
/**
* 'toDataPointer' function
*
* Accepts a JSON Pointer to a sub-schema inside a JSON schema and the schema.
*
* If possible, returns a generic Pointer to the corresponding value inside
* the data object described by the JSON schema.
*
* Returns null if the sub-schema is in an ambiguous location (such as
* definitions or additionalProperties) where the corresponding value
* location cannot be determined.
*
* // { Pointer } schemaPointer - JSON Pointer (string or array) to a JSON schema
* // schema - the JSON schema
* // { boolean = false } errors - Show errors?
* // { Pointer } - JSON Pointer (string) to the value in the data object
*/
static toDataPointer(schemaPointer, schema, errors = false) {
if (this.isJsonPointer(schemaPointer) && typeof schema === 'object' &&
this.has(schema, schemaPointer)
) {
const pointerArray = this.parse(schemaPointer);
if (!pointerArray.length) { return ''; }
const firstKey = pointerArray.shift();
if (firstKey === 'properties' ||
(firstKey === 'items' && isArray(schema.items))
) {
const secondKey = pointerArray.shift();
const pointerSuffix = this.toDataPointer(pointerArray, schema[firstKey][secondKey]);
return pointerSuffix === null ? null : '/' + secondKey + pointerSuffix;
} else if (firstKey === 'additionalItems' ||
(firstKey === 'items' && isObject(schema.items))
) {
const pointerSuffix = this.toDataPointer(pointerArray, schema[firstKey]);
return pointerSuffix === null ? null : '/-' + pointerSuffix;
} else if (['allOf', 'anyOf', 'oneOf'].includes(firstKey)) {
const secondKey = pointerArray.shift();
return this.toDataPointer(pointerArray, schema[firstKey][secondKey]);
} else if (firstKey === 'not') {
return this.toDataPointer(pointerArray, schema[firstKey]);
} else if (['contains', 'definitions', 'dependencies', 'additionalItems',
'additionalProperties', 'patternProperties', 'propertyNames'].includes(firstKey)
) {
if (errors) { console.error(`toDataPointer error: Ambiguous location`); }
}
return '';
}
if (errors) {
if (!this.isJsonPointer(schemaPointer)) {
console.error(`toDataPointer error: Invalid JSON Pointer: ${schemaPointer}`);
}
if (typeof schema !== 'object') {
console.error(`toDataPointer error: Invalid JSON Schema: ${schema}`);
}
if (typeof schema !== 'object') {
console.error(`toDataPointer error: Pointer ${schemaPointer} invalid for Schema: ${schema}`);
}
}
return null;
}
/**
* 'parseObjectPath' function
*
* Parses a JavaScript object path into an array of keys, which
* can then be passed to compile() to convert into a string JSON Pointer.
*
* Based on mike-marcacci's excellent objectpath parse function:
* https://github.com/mike-marcacci/objectpath
*
* // { Pointer } path - The object path to parse
* // { string[] } - The resulting array of keys
*/
static parseObjectPath(path) {
if (isArray(path)) { return <string[]>path; }
if (this.isJsonPointer(path)) { return this.parse(path); }
if (typeof path === 'string') {
let index = 0;
const parts: string[] = [];
while (index < path.length) {
const nextDot = path.indexOf('.', index);
const nextOB = path.indexOf('[', index); // next open bracket
if (nextDot === -1 && nextOB === -1) { // last item
parts.push(path.slice(index));
index = path.length;
} else if (nextDot !== -1 && (nextDot < nextOB || nextOB === -1)) { // dot notation
parts.push(path.slice(index, nextDot));
index = nextDot + 1;
} else { // bracket notation
if (nextOB > index) {
parts.push(path.slice(index, nextOB));
index = nextOB;
}
const quote = path.charAt(nextOB + 1);
if (quote === '"' || quote === '\'') { // enclosing quotes
let nextCB = path.indexOf(quote + ']', nextOB); // next close bracket
while (nextCB !== -1 && path.charAt(nextCB - 1) === '\\') {
nextCB = path.indexOf(quote + ']', nextCB + 2);
}
if (nextCB === -1) { nextCB = path.length; }
parts.push(path.slice(index + 2, nextCB)
.replace(new RegExp('\\' + quote, 'g'), quote));
index = nextCB + 2;
} else { // no enclosing quotes
let nextCB = path.indexOf(']', nextOB); // next close bracket
if (nextCB === -1) { nextCB = path.length; }
parts.push(path.slice(index + 1, nextCB));
index = nextCB + 1;
}
if (path.charAt(index) === '.') { index++; }
}
}
return parts;
}
console.error('parseObjectPath error: Input object path must be a string.');
}
} | the_stack |
import { NG_Chart } from "../../types/navigraph";
import { NavigraphApi } from "../../utils/NavigraphApi";
// TODO: split the actual viewer stuff from this class into a more generic viewer component for later reuse
export class CJ4_MFD_ChartView extends HTMLElement {
private readonly _renderCd: number = 50;
private _renderTmr: number = 50;
private _srcImage = new Image;
private _planeImage = new Image;
private _chart: NG_Chart = undefined;
private _canvas: HTMLCanvasElement;
private _zoom: number = 1;
private _yOffset: number = 0;
private _xOffset: number = 0;
private _isDirty: boolean = true;
private readonly STEP_RATE = 40;
private _chartindexnumber: HTMLElement;
private _chartprocidentifier: HTMLElement;
private _chartinfonogeoref: HTMLElement;
private _isChartLoading: boolean;
private _ngApi: NavigraphApi;
private _showDayChart: boolean;
/** Gets a boolean indicating if the view is visible */
public get isVisible(): boolean {
return this.style.visibility === "visible";
}
/** Gets a boolean indicating if the chart is in portrait format */
public get isPortrait(): boolean {
return this._srcImage.height > this._srcImage.width;
}
/** Sets the x offset of the chart view */
private set xOffset(value: number) {
this._xOffset = Math.min(0, Math.max(-(this._dimensions.chartW * this._zoom - this._canvas.width), value));
}
/** Gets the x offset of the chart view */
private get xOffset(): number {
return this._xOffset;
}
/** Sets the y offset of the chart view */
private set yOffset(value: number) {
this._yOffset = Math.min(0, Math.max(-(this._dimensions.chartH * this._zoom - this._canvas.height) - 20, value));
}
/** Gets the y offset of the chart view */
private get yOffset(): number {
return this._yOffset;
}
/** A struct containing different dimension values of the view and chart */
private readonly _dimensions = {
chartid: "",
bboxBorder: 54,
bboxW: 0,
bboxH: 0,
imgRatio: 0,
chartW: 0,
chartH: 0,
scaleW: 0,
scaleH: 0,
planW: 0,
planH: 0,
pxPerLong: 0,
pxPerLat: 0,
boxW: 0,
boxH: 0,
boxPosX: 0,
boxPosY: 0,
}
connectedCallback(): void {
this._ngApi = new NavigraphApi();
this._chartindexnumber = this.querySelector("#chartinfo_indexnumber");
this._chartprocidentifier = this.querySelector("#chartinfo_procidentifier");
this._chartinfonogeoref = this.querySelector("#chartinfo_nogeoref");
this._canvas = this.querySelector("#chartcanvas");
this._srcImage.src = "#";
this._srcImage.onload = this.onSrcImageLoaded.bind(this);
this._planeImage.src = "coui://html_UI/Pages/VCockpit/Instruments/Airliners/CJ4/WTLibs/Images/icon_plane.png?cb=323334";
}
/** Event thrown when chart image is loaded */
onSrcImageLoaded(): void {
this._xOffset = 0;
this._yOffset = 0;
this._zoom = 1;
this.scaleImgToFit();
this._isChartLoading = false;
this._isDirty = true;
}
/**
* Loads a chart into the view
* @param url The url for the chart to load
* @param chart The chart object
*/
async loadChart(chart: NG_Chart = undefined): Promise<void> {
if (chart !== undefined) {
this._chart = chart;
// get and load png
this._isChartLoading = true;
this._showDayChart = SimVar.GetSimVarValue("LIGHT POTENTIOMETER:3", "number") === 1;
this._srcImage.src = await this._ngApi.getChartPngUrl(this._chart, this._showDayChart);
this._chartindexnumber.textContent = `${chart.icao_airport_identifier} ${chart.index_number}`;
this._chartprocidentifier.textContent = chart.procedure_identifier;
this._chartinfonogeoref.style.display = (this._chart.georef) ? "none" : "";
}
}
update(dTime: number): void {
if (this.isVisible && !this._isChartLoading) {
this._renderTmr -= dTime;
if (this._renderTmr > 0 && this._isDirty === false) {
return;
}
this._renderTmr = this._renderCd;
this._isDirty = false;
// check for day/night change
const isDay = SimVar.GetSimVarValue("LIGHT POTENTIOMETER:3", "number") === 1;
if(isDay !== this._showDayChart) {
this.loadChart(this._chart);
}
const ctx = this._canvas.getContext("2d");
ctx.clearRect(0, 0, this._canvas.width, this._canvas.height)
ctx.setTransform(this._zoom, 0, 0, this._zoom, this._xOffset, this._yOffset);
if (this._srcImage.src !== "" && this._srcImage.src.indexOf("#") === -1) {
this.drawImage(ctx);
ctx.setTransform(1, 0, 0, 1, 0, 0);
// if (this._zoom === 1) {
// this.drawRect(ctx);
// }
} else {
ctx.fillStyle = "#cccac8";
ctx.textAlign = "center";
ctx.font = "26px Collins ProLine";
ctx.fillText("NO CHART AVAILABLE", this._canvas.width / 2, this._canvas.height / 2);
}
}
}
/** Draws the green box for panning and zooming */
private drawRect(ctx: CanvasRenderingContext2D): void {
ctx.strokeStyle = "green";
ctx.lineWidth = 4;
const scrollGapX = this._dimensions.chartW - this._canvas.width;
const scrollGapY = this._dimensions.chartH - this._canvas.height;
const scrollPercX = scrollGapX === 0 ? 0 : Math.min(1, Math.abs(((scrollGapX - (scrollGapX - this._xOffset)) / scrollGapX)));
const scrollPercY = scrollGapY === 0 ? 0 : Math.min(1, Math.abs(((scrollGapY - (scrollGapY - this._yOffset)) / scrollGapY)));
this._dimensions.boxW = this._canvas.width * 0.6;
this._dimensions.boxH = this._canvas.height * 0.6;
const rectScrollGapX = this._canvas.width - this._dimensions.boxW - 4;
const rectScrollGapY = this._canvas.height - this._dimensions.boxH - 24;
this._dimensions.boxPosX = rectScrollGapX * (scrollPercX) + 2;
this._dimensions.boxPosY = rectScrollGapY * (scrollPercY) + 2;
ctx.strokeRect(this._dimensions.boxPosX, this._dimensions.boxPosY, this._dimensions.boxW, this._dimensions.boxH);
}
/** Fits the chart to the canvas size and sets dimension values */
private scaleImgToFit(): void {
if (this._srcImage.width > 0) {
// get bbox measures
this._dimensions.bboxW = this._srcImage.width - (this._dimensions.bboxBorder * 2);
this._dimensions.bboxH = this._srcImage.height - (this._dimensions.bboxBorder * 2);
// img fitting
const ratio = this._srcImage.width / this._srcImage.height;
this._dimensions.chartW = this._canvas.width;
this._dimensions.chartH = this._dimensions.chartW / ratio;
if (!this.isPortrait) {
this._dimensions.chartH = this._canvas.height * 1.2;
this._dimensions.chartW = this._dimensions.chartW * ratio * 1.2;
}
this._dimensions.scaleW = this._dimensions.chartW / (this._srcImage.width - (this._dimensions.bboxBorder * 2));
this._dimensions.scaleH = this._dimensions.chartH / (this._srcImage.height - (this._dimensions.bboxBorder * 2));
// georef measures
if (this._chart.georef === true) {
this._dimensions.planW = this._chart.planview.bbox_local[2] - this._chart.planview.bbox_local[0];
this._dimensions.planH = this._chart.planview.bbox_local[1] - this._chart.planview.bbox_local[3];
this._dimensions.pxPerLong = this._dimensions.planW / (this._chart.planview.bbox_geo[2] - this._chart.planview.bbox_geo[0]);
this._dimensions.pxPerLat = this._dimensions.planH / (this._chart.planview.bbox_geo[3] - this._chart.planview.bbox_geo[1]);
}
}
}
/** Draws the chart */
private drawImage(ctx: CanvasRenderingContext2D): void {
ctx.drawImage(this._srcImage, this._dimensions.bboxBorder, this._dimensions.bboxBorder, this._dimensions.bboxW, this._dimensions.bboxH, 0, 0, this._dimensions.chartW, this._dimensions.chartH);
if (this._chart.georef === true) {
// planepos
const lat = SimVar.GetSimVarValue("PLANE LATITUDE", "degree latitude");
const long = SimVar.GetSimVarValue("PLANE LONGITUDE", "degree longitude");
if (this.isInsideGeoCoords(lat, long, this._chart.planview.bbox_geo)) {
let planeX = (long - this._chart.planview.bbox_geo[0]) * this._dimensions.pxPerLong;
let planeY = Math.abs(lat - this._chart.planview.bbox_geo[3]) * this._dimensions.pxPerLat;
// no idea why we need to offset more
planeX += (this._chart.planview.bbox_local[0]) - this._dimensions.bboxBorder;
planeY += (this._chart.planview.bbox_local[3]) - this._dimensions.bboxBorder;
// check if plane is under an inset
for (let i = 0; i < this._chart.insets.length; i++) {
const inset = this._chart.insets[i].bbox_local;
if (this.isInsidePxCoords(planeX, planeY, inset)) {
return;
}
}
const transX = Math.abs(planeX) * this._dimensions.scaleW;
const transY = Math.abs(planeY) * this._dimensions.scaleH;
const simTrack = (SimVar.GetSimVarValue("SIM ON GROUND", "bool")) ? SimVar.GetSimVarValue("PLANE HEADING DEGREES TRUE", "degree") : SimVar.GetSimVarValue("GPS GROUND TRUE TRACK", "degree");
const rot = Math.round(simTrack) * (Math.PI / 180);
ctx.translate(transX, transY);
ctx.rotate(rot);
const planeScale = this._zoom === 1 ? 1 : 1.5;
ctx.drawImage(this._planeImage, -20 / planeScale, -23.5 / planeScale, 40 / planeScale, 47 / planeScale);
ctx.translate(-transX, -transY);
ctx.rotate(-rot);
}
}
}
private isInsideGeoCoords(lat: number, long: number, bb: number[]): boolean {
return (bb[0] <= long && long <= bb[2] && bb[1] <= lat && lat <= bb[3]);
}
private isInsidePxCoords(x: number, y: number, bb: number[]): boolean {
return (bb[0] <= x && x <= bb[2] && bb[3] <= y && y <= bb[1]);
}
onEvent(event: string): boolean {
if (!this.isVisible) {
return false;
}
this._isDirty = true;
let handled = true;
switch (event) {
case "Lwr_Push_ZOOM_INC":
case "Lwr_Push_ZOOM_DEC":
const chartCtrX = ((this._canvas.width / 2)) + Math.abs(this._xOffset);
const chartCtrY = ((this._canvas.height / 2)) + Math.abs(this._yOffset);
this._zoom = this._zoom === 1 ? (this.isPortrait ? 2.0 : 1.6) : 1;
if (this._zoom === 1) {
this.xOffset = -(chartCtrX / (this.isPortrait ? 2.0 : 1.6)) + (this._canvas.width / 2);
this.yOffset = -(chartCtrY / (this.isPortrait ? 2.0 : 1.6)) + (this._canvas.height / 2);
} else {
this.xOffset = -(chartCtrX * this._zoom) + (this._canvas.width / 2);
this.yOffset = -(chartCtrY * this._zoom) + (this._canvas.height / 2);
}
break;
case "Lwr_JOYSTICK_UP":
this.yOffset += this.STEP_RATE;
break;
case "Lwr_JOYSTICK_DOWN":
this.yOffset -= this.STEP_RATE;
break;
case "Lwr_JOYSTICK_LEFT":
this.xOffset += this.STEP_RATE;
break;
case "Lwr_JOYSTICK_RIGHT":
this.xOffset -= this.STEP_RATE;
break;
default:
this._isDirty = false;
handled = false;
break;
}
return handled;
}
public show(): void {
this.fitCanvasToContainer(this._canvas);
this._isDirty = true;
this.style.visibility = "visible";
}
public hide(): void {
this.style.visibility = "hidden";
}
private fitCanvasToContainer(canvas: HTMLCanvasElement): void {
canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
}
}
customElements.define("cj4-mfd-chartview", CJ4_MFD_ChartView); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [sms](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsservermigrationservice.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Sms extends PolicyStatement {
public servicePrefix = 'sms';
/**
* Statement provider for service [sms](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsservermigrationservice.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to create an application configuration to migrate on-premise application onto AWS
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_CreateApp.html
*/
public toCreateApp() {
return this.to('CreateApp');
}
/**
* Grants permission to create a job to migrate on-premise server onto AWS
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_CreateReplicationJob.html
*/
public toCreateReplicationJob() {
return this.to('CreateReplicationJob');
}
/**
* Grants permission to delete an existing application configuration
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_DeleteApp.html
*/
public toDeleteApp() {
return this.to('DeleteApp');
}
/**
* Grants permission to delete launch configuration for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_DeleteAppLaunchConfiguration.html
*/
public toDeleteAppLaunchConfiguration() {
return this.to('DeleteAppLaunchConfiguration');
}
/**
* Grants permission to delete replication configuration for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_DeleteAppReplicationConfiguration.html
*/
public toDeleteAppReplicationConfiguration() {
return this.to('DeleteAppReplicationConfiguration');
}
/**
* Grants permission to delete validation configuration for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_DeleteAppValidationConfiguration.html
*/
public toDeleteAppValidationConfiguration() {
return this.to('DeleteAppValidationConfiguration');
}
/**
* Grants permission to delete an existing job to migrate on-premise server onto AWS
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_DeleteReplicationJob.html
*/
public toDeleteReplicationJob() {
return this.to('DeleteReplicationJob');
}
/**
* Grants permission to delete the complete list of on-premise servers gathered into AWS
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_DeleteServerCatalog.html
*/
public toDeleteServerCatalog() {
return this.to('DeleteServerCatalog');
}
/**
* Grants permission to disassociate a connector that has been associated
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_DisassociateConnector.html
*/
public toDisassociateConnector() {
return this.to('DisassociateConnector');
}
/**
* Grants permission to generate a changeSet for the CloudFormation stack of an application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GenerateChangeSet.html
*/
public toGenerateChangeSet() {
return this.to('GenerateChangeSet');
}
/**
* Grants permission to generate a CloudFormation template for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GenerateTemplate.html
*/
public toGenerateTemplate() {
return this.to('GenerateTemplate');
}
/**
* Grants permission to get the configuration and statuses for an existing application
*
* Access Level: Read
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GetApp.html
*/
public toGetApp() {
return this.to('GetApp');
}
/**
* Grants permission to get launch configuration for an existing application
*
* Access Level: Read
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GetAppLaunchConfiguration.html
*/
public toGetAppLaunchConfiguration() {
return this.to('GetAppLaunchConfiguration');
}
/**
* Grants permission to get replication configuration for an existing application
*
* Access Level: Read
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GetAppReplicationConfiguration.html
*/
public toGetAppReplicationConfiguration() {
return this.to('GetAppReplicationConfiguration');
}
/**
* Grants permission to get validation configuration for an existing application
*
* Access Level: Read
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GetAppValidationConfiguration.html
*/
public toGetAppValidationConfiguration() {
return this.to('GetAppValidationConfiguration');
}
/**
* Grants permission to get notification sent from application validation script.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GetAppValidationOutput.html
*/
public toGetAppValidationOutput() {
return this.to('GetAppValidationOutput');
}
/**
* Grants permission to get all connectors that have been associated
*
* Access Level: Read
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GetConnectors.html
*/
public toGetConnectors() {
return this.to('GetConnectors');
}
/**
* Grants permission to gets messages from AWS Server Migration Service to Server Migration Connector
*
* Access Level: Read
*/
public toGetMessages() {
return this.to('GetMessages');
}
/**
* Grants permission to get all existing jobs to migrate on-premise servers onto AWS
*
* Access Level: Read
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GetReplicationJobs.html
*/
public toGetReplicationJobs() {
return this.to('GetReplicationJobs');
}
/**
* Grants permission to get all runs for an existing job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GetReplicationRuns.html
*/
public toGetReplicationRuns() {
return this.to('GetReplicationRuns');
}
/**
* Grants permission to get all servers that have been imported
*
* Access Level: Read
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_GetServers.html
*/
public toGetServers() {
return this.to('GetServers');
}
/**
* Grants permission to import application catalog from AWS Application Discovery Service
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_ImportAppCatalog.html
*/
public toImportAppCatalog() {
return this.to('ImportAppCatalog');
}
/**
* Grants permission to gather a complete list of on-premise servers
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_ImportServerCatalog.html
*/
public toImportServerCatalog() {
return this.to('ImportServerCatalog');
}
/**
* Grants permission to create and launch a CloudFormation stack for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_LaunchApp.html
*/
public toLaunchApp() {
return this.to('LaunchApp');
}
/**
* Grants permission to get a list of summaries for existing applications
*
* Access Level: List
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_ListAppss.html
*/
public toListApps() {
return this.to('ListApps');
}
/**
* Grants permission to send notification for application validation script
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_NotifyAppValidationOutput.html
*/
public toNotifyAppValidationOutput() {
return this.to('NotifyAppValidationOutput');
}
/**
* Grants permission to create or update launch configuration for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_PutAppLaunchConfiguration.html
*/
public toPutAppLaunchConfiguration() {
return this.to('PutAppLaunchConfiguration');
}
/**
* Grants permission to create or update replication configuration for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_PutAppReplicationConfiguration.html
*/
public toPutAppReplicationConfiguration() {
return this.to('PutAppReplicationConfiguration');
}
/**
* Grants permission to put validation configuration for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_PutAppValidationConfiguration.html
*/
public toPutAppValidationConfiguration() {
return this.to('PutAppValidationConfiguration');
}
/**
* Grants permission to send message from Server Migration Connector to AWS Server Migration Service
*
* Access Level: Write
*/
public toSendMessage() {
return this.to('SendMessage');
}
/**
* Grants permission to create and start replication jobs for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_StartAppReplication.html
*/
public toStartAppReplication() {
return this.to('StartAppReplication');
}
/**
* Grants permission to start a replication run for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_StartOnDemandAppReplication.html
*/
public toStartOnDemandAppReplication() {
return this.to('StartOnDemandAppReplication');
}
/**
* Grants permission to start a replication run for an existing replication job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_StartOnDemandReplicationRun.html
*/
public toStartOnDemandReplicationRun() {
return this.to('StartOnDemandReplicationRun');
}
/**
* Grants permission to stop and delete replication jobs for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_StopAppReplication.html
*/
public toStopAppReplication() {
return this.to('StopAppReplication');
}
/**
* Grants permission to terminate the CloudFormation stack for an existing application
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_TerminateApp.html
*/
public toTerminateApp() {
return this.to('TerminateApp');
}
/**
* Grants permission to update an existing application configuration
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_UpdateApp.html
*/
public toUpdateApp() {
return this.to('UpdateApp');
}
/**
* Grants permission to update an existing job to migrate on-premise server onto AWS
*
* Access Level: Write
*
* https://docs.aws.amazon.com/server-migration-service/latest/APIReference/API_UpdateReplicationJob.html
*/
public toUpdateReplicationJob() {
return this.to('UpdateReplicationJob');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CreateApp",
"CreateReplicationJob",
"DeleteApp",
"DeleteAppLaunchConfiguration",
"DeleteAppReplicationConfiguration",
"DeleteAppValidationConfiguration",
"DeleteReplicationJob",
"DeleteServerCatalog",
"DisassociateConnector",
"GenerateChangeSet",
"GenerateTemplate",
"ImportAppCatalog",
"ImportServerCatalog",
"LaunchApp",
"NotifyAppValidationOutput",
"PutAppLaunchConfiguration",
"PutAppReplicationConfiguration",
"PutAppValidationConfiguration",
"SendMessage",
"StartAppReplication",
"StartOnDemandAppReplication",
"StartOnDemandReplicationRun",
"StopAppReplication",
"TerminateApp",
"UpdateApp",
"UpdateReplicationJob"
],
"Read": [
"GetApp",
"GetAppLaunchConfiguration",
"GetAppReplicationConfiguration",
"GetAppValidationConfiguration",
"GetAppValidationOutput",
"GetConnectors",
"GetMessages",
"GetReplicationJobs",
"GetReplicationRuns",
"GetServers"
],
"List": [
"ListApps"
]
};
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/myWorkbooksMappers";
import * as Parameters from "../models/parameters";
import { ApplicationInsightsManagementClientContext } from "../applicationInsightsManagementClientContext";
/** Class representing a MyWorkbooks. */
export class MyWorkbooks {
private readonly client: ApplicationInsightsManagementClientContext;
/**
* Create a MyWorkbooks.
* @param {ApplicationInsightsManagementClientContext} client Reference to the service client.
*/
constructor(client: ApplicationInsightsManagementClientContext) {
this.client = client;
}
/**
* Get all private workbooks defined within a specified resource group and category.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param category Category of workbook to return. Possible values include: 'workbook', 'TSG',
* 'performance', 'retention'
* @param [options] The optional parameters
* @returns Promise<Models.MyWorkbooksListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, category: Models.CategoryType, options?: Models.MyWorkbooksListByResourceGroupOptionalParams): Promise<Models.MyWorkbooksListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param category Category of workbook to return. Possible values include: 'workbook', 'TSG',
* 'performance', 'retention'
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, category: Models.CategoryType, callback: msRest.ServiceCallback<Models.MyWorkbooksListResult>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param category Category of workbook to return. Possible values include: 'workbook', 'TSG',
* 'performance', 'retention'
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, category: Models.CategoryType, options: Models.MyWorkbooksListByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.MyWorkbooksListResult>): void;
listByResourceGroup(resourceGroupName: string, category: Models.CategoryType, options?: Models.MyWorkbooksListByResourceGroupOptionalParams | msRest.ServiceCallback<Models.MyWorkbooksListResult>, callback?: msRest.ServiceCallback<Models.MyWorkbooksListResult>): Promise<Models.MyWorkbooksListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
category,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.MyWorkbooksListByResourceGroupResponse>;
}
/**
* Get all private workbooks defined within a specified subscription and category.
* @param category Category of workbook to return. Possible values include: 'workbook', 'TSG',
* 'performance', 'retention'
* @param [options] The optional parameters
* @returns Promise<Models.MyWorkbooksListBySubscriptionResponse>
*/
listBySubscription(category: Models.CategoryType, options?: Models.MyWorkbooksListBySubscriptionOptionalParams): Promise<Models.MyWorkbooksListBySubscriptionResponse>;
/**
* @param category Category of workbook to return. Possible values include: 'workbook', 'TSG',
* 'performance', 'retention'
* @param callback The callback
*/
listBySubscription(category: Models.CategoryType, callback: msRest.ServiceCallback<Models.MyWorkbooksListResult>): void;
/**
* @param category Category of workbook to return. Possible values include: 'workbook', 'TSG',
* 'performance', 'retention'
* @param options The optional parameters
* @param callback The callback
*/
listBySubscription(category: Models.CategoryType, options: Models.MyWorkbooksListBySubscriptionOptionalParams, callback: msRest.ServiceCallback<Models.MyWorkbooksListResult>): void;
listBySubscription(category: Models.CategoryType, options?: Models.MyWorkbooksListBySubscriptionOptionalParams | msRest.ServiceCallback<Models.MyWorkbooksListResult>, callback?: msRest.ServiceCallback<Models.MyWorkbooksListResult>): Promise<Models.MyWorkbooksListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
category,
options
},
listBySubscriptionOperationSpec,
callback) as Promise<Models.MyWorkbooksListBySubscriptionResponse>;
}
/**
* Get a single private workbook by its resourceName.
* @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.MyWorkbooksGetResponse>
*/
get(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.MyWorkbooksGetResponse>;
/**
* @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
*/
get(resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<Models.MyWorkbook>): 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
*/
get(resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MyWorkbook>): void;
get(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MyWorkbook>, callback?: msRest.ServiceCallback<Models.MyWorkbook>): Promise<Models.MyWorkbooksGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceName,
options
},
getOperationSpec,
callback) as Promise<Models.MyWorkbooksGetResponse>;
}
/**
* Delete a private workbook.
* @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<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @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
*/
deleteMethod(resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<void>): 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
*/
deleteMethod(resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Create a new private workbook.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param workbookProperties Properties that need to be specified to create a new private workbook.
* @param [options] The optional parameters
* @returns Promise<Models.MyWorkbooksCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, resourceName: string, workbookProperties: Models.MyWorkbook, options?: msRest.RequestOptionsBase): Promise<Models.MyWorkbooksCreateOrUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param workbookProperties Properties that need to be specified to create a new private workbook.
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, resourceName: string, workbookProperties: Models.MyWorkbook, callback: msRest.ServiceCallback<Models.MyWorkbook>): 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 workbookProperties Properties that need to be specified to create a new private workbook.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, resourceName: string, workbookProperties: Models.MyWorkbook, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MyWorkbook>): void;
createOrUpdate(resourceGroupName: string, resourceName: string, workbookProperties: Models.MyWorkbook, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MyWorkbook>, callback?: msRest.ServiceCallback<Models.MyWorkbook>): Promise<Models.MyWorkbooksCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceName,
workbookProperties,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.MyWorkbooksCreateOrUpdateResponse>;
}
/**
* Updates a private workbook that has already been added.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param workbookProperties Properties that need to be specified to create a new private workbook.
* @param [options] The optional parameters
* @returns Promise<Models.MyWorkbooksUpdateResponse>
*/
update(resourceGroupName: string, resourceName: string, workbookProperties: Models.MyWorkbook, options?: msRest.RequestOptionsBase): Promise<Models.MyWorkbooksUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName The name of the Application Insights component resource.
* @param workbookProperties Properties that need to be specified to create a new private workbook.
* @param callback The callback
*/
update(resourceGroupName: string, resourceName: string, workbookProperties: Models.MyWorkbook, callback: msRest.ServiceCallback<Models.MyWorkbook>): 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 workbookProperties Properties that need to be specified to create a new private workbook.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, resourceName: string, workbookProperties: Models.MyWorkbook, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MyWorkbook>): void;
update(resourceGroupName: string, resourceName: string, workbookProperties: Models.MyWorkbook, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MyWorkbook>, callback?: msRest.ServiceCallback<Models.MyWorkbook>): Promise<Models.MyWorkbooksUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceName,
workbookProperties,
options
},
updateOperationSpec,
callback) as Promise<Models.MyWorkbooksUpdateResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/myWorkbooks",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.category,
Parameters.tags,
Parameters.canFetchContent,
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MyWorkbooksListResult
},
default: {
bodyMapper: Mappers.MyWorkbookError
}
},
serializer
};
const listBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Insights/myWorkbooks",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.category,
Parameters.tags,
Parameters.canFetchContent,
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MyWorkbooksListResult
},
default: {
bodyMapper: Mappers.MyWorkbookError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/myWorkbooks/{resourceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MyWorkbook
},
default: {
bodyMapper: Mappers.MyWorkbookError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/myWorkbooks/{resourceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
201: {},
204: {},
default: {
bodyMapper: Mappers.MyWorkbookError
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/myWorkbooks/{resourceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "workbookProperties",
mapper: {
...Mappers.MyWorkbook,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.MyWorkbook
},
201: {
bodyMapper: Mappers.MyWorkbook
},
default: {
bodyMapper: Mappers.MyWorkbookError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/myWorkbooks/{resourceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "workbookProperties",
mapper: {
...Mappers.MyWorkbook,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.MyWorkbook
},
default: {
bodyMapper: Mappers.MyWorkbookError
}
},
serializer
}; | the_stack |
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing';
import { DataFeedCreateComponent } from './data-feed-create.component';
import { RouterTestingModule } from '@angular/router/testing';
import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { MockComponent } from 'ng2-mock-component';
import { StoreModule } from '@ngrx/store';
import { ngrxReducers, runtimeChecks } from 'app/ngrx.reducers';
import { FeatureFlagsService } from 'app/services/feature-flags/feature-flags.service';
import { Regex } from 'app/helpers/auth/regex';
import { Destination } from 'app/entities/destinations/destination.model';
describe('DataFeedCreateComponent', () => {
let component: DataFeedCreateComponent;
let fixture: ComponentFixture<DataFeedCreateComponent>;
// let element;
let createForm: FormGroup;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
MockComponent({ selector: 'chef-th' }),
MockComponent({ selector: 'chef-td' }),
MockComponent({ selector: 'chef-error' }),
MockComponent({ selector: 'chef-form-field' }),
MockComponent({ selector: 'chef-heading' }),
MockComponent({ selector: 'chef-icon' }),
MockComponent({ selector: 'chef-loading-spinner' }),
MockComponent({ selector: 'mat-select' }),
MockComponent({ selector: 'mat-option' }),
MockComponent({ selector: 'chef-page-header' }),
MockComponent({ selector: 'chef-subheading' }),
MockComponent({ selector: 'chef-toolbar' }),
MockComponent({ selector: 'chef-table' }),
MockComponent({ selector: 'chef-thead' }),
MockComponent({ selector: 'chef-tbody' }),
MockComponent({ selector: 'chef-tr' }),
MockComponent({ selector: 'chef-th' }),
MockComponent({ selector: 'chef-td' }),
MockComponent({ selector: 'a', inputs: ['routerLink'] }),
MockComponent({ selector: 'input', inputs: ['resetOrigin'] }),
DataFeedCreateComponent
],
providers: [
FeatureFlagsService
],
imports: [
FormsModule,
ReactiveFormsModule,
RouterTestingModule,
StoreModule.forRoot(ngrxReducers, { runtimeChecks })
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DataFeedCreateComponent);
component = fixture.componentInstance;
component.createForm = new FormBuilder().group({
name: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]],
endpoint: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]],
url: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]],
tokenType: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]],
token: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]],
username: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]],
password: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]],
headers: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]],
bucketName: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]],
accessKey: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]],
secretKey: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]]
});
createForm = component.createForm;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('Data Feed Create', () => {
const tokenType = 'Bearer';
const token = 'test123';
const bucketName = 'bar';
const accessKey = 'test123';
const secretKey = 'test123';
const userName = 'test123';
const password = 'test123';
const header = '{“test”:”123”}';
const region = 'region1';
const destination = <Destination> {
id: '1',
name: 'new data feed',
secret: 'testSecret',
url: 'http://foo.com'
};
it('should be invalid when no fields are filled out', () => {
expect(createForm.valid).toBeFalsy();
});
it('opening create slider resets name, url, token to empty string', () => {
component.createForm.controls['name'].setValue('any');
component.createForm.controls['url'].setValue('any');
component.createForm.controls['tokenType'].setValue('Bearer');
component.createForm.controls['token'].setValue('any');
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('Splunk');
expect(component.createForm.controls['name'].value).toBe(null);
expect(component.createForm.controls['url'].value).toBe(null);
expect(component.createForm.controls['tokenType'].value).toBe('Splunk');
expect(component.createForm.controls['token'].value).toBe(null);
});
it('should be valid when all fields are filled out for service-now', () => {
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('ServiceNow');
// component.selectChangeHandlers('Access Token');
component.createForm.controls['name'].setValue(destination.name);
component.createForm.controls['url'].setValue(destination.url);
component.createForm.controls['username'].setValue(userName);
component.createForm.controls['password'].setValue(password);
expect(component.validateForm()).toBeTruthy();
});
it('should be valid when all fields are filled out for ELK', () => {
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('ELK');
// component.selectChangeHandlers('Access Token');
component.createForm.controls['name'].setValue(destination.name);
component.createForm.controls['url'].setValue(destination.url);
component.createForm.controls['username'].setValue(userName);
component.createForm.controls['password'].setValue(password);
expect(component.validateForm()).toBeTruthy();
});
it('should be valid when all fields are filled out for splunk', () => {
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('Splunk');
// component.selectChangeHandlers('Access Token');
component.createForm.controls['name'].setValue(destination.name);
component.createForm.controls['url'].setValue(destination.url);
component.createForm.controls['tokenType'].setValue(tokenType);
component.createForm.controls['token'].setValue(token);
expect(component.validateForm()).toBeTruthy();
});
it('should be valid when all fields are filled out for minio', () => {
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('Minio');
// component.selectChangeHandlers('Access Token');
component.createForm.controls['name'].setValue(destination.name);
component.createForm.controls['endpoint'].setValue(destination.url);
component.createForm.controls['bucketName'].setValue(bucketName);
component.createForm.controls['accessKey'].setValue(accessKey);
component.createForm.controls['secretKey'].setValue(secretKey);
expect(component.validateForm()).toBeTruthy();
});
it('should be valid when all fields are filled out for custom with Access token', () => {
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('Custom');
component.createForm.controls['name'].setValue(destination.name);
component.createForm.controls['url'].setValue(destination.url);
component.createForm.controls['tokenType'].setValue(tokenType);
component.createForm.controls['token'].setValue(token);
expect(component.validateForm()).toBeTruthy();
});
it('should be valid when all fields are filled out for custom with UsernamePassword', () => {
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('Custom');
component.selectChangeHandlers('Username and Password');
component.createForm.controls['name'].setValue(destination.name);
component.createForm.controls['url'].setValue(destination.url);
component.createForm.controls['username'].setValue(userName);
component.createForm.controls['password'].setValue(password);
component.createForm.controls['headers'].setValue(header);
expect(component.validateForm()).toBeTruthy();
});
it('slider resets name, url, username and password to empty string for servicenow', () => {
component.createForm.controls['name'].setValue('any');
component.createForm.controls['url'].setValue('any');
component.createForm.controls['tokenType'].setValue(tokenType);
component.createForm.controls['token'].setValue('any');
component.slidePanel();
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('ServiceNow');
expect(component.createForm.controls['name'].value).toBe(null);
expect(component.createForm.controls['url'].value).toBe(null);
expect(component.createForm.controls['tokenType'].value).toBe(tokenType);
expect(component.createForm.controls['token'].value).toBe(null);
});
it('slider resets name, url, username and password to empty string for splunk', () => {
component.createForm.controls['name'].setValue('any');
component.createForm.controls['url'].setValue('any');
component.createForm.controls['tokenType'].setValue(tokenType);
component.createForm.controls['token'].setValue('any');
component.slidePanel();
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('Splunk');
expect(component.createForm.controls['name'].value).toBe(null);
expect(component.createForm.controls['url'].value).toBe(null);
expect(component.createForm.controls['tokenType'].value).toBe('Splunk');
expect(component.createForm.controls['token'].value).toBe(null);
});
it('slider resets name, url, username and password to empty string for ELK', () => {
component.createForm.controls['name'].setValue('any');
component.createForm.controls['url'].setValue('any');
component.createForm.controls['tokenType'].setValue(tokenType);
component.createForm.controls['token'].setValue('any');
component.slidePanel();
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('ELK');
expect(component.createForm.controls['name'].value).toBe(null);
expect(component.createForm.controls['url'].value).toBe(null);
expect(component.createForm.controls['tokenType'].value).toBe('Bearer');
expect(component.createForm.controls['token'].value).toBe(null);
});
it('slider resets name, url, username and password to empty string for Minio', () => {
component.createForm.controls['name'].setValue('any');
component.createForm.controls['endpoint'].setValue('any');
component.createForm.controls['bucketName'].setValue('any');
component.createForm.controls['accessKey'].setValue('any');
component.createForm.controls['secretKey'].setValue('any');
component.slidePanel();
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('Minio');
expect(component.createForm.controls['name'].value).toBe(null);
expect(component.createForm.controls['endpoint'].value).toBe(null);
expect(component.createForm.controls['bucketName'].value).toBe(null);
expect(component.createForm.controls['accessKey'].value).toBe(null);
expect(component.createForm.controls['secretKey'].value).toBe(null);
});
it('should be valid when all fields are filled out for S3', () => {
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => {} };
component.selectIntegration('S3');
component.createForm.controls['name'].setValue(destination.name);
component.createForm.controls['bucketName'].setValue(bucketName);
component.createForm.controls['accessKey'].setValue(accessKey);
component.createForm.controls['secretKey'].setValue(secretKey);
expect(component.validateForm()).toBeTruthy();
});
it('Dropdown is populated for S3', () => {
expect(component.dropDownVal).toBe(null);
component.dropDownChangeHandlers(region);
expect(component.dropDownVal).toBe(region);
});
it('slider resets name, bucketname , accessKey and secretkey to empty string for S3', () => {
component.createForm.controls['name'].setValue('any');
component.createForm.controls['bucketName'].setValue('any');
component.createForm.controls['accessKey'].setValue('any');
component.createForm.controls['secretKey'].setValue('any');
component.slidePanel();
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => {} };
component.selectIntegration('Amazon S3');
expect(component.createForm.controls['name'].value).toBe(null);
expect(component.createForm.controls['bucketName'].value).toBe(null);
expect(component.createForm.controls['accessKey'].value).toBe(null);
expect(component.createForm.controls['secretKey'].value).toBe(null);
});
});
describe('create data feed form validation', () => {
it('- url field validity', () => {
component.integrationSelected = true;
component.name = jasmine.createSpyObj('name', ['nativeElement']);
component.name.nativeElement = { focus: () => { }};
component.selectIntegration('ServiceNow');
expect(component.createForm.controls['url'].value).toBe(null);
let errors = {};
const url = component.createForm.controls['url'];
expect(url.valid).toBeFalsy();
// url field is required
errors = url.errors || {};
expect(errors['required']).toBeTruthy();
url.setValue('');
errors = url.errors || {};
expect(errors['required']).toBeTruthy();
// Set url to invalid inputs
url.setValue(' ');
errors = url.errors || {};
expect(errors['required']).toBeFalsy();
});
});
}); | the_stack |
import type Spec from './Spec';
import { offsetToLineAndColumn, validateEffects } from './utils';
export function parseStructuredHeaderH1(
spec: Spec,
header: Element
): {
name: string | null;
formattedHeader: string | null;
formattedParams: string | null;
formattedReturnType: string | null;
} {
// parsing is intentionally permissive; the linter can do stricter checks
// TODO have the linter do checks
let wrapper = null;
let headerText = header.innerHTML;
let beforeContents = 0;
const headerWrapperMatch = headerText.match(
/^(?<beforeContents>\s*<(?<tag>ins|del|mark)>)(?<contents>.*)<\/\k<tag>>\s*$/is
);
if (headerWrapperMatch != null) {
wrapper = headerWrapperMatch.groups!.tag;
headerText = headerWrapperMatch.groups!.contents;
beforeContents = headerWrapperMatch.groups!.beforeContents.length;
}
const prefix = headerText.match(/^\s*(Static|Runtime) Semantics:\s*/);
if (prefix != null) {
headerText = headerText.substring(prefix[0].length);
}
const parsed = headerText.match(
/^(?<beforeParams>\s*(?<name>[^(\s]+)\s*)(?:\((?<params>[^)]*)\)(?:\s*:(?<returnType>.*))?\s*)?$/s
);
if (parsed == null) {
spec.warn({
type: 'contents',
ruleId: 'header-format',
message: `failed to parse header`,
node: header,
nodeRelativeColumn: 1,
nodeRelativeLine: 1,
});
return { name: null, formattedHeader: null, formattedParams: null, formattedReturnType: null };
}
type Param = { name: string; type: string | null; wrapper: string | null };
const name = parsed.groups!.name;
let paramText = parsed.groups!.params ?? '';
const returnType = parsed.groups!.returnType?.trim() ?? null;
if (returnType === '') {
const { column, line } = offsetToLineAndColumn(
header.innerHTML,
beforeContents +
(prefix?.[0].length ?? 0) +
(headerText.length - headerText.match(/\s*$/)![0].length) -
1
);
spec.warn({
type: 'contents',
ruleId: 'header-format',
message: `if a return type is given, it must not be empty`,
node: header,
nodeRelativeColumn: column,
nodeRelativeLine: line,
});
}
const params: Array<Param> = [];
const optionalParams: Array<Param> = [];
let formattedHeader = null;
if (/\(\s*\n/.test(headerText)) {
// if it's multiline, parse it for types
const paramLines = paramText.split('\n');
let index = 0;
let offset = 0;
for (const line of paramLines) {
offset += line.length;
let chunk = line.trim();
if (chunk === '') {
continue;
}
const wrapperMatch = chunk.match(/^<(ins|del|mark)>(.*)<\/\1>$/i);
let paramWrapper = null;
if (wrapperMatch != null) {
paramWrapper = wrapperMatch[1];
chunk = wrapperMatch[2];
}
++index;
function getParameterOffset() {
return (
beforeContents +
(prefix?.[0].length ?? 0) +
parsed!.groups!.beforeParams.length +
1 + // `beforeParams` does not include the leading `(`
(offset - line.length) + // we've already updated offset to include line.length at this point
index + // to account for the `\n`s eaten by the .split
line.match(/^\s*/)![0].length
);
}
const parsedChunk = chunk.match(/^(optional\s+)?([A-Za-z0-9_]+)\s*:\s*(\S.*\S)/);
if (parsedChunk == null) {
const { line: nodeRelativeLine, column: nodeRelativeColumn } = offsetToLineAndColumn(
header.innerHTML,
getParameterOffset()
);
spec.warn({
type: 'contents',
ruleId: 'header-format',
message: `failed to parse parameter ${index}`,
node: header,
nodeRelativeColumn,
nodeRelativeLine,
});
continue;
}
const optional = parsedChunk[1] != null;
const paramName = parsedChunk[2];
let paramType = parsedChunk[3];
if (paramType.endsWith(',')) {
paramType = paramType.slice(0, -1);
}
if (!optional && optionalParams.length > 0) {
const { line: nodeRelativeLine, column: nodeRelativeColumn } = offsetToLineAndColumn(
header.innerHTML,
getParameterOffset()
);
spec.warn({
type: 'contents',
ruleId: 'header-format',
message: `required parameters should not follow optional parameters`,
node: header,
nodeRelativeColumn,
nodeRelativeLine,
});
}
(optional ? optionalParams : params).push({
name: paramName,
type: paramType === 'unknown' ? null : paramType,
wrapper: paramWrapper,
});
}
const formattedPrefix = prefix == null ? '' : prefix[0].trim() + ' ';
// prettier-ignore
const printParam = (p: Param) => ` ${p.wrapper == null ? '' : `<${p.wrapper}>`}${p.name}${p.wrapper == null ? '' : `</${p.wrapper}>`}`;
formattedHeader = `${formattedPrefix}${name} (${params.map(printParam).join(',')}`;
if (optionalParams.length > 0) {
formattedHeader +=
optionalParams
.map((p, i) => ' [ ' + (i > 0 || params.length > 0 ? ', ' : '') + p.name)
.join('') + optionalParams.map(() => ' ]').join('');
}
formattedHeader += ' )';
} else {
let optional = false;
paramText = paramText.trim();
while (true) {
if (paramText.length == 0) {
break;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
let { success, text, match } = eat(paramText, /^\s*\[(\s*,)?/);
if (success) {
optional = true;
paramText = text;
}
({ success, text, match } = eat(paramText, /^\s*([A-Za-z0-9_]+)/));
if (!success) {
spec.warn({
type: 'contents',
ruleId: 'header-format',
message: `failed to parse header`,
node: header,
// we could be more precise, but it's probably not worth the effort
nodeRelativeLine: 1,
nodeRelativeColumn: 1,
});
break;
}
paramText = text;
(optional ? optionalParams : params).push({ name: match![1], type: null, wrapper: null });
({ success, text } = eat(paramText, /^(\s*\])+|,/));
if (success) {
paramText = text;
}
}
}
// prettier-ignore
const printParamWithType = (p: Param) => `${p.wrapper == null ? '' : `<${p.wrapper}>`}${p.name}${p.type == null ? '' : ` (${p.type})`}${p.wrapper == null ? '' : `</${p.wrapper}>`}`;
const paramsWithTypes = params.map(printParamWithType);
const optionalParamsWithTypes = optionalParams.map(printParamWithType);
let formattedParams = '';
if (params.length === 0 && optionalParams.length === 0) {
formattedParams = 'no arguments';
} else {
if (params.length > 0) {
formattedParams =
(params.length === 1 ? 'argument' : 'arguments') + ' ' + formatEnglishList(paramsWithTypes);
if (optionalParams.length > 0) {
formattedParams += ' and ';
}
}
if (optionalParams.length > 0) {
formattedParams +=
'optional ' +
(optionalParams.length === 1 ? 'argument' : 'arguments') +
' ' +
formatEnglishList(optionalParamsWithTypes);
}
}
if (formattedHeader != null && wrapper != null) {
formattedHeader = `<${wrapper}>${formattedHeader}</${wrapper}>`;
}
return { name, formattedHeader, formattedParams, formattedReturnType: returnType };
}
export function parseStructuredHeaderDl(
spec: Spec,
type: string | null,
dl: Element
): { description: Element | null; for: Element | null; effects: string[] } {
let description = null;
let _for = null;
let effects: string[] = [];
for (let i = 0; i < dl.children.length; ++i) {
const dt = dl.children[i];
if (dt.tagName !== 'DT') {
spec.warn({
type: 'node',
ruleId: 'header-format',
message: `expecting header to have DT, but found ${dt.tagName}`,
node: dt,
});
break;
}
++i;
const dd = dl.children[i];
if (dd?.tagName !== 'DD') {
spec.warn({
type: 'node',
ruleId: 'header-format',
message: `expecting header to have DD, but found ${dd.tagName}`,
node: dd,
});
break;
}
const dtype = dt.textContent ?? '';
switch (dtype.trim().toLowerCase()) {
case 'description': {
if (description != null) {
spec.warn({
type: 'node',
ruleId: 'header-format',
message: `duplicate "description" attribute`,
node: dt,
});
}
description = dd;
break;
}
case 'for': {
if (_for != null) {
spec.warn({
type: 'node',
ruleId: 'header-format',
message: `duplicate "for" attribute`,
node: dt,
});
}
if (type === 'concrete method' || type === 'internal method') {
_for = dd;
} else {
spec.warn({
type: 'node',
ruleId: 'header-format',
message: `"for" attributes only apply to concrete or internal methods`,
node: dt,
});
}
break;
}
case 'effects': {
// The dd contains a comma-separated list of effects.
if (dd.textContent !== null) {
effects = validateEffects(
spec,
dd.textContent.split(',').map(c => c.trim()),
dd
);
}
break;
}
case '': {
spec.warn({
type: 'node',
ruleId: 'header-format',
message: `missing value for structured header attribute`,
node: dt,
});
break;
}
default: {
spec.warn({
type: 'node',
ruleId: 'header-format',
message: `unknown structured header entry type ${JSON.stringify(dtype)}`,
node: dt,
});
break;
}
}
}
return { description, for: _for, effects };
}
export function formatPreamble(
spec: Spec,
clause: Element,
dl: Element,
type: string | null,
name: string,
formattedParams: string,
formattedReturnType: string | null,
_for: Element | null,
description: Element | null
): Array<Element> {
const para = spec.doc.createElement('p');
const paras = [para];
type = (type ?? '').toLowerCase();
switch (type) {
case 'numeric method':
case 'abstract operation': {
// TODO tests (for each type of parametered thing) which have HTML in the parameter type
para.innerHTML += `The abstract operation ${name}`;
break;
}
case 'host-defined abstract operation': {
para.innerHTML += `The host-defined abstract operation ${name}`;
break;
}
case 'implementation-defined abstract operation': {
para.innerHTML += `The implementation-defined abstract operation ${name}`;
break;
}
case 'sdo':
case 'syntax-directed operation': {
para.innerHTML += `The syntax-directed operation ${name}`;
break;
}
case 'internal method':
case 'concrete method': {
if (_for == null) {
spec.warn({
type: 'contents',
ruleId: 'header-format',
message: `expected ${type} to have a "for"`,
node: dl,
nodeRelativeLine: 1,
nodeRelativeColumn: 1,
});
_for = spec.doc.createElement('div');
}
para.append(`The ${name} ${type} of `, ..._for.childNodes);
break;
}
default: {
if (type) {
spec.warn({
type: 'attr-value',
ruleId: 'header-type',
message: `unknown clause type ${JSON.stringify(type)}`,
node: clause,
attr: 'type',
});
} else {
spec.warn({
type: 'node',
ruleId: 'header-type',
message: `clauses with structured headers should have a type`,
node: clause,
});
}
}
}
para.innerHTML += ` takes ${formattedParams}`;
if (formattedReturnType != null) {
para.innerHTML += ` and returns ${formattedReturnType}`;
}
para.innerHTML += '.';
if (description != null) {
const isJustElements = [...description.childNodes].every(
n => n.nodeType === 1 || (n.nodeType === 3 && n.textContent?.trim() === '')
);
if (isJustElements) {
paras.push(...(description.childNodes as Iterable<HTMLParagraphElement>));
} else {
para.append(' ', ...description.childNodes);
}
}
const isSdo = type === 'sdo' || type === 'syntax-directed operation';
const lastSentence = isSdo
? 'It is defined piecewise over the following productions:'
: 'It performs the following steps when called:';
let next = dl.nextElementSibling;
while (next != null && next.tagName === 'EMU-NOTE') {
next = next.nextElementSibling;
}
if (
(isSdo && next?.tagName === 'EMU-GRAMMAR') ||
(!isSdo && next?.tagName === 'EMU-ALG' && !next.hasAttribute('replaces-step'))
) {
if (paras.length > 1 || next !== dl.nextElementSibling) {
const whitespace = next.previousSibling;
const after = spec.doc.createElement('p');
after.append(lastSentence);
next.parentElement!.insertBefore(after, next);
// fix up the whitespace in the generated HTML
if (whitespace?.nodeType === 3 /* TEXT_NODE */ && /^\s+$/.test(whitespace.nodeValue!)) {
next.parentElement!.insertBefore(whitespace.cloneNode(), next);
}
} else {
para.append(' ' + lastSentence);
}
}
return paras;
}
function eat(text: string, regex: RegExp) {
const match = text.match(regex);
if (match == null) {
return { success: false, match, text };
}
return { success: true, match, text: text.substring(match[0].length) };
}
function formatEnglishList(list: Array<string>) {
if (list.length === 0) {
throw new Error('formatEnglishList should not be called with an empty list');
}
if (list.length === 1) {
return list[0];
}
if (list.length === 2) {
return `${list[0]} and ${list[1]}`;
}
return `${list.slice(0, -1).join(', ')}, and ${list[list.length - 1]}`;
} | the_stack |
import path from 'path';
import gulp, { TaskFunction } from 'gulp';
import gulpAdd from 'gulp-add';
import { DependencyMap } from '../model/dependency-map';
import { BrowserBundleFormat } from '../model/browser-bundle-format';
import { NodeBundleFormat } from '../model/node-bundle-format';
import { BuildMode } from '../model/build-mode';
import { PackerOptions } from '../model/packer-options';
import { PackageConfig } from '../model/package-config';
import gulpHbsRuntime from '../plugins/gulp-hbs-runtime';
import { Logger } from '../common/logger';
import { parseLicenseType } from './parser';
import { TestEnvironment } from '../model/test-environment';
/**
* Parse package dependency map mode.
* @param packerOptions Packer options object.
*/
export const parseDependencyMapMode = (packerOptions: PackerOptions): DependencyMap => {
if (packerOptions.cliProject) {
return 'map-dependency';
}
return 'cross-map-peer-dependency';
};
/**
* Parse package bundle format.
* @param packerOptions Packer options object.
*/
export const parseBundleFormat = (packerOptions: PackerOptions): NodeBundleFormat | BrowserBundleFormat => {
if (packerOptions.browserCompliant) {
return packerOptions.bundleFormat || 'umd';
}
return 'cjs';
};
/**
* Generate and copy packer configuration file.
* @param packerOptions Packer options object.
* @param scriptExt Script file extension.
* @param buildMode Package build mode.
* @param testEnvironment Test environment type.
* @param projectDir Project root directory.
*/
export const copyPackerConfig = (
packerOptions: PackerOptions,
scriptExt: string,
buildMode: BuildMode,
testEnvironment: TestEnvironment,
projectDir: string
): TaskFunction => {
const entryFile = `index.${scriptExt}`;
const mapMode = parseDependencyMapMode(packerOptions);
const bundleFormat = parseBundleFormat(packerOptions);
const packerTemplatePath = path.join(__dirname, '../resources/dynamic/.packerrc.js.hbs');
return () => {
return gulp
.src([packerTemplatePath])
.pipe(
gulpHbsRuntime(
{
entry: entryFile,
buildMode,
scriptPreprocessor: packerOptions.scriptPreprocessor,
styleSupport: packerOptions.styleSupport,
inlineStyle: packerOptions.bundleStyles,
stylePreprocessor: packerOptions.stylePreprocessor,
isMocha: packerOptions.testFramework === 'mocha',
isReactLib: packerOptions.reactLib,
bundleFormat,
namespace: packerOptions.namespace,
amdId: packerOptions.amdId,
testFramework: packerOptions.testFramework,
testEnvironment,
serveSupport: packerOptions.browserCompliant,
dependencyMapMode: mapMode
},
{
replaceExt: ''
}
)
)
.pipe(gulp.dest(projectDir));
};
};
/**
* Copy license file.
* @param packerOptions Packer options object.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const licenseCopy = (packerOptions: PackerOptions, projectDir: string, log: Logger): TaskFunction => {
log.trace('copy license file');
const license = parseLicenseType(packerOptions.license);
const licenseFilePath = path.join(__dirname, '../resources/dynamic/license', `${license}.hbs`);
log.trace('license file path: %s', licenseFilePath);
const templateData = {
year: packerOptions.year,
author: packerOptions.author
};
log.trace('template data: %o', templateData);
return () => {
return gulp
.src([licenseFilePath])
.on('error', (e) => {
log.error('missing license file template: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(
gulpHbsRuntime(templateData, {
rename: 'LICENSE'
})
)
.pipe(gulp.dest(projectDir));
};
};
/**
* Copy readme.md file.
* @param packageConfig Package configuration object.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const copyReadme = (packageConfig: PackageConfig, projectDir: string, log: Logger): TaskFunction => {
log.trace('copy base dynamic and static config');
const templateData = {
packageName: packageConfig.name,
packageDescription: packageConfig.description
};
log.trace('template data: %o', templateData);
return () => {
return gulp
.src([path.join(__dirname, '../resources/dynamic/README.md.hbs')])
.on('error', (e) => {
log.error('missing README.md template: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(
gulpHbsRuntime(templateData, {
replaceExt: ''
})
)
.pipe(gulp.dest(projectDir));
};
};
/**
* Copy babel configuration.
* @param packerOptions Packer options object.
* @param buildMode Project build mode.
* @param testEnvironment Test environment type.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const copyBabelConfig = (
packerOptions: PackerOptions,
buildMode: BuildMode,
testEnvironment: TestEnvironment,
projectDir: string,
log: Logger
): TaskFunction => {
log.trace('copy babel config');
const babelrc = path.join(__dirname, '../resources/dynamic/.babelrc.hbs');
log.trace('babel config glob: %s', babelrc);
const templateData = {
browserCompliant: buildMode === 'browser',
reactLib: packerOptions.reactLib,
isBrowserEnvironment: testEnvironment === 'browser',
cjsTestModule: packerOptions.testFramework === 'jasmine' || packerOptions.testFramework === 'mocha'
};
log.trace('template data: %o', templateData);
return () => {
return gulp
.src([babelrc])
.pipe(
gulpHbsRuntime(templateData, {
replaceExt: ''
})
)
.pipe(gulp.dest(projectDir));
};
};
/**
* Copy gitignore file.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const copyGitIgnore = (projectDir: string, log: Logger): TaskFunction => {
log.trace('copy gitignore');
const gitignore = path.join(__dirname, '../resources/dynamic/.gitignore.hbs');
log.trace('.gitignore.hbs path: %s', gitignore);
return () => {
return gulp
.src([gitignore])
.on('error', (e) => {
log.error('missing .gitignore template: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(
gulpHbsRuntime(
{},
{
replaceExt: ''
}
)
)
.pipe(gulp.dest(projectDir));
};
};
/**
* Copy packer asset (banner.hbs and bin.hbs) files.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const copyPackerAssets = (projectDir: string, log: Logger): TaskFunction => {
log.trace('copy packer assets');
const banner = path.join(__dirname, '../resources/dynamic/packer/banner.hbs');
log.trace('banner template path: %s', banner);
const bin = path.join(__dirname, '../resources/dynamic/packer/bin.hbs');
log.trace('bin template path: %s', bin);
return () => {
return gulp
.src([banner, bin])
.on('error', (e) => {
log.error('missing packer asset: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(gulp.dest(path.join(projectDir, '.packer')));
};
};
/**
* Copy typescript configuration tsconfig.json and tslint.json files.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const copyTypescriptConfig = (projectDir: string, log: Logger): TaskFunction => {
const tsconfig = path.join(__dirname, '../resources/static/tsconfig.json');
log.trace('tsconfig.json path: %s', tsconfig);
const tslint = path.join(__dirname, '../resources/static/tslint.json');
log.trace('tslint.json path: %s', tslint);
return () => {
return gulp
.src([tsconfig, tslint])
.on('error', (e) => {
log.error('missing config file: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(gulp.dest(projectDir));
};
};
/**
* Copy postcss configuration file.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const copyPostCssConfig = (projectDir: string, log: Logger): TaskFunction => {
const postCss = path.join(__dirname, '../resources/static/postcss.config.js');
log.trace('karma.conf.js path: %s', postCss);
return () => {
return gulp
.src([postCss])
.on('error', (e) => {
log.error('missing config file: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(gulp.dest(projectDir));
};
};
/**
* Copy ESLint configuration file.
* @param packerOptions Packer options object reference.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const copyEsLintConfig = (packerOptions: PackerOptions, projectDir: string, log: Logger): TaskFunction => {
const eslintrc = path.join(__dirname, '../resources/dynamic/.eslintrc.json.hbs');
const eslintignore = path.join(__dirname, '../resources/static/.eslintignore');
log.trace('eslintrc.json.hbs path: %s', eslintrc);
log.trace('eslintignore path: %s', eslintignore);
return () => {
return gulp
.src([eslintrc, eslintignore])
.on('error', (e) => {
log.error('missing config file: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(
gulpHbsRuntime(
{
testFramework: packerOptions.testFramework
},
{
replaceExt: ''
}
)
)
.pipe(gulp.dest(projectDir));
};
};
/**
* Copy style lint configuration file.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const copyStyleLintConfig = (projectDir: string, log: Logger): TaskFunction => {
const stylelintrc = path.join(__dirname, '../resources/static/.stylelintrc.json');
const stylelintignore = path.join(__dirname, '../resources/static/.stylelintignore');
log.trace('.stylelintrc.json path: %s', stylelintrc);
log.trace('.stylelintignore path: %s', stylelintignore);
return () => {
return gulp
.src([stylelintrc, stylelintignore])
.on('error', (e) => {
log.error('missing config file: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(gulp.dest(projectDir));
};
};
/**
* Copy common configuration (package.json, .editorconfig and travis.yml) files
* @param packageConfig Package configuration object.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const copyCommonConfig = (packageConfig: PackageConfig, projectDir: string, log: Logger): TaskFunction => {
log.trace('copy base dynamic and static config');
const editorConfig = path.join(__dirname, '../resources/static/.editorconfig');
log.trace('.editorconfig path: %s', editorConfig);
const travis = path.join(__dirname, '../resources/static/.travis.yml');
log.trace('.travis.yml path: %s', travis);
return () => {
return gulp
.src([editorConfig, travis])
.on('error', (e) => {
log.error('missing config file: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(gulpAdd('package.json', JSON.stringify(packageConfig, null, 2)))
.pipe(gulp.dest(projectDir));
};
};
/**
* Copy prettier configuration file.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const copyPrettierConfig = (projectDir: string, log: Logger): TaskFunction => {
const prettierrc = path.join(__dirname, '../resources/static/.prettierrc');
const prettierignore = path.join(__dirname, '../resources/static/.prettierignore');
log.trace('.prettierrc path: %s', prettierrc);
log.trace('.prettierignore path: %s', prettierignore);
return () => {
return gulp
.src([prettierrc, prettierignore])
.on('error', (e) => {
log.error('missing config file: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(gulp.dest(projectDir));
};
};
/**
* Get project configuration file generation gulp tasks.
* @param packerOptions Packer configuration object.
* @param packageConfig Package configuration object.
* @param buildMode Project build mode.
* @param scriptExt Script file extension.
* @param testEnvironment Test environment type.
* @param projectDir Project root directory.
* @param log Logger reference.
*/
export const getConfigFileGenerateTasks = (
packerOptions: PackerOptions,
packageConfig: PackageConfig,
buildMode: BuildMode,
scriptExt: string,
testEnvironment: TestEnvironment,
projectDir: string,
log: Logger
): TaskFunction[] => {
const tasks: TaskFunction[] = [];
if (packerOptions.scriptPreprocessor === 'typescript') {
tasks.push(copyTypescriptConfig(projectDir, log));
} else {
tasks.push(copyEsLintConfig(packerOptions, projectDir, log));
}
if (packerOptions.styleSupport) {
tasks.push(copyPostCssConfig(projectDir, log));
tasks.push(copyStyleLintConfig(projectDir, log));
}
tasks.push(licenseCopy(packerOptions, projectDir, log));
tasks.push(copyReadme(packageConfig, projectDir, log));
tasks.push(copyBabelConfig(packerOptions, buildMode, testEnvironment, projectDir, log));
tasks.push(copyGitIgnore(projectDir, log));
tasks.push(copyPackerAssets(projectDir, log));
tasks.push(copyCommonConfig(packageConfig, projectDir, log));
tasks.push(copyPackerConfig(packerOptions, scriptExt, buildMode, testEnvironment, projectDir));
tasks.push(copyPrettierConfig(projectDir, log));
return tasks;
}; | the_stack |
import { initSqlite } from './utils';
import { initDotEnv } from '~/server/init-util';
import { MwActionApiClient } from '~/shared/mwapi';
const SqlString = require('sqlstring-sqlite');
const insertLinkEdges = async function(db, rows) {
const sql =
'INSERT OR REPLACE INTO link_graph_table (link_from, link_to, link_type, link_ttl, iteration) VALUES' +
rows.map((row) => SqlString.format(
'(?, ?, ?, ?, ?)', row)).join(', ');
return await db.exec(sql);
};
const insertLinkEdge = async function(db, from, to, type, ttl, iteration) {
const sql = SqlString.format(
`INSERT OR REPLACE INTO link_graph_table (link_from, link_to, link_type, link_ttl, iteration) VALUES
(?, ?, ?, ?, ?)`, [from, to, type, ttl, iteration]);
return await db.exec(sql);
};
const mainTraverseLinkGraph = async function() {
initDotEnv();
const db = await initSqlite(`tmp/database-link-${new Date().toISOString()}.db`);
const iterationTime = new Date();
const wiki = 'enwiki';
const seed = [
'2020 Democratic Party presidential debates',
'2020 North Dakota elections',
'2020 California elections',
'Political positions of the 2020 Democratic Party presidential primary candidates',
'2020 Democratic Party vice presidential candidate selection',
'Jo Jorgensen 2020 presidential campaign',
'Minnesota 2020',
'Results of the 2020 Democratic Party presidential primaries',
'2020 Constitution Party presidential primaries',
'2020 Arizona elections',
'2020 United States House of Representatives election ratings',
'2020 Oregon state elections',
'Opinion polling for the 2020 Republican Party presidential primaries',
'2020 Democratic Party presidential forums',
'News media endorsements in the 2020 United States presidential primaries',
'Nationwide opinion polling for the 2020 United States presidential election',
'Trump v. NAACP (DACA)',
'2020 Green Party presidential primaries',
'2020 Virginia Republican presidential primary',
'2020 Wisconsin elections',
'Arizona Republican primary, 2020',
'2020 Republican Party presidential primaries',
'2020 South Carolina Republican primary',
'2020 Libertarian Party presidential primaries',
'Trump v. Deutsche Bank AG',
'Chiafalo v. Washington',
'George Floyd protests in New Jersey',
'2020 United Nations Security Council election',
'Donald Trump presidential campaign, 2020',
'John Delaney 2020 presidential campaign',
'Andrew Yang 2020 presidential campaign',
'Bill Weld 2020 presidential campaign',
'Tulsi Gabbard 2020 presidential campaign',
'Kamala Harris 2020 presidential campaign',
'Cory Booker 2020 presidential campaign',
'Marianne Williamson 2020 presidential campaign',
'Elizabeth Warren 2020 presidential campaign',
'Bernie Sanders Presidential Campaign, 2020',
'Jay Inslee 2020 presidential campaign',
'Beto O\'Rourke 2020 presidential campaign',
'Mike Gravel 2020 presidential campaign',
'Joe Biden 2020 presidential campaign',
'Trump v. Mazars USA, LLP',
'Joe Walsh 2020 presidential campaign',
'Impeachment of Donald Trump',
'Impeachment trial of Donald Trump',
'2020 Democratic Party presidential primaries',
'2020 Iowa Republican caucuses',
'2020 Iowa Democratic presidential caucuses',
'2020 Minnesota House of Representatives District 60A special election',
'2020 New Hampshire Democratic presidential primary',
'2020 New Hampshire Republican presidential primary',
'2020 Nevada Democratic presidential caucuses',
'2020 South Carolina Democratic presidential primary',
'2020 California Democratic presidential primary',
'2020 Utah Republican primary',
'2020 North Carolina Republican primary',
'2020 Alabama Republican primary',
'2020 Alabama Democratic presidential primary',
'2020 Vermont Democratic presidential primary',
'2020 Tennessee Democratic presidential primary',
'2020 Arkansas Republican primary',
'2020 Colorado Democratic presidential primary',
'2020 Oklahoma Republican presidential primary',
'2020 Texas Democratic presidential primary',
'2020 Oklahoma Democratic presidential primary',
'2020 Maine Republican presidential primary',
'2020 Texas Republican primary',
'2020 North Carolina Democratic presidential primary',
'2020 Massachusetts Republican presidential primary',
'2020 Democrats Abroad presidential primary',
'2020 Massachusetts Republican primary',
'2020 Arkansas Democratic presidential primary',
'2020 Tennessee Republican primary',
'2020 Massachusetts Democratic presidential primary',
'2020 Minnesota Democratic primary',
'2020 Maine Democratic presidential primary',
'2020 Utah Democratic presidential primary',
'2020 Virginia Democratic presidential primary',
'2020 California Republican primary',
'2020 Colorado Republican primary',
'2020 Idaho Republican primary',
'2020 Washington Republican presidential primary',
'2020 North Dakota Democratic presidential caucuses',
'2020 Washington Democratic presidential primary',
'2020 Idaho Democratic presidential primary',
'2020 Michigan Republican primary',
'2020 Hawaii Republican caucuses',
'2020 Michigan Democratic presidential primary',
'2020 Missouri Republican primary',
'2020 Mississippi Republican primary',
'2020 Mississippi Democratic presidential primary',
'2020 Missouri Democratic presidential primary',
'2020 Illinois Republican primary',
'2020 Illinois Democratic presidential primary',
'2020 Florida Republican primary',
'2020 Arizona Democratic presidential primary',
'2020 Florida Democratic presidential primary',
'2020 Wisconsin Democratic presidential primary',
'2020 Wisconsin Republican presidential primary',
'2020 Alaska Democratic presidential primary',
'2020 Wyoming Democratic presidential caucuses',
'2020 Ohio Republican presidential primary',
'New York Republican primary, 2020',
'2020 Ohio Democratic presidential primary',
'2020 Maryland\'s 7th congressional district special election',
'2020 Kansas Democratic presidential primary',
'2020 Nebraska Democratic presidential primary',
'2020 Wisconsin\'s 7th congressional district special election',
'2020 Oregon Democratic presidential primary',
'2020 Oregon Republican primary',
'2020 Libertarian National Convention',
'2020 Hawaii Democratic presidential primary',
'Donald Trump photo op at St. John\'s Church',
'2020 Indiana Republican primary',
'2020 Montana Democratic presidential primary',
'2020 Montana Republican primary',
'2020 South Dakota Democratic presidential primary',
'2020 Maryland Democratic presidential primary',
'Rhode Island Republican primary, 2020',
'2020 District of Columbia Democratic presidential primary',
'2020 Indiana Democratic presidential primary',
'2020 Rhode Island Democratic presidential primary',
'2020 South Dakota Republican primary',
'2020 New Mexico Republican primary',
'2020 New Mexico Democratic presidential primary',
'2020 District of Columbia Republican primary',
'Buffalo police shoving incident',
'2020 West Virginia Democratic presidential primary',
'2020 Georgia Republican presidential primary',
'2020 Georgia Democratic presidential primary',
'2020 Trump Tulsa rally',
'2020 New York Democratic presidential primary',
'2020 Kentucky Republican primary',
'2020 New York\'s 27th congressional district special election',
'2020 Kentucky Democratic presidential primary',
'2020 Salute to America',
'New Jersey Republican primary, 2020',
'2020 New Jersey Democratic presidential primary',
'2020 Delaware Democratic presidential primary',
'2020 Delaware Republican primary',
'2020 Green National Convention',
'2020 Louisiana Democratic presidential primary',
'2020 Louisiana Republican primary',
'2020 Connecticut Republican primary',
'2020 Connecticut Democratic presidential primary',
'2020 Democratic National Convention',
'2020 Republican National Convention',
'2020 United States Senate election in New Mexico',
'2020 United States Senate election in West Virginia',
'2020 United States House of Representatives elections in Arkansas',
'2020 United States House of Representatives election in Alaska',
'2020 United States House of Representatives elections in Connecticut',
'2020 United States House of Representatives elections in California',
'2020 United States Senate election in Arkansas',
'2020 United States presidential election in Oregon',
'2020 United States House of Representatives elections in South Carolina',
'2020 United States Senate election in Illinois',
'United States Presidential election, 2020',
'2020 United States presidential election in Missouri',
'2020 United States House of Representatives elections in Pennsylvania',
'2020 United States Senate election in Virginia',
'2020 United States Senate election in Mississippi',
'2020 United States House of Representatives elections in Georgia',
'2020 United States Senate election in New Jersey',
'2020 United States Senate election in South Dakota',
'2020 United States House of Representatives elections in Florida',
'2020 United States House of Representatives elections in New Hampshire',
'2020 United States Senate election in Colorado',
'2020 United States House of Representatives election in Montana',
'2020 United States House of Representatives elections in New York',
'2020 Texas State Senate election',
'2020 United States House of Representatives elections in Colorado',
'2020 United States House of Representatives elections in Mississippi',
'2020 United States House of Representatives elections in Oklahoma',
'2020 United States Senate election in Idaho',
'2020 United States presidential election in Iowa',
'2020 United States Senate election in Wyoming',
'2020 Florida House of Representatives election',
'2020 United States presidential election in Montana',
'2020 United States House of Representatives election in Vermont',
'2020 United States presidential election in Wisconsin',
'2020 United States House of Representatives election in Delaware',
'2020 United States Senate election in Montana',
'2020 United States presidential election in Arizona',
'2020 United States House of Representatives elections in New Jersey',
'2020 United States Senate election in Nebraska',
'2020 United States House of Representatives elections in Kentucky',
'2020 United States presidential election in Pennsylvania',
'2020 United States Senate special election in Georgia',
'2020 United States House of Representatives elections in Illinois',
'2020 United States presidential election in Michigan',
'2020 United States presidential election in Georgia',
'2020 United States presidential election in Delaware',
'2020 United States presidential election in Ohio',
'2020 North Carolina Attorney General election',
'United States House of Representatives elections, 2020',
'2020 United States Senate election in Alaska',
'2020 United States House of Representatives elections in Utah',
'2020 United States Senate election in Kentucky',
'2020 Pennsylvania House of Representatives election',
'2020 United States House of Representatives elections in Ohio',
'2020 Oregon State Treasurer election',
'2020 United States presidential election in Virginia',
'2020 United States presidential election in North Carolina',
'2020 United States House of Representatives elections in Iowa',
'2020 United States House of Representatives elections in Missouri',
'2020 United States House of Representatives elections in Tennessee',
'2020 United States Senate special election in Arizona',
'2020 United States House of Representatives elections in Alabama',
'2020 United States Senate election in Maine',
'2020 United States House of Representatives elections in West Virginia',
'2020 United States House of Representatives elections in Kansas',
'2020 United States House of Representatives elections in Michigan',
'2020 United States presidential election in West Virginia',
'2020 United States Senate election in Georgia',
'2020 United States House of Representatives elections in Louisiana',
'2020 United States House of Representatives elections in Maine',
'2020 California State Assembly election',
'2020 United States presidential election in Indiana',
'2020 United States Senate election in Minnesota',
'2020 United States House of Representatives elections in Maryland',
'2020 United States presidential election in Colorado',
'2020 United States Senate election in Michigan',
'2020 United States Senate election in New Hampshire',
'2020 United States Senate election in Louisiana',
'2020 United States Senate election in Oregon',
'2020 United States House of Representatives elections in Massachusetts',
'2020 United States Senate election in Tennessee',
'2020 United States Senate election in Iowa',
'United States Senate elections, 2020',
'2020 Florida Senate election',
'2020 Ohio Senate election',
'2020 United States presidential election in Utah',
'2020 United States presidential election in Maryland',
'2020 United States Senate election in Delaware',
'2020 United States House of Representatives elections in Texas',
'2020 United States presidential election in Washington',
'2020 United States presidential election in New Hampshire',
'2020 United States presidential election in Kansas',
'2020 United States House of Representatives elections in Oregon',
'2020 United States Senate election in Oklahoma',
'2020 United States House of Representatives elections in Nebraska',
'2020 United States House of Representatives elections in Virginia',
'2020 United States Senate election in South Carolina',
'2020 United States House of Representatives elections in Washington',
'South Dakota Initiated Measure 26',
'2020 United States Senate election in Alabama',
'2020 United States House of Representatives elections in Hawaii',
'2020 United States presidential election in Nevada',
'2020 United States presidential election in Minnesota',
'2020 United States House of Representatives elections in Wisconsin',
'2020 United States presidential election in Florida',
'2020 United States presidential election in Texas',
'2020 United States presidential election in Kentucky',
'2020 United States presidential election in Nebraska',
'2020 United States House of Representatives elections in New Mexico',
'2020 United States House of Representatives elections in Nevada',
'United States Presidential election, 2020',
'2020 United States House of Representatives elections in North Carolina',
'2020 United States Senate election in North Carolina',
'2020 United States presidential election in Maine',
'2020 United States House of Representatives elections in Arizona',
'2020 United States general election',
'Presidential election in Alabama, 2020',
'2020 United States Senate election in Kansas',
'2020 United States House of Representatives elections in Minnesota',
'2020 United States Senate election in Rhode Island',
'2020 United States presidential election in Alaska',
'2020 United States presidential election in New Mexico',
'2020 United States Senate election in Texas',
'2020 California State Senate election',
'2020 United States presidential election in Mississippi',
'2020 United States Senate election in Massachusetts',
'2020 United States presidential election in California',
'2020 Missouri Attorney General election',
'2020 United States presidential election in South Carolina',
'2020 United States presidential election in Hawaii',
];
const exclusions = [
];
const started = new Date();
const crawled = new Set();
const stored = new Set();
const HOP_LIMIT = 2;
const toCrawl = [];
toCrawl.push(...seed.map((article) => [article, HOP_LIMIT]));
await Promise.all(seed.map(async (a) => await insertLinkEdge(db, '', a, 'seed', HOP_LIMIT, iterationTime)));
seed.forEach((article) => stored.add(article));
while (toCrawl.length > 0) {
console.log(`${(new Date().getTime() - started.getTime()) / 1000}s crawled ${crawled.size} pages, ${toCrawl.length} left to crawl, stored ${stored.size}, stored/craweld = ${Math.floor(stored.size / crawled.size)}, toCrawl/crawled = ${Math.floor(toCrawl.length / crawled.size)}, time per crawl = ${(new Date().getTime() - started.getTime()) / 1000 / crawled.size}s, ETA ${Math.floor(toCrawl.length * ((new Date().getTime() - started.getTime()) / 1000 / crawled.size) / 60)}min`);
const curr = toCrawl.shift();
const article = curr[0];
const ttl = curr[1];
if (crawled.has(article)) {
console.log(`Skipping already crawled ${article}`);
continue;
} else {
if (exclusions.includes(article)) {continue;}
console.log(`Crawling article="${article}" at ttl=${ttl}...`);
const fetchAt = new Date();
const result = (await MwActionApiClient.getLinkChildren(wiki, article));
console.log(`MwAPI delay = ${(new Date().getTime() - fetchAt.getTime()) / 1000}s`);
const storedAt = new Date();
if (ttl >= 1) {
const rowsToStore = [];
for (let i = 0; i < result.length; i++) {
const child = result[i];
if (stored.has(child)) {continue;} // already visited;
else if (exclusions.includes(child)) {continue;} // need to exclude
stored.add(child);
if (ttl - 1 >= 1) {toCrawl.push([child, ttl - 1]);}
// console.log(`Enqueueing ${child} to crawl.`);
rowsToStore.push([article, child, 'link', ttl - 1, iterationTime]);
}
if (rowsToStore.length) {await insertLinkEdges(db, rowsToStore);} else {console.log(`Skipping children of ${article}, because no rows to commit`);}
}
crawled.add(article);
console.log(`Storage delay = ${(new Date().getTime() - storedAt.getTime()) / 1000}s`);
}
}
};
mainTraverseLinkGraph().then(() => {
console.log('CMD Done!');
process.exit(0);
}); | the_stack |
import { Sparkline } from '../sparkline';
import { IThemes } from '../model/interface';
import { SparklineTheme } from '../model/enum';
import { createElement, remove } from '@syncfusion/ej2-base';
import { SvgRenderer } from '@syncfusion/ej2-svg-base';
import { SparklineBorderModel, SparklineFontModel } from '../model/base-model';
/**
* Sparkline control helper file
*/
/**
* sparkline internal use of `Size` type
*/
export class Size {
/**
* height of the size
*/
public height: number;
public width: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
}
/**
* To find the default colors based on theme.
*
* @private
*/
// tslint:disable-next-line:max-func-body-length
export function getThemeColor(theme: SparklineTheme): IThemes {
let themeColors: IThemes;
switch (theme.toLowerCase()) {
case 'bootstrapdark':
case 'fabricdark':
case 'materialdark':
case 'highcontrast':
themeColors = {
axisLineColor: '#ffffff',
dataLabelColor: '#ffffff',
rangeBandColor: '#ffffff',
tooltipFill: '#ffffff',
background: '#000000',
tooltipFontColor: '#363F4C',
trackerLineColor: '#ffffff'
};
break;
case 'bootstrap4':
themeColors = {
axisLineColor: '#6C757D',
dataLabelColor: '#212529',
rangeBandColor: '#212529',
tooltipFill: '#000000',
background: '#FFFFFF',
tooltipFontColor: '#FFFFFF',
trackerLineColor: '#212529',
fontFamily: 'HelveticaNeue-Medium',
tooltipFillOpacity: 1,
tooltipTextOpacity: 0.9,
labelFontFamily: 'HelveticaNeue'
};
break;
case 'tailwind':
themeColors = {
axisLineColor: '#4B5563',
dataLabelColor: '#212529',
rangeBandColor: '#212529',
background: '#FFFFFF',
tooltipFill: '#111827',
tooltipFontColor: '#F9FAFB',
trackerLineColor: '#1F2937',
fontFamily: 'Inter',
tooltipFillOpacity: 1,
tooltipTextOpacity: 1,
labelFontFamily: 'Inter'
};
break;
case 'tailwinddark':
themeColors = {
axisLineColor: '#D1D5DB',
dataLabelColor: '#F9FAFB',
rangeBandColor: '#F9FAFB',
background: 'transparent',
tooltipFill: '#F9FAFB',
tooltipFontColor: '#1F2937',
trackerLineColor: '#9CA3AF',
fontFamily: 'Inter',
tooltipFillOpacity: 1,
tooltipTextOpacity: 1,
labelFontFamily: 'Inter'
};
break;
case 'bootstrap5':
themeColors = {
axisLineColor: '#D1D5DB',
dataLabelColor: '#343A40',
rangeBandColor: '#212529',
background: 'rgba(255, 255, 255, 0.0)',
tooltipFill: '#212529',
tooltipFontColor: '#F9FAFB',
trackerLineColor: '#1F2937',
fontFamily: 'Helvetica Neue',
tooltipFillOpacity: 1,
tooltipTextOpacity: 1,
labelFontFamily: 'Helvetica Neue'
};
break;
case 'bootstrap5dark':
themeColors = {
axisLineColor: '#D1D5DB',
dataLabelColor: '#E9ECEF',
rangeBandColor: '#ADB5BD',
background: 'rgba(255, 255, 255, 0.0)',
tooltipFill: '#E9ECEF',
tooltipFontColor: '#212529',
trackerLineColor: '#ADB5BD',
fontFamily: 'Helvetica Neue',
tooltipFillOpacity: 1,
tooltipTextOpacity: 1,
labelFontFamily: 'Helvetica Neue'
};
break;
default: {
themeColors = {
axisLineColor: '#000000',
dataLabelColor: '#424242',
rangeBandColor: '#000000',
background: '#FFFFFF',
tooltipFill: '#363F4C',
tooltipFontColor: '#ffffff',
trackerLineColor: '#000000'
};
break;
}
}
return themeColors;
}
/**
* To find number from string
*
* @private
*/
export function stringToNumber(value: string, containerSize: number): number {
if (value !== null && value !== undefined) {
return value.indexOf('%') !== -1 ? (containerSize / 100) * parseInt(value, 10) : parseInt(value, 10);
}
return null;
}
/**
* Method to calculate the width and height of the sparkline
*/
export function calculateSize(sparkline: Sparkline): void {
const containerWidth: number = !sparkline.element.clientWidth ? (!sparkline.element.parentElement ? 100 :
(!sparkline.element.parentElement.clientWidth ? window.innerWidth : sparkline.element.parentElement.clientWidth)) :
sparkline.element.clientWidth;
const containerHeight: number = !sparkline.element.clientHeight ? (!sparkline.element.parentElement ? 50 :
sparkline.element.parentElement.clientHeight) : sparkline.element.clientHeight;
sparkline.availableSize = new Size(
stringToNumber(sparkline.width, containerWidth) || containerWidth,
stringToNumber(sparkline.height, containerHeight) || containerHeight || (sparkline.isDevice ?
Math.min(window.innerWidth, window.innerHeight) : containerHeight)
);
}
/**
* Method to create svg for sparkline.
*/
export function createSvg(sparkline: Sparkline): void {
sparkline.renderer = new SvgRenderer(sparkline.element.id);
calculateSize(sparkline);
sparkline.svgObject = sparkline.renderer.createSvg({
id: sparkline.element.id + '_svg',
width: sparkline.availableSize.width,
height: sparkline.availableSize.height
});
}
/**
* Internal use of type rect
*
* @private
*/
export class Rect {
public x: number;
public y: number;
public height: number;
public width: number;
constructor(x: number, y: number, width: number, height: number) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
/**
* Internal use of path options
*
* @private
*/
export class PathOption {
public opacity: number;
public id: string;
public stroke: string;
public fill: string;
public ['stroke-dasharray']: string;
public ['stroke-width']: number;
public d: string;
constructor(
id: string, fill: string, width: number, color: string, opacity?: number,
dashArray?: string, d?: string
) {
this.id = id;
this.fill = fill;
this.opacity = opacity;
this['stroke-width'] = width;
this.stroke = color;
this.d = d;
this['stroke-dasharray'] = dashArray;
}
}
/**
* Sparkline internal rendering options
*
* @private
*/
export interface SparkValues {
x?: number;
y?: number;
height?: number;
width?: number;
percent?: number;
degree?: number;
location?: { x: number, y: number };
markerPosition?: number;
xVal?: number;
yVal?: number;
}
/**
* Internal use of rectangle options
*
* @private
*/
export class RectOption extends PathOption {
public rect: Rect;
public topLeft: number;
public topRight: number;
public bottomLeft: number;
public bottomRight: number;
constructor(
id: string, fill: string, border: SparklineBorderModel, opacity: number,
rect: Rect, tl: number = 0, tr: number = 0, bl: number = 0, br: number = 0
) {
super(id, fill, border.width, border.color, opacity);
this.rect = rect;
this.topLeft = tl;
this.topRight = tr;
this.bottomLeft = bl;
this.bottomRight = br;
}
}
/**
* Internal use of circle options
*
* @private
*/
export class CircleOption extends PathOption {
public cy: number;
public cx: number;
public r: number;
public ['stroke-dasharray']: string;
constructor(id: string, fill: string, border: SparklineBorderModel, opacity: number, cx: number, cy: number, r: number,
dashArray: string) {
super(id, fill, border.width, border.color, opacity);
this.cy = cy;
this.cx = cx;
this.r = r;
this['stroke-dasharray'] = dashArray;
}
}
/**
* Internal use of append shape element
*
* @private
*/
export function appendShape(shape: Element, element: Element): Element {
if (element) { element.appendChild(shape); }
return shape;
}
/**
* Internal rendering of Circle
*
* @private
*/
export function drawCircle(sparkline: Sparkline, options: CircleOption, element?: Element): Element {
return appendShape(sparkline.renderer.drawCircle(options), element);
}
/**
* To get rounded rect path direction
*/
export function calculateRoundedRectPath(
r: Rect, topLeft: number, topRight: number,
bottomLeft: number, bottomRight: number
): string {
return 'M' + ' ' + r.x + ' ' + (topLeft + r.y) +
' Q ' + r.x + ' ' + r.y + ' ' + (r.x + topLeft) + ' ' +
r.y + ' ' + 'L' + ' ' + (r.x + r.width - topRight) + ' ' + r.y +
' Q ' + (r.x + r.width) + ' ' + r.y + ' ' +
(r.x + r.width) + ' ' + (r.y + topRight) + ' ' + 'L ' +
(r.x + r.width) + ' ' + (r.y + r.height - bottomRight)
+ ' Q ' + (r.x + r.width) + ' ' + (r.y + r.height) + ' ' + (r.x + r.width - bottomRight) + ' ' +
(r.y + r.height) + ' ' + 'L ' + (r.x + bottomLeft) + ' ' + (r.y + r.height) + ' Q ' + r.x + ' ' +
(r.y + r.height) + ' ' + r.x + ' ' + (r.y + r.height - bottomLeft) + ' ' + 'L' + ' ' + r.x + ' ' +
(topLeft + r.y) + ' ' + 'Z';
}
/**
* Internal rendering of Rectangle
*
* @private
*/
export function drawRectangle(sparkline: Sparkline, options: RectOption, element?: Element): Element {
options.d = calculateRoundedRectPath(options.rect, options.topLeft, options.topRight, options.bottomLeft, options.bottomRight);
return appendShape(sparkline.renderer.drawPath(options), element);
}
/**
* Internal rendering of Path
*
* @private
*/
export function drawPath(sparkline: Sparkline, options: PathOption, element?: Element): Element {
return appendShape(sparkline.renderer.drawPath(options), element);
}
/**
* Function to measure the height and width of the text.
*
* @private
*/
export function measureText(text: string, font: SparklineFontModel): Size {
let htmlObject: HTMLElement = document.getElementById('sparklinesmeasuretext');
if (htmlObject === null) {
htmlObject = createElement('text', { id: 'sparklinesmeasuretext' });
document.body.appendChild(htmlObject);
}
htmlObject.innerHTML = text;
htmlObject.style.fontStyle = font.fontStyle;
htmlObject.style.fontFamily = font.fontFamily;
htmlObject.style.visibility = 'hidden';
htmlObject.style.top = '-100';
htmlObject.style.left = '0';
htmlObject.style.position = 'absolute';
htmlObject.style.fontSize = font.size;
htmlObject.style.fontWeight = font.fontWeight;
htmlObject.style.whiteSpace = 'nowrap';
// For bootstrap line height issue
htmlObject.style.lineHeight = 'normal';
return new Size(htmlObject.clientWidth, htmlObject.clientHeight);
}
/**
* Internal use of text options
*
* @private
*/
export class TextOption {
public id: string;
public anchor: string;
public text: string;
public transform: string = '';
public x: number;
public y: number;
public baseLine: string = 'auto';
constructor(id?: string, x?: number, y?: number, anchor?: string, text?: string, baseLine?: string, transform: string = '') {
this.id = id;
this.x = x;
this.y = y;
this.anchor = anchor;
this.text = text;
this.transform = transform;
this.baseLine = baseLine;
}
}
/**
* Internal rendering of text
*
* @private
*/
export function renderTextElement(options: TextOption, font: SparklineFontModel, color: string, parent: HTMLElement | Element): Element {
const textOptions: Object = {
'id': options.id,
'x': options.x,
'y': options.y,
'transform': options.transform,
'opacity': font.opacity,
'fill': color,
'font-family': font.fontFamily,
'font-weight': font.fontWeight,
'font-size': font.size,
'font-style': font.fontStyle,
'text-anchor': options.anchor,
'dominant-baseline': options.baseLine
};
const renderer: SvgRenderer = new SvgRenderer('');
const htmlObject: HTMLElement = <HTMLElement>renderer.createText(textOptions, options.text);
htmlObject.style['user-select'] = 'none';
htmlObject.style['-moz-user-select'] = 'none';
htmlObject.style['-webkit-touch-callout'] = 'none';
htmlObject.style['-webkit-user-select'] = 'none';
htmlObject.style['-khtml-user-select'] = 'none';
htmlObject.style['-ms-user-select'] = 'none';
htmlObject.style['-o-user-select'] = 'none';
parent.appendChild(htmlObject);
return htmlObject;
}
/**
* To remove element by id
*/
export function removeElement(id: string): void {
const element: Element = document.getElementById(id);
return element ? remove(element) : null;
}
/**
* To find the element by id
*/
export function getIdElement(id: string): Element {
return document.getElementById(id);
}
/**
* To find point within the bounds.
*/
export function withInBounds(x: number, y: number, bounds: Rect): boolean {
return (x >= bounds.x && x <= bounds.x + bounds.width && y >= bounds.y && y <= bounds.y + bounds.height);
} | the_stack |
import {List} from 'immutable';
import {Twitter} from 'twit';
import Item from '../item/item';
import Tweet, {TwitterUser} from '../item/tweet';
import TimelineActivity, {TimelineActivityKind} from '../item/timeline_activity';
import Separator from '../item/separator';
import log from '../log';
import PM from '../plugin_manager';
import AppConfig from '../config';
const MaxTimelineLength = AppConfig.remote_config.max_timeline_items;
const Platform = global.process.platform;
const remote = global.require('electron').remote;
export type TimelineKind = 'home' | 'mention';
export type Notified = {home: boolean; mention: boolean};
function containsStatusInTimeline(is: List<Item>, t: Tweet) {
return is.find(i => {
if (i instanceof Tweet) {
return i.id === t.id;
} else {
return false;
}
});
}
function updateStatusIn(items: List<Item>, status: Tweet) {
const status_id = status.id;
// Note:
// One status may appear in timeline twice. (the status itself and RT for it).
// So we need to search 2 indices for the status in timeline.
const indices = items.reduce((acc: number[], item: Item, idx: number) => {
if (item instanceof Tweet) {
if (item.getMainStatus().id === status_id) {
acc.push(idx);
}
} else if (item instanceof TimelineActivity) {
if (item.status.id === status_id) {
acc.push(idx);
}
}
return acc;
}, [] as number[]);
if (indices.length === 0) {
return items;
}
const updater = (item: Item) => {
if (item instanceof Tweet) {
if (item.isRetweet()) {
const cloned = item.clone();
cloned.json.retweeted_status = status.json;
return cloned;
} else {
return status;
}
} else if (item instanceof TimelineActivity) {
const cloned = item.clone();
item.status = status;
return cloned;
} else {
log.error('Never reaches here');
return item;
}
};
return items.withMutations(items_ => {
for (const i of indices) {
items_.update(i, updater);
}
});
}
function replaceSeparatorWithItemsIn(tl: List<Item>, sep_index: number, items: Item[]) {
if (!(tl.get(sep_index) instanceof Separator)) {
log.debug('Replace target item is not a separator:', tl.get(sep_index));
return tl;
}
return tl.splice(sep_index, 1, ...items).toList();
}
function setBadge(visible: boolean) {
if (Platform === 'darwin') {
window.requestIdleCallback(() => remote.app.dock.setBadge(visible ? ' ' : ''));
}
}
// Note:
// This must be an immutable class because it is a part of state in a reducer
export default class TimelineState {
constructor(
public readonly kind: TimelineKind,
public /*readonly*/ home: List<Item>,
public /*readonly*/ mention: List<Item>,
public readonly user: TwitterUser | null,
public /*readonly*/ notified: Notified,
public readonly rejected_ids: List<number>,
public readonly no_retweet_ids: List<number>,
public /*readonly*/ focus_index: number | null,
public readonly friend_ids: List<number>,
) {}
updateActivityInMention(kind: TimelineActivityKind, status: Tweet, from: TwitterUser): [List<Item>, number | null] {
const status_id = status.id;
const index = this.mention.findIndex(item => {
if (item instanceof TimelineActivity) {
return item.kind === kind && item.status.id === status_id;
} else {
return false;
}
});
if (index === -1) {
return [
this.mention.unshift(new TimelineActivity(kind, status, [from])),
this.nextFocusIndex(this.mention.size + 1),
];
} else {
const will_updated = this.mention.get(index);
if (will_updated instanceof TimelineActivity) {
const updated = will_updated.update(status, from);
return [
this.mention.delete(index).unshift(updated),
index > this.focus_index ? this.nextFocusIndex(this.mention.size) : this.focus_index,
];
} else {
log.error('Invalid activity for update:', will_updated);
return [this.mention, this.focus_index];
}
}
}
nextFocusIndex(next_size: number) {
if (this.focus_index === null || next_size === 0) {
return null;
}
if (this.focus_index === (next_size - 1)) {
return this.focus_index;
}
return this.focus_index + 1;
}
prevFocusIndex(next_size: number) {
if (this.focus_index === null || next_size === 0) {
return null;
}
if (this.focus_index === 0) {
return 0;
}
return this.focus_index - 1;
}
checkMutedOrBlocked(status: Tweet) {
if (this.user && status.user.id === this.user.id) {
return false;
}
if (this.rejected_ids.contains(status.user.id)) {
return true;
}
for (const m of status.mentions) {
if (this.rejected_ids.contains(m.id)) {
return true;
}
}
if (status.isRetweet() && this.rejected_ids.contains(status.retweeted_status!.user.id)) {
return true;
}
if (status.isQuotedTweet() && this.rejected_ids.contains(status.quoted_status!.user.id)) {
return true;
}
if (status.isRetweet() && this.no_retweet_ids.contains(status.user.id)) {
return true;
}
return false;
}
shouldAddToTimeline(status: Tweet) {
const muted_or_blocked = this.checkMutedOrBlocked(status);
const should_add_to_home =
!PM.shouldRejectTweetInHomeTimeline(status, this) &&
(!AppConfig.mute.home || !muted_or_blocked);
const should_add_to_mention =
this.user && status.mentionsTo(this.user) &&
(status.user.id !== this.user.id) &&
!PM.shouldRejectTweetInMentionTimeline(status, this) &&
(!AppConfig.mute.mention || !muted_or_blocked);
return {
home: !!should_add_to_home,
mention: !!should_add_to_mention,
};
}
// Note:
// Currently this method is only for home timeline.
updateRelatedStatuses(status: Tweet): List<Item> {
const s = status.getMainStatus();
const id = s.id;
const in_reply_to_id = s.in_reply_to_status_id;
// Note:
// Set related statuses to newly added status
const statuses = [] as Tweet[];
this.home.forEach(item => {
if (item instanceof Tweet) {
const i = item.in_reply_to_status_id;
if (i && i === id) {
statuses.push(item);
}
if (in_reply_to_id! === item.id) {
status.in_reply_to_status = item;
}
}
});
if (statuses.length > 0) {
status.related_statuses = statuses;
}
// Note:
// Update existing statuses in timeline considering the newly added status.
return this.home.map((item: Item) => {
if (item instanceof Tweet) {
const main = item.getMainStatus();
if (main.id === in_reply_to_id!) {
const cloned = item.clone();
cloned.related_statuses.push(status);
log.debug('Related status updated:', cloned.related_statuses, cloned.json);
return cloned;
} else if (main.in_reply_to_status_id! === id) {
// Note:
// When above 'main.id === in_reply_to_id' condition is met,
// it never reaches here because no status can refer the same status
// as both in-reply-to status and in-reply-to-ed status at once.
const cloned = item.clone();
cloned.in_reply_to_status = s;
log.debug('In-reply-to status updated:', cloned);
return cloned;
}
}
return item;
}).toList();
}
putInHome(status: Tweet): [List<Item>, number|null] {
const home = this.updateRelatedStatuses(status);
const in_home = this.kind === 'home';
if (!status.isRetweet()) {
return [
home.unshift(status),
in_home ? this.nextFocusIndex(home.size + 1) : this.focus_index,
];
}
const status_id = status.retweeted_status!.id;
const index = home.findIndex(item => {
if (item instanceof Tweet) {
return item.isRetweet() && item.retweeted_status!.id === status_id;
} else {
return false;
}
});
if (index === -1) {
return [
home.unshift(status),
in_home ? this.nextFocusIndex(home.size + 1) : this.focus_index,
];
}
return [
home.delete(index).unshift(status),
// home.delete(index).unshift(status),
in_home && (this.focus_index < index) ?
this.nextFocusIndex(home.size) : this.focus_index,
];
}
updateNotified(home: boolean, mention: boolean) {
const prev_home = this.notified.home;
const prev_mention = this.notified.mention;
if (home === prev_home && mention === prev_mention) {
return this.notified;
}
if (!prev_mention && mention) {
setBadge(true);
} else if (prev_mention && !mention) {
setBadge(false);
}
return {home, mention};
}
addNewTweets(statuses: Tweet[]) {
let next: TimelineState = this;
for (const s of statuses) {
next = next.addNewTweet(s);
}
return next;
}
addNewTweet(status: Tweet) {
const should_add_to = this.shouldAddToTimeline(status);
if (!should_add_to.home && !should_add_to.mention) {
// Note: Nothing was changed.
log.debug('Status was marked as rejected:', status.user.screen_name, status.json);
return this;
}
let home = this.home;
let mention = this.mention;
let focus_index = this.focus_index;
if (should_add_to.home) {
[home, focus_index] = this.putInHome(status);
}
if (should_add_to.mention) {
if (status.isRetweet()) {
[mention, focus_index] = this.updateActivityInMention('retweeted', status.retweeted_status!, status.user);
} else {
mention = this.mention.unshift(status);
if (this.kind === 'mention') {
focus_index = this.nextFocusIndex(mention.size);
}
}
}
if (MaxTimelineLength !== null) {
if (home.size > MaxTimelineLength) {
home = home.take(MaxTimelineLength).toList();
}
if (mention.size > MaxTimelineLength) {
mention = mention.take(MaxTimelineLength).toList();
}
}
const notified = this.updateNotified(
should_add_to.home && this.kind !== 'home' || this.notified.home,
should_add_to.mention && this.kind !== 'mention' || this.notified.mention,
);
return this.update({home, mention, notified, focus_index});
}
addSeparator() {
const sep = new Separator();
const home =
this.home.first() instanceof Separator ?
this.home :
this.home.unshift(sep);
const mention =
this.mention.first() instanceof Separator ?
this.mention :
this.mention.unshift(sep);
const focus_index =
(home !== this.home && this.kind === 'home') ||
(mention !== this.mention && this.kind === 'mention') ?
this.nextFocusIndex(home.size) : this.focus_index;
return this.update({home, mention, focus_index});
}
focusOn(index: number | null) {
if (index === null) {
return this.update({focus_index: null});
}
const tl = this.getCurrentTimeline();
const size = tl.size;
if (index < 0 || (size - 1) < index) {
log.debug('Focus index out of range:', index, size);
return this;
}
return this.update({focus_index: index});
}
focusNext() {
if (this.focus_index === null) {
return this.focusTop();
}
return this.focusOn(this.focus_index + 1);
}
focusPrevious() {
if (this.focus_index === null) {
return this;
}
return this.focusOn(this.focus_index - 1);
}
focusTop() {
return this.focusOn(0);
}
focusBottom() {
const tl = this.getCurrentTimeline();
return this.focusOn(tl.size - 1);
}
switchTimeline(kind: TimelineKind) {
if (kind === this.kind) {
return this;
}
const notified = this.updateNotified(
kind === 'home' ? false : this.notified.home,
kind === 'mention' ? false : this.notified.mention,
);
return this.update({kind, notified, focus_index: null});
}
deleteStatusWithId(id: string) {
const predicate = (item: Item) => {
if (item instanceof Tweet) {
if (item.id === id) {
log.debug('Deleted status:', item);
return false;
}
if (item.isRetweet() && item.retweeted_status!.id === id) {
log.debug('Deleted retweet:', item.retweeted_status);
return false;
}
}
return true;
};
const next_home = this.home.filter(predicate).toList();
const next_mention = this.mention.filter(predicate).toList();
const home_updated = next_home.size !== this.home.size;
const mention_updated = next_mention.size !== this.mention.size;
if (!home_updated && !mention_updated) {
return this;
}
// XXX:
// Next focus index calculation is too complicated. I skipped it.
return this.update({
home: home_updated ? next_home : this.home,
mention: mention_updated ? next_mention : this.mention,
});
}
addMentions(mentions: Tweet[]) {
const added = List<Item>(
mentions.filter(
m => !containsStatusInTimeline(this.mention, m)
)
);
const notified = this.updateNotified(this.notified.home, this.kind !== 'mention');
const focus_index =
this.kind !== 'mention' || this.focus_index === null ?
this.focus_index :
(this.focus_index + added.size);
let next_mention = added.concat(this.mention);
if (MaxTimelineLength !== null && next_mention.size > MaxTimelineLength) {
next_mention = next_mention.take(MaxTimelineLength);
}
return this.update({
mention: next_mention.toList(),
notified,
focus_index,
});
}
updateStatus(status: Tweet) {
const home = updateStatusIn(this.home, status);
const mention = updateStatusIn(this.mention, status);
if (home === this.home && mention === this.mention) {
return this;
}
return this.update({home, mention});
}
setUser(user: TwitterUser) {
return this.update({user});
}
updateUser(update_json: Twitter.User) {
if (this.user === null) {
log.error('User is not set yet', this);
return this;
}
const j = this.user.json;
for (const prop in update_json) {
const v = (update_json as any)[prop];
if (v !== null) {
(j as any)[prop] = v;
}
}
return this.update({
user: new TwitterUser(j),
});
}
getCurrentTimeline() {
return this.getTimeline(this.kind);
}
getTimeline(kind: TimelineKind) {
switch (kind) {
case 'home':
return this.home;
case 'mention':
return this.mention;
default:
log.error('Invalid timeline kind', this);
return List<Item>(); // Fallback
}
}
addRejectedIds(ids: number[]) {
const will_added = ids.filter(id => !this.rejected_ids.contains(id));
if (will_added.length === 0) {
return this;
}
const predicate = (i: Item) => {
if (i instanceof Tweet) {
if (i.isRetweet() && will_added.indexOf(i.retweeted_status!.user.id) !== -1) {
return false;
}
return will_added.indexOf(i.user.id) === -1;
} else {
return true;
}
};
const next_home = this.home.filter(predicate).toList();
const next_mention = this.mention.filter(predicate).toList();
const home_updated = next_home.size !== this.home.size;
const mention_updated = next_mention.size !== this.mention.size;
const rejected_ids = this.rejected_ids.concat(will_added).toList();
// XXX:
// Next focus index calculation is too complicated. I skipped it.
return this.update({
home: home_updated ? next_home : this.home,
mention: mention_updated ? next_mention : this.mention,
rejected_ids,
});
}
addNoRetweetUserIds(ids: number[]) {
ids = ids.filter(id => !this.no_retweet_ids.contains(id));
const no_retweet_ids = this.no_retweet_ids.concat(ids).toList();
const home = this.home.filter((i: Item) => {
if (i instanceof Tweet) {
return !i.isRetweet() || ids.indexOf(i.user.id) === -1;
} else {
return true;
}
}).toList();
// Note:
// Mention timeline does not include retweet status. We might update
// retweet activities in mention timeline.
// XXX:
// Next focus index calculation is too complicated. I skipped it.
return this.update({home, no_retweet_ids});
}
removeRejectedIds(ids: number[]) {
const rejected_ids = this.rejected_ids.filter((id: number) => ids.indexOf(id) === -1).toList();
// Note:
// There is no way to restore muted/blocked tweets in timeline
return this.update({rejected_ids});
}
updateActivity(kind: TimelineActivityKind, status: Tweet, from: TwitterUser) {
if (this.user === null) {
log.error('User is not set yet.');
return this;
}
if (from.id === this.user.id) {
// Note:
// 'favorite' user event on stream is sent both when owner creates and when owner's
// tweet is favorited. We're only interested in favorites created by others because
// favorites created by owner is already handled by LikeSucceeded action.
return this;
}
const status_updated = this.updateStatus(status);
let [mention, focus_index] = this.updateActivityInMention(kind, status, from);
if (MaxTimelineLength !== null && mention.size > MaxTimelineLength) {
mention = mention.take(MaxTimelineLength).toList();
}
const notified = this.kind !== 'mention' && !this.notified.mention ?
this.updateNotified(this.notified.home, true) :
this.notified;
return status_updated.update({mention, focus_index, notified});
}
addFriends(ids: number[]) {
const will_added = ids.filter(id => !this.friend_ids.contains(id));
if (will_added.length === 0) {
return this;
}
return this.update({
friend_ids: this.friend_ids.concat(will_added).toList(),
});
}
removeFriends(ids: number[]) {
const friend_ids = this.friend_ids.filter((id: number) => ids.indexOf(id) === -1).toList();
return this.update({friend_ids});
}
resetFriends(ids: number[]) {
const friend_ids = List<number>(ids);
return this.update({friend_ids});
}
replaceSeparatorWithItems(kind: TimelineKind, sep_index: number, items: Item[]) {
// Note:
// We don't need to check this.shouldAddToTimeline() here because items are already
// considered to be added to each timeline.
// (e.g. items for mention timeline were fetched with reply-only search so items only contain
// replies and mentions.)
const filtered = items.filter(item => {
if (item instanceof Tweet) {
const rejected = this.checkMutedOrBlocked(item);
switch (kind) {
case 'home':
return !PM.shouldRejectTweetInHomeTimeline(item, this) &&
(!AppConfig.mute.home || !rejected);
case 'mention':
return !PM.shouldRejectTweetInMentionTimeline(item, this) &&
(!AppConfig.mute.mention || !rejected);
default:
log.error('Invalid kind on filtering missing statuses', kind);
return true;
}
} else {
return true;
}
});
switch (kind) {
case 'home':
const home = replaceSeparatorWithItemsIn(this.home, sep_index, filtered);
let next = this.update({home});
for (const i of filtered.reverse()) {
if (i instanceof Tweet) {
next.home = next.updateRelatedStatuses(i);
}
}
return next;
case 'mention':
return this.update({
mention: replaceSeparatorWithItemsIn(this.mention, sep_index, filtered),
});
default:
log.debug('Invalid timeline for replacing separator with statuses');
return this;
}
}
update(next: {
kind?: TimelineKind;
home?: List<Item>;
mention?: List<Item>;
user?: TwitterUser;
notified?: Notified;
rejected_ids?: List<number>;
no_retweet_ids?: List<number>;
focus_index?: number | null;
friend_ids?: List<number>;
}) {
return new TimelineState(
next.kind === undefined ? this.kind : next.kind,
next.home === undefined ? this.home : next.home,
next.mention === undefined ? this.mention : next.mention,
next.user === undefined ? this.user : next.user,
next.notified === undefined ? this.notified : next.notified,
next.rejected_ids === undefined ? this.rejected_ids : next.rejected_ids,
next.no_retweet_ids === undefined ? this.no_retweet_ids : next.no_retweet_ids,
next.focus_index === undefined ? this.focus_index : next.focus_index,
next.friend_ids === undefined ? this.friend_ids : next.friend_ids,
);
}
}
export const DefaultTimelineState =
new TimelineState(
'home',
List<Item>([new Separator()]),
List<Item>([new Separator()]),
null,
{home: false, mention: false},
List<number>(),
List<number>(),
null,
List<number>(),
); | the_stack |
import * as vscode from "vscode";
import * as utils from "./utils";
import { ConfigMembers, ConfigSetting, FontSettings } from "./types";
import { Constants } from "./constants";
import { LeoIntegration } from "./leoIntegration";
/**
* * Configuration Settings Service
*/
export class Config implements ConfigMembers {
// Config settings used in leobridgeserver.py, on Leo's side
public checkForChangeExternalFiles: string = Constants.CONFIG_DEFAULTS.CHECK_FOR_CHANGE_EXTERNAL_FILES;
public defaultReloadIgnore: string = Constants.CONFIG_DEFAULTS.DEFAULT_RELOAD_IGNORE;
// Config settings used in leoInteg/vscode's side
public leoTreeBrowse: boolean = Constants.CONFIG_DEFAULTS.LEO_TREE_BROWSE;
public treeKeepFocus: boolean = Constants.CONFIG_DEFAULTS.TREE_KEEP_FOCUS;
public treeKeepFocusWhenAside: boolean = Constants.CONFIG_DEFAULTS.TREE_KEEP_FOCUS_WHEN_ASIDE;
public statusBarString: string = Constants.CONFIG_DEFAULTS.STATUSBAR_STRING;
public statusBarColor: string = Constants.CONFIG_DEFAULTS.STATUSBAR_COLOR;
public treeInExplorer: boolean = Constants.CONFIG_DEFAULTS.TREE_IN_EXPLORER;
public showOpenAside: boolean = Constants.CONFIG_DEFAULTS.SHOW_OPEN_ASIDE;
public showEditOnNodes: boolean = Constants.CONFIG_DEFAULTS.SHOW_EDIT;
public showArrowsOnNodes: boolean = Constants.CONFIG_DEFAULTS.SHOW_ARROWS;
public showAddOnNodes: boolean = Constants.CONFIG_DEFAULTS.SHOW_ADD;
public showMarkOnNodes: boolean = Constants.CONFIG_DEFAULTS.SHOW_MARK;
public showCloneOnNodes: boolean = Constants.CONFIG_DEFAULTS.SHOW_CLONE;
public showCopyOnNodes: boolean = Constants.CONFIG_DEFAULTS.SHOW_COPY;
public showEditionOnBody: boolean = Constants.CONFIG_DEFAULTS.SHOW_EDITION_BODY;
public showClipboardOnBody: boolean = Constants.CONFIG_DEFAULTS.SHOW_CLIPBOARD_BODY;
public showPromoteOnBody: boolean = Constants.CONFIG_DEFAULTS.SHOW_PROMOTE_BODY;
public showExecuteOnBody: boolean = Constants.CONFIG_DEFAULTS.SHOW_EXECUTE_BODY;
public showExtractOnBody: boolean = Constants.CONFIG_DEFAULTS.SHOW_EXTRACT_BODY;
public showImportOnBody: boolean = Constants.CONFIG_DEFAULTS.SHOW_IMPORT_BODY;
public showRefreshOnBody: boolean = Constants.CONFIG_DEFAULTS.SHOW_REFRESH_BODY;
public showHoistOnBody: boolean = Constants.CONFIG_DEFAULTS.SHOW_HOIST_BODY;
public showMarkOnBody: boolean = Constants.CONFIG_DEFAULTS.SHOW_MARK_BODY;
public showSortOnBody: boolean = Constants.CONFIG_DEFAULTS.SHOW_SORT_BODY;
public invertNodeContrast: boolean = Constants.CONFIG_DEFAULTS.INVERT_NODES;
public leoPythonCommand: string = Constants.CONFIG_DEFAULTS.LEO_PYTHON_COMMAND;
public leoEditorPath: string = Constants.CONFIG_DEFAULTS.LEO_EDITOR_PATH;
public startServerAutomatically: boolean = Constants.CONFIG_DEFAULTS.AUTO_START_SERVER;
public connectToServerAutomatically: boolean = Constants.CONFIG_DEFAULTS.AUTO_CONNECT;
public connectionAddress: string = Constants.CONFIG_DEFAULTS.IP_ADDRESS;
public connectionPort: number = Constants.CONFIG_DEFAULTS.IP_PORT;
public setDetached: boolean = Constants.CONFIG_DEFAULTS.SET_DETACHED;
public limitUsers: number = Constants.CONFIG_DEFAULTS.LIMIT_USERS;
private _isBusySettingConfig: boolean = false;
private _needsTreeRefresh: boolean = false;
constructor(
private _context: vscode.ExtensionContext,
private _leoIntegration: LeoIntegration
) { }
/**
* * Get actual 'live' Leointeg configuration
* @returns An object with config settings members such as treeKeepFocus, defaultReloadIgnore, etc.
*/
public getConfig(): ConfigMembers {
return {
checkForChangeExternalFiles: this.checkForChangeExternalFiles, // Used in leoBridge script
defaultReloadIgnore: this.defaultReloadIgnore, // Used in leoBridge script
leoTreeBrowse: this.leoTreeBrowse,
treeKeepFocus: this.treeKeepFocus,
treeKeepFocusWhenAside: this.treeKeepFocusWhenAside,
statusBarString: this.statusBarString,
statusBarColor: this.statusBarColor,
treeInExplorer: this.treeInExplorer,
showOpenAside: this.showOpenAside,
showEditOnNodes: this.showEditOnNodes,
showArrowsOnNodes: this.showArrowsOnNodes,
showAddOnNodes: this.showAddOnNodes,
showMarkOnNodes: this.showMarkOnNodes,
showCloneOnNodes: this.showCloneOnNodes,
showCopyOnNodes: this.showCopyOnNodes,
showEditionOnBody: this.showEditionOnBody,
showClipboardOnBody: this.showClipboardOnBody,
showPromoteOnBody: this.showPromoteOnBody,
showExecuteOnBody: this.showExecuteOnBody,
showExtractOnBody: this.showExtractOnBody,
showImportOnBody: this.showImportOnBody,
showRefreshOnBody: this.showRefreshOnBody,
showHoistOnBody: this.showHoistOnBody,
showMarkOnBody: this.showMarkOnBody,
showSortOnBody: this.showSortOnBody,
invertNodeContrast: this.invertNodeContrast,
leoPythonCommand: this.leoPythonCommand,
leoEditorPath: this.leoEditorPath,
startServerAutomatically: this.startServerAutomatically,
connectToServerAutomatically: this.connectToServerAutomatically,
connectionAddress: this.connectionAddress,
connectionPort: this.connectionPort,
setDetached: this.setDetached,
limitUsers: this.limitUsers,
};
}
/**
* * Get config from vscode for the UI font sizes
* @returns the font settings object (zoom level and editor font size)
*/
public getFontConfig(): FontSettings {
let w_zoomLevel = vscode.workspace.getConfiguration(
"window"
).get("zoomLevel");
let w_fontSize = vscode.workspace.getConfiguration(
"editor"
).get("fontSize");
const w_config: FontSettings = {
zoomLevel: Number(w_zoomLevel),
fontSize: Number(w_fontSize)
};
return w_config;
}
/**
* * Apply changes to the expansion config settings and save them in user settings.
* @param p_changes is an array of codes and values to be changed
* @returns a promise that resolves upon completion
*/
public setLeoIntegSettings(p_changes: ConfigSetting[]): Promise<void> {
this._isBusySettingConfig = true;
const w_promises: Thenable<void>[] = [];
const w_vscodeConfig = vscode.workspace.getConfiguration(Constants.CONFIG_NAME);
p_changes.forEach(i_change => {
if (i_change && i_change.code.includes(Constants.CONFIG_REFRESH_MATCH)) {
// Check if tree refresh is required for hover-icons to be displayed or hidden accordingly
this._needsTreeRefresh = true;
}
if (w_vscodeConfig.inspect(i_change.code)!.defaultValue === i_change.value) {
// Set as undefined - same as default
w_promises.push(w_vscodeConfig.update(i_change.code, undefined, true));
} else {
// Set as value which is not default
w_promises.push(w_vscodeConfig.update(i_change.code, i_change.value, true));
}
});
return Promise.all(w_promises).then(() => {
if (this._needsTreeRefresh) {
this._needsTreeRefresh = false;
setTimeout(() => {
this._leoIntegration.configTreeRefresh();
}, 200);
}
this._isBusySettingConfig = false;
this.buildFromSavedSettings();
return Promise.resolve();
});
}
/**
* * Apply changes in font size settings and save them in user settings.
*/
public setFontConfig(p_settings: FontSettings): void {
if (p_settings.zoomLevel || p_settings.zoomLevel === 0) {
if (!isNaN(p_settings.zoomLevel) && p_settings.zoomLevel <= 12 && p_settings.zoomLevel >= -12) {
vscode.workspace.getConfiguration("window")
.update("zoomLevel", p_settings.zoomLevel, true);
} else {
vscode.window.showInformationMessage(
"Value for zoom level should be between -12 and 12"
);
}
}
if (p_settings.fontSize) {
if (!isNaN(p_settings.fontSize) && p_settings.fontSize <= 30 && p_settings.fontSize >= 6) {
vscode.workspace.getConfiguration("editor")
.update("fontSize", p_settings.fontSize, true);
} else {
vscode.window.showInformationMessage(
"Value for font size should be between 6 and 30"
);
}
}
}
/**
* * Set the workbench.editor.enablePreview vscode setting
*/
public setEnablePreview(): Thenable<void> {
return vscode.workspace.getConfiguration("workbench.editor")
.update("enablePreview", true, true);
}
/**
* * Clears the workbench.editor.closeEmptyGroups vscode setting
*/
public clearCloseEmptyGroups(): Thenable<void> {
return vscode.workspace.getConfiguration("workbench.editor")
.update("closeEmptyGroups", false, true);
}
/**
* * Set the "workbench.editor.closeOnFileDelete" vscode setting
*/
public setCloseOnFileDelete(): Thenable<void> {
return vscode.workspace.getConfiguration("workbench.editor")
.update("closeOnFileDelete", true, true);
}
/**
* * Check if the workbench.editor.enablePreview flag is set
* @param p_forced Forces the setting instead of just suggesting with a message
*/
public checkEnablePreview(p_forced?: boolean): void {
let w_result: any = true;
const w_setting = vscode.workspace.getConfiguration("workbench.editor");
if (w_setting.inspect("enablePreview")!.globalValue === undefined) {
w_result = w_setting.inspect("enablePreview")!.defaultValue;
} else {
w_result = w_setting.inspect("enablePreview")!.globalValue;
}
if (w_result === false) {
if (p_forced) {
this.setEnablePreview();
vscode.window.showInformationMessage("'Enable Preview' setting was set");
} else {
if (!this._leoIntegration.leoStates.leoStartupFinished) {
return;
}
vscode.window.showWarningMessage("'Enable Preview' setting is recommended (currently disabled)", "Fix it")
.then(p_chosenButton => {
if (p_chosenButton === "Fix it") {
vscode.commands.executeCommand(Constants.COMMANDS.SET_ENABLE_PREVIEW);
}
});
}
}
}
/**
* * Check if the 'workbench.editor.closeEmptyGroups' setting is false
* @param p_forced Forces the setting instead of just suggesting with a message
*/
public checkCloseEmptyGroups(p_forced?: boolean): void {
let w_result: any = false;
const w_setting = vscode.workspace.getConfiguration("workbench.editor");
if (w_setting.inspect("closeEmptyGroups")!.globalValue === undefined) {
w_result = w_setting.inspect("closeEmptyGroups")!.defaultValue;
} else {
w_result = w_setting.inspect("closeEmptyGroups")!.globalValue;
}
if (w_result === true) {
if (p_forced) {
this.clearCloseEmptyGroups();
vscode.window.showInformationMessage("'Close Empty Groups' setting was cleared");
} else {
if (!this._leoIntegration.leoStates.leoStartupFinished) {
return;
}
vscode.window.showWarningMessage("'Close Empty Groups' setting is NOT recommended!", "Fix it")
.then(p_chosenButton => {
if (p_chosenButton === "Fix it") {
vscode.commands.executeCommand(Constants.COMMANDS.CLEAR_CLOSE_EMPTY_GROUPS);
}
});
}
}
}
/**
* * Check if the workbench.editor.closeOnFileDelete flag is set
* @param p_forced Forces the setting instead of just suggesting with a message
*/
public checkCloseOnFileDelete(p_forced?: boolean): void {
let w_result: any = true;
const w_setting = vscode.workspace.getConfiguration("workbench.editor");
if (w_setting.inspect("closeOnFileDelete")!.globalValue === undefined) {
w_result = w_setting.inspect("closeOnFileDelete")!.defaultValue;
} else {
w_result = w_setting.inspect("closeOnFileDelete")!.globalValue;
}
if (w_result === false) {
if (p_forced) {
this.setCloseOnFileDelete();
vscode.window.showInformationMessage("'Close on File Delete' setting was set");
} else {
if (!this._leoIntegration.leoStates.leoStartupFinished) {
return;
}
vscode.window.showWarningMessage("'Close on File Delete' setting is recommended (currently disabled)", "Fix it")
.then(p_chosenButton => {
if (p_chosenButton === "Fix it") {
vscode.commands.executeCommand(Constants.COMMANDS.SET_CLOSE_ON_FILE_DELETE);
}
});
}
}
}
/**
* * Build config from settings from vscode's saved config settings
*/
public buildFromSavedSettings(): void {
// Shorthand pointers for readability
const GET = vscode.workspace.getConfiguration;
const NAME = Constants.CONFIG_NAME;
const NAMES = Constants.CONFIG_NAMES;
const DEFAULTS = Constants.CONFIG_DEFAULTS;
const FLAGS = Constants.CONTEXT_FLAGS;
if (this._isBusySettingConfig) {
// * Currently setting config, wait until its done all, and this will be called automatically
return;
} else {
this.checkForChangeExternalFiles = GET(NAME).get(NAMES.CHECK_FOR_CHANGE_EXTERNAL_FILES, DEFAULTS.CHECK_FOR_CHANGE_EXTERNAL_FILES);
this.defaultReloadIgnore = GET(NAME).get(NAMES.DEFAULT_RELOAD_IGNORE, DEFAULTS.DEFAULT_RELOAD_IGNORE);
this.leoTreeBrowse = GET(NAME).get(NAMES.LEO_TREE_BROWSE, DEFAULTS.LEO_TREE_BROWSE);
this.treeKeepFocus = GET(NAME).get(NAMES.TREE_KEEP_FOCUS, DEFAULTS.TREE_KEEP_FOCUS);
this.treeKeepFocusWhenAside = GET(NAME).get(NAMES.TREE_KEEP_FOCUS_WHEN_ASIDE, DEFAULTS.TREE_KEEP_FOCUS_WHEN_ASIDE);
this.statusBarString = GET(NAME).get(NAMES.STATUSBAR_STRING, DEFAULTS.STATUSBAR_STRING);
if (this.statusBarString.length > 8) {
this.statusBarString = DEFAULTS.STATUSBAR_STRING;
}
this.statusBarColor = GET(NAME).get(NAMES.STATUSBAR_COLOR, DEFAULTS.STATUSBAR_COLOR);
if (!utils.isHexColor(this.statusBarColor)) {
this.statusBarColor = DEFAULTS.STATUSBAR_COLOR;
}
this.treeInExplorer = GET(NAME).get(NAMES.TREE_IN_EXPLORER, DEFAULTS.TREE_IN_EXPLORER);
this.showOpenAside = GET(NAME).get(NAMES.SHOW_OPEN_ASIDE, DEFAULTS.SHOW_OPEN_ASIDE);
this.showEditOnNodes = GET(NAME).get(NAMES.SHOW_EDIT, DEFAULTS.SHOW_EDIT);
this.showArrowsOnNodes = GET(NAME).get(NAMES.SHOW_ARROWS, DEFAULTS.SHOW_ARROWS);
this.showAddOnNodes = GET(NAME).get(NAMES.SHOW_ADD, DEFAULTS.SHOW_ADD);
this.showMarkOnNodes = GET(NAME).get(NAMES.SHOW_MARK, DEFAULTS.SHOW_MARK);
this.showCloneOnNodes = GET(NAME).get(NAMES.SHOW_CLONE, DEFAULTS.SHOW_CLONE);
this.showCopyOnNodes = GET(NAME).get(NAMES.SHOW_COPY, DEFAULTS.SHOW_COPY);
this.showEditionOnBody = GET(NAME).get(NAMES.SHOW_EDITION_BODY, DEFAULTS.SHOW_EDITION_BODY);
this.showClipboardOnBody = GET(NAME).get(NAMES.SHOW_CLIPBOARD_BODY, DEFAULTS.SHOW_CLIPBOARD_BODY);
this.showPromoteOnBody = GET(NAME).get(NAMES.SHOW_PROMOTE_BODY, DEFAULTS.SHOW_PROMOTE_BODY);
this.showExecuteOnBody = GET(NAME).get(NAMES.SHOW_EXECUTE_BODY, DEFAULTS.SHOW_EXECUTE_BODY);
this.showExtractOnBody = GET(NAME).get(NAMES.SHOW_EXTRACT_BODY, DEFAULTS.SHOW_EXTRACT_BODY);
this.showImportOnBody = GET(NAME).get(NAMES.SHOW_IMPORT_BODY, DEFAULTS.SHOW_IMPORT_BODY);
this.showRefreshOnBody = GET(NAME).get(NAMES.SHOW_REFRESH_BODY, DEFAULTS.SHOW_REFRESH_BODY);
this.showHoistOnBody = GET(NAME).get(NAMES.SHOW_HOIST_BODY, DEFAULTS.SHOW_HOIST_BODY);
this.showMarkOnBody = GET(NAME).get(NAMES.SHOW_MARK_BODY, DEFAULTS.SHOW_MARK_BODY);
this.showSortOnBody = GET(NAME).get(NAMES.SHOW_SORT_BODY, DEFAULTS.SHOW_SORT_BODY);
this.invertNodeContrast = GET(NAME).get(NAMES.INVERT_NODES, DEFAULTS.INVERT_NODES);
this.leoEditorPath = GET(NAME).get(NAMES.LEO_EDITOR_PATH, DEFAULTS.LEO_EDITOR_PATH);
this.leoPythonCommand = GET(NAME).get(NAMES.LEO_PYTHON_COMMAND, DEFAULTS.LEO_PYTHON_COMMAND);
this.startServerAutomatically = GET(NAME).get(NAMES.AUTO_START_SERVER, DEFAULTS.AUTO_START_SERVER);
this.connectToServerAutomatically = GET(NAME).get(NAMES.AUTO_CONNECT, DEFAULTS.AUTO_CONNECT);
this.connectionAddress = GET(NAME).get(NAMES.IP_ADDRESS, DEFAULTS.IP_ADDRESS);
this.connectionPort = GET(NAME).get(NAMES.IP_PORT, DEFAULTS.IP_PORT);
this.setDetached = GET(NAME).get(NAMES.SET_DETACHED, DEFAULTS.SET_DETACHED);
this.limitUsers = GET(NAME).get(NAMES.LIMIT_USERS, DEFAULTS.LIMIT_USERS);
// * Set context for tree items visibility that are based on config options
if (this._leoIntegration.leoStates.leoBridgeReady) {
this._leoIntegration.sendConfigToServer(this.getConfig());
}
utils.setContext(FLAGS.LEO_TREE_BROWSE, this.leoTreeBrowse);
utils.setContext(FLAGS.TREE_IN_EXPLORER, this.treeInExplorer);
utils.setContext(FLAGS.SHOW_OPEN_ASIDE, this.showOpenAside);
utils.setContext(FLAGS.SHOW_EDIT, this.showEditOnNodes);
utils.setContext(FLAGS.SHOW_ARROWS, this.showArrowsOnNodes);
utils.setContext(FLAGS.SHOW_ADD, this.showAddOnNodes);
utils.setContext(FLAGS.SHOW_MARK, this.showMarkOnNodes);
utils.setContext(FLAGS.SHOW_CLONE, this.showCloneOnNodes);
utils.setContext(FLAGS.SHOW_COPY, this.showCopyOnNodes);
utils.setContext(FLAGS.SHOW_EDITION_BODY, this.showEditionOnBody);
utils.setContext(FLAGS.SHOW_CLIPBOARD_BODY, this.showClipboardOnBody);
utils.setContext(FLAGS.SHOW_PROMOTE_BODY, this.showPromoteOnBody);
utils.setContext(FLAGS.SHOW_EXECUTE_BODY, this.showExecuteOnBody);
utils.setContext(FLAGS.SHOW_EXTRACT_BODY, this.showExtractOnBody);
utils.setContext(FLAGS.SHOW_IMPORT_BODY, this.showImportOnBody);
utils.setContext(FLAGS.SHOW_REFRESH_BODY, this.showRefreshOnBody);
utils.setContext(FLAGS.SHOW_HOIST_BODY, this.showHoistOnBody);
utils.setContext(FLAGS.SHOW_MARK_BODY, this.showMarkOnBody);
utils.setContext(FLAGS.SHOW_SORT_BODY, this.showSortOnBody);
utils.setContext(FLAGS.AUTO_CONNECT, this.connectToServerAutomatically);
if (!this._leoIntegration.leoStates.leoStartupFinished && this.leoEditorPath) {
// Only relevant 'viewWelcome' content at startup.
utils.setContext(FLAGS.AUTO_START_SERVER, this.startServerAutomatically); // ok
// utils.setContext(FLAGS.AUTO_CONNECT, this.connectToServerAutomatically);
} else {
utils.setContext(FLAGS.AUTO_START_SERVER, false); // Save option but not context flag
//utils.setContext(FLAGS.AUTO_CONNECT, false);
}
}
}
} | the_stack |
import { AmbientLight, Vector3, Object3D, SpotLight, DirectionalLight, Euler, Scene } from "three";
import { ThreeJsPanel } from "./ThreeJsPanel";
import lightSettings from "./constants/lights";
import FusedChannelData from "./FusedChannelData";
import VolumeDrawable from "./VolumeDrawable";
import { Light, AREA_LIGHT, SKY_LIGHT } from "./Light";
import Volume from "./Volume";
import { VolumeChannelDisplayOptions, VolumeDisplayOptions, isOrthographicCamera } from "./types";
export const RENDERMODE_RAYMARCH = 0;
export const RENDERMODE_PATHTRACE = 1;
export interface View3dOptions {
useWebGL2: boolean;
}
/**
* @class
*/
export class View3d {
private canvas3d: ThreeJsPanel;
private scene: Scene;
private backgroundColor: number;
private pixelSamplingRate: number;
private exposure: number;
private volumeRenderMode: number;
private renderUpdateListener?: (iteration: number) => void;
private loaded: boolean;
private parentEl: HTMLElement;
private image?: VolumeDrawable;
private oldScale: Vector3;
private currentScale: Vector3;
private lights: Light[];
private lightContainer: Object3D;
private ambientLight: AmbientLight;
private spotLight: SpotLight;
private reflectedLight: DirectionalLight;
private fillLight: DirectionalLight;
/**
* @param {HTMLElement} parentElement the 3d display will try to fill the parent element.
* @param {Object} options This is an optional param. The only option is currently boolean {useWebGL2:true} which defaults to true.
*/
constructor(parentElement: HTMLElement, options: View3dOptions = { useWebGL2: true }) {
if (options.useWebGL2 === undefined) {
options.useWebGL2 = true;
}
this.canvas3d = new ThreeJsPanel(parentElement, options.useWebGL2);
this.redraw = this.redraw.bind(this);
this.scene = new Scene();
this.backgroundColor = 0x000000;
this.lights = [];
this.pixelSamplingRate = 0.75;
this.exposure = 0.5;
this.volumeRenderMode = RENDERMODE_RAYMARCH;
this.loaded = false;
this.parentEl = parentElement;
window.addEventListener("resize", () => this.resize(null, this.parentEl.offsetWidth, this.parentEl.offsetHeight));
this.oldScale = new Vector3();
this.currentScale = new Vector3();
this.lightContainer = new Object3D();
this.ambientLight = new AmbientLight();
this.spotLight = new SpotLight();
this.reflectedLight = new DirectionalLight();
this.fillLight = new DirectionalLight();
this.buildScene();
FusedChannelData.setOnFuseComplete(this.redraw.bind(this));
}
// prerender should be called on every redraw and should be the first thing done.
preRender(): void {
// TODO: if fps just updated and it's too low, do something:
// if (this.canvas3d.timer.lastFPS < 7 && this.canvas3d.timer.lastFPS > 0 && this.canvas3d.timer.frames === 0) {
// }
const lightContainer = this.scene.getObjectByName("lightContainer");
if (lightContainer) {
lightContainer.rotation.setFromRotationMatrix(this.canvas3d.camera.matrixWorld);
}
// keep the ortho scale up to date.
if (this.image && isOrthographicCamera(this.canvas3d.camera)) {
this.image.setOrthoScale(this.canvas3d.controls.scale);
}
}
/**
* Capture the contents of this canvas to a data url
* @param {Object} dataurlcallback function to call when data url is ready; function accepts dataurl as string arg
*/
capture(dataurlcallback: (name: string) => void): void {
return this.canvas3d.requestCapture(dataurlcallback);
}
/**
* Force a redraw.
*/
redraw(): void {
this.canvas3d.redraw();
}
unsetImage(): VolumeDrawable | undefined {
if (this.image) {
this.canvas3d.removeControlHandlers();
this.canvas3d.animateFuncs = [];
this.scene.remove(this.image.sceneRoot);
}
return this.image;
}
/**
* Add a new volume image to the viewer. (The viewer currently only supports a single image at a time - adding repeatedly, without removing in between, is a potential resource leak)
* @param {Volume} volume
* @param {VolumeDisplayOptions} options
*/
addVolume(volume: Volume, options?: VolumeDisplayOptions): void {
volume.addVolumeDataObserver(this);
options = options || {};
options.renderMode = this.volumeRenderMode === RENDERMODE_PATHTRACE ? 1 : 0;
this.setImage(new VolumeDrawable(volume, options));
}
/**
* Apply a set of display options to a given channel of a volume
* @param {Volume} volume
* @param {number} channelIndex the channel index
* @param {VolumeChannelDisplayOptions} options
*/
setVolumeChannelOptions(volume: Volume, channelIndex: number, options: VolumeChannelDisplayOptions): void {
if (!this.image) {
return;
}
this.image.setChannelOptions(channelIndex, options);
this.redraw();
}
/**
* Apply a set of display options to the given volume
* @param {Volume} volume
* @param {VolumeDisplayOptions} options
*/
setVolumeDisplayOptions(volume: Volume, options: VolumeDisplayOptions): void {
if (!this.image) {
return;
}
this.image.setOptions(options);
this.redraw();
}
/**
* Remove a volume image from the viewer. This will clean up the View3D's resources for the current volume
* @param {Volume} volume
*/
removeVolume(volume: Volume): void {
const oldImage = this.unsetImage();
if (oldImage) {
oldImage.cleanup();
}
if (volume) {
// assert oldImage.volume === volume!
volume.removeVolumeDataObserver(this);
}
}
/**
* Remove all volume images from the viewer.
*/
removeAllVolumes(): void {
if (this.image) {
this.removeVolume(this.image.volume);
}
}
/**
* @param {function} callback a function that will receive the number of render iterations when it changes
*/
setRenderUpdateListener(callback: (iteration: number) => void): void {
this.renderUpdateListener = callback;
if (this.image) {
this.image.setRenderUpdateListener(callback);
}
}
// channels is an array of channel indices for which new data just arrived.
onVolumeData(volume: Volume, channels: number[]): void {
if (this.image) {
this.image.onChannelLoaded(channels);
}
}
// do fixups for when the volume has had a new empty channel added.
onVolumeChannelAdded(volume: Volume, newChannelIndex: number): void {
if (this.image) {
this.image.onChannelAdded(newChannelIndex);
}
}
/**
* Assign a channel index as a mask channel (will multiply its color against the entire visible volume)
* @param {Object} volume
* @param {number} maskChannelIndex
*/
setVolumeChannelAsMask(volume: Volume, maskChannelIndex: number): void {
if (this.image) {
this.image.setChannelAsMask(maskChannelIndex);
}
this.redraw();
}
/**
* Set voxel dimensions - controls volume scaling. For example, the physical measurements of the voxels from a biological data set
* @param {Object} volume
* @param {number} values Array of x,y,z floating point values for the physical voxel size scaling
*/
setVoxelSize(volume: Volume, values: number[]): void {
if (this.image) {
this.image.setVoxelSize(values);
}
this.redraw();
}
setRayStepSizes(volume: Volume, primary: number, secondary: number): void {
if (this.image) {
this.image.setRayStepSizes(primary, secondary);
}
this.redraw();
}
setShowBoundingBox(volume: Volume, showBoundingBox: boolean): void {
if (this.image) {
this.image.setShowBoundingBox(showBoundingBox);
}
this.redraw();
}
setBoundingBoxColor(volume: Volume, color: [number, number, number]): void {
if (this.image) {
this.image.setBoundingBoxColor(color);
}
this.redraw();
}
/**
* If an isosurface is not already created, then create one. Otherwise change the isovalue of the existing isosurface.
* @param {Object} volume
* @param {number} channel
* @param {number} isovalue isovalue
* @param {number=} alpha Opacity
*/
createIsosurface(volume: Volume, channel: number, isovalue: number, alpha: number): void {
if (!this.image) {
return;
}
if (this.image.hasIsosurface(channel)) {
this.image.updateIsovalue(channel, isovalue);
} else {
this.image.createIsosurface(channel, isovalue, alpha, alpha < 0.95);
}
this.redraw();
}
/**
* Is an isosurface already created for this channel?
* @param {Object} volume
* @param {number} channel
* @return true if there is currently a mesh isosurface for this channel
*/
hasIsosurface(volume: Volume, channel: number): boolean {
if (this.image) {
return this.image.hasIsosurface(channel);
} else {
return false;
}
}
/**
* If an isosurface exists, update its isovalue and regenerate the surface. Otherwise do nothing.
* @param {Object} volume
* @param {number} channel
* @param {number} isovalue
*/
updateIsosurface(volume: Volume, channel: number, isovalue: number): void {
if (!this.image || !this.image.hasIsosurface(channel)) {
return;
}
this.image.updateIsovalue(channel, isovalue);
this.redraw();
}
/**
* Set opacity for isosurface
* @param {Object} volume
* @param {number} channel
* @param {number} opacity Opacity
*/
updateOpacity(volume: Volume, channel: number, opacity: number): void {
if (!this.image) {
return;
}
this.image.updateOpacity(channel, opacity);
this.redraw();
}
/**
* If an isosurface exists for this channel, hide it now
* @param {Object} volume
* @param {number} channel
*/
clearIsosurface(volume: Volume, channel: number): void {
if (this.image) {
this.image.destroyIsosurface(channel);
}
this.redraw();
}
/**
* Save a channel's isosurface as a triangle mesh to either STL or GLTF2 format. File will be named automatically, using image name and channel name.
* @param {Object} volume
* @param {number} channelIndex
* @param {string} type Either 'GLTF' or 'STL'
*/
saveChannelIsosurface(volume: Volume, channelIndex: number, type: string): void {
if (this.image) {
this.image.saveChannelIsosurface(channelIndex, type);
}
}
// Add a new volume image to the viewer. The viewer currently only supports a single image at a time, and will return any prior existing image.
setImage(img: VolumeDrawable): VolumeDrawable | undefined {
const oldImage = this.unsetImage();
this.image = img;
this.scene.add(img.sceneRoot);
// new image picks up current settings
this.image.setResolution(this.canvas3d);
this.image.setIsOrtho(isOrthographicCamera(this.canvas3d.camera));
this.image.setBrightness(this.exposure);
this.canvas3d.setControlHandlers(
this.onStartControls.bind(this),
this.onChangeControls.bind(this),
this.onEndControls.bind(this)
);
this.canvas3d.animateFuncs.push(this.preRender.bind(this));
this.canvas3d.animateFuncs.push(img.onAnimate.bind(img));
// redraw if not already in draw loop
this.redraw();
return oldImage;
}
onStartControls(): void {
if (this.volumeRenderMode !== RENDERMODE_PATHTRACE) {
// TODO: VR display requires a running renderloop
this.canvas3d.startRenderLoop();
}
if (this.image) {
this.image.onStartControls();
}
}
onChangeControls(): void {
if (this.image) {
this.image.onChangeControls();
}
}
onEndControls(): void {
if (this.image) {
this.image.onEndControls();
}
// If we are pathtracing or autorotating, then keep rendering. Otherwise stop now.
if (this.volumeRenderMode !== RENDERMODE_PATHTRACE && !this.canvas3d.controls.autoRotate) {
// TODO: VR display requires a running renderloop
this.canvas3d.stopRenderLoop();
}
// force a redraw. This mainly fixes a bug with the way TrackballControls deals with wheel events.
this.redraw();
}
buildScene(): void {
this.scene = this.canvas3d.scene;
this.oldScale = new Vector3(0.5, 0.5, 0.5);
this.currentScale = new Vector3(0.5, 0.5, 0.5);
// background color
this.canvas3d.renderer.setClearColor(this.backgroundColor, 1.0);
this.lights = [new Light(SKY_LIGHT), new Light(AREA_LIGHT)];
this.lightContainer = new Object3D();
this.lightContainer.name = "lightContainer";
this.ambientLight = new AmbientLight(
lightSettings.ambientLightSettings.color,
lightSettings.ambientLightSettings.intensity
);
this.lightContainer.add(this.ambientLight);
// key light
this.spotLight = new SpotLight(lightSettings.spotlightSettings.color, lightSettings.spotlightSettings.intensity);
this.spotLight.position.set(
lightSettings.spotlightSettings.position.x,
lightSettings.spotlightSettings.position.y,
lightSettings.spotlightSettings.position.z
);
this.spotLight.target = new Object3D(); // this.substrate;
this.spotLight.angle = lightSettings.spotlightSettings.angle;
this.lightContainer.add(this.spotLight);
// reflect light
this.reflectedLight = new DirectionalLight(lightSettings.reflectedLightSettings.color);
this.reflectedLight.position.set(
lightSettings.reflectedLightSettings.position.x,
lightSettings.reflectedLightSettings.position.y,
lightSettings.reflectedLightSettings.position.z
);
this.reflectedLight.castShadow = lightSettings.reflectedLightSettings.castShadow;
this.reflectedLight.intensity = lightSettings.reflectedLightSettings.intensity;
this.lightContainer.add(this.reflectedLight);
// fill light
this.fillLight = new DirectionalLight(lightSettings.fillLightSettings.color);
this.fillLight.position.set(
lightSettings.fillLightSettings.position.x,
lightSettings.fillLightSettings.position.y,
lightSettings.fillLightSettings.position.z
);
this.fillLight.castShadow = lightSettings.fillLightSettings.castShadow;
this.fillLight.intensity = lightSettings.fillLightSettings.intensity;
this.lightContainer.add(this.fillLight);
this.scene.add(this.lightContainer);
}
/**
* Change the camera projection to look along an axis, or to view in a 3d perspective camera.
* @param {string} mode Mode can be "3D", or "XY" or "Z", or "YZ" or "X", or "XZ" or "Y". 3D is a perspective view, and all the others are orthographic projections
*/
setCameraMode(mode: string): void {
this.canvas3d.switchViewMode(mode);
if (this.image) {
this.image.setIsOrtho(mode !== "3D");
}
this.canvas3d.redraw();
}
/**
* Enable or disable 3d axis display at lower left.
* @param {boolean} autorotate
*/
setShowAxis(showAxis: boolean): void {
this.canvas3d.showAxis = showAxis;
this.canvas3d.redraw();
}
/**
* Enable or disable a turntable rotation mode. The display will continuously spin about the vertical screen axis.
* @param {boolean} autorotate
*/
setAutoRotate(autorotate: boolean): void {
this.canvas3d.setAutoRotate(autorotate);
if (autorotate) {
this.onStartControls();
} else {
this.onEndControls();
}
}
/**
* Invert axes of volume. -1 to invert, +1 NOT to invert.
* @param {Object} volume
* @param {number} flipX x axis sense
* @param {number} flipY y axis sense
* @param {number} flipZ z axis sense
*/
setFlipVolume(volume: Volume, flipX: number, flipY: number, flipZ: number): void {
if (this.image) {
this.image.setFlipAxes(flipX, flipY, flipZ);
this.redraw();
}
}
/**
* Notify the view that it has been resized. This will automatically be connected to the window when the View3d is created.
* @param {HTMLElement=} comp Ignored.
* @param {number=} w Width, or parent element's offsetWidth if not specified.
* @param {number=} h Height, or parent element's offsetHeight if not specified.
* @param {number=} ow Ignored.
* @param {number=} oh Ignored.
* @param {Object=} eOpts Ignored.
*/
resize(comp: HTMLElement | null, w: number, h: number, ow?: number, oh?: number, eOpts?: unknown): void {
w = w || this.parentEl.offsetWidth;
h = h || this.parentEl.offsetHeight;
this.canvas3d.resize(comp, w, h, ow, oh, eOpts);
if (this.image) {
this.image.setResolution(this.canvas3d);
}
this.redraw();
}
/**
* Set the volume scattering density
* @param {Object} volume
* @param {number} density 0..1 UI slider value
*/
updateDensity(volume: Volume, density: number): void {
if (this.image) {
this.image.setDensity(density);
}
this.redraw();
}
/**
* Set the shading method - applies to pathtraced render mode only
* @param {Object} volume
* @param {number} isbrdf 0: brdf, 1: isotropic phase function, 2: mixed
*/
updateShadingMethod(volume: Volume, isbrdf: boolean): void {
if (this.image) {
this.image.updateShadingMethod(isbrdf);
}
}
/**
* Set gamma levels: this affects the transparency and brightness of the single pass ray march volume render
* @param {Object} volume
* @param {number} gmin
* @param {number} glevel
* @param {number} gmax
*/
setGamma(volume: Volume, gmin: number, glevel: number, gmax: number): void {
if (this.image) {
this.image.setGamma(gmin, glevel, gmax);
}
this.redraw();
}
/**
* Set max projection on or off - applies to single pass raymarch render mode only
* @param {Object} volume
* @param {boolean} isMaxProject true for max project, false for regular volume ray march integration
*/
setMaxProjectMode(volume: Volume, isMaxProject: boolean): void {
if (this.image) {
this.image.setMaxProjectMode(isMaxProject);
}
this.redraw();
}
/**
* Notify the view that the set of active volume channels has been modified.
* @param {Object} volume
*/
updateActiveChannels(_volume: Volume): void {
if (this.image) {
this.image.fuse();
}
}
/**
* Notify the view that transfer function lookup table data has been modified.
* @param {Object} volume
*/
updateLuts(_volume: Volume): void {
if (this.image) {
this.image.updateLuts();
}
}
/**
* Notify the view that color and appearance settings have been modified.
* @param {Object} volume
*/
updateMaterial(_volume: Volume): void {
if (this.image) {
this.image.updateMaterial();
}
}
/**
* Increase or decrease the overall brightness of the rendered image
* @param {number} e 0..1
*/
updateExposure(e: number): void {
this.exposure = e;
if (this.image) {
this.image.setBrightness(e);
}
this.redraw();
}
/**
* Set camera focus properties.
* @param {number} fov Vertical field of view in degrees
* @param {number} focalDistance view-space units for center of focus
* @param {number} apertureSize view-space units for radius of camera aperture
*/
updateCamera(fov: number, focalDistance: number, apertureSize: number): void {
this.canvas3d.updateCameraFocus(fov, focalDistance, apertureSize);
if (this.image) {
this.image.onCameraChanged(fov, focalDistance, apertureSize);
}
this.redraw();
}
/**
* Set clipping range (between 0 and 1, relative to bounds) for the current volume.
* @param {Object} volume
* @param {number} xmin 0..1, should be less than xmax
* @param {number} xmax 0..1, should be greater than xmin
* @param {number} ymin 0..1, should be less than ymax
* @param {number} ymax 0..1, should be greater than ymin
* @param {number} zmin 0..1, should be less than zmax
* @param {number} zmax 0..1, should be greater than zmin
*/
updateClipRegion(
volume: Volume,
xmin: number,
xmax: number,
ymin: number,
ymax: number,
zmin: number,
zmax: number
): void {
if (this.image) {
this.image.updateClipRegion(xmin, xmax, ymin, ymax, zmin, zmax);
}
this.redraw();
}
/**
* Set clipping range (between 0 and 1) for a given axis.
* Calling this allows the rendering to compensate for changes in thickness in orthographic views that affect how bright the volume is.
* @param {Object} volume
* @param {number} axis 0, 1, or 2 for x, y, or z axis
* @param {number} minval 0..1, should be less than maxval
* @param {number} maxval 0..1, should be greater than minval
* @param {boolean} isOrthoAxis is this an orthographic projection or just a clipping of the range for perspective view
*/
setAxisClip(volume: Volume, axis: number, minval: number, maxval: number, isOrthoAxis: boolean): void {
if (this.image) {
this.image.setAxisClip(axis, minval, maxval, isOrthoAxis);
}
this.redraw();
}
/**
* Update lights
* @param {Array} state array of Lights
*/
updateLights(state: Light[]): void {
// TODO flesh this out
this.lights = state;
if (this.image) {
this.image.updateLights(state);
}
}
/**
* Set a sampling rate to trade performance for quality.
* @param {number} value (+epsilon..1) 1 is max quality, ~0.1 for lowest quality and highest speed
*/
updatePixelSamplingRate(value: number): void {
if (this.pixelSamplingRate === value) {
return;
}
this.pixelSamplingRate = value;
if (this.image) {
this.image.setPixelSamplingRate(value);
}
}
/**
* Set the opacity of the mask channel
* @param {Object} volume
* @param {number} value (0..1) 0 for full transparent, 1 for fully opaque
*/
updateMaskAlpha(volume: Volume, value: number): void {
if (this.image) {
this.image.setMaskAlpha(value);
}
this.redraw();
}
/**
* Show / hide volume channels
* @param {Object} volume
* @param {number} channel
* @param {boolean} enabled
*/
setVolumeChannelEnabled(volume: Volume, channel: number, enabled: boolean): void {
if (this.image) {
this.image.setVolumeChannelEnabled(channel, enabled);
}
}
/**
* Set the material for a channel
* @param {Object} volume
* @param {number} channelIndex
* @param {Array.<number>} colorrgb [r,g,b]
* @param {Array.<number>} specularrgb [r,g,b]
* @param {Array.<number>} emissivergb [r,g,b]
* @param {number} glossiness
*/
updateChannelMaterial(
volume: Volume,
channelIndex: number,
colorrgb: [number, number, number],
specularrgb: [number, number, number],
emissivergb: [number, number, number],
glossiness: number
): void {
if (this.image) {
this.image.updateChannelMaterial(channelIndex, colorrgb, specularrgb, emissivergb, glossiness);
}
}
/**
* Set the color for a channel
* @param {Object} volume
* @param {number} channelIndex
* @param {Array.<number>} colorrgb [r,g,b]
*/
updateChannelColor(volume: Volume, channelIndex: number, colorrgb: [number, number, number]): void {
if (this.image) {
this.image.updateChannelColor(channelIndex, colorrgb);
}
}
/**
* Switch between single pass ray-marched volume rendering and progressive path traced rendering.
* @param {number} mode 0 for single pass ray march, 1 for progressive path trace
*/
setVolumeRenderMode(mode: number): void {
if (mode === this.volumeRenderMode) {
return;
}
this.volumeRenderMode = mode;
if (this.image) {
if (mode === RENDERMODE_PATHTRACE && this.canvas3d.hasWebGL2) {
this.image.setVolumeRendering(true);
this.image.updateLights(this.lights);
// pathtrace is a continuous rendering mode
this.canvas3d.startRenderLoop();
} else {
this.image.setVolumeRendering(false);
this.canvas3d.redraw();
}
this.updatePixelSamplingRate(this.pixelSamplingRate);
this.image.setIsOrtho(isOrthographicCamera(this.canvas3d.camera));
this.image.setResolution(this.canvas3d);
this.setAutoRotate(this.canvas3d.controls.autoRotate);
this.image.setRenderUpdateListener(this.renderUpdateListener);
}
}
/**
*
* @param {Object} volume
* @param {Array.<number>} xyz
*/
setVolumeTranslation(volume: Volume, xyz: [number, number, number]): void {
if (this.image) {
this.image.setTranslation(new Vector3().fromArray(xyz));
}
this.redraw();
}
/**
*
* @param {Object} volume
* @param {Array.<number>} eulerXYZ
*/
setVolumeRotation(volume: Volume, eulerXYZ: [number, number, number]): void {
if (this.image) {
this.image.setRotation(new Euler().fromArray(eulerXYZ));
}
this.redraw();
}
/**
* Reset the camera to its default position
*/
resetCamera(): void {
this.canvas3d.resetCamera();
if (this.image) {
this.image.onResetCamera();
}
this.redraw();
}
hasWebGL2(): boolean {
return this.canvas3d.hasWebGL2;
}
} | the_stack |
import { IpcMainInvokeEvent } from 'electron'
import log, { LogMessage } from 'electron-log'
import { JSONSchema7 } from 'json-schema'
import { Config, dispatch, Plugin, Result } from 'stencila'
import { Channel, CHANNEL, Handler } from './channels'
import { UnprotectedStoreKeys } from './stores'
type EntityId = number | string
export type JSONValue =
| string
| number
| boolean
| null
| JSONValue[]
| { [key: string]: JSONValue }
export interface AppConfigStore {
USER_ID?: string
REPORT_ERRORS: boolean
FIRST_LAUNCH?: boolean | undefined
EDITOR_LINE_WRAPPING: boolean
EDITOR_LINE_NUMBERS: boolean
EDITOR_NEW_FILE_SYNTAX: string
}
export interface NormalizedPlugins {
entities: Record<string, Plugin>
ids: string[]
}
type AnyFunction = (...args: any) => any
type Resultify<F> = F extends Result<any> ? F : Result<F>
/**
* Type wrapper for defining the return types of calling a `invoke`/`dispatch` method.
*/
type InvokeResult<T> = Promise<Resultify<T>>
type InvokeType<C extends Channel, F extends AnyFunction> = {
channel: C
args: Parameters<F>
result: InvokeResult<ReturnType<F>>
}
// -----------------------------------------------------------------------------
// Global
export type OpenLink = InvokeType<
typeof CHANNEL.OPEN_LINK_IN_DEFAULT_BROWSER,
(url: string) => void
>
export type GetAppVersion = InvokeType<
typeof CHANNEL.GET_APP_VERSION,
() => string
>
// Logs
export type LogsWindowOpen = InvokeType<
typeof CHANNEL.LOGS_WINDOW_OPEN,
() => void
>
export type LogsGet = InvokeType<typeof CHANNEL.LOGS_GET, () => LogMessage[]>
// Config
export type ConfigWindowOpen = InvokeType<
typeof CHANNEL.CONFIG_WINDOW_OPEN,
() => void
>
export type ReadConfig = InvokeType<
typeof CHANNEL.CONFIG_READ,
() => {
config: Config
schemas: JSONSchema7[]
}
>
export type ReadAppConfig = InvokeType<
typeof CHANNEL.CONFIG_APP_READ,
() => AppConfigStore
>
export type GetAppConfig = InvokeType<
typeof CHANNEL.CONFIG_APP_GET,
<K extends UnprotectedStoreKeys>(key: K) => AppConfigStore[K]
>
export type SetAppConfig = InvokeType<
typeof CHANNEL.CONFIG_APP_SET,
<K extends UnprotectedStoreKeys>(payload: {
key: K
value: AppConfigStore[K]
}) => void
>
// Plugins
export type PluginsList = InvokeType<
typeof CHANNEL.PLUGINS_LIST,
() => NormalizedPlugins
>
export type PluginsInstall = InvokeType<
typeof CHANNEL.PLUGINS_INSTALL,
typeof dispatch.plugins.install
>
export type PluginsUninstall = InvokeType<
typeof CHANNEL.PLUGINS_UNINSTALL,
typeof dispatch.plugins.uninstall
>
export type PluginsUpgrade = InvokeType<
typeof CHANNEL.PLUGIN_UPGRADE,
typeof dispatch.plugins.upgrade
>
export type PluginsRefresh = InvokeType<
typeof CHANNEL.PLUGINS_REFRESH,
typeof dispatch.plugins.refresh
>
// Launcher
export type LauncherWindowOpen = InvokeType<
typeof CHANNEL.LAUNCHER_WINDOW_OPEN,
() => void
>
export type LauncherWindowClose = InvokeType<
typeof CHANNEL.LAUNCHER_WINDOW_CLOSE,
() => void
>
// Onboarding
export type OnboardingWindowOpen = InvokeType<
typeof CHANNEL.ONBOARDING_WINDOW_OPEN,
() => void
>
export type OnboardingWindowClose = InvokeType<
typeof CHANNEL.ONBOARDING_WINDOW_CLOSE,
() => void
>
// Projects
export type ProjectsWindowOpen = InvokeType<
typeof CHANNEL.PROJECTS_WINDOW_OPEN,
(directoryPath: string) => void
>
export type ProjectsOpenUsingFilePicker = InvokeType<
typeof CHANNEL.PROJECTS_OPEN_FROM_FILE_PICKER,
() => {
canceled: boolean
}
>
export type ProjectsNew = InvokeType<typeof CHANNEL.PROJECTS_NEW, () => void>
export type ProjectsOpen = InvokeType<
typeof CHANNEL.PROJECTS_OPEN,
typeof dispatch.projects.open
>
export type ProjectsWrite = InvokeType<
typeof CHANNEL.PROJECTS_WRITE,
typeof dispatch.projects.write
>
export type ProjectsGraph = InvokeType<
typeof CHANNEL.PROJECTS_GRAPH,
typeof dispatch.projects.graph
>
export type ProjectsUnsubscribe = InvokeType<
typeof CHANNEL.PROJECTS_UNSUBSCRIBE,
typeof dispatch.projects.unsubscribe
>
// Documents
export type DocumentsOpen = InvokeType<
typeof CHANNEL.DOCUMENTS_OPEN,
typeof dispatch.documents.open
>
export type DocumentsAlter = InvokeType<
typeof CHANNEL.DOCUMENTS_ALTER,
typeof dispatch.documents.alter
>
export type DocumentsCreate = InvokeType<
typeof CHANNEL.DOCUMENTS_CREATE,
typeof dispatch.documents.create
>
export type DocumentsCreateFilePath = InvokeType<
typeof CHANNEL.DOCUMENTS_CREATE_FILE_PATH,
() =>
| {
filePath: string
canceled: false
}
| { canceled: true }
>
export type DocumentsClose = InvokeType<
typeof CHANNEL.DOCUMENTS_CLOSE,
typeof dispatch.documents.close
>
export type DocumentsCloseActive = InvokeType<
typeof CHANNEL.DOCUMENTS_CLOSE_ACTIVE,
(path: string) => void
>
export type DocumentsPreview = InvokeType<
typeof CHANNEL.DOCUMENTS_PREVIEW,
typeof dispatch.documents.dump
>
export type DocumentsDump = InvokeType<
typeof CHANNEL.DOCUMENTS_DUMP,
typeof dispatch.documents.dump
>
export type DocumentsLoad = InvokeType<
typeof CHANNEL.DOCUMENTS_LOAD,
typeof dispatch.documents.load
>
export type DocumentsGet = InvokeType<
typeof CHANNEL.DOCUMENTS_GET,
typeof dispatch.documents.get
>
export type DocumentsWrite = InvokeType<
typeof CHANNEL.DOCUMENTS_WRITE,
typeof dispatch.documents.write
>
export type DocumentsWriteAs = InvokeType<
typeof CHANNEL.DOCUMENTS_WRITE_AS,
| typeof dispatch.documents.writeAs
| ((...args: Parameters<typeof dispatch.documents.writeAs>) => null)
>
export type DocumentsUnsubscribe = InvokeType<
typeof CHANNEL.DOCUMENTS_UNSUBSCRIBE,
typeof dispatch.documents.unsubscribe
>
type InvokeTypes =
| OpenLink
| GetAppVersion
| LogsWindowOpen
| LogsGet
| ConfigWindowOpen
| ReadConfig
| ReadAppConfig
| GetAppConfig
| SetAppConfig
| PluginsList
| PluginsInstall
| PluginsUninstall
| PluginsUpgrade
| PluginsRefresh
| LauncherWindowOpen
| LauncherWindowClose
| OnboardingWindowOpen
| OnboardingWindowClose
| ProjectsWindowOpen
| ProjectsOpenUsingFilePicker
| ProjectsNew
| ProjectsOpen
| ProjectsWrite
| ProjectsGraph
| ProjectsUnsubscribe
| DocumentsOpen
| DocumentsAlter
| DocumentsCreate
| DocumentsCreateFilePath
| DocumentsClose
| DocumentsCloseActive
| DocumentsPreview
| DocumentsDump
| DocumentsLoad
| DocumentsGet
| DocumentsWrite
| DocumentsWriteAs
| DocumentsUnsubscribe
// -----------------------------------------------------------------------------
type InvokeListener<F extends InvokeTypes> = (
ipcEvent: IpcMainInvokeEvent,
...args: F['args']
) => F['result']
export type InvokeHandler<F extends InvokeTypes> = (
channel: F['channel'],
listener: InvokeListener<F>
) => void
// -----------------------------------------------------------------------------
interface Invoke {
// Global
invoke(
channel: OpenLink['channel'],
...args: OpenLink['args']
): OpenLink['result']
invoke(
channel: GetAppVersion['channel'],
...args: GetAppVersion['args']
): GetAppVersion['result']
// Logs
invoke(
channel: LogsWindowOpen['channel'],
...args: LogsWindowOpen['args']
): LogsWindowOpen['result']
invoke(
channel: LogsGet['channel'],
...args: LogsGet['args']
): LogsGet['result']
// Config
invoke(
channel: ConfigWindowOpen['channel'],
...args: ConfigWindowOpen['args']
): ConfigWindowOpen['result']
invoke(
channel: ReadConfig['channel'],
...args: ReadConfig['args']
): ReadConfig['result']
invoke(
channel: ReadAppConfig['channel'],
...args: ReadAppConfig['args']
): ReadAppConfig['result']
invoke(
channel: GetAppConfig['channel'],
...args: GetAppConfig['args']
): GetAppConfig['result']
invoke(
channel: SetAppConfig['channel'],
...args: SetAppConfig['args']
): SetAppConfig['result']
// Plugins
invoke(
channel: PluginsList['channel'],
...args: PluginsList['args']
): PluginsList['result']
invoke(
channel: PluginsInstall['channel'],
...args: PluginsInstall['args']
): PluginsInstall['result']
invoke(
channel: PluginsUninstall['channel'],
...args: PluginsUninstall['args']
): PluginsUninstall['result']
invoke(
channel: PluginsUpgrade['channel'],
...args: PluginsUpgrade['args']
): PluginsUpgrade['result']
invoke(
channel: PluginsRefresh['channel'],
...args: PluginsRefresh['args']
): PluginsRefresh['result']
invoke(channel: PluginsRefresh['channel']): PluginsRefresh['result']
// Launcher
invoke(
channel: LauncherWindowOpen['channel'],
...args: LauncherWindowOpen['args']
): LauncherWindowOpen['result']
invoke(
channel: LauncherWindowClose['channel'],
...args: LauncherWindowClose['args']
): LauncherWindowClose['result']
// Onboarding
invoke(
channel: OnboardingWindowOpen['channel'],
...args: OnboardingWindowOpen['args']
): OnboardingWindowOpen['result']
invoke(
channel: OnboardingWindowClose['channel'],
...args: OnboardingWindowClose['args']
): OnboardingWindowClose['result']
// Projects
invoke(
channel: ProjectsWindowOpen['channel'],
...args: ProjectsWindowOpen['args']
): ProjectsWindowOpen['result']
invoke(
channel: ProjectsOpenUsingFilePicker['channel'],
...args: ProjectsOpenUsingFilePicker['args']
): ProjectsOpenUsingFilePicker['result']
invoke(
channel: ProjectsNew['channel'],
...args: ProjectsNew['args']
): ProjectsNew['result']
invoke(
channel: ProjectsOpen['channel'],
...args: ProjectsOpen['args']
): ProjectsOpen['result']
invoke(
channel: ProjectsWrite['channel'],
...args: ProjectsWrite['args']
): ProjectsWrite['result']
invoke(
channel: ProjectsGraph['channel'],
...args: ProjectsGraph['args']
): ProjectsGraph['result']
invoke(
channel: ProjectsUnsubscribe['channel'],
...args: ProjectsUnsubscribe['args']
): ProjectsUnsubscribe['result']
// Documents
invoke(
channel: DocumentsOpen['channel'],
...args: DocumentsOpen['args']
): DocumentsOpen['result']
invoke(
channel: DocumentsAlter['channel'],
...args: DocumentsAlter['args']
): DocumentsAlter['result']
invoke(
channel: DocumentsCreate['channel'],
...args: DocumentsCreate['args']
): DocumentsCreate['result']
invoke(
channel: DocumentsCreateFilePath['channel'],
...args: DocumentsCreateFilePath['args']
): DocumentsCreateFilePath['result']
invoke(
channel: DocumentsClose['channel'],
...args: DocumentsClose['args']
): DocumentsClose['result']
invoke(
channel: DocumentsCloseActive['channel'],
...args: DocumentsCloseActive['args']
): DocumentsCloseActive['result']
invoke(
channel: DocumentsPreview['channel'],
...args: DocumentsPreview['args']
): DocumentsPreview['result']
invoke(
channel: DocumentsDump['channel'],
...args: DocumentsDump['args']
): DocumentsDump['result']
invoke(
channel: DocumentsLoad['channel'],
...args: DocumentsLoad['args']
): DocumentsLoad['result']
invoke(
channel: DocumentsGet['channel'],
...args: DocumentsGet['args']
): DocumentsGet['result']
invoke(
channel: DocumentsWrite['channel'],
...args: DocumentsWrite['args']
): DocumentsWrite['result']
invoke(
channel: DocumentsWriteAs['channel'],
...args: DocumentsWriteAs['args']
): DocumentsWriteAs['result']
invoke(
channel: DocumentsUnsubscribe['channel'],
...args: DocumentsUnsubscribe['args']
): DocumentsUnsubscribe['result']
}
export interface IpcRendererAPI extends Invoke {
send(channel: Channel, ...args: unknown[]): void
receive: (channel: Channel, func: Handler) => void
remove: (channel: Channel, func: Handler) => void
removeAll: (channel: Channel) => void
log: typeof log
}
declare global {
interface Window {
api: IpcRendererAPI
}
} | the_stack |
import {
action,
IReactionDisposer,
observable,
reaction,
runInAction
} from "mobx";
import { observer } from "mobx-react";
import moment from "moment";
import React from "react";
import { withTranslation, WithTranslation } from "react-i18next";
import styled from "styled-components";
import isDefined from "../../../Core/isDefined";
import {
ObjectifiedDates,
ObjectifiedYears
} from "../../../ModelMixins/DiscretelyTimeVaryingMixin";
import Button, { RawButton } from "../../../Styled/Button";
import { scrollBars } from "../../../Styled/mixins";
import Spacing from "../../../Styled/Spacing";
import Icon from "../../../Styled/Icon";
import { formatDateTime } from "./DateFormats";
const dateFormat = require("dateformat");
const DatePicker = require("react-datepicker").default;
function daysInMonth(month: number, year: number) {
const n = new Date(year, month, 0).getDate();
return (Array.apply as any)(null, { length: n }).map(
Number.call,
Number
) as number[];
}
const monthNames = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
const GridItem = styled.span<{ active: boolean }>`
background: ${p => p.theme.overlay};
${p =>
p.active &&
`
& {
background: ${p.theme.colorPrimary};
}
opacity: 0.9;
`}
`;
const GridRowInner = styled.span<{ marginRight: string }>`
display: table-row;
padding: 3px;
border-radius: 3px;
span {
display: inline-block;
height: 10px;
width: 2px;
margin-top: 1px;
margin-right: ${p => p.marginRight}px;
}
`;
const Grid = styled.div`
display: block;
width: 100%;
height: 100%;
margin: 0 auto;
color: ${(p: any) => p.theme.textLight};
padding: 0px 5px;
border-radius: 3px;
margin-top: -20px;
`;
const GridHeading = styled.div`
text-align: center;
color: ${(p: any) => p.theme.textLight};
font-size: 12px;
margin-bottom: 10px;
`;
export const GridRow = styled.div`
:hover {
background: ${p => p.theme.overlay};
cursor: pointer;
}
`;
const GridLabel = styled.span`
float: left;
display: inline-block;
width: 35px;
font-size: 10px;
padding-left: 3px;
`;
const GridBody = styled.div`
height: calc(100% - 30px);
overflow: auto;
${scrollBars()}
`;
const BackButton = styled(RawButton)`
display: inline-block;
z-index: 99;
position: relative;
svg {
height: 15px;
width: 20px;
fill: ${(p: any) => p.theme.textLight};
display: inline-block;
vertical-align: bottom;
}
&[disabled],
&:disabled {
opacity: 0.1;
}
`;
export const DateButton = styled(Button).attrs({
primary: true,
textProps: { medium: true }
})`
width: calc(100% - 20px);
margin: 3px 5px;
border-radius: 4px;
`;
interface PropsType extends WithTranslation {
dates: ObjectifiedDates;
currentDate?: Date; // JS Date object - must be an element of props.dates, or null/undefined.
onChange: (date: Date) => void;
openDirection?: string;
isOpen: boolean;
onOpen: () => void;
onClose: () => void;
dateFormat?: string;
}
type Granularity = "century" | "year" | "month" | "day" | "time" | "hour";
@observer
class DateTimePicker extends React.Component<PropsType> {
public static defaultProps = {
openDirection: "down"
};
@observable
currentDateIndice: {
century?: number;
year?: number;
month?: number;
day?: number;
time?: Date;
hour?: number;
granularity: Granularity;
} = { granularity: "century" };
private currentDateAutorunDisposer: IReactionDisposer | undefined;
componentWillMount() {
const datesObject = this.props.dates;
let defaultCentury: number | undefined;
let defaultYear: number | undefined;
let defaultMonth: number | undefined;
let defaultDay: number | undefined;
let defaultGranularity: Granularity = "century";
if (datesObject.indice.length === 1) {
// only one century
const soleCentury = datesObject.indice[0];
const dataFromThisCentury = datesObject[soleCentury];
defaultCentury = soleCentury;
if (dataFromThisCentury.indice.length === 1) {
// only one year, check if this year has only one month
const soleYear = dataFromThisCentury.indice[0];
const dataFromThisYear = dataFromThisCentury[soleYear];
defaultYear = soleYear;
defaultGranularity = "year";
if (dataFromThisYear.indice.length === 1) {
// only one month data from this one year, need to check day then
const soleMonth = dataFromThisYear.indice[0];
const dataFromThisMonth = dataFromThisYear[soleMonth];
defaultMonth = soleMonth;
defaultGranularity = "month";
if (dataFromThisMonth.indice.length === 1) {
// only one day has data
defaultDay = dataFromThisMonth.indice[0];
}
}
}
}
this.currentDateIndice = {
century: defaultCentury,
year: defaultYear,
month: defaultMonth,
day: defaultDay,
granularity: defaultGranularity
};
window.addEventListener("click", this.closePickerEventHandler);
// Update currentDateIndice when currentDate changes
this.currentDateAutorunDisposer = reaction(
() => this.props.currentDate,
() => {
// The current date must be one of the available item.dates, or null/undefined.
const currentDate = this.props.currentDate;
if (isDefined(currentDate)) {
Object.assign(this.currentDateIndice, {
day: isDefined(this.currentDateIndice.day)
? currentDate.getDate()
: undefined,
month: isDefined(this.currentDateIndice.month)
? currentDate.getMonth()
: undefined,
year: isDefined(this.currentDateIndice.year)
? currentDate.getFullYear()
: undefined,
century: isDefined(this.currentDateIndice.century)
? Math.floor(currentDate.getFullYear() / 100)
: undefined,
time: currentDate
});
}
},
{ fireImmediately: true }
);
}
componentWillUnmount() {
this.currentDateAutorunDisposer && this.currentDateAutorunDisposer();
window.removeEventListener("click", this.closePickerEventHandler);
}
@action.bound
closePickerEventHandler() {
this.closePicker();
}
closePicker(newTime?: Date) {
if (newTime !== undefined) {
runInAction(() => (this.currentDateIndice.time = newTime));
}
if (this.props.onClose) {
this.props.onClose();
}
}
renderCenturyGrid(datesObject: ObjectifiedDates) {
const centuries = datesObject.indice;
if (datesObject.dates && datesObject.dates.length >= 12) {
return (
<Grid>
<GridHeading>Select a century</GridHeading>
{centuries.map(c => (
<DateButton
key={c}
css={`
display: inline-block;
width: 40%;
`}
onClick={() =>
runInAction(() => (this.currentDateIndice.century = c))
}
>
{c}00
</DateButton>
))}
</Grid>
);
} else {
return this.renderList(datesObject.dates);
}
}
renderYearGrid(datesObject: ObjectifiedYears) {
if (datesObject.dates && datesObject.dates.length > 12) {
const years = datesObject.indice;
const monthOfYear = (Array.apply as any)(null, { length: 12 }).map(
Number.call,
Number
) as number[];
return (
<Grid>
<GridHeading>Select a year</GridHeading>
<GridBody>
{years.map(y => (
<GridRow
key={y}
onClick={() =>
runInAction(() => {
this.currentDateIndice.year = y;
this.currentDateIndice.month = undefined;
this.currentDateIndice.day = undefined;
this.currentDateIndice.time = undefined;
})
}
>
<GridLabel>{y}</GridLabel>
<GridRowInner marginRight="11">
{monthOfYear.map(m => (
<GridItem
// className={datesObject[y][m] ? Styles.activeGrid : ""}
active={isDefined(datesObject[y][m])}
key={m}
/>
))}
</GridRowInner>
</GridRow>
))}
</GridBody>
</Grid>
);
} else {
return this.renderList(datesObject.dates);
}
}
renderMonthGrid(datesObject: ObjectifiedYears) {
const year = this.currentDateIndice.year;
if (!isDefined(year)) {
return null;
}
if (datesObject[year].dates && datesObject[year].dates.length > 12) {
return (
<Grid>
<GridHeading>
<BackButton
title={this.props.t("dateTime.back")}
onClick={() => {
runInAction(() => {
this.currentDateIndice.year = undefined;
this.currentDateIndice.month = undefined;
this.currentDateIndice.day = undefined;
this.currentDateIndice.time = undefined;
});
}}
>
{year}
</BackButton>
</GridHeading>
<GridBody>
{monthNames.map((m, i) => (
<GridRow
css={`
${!isDefined(datesObject[year][i])
? `:hover {
background: transparent;
cursor: default;
}`
: ""}
`}
key={m}
onClick={() =>
isDefined(datesObject[year][i]) &&
runInAction(() => {
this.currentDateIndice.month = i;
this.currentDateIndice.day = undefined;
this.currentDateIndice.time = undefined;
})
}
>
<GridLabel>{m}</GridLabel>
<GridRowInner marginRight="3">
{daysInMonth(i + 1, year).map(d => (
<GridItem
active={
isDefined(datesObject[year][i]) &&
isDefined(datesObject[year][i][d + 1])
}
key={d}
/>
))}
</GridRowInner>
</GridRow>
))}
</GridBody>
</Grid>
);
} else {
return this.renderList(datesObject[year].dates);
}
}
renderDayView(datesObject: ObjectifiedYears) {
if (
!isDefined(this.currentDateIndice.year) ||
!isDefined(this.currentDateIndice.month)
) {
return null;
}
const dayObject =
datesObject[this.currentDateIndice.year][this.currentDateIndice.month];
if (dayObject.dates.length > 31) {
// Create one date object per day, using an arbitrary time. This does it via Object.keys and moment().
const days =
datesObject[this.currentDateIndice.year][this.currentDateIndice.month]
.indice;
const daysToDisplay = days.map(d =>
moment()
.date(d)
.month(this.currentDateIndice.month!)
.year(this.currentDateIndice.year!)
);
const selected = isDefined(this.currentDateIndice.day)
? moment()
.date(this.currentDateIndice.day!)
.month(this.currentDateIndice.month)
.year(this.currentDateIndice.year)
: null;
// Aside: You might think this implementation is clearer - use the first date available on each day.
// However it fails because react-datepicker actually requires a moment() object for selected, not a Date object.
// const monthObject = this.props.datesObject[this.currentDateIndice.year][this.currentDateIndice.month];
// const daysToDisplay = Object.keys(monthObject).map(dayNumber => monthObject[dayNumber][0]);
// const selected = isDefined(this.currentDateIndice.day) ? this.props.datesObject[this.currentDateIndice.year][this.currentDateIndice.month][this.currentDateIndice.day][0] : null;
return (
<div
css={`
text-align: center;
margin-top: -10px;
`}
>
<div>
<BackButton
title={this.props.t("dateTime.back")}
onClick={() =>
runInAction(() => {
this.currentDateIndice.year = undefined;
this.currentDateIndice.month = undefined;
this.currentDateIndice.day = undefined;
this.currentDateIndice.time = undefined;
})
}
>
{this.currentDateIndice.year}
</BackButton>
<BackButton
title={this.props.t("dateTime.back")}
onClick={() =>
runInAction(() => {
this.currentDateIndice.month = undefined;
this.currentDateIndice.day = undefined;
this.currentDateIndice.time = undefined;
})
}
>
{monthNames[this.currentDateIndice.month]}
</BackButton>
<Spacing bottom={1} />
</div>
<DatePicker
inline
onChange={(momentDateObj: moment.Moment) =>
runInAction(() => {
this.currentDateIndice.day = momentDateObj.date();
})
}
includeDates={daysToDisplay}
selected={selected}
/>
</div>
);
} else {
return this.renderList(
datesObject[this.currentDateIndice.year][this.currentDateIndice.month]
.dates
);
}
}
renderList(items: Date[]) {
if (isDefined(items)) {
return (
<Grid>
<GridHeading>Select a time</GridHeading>
<GridBody>
{items.map(item => (
<DateButton
key={formatDateTime(item)}
onClick={() => {
this.closePicker(item);
this.props.onChange(item);
}}
>
{isDefined(this.props.dateFormat)
? dateFormat(item, this.props.dateFormat)
: formatDateTime(item)}
</DateButton>
))}
</GridBody>
</Grid>
);
}
}
renderHourView(datesObject: ObjectifiedYears) {
if (
!isDefined(this.currentDateIndice.year) ||
!isDefined(this.currentDateIndice.month) ||
!isDefined(this.currentDateIndice.day)
) {
return null;
}
const timeOptions = datesObject[this.currentDateIndice.year][
this.currentDateIndice.month
][this.currentDateIndice.day].dates.map(m => ({
value: m,
label: formatDateTime(m)
}));
if (timeOptions.length > 24) {
return (
<Grid>
<GridHeading>
{`Select an hour on ${this.currentDateIndice.day} ${
monthNames[this.currentDateIndice.month + 1]
} ${this.currentDateIndice.year}`}{" "}
</GridHeading>
<GridBody>
{datesObject[this.currentDateIndice.year][
this.currentDateIndice.month
][this.currentDateIndice.day].indice.map(item => (
<DateButton
key={item}
onClick={() =>
runInAction(() => {
this.currentDateIndice.hour = item;
})
}
>
<span>
{item} : 00 - {item + 1} : 00
</span>{" "}
<span>
(
{
datesObject[this.currentDateIndice.year!][
this.currentDateIndice.month!
][this.currentDateIndice.day!][item].length
}{" "}
options)
</span>
</DateButton>
))}
</GridBody>
</Grid>
);
} else {
return this.renderList(
datesObject[this.currentDateIndice.year][this.currentDateIndice.month][
this.currentDateIndice.day
].dates
);
}
}
renderMinutesView(datesObject: ObjectifiedYears) {
if (
!isDefined(this.currentDateIndice.year) ||
!isDefined(this.currentDateIndice.month) ||
!isDefined(this.currentDateIndice.day) ||
!isDefined(this.currentDateIndice.hour)
) {
return null;
}
const options =
datesObject[this.currentDateIndice.year][this.currentDateIndice.month][
this.currentDateIndice.day
][this.currentDateIndice.hour];
return this.renderList(options);
}
@action
goBack() {
if (isDefined(this.currentDateIndice.time)) {
if (!isDefined(this.currentDateIndice.month)) {
this.currentDateIndice.year = undefined;
this.currentDateIndice.day = undefined;
}
if (!isDefined(this.currentDateIndice.hour)) {
this.currentDateIndice.day = undefined;
}
if (!isDefined(this.currentDateIndice.day)) {
this.currentDateIndice.month = undefined;
}
this.currentDateIndice.hour = undefined;
this.currentDateIndice.time = undefined;
} else if (isDefined(this.currentDateIndice.hour)) {
this.currentDateIndice.hour = undefined;
} else if (isDefined(this.currentDateIndice.day)) {
this.currentDateIndice.day = undefined;
} else if (isDefined(this.currentDateIndice.month)) {
this.currentDateIndice.month = undefined;
} else if (isDefined(this.currentDateIndice.year)) {
this.currentDateIndice.year = undefined;
} else if (isDefined(this.currentDateIndice.century)) {
this.currentDateIndice.century = undefined;
}
}
toggleDatePicker() {
if (!this.props.isOpen) {
this.props.onOpen();
} else {
this.props.onClose();
}
}
render() {
if (this.props.dates) {
const datesObject = this.props.dates;
return (
<div
css={`
color: ${(p: any) => p.theme.textLight};
display: table-cell;
width: 30px;
height: 30px;
`}
onClick={event => {
event.stopPropagation();
}}
>
{this.props.isOpen && (
<div
css={`
background: ${(p: any) => p.theme.dark};
width: 260px;
height: 300px;
border: 1px solid ${(p: any) => p.theme.grey};
border-radius: 5px;
padding: 5px;
position: relative;
top: -170px;
left: 0;
z-index: 100;
${this.props.openDirection === "down"
? `
top: 40px;
left: -190px;
`
: ""}
`}
className={"scrollbars"}
>
<BackButton
title={this.props.t("dateTime.back")}
css={`
padding-bottom: 5px;
padding-right: 5px;
`}
disabled={
!isDefined(
this.currentDateIndice[this.currentDateIndice.granularity]
)
}
type="button"
onClick={() => this.goBack()}
>
<Icon glyph={Icon.GLYPHS.left} />
</BackButton>
{!isDefined(this.currentDateIndice.century) &&
this.renderCenturyGrid(datesObject)}
{isDefined(this.currentDateIndice.century) &&
!isDefined(this.currentDateIndice.year) &&
this.renderYearGrid(
datesObject[this.currentDateIndice.century!]
)}
{isDefined(this.currentDateIndice.year) &&
!isDefined(this.currentDateIndice.month) &&
this.renderMonthGrid(
datesObject[this.currentDateIndice.century!]
)}
{isDefined(this.currentDateIndice.year) &&
isDefined(this.currentDateIndice.month) &&
!isDefined(this.currentDateIndice.day) &&
this.renderDayView(
datesObject[this.currentDateIndice.century!]
)}
{isDefined(this.currentDateIndice.year) &&
isDefined(this.currentDateIndice.month) &&
isDefined(this.currentDateIndice.day) &&
!isDefined(this.currentDateIndice.hour) &&
this.renderHourView(
datesObject[this.currentDateIndice.century!]
)}
{isDefined(this.currentDateIndice.year) &&
isDefined(this.currentDateIndice.month) &&
isDefined(this.currentDateIndice.day) &&
isDefined(this.currentDateIndice.hour) &&
this.renderMinutesView(
datesObject[this.currentDateIndice.century!]
)}
</div>
)}
</div>
);
} else {
return null;
}
}
}
export default withTranslation()(DateTimePicker); | the_stack |
import React from 'react';
import { unmountComponentAtNode, render } from 'reactant-web';
// eslint-disable-next-line import/no-extraneous-dependencies
import { act } from 'react-dom/test-utils';
import { LastAction } from 'reactant-last-action';
import {
injectable,
state,
action,
ViewModule,
useConnector,
subscribe,
createSharedApp,
spawn,
PortDetector,
optional,
mockPairTransports,
fork,
} from '..';
let serverContainer: Element;
let clientContainer: Element;
beforeEach(() => {
serverContainer = document.createElement('div');
document.body.appendChild(serverContainer);
clientContainer = document.createElement('div');
document.body.appendChild(clientContainer);
});
afterEach(() => {
unmountComponentAtNode(serverContainer);
serverContainer.remove();
unmountComponentAtNode(clientContainer);
clientContainer.remove();
});
describe('base', () => {
@injectable({
name: 'todoList',
})
class TodoList {
@state
list: number[] = [];
@action
add(num: number) {
this.list.push(num);
}
}
let onClientFn: jest.Mock<any, any>;
let subscribeOnClientFn: jest.Mock<any, any>;
let onServerFn: jest.Mock<any, any>;
let subscribeOnServerFn: jest.Mock<any, any>;
@injectable({
name: 'counter',
})
class Counter {
constructor(
private portDetector: PortDetector,
@optional('todoList') private todoList: TodoList
) {
this.portDetector.onClient(() => {
onClientFn?.();
return subscribe(this, () => {
subscribeOnClientFn?.();
});
});
this.portDetector.onServer(() => {
onServerFn?.();
return subscribe(this, () => {
subscribeOnServerFn?.();
});
});
}
num = 1;
setNum(num: number) {
this.num = num;
return this.num;
}
@state
count = 0;
@state
obj: Record<string, number> = {};
@action
increase() {
this.count += 1;
this.obj.number = this.count;
this.todoList?.add(this.count);
}
@action
decrease() {
this.count -= 1;
}
}
@injectable({
name: 'appView',
})
class AppView extends ViewModule {
constructor(public counter: Counter) {
super();
}
component() {
const count = useConnector(() => this.counter.count);
return (
<>
<button
id="decrease"
type="button"
onClick={() => spawn(this.counter, 'decrease', [])}
>
-
</button>
<div id="count">{count}</div>
<button
id="increase"
type="button"
onClick={() => spawn(this.counter, 'increase', [])}
>
+
</button>
</>
);
}
}
test.each([
{ type: 'Base' },
{ type: 'BrowserExtension' },
{ type: 'SharedWorker' },
{ type: 'ServiceWorker' },
])('base server/client port mode in $type', async ({ type }: any) => {
onClientFn = jest.fn();
subscribeOnClientFn = jest.fn();
onServerFn = jest.fn();
subscribeOnServerFn = jest.fn();
const transports = mockPairTransports();
const serverApp = await createSharedApp({
modules: [],
main: AppView,
render,
share: {
name: 'counter',
type,
port: 'server',
transports: {
server: transports[0],
},
},
});
expect(onClientFn.mock.calls.length).toBe(0);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
act(() => {
serverApp.bootstrap(serverContainer);
});
expect(onClientFn.mock.calls.length).toBe(0);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
expect(serverContainer.querySelector('#count')?.textContent).toBe('0');
const clientApp = await createSharedApp({
modules: [],
main: AppView,
render,
share: {
name: 'counter',
type,
port: 'client',
transports: {
client: transports[1],
},
},
});
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
act(() => {
clientApp.bootstrap(clientContainer);
});
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
expect(clientContainer.querySelector('#count')?.textContent).toBe('0');
act(() => {
serverContainer
.querySelector('#increase')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
// waiting for sync state
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(1);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(1);
expect(serverContainer.querySelector('#count')?.textContent).toBe('1');
expect(clientContainer.querySelector('#count')?.textContent).toBe('1');
act(() => {
clientContainer
.querySelector('#increase')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
// waiting for sync state
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(2);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(2);
expect(serverContainer.querySelector('#count')?.textContent).toBe('2');
expect(clientContainer.querySelector('#count')?.textContent).toBe('2');
expect(clientApp.instance.counter.num).toBe(1);
expect(serverApp.instance.counter.num).toBe(1);
const result0 = await fork(serverApp.instance.counter, 'setNum', [2]);
expect(clientApp.instance.counter.num).toBe(2);
expect(serverApp.instance.counter.num).toBe(1);
expect(result0).toBe(2);
const result1 = await fork(serverApp.instance.counter, 'setNum', [3], {
respond: false,
});
expect(clientApp.instance.counter.num).toBe(3);
expect(serverApp.instance.counter.num).toBe(1);
expect(result1).toBeUndefined();
const result2 = await spawn(clientApp.instance.counter, 'setNum', [4]);
expect(clientApp.instance.counter.num).toBe(3);
expect(serverApp.instance.counter.num).toBe(4);
expect(result2).toBe(4);
const result3 = await spawn(clientApp.instance.counter, 'setNum', [5], {
respond: false,
});
expect(clientApp.instance.counter.num).toBe(3);
expect(serverApp.instance.counter.num).toBe(5);
expect(result3).toBeUndefined();
});
test('base server/client port mode in SharedTab', async () => {
onClientFn = jest.fn();
subscribeOnClientFn = jest.fn();
onServerFn = jest.fn();
subscribeOnServerFn = jest.fn();
const transports = mockPairTransports();
const transports1 = mockPairTransports();
const sharedApp0 = await createSharedApp({
modules: [],
main: AppView,
render,
share: {
name: 'counter',
type: 'SharedTab',
transports: {
server: transports[0],
client: transports1[0],
},
},
});
expect(onClientFn.mock.calls.length).toBe(0);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
act(() => {
sharedApp0.bootstrap(serverContainer);
});
expect(onClientFn.mock.calls.length).toBe(0);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
expect(serverContainer.querySelector('#count')?.textContent).toBe('0');
await new Promise((resolve) => setTimeout(resolve, 1000 * 3));
const sharedApp1 = await createSharedApp({
modules: [],
main: AppView,
render,
share: {
name: 'counter',
type: 'SharedTab',
transports: {
server: transports1[0],
client: transports[1],
},
},
});
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
act(() => {
sharedApp1.bootstrap(clientContainer);
});
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
expect(clientContainer.querySelector('#count')?.textContent).toBe('0');
act(() => {
serverContainer
.querySelector('#increase')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
// waiting for sync state
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(1);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(1);
expect(serverContainer.querySelector('#count')?.textContent).toBe('1');
expect(clientContainer.querySelector('#count')?.textContent).toBe('1');
act(() => {
clientContainer
.querySelector('#increase')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
// waiting for sync state
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(2);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(2);
expect(serverContainer.querySelector('#count')?.textContent).toBe('2');
expect(clientContainer.querySelector('#count')?.textContent).toBe('2');
});
test('base server/Minimal set client port mode', async () => {
const transports = mockPairTransports();
const serverApp = await createSharedApp({
modules: [{ provide: 'todoList', useClass: TodoList }],
main: AppView,
render,
share: {
name: 'counter',
type: 'Base',
port: 'server',
transports: {
server: transports[0],
},
},
});
act(() => {
serverApp.bootstrap(serverContainer);
});
expect(serverContainer.querySelector('#count')?.textContent).toBe('0');
const clientApp = await createSharedApp({
modules: [],
main: AppView,
render,
share: {
name: 'counter',
type: 'Base',
port: 'client',
transports: {
client: transports[1],
},
enablePatchesFilter: true,
},
});
act(() => {
clientApp.bootstrap(clientContainer);
});
expect(clientContainer.querySelector('#count')?.textContent).toBe('0');
act(() => {
serverContainer
.querySelector('#increase')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
// waiting for sync state
await new Promise((resolve) => setTimeout(resolve));
expect(serverContainer.querySelector('#count')?.textContent).toBe('1');
expect(clientContainer.querySelector('#count')?.textContent).toBe('1');
expect(clientApp.store?.getState().counter.obj.number).toBe(1);
act(() => {
clientContainer
.querySelector('#increase')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
// waiting for sync state
await new Promise((resolve) => setTimeout(resolve));
expect(serverContainer.querySelector('#count')?.textContent).toBe('2');
expect(clientContainer.querySelector('#count')?.textContent).toBe('2');
expect(clientApp.store?.getState().counter.obj.number).toBe(2);
act(() => {
clientContainer
.querySelector('#increase')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
// waiting for sync state
await new Promise((resolve) => setTimeout(resolve));
const fn = jest.fn();
clientApp.store!.subscribe(fn);
expect(fn.mock.calls.length).toBe(0);
await serverApp.container.get(PortDetector).syncToClients();
expect(fn.mock.calls.length).toBe(1);
await clientApp.container
.get(PortDetector)
.syncFullState({ forceSync: false });
expect(fn.mock.calls.length).toBe(1);
expect(clientApp.container.get(LastAction).sequence).toBe(
serverApp.container.get(LastAction).sequence
);
clientApp.container.get(LastAction).sequence = -1;
await clientApp.container
.get(PortDetector)
.syncFullState({ forceSync: false });
expect(fn.mock.calls.length).toBe(2);
await clientApp.container
.get(PortDetector)
.syncFullState({ forceSync: false });
expect(fn.mock.calls.length).toBe(2);
await clientApp.container.get(PortDetector).syncFullState();
expect(fn.mock.calls.length).toBe(3);
});
}); | the_stack |
import "./item-list-layout.scss";
import type { ReactNode } from "react";
import React from "react";
import { computed, makeObservable } from "mobx";
import { Observer, observer } from "mobx-react";
import type { ConfirmDialogParams } from "../confirm-dialog";
import type { TableCellProps, TableProps, TableRowProps, TableSortCallbacks } from "../table";
import { Table, TableCell, TableHead, TableRow } from "../table";
import type { IClassName } from "../../utils";
import { autoBind, cssNames, isDefined, isReactNode, noop, prevDefault, stopPropagation } from "../../utils";
import type { AddRemoveButtonsProps } from "../add-remove-buttons";
import { AddRemoveButtons } from "../add-remove-buttons";
import { NoItems } from "../no-items";
import { Spinner } from "../spinner";
import type { ItemObject } from "../../../common/item.store";
import type { Filter, PageFiltersStore } from "./page-filters/store";
import type { ThemeStore } from "../../themes/store";
import { MenuActions } from "../menu/menu-actions";
import { MenuItem } from "../menu";
import { Checkbox } from "../checkbox";
import type { UserStore } from "../../../common/user-store";
import type { ItemListStore } from "./list-layout";
import { withInjectables } from "@ogre-tools/injectable-react";
import themeStoreInjectable from "../../themes/store.injectable";
import userStoreInjectable from "../../../common/user-store/user-store.injectable";
import pageFiltersStoreInjectable from "./page-filters/store.injectable";
import type { OpenConfirmDialog } from "../confirm-dialog/open.injectable";
import openConfirmDialogInjectable from "../confirm-dialog/open.injectable";
export interface ItemListLayoutContentProps<Item extends ItemObject, PreLoadStores extends boolean> {
getFilters: () => Filter[];
tableId?: string;
className: IClassName;
getItems: () => Item[];
store: ItemListStore<Item, PreLoadStores>;
getIsReady: () => boolean; // show loading indicator while not ready
isSelectable?: boolean; // show checkbox in rows for selecting items
isConfigurable?: boolean;
copyClassNameFromHeadCells?: boolean;
sortingCallbacks?: TableSortCallbacks<Item>;
tableProps?: Partial<TableProps<Item>>; // low-level table configuration
renderTableHeader?: (TableCellProps | undefined | null)[];
renderTableContents: (item: Item) => (ReactNode | TableCellProps)[];
renderItemMenu?: (item: Item, store: ItemListStore<Item, PreLoadStores>) => ReactNode;
customizeTableRowProps?: (item: Item) => Partial<TableRowProps<Item>>;
addRemoveButtons?: Partial<AddRemoveButtonsProps>;
virtual?: boolean;
// item details view
hasDetailsView?: boolean;
detailsItem?: Item;
onDetails?: (item: Item) => void;
// other
customizeRemoveDialog?: (selectedItems: Item[]) => Partial<ConfirmDialogParams>;
/**
* Message to display when a store failed to load
*
* @default "Failed to load items"
*/
failedToLoadMessage?: React.ReactNode;
}
interface Dependencies {
themeStore: ThemeStore;
userStore: UserStore;
pageFiltersStore: PageFiltersStore;
openConfirmDialog: OpenConfirmDialog;
}
@observer
class NonInjectedItemListLayoutContent<
Item extends ItemObject,
PreLoadStores extends boolean,
> extends React.Component<ItemListLayoutContentProps<Item, PreLoadStores> & Dependencies> {
constructor(props: ItemListLayoutContentProps<Item, PreLoadStores> & Dependencies) {
super(props);
makeObservable(this);
autoBind(this);
}
@computed get failedToLoad() {
return this.props.store.failedLoading;
}
renderRow(item: Item) {
return this.getTableRow(item);
}
getTableRow(item: Item) {
const {
isSelectable, renderTableHeader, renderTableContents, renderItemMenu,
store, hasDetailsView, onDetails,
copyClassNameFromHeadCells, customizeTableRowProps = () => ({}), detailsItem,
} = this.props;
const { isSelected } = store;
return (
<TableRow
nowrap
searchItem={item}
sortItem={item}
selected={detailsItem && detailsItem.getId() === item.getId()}
onClick={hasDetailsView ? prevDefault(() => onDetails?.(item)) : undefined}
{...customizeTableRowProps(item)}
>
{isSelectable && (
<TableCell
checkbox
isChecked={isSelected(item)}
onClick={prevDefault(() => store.toggleSelection(item))}
/>
)}
{renderTableContents(item).map((content, index) => {
const cellProps: TableCellProps = isReactNode(content)
? { children: content }
: content;
const headCell = renderTableHeader?.[index];
if (copyClassNameFromHeadCells && headCell) {
cellProps.className = cssNames(
cellProps.className,
headCell.className,
);
}
if (!headCell || this.showColumn(headCell)) {
return <TableCell key={index} {...cellProps} />;
}
return null;
})}
{renderItemMenu && (
<TableCell className="menu">
<div onClick={stopPropagation}>
{renderItemMenu(item, store)}
</div>
</TableCell>
)}
</TableRow>
);
}
getRow(uid: string) {
return (
<div key={uid}>
<Observer>
{() => {
const item = this.props.getItems().find(item => item.getId() === uid);
if (!item) return null;
return this.getTableRow(item);
}}
</Observer>
</div>
);
}
removeItemsDialog(selectedItems: Item[]) {
const { customizeRemoveDialog, store, openConfirmDialog } = this.props;
const visibleMaxNamesCount = 5;
const selectedNames = selectedItems.map(ns => ns.getName()).slice(0, visibleMaxNamesCount).join(", ");
const dialogCustomProps = customizeRemoveDialog ? customizeRemoveDialog(selectedItems) : {};
const selectedCount = selectedItems.length;
const tailCount = selectedCount > visibleMaxNamesCount
? selectedCount - visibleMaxNamesCount
: 0;
const tail = tailCount > 0
? (
<>
{", and "}
<b>{tailCount}</b>
{" more"}
</>
)
: null;
const message = selectedCount <= 1
? (
<p>
{"Remove item "}
<b>{selectedNames}</b>
?
</p>
)
: (
<p>
Remove
<b>{selectedCount}</b>
{" items "}
<b>{selectedNames}</b>
{tail}
?
</p>
);
const { removeSelectedItems, removeItems } = store;
const onConfirm = typeof removeItems === "function"
? () => removeItems.apply(store, [selectedItems])
: typeof removeSelectedItems === "function"
? removeSelectedItems.bind(store)
: noop;
openConfirmDialog({
ok: onConfirm,
labelOk: "Remove",
message,
...dialogCustomProps,
});
}
renderNoItems() {
if (this.failedToLoad) {
return <NoItems>{this.props.failedToLoadMessage}</NoItems>;
}
if (!this.props.getIsReady()) {
return <Spinner center />;
}
if (this.props.getFilters().length > 0) {
return (
<NoItems>
No items found.
<p>
<a onClick={() => this.props.pageFiltersStore.reset()} className="contrast">
Reset filters?
</a>
</p>
</NoItems>
);
}
return <NoItems />;
}
renderItems() {
if (this.props.virtual) {
return null;
}
return this.props.getItems().map(item => this.getRow(item.getId()));
}
renderTableHeader() {
const { customizeTableRowProps, renderTableHeader, isSelectable, isConfigurable, store } = this.props;
if (!renderTableHeader) {
return null;
}
const enabledItems = this.props.getItems().filter(item => !customizeTableRowProps?.(item).disabled);
return (
<TableHead showTopLine nowrap>
{isSelectable && (
<Observer>
{() => (
<TableCell
checkbox
isChecked={store.isSelectedAll(enabledItems)}
onClick={prevDefault(() => store.toggleSelectionAll(enabledItems))}
/>
)}
</Observer>
)}
{
renderTableHeader
.filter(isDefined)
.map((cellProps, index) => (
this.showColumn(cellProps) && (
<TableCell key={cellProps.id ?? index} {...cellProps} />
)
))
}
<TableCell className="menu">
{isConfigurable && this.renderColumnVisibilityMenu()}
</TableCell>
</TableHead>
);
}
render() {
const {
store, hasDetailsView, addRemoveButtons = {}, virtual, sortingCallbacks,
detailsItem, className, tableProps = {}, tableId, getItems, themeStore,
} = this.props;
const selectedItemId = detailsItem && detailsItem.getId();
const classNames = cssNames(className, "box", "grow", themeStore.activeTheme.type);
const items = getItems();
const selectedItems = store.pickOnlySelected(items);
return (
<div className="items box grow flex column">
<Table
tableId={tableId}
virtual={virtual}
selectable={hasDetailsView}
sortable={sortingCallbacks}
getTableRow={this.getRow}
renderRow={virtual ? undefined : this.renderRow}
items={items}
selectedItemId={selectedItemId}
noItems={this.renderNoItems()}
className={classNames}
{...tableProps}
>
{this.renderTableHeader()}
{this.renderItems()}
</Table>
<Observer>
{() => (
<AddRemoveButtons
onRemove={
(store.removeItems || store.removeSelectedItems) && selectedItems.length > 0
? () => this.removeItemsDialog(selectedItems)
: undefined
}
removeTooltip={`Remove selected items (${selectedItems.length})`}
{...addRemoveButtons}
/>
)}
</Observer>
</div>
);
}
showColumn({ id: columnId, showWithColumn }: TableCellProps): boolean {
const { tableId, isConfigurable } = this.props;
return !isConfigurable || !tableId || !this.props.userStore.isTableColumnHidden(tableId, columnId, showWithColumn);
}
renderColumnVisibilityMenu() {
const { renderTableHeader = [], tableId } = this.props;
return (
<MenuActions
className="ItemListLayoutVisibilityMenu"
toolbar={false}
autoCloseOnSelect={false}
>
{
renderTableHeader
.filter(isDefined)
.map((cellProps, index) => (
!cellProps.showWithColumn && (
<MenuItem key={index} className="input">
<Checkbox
label={cellProps.title ?? `<${cellProps.className}>`}
value={this.showColumn(cellProps)}
onChange={(
tableId
? (() => cellProps.id && this.props.userStore.toggleTableColumnVisibility(tableId, cellProps.id))
: undefined
)}
/>
</MenuItem>
)
))
}
</MenuActions>
);
}
}
export const ItemListLayoutContent = withInjectables<Dependencies, ItemListLayoutContentProps<ItemObject, boolean>>(NonInjectedItemListLayoutContent, {
getProps: (di, props) => ({
...props,
themeStore: di.inject(themeStoreInjectable),
userStore: di.inject(userStoreInjectable),
pageFiltersStore: di.inject(pageFiltersStoreInjectable),
openConfirmDialog: di.inject(openConfirmDialogInjectable),
}),
}) as <Item extends ItemObject, PreLoadStores extends boolean>(props: ItemListLayoutContentProps<Item, PreLoadStores>) => React.ReactElement; | the_stack |
* Created by Dolkkok on 2017. 7. 18..
*/
import {AfterViewInit, Component, ElementRef, Injector, OnInit, OnDestroy} from '@angular/core';
import {BaseChart, PivotTableInfo} from '../base-chart';
import {BaseOption} from '../option/base-option';
import {
ChartType, SymbolType, ShelveType, ShelveFieldType, SeriesType, LineMarkType, FontSize, UIChartDataLabelDisplayType
} from '../option/define/common';
import {OptionGenerator} from '../option/util/option-generator';
import {Position} from '../option/define/common';
import {Pivot} from '@domain/workbook/configurations/pivot';
import * as _ from 'lodash';
import {ColorOptionConverter} from '../option/converter/color-option-converter';
import {Series} from '../option/define/series';
import {LabelOptionConverter} from '../option/converter/label-option-converter';
import {FormatOptionConverter} from '../option/converter/format-option-converter';
import { UIChartFormat } from '../option/ui-option/ui-format';
import { UIOption } from '../option/ui-option';
import {UIRadarChart} from '@common/component/chart/option/ui-option/ui-radar-chart';
@Component({
selector: 'radar-chart',
template: '<div class="chartCanvas" style="width: 100%; height: 100%; display: block;"></div>'
})
export class RadarChartComponent extends BaseChart<UIRadarChart> implements OnInit, OnDestroy, AfterViewInit {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(protected elementRef: ElementRef,
protected injector: Injector) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// Init
public ngOnInit() {
// Init
super.ngOnInit();
}
// Destory
public ngOnDestroy() {
// Destory
super.ngOnDestroy();
}
// After View Init
public ngAfterViewInit(): void {
super.ngAfterViewInit();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 선반정보를 기반으로 차트를 그릴수 있는지 여부를 체크
* - 반드시 각 차트에서 Override
*/
public isValid(pivot: Pivot): boolean {
return (this.getFieldTypeCount(pivot, ShelveType.AGGREGATIONS, ShelveFieldType.DIMENSION) === 1 && this.getFieldTypeCount(pivot, ShelveType.AGGREGATIONS, ShelveFieldType.TIMESTAMP) === 0)
&& (this.getFieldTypeCount(pivot, ShelveType.AGGREGATIONS, ShelveFieldType.MEASURE) > 0 || this.getFieldTypeCount(pivot, ShelveType.AGGREGATIONS, ShelveFieldType.CALCULATED) > 0);
}
/**
* 차트에 설정된 옵션으로 차트를 그린다.
* - 각 차트에서 Override
* @param _isKeepRange: 현재 스크롤 위치를 기억해야 할 경우
*/
public draw(_isKeepRange?: boolean): void {
////////////////////////////////////////////////////////
// Valid 체크
////////////////////////////////////////////////////////
if( !this.isValid(this.pivot) ) {
// No Data 이벤트 발생
this.noData.emit();
return;
}
////////////////////////////////////////////////////////
// Basic (Type, Title, etc..)
////////////////////////////////////////////////////////
// 차트의 기본옵션을 생성한다.
this.chartOption = this.initOption();
// 차트 기본설정 정보를 변환
this.chartOption = this.convertBasic();
////////////////////////////////////////////////////////
// dataInfo
// - 시리즈를 구성하는 데이터의 min/max 정보. E-Chart 에서 사용하는 속성 아님
// - 그 외에도 custom한 정보를 담고 있는 속성
////////////////////////////////////////////////////////
// 차트 커스텀 정보를 변환
this.chartOption = this.convertDataInfo();
////////////////////////////////////////////////////////
// series
////////////////////////////////////////////////////////
// 차트 시리즈 정보를 변환
this.chartOption = this.convertSeries();
////////////////////////////////////////////////////////
// tooltip
////////////////////////////////////////////////////////
// 차트 툴팁 정보를 변환
this.chartOption = this.convertTooltip();
////////////////////////////////////////////////////////
// Legend
////////////////////////////////////////////////////////
this.chartOption = this.convertLegend();
////////////////////////////////////////////////////////
// grid
////////////////////////////////////////////////////////
// 차트 그리드(배치) 정보를 반환
this.chartOption = this.convertGrid();
////////////////////////////////////////////////////////
// 추가적인 옵션사항
////////////////////////////////////////////////////////
this.chartOption = this.convertEtc();
////////////////////////////////////////////////////////
// apply
////////////////////////////////////////////////////////
// 차트 반영
this.apply();
////////////////////////////////////////////////////////
// Draw Finish
// - 차트 표현 완료후 resize등 후속처리
////////////////////////////////////////////////////////
this.drawFinish();
////////////////////////////////////////////////////////
// Selection 이벤트 등록
////////////////////////////////////////////////////////
if (!this.isPage) {
this.selection();
}
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 차트의 기본 옵션을 생성한다.
* - 각 차트에서 Override
*/
protected initOption(): BaseOption {
return {
type: ChartType.RADAR,
radar: OptionGenerator.Axis.radarAxis(),
legend: OptionGenerator.Legend.custom(true, true, Position.LEFT, SymbolType.CIRCLE, '100%', 20, 5),
tooltip: OptionGenerator.Tooltip.itemTooltip(),
series: []
};
}
/**
* 차트 기본설정 정보를 변환한다.
* - 필요시 각 차트에서 Override
* @returns {BaseOption}
*/
protected convertBasic(): BaseOption {
// 차트가 그려진 후 UI에 필요한 옵션 설정
this.setMeasureList();
// pivot aggs 초기화
const aggs: string[] = [];
// indicator 최대치 설정
const max = this.data.info.maxValue + (this.data.info.maxValue * 0.1);
// indicator 설정
this.chartOption.radar.indicator = [];
this.data.rows.map((row) => {
if (_.indexOf(aggs, row) < 0) {
this.chartOption.radar.indicator.push({ max, name: row });
}
});
return this.chartOption;
}
/**
* 시리즈 정보를 변환한다.
* - 필요시 각 차트에서 Override
* @returns {BaseOption}
*/
protected convertSeries(): BaseOption {
////////////////////////////////////////////////////////
// 차트 데이터를 기반으로 시리즈 생성
////////////////////////////////////////////////////////
// 시리즈 설정
this.chartOption = this.convertSeriesData();
////////////////////////////////////////////////////////
// 색상옵션 적용
////////////////////////////////////////////////////////
// 색상 설정
const series: Series[] = this.chartOption.series && this.chartOption.series.length > 0 ? this.chartOption.series[0].data : [];
this.chartOption = ColorOptionConverter.convertColor(
this.chartOption,
this.uiOption,
this.fieldOriginInfo,
this.fieldInfo,
this.pivotInfo,
series
);
////////////////////////////////////////////////////////
// 데이터 레이블 옵션 적용
////////////////////////////////////////////////////////
// 레이블 설정
this.chartOption = LabelOptionConverter.convertLabel(this.chartOption, this.uiOption);
////////////////////////////////////////////////////////
// 숫자 포맷 옵션 적용
////////////////////////////////////////////////////////
this.chartOption = this.convertRadarFormatSeries(this.chartOption, this.uiOption);
////////////////////////////////////////////////////////
// 차트별 추가사항
////////////////////////////////////////////////////////
// 차트별 추가사항 반영
this.chartOption = this.additionalSeries();
// 차트옵션 반환
return this.chartOption;
}
/**
* 차트별 시리즈 추가정보
* - 반드시 각 차트에서 Override
* @returns {BaseOption}
*/
protected convertSeriesData(): BaseOption {
// 시리즈 설정
this.chartOption.series = [];
this.chartOption.series.push({
type: SeriesType.RADAR,
name: 'radar',
data: this.data.columns.map((column) => {
return column;
}),
uiData: this.data.columns.map((column) => {
return column;
})
});
return this.chartOption;
}
/**
* 차트별 시리즈 추가정보
* - 필요시 각 차트에서 Override
* @returns {BaseOption}
*/
protected additionalSeries(): BaseOption {
////////////////////////////////////////////////////////
// 차트 시리즈 변경 표현
////////////////////////////////////////////////////////
this.chartOption = this.convertViewType();
// 차트옵션 반환
return this.chartOption;
}
/**
* 차트별 tooltip 추가정보
* - 필요시 각 차트에서 Override
* @returns {BaseOption}
*/
protected additionalTooltip(): BaseOption {
///////////////////////////
// UI 옵션에서 값 추출
///////////////////////////
let format: UIChartFormat = this.uiOption.valueFormat;
// 축의 포멧이 있는경우 축의 포멧으로 설정
const axisFormat = FormatOptionConverter.getlabelAxisScaleFormatTooltip(this.uiOption);
if (axisFormat) format = axisFormat;
///////////////////////////
// 차트 옵션에 적용
// - tooltip
///////////////////////////
// 적용
if( _.isUndefined(this.chartOption.tooltip) ) { this.chartOption.tooltip = {}; }
this.chartOption.tooltip.formatter = ((params): any => {
const option = this.chartOption.series[params.seriesIndex];
let uiData = _.cloneDeep(option.uiData);
// uiData값이 array인 경우 해당 dataIndex에 해당하는 uiData로 설정해준다
if (uiData && uiData instanceof Array) uiData = option.uiData[params.dataIndex];
return this.getFormatRadarValueSeriesTooltip(params, format, this.uiOption, option, uiData);
});
// 차트옵션 반환
return this.chartOption;
}
/**
* 데이터 정보를 변환한다.
* - 필요시 각 차트에서 Override
* @returns {BaseOption}
*/
protected convertDataInfo(): BaseOption {
// min/max 값 설정
this.chartOption.dataInfo = {
minValue: this.data.info.minValue,
maxValue: this.data.info.maxValue
};
return this.chartOption;
}
/**
* 결과데이터를 기반으로 차트를 구성하는 피봇정보 설정
* - 필요시 각 차트에서 Override
*/
protected setPivotInfo(): void {
// pivot aggs 초기화
const aggs: string[] = [];
// indicator 설정
this.data.rows.map((row) => {
if (_.indexOf(aggs, row) < 0) {
aggs.push(row);
}
});
// pivot 정보 설정, rows 정보는 중복값이 존재 할 수 있기 때문에 중복 제거
this.pivotInfo = new PivotTableInfo([], [], aggs);
}
/**
* 레이더의 차트별 기타 추가정보
*/
protected additionalEtc(): BaseOption {
// 레이더의 폰트사이즈 설정
if (!this.uiOption.fontSize) return this.chartOption;
const uiFontSize = this.uiOption.fontSize;
let fontSize: number;
switch(uiFontSize) {
case FontSize.NORMAL:
fontSize = 13;
break;
case FontSize.SMALL:
fontSize = 11;
break;
case FontSize.LARGE:
fontSize = 15;
break;
}
// radar name값이 없는경우 초기설정
if (!this.chartOption.radar.name) this.chartOption.radar.name = {};
// 레이더의 이름에 폰트사이즈 설정
this.chartOption.radar.name.fontSize = fontSize;
return this.chartOption;
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 공통 설정
* - Line or Area
*/
private convertViewType(): BaseOption {
if( _.isUndefined(this.chartOption.series) ){ return this.chartOption; }
const type: LineMarkType = this.uiOption['mark'];
_.each(this.chartOption.series, (obj) => {
if (_.eq(obj.type, SeriesType.RADAR)) {
obj.areaStyle = _.eq(type, LineMarkType.AREA) ? OptionGenerator.AreaStyle.radarItemAreaStyle('default') : undefined;
}
});
return this.chartOption;
}
/**
* Series: 포맷에 해당하는 옵션을 모두 적용한다.
* @param chartOption
* @param uiOption
* @returns {BaseOption}
*/
private convertRadarFormatSeries(chartOption: BaseOption, uiOption: UIOption): BaseOption {
///////////////////////////
// UI 옵션에서 값 추출
///////////////////////////
let format: UIChartFormat = uiOption.valueFormat;
if (_.isUndefined(format)){ return chartOption; }
// 축의 포멧이 있는경우 축의 포멧으로 설정
const axisFormat = FormatOptionConverter.getlabelAxisScaleFormat(uiOption);
if (axisFormat) format = axisFormat;
///////////////////////////
// 차트 옵션에 적용
// - 시리즈
///////////////////////////
// 시리즈
const series: Series[] = chartOption.series;
// 적용
_.each(series, (option, _index) => {
if( _.isUndefined(option.label) ) { option.label = { normal: {} }; }
if( _.isUndefined(option.label.normal) ) { option.label.normal = {} }
// 적용
option.label.normal.formatter = ((params): any => {
let uiData = _.cloneDeep(option.uiData);
// uiData값이 array인 경우 해당 dataIndex에 해당하는 uiData로 설정해준다
if (uiData && uiData instanceof Array) uiData = option.uiData[params.dataIndex];
return this.getFormatRadarValueSeries(params, format, uiOption, option, uiData);
});
});
// 반환
return chartOption;
}
/**
* 레이더의 포멧레이블 설정
* @param params
* @param format
* @param uiOption
* @param series
* @param uiData
* @returns {any}
*/
private getFormatRadarValueSeries(params: any, format: UIChartFormat, uiOption?: UIOption, series?: any, uiData?: any): string {
// UI 데이터 정보가 있을경우
if( uiData ) {
if (!uiOption.dataLabel || !uiOption.dataLabel.displayTypes) return '';
// UI 데이터 가공
let isUiData: boolean = false;
const result: string[] = [];
if( uiData['categoryName'] && -1 !== uiOption.dataLabel.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_NAME) ){
// value의 index찾기
const valueIndex = uiData['value'].indexOf(params.value);
result.push(uiData['categoryName'][valueIndex]);
isUiData = true;
}
if ( uiData['value'] && -1 !== uiOption.dataLabel.displayTypes.indexOf(UIChartDataLabelDisplayType.VALUE) ) {
result.push(FormatOptionConverter.getFormatValue(params.value, format));
isUiData = true;
}
let label: string = '';
// UI 데이터기반 레이블 반환
if( isUiData ) {
for( let num: number = 0 ; num < result.length ; num++ ) {
if( num > 0 ) {
label += '\n';
}
if(series.label && series.label.normal && series.label.normal.rich) {
label += '{align|'+ result[num] +'}';
}
else {
label += result[num];
}
}
return label;
// 선택된 display label이 없는경우 빈값 리턴
} else {
return label;
}
}
return FormatOptionConverter.noUIDataFormat(params, format);
}
/**
* 레이더의 포멧툴팁 설정
* @param params
* @param format
* @param uiOption
* @param _series
* @param uiData
* @returns {any}
*/
private getFormatRadarValueSeriesTooltip(params: any, format: UIChartFormat, uiOption?: UIOption, _series?: any, uiData?: any): string {
// UI 데이터 정보가 있을경우
if( uiData ) {
if (!uiOption.toolTip) uiOption.toolTip = {};
if (!uiOption.toolTip.displayTypes) uiOption.toolTip.displayTypes = FormatOptionConverter.setDisplayTypes(uiOption.type);
// UI 데이터 가공
let result: string[] = [];
const categoryNameList = _.filter(this.pivot.aggregations, {type : 'dimension'});
const categoryValueList = _.filter(this.pivot.aggregations, {type : 'measure'});
// name, value를 두개를 선택한 경우
if( uiData['categoryName'] && -1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_NAME) &&
uiData['value'] && -1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.VALUE)){
// categoryName과 categoryNameList length를 갖게설정
while (uiData['categoryName'].length > categoryNameList.length) {
categoryNameList.push(categoryNameList[0]);
}
_.each(uiData['categoryName'], (item, index: number) => {
// categoryName 설정
result = FormatOptionConverter.getTooltipName([item], categoryNameList, result, true);
// categoryValue 설정
const seriesValue = FormatOptionConverter.getTooltipValue(params.name, categoryValueList, format, uiData['value'][index]);
result.push(seriesValue);
});
// 둘중 하나를 선택한 경우
} else {
if( uiData['categoryName'] && -1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_NAME) ){
_.each(uiData['categoryName'], (item) => {
// categoryName 설정
result = FormatOptionConverter.getTooltipName([item], categoryNameList, result, true);
})
}
if ( uiData['value'] && -1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.VALUE) ) {
_.each(params.value, (item, _index: number) => {
// categoryValue 설정
const seriesValue = FormatOptionConverter.getTooltipValue(params.name, categoryValueList, format, item);
result.push(seriesValue);
});
}
}
return result.join('<br/>');
}
return FormatOptionConverter.noUIDataFormatTooltip(uiOption, params, format, this.fieldInfo);
}
} | the_stack |
* Copyright © 2020 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*
*/
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import { Command, flags as flagParser } from '@oclif/command';
import * as fs from 'fs-extra';
import { ApplicationConfig, HTTPAPIPlugin, MonitorPlugin, utils } from 'lisk-sdk';
import {
getDefaultPath,
splitPath,
getFullPath,
getConfigDirs,
removeConfigDir,
ensureConfigDir,
getDefaultConfigDir,
getNetworkConfigFilesPath,
getDefaultNetworkConfigFilesPath,
} from '../utils/path';
import { flags as commonFlags } from '../utils/flags';
import { getApplication } from '../application';
import { DEFAULT_NETWORK } from '../constants';
import DownloadCommand from './genesis-block/download';
interface Flags {
[key: string]: string | number | boolean | undefined;
}
const LOG_OPTIONS = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
const setPluginConfig = (config: ApplicationConfig, flags: Flags): void => {
if (flags['http-api-plugin-host'] !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
config.plugins[HTTPAPIPlugin.alias] = config.plugins[HTTPAPIPlugin.alias] ?? {};
config.plugins[HTTPAPIPlugin.alias].host = flags['http-api-plugin-host'];
}
if (flags['http-api-plugin-port'] !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
config.plugins[HTTPAPIPlugin.alias] = config.plugins[HTTPAPIPlugin.alias] ?? {};
config.plugins[HTTPAPIPlugin.alias].port = flags['http-api-plugin-port'];
}
if (
flags['http-api-plugin-whitelist'] !== undefined &&
typeof flags['http-api-plugin-whitelist'] === 'string'
) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
config.plugins[HTTPAPIPlugin.alias] = config.plugins[HTTPAPIPlugin.alias] ?? {};
config.plugins[HTTPAPIPlugin.alias].whiteList = flags['http-api-plugin-whitelist']
.split(',')
.filter(Boolean);
}
if (flags['monitor-plugin-host'] !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
config.plugins[MonitorPlugin.alias] = config.plugins[MonitorPlugin.alias] ?? {};
config.plugins[MonitorPlugin.alias].host = flags['monitor-plugin-host'];
}
if (flags['monitor-plugin-port'] !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
config.plugins[MonitorPlugin.alias] = config.plugins[MonitorPlugin.alias] ?? {};
config.plugins[MonitorPlugin.alias].port = flags['monitor-plugin-port'];
}
if (
flags['monitor-plugin-whitelist'] !== undefined &&
typeof flags['monitor-plugin-whitelist'] === 'string'
) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
config.plugins[MonitorPlugin.alias] = config.plugins[MonitorPlugin.alias] ?? {};
config.plugins[MonitorPlugin.alias].whiteList = flags['monitor-plugin-whitelist']
.split(',')
.filter(Boolean);
}
};
export default class StartCommand extends Command {
static description = 'Start Lisk Core Node.';
static examples = [
'start',
'start --network devnet --data-path /path/to/data-dir --log debug',
'start --network devnet --api-ws',
'start --network devnet --api-ws --api-ws-host 0.0.0.0 --api-ws-port 8888',
'start --network devnet --port 9000',
'start --network devnet --port 9002 --seed-peers 127.0.0.1:9001,127.0.0.1:9000',
'start --network testnet --overwrite-config',
'start --network testnet --config ~/my_custom_config.json',
];
static flags = {
'data-path': flagParser.string({
...commonFlags.dataPath,
env: 'LISK_DATA_PATH',
}),
network: flagParser.string({
...commonFlags.network,
env: 'LISK_NETWORK',
default: DEFAULT_NETWORK,
}),
config: flagParser.string({
char: 'c',
description:
'File path to a custom config. Environment variable "LISK_CONFIG_FILE" can also be used.',
env: 'LISK_CONFIG_FILE',
}),
'overwrite-config': flagParser.boolean({
description: 'Overwrite network configs if they exist already',
default: false,
}),
port: flagParser.integer({
char: 'p',
description:
'Open port for the peer to peer incoming connections. Environment variable "LISK_PORT" can also be used.',
env: 'LISK_PORT',
}),
'api-ipc': flagParser.boolean({
description:
'Enable IPC communication. This will also load up plugins in child process and communicate over IPC.',
default: false,
exclusive: ['api-ws'],
}),
'api-ws': flagParser.boolean({
description: 'Enable websocket communication for api-client.',
default: false,
exclusive: ['api-ipc'],
}),
'api-ws-host': flagParser.string({
description: 'Host to be used for api-client websocket.',
env: 'LISK_API_WS_HOST',
dependsOn: ['api-ws'],
}),
'api-ws-port': flagParser.integer({
description: 'Port to be used for api-client websocket.',
env: 'LISK_API_WS_PORT',
dependsOn: ['api-ws'],
}),
'console-log': flagParser.string({
description:
'Console log level. Environment variable "LISK_CONSOLE_LOG_LEVEL" can also be used.',
env: 'LISK_CONSOLE_LOG_LEVEL',
options: LOG_OPTIONS,
}),
log: flagParser.string({
char: 'l',
description: 'File log level. Environment variable "LISK_FILE_LOG_LEVEL" can also be used.',
env: 'LISK_FILE_LOG_LEVEL',
options: LOG_OPTIONS,
}),
'seed-peers': flagParser.string({
env: 'LISK_SEED_PEERS',
description:
'Seed peers to initially connect to in format of comma separated "ip:port". IP can be DNS name or IPV4 format. Environment variable "LISK_SEED_PEERS" can also be used.',
}),
'enable-http-api-plugin': flagParser.boolean({
description:
'Enable HTTP API Plugin. Environment variable "LISK_ENABLE_HTTP_API_PLUGIN" can also be used.',
env: 'LISK_ENABLE_HTTP_API_PLUGIN',
default: false,
}),
'http-api-plugin-host': flagParser.string({
description:
'Host to be used for HTTP API Plugin. Environment variable "LISK_HTTP_API_PLUGIN_HOST" can also be used.',
env: 'LISK_HTTP_API_PLUGIN_HOST',
dependsOn: ['enable-http-api-plugin'],
}),
'http-api-plugin-port': flagParser.integer({
description:
'Port to be used for HTTP API Plugin. Environment variable "LISK_HTTP_API_PLUGIN_PORT" can also be used.',
env: 'LISK_HTTP_API_PLUGIN_PORT',
dependsOn: ['enable-http-api-plugin'],
}),
'http-api-plugin-whitelist': flagParser.string({
description:
'List of IPs in comma separated value to allow the connection. Environment variable "LISK_HTTP_API_PLUGIN_WHITELIST" can also be used.',
env: 'LISK_HTTP_API_PLUGIN_WHITELIST',
dependsOn: ['enable-http-api-plugin'],
}),
'enable-forger-plugin': flagParser.boolean({
description:
'Enable Forger Plugin. Environment variable "LISK_ENABLE_FORGER_PLUGIN" can also be used.',
env: 'LISK_ENABLE_FORGER_PLUGIN',
default: false,
}),
'enable-monitor-plugin': flagParser.boolean({
description:
'Enable Monitor Plugin. Environment variable "LISK_ENABLE_MONITOR_PLUGIN" can also be used.',
env: 'LISK_ENABLE_MONITOR_PLUGIN',
default: false,
}),
'monitor-plugin-host': flagParser.string({
description:
'Host to be used for Monitor Plugin. Environment variable "LISK_MONITOR_PLUGIN_HOST" can also be used.',
env: 'LISK_MONITOR_PLUGIN_HOST',
dependsOn: ['enable-monitor-plugin'],
}),
'monitor-plugin-port': flagParser.integer({
description:
'Port to be used for Monitor Plugin. Environment variable "LISK_MONITOR_PLUGIN_PORT" can also be used.',
env: 'LISK_MONITOR_PLUGIN_PORT',
dependsOn: ['enable-monitor-plugin'],
}),
'monitor-plugin-whitelist': flagParser.string({
description:
'List of IPs in comma separated value to allow the connection. Environment variable "LISK_MONITOR_PLUGIN_WHITELIST" can also be used.',
env: 'LISK_MONITOR_PLUGIN_WHITELIST',
dependsOn: ['enable-monitor-plugin'],
}),
'enable-report-misbehavior-plugin': flagParser.boolean({
description:
'Enable ReportMisbehavior Plugin. Environment variable "LISK_ENABLE_REPORT_MISBEHAVIOR_PLUGIN" can also be used.',
env: 'LISK_ENABLE_MONITOR_PLUGIN',
default: false,
}),
};
// eslint-disable-next-line @typescript-eslint/require-await
async run(): Promise<void> {
const { flags } = this.parse(StartCommand);
const dataPath = flags['data-path'] ? flags['data-path'] : getDefaultPath();
this.log(`Starting Lisk Core at ${getFullPath(dataPath)}.`);
const pathConfig = splitPath(dataPath);
const defaultNetworkConfigs = getDefaultConfigDir();
const defaultNetworkConfigDir = getConfigDirs(defaultNetworkConfigs);
if (!defaultNetworkConfigDir.includes(flags.network)) {
this.error(
`Network must be one of ${defaultNetworkConfigDir.join(',')} but received ${
flags.network
}.`,
);
}
// Validate dataPath/config if config for other network exists, throw error and exit unless overwrite-config is specified
const configDir = getConfigDirs(dataPath);
// If config file exist, do not copy unless overwrite-config is specified
if (configDir.length > 1 || (configDir.length === 1 && configDir[0] !== flags.network)) {
if (!flags['overwrite-config']) {
this.error(
`Datapath ${dataPath} already contains configs for ${configDir.join(
',',
)}. Please use --overwrite-config to overwrite the config.`,
);
}
// Remove other network configs
for (const configFolder of configDir) {
if (configFolder !== flags.network) {
removeConfigDir(dataPath, configFolder);
}
}
}
// If genesis block file exist, do not copy unless overwrite-config is specified
ensureConfigDir(dataPath, flags.network);
// Read network genesis block and config from the folder
const { genesisBlockFilePath, configFilePath } = getNetworkConfigFilesPath(
dataPath,
flags.network,
);
const {
genesisBlockFilePath: defaultGenesisBlockFilePath,
configFilePath: defaultConfigFilepath,
} = getDefaultNetworkConfigFilesPath(flags.network);
let genesisBlockExists = fs.existsSync(genesisBlockFilePath);
const configFileExists = fs.existsSync(configFilePath);
if (!genesisBlockExists && ['mainnet', 'testnet'].includes(flags.network)) {
this.log(`Genesis block from "${flags.network}" does not exists.`);
await DownloadCommand.run(['--network', flags.network, '--data-path', dataPath]);
genesisBlockExists = true;
}
if (
!genesisBlockExists ||
(genesisBlockExists &&
flags['overwrite-config'] &&
!['mainnet', 'testnet'].includes(flags.network))
) {
fs.copyFileSync(defaultGenesisBlockFilePath, genesisBlockFilePath);
}
if (!configFileExists || (configFileExists && flags['overwrite-config'])) {
fs.copyFileSync(defaultConfigFilepath, configFilePath);
}
// Get config from network config or config specified
const genesisBlock = await fs.readJSON(genesisBlockFilePath);
let config = await fs.readJSON(configFilePath);
if (flags.config) {
const customConfig: ApplicationConfig = await fs.readJSON(flags.config);
config = utils.objects.mergeDeep({}, config, customConfig) as ApplicationConfig;
}
config.rootPath = pathConfig.rootPath;
config.label = pathConfig.label;
config.version = this.config.pjson.version;
// Inject other properties specified
if (flags['api-ipc']) {
config.rpc = utils.objects.mergeDeep({}, config.rpc, {
enable: flags['api-ipc'],
mode: 'ipc',
});
}
if (flags['api-ws']) {
config.rpc = utils.objects.mergeDeep({}, config.rpc, {
enable: flags['api-ws'],
mode: 'ws',
host: flags['api-ws-host'],
port: flags['api-ws-port'],
});
}
if (flags['console-log']) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
config.logger = config.logger ?? {};
config.logger.consoleLogLevel = flags['console-log'];
}
if (flags.log) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
config.logger = config.logger ?? {};
config.logger.fileLogLevel = flags.log;
}
if (flags.port) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
config.network = config.network ?? {};
config.network.port = flags.port;
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (flags['seed-peers']) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
config.network = config.network ?? {};
config.network.seedPeers = [];
const peers = flags['seed-peers'].split(',');
for (const seed of peers) {
const [ip, port] = seed.split(':');
if (!ip || !port || Number.isNaN(Number(port))) {
this.error('Invalid seed-peers, ip or port is invalid or not specified.');
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
config.network.seedPeers.push({ ip, port: Number(port) });
}
}
// Plugin configs
setPluginConfig(config, flags);
// Get application and start
try {
const app = getApplication(genesisBlock, config, {
enableHTTPAPIPlugin: flags['enable-http-api-plugin'],
enableForgerPlugin: flags['enable-forger-plugin'],
enableMonitorPlugin: flags['enable-monitor-plugin'],
enableReportMisbehaviorPlugin: flags['enable-report-misbehavior-plugin'],
});
await app.run();
} catch (errors) {
this.error(
Array.isArray(errors) ? errors.map(err => (err as Error).message).join(',') : errors,
);
}
}
} | the_stack |
import {
IPageCreateInput,
IPageUpdateInput,
NotionFabricator,
TSchemaUnitInput
} from '@nishans/fabricator';
import { NotionLineage } from '@nishans/lineage';
import { NotionLogger } from '@nishans/logger';
import { NotionOperations } from '@nishans/operations';
import {
FilterType,
FilterTypes,
UpdateType,
UpdateTypes
} from '@nishans/traverser';
import {
ICollection,
IPage,
ISchemaMapValue,
TCollectionBlock,
TSchemaUnit
} from '@nishans/types';
import { NotionUtils } from '@nishans/utils';
import {
ICollectionUpdateInput,
INotionCoreOptions,
ISchemaUnitMap,
NotionCore
} from '../';
import { PopulateMap } from '../PopulateMap';
import { transformToMultiple } from '../utils';
import Page from './Block/Page';
import Data from './Data';
/**
* A class to represent collection of Notion
* @noInheritDoc
*/
class Collection extends Data<ICollection, ICollectionUpdateInput> {
constructor(args: INotionCoreOptions) {
super({ ...args, type: 'collection' });
}
getCachedParentData() {
return this.cache.block.get(
this.getCachedData().parent_id
) as TCollectionBlock;
}
/**
* Create multiple templates for the collection
* @param rows Array of Objects for configuring template options
*/
async createTemplates(rows: IPageCreateInput[]) {
return await NotionFabricator.CreateData.contents(
rows,
this.id,
this.type as 'collection',
this.getProps()
);
}
/**
* Get a single template page of the collection
* @param args string id or a predicate function
* @returns Template page object
*/
async getTemplate(arg?: FilterType<IPage>) {
return (await this.getTemplates(transformToMultiple(arg), false))[0];
}
async getTemplates(args?: FilterTypes<IPage>, multiple?: boolean) {
return await this.getIterate<IPage, Page[]>(
args,
{
child_ids: 'template_pages',
multiple,
child_type: 'block',
container: []
},
(page_id) => this.cache.block.get(page_id) as IPage,
(id, _, pages) => pages.push(new Page({ ...this.getProps(), id }))
);
}
async updateTemplate(arg: UpdateType<IPage, Omit<IPageUpdateInput, 'type'>>) {
return (await this.updateTemplates(transformToMultiple(arg), false))[0];
}
async updateTemplates(
args: UpdateTypes<IPage, Omit<IPageUpdateInput, 'type'>>,
multiple?: boolean
) {
return await this.updateIterate<
IPage,
Omit<IPageUpdateInput, 'type'>,
Page[]
>(
args,
{
child_ids: 'template_pages',
multiple,
child_type: 'block',
container: []
},
(child_id) => this.cache.block.get(child_id) as IPage,
(id, _, __, pages) => pages.push(new Page({ ...this.getProps(), id }))
);
}
/**
* Delete a single template page from the collection
* @param args string id or a predicate function
*/
async deleteTemplate(arg?: FilterType<IPage>) {
return await this.deleteTemplates(transformToMultiple(arg), false);
}
/**
* Delete multiple template pages from the collection
* @param args string of ids or a predicate function
* @param multiple whether multiple or single item is targeted
*/
async deleteTemplates(args?: FilterTypes<IPage>, multiple?: boolean) {
return await this.deleteIterate<IPage, Page[]>(
args,
{
multiple,
child_ids: 'template_pages',
child_type: 'block',
child_path: 'template_pages',
container: []
},
(child_id) => this.cache.block.get(child_id) as IPage,
async (id, _, container) =>
container.push(new Page({ ...this.getProps(), id }))
);
}
/**
* Add rows of data to the collection block
* @param rows
* @returns An array of newly created page objects
*/
async createRows(rows: IPageCreateInput[]) {
return await NotionFabricator.CreateData.contents(
rows,
this.id,
this.type as 'collection',
this.getProps()
);
}
async getRow(arg?: FilterType<IPage>) {
return (await this.getRows(transformToMultiple(arg), false))[0];
}
async getRows(args?: FilterTypes<IPage>, multiple?: boolean) {
await this.initializeCacheForThisData();
const row_page_ids = await NotionLineage.Collection.getRowPageIds(
this.id,
this.getProps()
);
return await this.getIterate<IPage, Page[]>(
args,
{
child_ids: row_page_ids,
child_type: 'block',
multiple,
container: [],
initialize_cache: false
},
(id) => this.cache.block.get(id) as IPage,
(id, _, pages) => pages.push(new Page({ ...this.getProps(), id }))
);
}
async updateRow(arg: UpdateType<IPage, Omit<IPageUpdateInput, 'type'>>) {
return (await this.updateRows(transformToMultiple(arg), false))[0];
}
async updateRows(
args: UpdateTypes<IPage, Omit<IPageUpdateInput, 'type'>>,
multiple?: boolean
) {
return await this.updateIterate<
IPage,
Omit<IPageUpdateInput, 'type'>,
Page[]
>(
args,
{
child_ids: await NotionLineage.Collection.getRowPageIds(
this.id,
this.getProps()
),
multiple,
child_type: 'block',
container: []
},
(child_id) => this.cache.block.get(child_id) as IPage,
(id, _, __, pages) => pages.push(new Page({ ...this.getProps(), id }))
);
}
async deleteRow(arg?: FilterType<IPage>) {
return await this.deleteRows(transformToMultiple(arg), false);
}
/**
* Delete multiple template pages from the collection
* @param args string of ids or a predicate function
* @param multiple whether multiple or single item is targeted
*/
async deleteRows(args?: FilterTypes<IPage>, multiple?: boolean) {
return await this.deleteIterate<IPage, Page[]>(
args,
{
child_ids: await NotionLineage.Collection.getRowPageIds(
this.id,
this.getProps()
),
child_type: 'block',
multiple,
container: []
},
(child_id) => this.cache.block.get(child_id) as IPage,
async (id, _, container) =>
container.push(new Page({ ...this.getProps(), id }))
);
}
/**
* Create multiple new columns in the collection schema
* @param args array of Schema creation properties
* @returns An array of SchemaUnit objects representing the columns
*/
async createSchemaUnits(args: TSchemaUnitInput[]) {
const data = this.getCachedData(),
schema_unit_map = NotionCore.CreateMaps.schemaUnit(),
props = this.getProps();
await NotionFabricator.CreateData.schema(
args,
{
name: data.name,
parent_collection_id: data.id,
current_schema: data.schema
},
this.getProps(),
(schema_unit) =>
PopulateMap.schemaUnit(
this.id,
schema_unit.schema_id,
schema_unit,
props,
schema_unit_map
)
);
await NotionOperations.executeOperations(
[
NotionOperations.Chunk.collection.update(
this.id,
['schema'],
data.schema
)
],
this.getProps()
);
return schema_unit_map;
}
async getSchemaUnit(arg?: FilterType<ISchemaMapValue>) {
return await this.getSchemaUnits(transformToMultiple(arg), false);
}
/**
* Return multiple columns from the collection schema
* @param args schema_id string array or predicate function
* @returns An array of SchemaUnit objects representing the columns
*/
async getSchemaUnits(
args?: FilterTypes<ISchemaMapValue>,
multiple?: boolean
) {
// Since all the data is in the cache, no need to initialize cache
const data = this.getCachedData(),
schema_map = NotionUtils.generateSchemaMap(data.schema);
return await this.getIterate<ISchemaMapValue, ISchemaUnitMap>(
args,
{
container: NotionCore.CreateMaps.schemaUnit(),
child_ids: Array.from(schema_map.keys()),
child_type: 'collection',
multiple,
initialize_cache: false
},
(name) => schema_map.get(name),
(_, schema_unit, schema_unit_map) =>
PopulateMap.schemaUnit(
this.id,
schema_unit.schema_id,
schema_unit,
this.getProps(),
schema_unit_map
)
);
}
/**
* Update and return a single column from the collection schema
* @param args schema_id string and schema properties tuple
* @returns A SchemaUnit object representing the column
*/
async updateSchemaUnit(
arg: UpdateType<ISchemaMapValue, Partial<TSchemaUnit>>
) {
return await this.updateSchemaUnits(transformToMultiple(arg), false);
}
/**
* Update and return multiple columns from the collection schema
* @param args schema_id string and schema properties array of tuples
* @returns An array of SchemaUnit objects representing the columns
*/
async updateSchemaUnits(
args: UpdateTypes<ISchemaMapValue, Partial<TSchemaUnit>>,
multiple?: boolean
) {
const data = this.getCachedData(),
schema_map = NotionUtils.generateSchemaMap(data.schema);
const results = await this.updateIterate<
ISchemaMapValue,
Partial<TSchemaUnit>,
ISchemaUnitMap
>(
args,
{
child_ids: Array.from(schema_map.keys()),
child_type: 'collection',
multiple,
manual: true,
container: NotionCore.CreateMaps.schemaUnit(),
initialize_cache: false
},
(name) => schema_map.get(name),
(_, schema_unit, updated_data, schema_unit_map) => {
data.schema[schema_unit.schema_id] = NotionUtils.deepMerge(
data.schema[schema_unit.schema_id],
updated_data
);
PopulateMap.schemaUnit(
this.id,
schema_unit.schema_id,
data.schema[schema_unit.schema_id],
this.getProps(),
schema_unit_map
);
}
);
await NotionOperations.executeOperations(
[
NotionOperations.Chunk.collection.update(
this.id,
['schema'],
data.schema
)
],
this.getProps()
);
return results;
}
/**
* Delete a single column from the collection schema
* @param args schema_id string or predicate function
* @returns A SchemaUnit object representing the column
*/
async deleteSchemaUnit(args?: FilterType<ISchemaMapValue>) {
return await this.deleteSchemaUnits(transformToMultiple(args), false);
}
/**
* Delete multiple columns from the collection schema
* @param args schema_id string array or predicate function
* @returns An array of SchemaUnit objects representing the columns
*/
async deleteSchemaUnits(
args?: FilterTypes<ISchemaMapValue>,
multiple?: boolean
) {
const data = this.getCachedData(),
schema_map = NotionUtils.generateSchemaMap(data.schema);
const deleted_schema_unit_map = await this.deleteIterate<
ISchemaMapValue,
ISchemaUnitMap
>(
args,
{
child_ids: Array.from(schema_map.keys()),
child_type: 'collection',
multiple,
manual: true,
container: NotionCore.CreateMaps.schemaUnit(),
initialize_cache: false
},
(name) => schema_map.get(name),
(_, schema_unit, schema_unit_map) => {
if (schema_unit.schema_id === 'title')
NotionLogger.error(`Title schema unit cannot be deleted`);
delete data.schema[schema_unit.schema_id];
PopulateMap.schemaUnit(
this.id,
schema_unit.schema_id,
schema_unit,
this.getProps(),
schema_unit_map
);
}
);
await NotionOperations.executeOperations(
[
NotionOperations.Chunk.collection.update(
this.id,
['schema'],
data.schema
)
],
this.getProps()
);
return deleted_schema_unit_map;
}
}
export default Collection; | the_stack |
import {
NetworkOrSignerOrProvider,
TransactionResult,
TransactionResultWithId,
} from "../core/types";
import { Erc721 } from "../core/classes/erc-721";
import { ContractMetadata } from "../core/classes/contract-metadata";
import { ContractRoles } from "../core/classes/contract-roles";
import { ContractRoyalty } from "../core/classes/contract-royalty";
import { ContractEvents } from "../core/classes/contract-events";
import { ContractEncoder } from "../core/classes/contract-encoder";
import { GasCostEstimator } from "../core/classes/gas-cost-estimator";
import { NFTMetadataOrUri, NFTMetadataOwner, SDKOptions } from "../schema";
import { Multiwrap as MultiwrapContract } from "contracts";
import { ContractWrapper } from "../core/classes/contract-wrapper";
import { uploadOrExtractURI } from "../common/nft";
import {
ERC1155Wrappable,
ERC20Wrappable,
ERC721Wrappable,
TokensToWrap,
WrappedTokens,
} from "../types/multiwrap";
import {
fetchCurrencyMetadata,
hasERC20Allowance,
normalizePriceValue,
} from "../common/currency";
import { ITokenBundle, TokensWrappedEvent } from "contracts/Multiwrap";
import { MultiwrapContractSchema } from "../schema/contracts/multiwrap";
import { BigNumberish, ethers } from "ethers";
import TokenStruct = ITokenBundle.TokenStruct;
import { QueryAllParams } from "../types";
import { isTokenApprovedForTransfer } from "../common/marketplace";
import { Erc721Supply } from "../core/classes/erc-721-supply";
import { IStorage } from "../core/interfaces/IStorage";
/**
* Multiwrap lets you wrap any number of ERC20, ERC721 and ERC1155 tokens you own into a single wrapped token bundle.
*
* @example
*
* ```javascript
* import { ThirdwebSDK } from "@thirdweb-dev/sdk";
*
* const sdk = new ThirdwebSDK("rinkeby");
* const contract = sdk.getMultiwrap("{{contract_address}}");
* ```
*
* @beta
*/
export class Multiwrap extends Erc721<MultiwrapContract> {
static contractType = "multiwrap" as const;
static contractRoles = ["transfer", "minter", "unwrap", "asset"] as const;
static contractAbi = require("../../abis/Multiwrap.json");
/**
* @internal
*/
static schema = MultiwrapContractSchema;
public encoder: ContractEncoder<MultiwrapContract>;
public estimator: GasCostEstimator<MultiwrapContract>;
public metadata: ContractMetadata<MultiwrapContract, typeof Multiwrap.schema>;
public events: ContractEvents<MultiwrapContract>;
public roles: ContractRoles<
MultiwrapContract,
typeof Multiwrap.contractRoles[number]
>;
/**
* Configure royalties
* @remarks Set your own royalties for the entire contract or per token
* @example
* ```javascript
* // royalties on the whole contract
* contract.royalties.setDefaultRoyaltyInfo({
* seller_fee_basis_points: 100, // 1%
* fee_recipient: "0x..."
* });
* // override royalty for a particular token
* contract.royalties.setTokenRoyaltyInfo(tokenId, {
* seller_fee_basis_points: 500, // 5%
* fee_recipient: "0x..."
* });
* ```
*/
public royalties: ContractRoyalty<MultiwrapContract, typeof Multiwrap.schema>;
private _query = this.query as Erc721Supply;
constructor(
network: NetworkOrSignerOrProvider,
address: string,
storage: IStorage,
options: SDKOptions = {},
contractWrapper = new ContractWrapper<MultiwrapContract>(
network,
address,
Multiwrap.contractAbi,
options,
),
) {
super(contractWrapper, storage, options);
this.metadata = new ContractMetadata(
this.contractWrapper,
Multiwrap.schema,
this.storage,
);
this.roles = new ContractRoles(
this.contractWrapper,
Multiwrap.contractRoles,
);
this.encoder = new ContractEncoder(this.contractWrapper);
this.estimator = new GasCostEstimator(this.contractWrapper);
this.events = new ContractEvents(this.contractWrapper);
this.royalties = new ContractRoyalty(this.contractWrapper, this.metadata);
}
/** ******************************
* READ FUNCTIONS
*******************************/
/**
* Get All Wrapped Token Bundles
*
* @remarks Get all the data associated with every token bundle in this contract.
*
* By default, returns the first 100 NFTs, use queryParams to fetch more.
*
* @example
* ```javascript
* const wrappedBundles = await contract.getAll();
* console.log(wrappedBundles);
* ```
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata for all NFTs queried.
*/
public async getAll(
queryParams?: QueryAllParams,
): Promise<NFTMetadataOwner[]> {
return this._query.all(queryParams);
}
/**
* Get the contents of a wrapped token bundle
* @example
* ```javascript
* const contents = await contract.getWrappedContents(wrappedTokenId);
* console.log(contents.erc20Tokens);
* console.log(contents.erc721Tokens);
* console.log(contents.erc1155Tokens);
* ```
* @param wrappedTokenId - the id of the wrapped token bundle
*/
public async getWrappedContents(
wrappedTokenId: BigNumberish,
): Promise<WrappedTokens> {
const wrappedTokens =
await this.contractWrapper.readContract.getWrappedContents(
wrappedTokenId,
);
const erc20Tokens: ERC20Wrappable[] = [];
const erc721Tokens: ERC721Wrappable[] = [];
const erc1155Tokens: ERC1155Wrappable[] = [];
for (const token of wrappedTokens) {
switch (token.tokenType) {
case 0: {
const tokenMetadata = await fetchCurrencyMetadata(
this.contractWrapper.getProvider(),
token.assetContract,
);
erc20Tokens.push({
contractAddress: token.assetContract,
quantity: ethers.utils.formatUnits(
token.totalAmount,
tokenMetadata.decimals,
),
});
break;
}
case 1: {
erc721Tokens.push({
contractAddress: token.assetContract,
tokenId: token.tokenId,
});
break;
}
case 2: {
erc1155Tokens.push({
contractAddress: token.assetContract,
tokenId: token.tokenId,
quantity: token.totalAmount.toString(),
});
break;
}
}
}
return {
erc20Tokens,
erc721Tokens,
erc1155Tokens,
};
}
/** ******************************
* WRITE FUNCTIONS
*******************************/
/**
* Wrap any number of ERC20/ERC721/ERC1155 tokens into a single wrapped token
* @example
* ```javascript
* const tx = await contract.wrap({
* erc20Tokens: [{
* contractAddress: "0x...",
* quantity: "0.8"
* }],
* erc721Tokens: [{
* contractAddress: "0x...",
* tokenId: "0"
* }],
* erc1155Tokens: [{
* contractAddress: "0x...",
* tokenId: "1",
* quantity: "2"
* }]
* }, {
* name: "Wrapped bundle",
* description: "This is a wrapped bundle of tokens and NFTs",
* image: "ipfs://...",
* });
* const receipt = tx.receipt(); // the transaction receipt
* const wrappedTokenId = tx.id; // the id of the wrapped token bundle
* ```
* @param contents - the contents to wrap
* @param wrappedTokenMetadata - metadata to represent the wrapped token bundle
* @param recipientAddress - Optional. The address to send the wrapped token bundle to
*/
public async wrap(
contents: TokensToWrap,
wrappedTokenMetadata: NFTMetadataOrUri,
recipientAddress?: string,
): Promise<TransactionResultWithId<NFTMetadataOwner>> {
const uri = await uploadOrExtractURI(wrappedTokenMetadata, this.storage);
const recipient = recipientAddress
? recipientAddress
: await this.contractWrapper.getSignerAddress();
const tokens = await this.toTokenStructList(contents);
const receipt = await this.contractWrapper.sendTransaction("wrap", [
tokens,
uri,
recipient,
]);
const event = this.contractWrapper.parseLogs<TokensWrappedEvent>(
"TokensWrapped",
receipt?.logs,
);
if (event.length === 0) {
throw new Error("TokensWrapped event not found");
}
const tokenId = event[0].args.tokenIdOfWrappedToken;
return {
id: tokenId,
receipt,
data: () => this.get(tokenId),
};
}
/**
* Unwrap a wrapped token bundle, and retrieve its contents
* @example
* ```javascript
* await contract.unwrap(wrappedTokenId);
* ```
* @param wrappedTokenId - the id of the wrapped token bundle
* @param recipientAddress - Optional. The address to send the unwrapped tokens to
*/
public async unwrap(
wrappedTokenId: BigNumberish,
recipientAddress?: string,
): Promise<TransactionResult> {
const recipient = recipientAddress
? recipientAddress
: await this.contractWrapper.getSignerAddress();
return {
receipt: await this.contractWrapper.sendTransaction("unwrap", [
wrappedTokenId,
recipient,
]),
};
}
/** ******************************
* PRIVATE FUNCTIONS
*******************************/
private async toTokenStructList(contents: TokensToWrap) {
const tokens: TokenStruct[] = [];
const provider = this.contractWrapper.getProvider();
const owner = await this.contractWrapper.getSignerAddress();
if (contents.erc20Tokens) {
for (const erc20 of contents.erc20Tokens) {
const normalizedQuantity = await normalizePriceValue(
provider,
erc20.quantity,
erc20.contractAddress,
);
const hasAllowance = await hasERC20Allowance(
this.contractWrapper,
erc20.contractAddress,
normalizedQuantity,
);
if (!hasAllowance) {
throw new Error(
`ERC20 token with contract address "${
erc20.contractAddress
}" does not have enough allowance to transfer.\n\nYou can set allowance to the multiwrap contract to transfer these tokens by running:\n\nawait sdk.getToken("${
erc20.contractAddress
}").setAllowance("${this.getAddress()}", ${erc20.quantity});\n\n`,
);
}
tokens.push({
assetContract: erc20.contractAddress,
totalAmount: normalizedQuantity,
tokenId: 0,
tokenType: 0,
});
}
}
if (contents.erc721Tokens) {
for (const erc721 of contents.erc721Tokens) {
const isApproved = await isTokenApprovedForTransfer(
this.contractWrapper.getProvider(),
this.getAddress(),
erc721.contractAddress,
erc721.tokenId,
owner,
);
if (!isApproved) {
throw new Error(
`ERC721 token "${erc721.tokenId}" with contract address "${
erc721.contractAddress
}" is not approved for transfer.\n\nYou can give approval the multiwrap contract to transfer this token by running:\n\nawait sdk.getNFTCollection("${
erc721.contractAddress
}").setApprovalForToken("${this.getAddress()}", ${
erc721.tokenId
});\n\n`,
);
}
tokens.push({
assetContract: erc721.contractAddress,
totalAmount: 0,
tokenId: erc721.tokenId,
tokenType: 1,
});
}
}
if (contents.erc1155Tokens) {
for (const erc1155 of contents.erc1155Tokens) {
const isApproved = await isTokenApprovedForTransfer(
this.contractWrapper.getProvider(),
this.getAddress(),
erc1155.contractAddress,
erc1155.tokenId,
owner,
);
if (!isApproved) {
throw new Error(
`ERC1155 token "${erc1155.tokenId}" with contract address "${
erc1155.contractAddress
}" is not approved for transfer.\n\nYou can give approval the multiwrap contract to transfer this token by running:\n\nawait sdk.getEdition("${
erc1155.contractAddress
}").setApprovalForAll("${this.getAddress()}", true);\n\n`,
);
}
tokens.push({
assetContract: erc1155.contractAddress,
totalAmount: erc1155.quantity,
tokenId: erc1155.tokenId,
tokenType: 2,
});
}
}
return tokens;
}
} | the_stack |
import {
getSnapshot,
unprotect,
recordPatches,
types,
IType,
IJsonPatch,
Instance,
cast,
IAnyModelType,
IMSTMap,
escapeJsonPath,
getPath,
resolvePath,
splitJsonPath,
joinJsonPath
} from "../../src"
function testPatches<C, S, T>(
type: IType<C, S, T>,
snapshot: C,
fn: any,
expectedPatches: IJsonPatch[]
) {
const instance = type.create(snapshot)
const baseSnapshot = getSnapshot(instance)
const recorder = recordPatches(instance)
unprotect(instance)
fn(instance)
recorder.stop()
expect(recorder.patches).toEqual(expectedPatches)
const clone = type.create(snapshot)
recorder.replay(clone)
expect(getSnapshot(clone)).toEqual(getSnapshot(instance))
recorder.undo()
expect(getSnapshot(instance)).toEqual(baseSnapshot)
}
const Node = types.model("Node", {
id: types.identifierNumber,
text: "Hi",
children: types.optional(types.array(types.late((): IAnyModelType => Node)), [])
})
test("it should apply simple patch", () => {
testPatches(
Node,
{ id: 1 },
(n: Instance<typeof Node>) => {
n.text = "test"
},
[
{
op: "replace",
path: "/text",
value: "test"
}
]
)
})
test("it should apply deep patches to arrays", () => {
testPatches(
Node,
{ id: 1, children: [{ id: 2 }] },
(n: Instance<typeof Node>) => {
const children = (n.children as unknown) as Instance<typeof Node>[]
children[0].text = "test" // update
children[0] = cast({ id: 2, text: "world" }) // this reconciles; just an update
children[0] = cast({ id: 4, text: "coffee" }) // new object
children[1] = cast({ id: 3, text: "world" }) // addition
children.splice(0, 1) // removal
},
[
{
op: "replace",
path: "/children/0/text",
value: "test"
},
{
op: "replace",
path: "/children/0/text",
value: "world"
},
{
op: "replace",
path: "/children/0",
value: {
id: 4,
text: "coffee",
children: []
}
},
{
op: "add",
path: "/children/1",
value: {
id: 3,
text: "world",
children: []
}
},
{
op: "remove",
path: "/children/0"
}
]
)
})
test("it should apply deep patches to arrays with object instances", () => {
testPatches(
Node,
{ id: 1, children: [{ id: 2 }] },
(n: Instance<typeof Node>) => {
const children = (n.children as unknown) as Instance<typeof Node>[]
children[0].text = "test" // update
children[0] = Node.create({ id: 2, text: "world" }) // this does not reconcile, new instance is provided
children[0] = Node.create({ id: 4, text: "coffee" }) // new object
},
[
{
op: "replace",
path: "/children/0/text",
value: "test"
},
{
op: "replace",
path: "/children/0",
value: {
id: 2,
text: "world",
children: []
}
},
{
op: "replace",
path: "/children/0",
value: {
id: 4,
text: "coffee",
children: []
}
}
]
)
})
test("it should apply non flat patches", () => {
testPatches(
Node,
{ id: 1 },
(n: Instance<typeof Node>) => {
const children = (n.children as unknown) as Instance<typeof Node>[]
children.push(
cast({
id: 2,
children: [{ id: 4 }, { id: 5, text: "Tea" }]
})
)
},
[
{
op: "add",
path: "/children/0",
value: {
id: 2,
text: "Hi",
children: [
{
id: 4,
text: "Hi",
children: []
},
{
id: 5,
text: "Tea",
children: []
}
]
}
}
]
)
})
test("it should apply non flat patches with object instances", () => {
testPatches(
Node,
{ id: 1 },
(n: Instance<typeof Node>) => {
const children = (n.children as unknown) as Instance<typeof Node>[]
children.push(
Node.create({
id: 2,
children: [{ id: 5, text: "Tea" }]
})
)
},
[
{
op: "add",
path: "/children/0",
value: {
id: 2,
text: "Hi",
children: [
{
id: 5,
text: "Tea",
children: []
}
]
}
}
]
)
})
test("it should apply deep patches to maps", () => {
// If user does not transpile const/let to var, trying to call Late' subType
// property getter during map's tryCollectModelTypes() will throw ReferenceError.
// But if it's transpiled to var, then subType will become 'undefined'.
const NodeMap = types.model("NodeMap", {
id: types.identifierNumber,
text: "Hi",
children: types.optional(types.map(types.late((): IAnyModelType => NodeMap)), {})
})
testPatches(
NodeMap,
{ id: 1, children: { 2: { id: 2 } } },
(n: Instance<typeof NodeMap>) => {
const children = n.children as IMSTMap<typeof NodeMap>
children.get("2")!.text = "test" // update
children.put({ id: 2, text: "world" }) // this reconciles; just an update
children.set(
"4",
NodeMap.create({ id: 4, text: "coffee", children: { 23: { id: 23 } } })
) // new object
children.put({ id: 3, text: "world", children: { 7: { id: 7 } } }) // addition
children.delete("2") // removal
},
[
{
op: "replace",
path: "/children/2/text",
value: "test"
},
{
op: "replace",
path: "/children/2/text",
value: "world"
},
{
op: "add",
path: "/children/4",
value: {
children: {
23: {
children: {},
id: 23,
text: "Hi"
}
},
id: 4,
text: "coffee"
}
},
{
op: "add",
path: "/children/3",
value: {
children: {
7: {
children: {},
id: 7,
text: "Hi"
}
},
id: 3,
text: "world"
}
},
{
op: "remove",
path: "/children/2"
}
]
)
})
test("it should apply deep patches to objects", () => {
const NodeObject = types.model("NodeObject", {
id: types.identifierNumber,
text: "Hi",
child: types.maybe(types.late((): IAnyModelType => NodeObject))
})
testPatches(
NodeObject,
{ id: 1, child: { id: 2 } },
(n: Instance<typeof NodeObject>) => {
n.child!.text = "test" // update
n.child = cast({ id: 2, text: "world" }) // this reconciles; just an update
n.child = NodeObject.create({ id: 2, text: "coffee", child: { id: 23 } })
n.child = cast({ id: 3, text: "world", child: { id: 7 } }) // addition
n.child = undefined // removal
},
[
{
op: "replace",
path: "/child/text",
value: "test"
},
{
op: "replace",
path: "/child/text",
value: "world"
},
{
op: "replace",
path: "/child",
value: {
child: {
child: undefined,
id: 23,
text: "Hi"
},
id: 2,
text: "coffee"
}
},
{
op: "replace",
path: "/child",
value: {
child: {
child: undefined,
id: 7,
text: "Hi"
},
id: 3,
text: "world"
}
},
{
op: "replace",
path: "/child",
value: undefined
}
]
)
})
test("it should correctly split/join json patches", () => {
function isValid(str: string, array: string[], altStr?: string) {
expect(splitJsonPath(str)).toEqual(array)
expect(joinJsonPath(array)).toBe(altStr !== undefined ? altStr : str)
}
isValid("", [])
isValid("/", [""])
isValid("//", ["", ""])
isValid("/a", ["a"])
isValid("/a/", ["a", ""])
isValid("/a//", ["a", "", ""])
isValid(".", ["."])
isValid("..", [".."])
isValid("./a", [".", "a"])
isValid("../a", ["..", "a"])
isValid("/.a", [".a"])
isValid("/..a", ["..a"])
// rooted relatives are equivalent to plain relatives
isValid("/.", ["."], ".")
isValid("/..", [".."], "..")
isValid("/./a", [".", "a"], "./a")
isValid("/../a", ["..", "a"], "../a")
function isInvalid(str: string) {
expect(() => {
splitJsonPath(str)
}).toThrow("a json path must be either rooted, empty or relative")
}
isInvalid("a")
isInvalid("a/")
isInvalid("a//")
isInvalid(".a")
isInvalid(".a/")
isInvalid("..a")
isInvalid("..a/")
})
test("it should correctly escape/unescape json patches", () => {
expect(escapeJsonPath("http://example.com")).toBe("http:~1~1example.com")
const AppStore = types.model({
items: types.map(types.frozen<any>())
})
testPatches(
AppStore,
{ items: {} },
(store: typeof AppStore.Type) => {
store.items.set("with/slash~tilde", 1)
},
[{ op: "add", path: "/items/with~1slash~0tilde", value: 1 }]
)
})
test("weird keys are handled correctly", () => {
const Store = types.model({
map: types.map(
types.model({
model: types.model({
value: types.string
})
})
)
})
const store = Store.create({
map: {
"": { model: { value: "val1" } },
"/": { model: { value: "val2" } },
"~": { model: { value: "val3" } }
}
})
{
const target = store.map.get("")!.model
const path = getPath(target)
expect(path).toBe("/map//model")
expect(resolvePath(store, path)).toBe(target)
}
{
const target = store.map.get("/")!.model
const path = getPath(target)
expect(path).toBe("/map/~1/model")
expect(resolvePath(store, path)).toBe(target)
}
{
const target = store.map.get("~")!.model
const path = getPath(target)
expect(path).toBe("/map/~0/model")
expect(resolvePath(store, path)).toBe(target)
}
})
test("relativePath with a different base than the root works correctly", () => {
const Store = types.model({
map: types.map(
types.model({
model: types.model({
value: types.string
})
})
)
})
const store = Store.create({
map: {
"1": { model: { value: "val1" } },
"2": { model: { value: "val2" } }
}
})
{
const target = store.map.get("1")!.model
expect(resolvePath(store.map, "./1/model")).toBe(target)
expect(resolvePath(store.map, "../map/1/model")).toBe(target)
// rooted relative should resolve to the given base as root
expect(resolvePath(store.map, "/./1/model")).toBe(target)
expect(resolvePath(store.map, "/../map/1/model")).toBe(target)
}
{
const target = store.map.get("2")!.model
expect(resolvePath(store.map, "./2/model")).toBe(target)
expect(resolvePath(store.map, "../map/2/model")).toBe(target)
// rooted relative should resolve to the given base as root
expect(resolvePath(store.map, "/./2/model")).toBe(target)
expect(resolvePath(store.map, "/../map/2/model")).toBe(target)
}
}) | the_stack |
import { CoreDomUtils } from '@services/utils/dom';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
import { CoreLogger } from '@singletons/logger';
import { AddonModQuizDdwtosQuestionData } from '../component/ddwtos';
/**
* Class to make a question of ddwtos type work.
*/
export class AddonQtypeDdwtosQuestion {
protected logger: CoreLogger;
protected nextDragItemNo = 1;
protected selectors!: AddonQtypeDdwtosQuestionCSSSelectors; // Result of cssSelectors.
protected placed: {[no: number]: number} = {}; // Map that relates drag elements numbers with drop zones numbers.
protected selected?: HTMLElement; // Selected element (being "dragged").
protected resizeFunction?: () => void;
/**
* Create the instance.
*
* @param logger Logger provider.
* @param domUtils Dom Utils provider.
* @param container The container HTMLElement of the question.
* @param question The question instance.
* @param readOnly Whether it's read only.
* @param inputIds Ids of the inputs of the question (where the answers will be stored).
*/
constructor(
protected container: HTMLElement,
protected question: AddonModQuizDdwtosQuestionData,
protected readOnly: boolean,
protected inputIds: string[],
) {
this.logger = CoreLogger.getInstance('AddonQtypeDdwtosQuestion');
this.initializer();
}
/**
* Clone a drag item and add it to the drag container.
*
* @param dragHome Item to clone
*/
cloneDragItem(dragHome: HTMLElement): void {
const drag = <HTMLElement> dragHome.cloneNode(true);
drag.classList.remove('draghome');
drag.classList.add('drag');
drag.classList.add('no' + this.nextDragItemNo);
this.nextDragItemNo++;
drag.setAttribute('tabindex', '0');
drag.style.visibility = 'visible';
drag.style.position = 'absolute';
const container = this.container.querySelector(this.selectors.dragContainer());
container?.appendChild(drag);
if (!this.readOnly) {
this.makeDraggable(drag);
}
}
/**
* Clone the 'drag homes'.
* Invisible 'drag homes' are output in the question. These have the same properties as the drag items but are invisible.
* We clone these invisible elements to make the actual drag items.
*/
cloneDragItems(): void {
const dragHomes = <HTMLElement[]> Array.from(this.container.querySelectorAll(this.selectors.dragHomes()));
for (let x = 0; x < dragHomes.length; x++) {
this.cloneDragItemsForOneChoice(dragHomes[x]);
}
}
/**
* Clone a certain 'drag home'. If it's an "infinite" drag, clone it several times.
*
* @param dragHome Element to clone.
*/
cloneDragItemsForOneChoice(dragHome: HTMLElement): void {
if (dragHome.classList.contains('infinite')) {
const groupNo = this.getGroup(dragHome) ?? -1;
const noOfDrags = this.container.querySelectorAll(this.selectors.dropsInGroup(groupNo)).length;
for (let x = 0; x < noOfDrags; x++) {
this.cloneDragItem(dragHome);
}
} else {
this.cloneDragItem(dragHome);
}
}
/**
* Deselect all drags.
*/
deselectDrags(): void {
// Remove the selected class from all drags.
const drags = <HTMLElement[]> Array.from(this.container.querySelectorAll(this.selectors.drags()));
drags.forEach((drag) => {
drag.classList.remove('selected');
});
this.selected = undefined;
}
/**
* Function to call when the instance is no longer needed.
*/
destroy(): void {
if (this.resizeFunction) {
window.removeEventListener('resize', this.resizeFunction);
}
}
/**
* Get the choice number of an element. It is extracted from the classes.
*
* @param node Element to check.
* @return Choice number.
*/
getChoice(node: HTMLElement | null): number | undefined {
return this.getClassnameNumericSuffix(node, 'choice');
}
/**
* Get the number in a certain class name of an element.
*
* @param node The element to check.
* @param prefix Prefix of the class to check.
* @return The number in the class.
*/
getClassnameNumericSuffix(node: HTMLElement | null, prefix: string): number | undefined {
if (node?.classList.length) {
const patt1 = new RegExp('^' + prefix + '([0-9])+$');
const patt2 = new RegExp('([0-9])+$');
for (let index = 0; index < node.classList.length; index++) {
if (patt1.test(node.classList[index])) {
const match = patt2.exec(node.classList[index]);
return Number(match?.[0]);
}
}
}
this.logger.warn('Prefix "' + prefix + '" not found in class names.');
}
/**
* Get the group number of an element. It is extracted from the classes.
*
* @param node Element to check.
* @return Group number.
*/
getGroup(node: HTMLElement | null): number | undefined {
return this.getClassnameNumericSuffix(node, 'group');
}
/**
* Get the number of an element ('no'). It is extracted from the classes.
*
* @param node Element to check.
* @return Number.
*/
getNo(node: HTMLElement | null): number | undefined {
return this.getClassnameNumericSuffix(node, 'no');
}
/**
* Get the place number of an element. It is extracted from the classes.
*
* @param node Element to check.
* @return Place number.
*/
getPlace(node: HTMLElement | null): number | undefined {
return this.getClassnameNumericSuffix(node, 'place');
}
/**
* Initialize the question.
*/
async initializer(): Promise<void> {
this.selectors = new AddonQtypeDdwtosQuestionCSSSelectors();
const container = <HTMLElement> this.container.querySelector(this.selectors.topNode());
if (this.readOnly) {
container.classList.add('readonly');
} else {
container.classList.add('notreadonly');
}
// Wait for the elements to be ready.
await this.waitForReady();
this.setPaddingSizesAll();
this.cloneDragItems();
this.initialPlaceOfDragItems();
this.makeDropZones();
this.positionDragItems();
this.resizeFunction = this.windowResized.bind(this);
window.addEventListener('resize', this.resizeFunction!);
}
/**
* Initialize drag items, putting them in their initial place.
*/
initialPlaceOfDragItems(): void {
const drags = <HTMLElement[]> Array.from(this.container.querySelectorAll(this.selectors.drags()));
// Add the class 'unplaced' to all elements.
drags.forEach((drag) => {
drag.classList.add('unplaced');
});
this.placed = {};
for (const placeNo in this.inputIds) {
const inputId = this.inputIds[placeNo];
const inputNode = this.container.querySelector('input#' + inputId);
const choiceNo = Number(inputNode?.getAttribute('value'));
if (choiceNo !== 0 && !isNaN(choiceNo)) {
const drop = this.container.querySelector<HTMLElement>(this.selectors.dropForPlace(parseInt(placeNo, 10) + 1));
const groupNo = this.getGroup(drop) ?? -1;
const drag = this.container.querySelector<HTMLElement>(
this.selectors.unplacedDragsForChoiceInGroup(choiceNo, groupNo),
);
this.placeDragInDrop(drag, drop);
this.positionDragItem(drag);
}
}
}
/**
* Make an element "draggable". In the mobile app, items are "dragged" using tap and drop.
*
* @param drag Element.
*/
makeDraggable(drag: HTMLElement): void {
drag.addEventListener('click', () => {
if (drag.classList.contains('selected')) {
this.deselectDrags();
} else {
this.selectDrag(drag);
}
});
}
/**
* Convert an element into a drop zone.
*
* @param drop Element.
*/
makeDropZone(drop: HTMLElement): void {
drop.addEventListener('click', () => {
const drag = this.selected;
if (!drag) {
// No element selected, nothing to do.
return false;
}
// Place it only if the same group is selected.
if (this.getGroup(drag) === this.getGroup(drop)) {
this.placeDragInDrop(drag, drop);
this.deselectDrags();
this.positionDragItem(drag);
}
});
}
/**
* Create all drop zones.
*/
makeDropZones(): void {
if (this.readOnly) {
return;
}
// Create all the drop zones.
const drops = <HTMLElement[]> Array.from(this.container.querySelectorAll(this.selectors.drops()));
drops.forEach((drop) => {
this.makeDropZone(drop);
});
// If home answer zone is clicked, return drag home.
const home = <HTMLElement> this.container.querySelector(this.selectors.topNode() + ' .answercontainer');
home.addEventListener('click', () => {
const drag = this.selected;
if (!drag) {
// No element selected, nothing to do.
return;
}
// Not placed yet, deselect.
if (drag.classList.contains('unplaced')) {
this.deselectDrags();
return;
}
// Remove, deselect and move back home in this order.
this.removeDragFromDrop(drag);
this.deselectDrags();
this.positionDragItem(drag);
});
}
/**
* Set the width and height of an element.
*
* @param node Element.
* @param width Width to set.
* @param height Height to set.
*/
protected padToWidthHeight(node: HTMLElement, width: number, height: number): void {
node.style.width = width + 'px';
node.style.height = height + 'px';
// Originally lineHeight was set as height to center the text but it comes on too height lines on multiline elements.
}
/**
* Place a draggable element inside a drop zone.
*
* @param drag Draggable element.
* @param drop Drop zone.
*/
placeDragInDrop(drag: HTMLElement | null, drop: HTMLElement | null): void {
if (!drop) {
return;
}
const placeNo = this.getPlace(drop) ?? -1;
const inputId = this.inputIds[placeNo - 1];
const inputNode = this.container.querySelector('input#' + inputId);
// Set the value of the drag element in the input of the drop zone.
if (drag !== null) {
inputNode?.setAttribute('value', String(this.getChoice(drag)));
} else {
inputNode?.setAttribute('value', '0');
}
// Remove the element from the "placed" map if it's there.
for (const alreadyThereDragNo in this.placed) {
if (this.placed[alreadyThereDragNo] === placeNo) {
delete this.placed[alreadyThereDragNo];
}
}
if (drag !== null) {
// Add the element in the "placed" map.
this.placed[this.getNo(drag) ?? -1] = placeNo;
}
}
/**
* Position a drag element in the right drop zone or in the home zone.
*
* @param drag Drag element.
*/
positionDragItem(drag: HTMLElement | null): void {
if (!drag) {
return;
}
let position;
const placeNo = this.placed[this.getNo(drag) ?? -1];
if (!placeNo) {
// Not placed, put it in home zone.
const groupNo = this.getGroup(drag) ?? -1;
const choiceNo = this.getChoice(drag) ?? -1;
position = CoreDomUtils.getElementXY(
this.container,
this.selectors.dragHome(groupNo, choiceNo),
'answercontainer',
);
drag.classList.add('unplaced');
} else {
// Get the drop zone position.
position = CoreDomUtils.getElementXY(
this.container,
this.selectors.dropForPlace(placeNo),
'addon-qtype-ddwtos-container',
);
drag.classList.remove('unplaced');
}
if (position) {
drag.style.left = position[0] + 'px';
drag.style.top = position[1] + 'px';
}
}
/**
* Postition, or reposition, all the drag items. They're placed in the right drop zone or in the home zone.
*/
positionDragItems(): void {
const drags = <HTMLElement[]> Array.from(this.container.querySelectorAll(this.selectors.drags()));
drags.forEach((drag) => {
this.positionDragItem(drag);
});
}
/**
* Wait for the drag items to have an offsetParent. For some reason it takes a while.
*
* @param retries Number of times this has been retried.
* @return Promise resolved when ready or if it took too long to load.
*/
protected async waitForReady(retries: number = 0): Promise<void> {
const drag = <HTMLElement | null> Array.from(this.container.querySelectorAll(this.selectors.drags()))[0];
if (drag?.offsetParent || retries >= 10) {
// Ready or too many retries, stop.
return;
}
const deferred = CoreUtils.promiseDefer<void>();
setTimeout(async () => {
try {
await this.waitForReady(retries + 1);
} finally {
deferred.resolve();
}
}, 20);
return deferred.promise;
}
/**
* Remove a draggable element from a drop zone.
*
* @param drag The draggable element.
*/
removeDragFromDrop(drag: HTMLElement): void {
const placeNo = this.placed[this.getNo(drag) ?? -1];
const drop = <HTMLElement> this.container.querySelector(this.selectors.dropForPlace(placeNo));
this.placeDragInDrop(null, drop);
}
/**
* Select a certain element as being "dragged".
*
* @param drag Element.
*/
selectDrag(drag: HTMLElement): void {
// Deselect previous drags, only 1 can be selected.
this.deselectDrags();
this.selected = drag;
drag.classList.add('selected');
}
/**
* Set the padding size for all groups.
*/
setPaddingSizesAll(): void {
for (let groupNo = 1; groupNo <= 8; groupNo++) {
this.setPaddingSizeForGroup(groupNo);
}
}
/**
* Set the padding size for a certain group.
*
* @param groupNo Group number.
*/
setPaddingSizeForGroup(groupNo: number): void {
const groupItems = <HTMLElement[]> Array.from(this.container.querySelectorAll(this.selectors.dragHomesGroup(groupNo)));
if (!groupItems.length) {
return;
}
let maxWidth = 0;
let maxHeight = 0;
// Find max height and width.
groupItems.forEach((item) => {
item.innerHTML = CoreTextUtils.decodeHTML(item.innerHTML);
maxWidth = Math.max(maxWidth, Math.ceil(item.offsetWidth));
maxHeight = Math.max(maxHeight, Math.ceil(item.offsetHeight));
});
maxWidth += 8;
maxHeight += 5;
groupItems.forEach((item) => {
this.padToWidthHeight(item, maxWidth, maxHeight);
});
const dropsGroup = <HTMLElement[]> Array.from(this.container.querySelectorAll(this.selectors.dropsGroup(groupNo)));
dropsGroup.forEach((item) => {
this.padToWidthHeight(item, maxWidth + 2, maxHeight + 2);
});
}
/**
* Window resized.
*/
async windowResized(): Promise<void> {
await CoreDomUtils.waitForResizeDone();
this.positionDragItems();
}
}
/**
* Set of functions to get the CSS selectors.
*/
export class AddonQtypeDdwtosQuestionCSSSelectors {
topNode(): string {
return '.addon-qtype-ddwtos-container';
}
dragContainer(): string {
return this.topNode() + ' div.drags';
}
drags(): string {
return this.dragContainer() + ' span.drag';
}
drag(no: number): string {
return this.drags() + `.no${no}`;
}
dragsInGroup(groupNo: number): string {
return this.drags() + `.group${groupNo}`;
}
unplacedDragsInGroup(groupNo: number): string {
return this.dragsInGroup(groupNo) + '.unplaced';
}
dragsForChoiceInGroup(choiceNo: number, groupNo: number): string {
return this.dragsInGroup(groupNo) + `.choice${choiceNo}`;
}
unplacedDragsForChoiceInGroup(choiceNo: number, groupNo: number): string {
return this.unplacedDragsInGroup(groupNo) + `.choice${choiceNo}`;
}
drops(): string {
return this.topNode() + ' span.drop';
}
dropForPlace(placeNo: number): string {
return this.drops() + `.place${placeNo}`;
}
dropsInGroup(groupNo: number): string {
return this.drops() + `.group${groupNo}`;
}
dragHomes(): string {
return this.topNode() + ' span.draghome';
}
dragHomesGroup(groupNo: number): string {
return this.topNode() + ` .draggrouphomes${groupNo} span.draghome`;
}
dragHome(groupNo: number, choiceNo: number): string {
return this.topNode() + ` .draggrouphomes${groupNo} span.draghome.choice${choiceNo}`;
}
dropsGroup(groupNo: number): string {
return this.topNode() + ` span.drop.group${groupNo}`;
}
} | the_stack |
import * as path from "path";
import deepdash from "deepdash";
import lodash from "lodash";
import { JsonLoader } from "../swagger/jsonLoader";
import { Operation, SwaggerSpec } from "../swagger/swaggerTypes";
import { traverseSwaggerAsync } from "../transform/traverseSwagger";
import { ModelValidationError } from "../util/modelValidationError";
import * as validate from "../validate";
import { AjvSchemaValidator } from "../swaggerValidator/ajvSchemaValidator";
import { TransformContext, getTransformContext } from "../transform/context";
import { xmsPathsTransformer } from "../transform/xmsPathsTransformer";
import { resolveNestedDefinitionTransformer } from "../transform/resolveNestedDefinitionTransformer";
import { referenceFieldsTransformer } from "../transform/referenceFieldsTransformer";
import { discriminatorTransformer } from "../transform/discriminatorTransformer";
import { allOfTransformer } from "../transform/allOfTransformer";
import { noAdditionalPropertiesTransformer } from "../transform/noAdditionalPropertiesTransformer";
import { applySpecTransformers, applyGlobalTransformers } from "../transform/transformer";
import { log } from "../util/logging";
import { inversifyGetInstance } from "../inversifyUtils";
import { ExampleRule, RuleSet } from "./exampleRule";
import * as util from "./util";
import Translator from "./translator";
import SwaggerMocker from "./swaggerMocker";
import { MockerCache, PayloadCache } from "./exampleCache";
const _ = deepdash(lodash);
export default class Generator {
private translator: Translator;
private spec!: SwaggerSpec;
private specFilePath: string;
private payloadDir?: string;
private jsonLoader: JsonLoader;
private swaggerMocker: SwaggerMocker;
private shouldMock: boolean;
private mockerCache: MockerCache;
private payloadCache: PayloadCache;
public readonly transformContext: TransformContext;
public constructor(specFilePath: string, payloadDir?: string) {
this.shouldMock = payloadDir ? false : true;
this.specFilePath = specFilePath;
this.payloadDir = payloadDir;
this.jsonLoader = inversifyGetInstance(JsonLoader, {
useJsonParser: false,
eraseXmsExamples: false,
});
this.mockerCache = new MockerCache();
this.payloadCache = new PayloadCache();
this.swaggerMocker = new SwaggerMocker(this.jsonLoader, this.mockerCache, this.payloadCache);
this.translator = new Translator(
this.jsonLoader,
this.payloadCache,
this.shouldMock ? this.swaggerMocker : undefined
);
const schemaValidator = new AjvSchemaValidator(this.jsonLoader);
this.transformContext = getTransformContext(this.jsonLoader, schemaValidator, [
xmsPathsTransformer,
resolveNestedDefinitionTransformer,
referenceFieldsTransformer,
discriminatorTransformer,
allOfTransformer,
noAdditionalPropertiesTransformer,
]);
}
private getSpecItem(spec: any, operationId: string): any {
const paths = spec.paths;
for (const pathName of Object.keys(paths)) {
for (const methodName of Object.keys(paths[pathName])) {
if (paths[pathName][methodName].operationId === operationId) {
return {
path: pathName,
methodName,
content: paths[pathName][methodName],
};
}
}
}
return null;
}
public async load() {
this.spec = (await (this.jsonLoader.load(this.specFilePath) as unknown)) as SwaggerSpec;
applySpecTransformers(this.spec, this.transformContext);
applyGlobalTransformers(this.transformContext);
await this.cacheExistingExamples();
}
public async generateAll(): Promise<readonly ModelValidationError[]> {
if (!this.spec) {
await this.load();
}
const errs: any[] = [];
await traverseSwaggerAsync(this.spec, {
onPath: async (apiPath, pathTemplate) => {
apiPath._pathTemplate = pathTemplate;
},
onOperation: async (operation: Operation, pathObject, methodName) => {
const pathName = pathObject._pathTemplate;
const specItem = {
path: pathName,
methodName,
content: operation,
};
const operationId: string = operation.operationId || "";
const errors = await this.generate(operationId, specItem);
if (errors.length > 0) {
errs.push(...errors);
return false;
}
return true;
},
});
return errs;
}
public async cacheExistingExamples() {
if (!this.shouldMock) {
return;
}
await traverseSwaggerAsync(this.spec, {
onOperation: async (operation: Operation, pathObject, methodName) => {
const pathName = pathObject._pathTemplate;
const specItem = {
path: pathName,
methodName,
content: operation,
};
const examples = operation["x-ms-examples"] || undefined;
if (!examples) {
return;
}
const operationId = operation.operationId;
/*
const validateErrors = await validate.validateExamples(this.specFilePath, operationId, {
});
if(validateErrors.length > 0) {
console.warn(`invalid examples for operation:${operationId}.`);
console.warn(validateErrors);
return
} */
for (const key of Object.keys(examples)) {
if (key.match(new RegExp(`^${operationId}_.*_Gen$`))) {
continue;
}
const example = this.jsonLoader.resolveRefObj(examples[key]);
if (!example) {
continue;
}
this.translator.extractParameters(specItem, example.parameters);
for (const code of Object.keys(operation.responses)) {
if (example.responses && example.responses[code]) {
this.translator.extractResponse(specItem, example.responses[code], code);
}
}
}
return true;
},
});
// reuse the payloadCache as exampleCache.
this.payloadCache.mergeCache();
}
private async generateExample(operationId: string, specItem: any, rule: ExampleRule) {
this.translator.setRule(rule);
this.swaggerMocker.setRule(rule);
let example;
console.log(`start generated example for ${operationId}, rule:${rule.ruleName}`);
if (!this.shouldMock) {
example = this.getExampleFromPayload(operationId, specItem);
if (!example) {
return [];
}
} else {
example = {
parameters: {},
responses: this.extractResponse(specItem, {}),
};
this.swaggerMocker.mockForExample(
example,
specItem,
this.spec,
util.getBaseName(this.specFilePath).split(".")[0]
);
}
log.info(example);
const unifiedExample = this.unifyCommonProperty(example);
const newSpec = util.referenceExmInSpec(
this.specFilePath,
specItem.path,
specItem.methodName,
`${operationId}_${rule.exampleNamePostfix}_Gen`
);
util.updateExmAndSpecFile(
unifiedExample,
newSpec,
this.specFilePath,
`${operationId}_${rule.exampleNamePostfix}_Gen.json`
);
log.info(`start validating generated example for ${operationId}`);
const validateErrors = await validate.validateExamples(this.specFilePath, operationId, {
// consoleLogLevel: "error"
});
if (validateErrors.length > 0) {
log.error(`the validation raised below error:`);
log.error(validateErrors);
return validateErrors;
}
console.log(`generated example for ${operationId}, rule:${rule.ruleName} successfully!`);
return [];
}
public async generate(
operationId: string,
specItem?: any
): Promise<readonly ModelValidationError[]> {
if (!this.spec) {
await this.load();
}
if (!specItem) {
specItem = this.getSpecItem(this.spec, operationId);
if (!specItem) {
console.error(`no specItem for the operation id ${operationId}`);
return [];
}
}
const ruleSet: RuleSet = [];
ruleSet.push({
exampleNamePostfix: "MaximumSet",
ruleName: "MaximumSet",
});
ruleSet.push({
exampleNamePostfix: "MinimumSet",
ruleName: "MinimumSet",
});
for (const rule of ruleSet) {
const error = await this.generateExample(operationId, specItem, rule);
if (error.length) {
return error;
}
}
return [];
}
private unifyCommonProperty(example: any) {
if (!example || !example.parameters || !example.responses) {
return;
}
type pathNode = string | number;
type pathNodes = pathNode[];
const requestPaths = _.paths(example.parameters, { pathFormat: "array" }).map((v) =>
(v as pathNode[]).reverse()
);
/**
* construct a inverted index , the key is leaf property key, value is reverse of the path from the root to the leaf property.
*/
const invertedIndex = new Map<string | number, pathNodes[]>();
requestPaths.forEach((v) => {
if (v.length && typeof v[0] === "string") {
const parentPaths = invertedIndex.get(v[0]);
if (!parentPaths) {
invertedIndex.set(v[0], [v.slice(1)]);
} else {
parentPaths.push(v.slice(1));
}
}
});
/**
* get two paths' common properties' count
*/
const getMatchedNodeCnt = (baseNode: pathNodes, destNode: pathNodes) => {
let count = 0;
baseNode.some((v, k) => {
if (k < destNode.length && destNode[k] === v) {
count++;
return false;
} else {
return true;
}
});
return count;
};
/**
* update the property value of response using the same value which is found in the request
*/
const res = _.mapValuesDeep(
example.responses,
(value, key, parentValue, context) => {
if (!parentValue) {
log.warn(`parent is null`);
}
if (
["integer", "number", "string"].some((type) => typeof value === type) &&
typeof key === "string"
) {
const possiblePaths = invertedIndex.get(key);
if (context.path && possiblePaths) {
const basePath = (context.path as pathNodes).slice().reverse().slice(1);
/**
* to find out the most matchable path in the parameters
*/
const candidates = possiblePaths.filter(
(apiPath) => getMatchedNodeCnt(basePath, apiPath) > 1
);
if (candidates.length === 0) {
return value;
}
/**
* if only one matched one path, just use it.
*/
if (candidates.length === 1) {
const pathOfParameter = _.pathToString([key, ...candidates[0]].reverse());
const parameterValue = _.get(example.parameters, pathOfParameter);
// console.debug(`use path ${pathOfParameter} ,value :${parameterValue}
// -- original path:${_.pathToString(context.path as pathNodes)},value:${value}`);
return parameterValue;
}
const mostMatched = candidates.reduce((previous, current) => {
const countPrevious = getMatchedNodeCnt(basePath, previous);
const countCurrent = getMatchedNodeCnt(basePath, current);
return countPrevious < countCurrent ? current : previous;
});
return _.get(example.parameters, _.pathToString([key, ...mostMatched].reverse()));
}
}
return value;
},
{
leavesOnly: true,
pathFormat: "array",
}
);
// console.debug(`unify common properties end!`);
example.responses = res;
return example;
}
private getExampleFromPayload(operationId: string, specItem: any) {
if (this.payloadDir) {
const subPaths = path.dirname(this.specFilePath).split(/\\|\//).slice(-3).join("/");
const payloadDir = path.join(this.payloadDir, subPaths);
const payload: any = util.readPayloadFile(payloadDir, operationId);
if (!payload) {
log.info(
`no payload file for operationId ${operationId} under directory ${path.resolve(
payloadDir,
operationId
)} named with <statusCode>.json`
);
return;
}
this.validatePayload(specItem, payload, operationId);
this.cachePayload(specItem, payload);
const example = {
parameters: this.extractRequest(specItem, payload),
responses: this.extractResponse(specItem, payload),
};
return example;
}
return undefined;
}
private cachePayload(specItem: any, payload: any) {
/**
* 1 cache parameter model
*
* 2 cache response model
*
* 3 merged cache
*/
this.extractRequest(specItem, payload);
this.extractResponse(specItem, payload);
this.payloadCache.mergeCache();
}
private validatePayload(specItem: any, payload: any, operationId: string) {
const specApiVersion = this.spec.info.version;
for (const statusCode of Object.keys(payload)) {
// remove payload with undefined status code
if (!(statusCode in specItem.content.responses)) {
delete payload[statusCode];
continue;
}
// remove payload with inconsistent api-version
if (!("query" in payload[statusCode].liveRequest)) {
continue;
}
const realApiVersion = payload[statusCode].liveRequest.query["api-version"];
if (realApiVersion && realApiVersion !== specApiVersion) {
delete payload[statusCode];
log.error(
`${operationId} payload ${statusCode}.json's api-version is ${realApiVersion}, inconsistent with swagger spec's api-version ${specApiVersion}`
);
}
}
}
private extractRequest(specItem: any, payload: any) {
log.info("extractRequest");
const liveRequest: any = this.getRequestPayload(specItem, payload);
if (!liveRequest) {
log.warn(`no live request in payload`);
return {};
}
const request = this.translator.extractRequest(specItem, liveRequest) || {};
return request;
}
private getRequestPayload(specItem: any, payload: any) {
const longRunning = util.isLongRunning(specItem);
for (const statusCode in payload) {
if (longRunning && statusCode === "200") {
continue;
}
if ("liveRequest" in payload[statusCode]) {
return payload[statusCode].liveRequest;
}
}
}
private extractResponse(specItem: any, payload: any) {
log.info("extractResponse");
const specResp = specItem.content.responses;
const longRunning: boolean = specItem.content["x-ms-long-running-operation"];
// below handled status code also should add in swaggerMocker.ts mockForExample() preHandledStatusCode array
if (longRunning && !("202" in specResp) && !("201" in specResp)) {
// console.warn('x-ms-long-running-operation is true, but no 202 or 201 response');
return {};
}
if (longRunning && !("200" in specResp || "204" in specResp)) {
// console.warn('x-ms-long-running-operation is true, but no 200 or 204 response');
}
if (!longRunning && ("202" in specResp || "201" in specResp)) {
// console.warn('x-ms-long-running-operation is not set true, but 202 or 201 response is provided');
return {};
}
const resp: any = {};
if (!longRunning && "200" in specResp) {
this.getResponseExample(specItem, payload, resp, "200", false);
}
if ("201" in specResp) {
this.getResponseExample(specItem, payload, resp, "201", "200" in specResp);
}
if ("202" in specResp) {
this.getResponseExample(specItem, payload, resp, "202", "200" in specResp);
}
if ("204" in specResp) {
resp["204"] = {};
}
return resp;
}
private getLongrunResp(specItem: any, payload: any) {
const payload200: any = payload[200];
if (!payload200 || !("liveResponse" in payload200)) {
// console.warn(`Payload doesn't have the response result for long running case`);
return {};
}
return {
body:
"schema" in specItem.content.responses["200"]
? this.translator.filterBodyContent(
payload200.liveResponse.body,
specItem.content.responses["200"].schema,
false
)
: undefined,
};
}
private getResponseExample(
specItem: any,
payloadGeneral: any,
resp: any,
statusCode: string,
getAsyncResp: boolean
) {
const payload: any = payloadGeneral[statusCode];
if (!payload || !("liveResponse" in payload)) {
// console.warn(`no payload recording for status code = ${statusCode}`);
resp[statusCode] = {};
} else {
resp[statusCode] = this.translator.extractResponse(
specItem,
payload.liveResponse,
statusCode
);
}
if (getAsyncResp) {
resp["200"] = this.getLongrunResp(specItem, payloadGeneral);
}
}
} | the_stack |
import { Context } from 'probot'
import { handlePullRequest } from '../src/handler'
describe('handlePullRequest', () => {
let event: any
let context: Context
beforeEach(async () => {
event = {
id: '123',
name: 'pull_request',
payload: {
action: 'opened',
number: '1',
pull_request: {
number: '1',
title: 'test',
user: {
login: 'pr-creator',
},
},
repository: {
name: 'auto-assign',
owner: {
login: 'kentaro-m',
},
},
},
draft: false,
}
context = new Context(event, {} as any, {} as any)
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: true,
numberOfReviewers: 0,
reviewers: ['reviewer1', 'reviewer2', 'reviewer3'],
skipKeywords: ['wip'],
}
})
context.log = jest.fn() as any
})
test('responds with the error if the configuration file failed to load', async () => {
try {
context.config = jest.fn().mockImplementation(async () => {})
await handlePullRequest(context)
} catch (error) {
expect(error).toEqual(new Error('the configuration file failed to load'))
}
})
test('exits the process if pull requests include skip words in the title', async () => {
const spy = jest.spyOn(context, 'log')
event.payload.pull_request.title = 'wip test'
await handlePullRequest(context)
expect(spy.mock.calls[0][0]).toEqual('skips adding reviewers')
})
test('skips drafts', async () => {
const spy = jest.spyOn(context, 'log')
event.payload.pull_request.draft = true
await handlePullRequest(context)
expect(spy.mock.calls[0][0]).toEqual('ignore draft PR')
})
test('adds reviewers to pull requests if the configuration is enabled, but no assignees', async () => {
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: false,
addReviewers: true,
numberOfReviewers: 0,
reviewers: ['reviewer1', 'reviewer2', 'reviewer3', 'pr-creator'],
skipKeywords: ['wip'],
}
})
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
await handlePullRequest(context)
expect(addAssigneesSpy).not.toBeCalled()
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers).toHaveLength(3)
expect(requestReviewersSpy.mock.calls[0][0]?.team_reviewers).toHaveLength(0)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[0]).toMatch(
/reviewer/
)
})
test('adds team_reviewers to pull requests if the configuration is enabled, but no assignees', async () => {
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: false,
addReviewers: true,
numberOfReviewers: 0,
reviewers: ['/team_reviewer1'],
skipKeywords: ['wip'],
}
})
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
await handlePullRequest(context)
expect(addAssigneesSpy).not.toBeCalled()
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers).toHaveLength(0)
expect(requestReviewersSpy.mock.calls[0][0]?.team_reviewers).toHaveLength(1)
expect(requestReviewersSpy.mock.calls[0][0]?.team_reviewers?.[0]).toMatch(
/team_reviewer/
)
})
test('adds pr-creator as assignee if addAssignees is set to author', async () => {
// MOCKS
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: 'author',
}
})
// WHEN
await handlePullRequest(context)
// THEN
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toHaveLength(1)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[0]).toMatch('pr-creator')
expect(requestReviewersSpy).not.toBeCalled()
})
test('responds with error if addAssignees is not set to boolean or author', async () => {
// MOCKS
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: 'test',
}
})
try {
await handlePullRequest(context)
} catch (error) {
expect(error).toEqual(
new Error(
"Error in configuration file to do with using addAssignees. Expected 'addAssignees' variable to be either boolean or 'author'"
)
)
}
})
test('adds reviewers to assignees to pull requests if the configuration is enabled ', async () => {
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: false,
numberOfReviewers: 0,
reviewers: ['reviewer1', 'reviewer2', 'reviewer3', 'pr-creator'],
skipKeywords: ['wip'],
}
})
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
await handlePullRequest(context)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toHaveLength(3)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[0]).toMatch(/reviewer/)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toEqual(
expect.arrayContaining(['reviewer1', 'reviewer2', 'reviewer3'])
)
expect(requestReviewersSpy).not.toBeCalled()
})
test('adds assignees to pull requests if the assigness are enabled explicitly', async () => {
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: false,
assignees: ['assignee1', 'pr-creator'],
numberOfAssignees: 2,
numberOfReviewers: 0,
reviewers: ['reviewer1', 'reviewer2', 'reviewer3'],
skipKeywords: ['wip'],
}
})
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
await handlePullRequest(context)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toHaveLength(1)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toEqual(
expect.arrayContaining(['assignee1'])
)
expect(requestReviewersSpy).not.toBeCalled()
})
test('adds assignees to pull requests using the numberOfReviewers when numberOfAssignees is unspecified', async () => {
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: true,
assignees: ['assignee1', 'assignee2', 'assignee3'],
numberOfReviewers: 2,
reviewers: ['reviewer1', 'reviewer2', 'reviewer3'],
skipKeywords: ['wip'],
}
})
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
await handlePullRequest(context)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toHaveLength(2)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[0]).toMatch(/assignee/)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers).toHaveLength(2)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[0]).toMatch(
/reviewer/
)
})
test("doesn't add assignees if the reviewers contain only a pr creator and assignees are not explicit", async () => {
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: true,
numberOfReviewers: 0,
reviewers: ['pr-creator'],
skipKeywords: ['wip'],
}
})
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
await handlePullRequest(context)
expect(addAssigneesSpy).not.toHaveBeenCalled()
expect(requestReviewersSpy).not.toHaveBeenCalled()
})
test('adds assignees to pull requests if throws error to add reviewers', async () => {
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: true,
assignees: ['maintainerX', 'maintainerY'],
numberOfReviewers: 0,
reviewers: ['reviewerA', 'reviewerB'],
skipKeywords: ['wip'],
}
})
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {
throw new Error('Review cannot be requested from pull request author.')
}),
} as any
const spy = jest.spyOn(context.octokit.issues, 'addAssignees')
await handlePullRequest(context)
expect(spy.mock.calls[0][0]?.assignees).toHaveLength(2)
expect(spy.mock.calls[0][0]?.assignees?.[0]).toMatch(/maintainer/)
})
test('adds reviewers to pull requests if throws error to add assignees', async () => {
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: true,
assignees: ['maintainerX', 'maintainerY'],
numberOfReviewers: 0,
reviewers: ['reviewerA', 'reviewerB'],
skipKeywords: ['wip'],
}
})
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {
throw new Error('failed to add assignees.')
}),
} as any
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const spy = jest.spyOn(context.octokit.pulls, 'requestReviewers')
await handlePullRequest(context)
expect(spy.mock.calls[0][0]?.reviewers).toHaveLength(2)
expect(spy.mock.calls[0][0]?.reviewers?.[0]).toMatch(/reviewer/)
})
/*
* If 'useReviewGroups' == true, then use the 'groups' object to select reviewers and assignees.
* The new functionality will still decide to add reviewers and assignees based on the 'addReviewers'
* and 'addAssignees' flags.
*
* Use Cases for group reviews:
* - if the groups are not present or an empty list, then use normal reviewer functionality
* - if 'addReviewers' == true
* - if #reviewers is 0, follow default behavior (add all users to review)
* - if #reviewers is > 0, select #reviewers randomly (exclude self) from each group
* + if #peopleInGroup is < #reviewers, select all people in that group to review
*
* - if 'addAssignees' == true
* - var assignees = #reviewers || #assignees
* - if assignees is 0, follow default behavior (add all users to review)
* - if assignees is > 0, select assignees randomly (exclude self) from each group
* - if #peopleInGroup is < assignees, select all people in that group to be assignees
*/
test('responds with the error if review groups are enabled, but no reviewGroups variable is defined in configuration', async () => {
try {
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
useReviewGroups: true,
}
})
// WHEN
await handlePullRequest(context)
} catch (error) {
// THEN
expect(error).toEqual(
new Error(
"Error in configuration file to do with using review groups. Expected 'reviewGroups' variable to be set because the variable 'useReviewGroups' = true."
)
)
}
})
test('responds with the error if assignee groups are enabled, but no assigneeGroups variable is defined in configuration', async () => {
try {
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
useAssigneeGroups: true,
}
})
// WHEN
await handlePullRequest(context)
} catch (error) {
// THEN
expect(error).toEqual(
new Error(
"Error in configuration file to do with using review groups. Expected 'assigneeGroups' variable to be set because the variable 'useAssigneeGroups' = true."
)
)
}
})
test('adds reviewers to pull request from reviewers if groups are enabled and empty', async () => {
// MOCKS
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: false,
addReviewers: true,
useReviewGroups: true,
numberOfReviewers: 1,
reviewers: ['reviewer1', 'reviewer2', 'reviewer3'],
reviewGroups: [],
}
})
// WHEN
await handlePullRequest(context)
// THEN
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers).toHaveLength(1)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[0]).toMatch(
/reviewer/
)
expect(addAssigneesSpy).not.toBeCalled()
})
test('adds reviewers to pull request from two different groups if review groups are enabled', async () => {
// MOCKS
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: false,
addReviewers: true,
useReviewGroups: true,
numberOfReviewers: 1,
reviewGroups: {
groupA: ['group1-user1', 'group1-user2', 'group1-user3'],
groupB: ['group2-user1', 'group2-user2', 'group2-user3'],
},
}
})
// WHEN
await handlePullRequest(context)
// THEN
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers).toHaveLength(2)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[0]).toMatch(
/group1/
)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[1]).toMatch(
/group2/
)
expect(addAssigneesSpy).not.toBeCalled()
})
test('adds all reviewers from a group that has less members than the number of reviews requested', async () => {
// MOCKS
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: false,
addReviewers: true,
useReviewGroups: true,
numberOfReviewers: 2,
reviewGroups: {
groupA: ['group1-user1', 'group1-user2', 'group1-user3'],
groupB: ['group2-user1'],
},
}
})
// WHEN
await handlePullRequest(context)
// THEN
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers).toHaveLength(3)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[0]).toMatch(
/group1/
)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[1]).toMatch(
/group1/
)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[2]).toMatch(
/group2-user1/
)
expect(addAssigneesSpy).not.toBeCalled()
})
test('adds assignees to pull request from two different groups if groups are enabled and number of assignees is specified', async () => {
// MOCKS
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: false,
useAssigneeGroups: true,
numberOfAssignees: 1,
numberOfReviewers: 2,
reviewers: ['reviewer1', 'reviewer2', 'reviewer3'],
assigneeGroups: {
groupA: ['group1-user1', 'group1-user2', 'group1-user3'],
groupB: ['group2-user1'],
groupC: ['group3-user1', 'group3-user2', 'group3-user3'],
},
}
})
// WHEN
await handlePullRequest(context)
// THEN
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toHaveLength(3)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[0]).toMatch(/group1/)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[1]).toMatch(/group2/)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[2]).toMatch(/group3/)
expect(requestReviewersSpy).not.toBeCalled()
})
test('adds assignees to pull request from two different groups using numberOfReviewers if groups are enabled and number of assignees is not specified', async () => {
// MOCKS
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: false,
useAssigneeGroups: true,
numberOfReviewers: 1,
reviewers: ['reviewer1', 'reviewer2', 'reviewer3'],
assigneeGroups: {
groupA: ['group1-user1', 'group1-user2', 'group1-user3'],
groupB: ['group2-user1'],
groupC: ['group3-user1', 'group3-user2', 'group3-user3'],
},
}
})
// WHEN
await handlePullRequest(context)
// THEN
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toHaveLength(3)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[0]).toMatch(/group1/)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[1]).toMatch(/group2/)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[2]).toMatch(/group3/)
expect(requestReviewersSpy).not.toBeCalled()
})
test('adds assignees to pull request from two different groups and reviewers are not specified', async () => {
// MOCKS
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: false,
useAssigneeGroups: true,
numberOfAssignees: 1,
numberOfReviewers: 2,
assigneeGroups: {
groupA: ['group1-user1', 'group1-user2', 'group1-user3'],
groupB: ['group2-user1'],
groupC: ['group3-user1', 'group3-user2', 'group3-user3'],
},
}
})
// WHEN
await handlePullRequest(context)
// THEN
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toHaveLength(3)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[0]).toMatch(/group1/)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[1]).toMatch(/group2/)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[2]).toMatch(/group3/)
expect(requestReviewersSpy).not.toBeCalled()
})
test('adds normal reviewers and assignees from groups into the pull request', async () => {
// MOCKS
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: true,
useAssigneeGroups: true,
numberOfAssignees: 1,
numberOfReviewers: 2,
reviewers: ['reviewer1', 'reviewer2', 'reviewer3'],
assigneeGroups: {
groupA: ['group1-user1', 'group1-user2', 'group1-user3'],
groupB: ['group2-user1'],
groupC: ['group3-user1', 'group3-user2', 'group3-user3'],
},
}
})
// WHEN
await handlePullRequest(context)
// THEN
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toHaveLength(3)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[0]).toMatch(/group1/)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[1]).toMatch(/group2/)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[2]).toMatch(/group3/)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers).toHaveLength(2)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[0]).toMatch(
/reviewer/
)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[1]).toMatch(
/reviewer/
)
})
test('adds normal assignees and reviewers from groups into the pull request', async () => {
// MOCKS
context.octokit.pulls = {
requestReviewers: jest.fn().mockImplementation(async () => {}),
} as any
const requestReviewersSpy = jest.spyOn(
context.octokit.pulls,
'requestReviewers'
)
context.octokit.issues = {
addAssignees: jest.fn().mockImplementation(async () => {}),
} as any
const addAssigneesSpy = jest.spyOn(context.octokit.issues, 'addAssignees')
// GIVEN
context.config = jest.fn().mockImplementation(async () => {
return {
addAssignees: true,
addReviewers: true,
useReviewGroups: true,
numberOfAssignees: 1,
numberOfReviewers: 2,
assignees: ['assignee1', 'assignee2', 'assignee3'],
reviewGroups: {
groupA: ['group1-reviewer1', 'group1-reviewer2', 'group1-reviewer3'],
groupB: ['group2-reviewer1'],
groupC: ['group3-reviewer1', 'group3-reviewer2', 'group3-reviewer3'],
},
}
})
// WHEN
await handlePullRequest(context)
// THEN
expect(addAssigneesSpy.mock.calls[0][0]?.assignees).toHaveLength(1)
expect(addAssigneesSpy.mock.calls[0][0]?.assignees?.[0]).toMatch(/assignee/)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers).toHaveLength(5)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[0]).toMatch(
/group1-reviewer/
)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[2]).toMatch(
/group2-reviewer/
)
expect(requestReviewersSpy.mock.calls[0][0]?.reviewers?.[3]).toMatch(
/group3-reviewer/
)
})
}) | the_stack |
import { from, merge, MonoTypeOperatorFunction, Observable, of, Subject, Subscription, throwError } from 'rxjs';
import { catchError, filter, map, mergeMap, retryWhen, share, takeUntil, tap, throwIfEmpty } from 'rxjs/operators';
import { fromFetch } from 'rxjs/fetch';
import { v4 as uuidv4 } from 'uuid';
import { BackendSrv as BackendService, BackendSrvRequest, FetchError, FetchResponse } from 'src/packages/datav-core/src/runtime';
import { AppEvents, config, DataQueryErrorType } from 'src/packages/datav-core/src/data';
import { DashboardSearchHit } from 'src/views/search/types';
import { DashboardDataDTO, DashboardDTO, FolderDTO, FolderInfo } from 'src/types';
import { ContextSrv, contextSrv } from '../context';
import { parseInitFromOptions, parseResponseBody, parseUrlFromOptions } from 'src/core/library/utils/fetch';
import { isDataQuery, isLocalUrl } from 'src/core/library/utils/query';
import { FetchQueue } from './fetch_queue';
import { ResponseQueue } from './response_queue';
import { FetchQueueWorker } from './fetch_queue_worker'
import { DataSourceResponse, ShowModalReactEvent } from 'src/types/events';
import appEvents from 'src/core/library/utils/app_events';
import { logout } from 'src/core/library/utils/user';
import { notification } from 'antd';
import { store } from 'src/store/store';
import localeAllData from 'src/core/library/locale'
import { getToken } from 'src/core/library/utils/auth';
const CANCEL_ALL_REQUESTS_REQUEST_ID = 'cancel_all_requests_request_id';
export interface BackendSrvDependencies {
fromFetch: (input: string | Request, init?: RequestInit) => Observable<Response>;
appEvents: typeof appEvents;
contextSrv: ContextSrv;
logout: () => void;
}
interface FetchResponseProps {
message?: string;
}
interface ErrorResponseProps extends FetchResponseProps {
status?: string;
error?: string | any;
}
interface ErrorResponse<T extends ErrorResponseProps = any> {
status: number;
statusText?: string;
isHandled?: boolean;
data: T | string;
cancelled?: boolean;
}
export class BackendSrv implements BackendService {
private inFlightRequests: Subject<string> = new Subject<string>();
private HTTP_REQUEST_CANCELED = -1;
private noBackendCache: boolean;
private inspectorStream: Subject<FetchResponse | FetchError> = new Subject<FetchResponse | FetchError>();
private readonly fetchQueue: FetchQueue;
private readonly responseQueue: ResponseQueue;
private dependencies: BackendSrvDependencies = {
fromFetch: fromFetch,
appEvents: appEvents,
contextSrv: contextSrv,
logout: () => {
},
};
constructor(deps?: BackendSrvDependencies) {
if (deps) {
this.dependencies = {
...this.dependencies,
...deps,
};
}
this.noBackendCache = false;
this.internalFetch = this.internalFetch.bind(this);
this.fetchQueue = new FetchQueue();
this.responseQueue = new ResponseQueue(this.fetchQueue, this.internalFetch);
new FetchQueueWorker(this.fetchQueue, this.responseQueue);
}
async request<T = any>(options: BackendSrvRequest): Promise<T> {
return this.fetch<T>(options)
.pipe(map((response: FetchResponse<T>) => response.data))
.toPromise();
}
fetch<T>(options: BackendSrvRequest): Observable<FetchResponse<T>> {
// We need to match an entry added to the queue stream with the entry that is eventually added to the response stream
const id = uuidv4();
const fetchQueue = this.fetchQueue;
return new Observable((observer) => {
// Subscription is an object that is returned whenever you subscribe to an Observable.
// You can also use it as a container of many subscriptions and when it is unsubscribed all subscriptions within are also unsubscribed.
const subscriptions: Subscription = new Subscription();
// We're using the subscriptions.add function to add the subscription implicitly returned by this.responseQueue.getResponses<T>(id).subscribe below.
subscriptions.add(
this.responseQueue.getResponses<T>(id).subscribe((result) => {
// The one liner below can seem magical if you're not accustomed to RxJs.
// Firstly, we're subscribing to the result from the result.observable and we're passing in the outer observer object.
// By passing the outer observer object then any updates on result.observable are passed through to any subscriber of the fetch<T> function.
// Secondly, we're adding the subscription implicitly returned by result.observable.subscribe(observer).
subscriptions.add(result.observable.subscribe(observer));
})
);
// Let the fetchQueue know that this id needs to start data fetching.
this.fetchQueue.add(id, options);
// This returned function will be called whenever the returned Observable from the fetch<T> function is unsubscribed/errored/completed/canceled.
return function unsubscribe() {
// Change status to Done moved here from ResponseQueue because this unsubscribe was called before the responseQueue produced a result
fetchQueue.setDone(id);
// When subscriptions is unsubscribed all the implicitly added subscriptions above are also unsubscribed.
subscriptions.unsubscribe();
};
});
}
private internalFetch<T>(options: BackendSrvRequest): Observable<FetchResponse<T>> {
if (options.requestId) {
this.inFlightRequests.next(options.requestId);
}
options = this.parseRequestOptions(options);
const fromFetchStream = this.getFromFetchStream(options);
const failureStream = fromFetchStream.pipe(this.toFailureStream(options));
const successStream = fromFetchStream.pipe(
filter((response) => response.ok === true),
// map(response => {
// // show response message
// if (response.data) {
// this.showMessage(response.data, 'info')
// }
// const fetchSuccessResponse = response.data;
// //
// return fetchSuccessResponse;
// }),
tap((response) => {
this.showSuccessAlert(response);
this.inspectorStream.next(response);
})
);
return merge(successStream, failureStream).pipe(
catchError((err: FetchError) => throwError(this.processRequestError(options, err))),
this.handleStreamCancellation(options)
);
}
resolveCancelerIfExists(requestId: string) {
this.inFlightRequests.next(requestId);
}
cancelAllInFlightRequests() {
this.inFlightRequests.next(CANCEL_ALL_REQUESTS_REQUEST_ID);
}
async datasourceRequest(options: BackendSrvRequest): Promise<any> {
return this.fetch(options).toPromise();
}
private parseRequestOptions = (options: BackendSrvRequest): BackendSrvRequest => {
options.retry = options.retry ?? 0;
const requestIsLocal = !options.url.match(/^http/);
if (requestIsLocal) {
if (options.url.startsWith('/')) {
options.url = options.url.substring(1);
}
if (options.url.endsWith('/')) {
options.url = options.url.slice(0, -1);
}
}
return options;
};
private getFromFetchStream = (options: BackendSrvRequest) => {
// add token to headers
options.headers === undefined ? options.headers = { 'X-Token': getToken() } : options.headers['X-Token'] = getToken()
let url = parseUrlFromOptions(options);
const requestIsLocal = !options.url.match(/^http/);
if (requestIsLocal) {
url = config.baseUrl + url
}
const init = parseInitFromOptions(options);
return this.dependencies.fromFetch(url, init).pipe(
mergeMap(async response => {
const { status, statusText, ok, headers, url, type, redirected } = response;
const textData = await response.text(); // this could be just a string, prometheus requests for instance
let data;
try {
data = JSON.parse(textData); // majority of the requests this will be something that can be parsed
} catch {
data = textData;
}
const fetchResponse: FetchResponse = {
status,
statusText,
ok,
data,
headers,
url,
type,
redirected,
config: options,
};
return fetchResponse;
}),
share() // sharing this so we can split into success and failure and then merge back
);
};
private toFailureStream = (options: BackendSrvRequest): MonoTypeOperatorFunction<FetchResponse> => inputStream =>
inputStream.pipe(
filter(response => response.ok === false),
mergeMap(response => {
const fetchErrorResponse = this.handleErrorResponse(response)
return throwError(fetchErrorResponse);
})
);
private handleErrorResponse(response: DataSourceResponse<any>): ErrorResponse {
const { status, statusText, data } = response;
this.showMessage(data, 'error')
const fetchErrorResponse: ErrorResponse = { status, statusText, data };
if (status === 401) { // need login
setTimeout(logout, 1000)
}
return fetchErrorResponse
}
private showMessage(data: any, level: string) {
if (!data.message) {
return
}
let msg = data.message;
if (data.i18n) {
const msgid = data.message
msg = this.getI18nMessage(msgid)
}
level === 'error' ? notification['error']({
message: "Error",
description: msg,
duration: 5
}) : notification['info']({
message: "Info",
description: msg,
duration: 5
});
}
private getI18nMessage(msgid: string): string {
const localeData = localeAllData[store.getState().application.locale]
if (!localeData) {
return 'Cant find data with language: ' + store.getState().application.locale
}
const content = localeData[msgid]
if (!content) {
return 'Cant find msg content with msgid: ' + msgid
}
return content
}
showApplicationErrorAlert(err: FetchError) { }
showSuccessAlert<T>(response: FetchResponse<T>) {
const { config } = response;
if (config.showSuccessAlert === false) {
return;
}
// is showSuccessAlert is undefined we only show alerts non GET request, non data query and local api requests
if (
config.showSuccessAlert === undefined &&
(config.method === 'GET' || isDataQuery(config.url) || !isLocalUrl(config.url))
) {
return;
}
const data: { message: string } = response.data as any;
if (data?.message) {
this.dependencies.appEvents.emit(AppEvents.alertSuccess, [data.message]);
}
}
showErrorAlert<T>(config: BackendSrvRequest, err: FetchError) {
if (config.showErrorAlert === false) {
return;
}
// is showErrorAlert is undefined we only show alerts non data query and local api requests
if (config.showErrorAlert === undefined && (isDataQuery(config.url) || !isLocalUrl(config.url))) {
return;
}
let description = '';
let message = err.data.message;
if (message.length > 80) {
description = message;
message = 'Error';
}
// Validation
if (err.status === 422) {
message = 'Validation failed';
}
this.dependencies.appEvents.emit(err.status < 500 ? AppEvents.alertWarning : AppEvents.alertError, [
message,
description,
]);
}
/**
* Processes FetchError to ensure "data" property is an object.
*
* @see DataQueryError.data
*/
processRequestError(options: BackendSrvRequest, err: FetchError): FetchError<{ message: string; error?: string }> {
err.data = err.data ?? { message: 'Unexpected error' };
if (typeof err.data === 'string') {
err.data = {
message: err.data,
error: err.statusText,
response: err.data,
};
}
// If no message but got error string, copy to message prop
if (err.data && !err.data.message && typeof err.data.error === 'string') {
err.data.message = err.data.error;
}
// check if we should show an error alert
if (err.data.message) {
setTimeout(() => {
if (!err.isHandled) {
this.showErrorAlert(options, err);
}
}, 50);
}
this.inspectorStream.next(err);
return err;
}
private handleStreamCancellation(options: BackendSrvRequest): MonoTypeOperatorFunction<FetchResponse<any>> {
return (inputStream) =>
inputStream.pipe(
takeUntil(
this.inFlightRequests.pipe(
filter((requestId) => {
let cancelRequest = false;
if (options && options.requestId && options.requestId === requestId) {
// when a new requestId is started it will be published to inFlightRequests
// if a previous long running request that hasn't finished yet has the same requestId
// we need to cancel that request
cancelRequest = true;
}
if (requestId === CANCEL_ALL_REQUESTS_REQUEST_ID) {
cancelRequest = true;
}
return cancelRequest;
})
)
),
// when a request is cancelled by takeUntil it will complete without emitting anything so we use throwIfEmpty to identify this case
// in throwIfEmpty we'll then throw an cancelled error and then we'll return the correct result in the catchError or rethrow
throwIfEmpty(() => ({
type: DataQueryErrorType.Cancelled,
cancelled: true,
data: null,
status: this.HTTP_REQUEST_CANCELED,
statusText: 'Request was aborted',
config: options,
}))
);
}
getInspectorStream(): Observable<FetchResponse<any> | FetchError> {
return this.inspectorStream;
}
async get<T = any>(url: string, params?: any, requestId?: string): Promise<T> {
return await this.request({ method: 'GET', url, params, requestId });
}
async delete(url: string) {
return await this.request({ method: 'DELETE', url });
}
async post(url: string, data?: any) {
return await this.request({ method: 'POST', url, data });
}
async patch(url: string, data: any) {
return await this.request({ method: 'PATCH', url, data });
}
async put(url: string, data: any) {
return await this.request({ method: 'PUT', url, data });
}
withNoBackendCache(callback: any) {
this.noBackendCache = true;
return callback().finally(() => {
this.noBackendCache = false;
});
}
loginPing() {
return this.request({ url: '/api/login/ping', method: 'GET', retry: 1 });
}
search(query: any){
return this.get('/api/search', query);
}
getDashboardByUid(uid: string) {
return this.get(`/api/dashboards/uid/${uid}`);
}
getFolderByUid(uid: string) {
return this.get<FolderDTO>(`/api/folders/${uid}`);
}
saveDashboard(
dashboard: DashboardDataDTO,
{ message = '', folderId, overwrite = false,fromTeam=0,alertChanged=false}: { message?: string; folderId?: number; overwrite?: boolean;fromTeam?:number;alertChanged?:boolean} = {}
) {
return this.post('/api/dashboard/save', {
dashboard,
folderId,
overwrite,
message,
fromTeam,
alertChanged
});
}
private createTask(fn: (...args: any[]) => Promise<any>, ignoreRejections: boolean, ...args: any[]) {
return async (result: any) => {
try {
const res = await fn(...args);
return Array.prototype.concat(result, [res]);
} catch (err) {
if (ignoreRejections) {
return result;
}
throw err;
}
};
}
private executeInOrder(tasks: any[]) {
return tasks.reduce((acc, task) => {
return Promise.resolve(acc).then(task);
}, []);
}
deleteFolder(uid: string, showSuccessAlert: boolean) {
return this.request({ method: 'DELETE', url: `/api/folders/${uid}`, showSuccessAlert: showSuccessAlert === true });
}
deleteDashboard(uid: string, showSuccessAlert: boolean) {
return this.request({
method: 'DELETE',
url: `/api/dashboard/uid/${uid}`,
showSuccessAlert: showSuccessAlert === true,
});
}
deleteFoldersAndDashboards(folderUids: string[], dashboardUids: string[]) {
const tasks = [];
for (const folderUid of folderUids) {
tasks.push(this.createTask(this.deleteFolder.bind(this), true, folderUid, true));
}
for (const dashboardUid of dashboardUids) {
tasks.push(this.createTask(this.deleteDashboard.bind(this), true, dashboardUid, true));
}
return this.executeInOrder(tasks);
}
moveDashboards(dashboardUids: string[], toFolder: FolderInfo) {
const tasks = [];
for (const uid of dashboardUids) {
tasks.push(this.createTask(this.moveDashboard.bind(this), true, uid, toFolder));
}
return this.executeInOrder(tasks).then((result: any) => {
return {
totalCount: result.length,
successCount: result.filter((res: any) => res.succeeded).length,
alreadyInFolderCount: result.filter((res: any) => res.alreadyInFolder).length,
};
});
}
private async moveDashboard(uid: string, toFolder: FolderInfo) {
const res = await this.getDashboardByUid(uid);
const fullDash: DashboardDTO = res.data
if ((!fullDash.meta.folderId && toFolder.id === 0) || fullDash.meta.folderId === toFolder.id) {
return { alreadyInFolder: true };
}
const clone = fullDash.dashboard;
const options = {
folderId: toFolder.id,
overwrite: false,
};
try {
await this.saveDashboard(clone, options);
return { succeeded: true };
} catch (err) {
if (err.data?.status !== 'plugin-dashboard') {
return { succeeded: false };
}
err.isHandled = true;
options.overwrite = true;
try {
await this.saveDashboard(clone, options);
return { succeeded: true };
} catch (e) {
return { succeeded: false };
}
}
}
}
// Used for testing and things that really need BackendSrv
export const backendSrv = new BackendSrv();
export const getBackendSrv = (): BackendSrv => backendSrv; | the_stack |
import {
AlterTableAddPrimaryKey,
AlterTableAddUnique,
} from '@vuerd/sql-ddl-parser';
import { getData, uuid } from '@/core/helper';
import {
SIZE_CANVAS_MAX,
SIZE_CANVAS_MIN,
SIZE_MIN_WIDTH,
} from '@/core/layout';
import {
AlterTableAddColumn,
AlterTableAddForeignKey,
AlterTableDropColumn,
AlterTableDropForeignKey,
Column,
CreateIndex,
CreateTable,
DropTable,
IndexColumn,
Statement,
} from '@/core/parser';
import { createCanvasState } from '@/engine/store/canvas.state';
import { createMemoState } from '@/engine/store/memo.state';
import { createRelationshipState } from '@/engine/store/relationship.state';
import { createTableState } from '@/engine/store/table.state';
import { Helper } from '@@types/core/helper';
import { ExportedStore } from '@@types/engine/store';
import { CanvasState, Database } from '@@types/engine/store/canvas.state';
import { MemoState } from '@@types/engine/store/memo.state';
import {
Column as PureColumn,
PureTable,
Table,
} from '@@types/engine/store/table.state';
interface Shape {
tables: CreateTable[];
indexes: CreateIndex[];
primaryKeys: AlterTableAddPrimaryKey[];
foreignKeys: AlterTableAddForeignKey[];
dropForeignKeys: AlterTableDropForeignKey[];
uniques: AlterTableAddUnique[];
addColumns: AlterTableAddColumn[];
dropColumns: AlterTableDropColumn[];
dropTable: DropTable[];
}
/**
* Sorts statements and adds them to shape
* @param statements List of statements
* @param shape (optional) Already existing shape that will just add new statements to itself
* @returns Shape with sorted statements
*/
function reshape(
statements: Statement[],
shape: Shape = {
tables: [],
indexes: [],
primaryKeys: [],
foreignKeys: [],
dropForeignKeys: [],
uniques: [],
addColumns: [],
dropColumns: [],
dropTable: [],
}
): Shape {
statements.forEach(statement => {
switch (statement.type) {
case 'create.table':
const table = statement;
const duplicateTable = findByName(shape.tables, table.name);
if (!duplicateTable && table.name) {
shape.tables.push(table);
}
break;
case 'create.index':
const index = statement;
const duplicateIndex = findByName(shape.indexes, index.name);
if (!duplicateIndex && index.tableName && index.columns.length) {
shape.indexes.push(index);
}
break;
case 'alter.table.add.primaryKey':
const primaryKey = statement;
const duplicatePK = findByName(shape.primaryKeys, primaryKey.name);
if (!duplicatePK && primaryKey.name && primaryKey.columnNames.length) {
shape.primaryKeys.push(primaryKey);
}
break;
case 'alter.table.add.foreignKey':
const foreignKey = statement;
const duplicateFK = findByConstraintName(
shape.foreignKeys,
foreignKey.constraintName
);
if (
!duplicateFK &&
foreignKey.name &&
foreignKey.columnNames.length &&
foreignKey.refTableName &&
foreignKey.refColumnNames.length &&
foreignKey.columnNames.length === foreignKey.refColumnNames.length
) {
shape.foreignKeys.push(foreignKey);
}
break;
case 'alter.table.add.unique':
const unique = statement;
const duplicateUnique = findByName(shape.uniques, unique.name);
if (!duplicateUnique && unique.name && unique.columnNames.length) {
shape.uniques.push(unique);
}
break;
case 'alter.table.add.column':
const addColumns = statement;
const duplicateAddColumns = findByName(
shape.addColumns,
addColumns.name
);
if (
!duplicateAddColumns &&
addColumns.name &&
addColumns.columns.length
) {
shape.addColumns.push(addColumns);
}
break;
case 'alter.table.drop.column':
const dropColumns = statement;
const duplicateDropColumns = findByName(
shape.dropColumns,
dropColumns.name
);
if (
!duplicateDropColumns &&
dropColumns.name &&
dropColumns.columns.length
) {
shape.dropColumns.push(dropColumns);
}
break;
case 'drop.table':
const dropTable = statement;
const duplicateDropTable = findByName(shape.dropTable, dropTable.name);
if (!duplicateDropTable && dropTable.name) {
shape.dropTable.push(dropTable);
}
break;
case 'alter.table.drop.foreignKey':
const dropForeignKey = statement;
const duplicateDropFK = findByName(
shape.dropForeignKeys,
dropForeignKey.name
);
if (
!duplicateDropFK &&
dropForeignKey.name &&
dropForeignKey.baseTableName
) {
shape.dropForeignKeys.push(dropForeignKey);
}
break;
}
});
return shape;
}
export function findByName<T extends { name: string }>(
list: T[],
name: string
): T | null {
for (const item of list) {
if (item.name.toUpperCase() === name.toUpperCase()) {
return item;
}
}
return null;
}
export function findByConstraintName<T extends { constraintName?: string }>(
list: T[],
constraintName?: string
): T | null {
if (!constraintName) return null;
for (const item of list) {
if (item.constraintName?.toUpperCase() === constraintName?.toUpperCase()) {
return item;
}
}
return null;
}
/**
* Adds all statements to CreateTable[]
* @param shape Shape with all statements
* @returns Final list of CreateTable[]
*/
function mergeTable(shape: Shape): CreateTable[] {
const {
indexes,
primaryKeys,
foreignKeys,
uniques,
addColumns,
dropColumns,
dropForeignKeys,
dropTable,
} = shape;
var { tables } = shape;
indexes.forEach(index => {
const table = findByName(tables, index.tableName);
if (table) {
table.indexes.push({
name: index.name,
unique: index.unique,
columns: index.columns,
id: index.id,
});
}
});
primaryKeys.forEach(primaryKey => {
const table = findByName(tables, primaryKey.name);
if (table) {
primaryKey.columnNames.forEach(columnName => {
const column = findByName(table.columns, columnName);
if (column) {
column.primaryKey = true;
}
});
}
});
uniques.forEach(unique => {
const table = findByName(tables, unique.name);
if (table) {
unique.columnNames.forEach(columnName => {
const column = findByName(table.columns, columnName);
if (column) {
column.unique = true;
}
});
}
});
foreignKeys.forEach(foreignKey => {
const table = findByName(tables, foreignKey.name);
if (table) {
table.foreignKeys.push({
columnNames: foreignKey.columnNames,
refTableName: foreignKey.refTableName,
refColumnNames: foreignKey.refColumnNames,
constraintName: foreignKey.constraintName,
visible: foreignKey.visible,
id: foreignKey.id,
});
}
});
addColumns.forEach(addColumn => {
const table = findByName(tables, addColumn.name);
if (table) {
addColumn.columns.forEach(column => {
const duplicateColumn = findByName(table.columns, column.name);
if (!duplicateColumn) {
table.columns.push(column);
}
});
}
});
dropColumns.forEach(dropColumn => {
const table = findByName(tables, dropColumn.name);
if (table) {
dropColumn.columns.forEach(columnToDrop => {
table.columns = table.columns.filter(
column => columnToDrop.name !== column.name
);
});
}
});
dropTable.forEach(dropTable => {
tables = tables.filter(table => table.name !== dropTable.name);
});
dropForeignKeys.forEach(dropForeignKey => {
const table = findByName(tables, dropForeignKey.baseTableName);
if (table) {
table.foreignKeys = table.foreignKeys.filter(
fk => fk.constraintName !== dropForeignKey.name
);
}
});
return tables;
}
/**
* Converts latest snapshot to shape, so there can be added more new statements
* @param snaphot Latest snapshot
* @returns Shape with all statements needed to replicate latest snapshot
*/
function snapshotToShape({ table, relationship }: ExportedStore): Shape {
const shape: Shape = {
tables: [],
indexes: [],
primaryKeys: [],
foreignKeys: [],
dropForeignKeys: [],
uniques: [],
addColumns: [],
dropColumns: [],
dropTable: [],
};
shape.tables.push(
...table.tables.map(table => {
const columns: Column[] = table.columns.map(column => {
return {
name: column.name,
dataType: column.dataType,
default: column.default,
comment: column.comment,
primaryKey: column.option.primaryKey,
autoIncrement: column.option.autoIncrement,
unique: column.option.unique,
nullable: !column.option.notNull,
id: column.id,
};
});
var createTable: CreateTable = {
type: 'create.table',
id: table.id,
columns: columns,
comment: table.comment,
foreignKeys: [],
indexes: [],
name: table.name,
visible: table.visible,
};
return createTable;
})
);
shape.indexes.push(
...table.indexes.map(index => {
const indexedTable = getData(table.tables, index.tableId);
const indexedColumns: IndexColumn[] = [];
if (indexedTable) {
index.columns.forEach(col => {
const column = getData(indexedTable.columns, col.id);
if (column)
indexedColumns.push({ name: column.name, sort: col.orderType });
});
}
var createIndex: CreateIndex = {
type: 'create.index',
id: index.id,
name: index.name,
unique: index.unique,
tableName: indexedTable?.name || '',
columns: indexedColumns,
};
return createIndex;
})
);
shape.foreignKeys.push(
...relationship.relationships.map(relationship => {
const baseTable = getData(table.tables, relationship.end.tableId);
const baseColumnNames = relationship.end.columnIds.map(colId => {
return getData(baseTable?.columns || [], colId)?.name || '';
});
const refTable = getData(table.tables, relationship.start.tableId);
const refColumnNames = relationship.start.columnIds.map(colId => {
return getData(refTable?.columns || [], colId)?.name || '';
});
const fk: AlterTableAddForeignKey = {
type: 'alter.table.add.foreignKey',
id: relationship.id,
name: baseTable?.name || '',
columnNames: baseColumnNames,
refTableName: refTable?.name || '',
refColumnNames: refColumnNames,
constraintName: relationship.constraintName ?? '',
visible: relationship.visible,
};
return fk;
})
);
return shape;
}
export function createJsonFormat(
canvasSize: number,
database: Database,
originalCanvas?: CanvasState,
originalMemo?: MemoState
): ExportedStore {
const canvas: CanvasState = createCanvasState();
canvas.width = canvasSize;
canvas.height = canvasSize;
canvas.database = database;
return {
canvas: originalCanvas ? originalCanvas : canvas,
table: createTableState(),
memo: originalMemo ? originalMemo : createMemoState(),
relationship: createRelationshipState(),
};
}
export function createJson(
statements: Statement[],
helper: Helper,
database: Database,
snapshot?: ExportedStore
): string {
var shape: Shape;
if (snapshot) {
shape = snapshotToShape(snapshot);
shape = reshape(statements, shape);
} else {
shape = reshape(statements);
}
const tables: CreateTable[] = mergeTable(shape);
let canvasSize = tables.length * 100;
if (canvasSize < SIZE_CANVAS_MIN) {
canvasSize = SIZE_CANVAS_MIN;
}
if (canvasSize > SIZE_CANVAS_MAX) {
canvasSize = SIZE_CANVAS_MAX;
}
var store: ExportedStore;
if (snapshot) {
store = createJsonFormat(
canvasSize,
database,
snapshot.canvas,
snapshot.memo
);
} else {
store = createJsonFormat(canvasSize, database);
}
tables.forEach(table => {
store.table.tables.push(createTable(helper, table, snapshot?.table.tables));
});
createRelationship(store, tables);
createIndex(store, tables);
return JSON.stringify(store);
}
function createTable(
helper: Helper,
table: CreateTable,
snapTables?: Table[]
): any {
const originalTable = findByName(snapTables || [], table.name);
const newTable: PureTable = {
id: table.id || uuid(),
name: table.name,
comment: table.comment,
columns: [],
ui: originalTable
? originalTable.ui
: {
active: false,
top: 0,
left: 0,
widthName: SIZE_MIN_WIDTH,
widthComment: SIZE_MIN_WIDTH,
zIndex: 2,
},
visible: table.visible === undefined ? true : table.visible,
};
const widthName = helper.getFastTextWidth(newTable.name);
if (SIZE_MIN_WIDTH < widthName) {
newTable.ui.widthName = widthName;
}
const widthComment = helper.getFastTextWidth(newTable.comment);
if (SIZE_MIN_WIDTH < widthComment) {
newTable.ui.widthComment = widthComment;
}
table.columns.forEach(column => {
newTable.columns.push(createColumn(helper, column));
});
return newTable;
}
export function createColumn(helper: Helper, column: Column): any {
const newColumn: PureColumn = {
id: column.id || uuid(),
name: column.name,
comment: column.comment,
dataType: column.dataType,
default: column.default,
option: {
autoIncrement: column.autoIncrement,
primaryKey: column.primaryKey,
unique: column.unique,
notNull: !column.nullable,
},
ui: {
active: false,
pk: column.primaryKey,
fk: false,
pfk: false,
widthName: SIZE_MIN_WIDTH,
widthComment: SIZE_MIN_WIDTH,
widthDataType: SIZE_MIN_WIDTH,
widthDefault: SIZE_MIN_WIDTH,
},
};
const widthName = helper.getFastTextWidth(newColumn.name);
if (SIZE_MIN_WIDTH < widthName) {
newColumn.ui.widthName = widthName;
}
const widthComment = helper.getFastTextWidth(newColumn.comment);
if (SIZE_MIN_WIDTH < widthComment) {
newColumn.ui.widthComment = widthComment;
}
const widthDataType = helper.getFastTextWidth(newColumn.dataType);
if (SIZE_MIN_WIDTH < widthDataType) {
newColumn.ui.widthDataType = widthDataType;
}
const widthDefault = helper.getFastTextWidth(newColumn.default);
if (SIZE_MIN_WIDTH < widthDefault) {
newColumn.ui.widthDefault = widthDefault;
}
return newColumn;
}
function createRelationship(data: ExportedStore, tables: CreateTable[]) {
tables.forEach(table => {
if (table.foreignKeys) {
const endTable = findByName(data.table.tables, table.name);
if (endTable) {
table.foreignKeys.forEach(foreignKey => {
const startTable = findByName(
data.table.tables,
foreignKey.refTableName
);
if (startTable) {
const startColumns: any[] = [];
const endColumns: any[] = [];
foreignKey.refColumnNames.forEach(refColumnName => {
const column = findByName(startTable.columns, refColumnName);
if (column) {
startColumns.push(column);
}
});
foreignKey.columnNames.forEach(columnName => {
const column = findByName(endTable.columns, columnName);
if (column) {
endColumns.push(column);
if (column.ui.pk) {
column.ui.pk = false;
column.ui.pfk = true;
} else {
column.ui.fk = true;
}
}
});
if (startTable.visible && endTable.visible) {
foreignKey.visible = true;
} else {
foreignKey.visible = false;
}
data.relationship.relationships.push({
id: foreignKey.id || uuid(),
identification: !endColumns.some(column => !column.ui.pfk),
relationshipType: 'ZeroOneN',
start: {
tableId: startTable.id,
columnIds: startColumns.map(column => column.id),
x: 0,
y: 0,
direction: 'top',
},
end: {
tableId: endTable.id,
columnIds: endColumns.map(column => column.id),
x: 0,
y: 0,
direction: 'top',
},
constraintName: foreignKey.constraintName,
visible: foreignKey.visible,
});
}
});
}
}
});
}
function createIndex(data: ExportedStore, tables: CreateTable[]) {
tables.forEach(table => {
if (table.indexes) {
table.indexes.forEach(index => {
const targetTable = findByName(data.table.tables, table.name);
if (targetTable) {
const indexColumns: any[] = [];
index.columns.forEach(column => {
const targetColumn = findByName(targetTable.columns, column.name);
if (targetColumn) {
indexColumns.push({
id: targetColumn.id,
orderType: column.sort,
});
}
});
if (indexColumns.length !== 0) {
data.table.indexes.push({
id: index.id || uuid(),
name: index.name,
tableId: targetTable.id,
columns: indexColumns,
unique: index.unique,
});
}
}
});
}
});
} | the_stack |
import '@pnp/polyfill-ie11';
import { sp, SPBatch, IAttachmentFileInfo, IRenderListDataParameters } from '@pnp/sp/presets/all';
import { BaseService } from './base.service';
import { LogHelper, ContentTypes, ListTitles, StandardFields, PostFields, ReplyFields, QuestionFields, ShowQuestionsOption, DiscussionType } from 'utilities';
import { IQuestionItem, IPostItem, IReplyItem, ICurrentUser, IQuestionsFilter, IPagedItems, IFileAttachment, IItemInfo, ICategoryLabelItem } from 'models';
import * as strings from 'QuestionsWebPartStrings';
export class QuestionService extends BaseService {
// private currentUser: ICurrentUser;
private listTitle = ListTitles.QUESTIONS;
private questionSelectColumns: string[] = [
StandardFields.ID,
StandardFields.TITLE,
PostFields.DETAILS,
PostFields.DETAILSTEXT,
QuestionFields.ISANSWERED,
QuestionFields.FOLLOW_EMAILS,
PostFields.PAGE,
PostFields.LIKE_COUNT,
PostFields.LIKE_IDS,
// Category and Type
PostFields.CATEGORY,
PostFields.TYPE,
// Standard Created/Modified Columns
StandardFields.CREATED,
StandardFields.MODIFIED,
StandardFields.AUTHOR_ID,
StandardFields.AUTHOR_NAME,
StandardFields.AUTHOR_TITLE,
StandardFields.EDITOR_ID,
StandardFields.EDITOR_NAME,
StandardFields.EDITOR_TITLE
];
private replySelectColumns: string[] = [
StandardFields.ID,
StandardFields.TITLE,
PostFields.DETAILS,
PostFields.DETAILSTEXT,
ReplyFields.ISANSWER,
PostFields.LIKE_COUNT,
PostFields.LIKE_IDS,
ReplyFields.HELPFULCOUNT,
ReplyFields.HELPFULIDS,
// question this item is related to
ReplyFields.QUESTIONLOOKUP_ID,
ReplyFields.QUESTIONLOOKUP_TITLE,
// parent of this item
ReplyFields.REPLYLOOKUP_ID,
ReplyFields.REPLYLOOKUP_TITLE,
// Standard Created/Modified Columns
StandardFields.CREATED,
StandardFields.MODIFIED,
StandardFields.AUTHOR_ID,
StandardFields.AUTHOR_NAME,
StandardFields.AUTHOR_TITLE,
StandardFields.EDITOR_ID,
StandardFields.EDITOR_NAME,
StandardFields.EDITOR_TITLE
];
private itemSelectColumns: string[] = [
StandardFields.ID,
StandardFields.TITLE,
PostFields.TYPE,
// question this item is related to
ReplyFields.QUESTIONLOOKUP_ID,
ReplyFields.QUESTIONLOOKUP_TITLE,
// parent of this item
ReplyFields.REPLYLOOKUP_ID,
ReplyFields.REPLYLOOKUP_TITLE,
];
private questionExpandColumns: string[] = [
StandardFields.CONTENTTYPE,
StandardFields.AUTHOR,
StandardFields.EDITOR
];
private replyExpandColumns: string[] = [
ReplyFields.QUESTIONLOOKUP,
ReplyFields.REPLYLOOKUP,
StandardFields.CONTENTTYPE,
StandardFields.AUTHOR,
StandardFields.EDITOR
];
private itemExpandColumns: string[] = [
ReplyFields.QUESTIONLOOKUP,
ReplyFields.REPLYLOOKUP
];
public async getPagedQuestions(currentUser: ICurrentUser, filter: IQuestionsFilter, previousPagedItems: IPagedItems<IQuestionItem>): Promise<IPagedItems<IQuestionItem>> {
LogHelper.verbose(this.constructor.name, 'getPagedQuestions2', `[filter=${JSON.stringify(filter)}]`);
let pagedItems: IPagedItems<IQuestionItem> = {
items: [],
nextHref: undefined
};
let parameters = this.getQuestionFilterParameters(filter);
if (previousPagedItems !== null && previousPagedItems.nextHref) {
parameters.Paging = previousPagedItems.nextHref.split('?')[1];
}
let data = await sp.web.lists.getByTitle(this.listTitle).renderListDataAsStream(parameters);
pagedItems.nextHref = data.NextHref;
for (let questionItem of data.Row) {
let question = this.mapQuestion(questionItem, currentUser, true);
let currentUserCreatedQuestion: boolean = false;
if (currentUser.loginName.toLowerCase() === question.author!.id!.toLowerCase()) {
currentUserCreatedQuestion = true;
}
this.updateUserPermissions(currentUser, question, currentUserCreatedQuestion);
pagedItems.items.push(question);
}
return pagedItems;
}
public async getQuestionById(currentUser: ICurrentUser, id: number, skipReplies: boolean = false): Promise<IQuestionItem | null> {
LogHelper.verbose(this.constructor.name, 'getQuestionById', `[id:${id}]`);
let questionItem = await sp.web.lists.getByTitle(this.listTitle).items
.getById(id)
.select(this.questionSelectColumns.join(','))
.expand(this.questionExpandColumns.join(','))
.get()
.catch(e => {
super.handleHttpError('getQuestionById', e);
throw e;
});
if (questionItem !== null) {
let question: IQuestionItem = this.mapQuestion(questionItem, currentUser);
if (skipReplies === false) {
let flatReplies = await this.getFlatRepliesByQuestionId(currentUser, id);
question.replies = this.buildReplyTree(flatReplies, [], null, true);
question.totalReplyCount = flatReplies.length;
if (question.isAnswered === true) {
question.answerReply = flatReplies.find(r => r.isAnswer === true);
}
if(question.id) {
question.attachments = await this.getAttachmentsForItem(question.id);
}
}
let currentUserCreatedQuestion: boolean = false;
if (currentUser.loginName.toLowerCase() === question.author!.id!.toLowerCase()) {
currentUserCreatedQuestion = true;
}
this.updateUserPermissions(currentUser, question, currentUserCreatedQuestion);
return question;
}
else {
return null;
}
}
public async getAllCategories(): Promise<ICategoryLabelItem[] | null> {
LogHelper.verbose(this.constructor.name, 'getAllCategories', "");
let all = await sp.web.lists.getByTitle(ListTitles.CATEGORY_LABELING).items
.orderBy("Title", true)
.get()
.catch(e => {
super.handleHttpError('getAllCategories', e);
throw e;
});
return all.map((item: any) => {
return this.mapCategoryLabel(item);
});
}
public async addCategory(category: string): Promise<void> {
LogHelper.verbose(this.constructor.name, 'addCategory', "");
await sp.web.lists.getByTitle(ListTitles.CATEGORY_LABELING).items
.add({ Title: category })
.then((iar: any) => {
LogHelper.verbose(this.constructor.name, 'addCategory', iar);
})
.catch(e => {
super.handleHttpError('addCategory', e);
throw e;
});
}
public async getItemInfoById(id: number): Promise<IItemInfo | null> {
LogHelper.verbose(this.constructor.name, 'getItemInfoById', `[id:${id}]`);
let item = await sp.web.lists.getByTitle(this.listTitle).items
.getById(id)
.select(this.itemSelectColumns.join(','))
.expand(this.itemExpandColumns.join(','))
.get()
.catch(e => {
super.handleHttpError('getItemInfoById', e);
throw e;
});
if (item !== null) {
return this.mapItemInfo(item);
}
else {
return null;
}
}
public async isDuplicateQuestion(question: IQuestionItem): Promise<boolean> {
LogHelper.verbose(this.constructor.name, 'isDuplicate', `[title:${question.title}]`);
let isDuplicate: boolean = false;
let cleanedTitle = question.title!.replace(/'/g, "''"); // the ' isn't encoded
let encodedTitle = encodeURIComponent(cleanedTitle); // encode all other characters
let filterText = `${StandardFields.TITLE} eq '${encodedTitle}'`;
let items = await sp.web.lists.getByTitle(this.listTitle).items
.select(StandardFields.ID)
.filter(filterText)
.get()
.catch(e => {
super.handleHttpError('isDuplicate', e);
throw e;
});
if (items !== null) {
for (let item of items) {
if (question.id != null && question.id !== 0) {
if (question.id !== item[StandardFields.ID]) {
// this is an update but matches an existing item
isDuplicate = true;
break;
}
}
else {
// this must be new but matches an existing item
isDuplicate = true;
break;
}
}
}
return isDuplicate;
}
public async deleteQuestion(question: IQuestionItem): Promise<void> {
await this.deletePostById(question.id!);
await this.deleteReplies(question);
}
public async deleteReply(reply: IReplyItem): Promise<void> {
await this.deletePostById(reply.id!);
await this.deleteReplies(reply);
}
private async deleteReplies(item: IReplyItem | IQuestionItem, batch?: SPBatch) {
if (!batch) { batch = sp.createBatch(); }
for (let reply of item.replies) {
sp.web.lists.getByTitle(this.listTitle).items
.getById(reply.id!)
.inBatch(batch)
.delete();
await this.deleteReplies(reply);
}
await batch.execute()
.catch(e => {
super.handleHttpError('deleteReplies', e);
throw e;
});
}
private async deletePostById(id: number): Promise<void> {
LogHelper.verbose(this.constructor.name, 'deletePostById', `id:[${id}]`);
if (id != null && id !== 0) {
await sp.web.lists.getByTitle(this.listTitle).items
.getById(id)
.delete()
.catch(e => {
super.handleHttpError('deletePostById', e);
throw e;
});
}
}
public async saveQuestion(question: IQuestionItem): Promise<number | null> {
let itemId = 0;
let item = {};
item[StandardFields.TITLE] = question.title;
item[PostFields.DETAILS] = question.details;
item[PostFields.DETAILSTEXT] = question.detailsText;
item[PostFields.CATEGORY] = question.category;
let contentType = await sp.web.lists.getByTitle(this.listTitle).contentTypes
.filter(`Name eq '${ContentTypes.QUESTION}'`)
.get()
.catch(e => {
super.handleHttpError('saveQuestion', e);
throw e;
});
item[StandardFields.CONTENTTYPEID] = contentType[0].StringId;
//Decision for UPDATE or ADD
if (question.id != null && question.id !== 0) {
//UPDATE
LogHelper.verbose(this.constructor.name, 'saveQuestion', `update [id:${question.id}]`);
let result: any = await sp.web.lists.getByTitle(this.listTitle).items
.getById(question.id)
.update(item)
.catch(e => {
super.handleHttpError('saveQuestion', e);
throw new Error(question.discussionType === DiscussionType.Question ? strings.ErrorMessage_QuestionUpdate : strings.ErrorMessage_ConversationUpdate);
});
if (!result) {
return null;
}
itemId = question.id;
}
else {
//ADD
LogHelper.verbose(this.constructor.name, 'saveQuestion', `add`);
item[PostFields.PAGE] = { Url: question.page };
item[QuestionFields.FOLLOW_EMAILS] = question.followEmails.join(';');
item[PostFields.TYPE] = question.discussionType;
let result: any = await sp.web.lists.getByTitle(this.listTitle).items
.add(item)
.catch(e => {
super.handleHttpError('saveQuestion', e);
throw new Error(question.discussionType === DiscussionType.Question ? strings.ErrorMessage_QuestionAdd : strings.ErrorMessage_ConversationAdd);
});
if (!result) {
return null;
}
itemId = result.data.Id;
}
if(question.removedAttachments && question.removedAttachments.length > 0) {
await this.deleteAttachmentsFromItem(itemId, question.removedAttachments);
}
if(question.newAttachments && question.newAttachments.length > 0) {
await this.addAttachmentsToItem(itemId, question.newAttachments);
}
return itemId;
}
public async getReplyById(currentUser: ICurrentUser, id: number, skipReplies: boolean = false): Promise<IReplyItem | null> {
LogHelper.verbose(this.constructor.name, 'getReplyById', `[id:${id}]`);
let replyItem = await sp.web.lists.getByTitle(this.listTitle).items
.getById(id)
.select(this.replySelectColumns.join(','))
.expand(this.replyExpandColumns.join(','))
.get()
.catch(e => {
super.handleHttpError('getReplyById', e);
throw e;
});
if (replyItem !== null) {
let reply: IReplyItem = this.mapReply(replyItem, currentUser);
if (skipReplies === false) {
let flatReplies = await this.getFlatRepliesByQuestionId(currentUser, reply.parentQuestionId!);
reply.replies = this.buildReplyTree(flatReplies, [], reply, true);
}
if(reply.id) {
reply.attachments = await this.getAttachmentsForItem(reply.id);
}
let currentUserCreatedQuestion: boolean = false;
if (reply.parentQuestionId) {
let question = await this.getQuestionById(currentUser, reply.parentQuestionId!, true);
if (question && currentUser.loginName.toLowerCase() === question.author!.id!.toLowerCase()) {
currentUserCreatedQuestion = true;
}
}
this.updateUserPermissions(currentUser, reply, currentUserCreatedQuestion);
return reply;
}
else {
return null;
}
}
public async saveReply(reply: IReplyItem): Promise<number | null> {
let itemId = 0;
let item = {};
item[StandardFields.TITLE] = reply.title;
item[PostFields.DETAILS] = reply.details;
item[PostFields.DETAILSTEXT] = reply.detailsText;
item[ReplyFields.ISANSWER] = reply.isAnswer ? reply.isAnswer : false;
item[ReplyFields.QUESTIONLOOKUPID] = reply.parentQuestionId;
item[ReplyFields.REPLYLOOKUPID] = reply.parentReplyId;
let contentType = await sp.web.lists.getByTitle(this.listTitle).contentTypes
.filter(`Name eq '${ContentTypes.REPLY}'`)
.get()
.catch(e => {
super.handleHttpError('saveReply', e);
throw e;
});
item[StandardFields.CONTENTTYPEID] = contentType[0].StringId;
if (reply.id != null && reply.id !== 0) {
LogHelper.verbose(this.constructor.name, 'saveReply', `update [id:${reply.id}]`);
let result: any = await sp.web.lists.getByTitle(this.listTitle).items
.getById(reply.id)
.update(item)
.catch(e => {
super.handleHttpError('saveReply', e);
throw e;
});
if (!result) {
return null;
}
itemId = reply.id;
}
else {
LogHelper.verbose(this.constructor.name, 'saveReply', `add`);
let result: any = await sp.web.lists.getByTitle(this.listTitle).items
.add(item)
.catch(e => {
super.handleHttpError('saveReply', e);
throw e;
});
if (!result) {
return null;
}
itemId = result.data.Id;
}
if(reply.removedAttachments && reply.removedAttachments.length > 0) {
await this.deleteAttachmentsFromItem(itemId, reply.removedAttachments);
}
if(reply.newAttachments && reply.newAttachments.length > 0) {
await this.addAttachmentsToItem(itemId, reply.newAttachments);
}
return itemId;
}
public async getAttachmentsForItem(id: number): Promise<IFileAttachment[]> {
LogHelper.verbose(this.constructor.name, 'getAttachmentsForItem', `[id:${id}]`);
let attachments = await sp.web.lists.getByTitle(this.listTitle).items
.getById(id)
.attachmentFiles()
.catch(e => {
super.handleHttpError('getAttachmentsForItem', e);
throw e;
});
let fileAttachments: IFileAttachment[] = [];
for(let attachment of attachments) {
fileAttachments.push( {
fileName: attachment.FileName,
serverRelativeUrl: attachment.ServerRelativeUrl,
isAttached: true
});
}
return fileAttachments;
}
public async addAttachmentsToItem(id: number, attachments: File[]): Promise<void> {
LogHelper.verbose(this.constructor.name, 'addAttachmentsToItem', `[id:${id},attachmentsCount:${attachments.length}]`);
if(attachments && attachments.length > 0) {
let fileInfos: IAttachmentFileInfo[] = [];
attachments.map(attachment => {
fileInfos.push({
name: encodeURIComponent(attachment.name),
content: attachment
});
});
await sp.web.lists.getByTitle(this.listTitle).items
.getById(id)
.attachmentFiles
.addMultiple(fileInfos)
.catch(e => {
super.handleHttpError('addAttachmentsToItem', e);
throw new Error(strings.ErrorMessage_AttachmentsAdd);
});
}
}
public async deleteAttachmentsFromItem(id: number, attachmentNames: string[]): Promise<void> {
LogHelper.verbose(this.constructor.name, 'deleteAttachmentsFromItem', `[id:${id},attachmentNames:${attachmentNames.join(",")}]`);
if(attachmentNames && attachmentNames.length > 0) {
attachmentNames = attachmentNames.map(a => encodeURIComponent(a));
await sp.web.lists.getByTitle(this.listTitle).items
.getById(id)
.attachmentFiles
.deleteMultiple(...attachmentNames)
.catch(e => {
super.handleHttpError('deleteAttachmentsFromItem', e);
throw new Error(strings.ErrorMessage_AttachmentsRemove);
});
}
}
public async markAnswer(reply: IReplyItem): Promise<void> {
if (reply !== null && reply.id != null && reply.id !== 0) {
LogHelper.verbose(this.constructor.name, 'markAnswer', `update [id:${reply.id}]`);
let replyItem = {};
replyItem[ReplyFields.ISANSWER] = reply.isAnswer;
await sp.web.lists.getByTitle(this.listTitle).items
.getById(reply.id)
.update(replyItem, '*')
.catch(e => {
super.handleHttpError('markAnswer', e);
throw e;
});
let questionItem = {};
questionItem[QuestionFields.ISANSWERED] = reply.isAnswer;
await sp.web.lists.getByTitle(this.listTitle).items
.getById(reply.parentQuestionId!)
.update(questionItem, '*')
.catch(e => {
super.handleHttpError('markAnswer', e);
throw e;
});
}
}
public async updateLiked(post: IPostItem): Promise<void> {
let item = {};
if (post.id != null && post.id !== 0) {
item[PostFields.LIKE_IDS] = post.likeIds.join(';');
item[PostFields.LIKE_COUNT] = post.likeIds.length;
LogHelper.verbose(this.constructor.name, 'updateLiked', `update [id:${post.id}]`);
await sp.web.lists.getByTitle(this.listTitle).items
.getById(post.id)
.update(item)
.catch(e => {
super.handleHttpError('updateLiked', e);
throw e;
});
}
}
public async updateFollowed(question: IQuestionItem): Promise<void> {
let item = {};
if (question.id != null && question.id !== 0) {
item[QuestionFields.FOLLOW_EMAILS] = question.followEmails.join(';');
LogHelper.verbose(this.constructor.name, 'updateFollowed', `update [id:${question.id}]`);
await sp.web.lists.getByTitle(this.listTitle).items
.getById(question.id)
.update(item)
.catch(e => {
super.handleHttpError('updateFollowed', e);
throw e;
});
}
}
public async updateDiscussionType(question: IQuestionItem): Promise<void> {
let item = {};
if (question.id != null && question.id !== 0) {
item[QuestionFields.DISCUSSION_TYPE] = question.discussionType;
LogHelper.verbose(this.constructor.name, 'updateDiscussionType', `update [id:${question.id}]`);
await sp.web.lists.getByTitle(this.listTitle).items
.getById(question.id)
.update(item)
.catch(e => {
super.handleHttpError('updateDiscussionType', e);
throw e;
});
}
}
public async updateHelpful(updateItem: IReplyItem): Promise<void> {
let item = {};
if (updateItem.id != null && updateItem.id !== 0) {
item[ReplyFields.HELPFULIDS] = updateItem.helpfulIds.join(';');
item[ReplyFields.HELPFULCOUNT] = updateItem.helpfulIds.length;
LogHelper.verbose(this.constructor.name, 'updateHelpful', `update [id:${updateItem.id}]`);
await sp.web.lists.getByTitle(this.listTitle).items
.getById(updateItem.id)
.update(item)
.catch(e => {
super.handleHttpError('updateHelpful', e);
throw e;
});
}
}
private async getFlatRepliesByQuestionId(currentUser: ICurrentUser, id: number): Promise<IReplyItem[]> {
LogHelper.verbose(this.constructor.name, 'getRepliesByQuestionId', `[id:${id}]`);
let replies: IReplyItem[] = [];
let filterText = `${StandardFields.CONTENTTYPE} eq '${ContentTypes.REPLY}'`;
filterText += `and ${ReplyFields.QUESTIONLOOKUP_ID} eq ${id}`;
let replyItems = await sp.web.lists.getByTitle(this.listTitle).items
.select(this.replySelectColumns.join(','))
.expand(this.replyExpandColumns.join(','))
.filter(filterText)
.top(5000)
.orderBy(StandardFields.ID, true)
.get()
.catch(e => {
super.handleHttpError('getRepliesByQuestionId', e);
throw e;
});
for (let replyItem of replyItems) {
let reply = this.mapReply(replyItem, currentUser);
if(reply.id) {
reply.attachments = await this.getAttachmentsForItem(reply.id);
}
replies.push(reply);
}
return replies;
}
private buildReplyTree(flatReplies: IReplyItem[], replyTree: IReplyItem[], parentReply: IReplyItem | null, isRoot: boolean) {
let matchingReplies = flatReplies.filter(f => f.parentReplyId === (parentReply !== null ? parentReply.id : null));
for (let reply of matchingReplies) {
this.buildReplyTree(flatReplies, replyTree, reply, false);
if (isRoot === true) {
replyTree.push(reply);
}
else {
parentReply!.replies.push(reply);
}
}
return replyTree;
}
private getQuestionFilterParameters(filter: IQuestionsFilter): IRenderListDataParameters {
const rowLimit = `<RowLimit Paged="TRUE">${filter.pageSize}</RowLimit>`;
const orderBy = `<OrderBy><FieldRef Name='${filter.orderByColumnName}' Ascending='${filter.orderByAscending === true ? "TRUE" : "FALSE"}' /></OrderBy>`;
// filter.orderByColumnName, filter.orderByAscending
let whereClause = "";
if (filter.searchText && filter.searchText.length > 0) {
let encodedSearchText = filter.searchText.trim();
const titleFilter = `<Contains><FieldRef Name='${StandardFields.TITLE}' /><Value Type="Text"><![CDATA[${encodedSearchText}]]></Value></Contains>`;
const detailsFilter = `<Contains><FieldRef Name='${PostFields.DETAILSTEXT}' /><Value Type="Note"><![CDATA[${encodedSearchText}]]></Value></Contains>`;
whereClause = `<Or>${titleFilter}${detailsFilter}</Or>`;
}
// filter to only question content type
if(whereClause.length > 0) {
whereClause = `<And>${whereClause}<Eq><FieldRef Name='${StandardFields.CONTENTTYPE}' /><Value Type='Computed'>${ContentTypes.QUESTION}</Value></Eq></And>`;
}
else {
whereClause = `<Eq><FieldRef Name='${StandardFields.CONTENTTYPE}' /><Value Type='Computed'>${ContentTypes.QUESTION}</Value></Eq>`;
}
// filter opened vs answered
switch (filter.selectedShowQuestionsOption) {
case ShowQuestionsOption.Answered:
whereClause = `<And>${whereClause}<Eq><FieldRef Name='${QuestionFields.ISANSWERED}' /><Value Type='Boolean'>1</Value></Eq></And>`;
break;
case ShowQuestionsOption.Open:
whereClause = `<And>${whereClause}<Eq><FieldRef Name='${QuestionFields.ISANSWERED}' /><Value Type='Boolean'>0</Value></Eq></And>`;
break;
}
// filter on category
if (!(filter.category === null || filter.category === undefined || filter.category === '')) {
whereClause = `<And>${whereClause}<Eq><FieldRef Name='${PostFields.CATEGORY}' /><Value Type='Text'><![CDATA[${filter.category}]]></Value></Eq></And>`;
}
// filter to only conversations or questions
if(filter.discussionType) {
whereClause = `<And>${whereClause}<Eq><FieldRef Name='${QuestionFields.DISCUSSION_TYPE}' /><Value Type='Text'>${filter.discussionType}</Value></Eq></And>`;
}
let camlQuery: IRenderListDataParameters = {
RenderOptions: 2,
ViewXml: `
<View>
<ViewFields>
<FieldRef Name='${StandardFields.ID}' />
<FieldRef Name='${StandardFields.TITLE}' />
<FieldRef Name='${PostFields.DETAILS}' />
<FieldRef Name='${PostFields.DETAILSTEXT}' />
<FieldRef Name='${QuestionFields.ISANSWERED}' />
<FieldRef Name='${QuestionFields.FOLLOW_EMAILS}' />
<FieldRef Name='${PostFields.LIKE_COUNT}' />
<FieldRef Name='${PostFields.LIKE_IDS}' />
<FieldRef Name='${PostFields.CATEGORY}' />
<FieldRef Name='${PostFields.TYPE}' />
<FieldRef Name='${StandardFields.CREATED}' />
<FieldRef Name='${StandardFields.MODIFIED}' />
<FieldRef Name='${StandardFields.AUTHOR}' />
<FieldRef Name='${StandardFields.EDITOR}' />
</ViewFields>
<Query>
<Where>
${whereClause}
</Where>
${orderBy}
</Query>
${rowLimit}
</View>`
};
return camlQuery;
}
private mapQuestion(item: any, currentUser: ICurrentUser, mapFromStream: boolean = false): IQuestionItem {
// Map Base Properties (id, created/modified info)
let base = super.mapBaseItemProperties(item, mapFromStream);
let isAnswered = item[QuestionFields.ISANSWERED];
// deal with Yes/No in RenderListDataAsStream
if(typeof(item[QuestionFields.ISANSWERED]) === "string") {
isAnswered = (item[QuestionFields.ISANSWERED] as string).toLowerCase() === 'yes' ? true : false;
}
let question: IQuestionItem = {
...base,
details: item[PostFields.DETAILS],
detailsText: item[PostFields.DETAILSTEXT],
isAnswered: isAnswered,
totalReplyCount: 0,
likeCount: 0,
likeIds: [],
likedByCurrentUser: false,
followEmails: [],
followedByCurrentUser: false,
canDelete: false,
canEdit: false,
canReact: false,
canReply: false,
replies: [],
category: item[PostFields.CATEGORY],
discussionType: item[PostFields.TYPE],
page: item[PostFields.PAGE],
attachments: [],
newAttachments: [],
removedAttachments: []
};
this.mapLikeInfo(item[PostFields.LIKE_IDS], question, currentUser);
this.mapFollowInfo(item[QuestionFields.FOLLOW_EMAILS], question, currentUser);
return question;
}
private mapReply(item: any, currentUser: ICurrentUser): IReplyItem {
// Map Base Properties (id, created/modified info)
let base = super.mapBaseItemProperties(item);
let reply: IReplyItem = {
...base,
details: item[PostFields.DETAILS],
detailsText: item[PostFields.DETAILSTEXT],
isAnswer: item[ReplyFields.ISANSWER],
parentQuestionId: super.getLookupId(item[ReplyFields.QUESTIONLOOKUP]),
parentQuestion: super.getLookup(item[ReplyFields.QUESTIONLOOKUP]),
parentReplyId: super.getLookupId(item[ReplyFields.REPLYLOOKUP]),
parentReply: super.getLookup(item[ReplyFields.REPLYLOOKUP]),
likeCount: 0,
likeIds: [],
likedByCurrentUser: false,
helpfulCount: 0,
helpfulIds: [],
helpfulByCurrentUser: false,
canDelete: false,
canEdit: false,
canMarkAsAnswer: false,
canReact: false,
canReply: false,
replies: [],
attachments: [],
newAttachments: [],
removedAttachments: []
};
this.mapLikeInfo(item[PostFields.LIKE_IDS], reply, currentUser);
this.mapHelpfulInfo(item[ReplyFields.HELPFULIDS], reply, currentUser);
return reply;
}
private mapCategoryLabel(item: any): ICategoryLabelItem {
let base = super.mapBaseItemProperties(item);
let cat: ICategoryLabelItem = {
...base
};
return cat;
}
private mapItemInfo(item: any): IItemInfo {
let itemInfo: IItemInfo = {
id: item.ID,
title: item.Title,
parentQuestionId: super.getLookupId(item[ReplyFields.QUESTIONLOOKUP]),
parentReplyId: super.getLookupId(item[ReplyFields.REPLYLOOKUP]),
discussionType: item[PostFields.TYPE]
};
return itemInfo;
}
private mapFollowInfo(ids: string, updateItem: IQuestionItem, currentUser: ICurrentUser) {
let currentUserMatch: boolean = false;
if (ids) {
updateItem.followEmails = ids.split(';');
currentUserMatch = updateItem.followEmails.indexOf(currentUser.email) != -1;
}
else {
updateItem.followEmails = [];
}
updateItem.followedByCurrentUser = currentUserMatch;
}
private mapLikeInfo(ids: string, updateItem: IQuestionItem | IReplyItem, currentUser: ICurrentUser) {
let currentUserMatch: boolean = false;
if (ids) {
updateItem.likeIds = ids.split(';');
updateItem.likeCount = updateItem.likeIds.length;
currentUserMatch = updateItem.likeIds.indexOf(`${currentUser.id}`) != -1;
}
else {
updateItem.likeIds = [];
updateItem.likeCount = 0;
}
updateItem.likedByCurrentUser = currentUserMatch;
}
private mapHelpfulInfo(ids: string, updateItem: IReplyItem, currentUser: ICurrentUser) {
let currentUserMatch: boolean = false;
if (ids) {
updateItem.helpfulIds = ids.split(';');
updateItem.helpfulCount = updateItem.helpfulIds.length;
currentUserMatch = updateItem.helpfulIds.indexOf(`${currentUser.id}`) != -1;
}
else {
updateItem.helpfulIds = [];
updateItem.helpfulCount = 0;
}
updateItem.helpfulByCurrentUser = currentUserMatch;
}
// business logic needs to move
private updateUserPermissions(currentUser: ICurrentUser, post: IQuestionItem | IReplyItem, currentUserCreatedQuestion: boolean) {
post.canEdit = false;
post.canDelete = false;
post.canReact = false;
post.canReply = false;
// current user can add
if (currentUser.canAddItems) {
post.canReply = true;
}
// current user can edit
if (currentUser.canEditItems) {
post.canReact = true;
// AND they created the question or reply
if (currentUser.loginName.toLowerCase() === post.author!.id!.toLowerCase()) {
post.canEdit = true;
}
}
// current user can delete
if (currentUser.canDeleteItems) {
// AND they created the question or reply
if (currentUser.loginName.toLowerCase() === post.author!.id!.toLowerCase()) {
// AND there are no replies
if (post.replies.length === 0) {
post.canDelete = true;
}
}
// OR they are a moderator
if (currentUser.canModerateItems) {
post.canDelete = true;
}
}
// find out if this is a question and the current user created the question
if (this.isReply(post)) {
post.canMarkAsAnswer = false;
// current user can mark as answer based on list permissions
if (currentUser.canModerateItems) {
post.canMarkAsAnswer = true;
}
// they mark as answer because created the question
if (currentUserCreatedQuestion === true && currentUser.canEditItems) {
post.canMarkAsAnswer = true;
}
}
if (post.replies.length > 0) {
for (let reply of post.replies) {
this.updateUserPermissions(currentUser, reply, currentUserCreatedQuestion);
}
}
}
private isReply(arg: any): arg is IReplyItem {
return arg.canMarkAsAnswer !== undefined;
}
} | the_stack |
import {
createTheme,
DefaultPalette,
IPalette,
Theme as ThemeV8,
ISemanticColors,
IFontStyles,
IFontWeight,
IEffects,
} from '@fluentui/react';
import { BrandVariants, Theme as ThemeV9 } from '@fluentui/react-components';
import { black, blackAlpha, grey, sharedColors, white, whiteAlpha } from './themeDuplicates';
/**
* Creates a v8 palette given a brand ramp
*/
const mapPalette = (brandColors: BrandVariants): IPalette => {
return {
...DefaultPalette,
// map v9 chromatic
black: black,
blackTranslucent40: blackAlpha[40],
neutralDark: grey[8],
neutralPrimary: grey[14],
neutralPrimaryAlt: grey[22],
neutralSecondary: grey[36],
neutralSecondaryAlt: grey[52],
neutralTertiary: grey[62],
neutralTertiaryAlt: grey[78],
neutralQuaternary: grey[82],
neutralQuaternaryAlt: grey[88],
neutralLight: grey[92],
neutralLighter: grey[96],
neutralLighterAlt: grey[98],
accent: brandColors[80],
white: white,
whiteTranslucent40: whiteAlpha[40],
// map v9 shared colors
yellowDark: sharedColors.marigold.shade10,
yellow: sharedColors.yellow.primary,
yellowLight: sharedColors.yellow.tint40,
orange: sharedColors.orange.primary,
orangeLight: sharedColors.orange.tint20,
orangeLighter: sharedColors.orange.tint40,
redDark: sharedColors.darkRed.primary,
red: sharedColors.red.primary,
magentaDark: sharedColors.magenta.shade30,
magenta: sharedColors.magenta.primary,
magentaLight: sharedColors.magenta.tint30,
purpleDark: sharedColors.darkPurple.primary,
purple: sharedColors.purple.primary,
purpleLight: sharedColors.purple.tint40,
blueDark: sharedColors.darkBlue.primary,
blueMid: sharedColors.royalBlue.primary,
blue: sharedColors.blue.primary,
blueLight: sharedColors.lightBlue.primary,
tealDark: sharedColors.darkTeal.primary,
teal: sharedColors.teal.primary,
tealLight: sharedColors.lightTeal.primary,
greenDark: sharedColors.darkGreen.primary,
green: sharedColors.green.primary,
greenLight: sharedColors.lightGreen.primary,
// map the v9 brand ramp
themeDarker: brandColors[40],
themeDark: brandColors[60],
themeDarkAlt: brandColors[70],
themePrimary: brandColors[80],
themeSecondary: brandColors[90],
themeTertiary: brandColors[120],
themeLight: brandColors[140],
themeLighter: brandColors[150],
themeLighterAlt: brandColors[160],
};
};
/**
* Returns v9 theme colors overlaid on a base set of v8 semantic colors
*/
const mapSemanticColors = (baseColors: ISemanticColors, theme: ThemeV9): ISemanticColors => {
return {
...baseColors,
accentButtonBackground: theme.colorBrandBackground,
accentButtonText: theme.colorNeutralForegroundOnBrand,
actionLink: theme.colorNeutralForeground1,
actionLinkHovered: theme.colorNeutralForeground1Hover,
// blockingBackground,
// blockingIcon,
bodyBackground: theme.colorNeutralBackground1,
bodyBackgroundChecked: theme.colorNeutralBackground1Selected,
bodyBackgroundHovered: theme.colorNeutralBackground1Hover,
bodyDivider: theme.colorNeutralStroke2,
bodyFrameBackground: theme.colorNeutralBackground1,
bodyFrameDivider: theme.colorNeutralStroke2,
bodyStandoutBackground: theme.colorNeutralBackground2,
bodySubtext: theme.colorNeutralForeground2,
bodyText: theme.colorNeutralForeground1,
bodyTextChecked: theme.colorNeutralForeground1Selected,
buttonBackground: theme.colorNeutralBackground1,
buttonBackgroundChecked: theme.colorNeutralBackground1Selected,
buttonBackgroundCheckedHovered: theme.colorNeutralBackground1Hover,
buttonBackgroundDisabled: theme.colorNeutralBackgroundDisabled,
buttonBackgroundHovered: theme.colorNeutralBackground1Hover,
buttonBackgroundPressed: theme.colorNeutralBackground1Pressed,
buttonBorder: theme.colorNeutralStroke1,
buttonBorderDisabled: theme.colorNeutralStrokeDisabled,
buttonText: theme.colorNeutralForeground1,
buttonTextChecked: theme.colorNeutralForeground1,
buttonTextCheckedHovered: theme.colorNeutralForeground1,
buttonTextDisabled: theme.colorNeutralForegroundDisabled,
buttonTextHovered: theme.colorNeutralForeground1,
buttonTextPressed: theme.colorNeutralForeground1,
cardShadow: theme.shadow4,
cardShadowHovered: theme.shadow8,
cardStandoutBackground: theme.colorNeutralBackground1,
defaultStateBackground: theme.colorNeutralBackground2,
disabledBackground: theme.colorNeutralBackgroundDisabled,
disabledBodySubtext: theme.colorNeutralForegroundDisabled,
disabledBodyText: theme.colorNeutralForegroundDisabled,
disabledBorder: theme.colorNeutralStrokeDisabled,
disabledSubtext: theme.colorNeutralForegroundDisabled,
disabledText: theme.colorNeutralForegroundDisabled,
// errorBackground,
// errorIcon,
// errorText: ,
focusBorder: theme.colorStrokeFocus2,
// infoBackground,
// infoIcon,
inputBackground: theme.colorNeutralBackground1,
inputBackgroundChecked: theme.colorBrandBackground,
inputBackgroundCheckedHovered: theme.colorBrandBackgroundHover,
inputBorder: theme.colorNeutralStrokeAccessible,
inputBorderHovered: theme.colorNeutralStrokeAccessibleHover,
inputFocusBorderAlt: theme.colorBrandStroke1,
inputForegroundChecked: theme.colorNeutralForegroundOnBrand,
inputIcon: theme.colorNeutralForeground3,
inputIconDisabled: theme.colorNeutralForegroundDisabled,
inputIconHovered: theme.colorNeutralForeground3,
inputPlaceholderBackgroundChecked: theme.colorBrandBackgroundInvertedSelected,
inputPlaceholderText: theme.colorNeutralForeground4,
inputText: theme.colorNeutralForeground1,
inputTextHovered: theme.colorNeutralForeground1Hover,
link: theme.colorBrandForegroundLink,
linkHovered: theme.colorBrandForegroundLinkHover,
listBackground: theme.colorNeutralBackground1,
listHeaderBackgroundHovered: theme.colorNeutralBackground1Hover,
listHeaderBackgroundPressed: theme.colorNeutralBackground1Pressed,
listItemBackgroundChecked: theme.colorNeutralBackground1Selected,
listItemBackgroundCheckedHovered: theme.colorNeutralBackground1Selected,
listItemBackgroundHovered: theme.colorNeutralBackground1Hover,
listText: theme.colorNeutralForeground1,
listTextColor: theme.colorNeutralForeground1,
menuBackground: theme.colorNeutralBackground1,
menuDivider: theme.colorNeutralStroke2,
menuHeader: theme.colorNeutralForeground3,
menuIcon: theme.colorNeutralForeground1,
menuItemBackgroundChecked: theme.colorNeutralBackground1,
menuItemBackgroundHovered: theme.colorNeutralBackground1Hover,
menuItemBackgroundPressed: theme.colorNeutralBackground1Hover,
menuItemText: theme.colorNeutralForeground1,
menuItemTextHovered: theme.colorNeutralForeground1Hover,
messageLink: theme.colorBrandForegroundLink,
messageLinkHovered: theme.colorBrandForegroundLinkHover,
messageText: theme.colorNeutralForeground1,
primaryButtonBackground: theme.colorBrandBackground,
primaryButtonBackgroundDisabled: theme.colorNeutralBackgroundDisabled,
primaryButtonBackgroundHovered: theme.colorBrandBackgroundHover,
primaryButtonBackgroundPressed: theme.colorBrandBackgroundPressed,
primaryButtonBorder: theme.colorTransparentStroke,
primaryButtonText: theme.colorNeutralForegroundOnBrand,
primaryButtonTextDisabled: theme.colorNeutralForegroundDisabled,
primaryButtonTextHovered: theme.colorNeutralForegroundOnBrand,
primaryButtonTextPressed: theme.colorNeutralForegroundOnBrand,
// severeWarningBackground,
// severeWarningIcon,
// smallInputBorder,
// successBackground,
// successIcon,
// successText: ,
// variantBorder,
// variantBorderHovered,
// warningBackground,
// warningHighlight,
// warningIcon,
// warningText: ,
};
};
/**
* Overlays v9 fonts on a set of base v8 fonts.
*/
const mapFonts = (baseFonts: IFontStyles, theme: ThemeV9): IFontStyles => {
return {
...baseFonts,
tiny: {
...baseFonts.tiny,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeBase100,
fontWeight: theme.fontWeightRegular as IFontWeight,
},
xSmall: {
...baseFonts.xSmall,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeBase100,
fontWeight: theme.fontWeightRegular as IFontWeight,
},
small: {
...baseFonts.small,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeBase200,
fontWeight: theme.fontWeightRegular as IFontWeight,
},
smallPlus: {
...baseFonts.smallPlus,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeBase200,
fontWeight: theme.fontWeightRegular as IFontWeight,
},
medium: {
...baseFonts.medium,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeBase300,
fontWeight: theme.fontWeightRegular as IFontWeight,
},
mediumPlus: {
...baseFonts.mediumPlus,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeBase400,
fontWeight: theme.fontWeightRegular as IFontWeight,
},
large: {
...baseFonts.large,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeBase400,
fontWeight: theme.fontWeightRegular as IFontWeight,
},
xLarge: {
...baseFonts.xxLarge,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeBase500,
fontWeight: theme.fontWeightSemibold as IFontWeight,
},
xxLarge: {
...baseFonts.xxLarge,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeHero700,
fontWeight: theme.fontWeightSemibold as IFontWeight,
},
superLarge: {
...baseFonts.superLarge,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeHero900,
fontWeight: theme.fontWeightSemibold as IFontWeight,
},
mega: {
...baseFonts.mega,
fontFamily: theme.fontFamilyBase,
fontSize: theme.fontSizeHero1000,
fontWeight: theme.fontWeightSemibold as IFontWeight,
},
};
};
/**
* Overlays v9 shadows and border radii on a base set of v8 effects.
*/
const mapEffects = (baseEffects: IEffects, theme: ThemeV9): IEffects => {
return {
...baseEffects,
elevation4: theme.shadow4,
elevation8: theme.shadow8,
elevation16: theme.shadow16,
elevation64: theme.shadow64,
roundedCorner2: theme.borderRadiusSmall,
roundedCorner4: theme.borderRadiusMedium,
roundedCorner6: theme.borderRadiusLarge,
};
};
/**
* Creates a v8 theme from v9 brand colora and theme.
* You can optionally pass a v8 base theme.
* Otherwise the default v8 theme is used.
*
* The v9 colors, fonts, and effects are applied on top of the v8 theme
* to allow v8 components to look as much like v9 components as possible.
*/
export const createv8Theme = (brandColors: BrandVariants, themeV9: ThemeV9, themeV8?: ThemeV8): ThemeV8 => {
const baseTheme = themeV8 || createTheme();
return {
...baseTheme,
palette: mapPalette(brandColors),
semanticColors: mapSemanticColors(baseTheme.semanticColors, themeV9),
fonts: mapFonts(baseTheme.fonts, themeV9),
effects: mapEffects(baseTheme.effects, themeV9),
};
}; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { AvailabilityStatuses } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { MicrosoftResourceHealth } from "../microsoftResourceHealth";
import {
AvailabilityStatus,
AvailabilityStatusesListBySubscriptionIdNextOptionalParams,
AvailabilityStatusesListBySubscriptionIdOptionalParams,
AvailabilityStatusesListByResourceGroupNextOptionalParams,
AvailabilityStatusesListByResourceGroupOptionalParams,
AvailabilityStatusesListNextOptionalParams,
AvailabilityStatusesListOptionalParams,
AvailabilityStatusesListBySubscriptionIdResponse,
AvailabilityStatusesListByResourceGroupResponse,
AvailabilityStatusesGetByResourceOptionalParams,
AvailabilityStatusesGetByResourceResponse,
AvailabilityStatusesListResponse,
AvailabilityStatusesListBySubscriptionIdNextResponse,
AvailabilityStatusesListByResourceGroupNextResponse,
AvailabilityStatusesListNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing AvailabilityStatuses operations. */
export class AvailabilityStatusesImpl implements AvailabilityStatuses {
private readonly client: MicrosoftResourceHealth;
/**
* Initialize a new instance of the class AvailabilityStatuses class.
* @param client Reference to the service client
*/
constructor(client: MicrosoftResourceHealth) {
this.client = client;
}
/**
* Lists the current availability status for all the resources in the subscription. Use the nextLink
* property in the response to get the next page of availability statuses.
* @param options The options parameters.
*/
public listBySubscriptionId(
options?: AvailabilityStatusesListBySubscriptionIdOptionalParams
): PagedAsyncIterableIterator<AvailabilityStatus> {
const iter = this.listBySubscriptionIdPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listBySubscriptionIdPagingPage(options);
}
};
}
private async *listBySubscriptionIdPagingPage(
options?: AvailabilityStatusesListBySubscriptionIdOptionalParams
): AsyncIterableIterator<AvailabilityStatus[]> {
let result = await this._listBySubscriptionId(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listBySubscriptionIdNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listBySubscriptionIdPagingAll(
options?: AvailabilityStatusesListBySubscriptionIdOptionalParams
): AsyncIterableIterator<AvailabilityStatus> {
for await (const page of this.listBySubscriptionIdPagingPage(options)) {
yield* page;
}
}
/**
* Lists the current availability status for all the resources in the resource group. Use the nextLink
* property in the response to get the next page of availability statuses.
* @param resourceGroupName The name of the resource group.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: AvailabilityStatusesListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<AvailabilityStatus> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: AvailabilityStatusesListByResourceGroupOptionalParams
): AsyncIterableIterator<AvailabilityStatus[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByResourceGroupNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: AvailabilityStatusesListByResourceGroupOptionalParams
): AsyncIterableIterator<AvailabilityStatus> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Lists all historical availability transitions and impacting events for a single resource. Use the
* nextLink property in the response to get the next page of availability status
* @param resourceUri The fully qualified ID of the resource, including the resource name and resource
* type. Currently the API support not nested and one nesting level resource types :
* /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
* and
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}
* @param options The options parameters.
*/
public list(
resourceUri: string,
options?: AvailabilityStatusesListOptionalParams
): PagedAsyncIterableIterator<AvailabilityStatus> {
const iter = this.listPagingAll(resourceUri, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(resourceUri, options);
}
};
}
private async *listPagingPage(
resourceUri: string,
options?: AvailabilityStatusesListOptionalParams
): AsyncIterableIterator<AvailabilityStatus[]> {
let result = await this._list(resourceUri, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(resourceUri, continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
resourceUri: string,
options?: AvailabilityStatusesListOptionalParams
): AsyncIterableIterator<AvailabilityStatus> {
for await (const page of this.listPagingPage(resourceUri, options)) {
yield* page;
}
}
/**
* Lists the current availability status for all the resources in the subscription. Use the nextLink
* property in the response to get the next page of availability statuses.
* @param options The options parameters.
*/
private _listBySubscriptionId(
options?: AvailabilityStatusesListBySubscriptionIdOptionalParams
): Promise<AvailabilityStatusesListBySubscriptionIdResponse> {
return this.client.sendOperationRequest(
{ options },
listBySubscriptionIdOperationSpec
);
}
/**
* Lists the current availability status for all the resources in the resource group. Use the nextLink
* property in the response to get the next page of availability statuses.
* @param resourceGroupName The name of the resource group.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: AvailabilityStatusesListByResourceGroupOptionalParams
): Promise<AvailabilityStatusesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
/**
* Gets current availability status for a single resource
* @param resourceUri The fully qualified ID of the resource, including the resource name and resource
* type. Currently the API support not nested and one nesting level resource types :
* /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
* and
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}
* @param options The options parameters.
*/
getByResource(
resourceUri: string,
options?: AvailabilityStatusesGetByResourceOptionalParams
): Promise<AvailabilityStatusesGetByResourceResponse> {
return this.client.sendOperationRequest(
{ resourceUri, options },
getByResourceOperationSpec
);
}
/**
* Lists all historical availability transitions and impacting events for a single resource. Use the
* nextLink property in the response to get the next page of availability status
* @param resourceUri The fully qualified ID of the resource, including the resource name and resource
* type. Currently the API support not nested and one nesting level resource types :
* /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
* and
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}
* @param options The options parameters.
*/
private _list(
resourceUri: string,
options?: AvailabilityStatusesListOptionalParams
): Promise<AvailabilityStatusesListResponse> {
return this.client.sendOperationRequest(
{ resourceUri, options },
listOperationSpec
);
}
/**
* ListBySubscriptionIdNext
* @param nextLink The nextLink from the previous successful call to the ListBySubscriptionId method.
* @param options The options parameters.
*/
private _listBySubscriptionIdNext(
nextLink: string,
options?: AvailabilityStatusesListBySubscriptionIdNextOptionalParams
): Promise<AvailabilityStatusesListBySubscriptionIdNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listBySubscriptionIdNextOperationSpec
);
}
/**
* ListByResourceGroupNext
* @param resourceGroupName The name of the resource group.
* @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method.
* @param options The options parameters.
*/
private _listByResourceGroupNext(
resourceGroupName: string,
nextLink: string,
options?: AvailabilityStatusesListByResourceGroupNextOptionalParams
): Promise<AvailabilityStatusesListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listByResourceGroupNextOperationSpec
);
}
/**
* ListNext
* @param resourceUri The fully qualified ID of the resource, including the resource name and resource
* type. Currently the API support not nested and one nesting level resource types :
* /subscriptions/{subscriptionId}/resourceGroups/{resource-group-name}/providers/{resource-provider-name}/{resource-type}/{resource-name}
* and
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resource-provider-name}/{parentResourceType}/{parentResourceName}/{resourceType}/{resourceName}
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
resourceUri: string,
nextLink: string,
options?: AvailabilityStatusesListNextOptionalParams
): Promise<AvailabilityStatusesListNextResponse> {
return this.client.sendOperationRequest(
{ resourceUri, nextLink, options },
listNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listBySubscriptionIdOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.ResourceHealth/availabilityStatuses",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AvailabilityStatusListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.expand
],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ResourceHealth/availabilityStatuses",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AvailabilityStatusListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.expand
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const getByResourceOperationSpec: coreClient.OperationSpec = {
path:
"/{resourceUri}/providers/Microsoft.ResourceHealth/availabilityStatuses/current",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AvailabilityStatus
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.expand
],
urlParameters: [Parameters.$host, Parameters.resourceUri],
headerParameters: [Parameters.accept],
serializer
};
const listOperationSpec: coreClient.OperationSpec = {
path:
"/{resourceUri}/providers/Microsoft.ResourceHealth/availabilityStatuses",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AvailabilityStatusListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.expand
],
urlParameters: [Parameters.$host, Parameters.resourceUri],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionIdNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AvailabilityStatusListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.expand
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AvailabilityStatusListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.expand
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AvailabilityStatusListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.expand
],
urlParameters: [
Parameters.$host,
Parameters.resourceUri,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
module Kiwi.GameObjects {
/**
* TextField is a GameObject that is used when you are wanting to render
* text onto the current State.
*
* TextField has width/height and a hitbox, but because text is difficult
* to measure, these may not be 100% accurate. It does not have an
* "Input" component either, although you may choose to add one. Be aware
* of these limitations.
*
* Note that there also exists a "Textfield" object. This is simply a
* legacy alias of "TextField", which was renamed in v1.2.0 for naming
* standardization purposes.
*
* @class TextField
* @namespace Kiwi.GameObjects
* @extends Kiwi.Entity
* @constructor
* @param state {Kiwi.State} The state that this TextField belongs to
* @param text {String} The text that is contained within this textfield.
* @param [x=0] {Number} The new x coordinate from the Position component
* @param [y=0] {Number} The new y coordinate from the Position component
* @param [color="#000000"] {String} The color of the text.
* @param [size=32] {Number} The size of the text in pixels.
* @param [weight="normal"] {String} The weight of the text.
* @param [fontFamily="sans-serif"] {String} The font family that is to be used when rendering.
* @return {TextField} This Game Object.
*/
export class TextField extends Kiwi.Entity {
constructor(state: Kiwi.State, text: string, x: number = 0, y: number = 0, color: string = "#000000", size: number = 32, weight: string = "normal", fontFamily: string = "sans-serif") {
super(state, x,y);
if (this.game.renderOption === Kiwi.RENDERER_WEBGL) {
this.glRenderer = this.game.renderer.requestSharedRenderer("TextureAtlasRenderer");
}
this._text = text;
this._fontWeight = weight;
this._fontSize = size;
this._fontColor = new Kiwi.Utils.Color( color );
this._fontFamily = fontFamily;
this._textAlign = "left";
this._baseline = "top";
this._tempDirty = true;
// Create the canvas
this._canvas = document.createElement("canvas");
this._canvas.width = 2;
this._canvas.height = 2;
this._ctx = this._canvas.getContext("2d");
// Add it to the TextureLibrary
this.atlas = new Kiwi.Textures.SingleImage(this.game.rnd.uuid(), this._canvas);
this.state.textureLibrary.add(this.atlas);
this.atlas.dirty = true;
// Track actual text width - not canvas width (which rounds up to powers of 2), necessary for proper alignment
this._alignWidth = 0;
// Setup components
this.box = this.components.add(
new Kiwi.Components.Box(
this, x, y, this.width, this.height ) );
}
/**
* Returns the type of object that this is.
*
* Note: This is not camel-cased because of an error in early development.
* To preserve API compatibility, all 1.x.x releases retail this form.
* This will be fixed in v2.
* @method objType
* @return {string} "Textfield"
* @public
*/
public objType() {
return "Textfield";
}
/**
* The text that is to be rendered.
* @property _text
* @type string
* @private
*/
private _text: string;
/**
* The weight of the font.
* @property _fontWeight
* @type string
* @default "normal"
* @private
*/
private _fontWeight: string;
/**
* The size of the font.
* @property _fontSize
* @type number
* @default 32
* @private
*/
private _fontSize: number;
/**
* The color of the text.
* @property _fontColor
* @type Kiwi.Utils.Color
* @private
*/
private _fontColor: Kiwi.Utils.Color;
/**
* The font family that is to be rendered.
* @property _fontFamily
* @type string
* @default "sans-serif"
* @private
*/
private _fontFamily: string;
/**
* The alignment of the text. This can either be "left", "right" or "center"
* @property _textAlign
* @type string
* @default "center"
* @private
*/
private _textAlign: string;
/**
* The pixel width of the text. Used internally for alignment purposes.
* @property _alignWidth
* @type number
* @default 0
* @private
* @since 1.1.0
*/
private _alignWidth: number;
/**
* The baseline of the text to be rendered.
* @property _baseline
* @type string
* @private
*/
private _baseline: string;
/**
* The text that you would like to appear in this textfield.
* @property text
* @type string
* @public
*/
public set text(value: string) {
this._text = value;
this._tempDirty = true;
}
public get text(): string {
return this._text;
}
/**
* The color of the font that is contained in this textfield.
* May be set with a string, or an array of any valid
* Kiwi.Utils.Color arguments.
* Returns a hex string prepended with "#".
* @property color
* @type string
* @public
*/
public set color( val: any ) {
if ( !Kiwi.Utils.Common.isArray( val ) ) {
val = [ val ];
}
this._fontColor.set.apply( this._fontColor, val );
this._tempDirty = true;
}
public get color(): any {
return "#" + this._fontColor.getHex();
}
/**
* The weight of the font.
* @property fontWeight
* @type string
* @public
*/
public set fontWeight(val: string) {
this._fontWeight = val;
this._tempDirty = true;
}
public get fontWeight(): string {
return this._fontWeight;
}
/**
* The size on font when being displayed onscreen.
* @property fontSize
* @type number
* @public
*/
public set fontSize(val: number) {
this._fontSize = val;
this._tempDirty = true;
}
public get fontSize(): number {
return this._fontSize;
}
/**
* The font family that is being used to render the text.
* @property fontFamily
* @type string
* @public
*/
public set fontFamily(val: string) {
this._fontFamily = val;
this._tempDirty = true;
}
public get fontFamily(): string {
return this._fontFamily;
}
/**
* A static property that contains the string to center align the text.
* @property TEXT_ALIGN_CENTER
* @type string
* @static
* @final
* @public
*/
public static TEXT_ALIGN_CENTER: string = "center";
/**
* A static property that contains the string to right align the text.
* @property TEXT_ALIGN_RIGHT
* @type string
* @static
* @final
* @public
*/
public static TEXT_ALIGN_RIGHT: string = "right";
/**
* A static property that contains the string to left align the text.
* @property TEXT_ALIGN_LEFT
* @type string
* @static
* @final
* @public
*/
public static TEXT_ALIGN_LEFT: string = "left";
/**
* Alignment of the text. You can either use the static TEXT_ALIGN constants or pass a string.
* @property textAlign
* @type string
* @public
*/
public set textAlign(val: string) {
this._textAlign = val;
this._tempDirty = true;
}
public get textAlign(): string {
return this._textAlign;
}
/**
* The canvas element which the text is rendered onto.
* @property _canvas
* @type HTMLCanvasElement.
* @private
*/
private _canvas: HTMLCanvasElement;
/**
* The context for the canvas element. Used whilst rendering text.
* @property _ctx
* @type CanvasRenderingContext2D
* @private
*/
private _ctx: CanvasRenderingContext2D;
/**
* If the temporary canvas is dirty and needs to be re-rendered. Only used when the text field rendering is being optimised.
* @property _tempDirty
* @type boolean
* @private
*/
private _tempDirty: boolean = true;
/**
* Hitbox component
* @property box
* @type Kiwi.Components.Box
* @public
* @since 1.2.0
*/
public box: Kiwi.Components.Box;
/**
* Geometry point used in rendering.
*
* @property _pt1
* @type Kiwi.Geom.Point
* @private
*/
private _pt1: Kiwi.Geom.Point = new Kiwi.Geom.Point( 0, 0 );
/**
* Geometry point used in rendering.
*
* @property _pt2
* @type Kiwi.Geom.Point
* @private
*/
private _pt2: Kiwi.Geom.Point = new Kiwi.Geom.Point( 0, 0 );
/**
* Geometry point used in rendering.
*
* @property _pt3
* @type Kiwi.Geom.Point
* @private
*/
private _pt3: Kiwi.Geom.Point = new Kiwi.Geom.Point( 0, 0 );
/**
* Geometry point used in rendering.
*
* @property _pt4
* @type Kiwi.Geom.Point
* @private
*/
private _pt4: Kiwi.Geom.Point = new Kiwi.Geom.Point( 0, 0 );
/**
* This method is used to render the text to an offscreen-canvas which is held in a TextureAtlas (which is generated upon the instanitation of this class).
* This is so that the canvas doesn't render it every frame as it can be costly and so that it can be used in WebGL with the TextureAtlasRenderer.
*
* @method _renderText
* @private
*/
private _renderText() {
//Get/Set the width
this._ctx.font = this._fontWeight + " " + this._fontSize + "px " + this._fontFamily;
// Get the size of the text.
var _measurements: TextMetrics = this._ctx.measureText(this._text); //when you measure the text for some reason it resets the values?!
var width = _measurements.width;
var height = this._fontSize * 1.3; //Need to find a better way to calculate
// Cache alignment width
this._alignWidth = width;
// Is the width base2?
if (Kiwi.Utils.Common.base2Sizes.indexOf(width) == -1) {
var i = 0;
while (width > Kiwi.Utils.Common.base2Sizes[i]) i++;
width = Kiwi.Utils.Common.base2Sizes[i];
}
// Is the height base2?
if (Kiwi.Utils.Common.base2Sizes.indexOf(height) == -1) {
var i = 0;
while (height > Kiwi.Utils.Common.base2Sizes[i]) i++;
height = Kiwi.Utils.Common.base2Sizes[i];
}
// Apply the width/height
this._canvas.width = width;
this._canvas.height = height;
// Clear the canvas
this._ctx.clearRect(0, 0, width, height);
// Reapply the styles....cause it unapplies after a measurement...?!?
this._ctx.font = this._fontWeight + " " + this._fontSize + "px " + this._fontFamily;
this._ctx.fillStyle = this.color.slice( 0, 7 );
this._ctx.textBaseline = this._baseline;
// Draw the text.
this._ctx.fillText(this._text, 0, 0);
// Update inherited properties
this.width = this._alignWidth;
this.height = this._canvas.height;
//Update the cell and dirty/undirtyfiy
this.atlas.cells[0] = {
x: 0,
y: 0,
w: this._canvas.width,
h: this._canvas.height,
hitboxes: [ {
x: this._textAlign === Kiwi.GameObjects.TextField.TEXT_ALIGN_LEFT ? 0 :
this._textAlign === Kiwi.GameObjects.TextField.TEXT_ALIGN_CENTER ?
-this._alignWidth * 0.5 : -this._alignWidth,
y: 0,
w: this.width,
h: this.height
} ] };
this._tempDirty = false;
this.atlas.dirty = true;
}
/**
* Called by the Layer to which this Game Object is attached
* @method render
* @param {Kiwi.Camera}
* @public
*/
public render(camera:Kiwi.Camera) {
if (this.alpha > 0 && this.visible) {
//render on stage
var ctx: CanvasRenderingContext2D = this.game.stage.ctx;
ctx.save();
var t: Kiwi.Geom.Transform = this.transform;
if (this.alpha > 0 && this.alpha <= 1) {
ctx.globalAlpha = this.alpha;
}
//Does the text need re-rendering
if (this._tempDirty) this._renderText();
//Align the text
var x = 0;
switch (this._textAlign) {
case Kiwi.GameObjects.TextField.TEXT_ALIGN_LEFT:
x = 0;
break;
case Kiwi.GameObjects.TextField.TEXT_ALIGN_CENTER:
x = this._alignWidth * 0.5;
break;
case Kiwi.GameObjects.TextField.TEXT_ALIGN_RIGHT:
x = this._alignWidth;
break;
}
//Draw the Image
var m: Kiwi.Geom.Matrix = t.getConcatenatedMatrix();
ctx.transform(m.a, m.b, m.c, m.d, m.tx, m.ty);
ctx.drawImage(this._canvas, 0, 0, this._canvas.width, this._canvas.height, -t.rotPointX - x, -t.rotPointY, this._canvas.width, this._canvas.height);
ctx.restore();
}
}
/**
* Renders the GameObject using WebGL.
* @method renderGL
* @param {WebGLRenderingContext} gl
* @param {Kiwi.Camera} camera
* @param {Object} params
* @public
*/
public renderGL(gl: WebGLRenderingContext, camera: Kiwi.Camera, params: any = null) {
//Does the text need re-rendering
if (this._tempDirty) this._renderText();
//Set-up the xyuv and alpha
var vertexItems = [];
//Transform/Matrix
var t: Kiwi.Geom.Transform = this.transform;
var m: Kiwi.Geom.Matrix = t.getConcatenatedMatrix();
//See where the text should be.
var x = 0;
switch (this._textAlign) {
case Kiwi.GameObjects.TextField.TEXT_ALIGN_LEFT:
x = 0;
break;
case Kiwi.GameObjects.TextField.TEXT_ALIGN_CENTER:
x = -(this._alignWidth * 0.5);
break;
case Kiwi.GameObjects.TextField.TEXT_ALIGN_RIGHT:
x = -(this._alignWidth);
break;
}
//Create the Point Objects.
this._pt1.setTo(x - t.rotPointX, 0 - t.rotPointY);
this._pt2.setTo(this._canvas.width + x - t.rotPointX , 0 - t.rotPointY);
this._pt3.setTo(this._canvas.width + x - t.rotPointX , this._canvas.height - t.rotPointY);
this._pt4.setTo(x - t.rotPointX, this._canvas.height - t.rotPointY);
//Add on the matrix to the points
m.transformPoint(this._pt1);
m.transformPoint(this._pt2);
m.transformPoint(this._pt3);
m.transformPoint(this._pt4);
//Append to the xyuv and alpha arrays
vertexItems.push(
this._pt1.x, this._pt1.y, 0, 0, this.alpha,
//Top Left Point
this._pt2.x, this._pt2.y, this._canvas.width, 0, this.alpha,
//Top Right Point
this._pt3.x, this._pt3.y, this._canvas.width, this._canvas.height, this.alpha, //Bottom Right Point
this._pt4.x, this._pt4.y, 0, this._canvas.height, this.alpha
//Bottom Left Point
);
//Add to the batch!
(<Kiwi.Renderers.TextureAtlasRenderer>this.glRenderer).concatBatch(vertexItems);
}
}
// Alias and reiteration for YuiDoc purposes
export var Textfield = Kiwi.GameObjects.TextField;
} | the_stack |
import {
combineLatest as observableCombineLatest,
empty as observableEmpty,
merge as observableMerge,
from as observableFrom,
Observable,
} from "rxjs";
import {
distinctUntilChanged,
filter,
first,
map,
mergeMap,
publishReplay,
refCount,
share,
skipWhile,
startWith,
switchMap,
tap,
} from "rxjs/operators";
import { TagCreator } from "./TagCreator";
import { TagDOMRenderer } from "./TagDOMRenderer";
import { TagScene } from "./TagScene";
import { TagMode } from "./TagMode";
import { TagSet } from "./TagSet";
import { Geometry } from "./geometry/Geometry";
import { PointsGeometry } from "./geometry/PointsGeometry";
import { CreateHandlerBase } from "./handlers/CreateHandlerBase";
import { CreatePointHandler } from "./handlers/CreatePointHandler";
import { CreatePointsHandler } from "./handlers/CreatePointsHandler";
import { CreatePolygonHandler } from "./handlers/CreatePolygonHandler";
import { CreateRectHandler } from "./handlers/CreateRectHandler";
import { CreateRectDragHandler } from "./handlers/CreateRectDragHandler";
import { EditVertexHandler } from "./handlers/EditVertexHandler";
import { Tag } from "./tag/Tag";
import { RenderTag } from "./tag/RenderTag";
import { CreateTag } from "./tag/CreateTag";
import { Component } from "../Component";
import { TagConfiguration } from "../interfaces/TagConfiguration";
import { Transform } from "../../geo/Transform";
import { ViewportCoords } from "../../geo/ViewportCoords";
import { Navigator } from "../../viewer/Navigator";
import { RenderPass } from "../../render/RenderPass";
import { RenderCamera } from "../../render/RenderCamera";
import { GLRenderHash } from "../../render/interfaces/IGLRenderHash";
import { ViewportSize } from "../../render/interfaces/ViewportSize";
import { VirtualNodeHash } from "../../render/interfaces/VirtualNodeHash";
import { AnimationFrame } from "../../state/interfaces/AnimationFrame";
import { Container } from "../../viewer/Container";
import { ISpriteAtlas } from "../../viewer/interfaces/ISpriteAtlas";
import { ComponentEventType } from "../events/ComponentEventType";
import { ComponentTagModeEvent } from "../events/ComponentTagModeEvent";
import { ComponentGeometryEvent } from "../events/ComponentGeometryEvent";
import { ComponentStateEvent } from "../events/ComponentStateEvent";
import { ComponentName } from "../ComponentName";
/**
* @class TagComponent
*
* @classdesc Component for showing and editing tags with different
* geometries composed from 2D basic image coordinates (see the
* {@link Viewer} class documentation for more information about coordinate
* systems).
*
* The `add` method is used for adding new tags or replacing
* tags already in the set. Tags are removed by id.
*
* If a tag already in the set has the same
* id as one of the tags added, the old tag will be removed and
* the added tag will take its place.
*
* The tag component mode can be set to either be non interactive or
* to be in creating mode of a certain geometry type.
*
* The tag properties can be updated at any time and the change will
* be visibile immediately.
*
* Tags are only relevant to a single image because they are based on
* 2D basic image coordinates. Tags related to a certain image should
* be removed when the viewer is moved to another image.
*
* To retrive and use the tag component
*
* @example
* ```js
* var viewer = new Viewer({ component: { tag: true } }, ...);
*
* var tagComponent = viewer.getComponent("tag");
* ```
*/
export class TagComponent extends Component<TagConfiguration> {
/** @inheritdoc */
public static componentName: ComponentName = "tag";
private _tagDomRenderer: TagDOMRenderer;
private _tagScene: TagScene;
private _tagSet: TagSet;
private _tagCreator: TagCreator;
private _viewportCoords: ViewportCoords;
private _renderTags$: Observable<RenderTag<Tag>[]>;
private _tagChanged$: Observable<Tag>;
private _renderTagGLChanged$: Observable<RenderTag<Tag>>;
private _createGeometryChanged$: Observable<CreateTag<Geometry>>;
private _createGLObjectsChanged$: Observable<CreateTag<Geometry>>;
private _creatingConfiguration$: Observable<TagConfiguration>;
private _createHandlers: {
[K in keyof typeof TagMode]: CreateHandlerBase;
};
private _editVertexHandler: EditVertexHandler;
/** @ignore */
constructor(
name: string,
container: Container,
navigator: Navigator) {
super(name, container, navigator);
this._tagDomRenderer = new TagDOMRenderer();
this._tagScene = new TagScene();
this._tagSet = new TagSet();
this._tagCreator = new TagCreator(this, navigator);
this._viewportCoords = new ViewportCoords();
this._createHandlers = {
"CreatePoint":
new CreatePointHandler(
this,
container,
navigator,
this._viewportCoords,
this._tagCreator),
"CreatePoints":
new CreatePointsHandler(
this,
container,
navigator,
this._viewportCoords,
this._tagCreator),
"CreatePolygon":
new CreatePolygonHandler(
this,
container,
navigator,
this._viewportCoords,
this._tagCreator),
"CreateRect":
new CreateRectHandler(
this,
container,
navigator,
this._viewportCoords,
this._tagCreator),
"CreateRectDrag":
new CreateRectDragHandler(
this,
container,
navigator,
this._viewportCoords,
this._tagCreator),
"Default": undefined,
};
this._editVertexHandler =
new EditVertexHandler(
this,
container,
navigator,
this._viewportCoords,
this._tagSet);
this._renderTags$ = this._tagSet.changed$.pipe(
map(
(tagSet: TagSet): RenderTag<Tag>[] => {
const tags: RenderTag<Tag>[] = tagSet.getAll();
// ensure that tags are always rendered in the same order
// to avoid hover tracking problems on first resize.
tags.sort(
(t1: RenderTag<Tag>, t2: RenderTag<Tag>): number => {
const id1: string = t1.tag.id;
const id2: string = t2.tag.id;
if (id1 < id2) {
return -1;
}
if (id1 > id2) {
return 1;
}
return 0;
});
return tags;
}),
share());
this._tagChanged$ = this._renderTags$.pipe(
switchMap(
(tags: RenderTag<Tag>[]): Observable<Tag> => {
return observableFrom(tags).pipe(
mergeMap(
(tag: RenderTag<Tag>): Observable<Tag> => {
return observableMerge(
tag.tag.changed$,
tag.tag.geometryChanged$);
}));
}),
share());
this._renderTagGLChanged$ = this._renderTags$.pipe(
switchMap(
(tags: RenderTag<Tag>[]): Observable<RenderTag<Tag>> => {
return observableFrom(tags).pipe(
mergeMap(
(tag: RenderTag<Tag>): Observable<RenderTag<Tag>> => {
return tag.glObjectsChanged$;
}));
}),
share());
this._createGeometryChanged$ = this._tagCreator.tag$.pipe(
switchMap(
(tag: CreateTag<Geometry>): Observable<CreateTag<Geometry>> => {
return tag != null ?
tag.geometryChanged$ :
observableEmpty();
}),
share());
this._createGLObjectsChanged$ = this._tagCreator.tag$.pipe(
switchMap(
(tag: CreateTag<Geometry>): Observable<CreateTag<Geometry>> => {
return tag != null ?
tag.glObjectsChanged$ :
observableEmpty();
}),
share());
this._creatingConfiguration$ = this._configuration$.pipe(
distinctUntilChanged(
(c1: TagConfiguration, c2: TagConfiguration): boolean => {
return c1.mode === c2.mode;
},
(configuration: TagConfiguration): TagConfiguration => {
return {
createColor: configuration.createColor,
mode: configuration.mode,
};
}),
publishReplay(1),
refCount());
this._creatingConfiguration$
.subscribe(
(configuration: TagConfiguration): void => {
const type: ComponentEventType = "tagmode";
const event: ComponentTagModeEvent = {
mode: configuration.mode,
target: this,
type,
};
this.fire(type, event);
});
}
/**
* Add tags to the tag set or replace tags in the tag set.
*
* @description If a tag already in the set has the same
* id as one of the tags added, the old tag will be removed
* the added tag will take its place.
*
* @param {Array<Tag>} tags - Tags to add.
*
* @example
* ```js
* tagComponent.add([tag1, tag2]);
* ```
*/
public add(tags: Tag[]): void {
if (this._activated) {
this._navigator.stateService.currentTransform$.pipe(
first())
.subscribe(
(transform: Transform): void => {
this._tagSet.add(tags, transform);
const renderTags: RenderTag<Tag>[] = tags
.map(
(tag: Tag): RenderTag<Tag> => {
return this._tagSet.get(tag.id);
});
this._tagScene.add(renderTags);
});
} else {
this._tagSet.addDeactivated(tags);
}
}
/**
* Calculate the smallest rectangle containing all the points
* in the points geometry.
*
* @description The result may be different depending on if the
* current image is an spherical or not. If the
* current image is an spherical the rectangle may
* wrap the horizontal border of the image.
*
* @returns {Promise<Array<number>>} Promise to the rectangle
* on the format specified for the {@link RectGeometry} in basic
* coordinates.
*/
public calculateRect(geometry: PointsGeometry): Promise<number[]> {
return new Promise<number[]>((resolve: (value: number[]) => void, reject: (reason: Error) => void): void => {
this._navigator.stateService.currentTransform$.pipe(
first(),
map(
(transform: Transform): number[] => {
return geometry.getRect2d(transform);
}))
.subscribe(
(rect: number[]): void => {
resolve(rect);
},
(error: Error): void => {
reject(error);
});
});
}
/**
* Force the creation of a geometry programatically using its
* current vertices.
*
* @description The method only has an effect when the tag
* mode is either of the following modes:
*
* {@link TagMode.CreatePoints}
* {@link TagMode.CreatePolygon}
* {@link TagMode.CreateRect}
* {@link TagMode.CreateRectDrag}
*
* In the case of points or polygon creation, only the created
* vertices are used, i.e. the mouse position is disregarded.
*
* In the case of rectangle creation the position of the mouse
* at the time of the method call is used as one of the vertices
* defining the rectangle.
*
* @fires geometrycreate
*
* @example
* ```js
* tagComponent.on("geometrycreate", function(geometry) {
* console.log(geometry);
* });
*
* tagComponent.create();
* ```
*/
public create(): void {
this._tagCreator.replayedTag$.pipe(
first(),
filter(
(tag: CreateTag<Geometry>): boolean => {
return !!tag;
}))
.subscribe(
(tag: CreateTag<Geometry>): void => {
tag.create();
});
}
/**
* Change the current tag mode.
*
* @description Change the tag mode to one of the create modes for creating new geometries.
*
* @param {TagMode} mode - New tag mode.
*
* @fires tagmode
*
* @example
* ```js
* tagComponent.changeMode(TagMode.CreateRect);
* ```
*/
public changeMode(mode: TagMode): void {
this.configure({ mode: mode });
}
public fire(
type: "geometrycreate",
event: ComponentGeometryEvent)
: void;
public fire(
type: "tagmode",
event: ComponentTagModeEvent)
: void;
/** @ignore */
public fire(
type:
| "tagcreateend"
| "tagcreatestart"
| "tags",
event: ComponentStateEvent)
: void;
public fire<T>(
type: ComponentEventType,
event: T)
: void {
super.fire(type, event);
}
/**
* Returns the tag in the tag set with the specified id, or
* undefined if the id matches no tag.
*
* @param {string} tagId - Id of the tag.
*
* @example
* ```js
* var tag = tagComponent.get("tagId");
* ```
*/
public get(tagId: string): Tag {
if (this._activated) {
const renderTag: RenderTag<Tag> = this._tagSet.get(tagId);
return renderTag !== undefined ? renderTag.tag : undefined;
} else {
return this._tagSet.getDeactivated(tagId);
}
}
/**
* Returns an array of all tags.
*
* @example
* ```js
* var tags = tagComponent.getAll();
* ```
*/
public getAll(): Tag[] {
if (this.activated) {
return this._tagSet
.getAll()
.map(
(renderTag: RenderTag<Tag>): Tag => {
return renderTag.tag;
});
} else {
return this._tagSet.getAllDeactivated();
}
}
/**
* Returns an array of tag ids for tags that contain the specified point.
*
* @description The pixel point must lie inside the polygon or rectangle
* of an added tag for the tag id to be returned. Tag ids for
* tags that do not have a fill will also be returned if the point is inside
* the geometry of the tag. Tags with point geometries can not be retrieved.
*
* No tag ids will be returned for polygons rendered in cropped spherical or
* rectangles rendered in spherical.
*
* Notice that the pixelPoint argument requires x, y coordinates from pixel space.
*
* With this function, you can use the coordinates provided by mouse
* events to get information out of the tag component.
*
* If no tag at exist the pixel point, an empty array will be returned.
*
* @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
* @returns {Promise<Array<string>>} Promise to the ids of the tags that
* contain the specified pixel point.
*
* @example
* ```js
* tagComponent.getTagIdsAt([100, 100])
* .then((tagIds) => { console.log(tagIds); });
* ```
*/
public getTagIdsAt(pixelPoint: number[]): Promise<string[]> {
return new Promise<string[]>((resolve: (value: string[]) => void, reject: (reason: Error) => void): void => {
this._container.renderService.renderCamera$.pipe(
first(),
map(
(render: RenderCamera): string[] => {
const viewport: number[] = this._viewportCoords
.canvasToViewport(
pixelPoint[0],
pixelPoint[1],
this._container.container);
const ids: string[] = this._tagScene.intersectObjects(viewport, render.perspective);
return ids;
}))
.subscribe(
(ids: string[]): void => {
resolve(ids);
},
(error: Error): void => {
reject(error);
});
});
}
/**
* Check if a tag exist in the tag set.
*
* @param {string} tagId - Id of the tag.
*
* @example
* ```js
* var tagExists = tagComponent.has("tagId");
* ```
*/
public has(tagId: string): boolean {
return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
}
public off(
type: "geometrycreate",
handler: (event: ComponentGeometryEvent) => void)
: void;
public off(
type: "tagmode",
handler: (event: ComponentTagModeEvent) => void)
: void;
public off(
type:
| "tagcreateend"
| "tagcreatestart"
| "tags",
handler: (event: ComponentStateEvent) => void)
: void;
public off<T>(
type: ComponentEventType,
handler: (event: T) => void)
: void {
super.off(type, handler);
}
/**
* Event fired when a geometry has been created.
*
* @event geometrycreated
* @example
* ```js
* // Initialize the viewer
* var viewer = new Viewer({ // viewer options });
* var component = viewer.getComponent('<component-name>');
* // Set an event listener
* component.on('geometrycreated', function() {
* console.log("A geometrycreated event has occurred.");
* });
* ```
*/
public on(
type: "geometrycreate",
handler: (event: ComponentGeometryEvent) => void)
: void;
/**
* Event fired when an interaction to create a geometry ends.
*
* @description A create interaction can by a geometry being created
* or by the creation being aborted.
*
* @event tagcreateend
* @example
* ```js
* // Initialize the viewer
* var viewer = new Viewer({ // viewer options });
* var component = viewer.getComponent('<component-name>');
* // Set an event listener
* component.on('tagcreateend', function() {
* console.log("A tagcreateend event has occurred.");
* });
* ```
*/
public on(
type: "tagcreateend",
handler: (event: ComponentStateEvent) => void)
: void;
/**
* Event fired when an interaction to create a geometry starts.
*
* @description A create interaction starts when the first vertex
* is created in the geometry.
*
* @event tagcreatestart
* @example
* ```js
* // Initialize the viewer
* var viewer = new Viewer({ // viewer options });
* var component = viewer.getComponent('<component-name>');
* // Set an event listener
* component.on('tagcreatestart', function() {
* console.log("A tagcreatestart event has occurred.");
* });
* ```
*/
public on(
type: "tagcreatestart",
handler: (event: ComponentStateEvent) => void)
: void;
/**
* Event fired when the create mode is changed.
*
* @event tagmode
* @example
* ```js
* // Initialize the viewer
* var viewer = new Viewer({ // viewer options });
* var component = viewer.getComponent('<component-name>');
* // Set an event listener
* component.on('tagmode', function() {
* console.log("A tagmode event has occurred.");
* });
* ```
*/
public on(
type: "tagmode",
handler: (event: ComponentTagModeEvent) => void)
: void;
/**
* Event fired when the tags collection has changed.
*
* @event tags
* @example
* ```js
* // Initialize the viewer
* var viewer = new Viewer({ // viewer options });
* var component = viewer.getComponent('<component-name>');
* // Set an event listener
* component.on('tags', function() {
* console.log("A tags event has occurred.");
* });
* ```
*/
public on(
type: "tags",
handler: (event: ComponentStateEvent) => void)
: void;
public on<T>(
type: ComponentEventType,
handler: (event: T) => void)
: void {
super.on(type, handler);
}
/**
* Remove tags with the specified ids from the tag set.
*
* @param {Array<string>} tagIds - Ids for tags to remove.
*
* @example
* ```js
* tagComponent.remove(["id-1", "id-2"]);
* ```
*/
public remove(tagIds: string[]): void {
if (this._activated) {
this._tagSet.remove(tagIds);
this._tagScene.remove(tagIds);
} else {
this._tagSet.removeDeactivated(tagIds);
}
}
/**
* Remove all tags from the tag set.
*
* @example
* ```js
* tagComponent.removeAll();
* ```
*/
public removeAll(): void {
if (this._activated) {
this._tagSet.removeAll();
this._tagScene.removeAll();
} else {
this._tagSet.removeAllDeactivated();
}
}
protected _activate(): void {
this._editVertexHandler.enable();
const handlerGeometryCreated$ =
observableFrom(<(keyof typeof TagMode)[]>Object.keys(this._createHandlers)).pipe(
map(
(key: keyof typeof TagMode): CreateHandlerBase => {
return this._createHandlers[key];
}),
filter(
(handler: CreateHandlerBase): boolean => {
return !!handler;
}),
mergeMap(
(handler: CreateHandlerBase): Observable<Geometry> => {
return handler.geometryCreated$;
}),
share());
const subs = this._subscriptions;
subs.push(handlerGeometryCreated$
.subscribe(
(geometry: Geometry): void => {
const type: ComponentEventType = "geometrycreate";
const event: ComponentGeometryEvent = {
geometry,
target: this,
type,
};
this.fire(type, event);
}));
subs.push(this._tagCreator.tag$.pipe(
skipWhile(
(tag: CreateTag<Geometry>): boolean => {
return tag == null;
}),
distinctUntilChanged())
.subscribe(
(tag: CreateTag<Geometry>): void => {
const type: ComponentEventType = tag != null ?
"tagcreatestart" :
"tagcreateend";
const event: ComponentStateEvent = {
target: this,
type,
};
this.fire(type, event);
}));
subs.push(handlerGeometryCreated$
.subscribe(
(): void => {
this.changeMode(TagMode.Default);
}));
subs.push(this._creatingConfiguration$
.subscribe(
(configuration: TagConfiguration): void => {
this._disableCreateHandlers();
const mode: keyof typeof TagMode = <keyof typeof TagMode>TagMode[configuration.mode];
const handler: CreateHandlerBase = this._createHandlers[mode];
if (!!handler) {
handler.enable();
}
}));
subs.push(this._renderTags$
.subscribe(
(): void => {
const type: ComponentEventType = "tags";
const event: ComponentStateEvent = {
target: this,
type,
};
this.fire(type, event);
}));
subs.push(this._tagCreator.tag$.pipe(
switchMap(
(tag: CreateTag<Geometry>): Observable<void> => {
return tag != null ?
tag.aborted$.pipe(
map((): void => { return null; })) :
observableEmpty();
}))
.subscribe((): void => { this.changeMode(TagMode.Default); }));
subs.push(this._tagCreator.tag$
.subscribe(
(tag: CreateTag<Geometry>): void => {
if (this._tagScene.hasCreateTag()) {
this._tagScene.removeCreateTag();
}
if (tag != null) {
this._tagScene.addCreateTag(tag);
}
}));
subs.push(this._createGLObjectsChanged$
.subscribe(
(tag: CreateTag<Geometry>): void => {
this._tagScene.updateCreateTagObjects(tag);
}));
subs.push(this._renderTagGLChanged$
.subscribe(
(tag: RenderTag<Tag>): void => {
this._tagScene.updateObjects(tag);
}));
subs.push(this._tagChanged$
.subscribe(
(): void => {
this._tagScene.update();
}));
subs.push(observableCombineLatest(
this._renderTags$.pipe(
startWith([]),
tap(
(): void => {
this._container.domRenderer.render$.next({
name: this._name,
vNode: this._tagDomRenderer.clear(),
});
})),
this._container.renderService.renderCamera$,
this._container.spriteService.spriteAtlas$,
this._container.renderService.size$,
this._tagChanged$.pipe(startWith(null)),
observableMerge(
this._tagCreator.tag$,
this._createGeometryChanged$).pipe(startWith(null))).pipe(
map(
([renderTags, rc, atlas, size, , ct]:
[RenderTag<Tag>[], RenderCamera, ISpriteAtlas, ViewportSize, Tag, CreateTag<Geometry>]):
VirtualNodeHash => {
return {
name: this._name,
vNode: this._tagDomRenderer.render(renderTags, ct, atlas, rc.perspective, size),
};
}))
.subscribe(this._container.domRenderer.render$));
subs.push(this._navigator.stateService.currentState$.pipe(
map(
(frame: AnimationFrame): GLRenderHash => {
const tagScene: TagScene = this._tagScene;
return {
name: this._name,
renderer: {
frameId: frame.id,
needsRender: tagScene.needsRender,
render: tagScene.render.bind(tagScene),
pass: RenderPass.Opaque,
},
};
}))
.subscribe(this._container.glRenderer.render$));
this._navigator.stateService.currentTransform$.pipe(
first())
.subscribe(
(transform: Transform): void => {
this._tagSet.activate(transform);
this._tagScene.add(this._tagSet.getAll());
});
}
protected _deactivate(): void {
this._editVertexHandler.disable();
this._disableCreateHandlers();
this._tagScene.clear();
this._tagSet.deactivate();
this._tagCreator.delete$.next(null);
this._subscriptions.unsubscribe();
this._container.container.classList.remove("component-tag-create");
}
protected _getDefaultConfiguration(): TagConfiguration {
return {
createColor: 0xFFFFFF,
indicatePointsCompleter: true,
mode: TagMode.Default,
};
}
private _disableCreateHandlers(): void {
const createHandlers: {
[K in keyof typeof TagMode]:
CreateHandlerBase
} = this._createHandlers;
for (const key in createHandlers) {
if (!createHandlers.hasOwnProperty(key)) {
continue;
}
const handler =
createHandlers[<keyof typeof TagMode>key];
if (!!handler) {
handler.disable();
}
}
}
} | the_stack |
module BABYLON {
export module LeaderBoard {
export class Client {
public zumo: Microsoft.WindowsAzure.MobileServiceClient;
constructor(public applicationUrl: string, public applicationKey: string, public gameId: number, public masterKey?: string) {
// Check url / key
if (!applicationUrl || applicationUrl.length == 0)
throw new Error("applicationUrl required");
if (!applicationKey || applicationKey.length == 0)
throw new Error("applicationKey required");
try {
if (!masterKey || masterKey == "") {
this.zumo = new WindowsAzure.MobileServiceClient(applicationUrl, applicationKey);
}
else {
this.zumo = new WindowsAzure.MobileServiceClient(applicationUrl, applicationKey)
.withFilter((request: any, next: (request: any, callback: (error: any, response: any) => void) => void, callback: (error: any, response: any) => void) => {
request.headers['X-ZUMO-MASTER'] = masterKey;
next(request, callback);
});
}
this.getCurrentUser();
}
catch (e) {
throw new Error("can't initialize to Mobile Service");
}
}
public getCurrentUser(): Microsoft.WindowsAzure.User {
if (this.zumo.currentUser == null) {
this.zumo.currentUser = this._getSavedUser();
}
return this.zumo.currentUser;
}
private _saveUser() {
sessionStorage.setItem('babylonleaderboardclientuser', JSON.stringify(this.zumo.currentUser));
}
private _deleteUser() {
sessionStorage.clear();
}
private _getSavedUser(): Microsoft.WindowsAzure.User {
var uStr = sessionStorage.getItem('babylonleaderboardclientuser');
if (uStr == null) {
return null;
}
return <Microsoft.WindowsAzure.User>JSON.parse(uStr);
}
public logout() {
this._deleteUser();
this.zumo.logout();
}
public getLoginProvider() {
var profile = {
source: null,
id: null
};
if (this.getCurrentUser() == null) {
return profile;
}
var id = this.getCurrentUser().userId;
var sep = id.indexOf(':');
profile.source = id.substring(0, sep).toLowerCase();
profile.id = id.substring(sep + 1);
return profile;
}
public loginWithProfile(source: string, done: (chars: Character[]) => void, error?: (e) => void) {
var profile = this.getLoginProvider();
// already logged with correct provider
if (profile && profile.source == source) {
return this.getCharacterFromProfile(profile.source, done, error);
}
this.zumo.login(source, null, false, (err, user) => {
if (err != null) {
error(err);
return;
}
this._saveUser();
profile = this.getLoginProvider();
return this.getCharacterFromProfile(profile.source, done, error);
});
}
public loginWithFacebook(done: (chars: Character[]) => void, error?: (e) => void) {
return this.loginWithProfile('facebook', done, error);
}
public loginWithMicrosoft(done: (chars: Character[]) => void, error?: (e) => void) {
return this.loginWithProfile('microsoftaccount', done, error);
}
public loginWithGoogle(done: (chars: Character[]) => void, error?: (e) => void) {
return this.loginWithProfile('google', done, error);
}
public uploadBlob(file: File, done: (blob: any) => void, error?: (e) => void) {
this.getNewBlobUrl(file.name, (r: Array<any>) => {
if (r == null || r.length <= 0) {
return error('response from your blob storage is not valid');
}
// get the file url
var blobUrl = r[0].blobUrl;
var fileUrl = r[0].imageUrl;
// get a file reader
var reader = new FileReader();
// block size
var maxBlockSize = 1024 * 512;
// file pointer in blocks
var currentFilePointer = 0;
// remaining bytes
var totalBytesRemaining = 0;
// number of blocks
var numberOfBlocks = 1;
// blocks ids
var blockIds = new Array();
// uploads bytes
var bytesUploaded = 0;
// get file size
var fileSize = file.size;
totalBytesRemaining = fileSize;
// if size < 256ko
if (fileSize < maxBlockSize) {
maxBlockSize = fileSize;
}
// calculating the number of blocks needed
if (fileSize % maxBlockSize == 0) {
numberOfBlocks = fileSize / maxBlockSize;
} else {
numberOfBlocks = parseInt((fileSize / maxBlockSize).toString(), 10) + 1;
}
var _pad = (number, length) => {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
};
var _commitBlockList = () => {
var comp = '&comp=blockList';
var uri = blobUrl + comp;
//var requestBody = '<?xml version="1.0" encoding="utf-8"?>\n<BlockList>\n';
var requestBody = '<?xml version="1.0" encoding="utf-8"?>';
requestBody += '<BlockList>';
for (var i = 0; i < blockIds.length; i++) {
requestBody += '<Latest>' + blockIds[i] + '</Latest>';
}
requestBody += '</BlockList>';
var xhr = new XMLHttpRequest();
xhr.open('PUT', uri);
xhr.setRequestHeader('x-ms-blob-content-type', 'application/octet-stream');
xhr.setRequestHeader('Content-Length', requestBody.length.toString());
xhr.setRequestHeader('Content-Type', 'text/plain; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
done([fileUrl]);
}
};
xhr.send(requestBody);
};
var _uploadFileInBlocks = () => {
if (totalBytesRemaining <= 0) {
if (numberOfBlocks > 1) {
return _commitBlockList();
} else {
return done([fileUrl]);
}
}
// get the sliced content
var fileContent = file.slice(currentFilePointer, currentFilePointer + maxBlockSize);
//get the blockId
var blockId = "" + _pad(blockIds.length, 6);
// push in
blockIds.push(btoa(blockId));
// read it
reader.readAsArrayBuffer(fileContent);
currentFilePointer += maxBlockSize;
totalBytesRemaining -= maxBlockSize;
if (totalBytesRemaining < maxBlockSize) {
maxBlockSize = totalBytesRemaining;
}
};
var _readerLoad = (evt: any) => {
var comp = '';
if (numberOfBlocks > 1)
comp += '&comp=block&blockid=' + blockIds[blockIds.length - 1];
var uri = blobUrl + comp;
var requestData = new Uint8Array(reader.result);
var xhr = new XMLHttpRequest();
xhr.open('PUT', uri);
xhr.setRequestHeader('x-ms-blob-type', 'BlockBlob');
xhr.setRequestHeader('Content-Length', requestData.length.toString());
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
bytesUploaded += requestData.length;
var percentComplete = ((parseFloat(bytesUploaded.toString()) / parseFloat(file.size.toString())) * 100).toFixed(2);
_uploadFileInBlocks();
}
};
xhr.send(requestData);
};
reader.onload = (evt: any) => _readerLoad(evt);
_uploadFileInBlocks();
},
(err) => {
return error(err);
});
}
public uploadImage(file: File, done: (img: any) => void, error?: (e) => void) {
if (!file) {
return error('file is mandatory');
}
if (file.size > (500 * 1024)) {
return error('only small images (size < 512ko) are valid when you want to upload directly in database\nFor large file use uploadBlob instead.');
}
var allowedTypes = ['png', 'jpg', 'jpeg', 'gif'];
// get type and see if allowed
var imgType = file.type.toLowerCase(); // On utilise toLowerCase() pour éviter les extensions en majuscules
if (allowedTypes.indexOf(imgType) >= 0) {
return error('only images (PNG, JPG, JPEG, GIF) are authorized.');
}
var reader = new FileReader();
var req = 'image/' + this.gameId + '/set.json';
var z = this.zumo;
reader.onload = (e) => {
var data = reader.result;
data = data.replace(/^data:image\/(png|jpg|jpeg|gif);base64,/, "");
var image = {
name: file.name,
size: file.size,
type: file.type,
data: data
};
Util.zumoInvoker(z, req, "post", image, done, error);
};
reader.readAsDataURL(file);
//-------------------------------------------------------------------
// we can't use this method if we want use the MobileService SDK ..
//-------------------------------------------------------------------
//var req = 'image/upload';
//var xhr = new XMLHttpRequest();
//xhr.open('POST', 'https://babylonjs.azure-mobile.net/api/image/upload');
//xhr.upload.onprogress = function (e) {
// progress.value = e.loaded;
// progress.max = e.total;
//};
//xhr.onload = function () {
// console.log('Upload terminé !');
//};
//xhr.onreadystatechange = function () {
// if (xhr.readyState === 4) {
// done(xhr);
// }
//};
//var form = new FormData();
//form.append('image', file);
//xhr.send(form);
}
public getNewBlobUrl(blobName: string, done: (fileUrl: Array<any>) => void, error?: (e) => void) {
var req = 'image/' + this.gameId + '/getnewbloburl.json';
Util.zumoInvoker(this.zumo, req, "post", { fileName: blobName }, done, error);
}
// Game
public getGame(done: (game: Game) => void, error?: (e) => void) {
var req = 'games/' + this.gameId + '/fetch.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
public getBlobAccount(done: (blob: any) => void, error?: (e) => void) {
var req = 'games/' + this.gameId + '/get.json';
var game = {
id: this.gameId,
fields: 'blobAccountName,blobAccountKey,blobContainerName'
};
Util.zumoInvoker(this.zumo, req, "post", game, done, error);
}
// Characters
public addOrUpdateCharacter(character: Character, done?: (c: Character) => void, error?: (e) => void) {
var req = 'characters/' + this.gameId + '/set.json';
Util.zumoInvoker(this.zumo, req, "post", character, done, error);
}
public deleteCharacter(character: Character, done: (c: Character) => void, error?: (e) => void) {
var req = 'characters/' + this.gameId + '/del.json';
Util.zumoInvoker(this.zumo, req, "post", character, done, error);
}
public getCharactersCount(done: (count: number) => void, error?: (e) => void) {
var req = 'characters/' + this.gameId + '/count.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
public getCharacter(name: string, fields?: any, done?: (c: Character) => void, error?: (e) => void) {
// Absent optional arguments
if ((error == null || error == undefined) && (typeof fields === 'function')) {
error = <any>done;
done = <any>fields;
fields = null;
}
var req = "";
if (fields == null) {
req = 'characters/' + this.gameId + '/get/' + name + '.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
} else {
var params = fields;
params['where'] = {
gameId: this.gameId,
name: name
};
req = 'characters/' + this.gameId + '/get.json';
Util.zumoInvoker(this.zumo, req, "post", params, done, error);
}
}
public getCharacters(params?: any, done?: (c: Character[]) => void, error?: (e) => void) {
// Absent optional arguments
if ((error == null || error == undefined) && (typeof params === 'function')) {
error = <any>done;
done = <any>params;
params = null;
}
var req = "";
if (params == null) {
req = 'characters/' + this.gameId + '/all.json';
Util.zumoInvoker(this.zumo, req, 'get', null, done, error);
} else {
req = 'characters/' + this.gameId + '/get.json';
Util.zumoInvoker(this.zumo, req, 'post', params, done, error);
}
}
public getCharacterFromProfile(source: string, done: (characters: Character[]) => void, error?: (e) => void) {
if (this.getCurrentUser() == null) {
error('you need to be authenticated to get a character from social profile');
return;
}
if (source != 'facebook' && source != 'microsoftaccount' && source != 'google') {
error('This source is not authorized');
return;
}
var req = 'characters/' + this.gameId + '/me/' + source + '.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
public getFacebookProfile(done: any, error?: (e) => void) {
if (this.getCurrentUser() == null) {
error('you need to be authenticated to get a character from social profile');
return;
}
var req = 'characters/' + this.gameId + '/id/facebook.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
public getMicrosoftProfile(done: any, error?: (e) => void) {
if (this.getCurrentUser() == null) {
error('you need to be authenticated to get a character from social profile');
return;
}
var req = 'characters/' + this.gameId + '/id/microsoftaccount.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
public getGoogleProfile(done: any, error?: (e) => void) {
if (this.getCurrentUser() == null) {
error('you need to be authenticated to get a character from social profile');
return;
}
var req = 'characters/' + this.gameId + '/id/google.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
// Rewards
public getReward(rewardName: string, done: (c: Reward) => void, error?: (e) => void) {
var req = 'rewards/' + this.gameId + '/get/' + rewardName + '.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
public addOrUpdateReward(reward: Reward, done: (c: Reward) => void, error?: (e) => void) {
var req = 'rewards/' + this.gameId + '/set.json';
Util.zumoInvoker(this.zumo, req, "post", reward, done, error);
}
public deleteReward(reward: Reward, done: (c: Reward) => void, error?: (e) => void) {
var req = 'rewards/' + this.gameId + '/del.json';
Util.zumoInvoker(this.zumo, req, "post", reward, done, error);
}
public getRewards(params?: any, done?: (c: Reward) => void, error?: (e) => void) {
// Absent optional arguments
if ((error == null || error == undefined) && (typeof params === 'function')) {
error = <any>done;
done = <any>params;
params = null;
}
var req = "";
if (params == null) {
req = 'rewards/' + this.gameId + '/all.json';
Util.zumoInvoker(this.zumo, req, 'get', null, done, error);
} else {
req = 'rewards/' + this.gameId + '/get.json';
Util.zumoInvoker(this.zumo, req, 'post', params, done, error);
}
}
public getRewardsCount(done: (count: number) => void, error?: (e) => void) {
var req = 'rewards/' + this.gameId + '/count.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
// Achievements
public getAchievement(achievementName: string, done: (c: Achievement) => void, error?: (e) => void) {
var req = 'achievements/' + this.gameId + '/get/' + achievementName + '.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
public addOrUpdateAchievement(achievement: Achievement, done: (c: Achievement) => void, error?: (e) => void) {
var req = 'achievements/' + this.gameId + '/set.json';
Util.zumoInvoker(this.zumo, req, "post", achievement, done, error);
}
public deleteAchievement(achievement: Achievement, done: (c: Achievement) => void, error?: (e) => void) {
var req = 'achievements/' + this.gameId + '/del.json';
Util.zumoInvoker(this.zumo, req, "post", achievement, done, error);
}
public getAchievements(params?: any, done?: (c: Achievement[]) => void, error?: (e) => void) {
// Optional arguments
if ((error == null || error == undefined) && (typeof params === 'function')) {
error = <any>done;
done = <any>params;
params = null;
}
var req = "";
if (params == null) {
req = 'achievements/' + this.gameId + '/all.json';
Util.zumoInvoker(this.zumo, req, 'get', null, done, error);
} else {
req = 'achievements/' + this.gameId + '/get.json';
Util.zumoInvoker(this.zumo, req, 'post', params, done, error);
}
}
public getAchievementsCount(done: (count: number) => void, error?: (e) => void) {
var req = 'achievements/' + this.gameId + '/count.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
// Character rewards
public getCharacterRewards(characterName: string, done: (rewards: any[]) => void, error?: (e) => void) {
var req = 'characterrewards/' + this.gameId + '/get/' + characterName + '.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
public addOrUpdateCharacterReward(cr: any, done: (c: any) => void, error?: (e) => void) {
var req = 'characterrewards/' + this.gameId + '/set.json';
Util.zumoInvoker(this.zumo, req, "post", cr, done, error);
}
public deleteCharacterReward(cr: any, done: (c: any) => void, error?: (e) => void) {
var req = 'characterrewards/' + this.gameId + '/del.json';
Util.zumoInvoker(this.zumo, req, "post", cr, done, error);
}
// Character Scores
public getCharacterScores(characterName: string, done: (scores: any[]) => void, error?: (e) => void) {
var req = 'characterscores/' + this.gameId + '/get/' + characterName + '.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
public addOrUpdateCharacterScore(cr: any, done: (c: any) => void, error?: (e) => void) {
var req = 'characterscores/' + this.gameId + '/set.json';
Util.zumoInvoker(this.zumo, req, "post", cr, done, error);
}
public deleteCharacterScore(cr: any, done: (c: any) => void, error?: (e) => void) {
var req = 'characterscores/' + this.gameId + '/del.json';
Util.zumoInvoker(this.zumo, req, "post", cr, done, error);
}
// email
public sendEmail(email: any, done: (r: any) => void, error?: (e) => void) {
if (!email.to)
throw new Error("to required");
if (!email.from)
throw new Error("from required");
if (!email.subject)
throw new Error("subject required");
if (!email.text)
throw new Error("text required");
var req = 'emails/' + this.gameId + '/sendemail.json';
Util.zumoInvoker(this.zumo, req, 'post', email, done, error);
}
}
export class Setup {
zumo: Microsoft.WindowsAzure.MobileServiceClient;
constructor(public applicationUrl: string, public applicationKey: string, public masterKey?: string) {
// Check url / key
if (!applicationUrl || applicationUrl.length == 0)
throw new Error("applicationUrl required");
if (!applicationKey || applicationKey.length == 0)
throw new Error("applicationKey required");
try {
if (!masterKey || masterKey == "") {
this.zumo = new WindowsAzure.MobileServiceClient(applicationUrl, applicationKey);
}
else {
this.zumo = new WindowsAzure.MobileServiceClient(applicationUrl, applicationKey)
.withFilter((request: any, next: (request: any, callback: (error: any, response: any) => void) => void, callback: (error: any, response: any) => void) => {
request.headers['X-ZUMO-MASTER'] = masterKey;
next(request, callback);
});
}
}
catch (e) {
throw new Error("can't initialize to Mobile Service");
}
}
public getCors(gameId: number, done: (c: any[]) => void, error: (e: any) => void) {
try {
var req = 'blob/' + gameId + '/getCors.json';
Util.zumoInvoker(this.zumo, req, 'get', null, done, error);
} catch (e) {
error(e);
}
}
public setCors(gameId: number, done: (c: any[]) => void, error: (e: any) => void) {
try {
var req = 'blob/' + gameId + '/setCors.json';
Util.zumoInvoker(this.zumo, req, 'get', null, done, error);
} catch (e) {
error(e);
}
}
public getTableCharacter(done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('character').read().done(
(chars: any[]) => done(chars),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public insertTableCharacter(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('character').insert(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public updateTableCharacter(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('character').update(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public deleteTableCharacter(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('character').del(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public getTableAchievement(done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('achievement').read().done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public insertTableAchievement(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('achievement').insert(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public updateTableAchievement(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('achievement').update(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public deleteTableAchievement(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('achievement').del(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public getTableCharacterReward(done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('characterReward').read().done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public insertTableCharacterReward(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('characterReward').insert(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public updateTableCharacterReward(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('characterReward').update(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public deleteTableCharacterReward(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('characterReward').del(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public getTableCharacterScore(done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('characterScore').read().done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public insertTableCharacterScore(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('characterScore').insert(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public updateTableCharacterScore(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('characterScore').update(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public deleteTableCharacterScore(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('characterScore').del(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public getTableGame(done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('game').read().done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public insertTableGame(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('game').insert(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public updateTableGame(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('game').update(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public deleteTableGame(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('game').del(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public getTableImage(done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('image').read().done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public insertTableImage(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('image').insert(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public updateTableImage(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('image').update(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public deleteTableImage(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('image').del(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public getTableReward(done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('reward').read().done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public insertTableReward(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('reward').insert(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public updateTableReward(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('reward').update(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public deleteTableReward(instance: any, done: (c: any[]) => void, error: (e: any) => void) {
try {
this.zumo.getTable('reward').del(instance).done(
(r: any[]) => done(r),
(err: any) => error(err));
} catch (e) {
error(e);
}
}
public dropDatabase(done: (res: any) => void, error: (e: any) => void) {
try {
var req = 'setupGame/dropDatabase.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
} catch (e) {
error(e);
}
}
public getGame(gameId: number, done: (game: Game) => void, error?: (e) => void) {
var req = 'games/' + gameId + '/fetch.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
}
public getGames(done: (res: Game[]) => void, error: (e: any) => void) {
try {
var req = 'games/all.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
} catch (e) {
error(e);
}
}
public deleteGame(gameId: number, done: (res: any) => void, error: (e: any) => void) {
try {
if (!gameId)
throw new Error("gameId required");
var req = 'setupGame/deleteGame/' + gameId + '.json';
Util.zumoInvoker(this.zumo, req, "get", gameId, done, error);
} catch (e) {
error(e);
}
}
public deleteGames(done: (res: any) => void, error: (e: any) => void) {
try {
var req = 'setupGame/deleteGames.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
} catch (e) {
error(e);
}
}
public createSampleDatas(gameId: number, done: (res: any) => void, error: (e: any) => void) {
try {
var req = 'setupGame/createSample/' + gameId + '.json';
Util.zumoInvoker(this.zumo, req, "get", null, done, error);
} catch (e) {
error(e);
}
}
public createGame(game: Game, char: Character, done: (res: any) => void, error: (e: any) => void) {
var req = 'setupGame/createGame.json';
try {
if (Util.isNullOrEmpty(game.name))
throw new Error("The game name is required");
if (Util.isNullOrEmpty(char.name))
throw new Error("The character name is required");
if (Util.isNullOrEmpty(char.email))
throw new Error("The character email is required");
Util.zumoInvoker(this.zumo, req, "post", [game, char], done, error);
}
catch (e) {
error(e);
}
}
public setBlobAccount(gameId: number, blobAccountName: string, blobAccountKey: string, blobContainerName: string, done: (blob: any) => void, error?: (e: any) => void) {
var req = 'games/' + gameId + '/set.json';
if (!gameId)
throw new Error("The game id is required");
if (!blobAccountName)
throw new Error("The blobAccountName is required");
if (!blobAccountKey)
throw new Error("The blobAccountKey is required");
if (!blobContainerName)
throw new Error("The blobContainerName is required");
var game = {
id: gameId,
blobAccountName: blobAccountName,
blobAccountKey: blobAccountKey,
blobContainerName: blobContainerName,
fields: 'id,blobAccountName,blobAccountKey,blobContainerName'
};
try {
Util.zumoInvoker(this.zumo, req, "post", game, done, error);
} catch (e) {
error(e);
}
}
public setSendgridAccount(gameId: number, sendgridSmtpServer: string, sendgridUsername: string, sendgridPassword: string, done: (blob: any) => void, error?: (e: any) => void) {
var req = 'games/' + gameId + '/set.json';
if (!gameId)
throw new Error("The game id is required");
if (!sendgridSmtpServer)
throw new Error("The sendgridSmtpServer is required");
if (!sendgridUsername)
throw new Error("The sendgridUsername is required");
if (!sendgridPassword)
throw new Error("The sendgridPassword is required");
var game = {
id: gameId,
sendgridSmtpServer: sendgridSmtpServer,
sendgridUsername: sendgridUsername,
sendgridPassword: sendgridPassword,
fields: 'id,sendgridSmtpServer,sendgridUsername,sendgridPassword'
};
try {
Util.zumoInvoker(this.zumo, req, "post", game, done, error);
} catch (e) {
error(e);
}
}
public updateGame(game: Game, done: (g: Game) => void, error?: (e) => void) {
var req = 'games/' + game.id + '/set.json';
try {
Util.zumoInvoker(this.zumo, req, "post", game, done, error);
} catch (e) {
error(e);
}
}
}
export class Util {
public static zumoInvoker(zumo: Microsoft.WindowsAzure.MobileServiceClient, url: string, method: string, options: any, done: (res: any) => void, error?: (e: any) => void) {
error = error != null ? error : (e) => console.error(e);
done = done != null ? done : (r) => { };
zumo.invokeApi(url, { method: method, parameters: null, body: options })
.done(response => {
if (!response.result || response.result == 0) {
if (done != null)
done([]);
return;
}
if (response.error) {
if (error != null)
error(response);
return;
}
if (done != null)
done(response.result);
}, e => {
if (error != null)
error(e.message);
});
}
public static directInvoker(options: any, done: (res: any) => void, error?: (e: any) => void) {
error = error != null ? error : (e) => console.error(e);
done = done != null ? done : (r) => { };
var headers = options.headers || {},
url = options.url.replace(/#.*$/, ""),
httpMethod = options.type ? options.type.toUpperCase() : "GET",
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
done(xhr);
}
};
xhr.open(httpMethod, url);
for (var key in headers) {
if (options.headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, options.headers[key]);
}
}
xhr.send(options.data);
}
public static isNull(value: any) {
return value === null || value === undefined;
}
public static isNullOrZero(value: any) {
return value === null || value === undefined || value === 0 || value === '';
}
public static isNullOrEmpty(value: any) {
return Util.isNull(value) || value.length === 0;
}
public static format(message: string) {
if (!Util.isNullOrEmpty(message) && arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
var pattern = '{' + (i - 1) + '}';
while (message.indexOf(pattern) !== -1) {
message = message.replace(pattern, arguments[i]);
}
}
}
return message;
}
public static has(value: any, key: any) {
return !Util.isNull(value) && value.hasOwnProperty(key);
}
public static hasProperty(object: any, properties: any) {
for (var i = 0; i < properties.length; i++) {
if (Util.has(object, properties[i])) {
return true;
}
}
return false;
}
public static isObject(value: any) {
return Util.isNull(value) || (typeof value === 'object' && !Util.isDate(value));
}
public static isString(value: any) {
return Util.isNull(value) || (typeof value === 'string');
}
public static isNumber(value: any) {
return !Util.isNull(value) && (typeof value === 'number');
}
public static isBool(value: any) {
return !Util.isNull(value) && (typeof value == 'boolean');
}
public static classOf(value) {
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
public static isDate(value: any) {
return !Util.isNull(value) && (Util.classOf(value) == 'date');
}
public static pad(value: any, length: any, ch: any) {
var text = value.toString();
while (text.length < length) {
text = ch + text;
}
return text;
}
public static trimEnd(text: any, ch: any) {
var end = text.length - 1;
while (end >= 0 && text[end] === ch) {
end--;
}
return end >= 0 ? text.substr(0, end + 1) : '';
}
public static trimStart(text: any, ch: any) {
var start = 0;
while (start < text.length && text[start] === ch) {
start++;
}
return start < text.length ?
text.substr(start, text.length - start) :
'';
}
public static compareCaseInsensitive(first: any, second: any) {
if (Util.isString(first) && !Util.isNullOrEmpty(first)) {
first = first.toUpperCase();
}
if (Util.isString(first) && !Util.isNullOrEmpty(second)) {
second = second.toUpperCase();
}
return first === second;
}
public static tryParseIsoDateString(text: any) {
// Matches an ISO date and separates out the fractional part of the seconds
// because IE < 10 has quirks parsing fractional seconds
var isoDateRegex = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d*))?Z$/;
// Check against a lenient regex
var matchedDate = isoDateRegex.exec(text);
if (matchedDate) {
// IE9 only handles precisely 0 or 3 decimal places when parsing ISO dates,
// and IE8 doesn't parse them at all. Fortunately, all browsers can handle
// 'yyyy/mm/dd hh:MM:ss UTC' (without fractional seconds), so we can rewrite
// the date to that format, and the apply fractional seconds.
var dateWithoutFraction = matchedDate[1],
fraction = matchedDate[2] || "0",
milliseconds = Math.round(1000 * Number("0." + fraction)); // 6 -> 600, 65 -> 650, etc.
dateWithoutFraction = dateWithoutFraction
.replace(/\-/g, "/") // yyyy-mm-ddThh:mm:ss -> yyyy/mm/ddThh:mm:ss
.replace("T", " "); // yyyy/mm/ddThh:mm:ss -> yyyy/mm/dd hh:mm:ss
// Try and parse - it will return NaN if invalid
var ticks = Date.parse(dateWithoutFraction + " UTC");
if (!isNaN(ticks)) {
return new Date(ticks + milliseconds); // ticks are just milliseconds since 1970/01/01
}
}
// Doesn't look like a date
return null;
}
}
export class Game {
id: number;
name: string;
shortDescription: string;
longDescription: string;
blobAccountName: string;
blobAccountKey: string;
blobContainerName: string;
sendgridSmtpServer: string;
sendgridPassword: string;
sendgridUsername: string;
createdDate: Date;
updatedDate: Date;
levelsCount: number;
platform: string;
gameUrl: string;
websiteUrl: string;
playersCount: number;
status: boolean;
iconFile: string;
}
export class Reward {
id: number;
gameId: number;
name: string;
points: number;
shortDescription: string;
longDescription: string;
createdDate: Date;
updatedDate: Date;
}
export class CharacterScore {
id: number;
gameId: number;
characterId: number;
score: number;
createdDate: Date;
updatedDate: Date;
}
export class CharacterReward {
id: number;
gameId: number;
characterId: number;
rewardId: number;
points: number;
createdDate: Date;
updatedDate: Date;
obtentionDate: Date;
}
export class Achievement {
id: number;
name: string;
shortDescription: string;
longDescription: string;
createdDate: Date;
updatedDate: Date;
obtentionDate: Date;
points: number;
iconFile: string;
}
export class Character {
id: number;
gameId: number;
name: string;
email: string;
firstName: string;
lastName: string;
createdDate: Date;
updatedDate: Date;
facebookId: string;
twitterId: string;
googleId: string;
liveId: string;
imageUrl: string;
achievementsPoints: number;
kills: number;
lives: number;
rank: number;
timePlayed: number;
inventory: string;
lastLevel: number;
currentLevel: number;
currentGolds: number;
currentLives: number;
experience: number;
latitude: number;
longitude: number;
}
}
} | the_stack |
import { ethers } from 'hardhat'
import { Interface, LogDescription } from '@ethersproject/abi'
import { Signer } from '@ethersproject/abstract-signer'
import { BigNumberish, BigNumber } from '@ethersproject/bignumber'
import { BytesLike, hexDataLength } from '@ethersproject/bytes'
import { ContractTransaction, PayableOverrides } from '@ethersproject/contracts'
import { Provider } from '@ethersproject/providers'
import { RollupUserFacet, RollupAdminFacet } from '../../build/types'
export interface ExecutionState {
machineHash: BytesLike
inboxCount: BigNumberish
gasUsed: BigNumberish
sendCount: BigNumberish
logCount: BigNumberish
sendAcc: BytesLike
logAcc: BytesLike
}
export interface Assertion {
beforeState: ExecutionState
afterState: ExecutionState
}
export interface Node {
proposedBlock: number
assertion: Assertion
inboxMaxCount: BigNumberish
nodeHash: BytesLike
}
export function nodeHash(
hasSibling: boolean,
lastHash: BytesLike,
assertionExecHash: BytesLike,
inboxAcc: BytesLike
): BytesLike {
return ethers.utils.solidityKeccak256(
['bool', 'bytes32', 'bytes32', 'bytes32'],
[hasSibling, lastHash, assertionExecHash, inboxAcc]
)
}
type AssertionBytes32Fields = [BytesLike, BytesLike, BytesLike]
type AssertionIntFields = [
BigNumberish,
BigNumberish,
BigNumberish,
BigNumberish
]
export interface NodeCreatedEvent {
nodeNum: BigNumberish
parentNodeHash: BytesLike
nodeHash: BytesLike
executionHash: BytesLike
inboxMaxCount: BigNumberish
afterInboxAcc: BytesLike
assertionBytes32Fields: [AssertionBytes32Fields, AssertionBytes32Fields]
assertionIntFields: [AssertionIntFields, AssertionIntFields]
}
export function challengeRestHash(e: ExecutionState): BytesLike {
return ethers.utils.solidityKeccak256(
['uint256', 'bytes32', 'bytes32', 'uint256', 'bytes32', 'uint256'],
[e.inboxCount, e.machineHash, e.sendAcc, e.sendCount, e.logAcc, e.logCount]
)
}
export function challengeHash(e: ExecutionState): BytesLike {
return ethers.utils.solidityKeccak256(
['uint256', 'bytes32'],
[e.gasUsed, challengeRestHash(e)]
)
}
function executionStateBytes32Fields(
e: ExecutionState
): AssertionBytes32Fields {
return [e.machineHash, e.sendAcc, e.logAcc]
}
function executionStateIntFields(e: ExecutionState): AssertionIntFields {
return [e.gasUsed, e.inboxCount, e.sendCount, e.logCount]
}
export function nodeStateHash(n: Node): string {
return ethers.utils.solidityKeccak256(
[
'uint256',
'bytes32',
'uint256',
'uint256',
'uint256',
'bytes32',
'bytes32',
'uint256',
'uint256',
],
[
n.assertion.afterState.gasUsed,
n.assertion.afterState.machineHash,
n.assertion.afterState.inboxCount,
n.assertion.afterState.sendCount,
n.assertion.afterState.logCount,
n.assertion.afterState.sendAcc,
n.assertion.afterState.logAcc,
n.proposedBlock,
n.inboxMaxCount,
]
)
}
export function assertionGasUsed(a: Assertion): BigNumber {
return ethers.BigNumber.from(a.afterState.gasUsed).sub(a.beforeState.gasUsed)
}
export function assertionExecutionHash(a: Assertion): BytesLike {
return ethers.utils.solidityKeccak256(
['uint256', 'uint256', 'bytes32', 'bytes32'],
[
a.beforeState.gasUsed,
assertionGasUsed(a),
challengeHash(a.beforeState),
challengeHash(a.afterState),
]
)
}
export function makeAssertion(
beforeState: ExecutionState,
gasUsed: BigNumberish,
afterMachineHash: BytesLike,
messages: BytesLike[],
sends: BytesLike[],
logs: BytesLike[]
): Assertion {
function buildAccumulator(base: BytesLike, vals: BytesLike[]): BytesLike {
let acc = base
for (const h of vals.map(val => ethers.utils.keccak256(val))) {
acc = ethers.utils.solidityKeccak256(['bytes32', 'bytes32'], [acc, h])
}
return acc
}
return {
beforeState: beforeState,
afterState: {
machineHash: afterMachineHash,
inboxCount: ethers.BigNumber.from(beforeState.inboxCount).add(
messages.length
),
gasUsed: ethers.BigNumber.from(beforeState.gasUsed).add(gasUsed),
sendCount: ethers.BigNumber.from(beforeState.sendCount).add(sends.length),
logCount: ethers.BigNumber.from(beforeState.logCount).add(logs.length),
sendAcc: buildAccumulator(beforeState.sendAcc, sends),
logAcc: buildAccumulator(beforeState.logAcc, logs),
},
}
}
async function nodeFromNodeCreatedLog(
blockNumber: number,
log: LogDescription
): Promise<{ node: Node; event: NodeCreatedEvent }> {
if (log.name != 'NodeCreated') {
throw Error('wrong event type')
}
const parsedEv = log as any as {
args: NodeCreatedEvent
}
const ev = parsedEv.args
const node = {
proposedBlock: blockNumber,
assertion: {
beforeState: {
machineHash: ev.assertionBytes32Fields[0][0],
inboxCount: ev.assertionIntFields[0][1],
gasUsed: ev.assertionIntFields[0][0],
sendCount: ev.assertionIntFields[0][2],
logCount: ev.assertionIntFields[0][3],
sendAcc: ev.assertionBytes32Fields[0][1],
logAcc: ev.assertionBytes32Fields[0][2],
},
afterState: {
machineHash: ev.assertionBytes32Fields[1][0],
inboxCount: ev.assertionIntFields[1][1],
gasUsed: ev.assertionIntFields[1][0],
sendCount: ev.assertionIntFields[1][2],
logCount: ev.assertionIntFields[1][3],
sendAcc: ev.assertionBytes32Fields[1][1],
logAcc: ev.assertionBytes32Fields[1][2],
},
},
inboxMaxCount: ev.inboxMaxCount,
nodeHash: ev.nodeHash,
}
const event = parsedEv.args
return { node, event }
}
async function nodeFromTx(
abi: Interface,
tx: ContractTransaction
): Promise<{ node: Node; event: NodeCreatedEvent }> {
const receipt = await tx.wait()
if (receipt.logs == undefined) {
throw Error('expected receipt to have logs')
}
const evs = receipt.logs
.map(log => {
try {
return abi.parseLog(log)
} catch (e) {
return undefined
}
})
.filter(ev => ev && ev.name == 'NodeCreated')
if (evs.length != 1) {
throw Error('unique event not found')
}
return nodeFromNodeCreatedLog(receipt.blockNumber, evs[0]!)
}
export class RollupContract {
constructor(public rollup: RollupUserFacet) {}
connect(signerOrProvider: Signer | Provider | string): RollupContract {
return new RollupContract(this.rollup.connect(signerOrProvider))
}
newStake(overrides: PayableOverrides = {}): Promise<ContractTransaction> {
return this.rollup.newStake(overrides)
}
async stakeOnNewNode(
parentNode: Node,
assertion: Assertion,
afterInboxAcc: BytesLike,
batchProof: BytesLike,
prevNode?: Node
): Promise<{ tx: ContractTransaction; node: Node; event: NodeCreatedEvent }> {
if (!prevNode) {
prevNode = parentNode
}
const isChild =
challengeHash(prevNode.assertion.afterState) ==
challengeHash(assertion.beforeState)
const newNodeHash = ethers.utils.solidityKeccak256(
['bool', 'bytes32', 'bytes32', 'bytes32'],
[
!isChild,
prevNode.nodeHash,
assertionExecutionHash(assertion),
afterInboxAcc,
]
)
const tx = await this.rollup.stakeOnNewNode(
newNodeHash,
[
executionStateBytes32Fields(assertion.beforeState),
executionStateBytes32Fields(assertion.afterState),
],
[
executionStateIntFields(assertion.beforeState),
executionStateIntFields(assertion.afterState),
],
parentNode.proposedBlock,
parentNode.inboxMaxCount,
batchProof
)
const { node, event } = await nodeFromTx(this.rollup.interface, tx)
return { tx, node, event }
}
stakeOnExistingNode(
nodeNum: BigNumberish,
nodeHash: BytesLike
): Promise<ContractTransaction> {
return this.rollup.stakeOnExistingNode(nodeNum, nodeHash)
}
confirmNextNode(
prevSendAcc: BytesLike,
prevSendCount: BigNumberish,
sends: BytesLike[],
afterlogAcc: BytesLike,
afterLogCount: BigNumberish
): Promise<ContractTransaction> {
const messageData = ethers.utils.concat(sends)
const messageLengths = sends.map(msg => hexDataLength(msg))
return this.rollup.confirmNextNode(
prevSendAcc,
messageData,
messageLengths,
BigNumber.from(prevSendCount).add(sends.length),
afterlogAcc,
afterLogCount
)
}
rejectNextNode(stakerAddress: string): Promise<ContractTransaction> {
return this.rollup.rejectNextNode(stakerAddress)
}
async createChallenge(
staker1Address: string,
nodeNum1: BigNumberish,
staker2Address: string,
nodeNum2: BigNumberish,
node1: Node,
node2: Node
): Promise<ContractTransaction> {
return this.rollup.createChallenge(
[staker1Address, staker2Address],
[nodeNum1, nodeNum2],
[
assertionExecutionHash(node1.assertion),
assertionExecutionHash(node2.assertion),
],
[node1.proposedBlock, node2.proposedBlock],
[
node1.assertion.afterState.inboxCount,
node2.assertion.afterState.inboxCount,
]
)
}
addToDeposit(
staker: string,
overrides: PayableOverrides = {}
): Promise<ContractTransaction> {
return this.rollup.addToDeposit(staker, overrides)
}
reduceDeposit(amount: BigNumberish): Promise<ContractTransaction> {
return this.rollup.reduceDeposit(amount)
}
returnOldDeposit(stakerAddress: string): Promise<ContractTransaction> {
return this.rollup.returnOldDeposit(stakerAddress)
}
// removeZombieStaker(
// nodeNum: BigNumberish,
// stakerAddress: string
// ): Promise<ContractTransaction> {
// return this.rollup.removeZombieStaker(nodeNum, stakerAddress)
// }
latestConfirmed(): Promise<BigNumber> {
return this.rollup.latestConfirmed()
}
getNode(index: BigNumberish): Promise<string> {
return this.rollup.getNode(index)
}
// async inboxMaxValue(): Promise<BytesLike> {
// const bridgeAddress = await this.rollup.delayedBridge()
// const Bridge = await ethers.getContractFactory('Bridge')
// const bridge = Bridge.attach(bridgeAddress) as Bridge
// const inboxInfo = await bridge.inboxInfo()
// return inboxInfo[1]
// }
currentRequiredStake(): Promise<BigNumber> {
return this.rollup.currentRequiredStake()
}
}
export async function forceCreateNode(
rollupAdmin: RollupAdminFacet,
newNodeHash: BytesLike,
assertion: Assertion,
batchProof: BytesLike,
prevNode: Node,
prevNodeIndex: BigNumberish
): Promise<{ tx: ContractTransaction; node: Node; event: NodeCreatedEvent }> {
const tx = await rollupAdmin.forceCreateNode(
newNodeHash,
[
executionStateBytes32Fields(assertion.beforeState),
executionStateBytes32Fields(assertion.afterState),
],
[
executionStateIntFields(assertion.beforeState),
executionStateIntFields(assertion.afterState),
],
batchProof,
prevNode.proposedBlock,
prevNode.inboxMaxCount,
prevNodeIndex
)
const { node, event } = await nodeFromTx(rollupAdmin.interface, tx)
return { tx, node, event }
} | the_stack |
import React from 'react'
import classNames from 'classnames'
import { findDOMNode } from 'react-dom'
import { Button, Icon } from '@blueprintjs/core'
import { FaCheckCircle, FaRegCircle } from 'react-icons/fa'
import { msg } from 'common/i18n/i18n'
import CancelablePromise, { isCancelError } from 'common/util/CancelablePromise'
import { bindMany, getErrorCode } from 'common/util/LangUtil'
import { PhotoId, Photo, PhotoSectionId } from 'common/CommonTypes'
import { LibrarySelectionController } from 'app/controller/LibrarySelectionController'
import { formatCommandLabel } from 'app/controller/HotkeyController'
import { selectionButtonSize, toolbarHeight } from 'app/style/variables'
import { JustifiedLayoutBox } from 'app/UITypes'
import RedCheckCircle from 'app/ui/widget/icon/RedCheckCircle'
import './Picture.less'
export const showDetailsCombo = 'enter'
export const toggleSelectedCombo = 'space'
export interface Props {
className?: any
inSelectionMode: boolean
sectionId: PhotoSectionId
photo: Photo
layoutBox: JustifiedLayoutBox
/** Whether this photo is the active photo (which has the keyboard focus) */
isActive: boolean
isSelected: boolean
/**
* Whether this photo is pre-(de)-selected. E.g. if the user holds the shift key while hovering another photo
* and this photo is between the active photo and the hovered photo.
* Is `undefined` if this photo is not pre-(de)-selected, `true` if it is preselected and
* `false` if it is pre-deselected.
*/
preselected?: boolean
librarySelectionController: LibrarySelectionController
getThumbnailSrc: (photo: Photo) => string
createThumbnail: (sectionId: PhotoSectionId, photo: Photo) => CancelablePromise<string>
showPhotoDetails(sectionId: PhotoSectionId, photoId: PhotoId): void
}
interface State {
thumbnailSrc: string | null
// We hide buttons using the `isHovered` state instead of a CSS rule, so the markup stays thin for most of the pictures.
isHovered: boolean
isThumbnailLoaded: boolean
thumbnailError: 'master-missing' | 'create-failed' | 'load-failed' | null
}
export default class Picture extends React.Component<Props, State> {
private mainRef: React.RefObject<HTMLDivElement>
private createThumbnailPromise: CancelablePromise<void> | null = null
private delayedUpdateTimout: number | null = null
constructor(props: Props) {
super(props)
bindMany(this, 'onMouseEnter', 'onMouseLeave', 'onToggleSelection', 'onSetPhotoActive', 'onShowDetails',
'onThumnailChange', 'onThumbnailLoad', 'onThumbnailLoadError')
this.state = {
thumbnailSrc: this.props.getThumbnailSrc(props.photo),
isHovered: false,
isThumbnailLoaded: false,
thumbnailError: null,
}
this.mainRef = React.createRef()
}
componentDidMount() {
window.addEventListener('edit:thumnailChange', this.onThumnailChange)
}
componentDidUpdate(prevProps: Props, prevState: State) {
const { props } = this
if (props.photo.id != prevProps.photo.id) {
if (this.delayedUpdateTimout) {
window.clearTimeout(this.delayedUpdateTimout)
}
if (this.createThumbnailPromise) {
this.createThumbnailPromise.cancel()
this.createThumbnailPromise = null
}
this.setState({
thumbnailSrc: this.props.getThumbnailSrc(this.props.photo),
isThumbnailLoaded: false,
thumbnailError: null,
})
}
if (props.isActive && props.isActive !== prevProps.isActive) {
const mainEl = findDOMNode(this.mainRef.current) as HTMLElement
const rect = mainEl.getBoundingClientRect()
let scrollParentElem = mainEl.parentElement
while (scrollParentElem && scrollParentElem.scrollHeight <= scrollParentElem.clientHeight) {
scrollParentElem = scrollParentElem.parentElement
}
if (scrollParentElem) {
const scrollParentRect = scrollParentElem.getBoundingClientRect()
const extraSpacingTop = 10
const extraSpacingBottom = 10 + toolbarHeight
if (rect.bottom > scrollParentRect.bottom) {
scrollParentElem.scrollTop += rect.bottom - scrollParentRect.bottom + extraSpacingBottom
} else if (rect.top < scrollParentRect.top) {
scrollParentElem.scrollTop += rect.top - scrollParentRect.top - extraSpacingTop
}
}
}
}
componentWillUnmount() {
window.removeEventListener('edit:thumnailChange', this.onThumnailChange)
if (this.createThumbnailPromise) {
if (this.delayedUpdateTimout) {
window.clearTimeout(this.delayedUpdateTimout)
}
this.createThumbnailPromise.cancel()
this.createThumbnailPromise = null
}
}
private onThumnailChange(evt: CustomEvent) {
const photoId = evt.detail.photoId
if (photoId === this.props.photo.id) {
this.createThumbnail(true)
}
}
private onThumbnailLoad() {
this.setState({ isThumbnailLoaded: true })
}
private onThumbnailLoadError() {
if (!this.createThumbnailPromise) {
this.createThumbnail(false)
} else {
this.setState({ thumbnailError: 'load-failed' })
}
}
private onMouseEnter() {
const { props } = this
this.setState({ isHovered: true })
props.librarySelectionController.setHoverPhoto({ sectionId: props.sectionId, photoId: props.photo.id })
}
private onMouseLeave() {
const { props } = this
this.setState({ isHovered: false })
props.librarySelectionController.setHoverPhoto(null)
}
private onToggleSelection(event: React.MouseEvent) {
const { props } = this
event.stopPropagation()
event.preventDefault()
if (props.preselected !== undefined) {
props.librarySelectionController.applyPreselection()
} else {
props.librarySelectionController.setPhotoSelected(props.sectionId, props.photo.id, !props.isSelected)
}
}
private onSetPhotoActive(event: React.MouseEvent) {
const { props } = this
event.stopPropagation()
event.preventDefault()
if (!props.isActive) {
props.librarySelectionController.setActivePhoto({
sectionId: props.sectionId,
photoId: props.photo.id
})
}
}
private onShowDetails(event: React.MouseEvent) {
const { props } = this
event.stopPropagation()
event.preventDefault()
props.showPhotoDetails(props.sectionId, props.photo.id)
}
private createThumbnail(delayUpdate: boolean) {
if (this.delayedUpdateTimout) {
window.clearTimeout(this.delayedUpdateTimout)
}
if (delayUpdate) {
this.delayedUpdateTimout = window.setTimeout(() => this.setState({ thumbnailSrc: null, isThumbnailLoaded: false }), 1000)
} else {
this.setState({ thumbnailSrc: null, isThumbnailLoaded: false })
}
this.createThumbnailPromise = this.props.createThumbnail(this.props.sectionId, this.props.photo)
.then(thumbnailSrc => {
if (this.delayedUpdateTimout) {
window.clearTimeout(this.delayedUpdateTimout)
}
if (thumbnailSrc === this.state.thumbnailSrc) {
// Force loading the same image again
this.setState({ thumbnailSrc: null, isThumbnailLoaded: false })
window.setTimeout(() => this.setState({ thumbnailSrc }))
} else {
this.setState({ thumbnailSrc, isThumbnailLoaded: false })
}
})
.catch(error => {
if (!isCancelError(error)) {
const errorCode = getErrorCode(error)
const isMasterMissing = errorCode === 'master-missing'
if (!isMasterMissing) {
console.error('Getting thumbnail failed', error)
}
this.setState({ thumbnailError: isMasterMissing ? 'master-missing' : 'create-failed' })
}
})
}
private renderThumbnailError() {
const isSmall = this.props.layoutBox.height < 150
const { thumbnailError } = this.state
const isMasterMissing = thumbnailError === 'master-missing'
return (
<div className={classNames('Picture-error', { isSmall })}>
<Icon
icon={isMasterMissing ? 'delete' : 'disable'}
iconSize={isSmall ? 20 : 40}
/>
<div>{msg(isMasterMissing ? 'common_error_photoNotExisting' : 'Picture_error_createThumbnail')}</div>
</div>
)
}
render() {
// Wanted behaviour:
// - If the photo changes, the thumbnail should load fast, so no spinner should be shown.
// - If there is no thumbnail yet, we trigger creating the thumbnail and show a spinner.
// - If the favorite state (photo.flag) changes, the thumbnail should not flicker.
// - If the photo is changed (e.g. rotated), the old thumbnail should stay until the new one is created.
// Only if creating the thumbnail takes a long time, a spinner should be shown.
const { props, state } = this
const showFavorite = !!(props.photo.flag && state.isThumbnailLoaded)
const layoutBox = props.layoutBox
const hasSelectionBorder = props.isSelected && props.inSelectionMode
return (
<div
ref={this.mainRef}
className={classNames(props.className, 'Picture',
{ isLoading: !state.isThumbnailLoaded, hasSelectionBorder }
)}
style={{
left: Math.round(layoutBox.left),
top: Math.round(layoutBox.top),
width: Math.round(layoutBox.width),
height: Math.round(layoutBox.height)
}}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
onClick={props.inSelectionMode ? this.onToggleSelection : this.onSetPhotoActive}
onDoubleClick={props.inSelectionMode ? undefined : this.onShowDetails}
>
{state.thumbnailSrc &&
<img
className='Picture-thumbnail'
src={state.thumbnailSrc}
onLoad={this.onThumbnailLoad}
onError={this.onThumbnailLoadError}
/>
}
{state.thumbnailError &&
this.renderThumbnailError()
}
{showFavorite &&
<div className='Picture-overlay Picture-favorite'>
<Icon iconSize={18} icon='star'/>
</div>
}
{state.isHovered && props.preselected === undefined &&
<Button className='Picture-overlay Picture-showDetails'
icon={<Icon iconSize={18} icon='zoom-in'/>}
minimal={true}
title={formatCommandLabel(msg('Picture_showDetails'), showDetailsCombo)}
onClick={this.onShowDetails}
/>
}
{(props.inSelectionMode || state.isHovered || props.preselected !== undefined) &&
<Button className={classNames('Picture-overlay Picture-toggleSelection')}
minimal={true}
icon={renderToggleSelectionIcon(props.isSelected, props.inSelectionMode, props.preselected)}
title={formatCommandLabel(msg(((props.preselected !== null) ? !props.preselected : props.isSelected) ? 'Picture_select' : 'Picture_deselect'), toggleSelectedCombo)}
onClick={this.onToggleSelection}
/>
}
{(props.isActive || props.preselected !== undefined) &&
<div className={props.isActive ? 'Picture-activeBorder' : 'Picture-preselectedBorder'}/>
}
</div>
)
}
}
function renderToggleSelectionIcon(isSelected: boolean, inSelectionMode: boolean, preselected?: boolean): JSX.Element {
if (inSelectionMode && isSelected && preselected !== false) {
return (
<RedCheckCircle className='Picture-icon' size={selectionButtonSize}/>
)
} else {
const Icon = (!inSelectionMode || (isSelected && preselected !== false) || preselected) ? FaCheckCircle : FaRegCircle
return (
<Icon className='Picture-icon'/>
)
}
} | the_stack |
import React, { useCallback, useMemo, RefObject } from 'react';
import { FormikProps } from 'formik';
import { defineMessages, FormattedMessage } from 'react-intl';
import { bigNumberify } from 'ethers/utils';
import moveDecimal from 'move-decimal-point';
import Button from '~core/Button';
import { ActionForm } from '~core/Fields';
import Heading from '~core/Heading';
import QuestionMarkTooltip from '~core/QuestionMarkTooltip';
import Numeral from '~core/Numeral';
import { MiniSpinnerLoader } from '~core/Preloaders';
import {
Colony,
useLoggedInUser,
useMotionVoteResultsQuery,
useMotionCurrentUserVotedQuery,
useMotionFinalizedQuery,
useMotionStakerRewardQuery,
} from '~data/index';
import { ActionTypes } from '~redux/index';
import { ColonyMotions } from '~types/index';
import { mapPayload } from '~utils/actions';
import { getMainClasses } from '~utils/css';
import { MotionVote, MotionState } from '~utils/colonyMotions';
import VoteResults from './VoteResults';
import styles from './FinalizeMotionAndClaimWidget.css';
interface Props {
colony: Colony;
motionId: number;
actionType: string;
scrollToRef?: RefObject<HTMLInputElement>;
motionState: MotionState;
}
export const MSG = defineMessages({
/*
* @NOTE I didn't want to create a mapping for this, since they will only
* be used in this instance
*
* If by chance we end up having to use this mapping elsewhere, feel free
* to create it's own map
*/
title: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.title',
defaultMessage: `Should "{actionType, select,
${ColonyMotions.MintTokensMotion} {Mint tokens}
${ColonyMotions.PaymentMotion} {Payment}
${ColonyMotions.CreateDomainMotion} {Create Team}
${ColonyMotions.EditDomainMotion} {Edit Team}
${ColonyMotions.ColonyEditMotion} {Colony Edit}
${ColonyMotions.SetUserRolesMotion} {Permission Management}
${ColonyMotions.MoveFundsMotion} {Move Funds}
${ColonyMotions.VersionUpgradeMotion} {Version Upgrade}
other {Generic Action}
}" be approved?`,
},
finalizeLabel: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.finalizeLabel',
defaultMessage: `Finalize motion`,
},
finalizeTooltip: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.finalizeTooltip',
defaultMessage: `Finalize completes a motion, allows stakes to be
reclaimed, and if applicable, takes the action the motion was
created to authorise.`,
},
finalizeButton: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.finalizeButton',
defaultMessage: `Finalize`,
},
outcomeCelebration: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.outcomeCelebration',
defaultMessage: `{outcome, select,
true {🎉 Congratulations, your side won!}
other {Sorry, your side lost. 😢}
}`,
},
claimLabel: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.claimLabel',
defaultMessage: `Claim your tokens`,
},
claimButton: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.claimButton',
defaultMessage: `{claimedReward, select,
true {Claimed}
other {Claim}
}`,
},
stakeLabel: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.stakeLabel',
defaultMessage: `Stake`,
},
winningsLabel: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.winningsLabel',
defaultMessage: `Winnings`,
},
penaltyLabel: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.penaltyLabel',
defaultMessage: `Penalty`,
},
totalLabel: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.totalLabel',
defaultMessage: `Total`,
},
loading: {
id: 'dashboard.ActionsPage.FinalizeMotionAndClaimWidget.loading',
defaultMessage: 'Loading motion rewards ...',
},
});
const FinalizeMotionAndClaimWidget = ({
colony: { colonyAddress, tokens, nativeTokenAddress },
colony,
motionId,
actionType,
scrollToRef,
motionState,
}: Props) => {
const { walletAddress, username, ethereal } = useLoggedInUser();
const {
data: voteResults,
loading: loadingVoteResults,
} = useMotionVoteResultsQuery({
variables: {
colonyAddress,
userAddress: walletAddress,
motionId,
},
fetchPolicy: 'network-only',
});
const {
data: userVoted,
loading: loadingUserVoted,
} = useMotionCurrentUserVotedQuery({
variables: {
colonyAddress,
userAddress: walletAddress,
motionId,
},
fetchPolicy: 'network-only',
});
const {
data: finalized,
loading: loadingFinalized,
} = useMotionFinalizedQuery({
variables: {
colonyAddress,
motionId,
},
fetchPolicy: 'network-only',
});
const {
data: stakerRewards,
loading: loadingStakerRewards,
} = useMotionStakerRewardQuery({
variables: {
colonyAddress,
userAddress: walletAddress,
motionId,
},
fetchPolicy: 'network-only',
});
const nativeToken = tokens.find(
({ address }) => address === nativeTokenAddress,
);
const transform = useCallback(
mapPayload(() => ({
colonyAddress,
userAddress: walletAddress,
motionId,
})),
[walletAddress],
);
const handleSuccess = useCallback(() => {
scrollToRef?.current?.scrollIntoView({ behavior: 'smooth' });
}, [scrollToRef]);
const { userStake, userWinnings, userTotals, isWinning } = useMemo(() => {
let stake = bigNumberify(0);
let winnings = bigNumberify(0);
let totals = bigNumberify(0);
if (stakerRewards?.motionStakerReward) {
const {
stakesYay,
stakesNay,
stakingRewardNay,
stakingRewardYay,
} = stakerRewards.motionStakerReward;
stake = stake.add(bigNumberify(stakesYay)).add(bigNumberify(stakesNay));
totals = totals
.add(bigNumberify(stakingRewardYay))
.add(bigNumberify(stakingRewardNay));
winnings = totals.sub(stake);
}
return {
userStake: moveDecimal(stake, -(nativeToken?.decimals || 0)),
userWinnings: moveDecimal(winnings, -(nativeToken?.decimals || 0)),
userTotals: moveDecimal(totals, -(nativeToken?.decimals || 0)),
isWinning: winnings.gte(0),
};
}, [stakerRewards, nativeToken]);
if (
loadingVoteResults ||
loadingUserVoted ||
loadingFinalized ||
loadingStakerRewards
) {
return (
<div className={styles.main}>
<MiniSpinnerLoader
className={styles.loading}
loadingText={MSG.loading}
/>
</div>
);
}
const hasRegisteredProfile = !!username && !ethereal;
const hasVotes =
bigNumberify(voteResults?.motionVoteResults?.nayVotes || 0).gt(0) ||
bigNumberify(voteResults?.motionVoteResults?.yayVotes || 0).gt(0);
/*
* If the motion is in the Root domain, it cannot be escalated further
* meaning it can be finalized directly
*/
const motionNotFinalizable = motionState === MotionState.FailedNoFinalizable;
const showFinalizeButton =
voteResults?.motionVoteResults &&
!finalized?.motionFinalized &&
!motionNotFinalizable;
const canClaimStakes =
(bigNumberify(stakerRewards?.motionStakerReward?.stakesYay || 0).gt(0) ||
bigNumberify(stakerRewards?.motionStakerReward?.stakesNay || 0).gt(0)) &&
userTotals !== '0';
const showClaimButton =
finalized?.motionFinalized || (motionNotFinalizable && canClaimStakes);
const yaySideWon = bigNumberify(
voteResults?.motionVoteResults?.yayVotes || 0,
).gt(voteResults?.motionVoteResults?.nayVotes || 0);
const userSideWon = yaySideWon
? voteResults?.motionVoteResults?.currentUserVoteSide === MotionVote.Yay
: voteResults?.motionVoteResults?.currentUserVoteSide === MotionVote.Nay;
return (
<div
className={getMainClasses({}, styles, {
margin: showFinalizeButton || showClaimButton || hasVotes,
})}
>
{showFinalizeButton && (
<ActionForm
initialValues={{}}
submit={ActionTypes.COLONY_MOTION_FINALIZE}
error={ActionTypes.COLONY_MOTION_FINALIZE_ERROR}
success={ActionTypes.COLONY_MOTION_FINALIZE_SUCCESS}
transform={transform}
onSuccess={handleSuccess}
>
{({ handleSubmit, isSubmitting }: FormikProps<{}>) => (
<div className={styles.itemWithForcedBorder}>
<div className={styles.label}>
<div>
<FormattedMessage {...MSG.finalizeLabel} />
<QuestionMarkTooltip
tooltipText={MSG.finalizeTooltip}
className={styles.help}
tooltipClassName={styles.tooltip}
tooltipPopperProps={{
placement: 'right',
}}
/>
</div>
</div>
<div className={styles.value}>
<Button
appearance={{ theme: 'primary', size: 'medium' }}
text={MSG.finalizeButton}
disabled={!hasRegisteredProfile}
onClick={() => handleSubmit()}
loading={isSubmitting}
/>
</div>
</div>
)}
</ActionForm>
)}
{showClaimButton && (
<ActionForm
initialValues={{}}
submit={ActionTypes.COLONY_MOTION_CLAIM}
error={ActionTypes.COLONY_MOTION_CLAIM_ERROR}
success={ActionTypes.COLONY_MOTION_CLAIM_SUCCESS}
transform={transform}
onSuccess={handleSuccess}
>
{({ handleSubmit, isSubmitting }: FormikProps<{}>) => (
<>
<div className={styles.title}>
<div className={styles.label}>
<div>
<FormattedMessage {...MSG.claimLabel} />
</div>
</div>
<div className={styles.value}>
<Button
appearance={{ theme: 'primary', size: 'medium' }}
text={MSG.claimButton}
textValues={{
claimedReward:
stakerRewards?.motionStakerReward?.claimedReward,
}}
disabled={
!hasRegisteredProfile ||
!canClaimStakes ||
stakerRewards?.motionStakerReward?.claimedReward
}
onClick={() => handleSubmit()}
loading={isSubmitting}
/>
</div>
</div>
{canClaimStakes && (
<>
<div className={styles.item}>
<div className={styles.label}>
<div>
<FormattedMessage {...MSG.stakeLabel} />
</div>
</div>
<div className={styles.value}>
<Numeral
value={userStake}
suffix={` ${nativeToken?.symbol}`}
truncate={5}
/>
</div>
</div>
<div className={styles.item}>
<div className={styles.label}>
<div>
<FormattedMessage
{...((isWinning && MSG.winningsLabel) ||
MSG.penaltyLabel)}
/>
</div>
</div>
<div className={styles.value}>
<Numeral
value={userWinnings}
suffix={` ${nativeToken?.symbol}`}
truncate={5}
/>
</div>
</div>
<div className={styles.item}>
<div className={styles.label}>
<div>
<FormattedMessage {...MSG.totalLabel} />
</div>
</div>
<div className={styles.value}>
<Numeral
value={userTotals}
suffix={` ${nativeToken?.symbol}`}
truncate={5}
/>
</div>
</div>
</>
)}
</>
)}
</ActionForm>
)}
<div className={styles.voteResults}>
{hasRegisteredProfile &&
voteResults?.motionVoteResults &&
hasVotes &&
userVoted?.motionCurrentUserVoted && (
<div className={styles.outcome}>
<FormattedMessage
{...MSG.outcomeCelebration}
values={{
outcome: userSideWon,
}}
/>
</div>
)}
{hasVotes && (
/*
* @NOTE If we have votes **AND** we're in a finalizable state (this is checked on the action page)
* then we are in a VOTING flow that needs to be finalized.
* Othewise, we're in a STAKING flow that needs to be finalized.
*/
<>
<Heading
text={MSG.title}
textValues={{ actionType }}
appearance={{ size: 'normal', theme: 'dark', margin: 'none' }}
/>
<VoteResults
/*
* @NOTE We are not passing down the `motionVoteResults` values
* since the `VoteResults` component is designed to work independent
* of this widget (since we'll need to use it in a system message)
*/
colony={colony}
motionId={motionId}
/>
</>
)}
</div>
</div>
);
};
FinalizeMotionAndClaimWidget.displayName =
'dashboard.ActionsPage.FinalizeMotionAndClaimWidget';
export default FinalizeMotionAndClaimWidget; | the_stack |
import {Program} from "../src/runtime/dsl2";
import {verify} from "./util";
import * as test from "tape";
test("Aggregate: Count in choose", (assert) => {
let prog = new Program("test");
prog.bind("test count in choose", ({find, choose, gather, record}) => {
let person = find("person");
let [count] = choose(
() => gather(person.pet).count(),
() => 0
);
return [
record("result", {person, count})
];
});
verify(assert, prog, [
["A", "tag", "person"],
], [
[1, "tag", "result", 1],
[1, "person", "A", 1],
[1, "count", 0, 1],
]);
verify(assert, prog, [
["A", "pet", "B"],
], [
[1, "tag", "result", 1, -1],
[1, "person", "A", 1, -1],
[1, "count", 0, 1, -1],
[2, "tag", "result", 1, 1],
[2, "person", "A", 1, 1],
[2, "count", 1, 1, 1],
]);
verify(assert, prog, [
["A", "pet", "C"],
], [
[2, "tag", "result", 1, -1],
[2, "person", "A", 1, -1],
[2, "count", 1, 1, -1],
[3, "tag", "result", 1],
[3, "person", "A", 1],
[3, "count", 2, 1],
]);
assert.end();
});
test("Aggregate: direction-less sort", (assert) => {
let prog = new Program("test");
prog.bind("test direction-less sort", ({find, choose, gather, record}) => {
let person = find("person");
let pos = gather(person.name).sort();
return [
person.add("pos", pos)
];
});
verify(assert, prog, [
["A", "tag", "person"],
["A", "name", "Jane"],
], [
["A", "pos", 1, 1],
]);
verify(assert, prog, [
["B", "tag", "person"],
["B", "name", "Chris"],
], [
["B", "pos", 1, 1],
["A", "pos", 1, 1, -1],
["A", "pos", 2, 1],
]);
verify(assert, prog, [
["C", "tag", "person"],
["C", "name", "Zaria"],
], [
["C", "pos", 3, 1],
]);
verify(assert, prog, [
["B", "tag", "person", 0, -1],
["B", "name", "Chris", 0, -1],
], [
["B", "pos", 1, 1, -1],
["A", "pos", 1, 1, 1],
["A", "pos", 2, 1, -1],
["C", "pos", 2, 1, 1],
["C", "pos", 3, 1, -1],
]);
assert.end();
});
test("Aggregate: down sort", (assert) => {
let prog = new Program("test");
prog.bind("test down sort", ({find, choose, gather, record}) => {
let person = find("person");
let pos = gather(person.name).sort("down");
return [
person.add("pos", pos)
];
});
verify(assert, prog, [
["A", "tag", "person"],
["A", "name", "Jane"],
], [
["A", "pos", 1, 1],
]);
verify(assert, prog, [
["B", "tag", "person"],
["B", "name", "Chris"],
], [
["B", "pos", 2, 1],
]);
verify(assert, prog, [
["C", "tag", "person"],
["C", "name", "Zaria"],
], [
["C", "pos", 1, 1],
["A", "pos", 1, 1, -1],
["A", "pos", 2, 1],
["B", "pos", 2, 1, -1],
["B", "pos", 3, 1],
]);
verify(assert, prog, [
["C", "tag", "person", 0, -1],
["C", "name", "Zaria", 0, -1],
], [
["C", "pos", 1, 1, -1],
["A", "pos", 1, 1, 1],
["A", "pos", 2, 1, -1],
["B", "pos", 2, 1, 1],
["B", "pos", 3, 1, -1],
]);
assert.end();
});
test("Aggregate: multi-direction sort", (assert) => {
let prog = new Program("test");
prog.bind("test multi-direction sort", ({find, choose, gather, record}) => {
let person = find("person");
let pos = gather(person.name, person.age).sort("down", "up");
return [
person.add("pos", pos)
];
});
verify(assert, prog, [
["A", "tag", "person"],
["A", "name", "Jane"],
["A", "age", 27],
], [
["A", "pos", 1, 1],
]);
verify(assert, prog, [
["B", "tag", "person"],
["B", "name", "Chris"],
["B", "age", 25],
], [
["B", "pos", 2, 1],
]);
verify(assert, prog, [
["C", "tag", "person"],
["C", "name", "Jane"],
["C", "age", 19],
], [
["C", "pos", 1, 1],
["A", "pos", 1, 1, -1],
["A", "pos", 2, 1],
["B", "pos", 2, 1, -1],
["B", "pos", 3, 1],
]);
verify(assert, prog, [
["C", "tag", "person", 0, -1],
], [
["C", "pos", 1, 1, -1],
["A", "pos", 1, 1, 1],
["A", "pos", 2, 1, -1],
["B", "pos", 2, 1, 1],
["B", "pos", 3, 1, -1],
]);
assert.end();
});
test("Aggregate: group sort", (assert) => {
let prog = new Program("test");
prog.bind("test group sort", ({find, choose, gather, record}) => {
let person = find("person");
let pos = gather(person.name).per(person.age).sort("down");
return [
person.add("pos", pos)
];
});
verify(assert, prog, [
["A", "tag", "person"],
["A", "name", "Jane"],
["A", "age", 27],
], [
["A", "pos", 1, 1],
]);
verify(assert, prog, [
["B", "tag", "person"],
["B", "name", "Chris"],
["B", "age", 27],
], [
["B", "pos", 2, 1],
]);
verify(assert, prog, [
["C", "tag", "person"],
["C", "name", "Zaria"],
["C", "age", 25],
], [
["C", "pos", 1, 1],
]);
verify(assert, prog, [
["D", "tag", "person"],
["D", "name", "Dana"],
["D", "age", 27],
], [
["D", "pos", 2, 1],
["B", "pos", 2, 1, -1],
["B", "pos", 3, 1],
]);
verify(assert, prog, [
["C", "tag", "person", 0, -1],
], [
["C", "pos", 1, 1, -1],
]);
assert.end();
});
test("Aggregate: committed sort with post filtering", (assert) => {
let prog = new Program("test")
.commit("Clear events when they come in.", ({find}) => {
let event = find("event/create-widget");
return [event.remove()];
})
.commit("Create a new widget of the given model.", ({find, choose, gather, record}) => {
let {model} = find("event/create-widget");
// The serial number of our next widget is the highest serial we've issued for this model so far + 1.
let {widget:other} = model;
1 == gather(other.serial).per(model).sort("down");
let serial = other.serial + 1;
return [model.add("widget", record("widget", {serial}))];
});
verify(assert, prog, [
[1, "tag", "model"],
[1, "widget", 2],
[1, "widget", 3],
[2, "tag", "widget"],
[2, "serial", 3],
[3, "tag", "widget"],
[3, "serial", 5],
[4, "tag", "event/create-widget"],
[4, "model", 1],
], [
[4, "tag", "event/create-widget", 0, -1],
[4, "model", 1, 0, -1],
[1, "widget", "tag|widget|serial|6", 0],
["tag|widget|serial|6", "tag", "widget", 0],
["tag|widget|serial|6", "serial", 6, 0],
]);
assert.end();
});
test("Aggregate: committed sort in choose", (assert) => {
let prog = new Program("test")
.commit("Clear events when they come in.", ({find}) => {
let event = find("event/create-widget");
return [event.remove()];
})
.commit("Create a new widget of the given model.", ({find, choose, gather, record}) => {
let {model} = find("event/create-widget");
// The serial number of our next widget is the highest serial we've issued for this model so far + 1.
let [serial] = choose(() => {
let {widget:other} = model;
1 == gather(other.serial).per(model).sort("down"); // @NOTE: This breaks differently due to equality bug.
return other.serial + 1;
}, () => 1);
return [model.add("widget", record("widget", {serial}))];
});
verify(assert, prog, [
[1, "tag", "model"],
[1, "widget", 2],
[1, "widget", 3],
[2, "tag", "widget"],
[2, "serial", 3],
[3, "tag", "widget"],
[3, "serial", 5],
[4, "tag", "event/create-widget"],
[4, "model", 1],
], [
[4, "tag", "event/create-widget", 0, -1],
[4, "model", 1, 0, -1],
[1, "widget", "tag|widget|serial|6", 0],
["tag|widget|serial|6", "tag", "widget", 0],
["tag|widget|serial|6", "serial", 6, 0],
]);
assert.end();
});
test("Aggregate: committed sort in choose with post filtering greater than", (assert) => {
let prog = new Program("test")
.commit("Clear events when they come in.", ({find}) => {
let event = find("event/create-widget");
return [event.remove()];
})
.commit("Create a new widget of the given model.", ({find, choose, gather, record}) => {
let {model} = find("event/create-widget");
// The serial number of our next widget is the highest serial we've issued for this model so far + 1.
let [serial] = choose(() => {
let {widget:other} = model;
2 > gather(other.serial).per(model).sort("down");
return other.serial + 1;
}, () => 1);
return [model.add("widget", record("widget", {serial}))];
});
verify(assert, prog, [
[1, "tag", "model"],
[1, "widget", 2],
[1, "widget", 3],
[2, "tag", "widget"],
[2, "serial", 3],
[3, "tag", "widget"],
[3, "serial", 5],
[4, "tag", "event/create-widget"],
[4, "model", 1],
], [
[4, "tag", "event/create-widget", 0, -1],
[4, "model", 1, 0, -1],
[1, "widget", "tag|widget|serial|6", 0],
["tag|widget|serial|6", "tag", "widget", 0],
["tag|widget|serial|6", "serial", 6, 0],
]);
assert.end();
});
test("Aggregate: committed sort with multiple groups", (assert) => {
let prog = new Program("test")
.commit("Clear events when they come in.", ({find}) => {
let event = find("event/create-widget");
return [event.remove()];
})
.commit("Create a new widget of the given model.", ({find, choose, gather, record}) => {
let {model} = find("event/create-widget");
// The serial number of our next widget is the highest serial we've issued for this model so far + 1.
let [serial] = choose(() => {
let {widget:other} = model;
2 > gather(other.serial).per(model).sort("down");
return other.serial + 1;
}, () => 1);
return [model.add("widget", record("widget", {serial}))];
});
verify(assert, prog, [
[1, "tag", "model"],
[1, "widget", 2],
[1, "widget", 3],
[2, "tag", "widget"],
[2, "serial", 3],
[3, "tag", "widget"],
[3, "serial", 5],
[5, "tag", "model"],
[5, "widget", 6],
[6, "tag", "widget"],
[6, "serial", 28],
[5, "widget", 7],
[7, "tag", "widget"],
[7, "serial", 30],
[4, "tag", "event/create-widget"],
[4, "model", 1],
], [
[4, "tag", "event/create-widget", 0, -1],
[4, "model", 1, 0, -1],
[1, "widget", "tag|widget|serial|6", 0],
["tag|widget|serial|6", "tag", "widget", 0],
["tag|widget|serial|6", "serial", 6, 0],
]);
assert.end();
});
test("Sort: incremental updates", (assert) => {
let prog = new Program("test");
prog.bind("the block's next is the highest node sort + 1.", ({find, gather, record}) => {
let block = find("block");
let {node} = block;
2 > gather(node.sort).per(block).sort("down");
let sort = node.sort + 1;
return [block.add("next", sort)];
});
verify(assert, prog, [
[1, "tag", "block"],
[1, "node", 2],
[2, "sort", 1],
], [
[1, "next", 2, 1]
]);
verify(assert, prog, [
[1, "node", 3],
[3, "sort", 2],
], [
[1, "next", 3, 1],
[1, "next", 2, 1, -1],
]);
verify(assert, prog, [
[1, "node", 4],
[4, "sort", 5],
], [
[1, "next", 6, 1],
[1, "next", 3, 1, -1],
]);
assert.end();
});
test("Aggregate: inside choose without outer in key", (assert) => {
let prog = new Program("test");
prog.bind("count the names of people", ({find, gather, record, choose}) => {
let person = find("person");
let [sort] = choose(() => {
return gather(person.name).count();
}, () => "yo yo yo");
return [person.add("next", sort)];
});
verify(assert, prog, [
[1, "tag", "person"],
[1, "name", "chris"],
[1, "name", "christopher"],
[2, "name", "joe"],
], [
[1, "next", 2, 1],
]);
assert.end();
});
test("Aggregate: no outer in key variations", (assert) => {
let prog = new Program("test");
prog.bind("count the names of people", ({find, gather, record, choose}) => {
let person = find("person");
let [sort] = choose(() => {
return gather(person.name).count();
}, () => "yo yo yo");
return [person.add("next", sort)];
});
verify(assert, prog, [
[1, "tag", "person"],
[1, "name", "chris"],
[1, "name", "christopher"],
[2, "name", "joe"],
], [
[1, "next", 2, 1],
]);
verify(assert, prog, [
[1, "tag", "person", 0, -1],
], [
[1, "next", 2, 1, -1],
]);
verify(assert, prog, [
[1, "name", "chris", 0, -1],
[1, "tag", "person"],
], [
[1, "next", 1, 1],
]);
verify(assert, prog, [
[1, "name", "chris"],
[1, "tag", "person", 0, -1],
], [
[1, "next", 1, 1, -1],
]);
assert.end();
});
test("Aggregate: Test limit", (assert) => {
let prog = new Program("test");
prog.bind("Find up to two people", ({find, gather, record, choose}) => {
let person = find("person");
gather(person).sort() <= 2;
return [record({person})];
});
verify(assert, prog, [
[1, "tag", "person"],
[2, "tag", "person"],
[3, "tag", "person"],
], [
["A", "person", 1, 1],
["B", "person", 2, 1],
]);
verify(assert, prog, [
[1, "tag", "person", 0, -1],
], [
["A", "person", 1, 1, -1],
["C", "person", 3, 1],
]);
verify(assert, prog, [
[2, "tag", "person", 0, -1],
], [
["B", "person", 2, 1, -1],
]);
assert.end();
});
// @NOTE: The not following the choose required for this example is currently marked dangerous
// test("Aggregate: stratified after choose", (assert) => {
// let prog = new Program("test");
// prog.bind("Count the next of kin", ({find, gather, choose, not, record}) => {
// let person = find("person");
// let [kin] = choose(() => person.family, () => person.friend, () => person.acquaintance);
// not(() => kin.nemesis == person);
// let count = gather(kin).per(person).count();
// return [person.add("kin_count", count)];
// });
// verify(assert, prog, [
// [1, "tag", "person"],
// [1, "name", "chris"],
// [1, "friend", "joe"],
// [1, "friend", "fred"],
// [1, "friend", "steve"],
// ["steve", "nemesis", 1],
// ], [
// [1, "kin_count", 2, 1],
// ]);
// verify(assert, prog, [
// [1, "tag", "person", 0, -1],
// ], [
// [1, "kin_count", 2, 1, -1],
// ]);
// assert.end();
// }); | the_stack |
import { Injectable } from '@angular/core';
import { matchAll } from '../polyfills/matchAll';
interface TextSegment {
startIndex: number;
endIndex: number;
}
/**
* A service that provides various functions for en- and decoding data type strings in order to make them
* meaningfully parseable by regex
*/
@Injectable()
export class DataTypeEncoder {
constructor() {
}
// Substrings
// -----------------------------------------------------
/**
* Finds all substrings in a piece of text and replaces all special characters within with @@@...@@@-placeholders.
*
* @param text - The text to parse for substrings
*/
encodeSubstrings(text: string): string {
// Get a list of all quotes (that are not preceded by an escaping backslash)
const singleQuotes: any = matchAll(text, /'/gm).filter(match => match.index === 0 || text[match.index - 1] !== '\\');
const doubleQuotes: any = matchAll(text, /"/gm).filter(match => match.index === 0 || text[match.index - 1] !== '\\');
const graveQuotes: any = matchAll(text, /`/gm).filter(match => match.index === 0 || text[match.index - 1] !== '\\');
const allQuotes = [...singleQuotes, ...doubleQuotes, ...graveQuotes];
allQuotes.sort((a, b) => a['index'] - b['index']);
// Create quotes text segments
const quoteSegments: Array<TextSegment> = [];
let outermostOpenedQuote = null;
for (const quote of allQuotes) {
if (!outermostOpenedQuote) {
outermostOpenedQuote = quote;
} else {
if (outermostOpenedQuote[0] === quote[0]) {
quoteSegments.push({
startIndex: outermostOpenedQuote.index + 1,
endIndex: quote['index']
});
outermostOpenedQuote = null;
}
}
}
if (outermostOpenedQuote !== null) {
throw Error('Input parse error. String was opened, but not closed.');
}
// Encode quote segments
const encodedBracketsText = this.encodeTextSegments(text, quoteSegments, this.encodeStringSpecialChars);
return encodedBracketsText;
}
/**
* Encodes all special characters that might be confused as code syntax in a piece of string
*
* @param text - The text to encode
*/
encodeStringSpecialChars(text: string): string {
text = text.replace(/'/g, '@@@singlequote@@@');
text = text.replace(/"/g, '@@@doublequote@@@');
text = text.replace(/`/g, '@@@gravequote@@@');
text = text.replace(/:/g, '@@@colon@@@');
text = text.replace(/;/g, '@@@semicolon@@@');
text = text.replace(/\./g, '@@@dot@@@');
text = text.replace(/,/g, '@@@comma@@@');
text = text.replace(/\\/g, '@@@backslash@@@');
text = text.replace(/\(/g, '@@@openRoundBracket@@@');
text = text.replace(/\)/g, '@@@closeRoundBracket@@@');
text = text.replace(/\[/g, '@@@openSquareBracket@@@');
text = text.replace(/\]/g, '@@@closeSquareBracket@@@');
text = text.replace(/\{/g, '@@@openCurlyBracket@@@');
text = text.replace(/\}/g, '@@@closeCurlyBracket@@@');
return text;
}
/**
* Decodes the special characters again
*
* @param text - The text to decode
*/
decodeStringSpecialChars(text: string): string {
text = text.replace(/@@@singlequote@@@/g, '\'');
text = text.replace(/@@@doublequote@@@/g, '"');
text = text.replace(/@@@gravequote@@@/g, '`');
text = text.replace(/@@@colon@@@/g, ':');
text = text.replace(/@@@semicolon@@@/g, ';');
text = text.replace(/@@@dot@@@/g, '.');
text = text.replace(/@@@comma@@@/g, ',');
text = text.replace(/@@@backslash@@@/g, '\\');
text = text.replace(/@@@openRoundBracket@@@/g, '(');
text = text.replace(/@@@closeRoundBracket@@@/g, ')');
text = text.replace(/@@@openSquareBracket@@@/g, '[');
text = text.replace(/@@@closeSquareBracket@@@/g, ']');
text = text.replace(/@@@openCurlyBracket@@@/g, '{');
text = text.replace(/@@@closeCurlyBracket@@@/g, '}');
return text;
}
// Subfunctions
// -----------------------------------------------------
/**
* Finds all subfunctions in a piece of text and replaces their round brackets with @@@...@@@-placeholders.
*
* @param text - The text to parse for substrings
*/
encodeSubfunctions(text: string): string {
const openingBrackets = matchAll(text, /\(/gm);
const closingBrackets = matchAll(text, /\)/gm);
const allBrackets = [...openingBrackets, ...closingBrackets];
allBrackets.sort((a, b) => a['index'] - b['index']);
// Create functions text segments
const functionSegments: Array<TextSegment> = [];
const openedBrackets = [];
for (const bracket of allBrackets) {
if (bracket[0] === '(') {
openedBrackets.push(bracket);
} else {
if (openedBrackets.length === 0) {
throw Error('Input parse error. Closed function bracket without opening it first.');
}
// Only collect the outermost function brackets, not nested ones
if (openedBrackets.length === 1) {
functionSegments.push({
startIndex: openedBrackets[0].index + 1,
endIndex: bracket['index']
});
}
openedBrackets.pop();
}
}
if (openedBrackets.length !== 0) {
throw Error('Input parse error. Opened function bracket without closing it.');
}
// Encode quote segments
const encodedFunctionsText = this.encodeTextSegments(text, functionSegments, this.encodeFunctionBrackets);
return encodedFunctionsText;
}
/**
* Encodes all round brackets with harmless placeholders
*
* @param text - The text to encode
*/
encodeFunctionBrackets(text: string): string {
text = text.replace(/\(/g, '@@@fnOpenBracket@@@');
text = text.replace(/\)/g, '@@@fnCloseBracket@@@');
return text;
}
/**
* Decodes all round brackets again
*
* @param text - The text to decode
*/
decodeFunctionBrackets(text: string): string {
text = text.replace(/@@@fnOpenBracket@@@/g, '\(');
text = text.replace(/@@@fnCloseBracket@@@/g, '\)');
return text;
}
// Subbrackets
// -----------------------------------------------------
/**
* Finds all subbrackets in a piece of text and replaces their brackets with @@@...@@@-placeholders.
*
* @param text - The text to parse for substrings
*/
encodeVariableSubbrackets(text: string): string {
// Property accessor opening brackets can be identified by what they are preceded by.
// Must be a) text, b) closing square bracket or c) closing round bracket. Arrays can't be preceded by any of these.
const variableOpeningBracketsWithLookbehinds = '(?<=[a-zA-Z_$\\]\)])\\['; // Too new for many older browsers
const variableOpeningBrackets = '(?:[a-zA-Z_$\\]\)])(\\[)';
const openingBrackets = matchAll(text, new RegExp(variableOpeningBrackets, 'gm'));
// Note: Can't simply find closing brackets as well (as is done in the other encoder functions), because the closing
// bracket doesn't have a uniquely identifiable syntax. Might also be array endings.
// Find the corresponding closing bracket for each opening bracket by parsing the following brackets
const bracketSegments: Array<TextSegment> = [];
for (const openingBracket of openingBrackets) {
const followingText = text.substr(openingBracket.index + 2); // openingBracket.index + 2, b/c the regex starts at the character before the opening bracket and followingText is supposed to start after the opening bracket
const followingOpeningBrackets = matchAll(followingText, /\[/gm);
const followingClosingBrackets = matchAll(followingText, /\]/gm);
const allFollowingBrackets = [...followingOpeningBrackets, ...followingClosingBrackets];
allFollowingBrackets.sort((a, b) => a['index'] - b['index']);
let openedBrackets = 1; // Start with the first opening bracket already counted
for (const followingBracket of allFollowingBrackets) {
openedBrackets = followingBracket[0] === ']' ? openedBrackets - 1 : openedBrackets + 1;
if (openedBrackets === 0) {
bracketSegments.push({
startIndex: openingBracket.index + 2,
endIndex: openingBracket.index + 2 + followingBracket['index']
});
break;
}
}
if (openedBrackets !== 0) {
throw Error('Input parse error. Opened bracket without closing it.');
}
}
// Throw out nested brackets
const outerBracketSegments = [];
for (const bracketSegment of bracketSegments) {
if (outerBracketSegments.length === 0) {
outerBracketSegments.push(bracketSegment);
} else {
if (outerBracketSegments[outerBracketSegments.length - 1].endIndex < bracketSegment.startIndex) {
outerBracketSegments.push(bracketSegment);
}
}
}
// Encode bracket segments
const encodedBracketsText = this.encodeTextSegments(text, outerBracketSegments, this.encodeVariableBrackets);
return encodedBracketsText;
}
/**
* Encodes all brackets with harmless placeholders
*
* @param text - The text to encode
*/
encodeVariableBrackets(text: string): string {
text = text.replace(/\[/g, '@@@variableOpeningBracket@@@');
text = text.replace(/\]/g, '@@@variableClosingBracket@@@');
return text;
}
/**
* Decodes all brackets again
*
* @param text - The text to encode
*/
decodeVariableBrackets(text: string): string {
text = text.replace(/@@@variableOpeningBracket@@@/g, '\[');
text = text.replace(/@@@variableClosingBracket@@@/g, '\]');
return text;
}
// Context var placeholder
// -----------------------------------------------------
/**
* Transforms a context var (that is already encoded for substrings, subfunctions and subbrackets) into a string placeholder
* by encoding the context var syntax itself. This is so that can be safely parsed by JSON.parse() as a string and also so it
* won't be misinterpreted by other regexes looking for JSON syntax (especially arrays b/c of context-var []-property-brackets)
*
* @param contextVar - The context var to transform
*/
transformContextVarIntoPlacerholder(contextVar: string): string {
// Replace context. with __CXT__
contextVar = '__CXT__' + contextVar.substr(7);
// Encode variable syntax
contextVar = contextVar.replace(/\"/g, '@@@cxtDoubleQuote@@@');
contextVar = contextVar.replace(/\./g, '@@@cxtDot@@@');
contextVar = contextVar.replace(/\[/g, '@@@cxtOpenSquareBracket@@@');
contextVar = contextVar.replace(/\]/g, '@@@cxtCloseSquareBracket@@@');
contextVar = contextVar.replace(/\(/g, '@@@cxtOpenRoundBracket@@@');
contextVar = contextVar.replace(/\)/g, '@@@cxtCloseRoundBracket@@@');
return contextVar;
}
transformPlaceholderIntoContextVar(contextVar: string): string {
contextVar = 'context' + contextVar.substr(7);
contextVar = contextVar.replace(/@@@cxtDoubleQuote@@@/g, '"');
contextVar = contextVar.replace(/@@@cxtDot@@@/g, '.');
contextVar = contextVar.replace(/@@@cxtOpenSquareBracket@@@/g, '[');
contextVar = contextVar.replace(/@@@cxtCloseSquareBracket@@@/g, ']');
contextVar = contextVar.replace(/@@@cxtOpenRoundBracket@@@/g, '(');
contextVar = contextVar.replace(/@@@cxtCloseRoundBracket@@@/g, ')');
return contextVar;
}
// Other
// -----------------------------------------------------
/**
* Takes a piece of text as well as array of TextSegments and encodes them with the help of an encodingFunction
* The encoded text is then automatically assembled and returned.
*
* @param text - The text in question
* @param specialTextSegments - The segments in the text to encode
* @param encodingFunction - The encoding function to use
*/
private encodeTextSegments(text: string, specialTextSegments: Array<TextSegment>, encodingFunction: any): string {
// 1. Divide whole text into two types of segments: Those to be encoded and those to be left as they are
const allTextSegments = [];
for (const specialTextSegment of specialTextSegments) {
// Push normal text segment since last special segment
const lastSegmentEndIndex = allTextSegments.length === 0 ? 0 : allTextSegments[allTextSegments.length - 1].endIndex;
allTextSegments.push({
type: 'text',
startIndex: lastSegmentEndIndex,
endIndex: specialTextSegment.startIndex,
string: text.substr(lastSegmentEndIndex, specialTextSegment.startIndex - lastSegmentEndIndex)
});
// Push next special segment
allTextSegments.push({
type: 'special',
startIndex: specialTextSegment.startIndex,
endIndex: specialTextSegment.endIndex,
string: text.substr(specialTextSegment.startIndex, specialTextSegment.endIndex - specialTextSegment.startIndex)
});
}
// Add text segment for trailing text after last special segment
const lastBracketEndIndex = allTextSegments.length === 0 ? 0 : allTextSegments[allTextSegments.length - 1].endIndex;
allTextSegments.push({
type: 'text',
startIndex: lastBracketEndIndex,
endIndex: text.length - 1,
string: text.substr(lastBracketEndIndex)
});
// 2. Encode all special segments
for (const segment of allTextSegments) {
if (segment.type === 'special') {
segment.string = encodingFunction(segment.string);
}
}
// 3. Concat everything together again
let encodedString = '';
for (const segment of allTextSegments) {
encodedString += segment.string;
}
return encodedString;
}
/**
* Strips all escaping backslashes from a piece of text
*
* @param text - The text in question
*/
stripSlashes(text: string): string {
return text.replace(/\\(.)/g, '$1');
// return text.replace(new RegExp('\\\\(.)', 'g'), '$1');
}
/**
* Escapes all double quotes in a piece of text
*
* @param text - The text in question
*/
escapeDoubleQuotes(text: string): string {
const result = text.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
return result;
}
} | the_stack |
import * as Stream from 'stream';
import * as fs from 'fs';
import * as vscode from 'vscode';
import * as path from 'path';
import * as mime from 'mime';
import { Disposable } from '../../utils/dispose';
import {
FormatFileSize,
FormatDateTime,
isFileInjectable,
} from '../../utils/utils';
import { HTMLInjector } from './HTMLInjector';
import TelemetryReporter from 'vscode-extension-telemetry';
import { WorkspaceManager } from '../../infoManagers/workspaceManager';
import { EndpointManager } from '../../infoManagers/endpointManager';
import { PathUtil } from '../../utils/pathUtil';
import { INJECTED_ENDPOINT_NAME } from '../../utils/constants';
import { ConnectionManager } from '../../infoManagers/connectionManager';
/**
* @description the response information to give back to the server object
*/
export interface RespInfo {
ContentType: string | undefined;
Stream: Stream.Readable | fs.ReadStream | undefined;
}
/**
* @description table entry for a file in the auto-generated index.
*/
export interface IndexFileEntry {
LinkSrc: string;
LinkName: string;
FileSize: string;
DateTime: string;
}
/**
* @description table entry for a directory in the auto-generated index.
*/
export interface IndexDirEntry {
LinkSrc: string;
LinkName: string;
DateTime: string;
}
/**
* @description object responsible for loading content requested by the HTTP server.
*/
export class ContentLoader extends Disposable {
private _scriptInjector: HTMLInjector | undefined;
private _servedFiles: Set<string> = new Set<string>();
private _insertionTags = ['head', 'body', 'html', '!DOCTYPE'];
constructor(
_extensionUri: vscode.Uri,
private readonly _reporter: TelemetryReporter,
private readonly _endpointManager: EndpointManager,
private readonly _workspaceManager: WorkspaceManager,
_connectionManager: ConnectionManager
) {
super();
this._scriptInjector = new HTMLInjector(_extensionUri, _connectionManager);
}
/**
* @description reset the list of served files; served files are used to watch changes for when being changed in the editor.
*/
public resetServedFiles(): void {
this._servedFiles = new Set<string>();
}
/**
* @returns the files served by the HTTP server
*/
public get servedFiles(): Set<string> {
return this._servedFiles;
}
/**
* @returns the script tags needed to reference the custom script endpoint.
*/
private get _scriptInjection(): string {
return `<script type="text/javascript" src="${INJECTED_ENDPOINT_NAME}"></script>`;
}
/**
* @returns {RespInfo} the injected script and its content type.
*/
public loadInjectedJS(): RespInfo {
const fileString = this._scriptInjector?.script ?? '';
return {
Stream: Stream.Readable.from(fileString),
ContentType: 'text/javascript',
};
}
/**
* @description create a "page does not exist" page to pair with the 404 error.
* @param relativePath the path that does not exist
* @returns {RespInfo} the response information
*/
public createPageDoesNotExist(relativePath: string): RespInfo {
/* __GDPR__
"server.pageDoesNotExist" : {}
*/
this._reporter.sendTelemetryEvent('server.pageDoesNotExist');
const htmlString = `
<!DOCTYPE html>
<html>
<head>
<title>File not found</title>
</head>
<body>
<h1>File not found</h1>
<p>The file <b>"${relativePath}"</b> cannot be found. It may have been moved, edited, or deleted.</p>
</body>
${this._scriptInjection}
</html>
`;
return {
Stream: Stream.Readable.from(htmlString),
ContentType: 'text/html',
};
}
/**
* @description In a multi-root case, the index will not lead to anything. Create this page to list all possible indices to visit.
* @returns {RespInfo} the response info
*/
public createNoRootServer(): RespInfo {
let customMsg;
if (this._workspaceManager.numPaths == 0) {
customMsg = `<p>You have no workspace open, so the index does not direct to anything.</p>`;
} else {
customMsg = `<p>You are in a multi-root workspace, so the index does not lead to one specific workspace. Access your workspaces using the links below:</p>
<ul>
`;
const workspaces = this._workspaceManager.workspaces;
if (workspaces) {
for (const i in workspaces) {
const workspacePath = this._endpointManager.encodeLooseFileEndpoint(
workspaces[i].uri.fsPath
);
customMsg += `
<li><a href="${workspacePath}/">${workspaces[i].name}</a></li>`;
}
}
customMsg += `</ul>`;
}
const htmlString = `
<!DOCTYPE html>
<html>
<head>
<title>No Server Root</title>
</head>
<body>
<h1>No Server Root</h1>
${customMsg}
</body>
${this._scriptInjection}
</html>
`;
return {
Stream: Stream.Readable.from(htmlString),
ContentType: 'text/html',
};
}
/**
* @description Create a defaut index page (served if no `index.html` file is available for the directory).
* @param {string} readPath the absolute path visited.
* @param {string} relativePath the relative path (from workspace root).
* @param {string} titlePath the path shown in the title.
* @returns {RespInfo} the response info.
*/
public createIndexPage(
readPath: string,
relativePath: string,
titlePath = relativePath
): RespInfo {
/* __GDPR__
"server.indexPage" : {}
*/
this._reporter.sendTelemetryEvent('server.indexPage');
const childFiles = fs.readdirSync(readPath);
const fileEntries = new Array<IndexFileEntry>();
const dirEntries = new Array<IndexDirEntry>();
if (relativePath != '/') {
dirEntries.push({ LinkSrc: '..', LinkName: '..', DateTime: '' });
}
for (const i in childFiles) {
const relativeFileWithChild = path.join(relativePath, childFiles[i]);
const absolutePath = path.join(readPath, childFiles[i]);
const fileStats = fs.statSync(absolutePath);
const modifiedDateTimeString = FormatDateTime(fileStats.mtime);
if (fileStats.isDirectory()) {
dirEntries.push({
LinkSrc: relativeFileWithChild,
LinkName: childFiles[i],
DateTime: modifiedDateTimeString,
});
} else {
const fileSize = FormatFileSize(fileStats.size);
fileEntries.push({
LinkSrc: relativeFileWithChild,
LinkName: childFiles[i],
FileSize: fileSize,
DateTime: modifiedDateTimeString,
});
}
}
let directoryContents = '';
dirEntries.forEach(
(elem: IndexDirEntry) =>
(directoryContents += `
<tr>
<td><a href="${elem.LinkSrc}/">${elem.LinkName}/</a></td>
<td></td>
<td>${elem.DateTime}</td>
</tr>\n`)
);
fileEntries.forEach(
(elem: IndexFileEntry) =>
(directoryContents += `
<tr>
<td><a href="${elem.LinkSrc}">${elem.LinkName}</a></td>
<td>${elem.FileSize}</td>
<td>${elem.DateTime}</td>
</tr>\n`)
);
const htmlString = `
<!DOCTYPE html>
<html>
<head>
<style>
table td {
padding:4px;
}
</style>
<title>Index of ${titlePath}</title>
</head>
<body>
<h1>Index of ${titlePath}</h1>
<table>
<th>Name</th><th>Size</th><th>Date Modified</th>
${directoryContents}
</table>
</body>
${this._scriptInjection}
</html>
`;
return {
Stream: Stream.Readable.from(htmlString),
ContentType: 'text/html',
};
}
/**
* @description get the file contents and load it into a form that can be served.
* @param {string} readPath the absolute file path to read from
* @param {boolean} inFilesystem whether the path is in the filesystem (false for untitled files in editor)
* @returns {RespInfo} the response info
*/
public getFileStream(readPath: string, inFilesystem = true): RespInfo {
this._servedFiles.add(readPath);
const workspaceDocuments = vscode.workspace.textDocuments;
let i = 0;
let stream;
let contentType = mime.getType(readPath) ?? 'text/plain';
while (i < workspaceDocuments.length) {
if (PathUtil.PathEquals(readPath, workspaceDocuments[i].fileName)) {
if (inFilesystem && workspaceDocuments[i].isUntitled) {
continue;
}
let fileContents = workspaceDocuments[i].getText();
if (workspaceDocuments[i].languageId == 'html') {
fileContents = this.injectIntoFile(fileContents);
contentType = 'text/html';
}
stream = Stream.Readable.from(fileContents);
break;
}
i++;
}
if (inFilesystem && i == workspaceDocuments.length) {
if (isFileInjectable(readPath)) {
const buffer = fs.readFileSync(readPath, 'utf8');
const injectedFileContents = this.injectIntoFile(buffer.toString());
stream = Stream.Readable.from(injectedFileContents);
} else {
stream = fs.createReadStream(readPath);
}
}
return {
Stream: stream,
ContentType: contentType,
};
}
/**
* Inject the script tags to reference the custom Live Preview script.
* NOTE: they are injected on the same line as existing content to ensure that
* the debugging works, since `js-debug` relies on the line numbers on the filesystem
* matching the served line numbers.
* @param {string} contents the contents to inject.
* @returns {string} the injected string.
*/
private injectIntoFile(contents: string): string {
// order of preference for script placement:
// 1. after <head>
// 2. after <body>
// 3. after <html>
// 4. after <!DOCTYPE >
// 5. at the very beginning
let re;
let tagEnd = 0;
for (const i in this._insertionTags) {
re = new RegExp(`<${this._insertionTags[i]}[^>]*>`, 'g');
re.test(contents);
tagEnd = re.lastIndex;
if (tagEnd != 0) {
break;
}
}
const newContents =
contents.substr(0, tagEnd) +
'\n' +
this._scriptInjection +
contents.substr(tagEnd);
return newContents;
}
} | the_stack |
import Tile2DHeader from './tile-2d-header';
import {getTileIndices, tileToBoundingBox} from './utils';
import {RequestScheduler} from '@loaders.gl/loader-utils';
import {Matrix4} from '@math.gl/core';
import {assert, Viewport} from '@deck.gl/core';
import {Bounds, TileIndex, ZRange} from './types';
import {TileLayerProps} from './tile-layer';
// bit masks
const TILE_STATE_VISITED = 1;
const TILE_STATE_VISIBLE = 2;
/*
show cached parent tile if children are loading
+-----------+ +-----+ +-----+-----+
| | | | | | |
| | | | | | |
| | --> +-----+-----+ -> +-----+-----+
| | | | | | |
| | | | | | |
+-----------+ +-----+ +-----+-----+
show cached children tiles when parent is loading
+-------+---- +------------
| | |
| | |
| | |
+-------+---- --> |
| | |
*/
export const STRATEGY_NEVER = 'never';
export const STRATEGY_REPLACE = 'no-overlap';
export const STRATEGY_DEFAULT = 'best-available';
export type RefinementStrategyFunction = (tiles: Tile2DHeader[]) => void;
export type RefinementStrategy =
| typeof STRATEGY_NEVER
| typeof STRATEGY_REPLACE
| typeof STRATEGY_DEFAULT
| RefinementStrategyFunction;
const DEFAULT_CACHE_SCALE = 5;
const STRATEGIES = {
[STRATEGY_DEFAULT]: updateTileStateDefault,
[STRATEGY_REPLACE]: updateTileStateReplace,
[STRATEGY_NEVER]: () => {}
};
export type Tileset2DProps = Pick<
TileLayerProps,
| 'getTileData'
| 'tileSize'
| 'maxCacheSize'
| 'maxCacheByteSize'
| 'refinementStrategy'
| 'extent'
| 'maxZoom'
| 'minZoom'
| 'maxRequests'
| 'zoomOffset'
> & {
onTileLoad: (tile: Tile2DHeader) => void;
onTileUnload: (tile: Tile2DHeader) => void;
onTileError: (error: any, tile: Tile2DHeader) => void;
};
/**
* Manages loading and purging of tile data. This class caches recently visited tiles
* and only creates new tiles if they are present.
*/
export default class Tileset2D {
private opts: Tileset2DProps;
private _requestScheduler: RequestScheduler;
private _cache: Map<string, Tile2DHeader>;
private _dirty: boolean;
private _tiles: Tile2DHeader[];
private _cacheByteSize: number;
private _viewport: Viewport | null;
private _selectedTiles: Tile2DHeader[] | null;
private _frameNumber: number;
private _modelMatrix: Matrix4;
private _modelMatrixInverse: Matrix4;
private _maxZoom?: number;
private _minZoom?: number;
private onTileLoad: (tile: Tile2DHeader) => void;
/**
* Takes in a function that returns tile data, a cache size, and a max and a min zoom level.
* Cache size defaults to 5 * number of tiles in the current viewport
*/
constructor(opts: Tileset2DProps) {
this.opts = opts;
this.onTileLoad = tile => {
this.opts.onTileLoad(tile);
if (this.opts.maxCacheByteSize) {
this._cacheByteSize += tile.byteLength;
this._resizeCache();
}
};
this._requestScheduler = new RequestScheduler({
maxRequests: opts.maxRequests,
throttleRequests: opts.maxRequests > 0
});
// Maps tile id in string {z}-{x}-{y} to a Tile object
this._cache = new Map();
this._tiles = [];
this._dirty = false;
this._cacheByteSize = 0;
// Cache the last processed viewport
this._viewport = null;
this._selectedTiles = null;
this._frameNumber = 0;
this._modelMatrix = new Matrix4();
this._modelMatrixInverse = new Matrix4();
this.setOptions(opts);
}
/* Public API */
get tiles() {
return this._tiles;
}
get selectedTiles(): Tile2DHeader[] | null {
return this._selectedTiles;
}
get isLoaded(): boolean {
return this._selectedTiles !== null && this._selectedTiles.every(tile => tile.isLoaded);
}
get needsReload(): boolean {
return this._selectedTiles !== null && this._selectedTiles.some(tile => tile.needsReload);
}
setOptions(opts: Tileset2DProps): void {
Object.assign(this.opts, opts);
if (Number.isFinite(opts.maxZoom)) {
this._maxZoom = Math.floor(opts.maxZoom);
}
if (Number.isFinite(opts.minZoom)) {
this._minZoom = Math.ceil(opts.minZoom);
}
}
// Clean up any outstanding tile requests.
finalize(): void {
for (const tile of this._cache.values()) {
if (tile.isLoading) {
tile.abort();
}
}
this._cache.clear();
this._tiles = [];
this._selectedTiles = null;
}
reloadAll(): void {
for (const id of this._cache.keys()) {
const tile = this._cache.get(id) as Tile2DHeader;
if (!this._selectedTiles || !this._selectedTiles.includes(tile)) {
this._cache.delete(id);
} else {
tile.setNeedsReload();
}
}
}
/**
* Update the cache with the given viewport and model matrix and triggers callback onUpdate.
*/
update(
viewport: Viewport,
{zRange, modelMatrix}: {zRange?: ZRange; modelMatrix?: Matrix4} = {}
): number {
const modelMatrixAsMatrix4 = new Matrix4(modelMatrix);
const isModelMatrixNew = !modelMatrixAsMatrix4.equals(this._modelMatrix);
if (!this._viewport || !viewport.equals(this._viewport) || isModelMatrixNew) {
if (isModelMatrixNew) {
this._modelMatrixInverse = modelMatrixAsMatrix4.clone().invert();
this._modelMatrix = modelMatrixAsMatrix4;
}
this._viewport = viewport;
const tileIndices = this.getTileIndices({
viewport,
maxZoom: this._maxZoom,
minZoom: this._minZoom,
zRange,
modelMatrix: this._modelMatrix,
modelMatrixInverse: this._modelMatrixInverse
});
this._selectedTiles = tileIndices.map(index => this._getTile(index, true));
if (this._dirty) {
// Some new tiles are added
this._rebuildTree();
}
// Check for needed reloads explicitly even if the view/matrix has not changed.
} else if (this.needsReload) {
this._selectedTiles = this._selectedTiles!.map(tile => this._getTile(tile.index));
}
// Update tile states
const changed = this.updateTileStates();
this._pruneRequests();
if (this._dirty) {
// cache size is either the user defined maxSize or 5 * number of current tiles in the viewport.
this._resizeCache();
}
if (changed) {
this._frameNumber++;
}
return this._frameNumber;
}
/* Public interface for subclassing */
/** Returns array of tile indices in the current viewport */
getTileIndices({
viewport,
maxZoom,
minZoom,
zRange,
modelMatrix,
modelMatrixInverse
}: {
viewport: Viewport;
maxZoom?: number;
minZoom?: number;
zRange: ZRange | undefined;
tileSize?: number;
modelMatrix?: Matrix4;
modelMatrixInverse?: Matrix4;
zoomOffset?: number;
}): TileIndex[] {
const {tileSize, extent, zoomOffset} = this.opts;
return getTileIndices({
viewport,
maxZoom,
minZoom,
zRange,
tileSize,
extent: extent as Bounds | undefined,
modelMatrix,
modelMatrixInverse,
zoomOffset
});
}
/** Returns unique string key for a tile index */
getTileId(index: TileIndex) {
return `${index.x}-${index.y}-${index.z}`;
}
/** Returns a zoom level for a tile index */
getTileZoom(index: TileIndex) {
return index.z;
}
/** Returns additional metadata to add to tile, bbox by default */
getTileMetadata(index: TileIndex) {
assert(this._viewport);
const {tileSize} = this.opts;
return {bbox: tileToBoundingBox(this._viewport, index.x, index.y, index.z, tileSize)};
}
/** Returns index of the parent tile */
getParentIndex(index: TileIndex) {
const x = Math.floor(index.x / 2);
const y = Math.floor(index.y / 2);
const z = index.z - 1;
return {x, y, z};
}
// Returns true if any tile's visibility changed
updateTileStates() {
assert(this._selectedTiles);
const refinementStrategy = this.opts.refinementStrategy || STRATEGY_DEFAULT;
const visibilities = new Array(this._cache.size);
let i = 0;
// Reset state
for (const tile of this._cache.values()) {
// save previous state
visibilities[i++] = tile.isVisible;
tile.isSelected = false;
tile.isVisible = false;
}
for (const tile of this._selectedTiles) {
tile.isSelected = true;
tile.isVisible = true;
}
// Strategy-specific state logic
(typeof refinementStrategy === 'function'
? refinementStrategy
: STRATEGIES[refinementStrategy])(Array.from(this._cache.values()));
i = 0;
// Check if any visibility has changed
for (const tile of this._cache.values()) {
if (visibilities[i++] !== tile.isVisible) {
return true;
}
}
return false;
}
/* Private methods */
_pruneRequests(): void {
const {maxRequests} = this.opts;
const abortCandidates: Tile2DHeader[] = [];
let ongoingRequestCount = 0;
for (const tile of this._cache.values()) {
// Keep track of all the ongoing requests
if (tile.isLoading) {
ongoingRequestCount++;
if (!tile.isSelected && !tile.isVisible) {
abortCandidates.push(tile);
}
}
}
while (maxRequests > 0 && ongoingRequestCount > maxRequests && abortCandidates.length > 0) {
// There are too many ongoing requests, so abort some that are unselected
const tile = abortCandidates.shift()!;
tile.abort();
ongoingRequestCount--;
}
}
// This needs to be called every time some tiles have been added/removed from cache
_rebuildTree() {
const {_cache} = this;
// Reset states
for (const tile of _cache.values()) {
tile.parent = null;
if (tile.children) {
tile.children.length = 0;
}
}
// Rebuild tree
for (const tile of _cache.values()) {
const parent = this._getNearestAncestor(tile);
tile.parent = parent;
if (parent?.children) {
parent.children.push(tile);
}
}
}
/**
* Clear tiles that are not visible when the cache is full
*/
/* eslint-disable complexity */
_resizeCache() {
assert(this.selectedTiles);
const {_cache, opts} = this;
const maxCacheSize =
opts.maxCacheSize ||
(opts.maxCacheByteSize ? Infinity : DEFAULT_CACHE_SCALE * this.selectedTiles.length);
const maxCacheByteSize = opts.maxCacheByteSize || Infinity;
const overflown = _cache.size > maxCacheSize || this._cacheByteSize > maxCacheByteSize;
if (overflown) {
for (const [id, tile] of _cache) {
if (!tile.isVisible) {
// delete tile
this._cacheByteSize -= opts.maxCacheByteSize ? tile.byteLength : 0;
_cache.delete(id);
this.opts.onTileUnload(tile);
}
if (_cache.size <= maxCacheSize && this._cacheByteSize <= maxCacheByteSize) {
break;
}
}
this._rebuildTree();
this._dirty = true;
}
if (this._dirty) {
// sort by zoom level so that smaller tiles are displayed on top
this._tiles = Array.from(this._cache.values()).sort((t1, t2) => t1.zoom - t2.zoom);
this._dirty = false;
}
}
/* eslint-enable complexity */
_getTile(index: TileIndex, create: true): Tile2DHeader;
_getTile(index: TileIndex, create?: false): Tile2DHeader | undefined;
_getTile(index: TileIndex, create?: boolean): Tile2DHeader | undefined {
const id = this.getTileId(index);
let tile = this._cache.get(id);
let needsReload = false;
if (!tile && create) {
tile = new Tile2DHeader(index);
Object.assign(tile, this.getTileMetadata(tile.index));
Object.assign(tile, {id, zoom: this.getTileZoom(tile.index)});
needsReload = true;
this._cache.set(id, tile);
this._dirty = true;
} else if (tile && tile.needsReload) {
needsReload = true;
}
if (tile && needsReload) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
tile.loadData({
getData: this.opts.getTileData,
requestScheduler: this._requestScheduler,
onLoad: this.onTileLoad,
onError: this.opts.onTileError
});
}
return tile;
}
_getNearestAncestor(tile: Tile2DHeader): Tile2DHeader | null {
const {_minZoom = 0} = this;
let index = tile.index;
while (this.getTileZoom(index) > _minZoom) {
index = this.getParentIndex(index);
const parent = this._getTile(index);
if (parent) {
return parent;
}
}
return null;
}
}
/* -- Refinement strategies --*/
/* eslint-disable max-depth */
// For all the selected && pending tiles:
// - pick the closest ancestor as placeholder
// - if no ancestor is visible, pick the closest children as placeholder
function updateTileStateDefault(allTiles: Tile2DHeader[]) {
for (const tile of allTiles) {
tile.state = 0;
}
for (const tile of allTiles) {
if (tile.isSelected && !getPlaceholderInAncestors(tile)) {
getPlaceholderInChildren(tile);
}
}
for (const tile of allTiles) {
tile.isVisible = Boolean(tile.state! & TILE_STATE_VISIBLE);
}
}
// Until a selected tile and all its selected siblings are loaded, use the closest ancestor as placeholder
function updateTileStateReplace(allTiles: Tile2DHeader[]) {
for (const tile of allTiles) {
tile.state = 0;
}
for (const tile of allTiles) {
if (tile.isSelected) {
getPlaceholderInAncestors(tile);
}
}
// Always process parents first
const sortedTiles = Array.from(allTiles).sort((t1, t2) => t1.zoom - t2.zoom);
for (const tile of sortedTiles) {
tile.isVisible = Boolean(tile.state! & TILE_STATE_VISIBLE);
if (tile.children && (tile.isVisible || tile.state! & TILE_STATE_VISITED)) {
// If the tile is rendered, or if the tile has been explicitly hidden, hide all of its children
for (const child of tile.children) {
child.state = TILE_STATE_VISITED;
}
} else if (tile.isSelected) {
getPlaceholderInChildren(tile);
}
}
}
// Walk up the tree until we find one ancestor that is loaded. Returns true if successful.
function getPlaceholderInAncestors(startTile: Tile2DHeader) {
let tile: Tile2DHeader | null = startTile;
while (tile) {
if (tile.isLoaded || tile.content) {
tile.state! |= TILE_STATE_VISIBLE;
return true;
}
tile = tile.parent;
}
return false;
}
// Recursively set children as placeholder
function getPlaceholderInChildren(tile) {
for (const child of tile.children) {
if (child.isLoaded || child.content) {
child.state |= TILE_STATE_VISIBLE;
} else {
getPlaceholderInChildren(child);
}
}
} | the_stack |
import 'chrome://webui-test/mojo_webui_test_support.js';
import {fuzzySearch, FuzzySearchOptions, TabData, TabGroup, TabItemType} from 'chrome://tab-search.top-chrome/tab_search.js';
import {assertDeepEquals, assertEquals} from 'chrome://webui-test/chai_assert.js';
import {createTab} from './tab_search_test_data.js';
/**
* Assert search results return in specific order.
*/
function assertSearchOrders(
input: string, items: TabData[], options: FuzzySearchOptions<TabData>,
expectedIndices: number[]) {
const results = fuzzySearch(input, items, options);
assertEquals(results.length, expectedIndices.length);
for (let i = 0; i < results.length; ++i) {
const expectedItem = items[expectedIndices[i]!]!;
const actualItem = results[i]!;
assertEquals(expectedItem.tab.title, actualItem.tab.title);
assertEquals(expectedItem.hostname, actualItem.hostname);
}
}
function assertResults(expectedRecords: Array<any>, actualRecords: TabData[]) {
assertEquals(expectedRecords.length, actualRecords.length);
expectedRecords.forEach((expected, i) => {
const actual = actualRecords[i]!;
assertEquals(expected.tab.title, actual.tab.title);
if (expected.tabGroup !== undefined) {
assertEquals(expected.tabGroup.title, actual.tabGroup!.title);
}
assertEquals(expected.hostname, actual.hostname);
assertDeepEquals(expected.highlightRanges, actual.highlightRanges);
});
}
suite('FuzzySearchTest', () => {
test('fuzzySearch', () => {
const records: TabData[] = [
new TabData(
createTab({title: 'OpenGL'}), TabItemType.OPEN_TAB, 'www.opengl.org'),
new TabData(
createTab({title: 'Google'}), TabItemType.OPEN_TAB, 'www.google.com'),
];
const matchedRecords = [
{
tab: {
title: 'Google',
},
hostname: 'www.google.com',
highlightRanges: {
'tab.title': [{start: 0, length: 1}, {start: 3, length: 3}],
hostname: [{start: 4, length: 1}, {start: 7, length: 3}],
},
},
{
tab: {
title: 'OpenGL',
},
hostname: 'www.opengl.org',
highlightRanges: {
'tab.title': [{start: 2, length: 1}, {start: 4, length: 2}],
hostname: [
{start: 6, length: 1}, {start: 8, length: 2}, {start: 13, length: 1}
],
},
},
];
const options = {
useFuzzySearch: true,
includeScore: true,
includeMatches: true,
keys: [
{
name: 'tab.title',
weight: 2,
},
{
name: 'hostname',
weight: 1,
},
],
};
assertResults(matchedRecords, fuzzySearch('gle', records, options));
assertResults(records, fuzzySearch('', records, options));
assertResults([], fuzzySearch('z', records, options));
});
test('fuzzy search title, hostname, and tab group title keys.', () => {
const tabDataWithGroup = new TabData(
createTab({title: 'Meet the cast'}), TabItemType.OPEN_TAB,
'meet the cast');
tabDataWithGroup.tabGroup = {title: 'Glee TV show'} as TabGroup;
const records = [
new TabData(
createTab({title: 'OpenGL'}), TabItemType.OPEN_TAB, 'www.opengl.org'),
new TabData(
createTab({title: 'Google'}), TabItemType.OPEN_TAB, 'www.google.com'),
tabDataWithGroup,
];
const matchedRecords = [
{
tab: {
title: 'Meet the cast',
},
hostname: 'meet the cast',
tabGroup: {title: 'Glee TV show'},
highlightRanges: {
'tabGroup.title': [{start: 0, length: 3}],
},
},
{
tab: {
title: 'Google',
},
hostname: 'www.google.com',
highlightRanges: {
'tab.title': [{start: 0, length: 1}, {start: 3, length: 3}],
hostname: [{start: 4, length: 1}, {start: 7, length: 3}],
},
},
{
tab: {
title: 'OpenGL',
},
hostname: 'www.opengl.org',
highlightRanges: {
'tab.title': [{start: 2, length: 1}, {start: 4, length: 2}],
hostname: [
{start: 6, length: 1}, {start: 8, length: 2}, {start: 13, length: 1}
],
},
},
];
const options = {
useFuzzySearch: true,
includeScore: true,
includeMatches: true,
keys: [
{
name: 'tab.title',
weight: 2,
},
{
name: 'hostname',
weight: 1,
},
{name: 'tabGroup.title', weight: 1.5},
],
};
assertResults(matchedRecords, fuzzySearch('gle', records, options));
assertResults(records, fuzzySearch('', records, options));
assertResults([], fuzzySearch('z', records, options));
});
test(
'Test fuzzy search prioritize string start over word start over others',
() => {
const records = [
new TabData(
createTab({title: 'Asear'}), TabItemType.OPEN_TAB, 'asear'),
new TabData(
createTab({title: 'Tab Search'}), TabItemType.OPEN_TAB,
'tab search'),
new TabData(
createTab({title: 'Search Engine'}), TabItemType.OPEN_TAB,
'search engine'),
];
const options = {
useFuzzySearch: true,
includeScore: true,
includeMatches: true,
keys: [
{
name: 'tab.title',
weight: 1,
},
]
};
assertSearchOrders('sear', records, options, [2, 1, 0]);
});
test('Test the exact match ranking order.', () => {
const options = {
useFuzzySearch: false,
keys: [
{
name: 'tab.title',
weight: 1,
},
{
name: 'hostname',
weight: 1,
},
],
};
// Initial pre-search item list.
const records = [
new TabData(
createTab({title: 'Code Search'}), TabItemType.OPEN_TAB,
'search.chromium.search'),
new TabData(
createTab({title: 'Marching band'}), TabItemType.OPEN_TAB,
'en.marching.band.com'),
new TabData(
createTab({title: 'Chrome Desktop Architecture'}),
TabItemType.OPEN_TAB, 'drive.google.com'),
new TabData(
createTab({title: 'Arch Linux'}), TabItemType.OPEN_TAB,
'www.archlinux.org'),
new TabData(
createTab({title: 'Arches National Park'}), TabItemType.OPEN_TAB,
'www.nps.gov'),
new TabData(
createTab({title: 'Search Engine Land - Search Engines'}),
TabItemType.OPEN_TAB, 'searchengineland.com'),
];
// Results for 'arch'.
const archMatchedRecords = [
{
tab: {title: 'Arch Linux'},
hostname: 'www.archlinux.org',
highlightRanges: {
'tab.title': [{start: 0, length: 4}],
hostname: [{start: 4, length: 4}],
},
},
{
tab: {title: 'Arches National Park'},
hostname: 'www.nps.gov',
highlightRanges: {
'tab.title': [{start: 0, length: 4}],
},
},
{
tab: {title: 'Chrome Desktop Architecture'},
hostname: 'drive.google.com',
highlightRanges: {
'tab.title': [{start: 15, length: 4}],
},
},
{
tab: {title: 'Code Search'},
hostname: 'search.chromium.search',
highlightRanges: {
'tab.title': [{start: 7, length: 4}],
hostname: [{start: 2, length: 4}, {start: 18, length: 4}],
},
},
{
tab: {title: 'Search Engine Land - Search Engines'},
hostname: 'searchengineland.com',
highlightRanges: {
'tab.title': [{start: 2, length: 4}, {start: 23, length: 4}],
hostname: [{start: 2, length: 4}]
},
},
{
tab: {title: 'Marching band'},
hostname: 'en.marching.band.com',
highlightRanges: {
'tab.title': [{start: 1, length: 4}],
hostname: [{start: 4, length: 4}],
},
},
];
// Results for 'search'.
const searchMatchedRecords = [
{
tab: {title: 'Code Search'},
hostname: 'search.chromium.search',
highlightRanges: {
'tab.title': [{start: 5, length: 6}],
hostname: [{start: 0, length: 6}, {start: 16, length: 6}],
},
},
{
tab: {title: 'Search Engine Land - Search Engines'},
hostname: 'searchengineland.com',
highlightRanges: {
'tab.title': [{start: 0, length: 6}, {start: 21, length: 6}],
hostname: [{start: 0, length: 6}],
},
},
];
// Empty search should return the full list.
assertResults(records, fuzzySearch('', records, options));
assertResults(archMatchedRecords, fuzzySearch('arch', records, options));
assertResults(
searchMatchedRecords, fuzzySearch('search', records, options));
// No matches should return an empty list.
assertResults([], fuzzySearch('archh', records, options));
});
test('Test exact search with escaped characters.', () => {
const options = {
useFuzzySearch: false,
keys: [
{
name: 'tab.title',
weight: 1,
},
{
name: 'hostname',
weight: 1,
},
],
};
// Initial pre-search item list.
const records = [
new TabData(
createTab({title: '\'beginning\\test\\end'}), TabItemType.OPEN_TAB,
'beginning\\test\"end'),
];
// Expected results for '\test'.
const backslashMatchedRecords = [
{
tab: {title: '\'beginning\\test\\end'},
hostname: 'beginning\\test\"end',
highlightRanges: {
'tab.title': [{start: 10, length: 5}],
hostname: [{start: 9, length: 5}],
},
},
];
// Expected results for '"end'.
const quoteMatchedRecords = [
{
tab: {title: '\'beginning\\test\\end'},
hostname: 'beginning\\test\"end',
highlightRanges: {
hostname: [{start: 14, length: 4}],
},
},
];
assertResults(
backslashMatchedRecords, fuzzySearch('\\test', records, options));
assertResults(quoteMatchedRecords, fuzzySearch('\"end', records, options));
});
test('Test exact match result scoring accounts for match position.', () => {
const options = {
useFuzzySearch: false,
keys: [
{
name: 'tab.title',
weight: 1,
},
{
name: 'hostname',
weight: 1,
},
],
};
assertSearchOrders(
'two',
[
new TabData(
createTab({title: 'three one two'}), TabItemType.OPEN_TAB,
'three one two'),
new TabData(
createTab({title: 'three two one'}), TabItemType.OPEN_TAB,
'three two one'),
new TabData(
createTab({title: 'one two three'}), TabItemType.OPEN_TAB,
'one two three'),
],
options, [2, 1, 0]);
});
test(
'Test exact match result scoring takes into account the number of matches per item.',
() => {
const options = {
useFuzzySearch: false,
keys: [
{
name: 'tab.title',
weight: 1,
},
{
name: 'hostname',
weight: 1,
},
],
};
assertSearchOrders(
'one',
[
new TabData(
createTab({title: 'one two three'}), TabItemType.OPEN_TAB,
'one two three'),
new TabData(
createTab({title: 'one one three'}), TabItemType.OPEN_TAB,
'one one three'),
new TabData(
createTab({title: 'one one one'}), TabItemType.OPEN_TAB,
'one one one'),
],
options, [2, 1, 0]);
});
test('Test exact match result scoring abides by the key weights.', () => {
const options = {
useFuzzySearch: false,
keys: [
{
name: 'tab.title',
weight: 2,
},
{
name: 'hostname',
weight: 1,
}
]
};
assertSearchOrders(
'search',
[
new TabData(
createTab({title: 'New tab'}), TabItemType.OPEN_TAB,
'chrome://tab-search'),
new TabData(
createTab({title: 'chrome://tab-search'}), TabItemType.OPEN_TAB,
'chrome://tab-search'),
new TabData(
createTab({title: 'chrome://tab-search'}), TabItemType.OPEN_TAB,
'chrome://tab-search'),
],
options, [2, 1, 0]);
});
}); | the_stack |
import * as fs from "fs";
import * as path from "path";
import { Menu, MenuItemConstructorOptions } from "electron";
import {
emuMachineContextAction,
emuSetClockMultiplierAction,
emuSetKeyboardLayoutAction,
} from "@state/emulator-panel-reducer";
import {
machineIdFromMenuId,
menuIdFromMachineId,
} from "../../main/utils/electron-utils";
import { LinkDescriptor, MachineContextProviderBase } from "./machine-context";
import {
setSoundLevel,
setSoundLevelMenu,
setupMenu,
} from "../../main/app/app-menu";
import { dialog } from "electron";
import { AppState } from "@state/AppState";
import { MachineCreationOptions } from "../abstractions/vm-core-types";
import {
CZ88_BATTERY_LOW,
CZ88_CARDS,
CZ88_HARD_RESET,
CZ88_PRESS_BOTH_SHIFTS,
CZ88_REFRESH_OPTIONS,
CZ88_SOFT_RESET,
} from "../../renderer/machines/cambridge-z88/macine-commands";
import {
Cz88ContructionOptions,
SlotContent,
Z88CardsState,
} from "../../extensions/cz88/common/cz88-specific";
import {
executeMachineCommand,
ExecuteMachineCommandResponse,
} from "@core/messaging/message-types";
import { ExtraMachineFeatures } from "@abstractions/machine-specfic";
import { VirtualMachineType } from "./machine-registry";
import { sendFromMainToEmu } from "@core/messaging/message-sending";
import { dispatch, getState } from "@core/service-registry";
import { emuWindow } from "../../main/app/emu-window";
// --- Default ROM file
const DEFAULT_ROM = "Z88OZ47.rom";
// --- Menu identifier contants
const SOFT_RESET = "cz88_soft_reset";
const HARD_RESET = "cz88_hard_reset";
const PRESS_SHIFTS = "cz88_press_shifts";
const BATTERY_LOW = "cz88_battery_low";
const LCD_DIMS = "cz88_lcd_dims";
const ROM_MENU = "cz88_roms";
const SELECT_ROM_FILE = "cz88_select_rom_file";
const USE_DEFAULT_ROM = "cz88_use_default_rom";
const USE_ROM_FILE = "cz88_rom";
const CARDS_DIALOG = "cz88_cards_dialog";
const KEYBOARDS = "cz88_keyboards";
const DE_KEYBOARD = "cz88_de_layout";
const DK_KEYBOARD = "cz88_dk_layout";
const FR_KEYBOARD = "cz88_fr_layout";
const ES_KEYBOARD = "cz88_es_layout";
const SE_KEYBOARD = "cz88_se_layout";
const UK_KEYBOARD = "cz88_uk_layout";
// --- Machine type (by LCD resolution) constants
const Z88_640_64 = "machine_cz88_255_8";
const Z88_640_320 = "machine_cz88_255_40";
const Z88_640_480 = "machine_cz88_255_60";
const Z88_800_320 = "machine_cz88_100_40";
const Z88_800_480 = "machine_cz88_100_60";
// ----------------------------------------------------------------------------
// Z88-specific help menu items
const z88Links: LinkDescriptor[] = [
{
label: "Cambridge Z88 User Guide",
uri: "https://cambridgez88.jira.com/wiki/spaces/UG/",
},
{
label: "Cambridge Z88 Developers' Notes",
uri: "https://cambridgez88.jira.com/wiki/spaces/DN/",
},
{
label: "BBC BASIC (Z80) Reference Guide for Z88",
uri: "https://docs.google.com/document/d/1ZFxKYsfNvbuTyErnH5Xtv2aKXWk1vg5TjrAxZnrLsuI",
},
{
label: null,
},
{
label: "Cambridge Z88 ROM && 3rd party application source code",
uri: "https://bitbucket.org/cambridge/",
},
{
label: "Cambridge Z88 on Wikipedia",
uri: "https://en.wikipedia.org/wiki/Cambridge_Z88",
},
{
label: "Cambridge Z88 assembler tools and utilities",
uri: "https://gitlab.com/bits4fun",
},
];
// ----------------------------------------------------------------------------
// We use these two variables to identify the current Z88 machine type
// The last used LCD specification
let recentLcdType = machineIdFromMenuId(Z88_640_64);
let lcdLabel = "640x64";
// The current ROM file (null, if default is used)
let usedRomFile: string | null = null;
// The current ROM size
let romSize = 512;
// The current RAM size
let ramSize = 512;
// The current keyboard layout
let kbLayout = "uk";
// ----------------------------------------------------------------------------
// Configuration we use to instantiate the Z88 machine
let recentOptions: MachineCreationOptions & Cz88ContructionOptions = {
baseClockFrequency: 1,
tactsInFrame: 16384,
scw: 0xff,
sch: 8,
};
// ----------------------------------------------------------------------------
// UI state of the ROM submenu
// The list of recently used ROMs
let recentRoms: string[] = [];
// Indicates that a recent ROM is selected. If false, we use the default ROM
let recentRomSelected = false;
// ----------------------------------------------------------------------------
// State of the card slots
let slotsState: Z88CardsState = {
slot1: { content: "empty" },
slot2: { content: "empty" },
slot3: { content: "empty" },
};
/**
* Context provider for the Cambridge Z88 machine type
*/
@VirtualMachineType({
id: "cz88",
label: "Cambridge Z88 (in progress)",
active: true,
})
export class Cz88ContextProvider extends MachineContextProviderBase {
/**
* Constructs the provider with the specified options
* @param options
*/
constructor(options?: Record<string, any>) {
super(options);
}
/**
* Gets the names of firmware files
*/
readonly firmwareFiles: string[] = [DEFAULT_ROM];
/**
* Firmware sizes accected by the virtual machine
*/
readonly acceptedFirmwareSizes: number[] | null = [
0x2_0000, 0x4_0000, 0x8_0000,
];
/**
* The normal CPU frequency of the machine
*/
getNormalCpuFrequency(): number {
return 3_276_800;
}
/**
* Context description for Z88
*/
getMachineContextDescription(): string {
return `Screen: ${lcdLabel}, ROM: ${
usedRomFile ? path.basename(usedRomFile) : DEFAULT_ROM
} (${romSize}KB), RAM: ${ramSize}KB`;
}
/**
* Items to add to the Show menu
*/
provideViewMenuItems(): MenuItemConstructorOptions[] | null {
return null;
}
/**
* Items to add to the machine menu
*/
provideMachineMenuItems(): MenuItemConstructorOptions[] | null {
// --- Create the submenu of recent roms
const romsSubmenu: MenuItemConstructorOptions[] = [];
romsSubmenu.push({
id: USE_DEFAULT_ROM,
label: "Use default ROM",
type: "checkbox",
checked: !recentRomSelected,
click: (mi) => {
mi.checked = true;
recentRomSelected = false;
usedRomFile = null;
const lastRomId = `${USE_ROM_FILE}_0`;
const item = Menu.getApplicationMenu().getMenuItemById(lastRomId);
if (item) {
item.checked = false;
}
if (recentOptions?.firmware) {
recentOptions = { ...recentOptions, firmware: undefined };
this.requestMachine();
}
this.setContext();
emuWindow.saveKliveProject();
},
});
if (recentRoms.length > 0) {
romsSubmenu.push({ type: "separator" });
for (let i = 0; i < recentRoms.length; i++) {
romsSubmenu.push({
id: `${USE_ROM_FILE}_${i}`,
label: path.basename(recentRoms[i]),
type: i === 0 ? "checkbox" : "normal",
checked: i === 0 && recentRomSelected,
click: async () => {
await this.selectRecentRomItem(i);
emuWindow.saveKliveProject();
},
});
}
}
romsSubmenu.push(
{ type: "separator" },
{
id: SELECT_ROM_FILE,
label: "Select ROM file...",
click: async () => {
await this.selectRomFileToUse();
emuWindow.saveKliveProject();
},
}
);
return [
{
id: LCD_DIMS,
type: "submenu",
label: "LCD resolution",
submenu: [
{
id: Z88_640_64,
type: "radio",
label: "640 x 64",
click: async () => await this.setLcd(Z88_640_64, "640x64", 0xff, 8),
},
{
id: Z88_640_320,
type: "radio",
label: "640 x 320",
click: async () =>
await this.setLcd(Z88_640_320, "640x320", 0xff, 40),
},
{
id: Z88_640_480,
type: "radio",
label: "640 x 480",
click: async () =>
await this.setLcd(Z88_640_480, "640x480", 0xff, 60),
},
{
id: Z88_800_320,
type: "radio",
label: "800 x 320",
click: async () =>
await this.setLcd(Z88_800_320, "800x320", 100, 40),
},
{
id: Z88_800_480,
type: "radio",
label: "800 x 480",
click: async () =>
await this.setLcd(Z88_800_480, "800x480", 100, 60),
},
],
},
{
id: KEYBOARDS,
label: "Keyboard layout",
type: "submenu",
submenu: [
{
id: UK_KEYBOARD,
label: "British && American",
type: "radio",
click: () => setKbLayout("uk"),
},
{
id: ES_KEYBOARD,
label: "Spanish",
type: "radio",
click: () => setKbLayout("es"),
},
{
id: FR_KEYBOARD,
label: "French",
type: "radio",
click: () => setKbLayout("fr"),
},
{
id: DE_KEYBOARD,
label: "German",
type: "radio",
click: () => setKbLayout("de"),
},
{
id: DK_KEYBOARD,
label: "Danish && Norwegian",
type: "radio",
click: () => setKbLayout("dk"),
},
{
id: SE_KEYBOARD,
label: "Swedish && Finish",
type: "radio",
click: () => setKbLayout("se"),
},
],
},
{ type: "separator" },
{
id: SOFT_RESET,
label: "Soft reset",
accelerator: "F8",
click: async () => await this.softReset(),
},
{
id: HARD_RESET,
label: "Hard reset",
accelerator: "F9",
click: async () => await this.hardReset(),
},
{ type: "separator" },
{
id: PRESS_SHIFTS,
label: "Press both SHIFT keys",
accelerator: "F6",
click: async () => await this.pressBothShifts(),
},
{
id: BATTERY_LOW,
label: "Raise Battery low signal",
click: async () => await this.raiseBatteryLow(),
},
{ type: "separator" },
{
id: ROM_MENU,
type: "submenu",
label: "Select ROM",
submenu: romsSubmenu,
},
{ type: "separator" },
{
id: CARDS_DIALOG,
label: "Insert or remove cards",
click: async () => await this.insertOrRemoveCards(),
},
];
function setKbLayout(layout: string): void {
kbLayout = layout;
dispatch(emuSetKeyboardLayoutAction(kbLayout));
emuWindow.saveKliveProject();
}
}
/**
* Items to add to the Help menu
*/
provideHelpMenuItems(): MenuItemConstructorOptions[] | null {
return this.getHyperlinkItems(z88Links);
}
/**
* When the application state changes, you can update the menus
*/
updateMenuStatus(state: AppState): void {
const menu = Menu.getApplicationMenu();
const softReset = menu.getMenuItemById(SOFT_RESET);
if (softReset) {
// --- Soft reset is available only if the machine is started, paused, or stopped.
softReset.enabled = state.emulatorPanel.executionState > 0;
}
// --- Select the current LCD dimension
const lcdType = menu.getMenuItemById(menuIdFromMachineId(recentLcdType));
if (lcdType) {
lcdType.checked = true;
}
// --- Select the current keyboard layout
const keyboardId = `cz88_${
state.emulatorPanel.keyboardLayout ?? "uk"
}_layout`;
const keyboardItem = menu.getMenuItemById(keyboardId);
if (keyboardItem) {
keyboardItem.checked = true;
}
// --- Enable/disable commands requiring a running machine
const bothShifts = menu.getMenuItemById(PRESS_SHIFTS);
if (bothShifts) {
bothShifts.enabled = state.emulatorPanel.executionState === 1;
}
const batLow = menu.getMenuItemById(BATTERY_LOW);
if (batLow) {
batLow.enabled = state.emulatorPanel.executionState === 1;
}
}
/**
* Get the list of machine features supported
*/
getExtraMachineFeatures(): ExtraMachineFeatures[] {
return ["Z88Cards"];
}
/**
* Sets the Z88 with the specified LCD type
* @param typeId Machine type with LCD size specification
*/
private async requestMachine(): Promise<void> {
const typeId = "cz88";
await emuWindow.requestMachineType(typeId, recentOptions);
}
/**
* Override this method to get the machine-specific settings
*/
getMachineSpecificSettings(): Record<string, any> {
const state = getState().emulatorPanel;
return {
lcd: lcdLabel,
kbLayout,
romFile: usedRomFile,
clockMultiplier: state.clockMultiplier,
soundLevel: state.soundLevel,
muted: state.muted,
slotsState,
};
}
/**
* Override this method to set the machine-specific settings
*/
async setMachineSpecificSettings(
settings: Record<string, any>
): Promise<MachineCreationOptions | null> {
if (settings.lcd) {
switch (settings.lcd) {
case "640x64":
await this.setLcd(Z88_640_64, "640x64", 0xff, 8);
break;
case "640x320":
await this.setLcd(Z88_640_320, "640x320", 0xff, 40);
break;
case "640x480":
await this.setLcd(Z88_640_480, "640x480", 0xff, 60);
break;
case "800x320":
await this.setLcd(Z88_800_320, "800x320", 100, 40);
break;
case "800x480":
await this.setLcd(Z88_800_480, "800x480", 100, 60);
break;
}
}
if (settings.kbLayout) {
switch (settings.kbLayout) {
case "uk":
case "fr":
case "es":
case "de":
case "dk":
case "se":
kbLayout = settings.kbLayout;
dispatch(emuSetKeyboardLayoutAction(kbLayout));
break;
}
}
if (settings.clockMultiplier) {
dispatch(emuSetClockMultiplierAction(settings.clockMultiplier));
}
if (settings.soundLevel) {
setSoundLevel(settings.soundLevel);
setSoundLevelMenu(settings.muted, settings.soundLevel);
}
await new Promise((r) => setTimeout(r, 600));
if (settings.romFile) {
await this.selectRomFileToUse(settings.romFile);
}
// --- Handle slot states
if (settings.slotsState) {
slotsState = settings.slotsState;
}
await this.processSlotState(1);
await this.processSlotState(2);
await this.processSlotState(3);
return recentOptions;
}
/**
* Processes the slot information for the specified card
* @param slot
* @returns
*/
private async processSlotState(
slot: number
): Promise<Uint8Array | undefined> {
const anySlot = slotsState as any;
if (!anySlot) {
return;
}
const slotProp = `slot${slot}`;
const cardProp = `card${slot}`;
if (!anySlot[slotProp]) {
anySlot[slotProp] = { content: "empty" };
} else {
let eprom: Uint8Array | undefined;
let ramSize: number | undefined;
switch (anySlot[slotProp].content) {
case "32K":
ramSize = 0x00_8000;
break;
case "128K":
ramSize = 0x02_0000;
break;
case "512K":
ramSize = 0x08_0000;
break;
case "1M":
ramSize = 0x10_0000;
break;
case "eprom":
const contents = await this.selectCardFileToUse(
anySlot[slotProp].epromFile
);
if (contents) {
eprom = contents;
}
break;
}
recentOptions[cardProp] = {
ramSize,
eprom,
};
return eprom;
}
}
/**
* Sets the Z88 LCD mode
* @param menuId LCD menu id
* @param label LCD label
* @param scw LCD width
* @param sch LCD height
*/
private async setLcd(
menuId: string,
label: string,
scw: number,
sch: number
): Promise<void> {
recentLcdType = machineIdFromMenuId(menuId);
lcdLabel = label;
recentOptions = { ...recentOptions, scw, sch };
await this.requestMachine();
this.setContext();
emuWindow.saveKliveProject();
}
/**
* Select the ROM file to use with Z88
*/
private async selectRomFileToUse(filename?: string): Promise<void> {
if (!filename) {
filename = await this.selectRomFileFromDialog();
if (!filename) {
return;
}
}
const contents = await this.checkCz88Rom(filename);
if (typeof contents === "string") {
await dialog.showMessageBox(emuWindow.window, {
title: "ROM error",
message: contents,
type: "error",
});
return;
}
// --- Ok, let's use the contents of this file
recentOptions = { ...recentOptions, firmware: [contents] };
// --- Use the selected contents
const recentFileIdx = recentRoms.indexOf(filename);
if (recentFileIdx >= 0) {
recentRoms.splice(recentFileIdx, 1);
}
usedRomFile = filename;
recentRoms.unshift(filename);
recentRoms.splice(4);
// --- Now set the ROM name and refresh the menu
recentRomSelected = true;
setupMenu();
// --- Request the current machine type
await this.requestMachine();
}
/**
* Select a ROM file to use with Z88
*/
private async selectRomFileFromDialog(): Promise<string | null> {
const window = emuWindow.window;
const result = await dialog.showOpenDialog(window, {
title: "Open ROM file",
filters: [
{ name: "ROM files", extensions: ["rom"] },
{ name: "BIN files", extensions: ["bin"] },
{ name: "All Files", extensions: ["*"] },
],
});
return result ? result.filePaths[0] : null;
}
/**
* Select the card file to use with Z88
*/
private async selectCardFileToUse(
filename?: string
): Promise<Uint8Array | null> {
if (!filename) {
return;
}
const contents = await this.checkSlotFile(filename);
if (typeof contents === "string") {
await dialog.showMessageBox(emuWindow.window, {
title: "Card file error",
message: contents,
type: "error",
});
return null;
}
return contents;
}
/**
* Checks if the specified file is a valid Z88 ROM
* @param filename ROM file name
* @returns The contents, if the ROM is valid; otherwise, the error message
*/
private async checkCz88Rom(filename: string): Promise<string | Uint8Array> {
try {
const contents = Uint8Array.from(fs.readFileSync(filename));
// --- Check contents length
if (
contents.length !== 0x8_0000 &&
contents.length !== 0x4_0000 &&
contents.length !== 0x2_0000
) {
return `Invalid ROM file length: ${contents.length}. The ROM file length can be 128K, 256K, or 512K.`;
}
// --- Check watermark
if (!this.isOZRom(contents)) {
return "The file does not contain the OZ ROM watermark.";
}
// --- Done: valid ROM
return contents;
} catch (err) {
// --- This error is intentionally ignored
return (
`Error processing ROM file ${filename}. ` +
"Please check if you have the appropriate access rights " +
"to read the files contents and the file is a valid ROM file."
);
}
}
/**
* Checks if the specified file is a valid Z88 ROM
* @param filename ROM file name
* @returns The contents, if the ROM is valid; otherwise, the error message
*/
private async checkSlotFile(filename: string): Promise<string | Uint8Array> {
try {
const contents = Uint8Array.from(fs.readFileSync(filename));
// --- Check contents length
if (
contents.length !== 0x10_0000 &&
contents.length !== 0x08_0000 &&
contents.length !== 0x04_0000 &&
contents.length !== 0x02_0000 &&
contents.length !== 0x00_8000
) {
return `Invalid card file length: ${contents.length}. The card file length can be 32K, 128K, 256K, 512K, or 1M.`;
}
// --- Done: valid ROM
return contents;
} catch (err) {
// --- This error is intentionally ignored
return (
`Error processing card file ${filename}. ` +
"Please check if you have the appropriate access rights " +
"to read the files contents and the file is a valid ROM file."
);
}
}
/**
* Selects one of the recent ROM items
* @param idx Selected ROM index
*/
private async selectRecentRomItem(idx: number): Promise<void> {
if (idx < 0 || idx >= recentRoms.length) {
return;
}
await this.selectRomFileToUse(recentRoms[idx]);
}
/**
* Check if specified slot contains an OZ Operating system
* @param contents Binary contents
* @returns true if Application Card is available in slot; otherwise false
*/
private isOZRom(contents: Uint8Array): boolean {
const topBankOffset = (contents.length & 0xe_c000) - 0x4000;
return (
contents[topBankOffset + 0x3ffb] === 0x81 &&
contents[topBankOffset + 0x3ffe] === "O".charCodeAt(0) &&
contents[topBankOffset + 0x3fff] === "Z".charCodeAt(0)
);
}
/**
* Execure soft reset
*/
private async softReset(): Promise<void> {
if (await this.confirmReset("Soft")) {
this.executeMachineCommand(CZ88_SOFT_RESET);
}
}
/**
* Execute hard reset
*/
private async hardReset(): Promise<void> {
if (await this.confirmReset("Hard")) {
this.executeMachineCommand(CZ88_HARD_RESET);
}
}
/**
* Execute insert/remove cards
*/
async insertOrRemoveCards(): Promise<void> {
const lastSlotState = { ...slotsState } as Z88CardsState;
const result = (await this.executeMachineCommand(
CZ88_CARDS,
slotsState
)) as Z88CardsState;
if (result) {
let changed = false;
let useSoftReset = true;
slotsState = result;
if (
lastSlotState.slot1?.content !== slotsState.slot1?.content ||
lastSlotState.slot1?.epromFile !== slotsState.slot1?.epromFile
) {
changed = true;
if (changed) {
useSoftReset =
useSoftReset &&
requiresSoftReset(
lastSlotState.slot1?.content,
slotsState.slot1?.content
);
await this.processSlotState(1);
}
}
if (
lastSlotState.slot2?.content !== slotsState.slot2?.content ||
lastSlotState.slot2?.epromFile !== slotsState.slot2?.epromFile
) {
changed = true;
if (changed) {
useSoftReset =
useSoftReset &&
requiresSoftReset(
lastSlotState.slot2?.content,
slotsState.slot2?.content
);
}
await this.processSlotState(2);
}
if (
lastSlotState.slot3?.content !== slotsState.slot3?.content ||
lastSlotState.slot3?.epromFile !== slotsState.slot3?.epromFile
) {
changed = true;
if (changed) {
useSoftReset =
useSoftReset &&
requiresSoftReset(
lastSlotState.slot3?.content,
slotsState.slot3?.content
);
}
await this.processSlotState(3);
}
if (changed) {
this.executeMachineCommand(CZ88_REFRESH_OPTIONS, recentOptions);
if (useSoftReset) {
this.executeMachineCommand(CZ88_SOFT_RESET);
} else {
const stateBefore = getState().emulatorPanel?.executionState ?? 0;
await this.requestMachine();
if (stateBefore) {
await this.executeMachineCommand(CZ88_HARD_RESET);
}
}
}
}
// --- Check if slot content change requires a soft reset
function requiresSoftReset(
oldContent: SlotContent,
newContent: SlotContent
): boolean {
return (
(oldContent === "eprom" && newContent === "empty") ||
(oldContent === "empty" && newContent === "eprom") ||
(oldContent === "empty" && newContent === "empty") ||
(oldContent === "eprom" && newContent === "eprom")
);
}
}
/**
* Executes the specified machine command
* @param command Command to execute
*/
private async executeMachineCommand(
command: string,
args?: unknown
): Promise<unknown> {
const response = (await sendFromMainToEmu(
executeMachineCommand(command, args)
)) as ExecuteMachineCommandResponse;
return response.result;
}
/**
* Press both shift keys
*/
private async pressBothShifts(): Promise<void> {
this.executeMachineCommand(CZ88_PRESS_BOTH_SHIFTS);
}
/**
* Press both shift keys
*/
private async raiseBatteryLow(): Promise<void> {
this.executeMachineCommand(CZ88_BATTERY_LOW);
}
/**
* Display a confirm message for reset
*/
private async confirmReset(type: string): Promise<boolean> {
const result = await dialog.showMessageBox(emuWindow.window, {
title: `Confirm Cambridge Z88 ${type} Reset`,
message: "Are you sure you want to reset the machine?",
buttons: ["Yes", "No"],
defaultId: 0,
type: "question",
});
return result.response === 0;
}
/**
* Sets the current machine context
*/
setContext(): void {
dispatch(emuMachineContextAction(this.getMachineContextDescription()));
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.