text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Command } from "commander";
import { log } from "console";
import * as fs from "fs";
import * as path from "path";
import { AnomalyDetectionModels, MindSphereSdk } from "../../api/sdk";
import { retry } from "../../api/utils";
import {
adjustColor,
errorLog,
generateTestData,
getColor,
getSdk,
homeDirLog,
proxyLog,
serviceCredentialLog,
verboseLog,
} from "./command-utils";
let color = getColor("blue");
export default (program: Command) => {
program
.command("anomaly-detection")
.alias("ad")
.option("-m, --mode [template|train|detect]", "mode [template | train | detect]", "train")
.option(
"-o, --on [data|asset]", // NOTE: 29/04/2021 - batch are excluded for now
"on [data | asset]", // NOTE: 29/04/2021 - batch are excluded for now
"data"
)
.option("-d, --data <data>", "time series data file", "timeseries.mdsp.json")
.option("-e, --epsilon <epsilon>", "threshold distance")
.option("-s, --clustersize <clustersize>", "minimum cluster size")
.option(
"-a, --algorithm [EUCLIDEAN|MANHATTAN|CHEBYSHEV]",
"distance measure algorithm [EUCLIDEAN | MANHATTAN | CHEBYSHEV]"
)
.option("-n, --modelname <modelname>", "human-friendly name of the model")
.option("-i, --modelid <modelid>", "mindsphere model id ")
.option("-i, --assetid <assetid>", "mindsphere asset id ")
.option("-n, --aspectname <aspectname>", "mindsphere aspect name")
.option("-f, --from <from>", "begining of the time range")
.option("-u, --to <to>", "end of the time range")
.option("-k, --passkey <passkey>", "passkey")
.option("-y, --retry <number>", "retry attempts before giving up", "3")
.option("-v, --verbose", "verbose output")
.description(color(`train anomaly detection models and detect timeseries anomalies *`))
.action((options) => {
(async () => {
try {
checkRequiredParameters(options);
const sdk = getSdk(options);
color = adjustColor(color, options, true);
homeDirLog(options.verbose, color);
proxyLog(options.verbose, color);
switch (options.mode) {
case "template":
await createTemplate(options, sdk);
console.log("Edit the files before submitting them to mindsphere.");
break;
case "train":
await trainNewModel(options, sdk);
break;
case "detect":
await detectAnomalies(options, sdk);
break;
default:
throw Error(`no such option: ${options.mode}`);
}
} catch (err) {
errorLog(err, options.verbose);
}
})();
})
.on("--help", () => printHelp());
};
function printHelp() {
log("\n Examples:\n");
log(` mc ad --mode template --data timeseries.data.mdsp.json \n \
creates a template for a time series data file`);
log(
` mc ad --mode train --on data --data timeseries.data.mdsp.json --epsilon 0.5 \n
trains a model on the timeserie specified in the data file`
);
log(
` mc ad --mode detect --on data --data timeseries.data.mdsp.json --modelid <modelid>\n \
detects anomalities of the timeseries in the data file using the model with specified id`
);
log(
` mc ad --mode train --on asset --assetid <assetid> --aspectname Environment --epsilon 0.5\n\
trains a model on the time series of the aspect "Environment" of the asset with the id <assetid>`
);
log(
` mc ad --mode detect --on asset --modelid <modelid> --assetid <assetid> --aspectname Environment --epsilon 0.5\n\
detect anomalities of the timeseries on the specified asset and aspect with selected model`
);
serviceCredentialLog();
}
function checkRequiredParameters(options: any) {
options.mode === "template" &&
!options.data &&
errorLog("you have to specify the output file of timeserie data", true);
options.mode === "detect" && !options.modelid && errorLog("you have to specify the modelid", true);
options.mode === "train" && !options.epsilon && errorLog("you have to specify the threshold distance", true);
options.on === "data" && !options.data && errorLog("you have to specify the timeserie data file", true);
options.on === "asset" && !options.assetid && errorLog("you have to specify the targeted assetId", true);
options.on === "asset" && !options.aspectname && errorLog("you have to specify the targeted aspect name", true);
}
async function createTemplate(options: any, sdk: MindSphereSdk) {
const generatedData = generateTestData(
10,
(x) => {
return 80 + Math.random() * 20 * Math.sin(x);
},
"Acceleration",
"number"
);
const fileName = options.data || "timeseries.data.mdsp.json";
fs.writeFileSync(fileName, JSON.stringify(generatedData, null, 2));
console.log(
`The time series data was written into ${color(
fileName
)}.\nRun \n\n\tmc ad --mode train --on data --data ${fileName} --epsilon 50.0 \n\nto create the model.\n`
);
}
async function trainNewModel(options: any, sdk: MindSphereSdk) {
const anomalyDetectionClient = sdk.GetAnomalyDetectionClient();
const tenant = sdk.GetTenant();
const timeOffset = new Date().getTime();
const on = options.on || "data";
const epsilon = options.epsilon;
const clustersize = options.clustersize || 2;
const algorithm = options.algorithm || "EUCLIDEAN";
const modelname = options.modelname || `Generated_by_CLI_${tenant}_${timeOffset}`;
switch (on) {
case "data":
// read the data file content
const filePath = path.resolve(options.data);
!fs.existsSync(filePath) && errorLog(`the metadata file ${filePath} doesn't exist!`, true);
const filecontent = fs.readFileSync(filePath);
const filedata = JSON.parse(filecontent.toString());
const result = (await retry(options.retry, async () =>
anomalyDetectionClient.PostModel(filedata, epsilon, clustersize, algorithm, modelname)
)) as AnomalyDetectionModels.Model;
console.log(`Model with modelid ${color(result.id)} and name ${color(result.name)} was created.`);
break;
case "asset":
const assetid = options.assetid;
const aspectname = options.aspectname;
const now = new Date();
const lastMonth = new Date();
lastMonth.setDate(lastMonth.getDate() - 7);
const fromLastMonth = new Date(lastMonth.getUTCFullYear(), lastMonth.getUTCMonth(), lastMonth.getUTCDate());
const toNow = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
let from = fromLastMonth;
try {
from = options.from ? new Date(options.from) : fromLastMonth;
} catch (error) {}
let to = toNow;
try {
to = options.to ? new Date(options.to) : toNow;
} catch (error) {}
const result_asset = (await retry(options.retry, async () =>
anomalyDetectionClient.PostModelDirect(
epsilon,
clustersize,
assetid,
aspectname,
from,
to,
algorithm,
modelname
)
)) as AnomalyDetectionModels.Model;
console.log(
`Model with modelid ${color(result_asset.id)} and name ${color(result_asset.name)} was created.`
);
default:
break;
}
}
async function detectAnomalies(options: any, sdk: MindSphereSdk) {
const anomalyDetectionClient = sdk.GetAnomalyDetectionClient();
const modelid = options.modelid;
const on = options.on || "data";
let result: AnomalyDetectionModels.Anomaly[] = [];
switch (on) {
case "data":
// read the data file content
const filePath = path.resolve(options.data);
!fs.existsSync(filePath) && errorLog(`the metadata file ${filePath} doesn't exist!`, true);
const filecontent = fs.readFileSync(filePath);
const filedata = JSON.parse(filecontent.toString());
result = (await retry(options.retry, async () =>
anomalyDetectionClient.DetectAnomalies(filedata, modelid)
)) as Array<AnomalyDetectionModels.Anomaly>;
break;
case "asset":
const assetid = options.assetid;
const aspectname = options.aspectname;
const now = new Date();
const lastMonth = new Date();
lastMonth.setDate(lastMonth.getDate() - 7);
const fromLastMonth = new Date(lastMonth.getUTCFullYear(), lastMonth.getUTCMonth(), lastMonth.getUTCDate());
const toNow = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
let from = fromLastMonth;
try {
from = options.from ? new Date(options.from) : fromLastMonth;
} catch (error) {}
let to = toNow;
try {
to = options.to ? new Date(options.to) : toNow;
} catch (error) {}
result = (await retry(options.retry, async () =>
anomalyDetectionClient.DetectAnomaliesDirect(modelid, assetid, aspectname, from, to)
)) as Array<AnomalyDetectionModels.Anomaly>;
default:
break;
}
console.log(`${color((result || [])?.length)} anomalies found.\n`);
(result || [])?.length > 0 && printDetectedAnomalies(result, options);
}
function printDetectedAnomalies(anomalies: Array<AnomalyDetectionModels.Anomaly>, options: any) {
console.log("\nDetected anomalies:");
console.table(anomalies || [], ["_time", "anomalyExtent"]);
verboseLog(JSON.stringify(anomalies, null, 2), options.verbose);
} | the_stack |
* @group unit/did
*/
import { IDidServiceEndpoint, KeyRelationship } from '@kiltprotocol/types'
import { BN, hexToU8a } from '@polkadot/util'
import type { IDidKeyDetails } from '@kiltprotocol/types'
import type {
INewPublicKey,
LightDidDetailsCreationOpts,
FullDidDetailsCreationOpts,
} from '../types'
import { FullDidDetails } from '../DidDetails/FullDidDetails'
import { LightDidDetails } from '../DidDetails/LightDidDetails'
import { exportToDidDocument } from './DidDocumentExporter'
describe('Full DID Document exporting tests', () => {
const identifier = '4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e'
const did = `did:kilt:${identifier}`
const keys: IDidKeyDetails[] = [
{
id: `${did}#1`,
controller: did,
includedAt: 100,
type: 'ed25519',
publicKeyHex:
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
},
{
id: `${did}#2`,
controller: did,
includedAt: 250,
type: 'x25519',
publicKeyHex:
'0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
},
{
id: `${did}#3`,
controller: did,
includedAt: 250,
type: 'x25519',
publicKeyHex:
'0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',
},
{
id: `${did}#4`,
controller: did,
includedAt: 200,
type: 'sr25519',
publicKeyHex:
'0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd',
},
]
const serviceEndpoints: IDidServiceEndpoint[] = [
{
id: `${did}#id-1`,
types: ['type-1'],
urls: ['url-1'],
},
{
id: `${did}#id-2`,
types: ['type-2'],
urls: ['url-2'],
},
]
const didDetails: FullDidDetailsCreationOpts = {
did,
keys,
keyRelationships: {
[KeyRelationship.authentication]: [keys[0].id],
[KeyRelationship.keyAgreement]: [keys[1].id, keys[2].id],
[KeyRelationship.assertionMethod]: [keys[3].id],
},
serviceEndpoints,
lastTxIndex: new BN(10),
}
it('exports the expected application/json W3C DID Document with an Ed25519 authentication key, two x25519 encryption keys, an Sr25519 assertion key, an Ecdsa delegation key, and two service endpoints', () => {
const ecdsaKey: IDidKeyDetails = {
id: `${did}#5`,
controller: did,
includedAt: 200,
type: 'ecdsa',
publicKeyHex:
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
}
const fullDidDetails = new FullDidDetails({
...didDetails,
keyRelationships: {
[KeyRelationship.authentication]: [keys[0].id],
[KeyRelationship.keyAgreement]: [keys[1].id, keys[2].id],
[KeyRelationship.assertionMethod]: [keys[3].id],
[KeyRelationship.capabilityDelegation]: [ecdsaKey.id],
},
keys: keys.concat([ecdsaKey]),
})
const didDoc = exportToDidDocument(fullDidDetails, 'application/json')
expect(didDoc).toStrictEqual({
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
verificationMethod: [
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#1',
controller:
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
type: 'Ed25519VerificationKey2018',
publicKeyBase58: 'CVDFLCAjXhVWiPXH9nTCTpCgVzmDVoiPzNJYuccr1dqB',
},
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#2',
controller:
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
type: 'X25519KeyAgreementKey2019',
publicKeyBase58: 'DdqGmK5uamYN5vmuZrzpQhKeehLdwtPLVJdhu5P2iJKC',
},
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#3',
controller:
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
type: 'X25519KeyAgreementKey2019',
publicKeyBase58: 'EnTJCS15dqbDTU2XywYSMaScoPv4Py4GzExrtY9DQxoD',
},
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#4',
controller:
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
type: 'Sr25519VerificationKey2020',
publicKeyBase58: 'Fw5KdYvFgue4q1HAQ264JTZax6VUr3jDVBJ1szuQ7dHE',
},
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#5',
controller:
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
type: 'EcdsaSecp256k1VerificationKey2019',
publicKeyBase58: '2pEER9q8Tu5XVwfBQeU2NE883JsUTX9jbbmVg3SL1g2fKCSd17',
},
],
authentication: [
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#1',
],
keyAgreement: [
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#2',
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#3',
],
assertionMethod: [
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#4',
],
capabilityDelegation: [
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#5',
],
service: [
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#id-1',
type: ['type-1'],
serviceEndpoint: ['url-1'],
},
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#id-2',
type: ['type-2'],
serviceEndpoint: ['url-2'],
},
],
})
})
it('exports the expected application/ld+json W3C DID Document with an Ed25519 authentication key, two x25519 encryption keys, an Sr25519 assertion key, an Ecdsa delegation key, and two service endpoints', () => {
const ecdsaKey: IDidKeyDetails = {
id: `${did}#5`,
controller: did,
includedAt: 200,
type: 'ecdsa',
publicKeyHex:
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
}
const fullDidDetails = new FullDidDetails({
...didDetails,
keyRelationships: {
[KeyRelationship.authentication]: [keys[0].id],
[KeyRelationship.keyAgreement]: [keys[1].id, keys[2].id],
[KeyRelationship.assertionMethod]: [keys[3].id],
[KeyRelationship.capabilityDelegation]: [ecdsaKey.id],
},
keys: keys.concat([ecdsaKey]),
})
const didDoc = exportToDidDocument(fullDidDetails, 'application/ld+json')
expect(didDoc).toStrictEqual({
'@context': ['https://www.w3.org/ns/did/v1'],
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
verificationMethod: [
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#1',
controller:
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
type: 'Ed25519VerificationKey2018',
publicKeyBase58: 'CVDFLCAjXhVWiPXH9nTCTpCgVzmDVoiPzNJYuccr1dqB',
},
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#2',
controller:
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
type: 'X25519KeyAgreementKey2019',
publicKeyBase58: 'DdqGmK5uamYN5vmuZrzpQhKeehLdwtPLVJdhu5P2iJKC',
},
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#3',
controller:
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
type: 'X25519KeyAgreementKey2019',
publicKeyBase58: 'EnTJCS15dqbDTU2XywYSMaScoPv4Py4GzExrtY9DQxoD',
},
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#4',
controller:
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
type: 'Sr25519VerificationKey2020',
publicKeyBase58: 'Fw5KdYvFgue4q1HAQ264JTZax6VUr3jDVBJ1szuQ7dHE',
},
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#5',
controller:
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e',
type: 'EcdsaSecp256k1VerificationKey2019',
publicKeyBase58: '2pEER9q8Tu5XVwfBQeU2NE883JsUTX9jbbmVg3SL1g2fKCSd17',
},
],
authentication: [
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#1',
],
keyAgreement: [
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#2',
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#3',
],
assertionMethod: [
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#4',
],
capabilityDelegation: [
'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#5',
],
service: [
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#id-1',
type: ['type-1'],
serviceEndpoint: ['url-1'],
},
{
id: 'did:kilt:4rp4rcDHP71YrBNvDhcH5iRoM3YzVoQVnCZvQPwPom9bjo2e#id-2',
type: ['type-2'],
serviceEndpoint: ['url-2'],
},
],
})
})
})
describe('Light DID Document exporting tests', () => {
const authPublicKey = hexToU8a(
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
)
const encPublicKey = hexToU8a(
'0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
)
let authenticationDidKeyDetails: INewPublicKey = {
publicKey: authPublicKey,
type: 'ed25519',
}
let encryptionDidKeyDetails: INewPublicKey | undefined
let serviceEndpoints: IDidServiceEndpoint[]
it('exports the expected application/json W3C DID Document with an Ed25519 authentication key, an x25519 encryption key, and two service endpoints', () => {
encryptionDidKeyDetails = {
publicKey: encPublicKey,
type: 'x25519',
}
serviceEndpoints = [
{
id: `id-1`,
types: ['type-1'],
urls: ['url-1'],
},
{
id: `id-2`,
types: ['type-2'],
urls: ['url-2'],
},
]
const didCreationDetails: LightDidDetailsCreationOpts = {
authenticationKey: authenticationDidKeyDetails,
encryptionKey: encryptionDidKeyDetails,
serviceEndpoints,
}
const didDetails = new LightDidDetails(didCreationDetails)
const didDoc = exportToDidDocument(didDetails, 'application/json')
expect(didDoc).toStrictEqual({
id: 'did:kilt:light:014rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF:z13nCdN4Pm2E11EsvuHFWcHY4c82dCFRxZP7MYtJD6ctPRrXzup7Cv8Wap18LHQaJYDnbvFdXQrpYjuXsoxKb2PhKXujiGAE5pFDyFGKjL8AJLGB2hXGSZyarmzeqjjYmEHSuHgCfH1cYPRHRCUaEAtehQvv6ZCpoPjChqcm7XaetboiWDisJ42smzR',
verificationMethod: [
{
id: 'did:kilt:light:014rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF:z13nCdN4Pm2E11EsvuHFWcHY4c82dCFRxZP7MYtJD6ctPRrXzup7Cv8Wap18LHQaJYDnbvFdXQrpYjuXsoxKb2PhKXujiGAE5pFDyFGKjL8AJLGB2hXGSZyarmzeqjjYmEHSuHgCfH1cYPRHRCUaEAtehQvv6ZCpoPjChqcm7XaetboiWDisJ42smzR#authentication',
controller:
'did:kilt:light:014rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF:z13nCdN4Pm2E11EsvuHFWcHY4c82dCFRxZP7MYtJD6ctPRrXzup7Cv8Wap18LHQaJYDnbvFdXQrpYjuXsoxKb2PhKXujiGAE5pFDyFGKjL8AJLGB2hXGSZyarmzeqjjYmEHSuHgCfH1cYPRHRCUaEAtehQvv6ZCpoPjChqcm7XaetboiWDisJ42smzR',
type: 'Ed25519VerificationKey2018',
publicKeyBase58: 'CVDFLCAjXhVWiPXH9nTCTpCgVzmDVoiPzNJYuccr1dqB',
},
{
id: 'did:kilt:light:014rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF:z13nCdN4Pm2E11EsvuHFWcHY4c82dCFRxZP7MYtJD6ctPRrXzup7Cv8Wap18LHQaJYDnbvFdXQrpYjuXsoxKb2PhKXujiGAE5pFDyFGKjL8AJLGB2hXGSZyarmzeqjjYmEHSuHgCfH1cYPRHRCUaEAtehQvv6ZCpoPjChqcm7XaetboiWDisJ42smzR#encryption',
controller:
'did:kilt:light:014rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF:z13nCdN4Pm2E11EsvuHFWcHY4c82dCFRxZP7MYtJD6ctPRrXzup7Cv8Wap18LHQaJYDnbvFdXQrpYjuXsoxKb2PhKXujiGAE5pFDyFGKjL8AJLGB2hXGSZyarmzeqjjYmEHSuHgCfH1cYPRHRCUaEAtehQvv6ZCpoPjChqcm7XaetboiWDisJ42smzR',
type: 'X25519KeyAgreementKey2019',
publicKeyBase58: 'DdqGmK5uamYN5vmuZrzpQhKeehLdwtPLVJdhu5P2iJKC',
},
],
authentication: [
'did:kilt:light:014rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF:z13nCdN4Pm2E11EsvuHFWcHY4c82dCFRxZP7MYtJD6ctPRrXzup7Cv8Wap18LHQaJYDnbvFdXQrpYjuXsoxKb2PhKXujiGAE5pFDyFGKjL8AJLGB2hXGSZyarmzeqjjYmEHSuHgCfH1cYPRHRCUaEAtehQvv6ZCpoPjChqcm7XaetboiWDisJ42smzR#authentication',
],
keyAgreement: [
'did:kilt:light:014rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF:z13nCdN4Pm2E11EsvuHFWcHY4c82dCFRxZP7MYtJD6ctPRrXzup7Cv8Wap18LHQaJYDnbvFdXQrpYjuXsoxKb2PhKXujiGAE5pFDyFGKjL8AJLGB2hXGSZyarmzeqjjYmEHSuHgCfH1cYPRHRCUaEAtehQvv6ZCpoPjChqcm7XaetboiWDisJ42smzR#encryption',
],
service: [
{
id: 'did:kilt:light:014rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF:z13nCdN4Pm2E11EsvuHFWcHY4c82dCFRxZP7MYtJD6ctPRrXzup7Cv8Wap18LHQaJYDnbvFdXQrpYjuXsoxKb2PhKXujiGAE5pFDyFGKjL8AJLGB2hXGSZyarmzeqjjYmEHSuHgCfH1cYPRHRCUaEAtehQvv6ZCpoPjChqcm7XaetboiWDisJ42smzR#id-1',
type: ['type-1'],
serviceEndpoint: ['url-1'],
},
{
id: 'did:kilt:light:014rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF:z13nCdN4Pm2E11EsvuHFWcHY4c82dCFRxZP7MYtJD6ctPRrXzup7Cv8Wap18LHQaJYDnbvFdXQrpYjuXsoxKb2PhKXujiGAE5pFDyFGKjL8AJLGB2hXGSZyarmzeqjjYmEHSuHgCfH1cYPRHRCUaEAtehQvv6ZCpoPjChqcm7XaetboiWDisJ42smzR#id-2',
type: ['type-2'],
serviceEndpoint: ['url-2'],
},
],
})
})
it('exports the expected application/json W3C DID Document with an Sr25519 authentication key', () => {
authenticationDidKeyDetails = {
publicKey: authPublicKey,
type: 'sr25519',
}
const didCreationDetails: LightDidDetailsCreationOpts = {
authenticationKey: authenticationDidKeyDetails,
}
const didDetails = new LightDidDetails(didCreationDetails)
const didDoc = exportToDidDocument(didDetails, 'application/json')
expect(didDoc).toStrictEqual({
id: 'did:kilt:light:004rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF',
verificationMethod: [
{
id: 'did:kilt:light:004rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF#authentication',
controller:
'did:kilt:light:004rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF',
type: 'Sr25519VerificationKey2020',
publicKeyBase58: 'CVDFLCAjXhVWiPXH9nTCTpCgVzmDVoiPzNJYuccr1dqB',
},
],
authentication: [
'did:kilt:light:004rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF#authentication',
],
})
})
it('exports the expected application/ld+json W3C DID Document with only an authentication key', () => {
authenticationDidKeyDetails = {
publicKey: authPublicKey,
type: 'sr25519',
}
const didCreationDetails: LightDidDetailsCreationOpts = {
authenticationKey: authenticationDidKeyDetails,
}
const didDetails = new LightDidDetails(didCreationDetails)
const didDoc = exportToDidDocument(didDetails, 'application/ld+json')
expect(didDoc).toStrictEqual({
'@context': ['https://www.w3.org/ns/did/v1'],
id: 'did:kilt:light:004rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF',
verificationMethod: [
{
id: 'did:kilt:light:004rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF#authentication',
controller:
'did:kilt:light:004rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF',
type: 'Sr25519VerificationKey2020',
publicKeyBase58: 'CVDFLCAjXhVWiPXH9nTCTpCgVzmDVoiPzNJYuccr1dqB',
},
],
authentication: [
'did:kilt:light:004rmqfMwFrv9mhwJwMb1vGWcmKmCNTRM8J365TRsJuPzXDNGF#authentication',
],
})
})
it('does not export a DID Document with an unsupported format', () => {
const didCreationDetails: LightDidDetailsCreationOpts = {
authenticationKey: authenticationDidKeyDetails,
}
const didDetails = new LightDidDetails(didCreationDetails)
expect(() => exportToDidDocument(didDetails, 'text/html')).toThrow()
})
}) | the_stack |
import * as React from 'react';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Observable, Subscription } from 'rxjs';
import { Viewport } from '../../mol-canvas3d/camera/util';
import { PluginContext } from '../../mol-plugin/context';
import { ViewportScreenshotHelper } from '../../mol-plugin/util/viewport-screenshot';
import { shallowEqual } from '../../mol-util/object';
import { useBehavior } from '../hooks/use-behavior';
export interface ScreenshotPreviewProps {
plugin: PluginContext,
suspend?: boolean,
cropFrameColor?: string,
borderColor?: string,
borderWidth?: number,
customBackground?: string
}
const _ScreenshotPreview = (props: ScreenshotPreviewProps) => {
const { plugin, cropFrameColor } = props;
const helper = plugin.helpers.viewportScreenshot!;
const [currentCanvas, setCurrentCanvas] = useState<HTMLCanvasElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const propsRef = useRef(props);
useEffect(() => {
propsRef.current = props;
}, Object.values(props));
useEffect(() => {
if (currentCanvas !== canvasRef.current) {
setCurrentCanvas(canvasRef.current);
}
});
useEffect(() => {
let isDirty = false;
const subs: Subscription[] = [];
function subscribe<T>(xs: Observable<T> | undefined, f: (v: T) => any) {
if (!xs) return;
subs.push(xs.subscribe(f));
}
function preview() {
const p = propsRef.current;
if (!p.suspend && canvasRef.current) {
drawPreview(helper, canvasRef.current, p.customBackground, p.borderColor, p.borderWidth);
}
if (!canvasRef.current) isDirty = true;
}
const interval = setInterval(() => {
if (isDirty) {
isDirty = false;
preview();
}
}, 1000 / 8);
subscribe(plugin.events.canvas3d.settingsUpdated, () => isDirty = true);
subscribe(plugin.canvas3d?.didDraw, () => isDirty = true);
subscribe(plugin.state.data.behaviors.isUpdating, v => {
if (!v) isDirty = true;
});
subscribe(helper.behaviors.values, () => isDirty = true);
subscribe(helper.behaviors.cropParams, () => isDirty = true);
let resizeObserver: any = void 0;
if (typeof ResizeObserver !== 'undefined') {
resizeObserver = new ResizeObserver(() => isDirty = true);
}
const canvas = canvasRef.current;
resizeObserver?.observe(canvas);
preview();
return () => {
clearInterval(interval);
subs.forEach(s => s.unsubscribe());
resizeObserver?.unobserve(canvas);
};
}, [helper]);
useLayoutEffect(() => {
if (canvasRef.current) {
drawPreview(helper, canvasRef.current, props.customBackground, props.borderColor, props.borderWidth);
}
}, [...Object.values(props)]);
return <>
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
<canvas ref={canvasRef} onContextMenu={e => { e.preventDefault(); e.stopPropagation(); }} style={{ display: 'block', width: '100%', height: '100%' }}></canvas>
<ViewportFrame plugin={plugin} canvas={currentCanvas} color={cropFrameColor} />
</div>
</>;
};
export const ScreenshotPreview = React.memo(_ScreenshotPreview, (prev, next) => shallowEqual(prev, next));
declare const ResizeObserver: any;
function drawPreview(helper: ViewportScreenshotHelper, target: HTMLCanvasElement, customBackground?: string, borderColor?: string, borderWidth?: number) {
const { canvas, width, height } = helper.getPreview()!;
const ctx = target.getContext('2d');
if (!ctx) return;
const w = target.clientWidth;
const h = target.clientHeight;
target.width = w;
target.height = h;
ctx.clearRect(0, 0, w, h);
const frame = getViewportFrame(width, height, w, h);
if (customBackground) {
ctx.fillStyle = customBackground;
ctx.fillRect(frame.x, frame.y, frame.width, frame.height);
} else if (helper.values.transparent) {
// must be an odd number
const s = 13;
for (let i = 0; i < frame.width; i += s) {
for (let j = 0; j < frame.height; j += s) {
ctx.fillStyle = (i + j) % 2 ? '#ffffff' : '#bfbfbf';
const x = frame.x + i, y = frame.y + j;
const w = i + s > frame.width ? frame.width - i : s;
const h = j + s > frame.height ? frame.height - j : s;
ctx.fillRect(x, y, w, h);
}
}
}
ctx.drawImage(canvas, frame.x, frame.y, frame.width, frame.height);
if (borderColor && borderWidth) {
const w = borderWidth;
ctx.rect(frame.x, frame.y, frame.width, frame.height);
ctx.rect(frame.x + w, frame.y + w, frame.width - 2 * w, frame.height - 2 * w);
ctx.fillStyle = borderColor;
ctx.fill('evenodd');
}
}
function ViewportFrame({ plugin, canvas, color = 'rgba(255, 87, 45, 0.75)' }: { plugin: PluginContext, canvas: HTMLCanvasElement | null, color?: string }) {
const helper = plugin.helpers.viewportScreenshot;
const params = useBehavior(helper?.behaviors.values!);
const cropParams = useBehavior(helper?.behaviors.cropParams!);
const crop = useBehavior(helper?.behaviors.relativeCrop!);
const cropFrameRef = useRef<Viewport>({ x: 0, y: 0, width: 0, height: 0 });
useBehavior(params?.resolution.name === 'viewport' ? plugin.canvas3d?.resized : void 0);
const [drag, setDrag] = React.useState<string>('');
const [start, setStart] = useState([0, 0]);
const [current, setCurrent] = useState([0, 0]);
if (!helper || !canvas) return null;
const { width, height } = helper.getSizeAndViewport();
const frame = getViewportFrame(width, height, canvas.clientWidth, canvas.clientHeight);
const cropFrame: Viewport = {
x: frame.x + Math.floor(frame.width * crop.x),
y: frame.y + Math.floor(frame.height * crop.y),
width: Math.ceil(frame.width * crop.width),
height: Math.ceil(frame.height * crop.height)
};
const rectCrop = toRect(cropFrame);
const rectFrame = toRect(frame);
if (drag === 'move') {
rectCrop.l += current[0] - start[0];
rectCrop.r += current[0] - start[0];
rectCrop.t += current[1] - start[1];
rectCrop.b += current[1] - start[1];
} else if (drag) {
if (drag.indexOf('left') >= 0) {
rectCrop.l += current[0] - start[0];
} else if (drag.indexOf('right') >= 0) {
rectCrop.r += current[0] - start[0];
}
if (drag.indexOf('top') >= 0) {
rectCrop.t += current[1] - start[1];
} else if (drag.indexOf('bottom') >= 0) {
rectCrop.b += current[1] - start[1];
}
}
if (rectCrop.l > rectCrop.r) {
const t = rectCrop.l;
rectCrop.l = rectCrop.r;
rectCrop.r = t;
}
if (rectCrop.t > rectCrop.b) {
const t = rectCrop.t;
rectCrop.t = rectCrop.b;
rectCrop.b = t;
}
const pad = 40;
rectCrop.l = Math.min(rectFrame.r - pad, Math.max(rectFrame.l, rectCrop.l));
rectCrop.r = Math.max(rectFrame.l + pad, Math.min(rectFrame.r, rectCrop.r));
rectCrop.t = Math.min(rectFrame.b - pad, Math.max(rectFrame.t, rectCrop.t));
rectCrop.b = Math.max(rectFrame.t + pad, Math.min(rectFrame.b, rectCrop.b));
cropFrame.x = rectCrop.l;
cropFrame.y = rectCrop.t;
cropFrame.width = rectCrop.r - rectCrop.l + 1;
cropFrame.height = rectCrop.b - rectCrop.t + 1;
cropFrameRef.current = cropFrame;
const onMove = (e: MouseEvent) => {
e.preventDefault();
setCurrent([e.pageX, e.pageY]);
};
const onTouchMove = (e: TouchEvent) => {
e.preventDefault();
const t = e.touches[0];
setCurrent([t.pageX, t.pageY]);
};
const onTouchStart = (e: React.TouchEvent) => {
e.preventDefault();
setDrag(e.currentTarget.getAttribute('data-drag')! as any);
const t = e.touches[0];
const p = [t.pageX, t.pageY];
setStart(p);
setCurrent(p);
window.addEventListener('touchend', onTouchEnd);
window.addEventListener('touchmove', onTouchMove);
};
const onStart = (e: React.MouseEvent<HTMLElement>) => {
e.preventDefault();
setDrag(e.currentTarget.getAttribute('data-drag')! as any);
const p = [e.pageX, e.pageY];
setStart(p);
setCurrent(p);
window.addEventListener('mouseup', onEnd);
window.addEventListener('mousemove', onMove);
};
const onEnd = () => {
window.removeEventListener('mouseup', onEnd);
window.removeEventListener('mousemove', onMove);
finish();
};
const onTouchEnd = () => {
window.removeEventListener('touchend', onTouchEnd);
window.removeEventListener('touchmove', onTouchMove);
finish();
};
function finish() {
const cropFrame = cropFrameRef.current;
if (cropParams.auto) {
helper?.behaviors.cropParams.next({ ...cropParams, auto: false });
}
helper?.behaviors.relativeCrop.next({
x: (cropFrame.x - frame.x) / frame.width,
y: (cropFrame.y - frame.y) / frame.height,
width: cropFrame.width / frame.width,
height: cropFrame.height / frame.height
});
setDrag('');
const p = [0, 0];
setStart(p);
setCurrent(p);
}
const contextMenu = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
};
const d = 4;
const border = `3px solid ${color}`;
const transparent = 'transparent';
return <>
<div data-drag='move' style={{ position: 'absolute', left: cropFrame.x, top: cropFrame.y, width: cropFrame.width, height: cropFrame.height, border, cursor: 'move' }} onMouseDown={onStart} onTouchStart={onTouchStart} draggable={false} onContextMenu={contextMenu} />
<div data-drag='left' style={{ position: 'absolute', left: cropFrame.x - d, top: cropFrame.y + d, width: 4 * d, height: cropFrame.height - d, background: transparent, cursor: 'w-resize' }} onMouseDown={onStart} onTouchStart={onTouchStart} draggable={false} onContextMenu={contextMenu} />
<div data-drag='right' style={{ position: 'absolute', left: rectCrop.r - 2 * d, top: cropFrame.y, width: 4 * d, height: cropFrame.height - d, background: transparent, cursor: 'w-resize' }} onMouseDown={onStart} onTouchStart={onTouchStart} draggable={false} onContextMenu={contextMenu} />
<div data-drag='top' style={{ position: 'absolute', left: cropFrame.x - d, top: cropFrame.y - d, width: cropFrame.width + 2 * d, height: 4 * d, background: transparent, cursor: 'n-resize' }} onMouseDown={onStart} onTouchStart={onTouchStart} draggable={false} onContextMenu={contextMenu} />
<div data-drag='bottom' style={{ position: 'absolute', left: cropFrame.x - d, top: rectCrop.b - 2 * d, width: cropFrame.width + 2 * d, height: 4 * d, background: transparent, cursor: 'n-resize' }} onMouseDown={onStart} onTouchStart={onTouchStart} draggable={false} onContextMenu={contextMenu} />
<div data-drag='top, left' style={{ position: 'absolute', left: rectCrop.l - d, top: rectCrop.t - d, width: 4 * d, height: 4 * d, background: transparent, cursor: 'nw-resize' }} onMouseDown={onStart} onTouchStart={onTouchStart} draggable={false} onContextMenu={contextMenu} />
<div data-drag='bottom, right' style={{ position: 'absolute', left: rectCrop.r - 2 * d, top: rectCrop.b - 2 * d, width: 4 * d, height: 4 * d, background: transparent, cursor: 'nw-resize' }} onMouseDown={onStart} onTouchStart={onTouchStart} draggable={false} onContextMenu={contextMenu} />
<div data-drag='top, right' style={{ position: 'absolute', left: rectCrop.r - 2 * d, top: rectCrop.t - d, width: 4 * d, height: 4 * d, background: transparent, cursor: 'ne-resize' }} onMouseDown={onStart} onTouchStart={onTouchStart} draggable={false} onContextMenu={contextMenu} />
<div data-drag='bottom, left' style={{ position: 'absolute', left: rectCrop.l - d, top: rectCrop.b - 2 * d, width: 4 * d, height: 4 * d, background: transparent, cursor: 'ne-resize' }} onMouseDown={onStart} onTouchStart={onTouchStart} draggable={false} onContextMenu={contextMenu} />
</>;
}
function toRect(viewport: Viewport) {
return { l: viewport.x, t: viewport.y, r: viewport.x + viewport.width - 1, b: viewport.y + viewport.height - 1 };
}
function getViewportFrame(srcWidth: number, srcHeight: number, w: number, h: number): Viewport {
const a0 = srcWidth / srcHeight;
const a1 = w / h;
if (a0 <= a1) {
const t = h * a0;
return { x: Math.round((w - t) / 2), y: 0, width: Math.round(t), height: h };
} else {
const t = w / a0;
return { x: 0, y: Math.round((h - t) / 2), width: w, height: Math.round(t) };
}
} | the_stack |
import { IServer } from "./IServer.interface";
import { ISocket } from "./ISocket.interface";
import { EventEmitter } from "./EventEmitter";
import { Stub } from "./Stub";
import { Transport } from "./Transport";
import { Util } from "./Util.class";
import { Contract } from "./Contract.class";
import { Protocol } from "./Protocol.static";
import { InvokeContext } from "./InvokeContext.class";
import * as Transports from './transport/index';
import * as fs from "fs";
import * as http from "http";
import * as url from "url";
//var fs = require('fs');
//var http = require('http');
//var url = require('url');
/**
* Eureca server constructor
* This constructor takes an optional settings object
* @constructor Server
* @param {object} [settings] - have the following properties
* @property {string} [settings.transport=engine.io] - can be "engine.io", "sockjs", "websockets", "faye" or "browserchannel" by default "engine.io" is used
* @property {function} [settings.authenticate] - If this function is defined, the client will not be able to invoke server functions until it successfully call the client side authenticate method, which will invoke this function.
* @property {function} [settings.serialize] - If defined, this function is used to serialize the request object before sending it to the client (default is JSON.stringify). This function can be useful to add custom information/meta-data to the transmitted request.
* @property {function} [settings.deserialize] - If defined, this function is used to deserialize the received response string.
* @property {function} [settings.cookieParser] - If defined, middleweare will be used to parse cookies (to use with express cookieParser).
* @property {object} [settings.transportSettings] - If defined, all parameters passed here will be sent to the underlying transport settings, this can be used to finetune, or override transport settings.
*
* @example
* <h4> # default instantiation</h4>
* var Eureca = require('eureca.io');
* //use default transport
* var server = new Eureca.Server();
*
*
* @example
* <h4> # custom transport instantiation </h4>
* var Eureca = require('eureca.io');
* //use websockets transport
* var server = new Eureca.Server({transport:'websockets'});
*
* @example
* <h4> # Authentication </h4>
* var Eureca = require('eureca.io');
*
* var eurecaServer = new Eureca.Server({
* authenticate: function (authToken, next) {
* console.log('Called Auth with token=', authToken);
*
* if (isValidToekn(authToken)) next(); // authentication success
* else next('Auth failed'); //authentication fail
* }
* });
*
* @see attach
* @see getClient
*
*
*/
export class Server extends EventEmitter {
public transport;
public exports = {};
public stub: Stub;
public contract = [];
public clients = {};
private appServer;
private __eureca_exports__: any = {};
private __eureca_rest__: any = { get: [], put: [], head: [] };
private scriptCache = '';
private useAuthentication: boolean;
/**
* Allowed regular expression is used to check the validity of a function received from client
*/
private allowedRx: RegExp;
private allowedF: Array<string> = [];
private ioServer: IServer;
private serialize = (v) => v;
private deserialize = (v) => v;
constructor(public settings: any = {}) {
super();
if (!settings.transport) settings.transport = 'engine.io';
if (!settings.prefix) settings.prefix = 'eureca.io';
if (!settings.clientScript) settings.clientScript = '/eureca.js';
this.loadTransports();
this.transport = Transport.get(settings.transport);
if (this.transport.serialize) this.serialize = this.transport.serialize;
if (this.transport.deserialize) this.deserialize = this.transport.deserialize;
settings.serialize = settings.serialize || this.serialize;
settings.deserialize = settings.deserialize || this.deserialize;
this.useAuthentication = (typeof this.settings.authenticate == 'function');
// if (this.useAuthentication)
// this.exports.authenticate = this.settings.authenticate;
this.allowedF = this.settings.allow instanceof Array ? this.settings.allow : [];
if (typeof this.settings.allow === 'string') {
this.settings.allow = this.settings.allow.trim();
let match = this.settings.allow.match(new RegExp('^/(.*?)/([gimy]*)$'));
if (!match || match[1]) this.settings.allow = `/${this.settings.allow.replace('.', '\.').replace('*', '.*')}/`;
match = this.settings.allow.match(new RegExp('^/(.*?)/([gimy]*)$'));
if (match) this.allowedRx = new RegExp(match[1], match[2]);
}
this.stub = new Stub(settings);
}
private loadTransports() {
for (let tr in Transports) {
if (typeof Transports[tr].register === 'function') Transports[tr].register();
}
}
private sendScript(request, response, prefix) {
let scriptConfig = '';
scriptConfig += `\nconst _eureca_prefix = '${prefix}';\n`;
scriptConfig += `\nconst _eureca_host = '${Util.getUrl(request)}';\n`;
scriptConfig += "\nconst _eureca_uri = `${_eureca_host}/${_eureca_prefix}`;\n";
if (this.scriptCache != '') {
//FIXME : don't cache _eureca_host, it can lead to inconsistencies (for example if you first load the page from localhost then from external IP, the localhost will be cached)
response.writeHead(200);
response.write(scriptConfig + this.scriptCache);
response.end();
return;
}
this.scriptCache = '';
if (this.transport.script) {
if (this.transport.script.length < 256 && fs.existsSync(__dirname + this.transport.script))
this.scriptCache += fs.readFileSync(__dirname + this.transport.script);
else
this.scriptCache += this.transport.script;
}
//FIXME : override primus hardcoded pathname
this.scriptCache += '\nif (typeof Primus != "undefined") Primus.prototype.pathname = "/' + prefix + '";\n';
//Add eureca client script
this.scriptCache += fs.readFileSync(__dirname + '/EurecaClient.js');
response.writeHead(200);
response.write(scriptConfig + this.scriptCache);
response.end();
}
private _export(obj, name, update = true) {
if (typeof name !== 'string') throw new Error('invalid object name');
if (name !== '__default__' && this.__eureca_exports__[name]) {
console.warn(`Export name "${name}" already used, will be overwritten`);
}
const cexport = {
exports: obj,
contract: Contract.ensureContract(obj),
context: (obj && obj.constructor && obj.constructor.name === 'Object') ? undefined : obj
}
this.__eureca_exports__[name] = cexport;
if (update) {
const sendObj = {};
sendObj[Protocol.contractFnList] = cexport.contract;
sendObj[Protocol.contractObjId] = name;
if (this.allowedRx !== undefined)
sendObj[Protocol.command] = this.settings.allow;
for (let id in this.clients) {
const eurecaClientSocket: ISocket = this.clients[id];
eurecaClientSocket.send(this.settings.serialize(sendObj));
}
}
}
private _handleEurecaClientSocketEvents(eurecaClientSocket: ISocket) {
eurecaClientSocket.on('message', (message) => {
/**
* Triggered each time a new message is received from a client.
*
* @event Server#message
* @property {String} message - the received message.
* @property {ISocket} socket - client socket.
*/
this.emit('message', message, eurecaClientSocket);
const jobj = this.deserialize.call(eurecaClientSocket, message);
if (jobj === undefined) {
this.emit('unhandledMessage', message, eurecaClientSocket);
return;
}
//Handle authentication
if (jobj[Protocol.authReq] !== undefined) {
if (typeof this.settings.authenticate == 'function') {
const args = jobj[Protocol.authReq];
args.push((error) => {
if (error == null) {
eurecaClientSocket.eureca.authenticated = true;
this._export(this.exports, '__default__', false);
}
const authResponse = {};
authResponse[Protocol.authResp] = [error];
eurecaClientSocket.send(this.serialize(authResponse));
this.emit('authentication', error);
});
const context: any = {
user: { clientId: eurecaClientSocket.id },
socket: eurecaClientSocket,
request: eurecaClientSocket['request']
};
this.settings.authenticate.apply(context, args);
}
return;
}
if (this.useAuthentication && !eurecaClientSocket.eureca.authenticated) {
return;
}
if (this.allowedRx && jobj[Protocol.contractFnList] !== undefined) {
const contractObjId = jobj[Protocol.contractObjId] || '__default__';
//regenerate the client proxy
this.stub.importRemoteFunction(eurecaClientSocket, jobj[Protocol.contractFnList], contractObjId, this.allowedRx);
return;
}
/*****************************************/
//handle remote call
if (jobj[Protocol.functionId] !== undefined) {
const invokeContext = new InvokeContext(eurecaClientSocket, jobj);
invokeContext.serialize = this.serialize;
const handle = jobj[Protocol.contractObjId] ? this.__eureca_exports__[jobj[Protocol.contractObjId]] : this;
this.stub.invokeLocal(invokeContext, handle);
return;
}
//handle remote response
if (jobj[Protocol.signatureId] !== undefined) //invoke result
{
//_this.stub.doCallBack(jobj[Protocol.signatureId], jobj[Protocol.resultId], jobj[Protocol.errorId]);
Stub.doCallBack(jobj[Protocol.signatureId], jobj[Protocol.resultId], jobj[Protocol.errorId], eurecaClientSocket);
return;
}
this.emit('unhandledMessage', message, eurecaClientSocket);
});
eurecaClientSocket.on('error', (e) => {
/**
* triggered if an error occure.
*
* @event Server#error
* @property {String} error - the error message
* @property {ISocket} socket - client socket.
*/
this.emit('error', e, eurecaClientSocket);
});
eurecaClientSocket.on('close', () => {
/**
* triggered when the client is disconneced.
*
* @event Server#disconnect
* @property {ISocket} socket - client socket.
*/
this.emit('disconnect', eurecaClientSocket);
delete this.clients[eurecaClientSocket.id];
});
eurecaClientSocket.on('stateChange', (s) => {
this.emit('stateChange', s);
});
}
private _handleServer(ioServer: IServer) {
//ioServer.on('connection', function (socket) {
ioServer.onconnect((eurecaClientSocket: ISocket) => {
if ((<any>eurecaClientSocket).request && (<any>eurecaClientSocket).request.primus) {
eurecaClientSocket.eureca.remoteAddress = (<any>eurecaClientSocket).request.primus.remoteAddress;
eurecaClientSocket.eureca.remotePort = (<any>eurecaClientSocket).request.primus.remotePort;
}
else {
eurecaClientSocket.eureca.remoteAddress = (<any>eurecaClientSocket).remoteAddress;
}
this.clients[eurecaClientSocket.id] = eurecaClientSocket;
//send contract to client
//this.sendContract(eurecaClientSocket);
if (!this.useAuthentication) this._export(this.exports, '__default__', false);
//generate client proxy
eurecaClientSocket.proxy = this.getClient(eurecaClientSocket.id);
//Deprecation wrapper
Object.defineProperty(eurecaClientSocket, 'clientProxy', {
get: function () {
console.warn('DEPRECATED: socket.clientProxy is deprecated, please use socket.proxy instead');
return eurecaClientSocket.proxy;
}
})
this._handleEurecaClientSocketEvents(eurecaClientSocket);
for (let name in this.__eureca_exports__) {
const cexport = this.__eureca_exports__[name];
const sendObj = {};
sendObj[Protocol.contractFnList] = cexport.contract;
sendObj[Protocol.contractObjId] = name;
//add ns list
if (name === '__default__') sendObj[Protocol.nsListId] = Object.keys(this.__eureca_exports__);
if (this.allowedRx !== undefined)
sendObj[Protocol.command] = this.settings.allow;
eurecaClientSocket.send(this.settings.serialize(sendObj));
}
this.emit('connect', eurecaClientSocket);
});
}
/**
* This method is used to get the client proxy of a given connection.
* it allows the server to call remote client function
*
* @function Server#getClient
* @param {String} id - client identifier
* @returns {Proxy}
*
* @example
* //we suppose here that the clients are exposing hello() function
* //onConnect event give the server an access to the client socket
* server.onConnect(function (socket) {
* //get client proxy by socket ID
* var client = server.getClient(socket.id);
* //call remote hello() function.
* client.hello();
* }
*/
public getClient(id) {
const socket: ISocket = this.clients[id];
if (socket === undefined) return undefined;
if (socket.proxy !== undefined) return socket.proxy;
this.stub.importRemoteFunction(socket, socket.contract || this.allowedF, undefined, this.allowedRx);
return socket.proxy;
}
/**
* returns the client socket
* @param id connection id
*/
public getClientSocket(id) {
return this.clients[id];
}
public getConnection(id) {
console.warn('DEPRECATED: getConnection() is deprecated, please use getClientSocket() instead');
return this.getClientSocket(id);
}
/**
* Sends exported server functions to all connected clients <br />
*
* @function bind
* @memberof Server#
* @param {appServer} - a nodejs {@link https://nodejs.org/api/http.html#http_class_http_server|nodejs http server}
* or {@link http://expressjs.com/api.html#application|expressjs Application}
*
*/
public bind(httpServer: any) {
let app = undefined;
//is it express application ?
if (httpServer._events && httpServer._events.request !== undefined && httpServer.routes === undefined && httpServer._events.request.on)
app = httpServer._events.request;
//is standard http server ?
if (app === undefined && httpServer instanceof http.Server)
app = httpServer
//not standard http server nor express app ==> try to guess http.Server instance
if (app === undefined) {
var keys = Object.getOwnPropertyNames(httpServer);
for (let k of keys) {
if (httpServer[k] instanceof http.Server) {
//got it !
app = httpServer[k];
break;
}
}
}
this.appServer = httpServer;
//this._checkHarmonyProxies();
httpServer.eurecaServer = this;
this.ioServer = this.transport.createServer(httpServer, this.settings);
this._handleServer(this.ioServer);
//install on express
//sockjs_server.installHandlers(server, {prefix:_prefix});
if (app.get && app.post) //TODO : better way to detect express
{
app.get(this.settings.clientScript, (request, response) => this.sendScript(request, response, this.settings.prefix));
}
else //Fallback to nodejs
{
app.on('request', (request, response) => {
if (request.method === 'GET') {
if (request.url.split('?')[0] === this.settings.clientScript) {
this.sendScript(request, response, this.settings.prefix);
}
}
});
}
}
public attach(appServer: any) {
console.warn('DEPRECATED: Eureca.Server.attach() is deprecated, please use Eureca.Server.bind() instead');
return this.bind(appServer);
}
//#region ==[ Deprecated Events bindings ]===================
public onConnect(callback: (any) => void) {
this.on('connect', callback);
}
public onDisconnect(callback: (any) => void) {
this.on('disconnect', callback);
}
public onMessage(callback: (any) => void) {
this.on('message', callback);
}
public onError(callback: (any) => void) {
this.on('error', callback);
}
//#endregion
} | the_stack |
import { Spreadsheet, SpreadsheetModel, CellSaveEventArgs, RowModel, SheetModel, getCell } from '../../../src/index';
import { SpreadsheetHelper } from '../util/spreadsheethelper.spec';
import { defaultData } from '../util/datasource.spec';
import { createElement } from '@syncfusion/ej2-base';
/**
* Clipboard test cases
*/
describe('Clipboard ->', () => {
let helper: SpreadsheetHelper = new SpreadsheetHelper('spreadsheet');
let model: SpreadsheetModel;
describe('UI Interaction ->', () => {
describe('', () => {
beforeAll((done: Function) => {
model = {
sheets: [{ ranges: [{ dataSource: defaultData }] }]
};
helper.initializeSpreadsheet(model, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Copy pasting cells with increased font size does not increase row height', (done: Function) => {
helper.invoke('cellFormat', [{ fontSize: '20pt' }, 'A2:B4']);
helper.invoke('copy', ['A2:B4']).then(() => {
helper.invoke('paste', ['D5']);
expect(helper.invoke('getRow', [4]).style.height).toBe('35px');
expect(helper.invoke('getRow', [5]).style.height).toBe('35px');
expect(helper.invoke('getRow', [6]).style.height).toBe('35px');
const sheet: SheetModel = helper.invoke('getActiveSheet');
expect(sheet.rows[4].height).toBe(35);
expect(sheet.rows[5].height).toBe(35);
expect(sheet.rows[6].height).toBe(35);
expect(getCell(4, 3, sheet).style.fontSize).toBe('20pt');
expect(getCell(5, 4, sheet).style.fontSize).toBe('20pt');
expect(getCell(6, 3, sheet).style.fontSize).toBe('20pt');
done();
});
});
});
});
describe('CR-Issues ->', () => {
describe('F163240, FB23869, EJ2-59226 ->', () => {
beforeAll((done: Function) => {
model = {
sheets: [{ ranges: [{ dataSource: defaultData }] }],
created: (): void => {
helper.getInstance().cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'A1:H1');
}
};
helper.initializeSpreadsheet(model, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Paste behaviour erroneous after cut', (done: Function) => {
helper.invoke('selectRange', ['A1:D5']);
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[0].cells[0].value).toEqual('Item Name');
expect(spreadsheet.sheets[0].rows[4].cells[3].value.toString()).toEqual('15');
expect(spreadsheet.sheets[0].rows[3].cells[0].value).toEqual('Formal Shoes');
expect(spreadsheet.sheets[0].rows[2].cells[2].value).toEqual('0.2475925925925926');
setTimeout((): void => {
helper.invoke('cut').then((): void => {
helper.invoke('selectRange', ['A2']);
setTimeout((): void => {
helper.invoke('paste', ['Sheet1!A2:A2']);
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[0].cells[0]).toBeNull();
expect(helper.invoke('getCell', [0, 0]).textContent).toEqual('');
expect(spreadsheet.sheets[0].rows[4].cells[3].value.toString()).toEqual('20');
expect(helper.invoke('getCell', [4, 3]).textContent).toEqual('20');
expect(spreadsheet.sheets[0].rows[3].cells[0].value).toEqual('Sports Shoes');
expect(helper.invoke('getCell', [3, 0]).textContent).toEqual('Sports Shoes');
expect(spreadsheet.sheets[0].rows[2].cells[2].value.toString()).toEqual('0.4823148148148148');
done();
});
});
});
});
});
it('Paste values only for formula is not working', (done: Function) => {
helper.edit('I1', '=SUM(F2:F8)');
helper.invoke('copy', ['I1']).then(() => {
helper.invoke('paste', ['I2', 'Values']);
setTimeout(() => {
expect(helper.invoke('getCell', [1, 8]).textContent).toBe('2700');
expect(helper.getInstance().sheets[0].rows[1].cells[8].formula).toBeUndefined();
done();
});
});
});
it('When we copy the values with empty cell, it pasted to additional range with new values', (done: Function) => {
helper.edit('H3', '=SUM(F3:G3)');
helper.invoke('copy', ['H3:I3']).then(() => {
helper.invoke('paste', ['I3']);
expect(helper.getInstance().sheets[0].rows[2].cells[9].value).toEqual('');
expect(helper.invoke('getCell', [2, 9]).textContent).toBe('');
});
helper.invoke('copy', ['G3:G3']).then(() => {
helper.invoke('paste', ['H3']);
expect(helper.getInstance().sheets[0].rows[2].cells[7].value).not.toEqual('');
expect(helper.invoke('getCell', [2, 7]).textContent).not.toBe('');
done();
});
});
});
describe('F162960 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{
rows: [{ cells: [{ value: '100' }, { value: '25' }, { value: '1001' }] }, {
cells: [{ value: '100' },
{ value: '25' }, { value: '1001' }]
}], selectedRange: 'A1:B2'
}],
created: (): void => helper.getInstance().setRowHeight(45)
}, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Row height not persistent after cut/paste', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[0].height).toEqual(45);
expect(spreadsheet.sheets[0].rows[3]).toBeUndefined();
helper.invoke('cut').then((): void => {
helper.invoke('selectRange', ['A4']);
setTimeout((): void => {
helper.invoke('paste', ['Sheet1!A4:A4']);
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[0].height).toEqual(45);
expect(helper.invoke('getRow', [0, 0]).style.height).toEqual('45px');
expect(spreadsheet.sheets[0].rows[3].cells[0].value.toString()).toEqual('100');
done();
});
});
});
});
});
describe('I299870, I298549, I296802 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{ rows: [{ cells: [{ value: 'Value' }] }], selectedRange: 'A1' }],
cellSave: (): void => {
(helper.getInstance() as Spreadsheet).insertRow([{ index: 1, cells: [{ value: 'Added' }] }]);
}
}, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Trigger the cellSave event for paste action and while insertRow inn actionComplete script error throws', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
helper.invoke('copy').then((): void => {
helper.invoke('selectRange', ['A4']);
setTimeout((): void => {
helper.invoke('paste');
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[4].cells[0].value).toEqual('Value');
expect(spreadsheet.sheets[0].rows[1].cells[0].value).toEqual('Added');
done();
});
});
});
});
});
describe('I301708 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{ selectedRange: 'C2' }],
created: (): void => {
(helper.getInstance() as Spreadsheet).setBorder({ border: '1px solid #000' }, 'C2');
}
}, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Border copy paste issue (copy the border and paste it in adjacent cells, border removed)', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
let dataSourceChangedFunction: () => void = jasmine.createSpy('dataSourceChanged');
spreadsheet.dataSourceChanged = dataSourceChangedFunction;
spreadsheet.dataBind();
expect(helper.invoke('getCell', [1, 1]).style.borderRight).toEqual('1px solid rgb(0, 0, 0)');
expect(helper.invoke('getCell', [0, 2]).style.borderBottom).toEqual('1px solid rgb(0, 0, 0)');
expect(helper.invoke('getCell', [1, 2]).style.borderRight).toEqual('1px solid rgb(0, 0, 0)');
expect(helper.invoke('getCell', [1, 2]).style.borderBottom).toEqual('1px solid rgb(0, 0, 0)');
helper.invoke('copy').then((): void => {
helper.invoke('selectRange', ['B2']);
setTimeout((): void => {
helper.invoke('paste');
setTimeout((): void => {
//expect(dataSourceChangedFunction).toHaveBeenCalled();
expect(spreadsheet.sheets[0].rows[1].cells[1].style.border).toBeUndefined();
expect(spreadsheet.sheets[0].rows[1].cells[1].style.borderLeft).toEqual('1px solid #000');
expect(spreadsheet.sheets[0].rows[1].cells[1].style.borderTop).toEqual('1px solid #000');
expect(spreadsheet.sheets[0].rows[1].cells[1].style.borderRight).toEqual('1px solid #000');
expect(spreadsheet.sheets[0].rows[1].cells[1].style.borderBottom).toEqual('1px solid #000');
expect(helper.invoke('getCell', [1, 0]).style.borderRight).toEqual('1px solid rgb(0, 0, 0)');
expect(helper.invoke('getCell', [0, 1]).style.borderBottom).toEqual('1px solid rgb(0, 0, 0)');
expect(helper.invoke('getCell', [1, 1]).style.borderRight).toEqual('1px solid rgb(0, 0, 0)');
expect(helper.invoke('getCell', [1, 1]).style.borderBottom).toEqual('1px solid rgb(0, 0, 0)');
expect(helper.invoke('getCell', [1, 2]).style.borderRight).toEqual('1px solid rgb(0, 0, 0)');
expect(helper.invoke('getCell', [1, 2]).style.borderBottom).toEqual('1px solid rgb(0, 0, 0)');
done();
});
});
});
});
});
describe('I329167, I328868 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{
rows: [{ cells: [{ index: 5, value: '10' }, { value: '11' }, { value: '8' }] }, {
cells: [{
index: 5,
formula: '=IF(F1>10,"Pass","Fail")'
}, { index: 7, value: '10' }]
}, { cells: [{ index: 7, formula: '=SUM(H1:H2)' }] }],
selectedRange: 'F2'
}]
}, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Copy Paste functions with Formula applied cells issue', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
helper.invoke('copy').then((): void => {
helper.invoke('selectRange', ['G2']);
setTimeout((): void => {
helper.invoke('paste');
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[1].cells[5].formula).toEqual('=IF(F1>10,"Pass","Fail")');
expect(spreadsheet.sheets[0].rows[1].cells[6].value).toEqual('Pass');
expect(spreadsheet.sheets[0].rows[1].cells[6].formula).toEqual('=IF(G1>10,"Pass","Fail")');
helper.invoke('selectRange', ['H3']);
done();
});
});
});
});
it('Copy a formula from one cell to another (onto multiple cells), it shows the correct result only for the final row', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
helper.invoke('copy').then((): void => {
helper.invoke('selectRange', ['I3:I5']);
setTimeout((): void => {
helper.invoke('paste');
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[2].cells[8].formula).toEqual('=SUM(I1:I2)');
expect(spreadsheet.sheets[0].rows[3].cells[8].formula).toEqual('=SUM(I2:I3)');
expect(spreadsheet.sheets[0].rows[4].cells[8].formula).toEqual('=SUM(I3:I4)');
done();
});
});
});
});
});
describe('SF-358133 ->', () => {
let count: number = 0;
beforeEach((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{ selectedRange: 'C2', ranges: [{ startCell: 'C1', dataSource: [{ 'start': '2/14/2014', 'end': '6/11/2014' }] }] }],
cellSave: (args: CellSaveEventArgs): void => {
count++;
if (count === 1) { // Pasted cell details
expect(args.address).toEqual('Sheet1!D2');
expect(args.value as any).toEqual(41684);
expect(args.oldValue).toEqual('6/11/2014');
expect(args.displayText).toEqual('2/14/2014');
}
if (count === 2) { // Cut cell details
expect(args.address).toEqual('Sheet1!C2');
expect(args.value).toEqual('');
expect(args.oldValue).toEqual('2/14/2014');
expect(args.displayText).toEqual('');
}
}
}, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Cut / paste cell save event arguments are not proper', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[1].cells[2].value).toEqual('41684');
expect(helper.invoke('getDisplayText', [spreadsheet.sheets[0].rows[1].cells[2]])).toEqual('2/14/2014');
expect(spreadsheet.sheets[0].rows[1].cells[3].value).toEqual('41801');
expect(helper.invoke('getDisplayText', [spreadsheet.sheets[0].rows[1].cells[3]])).toEqual('6/11/2014');
helper.invoke('cut').then((): void => {
helper.invoke('selectRange', ['D2']);
setTimeout((): void => {
helper.invoke('paste');
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[1].cells[2]).toBeNull();
expect(spreadsheet.sheets[0].rows[1].cells[3].value as any).toEqual(41684);
expect(helper.invoke('getDisplayText', [spreadsheet.sheets[0].rows[1].cells[3]])).toEqual('2/14/2014');
done();
});
});
});
});
});
// describe('SF-355018 ->', () => {
// beforeAll((done: Function) => {
// dataSource();
// model = {
// sheets: [{ ranges: [{ dataSource: virtualData.slice(0, 10000) }] }]
// };
// helper.initializeSpreadsheet(model, done);
// });
// afterAll(() => {
// helper.invoke('destroy');
// });
// it('Performance issue on pasting 10k cells', (done: Function) => {
// helper.invoke('selectRange', ['A1:A10001']);
// helper.invoke('copy').then(() => {
// helper.invoke('selectRange', ['B1']);
// let time: number = Date.now();
// helper.invoke('paste');
// setTimeout(() => {
// expect(helper.invoke('getCell', [0, 1]).textContent).toBe('Name');
// expect(Date.now() - time).toBeLessThan(4000);
// time = Date.now();
// helper.invoke('getCell', [1000000, 0]);
// expect(Date.now() - time).toBeLessThan(10);
// done();
// });
// });
// });
// });
describe('EJ2-56500 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{ ranges: [{ dataSource: defaultData }] }]
}, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Copy indicator size and position does not change after row height and column width changes', (done: Function) => {
helper.invoke('copy', ['C4:E7']).then(() => {
setTimeout((): void => {
helper.invoke('setRowHeight', [50, 0]);
const elem: HTMLElement = helper.getElementFromSpreadsheet('.e-copy-indicator');
expect(elem.style.top).toBe('89px');
helper.invoke('setRowHeight', [50, 4]);
expect(elem.style.height).toBe('111px');
helper.invoke('setColWidth', [100, 0]);
expect(elem.style.left).toBe('163px');
helper.invoke('setColWidth', [100, 3]);
expect(elem.style.width).toBe('229px');
done();
});
});
});
it('Copy paste the wrap cell changes height of the copy indicator', (done: Function) => {
helper.invoke('wrap', ['A6']);
helper.invoke('copy', ['A6']).then(() => {
helper.invoke('selectRange', ['A11']);
helper.invoke('paste');
setTimeout(() => {
const elem: HTMLElement = helper.getElementFromSpreadsheet('.e-copy-indicator');
expect(elem.style.top).toBe('159px');
expect(elem.style.height).toBe('39px');
expect(helper.invoke('getCell', [10, 0]).textContent).toBe('Flip- Flops & Slippers');
done();
});
});
});
});
describe('EJ2-56522 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({}, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('While copy paste the merge cell with all borders, the left border is missing in pasted cell', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
spreadsheet.setBorder({ borderLeft: '1px solid #e0e0e0' }, 'A1:B2');
spreadsheet.setBorder({ borderRight: '1px solid #e0e0e0' }, 'A1:B2');
spreadsheet.setBorder({ borderTop: '1px solid #e0e0e0' }, 'A1:B2');
spreadsheet.setBorder({ borderBottom: '1px solid #e0e0e0' }, 'A1:B2');
helper.invoke('selectRange', ['A1:B2']);
helper.invoke('copy').then((): void => {
setTimeout((): void => {
helper.invoke('paste', ['A4:A4', "Formats"]);
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[3].cells[0].style.borderLeft).toBe('1px solid #e0e0e0');
expect(spreadsheet.sheets[0].rows[4].cells[0].style.borderLeft).toBe('1px solid #e0e0e0');
done();
});
});
});
});
});
describe('EJ2-56649 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{
conditionalFormats: [
{ type: "ContainsText", cFColor: "RedFT", value: 'shoes', range: 'A2:A11' },
{ type: "DateOccur", cFColor: "YellowFT", value: '7/22/2014', range: 'B2:B11' },
{ type: "GreaterThan", cFColor: "GreenFT", value: '11:26:32 AM', range: 'C2:C11' },
{ type: "LessThan", cFColor: "RedF", value: '20', range: 'D2:D11' },
],
ranges: [{ dataSource: defaultData }]
}]
}, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Copy and paste didnt work properly with conditional formatting after save and load the spreadsheet as JSON', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
let td: HTMLElement = helper.invoke('getCell', [1, 0]);
expect(td.style.backgroundColor).toBe('rgb(255, 199, 206)');
expect(td.style.color).toBe('rgb(156, 0, 85)');
td = helper.invoke('getCell', [4, 0]);
expect(td.style.backgroundColor).toBe('');
expect(td.style.color).toBe('');
helper.invoke('copy', ['A2:A11']).then(() => {
helper.invoke('selectRange', ['H2']);
helper.invoke('paste');
setTimeout(() => {
let td: HTMLElement = helper.invoke('getCell', [1, 7]);
expect(td.style.backgroundColor).toBe('rgb(255, 199, 206)');
expect(td.style.color).toBe('rgb(156, 0, 85)');
done();
});
});
});
});
describe('SF-367525, SF-367519 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({}, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('External copy and paste cell model with style creation - copied from PowerPoint', (done: Function) => {
const tableStr: string = '<style>col{mso-width-source:auto;}td{color:windowtext;vertical-align:bottom;border:none;}' +
'.oa1{border:1.0pt solid black;vertical-align:top;}</style>' +
'<table><tbody>' +
'<tr height="42" style="height:20.93pt">' +
'<td class="oa1"><p style="text-align:left;"><s style="text-line-through:single">' +
'<span style="font-size:18.0pt;font-family:Calibri;color:#2E75B6;font-weight:bold;font-style:italic;">115</span>' +
'</s></p></td>' +
'<td class="oa1"><p style="text-align:left;"><s style="text-line-through:single">' +
'<span style="font-size:18.0pt;font-family:Calibri;color:#2E75B6;font-weight:bold;font-style:italic;">313</span>' +
'</s></p></td>' +
'</tr>' +
'<tr>' +
'<td class="oa1"><p style="text-align:left;"><s style="text-line-through:single"><u style="text-underline:single">' +
'<span style="font-size:18.0pt;font-family:Calibri;color:#2E75B6;font-style:italic;"">225</span></u></s></p>' +
'</td>' +
'<td class="oa1"><p style="text-align:left;"><s style="text-line-through:single"><u style="text-underline:single">' +
'<span style="font-size:18.0pt;font-family:Calibri;color:#2E75B6;font-style:italic;">406</span></u></s></p>' +
'</td>' +
'</tr>' +
'</tbody></table>';
const tableCont: Element = createElement('span', { innerHTML: tableStr });
const spreadsheet: any = helper.getInstance();
let rows: RowModel[] = [];
spreadsheet.clipboardModule.generateCells(tableCont, rows);
expect(rows.length).toBe(2);
expect(rows[0].cells.length).toBe(2);
expect(rows[0].cells[0].value as any).toBe(115);
let style: string = '{"verticalAlign":"top","textAlign":"left","fontSize":"18pt","fontFamily":"Calibri","color":"#2E75B6",'
+ '"fontWeight":"bold","fontStyle":"italic","textDecoration":"line-through","borderBottom":"1.33px solid black",' +
'"borderTop":"1.33px solid black","borderLeft":"1.33px solid black","borderRight":"1.33px solid black"}';
expect(JSON.stringify(rows[0].cells[0].style)).toBe(style);
expect(rows[0].cells[1].value as any).toBe(313);
expect(JSON.stringify(rows[0].cells[1].style)).toBe(style);
expect(rows[1].cells.length).toBe(2);
expect(rows[1].cells[0].value as any).toBe(225);
style = '{"verticalAlign":"top","textAlign":"left","textDecoration":"underline line-through","fontSize":"18pt",' +
'"fontFamily":"Calibri","color":"#2E75B6","fontStyle":"italic","borderBottom":"1.33px solid black",' +
'"borderTop":"1.33px solid black","borderLeft":"1.33px solid black","borderRight":"1.33px solid black"}';
expect(JSON.stringify(rows[1].cells[0].style)).toBe(style);
expect(rows[1].cells[1].value as any).toBe(406);
expect(JSON.stringify(rows[1].cells[1].style)).toBe(style);
done();
});
});
describe('EJ2-58124 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{
ranges: [{
dataSource: defaultData
}]
}]
}, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('copy the unique formula and paste same sheet', (done: Function) => {
helper.getInstance().selectRange('I1:I1')
helper.invoke('startEdit');
helper.getElement('.e-spreadsheet-edit').textContent = '=UNIQUE(D2:D6)';
helper.triggerKeyNativeEvent(13);
setTimeout(() => {
expect(helper.getInstance().sheets[0].rows[0].cells[8].formula).toBe('=UNIQUE(D2:D6)');
expect(helper.getInstance().sheets[0].rows[0].cells[8].value).toBe('10');
done();
});
});
it('copying unique formula to another range', (done: Function) => {
helper.invoke('copy', ['I1:I4']).then(() => {
helper.invoke('selectRange', ['J2']);
helper.invoke('paste');
setTimeout(() => {
expect(helper.getInstance().sheets[0].rows[1].cells[9].value).toBe('30');
done();
});
});
});
it('copying unique formula to another value containing range', (done: Function) => {
helper.invoke('selectRange', ['I2:I4']);
helper.invoke('copy', ['I1:I4']).then(() => {
helper.invoke('selectRange', ['F2']);
helper.invoke('paste');
setTimeout(() => {
expect(helper.getInstance().sheets[0].rows[1].cells[5].value).toBe('#SPILL!');
done();
});
});
});
it('copy the unique formula and paste without spill', (done: Function) => {
helper.getInstance().selectRange('I7:I7');
helper.invoke('startEdit');
helper.getElement('.e-spreadsheet-edit').textContent = '=UNIQUE(D4:D7)';
helper.triggerKeyNativeEvent(13);
setTimeout(() => {
expect(helper.getInstance().sheets[0].rows[6].cells[8].formula).toBe('=UNIQUE(D4:D7)');
expect(helper.getInstance().sheets[0].rows[0].cells[8].value).toBe('10');
helper.invoke('selectRange', ['I7:I10']);
helper.invoke('copy', ['I7:I10']).then(() => {
helper.invoke('selectRange', ['E7']);
helper.invoke('paste');
setTimeout(() => {
expect(helper.getInstance().sheets[0].rows[6].cells[5].value).toBe('Formal Shoes');
done();
});
});
done();
});
});
});
});
}); | the_stack |
import {} from "ts-expose-internals";
import * as path from "path";
import {
createTsProgram,
EmittedFiles,
getEmitResultFromProgram,
getManualEmitResult,
getTsNodeEmitResult,
} from "../../utils";
import { projectsPaths, ts, tsModules } from "../../config";
import { TsTransformPathsConfig } from "../../../src";
import TS from "typescript";
/* ****************************************************************************************************************** *
* Config
* ****************************************************************************************************************** */
const baseConfig: TsTransformPathsConfig = { exclude: ["**/excluded/**", "excluded-file.*"] };
/* Test Mapping */
const modes = ["program", "manual", "ts-node"] as const;
const testConfigs: { label: string; tsInstance: any; mode: typeof modes[number]; tsSpecifier: string }[] = [];
for (const cfg of tsModules)
testConfigs.push(...modes.map((mode) => ({ label: cfg[0], tsInstance: cfg[1], mode, tsSpecifier: cfg[2] })));
/* File Paths */
const projectRoot = ts.normalizePath(path.join(projectsPaths, "specific"));
const tsConfigFile = ts.normalizePath(path.join(projectsPaths, "specific/tsconfig.json"));
const genFile = ts.normalizePath(path.join(projectRoot, "generated/dir/gen-file.ts"));
const srcFile = ts.normalizePath(path.join(projectRoot, "src/dir/src-file.ts"));
const indexFile = ts.normalizePath(path.join(projectRoot, "src/index.ts"));
const tagFile = ts.normalizePath(path.join(projectRoot, "src/tags.ts"));
const typeElisionIndex = ts.normalizePath(path.join(projectRoot, "src/type-elision/index.ts"));
const subPackagesFile = ts.normalizePath(path.join(projectRoot, "src/sub-packages.ts"));
const moduleAugmentFile = ts.normalizePath(path.join(projectRoot, "src/module-augment.ts"));
/* ****************************************************************************************************************** *
* Types
* ****************************************************************************************************************** */
declare global {
namespace jest {
interface Matchers<R> {
transformedMatches(expected: RegExp | string, opt?: { base?: EmittedFiles[]; kind?: ("dts" | "js")[] }): void;
}
}
}
/* ****************************************************************************************************************** *
* Tests
* ****************************************************************************************************************** */
describe(`Specific Tests`, () => {
describe.each(testConfigs)(`TypeScript $label - Mode: $mode`, ({ tsInstance, mode, tsSpecifier }) => {
const tsVersion = +tsInstance.versionMajorMinor.split(".").slice(0, 2).join("");
let normalEmit: EmittedFiles;
let rootDirsEmit: EmittedFiles;
let skipDts = false;
beforeAll(() => {
switch (mode) {
case "program":
const program = createTsProgram({
tsInstance,
tsConfigFile,
pluginOptions: {
...baseConfig,
useRootDirs: false,
},
});
normalEmit = getEmitResultFromProgram(program);
const rootDirsProgram = createTsProgram({
tsInstance,
tsConfigFile,
pluginOptions: {
...baseConfig,
useRootDirs: true,
},
});
rootDirsEmit = getEmitResultFromProgram(rootDirsProgram);
break;
case "manual": {
skipDts = true;
const pcl = tsInstance.getParsedCommandLineOfConfigFile(
tsConfigFile,
{},
<any>tsInstance.sys
)! as TS.ParsedCommandLine;
normalEmit = getManualEmitResult({ ...baseConfig, useRootDirs: false }, tsInstance, pcl);
rootDirsEmit = getManualEmitResult({ ...baseConfig, useRootDirs: true }, tsInstance, pcl);
break;
}
case "ts-node": {
const pcl = tsInstance.getParsedCommandLineOfConfigFile(
tsConfigFile,
{},
<any>tsInstance.sys
)! as TS.ParsedCommandLine;
skipDts = true;
normalEmit = getTsNodeEmitResult({ ...baseConfig, useRootDirs: false }, pcl, tsSpecifier);
rootDirsEmit = getTsNodeEmitResult({ ...baseConfig, useRootDirs: true }, pcl, tsSpecifier);
}
}
expect.extend({
transformedMatches(
fileName: string,
expected: RegExp | string,
opt?: { base?: EmittedFiles[]; kind?: ("dts" | "js")[] }
) {
const bases = opt?.base ?? [normalEmit, rootDirsEmit];
const kinds = (opt?.kind ?? ["dts", "js"]).filter((k) => !skipDts || k !== "dts");
let failed: boolean = false;
const messages: string[] = [];
for (const base of bases) {
for (const kind of kinds) {
const content = base[fileName][kind];
const isValid = typeof expected === "string" ? content.indexOf(expected) >= 0 : expected.test(content);
if (!isValid) {
failed = true;
messages.push(
`File: ${fileName}\nKind: ${kind}\nrootDirs: ${base === normalEmit}\n\n` +
`Expected: \`${expected}\`\nReceived:\n\t${content.replace(/(\r?\n)+/g, "$1\t")}`
);
}
}
}
return { message: () => messages.join("\n\n"), pass: !failed };
},
});
});
describe(`Options`, () => {
test(`(useRootDirs: true) Re-maps for rootDirs`, () => {
expect(genFile).transformedMatches(`import "./src-file"`, { base: [rootDirsEmit] });
expect(srcFile).transformedMatches(`import "./gen-file"`, { base: [rootDirsEmit] });
expect(indexFile).transformedMatches(`export { b } from "./dir/gen-file"`, { base: [rootDirsEmit] });
expect(indexFile).transformedMatches(`export { a } from "./dir/src-file"`, { base: [rootDirsEmit] });
});
test(`(useRootDirs: false) Ignores rootDirs`, () => {
expect(genFile).transformedMatches(`import "../../src/dir/src-file"`, { base: [normalEmit] });
expect(srcFile).transformedMatches(`import "../../generated/dir/gen-file"`, { base: [normalEmit] });
expect(indexFile).transformedMatches(`export { b } from "../generated/dir/gen-file"`, { base: [normalEmit] });
expect(indexFile).transformedMatches(`export { a } from "./dir/src-file"`, { base: [normalEmit] });
});
test(`(exclude) Doesn't transform for exclusion patterns`, () => {
expect(indexFile).transformedMatches(
/export { bb } from "#exclusion\/ex";\s*export { dd } from "#root\/excluded-file"/
);
});
});
describe(`Tags`, () => {
test(`(@no-transform-path) Doesn't transform path`, () => {
for (let i = 1; i <= 4; i++)
expect(tagFile).transformedMatches(`import * as skipTransform${i} from "#root\/index`);
});
test(`(@transform-path) Transforms path with explicit value`, () => {
expect(tagFile).transformedMatches(`import * as explicitTransform1 from "./dir/src-file"`);
expect(tagFile).transformedMatches(`import * as explicitTransform2 from "http://www.go.com/react.js"`);
expect(tagFile).transformedMatches(`import * as explicitTransform3 from "./dir/src-file"`);
expect(tagFile).transformedMatches(`import * as explicitTransform4 from "http://www.go.com/react.js"`);
});
});
(mode === "program" ? test : test.skip)(`Type elision works properly`, () => {
expect(typeElisionIndex).transformedMatches(/import { ConstB } from "\.\/a";\s*export { ConstB };/, {
kind: ["js"],
});
expect(typeElisionIndex).transformedMatches(
/import { ConstB, TypeA } from "\.\/a";\s*import { TypeA as TypeA2 } from "\.\/a";\s*export { ConstB, TypeA };\s*export { TypeA2 };/,
{ kind: ["dts"] }
);
});
(!skipDts && tsVersion >= 38 ? test : test.skip)(`Import type-only transforms`, () => {
expect(indexFile).transformedMatches(`import type { A as ATypeOnly } from "./dir/src-file"`, { kind: ["dts"] });
});
test(`Copies comments in async import`, () => {
expect(indexFile).transformedMatches(`import(/* webpackChunkName: "Comment" */ "./dir/src-file");`, {
kind: ["js"],
});
expect(indexFile).transformedMatches(
/\/\/ comment 1\r?\n\s*\r?\n\/\*\r?\n\s*comment 2\r?\n\s*\*\/\r?\n\s*"\.\/dir\/src-file"/,
{ kind: ["js"] }
);
});
test(`Preserves explicit extensions`, () => {
expect(indexFile).transformedMatches(`export { JsonValue } from "./data.json"`);
expect(indexFile).transformedMatches(`export { GeneralConstA } from "./general"`);
expect(indexFile).transformedMatches(`export { GeneralConstB } from "./general.js"`);
});
test(`Does not output implicit index filenames`, () => {
expect(indexFile).transformedMatches(`export { ConstB } from "./type-elision"`);
});
test(`Resolves sub-modules properly`, () => {
const a = {
js: `export { packageAConst } from "./packages/pkg-a"`,
full: `export { packageAConst, PackageAType } from "./packages/pkg-a"`,
};
const b = {
js: `export { packageBConst } from "./packages/pkg-b"`,
full: `export { packageBConst, PackageBType } from "./packages/pkg-b"`,
};
const c = {
js: `export { packageCConst } from "./packages/pkg-c"`,
full: `export { packageCConst, PackageCType } from "./packages/pkg-c"`,
};
const sub = {
js: `export { subPackageConst } from "./packages/pkg-a/sub-pkg"`,
full: `export { SubPackageType, subPackageConst } from "./packages/pkg-a/sub-pkg"`,
};
for (const exp of [a, b, c, sub]) {
expect(subPackagesFile).transformedMatches(mode !== "program" ? exp.full : exp.js, { kind: ["js"] });
if (!skipDts) expect(subPackagesFile).transformedMatches(exp.full, { kind: ["dts"] });
}
expect(subPackagesFile).transformedMatches(`export { packageCConst as C2 } from "./packages/pkg-c/main"`);
expect(subPackagesFile).transformedMatches(`export { packageCConst as C3 } from "./packages/pkg-c/main.js"`);
expect(subPackagesFile).transformedMatches(
`export { subPackageConst as C4 } from "./packages/pkg-a/sub-pkg/main"`
);
expect(subPackagesFile).transformedMatches(
`export { subPackageConst as C5 } from "./packages/pkg-a/sub-pkg/main.js"`
);
});
(!skipDts ? test : test.skip)(`Resolves module augmentation`, () => {
expect(moduleAugmentFile).transformedMatches(`declare module "./general" {`, { kind: ["dts"] });
expect(moduleAugmentFile).transformedMatches(`declare module "./excluded-file" {`, { kind: ["dts"] });
});
});
}); | the_stack |
import { expect } from "chai";
import { BeDuration } from "@itwin/core-bentley";
import { ColorDef, Environment, EnvironmentProps, ImageSource, ImageSourceFormat, RenderTexture, SkyBox, SkyBoxImageType } from "@itwin/core-common";
import { EnvironmentDecorations } from "../../EnvironmentDecorations";
import { imageElementFromImageSource } from "../../ImageUtil";
import { SpatialViewState } from "../../SpatialViewState";
import { IModelConnection } from "../../IModelConnection";
import { IModelApp } from "../../IModelApp";
import { createBlankConnection } from "../createBlankConnection";
describe("EnvironmentDecorations", () => {
let iModel: IModelConnection;
function createView(env?: EnvironmentProps): SpatialViewState {
const view = SpatialViewState.createBlank(iModel, {x: 0, y: 0, z: 0}, {x: 1, y: 1, z: 1});
if (env)
view.displayStyle.environment = Environment.fromJSON(env);
return view;
}
class Decorations extends EnvironmentDecorations {
public get sky() { return this._sky; }
public get ground() { return this._ground; }
public get environment() { return this._environment; }
public constructor(view?: SpatialViewState, onLoad?: () => void, onDispose?: () => void) {
super(view ?? createView(), onLoad ?? (() => undefined), onDispose ?? (() => undefined));
}
public static async create(view?: SpatialViewState, onLoad?: () => void, onDispose?: () => void): Promise<Decorations> {
const dec = new Decorations(view, onLoad, onDispose);
await dec.load();
return dec;
}
public async load(): Promise<void> {
if (!this.sky.promise)
return;
await this.sky.promise;
return BeDuration.wait(1);
}
}
before(async () => {
await IModelApp.startup();
const pngData = new Uint8Array([
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 3, 0, 0, 0, 3, 8, 2, 0, 0, 0, 217, 74, 34, 232, 0, 0, 0, 1, 115, 82, 71, 66, 0, 174, 206,
28, 233, 0, 0, 0, 4, 103, 65, 77, 65, 0, 0, 177, 143, 11, 252, 97, 5, 0, 0, 0, 9, 112, 72, 89, 115, 0, 0, 14, 195, 0, 0, 14, 195, 1, 199, 111, 168, 100, 0, 0, 0,
24, 73, 68, 65, 84, 24, 87, 99, 248, 15, 4, 12, 12, 64, 4, 198, 64, 46, 132, 5, 162, 254, 51, 0, 0, 195, 90, 10, 246, 127, 175, 154, 145, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
]);
const textureImage = {
image: await imageElementFromImageSource(new ImageSource(pngData, ImageSourceFormat.Png)),
format: ImageSourceFormat.Png,
};
const createTexture = () => { return {} as unknown as RenderTexture; };
IModelApp.renderSystem.createTextureFromCubeImages = createTexture;
IModelApp.renderSystem.createTexture = createTexture;
IModelApp.renderSystem.loadTextureImage = async () => Promise.resolve(textureImage);
iModel = createBlankConnection();
});
after(async () => {
await iModel.close();
await IModelApp.shutdown();
});
it("initializes from environment", async () => {
const dec = await Decorations.create(createView({
ground: {
display: true,
elevation: 20,
aboveColor: ColorDef.blue.toJSON(),
belowColor: ColorDef.red.toJSON(),
},
sky: {
display: true,
nadirColor: ColorDef.blue.toJSON(),
zenithColor: ColorDef.red.toJSON(),
skyColor: ColorDef.white.toJSON(),
groundColor: ColorDef.black.toJSON(),
skyExponent: 42,
groundExponent: 24,
},
}));
expect(dec.ground).not.to.be.undefined;
expect(dec.ground!.aboveParams.lineColor.equals(ColorDef.blue.withTransparency(0xff))).to.be.true;
expect(dec.ground!.belowParams.lineColor.equals(ColorDef.red.withTransparency(0xff))).to.be.true;
let params = dec.sky.params!;
expect(params).not.to.be.undefined;
expect(params.type).to.equal("gradient");
if ("gradient" === params.type) {
const sky = params.gradient;
expect(sky).not.to.be.undefined;
expect(sky.twoColor).to.be.false;
expect(sky.nadirColor.equals(ColorDef.blue)).to.be.true;
expect(sky.zenithColor.equals(ColorDef.red)).to.be.true;
expect(sky.skyColor.equals(ColorDef.white)).to.be.true;
expect(sky.groundColor.equals(ColorDef.black)).to.be.true;
expect(sky.skyExponent).to.equal(42);
expect(sky.groundExponent).to.equal(24);
}
dec.setEnvironment(Environment.fromJSON({
ground: {
display: true,
aboveColor: ColorDef.white.toJSON(),
belowColor: ColorDef.black.toJSON(),
},
sky: {
display: false,
nadirColor: ColorDef.white.toJSON(),
zenithColor: ColorDef.black.toJSON(),
skyColor: ColorDef.red.toJSON(),
groundColor: ColorDef.green.toJSON(),
skyExponent: 123,
groundExponent: 456,
},
}));
await dec.load();
expect(dec.ground!.aboveParams.lineColor.equals(ColorDef.white.withTransparency(0xff))).to.be.true;
expect(dec.ground!.belowParams.lineColor.equals(ColorDef.black.withTransparency(0xff))).to.be.true;
params = dec.sky.params!;
expect(params).not.to.be.undefined;
expect(params.type).to.equal("gradient");
if ("gradient" === params.type) {
const sky = params.gradient;
expect(sky.nadirColor.equals(ColorDef.white)).to.be.true;
expect(sky.zenithColor.equals(ColorDef.black)).to.be.true;
expect(sky.skyColor.equals(ColorDef.red)).to.be.true;
expect(sky.groundColor.equals(ColorDef.green)).to.be.true;
expect(sky.skyExponent).to.equal(123);
expect(sky.groundExponent).to.equal(456);
}
});
it("disposes", async () => {
let disposed = false;
const dec = new Decorations(createView({ ground: { display: true } }), undefined, () => disposed = true);
expect(disposed).to.be.false;
expect(dec.ground).not.to.be.undefined;
expect(dec.sky.promise).not.to.be.undefined;
expect(dec.sky.params).to.be.undefined;
await dec.load();
expect(disposed).to.be.false;
expect(dec.ground).not.to.be.undefined;
expect(dec.sky.promise).to.be.undefined;
expect(dec.sky.params).not.to.be.undefined;
dec.dispose();
expect(disposed).to.be.true;
expect(dec.ground).to.be.undefined;
expect(dec.sky.promise).to.be.undefined;
expect(dec.sky.params).to.be.undefined;
});
it("only allocates ground while displayed", async () => {
const dec = await Decorations.create();
expect(dec.ground).to.be.undefined;
dec.setEnvironment(Environment.fromJSON({ ground: { display: true } }));
expect(dec.ground).not.to.be.undefined;
dec.setEnvironment(Environment.fromJSON());
expect(dec.ground).to.be.undefined;
});
it("only recreates ground if settings change", async () => {
const dec = new Decorations(createView({ ground: { display: true } }));
const prevGround = dec.ground;
expect(prevGround).not.to.be.undefined;
dec.setEnvironment(dec.environment.clone({ displaySky: true }));
expect(dec.ground).to.equal(prevGround);
dec.setEnvironment(dec.environment.clone({ ground: dec.environment.ground.clone({ elevation: 100 }) }));
expect(dec.ground).not.to.equal(prevGround);
expect(dec.ground).not.to.be.undefined;
await dec.load();
});
it("always loads sky", async () => {
const dec = new Decorations(createView({ sky: { display: false } }));
expect(dec.sky.params).to.be.undefined;
expect(dec.sky.promise).not.to.be.undefined;
await dec.load();
expect(dec.sky.params).not.to.be.undefined;
expect(dec.sky.promise).to.be.undefined;
});
it("notifies when asynchronous loading completes", async () => {
let loaded = false;
const dec = new Decorations(undefined, () => loaded = true);
expect(loaded).to.be.false;
await dec.load();
expect(loaded).to.be.true;
loaded = false;
dec.setEnvironment(dec.environment.clone({ sky: SkyBox.fromJSON({ twoColor: true }) }));
expect(loaded).to.be.false;
await dec.load();
expect(loaded).to.be.true;
});
it("preserves previous skybox until new skybox loads", async () => {
const dec = await Decorations.create();
const params = dec.sky.params;
expect(params).not.to.be.undefined;
dec.setEnvironment(dec.environment.clone({ sky: SkyBox.fromJSON({ twoColor: true }) }));
expect(dec.sky.params).to.equal(params);
expect(dec.sky.promise).not.to.be.undefined;
await dec.load();
expect(dec.sky.params).not.to.equal(params);
expect(dec.sky.promise).to.be.undefined;
});
it("produces sky sphere", async () => {
const dec = await Decorations.create(createView({
sky: {
image: {
type: SkyBoxImageType.Spherical,
texture: "0x123",
},
},
}));
expect(dec.sky.params!.type).to.equal("sphere");
});
it("produces sky cube", async () => {
const dec = await Decorations.create(createView({
sky: {
image: {
type: SkyBoxImageType.Cube,
textures: {
front: "0x1", back: "0x2",
left: "0x3", right: "0x4",
top: "0x5", bottom: "0x6",
},
},
},
}));
expect(dec.sky.params!.type).to.equal("cube");
});
it("falls back to sky gradient on error", async () => {
let dec = await Decorations.create(createView({
sky: {
display: true,
image: {
type: SkyBoxImageType.Spherical,
texture: "NotATexture",
},
},
}));
expect(dec.sky.params).not.to.be.undefined;
expect(dec.sky.params!.type).to.equal("gradient");
dec = await Decorations.create(createView({
sky: {
display: true,
image: {
type: SkyBoxImageType.Cube,
textures: {
front: "front",
back: "back",
top: "top",
bottom: "bottom",
left: "left",
right: "right",
},
},
},
}));
expect(dec.sky.params).not.to.be.undefined;
expect(dec.sky.params!.type).to.equal("gradient");
});
}); | the_stack |
import { Language, cordovaApp, state, KaiDiscipline, projectAon, Section, MgnDiscipline, GndDiscipline, BookSeriesId, SectionRenderer, BookSeries, mechanicsEngine } from "..";
/** Book disciplines table */
export interface DisciplinesTable {
/** Discipline id */
[disciplineId: string]: {
/** Discipline id */
id: string,
/** Discipline translated name */
name: string,
/** Discipline translated description */
description: string,
/** Discipline image HTML. Only for series >= Grand Master, empty string otherwise */
imageHtml: string
};
}
/**
* Class to handle the Project Aon books XML
*/
export class Book {
/** Initial books section */
public static readonly INITIAL_SECTION = "tssf";
/** Special unexistent section where to store objects on the Kai monastery */
public static readonly KAIMONASTERY_SECTION = "kaimonastery";
/** Books equipment section */
public static readonly EQUIPMENT_SECTION = "equipmnt";
/** Game rules section */
public static readonly GAMERULZ_SECTION = "gamerulz";
public static readonly COMBATRULESSUMMARY_SECTION = "crsumary";
public static readonly KAILEVELS_SECTION = "levels";
public static readonly HOWTOCARRY_SECTION = "howcarry";
public static readonly HOWTOUSE_SECTION = "howuse";
public static readonly LORECIRCLES_SECTION = "lorecrcl";
public static readonly IMPROVEDDISCIPLINES_SECTION = "imprvdsc";
public static readonly DISCIPLINES_SECTION = "discplnz";
public static readonly MAP_SECTION = "map";
/** Book index number (1 = first book) */
public bookNumber: number;
/** The book language */
public language: Language;
/** The book XML document */
public bookXml: any;
/**
* Array of 100 positions with the random table numbers as they appear on the book
*/
public bookRandomTable: number[];
/** The book title cache, plain text */
private bookTitle: string = null;
/** The book copyright text cache, HTML formatted */
private bookCopyrightHtml: string = null;
/** The book disciplines cache */
private disciplines: DisciplinesTable = null;
/**
* Constructor
* @param number The book index number to create (1 = first)
* @param language The book language ('es' = spanish / 'en' = english )
*/
public constructor(num: number, language: Language) {
this.bookNumber = num;
this.language = language;
this.bookXml = null;
this.bookRandomTable = [];
}
/**
* Get the root URL to download book contents
* @return The base URL
*/
public static getBaseUrl(): string {
if ( cordovaApp.isRunningApp() ) {
// Return the local downloaded books directory
return state.localBooksLibrary.BOOKS_PATH + "/";
} else {
return "data/projectAon/";
}
}
/** Do replacements on original XML to have a valid standalone XML.
* It removes inclusions and replaces
* @param xmlText The original XML
* @return The fixed XML
*/
public static fixXml(xmlText: string): string {
// Code taken from Lone Wolf Adventures, by Liquid State Limited.
// remove general directives
// TODO: Handle all inclusions with a regex?
xmlText = xmlText.replaceAll("%general.links;", "");
xmlText = xmlText.replaceAll("%xhtml.links;", "");
xmlText = xmlText.replaceAll("%general.inclusions;", "");
xmlText = xmlText.replaceAll("%xhtml.characters;", "");
xmlText = xmlText.replaceAll("&inclusion.joe.dever.bio.lw;", "");
xmlText = xmlText.replaceAll("&inclusion.gary.chalk.bio.lw;", "");
xmlText = xmlText.replaceAll("&inclusion.project.aon.license;", "");
xmlText = xmlText.replaceAll("&inclusion.joe.dever.endowment;", "");
xmlText = xmlText.replaceAll("&inclusion.action.chart;", "");
xmlText = xmlText.replaceAll("&inclusion.combat.results.table;", "");
xmlText = xmlText.replaceAll("&inclusion.action.chart.magnakai;", "");
xmlText = xmlText.replaceAll("&inclusion.brian.williams.bio.lw;", "");
// Link to readers handbook (Book 13)
xmlText = xmlText.replaceAll("&link.rh;", "https://www.projectaon.org/en/ReadersHandbook/Home");
/*xmlText = xmlText.replaceAll('&link.project.website;', '')
xmlText = xmlText.replaceAll('&link.staff.contact;', '')
xmlText = xmlText.replaceAll('&link.01hdlo;', '');*/
// Replace links
// 12-21 12:37:11.655: E/browser(1884): Console: Uncaught TypeError: Cannot supply flags when constructing one RegExp from another http://10.0.2.2/ls/statskeeper3/model/book.js:51
// xmlText = xmlText.replace( new RegExp( /\&link\..+?\;/ , 'g' ) , '' );
let exp = /\&link\..+?\;/g;
xmlText = xmlText.replace( exp , "" );
xmlText = xmlText.replaceAll("©", "&copy;" );
xmlText = xmlText.replaceAll("&endash;", "-" );
xmlText = xmlText.replaceAll("&lellips;", "&hellip;" );
// replace non-valid special characters with html special characters
xmlText = xmlText.replaceAll("<ch.ellips/>", "&hellip;");
xmlText = xmlText.replaceAll("<ch.lellips/>", "&hellip;");
xmlText = xmlText.replaceAll("<ch.emdash/>", "&mdash;");
xmlText = xmlText.replaceAll("<ch.endash/>", "&ndash;");
xmlText = xmlText.replaceAll("<ch.apos/>", "&rsquo;");
xmlText = xmlText.replaceAll("<ch.blankline/>", "<br />");
xmlText = xmlText.replaceAll("<ch.minus/>", "-");
xmlText = xmlText.replaceAll("<ch.ampersand/>", "&amp;");
xmlText = xmlText.replaceAll("<ch.thinspace/>", " ");
xmlText = xmlText.replaceAll("<ch.percent/>", "&percnt;");
// replace html special characters
// 12-21 12:42:19.090: E/browser(1884): Console: Uncaught TypeError: Cannot supply flags when constructing one RegExp from another http://10.0.2.2/ls/statskeeper3/model/book.js:68
// xmlText = xmlText.replace( new RegExp( /<ch\.(.+?)\/>/ , 'g' ) , "&$1;");
exp = /<ch\.(.+?)\/>/g;
xmlText = xmlText.replace( exp , "&$1;");
// This code was previously at SectionRenderer.illustration:
// Fix single quote markup
xmlText = xmlText.replaceAll("&rsquot;", "&rsquo;");
xmlText = xmlText.replaceAll("&lsquot;", "&lsquo;");
// Fix double quote markup
xmlText = xmlText.replaceAll("&rdquot;", "&rdquo;");
xmlText = xmlText.replaceAll("&ldquot;", "&ldquo;");
// On book 4, English version, the discipline id "mndblst" has been changed to "mndblast"
// This will break the game mechanics, so keep it as "mndblst":
xmlText = xmlText.replaceAll('"mndblast"', `"${KaiDiscipline.Mindblast}"`);
return xmlText;
}
/**
* Start the download and fix a game book
* @return Promise with the download / fix task
*/
public downloadBookXml(): JQueryPromise<void> {
const self = this;
const bookXmlUrl = this.getBookXmlURL();
// console.log( 'Downloading book XML URL: ' + bookXmlUrl);
return $.ajax({
url: bookXmlUrl,
dataType: "text"
})
.done((xml) => {
self.setXml(xml);
});
}
public setXml(xml: string) {
try {
xml = Book.fixXml(xml);
this.bookXml = $.parseXML(xml);
this.bookRandomTable = this.getRandomTable();
} catch (e) {
mechanicsEngine.debugWarning(e);
throw e;
}
}
/**
* Start promises to download authors info
* Added on v 1.8
* @returns The download promises. The promises text is the author XML bio, fixed
*/
public downloadAuthorsBio(): Array<JQueryPromise<string>> {
try {
const promises: Array<JQueryPromise<string>> = [];
for ( const authorId of projectAon.supportedBooks[this.bookNumber - 1].biographies ) {
promises.push( this.downloadAuthorInfo( authorId ) );
}
return promises;
} catch (ex) {
mechanicsEngine.debugWarning(ex);
return null;
}
}
/**
* Start a promise to download an author info
* @param authorId The author id (ex. "jdbiolw")
* @returns The download promise. The promise text is the author XML bio, fixed
*/
private downloadAuthorInfo( authorId: string ): JQueryPromise<string> {
const authorFileUrl = Book.getBaseUrl() + this.bookNumber + "/" + authorId + "-" + this.language + ".inc";
return $.ajax({
url: authorFileUrl,
dataType: "text"
});
}
/**
* Get the code name given to the book by the Project Aon
* @param language The language for the book. If null, the current book language
* will be used
* @returns The book code name. null if it was not found
*/
public getProjectAonBookCode(language: string = null): string {
if ( !language ) {
language = this.language;
}
const bookMetadata = projectAon.supportedBooks[ this.bookNumber - 1 ];
if ( !bookMetadata ) {
return null;
}
const languageCode = "code_" + language;
const bookCode = bookMetadata[ languageCode ];
if ( !bookCode ) {
return null;
}
return bookCode;
}
/**
* Returns the book XML source URL
*/
public getBookXmlURL() {
return Book.getBaseUrl() + this.bookNumber + "/" + this.getProjectAonBookCode() +
".xml";
}
/**
* Returns an illustration URL
* @param fileName The illustration file name
* @param {Mechanics} mechanics The book mechanics. It can be null. In this case,
* no translated images will be searched
* @returns The image URL, relative to application root
*/
public getIllustrationURL(fileName: string, mechanics: any = null): string {
let illDirectory;
if ( mechanics && mechanics.imageIsTranslated(fileName) ) {
illDirectory = "ill_" + this.language;
} else {
illDirectory = "ill_en";
}
const illUrl = Book.getBaseUrl() + this.bookNumber + "/" + illDirectory + "/" +
fileName;
// console.log('Image URL: ' + illUrl);
return illUrl;
}
/**
* Returns the book HTML directory on the Project Aon web site
* @param language The book language to get. null to get the current book
* language
*/
public getBookProjectAonHtmlDir(language: string): string {
if (!language) {
language = this.language;
}
return "https://projectaon.org/" + language + "/xhtml/" +
( language === "en" ? "lw" : "ls" ) + "/" +
this.getProjectAonBookCode(language) + "/";
}
/**
* Returns the book title
* @returns The book title, plain text
*/
public getBookTitle(): string {
if ( !this.bookTitle ) {
this.bookTitle = $( this.bookXml ).find( "gamebook > meta > title").first().text();
}
return this.bookTitle;
}
/**
* Returns a dictionary with the disciplines info
*/
public getDisciplinesTable(): DisciplinesTable {
if ( !this.disciplines ) {
const bookSeries = this.getBookSeries();
const disciplinesSection = new Section(this, Book.DISCIPLINES_SECTION, state.mechanics);
this.disciplines = {};
const self = this;
// Parse the disciplines section
$(this.bookXml).find('section[id=discplnz] > data > section[id!="mksumary"]')
.each( function(disciplineSection) {
const $node = $(this);
const disciplineId = $node.attr("id");
let description: string;
if ( disciplineId === MgnDiscipline.PsiSurge) {
// Magnakai: Special case, with useful info on second paragraph. Exclude last paragraph
description = $node.find("p:not(:last)").text();
} else if (disciplineId === GndDiscipline.KaiSurge) {
// Grand Master: Other special case (different). Include both (all) paragraphs
description = $node.find("p").text();
} else {
description = $node.find("p").first().text();
}
let imageHtml: string = "";
if (bookSeries.id >= BookSeriesId.GrandMaster) {
const $disciplineIll = $node.find("> data > illustration").first();
imageHtml = SectionRenderer.renderIllustration(disciplinesSection, $disciplineIll);
}
self.disciplines[disciplineId] = {
id: disciplineId,
name: $node.find("> meta > title").text(),
description,
imageHtml
};
});
}
return this.disciplines;
}
/**
* Get the book section with the given id.
* @param sectionId The section id to get
* @return The related section. An empty selection if the section id was not found
*/
public getSectionXml(sectionId: string): JQuery<Element> {
return $(this.bookXml).find("section[id=" + sectionId + "]");
}
/**
* Check if the book contains a section id
* @param sectionId The section id to search
* @return True if the book contains the given section
*/
public hasSection(sectionId: string): boolean {
return this.getSectionXml(sectionId).length > 0;
}
/**
* Get the book copyright HTML
* @returns The book copyright text, HTML formatted
*/
public getCopyrightHtml(): string {
if ( !this.bookCopyrightHtml ) {
const fakeSection = new Section(this, "fakeSection", null);
const renderer = new SectionRenderer(fakeSection);
const selector = 'rights[class="copyrights"]';
this.bookCopyrightHtml = renderer.renderNodeChildren( $(this.bookXml).find(selector) , 0 );
}
return this.bookCopyrightHtml;
}
/**
* Get the Kai title for a given number of disciplines
* @param nDisciplines Number of disciplines
* @return The kai title
*/
public getKaiTitle(nDisciplines: number): string {
// Normalize
if ( nDisciplines < 1 ) {
nDisciplines = 1;
} else if ( nDisciplines > 10 ) {
nDisciplines = 10;
}
// Get the title
let title = $(this.bookXml)
.find('section[id="levels"] > data > ol > li:eq(' + (nDisciplines - 1) + ")")
.text();
if ( !title ) {
title = "Unknown";
}
// For the level 5, there is an extra explanation to remove:
// —You begin the Lone Wolf adventures with this level of Kai training
let idx = title.indexOf( "—");
if ( idx >= 0 ) {
title = title.substr(0, idx).trim();
}
// On book 6 (spanish), there is a parenthesis: Maestro Superior del Kai (con este...
idx = title.indexOf( "(");
if ( idx >= 0 ) {
title = title.substr(0, idx).trim();
}
return title;
}
/**
* Get sections that have a choice to go to some section
* @param sectionId The destination section
* @return Section ids that can go to the given section
*/
public getOriginSections(sectionId: string): string[] {
const sourceSectionIds = [];
const sourceSections = $(this.bookXml)
.find('section[class="numbered"]' )
.has( 'data > choice[idref="' + sectionId + '"]')
.each( (index, section) => {
sourceSectionIds.push( $(section).attr("id") );
}) ;
return sourceSectionIds;
}
/**
* Get the book cover image URL
*/
public getCoverURL(): string {
return Book.getBaseUrl() + this.bookNumber + "/cover.jpg";
}
/**
* Return an array of 2 positions with the combat tables images
*/
public getCombatTablesImagesUrls(mechanics) {
const images = [];
images.push( this.getIllustrationURL( "crtpos.png", mechanics) );
images.push( this.getIllustrationURL( "crtneg.png", mechanics ) );
return images;
}
/**
* Get the book random table number
* @return Array with the 100 numbers of the random table
*/
public getRandomTable(): number[] {
const $randomCells = $(this.bookXml)
.find("section[id=random] > data > illustration > instance[class=text]")
.find("td");
const numbers = [];
for (const cell of $randomCells.toArray()) {
numbers.push( parseInt( $(cell).text(), 10 ) );
}
return numbers;
}
public getBookSeries(): BookSeries {
return BookSeries.getBookNumberSeries(this.bookNumber);
}
public getSectionsIds(): string[] {
const sectionIds: string[] = [];
let sectionId = Book.INITIAL_SECTION;
while (sectionId != null) {
sectionIds.push(sectionId);
const section = new Section(this, sectionId, state.mechanics);
sectionId = section.getNextSectionId();
}
return sectionIds;
}
} | the_stack |
import {Graph} from './graph';
import {MondrianArtConfig, GeneratorData, Item, ItemType, TPoint} from './types';
import { RC, RGN } from './utils';
import {gradient} from './styling';
import * as isect from 'isect';
import * as tinycolor_ from 'tinycolor2';
const tinycolor = tinycolor_;
export default (config: MondrianArtConfig): Item[] => {
const width = config.width || 500;
const height = config.height || 500;
let style = config.mondrian?.style || 'random';
const lineWidth = config.mondrian?.lineWidth || 1;
const backgroundColor = config.mondrian?.backgroundColor || '#fff';
const enableGradient = config.mondrian?.enableGradient || false;
const palette = config.mondrian?.palette || ['#0e448c', '#f61710', 'transparent', '#ffd313', 'transparent'];
if (style === 'random') {
style = RC(['neo', 'classic']);
}
// 1. Generate lines and polygons (rects). Default it's random
let data;
if (style === 'classic') {
// Classic generator
data = classicGenerator(width, height);
}
if (style === 'neo') {
// Neo generator
data = neoGenerator(width, height);
}
// 2. Generate style
const items: Item[] = [];
// Style lines
data.lines.forEach(line => {
items.push({
type: ItemType.line,
points: line,
fill: tinycolor.isReadable(backgroundColor, '#fff') ? '#fff' : '#000',
strokeWidth: lineWidth === 'random' ? RGN(0.5, 4) : lineWidth,
target: null
});
});
// Style polygons
data.polygons.forEach(polygon => {
items.push({
type: ItemType.polygon,
points: polygon,
gradient: enableGradient ? gradient(RC(palette), height) : undefined,
fill: RC(palette),
target: null
});
});
return items;
};
const neoGenerator = (width: number, height: number): GeneratorData => {
const maxValue = Math.floor((width > height ? width : height) / 100 * 30);
const w = RGN(30, width - Math.floor(width / 100 * 10));
const h = RGN(30, height - Math.floor(height / 100 * 10));
const r = {
x: (width - w) / 2,
y: (height - h) / 2,
w: w,
h: h
};
const lines: number[][] = [];
const skew = RGN(1, 5) === 3;
const skewX = skew ? RGN(-20, 20) : 0;
const skewY = skew ? RGN(-20, 20) : 0;
const isAdd = !(RGN(1, 5) === 3);
const genExtraDots = (points: TPoint[]): TPoint[] => {
const extra_points: TPoint[] = [];
points.slice(0, 2).forEach((point, i) => {
const dot1 = isAdd ? RGN(-maxValue, maxValue) : RGN(-maxValue / 2, maxValue / 2);
const dot2 = isAdd ? RGN(-maxValue, maxValue) : -dot1;
const dot3 = isAdd ? RGN(-maxValue, maxValue) : RGN(-maxValue / 2, maxValue / 2);
const dot4 = isAdd ? RGN(-maxValue, maxValue) : -dot3;
const { x, y, toIdx } = point;
const { x: x1, y: y1 } = points[toIdx || 0];
const angle = Math.atan2(y1 - y, x1 - x);
const { x: x2, y: y2, toIdx: t2 } = points[i + 2];
const { x: x21, y: y21 } = points[t2 || 0];
const angle2 = Math.atan2(y21 - y2, x21 - x2);
extra_points.push(...[
{
x: ((x2 + x21) / 2) - dot1 * Math.cos(angle2),
y: ((y2 + y21) / 2) - dot1 * Math.sin(angle2),
toIdx: points.length + extra_points.length + 1,
line0: 0,
line1: 1
},
{
x: ((x + x1) / 2) - dot2 * Math.cos(angle),
y: ((y + y1) / 2) - dot2 * Math.sin(angle),
line0: 0,
line1: 1
}
]);
if (i === RGN(1, 2)) {
extra_points.push(...[
{
x: ((x2 + x21) / 2) - dot3 * Math.cos(angle2), // RN(-100, 100)
y: ((y2 + y21) / 2) - dot3 * Math.sin(angle2),
toIdx: points.length + extra_points.length + 1,
line0: 0,
line1: 1
},
{
x: ((x + x1) / 2) - dot4 * Math.cos(angle),
y: ((y + y1) / 2) - dot4 * Math.sin(angle),
line0: 0,
line1: 1
}
]);
}
});
return extra_points;
};
let dots: TPoint[] = [
{
x: r.x,
y: r.x,
toIdx: 1,
line0: 0,
line1: 1
},
{
x: r.x + r.w,
y: r.y,
toIdx: 2,
line0: 0,
line1: 1
},
{
x: r.x + r.w,
y: r.y + r.h,
toIdx: 3,
line0: 0,
line1: 1
},
{
x: r.x,
y: r.y + r.h,
toIdx: 0,
line0: 0,
line1: 1
}
];
dots = dots.concat(genExtraDots(dots)).map((value => {
const tan_a = Math.tan(skewX * Math.PI / 180);
const tan_b = Math.tan(skewY * Math.PI / 180);
const {x, y} = value;
value.origX = x;
value.origY = y;
value.y = x * tan_b + y - tan_b * r.h;
value.x = x + y * tan_a - tan_a * r.w;
value.y = x * tan_b + y - tan_b * r.h;
return value;
}));
// Generate lines
dots
.filter(a => a.toIdx !== undefined)
.forEach((point, i) => {
const adding = isAdd ? RGN(10, maxValue) : 0;
const { x, y, toIdx } = point;
const { x: x1, y: y1 } = dots[toIdx === undefined ? 0 : toIdx];
const angle = Math.atan2(y1 - y, x1 - x);
// const isCur = RN(1, 2) === 1;
lines.push([
x - (adding * Math.cos(angle)),
y - (adding * Math.sin(angle)),
// ((x - (adding * Math.cos(angle))) + (x1 + (adding * Math.cos(angle)))) / 2 + (isCur ? RN(-50, 50) : 0),
// ((y - (adding * Math.sin(angle))) + (y1 + (adding * Math.sin(angle)))) / 2 + (isCur ? RN(-50, 50) : 0),
x1 + (adding * Math.cos(angle)),
y1 + (adding * Math.sin(angle))
]);
});
// DETECT-POLYGONS(Ψ)
// 1 G ← COMPUTE-INDUCED-GRAPH(Ψ)
// 2 Γ ← MINIMUM-CYCLE-BASIS(G)
// 3 Θ ← POLYGONS-FROM-CYCLES(Γ)
// 0. Find intersection
const _lines = lines.map((a, i) => { return {from: {x: a[0], y: a[1]}, to: {x: a[2], y: a[3]}, i: i}; });
// @ts-ignore
const detectIntersections = isect.sweep(_lines, {});
const intersections = detectIntersections.run().map((a, i) => { return {...a, index: i}; });
// 1. Create graph
// COMPUTE- INDUCED-GRAPH, computes the graph G induced by set Φ in O((N+M)logN)
// The first step of our approach consists in detecting all M intersections between N line segments in a plane.
const graph = new Graph();
intersections.forEach((inter, i) => {
graph.addVertex(i);
});
const distance: any = {};
intersections.forEach((inter, i) => {
inter.segments.forEach(seg => {
let r = 0;
let minId = '';
let ids = 0;
intersections
.filter((a, z) => z !== i && a.segments.map(y => y.i).includes(seg.i))
.forEach(int => {
const dist = Math.hypot(inter.point.x - int.point.x, inter.point.y - int.point.y);
if (dist < r || r === 0) {
r = dist;
minId = `${i}_${int.index}`;
ids = int.index;
}
});
graph.addEdge(i, ids, r);
graph.addEdge(ids, i, r);
distance[minId] = r;
});
});
// 2. Get cycles in an undirected graph
const bases: number[][] = [];
const hack = Object.keys(graph.vertices).length + 1;
Object.keys(graph.vertices).map(a => parseInt(a)).forEach(a => {
// MIN CYCLE
const N = 1000;
const graph1: any[] = new Array(N).fill(Boolean).map(a => []);
const cycles: any[] = new Array(N).fill(Boolean).map(a => []);
const addEdge = (u, v) => {
graph1[u].push(v);
graph1[v].push(u);
};
const index = a;
if (!graph.vertices[index]) {
return;
}
const vert = graph.vertices[index];
const edg: any[] = [];
const eedges = Object.keys(vert.edges).map(a => parseInt(a));
// TODO Optimization
eedges.forEach(edge => {
edg.push([index, edge]);
Object.keys(graph.vertices[edge].edges).map(a => parseInt(a)).forEach(edge2 => {
edg.push([edge, edge2]);
});
});
eedges.forEach(edge => {
Object.keys(graph.vertices[edge].edges).map(a => parseInt(a)).forEach(edge2 => {
edg.push([edge, edge2]);
});
});
edg.forEach(e => {
addEdge(e[0] === 0 ? hack : e[0], e[1] === 0 ? hack : e[1]);
});
const color = new Array(N).fill(Boolean).map(a => 0);
const par = new Array(N).fill(Boolean).map(a => 0);
/// mark with unique numbers
const mark = new Array(N).fill(Boolean).map(a => 0);
// store the numbers of cycle
let cyclenumber = 0;
const edges = 23;
const dfs_cycle = (u, p, color, mark, par) => {
if (color[u] === 2) {
return;
}
// seen vertex, but was not
// completely visited -> cycle detected.
// backtrack based on parents to
// find the complete cycle.
if (color[u] === 1) {
cyclenumber += 1;
let cur = p;
mark[cur] = cyclenumber;
while (cur !== u) {
cur = par[cur];
mark[cur] = cyclenumber;
}
return;
}
par[u] = p;
color[u] = 1;
for (const va in graph1[u]) {
const v = graph1[u][parseInt(va)];
if (v === par[u]) {
continue;
}
dfs_cycle(v, u, color, mark, par);
}
color[u] = 2;
};
dfs_cycle(index, 0, color, mark, par);
for (let i = 1; i < edges + 1; i++) {
if (mark[i] !== 0) {
cycles[mark[i]].push(i);
}
}
for (let i = 1; i < cyclenumber + 1; i++) {
if (cycles[i].length >= 3) {
const value = cycles[i].flat().map(b => b === hack ? 0 : b);
if (!bases.map(b => b.join()).includes(value.join())) {
bases.push(value);
}
}
}
});
// 3. Constructs a set of polygon, sort clockwise
const polygons: number[][] = [];
bases.forEach(base => {
const points = base.map(a => { return {
x: intersections[a].point.x,
y: intersections[a].point.y,
angle: 0
}; });
const center = points.reduce((acc, { x, y }) => {
acc.x += x / points.length;
acc.y += y / points.length;
return acc;
}, { x: 0, y: 0 });
// Add an angle property to each point using tan(angle) = y/x
const angles = points.map(({ x, y }) => {
return { x, y, angle: Math.atan2(y - center.y, x - center.x) * 180 / Math.PI };
});
// Sort your points by angle
const pointsSorted = angles.sort((a, b) => a.angle - b.angle);
polygons.push(pointsSorted.map(a => [a.x, a.y]).flat());
});
return {
lines,
polygons
};
};
const classicGenerator = (width: number, height: number): GeneratorData => {
const polygons: number[][] = [];
const lines: number[][] = [];
const grid = () => {
// TODO Set config, size
const col = Math.floor((width) / Math.floor(width / 100 * 15));
const row = Math.floor((height) / Math.floor(height / 100 * 15));
const matrix = Array(row).fill(0).map(() => Array(col).fill(0));
let curRow = 0;
let curCol = 0;
let maxRows = row;
let maxColumns = col;
const grid: any[] = [];
while (curRow < row) {
const rowSpan = Math.floor(Math.random() * maxRows + 1);
const columnSpan = Math.floor(Math.random() * maxColumns + 1);
grid.push({
x: (curRow / row * width),
y: (curCol / col * height),
width: ((((curRow + rowSpan)) / row * width) - curRow / row * width), // - border,
height: ((((curCol + columnSpan)) / col * height) - curCol / col * height) // - border
});
for (let i = curRow; i < curRow + rowSpan; i++) {
for (let j = curCol; j < curCol + columnSpan; j++) {
matrix[i][j] = 1;
}
}
if (curCol + columnSpan >= col) {
curRow++;
curCol = 0;
} else {
curCol += columnSpan;
}
if (curRow >= row) {
return grid;
}
while (matrix[curRow][curCol] === 1) {
curCol = curCol + 1;
if (curCol >= col) {
curRow++;
curCol = 0;
}
if (curRow >= row) {
return grid;
}
}
for (let i = curRow; i < row; i++) {
if (matrix[i][curCol] === 0) {
maxRows = i - curRow + 1;
} else {
break;
}
}
for (let j = curCol; j < col; j++) {
if (matrix[curRow][j] === 0) {
maxColumns = j - curCol + 1;
} else {
break;
}
}
}
return grid;
};
const items = grid();
items.forEach(rect => {
polygons.push([
rect.x, rect.y, rect.x + rect.width, rect.y,
rect.x + rect.width, rect.y + rect.height, rect.x, rect.y + rect.height
]);
lines.push([rect.x, rect.y, rect.x + rect.width, rect.y]);
lines.push([rect.x + rect.width, rect.y + rect.height, rect.x + rect.width, rect.y]);
});
return {
lines: lines,
polygons: polygons
};
}; | the_stack |
import expect from 'expect.js';
import { BinaryStream, ByteUtils, Consts, Int64, VarDictionary } from '../../lib';
import { ValueType } from '../../lib/utils/var-dictionary';
describe('VarDictionary', () => {
const data =
'00010808000000426f6f6c5472756501000000010809000000426f6f6c46616c' +
'73650100000000040600000055496e743332040000002a000000050600000055' +
'496e74363408000000ccccddddeeeeffff0c05000000496e74333204000000d6' +
'ffffff0d05000000496e74363408000000444433332222111118060000005374' +
'72696e670b000000537472696e6756616c756542090000004279746541727261' +
'7907000000000102030405ff00';
it('reads and writes dictionary', () => {
const dataBytes = ByteUtils.hexToBytes(data);
let stm = new BinaryStream(ByteUtils.arrayToBuffer(dataBytes));
const dict = VarDictionary.read(stm);
expect(dict).to.be.a(VarDictionary);
expect(dict.length).to.be(8);
expect(dict.get('BoolTrue')).to.be(true);
expect(dict.get('BoolFalse')).to.be(false);
expect(dict.get('UInt32')).to.be(42);
expect((dict.get('UInt64') as Int64).hi).to.be(0xffffeeee);
expect((dict.get('UInt64') as Int64).lo).to.be(0xddddcccc);
expect(dict.get('Int32')).to.be(-42);
expect((dict.get('Int64') as Int64).hi).to.be(0x11112222);
expect((dict.get('Int64') as Int64).lo).to.be(0x33334444);
expect(dict.get('String')).to.be('StringValue');
expect(dict.keys()).to.eql([
'BoolTrue',
'BoolFalse',
'UInt32',
'UInt64',
'Int32',
'Int64',
'String',
'ByteArray'
]);
expect(ByteUtils.bytesToHex(dict.get('ByteArray') as ArrayBuffer)).to.be('000102030405ff');
stm = new BinaryStream();
dict.write(stm);
expect(ByteUtils.bytesToHex(stm.getWrittenBytes())).to.be(data);
});
it('writes dictionary', () => {
const dict = new VarDictionary();
dict.set('BoolTrue', ValueType.Bool, true);
dict.set('BoolFalse', ValueType.Bool, false);
dict.set('UInt32', ValueType.UInt32, 42);
dict.set('UInt64', ValueType.UInt64, new Int64(0xddddcccc, 0xffffeeee));
dict.set('Int32', ValueType.Int32, -42);
dict.set('Int64', ValueType.Int64, new Int64(0x33334444, 0x11112222));
dict.set('String', ValueType.String, 'StringValue');
dict.set('ByteArray', ValueType.Bytes, ByteUtils.hexToBytes('000102030405ff'));
const stm = new BinaryStream();
dict.write(stm);
expect(ByteUtils.bytesToHex(stm.getWrittenBytes())).to.be(data);
});
it('returns undefined for not found value', () => {
const dict = new VarDictionary();
expect(dict.length).to.be(0);
expect(dict.get('val')).to.be(undefined);
});
it('removes item from dictionary', () => {
const dict = new VarDictionary();
expect(dict.length).to.be(0);
expect(dict.get('val')).to.be(undefined);
dict.set('val', ValueType.Bool, true);
expect(dict.length).to.be(1);
expect(dict.get('val')).to.be(true);
dict.remove('val');
expect(dict.length).to.be(0);
expect(dict.get('val')).to.be(undefined);
});
it('allows to add key twice', () => {
const dict = new VarDictionary();
dict.set('UInt32', ValueType.UInt32, 42);
expect(dict.length).to.be(1);
dict.set('UInt32', ValueType.UInt32, 42);
expect(dict.length).to.be(1);
});
it('throws error for empty version', () => {
expect(() => {
VarDictionary.read(
new BinaryStream(ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('0000')))
);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidVersion);
});
});
it('throws error for larger version', () => {
expect(() => {
VarDictionary.read(
new BinaryStream(ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('0002')))
);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidVersion);
});
});
it('throws error for bad value type', () => {
expect(() => {
VarDictionary.read(
new BinaryStream(
ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('0001ff01000000dd10000000'))
)
);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.FileCorrupt);
expect(e.message).to.contain('bad value type');
});
});
it('reads empty dictionary', () => {
const dict = VarDictionary.read(
new BinaryStream(ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('000100')))
);
expect(dict.length).to.be(0);
});
it('throws error for bad key length', () => {
expect(() => {
VarDictionary.read(
new BinaryStream(
ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('0001ff00000000dd10000000'))
)
);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.FileCorrupt);
expect(e.message).to.contain('bad key length');
});
});
it('throws error for bad value length', () => {
expect(() => {
VarDictionary.read(
new BinaryStream(
ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('0001ff01000000ddffffffff'))
)
);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.FileCorrupt);
expect(e.message).to.contain('bad value length');
});
});
it('throws error for bad uint32 value', () => {
expect(() => {
VarDictionary.read(
new BinaryStream(
ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('00010401000000dd0500000000'))
)
);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.FileCorrupt);
expect(e.message).to.contain('bad uint32');
});
});
it('throws error for bad uint64 value', () => {
expect(() => {
VarDictionary.read(
new BinaryStream(
ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('00010501000000dd0500000000'))
)
);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.FileCorrupt);
expect(e.message).to.contain('bad uint64');
});
});
it('throws error for bad bool value', () => {
expect(() => {
VarDictionary.read(
new BinaryStream(
ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('00010801000000dd0500000000'))
)
);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.FileCorrupt);
expect(e.message).to.contain('bad bool');
});
});
it('throws error for bad int32 value', () => {
expect(() => {
VarDictionary.read(
new BinaryStream(
ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('00010c01000000dd0500000000'))
)
);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.FileCorrupt);
expect(e.message).to.contain('bad int32');
});
});
it('throws error for bad int64 value', () => {
expect(() => {
VarDictionary.read(
new BinaryStream(
ByteUtils.arrayToBuffer(ByteUtils.hexToBytes('00010d01000000dd0500000000'))
)
);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.FileCorrupt);
expect(e.message).to.contain('bad int64');
});
});
it('throws error for bad value type on write', () => {
expect(() => {
const dict = new VarDictionary();
dict.set('BoolTrue', ValueType.Bool, true);
// @ts-ignore
dict._items[0].type = 0xff;
dict.write(new BinaryStream());
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.Unsupported);
});
});
it('throws error for bad value type on set', () => {
expect(() => {
const dict = new VarDictionary();
dict.set('val', 0xff, true);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
});
it('throws error for bad int32 on set', () => {
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.Int32, 'str');
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
// @ts-ignore
dict.set('val', ValueType.Int32, null);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
});
it('throws error for bad int64 on set', () => {
expect(() => {
const dict = new VarDictionary();
// @ts-ignore
dict.set('val', ValueType.Int64, null);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.Int64, 'str');
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.Int64, 123);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
// @ts-ignore
dict.set('val', ValueType.Int64, { hi: 1 });
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
// @ts-ignore
dict.set('val', ValueType.Int64, { lo: 1 });
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
});
it('throws error for bad bool on set', () => {
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.Bool, 'true');
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.Bool, 1);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
// @ts-ignore
dict.set('val', ValueType.Bool, null);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.Bool, undefined);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
});
it('throws error for bad uint32 on set', () => {
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.UInt32, 'str');
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.UInt32, -1);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
});
it('throws error for bad uint64 on set', () => {
expect(() => {
const dict = new VarDictionary();
// @ts-ignore
dict.set('val', ValueType.UInt64, null);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.UInt64, 'str');
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.UInt64, 123);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
// @ts-ignore
dict.set('val', ValueType.UInt64, { hi: 1 });
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
// @ts-ignore
dict.set('val', ValueType.UInt64, { lo: 1 });
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
});
it('throws error for bad string on set', () => {
expect(() => {
const dict = new VarDictionary();
// @ts-ignore
dict.set('val', ValueType.String, null);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.String, 123);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
});
it('throws error for bad bytes', () => {
expect(() => {
const dict = new VarDictionary();
// @ts-ignore
dict.set('val', ValueType.Bytes, null);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.Bytes, 123);
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
expect(() => {
const dict = new VarDictionary();
dict.set('val', ValueType.Bytes, '0000');
}).to.throwException((e) => {
expect(e.code).to.be(Consts.ErrorCodes.InvalidArg);
});
});
}); | the_stack |
import { Config } from '../../lib/core/configApi';
/**
* Org Preferences are exposed through different APIs
* Singleton object encapsulating registry of supported Org Preference types
*/
// P R I V A T E
let currentApiVersion: string;
// pref APIs
const AccountSettingsApi = 'accountSettings';
const ActivitiesSettingsApi = 'activitiesSettings';
const ApexSettingsApi = 'apexSettings';
const ChatterSettingsApi = 'chatterSettings';
const ContractSettingsApi = 'contractSettings';
const CommunitiesSettingsApi = 'communitiesSettings';
const DevHubSettingsApi = 'devhubSettings';
const EmailAdministrationSettingsApi = 'emailAdministrationSettings';
const EnhancedNotesSettingsApi = 'enhancedNotesSettings';
const EntitlementSettingsApi = 'entitlementSettings';
const EventSettingsApi = 'eventSettings';
const ForecastingSettingsApi = 'forecastingSettings';
const IdeasSettingsApi = 'ideasSettings';
const KnowledgeSettingsApi = 'knowledgeSettings';
const LanguageSettingsApi = 'languageSettings';
const LightningExperienceSettingsApi = 'lightningExperienceSettings';
const LiveAgentSettingsApi = 'liveAgentSettings';
const MobileSettingsApi = 'mobileSettings';
const NameSettingsApi = 'nameSettings';
const OpportunitySettingsApi = 'opportunitySettings';
const OrderSettingsApi = 'orderSettings';
const PardotSettingsApi = 'pardotSettings';
const PartyDataModelSettingsApi = 'partyDataModelSettings';
const ProductSettingsApi = 'productSettings';
const OrgPreferenceSettingsApi = 'orgPreferenceSettings';
const QuoteSettingsApi = 'quoteSettings';
const SecuritySessionSettingsApi = 'securitySettings.sessionSettings';
const SearchSettingsApi = 'searchSettings';
const SharingSettingsApi = 'sharingSettings';
const SocialProfileSettingsApi = 'socialProfileSettings';
const OrganizationSettingsDetailApi = 'orgPreferenceSettings';
const Territory2SettingsApi = 'territory2Settings';
const PathAssistantSettingsApi = 'pathAssistantSettings';
const VoiceSettingsApi = 'voiceSettings';
const SecuritySettingsPasswordPoliciesApi = 'securitySettings.passwordPolicies';
const DeprecatedSettingsApi = 'DEPRECATED';
// This map is used in the migration from orgPreferences -> settings types before 47.0
// pre apiVersion 47.0 supported org preferences and the API through which they are set
const orgPreferenceApiMapPre47 = new Map([
['IsAccountTeamsEnabled', AccountSettingsApi],
['ShowViewHierarchyLink', AccountSettingsApi],
['IsActivityRemindersEnabled', ActivitiesSettingsApi],
['IsDragAndDropSchedulingEnabled', ActivitiesSettingsApi],
['IsEmailTrackingEnabled', ActivitiesSettingsApi],
['IsGroupTasksEnabled', ActivitiesSettingsApi],
['IsMultidayEventsEnabled', ActivitiesSettingsApi],
['IsRecurringEventsEnabled', ActivitiesSettingsApi],
['IsRecurringTasksEnabled', ActivitiesSettingsApi],
['IsSidebarCalendarShortcutEnabled', ActivitiesSettingsApi],
['IsSimpleTaskCreateUIEnabled', ActivitiesSettingsApi],
['ShowEventDetailsMultiUserCalendar', ActivitiesSettingsApi],
['ShowHomePageHoverLinksForEvents', ActivitiesSettingsApi],
['ShowMyTasksHoverLinks', ActivitiesSettingsApi],
['ShowRequestedMeetingsOnHomePage', ActivitiesSettingsApi],
['AutoCalculateEndDate', ContractSettingsApi],
['IsContractHistoryTrackingEnabled', ContractSettingsApi],
['NotifyOwnersOnContractExpiration', ContractSettingsApi],
['AssetLookupLimitedToActiveEntitlementsOnAccount', EntitlementSettingsApi],
['AssetLookupLimitedToActiveEntitlementsOnContact', EntitlementSettingsApi],
['AssetLookupLimitedToSameAccount', EntitlementSettingsApi],
['AssetLookupLimitedToSameContact', EntitlementSettingsApi],
['IsEntitlementsEnabled', EntitlementSettingsApi],
['EntitlementLookupLimitedToActiveStatus', EntitlementSettingsApi],
['EntitlementLookupLimitedToSameAccount', EntitlementSettingsApi],
['EntitlementLookupLimitedToSameAsset', EntitlementSettingsApi],
['EntitlementLookupLimitedToSameContact', EntitlementSettingsApi],
['IsForecastsEnabled', ForecastingSettingsApi],
['IsChatterProfileEnabled', IdeasSettingsApi],
['IsIdeaThemesEnabled', IdeasSettingsApi],
['IsIdeasEnabled', IdeasSettingsApi],
['IsIdeasReputationEnabled', IdeasSettingsApi],
['IsCreateEditOnArticlesTabEnabled', KnowledgeSettingsApi],
['IsExternalMediaContentEnabled', KnowledgeSettingsApi],
['IsKnowledgeEnabled', KnowledgeSettingsApi],
['ShowArticleSummariesCustomerPortal', KnowledgeSettingsApi],
['ShowArticleSummariesInternalApp', KnowledgeSettingsApi],
['ShowArticleSummariesPartnerPortal', KnowledgeSettingsApi],
['ShowValidationStatusField', KnowledgeSettingsApi],
['IsLiveAgentEnabled', LiveAgentSettingsApi],
['IsMiddleNameEnabled', NameSettingsApi],
['IsNameSuffixEnabled', NameSettingsApi],
['IsOpportunityTeamEnabled', OpportunitySettingsApi],
['IsOrdersEnabled', OrderSettingsApi],
['IsNegativeQuantityEnabled', OrderSettingsApi],
['IsReductionOrdersEnabled', OrderSettingsApi],
['IsCascadeActivateToRelatedPricesEnabled', ProductSettingsApi],
['IsQuantityScheduleEnabled', ProductSettingsApi],
['IsRevenueScheduleEnabled', ProductSettingsApi],
['IsQuoteEnabled', QuoteSettingsApi],
['DocumentContentSearchEnabled', SearchSettingsApi],
['OptimizeSearchForCjkEnabled', SearchSettingsApi],
['RecentlyViewedUsersForBlankLookupEnabled', SearchSettingsApi],
['SidebarAutoCompleteEnabled', SearchSettingsApi],
['SidebarDropDownListEnabled', SearchSettingsApi],
['SidebarLimitToItemsIownCheckboxEnabled', SearchSettingsApi],
['SingleSearchResultShortcutEnabled', SearchSettingsApi],
['SpellCorrectKnowledgeSearchEnabled', SearchSettingsApi],
['AnalyticsSharingEnable', OrganizationSettingsDetailApi],
['DisableParallelApexTesting', OrganizationSettingsDetailApi],
['EnhancedEmailEnabled', OrganizationSettingsDetailApi],
['EventLogWaveIntegEnabled', OrganizationSettingsDetailApi],
['SendThroughGmailPref', OrganizationSettingsDetailApi],
['Translation', OrganizationSettingsDetailApi],
['S1OfflinePref', OrganizationSettingsDetailApi],
['S1EncryptedStoragePref2', OrganizationSettingsDetailApi],
['OfflineDraftsEnabled', OrganizationSettingsDetailApi],
['AsyncSaveEnabled', OrganizationSettingsDetailApi],
['ChatterEnabled', OrganizationSettingsDetailApi],
['SelfSetPasswordInApi', OrganizationSettingsDetailApi],
['SocialProfilesEnable', OrganizationSettingsDetailApi],
['PathAssistantsEnabled', OrganizationSettingsDetailApi],
['LoginForensicsEnabled', OrganizationSettingsDetailApi],
['S1DesktopEnabled', OrganizationSettingsDetailApi],
['NetworksEnabled', OrganizationSettingsDetailApi],
['NotesReservedPref01', OrganizationSettingsDetailApi],
['CompileOnDeploy', OrganizationSettingsDetailApi],
['VoiceEnabled', OrganizationSettingsDetailApi],
['TerritoryManagement2Enable', OrganizationSettingsDetailApi],
['ApexApprovalLockUnlock', OrganizationSettingsDetailApi],
]);
// This map is used in the migration from orgPreferences -> settings types before 47.0
const orgPreferenceMdMapPre47 = new Map([
['IsAccountTeamsEnabled', 'enableAccountTeams'],
['ShowViewHierarchyLink', 'showViewHierarchyLink'],
['IsActivityRemindersEnabled', 'enableActivityReminders'],
['IsDragAndDropSchedulingEnabled', 'enableDragAndDropScheduling'],
['IsEmailTrackingEnabled', 'enableEmailTracking'],
['IsGroupTasksEnabled', 'enableGroupTasks'],
['IsMultidayEventsEnabled', 'enableMultidayEvents'],
['IsRecurringEventsEnabled', 'enableRecurringEvents'],
['IsRecurringTasksEnabled', 'enableRecurringTasks'],
['IsSidebarCalendarShortcutEnabled', 'enableSidebarCalendarShortcut'],
['IsSimpleTaskCreateUIEnabled', 'enableSimpleTaskCreateUI'],
['ShowEventDetailsMultiUserCalendar', 'showEventDetailsMultiUserCalendar'],
['ShowHomePageHoverLinksForEvents', 'showHomePageHoverLinksForEvents'],
['ShowMyTasksHoverLinks', 'showMyTasksHoverLinks'],
['ShowRequestedMeetingsOnHomePage', 'showRequestedMeetingsOnHomePage'],
['AutoCalculateEndDate', 'autoCalculateEndDate'],
['IsContractHistoryTrackingEnabled', 'enableContractHistoryTracking'],
['NotifyOwnersOnContractExpiration', 'notifyOwnersOnContractExpiration'],
['AssetLookupLimitedToActiveEntitlementsOnAccount', 'assetLookupLimitedToActiveEntitlementsOnAccount'],
['AssetLookupLimitedToActiveEntitlementsOnContact', 'assetLookupLimitedToActiveEntitlementsOnContact'],
['AssetLookupLimitedToSameAccount', 'assetLookupLimitedToSameAccount'],
['AssetLookupLimitedToSameContact', 'assetLookupLimitedToSameContact'],
['IsEntitlementsEnabled', 'enableEntitlements'],
['EntitlementLookupLimitedToActiveStatus', 'entitlementLookupLimitedToActiveStatus'],
['EntitlementLookupLimitedToSameAccount', 'entitlementLookupLimitedToSameAccount'],
['EntitlementLookupLimitedToSameAsset', 'entitlementLookupLimitedToSameAsset'],
['EntitlementLookupLimitedToSameContact', 'entitlementLookupLimitedToSameContact'],
['IsForecastsEnabled', 'enableForecasts'],
['IsChatterProfileEnabled', 'enableChatterProfile'],
['IsIdeaThemesEnabled', 'enableIdeaThemes'],
['IsIdeasEnabled', 'enableIdeas'],
['IsIdeasReputationEnabled', 'enableIdeasReputation'],
['IsCreateEditOnArticlesTabEnabled', 'enableCreateEditOnArticlesTab'],
['IsExternalMediaContentEnabled', 'enableExternalMediaContent'],
['IsKnowledgeEnabled', 'enableKnowledge'],
['ShowArticleSummariesCustomerPortal', 'showArticleSummariesCustomerPortal'],
['ShowArticleSummariesInternalApp', 'showArticleSummariesInternalApp'],
['ShowArticleSummariesPartnerPortal', 'showArticleSummariesPartnerPortal'],
['ShowValidationStatusField', 'showValidationStatusField'],
['IsLiveAgentEnabled', 'enableLiveAgent'],
['IsMiddleNameEnabled', 'enableMiddleName'],
['IsNameSuffixEnabled', 'enableNameSuffix'],
['IsOpportunityTeamEnabled', 'enableOpportunityTeam'],
['IsOrdersEnabled', 'enableOrders'],
['IsNegativeQuantityEnabled', 'enableNegativeQuantity'],
['IsReductionOrdersEnabled', 'enableReductionOrders'],
['IsCascadeActivateToRelatedPricesEnabled', 'enableCascadeActivateToRelatedPrices'],
['IsQuantityScheduleEnabled', 'enableQuantitySchedule'],
['IsRevenueScheduleEnabled', 'enableRevenueSchedule'],
['IsQuoteEnabled', 'enableQuote'],
['DocumentContentSearchEnabled', 'documentContentSearchEnabled'],
['OptimizeSearchForCjkEnabled', 'optimizeSearchForCJKEnabled'],
['RecentlyViewedUsersForBlankLookupEnabled', 'recentlyViewedUsersForBlankLookupEnabled'],
['SidebarAutoCompleteEnabled', 'sidebarAutoCompleteEnabled'],
['SidebarDropDownListEnabled', 'sidebarDropDownListEnabled'],
['SidebarLimitToItemsIownCheckboxEnabled', 'sidebarLimitToItemsIOwnCheckboxEnabled'],
['SingleSearchResultShortcutEnabled', 'singleSearchResultShortcutEnabled'],
['SpellCorrectKnowledgeSearchEnabled', 'spellCorrectKnowledgeSearchEnabled'],
['AnalyticsSharingEnable', 'analyticsSharingEnable'],
['DisableParallelApexTesting', 'disableParallelApexTesting'],
['EnhancedEmailEnabled', 'enhancedEmailEnabled'],
['EventLogWaveIntegEnabled', 'eventLogWaveIntegEnabled'],
['SendThroughGmailPref', 'sendThroughGmailPref'],
['Translation', 'translation'],
['S1OfflinePref', 's1OfflinePref'],
['S1EncryptedStoragePref2', 's1EncryptedStoragePref2'],
['OfflineDraftsEnabled', 'offlineDraftsEnabled'],
['AsyncSaveEnabled', 'asyncSaveEnabled'],
['ChatterEnabled', 'chatterEnabled'],
['SelfSetPasswordInApi', 'selfSetPasswordInApi'],
['SocialProfilesEnable', 'socialProfilesEnable'],
['PathAssistantsEnabled', 'pathAssistantsEnabled'],
['LoginForensicsEnabled', 'loginForensicsEnabled'],
['S1DesktopEnabled', 's1DesktopEnabled'],
['NetworksEnabled', 'networksEnabled'],
['NotesReservedPref01', 'notesReservedPref01'],
['CompileOnDeploy', 'compileOnDeploy'],
['VoiceEnabled', 'voiceEnabled'],
['TerritoryManagement2Enable', 'territoryManagement2Enable'],
['ApexApprovalLockUnlock', 'apexApprovalLockUnlock'],
]);
// This map is used in the migration from orgPreferences -> settings types
// supported org preferences and the API through which they are set
const orgPreferenceApiMap = new Map([
['IsAccountTeamsEnabled', AccountSettingsApi],
['ShowViewHierarchyLink', AccountSettingsApi],
['IsActivityRemindersEnabled', ActivitiesSettingsApi],
['IsDragAndDropSchedulingEnabled', ActivitiesSettingsApi],
['IsEmailTrackingEnabled', ActivitiesSettingsApi],
['IsGroupTasksEnabled', ActivitiesSettingsApi],
['IsMultidayEventsEnabled', ActivitiesSettingsApi],
['IsRecurringEventsEnabled', ActivitiesSettingsApi],
['IsRecurringTasksEnabled', ActivitiesSettingsApi],
['IsSidebarCalendarShortcutEnabled', ActivitiesSettingsApi],
['IsSimpleTaskCreateUIEnabled', ActivitiesSettingsApi],
['ShowEventDetailsMultiUserCalendar', ActivitiesSettingsApi],
['ShowHomePageHoverLinksForEvents', ActivitiesSettingsApi],
['ShowMyTasksHoverLinks', ActivitiesSettingsApi],
['ShowRequestedMeetingsOnHomePage', ActivitiesSettingsApi],
['AutoCalculateEndDate', ContractSettingsApi],
['IsContractHistoryTrackingEnabled', ContractSettingsApi],
['NotifyOwnersOnContractExpiration', ContractSettingsApi],
['AssetLookupLimitedToActiveEntitlementsOnAccount', EntitlementSettingsApi],
['AssetLookupLimitedToActiveEntitlementsOnContact', EntitlementSettingsApi],
['AssetLookupLimitedToSameAccount', EntitlementSettingsApi],
['AssetLookupLimitedToSameContact', EntitlementSettingsApi],
['IsEntitlementsEnabled', EntitlementSettingsApi],
['EntitlementLookupLimitedToActiveStatus', EntitlementSettingsApi],
['EntitlementLookupLimitedToSameAccount', EntitlementSettingsApi],
['EntitlementLookupLimitedToSameAsset', EntitlementSettingsApi],
['EntitlementLookupLimitedToSameContact', EntitlementSettingsApi],
['IsForecastsEnabled', ForecastingSettingsApi],
['IsChatterProfileEnabled', IdeasSettingsApi],
['IsIdeaThemesEnabled', IdeasSettingsApi],
['IsIdeasEnabled', IdeasSettingsApi],
['IsIdeasReputationEnabled', IdeasSettingsApi],
['IsCreateEditOnArticlesTabEnabled', KnowledgeSettingsApi],
['IsExternalMediaContentEnabled', KnowledgeSettingsApi],
['IsKnowledgeEnabled', KnowledgeSettingsApi],
['ShowArticleSummariesCustomerPortal', KnowledgeSettingsApi],
['ShowArticleSummariesInternalApp', KnowledgeSettingsApi],
['ShowArticleSummariesPartnerPortal', KnowledgeSettingsApi],
['ShowValidationStatusField', KnowledgeSettingsApi],
['IsLiveAgentEnabled', LiveAgentSettingsApi],
['IsMiddleNameEnabled', NameSettingsApi],
['IsNameSuffixEnabled', NameSettingsApi],
['IsOpportunityTeamEnabled', OpportunitySettingsApi],
['IsOrdersEnabled', OrderSettingsApi],
['IsNegativeQuantityEnabled', OrderSettingsApi],
['IsReductionOrdersEnabled', OrderSettingsApi],
['IsCascadeActivateToRelatedPricesEnabled', ProductSettingsApi],
['IsQuantityScheduleEnabled', ProductSettingsApi],
['IsRevenueScheduleEnabled', ProductSettingsApi],
['IsQuoteEnabled', QuoteSettingsApi],
['DocumentContentSearchEnabled', SearchSettingsApi],
['OptimizeSearchForCjkEnabled', SearchSettingsApi],
['RecentlyViewedUsersForBlankLookupEnabled', SearchSettingsApi],
['SidebarAutoCompleteEnabled', SearchSettingsApi],
['SidebarDropDownListEnabled', SearchSettingsApi],
['SidebarLimitToItemsIownCheckboxEnabled', SearchSettingsApi],
['SingleSearchResultShortcutEnabled', SearchSettingsApi],
['SpellCorrectKnowledgeSearchEnabled', SearchSettingsApi],
['DisableParallelApexTesting', ApexSettingsApi],
['EnhancedEmailEnabled', EmailAdministrationSettingsApi],
['EventLogWaveIntegEnabled', EventSettingsApi],
['SendThroughGmailPref', EmailAdministrationSettingsApi],
['Translation', LanguageSettingsApi],
['S1OfflinePref', MobileSettingsApi],
['S1EncryptedStoragePref2', MobileSettingsApi],
['OfflineDraftsEnabled', MobileSettingsApi],
['ChatterEnabled', ChatterSettingsApi],
['SelfSetPasswordInApi', SecuritySettingsPasswordPoliciesApi],
['SocialProfilesEnable', SocialProfileSettingsApi],
['PathAssistantsEnabled', PathAssistantSettingsApi],
['LoginForensicsEnabled', EventSettingsApi],
['S1DesktopEnabled', LightningExperienceSettingsApi],
['NetworksEnabled', CommunitiesSettingsApi],
['NotesReservedPref01', EnhancedNotesSettingsApi],
['CompileOnDeploy', ApexSettingsApi],
['TerritoryManagement2Enable', Territory2SettingsApi],
['ApexApprovalLockUnlock', ApexSettingsApi],
]);
// This map is used in the migration from orgPreferences -> settings types
const orgPreferenceMdMap = new Map([
['IsAccountTeamsEnabled', 'enableAccountTeams'],
['ShowViewHierarchyLink', 'showViewHierarchyLink'],
['IsActivityRemindersEnabled', 'enableActivityReminders'],
['IsDragAndDropSchedulingEnabled', 'enableDragAndDropScheduling'],
['IsEmailTrackingEnabled', 'enableEmailTracking'],
['IsGroupTasksEnabled', 'enableGroupTasks'],
['IsMultidayEventsEnabled', 'enableMultidayEvents'],
['IsRecurringEventsEnabled', 'enableRecurringEvents'],
['IsRecurringTasksEnabled', 'enableRecurringTasks'],
['IsSidebarCalendarShortcutEnabled', 'enableSidebarCalendarShortcut'],
['IsSimpleTaskCreateUIEnabled', 'enableSimpleTaskCreateUI'],
['ShowEventDetailsMultiUserCalendar', 'showEventDetailsMultiUserCalendar'],
['ShowHomePageHoverLinksForEvents', 'showHomePageHoverLinksForEvents'],
['ShowMyTasksHoverLinks', 'showMyTasksHoverLinks'],
['ShowRequestedMeetingsOnHomePage', 'showRequestedMeetingsOnHomePage'],
['AutoCalculateEndDate', 'autoCalculateEndDate'],
['IsContractHistoryTrackingEnabled', 'enableContractHistoryTracking'],
['NotifyOwnersOnContractExpiration', 'notifyOwnersOnContractExpiration'],
['AssetLookupLimitedToActiveEntitlementsOnAccount', 'assetLookupLimitedToActiveEntitlementsOnAccount'],
['AssetLookupLimitedToActiveEntitlementsOnContact', 'assetLookupLimitedToActiveEntitlementsOnContact'],
['AssetLookupLimitedToSameAccount', 'assetLookupLimitedToSameAccount'],
['AssetLookupLimitedToSameContact', 'assetLookupLimitedToSameContact'],
['IsEntitlementsEnabled', 'enableEntitlements'],
['EntitlementLookupLimitedToActiveStatus', 'entitlementLookupLimitedToActiveStatus'],
['EntitlementLookupLimitedToSameAccount', 'entitlementLookupLimitedToSameAccount'],
['EntitlementLookupLimitedToSameAsset', 'entitlementLookupLimitedToSameAsset'],
['EntitlementLookupLimitedToSameContact', 'entitlementLookupLimitedToSameContact'],
['IsForecastsEnabled', 'enableForecasts'],
['IsChatterProfileEnabled', 'enableChatterProfile'],
['IsIdeaThemesEnabled', 'enableIdeaThemes'],
['IsIdeasEnabled', 'enableIdeas'],
['IsIdeasReputationEnabled', 'enableIdeasReputation'],
['IsCreateEditOnArticlesTabEnabled', 'enableCreateEditOnArticlesTab'],
['IsExternalMediaContentEnabled', 'enableExternalMediaContent'],
['IsKnowledgeEnabled', 'enableKnowledge'],
['ShowArticleSummariesCustomerPortal', 'showArticleSummariesCustomerPortal'],
['ShowArticleSummariesInternalApp', 'showArticleSummariesInternalApp'],
['ShowArticleSummariesPartnerPortal', 'showArticleSummariesPartnerPortal'],
['ShowValidationStatusField', 'showValidationStatusField'],
['IsLiveAgentEnabled', 'enableLiveAgent'],
['IsMiddleNameEnabled', 'enableMiddleName'],
['IsNameSuffixEnabled', 'enableNameSuffix'],
['IsOpportunityTeamEnabled', 'enableOpportunityTeam'],
['IsOrdersEnabled', 'enableOrders'],
['IsNegativeQuantityEnabled', 'enableNegativeQuantity'],
['IsReductionOrdersEnabled', 'enableReductionOrders'],
['IsCascadeActivateToRelatedPricesEnabled', 'enableCascadeActivateToRelatedPrices'],
['IsQuantityScheduleEnabled', 'enableQuantitySchedule'],
['IsRevenueScheduleEnabled', 'enableRevenueSchedule'],
['IsQuoteEnabled', 'enableQuote'],
['DocumentContentSearchEnabled', 'documentContentSearchEnabled'],
['OptimizeSearchForCjkEnabled', 'optimizeSearchForCJKEnabled'],
['RecentlyViewedUsersForBlankLookupEnabled', 'recentlyViewedUsersForBlankLookupEnabled'],
['SidebarAutoCompleteEnabled', 'sidebarAutoCompleteEnabled'],
['SidebarDropDownListEnabled', 'sidebarDropDownListEnabled'],
['SidebarLimitToItemsIownCheckboxEnabled', 'sidebarLimitToItemsIOwnCheckboxEnabled'],
['SingleSearchResultShortcutEnabled', 'singleSearchResultShortcutEnabled'],
['SpellCorrectKnowledgeSearchEnabled', 'spellCorrectKnowledgeSearchEnabled'],
['AnalyticsSharingEnable', 'analyticsSharingEnable'],
['DisableParallelApexTesting', 'enableDisableParallelApexTesting'],
['EnhancedEmailEnabled', 'enableEnhancedEmailEnabled'],
['EventLogWaveIntegEnabled', 'enableEventLogWaveIntegration'],
['SendThroughGmailPref', 'enableSendThroughGmailPref'],
['Translation', 'EnableTranslationWorkbench'],
['S1OfflinePref', 'enableS1OfflinePref'],
['S1EncryptedStoragePref2', 'enableS1EncryptedStoragePref2'],
['OfflineDraftsEnabled', 'enableOfflineDraftsEnabled'],
['AsyncSaveEnabled', 'asyncSaveEnabled'],
['ChatterEnabled', 'enableChatter'],
['SelfSetPasswordInApi', 'selfSetPasswordInApi'],
['SocialProfilesEnable', 'enableSocialProfiles'],
['PathAssistantsEnabled', 'pathAssistantsEnabled'],
['LoginForensicsEnabled', 'enableLoginForensics'],
['S1DesktopEnabled', 'enableS1DesktopEnabled'],
['NetworksEnabled', 'enableNetworksEnabled'],
['NotesReservedPref01', 'enableEnhancedNotes'],
['CompileOnDeploy', 'enableCompileOnDeploy'],
['VoiceEnabled', 'voiceEnabled'],
['TerritoryManagement2Enable', 'territoryManagement2Enable'],
['ApexApprovalLockUnlock', 'enableApexApprovalLockUnlock'],
]);
// this maps the old orgPreferenceSettings preference names to the
// new preference names
const orgPreferenceSettingsPrefNameMigrateMap = new Map([
['apexApprovalLockUnlock', 'enableApexApprovalLockUnlock'],
['b2bmaAppEnabled', 'enableB2bmaAppEnabled'],
['callDispositionEnabled', 'enableCallDisposition'],
['chatterEnabled', 'enableChatter'],
['compileOnDeploy', 'enableCompileOnDeploy'],
['consentManagementEnabled', 'enableConsentManagement'],
['contentSniffingProtection', 'enableContentSniffingProtection'],
['deleteMonitoringDataEnabled', 'enableDeleteMonitoringData'],
['disableParallelApexTesting', 'enableDisableParallelApexTesting'],
['enhancedEmailEnabled', 'enableEnhancedEmailEnabled'],
['eventLogWaveIntegEnabled', 'enableEventLogWaveIntegration'],
['hstsSitesCommunities', 'hstsOnForecomSites'],
['localNames', 'enableLocalNamesForStdObjects'],
['loginForensicsEnabled', 'enableLoginForensics'],
['networksEnabled', 'enableNetworksEnabled'],
['notesReservedPref01', 'enableEnhancedNotes'],
['offlineDraftsEnabled', 'enableOfflineDraftsEnabled'],
['packaging2', 'enablePackaging2'],
['pathAssistantsEnabled', 'pathAssistantEnabled'],
['pRMAccRelPref', 'enablePRMAccRelPref'],
['pardotAppV1Enabled', 'enablePardotAppV1Enabled'],
['pardotEmbeddedAnalyticsPref', 'enableEngagementHistoryDashboards'],
['pardotEnabled', 'enablePardotEnabled'],
['portalUserShareOnCase', 'enablePortalUserCaseSharing'],
['removeThemeBrandBanner', 'enableRemoveThemeBrandBanner'],
['s1OfflinePref', 'enableS1OfflinePref'],
['s1DesktopEnabled', 'enableS1DesktopEnabled'],
['s1EncryptedStoragePref2', 'enableS1EncryptedStoragePref2'],
['scratchOrgManagementPref', 'enableScratchOrgManagementPref'],
['shapeExportPref', 'enableShapeExportPref'],
['selfSetPasswordInApi', 'enableSetPasswordInApi'],
['sendThroughGmailPref', 'enableSendThroughGmailPref'],
['socialProfilesEnable', 'enableSocialProfiles'],
['territoryManagement2Enable', 'enableTerritoryManagement2'],
['translation', 'enableTranslationWorkbench'],
['upgradeInsecureRequestsPref', 'enableUpgradeInsecureRequestsPref'],
['useLanguageFallback', 'useLanguageFallback'],
['usePathCollapsedUserPref', 'canOverrideAutoPathCollapseWithUserPref'],
['usersAreLightningOnly', 'enableUsersAreLightningOnly'],
['verifyOn2faRegistration', 'identityConfirmationOnTwoFactorRegistrationEnabled'],
['verifyOnEmailChange', 'identityConfirmationOnEmailChange'],
['voiceCallListEnabled', 'enableVoiceCallList'],
['voiceCallRecordingEnabled', 'enableVoiceCallRecording'],
['voiceCoachingEnabled', 'enableVoiceCoaching'],
['voiceConferencingEnabled', 'enableVoiceConferencing'],
['voiceEnabled', 'voiceEnabled'],
['voiceLocalPresenceEnabled', 'enableVoiceLocalPresence'],
['voiceMailDropEnabled', 'enableVoiceMailDrop'],
['voiceMailEnabled', 'enableVoiceMail'],
['xssProtection', 'enableXssProtection'],
]);
// this maps the old orgPreferenceSettings preferences
// (using their new names) to their proper settings types
const orgPreferenceSettingsTypeMigrateMap = new Map([
['activityAnalyticsEnabled', DeprecatedSettingsApi],
['analyticsSharingEnable', DeprecatedSettingsApi],
['canOverrideAutoPathCollapseWithUserPref', PathAssistantSettingsApi],
['channelAccountHierarchyPref', DeprecatedSettingsApi],
['dialerBasicEnabled', DeprecatedSettingsApi],
['enableApexApprovalLockUnlock', ApexSettingsApi],
['enableB2bmaAppEnabled', PardotSettingsApi],
['enableCallDisposition', VoiceSettingsApi],
['enableChatter', ChatterSettingsApi],
['enableCompileOnDeploy', ApexSettingsApi],
['enableConsentManagement', PartyDataModelSettingsApi],
['enableContentSniffingProtection', SecuritySessionSettingsApi],
['enableDeleteMonitoringData', EventSettingsApi],
['enableDisableParallelApexTesting', ApexSettingsApi],
['enableEngagementHistoryDashboards', PardotSettingsApi],
['enableEnhancedEmailEnabled', EmailAdministrationSettingsApi],
['enableEnhancedNotes', EnhancedNotesSettingsApi],
['enableEventLogWaveIntegration', EventSettingsApi],
['enableLocalNamesForStdObjects', LanguageSettingsApi],
['enableLoginForensics', EventSettingsApi],
['enableNetworksEnabled', CommunitiesSettingsApi],
['enablePackaging2', DevHubSettingsApi],
['enablePardotAppV1Enabled', PardotSettingsApi],
['enablePardotEnabled', PardotSettingsApi],
['enablePortalUserCaseSharing', SharingSettingsApi],
['enablePRMAccRelPref', CommunitiesSettingsApi],
['enableRemoveThemeBrandBanner', LightningExperienceSettingsApi],
['enableOfflineDraftsEnabled', MobileSettingsApi],
['enableS1OfflinePref', MobileSettingsApi],
['enableS1DesktopEnabled', LightningExperienceSettingsApi],
['enableS1EncryptedStoragePref2', MobileSettingsApi],
['enableScratchOrgManagementPref', DevHubSettingsApi],
['enableShapeExportPref', DevHubSettingsApi],
['enableSendThroughGmailPref', EmailAdministrationSettingsApi],
['enableSetPasswordInApi', SecuritySettingsPasswordPoliciesApi],
['enableSocialProfiles', SocialProfileSettingsApi],
['expandedSourceTrackingPref', DeprecatedSettingsApi],
['enableTerritoryManagement2', Territory2SettingsApi],
['enableTranslationWorkbench', LanguageSettingsApi],
['enableUpgradeInsecureRequestsPref', SecuritySessionSettingsApi],
['enableUsersAreLightningOnly', LightningExperienceSettingsApi],
['enableVoiceCallList', VoiceSettingsApi],
['enableVoiceCallRecording', VoiceSettingsApi],
['enableVoiceCoaching', VoiceSettingsApi],
['enableVoiceConferencing', VoiceSettingsApi],
['enableVoiceLocalPresence', VoiceSettingsApi],
['enableVoiceMailDrop', VoiceSettingsApi],
['enableVoiceMail', VoiceSettingsApi],
['enableXssProtection', SecuritySessionSettingsApi],
['hstsOnForecomSites', SecuritySessionSettingsApi],
['identityConfirmationOnEmailChange', SecuritySessionSettingsApi],
['identityConfirmationOnTwoFactorRegistrationEnabled', SecuritySessionSettingsApi],
['pathAssistantEnabled', PathAssistantSettingsApi],
['redirectionWarning', SecuritySessionSettingsApi],
['referrerPolicy', SecuritySessionSettingsApi],
['useLanguageFallback', LanguageSettingsApi],
['voiceEnabled', DeprecatedSettingsApi],
]);
function getCurrentApiVersion(): string {
if (!currentApiVersion) {
currentApiVersion = new Config().getApiVersion();
}
return currentApiVersion;
}
// P U B L I C
// vars and functions below exposed in API
export = {
ACCOUNT_SETTINGS_API: AccountSettingsApi,
ACTIVITIES_SETTINGS_API: ActivitiesSettingsApi,
APEX_SETTINGS_API: ApexSettingsApi,
CHATTER_SETTINGS_API: ChatterSettingsApi,
CONTRACT_SETTINGS_API: ContractSettingsApi,
COMMUNITIES_SETTINGS_API: CommunitiesSettingsApi,
DEV_HUB_SETTINGS_API: DevHubSettingsApi,
EMAIL_ADMINISTRATION_SETTINGS_API: EmailAdministrationSettingsApi,
ENHANCED_NOTE_SETTINGS_API: EnhancedNotesSettingsApi,
ENTITLEMENT_SETTINGS_API: EntitlementSettingsApi,
EVENT_SETTINGS_API: EventSettingsApi,
FORECASTING_SETTINGS_API: ForecastingSettingsApi,
IDEAS_SETTINGS_API: IdeasSettingsApi,
KNOWLEDGE_SETTINGS_API: KnowledgeSettingsApi,
LANGUAGE_SETTINGS_API: LanguageSettingsApi,
LIGHTNING_EXPERIENCE_SETTINGS_API: LightningExperienceSettingsApi,
LIVE_AGENT_SETTINGS_API: LiveAgentSettingsApi,
MOBILE_SETTINGS_API: MobileSettingsApi,
NAME_SETTINGS_API: NameSettingsApi,
OPPORTUNITY_SETTINGS_API: OpportunitySettingsApi,
ORDER_SETTINGS_API: OrderSettingsApi,
ORG_PREFERENCE_SETTINGS: OrgPreferenceSettingsApi,
PRODUCT_SETTINGS_API: ProductSettingsApi,
QUOTE_SETTINGS_API: QuoteSettingsApi,
SECURITY_SETTINGS_API: SecuritySessionSettingsApi,
SEARCH_SETTINGS_API: SearchSettingsApi,
SOCIAL_PROFILE_SETTINGS_API: SocialProfileSettingsApi,
ORGANIZATION_SETTINGS_DETAIL_API: OrganizationSettingsDetailApi,
TERRITORY2_SETTINGS_API: Territory2SettingsApi,
PATH_ASSISTANT_SETTINGS_API: PathAssistantSettingsApi,
SECURITY_SETTINGS_PASSWORD_POLICY_API: SecuritySettingsPasswordPoliciesApi,
/**
* This method returns the correct name of the preference
* only if it is being migrated from the org preference settings
* to a new object.
*/
newPrefNameForOrgSettingsMigration(prefName): string {
return orgPreferenceSettingsPrefNameMigrateMap.get(prefName);
},
/**
* Does a lookup for the proper apiName for
* the given final pref name.
*/
whichApiFromFinalPrefName(prefName): string {
return orgPreferenceSettingsTypeMigrateMap.get(prefName);
},
/**
*
* Return true if this preference was deprected in the migration from org preference settings to concreate settings types.
*
* @param apiVersion
*/
isMigrationDeprecated(prefType): boolean {
return DeprecatedSettingsApi == prefType;
},
/**
* Takes in an org preference name and returns the MD-API name
*
* @param prefName The org preference name
* @returns the MDAPI name for the org preference
*/
forMdApi(prefName, apiVersion: string = getCurrentApiVersion()) {
const _apiVersion = parseInt(apiVersion, 10);
if (_apiVersion >= 47.0) {
return orgPreferenceMdMap.get(prefName);
} else {
return orgPreferenceMdMapPre47.get(prefName);
}
},
/**
* Takes in an org preference name and returns the API through which it is set
*
* @param prefName The org preference name
* @returns the API name for the org preference
*/
whichApi(prefName, apiVersion: string = getCurrentApiVersion()) {
const _apiVersion = parseInt(apiVersion, 10);
if (_apiVersion >= 47.0) {
return orgPreferenceApiMap.get(prefName);
} else {
return orgPreferenceApiMapPre47.get(prefName);
}
},
/**
* Convenience method for testing to get Org Preference Map
*
* @returns the Org Preference Map
*/
allPrefsMap(apiVersion: string = getCurrentApiVersion()) {
const _apiVersion = parseInt(apiVersion, 10);
if (_apiVersion >= 47.0) {
return orgPreferenceApiMap;
} else {
return orgPreferenceApiMapPre47;
}
},
}; | the_stack |
import { JsPsych } from "./JsPsych";
import {
repeat,
sampleWithReplacement,
sampleWithoutReplacement,
shuffle,
shuffleAlternateGroups,
} from "./modules/randomization";
import { deepCopy } from "./modules/utils";
export class TimelineNode {
// a unique ID for this node, relative to the parent
relative_id;
// store the parent for this node
parent_node;
// parameters for the trial if the node contains a trial
trial_parameters;
// parameters for nodes that contain timelines
timeline_parameters;
// stores trial information on a node that contains a timeline
// used for adding new trials
node_trial_data;
// track progress through the node
progress = <any>{
current_location: -1, // where on the timeline (which timelinenode)
current_variable_set: 0, // which set of variables to use from timeline_variables
current_repetition: 0, // how many times through the variable set on this run of the node
current_iteration: 0, // how many times this node has been revisited
done: false,
};
end_message?: string;
// constructor
constructor(private jsPsych: JsPsych, parameters, parent?, relativeID?) {
// store a link to the parent of this node
this.parent_node = parent;
// create the ID for this node
this.relative_id = typeof parent === "undefined" ? 0 : relativeID;
// check if there is a timeline parameter
// if there is, then this node has its own timeline
if (typeof parameters.timeline !== "undefined") {
// create timeline properties
this.timeline_parameters = {
timeline: [],
loop_function: parameters.loop_function,
conditional_function: parameters.conditional_function,
sample: parameters.sample,
randomize_order:
typeof parameters.randomize_order == "undefined" ? false : parameters.randomize_order,
repetitions: typeof parameters.repetitions == "undefined" ? 1 : parameters.repetitions,
timeline_variables:
typeof parameters.timeline_variables == "undefined"
? [{}]
: parameters.timeline_variables,
on_timeline_finish: parameters.on_timeline_finish,
on_timeline_start: parameters.on_timeline_start,
};
this.setTimelineVariablesOrder();
// extract all of the node level data and parameters
// but remove all of the timeline-level specific information
// since this will be used to copy things down hierarchically
var node_data = Object.assign({}, parameters);
delete node_data.timeline;
delete node_data.conditional_function;
delete node_data.loop_function;
delete node_data.randomize_order;
delete node_data.repetitions;
delete node_data.timeline_variables;
delete node_data.sample;
delete node_data.on_timeline_start;
delete node_data.on_timeline_finish;
this.node_trial_data = node_data; // store for later...
// create a TimelineNode for each element in the timeline
for (var i = 0; i < parameters.timeline.length; i++) {
// merge parameters
var merged_parameters = Object.assign({}, node_data, parameters.timeline[i]);
// merge any data from the parent node into child nodes
if (typeof node_data.data == "object" && typeof parameters.timeline[i].data == "object") {
var merged_data = Object.assign({}, node_data.data, parameters.timeline[i].data);
merged_parameters.data = merged_data;
}
this.timeline_parameters.timeline.push(
new TimelineNode(this.jsPsych, merged_parameters, this, i)
);
}
}
// if there is no timeline parameter, then this node is a trial node
else {
// check to see if a valid trial type is defined
if (typeof parameters.type === "undefined") {
console.error(
'Trial level node is missing the "type" parameter. The parameters for the node are: ' +
JSON.stringify(parameters)
);
}
// create a deep copy of the parameters for the trial
this.trial_parameters = { ...parameters };
}
}
// recursively get the next trial to run.
// if this node is a leaf (trial), then return the trial.
// otherwise, recursively find the next trial in the child timeline.
trial() {
if (typeof this.timeline_parameters == "undefined") {
// returns a clone of the trial_parameters to
// protect functions.
return deepCopy(this.trial_parameters);
} else {
if (this.progress.current_location >= this.timeline_parameters.timeline.length) {
return null;
} else {
return this.timeline_parameters.timeline[this.progress.current_location].trial();
}
}
}
markCurrentTrialComplete() {
if (typeof this.timeline_parameters === "undefined") {
this.progress.done = true;
} else {
this.timeline_parameters.timeline[this.progress.current_location].markCurrentTrialComplete();
}
}
nextRepetiton() {
this.setTimelineVariablesOrder();
this.progress.current_location = -1;
this.progress.current_variable_set = 0;
this.progress.current_repetition++;
for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
this.timeline_parameters.timeline[i].reset();
}
}
// set the order for going through the timeline variables array
setTimelineVariablesOrder() {
const timeline_parameters = this.timeline_parameters;
// check to make sure this node has variables
if (
typeof timeline_parameters === "undefined" ||
typeof timeline_parameters.timeline_variables === "undefined"
) {
return;
}
var order = [];
for (var i = 0; i < timeline_parameters.timeline_variables.length; i++) {
order.push(i);
}
if (typeof timeline_parameters.sample !== "undefined") {
if (timeline_parameters.sample.type == "custom") {
order = timeline_parameters.sample.fn(order);
} else if (timeline_parameters.sample.type == "with-replacement") {
order = sampleWithReplacement(
order,
timeline_parameters.sample.size,
timeline_parameters.sample.weights
);
} else if (timeline_parameters.sample.type == "without-replacement") {
order = sampleWithoutReplacement(order, timeline_parameters.sample.size);
} else if (timeline_parameters.sample.type == "fixed-repetitions") {
order = repeat(order, timeline_parameters.sample.size, false);
} else if (timeline_parameters.sample.type == "alternate-groups") {
order = shuffleAlternateGroups(
timeline_parameters.sample.groups,
timeline_parameters.sample.randomize_group_order
);
} else {
console.error(
'Invalid type in timeline sample parameters. Valid options for type are "custom", "with-replacement", "without-replacement", "fixed-repetitions", and "alternate-groups"'
);
}
}
if (timeline_parameters.randomize_order) {
order = shuffle(order);
}
this.progress.order = order;
}
// next variable set
nextSet() {
this.progress.current_location = -1;
this.progress.current_variable_set++;
for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
this.timeline_parameters.timeline[i].reset();
}
}
// update the current trial node to be completed
// returns true if the node is complete after advance (all subnodes are also complete)
// returns false otherwise
advance() {
const progress = this.progress;
const timeline_parameters = this.timeline_parameters;
const internal = this.jsPsych.internal;
// first check to see if done
if (progress.done) {
return true;
}
// if node has not started yet (progress.current_location == -1),
// then try to start the node.
if (progress.current_location == -1) {
// check for on_timeline_start and conditonal function on nodes with timelines
if (typeof timeline_parameters !== "undefined") {
// only run the conditional function if this is the first repetition of the timeline when
// repetitions > 1, and only when on the first variable set
if (
typeof timeline_parameters.conditional_function !== "undefined" &&
progress.current_repetition == 0 &&
progress.current_variable_set == 0
) {
internal.call_immediate = true;
var conditional_result = timeline_parameters.conditional_function();
internal.call_immediate = false;
// if the conditional_function() returns false, then the timeline
// doesn't run and is marked as complete.
if (conditional_result == false) {
progress.done = true;
return true;
}
}
// if we reach this point then the node has its own timeline and will start
// so we need to check if there is an on_timeline_start function if we are on the first variable set
if (
typeof timeline_parameters.on_timeline_start !== "undefined" &&
progress.current_variable_set == 0
) {
timeline_parameters.on_timeline_start();
}
}
// if we reach this point, then either the node doesn't have a timeline of the
// conditional function returned true and it can start
progress.current_location = 0;
// call advance again on this node now that it is pointing to a new location
return this.advance();
}
// if this node has a timeline, propogate down to the current trial.
if (typeof timeline_parameters !== "undefined") {
var have_node_to_run = false;
// keep incrementing the location in the timeline until one of the nodes reached is incomplete
while (
progress.current_location < timeline_parameters.timeline.length &&
have_node_to_run == false
) {
// check to see if the node currently pointed at is done
var target_complete = timeline_parameters.timeline[progress.current_location].advance();
if (!target_complete) {
have_node_to_run = true;
return false;
} else {
progress.current_location++;
}
}
// if we've reached the end of the timeline (which, if the code is here, we have)
// there are a few steps to see what to do next...
// first, check the timeline_variables to see if we need to loop through again
// with a new set of variables
if (progress.current_variable_set < progress.order.length - 1) {
// reset the progress of the node to be with the new set
this.nextSet();
// then try to advance this node again.
return this.advance();
}
// if we're all done with the timeline_variables, then check to see if there are more repetitions
else if (progress.current_repetition < timeline_parameters.repetitions - 1) {
this.nextRepetiton();
// check to see if there is an on_timeline_finish function
if (typeof timeline_parameters.on_timeline_finish !== "undefined") {
timeline_parameters.on_timeline_finish();
}
return this.advance();
}
// if we're all done with the repetitions...
else {
// check to see if there is an on_timeline_finish function
if (typeof timeline_parameters.on_timeline_finish !== "undefined") {
timeline_parameters.on_timeline_finish();
}
// if we're all done with the repetitions, check if there is a loop function.
if (typeof timeline_parameters.loop_function !== "undefined") {
internal.call_immediate = true;
if (timeline_parameters.loop_function(this.generatedData())) {
this.reset();
internal.call_immediate = false;
return this.parent_node.advance();
} else {
progress.done = true;
internal.call_immediate = false;
return true;
}
}
}
// no more loops on this timeline, we're done!
progress.done = true;
return true;
}
}
// check the status of the done flag
isComplete() {
return this.progress.done;
}
// getter method for timeline variables
getTimelineVariableValue(variable_name: string) {
if (typeof this.timeline_parameters == "undefined") {
return undefined;
}
var v =
this.timeline_parameters.timeline_variables[
this.progress.order[this.progress.current_variable_set]
][variable_name];
return v;
}
// recursive upward search for timeline variables
findTimelineVariable(variable_name) {
var v = this.getTimelineVariableValue(variable_name);
if (typeof v == "undefined") {
if (typeof this.parent_node !== "undefined") {
return this.parent_node.findTimelineVariable(variable_name);
} else {
return undefined;
}
} else {
return v;
}
}
// recursive downward search for active trial to extract timeline variable
timelineVariable(variable_name: string) {
if (typeof this.timeline_parameters == "undefined") {
return this.findTimelineVariable(variable_name);
} else {
// if progress.current_location is -1, then the timeline variable is being evaluated
// in a function that runs prior to the trial starting, so we should treat that trial
// as being the active trial for purposes of finding the value of the timeline variable
var loc = Math.max(0, this.progress.current_location);
// if loc is greater than the number of elements on this timeline, then the timeline
// variable is being evaluated in a function that runs after the trial on the timeline
// are complete but before advancing to the next (like a loop_function).
// treat the last active trial as the active trial for this purpose.
if (loc == this.timeline_parameters.timeline.length) {
loc = loc - 1;
}
// now find the variable
return this.timeline_parameters.timeline[loc].timelineVariable(variable_name);
}
}
// recursively get all the timeline variables for this trial
allTimelineVariables() {
var all_tvs = this.allTimelineVariablesNames();
var all_tvs_vals = <any>{};
for (var i = 0; i < all_tvs.length; i++) {
all_tvs_vals[all_tvs[i]] = this.timelineVariable(all_tvs[i]);
}
return all_tvs_vals;
}
// helper to get all the names at this stage.
allTimelineVariablesNames(so_far = []) {
if (typeof this.timeline_parameters !== "undefined") {
so_far = so_far.concat(
Object.keys(
this.timeline_parameters.timeline_variables[
this.progress.order[this.progress.current_variable_set]
]
)
);
// if progress.current_location is -1, then the timeline variable is being evaluated
// in a function that runs prior to the trial starting, so we should treat that trial
// as being the active trial for purposes of finding the value of the timeline variable
var loc = Math.max(0, this.progress.current_location);
// if loc is greater than the number of elements on this timeline, then the timeline
// variable is being evaluated in a function that runs after the trial on the timeline
// are complete but before advancing to the next (like a loop_function).
// treat the last active trial as the active trial for this purpose.
if (loc == this.timeline_parameters.timeline.length) {
loc = loc - 1;
}
// now find the variable
return this.timeline_parameters.timeline[loc].allTimelineVariablesNames(so_far);
}
if (typeof this.timeline_parameters == "undefined") {
return so_far;
}
}
// recursively get the number of **trials** contained in the timeline
// assuming that while loops execute exactly once and if conditionals
// always run
length() {
var length = 0;
if (typeof this.timeline_parameters !== "undefined") {
for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
length += this.timeline_parameters.timeline[i].length();
}
} else {
return 1;
}
return length;
}
// return the percentage of trials completed, grouped at the first child level
// counts a set of trials as complete when the child node is done
percentComplete() {
var total_trials = this.length();
var completed_trials = 0;
for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
if (this.timeline_parameters.timeline[i].isComplete()) {
completed_trials += this.timeline_parameters.timeline[i].length();
}
}
return (completed_trials / total_trials) * 100;
}
// resets the node and all subnodes to original state
// but increments the current_iteration counter
reset() {
this.progress.current_location = -1;
this.progress.current_repetition = 0;
this.progress.current_variable_set = 0;
this.progress.current_iteration++;
this.progress.done = false;
this.setTimelineVariablesOrder();
if (typeof this.timeline_parameters != "undefined") {
for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
this.timeline_parameters.timeline[i].reset();
}
}
}
// mark this node as finished
end() {
this.progress.done = true;
}
// recursively end whatever sub-node is running the current trial
endActiveNode() {
if (typeof this.timeline_parameters == "undefined") {
this.end();
this.parent_node.end();
} else {
this.timeline_parameters.timeline[this.progress.current_location].endActiveNode();
}
}
// get a unique ID associated with this node
// the ID reflects the current iteration through this node.
ID() {
var id = "";
if (typeof this.parent_node == "undefined") {
return "0." + this.progress.current_iteration;
} else {
id += this.parent_node.ID() + "-";
id += this.relative_id + "." + this.progress.current_iteration;
return id;
}
}
// get the ID of the active trial
activeID() {
if (typeof this.timeline_parameters == "undefined") {
return this.ID();
} else {
return this.timeline_parameters.timeline[this.progress.current_location].activeID();
}
}
// get all the data generated within this node
generatedData() {
return this.jsPsych.data.getDataByTimelineNode(this.ID());
}
// get all the trials of a particular type
trialsOfType(type) {
if (typeof this.timeline_parameters == "undefined") {
if (this.trial_parameters.type == type) {
return this.trial_parameters;
} else {
return [];
}
} else {
var trials = [];
for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
var t = this.timeline_parameters.timeline[i].trialsOfType(type);
trials = trials.concat(t);
}
return trials;
}
}
// add new trials to end of this timeline
insert(parameters) {
if (typeof this.timeline_parameters === "undefined") {
console.error("Cannot add new trials to a trial-level node.");
} else {
this.timeline_parameters.timeline.push(
new TimelineNode(
this.jsPsych,
{ ...this.node_trial_data, ...parameters },
this,
this.timeline_parameters.timeline.length
)
);
}
}
} | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Pricings
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface Pricings {
/**
* Security pricing configurations in the subscription
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<PricingList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PricingList>>;
/**
* Security pricing configurations in the subscription
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {PricingList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {PricingList} [result] - The deserialized result object if an error did not occur.
* See {@link PricingList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PricingList>;
list(callback: ServiceCallback<models.PricingList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PricingList>): void;
/**
* Security pricing configurations in the resource group
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<PricingList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PricingList>>;
/**
* Security pricing configurations in the resource group
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {PricingList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {PricingList} [result] - The deserialized result object if an error did not occur.
* See {@link PricingList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PricingList>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.PricingList>): void;
listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PricingList>): void;
/**
* Security pricing configuration in the subscriptionSecurity pricing
* configuration in the subscription
*
* @param {string} pricingName name of the pricing configuration
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Pricing>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getSubscriptionPricingWithHttpOperationResponse(pricingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Pricing>>;
/**
* Security pricing configuration in the subscriptionSecurity pricing
* configuration in the subscription
*
* @param {string} pricingName name of the pricing configuration
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Pricing} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Pricing} [result] - The deserialized result object if an error did not occur.
* See {@link Pricing} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getSubscriptionPricing(pricingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Pricing>;
getSubscriptionPricing(pricingName: string, callback: ServiceCallback<models.Pricing>): void;
getSubscriptionPricing(pricingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Pricing>): void;
/**
* Security pricing configuration in the subscription
*
* @param {string} pricingName name of the pricing configuration
*
* @param {object} pricing Pricing object
*
* @param {string} pricing.pricingTier Pricing tier type. Possible values
* include: 'Free', 'Standard'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Pricing>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateSubscriptionPricingWithHttpOperationResponse(pricingName: string, pricing: models.Pricing, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Pricing>>;
/**
* Security pricing configuration in the subscription
*
* @param {string} pricingName name of the pricing configuration
*
* @param {object} pricing Pricing object
*
* @param {string} pricing.pricingTier Pricing tier type. Possible values
* include: 'Free', 'Standard'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Pricing} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Pricing} [result] - The deserialized result object if an error did not occur.
* See {@link Pricing} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
updateSubscriptionPricing(pricingName: string, pricing: models.Pricing, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Pricing>;
updateSubscriptionPricing(pricingName: string, pricing: models.Pricing, callback: ServiceCallback<models.Pricing>): void;
updateSubscriptionPricing(pricingName: string, pricing: models.Pricing, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Pricing>): void;
/**
* Security pricing configuration in the resource group
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} pricingName name of the pricing configuration
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Pricing>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getResourceGroupPricingWithHttpOperationResponse(resourceGroupName: string, pricingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Pricing>>;
/**
* Security pricing configuration in the resource group
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} pricingName name of the pricing configuration
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Pricing} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Pricing} [result] - The deserialized result object if an error did not occur.
* See {@link Pricing} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getResourceGroupPricing(resourceGroupName: string, pricingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Pricing>;
getResourceGroupPricing(resourceGroupName: string, pricingName: string, callback: ServiceCallback<models.Pricing>): void;
getResourceGroupPricing(resourceGroupName: string, pricingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Pricing>): void;
/**
* Security pricing configuration in the resource group
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} pricingName name of the pricing configuration
*
* @param {object} pricing Pricing object
*
* @param {string} pricing.pricingTier Pricing tier type. Possible values
* include: 'Free', 'Standard'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Pricing>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateResourceGroupPricingWithHttpOperationResponse(resourceGroupName: string, pricingName: string, pricing: models.Pricing, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Pricing>>;
/**
* Security pricing configuration in the resource group
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} pricingName name of the pricing configuration
*
* @param {object} pricing Pricing object
*
* @param {string} pricing.pricingTier Pricing tier type. Possible values
* include: 'Free', 'Standard'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Pricing} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Pricing} [result] - The deserialized result object if an error did not occur.
* See {@link Pricing} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdateResourceGroupPricing(resourceGroupName: string, pricingName: string, pricing: models.Pricing, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Pricing>;
createOrUpdateResourceGroupPricing(resourceGroupName: string, pricingName: string, pricing: models.Pricing, callback: ServiceCallback<models.Pricing>): void;
createOrUpdateResourceGroupPricing(resourceGroupName: string, pricingName: string, pricing: models.Pricing, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Pricing>): void;
/**
* Security pricing configurations in the subscription
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<PricingList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PricingList>>;
/**
* Security pricing configurations in the subscription
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {PricingList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {PricingList} [result] - The deserialized result object if an error did not occur.
* See {@link PricingList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PricingList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.PricingList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PricingList>): void;
/**
* Security pricing configurations in the resource group
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<PricingList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PricingList>>;
/**
* Security pricing configurations in the resource group
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {PricingList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {PricingList} [result] - The deserialized result object if an error did not occur.
* See {@link PricingList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PricingList>;
listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.PricingList>): void;
listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PricingList>): void;
}
/**
* @class
* SecurityContacts
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface SecurityContacts {
/**
* Security contact configurations for the subscription
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityContactList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityContactList>>;
/**
* Security contact configurations for the subscription
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityContactList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityContactList} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityContactList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityContactList>;
list(callback: ServiceCallback<models.SecurityContactList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityContactList>): void;
/**
* Security contact configurations for the subscription
*
* @param {string} securityContactName Name of the security contact object
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityContact>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(securityContactName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityContact>>;
/**
* Security contact configurations for the subscription
*
* @param {string} securityContactName Name of the security contact object
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityContact} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityContact} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityContact} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(securityContactName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityContact>;
get(securityContactName: string, callback: ServiceCallback<models.SecurityContact>): void;
get(securityContactName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityContact>): void;
/**
* Security contact configurations for the subscription
*
* @param {string} securityContactName Name of the security contact object
*
* @param {object} securityContact Security contact object
*
* @param {string} securityContact.email The email of this security contact
*
* @param {string} [securityContact.phone] The phone number of this security
* contact
*
* @param {string} securityContact.alertNotifications Whether to send security
* alerts notifications to the security contact. Possible values include: 'On',
* 'Off'
*
* @param {string} securityContact.alertsToAdmins Whether to send security
* alerts notifications to subscription admins. Possible values include: 'On',
* 'Off'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityContact>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(securityContactName: string, securityContact: models.SecurityContact, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityContact>>;
/**
* Security contact configurations for the subscription
*
* @param {string} securityContactName Name of the security contact object
*
* @param {object} securityContact Security contact object
*
* @param {string} securityContact.email The email of this security contact
*
* @param {string} [securityContact.phone] The phone number of this security
* contact
*
* @param {string} securityContact.alertNotifications Whether to send security
* alerts notifications to the security contact. Possible values include: 'On',
* 'Off'
*
* @param {string} securityContact.alertsToAdmins Whether to send security
* alerts notifications to subscription admins. Possible values include: 'On',
* 'Off'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityContact} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityContact} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityContact} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
create(securityContactName: string, securityContact: models.SecurityContact, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityContact>;
create(securityContactName: string, securityContact: models.SecurityContact, callback: ServiceCallback<models.SecurityContact>): void;
create(securityContactName: string, securityContact: models.SecurityContact, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityContact>): void;
/**
* Security contact configurations for the subscription
*
* @param {string} securityContactName Name of the security contact object
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(securityContactName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Security contact configurations for the subscription
*
* @param {string} securityContactName Name of the security contact object
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(securityContactName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(securityContactName: string, callback: ServiceCallback<void>): void;
deleteMethod(securityContactName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Security contact configurations for the subscription
*
* @param {string} securityContactName Name of the security contact object
*
* @param {object} securityContact Security contact object
*
* @param {string} securityContact.email The email of this security contact
*
* @param {string} [securityContact.phone] The phone number of this security
* contact
*
* @param {string} securityContact.alertNotifications Whether to send security
* alerts notifications to the security contact. Possible values include: 'On',
* 'Off'
*
* @param {string} securityContact.alertsToAdmins Whether to send security
* alerts notifications to subscription admins. Possible values include: 'On',
* 'Off'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityContact>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(securityContactName: string, securityContact: models.SecurityContact, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityContact>>;
/**
* Security contact configurations for the subscription
*
* @param {string} securityContactName Name of the security contact object
*
* @param {object} securityContact Security contact object
*
* @param {string} securityContact.email The email of this security contact
*
* @param {string} [securityContact.phone] The phone number of this security
* contact
*
* @param {string} securityContact.alertNotifications Whether to send security
* alerts notifications to the security contact. Possible values include: 'On',
* 'Off'
*
* @param {string} securityContact.alertsToAdmins Whether to send security
* alerts notifications to subscription admins. Possible values include: 'On',
* 'Off'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityContact} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityContact} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityContact} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(securityContactName: string, securityContact: models.SecurityContact, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityContact>;
update(securityContactName: string, securityContact: models.SecurityContact, callback: ServiceCallback<models.SecurityContact>): void;
update(securityContactName: string, securityContact: models.SecurityContact, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityContact>): void;
/**
* Security contact configurations for the subscription
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityContactList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityContactList>>;
/**
* Security contact configurations for the subscription
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityContactList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityContactList} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityContactList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityContactList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.SecurityContactList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityContactList>): void;
}
/**
* @class
* WorkspaceSettings
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface WorkspaceSettings {
/**
* Settings about where we should store your security data and logs
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceSettingList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceSettingList>>;
/**
* Settings about where we should store your security data and logs
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceSettingList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceSettingList} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceSettingList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceSettingList>;
list(callback: ServiceCallback<models.WorkspaceSettingList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceSettingList>): void;
/**
* Settings about where we should store your security data and logs
*
* @param {string} workspaceSettingName Name of the security setting
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceSetting>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(workspaceSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceSetting>>;
/**
* Settings about where we should store your security data and logs
*
* @param {string} workspaceSettingName Name of the security setting
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceSetting} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceSetting} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceSetting} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(workspaceSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceSetting>;
get(workspaceSettingName: string, callback: ServiceCallback<models.WorkspaceSetting>): void;
get(workspaceSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceSetting>): void;
/**
* creating settings about where we should store your security data and logs
*
* @param {string} workspaceSettingName Name of the security setting
*
* @param {object} workspaceSetting Security data setting object
*
* @param {string} workspaceSetting.workspaceId The full Azure ID of the
* workspace to save the data in
*
* @param {string} workspaceSetting.scope All the VMs in this scope will send
* their security data to the mentioned workspace unless overridden by a
* setting with more specific scope
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceSetting>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(workspaceSettingName: string, workspaceSetting: models.WorkspaceSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceSetting>>;
/**
* creating settings about where we should store your security data and logs
*
* @param {string} workspaceSettingName Name of the security setting
*
* @param {object} workspaceSetting Security data setting object
*
* @param {string} workspaceSetting.workspaceId The full Azure ID of the
* workspace to save the data in
*
* @param {string} workspaceSetting.scope All the VMs in this scope will send
* their security data to the mentioned workspace unless overridden by a
* setting with more specific scope
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceSetting} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceSetting} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceSetting} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
create(workspaceSettingName: string, workspaceSetting: models.WorkspaceSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceSetting>;
create(workspaceSettingName: string, workspaceSetting: models.WorkspaceSetting, callback: ServiceCallback<models.WorkspaceSetting>): void;
create(workspaceSettingName: string, workspaceSetting: models.WorkspaceSetting, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceSetting>): void;
/**
* Settings about where we should store your security data and logs
*
* @param {string} workspaceSettingName Name of the security setting
*
* @param {object} workspaceSetting Security data setting object
*
* @param {string} workspaceSetting.workspaceId The full Azure ID of the
* workspace to save the data in
*
* @param {string} workspaceSetting.scope All the VMs in this scope will send
* their security data to the mentioned workspace unless overridden by a
* setting with more specific scope
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceSetting>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(workspaceSettingName: string, workspaceSetting: models.WorkspaceSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceSetting>>;
/**
* Settings about where we should store your security data and logs
*
* @param {string} workspaceSettingName Name of the security setting
*
* @param {object} workspaceSetting Security data setting object
*
* @param {string} workspaceSetting.workspaceId The full Azure ID of the
* workspace to save the data in
*
* @param {string} workspaceSetting.scope All the VMs in this scope will send
* their security data to the mentioned workspace unless overridden by a
* setting with more specific scope
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceSetting} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceSetting} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceSetting} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(workspaceSettingName: string, workspaceSetting: models.WorkspaceSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceSetting>;
update(workspaceSettingName: string, workspaceSetting: models.WorkspaceSetting, callback: ServiceCallback<models.WorkspaceSetting>): void;
update(workspaceSettingName: string, workspaceSetting: models.WorkspaceSetting, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceSetting>): void;
/**
* Deletes the custom workspace settings for this subscription. new VMs will
* report to the default workspace
*
* @param {string} workspaceSettingName Name of the security setting
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(workspaceSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the custom workspace settings for this subscription. new VMs will
* report to the default workspace
*
* @param {string} workspaceSettingName Name of the security setting
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(workspaceSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(workspaceSettingName: string, callback: ServiceCallback<void>): void;
deleteMethod(workspaceSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Settings about where we should store your security data and logs
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceSettingList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceSettingList>>;
/**
* Settings about where we should store your security data and logs
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceSettingList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceSettingList} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceSettingList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceSettingList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.WorkspaceSettingList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceSettingList>): void;
}
/**
* @class
* AutoProvisioningSettings
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface AutoProvisioningSettings {
/**
* Exposes the auto provisioning settings of the subscriptions
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AutoProvisioningSettingList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AutoProvisioningSettingList>>;
/**
* Exposes the auto provisioning settings of the subscriptions
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AutoProvisioningSettingList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AutoProvisioningSettingList} [result] - The deserialized result object if an error did not occur.
* See {@link AutoProvisioningSettingList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AutoProvisioningSettingList>;
list(callback: ServiceCallback<models.AutoProvisioningSettingList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AutoProvisioningSettingList>): void;
/**
* Details of a specific setting
*
* @param {string} settingName Auto provisioning setting key
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AutoProvisioningSetting>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(settingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AutoProvisioningSetting>>;
/**
* Details of a specific setting
*
* @param {string} settingName Auto provisioning setting key
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AutoProvisioningSetting} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AutoProvisioningSetting} [result] - The deserialized result object if an error did not occur.
* See {@link AutoProvisioningSetting} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(settingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AutoProvisioningSetting>;
get(settingName: string, callback: ServiceCallback<models.AutoProvisioningSetting>): void;
get(settingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AutoProvisioningSetting>): void;
/**
* Details of a specific setting
*
* @param {string} settingName Auto provisioning setting key
*
* @param {object} setting Auto provisioning setting key
*
* @param {string} setting.autoProvision Describes what kind of security agent
* provisioning action to take. Possible values include: 'On', 'Off'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AutoProvisioningSetting>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(settingName: string, setting: models.AutoProvisioningSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AutoProvisioningSetting>>;
/**
* Details of a specific setting
*
* @param {string} settingName Auto provisioning setting key
*
* @param {object} setting Auto provisioning setting key
*
* @param {string} setting.autoProvision Describes what kind of security agent
* provisioning action to take. Possible values include: 'On', 'Off'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AutoProvisioningSetting} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AutoProvisioningSetting} [result] - The deserialized result object if an error did not occur.
* See {@link AutoProvisioningSetting} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
create(settingName: string, setting: models.AutoProvisioningSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AutoProvisioningSetting>;
create(settingName: string, setting: models.AutoProvisioningSetting, callback: ServiceCallback<models.AutoProvisioningSetting>): void;
create(settingName: string, setting: models.AutoProvisioningSetting, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AutoProvisioningSetting>): void;
/**
* Exposes the auto provisioning settings of the subscriptions
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AutoProvisioningSettingList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AutoProvisioningSettingList>>;
/**
* Exposes the auto provisioning settings of the subscriptions
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AutoProvisioningSettingList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AutoProvisioningSettingList} [result] - The deserialized result object if an error did not occur.
* See {@link AutoProvisioningSettingList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AutoProvisioningSettingList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.AutoProvisioningSettingList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AutoProvisioningSettingList>): void;
}
/**
* @class
* Compliances
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface Compliances {
/**
* The Compliance scores of the specific management group.
*
* @param {string} scope Scope of the query, can be subscription
* (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
* (/providers/Microsoft.Management/managementGroups/mgName).
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ComplianceList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(scope: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ComplianceList>>;
/**
* The Compliance scores of the specific management group.
*
* @param {string} scope Scope of the query, can be subscription
* (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
* (/providers/Microsoft.Management/managementGroups/mgName).
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ComplianceList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ComplianceList} [result] - The deserialized result object if an error did not occur.
* See {@link ComplianceList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(scope: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ComplianceList>;
list(scope: string, callback: ServiceCallback<models.ComplianceList>): void;
list(scope: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ComplianceList>): void;
/**
* Details of a specific Compliance.
*
* @param {string} scope Scope of the query, can be subscription
* (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
* (/providers/Microsoft.Management/managementGroups/mgName).
*
* @param {string} complianceName name of the Compliance
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Compliance>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(scope: string, complianceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Compliance>>;
/**
* Details of a specific Compliance.
*
* @param {string} scope Scope of the query, can be subscription
* (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
* (/providers/Microsoft.Management/managementGroups/mgName).
*
* @param {string} complianceName name of the Compliance
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Compliance} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Compliance} [result] - The deserialized result object if an error did not occur.
* See {@link Compliance} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(scope: string, complianceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Compliance>;
get(scope: string, complianceName: string, callback: ServiceCallback<models.Compliance>): void;
get(scope: string, complianceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Compliance>): void;
/**
* The Compliance scores of the specific management group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ComplianceList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ComplianceList>>;
/**
* The Compliance scores of the specific management group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ComplianceList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ComplianceList} [result] - The deserialized result object if an error did not occur.
* See {@link ComplianceList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ComplianceList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.ComplianceList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ComplianceList>): void;
}
/**
* @class
* AdvancedThreatProtection
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface AdvancedThreatProtection {
/**
* Gets the Advanced Threat Protection settings for the specified resource.
*
* @param {string} resourceId The identifier of the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AdvancedThreatProtectionSetting>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AdvancedThreatProtectionSetting>>;
/**
* Gets the Advanced Threat Protection settings for the specified resource.
*
* @param {string} resourceId The identifier of the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AdvancedThreatProtectionSetting} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AdvancedThreatProtectionSetting} [result] - The deserialized result object if an error did not occur.
* See {@link AdvancedThreatProtectionSetting} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AdvancedThreatProtectionSetting>;
get(resourceId: string, callback: ServiceCallback<models.AdvancedThreatProtectionSetting>): void;
get(resourceId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AdvancedThreatProtectionSetting>): void;
/**
* Creates or updates the Advanced Threat Protection settings on a specified
* resource.
*
* @param {string} resourceId The identifier of the resource.
*
* @param {object} advancedThreatProtectionSetting Advanced Threat Protection
* Settings
*
* @param {boolean} [advancedThreatProtectionSetting.isEnabled] Indicates
* whether Advanced Threat Protection is enabled.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AdvancedThreatProtectionSetting>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(resourceId: string, advancedThreatProtectionSetting: models.AdvancedThreatProtectionSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AdvancedThreatProtectionSetting>>;
/**
* Creates or updates the Advanced Threat Protection settings on a specified
* resource.
*
* @param {string} resourceId The identifier of the resource.
*
* @param {object} advancedThreatProtectionSetting Advanced Threat Protection
* Settings
*
* @param {boolean} [advancedThreatProtectionSetting.isEnabled] Indicates
* whether Advanced Threat Protection is enabled.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AdvancedThreatProtectionSetting} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AdvancedThreatProtectionSetting} [result] - The deserialized result object if an error did not occur.
* See {@link AdvancedThreatProtectionSetting} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
create(resourceId: string, advancedThreatProtectionSetting: models.AdvancedThreatProtectionSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AdvancedThreatProtectionSetting>;
create(resourceId: string, advancedThreatProtectionSetting: models.AdvancedThreatProtectionSetting, callback: ServiceCallback<models.AdvancedThreatProtectionSetting>): void;
create(resourceId: string, advancedThreatProtectionSetting: models.AdvancedThreatProtectionSetting, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AdvancedThreatProtectionSetting>): void;
}
/**
* @class
* Settings
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface Settings {
/**
* Settings about different configurations in security center
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SettingsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SettingsList>>;
/**
* Settings about different configurations in security center
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SettingsList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SettingsList} [result] - The deserialized result object if an error did not occur.
* See {@link SettingsList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SettingsList>;
list(callback: ServiceCallback<models.SettingsList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SettingsList>): void;
/**
* Settings of different configurations in security center
*
* @param {string} settingName Name of setting. Possible values include:
* 'MCAS', 'WDATP'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Setting>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(settingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Setting>>;
/**
* Settings of different configurations in security center
*
* @param {string} settingName Name of setting. Possible values include:
* 'MCAS', 'WDATP'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Setting} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Setting} [result] - The deserialized result object if an error did not occur.
* See {@link Setting} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(settingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Setting>;
get(settingName: string, callback: ServiceCallback<models.Setting>): void;
get(settingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Setting>): void;
/**
* updating settings about different configurations in security center
*
* @param {string} settingName Name of setting. Possible values include:
* 'MCAS', 'WDATP'
*
* @param {object} setting Setting object
*
* @param {string} setting.kind Polymorphic Discriminator
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Setting>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(settingName: string, setting: models.Setting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Setting>>;
/**
* updating settings about different configurations in security center
*
* @param {string} settingName Name of setting. Possible values include:
* 'MCAS', 'WDATP'
*
* @param {object} setting Setting object
*
* @param {string} setting.kind Polymorphic Discriminator
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Setting} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Setting} [result] - The deserialized result object if an error did not occur.
* See {@link Setting} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(settingName: string, setting: models.Setting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Setting>;
update(settingName: string, setting: models.Setting, callback: ServiceCallback<models.Setting>): void;
update(settingName: string, setting: models.Setting, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Setting>): void;
/**
* Settings about different configurations in security center
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SettingsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SettingsList>>;
/**
* Settings about different configurations in security center
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SettingsList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SettingsList} [result] - The deserialized result object if an error did not occur.
* See {@link SettingsList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SettingsList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.SettingsList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SettingsList>): void;
}
/**
* @class
* InformationProtectionPolicies
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface InformationProtectionPolicies {
/**
* Details of the information protection policy.
*
* @param {string} scope Scope of the query, can be subscription
* (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
* (/providers/Microsoft.Management/managementGroups/mgName).
*
* @param {string} informationProtectionPolicyName Name of the information
* protection policy. Possible values include: 'effective', 'custom'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<InformationProtectionPolicy>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(scope: string, informationProtectionPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.InformationProtectionPolicy>>;
/**
* Details of the information protection policy.
*
* @param {string} scope Scope of the query, can be subscription
* (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
* (/providers/Microsoft.Management/managementGroups/mgName).
*
* @param {string} informationProtectionPolicyName Name of the information
* protection policy. Possible values include: 'effective', 'custom'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {InformationProtectionPolicy} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {InformationProtectionPolicy} [result] - The deserialized result object if an error did not occur.
* See {@link InformationProtectionPolicy} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(scope: string, informationProtectionPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.InformationProtectionPolicy>;
get(scope: string, informationProtectionPolicyName: string, callback: ServiceCallback<models.InformationProtectionPolicy>): void;
get(scope: string, informationProtectionPolicyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.InformationProtectionPolicy>): void;
/**
* Details of the information protection policy.
*
* @param {string} scope Scope of the query, can be subscription
* (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
* (/providers/Microsoft.Management/managementGroups/mgName).
*
* @param {string} informationProtectionPolicyName Name of the information
* protection policy. Possible values include: 'effective', 'custom'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<InformationProtectionPolicy>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(scope: string, informationProtectionPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.InformationProtectionPolicy>>;
/**
* Details of the information protection policy.
*
* @param {string} scope Scope of the query, can be subscription
* (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
* (/providers/Microsoft.Management/managementGroups/mgName).
*
* @param {string} informationProtectionPolicyName Name of the information
* protection policy. Possible values include: 'effective', 'custom'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {InformationProtectionPolicy} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {InformationProtectionPolicy} [result] - The deserialized result object if an error did not occur.
* See {@link InformationProtectionPolicy} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(scope: string, informationProtectionPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.InformationProtectionPolicy>;
createOrUpdate(scope: string, informationProtectionPolicyName: string, callback: ServiceCallback<models.InformationProtectionPolicy>): void;
createOrUpdate(scope: string, informationProtectionPolicyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.InformationProtectionPolicy>): void;
/**
* Information protection policies of a specific management group.
*
* @param {string} scope Scope of the query, can be subscription
* (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
* (/providers/Microsoft.Management/managementGroups/mgName).
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<InformationProtectionPolicyList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(scope: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.InformationProtectionPolicyList>>;
/**
* Information protection policies of a specific management group.
*
* @param {string} scope Scope of the query, can be subscription
* (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group
* (/providers/Microsoft.Management/managementGroups/mgName).
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {InformationProtectionPolicyList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {InformationProtectionPolicyList} [result] - The deserialized result object if an error did not occur.
* See {@link InformationProtectionPolicyList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(scope: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.InformationProtectionPolicyList>;
list(scope: string, callback: ServiceCallback<models.InformationProtectionPolicyList>): void;
list(scope: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.InformationProtectionPolicyList>): void;
/**
* Information protection policies of a specific management group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<InformationProtectionPolicyList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.InformationProtectionPolicyList>>;
/**
* Information protection policies of a specific management group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {InformationProtectionPolicyList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {InformationProtectionPolicyList} [result] - The deserialized result object if an error did not occur.
* See {@link InformationProtectionPolicyList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.InformationProtectionPolicyList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.InformationProtectionPolicyList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.InformationProtectionPolicyList>): void;
}
/**
* @class
* Operations
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface Operations {
/**
* Exposes all available operations for discovery purposes.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationList>>;
/**
* Exposes all available operations for discovery purposes.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationList} [result] - The deserialized result object if an error did not occur.
* See {@link OperationList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationList>;
list(callback: ServiceCallback<models.OperationList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationList>): void;
/**
* Exposes all available operations for discovery purposes.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationList>>;
/**
* Exposes all available operations for discovery purposes.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationList} [result] - The deserialized result object if an error did not occur.
* See {@link OperationList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.OperationList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationList>): void;
}
/**
* @class
* Locations
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface Locations {
/**
* The location of the responsible ASC of the specific subscription (home
* region). For each subscription there is only one responsible location. The
* location in the response should be used to read or write other resources in
* ASC according to their ID.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AscLocationList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AscLocationList>>;
/**
* The location of the responsible ASC of the specific subscription (home
* region). For each subscription there is only one responsible location. The
* location in the response should be used to read or write other resources in
* ASC according to their ID.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AscLocationList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AscLocationList} [result] - The deserialized result object if an error did not occur.
* See {@link AscLocationList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AscLocationList>;
list(callback: ServiceCallback<models.AscLocationList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AscLocationList>): void;
/**
* Details of a specific location
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AscLocation>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AscLocation>>;
/**
* Details of a specific location
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AscLocation} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AscLocation} [result] - The deserialized result object if an error did not occur.
* See {@link AscLocation} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AscLocation>;
get(callback: ServiceCallback<models.AscLocation>): void;
get(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AscLocation>): void;
/**
* The location of the responsible ASC of the specific subscription (home
* region). For each subscription there is only one responsible location. The
* location in the response should be used to read or write other resources in
* ASC according to their ID.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AscLocationList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AscLocationList>>;
/**
* The location of the responsible ASC of the specific subscription (home
* region). For each subscription there is only one responsible location. The
* location in the response should be used to read or write other resources in
* ASC according to their ID.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AscLocationList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AscLocationList} [result] - The deserialized result object if an error did not occur.
* See {@link AscLocationList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AscLocationList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.AscLocationList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AscLocationList>): void;
}
/**
* @class
* Tasks
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface Tasks {
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityTaskList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityTaskList>>;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityTaskList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityTaskList} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityTaskList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityTaskList>;
list(callback: ServiceCallback<models.SecurityTaskList>): void;
list(options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityTaskList>): void;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityTaskList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByHomeRegionWithHttpOperationResponse(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityTaskList>>;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityTaskList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityTaskList} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityTaskList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByHomeRegion(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityTaskList>;
listByHomeRegion(callback: ServiceCallback<models.SecurityTaskList>): void;
listByHomeRegion(options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityTaskList>): void;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} taskName Name of the task object, will be a GUID
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityTask>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getSubscriptionLevelTaskWithHttpOperationResponse(taskName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityTask>>;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} taskName Name of the task object, will be a GUID
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityTask} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityTask} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityTask} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getSubscriptionLevelTask(taskName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityTask>;
getSubscriptionLevelTask(taskName: string, callback: ServiceCallback<models.SecurityTask>): void;
getSubscriptionLevelTask(taskName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityTask>): void;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} taskName Name of the task object, will be a GUID
*
* @param {string} taskUpdateActionType Type of the action to do on the task.
* Possible values include: 'Activate', 'Dismiss', 'Start', 'Resolve', 'Close'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateSubscriptionLevelTaskStateWithHttpOperationResponse(taskName: string, taskUpdateActionType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} taskName Name of the task object, will be a GUID
*
* @param {string} taskUpdateActionType Type of the action to do on the task.
* Possible values include: 'Activate', 'Dismiss', 'Start', 'Resolve', 'Close'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
updateSubscriptionLevelTaskState(taskName: string, taskUpdateActionType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
updateSubscriptionLevelTaskState(taskName: string, taskUpdateActionType: string, callback: ServiceCallback<void>): void;
updateSubscriptionLevelTaskState(taskName: string, taskUpdateActionType: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityTaskList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityTaskList>>;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityTaskList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityTaskList} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityTaskList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroup(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityTaskList>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.SecurityTaskList>): void;
listByResourceGroup(resourceGroupName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityTaskList>): void;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} taskName Name of the task object, will be a GUID
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityTask>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getResourceGroupLevelTaskWithHttpOperationResponse(resourceGroupName: string, taskName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityTask>>;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} taskName Name of the task object, will be a GUID
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityTask} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityTask} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityTask} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getResourceGroupLevelTask(resourceGroupName: string, taskName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityTask>;
getResourceGroupLevelTask(resourceGroupName: string, taskName: string, callback: ServiceCallback<models.SecurityTask>): void;
getResourceGroupLevelTask(resourceGroupName: string, taskName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityTask>): void;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} taskName Name of the task object, will be a GUID
*
* @param {string} taskUpdateActionType Type of the action to do on the task.
* Possible values include: 'Activate', 'Dismiss', 'Start', 'Resolve', 'Close'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateResourceGroupLevelTaskStateWithHttpOperationResponse(resourceGroupName: string, taskName: string, taskUpdateActionType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} taskName Name of the task object, will be a GUID
*
* @param {string} taskUpdateActionType Type of the action to do on the task.
* Possible values include: 'Activate', 'Dismiss', 'Start', 'Resolve', 'Close'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
updateResourceGroupLevelTaskState(resourceGroupName: string, taskName: string, taskUpdateActionType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
updateResourceGroupLevelTaskState(resourceGroupName: string, taskName: string, taskUpdateActionType: string, callback: ServiceCallback<void>): void;
updateResourceGroupLevelTaskState(resourceGroupName: string, taskName: string, taskUpdateActionType: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityTaskList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityTaskList>>;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityTaskList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityTaskList} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityTaskList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityTaskList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.SecurityTaskList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityTaskList>): void;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityTaskList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByHomeRegionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityTaskList>>;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityTaskList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityTaskList} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityTaskList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByHomeRegionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityTaskList>;
listByHomeRegionNext(nextPageLink: string, callback: ServiceCallback<models.SecurityTaskList>): void;
listByHomeRegionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityTaskList>): void;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SecurityTaskList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecurityTaskList>>;
/**
* Recommended tasks that will help improve the security of the subscription
* proactively
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SecurityTaskList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SecurityTaskList} [result] - The deserialized result object if an error did not occur.
* See {@link SecurityTaskList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecurityTaskList>;
listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.SecurityTaskList>): void;
listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecurityTaskList>): void;
}
/**
* @class
* Alerts
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface Alerts {
/**
* List all the alerts that are associated with the subscription
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {string} [options.select] OData select. Optional.
*
* @param {string} [options.expand] OData expand. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AlertList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertList>>;
/**
* List all the alerts that are associated with the subscription
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {string} [options.select] OData select. Optional.
*
* @param {string} [options.expand] OData expand. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AlertList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AlertList} [result] - The deserialized result object if an error did not occur.
* See {@link AlertList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertList>;
list(callback: ServiceCallback<models.AlertList>): void;
list(options: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertList>): void;
/**
* List all the alerts alerts that are associated with the resource group
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {string} [options.select] OData select. Optional.
*
* @param {string} [options.expand] OData expand. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AlertList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertList>>;
/**
* List all the alerts alerts that are associated with the resource group
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {string} [options.select] OData select. Optional.
*
* @param {string} [options.expand] OData expand. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AlertList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AlertList} [result] - The deserialized result object if an error did not occur.
* See {@link AlertList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroup(resourceGroupName: string, options?: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertList>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.AlertList>): void;
listByResourceGroup(resourceGroupName: string, options: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertList>): void;
/**
* List all the alerts that are associated with the subscription that are
* stored in a specific location
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {string} [options.select] OData select. Optional.
*
* @param {string} [options.expand] OData expand. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AlertList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listSubscriptionLevelAlertsByRegionWithHttpOperationResponse(options?: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertList>>;
/**
* List all the alerts that are associated with the subscription that are
* stored in a specific location
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {string} [options.select] OData select. Optional.
*
* @param {string} [options.expand] OData expand. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AlertList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AlertList} [result] - The deserialized result object if an error did not occur.
* See {@link AlertList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listSubscriptionLevelAlertsByRegion(options?: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertList>;
listSubscriptionLevelAlertsByRegion(callback: ServiceCallback<models.AlertList>): void;
listSubscriptionLevelAlertsByRegion(options: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertList>): void;
/**
* List all the alerts that are associated with the resource group that are
* stored in a specific location
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {string} [options.select] OData select. Optional.
*
* @param {string} [options.expand] OData expand. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AlertList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listResourceGroupLevelAlertsByRegionWithHttpOperationResponse(resourceGroupName: string, options?: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertList>>;
/**
* List all the alerts that are associated with the resource group that are
* stored in a specific location
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {string} [options.select] OData select. Optional.
*
* @param {string} [options.expand] OData expand. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AlertList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AlertList} [result] - The deserialized result object if an error did not occur.
* See {@link AlertList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listResourceGroupLevelAlertsByRegion(resourceGroupName: string, options?: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertList>;
listResourceGroupLevelAlertsByRegion(resourceGroupName: string, callback: ServiceCallback<models.AlertList>): void;
listResourceGroupLevelAlertsByRegion(resourceGroupName: string, options: { filter? : string, select? : string, expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertList>): void;
/**
* Get an alert that is associated with a subscription
*
* @param {string} alertName Name of the alert object
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Alert>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getSubscriptionLevelAlertWithHttpOperationResponse(alertName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Alert>>;
/**
* Get an alert that is associated with a subscription
*
* @param {string} alertName Name of the alert object
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Alert} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Alert} [result] - The deserialized result object if an error did not occur.
* See {@link Alert} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getSubscriptionLevelAlert(alertName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Alert>;
getSubscriptionLevelAlert(alertName: string, callback: ServiceCallback<models.Alert>): void;
getSubscriptionLevelAlert(alertName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Alert>): void;
/**
* Get an alert that is associated a resource group or a resource in a resource
* group
*
* @param {string} alertName Name of the alert object
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Alert>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getResourceGroupLevelAlertsWithHttpOperationResponse(alertName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Alert>>;
/**
* Get an alert that is associated a resource group or a resource in a resource
* group
*
* @param {string} alertName Name of the alert object
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Alert} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Alert} [result] - The deserialized result object if an error did not occur.
* See {@link Alert} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getResourceGroupLevelAlerts(alertName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Alert>;
getResourceGroupLevelAlerts(alertName: string, resourceGroupName: string, callback: ServiceCallback<models.Alert>): void;
getResourceGroupLevelAlerts(alertName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Alert>): void;
/**
* Update the alert's state
*
* @param {string} alertName Name of the alert object
*
* @param {string} alertUpdateActionType Type of the action to do on the alert.
* Possible values include: 'Dismiss', 'Reactivate'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateSubscriptionLevelAlertStateWithHttpOperationResponse(alertName: string, alertUpdateActionType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Update the alert's state
*
* @param {string} alertName Name of the alert object
*
* @param {string} alertUpdateActionType Type of the action to do on the alert.
* Possible values include: 'Dismiss', 'Reactivate'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
updateSubscriptionLevelAlertState(alertName: string, alertUpdateActionType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
updateSubscriptionLevelAlertState(alertName: string, alertUpdateActionType: string, callback: ServiceCallback<void>): void;
updateSubscriptionLevelAlertState(alertName: string, alertUpdateActionType: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Update the alert's state
*
* @param {string} alertName Name of the alert object
*
* @param {string} alertUpdateActionType Type of the action to do on the alert.
* Possible values include: 'Dismiss', 'Reactivate'
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateResourceGroupLevelAlertStateWithHttpOperationResponse(alertName: string, alertUpdateActionType: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Update the alert's state
*
* @param {string} alertName Name of the alert object
*
* @param {string} alertUpdateActionType Type of the action to do on the alert.
* Possible values include: 'Dismiss', 'Reactivate'
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
updateResourceGroupLevelAlertState(alertName: string, alertUpdateActionType: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
updateResourceGroupLevelAlertState(alertName: string, alertUpdateActionType: string, resourceGroupName: string, callback: ServiceCallback<void>): void;
updateResourceGroupLevelAlertState(alertName: string, alertUpdateActionType: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* List all the alerts that are associated with the subscription
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AlertList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertList>>;
/**
* List all the alerts that are associated with the subscription
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AlertList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AlertList} [result] - The deserialized result object if an error did not occur.
* See {@link AlertList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.AlertList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertList>): void;
/**
* List all the alerts alerts that are associated with the resource group
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AlertList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertList>>;
/**
* List all the alerts alerts that are associated with the resource group
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AlertList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AlertList} [result] - The deserialized result object if an error did not occur.
* See {@link AlertList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertList>;
listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.AlertList>): void;
listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertList>): void;
/**
* List all the alerts that are associated with the subscription that are
* stored in a specific location
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AlertList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listSubscriptionLevelAlertsByRegionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertList>>;
/**
* List all the alerts that are associated with the subscription that are
* stored in a specific location
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AlertList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AlertList} [result] - The deserialized result object if an error did not occur.
* See {@link AlertList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listSubscriptionLevelAlertsByRegionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertList>;
listSubscriptionLevelAlertsByRegionNext(nextPageLink: string, callback: ServiceCallback<models.AlertList>): void;
listSubscriptionLevelAlertsByRegionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertList>): void;
/**
* List all the alerts that are associated with the resource group that are
* stored in a specific location
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AlertList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listResourceGroupLevelAlertsByRegionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertList>>;
/**
* List all the alerts that are associated with the resource group that are
* stored in a specific location
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AlertList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AlertList} [result] - The deserialized result object if an error did not occur.
* See {@link AlertList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listResourceGroupLevelAlertsByRegionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertList>;
listResourceGroupLevelAlertsByRegionNext(nextPageLink: string, callback: ServiceCallback<models.AlertList>): void;
listResourceGroupLevelAlertsByRegionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertList>): void;
}
/**
* @class
* DiscoveredSecuritySolutions
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface DiscoveredSecuritySolutions {
/**
* Gets a list of discovered Security Solutions for the subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DiscoveredSecuritySolutionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DiscoveredSecuritySolutionList>>;
/**
* Gets a list of discovered Security Solutions for the subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DiscoveredSecuritySolutionList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DiscoveredSecuritySolutionList} [result] - The deserialized result object if an error did not occur.
* See {@link DiscoveredSecuritySolutionList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DiscoveredSecuritySolutionList>;
list(callback: ServiceCallback<models.DiscoveredSecuritySolutionList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DiscoveredSecuritySolutionList>): void;
/**
* Gets a list of discovered Security Solutions for the subscription and
* location.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DiscoveredSecuritySolutionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByHomeRegionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DiscoveredSecuritySolutionList>>;
/**
* Gets a list of discovered Security Solutions for the subscription and
* location.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DiscoveredSecuritySolutionList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DiscoveredSecuritySolutionList} [result] - The deserialized result object if an error did not occur.
* See {@link DiscoveredSecuritySolutionList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByHomeRegion(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DiscoveredSecuritySolutionList>;
listByHomeRegion(callback: ServiceCallback<models.DiscoveredSecuritySolutionList>): void;
listByHomeRegion(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DiscoveredSecuritySolutionList>): void;
/**
* Gets a specific discovered Security Solution.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} discoveredSecuritySolutionName Name of a discovered security
* solution.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DiscoveredSecuritySolution>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, discoveredSecuritySolutionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DiscoveredSecuritySolution>>;
/**
* Gets a specific discovered Security Solution.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} discoveredSecuritySolutionName Name of a discovered security
* solution.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DiscoveredSecuritySolution} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DiscoveredSecuritySolution} [result] - The deserialized result object if an error did not occur.
* See {@link DiscoveredSecuritySolution} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, discoveredSecuritySolutionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DiscoveredSecuritySolution>;
get(resourceGroupName: string, discoveredSecuritySolutionName: string, callback: ServiceCallback<models.DiscoveredSecuritySolution>): void;
get(resourceGroupName: string, discoveredSecuritySolutionName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DiscoveredSecuritySolution>): void;
/**
* Gets a list of discovered Security Solutions for the subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DiscoveredSecuritySolutionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DiscoveredSecuritySolutionList>>;
/**
* Gets a list of discovered Security Solutions for the subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DiscoveredSecuritySolutionList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DiscoveredSecuritySolutionList} [result] - The deserialized result object if an error did not occur.
* See {@link DiscoveredSecuritySolutionList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DiscoveredSecuritySolutionList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.DiscoveredSecuritySolutionList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DiscoveredSecuritySolutionList>): void;
/**
* Gets a list of discovered Security Solutions for the subscription and
* location.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DiscoveredSecuritySolutionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByHomeRegionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DiscoveredSecuritySolutionList>>;
/**
* Gets a list of discovered Security Solutions for the subscription and
* location.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DiscoveredSecuritySolutionList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DiscoveredSecuritySolutionList} [result] - The deserialized result object if an error did not occur.
* See {@link DiscoveredSecuritySolutionList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByHomeRegionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DiscoveredSecuritySolutionList>;
listByHomeRegionNext(nextPageLink: string, callback: ServiceCallback<models.DiscoveredSecuritySolutionList>): void;
listByHomeRegionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DiscoveredSecuritySolutionList>): void;
}
/**
* @class
* JitNetworkAccessPolicies
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface JitNetworkAccessPolicies {
/**
* Policies for protecting resources using Just-in-Time access control.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessPoliciesList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessPoliciesList>>;
/**
* Policies for protecting resources using Just-in-Time access control.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessPoliciesList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessPoliciesList} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessPoliciesList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessPoliciesList>;
list(callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessPoliciesList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByRegionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessPoliciesList>>;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessPoliciesList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessPoliciesList} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessPoliciesList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByRegion(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessPoliciesList>;
listByRegion(callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
listByRegion(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessPoliciesList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessPoliciesList>>;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessPoliciesList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessPoliciesList} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessPoliciesList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessPoliciesList>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessPoliciesList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupAndRegionWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessPoliciesList>>;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessPoliciesList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessPoliciesList} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessPoliciesList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroupAndRegion(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessPoliciesList>;
listByResourceGroupAndRegion(resourceGroupName: string, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
listByResourceGroupAndRegion(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} jitNetworkAccessPolicyName Name of a Just-in-Time access
* configuration policy.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessPolicy>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, jitNetworkAccessPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessPolicy>>;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} jitNetworkAccessPolicyName Name of a Just-in-Time access
* configuration policy.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessPolicy} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessPolicy} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessPolicy} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, jitNetworkAccessPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessPolicy>;
get(resourceGroupName: string, jitNetworkAccessPolicyName: string, callback: ServiceCallback<models.JitNetworkAccessPolicy>): void;
get(resourceGroupName: string, jitNetworkAccessPolicyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessPolicy>): void;
/**
* Create a policy for protecting resources using Just-in-Time access control
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} jitNetworkAccessPolicyName Name of a Just-in-Time access
* configuration policy.
*
* @param {object} body
*
* @param {string} [body.kind] Kind of the resource
*
* @param {array} body.virtualMachines Configurations for
* Microsoft.Compute/virtualMachines resource type.
*
* @param {array} [body.requests]
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessPolicy>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, jitNetworkAccessPolicyName: string, body: models.JitNetworkAccessPolicy, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessPolicy>>;
/**
* Create a policy for protecting resources using Just-in-Time access control
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} jitNetworkAccessPolicyName Name of a Just-in-Time access
* configuration policy.
*
* @param {object} body
*
* @param {string} [body.kind] Kind of the resource
*
* @param {array} body.virtualMachines Configurations for
* Microsoft.Compute/virtualMachines resource type.
*
* @param {array} [body.requests]
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessPolicy} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessPolicy} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessPolicy} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, jitNetworkAccessPolicyName: string, body: models.JitNetworkAccessPolicy, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessPolicy>;
createOrUpdate(resourceGroupName: string, jitNetworkAccessPolicyName: string, body: models.JitNetworkAccessPolicy, callback: ServiceCallback<models.JitNetworkAccessPolicy>): void;
createOrUpdate(resourceGroupName: string, jitNetworkAccessPolicyName: string, body: models.JitNetworkAccessPolicy, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessPolicy>): void;
/**
* Delete a Just-in-Time access control policy.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} jitNetworkAccessPolicyName Name of a Just-in-Time access
* configuration policy.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, jitNetworkAccessPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Delete a Just-in-Time access control policy.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} jitNetworkAccessPolicyName Name of a Just-in-Time access
* configuration policy.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, jitNetworkAccessPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, jitNetworkAccessPolicyName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, jitNetworkAccessPolicyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Initiate a JIT access from a specific Just-in-Time policy configuration.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} jitNetworkAccessPolicyName Name of a Just-in-Time access
* configuration policy.
*
* @param {object} body
*
* @param {array} body.virtualMachines A list of virtual machines & ports to
* open access for
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessRequest>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
initiateWithHttpOperationResponse(resourceGroupName: string, jitNetworkAccessPolicyName: string, body: models.JitNetworkAccessPolicyInitiateRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessRequest>>;
/**
* Initiate a JIT access from a specific Just-in-Time policy configuration.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} jitNetworkAccessPolicyName Name of a Just-in-Time access
* configuration policy.
*
* @param {object} body
*
* @param {array} body.virtualMachines A list of virtual machines & ports to
* open access for
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessRequest} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessRequest} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessRequest} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
initiate(resourceGroupName: string, jitNetworkAccessPolicyName: string, body: models.JitNetworkAccessPolicyInitiateRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessRequest>;
initiate(resourceGroupName: string, jitNetworkAccessPolicyName: string, body: models.JitNetworkAccessPolicyInitiateRequest, callback: ServiceCallback<models.JitNetworkAccessRequest>): void;
initiate(resourceGroupName: string, jitNetworkAccessPolicyName: string, body: models.JitNetworkAccessPolicyInitiateRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessRequest>): void;
/**
* Policies for protecting resources using Just-in-Time access control.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessPoliciesList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessPoliciesList>>;
/**
* Policies for protecting resources using Just-in-Time access control.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessPoliciesList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessPoliciesList} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessPoliciesList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessPoliciesList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessPoliciesList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByRegionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessPoliciesList>>;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessPoliciesList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessPoliciesList} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessPoliciesList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByRegionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessPoliciesList>;
listByRegionNext(nextPageLink: string, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
listByRegionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessPoliciesList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessPoliciesList>>;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessPoliciesList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessPoliciesList} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessPoliciesList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessPoliciesList>;
listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<JitNetworkAccessPoliciesList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupAndRegionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JitNetworkAccessPoliciesList>>;
/**
* Policies for protecting resources using Just-in-Time access control for the
* subscription, location
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {JitNetworkAccessPoliciesList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {JitNetworkAccessPoliciesList} [result] - The deserialized result object if an error did not occur.
* See {@link JitNetworkAccessPoliciesList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroupAndRegionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JitNetworkAccessPoliciesList>;
listByResourceGroupAndRegionNext(nextPageLink: string, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
listByResourceGroupAndRegionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JitNetworkAccessPoliciesList>): void;
}
/**
* @class
* ExternalSecuritySolutions
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface ExternalSecuritySolutions {
/**
* Gets a list of external security solutions for the subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ExternalSecuritySolutionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ExternalSecuritySolutionList>>;
/**
* Gets a list of external security solutions for the subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ExternalSecuritySolutionList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ExternalSecuritySolutionList} [result] - The deserialized result object if an error did not occur.
* See {@link ExternalSecuritySolutionList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ExternalSecuritySolutionList>;
list(callback: ServiceCallback<models.ExternalSecuritySolutionList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ExternalSecuritySolutionList>): void;
/**
* Gets a list of external Security Solutions for the subscription and
* location.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ExternalSecuritySolutionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByHomeRegionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ExternalSecuritySolutionList>>;
/**
* Gets a list of external Security Solutions for the subscription and
* location.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ExternalSecuritySolutionList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ExternalSecuritySolutionList} [result] - The deserialized result object if an error did not occur.
* See {@link ExternalSecuritySolutionList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByHomeRegion(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ExternalSecuritySolutionList>;
listByHomeRegion(callback: ServiceCallback<models.ExternalSecuritySolutionList>): void;
listByHomeRegion(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ExternalSecuritySolutionList>): void;
/**
* Gets a specific external Security Solution.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} externalSecuritySolutionsName Name of an external security
* solution.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ExternalSecuritySolution>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, externalSecuritySolutionsName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ExternalSecuritySolution>>;
/**
* Gets a specific external Security Solution.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} externalSecuritySolutionsName Name of an external security
* solution.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ExternalSecuritySolution} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ExternalSecuritySolution} [result] - The deserialized result object if an error did not occur.
* See {@link ExternalSecuritySolution} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, externalSecuritySolutionsName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ExternalSecuritySolution>;
get(resourceGroupName: string, externalSecuritySolutionsName: string, callback: ServiceCallback<models.ExternalSecuritySolution>): void;
get(resourceGroupName: string, externalSecuritySolutionsName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ExternalSecuritySolution>): void;
/**
* Gets a list of external security solutions for the subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ExternalSecuritySolutionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ExternalSecuritySolutionList>>;
/**
* Gets a list of external security solutions for the subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ExternalSecuritySolutionList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ExternalSecuritySolutionList} [result] - The deserialized result object if an error did not occur.
* See {@link ExternalSecuritySolutionList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ExternalSecuritySolutionList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.ExternalSecuritySolutionList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ExternalSecuritySolutionList>): void;
/**
* Gets a list of external Security Solutions for the subscription and
* location.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ExternalSecuritySolutionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByHomeRegionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ExternalSecuritySolutionList>>;
/**
* Gets a list of external Security Solutions for the subscription and
* location.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ExternalSecuritySolutionList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ExternalSecuritySolutionList} [result] - The deserialized result object if an error did not occur.
* See {@link ExternalSecuritySolutionList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByHomeRegionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ExternalSecuritySolutionList>;
listByHomeRegionNext(nextPageLink: string, callback: ServiceCallback<models.ExternalSecuritySolutionList>): void;
listByHomeRegionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ExternalSecuritySolutionList>): void;
}
/**
* @class
* Topology
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface Topology {
/**
* Gets a list that allows to build a topology view of a subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TopologyList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TopologyList>>;
/**
* Gets a list that allows to build a topology view of a subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TopologyList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TopologyList} [result] - The deserialized result object if an error did not occur.
* See {@link TopologyList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TopologyList>;
list(callback: ServiceCallback<models.TopologyList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TopologyList>): void;
/**
* Gets a list that allows to build a topology view of a subscription and
* location.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TopologyList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByHomeRegionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TopologyList>>;
/**
* Gets a list that allows to build a topology view of a subscription and
* location.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TopologyList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TopologyList} [result] - The deserialized result object if an error did not occur.
* See {@link TopologyList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByHomeRegion(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TopologyList>;
listByHomeRegion(callback: ServiceCallback<models.TopologyList>): void;
listByHomeRegion(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TopologyList>): void;
/**
* Gets a specific topology component.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} topologyResourceName Name of a topology resources
* collection.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TopologyResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, topologyResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TopologyResource>>;
/**
* Gets a specific topology component.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} topologyResourceName Name of a topology resources
* collection.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TopologyResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TopologyResource} [result] - The deserialized result object if an error did not occur.
* See {@link TopologyResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, topologyResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TopologyResource>;
get(resourceGroupName: string, topologyResourceName: string, callback: ServiceCallback<models.TopologyResource>): void;
get(resourceGroupName: string, topologyResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TopologyResource>): void;
/**
* Gets a list that allows to build a topology view of a subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TopologyList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TopologyList>>;
/**
* Gets a list that allows to build a topology view of a subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TopologyList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TopologyList} [result] - The deserialized result object if an error did not occur.
* See {@link TopologyList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TopologyList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.TopologyList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TopologyList>): void;
/**
* Gets a list that allows to build a topology view of a subscription and
* location.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TopologyList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByHomeRegionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TopologyList>>;
/**
* Gets a list that allows to build a topology view of a subscription and
* location.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TopologyList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TopologyList} [result] - The deserialized result object if an error did not occur.
* See {@link TopologyList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByHomeRegionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TopologyList>;
listByHomeRegionNext(nextPageLink: string, callback: ServiceCallback<models.TopologyList>): void;
listByHomeRegionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TopologyList>): void;
}
/**
* @class
* AllowedConnections
* __NOTE__: An instance of this class is automatically created for an
* instance of the SecurityCenter.
*/
export interface AllowedConnections {
/**
* Gets the list of all possible traffic between resources for the subscription
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AllowedConnectionsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AllowedConnectionsList>>;
/**
* Gets the list of all possible traffic between resources for the subscription
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AllowedConnectionsList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AllowedConnectionsList} [result] - The deserialized result object if an error did not occur.
* See {@link AllowedConnectionsList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AllowedConnectionsList>;
list(callback: ServiceCallback<models.AllowedConnectionsList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AllowedConnectionsList>): void;
/**
* Gets the list of all possible traffic between resources for the subscription
* and location.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AllowedConnectionsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByHomeRegionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AllowedConnectionsList>>;
/**
* Gets the list of all possible traffic between resources for the subscription
* and location.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AllowedConnectionsList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AllowedConnectionsList} [result] - The deserialized result object if an error did not occur.
* See {@link AllowedConnectionsList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByHomeRegion(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AllowedConnectionsList>;
listByHomeRegion(callback: ServiceCallback<models.AllowedConnectionsList>): void;
listByHomeRegion(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AllowedConnectionsList>): void;
/**
* Gets the list of all possible traffic between resources for the subscription
* and location, based on connection type.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} connectionType The type of allowed connections (Internal,
* External). Possible values include: 'Internal', 'External'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AllowedConnectionsResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, connectionType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AllowedConnectionsResource>>;
/**
* Gets the list of all possible traffic between resources for the subscription
* and location, based on connection type.
*
* @param {string} resourceGroupName The name of the resource group within the
* user's subscription. The name is case insensitive.
*
* @param {string} connectionType The type of allowed connections (Internal,
* External). Possible values include: 'Internal', 'External'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AllowedConnectionsResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AllowedConnectionsResource} [result] - The deserialized result object if an error did not occur.
* See {@link AllowedConnectionsResource} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, connectionType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AllowedConnectionsResource>;
get(resourceGroupName: string, connectionType: string, callback: ServiceCallback<models.AllowedConnectionsResource>): void;
get(resourceGroupName: string, connectionType: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AllowedConnectionsResource>): void;
/**
* Gets the list of all possible traffic between resources for the subscription
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AllowedConnectionsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AllowedConnectionsList>>;
/**
* Gets the list of all possible traffic between resources for the subscription
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AllowedConnectionsList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AllowedConnectionsList} [result] - The deserialized result object if an error did not occur.
* See {@link AllowedConnectionsList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AllowedConnectionsList>;
listNext(nextPageLink: string, callback: ServiceCallback<models.AllowedConnectionsList>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AllowedConnectionsList>): void;
/**
* Gets the list of all possible traffic between resources for the subscription
* and location.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AllowedConnectionsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByHomeRegionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AllowedConnectionsList>>;
/**
* Gets the list of all possible traffic between resources for the subscription
* and location.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AllowedConnectionsList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AllowedConnectionsList} [result] - The deserialized result object if an error did not occur.
* See {@link AllowedConnectionsList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByHomeRegionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AllowedConnectionsList>;
listByHomeRegionNext(nextPageLink: string, callback: ServiceCallback<models.AllowedConnectionsList>): void;
listByHomeRegionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AllowedConnectionsList>): void;
} | the_stack |
import { CSSState, CSSToken } from '../types/global/global.js'
import * as cp from './code-points.js'
import * as is from './is.js'
import * as tt from './token-types.scss.js'
const { fromCharCode } = String
/** Consumes and returns a token. [↗](https://drafts.csswg.org/css-syntax/#consume-token) */
export const consume = (
/** Condition of the current tokenizer. */
state: CSSState
) => {
switch (true) {
/* <comment-token>
/* https://drafts.csswg.org/css-syntax/#consume-comment */
case state.codeAt0 === cp.SOLIDUS:
if (state.codeAt1 === cp.ASTERISK) return consumeCommentToken(state)
break
/* <space-token>
/* https://drafts.csswg.org/css-syntax/#whitespace-token-diagram */
case is.space(state.codeAt0):
return consumeSpaceToken(state)
/* <string-token>
/* https://drafts.csswg.org/css-syntax/#string-token-diagram */
case state.codeAt0 === cp.QUOTATION_MARK:
case state.codeAt0 === cp.APOSTROPHE:
// "" || ''
return consumeStringToken(state)
/* <hash-token>
/* https://drafts.csswg.org/css-syntax/#hash-token-diagram */
case state.codeAt0 === cp.NUMBER_SIGN:
// #W
if (is.identifier(state.codeAt1)) return {
tick: state.tick,
type: tt.HASH,
code: -1,
lead: consumeAnyValue(state),
data: consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
} as CSSToken
// #\:
if (is.validEscape(state.codeAt1, state.codeAt2)) return {
tick: state.tick,
type: tt.HASH,
code: -1,
lead: consumeAnyValue(state),
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
} as CSSToken
break
/* <variable-token>
/* https://sass-lang.com/documentation/variables */
case state.codeAt0 === cp.DOLLAR_SIGN:
// $W
if (is.identifier(state.codeAt1)) return {
tick: state.tick,
type: tt.VARIABLE,
code: -1,
lead: consumeAnyValue(state),
data: consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
} as CSSToken
// $\:
if (is.validEscape(state.codeAt1, state.codeAt2)) return {
tick: state.tick,
type: tt.VARIABLE,
code: -1,
lead: consumeAnyValue(state),
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
} as CSSToken
break
/* <ident-token> */
/* https://drafts.csswg.org/css-syntax/#ident-token-diagram */
case state.codeAt0 === cp.REVERSE_SOLIDUS:
if (is.validEscape(state.codeAt0, state.codeAt1)) return consumeIdentifierLikeToken(state, {
tick: state.tick,
type: tt.WORD,
code: -1,
lead: '',
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
})
break
case is.identifierStart(state.codeAt0):
// W
return consumeIdentifierLikeToken(state, {
tick: state.tick,
type: tt.WORD,
code: -1,
lead: '',
data: consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
})
case state.codeAt0 === cp.HYPHEN_MINUS:
// -W
if (state.codeAt1 === cp.HYPHEN_MINUS || is.identifierStart(state.codeAt1)) return consumeIdentifierLikeToken(state, {
tick: state.tick,
type: tt.WORD,
code: -1,
lead: '',
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
})
// -\:
if (is.validEscape(state.codeAt1, state.codeAt2)) return consumeIdentifierLikeToken(state, {
tick: state.tick,
type: tt.WORD,
code: -1,
lead: '',
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
})
/* <number-token> */
/* https://drafts.csswg.org/css-syntax/#number-token-diagram */
// -8
if (is.digit(state.codeAt1)) return {
tick: state.tick,
type: tt.NUMBER,
code: -1,
lead: '',
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeNumberSansAdditiveValue(state),
tail: consumeNumericUnitValue(state),
} as CSSToken
// -.8
if (state.codeAt1 === cp.FULL_STOP && is.digit(state.codeAt2)) return {
tick: state.tick,
type: tt.NUMBER,
code: -1,
lead: '',
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeAnyValue(state) + consumeNumberSansDecimalValue(state),
tail: consumeNumericUnitValue(state),
} as CSSToken
case state.codeAt0 === cp.FULL_STOP:
// .8
if (is.digit(state.codeAt1)) return {
tick: state.tick,
type: tt.NUMBER,
code: -1,
lead: '',
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeNumberSansDecimalValue(state),
tail: consumeNumericUnitValue(state),
} as CSSToken
break
case state.codeAt0 === cp.PLUS_SIGN:
// +8
if (is.digit(state.codeAt1)) return {
tick: state.tick,
type: tt.NUMBER,
code: -1,
lead: '',
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeNumberSansAdditiveValue(state),
tail: consumeNumericUnitValue(state),
} as CSSToken
// +.8
if (state.codeAt1 === cp.FULL_STOP && is.digit(state.codeAt2)) return {
tick: state.tick,
type: tt.NUMBER,
code: -1,
lead: '',
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeAnyValue(state) + consumeNumberSansDecimalValue(state),
tail: consumeNumericUnitValue(state),
} as CSSToken
break
case is.digit(state.codeAt0):
// 8
return {
tick: state.tick,
type: tt.NUMBER,
code: -1,
lead: '',
data: consumeAnyValue(state) + consumeNumberSansAdditiveValue(state),
tail: consumeNumericUnitValue(state),
} as CSSToken
/* <atident-token> */
/* https://drafts.csswg.org/css-syntax/#at-keyword-token-diagram */
case state.codeAt0 === cp.COMMERCIAL_AT:
if (state.codeAt1 === cp.HYPHEN_MINUS) {
// @--
if (state.codeAt2 === cp.HYPHEN_MINUS) return {
tick: state.tick,
type: tt.ATWORD,
code: -1,
lead: consumeAnyValue(state),
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
} as CSSToken
// @-W
if (is.identifierStart(state.codeAt2)) return {
tick: state.tick,
type: tt.ATWORD,
code: -1,
lead: consumeAnyValue(state),
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
} as CSSToken
// @-\:
if (is.validEscape(state.codeAt2, state.codeAt3)) return {
tick: state.tick,
type: tt.ATWORD,
code: -1,
lead: consumeAnyValue(state),
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
} as CSSToken
}
// @W
if (is.identifierStart(state.codeAt1)) return {
tick: state.tick,
type: tt.ATWORD,
code: -1,
lead: consumeAnyValue(state),
data: consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
} as CSSToken
// @\:
if (is.validEscape(state.codeAt1, state.codeAt2)) return {
tick: state.tick,
type: tt.ATWORD,
code: -1,
lead: consumeAnyValue(state),
data: consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state),
tail: '',
} as CSSToken
break
}
/* <delim-token> */
/* https://drafts.csswg.org/css-syntax/#typedef-delim-token */
return {
tick: state.tick,
type: tt.SYMBOL,
code: state.codeAt0,
lead: '',
data: consumeAnyValue(state),
tail: '',
} as CSSToken
}
/** Consume and return a value. [↗](https://drafts.csswg.org/css-syntax/#consume-token) */
const consumeAnyValue = (state: CSSState) => {
const result = fromCharCode(state.codeAt0)
state.next()
return result
}
/** Consume and return an identifier value. [↗](https://drafts.csswg.org/css-syntax/#consume-an-identifier) */
const consumeIdentifierValue = (state: CSSState) => {
let result = ''
while (true) {
switch (true) {
case is.validEscape(state.codeAt0, state.codeAt1):
result += fromCharCode(state.codeAt0)
state.next()
case is.identifier(state.codeAt0):
result += fromCharCode(state.codeAt0)
state.next()
continue
}
break
}
return result
}
/** Consume and return an identifier or function token. [↗](https://drafts.csswg.org/css-syntax/#consume-an-identifier) */
const consumeIdentifierLikeToken = (state: CSSState, token: CSSToken) => {
if (state.codeAt0 === cp.LEFT_PARENTHESIS) {
token.code = 40
token.type = tt.FUNCTION
token.lead = token.data
token.data = '('
state.next()
}
return token
}
/** Consume and return a comment token. [↗](https://drafts.csswg.org/css-syntax/#consume-comment) */
const consumeCommentToken = (state: CSSState) => {
const token: CSSToken = {
tick: state.tick,
type: tt.COMMENT,
code: -1,
lead: '/*',
data: '',
tail: '',
}
state.next()
state.next()
while (state.tick < state.size) {
// @ts-ignore
if (state.codeAt0 === cp.ASTERISK && state.codeAt1 === cp.SOLIDUS) {
token.tail = '*/'
state.next()
state.next()
break
}
token.data += consumeAnyValue(state)
}
return token
}
/** Consumes and returns a space token. [↗](https://drafts.csswg.org/css-syntax/#whitespace-token-diagram) */
const consumeSpaceToken = (state: CSSState) => {
const token: CSSToken = {
tick: state.tick,
type: tt.SPACE,
code: -1,
lead: '',
data: consumeAnyValue(state),
tail: '',
}
while (state.tick < state.size) {
if (!is.space(state.codeAt0)) break
token.data += consumeAnyValue(state)
}
return token
}
/** Consumes and returns a string token. [↗](https://drafts.csswg.org/css-syntax/#string-token-diagram) */
const consumeStringToken = (state: CSSState) => {
const { codeAt0 } = state
const token: CSSToken = {
tick: state.tick,
type: tt.STRING,
code: -1,
lead: '',
data: consumeAnyValue(state),
tail: '',
}
while (state.tick < state.size) {
switch (true) {
case is.validEscape(state.codeAt0, state.codeAt1):
token.data += consumeAnyValue(state)
default:
token.data += consumeAnyValue(state)
continue
case state.codeAt0 === codeAt0:
token.tail = consumeAnyValue(state)
}
break
}
return token
}
/** Consumes and returns a number value after an additive symbol. [↗](https://drafts.csswg.org/css-syntax/#consume-a-number) */
export const consumeNumberSansAdditiveValue = (state: CSSState) => {
let result = ''
result += consumeDigitValue(state)
if (state.codeAt0 === cp.FULL_STOP && is.digit(state.codeAt1)) result += consumeAnyValue(state) + consumeAnyValue(state) + consumeDigitValue(state)
return result + consumeNumberSansDecimalValue(state)
}
/** Consumes and returns a number value after a decimal place. [↗](https://drafts.csswg.org/css-syntax/#consume-a-number) */
const consumeNumberSansDecimalValue = (state: CSSState) => {
let result = ''
result += consumeDigitValue(state)
if (state.codeAt0 === cp.LATIN_CAPITAL_LETTER_E || state.codeAt0 === cp.LATIN_SMALL_LETTER_E) {
switch (true) {
case (state.codeAt1 === cp.PLUS_SIGN || state.codeAt1 === cp.HYPHEN_MINUS):
if (!is.digit(state.codeAt2)) break
result += consumeAnyValue(state)
case is.digit(state.codeAt1):
result += consumeAnyValue(state) + consumeAnyValue(state) + consumeDigitValue(state)
}
}
return result
}
/** Consumes and returns a digit value. [↗](https://drafts.csswg.org/css-syntax/#consume-a-number) */
const consumeDigitValue = (state: CSSState) => {
let result = ''
while (state.tick < state.size) {
if (!is.digit(state.codeAt0)) break
result += consumeAnyValue(state)
}
return result
}
/** Consumes and returns a numeric unit value. [↗](https://drafts.csswg.org/css-syntax/#consume-an-identifier) */
const consumeNumericUnitValue = (state: CSSState) => (
state.codeAt0 === cp.HYPHEN_MINUS
? state.codeAt1 === cp.HYPHEN_MINUS
? consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state)
: is.identifierStart(state.codeAt1)
? consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state)
: is.validEscape(state.codeAt1, state.codeAt2)
? consumeAnyValue(state) + consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state)
: ''
: is.identifierStart(state.codeAt0)
? consumeAnyValue(state) + consumeIdentifierValue(state)
: is.validEscape(state.codeAt0, state.codeAt1)
? consumeAnyValue(state) + consumeAnyValue(state) + consumeIdentifierValue(state)
: ''
) | the_stack |
import { Component, NgZone, OnInit, ViewChild } from "@angular/core";
import { animate, state, style, transition, trigger } from "@angular/animations";
import { AbstractMenuPageComponent } from "~/abstract-menu-page-component";
import { RouterExtensions } from "nativescript-angular";
import { PluginInfo } from "~/shared/plugin-info";
import { PluginInfoWrapper } from "~/shared/plugin-info-wrapper";
import { AppComponent } from "~/app.component";
import {
firestore,
login as firebaseLogin,
LoginType,
logout as firebaseLogout,
User as firebaseUser
} from "nativescript-plugin-firebase";
import { ListViewEventData } from "nativescript-ui-listview";
import { Color } from "tns-core-modules/color";
import { isIOS } from "tns-core-modules/platform";
import { getBoolean, setBoolean } from "tns-core-modules/application-settings";
import { View } from "tns-core-modules/ui/core/view";
import { ad, layout } from "tns-core-modules/utils/utils";
import { prompt, PromptResult } from "tns-core-modules/ui/dialogs";
import { RadListViewComponent } from "nativescript-ui-listview/angular";
const firebase = require("nativescript-plugin-firebase/app");
declare const Crashlytics: any;
interface City {
name: string;
population: number;
author: string;
// set in the app
id?: string;
}
// Note that firebase.init runs in app.component.ts
@Component({
selector: "page-firebase",
moduleId: module.id,
templateUrl: "./firebase.component.html",
styleUrls: ["firebase-common.css"],
animations: [
trigger("from-bottom", [
state("in", style({
"opacity": 1,
transform: "translateY(0)"
})),
state("void", style({
"opacity": 0,
transform: "translateY(20%)"
})),
transition("void => *", [animate("1600ms 700ms ease-out")])
]),
trigger("fade-in", [
state("in", style({
"opacity": 1
})),
state("void", style({
"opacity": 0
})),
transition("void => *", [animate("800ms 2000ms ease-out")])
]),
trigger("scale-in", [
state("in", style({
"opacity": 1,
transform: "scale(1)"
})),
state("void", style({
"opacity": 0,
transform: "scale(0.9)"
})),
transition("void => *", [animate("1100ms ease-out")])
]),
trigger("from-right", [
state("in", style({
"opacity": 1,
transform: "translate(0)"
})),
state("void", style({
"opacity": 0,
transform: "translate(20%)"
})),
transition("void => *", [animate("600ms 1500ms ease-out")])
])
]
})
export class FirebaseComponent extends AbstractMenuPageComponent implements OnInit {
private static APP_SETTINGS_KEY_HAS_LOGGED_IN_WITH_GOOGLE = "HAS_LOGGED_IN_WITH_GOOGLE";
private citiesCollectionRef: firestore.CollectionReference;
private animationApplied = false;
private leftItem: View;
private rightItem: View;
private mainView: View;
loadingUser: boolean = true;
user: firebaseUser;
cities: Array<City>;
@ViewChild("citiesListView", {static: false}) listViewComponent: RadListViewComponent;
constructor(protected appComponent: AppComponent,
protected routerExtensions: RouterExtensions,
private zone: NgZone) {
super(appComponent, routerExtensions);
}
private getCity(cityDoc: firestore.DocumentSnapshot): City {
const city = <City>cityDoc.data();
// set the id, so we can update and delete the item more easily later on
city.id = cityDoc.id;
return city;
}
ngOnInit(): void {
this.citiesCollectionRef = firebase.firestore().collection("cities");
this.citiesCollectionRef.onSnapshot((snapshot: firestore.QuerySnapshot) => {
this.zone.run(() => {
const cities: Array<City> = [];
snapshot.forEach(docSnap => cities.push(this.getCity(docSnap)));
// case-insensitively sort alphabetically by city.name
this.cities = cities.sort((cityA, cityB) => cityA.name.toLowerCase() > cityB.name.toLowerCase() ? 1 : -1);
});
});
// if the user previously logged in with Google, try again now
if (getBoolean(FirebaseComponent.APP_SETTINGS_KEY_HAS_LOGGED_IN_WITH_GOOGLE, false)) {
this.loginWithGoogle();
} else {
this.loadingUser = false;
}
}
getAuthor(city: City): string {
if (this.user && city.author && city.author.indexOf("@gmail.com") > -1) {
return city.author === this.user.email ? "You 😍" : "A Google User";
} else {
return "Anonymous";
}
}
loginWithGoogle(): void {
this.loadingUser = true;
firebaseLogin({type: LoginType.GOOGLE})
.then(result => {
this.user = result;
this.loadingUser = false;
setBoolean(FirebaseComponent.APP_SETTINGS_KEY_HAS_LOGGED_IN_WITH_GOOGLE, true);
this.logEvent("login");
})
.catch(err => this.loadingUser = false);
}
logout(): void {
firebaseLogout()
.then(() => {
this.user = null;
setBoolean(FirebaseComponent.APP_SETTINGS_KEY_HAS_LOGGED_IN_WITH_GOOGLE, false);
})
.catch(err => console.log("Logout error: " + err));
}
fabTapped(): void {
prompt({
title: "What's the name of the city?",
okButtonText: "Confirm",
cancelButtonText: "Cancel",
cancelable: true
}).then((result: PromptResult) => {
if (result.result && result.text) {
let name = result.text.trim().length === 0 ? undefined : result.text.trim();
this.citiesCollectionRef.add(
{
name: name,
author: this.user ? this.user.email : "Anonymous"
})
.then(() => ad && ad.dismissSoftInput())
.catch(err => console.log(`Create err: ${err}`));
}
});
}
onItemLoading(args: ListViewEventData) {
args.view.backgroundColor = new Color(args.index % 2 === 0 ? "#ffa539" : "#f39c38");
}
onSwipeCellFinished(args: ListViewEventData) {
if (args.data.x > 200) {
console.log("Perform left action");
} else if (args.data.x < -200) {
console.log("Perform right action");
}
this.animationApplied = false;
}
onSwipeCellStarted(args: ListViewEventData) {
const swipeLimits = args.data.swipeLimits;
swipeLimits.threshold = args['mainView'].getMeasuredWidth() * 0.2; // 20% of whole width
swipeLimits.left = args['mainView'].getMeasuredWidth() * 0.65; // 65% of whole width
swipeLimits.right = args['mainView'].getMeasuredWidth() * 0.35; // 35% of whole width
}
onCellSwiping(args: ListViewEventData) {
const swipeView = args['swipeView'];
this.mainView = args['mainView'];
this.leftItem = swipeView.getViewById('left-stack');
this.rightItem = swipeView.getViewById('right-stack');
if (args.data.x > 0) {
const leftDimensions = View.measureChild(
<View>this.leftItem.parent,
this.leftItem,
layout.makeMeasureSpec(Math.abs(args.data.x), layout.EXACTLY),
layout.makeMeasureSpec(this.mainView.getMeasuredHeight(), layout.EXACTLY));
View.layoutChild(<View>this.leftItem.parent, this.leftItem, 0, 0, leftDimensions.measuredWidth, leftDimensions.measuredHeight);
this.hideOtherSwipeTemplateView("left");
} else {
const rightDimensions = View.measureChild(
<View>this.rightItem.parent,
this.rightItem,
layout.makeMeasureSpec(Math.abs(args.data.x), layout.EXACTLY),
layout.makeMeasureSpec(this.mainView.getMeasuredHeight(), layout.EXACTLY));
View.layoutChild(<View>this.rightItem.parent, this.rightItem, this.mainView.getMeasuredWidth() - rightDimensions.measuredWidth, 0, this.mainView.getMeasuredWidth(), rightDimensions.measuredHeight);
this.hideOtherSwipeTemplateView("right");
}
}
onLeftSwipeClick(args: ListViewEventData) {
const city = <City>args.object.bindingContext;
this.listViewComponent.listView.notifySwipeToExecuteFinished();
if (args.object.id === "btnName") {
prompt({
title: "City name",
defaultText: city.name ? city.name : "",
okButtonText: "Confirm",
cancelButtonText: "Cancel",
cancelable: true
}).then((result: PromptResult) => {
if (result.result) {
city.name = result.text.trim().length === 0 ? undefined : result.text.trim();
this.citiesCollectionRef.doc(city.id).update(
{
name: city.name,
author: this.user ? this.user.email : "Anonymous"
})
.then(() => ad && ad.dismissSoftInput())
.catch(err => console.log(`Update err: ${err}`));
}
});
} else if (args.object.id === "btnPopulation") {
prompt({
title: "City population",
defaultText: city.population ? "" + city.population : "",
okButtonText: "Confirm",
cancelButtonText: "Cancel",
cancelable: true
}).then((result: PromptResult) => {
if (result.result) {
city.population = +(result.text.trim().length === 0 ? undefined : result.text.trim());
// I need to test Crashlytics, so crashing the app when a specific population is set 👹
if (city.population === 6660666) {
this.forceCrash();
return;
}
this.citiesCollectionRef.doc(city.id).update(
{
population: city.population,
author: this.user ? this.user.email : "Anonymous"
})
.then(() => ad && ad.dismissSoftInput())
.catch(err => console.log(`Update err: ${err}`));
}
});
}
}
onRightSwipeClick(args) {
const city = <City>args.object.bindingContext;
this.listViewComponent.listView.notifySwipeToExecuteFinished();
this.citiesCollectionRef.doc(city.id).delete()
.then(() => console.log(`Delete city '${city.name}'`))
.catch(err => console.log(`Delete err: ${err}`));
}
hideOtherSwipeTemplateView(currentSwipeView: string) {
switch (currentSwipeView) {
case "left":
if (this.rightItem.getActualSize().width !== 0) {
View.layoutChild(<View>this.rightItem.parent, this.rightItem, this.mainView.getMeasuredWidth(), 0, this.mainView.getMeasuredWidth(), 0);
}
break;
case "right":
if (this.leftItem.getActualSize().width !== 0) {
View.layoutChild(<View>this.leftItem.parent, this.leftItem, 0, 0, 0, 0);
}
break;
default:
break;
}
}
protected getScreenName(): string {
return "Firebase";
}
protected getPluginInfo(): PluginInfoWrapper {
return new PluginInfoWrapper(
"Google's cloud storage product, but it can do a whole lot more! This app includes 4 of those sub modules.",
Array.of(
new PluginInfo(
"nativescript-plugin-firebase",
"Firebase",
"https://github.com/EddyVerbruggen/nativescript-plugin-firebase",
`CLOUD FIRESTORE: A flexible, scalable database which keeps your data in sync across client apps through realtime listeners and offers offline support so you can build responsive apps that work regardless of network latency or Internet connectivity.
GOOGLE AUTH: You can let your users authenticate with Firebase using their Google Accounts. This is just one of the support authentication methods Firebase offers.
ANALYTICS: Google Analytics for Firebase is a free app measurement solution that provides insight on app usage and user engagement.
CRASHLYTICS: Get clear, actionable insight into app issues with this powerful crash reporting solution.`),
new PluginInfo(
"nativescript-floatingactionbutton",
"FAB",
"https://github.com/bradmartin/nativescript-floatingactionbutton",
"Add a Material Design Floating Action Button to your page, at a corner of your liking."
),
new PluginInfo(
"nativescript-ui-listview",
"NativeScript UI ListView",
"https://www.npmjs.com/package/nativescript-ui-listview",
"The ListView is one of the components that used to be part of Progress NativeScript UI, but now lives on its own. For other components see https://www.npmjs.com/package/nativescript-pro-ui."
)
)
);
}
private forceCrash(): void {
if (isIOS) {
Crashlytics.sharedInstance().crash();
} else {
throw new java.lang.Exception("Forced an exception.");
}
}
} | the_stack |
import { IPC } from "../../ipc/client";
import {Dictionary} from "../../dictionary";
const ipc = IPC();
const Dialogs = require('dialogs');
const $ = require("jquery");
const ellipsis = require('text-ellipsis');
const electron = require('electron');
const remote = electron.remote;
const {Menu, MenuItem} = remote;
const app = remote.app;
const path = require('path');
const nativeImage = electron.nativeImage;
const storage = require('electron-json-storage');
import {WorkspaceTab, WorkspaceTabConstructor} from "./tabs/tab";
import {DefaultTab} from "./tabs/default";
import {NodeClassTab} from "./tabs/class";
import {NodeResourceTab} from "./tabs/resource";
import { ipcRenderer } from 'electron';
import {TreeView, TreeViewNode} from "./treeview";
import { NodeDump } from "../../ipc/objects";
const dialogs = Dialogs();
let renderer: WorkspaceRenderer;
let selectedNode: any = null;
function confirm(title: string): Promise<boolean>
{
return new Promise<boolean>((resolve: any) => {
dialogs.confirm(title, (result: boolean) =>
{
resolve(result);
})
});
}
function prompt(title: string, value: string): Promise<string>
{
return new Promise<string>((resolve: any) => {
dialogs.prompt(title, value, (result: string) =>
{
resolve(result);
})
});
}
class NodeItemRenderer
{
private certname: string;
private env: EnvironmentTreeItemRenderer;
private info: NodeDump;
private n_node: TreeViewNode;
private n_parent: TreeViewNode;
constructor(n_parent: TreeViewNode, env: EnvironmentTreeItemRenderer, certname: string, info: NodeDump)
{
this.certname = certname;
this.env = env;
this.info = info;
this.n_parent = n_parent;
}
public async init()
{
this.render();
}
private renderClasses(node: TreeViewNode, hieraInclude: string, hierarchyLevel: number = -1): boolean
{
const zis = this;
let hadAny: boolean = false;
const nodeClassNames = Object.keys(this.info.classes);
nodeClassNames.sort();
for (const className of nodeClassNames)
{
const classInfo = this.info.classes[className];
const iconData = classInfo != null ? classInfo.options.icon : null;
const classHieraInclude = classInfo != null ? classInfo.options["hiera_include"] : null;
if (classInfo != null && hieraInclude != classHieraInclude)
{
continue;
}
const classNode = node.addChild(
(node) =>
{
if (iconData != null)
{
node.icon = $('<img class="node-entry-icon treeview-node-offset" src="' + iconData +
'" style="width: 16px; height: 16px;">');
}
else
{
node.icon = $('<i class="node-entry-icon fas fa-puzzle-piece treeview-node-offset"></i>');
}
node.title = className;
node.leaf = true;
node.selectable = true;
node.onSelect = (node) =>
{
renderer.openTab("class", [zis.env.name, zis.certname, className]);
};
}, "class-" + this.env.name + "-" + zis.certname + "-" + className, renderer.openNodes);
if (classHieraInclude != null)
{
classNode.contextMenu([
{
label: "Remove",
click: async () =>
{
await ipc.removeHieraClassFromNode(zis.env.name, zis.certname, classHieraInclude, hierarchyLevel, className);
await renderer.refreshWorkspace();
}
}
]);
}
hadAny = true;
}
return hadAny;
}
private renderResources(node: TreeViewNode, hieraInclude: string, hierarchyLevel: number)
{
const zis = this;
const nodeResources = this.info.resources;
const nodeResourcesNames = Object.keys(nodeResources);
nodeResourcesNames.sort();
for (const definedTypeName of nodeResourcesNames)
{
const resourceType = this.info.resources[definedTypeName];
const resourceTypeInfo = resourceType.definedType;
if (resourceTypeInfo == null)
continue;
const resourceTitles = resourceType.titles;
const resourceTitleKeys = Object.keys(resourceTitles);
resourceTitleKeys.sort();
let haveAny = false;
for (const title of resourceTitleKeys)
{
const entry = resourceTitles[title];
const resourceInclude = entry.options != null ? entry.options["hiera_resources"] : null;
if (resourceInclude == hieraInclude)
{
haveAny = true;
break;
}
}
if (!haveAny)
continue;
const iconData = resourceTypeInfo != null && resourceTypeInfo.options != null ? resourceTypeInfo.options.icon : null;
const resourceNode = node.addChild(
(node) =>
{
if (iconData != null)
{
node.icon = $('<img class="node-entry-icon treeview-node-offset" src="' + iconData +
'" style="width: 16px; height: 16px;">');
}
else
{
node.icon = $('<i class="node-entry-icon fas fa-puzzle-piece treeview-node-offset"></i>');
}
node.title = definedTypeName;
node.leaf = false;
}, "resources-" + zis.env.name + "-" + zis.certname + "-" + definedTypeName, renderer.openNodes);
resourceNode.contextMenu([
{
label: "Create New Resource",
click: async () =>
{
const newTitle = await prompt("Enter a title for new resource " + definedTypeName, "");
if (newTitle == null)
return;
if (!(await ipc.createNewResourceToNode(zis.env.name, zis.certname,
hieraInclude, hierarchyLevel, definedTypeName, newTitle)))
return;
await renderer.refreshWorkspace();
await renderer.openTab("resource",
[zis.env.name, zis.certname, definedTypeName, newTitle]);
}
},
{
type: "separator"
},
{
label: "Remove All",
click: async () =>
{
await ipc.removeResourcesFromNode(zis.env.name, zis.certname,
hieraInclude, hierarchyLevel, definedTypeName);
await renderer.refreshWorkspace();
}
}
]);
for (const title of resourceTitleKeys)
{
const entry = resourceTitles[title];
const resourceInclude = entry.options != null ? entry.options["hiera_resources"] : null;
if (resourceInclude != hieraInclude)
{
continue;
}
const resourceNameNode = resourceNode.addChild(
(node) =>
{
node.icon = $('<i class="node-entry-icon far fa-clone treeview-node-offset"></i>');
node.title = title;
node.selectable = true;
node.leaf = true;
node.onSelect = (node) =>
{
renderer.openTab("resource", [zis.env.name, zis.certname, definedTypeName, title]);
};
}, "resource-" + zis.env.name + "-" + zis.certname + "-" + definedTypeName + "-" + title, renderer.openNodes);
resourceNameNode.contextMenu([
{
label: "Rename",
click: async () =>
{
const newTitle = await prompt("Enter new name for resource " + definedTypeName, title);
if (newTitle == null || newTitle == title)
return;
if (!(await ipc.renameNodeResource(zis.env.name, zis.certname,
hieraInclude, hierarchyLevel, definedTypeName, title, newTitle)))
return;
await renderer.refreshWorkspace();
}
},
{
type: "separator"
},
{
label: "Remove",
click: async () =>
{
await ipc.removeResourceFromNode(zis.env.name, zis.certname,
hieraInclude, hierarchyLevel, definedTypeName, title);
await renderer.refreshWorkspace();
}
}
]);
}
}
}
private havePuppetDefinedClasses(): boolean
{
const nodeClassNames = Object.keys(this.info.classes);
for (const className of nodeClassNames)
{
const classInfo = this.info.classes[className];
if (classInfo != null && classInfo.options["hiera_include"] == null)
{
return true;
}
}
return false;
}
private get hierarchy(): any[]
{
return this.info.hierarchy;
}
private render()
{
const zis = this;
this.n_node = this.n_parent.addChild(
(node) =>
{
node.icon = $('<i class="fa fa-server treeview-node-offset"></i>');
node.title = zis.certname;
node.selectable = false;
}, "node-" + zis.env.name + "-" + zis.certname, renderer.openNodes);
this.n_node.contextMenu([
{
label: "Ignore This Node",
click: async () =>
{
await ipc.ignoreNode(zis.certname);
await renderer.refreshWorkspace();
}
}
])
const includeNames = Object.keys(this.info.hiera_includes);
includeNames.sort();
for (const includeName of includeNames)
{
const hierarchyLevel = this.info.hiera_includes[includeName];
const nodeIcon = hierarchyLevel >= 0 ? '<span class="modified-' +
(hierarchyLevel % 12) + '"><i class="fas fa-flask treeview-node-offset"></i></span>' :
'<i class="fas fa-flask treeview-node-offset"></i>';
const nodeTitle = hierarchyLevel >= 0 ? '<span class="modified-' +
(hierarchyLevel % 12) + '">Hiera Classes [' + includeName + ']</span>' : 'Hiera Classes [' + includeName + ']';
const n_classes = this.n_node.addChild(
(node) =>
{
node.icon = $(nodeIcon);
node.title = nodeTitle;
node.emptyText = "This hiera_include has no classes";
node.leaf = false;
node.selectable = false;
}, "node-" + zis.env.name + "-" + zis.certname + "-hiera-" + includeName, renderer.openNodes);
let hierarcyName_ = "";
if (hierarchyLevel >= 0)
{
const hierarchy = zis.hierarchy[hierarchyLevel];
hierarcyName_ = hierarchy.path;
}
const hierarcyName = hierarcyName_;
const contextOptions: any = [
{
label: "Assign New Class",
click: async () =>
{
if (hierarchyLevel < 0)
{
const changed = await ipc.managePropertyHierarchy(zis.env.name, zis.certname,
includeName, "array");
if (changed)
{
await renderer.refreshWorkspace();
}
return;
}
const className = await ipc.assignNewHieraClass(
zis.env.name, zis.certname, includeName, hierarchyLevel);
if (className)
{
await renderer.refreshWorkspace();
}
}
},
{
label: "Manage Hierarchy",
click: async () =>
{
const changed = await ipc.managePropertyHierarchy(zis.env.name, zis.certname,
includeName, "array");
if (changed)
{
await renderer.refreshWorkspace();
}
}
},
{
type: "separator"
},
{
label: "Remove All Classes",
click: async () =>
{
if (!await confirm("This will completely destroy all classes defined in property \"" + includeName +
"\" on hierarchy level \"" + hierarcyName + "\". Are you sure?"))
return;
await ipc.removeNodeProperty(zis.env.name, zis.certname, hierarchyLevel, includeName);
await renderer.refreshWorkspace();
}
}
];
if (hierarchyLevel >= 0)
{
contextOptions.splice(0, 0, {
label: "Defined at: " + hierarcyName,
enabled: false
});
}
n_classes.contextMenu(contextOptions)
this.renderClasses(n_classes, includeName, hierarchyLevel);
}
const recourceIncludeNames = Object.keys(this.info.hiera_resources);
recourceIncludeNames.sort();
if (recourceIncludeNames.length > 0)
{
for (const includeName of recourceIncludeNames)
{
const hierarchyLevel = this.info.hiera_resources[includeName];
let hierarcyName_ = "";
if (hierarchyLevel >= 0)
{
const hierarchy = zis.hierarchy[hierarchyLevel];
hierarcyName_ = hierarchy.path;
}
const hierarcyName = hierarcyName_;
const nodeIcon = hierarchyLevel >= 0 ? '<span class="modified-' +
(hierarchyLevel % 12) + '"><i class="fas fa-clone treeview-node-offset"></i></span>' :
'<i class="fas fa-clone treeview-node-offset"></i>';
const nodeTitle = hierarchyLevel >= 0 ? '<span class="modified-' +
(hierarchyLevel % 12) + '">Hiera Resources [' + includeName + ']</span>' : 'Hiera Resources [' + includeName + ']';
const n_resources = this.n_node.addChild(
(node) =>
{
node.icon = $(nodeIcon);
node.title = nodeTitle;
node.emptyText = "Node has no resources";
node.leaf = false;
node.selectable = false;
}, "node-" + zis.env.name + "-" + zis.certname + "-resources", renderer.openNodes);
const contextOptions: any[] = [
{
label: "Create New Resource",
click: async () =>
{
if (hierarchyLevel < 0)
{
const changed = await ipc.managePropertyHierarchy(zis.env.name, zis.certname,
includeName, "object");
if (changed)
{
await renderer.refreshWorkspace();
}
return;
}
const definedTypeName = await ipc.chooseDefinedType(zis.env.name, zis.certname);
if (!definedTypeName)
return;
const newTitle = await prompt("Enter a title for new resource " + definedTypeName, "");
if (newTitle == null)
return;
if (!(await ipc.createNewResourceToNode(zis.env.name, zis.certname,
includeName, hierarchyLevel, definedTypeName, newTitle)))
return;
await renderer.refreshWorkspace();
await renderer.openTab("resource",
[zis.env.name, zis.certname, definedTypeName, newTitle]);
}
},
{
label: "Manage Hierarchy",
click: async () =>
{
const changed = await ipc.managePropertyHierarchy(zis.env.name, zis.certname,
includeName, "object");
if (changed)
{
await renderer.refreshWorkspace();
}
}
},
{
type: "separator"
},
{
label: "Remove All Resources",
click: async () =>
{
if (!await confirm("This will completely destroy all resources defined in property \"" + includeName +
"\" on hierarchy level \"" + hierarcyName + "\". Are you sure?"))
return;
await ipc.removeAllResourcesFromNode(zis.env.name, zis.certname, includeName, hierarchyLevel);
await renderer.refreshWorkspace();
}
}
];
if (hierarchyLevel >= 0)
{
contextOptions.splice(0, 0, {
label: "Defined at: " + hierarcyName,
enabled: false
});
}
n_resources.contextMenu(contextOptions);
this.renderResources(n_resources, includeName, hierarchyLevel);
}
}
if (this.havePuppetDefinedClasses())
{
const n_classes = this.n_node.addChild(
(node) =>
{
node.icon = $('<i class="ic ic-puppet treeview-node-offset"></i>');
node.title = "Puppet Defined Classes";
node.emptyText = "Node has no classes";
node.leaf = false;
node.selectable = false;
}, "node-" + zis.env.name + "-" + zis.certname + "-classes", renderer.openNodes);
this.renderClasses(n_classes, null);
}
/*
const n_facts = this.n_node.addChild(
(node) =>
{
node.icon = $('<i class="fas fa-bars treeview-node-offset"></i>');
node.title = "Facts";
node.leaf = true;
node.selectable = true;
node.onSelect = (node: TreeViewNode) =>
{
renderer.openTab("facts", [zis.localPath]);
};
}, "node-" + zis.localPath + "-facts", renderer.openNodes);
n_facts.contextMenu([
{
label: "About Facts",
click: async () => {
alert('This page can configure fake facts for this node, thus allowing to resolve ' +
'defaults correctly. For example, addting a variable with name \"hostname\" will implement the ${hostname} variable ' +
'in Puppet accordingly.');
}
}
])
*/
}
}
class EnvironmentTreeItemRenderer
{
public nodes: Dictionary<string, NodeItemRenderer>;
public renderer: WorkspaceRenderer;
public name: string;
private n_environment: TreeViewNode;
private readonly n_treeView: TreeViewNode;
constructor(renderer: WorkspaceRenderer, name: string, treeView: TreeViewNode)
{
this.renderer = renderer;
this.name = name;
this.nodes = new Dictionary();
this.n_treeView = treeView;
this.render();
}
private render()
{
const zis = this;
this.n_environment = this.n_treeView.addChild(
(node) =>
{
node.title = zis.name;
node.bold = true;
node.emptyText = "No nodes";
node.icon = $('<i class="ic ic-environment treeview-node-offset"/></i>');
}, "environment-" + this.name, renderer.openNodes);
this.n_environment.contextMenu([
/*
{
label: "New Node",
click: async () =>
{
const nodeName = await prompt("Enter a cert name for new node", "");
if (nodeName == null || nodeName.length == 0)
return;
if (!await ipc.createNode(zis.name, nodeName))
{
alert("Failed to create a node");
return;
}
await renderer.refresh();
}
},
{
type: "separator"
},
*/
{
label: "Delete",
click: async () =>
{
if (!await confirm("Are you sure you would like to delete this environment?"))
return;
if (!await ipc.removeEnvironment(zis.name))
{
return;
}
await renderer.refresh();
}
}
]);
}
public async init()
{
const tree = await ipc.getEnvironmentTree(this.name);
const nodes = tree.nodes;
const warnings = tree.warnings;
for (const certname in nodes)
{
const info = nodes[certname];
const itemRenderer = new NodeItemRenderer(this.n_environment, this, certname, info);
this.nodes.put(certname, itemRenderer);
await itemRenderer.init();
}
if (warnings.length > 0)
{
const warningsNode = this.n_environment.addChild(
(node) =>
{
node.title = "Warnings (" + warnings.length + ")";
node.leaf = true;
node.icon = $('<i class="fas fa-exclamation-triangle text-warning treeview-node-offset"></i>');
}, "environment-warnings-" + this.name, renderer.openNodes);
warningsNode.click(() =>
{
$('#warnings-modal-label').text("Warnings of " + this.name + " (" + warnings.length + ")");
const body = $('#warnings-modal-body').html('');
for (const warning of warnings)
{
const div = $('<div></div>').appendTo(body);
$('<p><i class="fas fa-exclamation-triangle text-warning"></i> ' + warning.title + '</p>').appendTo(div);
$('<p style="white-space: pre-line; overflow: auto;"></p>').appendTo(div).text(warning.message);
}
$('#warnings-modal').modal();
});
}
}
}
class EnvironmentModulesRenderer
{
private renderer: WorkspaceRenderer;
private modules: any;
private name: string;
private n_modules: TreeViewNode;
private readonly n_treeView: TreeViewNode;
constructor(renderer: WorkspaceRenderer, name: string, treeView: TreeViewNode)
{
this.renderer = renderer;
this.name = name;
this.n_treeView = treeView;
this.render();
}
private render()
{
const zis = this;
this.n_modules = this.n_treeView.addChild(
(node) =>
{
node.title = zis.global ? "global" : zis.name;
node.bold = true;
node.emptyText = "No modules";
node.icon = $(zis.global ? '<i class="fas text-danger fa-sitemap treeview-node-offset"></i>' : '<i class="fas text-primary fa-sitemap"></i>');
}, this.global ? "modules" : ("modules-" + this.name), this.renderer.openNodes);
this.n_modules.contextMenu([
{
label: "Install New Module",
click: async () =>
{
//
}
}
]);
}
public get global()
{
return this.name == "";
}
public async init()
{
if (this.global)
{
this.modules = await ipc.getGlobalModules();
}
else
{
this.modules = await ipc.getEnvironmentModules(this.name);
}
const names = Object.keys(this.modules);
names.sort();
for (const moduleName of names)
{
const n_module = this.n_modules.addChild(
(node) =>
{
node.title = moduleName;
node.bold = false;
node.leaf = true;
node.icon = $('<i class="fas fa-folder"></i>');
}, this.global ? ("module-" + moduleName) : ("module-" + this.name + "-" + moduleName),
this.renderer.openNodes);
}
}
}
export class WorkspaceRenderer
{
settingsTimer: NodeJS.Timer;
environments: Dictionary<string, EnvironmentTreeItemRenderer>;
modules: Dictionary<string, EnvironmentModulesRenderer>;
tabs: Dictionary<string, WorkspaceTab>;
private workspaceTree: TreeView;
private modulesTree: TreeView;
private cachedClassInfo: any;
private readonly tabClasses: Dictionary<string, WorkspaceTabConstructor>;
n_editorTabs: any;
n_editorContent: any;
private _openNodes: Set<string>;
constructor()
{
this._openNodes = new Set<string>();
this.cachedClassInfo = {};
this.environments = new Dictionary();
this.modules = new Dictionary();
this.tabs = new Dictionary();
this.tabClasses = new Dictionary();
this.tabClasses.put("default", DefaultTab);
this.tabClasses.put("class", NodeClassTab);
this.tabClasses.put("resource", NodeResourceTab);
this.init();
}
public get openNodes(): Set<string>
{
return this._openNodes;
}
public async getClassInfo(env: string): Promise<any>
{
if (this.cachedClassInfo.hasOwnProperty(env))
{
return this.cachedClassInfo[env];
}
const classInfo = await ipc.getClassInfo(env);
this.cachedClassInfo[env] = classInfo;
return classInfo;
}
public async refreshModules()
{
this.modulesTree.clear();
}
public async refresh()
{
this.workspaceTree.clear();
const environments: string[] = await ipc.getEnvironmentList();
this.environments = new Dictionary();
for (const environment of environments)
{
const env = this.addEnvironment(environment);
await env.init();
}
}
private async init()
{
this.initSidebar();
WorkspaceRenderer.OpenLoading();
const path: string = await ipc.getCurrentWorkspacePath();
if (path != null)
{
document.title = ellipsis(path, 80, {side: 'start'});
}
await this.initUI();
try
{
await ipc.initWorkspace();
}
catch (e)
{
if (e.hasOwnProperty("title"))
{
WorkspaceRenderer.OpenError(e.title, e.message);
}
else
{
WorkspaceRenderer.OpenError("Failed to process the workspace", e.message);
}
return;
}
await this.initWorkspace();
await this.initModules();
await this.enable();
await this.registerCallbacks();
}
private async registerCallbacks()
{
const zis = this;
$('#workspace-menu').click(function (event: any)
{
event.preventDefault();
const contextMenu = new Menu();
const menuEntries: any[] = [
{
label: 'New Environment',
async click ()
{
const success = await ipc.createEnvironment();
if (!success)
return;
await renderer.refresh();
}
},
{
label: 'Install/Update Puppetfile modules',
async click ()
{
await ipc.installModules();
}
},
{
label: 'Refresh',
async click ()
{
await zis.refreshWorkspace();
}
},
{
label: 'Clear Node Ignore List',
async click ()
{
if (await ipc.clearIgnoreNodeList())
await zis.refreshWorkspace();
}
}
];
for (const entry of menuEntries)
{
contextMenu.append(new MenuItem(entry));
}
contextMenu.popup({window: remote.getCurrentWindow()})
});
ipcRenderer.on('refresh', async function (event: any)
{
await renderer.refresh();
});
}
private async initUI()
{
electron.ipcRenderer.on('refreshWorkspaceCategory', function(event: any, text: number, showProgress: boolean)
{
$('#loading-category').text(text);
if (showProgress)
{
$('#loading-progress-p').show();
}
else
{
$('#loading-progress-p').hide();
}
});
electron.ipcRenderer.on('refreshWorkspaceProgress', function(event: any, progress: number)
{
const p = Math.floor(progress * 100);
$('#loading-progress').css('width', "" + p + "%");
});
}
private async initWorkspace()
{
if (this.workspaceTree == null)
{
this.workspaceTree = new TreeView($('#workspace-tree'));
}
else
{
this.workspaceTree.clear();
}
this.environments.clear();
const environments: string[] = await ipc.getEnvironmentList();
for (const environment of environments)
{
const env = this.addEnvironment(environment);
await env.init();
}
}
private async initModules()
{
if (this.modulesTree == null)
{
this.modulesTree = new TreeView($('#workspace-modules'));
}
else
{
this.modulesTree.clear();
}
this.modules.clear();
{
// global modules
const modules = this.addModules("");
await modules.init();
}
const environments: string[] = await ipc.getEnvironmentList();
for (const environment of environments)
{
const modules = this.addModules(environment);
await modules.init();
}
}
public addModules(env: string): EnvironmentModulesRenderer
{
const modules = new EnvironmentModulesRenderer(this, env, this.modulesTree.root);
this.modules.put(env, modules);
return modules;
}
public addEnvironment(name: string): EnvironmentTreeItemRenderer
{
const environment = new EnvironmentTreeItemRenderer(this, name, this.workspaceTree.root);
this.environments.put(name, environment);
return environment;
}
private static OpenError(title: string, text: string)
{
$('#workspace-contents').html('<div class="vertical-center h-100"><div><p class="text-center">' +
'<span class="text text-danger"><i class="fas fa-2x fa-exclamation-triangle"></i></span></p>' +
'<p class="text-center text-danger">' +
'<span class="text text-muted" style="white-space: pre-line;" id="loading-error-title"></span></p>' +
'<p class="text-center" style="max-height: 250px; overflow-y: scroll;">' +
'<span class="text text-muted" style="white-space: pre-line;" id="loading-error-contents"></span></p></div></div>');
$('#loading-error-title').text(title);
$('#loading-error-contents').text(text);
}
private static OpenLoading()
{
$('#workspace-contents').html('<div class="vertical-center h-100"><div><p class="text-center">' +
'<span class="text text-muted"><i class="fas fa-cog fa-4x fa-spin"></i></span></p>' +
'<p class="text-center"><span class="text text-muted" style="white-space: pre-line;" id="loading-category">' +
'Please wait while the workspace is updating cache</span></p>' +
'<p class="text-center"><div class="progress" id="loading-progress-p" style="width: 400px;">' +
'<div class="progress-bar progress-bar-striped progress-bar-animated" ' +
'id="loading-progress" role="progressbar" aria-valuenow="0" ' +
'aria-valuemin="0" aria-valuemax="100" style="width:0">' +
'</div></div></p></div></div>');
}
private openEditor()
{
const root = $('#workspace-contents');
root.html('');
const contents = $('<div class="h-100 h-100" style="display: flex; overflow: hidden; ' +
'flex-direction: column;"></div>').appendTo(root);
this.n_editorTabs = $('<ul class="nav nav-tabs compact" role="tablist"></ul>').appendTo(contents);
this.n_editorContent = $('<div class="tab-content w-100 h-100 d-flex"></div>').appendTo(contents);
}
private async checkEmpty()
{
const keys = this.tabs.getKeys();
if (keys.length == 0)
{
await this.openTab("default", []);
}
else if (keys.length > 0)
{
const hasDefault = keys.indexOf("default") >= 0;
if (hasDefault && keys.length > 1)
{
await this.closeTab("default");
}
}
}
public async openTab(kind: string, path: Array<string>): Promise<any>
{
const key = path.length > 0 ? kind + "_" + path.join("_") : kind;
if (this.tabs.has(key))
{
const tab = this.tabs.get(key);
$(tab.buttonNode).find('a').tab('show');
return;
}
const fixedPath = key.replace(/:/g, '_');
const _class: WorkspaceTabConstructor = this.tabClasses.get(kind);
if (!_class)
return;
const tabButton = $('<li class="nav-item">' +
'<a class="nav-link" id="' + fixedPath + '-tab" data-toggle="tab" href="#' + fixedPath + '" ' +
'role="tab" aria-controls="' + fixedPath + '" aria-selected="false"></a>' +
'</li>').appendTo(this.n_editorTabs);
const tabContents = $('<div class="tab-pane w-100 h-100" id="' + fixedPath +
'" role="tabpanel" aria-labelledby="' + fixedPath + '-tab">' +
'</div>').appendTo(this.n_editorContent);
const _tab = new _class(path, tabButton, tabContents, this);
await _tab.init();
_tab.render();
const _a = $(tabButton).find('a');
const _icon = _tab.getIcon();
if (_icon)
{
_icon.addClass('tab-icon').appendTo(_a);
}
const shortTitle = _tab.shortTitle;
let foundOtherTabWithSameTitle = false;
for (const otherTab of this.tabs.getValues())
{
if (otherTab.shortTitle == shortTitle)
{
otherTab.changeTitle(otherTab.fullTitle);
foundOtherTabWithSameTitle = true;
break;
}
}
$('<span>' + (foundOtherTabWithSameTitle ? _tab.fullTitle : _tab.shortTitle) + '</span>').appendTo(_a);
if (_tab.canBeClosed)
{
const _i = $('<i class="fas fa-times close-btn"></i>').appendTo(_a).click(async () => {
await this.closeTab(key);
});
}
_a.tab('show').on('shown.bs.tab', async () => {
await _tab.focusIn();
});
this.tabs.put(key, _tab);
await this.checkEmpty();
}
public async closeTabKind(kind: string, path: Array<string>): Promise<boolean>
{
const key = path.length > 0 ? kind + "_" + path.join("_") : kind;
return await this.closeTab(key);
}
public async refreshTabKind(kind: string, path: Array<string>): Promise<any>
{
const key = path.length > 0 ? kind + "_" + path.join("_") : kind;
await this.refreshTab(key);
}
public async refreshTab(key: string): Promise<void>
{
if (!this.tabs.has(key))
return;
const tab = this.tabs.get(key);
await tab.refresh();
}
public async closeTab(key: string): Promise<boolean>
{
if (!this.tabs.has(key))
return false;
const tab = this.tabs.get(key);
await tab.release();
const btn = tab.buttonNode;
if (btn.prev().length)
{
btn.prev().find('a').tab('show');
}
else if (btn.next().length)
{
btn.next().find('a').tab('show');
}
btn.remove();
tab.contentNode.remove();
const shortTitle = tab.shortTitle;
let cnt = 0;
let otherFoundTab = null;
this.tabs.remove(key);
for (const otherTab of this.tabs.getValues())
{
if (otherTab.shortTitle == shortTitle)
{
cnt++;
otherFoundTab = otherTab;
}
}
if (cnt == 1)
{
otherFoundTab.changeTitle(otherFoundTab.shortTitle);
}
await this.checkEmpty();
return true;
}
private static Sleep(ms: number)
{
return new Promise(resolve => setTimeout(resolve, ms));
}
public async refreshWorkspace()
{
await WorkspaceRenderer.Sleep(50);
await this.disable();
WorkspaceRenderer.OpenLoading();
try
{
await ipc.initWorkspace();
}
catch (e)
{
if (e.hasOwnProperty("title"))
{
WorkspaceRenderer.OpenError(e.title, e.message);
}
else
{
WorkspaceRenderer.OpenError("Failed to process the workspace", e.message);
}
return;
}
await this.initWorkspace();
await this.initModules();
await this.enable();
}
private async disable()
{
$('#workspace').addClass('disabled');
}
private async enable()
{
$('#workspace').removeClass('disabled');
this.openEditor();
await this.checkEmpty();
}
private initSidebar()
{
const sidebarMin = 200;
const sidebarMax = 3600;
const contentsMin = 200;
const sideBar = $('.workspace-sidebar');
const zis = this;
storage.get('workspace-window-settings', function(error: any, data: any)
{
if (!error)
{
const x: any = data["x"];
WorkspaceRenderer.applyWorkspaceSettings(x);
}
// noinspection TypeScriptValidateJSTypes
$('.split-bar').mousedown(function (e: any)
{
e.preventDefault();
$('#workspace-panel').addClass('workspace-frame-dragging');
const move = function (e: any)
{
e.preventDefault();
const x = e.pageX - sideBar.offset().left;
if (x > sidebarMin && x < sidebarMax && e.pageX < ($(window).width() - contentsMin))
{
WorkspaceRenderer.applyWorkspaceSettings(x);
zis.saveWorkspaceSettings(x);
}
};
// noinspection TypeScriptValidateJSTypes
$(document).on('mousemove', move).mouseup(function (e: any)
{
$('#workspace-panel').removeClass('workspace-frame-dragging');
$(document).unbind('mousemove', move);
});
});
});
}
private static applyWorkspaceSettings(x: any)
{
$('.workspace-sidebar').css("width", x);
$('.workspace-contents').css("margin-left", x);
}
private saveWorkspaceSettings(x: any)
{
if (this.settingsTimer)
{
clearTimeout(this.settingsTimer);
}
this.settingsTimer = setTimeout(() =>
{
storage.set('workspace-window-settings', {
"x": x
});
}, 1000);
}
}
// @ts-ignore
window.eval = global.eval = function () {
throw new Error(`Sorry, this app does not support window.eval().`)
};
$(() =>
{
renderer = new WorkspaceRenderer();
}); | the_stack |
module TDev.RT {
//? A json data structure builder
//@ stem("jsb") ctx(general,enumerable,json)
//@ serializable
export class JsonBuilder
extends RTValue {
private item: any = {};
public isSerializable() { return true; }
static wrap(i: any) {
if (i === undefined) return undefined; // null must be wrapped
var r = new (<any>JsonBuilder)(); //TS9
r.item = i
return r
}
public value() { return this.item }
public exportJson(ctx: JsonExportCtx): any {
return Util.jsonClone(this.item);
}
public importJson(ctx: JsonImportCtx, json: any): RT.RTValue {
if (json !== undefined) {
this.item = Util.jsonClone(json);
return this;
}
else
return undefined;
}
private ensureObject() {
if (this.item === null || typeof this.item !== "object" || Array.isArray(this.item))
this.item = {};
}
//? Sets the field value.
public set_field(name: string, value: JsonObject): void {
if (name.length == 0) return;
this.ensureObject();
this.item[name] = this.toValue(value);
}
//? Sets the field the the reference to JsonBuilder.
public set_builder(name: string, value: JsonBuilder): void {
if (name.length == 0) return;
this.ensureObject();
this.item[name] = value.item;
}
//? Sets the string value.
public set_string(name: string, value: string): void {
if (name.length == 0) return;
this.ensureObject();
this.item[name] = value;
}
//? Creates a deep copy clone of the object
public clone(): JsonBuilder {
return JsonBuilder.wrap(Util.jsonClone(this.item));
}
//? Sets the number value.
public set_number(name: string, value: number): void {
if (name.length == 0) return;
this.ensureObject();
this.item[name] = value;
}
//? Sets the boolean value.
public set_boolean(name: string, value: boolean): void {
if (name.length == 0) return;
this.ensureObject();
this.item[name] = value;
}
//? Sets the Sound value as a data uri.
public set_sound(name: string, snd: Sound): void {
if (name.length == 0) return;
this.ensureObject();
this.item[name] = snd.getDataUri();
}
//? Sets the Picture value as a data uri.
//@ picAsync
public set_picture(name: string, pic: Picture, quality: number, r: ResumeCtx): void {
if (name.length == 0) return;
this.ensureObject();
pic.loadFirst(r, () => {
this.item[name] = pic.getDataUri(Math_.normalize(quality));
});
}
//? Sets the field value as null.
public set_field_null(name: string): void {
this.set_field(name, null);
}
private ensureArray() {
if (!Array.isArray(this.item)) this.item = [];
}
//? Adds a value to the array.
public add(value: JsonObject): void {
this.ensureArray();
this.item.push(this.toValue(value));
}
//? Adds a number to the array.
public add_number(value: number): void {
this.ensureArray();
this.item.push(value);
}
//? Adds a string to the array.
public add_string(value: string): void {
this.ensureArray();
this.item.push(value);
}
//? Adds a boolean to the array.
public add_boolean(value: boolean): void {
this.ensureArray();
this.item.push(value);
}
//? Copy all fields from given JSON object
public copy_from(value: JsonObject): void
{
if (value.kind() != "object")
Util.userError("cannot copy from non-object")
var v = Util.jsonClone(value.value())
Object.keys(v).forEach(k => {
this.item[k] = v[k]
})
}
//? Add a reference to JsonBuilder to the array.
public add_builder(value: JsonBuilder): void {
if (!Array.isArray(this.item))
this.item = [];
this.item.push(value.item);
}
//? Deletes all array elements from the current builder.
public clear() {
if (Array.isArray(this.item))
while (this.item.length > 0)
this.item.pop();
}
//? Adds a null value to the array.
public add_null(): void {
this.add(null);
}
public toString(): string {
return JSON.stringify(this.item);
}
public setItem(i: any) {
this.item = i
}
private toValue(o: JsonObject): any {
return o === null ? null : o.value();
}
//? Converts the builder into a json data structure
public to_json(): JsonObject {
return JsonObject.wrap(JSON.parse(JSON.stringify(this.item)));
}
//? Gets the number of values
public count(): number {
return Array.isArray(this.item) ? this.item.length : undefined;
}
//? Gets the i-th json value
public at(index: number): JsonBuilder {
return Array.isArray(this.item) ? JsonBuilder.wrap(this.item[Math.floor(index)]) : undefined;
}
//? Sets the i-th json value
public set_at(index: number, v: JsonBuilder) {
if (!Array.isArray(this.item))
this.item = [];
this.item[index] = v.item;
}
//? Removes the i-th json value
public remove_at(index: number) {
if (!Array.isArray(this.item))
this.item = [];
this.item.splice(index, 1);
}
//? Deletes named field
public remove_field(name: string) {
var v = this.item;
this.ensureObject();
delete this.item[name];
}
//? Gets a field value as a boolean
public boolean(key: string): boolean {
if (this.item === null) return undefined;
var v: any = this.item[key];
if (typeof v === 'boolean') return <boolean>v;
if (typeof v === 'string') return /^true$/i.test(<string>v) ? true : false;
if (typeof v === 'number') return (<number>v) == 0 ? false : true;
else return !!v;
}
//? Indicates if the key exists
public contains_key(key: string): boolean {
var v = this.item;
return v !== null && typeof v === 'object' && v.hasOwnProperty(key);
}
//? Gets the field value as a time
public time(key: string): DateTime {
if (this.item !== null) {
var v = this.item[key];
if (typeof v === 'string') return DateTime.mkMs(Date.parse(<string>v));
if (typeof v === 'number') return DateTime.mkMs(<number>v);
}
return undefined;
}
//? Gets a value by name
public field(key: string): JsonBuilder {
var v = this.item;
return v === null ? undefined : JsonBuilder.wrap(v[key]);
}
//? Gets the list of keys
public keys(): Collection<string> {
return Collection.mkStrings(this.kind() === "object" ? Object.keys(this.item) : []);
}
//? Gets a json kind (string, number, object, array, boolean, null)
public kind(): string {
var result = 'array';
if (this.item === null) result = "null";
else if (Array.isArray(this.item)) { }
else if (typeof this.item === 'string') result = 'string';
else if (typeof this.item === 'number') result = 'number';
else if (typeof this.item === 'boolean') result = 'boolean';
else if (typeof this.item === 'object') result = 'object';
return result;
}
//? Gets a field value as a number
public number(key: string): number {
if (this.item !== null) {
var v = this.item[key];
if (typeof v === 'number') return <number>v;
if (typeof v === 'string') return parseFloat(<string>v);
if (typeof v === 'boolean') return (<boolean>v) ? 1 : 0;
}
return undefined;
}
//? Gets a field value as a string
public string(key: string): string {
if (this.item !== null) {
var v = this.item[key];
if (typeof v === 'string') return <string>v;
if (typeof v === 'number') return (<number>v).toString();
if (typeof v === 'boolean') return (<boolean>v) ? 'true' : 'false';
}
return undefined;
}
//? Prints the value to the wall
public post_to_wall(s: IStackFrame): void {
var txt;
try {
txt = JSON.stringify(this.item, null, 2)
} catch (e) {
txt = "error stringifying json builder: " + e.message;
}
s.rt.postBoxedText(txt, s.pc);
}
//? Converts to a boolean (type must be boolean)
public to_boolean(): boolean {
if (typeof this.item === 'boolean') return <boolean>this.item;
if (typeof this.item === 'string') return /^true$/i.test(<string>this.item) ? true : false;
if (typeof this.item === 'number') return (<number>this.item) == 0 ? false : true;
return undefined;
}
//? Converts to a number (type must be number)
public to_number(): number {
if (typeof this.item === 'number') return <number>this.item;
if (typeof this.item === 'string') return parseFloat(<string>this.item);
if (typeof this.item === 'boolean') return (<boolean>this.item) ? 1 : 0;
return undefined;
}
//? Converts to a string (type must be string)
public to_string(): string {
if (typeof this.item === 'string') return <string>this.item;
if (typeof this.item === 'number') return (<number>this.item).toString();
if (typeof this.item === 'boolean') return (<boolean>this.item) ? 'true' : 'false';
return undefined;
}
//? Converts and parses to a date time (type must be string)
public to_time(): DateTime {
if (typeof this.item === 'string') return DateTime.mkMs(Date.parse(<string>this.item));
if (typeof this.item === 'number') return DateTime.mkMs(<number>this.item);
return undefined;
}
//? Converts to a collection of JsonBuilders (type must be array)
//@ readsMutable [result].writesMutable
public to_collection(): Collection<JsonBuilder> {
if (Array.isArray(this.item))
return Collection.fromArray<JsonBuilder>(this.item.map(e => JsonBuilder.wrap(e)), JsonBuilder)
else
return undefined
}
//? Stringify the current JSON object
public serialize(): string {
return JSON.stringify(this.item)
}
public getShortStringRepresentation(): string {
return JSON.stringify(this.item, null, 2);
}
public debuggerDisplay(clickHandler) {
return this.to_json().debuggerDisplay(clickHandler);
}
public debuggerChildren(): any {
return this.to_json().debuggerChildren();
}
}
} | the_stack |
import { QueryFilter } from "@graphback/core"
import * as Knex from 'knex';
import { createKnexQueryMapper, CRUDKnexQueryMapper } from "../src/knexQueryMapper"
describe('knexQueryMapper', () => {
let queryBuilder: CRUDKnexQueryMapper;
let db: Knex;
beforeAll(() => {
db = Knex({
client: 'sqlite3',
connection: ':memory:',
useNullAsDefault: true
});
queryBuilder = createKnexQueryMapper(db);
});
test('select *', () => {
expect(queryBuilder.buildQuery(undefined).toQuery()).toEqual("select *")
expect(queryBuilder.buildQuery({}).toQuery()).toEqual("select *")
});
test('where name = ?', () => {
const filter: QueryFilter = {
name: {
eq: 'Enda'
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` = 'Enda')")
});
test('where name is null', () => {
const filter: QueryFilter = {
name: {
// eslint-disable-next-line no-null/no-null
eq: null
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` is null)")
})
test('where name is not null', () => {
const filter: QueryFilter = {
name: {
// eslint-disable-next-line no-null/no-null
ne: null
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` is not null)")
})
test('where name <> ?', () => {
const filter: QueryFilter = {
name: {
ne: 'Enda'
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` <> 'Enda')")
});
test('where age < ?', () => {
const filter: QueryFilter = {
age: {
lt: 25
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`age` < 25)")
});
test('where age <= ?', () => {
const filter: QueryFilter = {
age: {
le: 25
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`age` <= 25)")
});
test('where age > ?', () => {
const filter: QueryFilter = {
age: {
gt: 25
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`age` > 25)")
});
test('where age >= ?', () => {
const filter: QueryFilter = {
age: {
ge: 25
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`age` >= 25)")
});
test('where name = ? and id = ?', () => {
const filter: QueryFilter = {
name: {
eq: 'Enda'
},
surname: {
eq: 'Stevens'
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` = 'Enda' and `surname` = 'Stevens')")
});
test('where age in [...]', () => {
const filter: QueryFilter = {
age: {
in: [26, 30, 45]
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual('select * where (`age` in (26, 30, 45))');
});
test('where age between [...]', () => {
const filter: QueryFilter = {
age: {
between: [26, 30]
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual('select * where (`age` between 26 and 30)');
});
describe('and', () => {
test("select * where (`name` = ?) and (`surname` = ?)", () => {
const filter: QueryFilter = {
and: [
{
name: {
eq: 'Jerry'
}
},
{
surname: {
eq: 'Seinfeld'
}
}
]
};
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where ((`name` = 'Jerry') and (`surname` = 'Seinfeld'))")
});
test("select * where (`name` = 'Jerry') and ((`profession` = ?) and ((`surname` = ?) or (`surname` = ?)))", () => {
const filter: QueryFilter = {
name: {
eq: 'Jerry'
},
and: [
{
profession: {
eq: 'Actor'
},
or: [
{
surname: {
eq: 'Seinfeld'
}
},
{
surname: {
eq: 'Stiller'
}
}
]
}
]
};
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` = 'Jerry') and ((`profession` = 'Actor') and ((`surname` = 'Seinfeld') or (`surname` = 'Stiller')))")
})
})
describe('not', () => {
test('where not name = ?', () => {
const filter: QueryFilter = {
not: {
name: {
eq: 'Enda'
}
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (not (`name` = 'Enda'))")
});
})
describe('or', () => {
test('where select * from name = ? or name = ?', () => {
const filter: QueryFilter = {
or: [
{
name: {
eq: 'Enda'
},
},
{
name: {
eq: 'Matthew'
}
}
]
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where ((`name` = 'Enda') or (`name` = 'Matthew'))")
})
test('where select * from name = ? or (name = ? and surname = ?)', () => {
const filter: QueryFilter = {
or: [
{
name: {
eq: 'Enda'
},
},
{
name: {
eq: 'Lewis'
},
surname: {
eq: 'Conlon'
}
}
]
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where ((`name` = 'Enda') or (`name` = 'Lewis' and `surname` = 'Conlon'))")
});
test('where select * from users where name = ? and (lname = ? or lname = ?)', () => {
const filter: QueryFilter = {
name: {
eq: 'James'
},
or: [
{
surname: {
eq: 'McMorrow'
}
},
{
surname: {
eq: 'McLean'
}
}
]
};
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` = 'James') and ((`surname` = 'McMorrow') or (`surname` = 'McLean'))");
});
test('where name = ? and (surname = ? or (surname = ? and id = ?))', () => {
const filter: QueryFilter = {
name: {
eq: 'Sarah'
},
or: [
{
surname: {
eq: 'Smith'
}
},
{
surname: {
eq: 'Simone'
},
id: {
eq: 1
}
}
]
};
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` = 'Sarah') and ((`surname` = 'Smith') or (`surname` = 'Simone' and `id` = 1))")
})
test('where name = ? and ((id > ? or id < ?) or (id > ? and lname = ?))', () => {
const filter: QueryFilter = {
name: {
eq: 'Jimi'
},
or: [
{
id: {
gt: 99
}
},
{
id: {
lt: 49
}
},
{
id: {
gt: 2000,
lt: 2500
},
surname: {
eq: 'Hendrix'
}
}
]
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (`name` = 'Jimi') and ((`id` > 99) or (`id` < 49) or (`id` > 2000 and `id` < 2500 and `surname` = 'Hendrix'))")
})
test('where ((id > ? or id < ?) and (id > ? or id > ?))', () => {
const filter: QueryFilter = {
or: [
{
or: [
{
id: {
gt: 99
}
},
{
id: {
lt: 49
}
}
]
},
{
or: [
{
id: {
gt: 2000,
lt: 2500
},
surname: {
eq: 'Hendrix'
}
}
]
}
]
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where (((`id` > 99) or (`id` < 49)) and ((`id` > 2000 and `id` < 2500 and `surname` = 'Hendrix')))")
});
describe('not', () => {
test('where (not (id = 5 or not id = 2)', () => {
const filter: QueryFilter = {
not: {
or: [
{
id: {
eq: 5
}
},
{
id: {
eq: 2
}
}
]
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual("select * where ((not (`id` = 5) or not (`id` = 2)))")
});
})
});
describe('nested root conditions', () => {
test('or > not', () => {
const filter: QueryFilter = {
or: [
{
a: {
in: [1, 11]
}
},
{
not: {
a: {
eq: 2
}
}
}
]
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual('select * where ((`a` in (1, 11)) or (not (`a` = 2)))')
})
test('not > or', () => {
const filter: QueryFilter = {
not: {
or: [
{
a: {
eq: 1
}
},
{
a: {
eq: 2
}
}
]
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual('select * where ((not (`a` = 1) or not (`a` = 2)))')
})
test('not > and', () => {
const filter: QueryFilter = {
not: {
and: [
{
a: {
eq: 1
}
},
{
a: {
eq: 2
}
}
]
}
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual('select * where ((not (`a` = 1) and not (`a` = 2)))')
})
test('and > or', () => {
const filter: QueryFilter = {
and: [
{
c: {
eq: 1
}
},
{
or: [
{
a: {
eq: 1
}
},
{
a: {
eq: 2
}
}
]
}
]
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual('select * where ((`c` = 1) and ((`a` = 1) or (`a` = 2)))')
})
test('and > not', () => {
const filter: QueryFilter = {
and: [
{
a: {
eq: 1
}
},
{
not: {
a: {
eq: 2
}
}
}
]
}
expect(queryBuilder.buildQuery(filter).toQuery()).toEqual('select * where ((`a` = 1) and (not (`a` = 2)))')
})
})
}); | the_stack |
import { MathConstants } from './MathConstants';
/**
* Units - class representing the most important units (length, area, volume, mass).
*
* @author <b>Mariusz Gromada</b><br>
* <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
*
* @version 4.2.0
* @class
*/
export class Units {
/**
* Percentage
*/
public static PERC: number = 0.01;
/**
* Promil, Per mille
*/
public static PROMIL: number = 0.001;
/**
* Yotta
*/
public static YOTTA: number = 1.0E24;
/**
* Zetta
*/
public static ZETTA: number = 1.0E21;
/**
* Exa
*/
public static EXA: number = 1.0E18;
/**
* Peta
*/
public static PETA: number = 1.0E15;
/**
* Tera
*/
public static TERA: number = 1.0E12;
/**
* Giga
*/
public static GIGA: number = 1.0E9;
/**
* Mega
*/
public static MEGA: number = 1000000.0;
/**
* Kilo
*/
public static KILO: number = 1000.0;
/**
* Hecto
*/
public static HECTO: number = 100.0;
/**
* Deca
*/
public static DECA: number = 10.0;
/**
* Deci
*/
public static DECI: number = 0.1;
/**
* Centi
*/
public static CENTI: number = 0.01;
/**
* Milli
*/
public static MILLI: number = 0.001;
/**
* Micro
*/
public static MICRO: number = 1.0E-6;
/**
* Nano
*/
public static NANO: number = 1.0E-9;
/**
* Pico
*/
public static PICO: number = 1.0E-12;
/**
* Femto
*/
public static FEMTO: number = 1.0E-15;
/**
* Atto
*/
public static ATTO: number = 1.0E-18;
/**
* Zepto
*/
public static ZEPTO: number = 1.0E-21;
/**
* Yocto
*/
public static YOCTO: number = 1.0E-24;
/**
* Meter
*/
public static METRE: number = 1.0;
/**
* Kilometer
*/
public static KILOMETRE: number; public static KILOMETRE_$LI$(): number { if (Units.KILOMETRE == null) { Units.KILOMETRE = 1000.0 * Units.METRE; } return Units.KILOMETRE; }
/**
* Centimeter
*/
public static CENTIMETRE: number; public static CENTIMETRE_$LI$(): number { if (Units.CENTIMETRE == null) { Units.CENTIMETRE = Units.CENTI * Units.METRE; } return Units.CENTIMETRE; }
/**
* Millimetre
*/
public static MILLIMETRE: number; public static MILLIMETRE_$LI$(): number { if (Units.MILLIMETRE == null) { Units.MILLIMETRE = Units.MILLI * Units.METRE; } return Units.MILLIMETRE; }
/**
* Inch
*/
public static INCH: number; public static INCH_$LI$(): number { if (Units.INCH == null) { Units.INCH = 2.54 * Units.CENTIMETRE_$LI$(); } return Units.INCH; }
/**
* Yard
*/
public static YARD: number; public static YARD_$LI$(): number { if (Units.YARD == null) { Units.YARD = 0.9144 * Units.METRE; } return Units.YARD; }
/**
* Feet
*/
public static FEET: number; public static FEET_$LI$(): number { if (Units.FEET == null) { Units.FEET = 30.48 * Units.CENTIMETRE_$LI$(); } return Units.FEET; }
/**
* Mile
*/
public static MILE: number; public static MILE_$LI$(): number { if (Units.MILE == null) { Units.MILE = 1.609344 * Units.KILOMETRE_$LI$(); } return Units.MILE; }
/**
* Nautical mile
*/
public static NAUTICAL_MILE: number; public static NAUTICAL_MILE_$LI$(): number { if (Units.NAUTICAL_MILE == null) { Units.NAUTICAL_MILE = 1.852 * Units.KILOMETRE_$LI$(); } return Units.NAUTICAL_MILE; }
/**
* Square metre
*/
public static METRE2: number; public static METRE2_$LI$(): number { if (Units.METRE2 == null) { Units.METRE2 = Units.METRE * Units.METRE; } return Units.METRE2; }
/**
* Square centimetre
*/
public static CENTIMETRE2: number; public static CENTIMETRE2_$LI$(): number { if (Units.CENTIMETRE2 == null) { Units.CENTIMETRE2 = Units.CENTIMETRE_$LI$() * Units.CENTIMETRE_$LI$(); } return Units.CENTIMETRE2; }
/**
* Square millimetre
*/
public static MILLIMETRE2: number; public static MILLIMETRE2_$LI$(): number { if (Units.MILLIMETRE2 == null) { Units.MILLIMETRE2 = Units.MILLIMETRE_$LI$() * Units.MILLIMETRE_$LI$(); } return Units.MILLIMETRE2; }
/**
* Are
*/
public static ARE: number; public static ARE_$LI$(): number { if (Units.ARE == null) { Units.ARE = (10.0 * Units.METRE) * (10.0 * Units.METRE); } return Units.ARE; }
/**
* Hectare
*/
public static HECTARE: number; public static HECTARE_$LI$(): number { if (Units.HECTARE == null) { Units.HECTARE = (100.0 * Units.METRE) * (100.0 * Units.METRE); } return Units.HECTARE; }
/**
* Square kilometre
*/
public static KILOMETRE2: number; public static KILOMETRE2_$LI$(): number { if (Units.KILOMETRE2 == null) { Units.KILOMETRE2 = Units.KILOMETRE_$LI$() * Units.KILOMETRE_$LI$(); } return Units.KILOMETRE2; }
/**
* Acre
*/
public static ACRE: number; public static ACRE_$LI$(): number { if (Units.ACRE == null) { Units.ACRE = (66.0 * Units.FEET_$LI$()) * (660.0 * Units.FEET_$LI$()); } return Units.ACRE; }
/**
* Qubic millimetre
*/
public static MILLIMETRE3: number; public static MILLIMETRE3_$LI$(): number { if (Units.MILLIMETRE3 == null) { Units.MILLIMETRE3 = Units.MILLIMETRE_$LI$() * Units.MILLIMETRE_$LI$() * Units.MILLIMETRE_$LI$(); } return Units.MILLIMETRE3; }
/**
* Qubic centimetre
*/
public static CENTIMETRE3: number; public static CENTIMETRE3_$LI$(): number { if (Units.CENTIMETRE3 == null) { Units.CENTIMETRE3 = Units.CENTIMETRE_$LI$() * Units.CENTIMETRE_$LI$() * Units.CENTIMETRE_$LI$(); } return Units.CENTIMETRE3; }
/**
* Qubic metre
*/
public static METRE3: number; public static METRE3_$LI$(): number { if (Units.METRE3 == null) { Units.METRE3 = Units.METRE * Units.METRE * Units.METRE; } return Units.METRE3; }
/**
* Qubic kilometre
*/
public static KILOMETRE3: number; public static KILOMETRE3_$LI$(): number { if (Units.KILOMETRE3 == null) { Units.KILOMETRE3 = Units.KILOMETRE_$LI$() * Units.KILOMETRE_$LI$() * Units.KILOMETRE_$LI$(); } return Units.KILOMETRE3; }
/**
* Millilitre
*/
public static MILLILITRE: number; public static MILLILITRE_$LI$(): number { if (Units.MILLILITRE == null) { Units.MILLILITRE = Units.CENTIMETRE3_$LI$(); } return Units.MILLILITRE; }
/**
* Litre
*/
public static LITRE: number; public static LITRE_$LI$(): number { if (Units.LITRE == null) { Units.LITRE = 1000.0 * Units.MILLILITRE_$LI$(); } return Units.LITRE; }
/**
* Gallon
*/
public static GALLON: number; public static GALLON_$LI$(): number { if (Units.GALLON == null) { Units.GALLON = 3.78541178 * Units.LITRE_$LI$(); } return Units.GALLON; }
/**
* Pint
*/
public static PINT: number; public static PINT_$LI$(): number { if (Units.PINT == null) { Units.PINT = 473.176473 * Units.MILLILITRE_$LI$(); } return Units.PINT; }
/**
* Second
*/
public static SECOND: number = 1.0;
/**
* Millisecond
*/
public static MILLISECOND: number; public static MILLISECOND_$LI$(): number { if (Units.MILLISECOND == null) { Units.MILLISECOND = Units.MILLI * Units.SECOND; } return Units.MILLISECOND; }
/**
* MINUTE
*/
public static MINUTE: number; public static MINUTE_$LI$(): number { if (Units.MINUTE == null) { Units.MINUTE = 60.0 * Units.SECOND; } return Units.MINUTE; }
/**
* HOUR
*/
public static HOUR: number; public static HOUR_$LI$(): number { if (Units.HOUR == null) { Units.HOUR = 60.0 * Units.MINUTE_$LI$(); } return Units.HOUR; }
/**
* DAY
*/
public static DAY: number; public static DAY_$LI$(): number { if (Units.DAY == null) { Units.DAY = 24.0 * Units.HOUR_$LI$(); } return Units.DAY; }
/**
* WEEK
*/
public static WEEK: number; public static WEEK_$LI$(): number { if (Units.WEEK == null) { Units.WEEK = 7.0 * Units.DAY_$LI$(); } return Units.WEEK; }
/**
* JULIAN YEAR
*/
public static JULIAN_YEAR: number; public static JULIAN_YEAR_$LI$(): number { if (Units.JULIAN_YEAR == null) { Units.JULIAN_YEAR = 365.25 * Units.DAY_$LI$(); } return Units.JULIAN_YEAR; }
/**
* Kilogram
*/
public static KILOGRAM: number = 1.0;
/**
* Gram
*/
public static GRAM: number; public static GRAM_$LI$(): number { if (Units.GRAM == null) { Units.GRAM = 0.001 * Units.KILOGRAM; } return Units.GRAM; }
/**
* Milligram
*/
public static MILLIGRAM: number; public static MILLIGRAM_$LI$(): number { if (Units.MILLIGRAM == null) { Units.MILLIGRAM = Units.MILLI * Units.GRAM_$LI$(); } return Units.MILLIGRAM; }
/**
* Decagram
*/
public static DECAGRAM: number; public static DECAGRAM_$LI$(): number { if (Units.DECAGRAM == null) { Units.DECAGRAM = Units.DECA * Units.GRAM_$LI$(); } return Units.DECAGRAM; }
/**
* Tonne
*/
public static TONNE: number; public static TONNE_$LI$(): number { if (Units.TONNE == null) { Units.TONNE = 1000.0 * Units.KILOGRAM; } return Units.TONNE; }
/**
* Ounce
*/
public static OUNCE: number; public static OUNCE_$LI$(): number { if (Units.OUNCE == null) { Units.OUNCE = 28.3495231 * Units.GRAM_$LI$(); } return Units.OUNCE; }
/**
* Pound
*/
public static POUND: number; public static POUND_$LI$(): number { if (Units.POUND == null) { Units.POUND = 0.45359237 * Units.KILOGRAM; } return Units.POUND; }
public static MOLE: number = 1.0;
/**
* Coulomb
*/
public static COULOMB: number = 1.0;
/**
* Ampere
*/
public static AMPERE: number; public static AMPERE_$LI$(): number { if (Units.AMPERE == null) { Units.AMPERE = Units.COULOMB / Units.SECOND; } return Units.AMPERE; }
/**
* Kelvin
*/
public static KELVIN: number = 1.0;
/**
* Celcius
*/
public static CELCIUS: number = 1.0;
/**
* Farenheight
*/
public static FARENHEIGHT: number = 1.8;
/**
* Bit
*/
public static BIT: number = 1.0;
/**
* Kilobit
*/
public static KILOBIT: number; public static KILOBIT_$LI$(): number { if (Units.KILOBIT == null) { Units.KILOBIT = 1024.0 * Units.BIT; } return Units.KILOBIT; }
/**
* Megabit
*/
public static MEGABIT: number; public static MEGABIT_$LI$(): number { if (Units.MEGABIT == null) { Units.MEGABIT = 1024.0 * Units.KILOBIT_$LI$(); } return Units.MEGABIT; }
/**
* Gigabit
*/
public static GIGABIT: number; public static GIGABIT_$LI$(): number { if (Units.GIGABIT == null) { Units.GIGABIT = 1024.0 * Units.MEGABIT_$LI$(); } return Units.GIGABIT; }
/**
* Terabit
*/
public static TERABIT: number; public static TERABIT_$LI$(): number { if (Units.TERABIT == null) { Units.TERABIT = 1024.0 * Units.GIGABIT_$LI$(); } return Units.TERABIT; }
/**
* Petabit
*/
public static PETABIT: number; public static PETABIT_$LI$(): number { if (Units.PETABIT == null) { Units.PETABIT = 1024.0 * Units.TERABIT_$LI$(); } return Units.PETABIT; }
/**
* Exabit
*/
public static EXABIT: number; public static EXABIT_$LI$(): number { if (Units.EXABIT == null) { Units.EXABIT = 1024.0 * Units.PETABIT_$LI$(); } return Units.EXABIT; }
/**
* Zettabit
*/
public static ZETTABIT: number; public static ZETTABIT_$LI$(): number { if (Units.ZETTABIT == null) { Units.ZETTABIT = 1024.0 * Units.EXABIT_$LI$(); } return Units.ZETTABIT; }
/**
* Yottabit
*/
public static YOTTABIT: number; public static YOTTABIT_$LI$(): number { if (Units.YOTTABIT == null) { Units.YOTTABIT = 1024.0 * Units.ZETTABIT_$LI$(); } return Units.YOTTABIT; }
/**
* Byte
*/
public static BYTE: number; public static BYTE_$LI$(): number { if (Units.BYTE == null) { Units.BYTE = 8.0 * Units.BIT; } return Units.BYTE; }
/**
* Kilobyte
*/
public static KILOBYTE: number; public static KILOBYTE_$LI$(): number { if (Units.KILOBYTE == null) { Units.KILOBYTE = 1024.0 * Units.BYTE_$LI$(); } return Units.KILOBYTE; }
/**
* Megabyte
*/
public static MEGABYTE: number; public static MEGABYTE_$LI$(): number { if (Units.MEGABYTE == null) { Units.MEGABYTE = 1024.0 * Units.KILOBYTE_$LI$(); } return Units.MEGABYTE; }
/**
* Gigabyte
*/
public static GIGABYTE: number; public static GIGABYTE_$LI$(): number { if (Units.GIGABYTE == null) { Units.GIGABYTE = 1024.0 * Units.MEGABYTE_$LI$(); } return Units.GIGABYTE; }
/**
* Terabyte
*/
public static TERABYTE: number; public static TERABYTE_$LI$(): number { if (Units.TERABYTE == null) { Units.TERABYTE = 1024.0 * Units.GIGABYTE_$LI$(); } return Units.TERABYTE; }
/**
* Petabyte
*/
public static PETABYTE: number; public static PETABYTE_$LI$(): number { if (Units.PETABYTE == null) { Units.PETABYTE = 1024.0 * Units.TERABYTE_$LI$(); } return Units.PETABYTE; }
/**
* Exabyte
*/
public static EXABYTE: number; public static EXABYTE_$LI$(): number { if (Units.EXABYTE == null) { Units.EXABYTE = 1024.0 * Units.PETABYTE_$LI$(); } return Units.EXABYTE; }
/**
* Zettabyte
*/
public static ZETTABYTE: number; public static ZETTABYTE_$LI$(): number { if (Units.ZETTABYTE == null) { Units.ZETTABYTE = 1024.0 * Units.EXABYTE_$LI$(); } return Units.ZETTABYTE; }
/**
* Yottabyte
*/
public static YOTTABYTE: number; public static YOTTABYTE_$LI$(): number { if (Units.YOTTABYTE == null) { Units.YOTTABYTE = 1024.0 * Units.ZETTABYTE_$LI$(); } return Units.YOTTABYTE; }
/**
* Jule
*/
public static JOULE: number; public static JOULE_$LI$(): number { if (Units.JOULE == null) { Units.JOULE = (Units.KILOGRAM * Units.METRE * Units.METRE) / (Units.SECOND * Units.SECOND); } return Units.JOULE; }
/**
* Electrono-Volt
*/
public static ELECTRONO_VOLT: number; public static ELECTRONO_VOLT_$LI$(): number { if (Units.ELECTRONO_VOLT == null) { Units.ELECTRONO_VOLT = 1.6021766208E-19 * Units.JOULE_$LI$(); } return Units.ELECTRONO_VOLT; }
/**
* Kilo Electrono-Volt
*/
public static KILO_ELECTRONO_VOLT: number; public static KILO_ELECTRONO_VOLT_$LI$(): number { if (Units.KILO_ELECTRONO_VOLT == null) { Units.KILO_ELECTRONO_VOLT = Units.KILO * Units.ELECTRONO_VOLT_$LI$(); } return Units.KILO_ELECTRONO_VOLT; }
/**
* Mega Electrono-Volt
*/
public static MEGA_ELECTRONO_VOLT: number; public static MEGA_ELECTRONO_VOLT_$LI$(): number { if (Units.MEGA_ELECTRONO_VOLT == null) { Units.MEGA_ELECTRONO_VOLT = Units.MEGA * Units.ELECTRONO_VOLT_$LI$(); } return Units.MEGA_ELECTRONO_VOLT; }
/**
* Giga Electrono-Volt
*/
public static GIGA_ELECTRONO_VOLT: number; public static GIGA_ELECTRONO_VOLT_$LI$(): number { if (Units.GIGA_ELECTRONO_VOLT == null) { Units.GIGA_ELECTRONO_VOLT = Units.GIGA * Units.ELECTRONO_VOLT_$LI$(); } return Units.GIGA_ELECTRONO_VOLT; }
/**
* Tera Electrono-Volt
*/
public static TERA_ELECTRONO_VOLT: number; public static TERA_ELECTRONO_VOLT_$LI$(): number { if (Units.TERA_ELECTRONO_VOLT == null) { Units.TERA_ELECTRONO_VOLT = Units.TERA * Units.ELECTRONO_VOLT_$LI$(); } return Units.TERA_ELECTRONO_VOLT; }
/**
* Metre per second
*/
public static METRE_PER_SECOND: number; public static METRE_PER_SECOND_$LI$(): number { if (Units.METRE_PER_SECOND == null) { Units.METRE_PER_SECOND = Units.METRE / Units.SECOND; } return Units.METRE_PER_SECOND; }
/**
* Kilometre per hour
*/
public static KILOMETRE_PER_HOUR: number; public static KILOMETRE_PER_HOUR_$LI$(): number { if (Units.KILOMETRE_PER_HOUR == null) { Units.KILOMETRE_PER_HOUR = Units.KILOMETRE_$LI$() / Units.HOUR_$LI$(); } return Units.KILOMETRE_PER_HOUR; }
/**
* Mile per hour
*/
public static MILE_PER_HOUR: number; public static MILE_PER_HOUR_$LI$(): number { if (Units.MILE_PER_HOUR == null) { Units.MILE_PER_HOUR = Units.MILE_$LI$() / Units.HOUR_$LI$(); } return Units.MILE_PER_HOUR; }
/**
* Knot
*/
public static KNOT: number; public static KNOT_$LI$(): number { if (Units.KNOT == null) { Units.KNOT = 0.514444444 * Units.METRE / Units.SECOND; } return Units.KNOT; }
/**
* Metre per squared second
*/
public static METRE_PER_SECOND2: number; public static METRE_PER_SECOND2_$LI$(): number { if (Units.METRE_PER_SECOND2 == null) { Units.METRE_PER_SECOND2 = Units.METRE / (Units.SECOND * Units.SECOND); } return Units.METRE_PER_SECOND2; }
/**
* Kilometre per squared hour
*/
public static KILOMETRE_PER_HOUR2: number; public static KILOMETRE_PER_HOUR2_$LI$(): number { if (Units.KILOMETRE_PER_HOUR2 == null) { Units.KILOMETRE_PER_HOUR2 = Units.KILOMETRE_$LI$() / (Units.HOUR_$LI$() * Units.HOUR_$LI$()); } return Units.KILOMETRE_PER_HOUR2; }
/**
* Mile per squared hour
*/
public static MILE_PER_HOUR2: number; public static MILE_PER_HOUR2_$LI$(): number { if (Units.MILE_PER_HOUR2 == null) { Units.MILE_PER_HOUR2 = Units.MILE_$LI$() / (Units.HOUR_$LI$() * Units.HOUR_$LI$()); } return Units.MILE_PER_HOUR2; }
/**
* Radian (angle)
*/
public static RADIAN_ARC: number = 1.0;
/**
* Degree (angle)
*/
public static DEGREE_ARC: number; public static DEGREE_ARC_$LI$(): number { if (Units.DEGREE_ARC == null) { Units.DEGREE_ARC = (MathConstants.PI / 180.0) * Units.RADIAN_ARC; } return Units.DEGREE_ARC; }
/**
* Minute (angle)
*/
public static MINUTE_ARC: number; public static MINUTE_ARC_$LI$(): number { if (Units.MINUTE_ARC == null) { Units.MINUTE_ARC = Units.DEGREE_ARC_$LI$() / 60.0; } return Units.MINUTE_ARC; }
/**
* Second (angle)
*/
public static SECOND_ARC: number; public static SECOND_ARC_$LI$(): number { if (Units.SECOND_ARC == null) { Units.SECOND_ARC = Units.MINUTE_ARC_$LI$() / 60.0; } return Units.SECOND_ARC; }
}
Units["__class"] = "org.mariuszgromada.math.mxparser.mathcollection.Units"; | the_stack |
declare module 'jscodeshift' {
import {
NodePath,
Node,
Builders,
NamedTypes,
AstTypes,
Type,
NamedType,
AstNode,
TypeName,
} from 'ast-types';
import { PrinterOptions, Parser, ParserOptions } from 'recast';
interface CollectionBase<TNode> {
/**
* Returns a new collection containing the nodes for which the callback
* returns true.
*
* @param {function} callback
* @return {Collection}
*/
filter(callback: (nodePath: NodePath<TNode>) => boolean): Collection<TNode>;
/**
* Executes callback for each node/path in the collection.
*
* @param {function} callback
* @return {Collection} The collection itself
*/
forEach(
callback: (
this: NodePath<TNode>,
path: NodePath<TNode>,
i: number,
paths: NodePath<TNode>[]
) => void
): void;
/**
* Executes the callback for every path in the collection and returns a new
* collection from the return values (which must be paths).
*
* The callback can return null to indicate to exclude the element from the
* new collection.
*
* If an array is returned, the array will be flattened into the result
* collection.
*
* @param {function} callback
* @param {Type} type Force the new collection to be of a specific type
*/
map<TReturnNode>(
callback: (
this: NodePath<TNode>,
path: NodePath<TNode>,
i: number,
paths: NodePath<TNode>[]
) => NodePath<TReturnNode> | NodePath<TReturnNode>[] | null,
type?: TypeName
): Collection;
/**
* Returns the number of elements in this collection.
*
* @return {number}
*/
size(): number;
/**
* Returns the number of elements in this collection.
*
* @return {number}
*/
length: number;
/**
* Returns an array of AST nodes in this collection.
*
* @return {Array}
*/
nodes(): TNode[];
/**
* Returns an array of node paths in this collection.
*
* @return {Array}
*/
paths(): NodePath<TNode>[];
/**
* Returns the root NodePath[] which have no parent.
*/
getAST(): NodePath<any>[];
/**
* Returns printed representation of the whole AST (goes to the top-most ancestor and prints from there)
*/
toSource(options?: PrinterOptions): string;
/**
* Returns a new collection containing only the element at position index.
*
* In case of a negative index, the element is taken from the end:
*
* .at(0) - first element
* .at(-1) - last element
*
* @param {number} index
* @return {Collection}
*/
at(index: number): Collection<TNode>;
/**
* Proxies to NodePath#get of the first path.
*
* @param {string|number} ...fields
*/
get(...args: Array<string | number>): any;
/**
* Returns the type(s) of the collection. This is only used for unit tests,
* I don't think other consumers would need it.
*
* @return {Array<string>}
*/
getTypes(): string[];
/**
* Returns true if this collection has the type 'type'.
*
* @param {Type} type
* @return {boolean}
*/
isOfType(type: string): boolean;
}
interface CollectionJSXElementExtension<TNode> {
/**
* Finds all JSXElements optionally filtered by name
*
* @param {string} name
* @return {Collection}
*/
findJSXElements(name: string): Collection<TNode>;
/**
* Finds all JSXElements by module name. Given
*
* var Bar = require('Foo');
* <Bar />
*
* findJSXElementsByModuleName('Foo') will find <Bar />, without having to
* know the variable name.
*/
findJSXElementsByModuleName(moduleName: string): Collection<TNode>;
/**
* JSX: Filter method for attributes.
*
* @param {Object} attributeFilter
* @return {function}
*/
hasAttributes(attributeFilter: { [attributeName: string]: any }): boolean;
/**
* Filter elements which contain a specific child type
*
* @param {string} name
* @return {function}
*/
hasChildren(name: string): boolean;
/**
* JSX: Returns all child nodes, including literals and expressions.
*
* @return {Collection}
*/
childNodes(): Collection<TNode>;
/**
* JSX: Returns all children that are JSXElements.
*
* @return {JSXElementCollection}
*/
childElements(): Collection<TNode>;
/**
* Given a JSXElement, returns its "root" name. E.g. it would return "Foo" for
* both <Foo /> and <Foo.Bar />.
*
* @param {NodePath} path
* @return {string}
*/
getRootName(path: NodePath<TNode>): string;
}
interface CollectionNodeExtension<TNode> {
/**
* Find nodes of a specific type within the nodes of this collection.
*
* @param {type}
* @param {filter}
* @return {Collection}
*/
find<TNode>(type: NamedType<TNode>, filter?: any): Collection<TNode>;
/**
* Returns a collection containing the paths that create the scope of the
* currently selected paths. Dedupes the paths.
*
* @return {Collection}
*/
closestScope(): Collection;
/**
* Traverse the AST up and finds the closest node of the provided type.
*
* @param {Collection} type
* @param {filter} filter
* @return {Collection}
*/
closest<TNode>(type: NamedType<TNode>, filter?: any): Collection<TNode>;
/**
* Finds the declaration for each selected path. Useful for member expressions
* or JSXElements. Expects a callback function that maps each path to the name
* to look for.
*
* If the callback returns a falsey value, the element is skipped.
*
* @param {function} nameGetter
*
* @return {Collection}
*/
getVariableDeclarators(nameGetter: () => string | null | undefined): Collection;
/**
* Simply replaces the selected nodes with the provided node. If a function
* is provided it is executed for every node and the node is replaced with the
* functions return value.
*
* @param {Node|Array<Node>|function} nodes
* @return {Collection}
*/
replaceWith(
nodes: AstNode | AstNode[] | ((node: AstNode, i: number) => AstNode)
): Collection;
/**
* Inserts a new node before the current one.
*
* @param {Node|Array<Node>|function} insert
* @return {Collection}
*/
insertBefore(
insert: AstNode | AstNode[] | ((node: AstNode, i: number) => AstNode)
): Collection;
/**
* Inserts a new node after the current one.
*
* @param {Node|Array<Node>|function} insert
* @return {Collection}
*/
insertAfter(
insert: AstNode | AstNode[] | ((node: AstNode, i: number) => AstNode)
): Collection;
remove(): Collection;
}
interface CollectionVariableDeclaratorExtension<TNode> {
/**
* Finds all variable declarators, optionally filtered by name.
*
* @param {string} name
* @return {Collection}
*/
findVariableDeclarators(name?: string): Collection;
/**
* Renames a variable and all its occurrences.
*
* @param {string} newName
* @return {Collection}
*/
renameTo(newName: string): Collection;
}
export interface Collection<TNode = AstNode>
extends CollectionBase<TNode>,
CollectionJSXElementExtension<TNode>,
CollectionNodeExtension<TNode>,
CollectionVariableDeclaratorExtension<TNode> {
/**
* @param {Array} paths An array of AST paths
* @param {Collection} parent A parent collection
* @param {Array} types An array of types all the paths in the collection
* have in common. If not passed, it will be inferred from the paths.
* @return {Collection}
*/
new (paths: NodePath<TNode>[], parent: Collection, types?: string[]): Collection<TNode>;
}
export interface JsCodeShift extends Builders, NamedTypes {
/**
* Main entry point to the tool. The function accepts multiple different kinds
* of arguments as a convenience. In particular the function accepts either
*
* - a string containing source code
* The string is parsed with Recast
* - a single AST node
* - a single node path
* - an array of nodes
* - an array of node paths
*
* @exports jscodeshift
* @param {Node|NodePath|Array|string} source
* @param {Object} options Options to pass to Recast when passing source code
* @return {Collection}
*/
<TNode>(
source: string | TNode | NodePath<TNode> | TNode[] | NodePath<TNode>[],
options?: ParserOptions
): Collection;
/**
* The ast-types library
* @external astTypes
* @see {@link https://github.com/benjamn/ast-types}
*/
types: AstTypes;
/**
* Utility function to match a node against a pattern.
* @augments core
* @static
* @param {Node|NodePath|Object} path
* @param {Object} filter
* @return boolean
*/
match<TFilter extends Node>(
path: AstNode | NodePath<any> | any,
filter: Partial<TFilter>
): path is TFilter;
/**
* Utility function for registering plugins.
*
* Plugins are simple functions that are passed the core jscodeshift instance.
* They should extend jscodeshift by calling `registerMethods`, etc.
* This method guards against repeated registrations (the plugin callback will only be called once).
*
* @augments core
* @static
* @param {Function} plugin
*/
use(plugin: (core: JsCodeShift) => void): void;
/**
* Returns a version of the core jscodeshift function "bound" to a specific
* parser.
*
* @augments core
* @static
*/
withParser(parser: string | Parser): JsCodeShift;
/**
* This function adds the provided methods to the prototype of the corresponding
* typed collection. If no type is passed, the methods are added to
* Collection.prototype and are available for all collections.
*
* @param {Object} methods Methods to add to the prototype
* @param {Type=} type Optional type to add the methods to
*/
registerMethods<TNode>(
methods: {
[methodName: string]: Function;
},
type?: NamedType<TNode>
): void;
}
/**
* Returns a version of the core jscodeshift function "bound" to a specific
* parser.
*/
export function withParser(parser: string | Parser): JsCodeShift;
} | the_stack |
import { copy, defineConfig } from '@agile-ts/utils';
import { logCodeManager } from '../logCodeManager';
import { Agile } from '../agile';
import { getSharedStorageManager } from './shared';
import { StorageKey } from './storage';
export class Persistent {
// Agile Instance the Persistent belongs to
public agileInstance: () => Agile;
public static placeHolderKey = '__THIS_IS_A_PLACEHOLDER__';
public config: PersistentConfigInterface;
// Key/Name identifier of the Persistent
public _key: PersistentKey;
// Whether the Persistent is ready
// and is able to persist values in an external Storage
public ready = false;
// Whether the Persistent value is stored in a corresponding external Storage/s
public isPersisted = false;
// Callback that is called when the persisted value was loaded into the Persistent for the first time
public onLoad: ((success: boolean) => void) | undefined;
// Key/Name identifier of the Storages the Persistent value is stored in
public storageKeys: StorageKey[] = [];
/**
* A Persistent manages the permanent persistence
* of an Agile Class such as the `State Class` in external Storages.
*
* Note that the Persistent itself is no standalone class
* and should be adapted to the Agile Class needs it belongs to.
*
* @internal
* @param agileInstance - Instance of Agile the Persistent belongs to.
* @param config - Configuration object
*/
constructor(
agileInstance: Agile,
config: CreatePersistentConfigInterface = {}
) {
this.agileInstance = () => agileInstance;
this._key = Persistent.placeHolderKey;
config = defineConfig(config, {
loadValue: true,
storageKeys: [],
defaultStorageKey: null as any,
});
this.config = { defaultStorageKey: config.defaultStorageKey as any };
// Instantiate Persistent
if (config.loadValue) {
this.instantiatePersistent({
storageKeys: config.storageKeys,
key: config.key,
defaultStorageKey: config.defaultStorageKey,
});
}
}
/**
* Updates the key/name identifier of the Persistent.
*
* @public
* @param value - New key/name identifier.
*/
public set key(value: StorageKey) {
this.setKey(value);
}
/**
* Returns the key/name identifier of the Persistent.
*
* @public
*/
public get key(): StorageKey {
return this._key;
}
/**
* Updates the key/name identifier of the Persistent.
*
* @public
* @param value - New key/name identifier.
*/
public async setKey(value?: StorageKey): Promise<void> {
const oldKey = this._key;
const wasReady = this.ready;
// Assign new key to Persistent
if (value === this._key) return;
this._key = value ?? Persistent.placeHolderKey;
const isValid = this.validatePersistent();
// Try to initial load value if Persistent hasn't been ready before
if (!wasReady) {
if (isValid) await this.initialLoading();
return;
}
// Remove persisted value that is located at the old key
await this.removePersistedValue(oldKey);
// Persist value at the new key
if (isValid) await this.persistValue(value);
}
/**
* Instantiates the Persistent by assigning the specified Storage keys to it
* and validating it to make sure everything was setup correctly.
*
* This was moved out of the `constructor()`
* because some classes (that extend the Persistent) need to configure some
* things before they can properly instantiate the parent Persistent.
*
* @internal
* @param config - Configuration object
*/
public instantiatePersistent(
config: InstantiatePersistentConfigInterface = {}
) {
this._key = this.formatKey(config.key) ?? Persistent.placeHolderKey;
this.assignStorageKeys(config.storageKeys, config.defaultStorageKey);
this.validatePersistent();
// Register Persistent to Storage Manager
const storageManager = getSharedStorageManager();
if (this._key !== Persistent.placeHolderKey && storageManager != null) {
storageManager.persistentInstances[this._key] = this;
}
}
/**
* Returns a boolean indicating whether the Persistent was setup correctly
* and is able to persist a value permanently in an external Storage.
*
* Based on the tapped boolean value,
* the Persistent's `ready` property is updated.
*
* @internal
*/
public validatePersistent(): boolean {
let isValid = true;
// Validate Persistent key/name identifier
if (this._key === Persistent.placeHolderKey) {
logCodeManager.log('12:03:00');
isValid = false;
}
// Validate Storage keys
if (this.config.defaultStorageKey == null || this.storageKeys.length <= 0) {
logCodeManager.log('12:03:01');
isValid = false;
}
// Check if the Storages exist at the specified Storage keys
this.storageKeys.map((key) => {
if (!getSharedStorageManager()?.storages[key]) {
logCodeManager.log('12:03:02', { replacers: [this._key, key] });
isValid = false;
}
});
this.ready = isValid;
return isValid;
}
/**
* Assigns the specified Storage identifiers to the Persistent
* and extracts the default Storage if necessary.
*
* When no Storage key was provided the default Storage
* of the Agile Instance is applied to the Persistent.
*
* @internal
* @param storageKeys - Key/Name identifier of the Storages to be assigned.
* @param defaultStorageKey - Key/Name identifier of the default Storage.
*/
public assignStorageKeys(
storageKeys: StorageKey[] = [],
defaultStorageKey?: StorageKey
): void {
const _storageKeys = copy(storageKeys);
// Assign specified default Storage key to the 'storageKeys' array
if (defaultStorageKey != null && !_storageKeys.includes(defaultStorageKey))
_storageKeys.push(defaultStorageKey);
// Assign the default Storage key of the Agile Instance to the 'storageKeys' array
// and specify it as the Persistent's default Storage key
// if no valid Storage key was provided
if (_storageKeys.length <= 0) {
const defaultStorageKey =
getSharedStorageManager()?.config.defaultStorageKey;
if (defaultStorageKey != null) {
this.config.defaultStorageKey = defaultStorageKey;
_storageKeys.push(
getSharedStorageManager()?.config.defaultStorageKey as any
);
}
} else {
this.config.defaultStorageKey = defaultStorageKey ?? _storageKeys[0];
}
this.storageKeys = _storageKeys;
}
/**
* Stores or loads the Persistent value
* from the external Storages for the first time.
*
* @internal
*/
public async initialLoading(): Promise<void> {
const success = await this.loadPersistedValue();
if (this.onLoad) this.onLoad(success);
if (!success) await this.persistValue();
}
/**
* Loads the Persistent value from the corresponding Storage.
*
* Note that this method should be overwritten
* to correctly apply the changes to the Agile Class
* the Persistent belongs to.
*
* @internal
* @param storageItemKey - Storage key of the to load value.
* | default = Persistent.key |
* @return Whether the loading of the persisted value was successful.
*/
public async loadPersistedValue(
storageItemKey?: PersistentKey
): Promise<boolean> {
if (process.env.NODE_ENV !== 'production') {
logCodeManager.log('00:03:00', {
replacers: ['loadPersistedValue', 'Persistent'],
});
}
return false;
}
/**
* Persists the Persistent value in the corresponding Storage.
*
* Note that this method should be overwritten
* to correctly apply the changes to the Agile Class
* the Persistent belongs to.
*
* @internal
* @param storageItemKey - Storage key of the to persist value
* | default = Persistent.key |
* @return Whether the persisting of the value was successful.
*/
public async persistValue(storageItemKey?: PersistentKey): Promise<boolean> {
if (process.env.NODE_ENV !== 'production') {
logCodeManager.log('00:03:00', {
replacers: ['persistValue', 'Persistent'],
});
}
return false;
}
/**
* Removes the Persistent value from the corresponding Storage.
* -> Persistent value is no longer persisted
*
* Note that this method should be overwritten
* to correctly apply the changes to the Agile Class
* the Persistent belongs to.
*
* @internal
* @param storageItemKey - Storage key of the to remove value.
* | default = Persistent.key |
* @return Whether the removal of the persisted value was successful.
*/
public async removePersistedValue(
storageItemKey?: PersistentKey
): Promise<boolean> {
if (process.env.NODE_ENV !== 'production') {
logCodeManager.log('00:03:00', {
replacers: ['removePersistedValue', 'Persistent'],
});
}
return false;
}
/**
* Formats the specified key so that it can be used as a valid Storage key
* and returns the formatted variant of it.
*
* Note that this method should be overwritten
* to correctly apply the changes to the Agile Class
* the Persistent belongs to.
*
* @internal
* @param key - Storage key to be formatted.
*/
public formatKey(key?: PersistentKey): PersistentKey | undefined {
return key;
}
}
export type PersistentKey = string | number;
export interface CreatePersistentConfigInterface {
/**
* Key/Name identifier of the Persistent.
*/
key?: PersistentKey;
/**
* Key/Name identifier of Storages
* in which the Persistent value is to be persisted
* or is already persisted.
* @default [`defaultStorageKey`]
*/
storageKeys?: StorageKey[];
/**
* Key/Name identifier of the default Storage of the specified Storage keys.
*
* The persisted value is loaded from the default Storage by default,
* since only one persisted value can be applied.
* If the loading of the value from the default Storage failed,
* an attempt is made to load the value from the remaining Storages.
*
* @default first index of the specified Storage keys or the Agile Instance's default Storage key
*/
defaultStorageKey?: StorageKey;
/**
* Whether the Persistent should load/persist the value immediately
* or whether this should be done manually.
* @default true
*/
loadValue?: boolean;
}
export interface PersistentConfigInterface {
/**
* Key/Name identifier of the default Storage of the specified Storage keys.
*
* The persisted value is loaded from the default Storage by default,
* since only one persisted value can be applied.
* If the loading of the value from the default Storage failed,
* an attempt is made to load the value from the remaining Storages.
*
* @default first index of the specified Storage keys or the Agile Instance's default Storage key
*/
defaultStorageKey: StorageKey | null;
}
export interface InstantiatePersistentConfigInterface {
/**
* Key/Name identifier of the Persistent.
*/
key?: PersistentKey;
/**
* Key/Name identifier of Storages
* in which the Persistent value is to be persisted
* or is already persisted.
* @default [`defaultStorageKey`]
*/
storageKeys?: StorageKey[];
/**
* Key/Name identifier of the default Storage of the specified Storage keys.
*
* The persisted value is loaded from the default Storage by default,
* since only one persisted value can be applied.
* If the loading of the value from the default Storage failed,
* an attempt is made to load the value from the remaining Storages.
*
* @default first index of the specified Storage keys or the Agile Instance's default Storage key
*/
defaultStorageKey?: StorageKey;
} | the_stack |
import {
BigNumber,
BigNumberish,
BytesLike,
ethers,
constants,
providers,
utils,
} from "ethers";
import {
SnapshotInputSchema,
SnapshotSchema,
} from "../schema/contracts/common/snapshots";
import {
approveErc20Allowance,
fetchCurrencyValue,
isNativeToken,
normalizePriceValue,
} from "./currency";
import {
ClaimCondition,
ClaimConditionInput,
ClaimVerification,
FilledConditionInput,
SnapshotInfo,
} from "../types";
import { ContractWrapper } from "../core/classes/contract-wrapper";
import { IStorage } from "../core";
import {
ClaimConditionInputArray,
ClaimConditionInputSchema,
ClaimConditionOutputSchema,
} from "../schema/contracts/common/claim-conditions";
import { createSnapshot } from "./snapshots";
import { NATIVE_TOKEN_ADDRESS } from "../constants";
import { IDropClaimCondition } from "contracts/DropERC20";
/**
* Returns proofs and the overrides required for the transaction.
* @internal
* @returns - `overrides` and `proofs` as an object.
*/
export async function prepareClaim(
quantity: BigNumberish,
activeClaimCondition: ClaimCondition,
merkleMetadata: Record<string, string>,
tokenDecimals: number,
contractWrapper: ContractWrapper<any>,
storage: IStorage,
proofs: BytesLike[] = [utils.hexZeroPad([0], 32)],
): Promise<ClaimVerification> {
const addressToClaim = await contractWrapper.getSignerAddress();
let maxClaimable = BigNumber.from(0);
try {
if (
!activeClaimCondition.merkleRootHash
.toString()
.startsWith(constants.AddressZero)
) {
const claims = await fetchSnapshot(
activeClaimCondition.merkleRootHash.toString(),
merkleMetadata,
storage,
);
const item =
claims &&
claims.find(
(c) => c.address.toLowerCase() === addressToClaim.toLowerCase(),
);
if (item === undefined) {
throw new Error("No claim found for this address");
}
proofs = item.proof;
maxClaimable = ethers.utils.parseUnits(item.maxClaimable, tokenDecimals);
}
} catch (e) {
// have to handle the valid error case that we *do* want to throw on
if ((e as Error)?.message === "No claim found for this address") {
throw e;
}
// other errors we wanna ignore and try to continue
console.warn(
"failed to check claim condition merkle root hash, continuing anyways",
e,
);
}
const overrides = (await contractWrapper.getCallOverrides()) || {};
const price = activeClaimCondition.price;
const currencyAddress = activeClaimCondition.currencyAddress;
if (price.gt(0)) {
if (isNativeToken(currencyAddress)) {
overrides["value"] = BigNumber.from(price)
.mul(quantity)
.div(ethers.utils.parseUnits("1", tokenDecimals));
} else {
await approveErc20Allowance(
contractWrapper,
currencyAddress,
price,
quantity,
tokenDecimals,
);
}
}
return {
overrides,
proofs,
maxQuantityPerTransaction: maxClaimable,
price,
currencyAddress,
};
}
/**
* @internal
* @param merkleRoot
* @param merkleMetadata
* @param storage
*/
export async function fetchSnapshot(
merkleRoot: string,
merkleMetadata: Record<string, string>,
storage: IStorage,
) {
const snapshotUri = merkleMetadata[merkleRoot];
let snapshot = undefined;
if (snapshotUri) {
const raw = await storage.get(snapshotUri);
const snapshotData = SnapshotSchema.parse(raw);
if (merkleRoot === snapshotData.merkleRoot) {
snapshot = snapshotData.claims;
}
}
return snapshot;
}
/**
* @internal
* @param index
* @param claimConditionInput
* @param existingConditions
*/
export async function updateExistingClaimConditions(
index: number,
claimConditionInput: ClaimConditionInput,
existingConditions: ClaimCondition[],
): Promise<ClaimConditionInput[]> {
if (index >= existingConditions.length) {
throw Error(
`Index out of bounds - got index: ${index} with ${existingConditions.length} conditions`,
);
}
// merge input with existing claim condition
const priceDecimals = existingConditions[index].currencyMetadata.decimals;
const priceInWei = existingConditions[index].price;
const priceInTokens = ethers.utils.formatUnits(priceInWei, priceDecimals);
// merge existing (output format) with incoming (input format)
const newConditionParsed = ClaimConditionInputSchema.parse({
...existingConditions[index],
price: priceInTokens,
...claimConditionInput,
});
// convert to output claim condition
const mergedConditionOutput = ClaimConditionOutputSchema.parse({
...newConditionParsed,
price: priceInWei,
});
return existingConditions.map((existingOutput, i) => {
let newConditionAtIndex;
if (i === index) {
newConditionAtIndex = mergedConditionOutput;
} else {
newConditionAtIndex = existingOutput;
}
const formattedPrice = ethers.utils.formatUnits(
newConditionAtIndex.price,
priceDecimals,
);
return {
...newConditionAtIndex,
price: formattedPrice, // manually transform back to input price type
};
});
}
/**
* Fetches the proof for the current signer for a particular wallet.
*
* @param merkleRoot - The merkle root of the condition to check.
* @returns - The proof for the current signer for the specified condition.
*/
export async function getClaimerProofs(
addressToClaim: string,
merkleRoot: string,
tokenDecimals: number,
merkleMetadata: Record<string, string>,
storage: IStorage,
): Promise<{ maxClaimable: BigNumber; proof: string[] }> {
const claims = await fetchSnapshot(merkleRoot, merkleMetadata, storage);
if (claims === undefined) {
return {
proof: [],
maxClaimable: BigNumber.from(0),
};
}
const item = claims.find(
(c) => c.address.toLowerCase() === addressToClaim?.toLowerCase(),
);
if (item === undefined) {
return {
proof: [],
maxClaimable: BigNumber.from(0),
};
}
return {
proof: item.proof,
maxClaimable: ethers.utils.parseUnits(item.maxClaimable, tokenDecimals),
};
}
/**
* Create and uploads snapshots + converts claim conditions to contract format
* @param claimConditionInputs
* @param tokenDecimals
* @param provider
* @param storage
* @internal
*/
export async function processClaimConditionInputs(
claimConditionInputs: ClaimConditionInput[],
tokenDecimals: number,
provider: providers.Provider,
storage: IStorage,
) {
const snapshotInfos: SnapshotInfo[] = [];
const inputsWithSnapshots = await Promise.all(
claimConditionInputs.map(async (conditionInput) => {
// check snapshots and upload if provided
if (conditionInput.snapshot && conditionInput.snapshot.length > 0) {
const snapshotInfo = await createSnapshot(
SnapshotInputSchema.parse(conditionInput.snapshot),
tokenDecimals,
storage,
);
snapshotInfos.push(snapshotInfo);
conditionInput.merkleRootHash = snapshotInfo.merkleRoot;
} else {
// if no snapshot is passed or empty, reset the merkle root
conditionInput.merkleRootHash = utils.hexZeroPad([0], 32);
}
// fill condition with defaults values if not provided
return conditionInput;
}),
);
const parsedInputs = ClaimConditionInputArray.parse(inputsWithSnapshots);
// Convert processed inputs to the format the contract expects, and sort by timestamp
const sortedConditions: IDropClaimCondition.ClaimConditionStruct[] = (
await Promise.all(
parsedInputs.map((c) =>
convertToContractModel(c, tokenDecimals, provider),
),
)
).sort((a, b) => {
const left = BigNumber.from(a.startTimestamp);
const right = BigNumber.from(b.startTimestamp);
if (left.eq(right)) {
return 0;
} else if (left.gt(right)) {
return 1;
} else {
return -1;
}
});
return { snapshotInfos, sortedConditions };
}
/**
* Converts a local SDK model to contract model
* @param c
* @param tokenDecimals
* @param provider
* @internal
*/
async function convertToContractModel(
c: FilledConditionInput,
tokenDecimals: number,
provider: providers.Provider,
): Promise<IDropClaimCondition.ClaimConditionStruct> {
const currency =
c.currencyAddress === constants.AddressZero
? NATIVE_TOKEN_ADDRESS
: c.currencyAddress;
let maxClaimableSupply;
let quantityLimitPerTransaction;
if (c.maxQuantity === "unlimited") {
maxClaimableSupply = ethers.constants.MaxUint256.toString();
} else {
maxClaimableSupply = ethers.utils.parseUnits(c.maxQuantity, tokenDecimals);
}
if (c.quantityLimitPerTransaction === "unlimited") {
quantityLimitPerTransaction = ethers.constants.MaxUint256.toString();
} else {
quantityLimitPerTransaction = ethers.utils.parseUnits(
c.quantityLimitPerTransaction,
tokenDecimals,
);
}
return {
startTimestamp: c.startTime,
maxClaimableSupply,
supplyClaimed: 0,
quantityLimitPerTransaction,
waitTimeInSecondsBetweenClaims: c.waitInSeconds,
pricePerToken: await normalizePriceValue(provider, c.price, currency),
currency,
merkleRoot: c.merkleRootHash,
};
}
/**
* Transforms a contract model to local model
* @param pm
* @param tokenDecimals
* @param provider
* @param merkleMetadata
* @param storage
* @internal
*/
export async function transformResultToClaimCondition(
pm: IDropClaimCondition.ClaimConditionStructOutput,
tokenDecimals: number,
provider: providers.Provider,
merkleMetadata: Record<string, string>,
storage: IStorage,
): Promise<ClaimCondition> {
const cv = await fetchCurrencyValue(provider, pm.currency, pm.pricePerToken);
const claims = await fetchSnapshot(pm.merkleRoot, merkleMetadata, storage);
const maxClaimableSupply = convertToReadableQuantity(
pm.maxClaimableSupply,
tokenDecimals,
);
const quantityLimitPerTransaction = convertToReadableQuantity(
pm.quantityLimitPerTransaction,
tokenDecimals,
);
const availableSupply = convertToReadableQuantity(
BigNumber.from(pm.maxClaimableSupply).sub(pm.supplyClaimed),
tokenDecimals,
);
const currentMintSupply = convertToReadableQuantity(
pm.supplyClaimed,
tokenDecimals,
);
return ClaimConditionOutputSchema.parse({
startTime: pm.startTimestamp,
maxQuantity: maxClaimableSupply,
currentMintSupply,
availableSupply,
quantityLimitPerTransaction,
waitInSeconds: pm.waitTimeInSecondsBetweenClaims.toString(),
price: BigNumber.from(pm.pricePerToken),
currency: pm.currency,
currencyAddress: pm.currency,
currencyMetadata: cv,
merkleRootHash: pm.merkleRoot,
snapshot: claims,
});
}
function convertToReadableQuantity(bn: BigNumber, tokenDecimals: number) {
if (bn.toString() === ethers.constants.MaxUint256.toString()) {
return "unlimited";
} else {
return ethers.utils.formatUnits(bn, tokenDecimals);
}
} | the_stack |
import { AssigneeIdentifierRepresentation } from '../model/assigneeIdentifierRepresentation';
import { FormIdentifierRepresentation } from '../model/formIdentifierRepresentation';
import { TaskRepresentation } from '../model/taskRepresentation';
import { UserIdentifierRepresentation } from '../model/userIdentifierRepresentation';
import { BaseApi } from './base.api';
import { throwIfNotDefined } from '../../../assert';
/**
* Taskactions service.
* @module TaskactionsApi
*/
export class TaskActionsApi extends BaseApi {
/**
* Assign a task to a user
*
*
*
* @param taskId taskId
* @param userIdentifier userIdentifier
* @return Promise<TaskRepresentation>
*/
assignTask(taskId: string, userIdentifier: AssigneeIdentifierRepresentation): Promise<TaskRepresentation> {
throwIfNotDefined(taskId, 'taskId');
throwIfNotDefined(userIdentifier, 'userIdentifier');
let postBody = userIdentifier;
let pathParams = {
'taskId': taskId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/action/assign', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, TaskRepresentation);
}
/**
* Attach a form to a task
*
*
*
* @param taskId taskId
* @param formIdentifier formIdentifier
* @return Promise<{}>
*/
attachForm(taskId: string, formIdentifier: FormIdentifierRepresentation): Promise<any> {
throwIfNotDefined(taskId, 'taskId');
throwIfNotDefined(formIdentifier, 'formIdentifier');
let postBody = formIdentifier;
let pathParams = {
'taskId': taskId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/action/attach-form', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Claim a task
*
* To claim a task (in case the task is assigned to a group)
*
* @param taskId taskId
* @return Promise<{}>
*/
claimTask(taskId: string): Promise<any> {
throwIfNotDefined(taskId, 'taskId');
let postBody = null;
let pathParams = {
'taskId': taskId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/action/claim', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Complete a task
*
* Use this endpoint to complete a standalone task or task without a form
*
* @param taskId taskId
* @return Promise<{}>
*/
completeTask(taskId: string): Promise<any> {
throwIfNotDefined(taskId, 'taskId');
let postBody = null;
let pathParams = {
'taskId': taskId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/action/complete', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Delegate a task
*
*
*
* @param taskId taskId
* @param userIdentifier userIdentifier
* @return Promise<{}>
*/
delegateTask(taskId: string, userIdentifier: UserIdentifierRepresentation): Promise<any> {
throwIfNotDefined(taskId, 'taskId');
throwIfNotDefined(userIdentifier, 'userIdentifier');
let postBody = userIdentifier;
let pathParams = {
'taskId': taskId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/action/delegate', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Involve a group with a task
*
*
*
* @param taskId taskId
* @param groupId groupId
* @return Promise<{}>
*/
involveGroup(taskId: string, groupId: string): Promise<any> {
throwIfNotDefined(taskId, 'taskId');
throwIfNotDefined(groupId, 'groupId');
let postBody = null;
let pathParams = {
'taskId': taskId, 'groupId': groupId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/groups/{groupId}', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Involve a user with a task
*
*
*
* @param taskId taskId
* @param userIdentifier userIdentifier
* @return Promise<{}>
*/
involveUser(taskId: string, userIdentifier: UserIdentifierRepresentation): Promise<any> {
throwIfNotDefined(taskId, 'taskId');
throwIfNotDefined(userIdentifier, 'userIdentifier');
let postBody = userIdentifier;
let pathParams = {
'taskId': taskId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/action/involve', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Remove a form from a task
*
*
*
* @param taskId taskId
* @return Promise<{}>
*/
removeForm(taskId: string): Promise<any> {
throwIfNotDefined(taskId, 'taskId');
let postBody = null;
let pathParams = {
'taskId': taskId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/action/remove-form', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Remove an involved group from a task
*
*
*
* @param taskId taskId
* @param groupId groupId
* @return Promise<{}>
*/
removeInvolvedUser(taskId: string, identifier: string | UserIdentifierRepresentation): Promise<any> {
throwIfNotDefined(taskId, 'taskId');
throwIfNotDefined(identifier, 'identifier');
let pathParams = {
'taskId': taskId, 'groupId': identifier
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
if (identifier instanceof String) {
let postBody = null;
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/groups/{groupId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
} else {
let postBody = identifier;
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/action/remove-involved', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
}
/**
* Resolve a task
*
*
*
* @param taskId taskId
* @return Promise<{}>
*/
resolveTask(taskId: string): Promise<any> {
throwIfNotDefined(taskId, 'taskId');
let postBody = null;
let pathParams = {
'taskId': taskId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/action/resolve', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Unclaim a task
*
* To unclaim a task (in case the task was assigned to a group)
*
* @param taskId taskId
* @return Promise<{}>
*/
unclaimTask(taskId: string): Promise<any> {
throwIfNotDefined(taskId, 'taskId');
let postBody = null;
let pathParams = {
'taskId': taskId
};
let queryParams = {};
let headerParams = {};
let formParams = {};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/tasks/{taskId}/action/unclaim', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
} | the_stack |
import { Component, Inject } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import * as dataverseActions from '../../shared/actions/dataverse.actions';
import * as datasetActions from '../../shared/actions/dataset.actions';
import * as datatypesActions from '../../shared/actions/datatype.actions';
import * as indexesActions from '../../shared/actions/index.actions';
import * as functionActions from '../../shared/actions/function.actions';
import { ViewChild} from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import {MatTreeNestedDataSource} from "@angular/material/tree";
import {NestedTreeControl} from "@angular/cdk/tree";
import {Data} from "@angular/router";
interface DataTypeNode {
DatatypeName: string;
DatatypeType?: string;
fields?: DataTypeNode[];
primitive: boolean;
isNullable?: boolean;
isMissable?: boolean;
OrderedList?: boolean;
UnorderedList?: boolean;
anonymous: boolean;
}
enum MetadataTypes {
record = "RECORD",
orderedList = "ORDEREDLIST",
unorderedList = "UNORDEREDLIST"
}
enum MetadataTypesNames {
record = "Record",
orderedList = "Ordered List",
unorderedList = "Unordered List"
}
enum MetadataListTypes {
orderedList = "OrderedList",
unorderedList = "UnorderedList"
}
@Component({
moduleId: module.id,
selector: 'awc-metadata',
templateUrl: 'metadata.component.html',
styleUrls: ['metadata.component.scss']
})
export class MetadataComponent {
dataverses$: Observable<any>;
dataverses: any;
datasetsFiltered: any;
datasets$: Observable<any>;
datasets: any;
datatypesFiltered :any;
datatypes$: Observable<any>;
datatypes: any;
indexesFiltered: any;
indexes$: Observable<any>;
indexes: any;
functionsFiltered: any;
functions$: Observable<any>;
functions: any;
curr_dialogRef: any;
dialogActive: boolean;
//added variables for sample
sampleDataset$: Observable<any>;
sampleDataset: any;
checkedDataverses: any = {};
//added variables for flattening
datatypesDict: Object;
dialogSamples = {};
constructor(private store: Store<any>, public dialog: MatDialog) {
this.refreshMetadata();
this.dialogActive = false;
}
ngOnInit() {
this.dataverses$ = this.store.select(s => s.dataverse.dataverses.results);
// Watching for Dataverses
this.dataverses$ = this.store.select(s => s.dataverse.dataverses.results);
this.dataverses$.subscribe((data: any[]) => {
this.dataverses = data;
if (Object.keys(this.checkedDataverses).length > 0) {
for (let dataverse of this.dataverses) {
if (this.checkedDataverses[dataverse.DataverseName]) {
dataverse.active = true;
}
}
this.checkedDataverses = {};
}
});
// Watching for Datasets
this.datasets$ = this.store.select(s => s.dataset.datasets.results);
this.datasets$.subscribe((data: any[]) => {
this.datasets = data;
this.datasetsFiltered = this.filter(this.datasets);
});
// Watching for Datatypes
this.datatypes$ = this.store.select(s => s.datatype.datatypes.results);
this.datatypes$.subscribe((data: any[]) => {
this.datatypes = data;
this.datatypesFiltered = this.filter(this.datatypes);
this.datatypesDict = this.createDatatypeDict(this.datatypes);
});
// Watching for indexes
this.indexes$ = this.store.select(s => s.index.indexes.results);
this.indexes$.subscribe((data: any[]) => {
this.indexes = data;
this.indexesFiltered = this.filter(this.indexes);
});
//Watching for functions
this.functions$ = this.store.select(s => s.functions.functions.results);
this.functions$.subscribe((data: any[]) => {
this.functions = data;
this.functionsFiltered = this.filter(this.functions);
});
// Watching for samples
this.sampleDataset$ = this.store.select(s => s.dataset.sample);
}
refreshMetadata() {
if (this.dataverses) {
for (let dataverse of this.dataverses) {
if (dataverse.active) {
this.checkedDataverses[dataverse.DataverseName] = true;
}
}
}
this.store.dispatch(new dataverseActions.SelectDataverses('-'));
this.store.dispatch(new datasetActions.SelectDatasets('-'));
this.store.dispatch(new datatypesActions.SelectDatatypes('-'));
this.store.dispatch(new indexesActions.SelectIndexes('-'));
this.store.dispatch(new functionActions.SelectFunctions('-'));
}
dataverseFilter = {}
dataverseFilterMap = new Map();
createDatatypeDict(data) {
let newDict = new Object();
if (data) {
for (let i=0; i < data.length; i++) {
newDict[data[i].DataverseName + "." + data[i].DatatypeName] = i;
}
}
return newDict;
}
filter(data){
let results = [];
if (data) {
for (let i=0; i< data.length; i++){
let keyCompare = data[i].DataverseName
this.dataverseFilterMap.forEach((value: boolean, key: string) => {
if (keyCompare === key) {
results.push(data[i]);
}
});
}
}
return results;
}
@ViewChild('datasetsPanel') datasetsPanel;
panelOpenState: boolean = false;
checkStatus = [];
generateFilter(dataverse, event, i) {
if (this.checkStatus[i] == undefined) {
this.checkStatus.push(event.checked);
} else {
this.checkStatus[i] = event.checked;
}
if (event.checked === true) {
this.dataverseFilter[dataverse] = event.checked;
this.dataverseFilterMap.set(dataverse, event.checked);
} else {
delete this.dataverseFilter[dataverse];
this.dataverseFilterMap.delete(dataverse);
}
this.datasetsFiltered = this.filter(this.datasets);
this.datatypesFiltered = this.filter(this.datatypes);
this.indexesFiltered = this.filter(this.indexes);
this.functionsFiltered = this.filter(this.functions);
/* Open the dataset expansion panel if there is anything to show */
if (this.datasetsFiltered.length > 0) {
this.panelOpenState = true;
} else {
this.panelOpenState = false;
}
}
/*
* Traverse Metadata recursively, handles Metadata dataverse as well as regular dataverses
*/
recursiveMetadataTraverse(data, toCreate): Object {
toCreate.DatatypeName = data.DatatypeName;
//primitive == no Derived field or Derived == undefined
if (data.Derived == undefined) {
//if primitive
toCreate.DatatypeName = data.DatatypeName;
toCreate.fields = [];
toCreate.primitive = true;
} else {
//if not primitive, need to check .Derived exists every time, or else handle primitive type
toCreate.DatatypeType = data.Derived.Tag;
//determine what type it is (Record, Ordered List or Unordered List). Ordered list and unordered list are handled the same
let list_type = "";
switch(toCreate.DatatypeType) {
case MetadataTypes.record:
toCreate.DatatypeType = MetadataTypesNames.record;
break;
case MetadataTypes.orderedList:
toCreate.DatatypeType = MetadataTypesNames.orderedList;
list_type = MetadataListTypes.orderedList;
break;
case MetadataTypes.unorderedList:
toCreate.DatatypeType = MetadataTypesNames.unorderedList;
list_type = MetadataListTypes.unorderedList;
break;
default:
break;
}
toCreate.fields = [];
if (data.Derived.Tag == "RECORD") {
// if it is a record, we must iterate over the fields and may have to recurse if there is a non primitive type
for (let field of data.Derived.Record.Fields) {
//if it is NOT a primitive type
if ((data.DataverseName + "." + field.FieldType) in this.datatypesDict &&
this.datatypes[this.datatypesDict[data.DataverseName + "." + field.FieldType]].Derived != undefined) {
field.Nested = true;
//get the nested object from datatypesDict
let nestedName = this.datatypesDict[data.DataverseName + "." + field.FieldType];
let nestedObject = this.datatypes[nestedName];
let nested_field = {
DatatypeName: field.FieldName,
DatatypeType: field.FieldType,
primitive: false,
fields: [],
isNullable: field.IsNullable,
isMissable: field.IsMissable,
OrderedList: false,
UnorderedList: false,
anonymous: nestedObject.Derived.IsAnonymous,
}
if (nestedObject.Derived.Tag == "RECORD") {
//object and should iterate over fields
field.NestedType = "Record";
field.NestedTypeType = nestedObject.DatatypeName;
let recurse_result = this.recursiveMetadataTraverse(nestedObject, {})
field.NestedRecord = recurse_result[0];
let toAdd = recurse_result[1];
toAdd.DatatypeType = "Record";
toAdd.primitive = false;
toAdd.anonymous = nestedObject.Derived.IsAnonymous;
nested_field.fields.push(toAdd);
}
else {
let listObject;
let nestedListType = "";
let nestedListTypeName = "";
//determine the type of list of the nested object
if (nestedObject.Derived.Tag == MetadataTypes.orderedList) {
nestedListType = MetadataListTypes.orderedList;
nestedListTypeName = MetadataTypesNames.orderedList;
} else {
nestedListType = MetadataListTypes.unorderedList;
nestedListTypeName = MetadataTypesNames.unorderedList;
}
nested_field[nestedListType] = true;
field.NestedType = nestedListTypeName;
if (data.DataverseName + "." + nestedObject.Derived[nestedListType] in this.datatypesDict) {
field.primitive = false;
listObject = this.datatypes[this.datatypesDict[data.DataverseName + "." + nestedObject.Derived[nestedListType]]];
let recurse_result = this.recursiveMetadataTraverse(listObject, {});
field.NestedRecord = recurse_result[0];
let toAdd = recurse_result[1];
if (toAdd.DatatypeType == nestedListTypeName) {
toAdd[nestedListType] = true;
} else {
toAdd[nestedListType] = false;
}
toAdd.primitive = false;
if (listObject.Derived != undefined)
toAdd.anonymous = listObject.Derived.IsAnonymous;
nested_field.fields.push(toAdd);
} else {
field.primitive = true;
nested_field.fields.push({
DatatypeName: nestedObject.Derived[nestedListType],
[nestedListType]: true,
primitive: true,
});
}
}
toCreate.fields.push(nested_field);
}
else {
field.Nested = false;
toCreate.fields.push({
DatatypeName: field.FieldName,
DatatypeType: field.FieldType,
primitive: true,
isMissable: field.IsMissable,
isNullable: field.IsNullable,
anonymous: false,
});
}
}
} else {
let listItem = this.datatypes[this.datatypesDict[data.DataverseName + "." + data.Derived[list_type]]];
toCreate[list_type] = true;
if (listItem == undefined) {
toCreate.fields.push({
DatatypeName: data.Derived[list_type],
[list_type]: true,
primitive: true,
anonymous: data.Derived.IsAnonymous,
})
} else {
let recurse_result = this.recursiveMetadataTraverse(listItem, {});
let toAdd = recurse_result[1];
toAdd.primitive = false;
if (listItem.Derived != undefined)
toAdd.anonymous = listItem.Derived.IsAnonymous;
toCreate.fields.push(toAdd);
}
}
}
return [data, toCreate];
}
/*
* opens the metadata inspector
*/
openMetadataInspectorDialog(data, metadata_type): void {
let metadata = JSON.stringify(data, null, 8);
metadata = metadata.replace(/^{/, '');
metadata = metadata.replace(/^\n/, '');
metadata = metadata.replace(/}$/, '');
//if metadata_type is dataset, sample said dataset and add to data to be displayed.
data.guts = metadata;
data.MetadataType = metadata_type
if (metadata_type == 'dataset') {
let dataset = "`" + data.DataverseName + "`" + "." + "`" + data.DatasetName + "`";
this.store.dispatch(new datasetActions.SampleDataset({dataset: dataset}));
this.sampleDataset$.subscribe((resp: any[]) => {
if (resp) {
this.dialogSamples[dataset] = JSON.stringify(resp[dataset], null, 2);
data.sample = this.dialogSamples[dataset];
} else {
data.sample = undefined;
}
});
}
//flatten data if datatype
if (metadata_type == 'datatype') {
let new_datatype = new Object();
let recurseResults = this.recursiveMetadataTraverse(data, new_datatype);
let converted = recurseResults[1];
data = recurseResults[0];
data.DataTypeTree = converted;
}
this.curr_dialogRef = this.dialog.open(DialogMetadataInspector, {
minWidth: '500px',
data: data,
hasBackdrop: false
});
}
}
@Component({
selector: 'dataset-create-dialog',
templateUrl: 'metadata-inspector.component.html',
styleUrls: ['metadata-inspector.component.scss']
})
export class DialogMetadataInspector {
constructor( public dialogCreateDsRef: MatDialogRef<DialogMetadataInspector>,
@Inject(MAT_DIALOG_DATA) public data: any) {
if (data.MetadataType == "datatype") {
this.dataSource.data = data.DataTypeTree.fields;
}
}
onClickClose() {
this.dialogCreateDsRef.close(this.data['dialogID']);
}
onClickJSON() {
this.showGuts = true;
this.hideJSONButton = true;
}
onClickParsed() {
this.showGuts = false;
this.hideJSONButton = false;
}
showGuts = false;
hideJSONButton = false
treeControl = new NestedTreeControl<DataTypeNode>(node => node.fields);
dataSource = new MatTreeNestedDataSource<DataTypeNode>();
hasChild = (_: number, node: DataTypeNode) => !!node.fields && node.fields.length > 0;
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/moveCollectionsMappers";
import * as Parameters from "../models/parameters";
import { ResourceMoverServiceAPIContext } from "../resourceMoverServiceAPIContext";
/** Class representing a MoveCollections. */
export class MoveCollections {
private readonly client: ResourceMoverServiceAPIContext;
/**
* Create a MoveCollections.
* @param {ResourceMoverServiceAPIContext} client Reference to the service client.
*/
constructor(client: ResourceMoverServiceAPIContext) {
this.client = client;
}
/**
* Creates or updates a move collection.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsCreateResponse>
*/
create(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsCreateOptionalParams): Promise<Models.MoveCollectionsCreateResponse>;
/**
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param callback The callback
*/
create(resourceGroupName: string, moveCollectionName: string, callback: msRest.ServiceCallback<Models.MoveCollection>): void;
/**
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param options The optional parameters
* @param callback The callback
*/
create(resourceGroupName: string, moveCollectionName: string, options: Models.MoveCollectionsCreateOptionalParams, callback: msRest.ServiceCallback<Models.MoveCollection>): void;
create(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsCreateOptionalParams | msRest.ServiceCallback<Models.MoveCollection>, callback?: msRest.ServiceCallback<Models.MoveCollection>): Promise<Models.MoveCollectionsCreateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
moveCollectionName,
options
},
createOperationSpec,
callback) as Promise<Models.MoveCollectionsCreateResponse>;
}
/**
* Updates a move collection.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsUpdateResponse>
*/
update(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsUpdateOptionalParams): Promise<Models.MoveCollectionsUpdateResponse>;
/**
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param callback The callback
*/
update(resourceGroupName: string, moveCollectionName: string, callback: msRest.ServiceCallback<Models.MoveCollection>): void;
/**
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, moveCollectionName: string, options: Models.MoveCollectionsUpdateOptionalParams, callback: msRest.ServiceCallback<Models.MoveCollection>): void;
update(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsUpdateOptionalParams | msRest.ServiceCallback<Models.MoveCollection>, callback?: msRest.ServiceCallback<Models.MoveCollection>): Promise<Models.MoveCollectionsUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
moveCollectionName,
options
},
updateOperationSpec,
callback) as Promise<Models.MoveCollectionsUpdateResponse>;
}
/**
* Deletes a move collection.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsDeleteMethodResponse>
*/
deleteMethod(resourceGroupName: string, moveCollectionName: string, options?: msRest.RequestOptionsBase): Promise<Models.MoveCollectionsDeleteMethodResponse> {
return this.beginDeleteMethod(resourceGroupName,moveCollectionName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.MoveCollectionsDeleteMethodResponse>;
}
/**
* Gets the move collection.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsGetResponse>
*/
get(resourceGroupName: string, moveCollectionName: string, options?: msRest.RequestOptionsBase): Promise<Models.MoveCollectionsGetResponse>;
/**
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param callback The callback
*/
get(resourceGroupName: string, moveCollectionName: string, callback: msRest.ServiceCallback<Models.MoveCollection>): void;
/**
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, moveCollectionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MoveCollection>): void;
get(resourceGroupName: string, moveCollectionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MoveCollection>, callback?: msRest.ServiceCallback<Models.MoveCollection>): Promise<Models.MoveCollectionsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
moveCollectionName,
options
},
getOperationSpec,
callback) as Promise<Models.MoveCollectionsGetResponse>;
}
/**
* Initiates prepare for the set of resources included in the request body. The prepare operation
* is on the moveResources that are in the moveState 'PreparePending' or 'PrepareFailed', on a
* successful completion the moveResource moveState do a transition to MovePending. To aid the user
* to prerequisite the operation the client can call operation with validateOnly property set to
* true.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsPrepareResponse>
*/
prepare(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsPrepareOptionalParams): Promise<Models.MoveCollectionsPrepareResponse> {
return this.beginPrepare(resourceGroupName,moveCollectionName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.MoveCollectionsPrepareResponse>;
}
/**
* Moves the set of resources included in the request body. The move operation is triggered after
* the moveResources are in the moveState 'MovePending' or 'MoveFailed', on a successful completion
* the moveResource moveState do a transition to CommitPending. To aid the user to prerequisite the
* operation the client can call operation with validateOnly property set to true.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsInitiateMoveResponse>
*/
initiateMove(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsInitiateMoveOptionalParams): Promise<Models.MoveCollectionsInitiateMoveResponse> {
return this.beginInitiateMove(resourceGroupName,moveCollectionName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.MoveCollectionsInitiateMoveResponse>;
}
/**
* Commits the set of resources included in the request body. The commit operation is triggered on
* the moveResources in the moveState 'CommitPending' or 'CommitFailed', on a successful completion
* the moveResource moveState do a transition to Committed. To aid the user to prerequisite the
* operation the client can call operation with validateOnly property set to true.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsCommitResponse>
*/
commit(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsCommitOptionalParams): Promise<Models.MoveCollectionsCommitResponse> {
return this.beginCommit(resourceGroupName,moveCollectionName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.MoveCollectionsCommitResponse>;
}
/**
* Discards the set of resources included in the request body. The discard operation is triggered
* on the moveResources in the moveState 'CommitPending' or 'DiscardFailed', on a successful
* completion the moveResource moveState do a transition to MovePending. To aid the user to
* prerequisite the operation the client can call operation with validateOnly property set to true.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsDiscardResponse>
*/
discard(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsDiscardOptionalParams): Promise<Models.MoveCollectionsDiscardResponse> {
return this.beginDiscard(resourceGroupName,moveCollectionName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.MoveCollectionsDiscardResponse>;
}
/**
* Computes, resolves and validate the dependencies of the moveResources in the move collection.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsResolveDependenciesResponse>
*/
resolveDependencies(resourceGroupName: string, moveCollectionName: string, options?: msRest.RequestOptionsBase): Promise<Models.MoveCollectionsResolveDependenciesResponse> {
return this.beginResolveDependencies(resourceGroupName,moveCollectionName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.MoveCollectionsResolveDependenciesResponse>;
}
/**
* Removes the set of move resources included in the request body from move collection. The
* orchestration is done by service. To aid the user to prerequisite the operation the client can
* call operation with validateOnly property set to true.
* @param resourceGroupName
* @param moveCollectionName
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsBulkRemoveResponse>
*/
bulkRemove(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsBulkRemoveOptionalParams): Promise<Models.MoveCollectionsBulkRemoveResponse> {
return this.beginBulkRemove(resourceGroupName,moveCollectionName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.MoveCollectionsBulkRemoveResponse>;
}
/**
* Get all the Move Collections in the subscription.
* @summary Get all Move Collections.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsListMoveCollectionsBySubscriptionResponse>
*/
listMoveCollectionsBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.MoveCollectionsListMoveCollectionsBySubscriptionResponse>;
/**
* @param callback The callback
*/
listMoveCollectionsBySubscription(callback: msRest.ServiceCallback<Models.MoveCollectionResultList>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listMoveCollectionsBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MoveCollectionResultList>): void;
listMoveCollectionsBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MoveCollectionResultList>, callback?: msRest.ServiceCallback<Models.MoveCollectionResultList>): Promise<Models.MoveCollectionsListMoveCollectionsBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
options
},
listMoveCollectionsBySubscriptionOperationSpec,
callback) as Promise<Models.MoveCollectionsListMoveCollectionsBySubscriptionResponse>;
}
/**
* Get all the Move Collections in the resource group.
* @summary Get all Move Collections.
* @param resourceGroupName The Resource Group Name.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsListMoveCollectionsByResourceGroupResponse>
*/
listMoveCollectionsByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.MoveCollectionsListMoveCollectionsByResourceGroupResponse>;
/**
* @param resourceGroupName The Resource Group Name.
* @param callback The callback
*/
listMoveCollectionsByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.MoveCollectionResultList>): void;
/**
* @param resourceGroupName The Resource Group Name.
* @param options The optional parameters
* @param callback The callback
*/
listMoveCollectionsByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MoveCollectionResultList>): void;
listMoveCollectionsByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MoveCollectionResultList>, callback?: msRest.ServiceCallback<Models.MoveCollectionResultList>): Promise<Models.MoveCollectionsListMoveCollectionsByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listMoveCollectionsByResourceGroupOperationSpec,
callback) as Promise<Models.MoveCollectionsListMoveCollectionsByResourceGroupResponse>;
}
/**
* List of the move resources for which an arm resource is required for.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param sourceId The sourceId for which the api is invoked.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsListRequiredForResponse>
*/
listRequiredFor(resourceGroupName: string, moveCollectionName: string, sourceId: string, options?: msRest.RequestOptionsBase): Promise<Models.MoveCollectionsListRequiredForResponse>;
/**
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param sourceId The sourceId for which the api is invoked.
* @param callback The callback
*/
listRequiredFor(resourceGroupName: string, moveCollectionName: string, sourceId: string, callback: msRest.ServiceCallback<Models.RequiredForResourcesCollection>): void;
/**
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param sourceId The sourceId for which the api is invoked.
* @param options The optional parameters
* @param callback The callback
*/
listRequiredFor(resourceGroupName: string, moveCollectionName: string, sourceId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RequiredForResourcesCollection>): void;
listRequiredFor(resourceGroupName: string, moveCollectionName: string, sourceId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RequiredForResourcesCollection>, callback?: msRest.ServiceCallback<Models.RequiredForResourcesCollection>): Promise<Models.MoveCollectionsListRequiredForResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
moveCollectionName,
sourceId,
options
},
listRequiredForOperationSpec,
callback) as Promise<Models.MoveCollectionsListRequiredForResponse>;
}
/**
* Deletes a move collection.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, moveCollectionName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
moveCollectionName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* Initiates prepare for the set of resources included in the request body. The prepare operation
* is on the moveResources that are in the moveState 'PreparePending' or 'PrepareFailed', on a
* successful completion the moveResource moveState do a transition to MovePending. To aid the user
* to prerequisite the operation the client can call operation with validateOnly property set to
* true.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginPrepare(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsBeginPrepareOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
moveCollectionName,
options
},
beginPrepareOperationSpec,
options);
}
/**
* Moves the set of resources included in the request body. The move operation is triggered after
* the moveResources are in the moveState 'MovePending' or 'MoveFailed', on a successful completion
* the moveResource moveState do a transition to CommitPending. To aid the user to prerequisite the
* operation the client can call operation with validateOnly property set to true.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginInitiateMove(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsBeginInitiateMoveOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
moveCollectionName,
options
},
beginInitiateMoveOperationSpec,
options);
}
/**
* Commits the set of resources included in the request body. The commit operation is triggered on
* the moveResources in the moveState 'CommitPending' or 'CommitFailed', on a successful completion
* the moveResource moveState do a transition to Committed. To aid the user to prerequisite the
* operation the client can call operation with validateOnly property set to true.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCommit(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsBeginCommitOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
moveCollectionName,
options
},
beginCommitOperationSpec,
options);
}
/**
* Discards the set of resources included in the request body. The discard operation is triggered
* on the moveResources in the moveState 'CommitPending' or 'DiscardFailed', on a successful
* completion the moveResource moveState do a transition to MovePending. To aid the user to
* prerequisite the operation the client can call operation with validateOnly property set to true.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDiscard(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsBeginDiscardOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
moveCollectionName,
options
},
beginDiscardOperationSpec,
options);
}
/**
* Computes, resolves and validate the dependencies of the moveResources in the move collection.
* @param resourceGroupName The Resource Group Name.
* @param moveCollectionName The Move Collection Name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginResolveDependencies(resourceGroupName: string, moveCollectionName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
moveCollectionName,
options
},
beginResolveDependenciesOperationSpec,
options);
}
/**
* Removes the set of move resources included in the request body from move collection. The
* orchestration is done by service. To aid the user to prerequisite the operation the client can
* call operation with validateOnly property set to true.
* @param resourceGroupName
* @param moveCollectionName
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginBulkRemove(resourceGroupName: string, moveCollectionName: string, options?: Models.MoveCollectionsBeginBulkRemoveOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
moveCollectionName,
options
},
beginBulkRemoveOperationSpec,
options);
}
/**
* Get all the Move Collections in the subscription.
* @summary Get all Move Collections.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsListMoveCollectionsBySubscriptionNextResponse>
*/
listMoveCollectionsBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.MoveCollectionsListMoveCollectionsBySubscriptionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listMoveCollectionsBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.MoveCollectionResultList>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listMoveCollectionsBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MoveCollectionResultList>): void;
listMoveCollectionsBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MoveCollectionResultList>, callback?: msRest.ServiceCallback<Models.MoveCollectionResultList>): Promise<Models.MoveCollectionsListMoveCollectionsBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listMoveCollectionsBySubscriptionNextOperationSpec,
callback) as Promise<Models.MoveCollectionsListMoveCollectionsBySubscriptionNextResponse>;
}
/**
* Get all the Move Collections in the resource group.
* @summary Get all Move Collections.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.MoveCollectionsListMoveCollectionsByResourceGroupNextResponse>
*/
listMoveCollectionsByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.MoveCollectionsListMoveCollectionsByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listMoveCollectionsByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.MoveCollectionResultList>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listMoveCollectionsByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MoveCollectionResultList>): void;
listMoveCollectionsByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MoveCollectionResultList>, callback?: msRest.ServiceCallback<Models.MoveCollectionResultList>): Promise<Models.MoveCollectionsListMoveCollectionsByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listMoveCollectionsByResourceGroupNextOperationSpec,
callback) as Promise<Models.MoveCollectionsListMoveCollectionsByResourceGroupNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const createOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"body"
],
mapper: Mappers.MoveCollection
},
responses: {
200: {
bodyMapper: Mappers.MoveCollection
},
201: {
bodyMapper: Mappers.MoveCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"body"
],
mapper: Mappers.UpdateMoveCollectionRequest
},
responses: {
200: {
bodyMapper: Mappers.MoveCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MoveCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listMoveCollectionsBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Migrate/moveCollections",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MoveCollectionResultList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listMoveCollectionsByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MoveCollectionResultList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listRequiredForOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}/requiredFor",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.sourceId,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.RequiredForResourcesCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginPrepareOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}/prepare",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"body"
],
mapper: Mappers.PrepareRequest
},
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginInitiateMoveOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}/initiateMove",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"body"
],
mapper: Mappers.ResourceMoveRequest
},
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCommitOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}/commit",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"body"
],
mapper: Mappers.CommitRequest
},
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDiscardOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}/discard",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"body"
],
mapper: Mappers.DiscardRequest
},
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginResolveDependenciesOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}/resolveDependencies",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginBulkRemoveOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}/bulkRemove",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.moveCollectionName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"body"
],
mapper: Mappers.BulkRemoveRequest
},
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listMoveCollectionsBySubscriptionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MoveCollectionResultList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listMoveCollectionsByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MoveCollectionResultList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import type { JsonlDB } from "@alcalzone/jsonl-db";
import { TypedEventEmitter } from "@zwave-js/shared";
import { CommandClasses } from "../capabilities/CommandClasses";
import { isZWaveError, ZWaveError, ZWaveErrorCodes } from "../error/ZWaveError";
import type { ValueMetadata } from "../values/Metadata";
/** Uniquely identifies to which CC, endpoint and property a value belongs to */
export interface ValueID {
commandClass: CommandClasses;
endpoint?: number;
property: string | number;
propertyKey?: string | number;
}
export interface TranslatedValueID extends ValueID {
commandClassName: string;
propertyName?: string;
propertyKeyName?: string;
}
export interface ValueUpdatedArgs extends ValueID {
prevValue: unknown;
newValue: unknown;
}
export interface ValueAddedArgs extends ValueID {
newValue: unknown;
}
export interface ValueRemovedArgs extends ValueID {
prevValue: unknown;
}
export interface ValueNotificationArgs extends ValueID {
value: unknown;
}
export interface MetadataUpdatedArgs extends ValueID {
metadata: ValueMetadata | undefined;
}
type ValueAddedCallback = (args: ValueAddedArgs) => void;
type ValueUpdatedCallback = (args: ValueUpdatedArgs) => void;
type ValueRemovedCallback = (args: ValueRemovedArgs) => void;
type ValueNotificationCallback = (args: ValueNotificationArgs) => void;
type MetadataUpdatedCallback = (args: MetadataUpdatedArgs) => void;
interface ValueDBEventCallbacks {
"value added": ValueAddedCallback;
"value updated": ValueUpdatedCallback;
"value removed": ValueRemovedCallback;
"value notification": ValueNotificationCallback;
"metadata updated": MetadataUpdatedCallback;
}
type ValueDBEvents = Extract<keyof ValueDBEventCallbacks, string>;
export function isValueID(param: Record<any, any>): param is ValueID {
// commandClass is mandatory and must be numeric
if (typeof param.commandClass !== "number") return false;
// property is mandatory and must be a number or string
if (
typeof param.property !== "number" &&
typeof param.property !== "string"
) {
return false;
}
// propertyKey is optional and must be a number or string
if (
param.propertyKey != undefined &&
typeof param.propertyKey !== "number" &&
typeof param.propertyKey !== "string"
) {
return false;
}
// endpoint is optional and must be a number
if (param.endpoint != undefined && typeof param.endpoint !== "number") {
return false;
}
return true;
}
export function assertValueID(
param: Record<any, any>,
): asserts param is ValueID {
if (!isValueID(param)) {
throw new ZWaveError(
`Invalid ValueID passed!`,
ZWaveErrorCodes.Argument_Invalid,
);
}
}
/**
* Ensures all Value ID properties are in the same order and there are no extraneous properties.
* A normalized value ID can be used as a database key */
export function normalizeValueID(valueID: ValueID): ValueID {
// valueIdToString is used by all other methods of the Value DB.
// Since those may be called by unsanitized value IDs, we need
// to make sure we have a valid value ID at our hands
assertValueID(valueID);
const { commandClass, endpoint, property, propertyKey } = valueID;
const jsonKey: ValueID = {
commandClass,
endpoint: endpoint ?? 0,
property,
};
if (propertyKey != undefined) jsonKey.propertyKey = propertyKey;
return jsonKey;
}
export function valueIdToString(valueID: ValueID): string {
return JSON.stringify(normalizeValueID(valueID));
}
export interface SetValueOptions {
/** When this is true, no event will be emitted for the value change */
noEvent?: boolean;
/** When this is true, */
noThrow?: boolean;
/**
* When this is `false`, the value will not be stored and a `value notification` event will be emitted instead (implies `noEvent: false`).
*/
stateful?: boolean;
}
/**
* The value store for a single node
*/
export class ValueDB extends TypedEventEmitter<ValueDBEventCallbacks> {
// This is a wrapper around the driver's on-disk value and metadata key value stores
/**
* @param nodeId The ID of the node this Value DB belongs to
* @param valueDB The DB instance which stores values
* @param metadataDB The DB instance which stores metadata
* @param ownKeys An optional pre-created index of this ValueDB's own keys
*/
public constructor(
nodeId: number,
valueDB: JsonlDB,
metadataDB: JsonlDB<ValueMetadata>,
ownKeys?: Set<string>,
) {
super();
this.nodeId = nodeId;
this._db = valueDB;
this._metadata = metadataDB;
this._index = ownKeys ?? this.buildIndex();
}
private nodeId: number;
private _db: JsonlDB<unknown>;
private _metadata: JsonlDB<ValueMetadata>;
private _index: Set<string>;
private buildIndex(): Set<string> {
const ret = new Set<string>();
for (const key of this._db.keys()) {
if (compareDBKeyFast(key, this.nodeId)) ret.add(key);
}
for (const key of this._metadata.keys()) {
if (!ret.has(key) && compareDBKeyFast(key, this.nodeId))
ret.add(key);
}
return ret;
}
private valueIdToDBKey(valueID: ValueID): string {
return JSON.stringify({
nodeId: this.nodeId,
...normalizeValueID(valueID),
});
}
private dbKeyToValueId(key: string): { nodeId: number } & ValueID {
try {
// Try the dumb but fast way first
return dbKeyToValueIdFast(key);
} catch {
// Fall back to JSON.parse if anything went wrong
return JSON.parse(key);
}
}
/**
* Stores a value for a given value id
*/
public setValue(
valueId: ValueID,
value: unknown,
options: SetValueOptions = {},
): void {
let dbKey: string;
try {
dbKey = this.valueIdToDBKey(valueId);
} catch (e) {
if (
isZWaveError(e) &&
e.code === ZWaveErrorCodes.Argument_Invalid &&
options.noThrow === true
) {
// ignore invalid value IDs
return;
}
throw e;
}
if (options.stateful !== false) {
const cbArg: ValueAddedArgs | ValueUpdatedArgs = {
...valueId,
newValue: value,
};
let event: ValueDBEvents;
if (this._db.has(dbKey)) {
event = "value updated";
(cbArg as ValueUpdatedArgs).prevValue = this._db.get(dbKey);
} else {
event = "value added";
}
this._index.add(dbKey);
this._db.set(dbKey, value);
if (
valueId.commandClass !== CommandClasses._NONE &&
options.noEvent !== true
) {
this.emit(event, cbArg);
}
} else if (valueId.commandClass !== CommandClasses._NONE) {
// For non-stateful values just emit a notification
this.emit("value notification", {
...valueId,
value,
});
}
}
/**
* Removes a value for a given value id
*/
public removeValue(
valueId: ValueID,
options: SetValueOptions = {},
): boolean {
const dbKey: string = this.valueIdToDBKey(valueId);
if (!this._metadata.has(dbKey)) {
this._index.delete(dbKey);
}
if (this._db.has(dbKey)) {
const prevValue = this._db.get(dbKey);
this._db.delete(dbKey);
if (
valueId.commandClass !== CommandClasses._NONE &&
options.noEvent !== true
) {
const cbArg: ValueRemovedArgs = {
...valueId,
prevValue,
};
this.emit("value removed", cbArg);
}
return true;
}
return false;
}
/**
* Retrieves a value for a given value id
*/
public getValue<T = unknown>(valueId: ValueID): T | undefined {
const key = this.valueIdToDBKey(valueId);
return this._db.get(key) as T | undefined;
}
/**
* Checks if a value for a given value id exists in this ValueDB
*/
public hasValue(valueId: ValueID): boolean {
const key = this.valueIdToDBKey(valueId);
return this._db.has(key);
}
/** Returns all values whose id matches the given predicate */
public findValues(
predicate: (id: ValueID) => boolean,
): (ValueID & { value: unknown })[] {
const ret: ReturnType<ValueDB["findValues"]> = [];
for (const key of this._index) {
if (!this._db.has(key)) continue;
const { nodeId, ...valueId } = this.dbKeyToValueId(key);
if (predicate(valueId)) {
ret.push({ ...valueId, value: this._db.get(key) });
}
}
return ret;
}
/** Returns all values that are stored for a given CC */
public getValues(forCC: CommandClasses): (ValueID & { value: unknown })[] {
const ret: ReturnType<ValueDB["getValues"]> = [];
for (const key of this._index) {
if (
compareDBKeyFast(key, this.nodeId, { commandClass: forCC }) &&
this._db.has(key)
) {
const { nodeId, ...valueId } = this.dbKeyToValueId(key);
const value = this._db.get(key);
ret.push({ ...valueId, value });
}
}
return ret;
}
/** Clears all values from the value DB */
public clear(options: SetValueOptions = {}): void {
for (const key of this._index) {
const { nodeId, ...valueId } = this.dbKeyToValueId(key);
if (this._db.has(key)) {
const prevValue = this._db.get(key);
this._db.delete(key);
if (
valueId.commandClass !== CommandClasses._NONE &&
options.noEvent !== true
) {
const cbArg: ValueRemovedArgs = {
...valueId,
prevValue,
};
this.emit("value removed", cbArg);
}
}
if (this._metadata.has(key)) {
this._metadata.delete(key);
if (
valueId.commandClass !== CommandClasses._NONE &&
options.noEvent !== true
) {
const cbArg: MetadataUpdatedArgs = {
...valueId,
metadata: undefined,
};
this.emit("metadata updated", cbArg);
}
}
}
this._index.clear();
}
/**
* Stores metadata for a given value id
*/
public setMetadata(
valueId: ValueID,
metadata: ValueMetadata | undefined,
options: SetValueOptions = {},
): void {
let dbKey: string;
try {
dbKey = this.valueIdToDBKey(valueId);
} catch (e) {
if (
isZWaveError(e) &&
e.code === ZWaveErrorCodes.Argument_Invalid &&
options.noThrow === true
) {
// ignore invalid value IDs
return;
}
throw e;
}
if (metadata) {
this._index.add(dbKey);
this._metadata.set(dbKey, metadata);
} else {
if (!this._db.has(dbKey)) {
this._index.delete(dbKey);
}
this._metadata.delete(dbKey);
}
const cbArg: MetadataUpdatedArgs = {
...valueId,
metadata,
};
if (
valueId.commandClass !== CommandClasses._NONE &&
options.noEvent !== true
) {
this.emit("metadata updated", cbArg);
}
}
/**
* Checks if metadata for a given value id exists in this ValueDB
*/
public hasMetadata(valueId: ValueID): boolean {
const key = this.valueIdToDBKey(valueId);
return this._metadata.has(key);
}
/**
* Retrieves metadata for a given value id
*/
public getMetadata(valueId: ValueID): ValueMetadata | undefined {
const key = this.valueIdToDBKey(valueId);
return this._metadata.get(key);
}
/** Returns all metadata that is stored for a given CC */
public getAllMetadata(forCC: CommandClasses): (ValueID & {
metadata: ValueMetadata;
})[] {
const ret: ReturnType<ValueDB["getAllMetadata"]> = [];
for (const key of this._index) {
if (
compareDBKeyFast(key, this.nodeId, { commandClass: forCC }) &&
this._metadata.has(key)
) {
const { nodeId, ...valueId } = this.dbKeyToValueId(key);
const metadata = this._metadata.get(key)!;
ret.push({ ...valueId, metadata });
}
}
return ret;
}
/** Returns all values whose id matches the given predicate */
public findMetadata(predicate: (id: ValueID) => boolean): (ValueID & {
metadata: ValueMetadata;
})[] {
const ret: ReturnType<ValueDB["findMetadata"]> = [];
for (const key of this._index) {
if (!this._metadata.has(key)) continue;
const { nodeId, ...valueId } = this.dbKeyToValueId(key);
if (predicate(valueId)) {
ret.push({ ...valueId, metadata: this._metadata.get(key)! });
}
}
return ret;
}
}
/**
* Really dumb but very fast way to parse one-lined JSON strings of the following schema
* {
* nodeId: number,
* commandClass: number,
* endpoint: number,
* property: string | number,
* propertyKey: string | number,
* }
*
* In benchmarks this was about 58% faster than JSON.parse
*/
export function dbKeyToValueIdFast(key: string): { nodeId: number } & ValueID {
let start = 10; // {"nodeId":
if (key.charCodeAt(start - 1) !== 58) {
console.error(key.slice(start - 1));
throw new Error("Invalid input format!");
}
let end = start + 1;
const len = key.length;
while (end < len && key.charCodeAt(end) !== 44) end++;
const nodeId = parseInt(key.slice(start, end));
start = end + 16; // ,"commandClass":
if (key.charCodeAt(start - 1) !== 58)
throw new Error("Invalid input format!");
end = start + 1;
while (end < len && key.charCodeAt(end) !== 44) end++;
const commandClass = parseInt(key.slice(start, end));
start = end + 12; // ,"endpoint":
if (key.charCodeAt(start - 1) !== 58)
throw new Error("Invalid input format!");
end = start + 1;
while (end < len && key.charCodeAt(end) !== 44) end++;
const endpoint = parseInt(key.slice(start, end));
start = end + 12; // ,"property":
if (key.charCodeAt(start - 1) !== 58)
throw new Error("Invalid input format!");
let property;
if (key.charCodeAt(start) === 34) {
start++; // skip leading "
end = start + 1;
while (end < len && key.charCodeAt(end) !== 34) end++;
property = key.slice(start, end);
end++; // skip trailing "
} else {
end = start + 1;
while (
end < len &&
key.charCodeAt(end) !== 44 &&
key.charCodeAt(end) !== 125
)
end++;
property = parseInt(key.slice(start, end));
}
if (key.charCodeAt(end) !== 125) {
let propertyKey;
start = end + 15; // ,"propertyKey":
if (key.charCodeAt(start - 1) !== 58)
throw new Error("Invalid input format!");
if (key.charCodeAt(start) === 34) {
start++; // skip leading "
end = start + 1;
while (end < len && key.charCodeAt(end) !== 34) end++;
propertyKey = key.slice(start, end);
end++; // skip trailing "
} else {
end = start + 1;
while (
end < len &&
key.charCodeAt(end) !== 44 &&
key.charCodeAt(end) !== 125
)
end++;
propertyKey = parseInt(key.slice(start, end));
}
return {
nodeId,
commandClass,
endpoint,
property,
propertyKey,
};
} else {
return {
nodeId,
commandClass,
endpoint,
property,
};
}
}
/** Used to filter DB entries without JSON parsing */
function compareDBKeyFast(
key: string,
nodeId: number,
valueId?: Partial<ValueID>,
): boolean {
if (-1 === key.indexOf(`{"nodeId":${nodeId},`)) return false;
if (!valueId) return true;
if ("commandClass" in valueId) {
if (-1 === key.indexOf(`,"commandClass":${valueId.commandClass},`))
return false;
}
if ("endpoint" in valueId) {
if (-1 === key.indexOf(`,"endpoint":${valueId.endpoint},`))
return false;
}
if (typeof valueId.property === "string") {
if (-1 === key.indexOf(`,"property":"${valueId.property}"`))
return false;
} else if (typeof valueId.property === "number") {
if (-1 === key.indexOf(`,"property":${valueId.property}`)) return false;
}
if (typeof valueId.propertyKey === "string") {
if (-1 === key.indexOf(`,"propertyKey":"${valueId.propertyKey}"`))
return false;
} else if (typeof valueId.propertyKey === "number") {
if (-1 === key.indexOf(`,"propertyKey":${valueId.propertyKey}`))
return false;
}
return true;
}
/** Extracts an index for each node from one or more JSONL DBs */
export function indexDBsByNode(databases: JsonlDB[]): Map<number, Set<string>> {
const indexes = new Map<number, Set<string>>();
for (const db of databases) {
for (const key of db.keys()) {
const nodeId = extractNodeIdFromDBKeyFast(key);
if (nodeId == undefined) continue;
if (!indexes.has(nodeId)) {
indexes.set(nodeId, new Set());
}
indexes.get(nodeId)!.add(key);
}
}
return indexes;
}
function extractNodeIdFromDBKeyFast(key: string): number | undefined {
const start = 10; // {"nodeId":
if (key.charCodeAt(start - 1) !== 58) {
// Invalid input format for a node value, assume it is for the driver
return undefined;
}
let end = start + 1;
const len = key.length;
while (end < len && key.charCodeAt(end) !== 44) end++;
return parseInt(key.slice(start, end));
} | the_stack |
import path from 'path';
import { promises as fs } from 'fs';
import {
branchFromContentKey,
generateContentKey,
contentKeyFromBranch,
CMS_BRANCH_PREFIX,
statusToLabel,
labelToStatus,
parseContentKey,
} from 'netlify-cms-lib-util/src/APIUtils';
import { parse } from 'what-the-diff';
import simpleGit from 'simple-git/promise';
import { Mutex, withTimeout } from 'async-mutex';
import { defaultSchema, joi } from '../joi';
import { pathTraversal } from '../joi/customValidators';
import { listRepoFiles, writeFile, move, deleteFile, getUpdateDate } from '../utils/fs';
import { entriesFromFiles, readMediaFile } from '../utils/entries';
import type {
EntriesByFolderParams,
EntriesByFilesParams,
GetEntryParams,
DefaultParams,
UnpublishedEntryParams,
PersistEntryParams,
GetMediaParams,
Asset,
PublishUnpublishedEntryParams,
PersistMediaParams,
DeleteFileParams,
UpdateUnpublishedEntryStatusParams,
DataFile,
GetMediaFileParams,
DeleteEntryParams,
DeleteFilesParams,
UnpublishedEntryDataFileParams,
UnpublishedEntryMediaFileParams,
} from '../types';
import type express from 'express';
import type winston from 'winston';
async function commit(git: simpleGit.SimpleGit, commitMessage: string) {
await git.add('.');
await git.commit(commitMessage, undefined, {
// setting the value to a string passes name=value
// any other value passes just the key
'--no-verify': null,
'--no-gpg-sign': null,
});
}
async function getCurrentBranch(git: simpleGit.SimpleGit) {
const currentBranch = await git.branchLocal().then(summary => summary.current);
return currentBranch;
}
async function runOnBranch<T>(git: simpleGit.SimpleGit, branch: string, func: () => Promise<T>) {
const currentBranch = await getCurrentBranch(git);
try {
if (currentBranch !== branch) {
await git.checkout(branch);
}
const result = await func();
return result;
} finally {
await git.checkout(currentBranch);
}
}
function branchDescription(branch: string) {
return `branch.${branch}.description`;
}
type GitOptions = {
repoPath: string;
logger: winston.Logger;
};
async function commitEntry(
git: simpleGit.SimpleGit,
repoPath: string,
dataFiles: DataFile[],
assets: Asset[],
commitMessage: string,
) {
// save entry content
await Promise.all(
dataFiles.map(dataFile => writeFile(path.join(repoPath, dataFile.path), dataFile.raw)),
);
// save assets
await Promise.all(
assets.map(a => writeFile(path.join(repoPath, a.path), Buffer.from(a.content, a.encoding))),
);
if (dataFiles.every(dataFile => dataFile.newPath)) {
dataFiles.forEach(async dataFile => {
await move(path.join(repoPath, dataFile.path), path.join(repoPath, dataFile.newPath!));
});
}
// commits files
await commit(git, commitMessage);
}
async function rebase(git: simpleGit.SimpleGit, branch: string) {
const gpgSign = await git.raw(['config', 'commit.gpgsign']);
try {
if (gpgSign === 'true') {
await git.addConfig('commit.gpgsign', 'false');
}
await git.rebase([branch, '--no-verify']);
} finally {
if (gpgSign === 'true') {
await git.addConfig('commit.gpgsign', gpgSign);
}
}
}
async function merge(git: simpleGit.SimpleGit, from: string, to: string) {
const gpgSign = await git.raw(['config', 'commit.gpgsign']);
try {
if (gpgSign === 'true') {
await git.addConfig('commit.gpgsign', 'false');
}
await git.mergeFromTo(from, to);
} finally {
if (gpgSign === 'true') {
await git.addConfig('commit.gpgsign', gpgSign);
}
}
}
async function isBranchExists(git: simpleGit.SimpleGit, branch: string) {
const branchExists = await git.branchLocal().then(({ all }) => all.includes(branch));
return branchExists;
}
async function getDiffs(git: simpleGit.SimpleGit, source: string, dest: string) {
const rawDiff = await git.diff([source, dest]);
const diffs = parse(rawDiff).map(d => {
const oldPath = d.oldPath?.replace(/b\//, '') || '';
const newPath = d.newPath?.replace(/b\//, '') || '';
const path = newPath || (oldPath as string);
return {
oldPath,
newPath,
status: d.status,
newFile: d.status === 'added',
path,
id: path,
binary: d.binary || /.svg$/.test(path),
};
});
return diffs;
}
export async function validateRepo({ repoPath }: { repoPath: string }) {
const git = simpleGit(repoPath);
const isRepo = await git.checkIsRepo();
if (!isRepo) {
throw Error(`${repoPath} is not a valid git repository`);
}
}
export function getSchema({ repoPath }: { repoPath: string }) {
const schema = defaultSchema({ path: pathTraversal(repoPath) });
return schema;
}
export function localGitMiddleware({ repoPath, logger }: GitOptions) {
const git = simpleGit(repoPath);
// we can only perform a single git operation at any given time
const mutex = withTimeout(new Mutex(), 3000, new Error('Request timed out'));
return async function (req: express.Request, res: express.Response) {
let release;
try {
release = await mutex.acquire();
const { body } = req;
if (body.action === 'info') {
res.json({
repo: path.basename(repoPath),
publish_modes: ['simple', 'editorial_workflow'],
type: 'local_git',
});
return;
}
const { branch } = body.params as DefaultParams;
const branchExists = await isBranchExists(git, branch);
if (!branchExists) {
const message = `Default branch '${branch}' doesn't exist`;
res.status(422).json({ error: message });
return;
}
switch (body.action) {
case 'entriesByFolder': {
const payload = body.params as EntriesByFolderParams;
const { folder, extension, depth } = payload;
const entries = await runOnBranch(git, branch, () =>
listRepoFiles(repoPath, folder, extension, depth).then(files =>
entriesFromFiles(
repoPath,
files.map(file => ({ path: file })),
),
),
);
res.json(entries);
break;
}
case 'entriesByFiles': {
const payload = body.params as EntriesByFilesParams;
const entries = await runOnBranch(git, branch, () =>
entriesFromFiles(repoPath, payload.files),
);
res.json(entries);
break;
}
case 'getEntry': {
const payload = body.params as GetEntryParams;
const [entry] = await runOnBranch(git, branch, () =>
entriesFromFiles(repoPath, [{ path: payload.path }]),
);
res.json(entry);
break;
}
case 'unpublishedEntries': {
const cmsBranches = await git
.branchLocal()
.then(result => result.all.filter(b => b.startsWith(`${CMS_BRANCH_PREFIX}/`)));
res.json(cmsBranches.map(contentKeyFromBranch));
break;
}
case 'unpublishedEntry': {
let { id, collection, slug, cmsLabelPrefix } = body.params as UnpublishedEntryParams;
if (id) {
({ collection, slug } = parseContentKey(id));
}
const contentKey = generateContentKey(collection as string, slug as string);
const cmsBranch = branchFromContentKey(contentKey);
const branchExists = await isBranchExists(git, cmsBranch);
if (branchExists) {
const diffs = await getDiffs(git, branch, cmsBranch);
const label = await git.raw(['config', branchDescription(cmsBranch)]);
const status = label && labelToStatus(label.trim(), cmsLabelPrefix || '');
const updatedAt =
diffs.length >= 0
? await runOnBranch(git, cmsBranch, async () => {
const dates = await Promise.all(
diffs.map(({ newPath }) => getUpdateDate(repoPath, newPath)),
);
return dates.reduce((a, b) => {
return a > b ? a : b;
});
})
: new Date();
const unpublishedEntry = {
collection,
slug,
status,
diffs,
updatedAt,
};
res.json(unpublishedEntry);
} else {
return res.status(404).json({ message: 'Not Found' });
}
break;
}
case 'unpublishedEntryDataFile': {
const { path, collection, slug } = body.params as UnpublishedEntryDataFileParams;
const contentKey = generateContentKey(collection as string, slug as string);
const cmsBranch = branchFromContentKey(contentKey);
const [entry] = await runOnBranch(git, cmsBranch, () =>
entriesFromFiles(repoPath, [{ path }]),
);
res.json({ data: entry.data });
break;
}
case 'unpublishedEntryMediaFile': {
const { path, collection, slug } = body.params as UnpublishedEntryMediaFileParams;
const contentKey = generateContentKey(collection as string, slug as string);
const cmsBranch = branchFromContentKey(contentKey);
const file = await runOnBranch(git, cmsBranch, () => readMediaFile(repoPath, path));
res.json(file);
break;
}
case 'deleteUnpublishedEntry': {
const { collection, slug } = body.params as DeleteEntryParams;
const contentKey = generateContentKey(collection, slug);
const cmsBranch = branchFromContentKey(contentKey);
const currentBranch = await getCurrentBranch(git);
if (currentBranch === cmsBranch) {
await git.checkoutLocalBranch(branch);
}
await git.branch(['-D', cmsBranch]);
res.json({ message: `deleted branch: ${cmsBranch}` });
break;
}
case 'persistEntry': {
const {
cmsLabelPrefix,
entry,
dataFiles = [entry as DataFile],
assets,
options,
} = body.params as PersistEntryParams;
if (!options.useWorkflow) {
await runOnBranch(git, branch, async () => {
await commitEntry(git, repoPath, dataFiles, assets, options.commitMessage);
});
} else {
const slug = dataFiles[0].slug;
const collection = options.collectionName as string;
const contentKey = generateContentKey(collection, slug);
const cmsBranch = branchFromContentKey(contentKey);
await runOnBranch(git, branch, async () => {
const branchExists = await isBranchExists(git, cmsBranch);
if (branchExists) {
await git.checkout(cmsBranch);
} else {
await git.checkoutLocalBranch(cmsBranch);
}
await rebase(git, branch);
const diffs = await getDiffs(git, branch, cmsBranch);
// delete media files that have been removed from the entry
const toDelete = diffs.filter(
d => d.binary && !assets.map(a => a.path).includes(d.path),
);
await Promise.all(toDelete.map(f => fs.unlink(path.join(repoPath, f.path))));
await commitEntry(git, repoPath, dataFiles, assets, options.commitMessage);
// add status for new entries
if (!branchExists) {
const description = statusToLabel(options.status, cmsLabelPrefix || '');
await git.addConfig(branchDescription(cmsBranch), description);
}
});
}
res.json({ message: 'entry persisted' });
break;
}
case 'updateUnpublishedEntryStatus': {
const { collection, slug, newStatus, cmsLabelPrefix } =
body.params as UpdateUnpublishedEntryStatusParams;
const contentKey = generateContentKey(collection, slug);
const cmsBranch = branchFromContentKey(contentKey);
const description = statusToLabel(newStatus, cmsLabelPrefix || '');
await git.addConfig(branchDescription(cmsBranch), description);
res.json({ message: `${branch} description was updated to ${description}` });
break;
}
case 'publishUnpublishedEntry': {
const { collection, slug } = body.params as PublishUnpublishedEntryParams;
const contentKey = generateContentKey(collection, slug);
const cmsBranch = branchFromContentKey(contentKey);
await merge(git, cmsBranch, branch);
await git.deleteLocalBranch(cmsBranch);
res.json({ message: `branch ${cmsBranch} merged to ${branch}` });
break;
}
case 'getMedia': {
const { mediaFolder } = body.params as GetMediaParams;
const mediaFiles = await runOnBranch(git, branch, async () => {
const files = await listRepoFiles(repoPath, mediaFolder, '', 1);
const serializedFiles = await Promise.all(
files.map(file => readMediaFile(repoPath, file)),
);
return serializedFiles;
});
res.json(mediaFiles);
break;
}
case 'getMediaFile': {
const { path } = body.params as GetMediaFileParams;
const mediaFile = await runOnBranch(git, branch, () => {
return readMediaFile(repoPath, path);
});
res.json(mediaFile);
break;
}
case 'persistMedia': {
const {
asset,
options: { commitMessage },
} = body.params as PersistMediaParams;
const file = await runOnBranch(git, branch, async () => {
await writeFile(
path.join(repoPath, asset.path),
Buffer.from(asset.content, asset.encoding),
);
await commit(git, commitMessage);
return readMediaFile(repoPath, asset.path);
});
res.json(file);
break;
}
case 'deleteFile': {
const {
path: filePath,
options: { commitMessage },
} = body.params as DeleteFileParams;
await runOnBranch(git, branch, async () => {
await deleteFile(repoPath, filePath);
await commit(git, commitMessage);
});
res.json({ message: `deleted file ${filePath}` });
break;
}
case 'deleteFiles': {
const {
paths,
options: { commitMessage },
} = body.params as DeleteFilesParams;
await runOnBranch(git, branch, async () => {
await Promise.all(paths.map(filePath => deleteFile(repoPath, filePath)));
await commit(git, commitMessage);
});
res.json({ message: `deleted files ${paths.join(', ')}` });
break;
}
case 'getDeployPreview': {
res.json(null);
break;
}
default: {
const message = `Unknown action ${body.action}`;
res.status(422).json({ error: message });
break;
}
}
} catch (e) {
logger.error(`Error handling ${JSON.stringify(req.body)}: ${e.message}`);
res.status(500).json({ error: 'Unknown error' });
} finally {
release && release();
}
};
}
type Options = {
logger: winston.Logger;
};
export async function registerMiddleware(app: express.Express, options: Options) {
const { logger } = options;
const repoPath = path.resolve(process.env.GIT_REPO_DIRECTORY || process.cwd());
await validateRepo({ repoPath });
app.post('/api/v1', joi(getSchema({ repoPath })));
app.post('/api/v1', localGitMiddleware({ repoPath, logger }));
logger.info(`Netlify CMS Git Proxy Server configured with ${repoPath}`);
} | the_stack |
import { memoize, mutableProxyFactory } from '../package'
import { Parser, TokenPointer } from './url-attributes/types'
interface ParsedView extends Array<TokenPointer> {
// Array of course already had a toString() method, but we redefine it, so just to be explicit:
toString(): string;
}
/**
* Allows manipulating tokens within a string.
* @param {string => Object[]} parse - given a string, must return an array of objects { token,
* index, note? }
* @=>
* @param {string} value - the string to be parsed.
* @returns {Object[]} tokens - the array of { token, index, note? } objects as returned by
* parse(value), where each token field is writable, and with a special toString() method that
* reconstructs the original string using the current values of the tokens.
* @example
* const view = parsedView(extractUrls)('bla http://example.com blub')
* view.forEach(tokenInfo => { tokenInfo.token = tokenInfo.token.replace(/^https?:/, 'dat:') })
* view.toString() // 'bla dat://example.com blub'
*/
export const parsedView: (parse: Parser) => (value: string) => ParsedView = parse => value => {
const parsedValue = parse(value)
// Split the string into tokens and 'glue' (the segments before, between and after the tokens).
const tokens: ParsedView = []
const glueStrings: string[] = []
let start = 0
for (const { token, index, note } of parsedValue) {
glueStrings.push(value.substring(start, index))
tokens.push({
token,
get index() { return index },
get note() { return note },
})
start = index + token.length
}
glueStrings.push(value.substring(start, ))
tokens.toString = () => {
// Glue everything back together, with the current values of the tokens.
let newValue = glueStrings[0]
tokens.forEach(({ token }, i) => {
newValue += token + glueStrings[i+1]
})
return newValue
}
return tokens
}
/**
* Like parsedView, but helps syncing the string with another variable/state/attribute/...
* It reads the string using get() at any operation, and afterward writes it back using set(string).
* @param {string => Object[]} options.parse - parser to apply to the string, should return an array
* of objects { token, index, note? }
* @param {() => string} options.get - string getter; invoked whenever a token is accessed.
* @param {string => void} options.set - string setter; invoked when any of its tokens was modified.
*/
export const syncingParsedView: (kwargs: {
parse: Parser,
get: () => string,
set: (string: string) => void,
}) => ParsedView = ({ parse, get, set }) => deepSyncingProxy(
transformingCache({
get,
set,
transform: parsedView(parse),
untransform: stringView => stringView.toString(),
})
)
/**
* Transparently handles getting+transforming and untransforming+setting of a variable.
* The result is nearly equivalent to the following: {
* get: () => transform(get()),
* set: value => set(untransform(value)),
* }
* ..except it remembers the last value to only run transform() or set() when needed.
* @param {() => T1} options.get - getter for the current untransformed value.
* @param {T1 => void} options.set - setter to update the current untransformed value.
* @param {T1 => T2} options.transform - the transformation to apply.
* @param {T2 => T1} options.untransform - the exact inverse of transformation.
* @param {(T1, T1) => boolean} [options.isEqual] - compares equality of two untransformed values.
* Defaults to (new, old) => new === old.
* @returns {Object} A pair of functions { get, set }.
*/
export function transformingCache<T1, T2>({
get,
set,
transform,
untransform,
isEqual = (a, b) => a === b,
}: {
get: () => T1,
set: (value: T1) => void,
transform: (value: T1) => T2,
untransform: (transformedValue: T2) => T1,
isEqual?: (newValue: T1, oldValue: T1) => boolean,
}): {
get: () => T2,
set: (transformedValue: T2, options?: { trustCache?: boolean }) => void,
} {
const uninitialised = Symbol('uninitialised')
let lastValue: T1 | typeof uninitialised = uninitialised
let lastTransformedValue: T2 | typeof uninitialised = uninitialised
return {
get() {
const newValue = get()
if (lastValue === uninitialised
|| !isEqual(newValue, lastValue)
|| lastTransformedValue === uninitialised // (this line should be superfluous)
) {
lastTransformedValue = transform(newValue)
}
lastValue = newValue
return lastTransformedValue
},
// trustCache allows skipping the get(); for optimisation in case you can guarantee that the
// value has not changed since the previous get or set (e.g. in an atomic update).
set(transformedValue, { trustCache = false }: { trustCache?: boolean } = {}) {
// Idea: return directly if the transformed value is equal and known to be immutable.
const newValue = untransform(transformedValue)
const currentValue = trustCache ? lastValue : get()
if (currentValue === uninitialised || !isEqual(newValue, currentValue)) {
set(newValue)
}
lastValue = newValue
lastTransformedValue = transformedValue
},
}
}
type ProxyMethodListener<T> = (method: keyof typeof Reflect, args: [T, ...any[] ]) => void
/**
* A Proxy that appears as the object returned by get(), *at any moment*, and writes back changes
* using set(object).
* @param {() => Object} get - getter for the object; is run before any operation on the object.
* @param {Object => void} set - setter for the object; is run after any operation on the object.
* @returns {Proxy} The proxy.
*/
export function syncingProxy<T extends object>({ get, set }: {
get: () => T,
set: (value: T) => void,
}): T {
// Get the current object to ensure the proxy's initial target has correct property descriptors.
// (changing e.g. from a normal object to an Array causes trouble)
const initialTarget = get()
const { proxy, getTarget, setTarget } = mutableProxyFactory(initialTarget)
const refreshProxyTarget = () => {
const object = get()
setTarget(object)
}
const writeBack = () => {
const object = getTarget()
set(object)
}
return makeListenerProxy<T>(refreshProxyTarget, writeBack)(proxy)
}
/**
* Like syncingProxy, this appears as the object return by get(), at any moment. It also proxies any
* member object, so that e.g. proxy.a.b will be updated to correspond to get().a.b at any moment.
* @param {() => Object} get - getter to obtain the object; is run before any operation on the
* object or any of its members (or members' members, etc.).
* @param {Object => void} set - setter to update the object; is run after any operation on the
* object or any of its members (or members' members, etc.).
* @returns {Proxy} The proxy.
*/
export function deepSyncingProxy<R extends object>({ get, set, alwaysSet = false }: {
get: () => R,
set: (value: R) => void,
alwaysSet?: boolean,
}): R {
let rootObject: R
// We will reload the whole object before any operation on any (sub)object.
const getRootObject = () => { rootObject = get() }
// We write back the whole object after any operation on any (sub)object.
const writeBack = () => { set(rootObject) }
function createProxy<S extends object>(
object: S,
path: string
): S {
// Create a mutable proxy, using object as the initial target.
const { proxy, setTarget } = mutableProxyFactory(object)
const refreshProxyTarget = () => {
// Update the root object.
getRootObject()
if (!isNonNullObject(rootObject)) throw new TypeError(
`Expected get()${path} to be an object, but get() is ${rootObject}.`
)
// Walk to the corresponding object within the root object.
let targetWalker: { [key: string]: any } = rootObject
const properties = path.split('.').slice(1)
for (let i = 0; i < properties.length; i++) {
const child: any = targetWalker[properties[i]]
if (!isNonNullObject(child)) {
const pathSoFar = '.' + properties.slice(0, i+1).join('.')
throw new TypeError(
`Expected get()${path} to be an object, but get()${pathSoFar} is ${child}.`
)
}
targetWalker = child
}
// Swap this proxy's target to the found object (we can leave other proxies outdated).
setTarget(targetWalker as S) // the object at the given path has the same type as initially.
}
const writeBackIfMutating: ProxyMethodListener<S> = (method, args) => {
// If the operation would have mutated a normal object, trigger a set()-sync
if (modifyingOperations.includes(method)) {
writeBack()
}
}
const afterHook = alwaysSet ? writeBack : writeBackIfMutating
return makeListenerProxy<S>(refreshProxyTarget, afterHook)(proxy)
}
// Get the current object to ensure the proxy's initial target has correct property descriptors.
// (changing e.g. from a normal object to an Array causes trouble)
const initialRootObject = get()
return deepProxy(createProxy)(initialRootObject)
}
function isNonNullObject(value: any): value is object {
return (typeof value === 'object' && value !== null)
}
// Operations which modify an object (if not performing tricks with getters or Proxies)
// (XXX hand-picked from the Reflect.* methods, potentially misguided)
const modifyingOperations = [
'set', 'delete', 'defineProperty', 'deleteProperty', 'preventExtensions', 'setPrototypeOf',
]
/**
* A proxy to the object, that runs the given hooks before and after every operation on the object.
* @param {(method: string, args[]) => void} before - is run before any operation on the object.
* Gets passed the name of the method that will be invoked, and its arguments.
* @param {(method: string, args[]) => void} after - is run after any operation on the object.
* Gets passed the name of the method that will be invoked, and its arguments.
* @=>
* @param {Object} object - the object to be proxied.
* @returns {Proxy} The proxy to the given object.
*/
export function makeListenerProxy<T extends object>(
before: ProxyMethodListener<T> = () => {},
after: ProxyMethodListener<T> = () => {},
): (object: T) => T {
return (object: T) => {
const handler = Object.assign(
{},
...Object.getOwnPropertyNames(Reflect).map((method: keyof typeof Reflect) => ({
[method](...args: [T, ...any[]]) {
before(method, args)
const result = Reflect[method].apply(null, args)
after(method, args)
return result
},
})),
)
return new Proxy(object, handler)
}
}
/**
* A higher order proxy to have a proxy also wrap every attribute in the same type of proxy.
* @param {(Object, path: string) => Proxy} createProxy
* @=>
* @param {Object} object - the object which, and whose members, will be wrapped using createProxy.
* @returns {Proxy} A proxy around the proxy of the object.
*/
export function deepProxy<T extends object>(
createProxy: (object: T, path: string) => T
): (object: T) => T {
let createDeepProxy: (object: T, path: string) => T = (object, path) => {
const target = createProxy(object, path)
return new Proxy(target, {
// Trap the get() method, to also wrap any subobjects using createProxy.
get(target, property, receiver) {
const value = Reflect.get(target, property, receiver)
if (
value instanceof Object
&& target.hasOwnProperty(property) // ignore .prototype, etc.
&& typeof property === 'string' // would we want to support Symbols?
) {
// Wrap the object using createProxy; but recursively.
const innerProxy = createDeepProxy(value, `${path}.${property}`)
return innerProxy
} else {
return value
}
},
})
}
// Memoize to not create duplicate proxies of the same object (so that proxy.x === proxy.x).
// FIXME Path could be an array, but then memoize should deep-compare arrays. For now, do not
// put periods into property names!
// (note that we do want path to be part of the memoization key: if two paths currently hold the
// same object, they should result in two proxies because this situation might change)
createDeepProxy = memoize(createDeepProxy)
return object => createDeepProxy(object, '')
} | the_stack |
var Color = xray.Color;
var Color3 = xray.Color3;
var Camera = xray.Camera;
var Sampler = xray.Sampler;
// var Vector = xray.Vector;
// var Scene = xray.Scene;
export class xRayTracer {
id:number;
flags:Uint8Array;
pixelMemory:Uint8ClampedArray;
sampleMemory:Float32Array;
camera:number;
scene:number;
full_width:number;
full_height:number;
width:number;
height:number;
xoffset:number;
yoffset:number;
cameraSamples:number;
absCameraSamples:number;
hitSamples:number;
bounces:number;
iterations:number = 1;
private locked:boolean;
/* Render Domain */
public sampler;
public buffer:number;
public samplesPerPixel:number = 1;
public stratifiedSampling:boolean = true;
public AdaptiveSamples:number;
public FireflySamples:number;
public FireflyThreshold:number;
constructor(data?) {
if(data){
this.init(data);
}
}
init(data:any) {
this.id = data.id;
this.flags = new Uint8Array(data.flagBuffer);
this.pixelMemory = new Uint8ClampedArray(data.pixelBuffer);
this.sampleMemory = new Float32Array(data.sampleBuffer);
this.scene = data.traceData.scene;
this.camera = data.traceData.camera;
this.full_width = data.traceData.renderOptions.full_width;
this.full_height = data.traceData.renderOptions.full_height;
this.cameraSamples = data.traceData.renderOptions.cameraSamples;
this.hitSamples = data.traceData.renderOptions.hitSamples;
this.bounces = data.traceData.renderOptions.bounces;
if(!this.sampler){
this.sampler = xray.NewSampler(4, 4);
}
}
updateRenderRegion(width:number, height:number, xoffset:number, yoffset:number):void {
this.width = width;
this.height = height;
this.xoffset = xoffset;
this.yoffset = yoffset;
this.absCameraSamples = Math.round(Math.abs(this.cameraSamples));
}
private lock() {
if (!this.locked) {
this.locked = true;
postMessage("LOCKED");
}
}
trace(data):boolean {
if (this.flags[this.id] === 2) {//thread locked
Terminal.write("exit:1");
this.lock();
return;
}
this.updateRenderRegion(
data.rect.width,
data.rect.height,
data.rect.xoffset,
data.rect.yoffset
);
this.cameraSamples = data.cameraSamples || this.cameraSamples;
this.hitSamples = data.hitSamples || this.hitSamples;
this.iterations = data.init_iterations || 0;
if (this.locked) {
Terminal.write("restarted:" + this.iterations, "samples:" + this.checkSamples());
this.locked = false;
}
if (this.iterations > 0 && data.blockIterations) {
for (var i = 0; i < data.blockIterations; i++) {
if (this.flags[this.id] === 2) {//thread locked
this.lock();
return false;
}
this.run();
}
} else {
if (this.flags[this.id] === 2) {//thread locked
this.lock();
return false;
}
this.run();
}
if (this.flags[this.id] === 2) {//thread locked
this.lock();
return false;
}
return true;
}
run():void {
let scene = this.scene;
let camera = this.camera;
let sampler = this.sampler;
let buf = this.buffer;
// let w = buf.width;
// let h = buf.height;
let spp = this.samplesPerPixel;
let sppRoot = Math.round(Math.sqrt(this.samplesPerPixel));
this.iterations++;
var hitSamples = this.hitSamples;
var cameraSamples = this.cameraSamples;
var absCameraSamples = this.absCameraSamples;
if (this.iterations == 1) {
hitSamples = 1;
cameraSamples = -1;
absCameraSamples = Math.round(Math.abs(cameraSamples));
}
for (var y:number = this.yoffset; y < this.yoffset + this.height; y++) {
for (var x:number = this.xoffset; x < this.xoffset + this.width; x++) {
if (this.flags[this.id] === 2) {//thread locked
Terminal.write("exit:3");
this.lock();
return;
}
let c = new Color3();
if (this.stratifiedSampling) {
// stratified subsampling
for (let u = 0; u < sppRoot; u++) {
for (let v = 0; v < sppRoot; v++) {
let fu = (u + 0.5) / sppRoot;
let fv = (v + 0.5) / sppRoot;
let ray = Camera.CastRay(camera, x, y, this.full_width, this.full_height, fu, fv);
let sample = sampler.sample(scene, ray, true, sampler.firstHitSamples, 1);
c = c.add(sample);
}
}
c = c.divScalar(sppRoot * sppRoot);
} else {
// random subsampling
for (let i = 0; i < spp; i++) {
let fu = Math.random();
let fv = Math.random();
let ray = Camera.CastRay(camera, x, y, this.full_width, this.full_height, fu, fv);
// let sample = Sampler.Sample(sampler, scene, ray);
let sample = sampler.sample(scene, ray, true, sampler.firstHitSamples, 1);
c = c.add(sample);
//Color.Add_mem(c, sample, c);
//Buffer.AddSample(buf, x, y, sample);
}
c = c.divScalar(spp);
}
/*// adaptive sampling
if (this.AdaptiveSamples > 0) {
let v = clamp(buf.StandardDeviation(x, y).MaxComponent(), 0, 1);
// v = math.Pow(v, 2)
let samples = int(v * float64(r.AdaptiveSamples))
for (let i = 0; i < samples; i++) {
let fu = Math.random();
let fv = Math.random();
let ray = Camera.CastRay(camera, x, y, this.full_width, this.full_height, fu, fv);
let sample = Sampler.Sample(sampler, scene, ray);
Color.Add_mem(this.c, sample, this.c);
//Buffer.AddSample(buf, x, y, sample);
}
}
// firefly reduction
if (this.FireflySamples > 0) {
if (buf.StandardDeviation(x, y).MaxComponent() > this.FireflyThreshold) {
for (let i = 0; i < this.FireflySamples; i++) {
let fu = Math.random();
let fv = Math.random();
let ray = Camera.CastRay(camera, x, y, this.full_width, this.full_height, fu, fv);
let sample = Sampler.Sample(sampler, scene, ray);
Color.Add_mem(this.c, sample, this.c);
// Buffer.AddSample(buf, x, y, sample);
}
}
}*/
c = c.pow(1 / 2.2);
var screen_index:number = (y * (this.full_width * 3)) + (x * 3);
this.updatePixel(c, screen_index);
}
}
//Terminal.time("render");
/*for (var y:number = this.yoffset; y < this.yoffset + this.height; y++) {
for (var x:number = this.xoffset; x < this.xoffset + this.width; x++) {
if (this.flags[this.id] === 2) {//thread locked
Terminal.write("exit:3");
this.lock();
return;
}
var screen_index:number = (y * (this.full_width * 3)) + (x * 3);
// var _x:number = x - this.xoffset;
// var _y:number = y - this.yoffset;
var c:Color = new Color();
if (cameraSamples <= 0) {
// random subsampling
for (let i = 0; i < absCameraSamples; i++) {
var fu = Math.random();
var fv = Math.random();
var ray = this.camera.castRay(x, y, this.full_width, this.full_height, fu, fv);
c = c.add(this.scene.sample(ray, true, hitSamples, this.bounces))
}
c = c.divScalar(absCameraSamples);
} else {
// stratified subsampling
var n:number = Math.round(Math.sqrt(cameraSamples));
for (var u = 0; u < n; u++) {
for (var v = 0; v < n; v++) {
var fu = (u + 0.5) / n;
var fv = (v + 0.5) / n;
var ray:Ray = this.camera.castRay(x, y, this.full_width, this.full_height, fu, fv);
c = c.add(this.scene.sample(ray, true, hitSamples, this.bounces));
}
}
c = c.divScalar(n * n);
}
if (this.flags[this.id] === 2) {//thread locked
Terminal.write("exit:7");
this.lock();
return;
}
c = c.pow(1 / 2.2);
this.updatePixel(c, screen_index);
}
}*/
//Terminal.timeEnd("render");
}
updatePixel(color, si:number):void {
if (this.flags[this.id] === 2) {//thread locked
Terminal.write("exit:8");
this.lock();
return;
}
this.sampleMemory[si] += color.R;
this.sampleMemory[si + 1] += color.G;
this.sampleMemory[si + 2] += color.B;
this.pixelMemory[si] = Math.max(0, Math.min(255, (this.sampleMemory[si] / this.iterations) * 255));
this.pixelMemory[si + 1] = Math.max(0, Math.min(255, (this.sampleMemory[si + 1] / this.iterations) * 255));
this.pixelMemory[si + 2] = Math.max(0, Math.min(255, (this.sampleMemory[si + 2] / this.iterations) * 255));
}
checkSamples() {
for (var y:number = this.yoffset; y < this.yoffset + this.height; y++) {
for (var x:number = this.xoffset; x < this.xoffset + this.width; x++) {
var si:number = (y * (this.full_width * 3)) + (x * 3);
if (this.sampleMemory[si] !== 0 &&
this.sampleMemory[si + 1] !== 0 &&
this.sampleMemory[si + 2] !== 0) {
return "NOT_OK";
}
}
}
return "OK";
}
} | the_stack |
import * as React from 'react';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { Modal } from '../src';
describe('modal', () => {
describe('overlay', () => {
it('should call onClose when click on the overlay', () => {
const onClose = jest.fn();
const { getByTestId } = render(
<Modal open onClose={onClose}>
<div>modal content</div>
</Modal>
);
fireEvent.click(getByTestId('modal-container'));
expect(onClose).toHaveBeenCalledTimes(1);
});
it('should disable the handler when closeOnOverlayClick is false', () => {
const onClose = jest.fn();
const { getByTestId } = render(
<Modal open onClose={onClose} closeOnOverlayClick={false}>
<div>modal content</div>
</Modal>
);
fireEvent.click(getByTestId('modal-container'));
expect(onClose).not.toHaveBeenCalled();
});
it('should ignore the overlay click if the event does not come from the overlay', () => {
const onClose = jest.fn();
const { getByTestId } = render(
<Modal open onClose={onClose}>
<div>modal content</div>
</Modal>
);
fireEvent.click(getByTestId('modal'));
expect(onClose).not.toHaveBeenCalled();
});
});
describe('key events', () => {
it('an invalid event should not call onClose', () => {
const onClose = jest.fn();
const { container } = render(
<Modal open onClose={onClose}>
<div>modal content</div>
</Modal>
);
fireEvent.keyDown(container, { key: 'Enter', keyCode: 13 });
expect(onClose).not.toHaveBeenCalled();
});
it('should not call onClose when closeOnEsc is false', () => {
const onClose = jest.fn();
const { container } = render(
<Modal open onClose={onClose} closeOnEsc={false}>
<div>modal content</div>
</Modal>
);
fireEvent.keyDown(container, { keyCode: 27 });
expect(onClose).not.toHaveBeenCalled();
});
it('should call onClose when pressing esc key', () => {
const onClose = jest.fn();
const { container } = render(
<Modal open onClose={onClose}>
<div>modal content</div>
</Modal>
);
fireEvent.keyDown(container, { keyCode: 27 });
expect(onClose).toHaveBeenCalledTimes(1);
});
it('should call onClose of last modal only when pressing esc key when multiple modals are opened', () => {
const onClose = jest.fn();
const onClose2 = jest.fn();
const { container } = render(
<>
<Modal open onClose={onClose}>
<div>modal content</div>
</Modal>
<Modal open onClose={onClose2}>
<div>modal content</div>
</Modal>
</>
);
fireEvent.keyDown(container, { keyCode: 27 });
expect(onClose).not.toHaveBeenCalled();
expect(onClose2).toHaveBeenCalledTimes(1);
});
});
describe('body scroll', () => {
it('should not block the scroll when modal is rendered closed', () => {
render(
<Modal open={false} onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(document.body.style.overflow).toBe('');
});
it('should block the scroll when modal is rendered open', () => {
render(
<Modal open={true} onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(document.body.style.overflow).toBe('hidden');
});
it('should block scroll when prop open change to true', () => {
const { rerender } = render(
<Modal open={false} onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(document.body.style.overflow).toBe('');
rerender(
<Modal open={true} onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(document.body.style.overflow).toBe('hidden');
});
it('should unblock scroll when prop open change to false', async () => {
const { rerender, queryByTestId, getByTestId } = render(
<Modal open={true} onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(document.body.style.overflow).toBe('hidden');
rerender(
<Modal open={false} onClose={() => null} animationDuration={0}>
<div>modal content</div>
</Modal>
);
// Simulate the browser animation end
fireEvent.animationEnd(getByTestId('modal'));
await waitFor(
() => {
expect(queryByTestId('modal')).not.toBeInTheDocument();
},
{ timeout: 1 }
);
expect(document.body.style.overflow).toBe('');
});
it('should unblock scroll when unmounted directly', async () => {
const { unmount } = render(
<Modal open={true} onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(document.body.style.overflow).toBe('hidden');
unmount();
expect(document.body.style.overflow).toBe('');
});
it('should unblock scroll when multiple modals are opened and then closed', async () => {
const { rerender, getAllByTestId, queryByText } = render(
<React.Fragment>
<Modal open onClose={() => null}>
<div>first modal</div>
</Modal>
<Modal open onClose={() => null}>
<div>second modal</div>
</Modal>
</React.Fragment>
);
expect(document.body.style.overflow).toBe('hidden');
// We close one modal, the scroll should be locked
rerender(
<React.Fragment>
<Modal open onClose={() => null}>
<div>first modal</div>
</Modal>
<Modal open={false} onClose={() => null}>
<div>second modal</div>
</Modal>
</React.Fragment>
);
fireEvent.animationEnd(getAllByTestId('modal')[1]);
await waitFor(
() => {
expect(queryByText(/second modal/)).not.toBeInTheDocument();
},
{ timeout: 1 }
);
expect(document.body.style.overflow).toBe('hidden');
// We close the second modal, the scroll should be unlocked
rerender(
<React.Fragment>
<Modal open={false} onClose={() => null}>
<div>first modal</div>
</Modal>
<Modal open={false} onClose={() => null}>
<div>second modal</div>
</Modal>
</React.Fragment>
);
fireEvent.animationEnd(getAllByTestId('modal')[0]);
await waitFor(
() => {
expect(queryByText(/first modal/)).not.toBeInTheDocument();
},
{ timeout: 1 }
);
expect(document.body.style.overflow).toBe('');
});
it('should unblock scroll when one modal is closed and the one still open has blockScroll set to false', async () => {
const { rerender, getAllByTestId, queryByText } = render(
<React.Fragment>
<Modal open blockScroll={false} onClose={() => null}>
<div>first modal</div>
</Modal>
<Modal open onClose={() => null}>
<div>second modal</div>
</Modal>
</React.Fragment>
);
expect(document.body.style.overflow).toBe('hidden');
// We close one modal, the scroll should be unlocked as remaining modal is not locking the scroll
rerender(
<React.Fragment>
<Modal open blockScroll={false} onClose={() => null}>
<div>first modal</div>
</Modal>
<Modal open={false} onClose={() => null}>
<div>second modal</div>
</Modal>
</React.Fragment>
);
fireEvent.animationEnd(getAllByTestId('modal')[1]);
await waitFor(
() => {
expect(queryByText(/second modal/)).not.toBeInTheDocument();
},
{ timeout: 1 }
);
expect(document.body.style.overflow).toBe('');
});
});
describe('closeIcon', () => {
it('should render the closeIcon by default', () => {
const { getByTestId } = render(
<Modal open onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(getByTestId('close-button')).toMatchSnapshot();
});
it('should hide closeIcon when showCloseIcon is false', () => {
const { queryByTestId } = render(
<Modal open onClose={() => null} showCloseIcon={false}>
<div>modal content</div>
</Modal>
);
expect(queryByTestId('close-button')).toBeNull();
});
it('should call onClose when clicking on the icon', () => {
const onClose = jest.fn();
const { getByTestId } = render(
<Modal open onClose={onClose}>
<div>modal content</div>
</Modal>
);
fireEvent.click(getByTestId('close-button'));
expect(onClose).toHaveBeenCalledTimes(1);
});
});
describe('render', () => {
it('should render null when then modal is not open', () => {
const { queryByText } = render(
<Modal open={false} onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(queryByText(/modal content/)).toBeNull();
});
it('should render the content when modal is open', () => {
const { queryByText } = render(
<Modal open onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(queryByText(/modal content/)).toBeTruthy();
});
});
describe('lifecycle', () => {
it('should show modal when prop open change to true', () => {
const { queryByTestId, rerender } = render(
<Modal open={false} onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(queryByTestId('modal')).toBeNull();
rerender(
<Modal open={true} onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(queryByTestId('modal')).toBeTruthy();
});
it('should hide modal when prop open change to false', async () => {
const { getByTestId, queryByTestId, rerender } = render(
<Modal open={true} onClose={() => null} animationDuration={0.01}>
<div>modal content</div>
</Modal>
);
expect(queryByTestId('modal')).toBeTruthy();
rerender(
<Modal open={false} onClose={() => null} animationDuration={0.01}>
<div>modal content</div>
</Modal>
);
fireEvent.animationEnd(getByTestId('modal'));
expect(queryByTestId('modal')).toBeNull();
});
});
describe('prop: center', () => {
it('should not apply center class by default', async () => {
const { getByTestId } = render(
<Modal open onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(getByTestId('modal-container').classList.length).toBe(1);
expect(
getByTestId('modal-container').classList.contains(
'react-responsive-modal-containerCenter'
)
).toBeFalsy();
});
it('should apply center class to modal', async () => {
const { getByTestId } = render(
<Modal open onClose={() => null} center>
<div>modal content</div>
</Modal>
);
expect(getByTestId('modal-container').classList.length).toBe(2);
expect(
getByTestId('modal-container').classList.contains(
'react-responsive-modal-containerCenter'
)
).toBeTruthy();
});
});
describe('prop: closeIcon', () => {
it('should render custom icon instead of the default one', async () => {
const { queryByTestId, getByTestId } = render(
<Modal
open
onClose={() => null}
closeIcon={<div data-testid="custom-icon">custom icon</div>}
>
<div>modal content</div>
</Modal>
);
expect(queryByTestId('close-icon')).toBeNull();
expect(getByTestId('custom-icon')).toMatchSnapshot();
});
});
describe('prop: classNames', () => {
it('should apply custom classes to the modal', async () => {
const { getByTestId } = render(
<Modal
open
onClose={() => null}
classNames={{
overlay: 'custom-overlay',
modal: 'custom-modal',
closeButton: 'custom-closeButton',
closeIcon: 'custom-closeIcon',
}}
>
<div>modal content</div>
</Modal>
);
expect(
getByTestId('overlay').classList.contains('custom-overlay')
).toBeTruthy();
expect(
getByTestId('modal').classList.contains('custom-modal')
).toBeTruthy();
expect(
getByTestId('close-button').classList.contains('custom-closeButton')
).toBeTruthy();
expect(
getByTestId('close-icon').classList.contains('custom-closeIcon')
).toBeTruthy();
});
});
describe('prop: blockScroll', () => {
it('should not block the scroll when modal is opened and blockScroll is false', () => {
render(
<Modal open blockScroll={false} onClose={() => null}>
<div>modal content</div>
</Modal>
);
expect(document.body.style.overflow).toBe('');
});
});
describe('prop: onEscKeyDown', () => {
it('should be called when esc key is pressed', async () => {
const onEscKeyDown = jest.fn();
const { container } = render(
<Modal open onClose={() => null} onEscKeyDown={onEscKeyDown}>
<div>modal content</div>
</Modal>
);
fireEvent.keyDown(container, { keyCode: 27 });
expect(onEscKeyDown).toHaveBeenCalledTimes(1);
});
});
describe('prop: onOverlayClick', () => {
it('should be called when user click on overlay', async () => {
const onOverlayClick = jest.fn();
const { getByTestId } = render(
<Modal open onClose={() => null} onOverlayClick={onOverlayClick}>
<div>modal content</div>
</Modal>
);
fireEvent.click(getByTestId('modal-container'));
expect(onOverlayClick).toHaveBeenCalledTimes(1);
});
});
describe('prop: onAnimationEnd', () => {
it('should be called when the animation is finished', async () => {
const onAnimationEnd = jest.fn();
const { getByTestId } = render(
<Modal open onClose={() => null} onAnimationEnd={onAnimationEnd}>
<div>modal content</div>
</Modal>
);
fireEvent.animationEnd(getByTestId('modal'));
expect(onAnimationEnd).toHaveBeenCalledTimes(1);
});
});
}); | the_stack |
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { sp, Web, PermissionKind, RegionalSettings } from '@pnp/sp';
import { graph, } from "@pnp/graph";
import * as $ from 'jquery';
import { IEventData } from './IEventData';
import * as moment from 'moment';
import { SiteUser } from "@pnp/sp/src/siteusers";
import { IUserPermissions } from './IUserPermissions';
import parseRecurrentEvent from './parseRecurrentEvent';
// Class Services
export default class spservices {
constructor(private context: WebPartContext) {
// Setuo Context to PnPjs and MSGraph
sp.setup({
spfxContext: this.context
});
graph.setup({
spfxContext: this.context
});
// Init
this.onInit();
}
// OnInit Function
private async onInit() {
}
/**
*
* @private
* @returns {Promise<string>}
* @memberof spservices
*/
public async getLocalTime(date: string | Date): Promise<string> {
try {
const localTime = await sp.web.regionalSettings.timeZone.utcToLocalTime(date);
return localTime;
}
catch (error) {
return Promise.reject(error);
}
}
/**
*
* @private
* @returns {Promise<string>}
* @memberof spservices
*/
public async getUtcTime(date: string | Date): Promise<string> {
try {
const utcTime = await sp.web.regionalSettings.timeZone.localTimeToUTC(date);
return utcTime;
}
catch (error) {
return Promise.reject(error);
}
}
/**
*
* @param {IEventData} newEvent
* @param {string} siteUrl
* @param {string} listId
* @returns
* @memberof spservices
*/
public async addEvent(newEvent: IEventData, siteUrl: string, listId: string) {
let results = null;
try {
const web = new Web(siteUrl);
results = await web.lists.getById(listId).items.add({
Title: newEvent.title,
Description: newEvent.Description,
Geolocation: newEvent.geolocation,
ParticipantsPickerId: { results: newEvent.attendes },
EventDate: await this.getUtcTime(newEvent.EventDate),
EndDate: await this.getUtcTime(newEvent.EndDate),
Location: newEvent.location,
fAllDayEvent: newEvent.fAllDayEvent,
fRecurrence: newEvent.fRecurrence,
Category: newEvent.Category,
EventType: newEvent.EventType,
UID: newEvent.UID,
RecurrenceData: newEvent.RecurrenceData ? await this.deCodeHtmlEntities(newEvent.RecurrenceData) : "",
MasterSeriesItemID: newEvent.MasterSeriesItemID,
RecurrenceID: newEvent.RecurrenceID ? newEvent.RecurrenceID : undefined,
});
}
catch (error) {
return Promise.reject(error);
}
return results;
}
/**
*
*
* @param {string} siteUrl
* @param {string} listId
* @param {number} eventId
* @returns {Promise<IEventData>}
* @memberof spservices
*/
public async getEvent(siteUrl: string, listId: string, eventId: number): Promise<IEventData> {
let returnEvent: IEventData = undefined;
try {
const web = new Web(siteUrl);
//"Title","fRecurrence", "fAllDayEvent","EventDate", "EndDate", "Description","ID", "Location","Geolocation","ParticipantsPickerId"
const event = await web.lists.getById(listId).items.usingCaching().getById(eventId)
.select("RecurrenceID", "MasterSeriesItemID", "Id", "ID", "ParticipantsPickerId", "EventType", "Title", "Description", "EventDate", "EndDate", "Location", "Author/SipAddress", "Author/Title", "Geolocation", "fAllDayEvent", "fRecurrence", "RecurrenceData", "RecurrenceData", "Duration", "Category", "UID")
.expand("Author")
.get();
const eventDate = await this.getLocalTime(event.EventDate);
const endDate = await this.getLocalTime(event.EndDate);
returnEvent = {
Id: event.ID,
ID: event.ID,
EventType: event.EventType,
title: await this.deCodeHtmlEntities(event.Title),
Description: event.Description ? event.Description : '',
EventDate: new Date(eventDate),
EndDate: new Date(endDate),
location: event.Location,
ownerEmail: event.Author.SipAddress,
ownerPhoto: "",
ownerInitial: '',
color: '',
ownerName: event.Author.Title,
attendes: event.ParticipantsPickerId,
fAllDayEvent: event.fAllDayEvent,
geolocation: { Longitude: event.Geolocation ? event.Geolocation.Longitude : 0, Latitude: event.Geolocation ? event.Geolocation.Latitude : 0 },
Category: event.Category,
Duration: event.Duration,
UID: event.UID,
RecurrenceData: event.RecurrenceData ? await this.deCodeHtmlEntities(event.RecurrenceData) : "",
fRecurrence: event.fRecurrence,
RecurrenceID: event.RecurrenceID,
MasterSeriesItemID: event.MasterSeriesItemID,
};
}
catch (error) {
return Promise.reject(error);
}
return returnEvent;
}
/**
*
* @param {IEventData} newEvent
* @param {string} siteUrl
* @param {string} listId
* @returns
* @memberof spservices
*/
public async updateEvent(updateEvent: IEventData, siteUrl: string, listId: string) {
let results = null;
try {
// delete all recursive extentions before update recurrence event
if (updateEvent.EventType.toString() == "1") await this.deleteRecurrenceExceptions(updateEvent, siteUrl, listId);
const web = new Web(siteUrl);
const eventDate = await this.getUtcTime(updateEvent.EventDate);
const endDate = await this.getUtcTime(updateEvent.EndDate);
//"Title","fRecurrence", "fAllDayEvent","EventDate", "EndDate", "Description","ID", "Location","Geolocation","ParticipantsPickerId"
let newItem: any = {
Title: updateEvent.title,
Description: updateEvent.Description,
Geolocation: updateEvent.geolocation,
ParticipantsPickerId: { results: updateEvent.attendes },
EventDate: new Date(eventDate),
EndDate: new Date(endDate),
Location: updateEvent.location,
fAllDayEvent: updateEvent.fAllDayEvent,
fRecurrence: updateEvent.fRecurrence,
Category: updateEvent.Category,
RecurrenceData: updateEvent.RecurrenceData ? await this.deCodeHtmlEntities(updateEvent.RecurrenceData) : "",
EventType: updateEvent.EventType,
};
if (updateEvent.UID) {
newItem.UID = updateEvent.UID;
}
if (updateEvent.MasterSeriesItemID) {
newItem.MasterSeriesItemID = updateEvent.MasterSeriesItemID;
}
results = await web.lists.getById(listId).items.getById(updateEvent.Id).update(newItem);
}
catch (error) {
return Promise.reject(error);
}
return results;
}
public async deleteRecurrenceExceptions(event: IEventData, siteUrl: string, listId: string) {
let results = null;
try {
const web = new Web(siteUrl);
results = await web.lists.getById(listId).items
.select('Id')
.filter(`EventType eq '3' or EventType eq '4' and MasterSeriesItemID eq '${event.Id}' `)
.get();
if (results && results.length > 0) {
for (const recurrenceException of results) {
await web.lists.getById(listId).items.getById(recurrenceException.Id).delete();
}
}
} catch (error) {
return Promise.reject(error);
}
return;
}
/**
*
* @param {IEventData} event
* @param {string} siteUrl
* @param {string} listId
* @returns
* @memberof spservices
*/
public async deleteEvent(event: IEventData, siteUrl: string, listId: string, recurrenceSeriesEdited: boolean) {
let results = null;
try {
const web = new Web(siteUrl);
// Exception Recurrence eventtype = 4 ? update to deleted Recurrence eventtype=3
switch (event.EventType.toString()) {
case '4': // Exception Recurrence Event
results = await web.lists.getById(listId).items.getById(event.Id).update({
Title: `Deleted: ${event.title}`,
EventType: '3',
});
break;
case '1': // recurrence Event
// if delete is a main recrrence delete all recurrences and main recurrence
if (recurrenceSeriesEdited) {
// delete execptions if exists before delete recurrence event
await this.deleteRecurrenceExceptions(event, siteUrl, listId);
await web.lists.getById(listId).items.getById(event.Id).delete();
} else {
//Applying the Standard funactionality of SharePoint When deleting for deleting one occurrence of recurrent event by
// 1) adding prefix "Deleted" to event title 2) Set RecurrenceID to event Date 3) Set MasterSeriesItemID to event ID 4)Set fRecurrence to true 5) Set event type to 3
event.title = `Deleted: ${event.title}`;
event.RecurrenceID = event.EventDate;
event.MasterSeriesItemID = event.ID.toString();
event.fRecurrence = true;
event.EventType = '3';
await this.addEvent(event, siteUrl, listId);
}
break;
case '0': // normal Event
await web.lists.getById(listId).items.getById(event.Id).delete();
break;
}
} catch (error) {
return Promise.reject(error);
}
return;
}
/**
*
* @param {number} userId
* @param {string} siteUrl
* @returns {Promise<SiteUser>}
* @memberof spservices
*/
public async getUserById(userId: number, siteUrl: string): Promise<SiteUser> {
let results: SiteUser = null;
if (!userId && !siteUrl) {
return null;
}
try {
const web = new Web(siteUrl);
results = await web.siteUsers.getById(userId).get();
//results = await web.siteUsers.getByLoginName(userId).get();
} catch (error) {
return Promise.reject(error);
}
return results;
}
/**
*
*
* @param {string} loginName
* @param {string} siteUrl
* @returns {Promise<SiteUser>}
* @memberof spservices
*/
public async getUserByLoginName(loginName: string, siteUrl: string): Promise<SiteUser> {
let results: SiteUser = null;
if (!loginName && !siteUrl) {
return null;
}
try {
const web = new Web(siteUrl);
await web.ensureUser(loginName);
results = await web.siteUsers.getByLoginName(loginName).get();
//results = await web.siteUsers.getByLoginName(userId).get();
} catch (error) {
return Promise.reject(error);
}
return results;
}
/**
*
* @param {string} loginName
* @returns
* @memberof spservices
*/
public async getUserProfilePictureUrl(loginName: string) {
let results: any = null;
try {
results = await sp.profiles.usingCaching().getPropertiesFor(loginName);
} catch (error) {
results = null;
}
return results.PictureUrl;
}
/**
*
* @param {string} siteUrl
* @param {string} listId
* @returns {Promise<IUserPermissions>}
* @memberof spservices
*/
public async getUserPermissions(siteUrl: string, listId: string): Promise<IUserPermissions> {
let hasPermissionAdd: boolean = false;
let hasPermissionEdit: boolean = false;
let hasPermissionDelete: boolean = false;
let hasPermissionView: boolean = false;
let userPermissions: IUserPermissions = undefined;
try {
const web = new Web(siteUrl);
const userEffectivePermissions = await web.lists.getById(listId).effectiveBasePermissions.get();
// ...
hasPermissionAdd = sp.web.lists.getById(listId).hasPermissions(userEffectivePermissions, PermissionKind.AddListItems);
hasPermissionDelete = sp.web.lists.getById(listId).hasPermissions(userEffectivePermissions, PermissionKind.DeleteListItems);
hasPermissionEdit = sp.web.lists.getById(listId).hasPermissions(userEffectivePermissions, PermissionKind.EditListItems);
hasPermissionView = sp.web.lists.getById(listId).hasPermissions(userEffectivePermissions, PermissionKind.ViewListItems);
userPermissions = { hasPermissionAdd: hasPermissionAdd, hasPermissionEdit: hasPermissionEdit, hasPermissionDelete: hasPermissionDelete, hasPermissionView: hasPermissionView };
} catch (error) {
return Promise.reject(error);
}
return userPermissions;
}
/**
*
* @param {string} siteUrl
* @returns
* @memberof spservices
*/
public async getSiteLists(siteUrl: string) {
let results: any[] = [];
if (!siteUrl) {
return [];
}
try {
const web = new Web(siteUrl);
results = await web.lists.select("Title", "ID").filter('BaseTemplate eq 106').get();
} catch (error) {
return Promise.reject(error);
}
return results;
}
/**
*
* @private
* @returns
* @memberof spservices
*/
public async colorGenerate() {
var hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e"];
var newColor = "#";
for (var i = 0; i < 6; i++) {
var x = Math.round(Math.random() * 14);
var y = hexValues[x];
newColor += y;
}
return newColor;
}
/**
*
* @param {string} siteUrl
* @param {string} listId
* @param {string} fieldInternalName
* @returns {Promise<{ key: string, text: string }[]>}
* @memberof spservices
*/
public async getChoiceFieldOptions(siteUrl: string, listId: string, fieldInternalName: string): Promise<{ key: string, text: string }[]> {
let fieldOptions: { key: string, text: string }[] = [];
try {
const web = new Web(siteUrl);
const results = await web.lists.getById(listId)
.fields
.getByInternalNameOrTitle(fieldInternalName)
.select("Title", "InternalName", "Choices")
.get();
if (results && results.Choices.length > 0) {
for (const option of results.Choices) {
fieldOptions.push({
key: option,
text: option
});
}
}
} catch (error) {
return Promise.reject(error);
}
return fieldOptions;
}
/**
*
* @param {string} siteUrl
* @param {string} listId
* @param {Date} eventStartDate
* @param {Date} eventEndDate
* @returns {Promise< IEventData[]>}
* @memberof spservices
*/
public async getEvents(siteUrl: string, listId: string, eventStartDate: Date, eventEndDate: Date): Promise<IEventData[]> {
let events: IEventData[] = [];
if (!siteUrl) {
return [];
}
try {
// Get Category Field Choices
const categoryDropdownOption = await this.getChoiceFieldOptions(siteUrl, listId, 'Category');
let categoryColor: { category: string, color: string }[] = [];
for (const cat of categoryDropdownOption) {
categoryColor.push({ category: cat.text, color: await this.colorGenerate() });
}
const web = new Web(siteUrl);
const results = await web.lists.getById(listId).usingCaching().renderListDataAsStream(
{
DatesInUtc: true,
ViewXml: `<View><ViewFields><FieldRef Name='RecurrenceData'/><FieldRef Name='Duration'/><FieldRef Name='Author'/><FieldRef Name='Category'/><FieldRef Name='Description'/><FieldRef Name='ParticipantsPicker'/><FieldRef Name='Geolocation'/><FieldRef Name='ID'/><FieldRef Name='EndDate'/><FieldRef Name='EventDate'/><FieldRef Name='ID'/><FieldRef Name='Location'/><FieldRef Name='Title'/><FieldRef Name='fAllDayEvent'/><FieldRef Name='EventType'/><FieldRef Name='UID' /><FieldRef Name='fRecurrence' /></ViewFields>
<Query>
<Where>
<And>
<Geq>
<FieldRef Name='EventDate' />
<Value IncludeTimeValue='false' Type='DateTime'>${moment(eventStartDate).format('YYYY-MM-DD')}</Value>
</Geq>
<Leq>
<FieldRef Name='EventDate' />
<Value IncludeTimeValue='false' Type='DateTime'>${moment(eventEndDate).format('YYYY-MM-DD')}</Value>
</Leq>
</And>
</Where>
</Query>
<RowLimit Paged=\"FALSE\">2000</RowLimit>
</View>`
}
);
if (results && results.Row.length > 0) {
let event: any = '';
const mapEvents = async () : Promise<boolean> => {
for (event of results.Row) {
const eventDate = await this.getLocalTime(event.EventDate);
const endDate = await this.getLocalTime(event.EndDate);
const initialsArray: string[] = event.Author[0].title.split(' ');
const initials: string = initialsArray[0].charAt(0) + initialsArray[initialsArray.length - 1].charAt(0);
const userPictureUrl = await this.getUserProfilePictureUrl(`i:0#.f|membership|${event.Author[0].email}`);
const attendees: number[] = [];
const first: number = event.Geolocation.indexOf('(') + 1;
const last: number = event.Geolocation.indexOf(')');
const geo = event.Geolocation.substring(first, last);
const geolocation = geo.split(' ');
const CategoryColorValue: any[] = categoryColor.filter((value) => {
return value.category == event.Category;
});
const isAllDayEvent: boolean = event["fAllDayEvent.value"] === "1";
for (const attendee of event.ParticipantsPicker) {
attendees.push(parseInt(attendee.id));
}
events.push({
Id: event.ID,
ID: event.ID,
EventType: event.EventType,
title: await this.deCodeHtmlEntities(event.Title),
Description: event.Description,
EventDate: isAllDayEvent ? new Date(event.EventDate.slice(0, -1)) : new Date(eventDate),
EndDate: isAllDayEvent ? new Date(event.EndDate.slice(0, -1)) : new Date(endDate),
location: event.Location,
ownerEmail: event.Author[0].email,
ownerPhoto: userPictureUrl ?
`https://outlook.office365.com/owa/service.svc/s/GetPersonaPhoto?email=${event.Author[0].email}&UA=0&size=HR96x96` : '',
ownerInitial: initials,
color: CategoryColorValue.length > 0 ? CategoryColorValue[0].color : '#1a75ff', // blue default
ownerName: event.Author[0].title,
attendes: attendees,
fAllDayEvent: isAllDayEvent,
geolocation: { Longitude: parseFloat(geolocation[0]), Latitude: parseFloat(geolocation[1]) },
Category: event.Category,
Duration: event.Duration,
RecurrenceData: event.RecurrenceData ? await this.deCodeHtmlEntities(event.RecurrenceData) : "",
fRecurrence: event.fRecurrence,
RecurrenceID: event.RecurrenceID ? event.RecurrenceID : undefined,
MasterSeriesItemID: event.MasterSeriesItemID,
UID: event.UID.replace("{", "").replace("}", ""),
});
}
return true;
};
//Checks to see if there are any results saved in local storage
if(window.localStorage.getItem("eventResult")){
//if there is a local version - compares it to the current version
if(window.localStorage.getItem("eventResult") === JSON.stringify(results)){
//No update needed use current savedEvents
events = JSON.parse(window.localStorage.getItem("calendarEventsWithLocalTime"));
}else{
//update local storage
window.localStorage.setItem("eventResult", JSON.stringify(results));
//when they are not equal then we loop through the results and maps them to IEventData
/* tslint:disable:no-unused-expression */
await mapEvents() ? window.localStorage.setItem("calendarEventsWithLocalTime", JSON.stringify(events)) : null;
}
}else{
//if there is no local storage of the events we create them
window.localStorage.setItem("eventResult", JSON.stringify(results));
//we also needs to map through the events the first time and save the mapped version to local storage
await mapEvents() ? window.localStorage.setItem("calendarEventsWithLocalTime", JSON.stringify(events)) : null;
}
}
let parseEvt: parseRecurrentEvent = new parseRecurrentEvent();
events = parseEvt.parseEvents(events, null, null);
// Return Data
return events;
} catch (error) {
console.dir(error);
return Promise.reject(error);
}
}
/**
*
* @private
* @param {string} siteUrl
* @returns
* @memberof spservices
*/
public async getSiteRegionalSettingsTimeZone(siteUrl: string) {
let regionalSettings: RegionalSettings;
try {
const web = new Web(siteUrl);
regionalSettings = await web.regionalSettings.timeZone.usingCaching().get();
} catch (error) {
return Promise.reject(error);
}
return regionalSettings;
}
/**
* @param {string} webUrl
* @param {string} siteDesignId
* @returns
* @memberof spservices
*/
public async getGeoLactionName(latitude: number, longitude: number) {
try {
const apiUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}&zoom=18&addressdetails=1`;
const results = await $.ajax({
url: apiUrl,
type: 'GET',
dataType: 'json',
headers: {
'content-type': 'application/json;charset=utf-8',
'accept': 'application/json;odata=nometadata',
}
});
if (results) {
return results;
}
} catch (error) {
return Promise.reject(error);
}
}
public async enCodeHtmlEntities(string: string) {
const HtmlEntitiesMap = {
"'": "'",
"<": "<",
">": ">",
" ": " ",
"¡": "¡",
"¢": "¢",
"£": "£",
"¤": "¤",
"¥": "¥",
"¦": "¦",
"§": "§",
"¨": "¨",
"©": "©",
"ª": "ª",
"«": "«",
"¬": "¬",
"®": "®",
"¯": "¯",
"°": "°",
"±": "±",
"²": "²",
"³": "³",
"´": "´",
"µ": "µ",
"¶": "¶",
"·": "·",
"¸": "¸",
"¹": "¹",
"º": "º",
"»": "»",
"¼": "¼",
"½": "½",
"¾": "¾",
"¿": "¿",
"À": "À",
"Á": "Á",
"Â": "Â",
"Ã": "Ã",
"Ä": "Ä",
"Å": "Å",
"Æ": "Æ",
"Ç": "Ç",
"È": "È",
"É": "É",
"Ê": "Ê",
"Ë": "Ë",
"Ì": "Ì",
"Í": "Í",
"Î": "Î",
"Ï": "Ï",
"Ð": "Ð",
"Ñ": "Ñ",
"Ò": "Ò",
"Ó": "Ó",
"Ô": "Ô",
"Õ": "Õ",
"Ö": "Ö",
"×": "×",
"Ø": "Ø",
"Ù": "Ù",
"Ú": "Ú",
"Û": "Û",
"Ü": "Ü",
"Ý": "Ý",
"Þ": "Þ",
"ß": "ß",
"à": "à",
"á": "á",
"â": "â",
"ã": "ã",
"ä": "ä",
"å": "å",
"æ": "æ",
"ç": "ç",
"è": "è",
"é": "é",
"ê": "ê",
"ë": "ë",
"ì": "ì",
"í": "í",
"î": "î",
"ï": "ï",
"ð": "ð",
"ñ": "ñ",
"ò": "ò",
"ó": "ó",
"ô": "ô",
"õ": "õ",
"ö": "ö",
"÷": "÷",
"ø": "ø",
"ù": "ù",
"ú": "ú",
"û": "û",
"ü": "ü",
"ý": "ý",
"þ": "þ",
"ÿ": "ÿ",
"Œ": "Œ",
"œ": "œ",
"Š": "Š",
"š": "š",
"Ÿ": "Ÿ",
"ƒ": "ƒ",
"ˆ": "ˆ",
"˜": "˜",
"Α": "Α",
"Β": "Β",
"Γ": "Γ",
"Δ": "Δ",
"Ε": "Ε",
"Ζ": "Ζ",
"Η": "Η",
"Θ": "Θ",
"Ι": "Ι",
"Κ": "Κ",
"Λ": "Λ",
"Μ": "Μ",
"Ν": "Ν",
"Ξ": "Ξ",
"Ο": "Ο",
"Π": "Π",
"Ρ": "Ρ",
"Σ": "Σ",
"Τ": "Τ",
"Υ": "Υ",
"Φ": "Φ",
"Χ": "Χ",
"Ψ": "Ψ",
"Ω": "Ω",
"α": "α",
"β": "β",
"γ": "γ",
"δ": "δ",
"ε": "ε",
"ζ": "ζ",
"η": "η",
"θ": "θ",
"ι": "ι",
"κ": "κ",
"λ": "λ",
"μ": "μ",
"ν": "ν",
"ξ": "ξ",
"ο": "ο",
"π": "π",
"ρ": "ρ",
"ς": "ς",
"σ": "σ",
"τ": "τ",
"υ": "υ",
"φ": "φ",
"χ": "χ",
"ψ": "ψ",
"ω": "ω",
"ϑ": "ϑ",
"ϒ": "&Upsih;",
"ϖ": "ϖ",
"–": "–",
"—": "—",
"‘": "‘",
"’": "’",
"‚": "‚",
"“": "“",
"”": "”",
"„": "„",
"†": "†",
"‡": "‡",
"•": "•",
"…": "…",
"‰": "‰",
"′": "′",
"″": "″",
"‹": "‹",
"›": "›",
"‾": "‾",
"⁄": "⁄",
"€": "€",
"ℑ": "ℑ",
"℘": "℘",
"ℜ": "ℜ",
"™": "™",
"ℵ": "ℵ",
"←": "←",
"↑": "↑",
"→": "→",
"↓": "↓",
"↔": "↔",
"↵": "↵",
"⇐": "⇐",
"⇑": "&UArr;",
"⇒": "⇒",
"⇓": "⇓",
"⇔": "⇔",
"∀": "∀",
"∂": "∂",
"∃": "∃",
"∅": "∅",
"∇": "∇",
"∈": "∈",
"∉": "∉",
"∋": "∋",
"∏": "∏",
"∑": "∑",
"−": "−",
"∗": "∗",
"√": "√",
"∝": "∝",
"∞": "∞",
"∠": "∠",
"∧": "∧",
"∨": "∨",
"∩": "∩",
"∪": "∪",
"∫": "∫",
"∴": "∴",
"∼": "∼",
"≅": "≅",
"≈": "≈",
"≠": "≠",
"≡": "≡",
"≤": "≤",
"≥": "≥",
"⊂": "⊂",
"⊃": "⊃",
"⊄": "⊄",
"⊆": "⊆",
"⊇": "⊇",
"⊕": "⊕",
"⊗": "⊗",
"⊥": "⊥",
"⋅": "⋅",
"⌈": "⌈",
"⌉": "⌉",
"⌊": "⌊",
"⌋": "⌋",
"⟨": "⟨",
"⟩": "⟩",
"◊": "◊",
"♠": "♠",
"♣": "♣",
"♥": "♥",
"♦": "♦"
};
var entityMap = HtmlEntitiesMap;
string = string.replace(/&/g, '&');
string = string.replace(/"/g, '"');
for (var key in entityMap) {
var entity = entityMap[key];
var regex = new RegExp(key, 'g');
string = string.replace(regex, entity);
}
return string;
}
public async deCodeHtmlEntities(string: string) {
const HtmlEntitiesMap = {
"'": "'",
"<": "<",
">": ">",
" ": " ",
"¡": "¡",
"¢": "¢",
"£": "£",
"¤": "¤",
"¥": "¥",
"¦": "¦",
"§": "§",
"¨": "¨",
"©": "©",
"ª": "ª",
"«": "«",
"¬": "¬",
"®": "®",
"¯": "¯",
"°": "°",
"±": "±",
"²": "²",
"³": "³",
"´": "´",
"µ": "µ",
"¶": "¶",
"·": "·",
"¸": "¸",
"¹": "¹",
"º": "º",
"»": "»",
"¼": "¼",
"½": "½",
"¾": "¾",
"¿": "¿",
"À": "À",
"Á": "Á",
"Â": "Â",
"Ã": "Ã",
"Ä": "Ä",
"Å": "Å",
"Æ": "Æ",
"Ç": "Ç",
"È": "È",
"É": "É",
"Ê": "Ê",
"Ë": "Ë",
"Ì": "Ì",
"Í": "Í",
"Î": "Î",
"Ï": "Ï",
"Ð": "Ð",
"Ñ": "Ñ",
"Ò": "Ò",
"Ó": "Ó",
"Ô": "Ô",
"Õ": "Õ",
"Ö": "Ö",
"×": "×",
"Ø": "Ø",
"Ù": "Ù",
"Ú": "Ú",
"Û": "Û",
"Ü": "Ü",
"Ý": "Ý",
"Þ": "Þ",
"ß": "ß",
"à": "à",
"á": "á",
"â": "â",
"ã": "ã",
"ä": "ä",
"å": "å",
"æ": "æ",
"ç": "ç",
"è": "è",
"é": "é",
"ê": "ê",
"ë": "ë",
"ì": "ì",
"í": "í",
"î": "î",
"ï": "ï",
"ð": "ð",
"ñ": "ñ",
"ò": "ò",
"ó": "ó",
"ô": "ô",
"õ": "õ",
"ö": "ö",
"÷": "÷",
"ø": "ø",
"ù": "ù",
"ú": "ú",
"û": "û",
"ü": "ü",
"ý": "ý",
"þ": "þ",
"ÿ": "ÿ",
"Œ": "Œ",
"œ": "œ",
"Š": "Š",
"š": "š",
"Ÿ": "Ÿ",
"ƒ": "ƒ",
"ˆ": "ˆ",
"˜": "˜",
"Α": "Α",
"Β": "Β",
"Γ": "Γ",
"Δ": "Δ",
"Ε": "Ε",
"Ζ": "Ζ",
"Η": "Η",
"Θ": "Θ",
"Ι": "Ι",
"Κ": "Κ",
"Λ": "Λ",
"Μ": "Μ",
"Ν": "Ν",
"Ξ": "Ξ",
"Ο": "Ο",
"Π": "Π",
"Ρ": "Ρ",
"Σ": "Σ",
"Τ": "Τ",
"Υ": "Υ",
"Φ": "Φ",
"Χ": "Χ",
"Ψ": "Ψ",
"Ω": "Ω",
"α": "α",
"β": "β",
"γ": "γ",
"δ": "δ",
"ε": "ε",
"ζ": "ζ",
"η": "η",
"θ": "θ",
"ι": "ι",
"κ": "κ",
"λ": "λ",
"μ": "μ",
"ν": "ν",
"ξ": "ξ",
"ο": "ο",
"π": "π",
"ρ": "ρ",
"ς": "ς",
"σ": "σ",
"τ": "τ",
"υ": "υ",
"φ": "φ",
"χ": "χ",
"ψ": "ψ",
"ω": "ω",
"ϑ": "ϑ",
"ϒ": "&Upsih;",
"ϖ": "ϖ",
"–": "–",
"—": "—",
"‘": "‘",
"’": "’",
"‚": "‚",
"“": "“",
"”": "”",
"„": "„",
"†": "†",
"‡": "‡",
"•": "•",
"…": "…",
"‰": "‰",
"′": "′",
"″": "″",
"‹": "‹",
"›": "›",
"‾": "‾",
"⁄": "⁄",
"€": "€",
"ℑ": "ℑ",
"℘": "℘",
"ℜ": "ℜ",
"™": "™",
"ℵ": "ℵ",
"←": "←",
"↑": "↑",
"→": "→",
"↓": "↓",
"↔": "↔",
"↵": "↵",
"⇐": "⇐",
"⇑": "&UArr;",
"⇒": "⇒",
"⇓": "⇓",
"⇔": "⇔",
"∀": "∀",
"∂": "∂",
"∃": "∃",
"∅": "∅",
"∇": "∇",
"∈": "∈",
"∉": "∉",
"∋": "∋",
"∏": "∏",
"∑": "∑",
"−": "−",
"∗": "∗",
"√": "√",
"∝": "∝",
"∞": "∞",
"∠": "∠",
"∧": "∧",
"∨": "∨",
"∩": "∩",
"∪": "∪",
"∫": "∫",
"∴": "∴",
"∼": "∼",
"≅": "≅",
"≈": "≈",
"≠": "≠",
"≡": "≡",
"≤": "≤",
"≥": "≥",
"⊂": "⊂",
"⊃": "⊃",
"⊄": "⊄",
"⊆": "⊆",
"⊇": "⊇",
"⊕": "⊕",
"⊗": "⊗",
"⊥": "⊥",
"⋅": "⋅",
"⌈": "⌈",
"⌉": "⌉",
"⌊": "⌊",
"⌋": "⌋",
"⟨": "⟨",
"⟩": "⟩",
"◊": "◊",
"♠": "♠",
"♣": "♣",
"♥": "♥",
"♦": "♦"
};
var entityMap = HtmlEntitiesMap;
for (var key in entityMap) {
var entity = entityMap[key];
var regex = new RegExp(entity, 'g');
string = string.replace(regex, key);
}
string = string.replace(/"/g, '"');
string = string.replace(/&/g, '&');
return string;
}
} | the_stack |
import { App, aws_lambda, Stack } from "aws-cdk-lib";
import "jest";
import {
Function,
AppsyncContext,
EventBus,
AsyncFunctionResponseEvent,
AsyncResponseSuccess,
AsyncResponseFailure,
asyncSynth,
} from "../src";
import { reflect } from "../src/reflect";
import { appsyncTestCase } from "./util";
interface Item {
id: string;
name: number;
}
let app: App;
let stack: Stack;
let lambda: aws_lambda.Function;
beforeEach(() => {
app = new App({ autoSynth: false });
stack = new Stack(app, "stack");
lambda = new aws_lambda.Function(stack, "F", {
code: aws_lambda.Code.fromInline(
"exports.handler = function() { return null; }"
),
handler: "index.handler",
runtime: aws_lambda.Runtime.NODEJS_14_X,
});
});
test("call function", () => {
const fn1 = Function.fromFunction<{ arg: string }, Item>(lambda);
appsyncTestCase(
reflect((context: AppsyncContext<{ arg: string }>) => {
return fn1(context.arguments);
})
);
});
test("call function and conditional return", () => {
const fn1 = Function.fromFunction<{ arg: string }, Item>(lambda);
appsyncTestCase(
reflect((context: AppsyncContext<{ arg: string }>) => {
const result = fn1(context.arguments);
if (result.id === "sam") {
return true;
} else {
return false;
}
})
);
});
test("call function omitting optional arg", () => {
const fn2 = Function.fromFunction<{ arg: string; optional?: string }, Item>(
lambda
);
appsyncTestCase(
reflect((context: AppsyncContext<{ arg: string }>) => {
return fn2(context.arguments);
})
);
});
test("call function including optional arg", () => {
const fn2 = Function.fromFunction<{ arg: string; optional?: string }, Item>(
lambda
);
appsyncTestCase(
reflect((context: AppsyncContext<{ arg: string }>) => {
return fn2({ arg: context.arguments.arg, optional: "hello" });
})
);
});
test("call function including with no parameters", () => {
const fn3 = Function.fromFunction<undefined, Item>(lambda);
appsyncTestCase(
reflect(() => {
return fn3();
})
);
});
test("call function including with void result", () => {
const fn4 = Function.fromFunction<{ arg: string }, void>(lambda);
appsyncTestCase(
reflect((context: AppsyncContext<{ arg: string }>) => {
return fn4(context.arguments);
})
);
});
test("set on success bus", () => {
const bus = new EventBus<AsyncFunctionResponseEvent<string, void>>(
stack,
"bus"
);
const func = new Function<string, void>(
stack,
"func2",
{
onSuccess: bus,
},
async () => {}
);
expect(
(<aws_lambda.CfnEventInvokeConfig.OnSuccessProperty>(
(<aws_lambda.CfnEventInvokeConfig.DestinationConfigProperty>(
(<aws_lambda.CfnEventInvokeConfig>(
(<aws_lambda.EventInvokeConfig>(
func.resource.node.tryFindChild("EventInvokeConfig")
))?.node?.tryFindChild("Resource")
))?.destinationConfig
))?.onSuccess
)).destination
).toEqual(bus.resource.eventBusArn);
});
test("set on failure bus", () => {
const bus = new EventBus<AsyncFunctionResponseEvent<string, void>>(
stack,
"bus2"
);
const func = new Function<string, void>(
stack,
"func3",
{
onFailure: bus,
},
async () => {}
);
expect(
(<aws_lambda.CfnEventInvokeConfig.OnFailureProperty>(
(<aws_lambda.CfnEventInvokeConfig.DestinationConfigProperty>(
(<aws_lambda.CfnEventInvokeConfig>(
(<aws_lambda.EventInvokeConfig>(
func.resource.node.tryFindChild("EventInvokeConfig")
))?.node?.tryFindChild("Resource")
))?.destinationConfig
))?.onFailure
)).destination
).toEqual(bus.resource.eventBusArn);
});
test("set on success function", () => {
const onSuccessFunction = new Function<
AsyncResponseSuccess<string, void>,
void
>(stack, "func", async () => {});
const func = new Function<string, void>(
stack,
"func2",
{
onSuccess: onSuccessFunction,
},
async () => {}
);
expect(
(<aws_lambda.CfnEventInvokeConfig.OnSuccessProperty>(
(<aws_lambda.CfnEventInvokeConfig.DestinationConfigProperty>(
(<aws_lambda.CfnEventInvokeConfig>(
(<aws_lambda.EventInvokeConfig>(
func.resource.node.tryFindChild("EventInvokeConfig")
))?.node?.tryFindChild("Resource")
))?.destinationConfig
))?.onSuccess
)).destination
).toEqual(onSuccessFunction.resource.functionArn);
});
test("set on failure function", () => {
const onFailureFunction = new Function<AsyncResponseFailure<string>, void>(
stack,
"func",
async () => {}
);
const func = new Function<string, void>(
stack,
"func3",
{
onFailure: onFailureFunction,
},
async () => {}
);
expect(
(<aws_lambda.CfnEventInvokeConfig.OnFailureProperty>(
(<aws_lambda.CfnEventInvokeConfig.DestinationConfigProperty>(
(<aws_lambda.CfnEventInvokeConfig>(
(<aws_lambda.EventInvokeConfig>(
func.resource.node.tryFindChild("EventInvokeConfig")
))?.node?.tryFindChild("Resource")
))?.destinationConfig
))?.onFailure
)).destination
).toEqual(onFailureFunction.resource.functionArn);
});
test("configure async with functions", () => {
const handleAsyncFunction = new Function<
AsyncResponseFailure<string> | AsyncResponseSuccess<string, void>,
void
>(stack, "func", async () => {});
const func = new Function<string, void>(stack, "func3", async () => {});
func.enableAsyncInvoke({
onFailure: handleAsyncFunction,
onSuccess: handleAsyncFunction,
});
const config = <aws_lambda.CfnEventInvokeConfig.DestinationConfigProperty>(
(<aws_lambda.CfnEventInvokeConfig>(
(<aws_lambda.EventInvokeConfig>(
func.resource.node.tryFindChild("EventInvokeConfig")
))?.node?.tryFindChild("Resource")
))?.destinationConfig
);
expect(
(<aws_lambda.CfnEventInvokeConfig.OnFailureProperty>config?.onFailure)
.destination
).toEqual(handleAsyncFunction.resource.functionArn);
expect(
(<aws_lambda.CfnEventInvokeConfig.OnFailureProperty>config?.onSuccess)
.destination
).toEqual(handleAsyncFunction.resource.functionArn);
});
test("configure async with bus", () => {
const bus = new EventBus<AsyncFunctionResponseEvent<string, void>>(
stack,
"bus2"
);
const func = new Function<string, void>(stack, "func3", async () => {});
func.enableAsyncInvoke({
onFailure: bus,
onSuccess: bus,
});
const config = <aws_lambda.CfnEventInvokeConfig.DestinationConfigProperty>(
(<aws_lambda.CfnEventInvokeConfig>(
(<aws_lambda.EventInvokeConfig>(
func.resource.node.tryFindChild("EventInvokeConfig")
))?.node?.tryFindChild("Resource")
))?.destinationConfig
);
expect(
(<aws_lambda.CfnEventInvokeConfig.OnFailureProperty>config?.onFailure)
.destination
).toEqual(bus.resource.eventBusArn);
expect(
(<aws_lambda.CfnEventInvokeConfig.OnFailureProperty>config?.onSuccess)
.destination
).toEqual(bus.resource.eventBusArn);
});
test("set on success rule", () => {
const bus = new EventBus<AsyncFunctionResponseEvent<string, void>>(
stack,
"bus3"
);
const func = new Function<string, void>(stack, "func3", async () => {});
const onSuccess = func.onSuccess(bus, "funcSuccess");
onSuccess.pipe(bus);
expect(onSuccess.resource._renderEventPattern()).toEqual({
source: ["lambda"],
"detail-type": ["Lambda Function Invocation Result - Success"],
resources: [func.resource.functionArn],
});
});
test("set on failure rule", () => {
const bus = new EventBus<AsyncFunctionResponseEvent<string, void>>(
stack,
"bus3"
);
const func = new Function<string, void>(stack, "func3", async () => {});
const onFailure = func.onFailure(bus, "funcFailure");
onFailure.pipe(bus);
expect(onFailure.resource._renderEventPattern()).toEqual({
source: ["lambda"],
"detail-type": ["Lambda Function Invocation Result - Failure"],
resources: [func.resource.functionArn],
});
});
test("onFailure().pipe should type check", () => {
const bus = new EventBus<AsyncFunctionResponseEvent<string, void>>(
stack,
"bus3"
);
const func = new Function<number, void>(stack, "func3", async () => {});
// @ts-expect-error
const onFailure = func.onFailure(bus, "funcFailure");
// @ts-expect-error
const onSuccess = func.onSuccess(bus, "funcSuccess");
// @ts-expect-error
onFailure.pipe(bus);
// @ts-expect-error
onSuccess.pipe(bus);
expect(onFailure.resource._renderEventPattern()).toEqual({
source: ["lambda"],
"detail-type": ["Lambda Function Invocation Result - Failure"],
resources: [func.resource.functionArn],
});
});
test("function inline arrow closure", () => {
new Function(stack, "inline", async (p: string) => p);
});
test("function block closure", () => {
new Function(stack, "block", async (p: string) => {
return p;
});
});
test("function accepts a superset of primitives", () => {
const func1 = new Function(stack, "superset", async (p: string | number) => {
return p;
});
new Function(
stack,
"subset",
async (p: { sn: string | number; b: boolean; bs: boolean | string }) => {
func1("hello");
func1(1);
func1(p.sn);
// @ts-expect-error - func1 accepts a string or number
func1(p.b);
if (typeof p.bs === "string") {
func1(p.bs);
}
}
);
});
test("function accepts a superset of objects", () => {
const func1 = new Function(
stack,
"superset",
async (p: { a: string } | { b: string }) => {
return p;
}
);
new Function(
stack,
"subset",
async (p: {
a: { a: string };
b: { b: string };
ab: { a: string } | { b: string };
aabb: { a: string; b: string };
c: { c: string };
ac: { a: string; c: string };
}) => {
func1(p.a);
func1(p.b);
func1(p.ab);
func1(p.aabb);
// @ts-expect-error - func1 requires a or b
func1(p.c);
func1(p.ac);
}
);
});
test("function fails to synth when compile promise is not complete", async () => {
expect(() => {
new Function(
stack,
"superset",
async (p: { a: string } | { b: string }) => {
return p;
}
);
app.synth();
}).toThrow("Function closure serialization was not allowed to complete");
});
test("synth succeeds with async synth", async () => {
new Function(stack, "superset", async (p: { a: string } | { b: string }) => {
return p;
});
await asyncSynth(app);
// synth is slow
}, 500000); | the_stack |
import {CollectionViewer, DataSource} from '@angular/cdk/collections';
import {Component, Type, ViewChild} from '@angular/core';
import {ComponentFixture, fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing';
import {BehaviorSubject, combineLatest} from 'rxjs';
import {map} from 'rxjs/operators';
import {CdkTable, CdkTableModule} from '@angular/cdk/table';
import {Platform} from '@angular/cdk/platform';
import {CdkTableScrollContainerModule} from './index';
describe('CdkTableScrollContainer', () => {
let fixture: ComponentFixture<any>;
let component: any;
let platform: Platform;
let tableElement: HTMLElement;
let scrollerElement: HTMLElement;
let dataRows: HTMLElement[];
let headerRows: HTMLElement[];
let footerRows: HTMLElement[];
function createComponent<T>(
componentType: Type<T>,
declarations: any[] = [],
): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [CdkTableModule, CdkTableScrollContainerModule],
declarations: [componentType, ...declarations],
}).compileComponents();
return TestBed.createComponent<T>(componentType);
}
function setupTableTestApp(componentType: Type<any>, declarations: any[] = []) {
fixture = createComponent(componentType, declarations);
component = fixture.componentInstance;
fixture.detectChanges();
tableElement = fixture.nativeElement.querySelector('.cdk-table');
scrollerElement = fixture.nativeElement.querySelector('.cdk-table-scroll-container');
}
beforeEach(() => {
setupTableTestApp(StickyNativeLayoutCdkTableApp);
platform = TestBed.inject(Platform);
headerRows = getHeaderRows(tableElement);
footerRows = getFooterRows(tableElement);
dataRows = getRows(tableElement);
});
it('sets scrollbar track margin for sticky headers', fakeAsync(() => {
component.stickyHeaders = ['header-1', 'header-3'];
fixture.detectChanges();
flushMicrotasks();
if (platform.FIREFOX) {
// ::-webkit-scrollbar-track is not recognized by Firefox.
return;
}
const scrollerStyle = window.getComputedStyle(scrollerElement, '::-webkit-scrollbar-track');
expect(scrollerStyle.getPropertyValue('margin-top')).toBe(`${headerRows[0].offsetHeight}px`);
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
component.stickyHeaders = [];
fixture.detectChanges();
flushMicrotasks();
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
}));
it('sets scrollbar track margin for sticky footers', fakeAsync(() => {
component.stickyFooters = ['footer-1', 'footer-3'];
fixture.detectChanges();
flushMicrotasks();
if (platform.FIREFOX) {
// ::-webkit-scrollbar-track is not recognized by Firefox.
return;
}
const scrollerStyle = window.getComputedStyle(scrollerElement, '::-webkit-scrollbar-track');
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe(`${footerRows[2].offsetHeight}px`);
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
component.stickyFooters = [];
fixture.detectChanges();
flushMicrotasks();
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
}));
it('sets scrollbar track margin for sticky start columns', fakeAsync(() => {
component.stickyStartColumns = ['column-1', 'column-3'];
fixture.detectChanges();
flushMicrotasks();
if (platform.FIREFOX) {
// ::-webkit-scrollbar-track is not recognized by Firefox.
return;
}
const scrollerStyle = window.getComputedStyle(scrollerElement, '::-webkit-scrollbar-track');
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe(
`${getCells(dataRows[0])[0].offsetWidth}px`,
);
component.stickyStartColumns = [];
fixture.detectChanges();
flushMicrotasks();
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
}));
it('sets scrollbar track margin for sticky end columns', fakeAsync(() => {
component.stickyEndColumns = ['column-4', 'column-6'];
fixture.detectChanges();
flushMicrotasks();
if (platform.FIREFOX) {
// ::-webkit-scrollbar-track is not recognized by Firefox.
return;
}
const scrollerStyle = window.getComputedStyle(scrollerElement, '::-webkit-scrollbar-track');
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe(
`${getCells(dataRows[0])[5].offsetWidth}px`,
);
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
component.stickyEndColumns = [];
fixture.detectChanges();
flushMicrotasks();
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
}));
it('sets scrollbar track margin for a combination of sticky rows and columns', fakeAsync(() => {
component.stickyHeaders = ['header-1'];
component.stickyFooters = ['footer-3'];
component.stickyStartColumns = ['column-1'];
component.stickyEndColumns = ['column-6'];
fixture.detectChanges();
flushMicrotasks();
if (platform.FIREFOX) {
// ::-webkit-scrollbar-track is not recognized by Firefox.
return;
}
const scrollerStyle = window.getComputedStyle(scrollerElement, '::-webkit-scrollbar-track');
expect(scrollerStyle.getPropertyValue('margin-top')).toBe(`${headerRows[0].offsetHeight}px`);
expect(scrollerStyle.getPropertyValue('margin-right')).toBe(
`${getCells(dataRows[0])[5].offsetWidth}px`,
);
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe(`${footerRows[2].offsetHeight}px`);
expect(scrollerStyle.getPropertyValue('margin-left')).toBe(
`${getCells(dataRows[0])[0].offsetWidth}px`,
);
component.stickyHeaders = [];
component.stickyFooters = [];
component.stickyStartColumns = [];
component.stickyEndColumns = [];
fixture.detectChanges();
flushMicrotasks();
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
}));
});
interface TestData {
a: string;
b: string;
c: string;
}
class FakeDataSource extends DataSource<TestData> {
isConnected = false;
get data() {
return this._dataChange.getValue();
}
set data(data: TestData[]) {
this._dataChange.next(data);
}
_dataChange = new BehaviorSubject<TestData[]>([]);
constructor() {
super();
for (let i = 0; i < 3; i++) {
this.addData();
}
}
connect(collectionViewer: CollectionViewer) {
this.isConnected = true;
return combineLatest([this._dataChange, collectionViewer.viewChange]).pipe(
map(data => data[0]),
);
}
disconnect() {
this.isConnected = false;
}
addData() {
const nextIndex = this.data.length + 1;
let copiedData = this.data.slice();
copiedData.push({
a: `a_${nextIndex}`,
b: `b_${nextIndex}`,
c: `c_${nextIndex}`,
});
this.data = copiedData;
}
}
@Component({
template: `
<div cdkTableScrollContainer>
<table cdk-table [dataSource]="dataSource">
<ng-container [cdkColumnDef]="column" *ngFor="let column of columns"
[sticky]="isStuck(stickyStartColumns, column)"
[stickyEnd]="isStuck(stickyEndColumns, column)">
<th cdk-header-cell *cdkHeaderCellDef> Header {{column}} </th>
<td cdk-cell *cdkCellDef="let row"> {{column}} </td>
<td cdk-footer-cell *cdkFooterCellDef> Footer {{column}} </td>
</ng-container>
<tr cdk-header-row *cdkHeaderRowDef="columns; sticky: isStuck(stickyHeaders, 'header-1')">
</tr>
<tr cdk-header-row *cdkHeaderRowDef="columns; sticky: isStuck(stickyHeaders, 'header-2')">
</tr>
<tr cdk-header-row *cdkHeaderRowDef="columns; sticky: isStuck(stickyHeaders, 'header-3')">
</tr>
<tr cdk-row *cdkRowDef="let row; columns: columns"></tr>
<tr cdk-footer-row *cdkFooterRowDef="columns; sticky: isStuck(stickyFooters, 'footer-1')">
</tr>
<tr cdk-footer-row *cdkFooterRowDef="columns; sticky: isStuck(stickyFooters, 'footer-2')">
</tr>
<tr cdk-footer-row *cdkFooterRowDef="columns; sticky: isStuck(stickyFooters, 'footer-3')">
</tr>
</table>
</div>
`,
styles: [
`
.cdk-header-cell, .cdk-cell, .cdk-footer-cell {
display: block;
width: 20px;
box-sizing: border-box;
}
`,
],
})
class StickyNativeLayoutCdkTableApp {
dataSource: FakeDataSource = new FakeDataSource();
columns = ['column-1', 'column-2', 'column-3', 'column-4', 'column-5', 'column-6'];
@ViewChild(CdkTable) table: CdkTable<TestData>;
stickyHeaders: string[] = [];
stickyFooters: string[] = [];
stickyStartColumns: string[] = [];
stickyEndColumns: string[] = [];
isStuck(list: string[], id: string) {
return list.indexOf(id) != -1;
}
}
function getElements(element: Element, query: string): HTMLElement[] {
return [].slice.call(element.querySelectorAll(query));
}
function getHeaderRows(tableElement: Element): HTMLElement[] {
return [].slice.call(tableElement.querySelectorAll('.cdk-header-row'));
}
function getFooterRows(tableElement: Element): HTMLElement[] {
return [].slice.call(tableElement.querySelectorAll('.cdk-footer-row'));
}
function getRows(tableElement: Element): HTMLElement[] {
return getElements(tableElement, '.cdk-row');
}
function getCells(row: Element): HTMLElement[] {
if (!row) {
return [];
}
let cells = getElements(row, 'cdk-cell');
if (!cells.length) {
cells = getElements(row, 'td.cdk-cell');
}
return cells;
} | the_stack |
import deepmerge from 'deepmerge';
import Color from 'color';
import { object } from './dot';
import * as designLanguage from './colors';
import codesandboxBlack from '../themes/codesandbox-black';
import codesandboxLight from '../themes/codesandbox-light.json';
const polyfillTheme = (vsCodeTheme) => {
/**
*
* In order of importance, this is the value we use:
* 1. Value from theme
* 2. or inferred value from theme
* 3. or value from codesandbox black/light
*
* The steps required to get there are -
* 1. Take vscode theme
* 2. Fill missing values based on existing values or codesandbox dark/light
* 3. Infer values that are not defined by vscode theme
*
*/
let uiColors: any = {
// initialise objects to avoid null checks later
editor: {},
button: {},
input: {},
inputOption: {},
list: {},
sideBar: {},
activityBar: {},
titleBar: {},
quickInput: {},
editorHoverWidget: {},
menuList: {},
dialog: {},
tab: {},
};
const type = vsCodeTheme.type || guessType(vsCodeTheme);
// Step 1: Initialise with vscode theme
const vsCodeColors = object(vsCodeTheme.colors || {});
uiColors = deepmerge(uiColors, vsCodeColors);
// Step 2: Fill missing values from existing values or codesandbox dark/light
const codesandboxColors: any = ['dark', 'lc'].includes(type)
? object(codesandboxBlack.colors)
: object(codesandboxLight.colors);
// 2.1 First, lets fill in core values that are used to infer other values
uiColors.foreground = uiColors.foreground || codesandboxColors.foreground;
uiColors.errorForeground =
uiColors.errorForeground || codesandboxColors.errorForeground;
uiColors.sideBar = {
background:
uiColors.sideBar.background ||
uiColors.editor.background ||
codesandboxColors.sideBar.background,
foreground:
uiColors.sideBar.foreground ||
uiColors.editor.foreground ||
codesandboxColors.sideBar.foreground,
border:
uiColors.sideBar.border ||
uiColors.editor.lineHighlightBackground ||
codesandboxColors.sideBar.border,
};
uiColors.input = {
background: uiColors.input.background || uiColors.sideBar.border,
foreground: uiColors.input.foreground || uiColors.sideBar.foreground,
border: uiColors.input.border || uiColors.sideBar.border,
placeholderForeground:
uiColors.input.placeholderForeground ||
codesandboxColors.input.placeholderForeground,
};
uiColors.quickInput = {
background: uiColors.quickInput.background || uiColors.sideBar.background,
foreground: uiColors.quickInput.foreground || uiColors.sideBar.foreground,
};
uiColors.editorHoverWidget = {
background:
uiColors.editorHoverWidget.background || uiColors.sideBar.background,
foreground:
uiColors.editorHoverWidget.foreground || uiColors.sideBar.foreground,
border: uiColors.editorHoverWidget.border || uiColors.sideBar.border,
};
uiColors.inputOption.activeBorder =
uiColors.inputOption.activeBorder || uiColors.input.placeholderForeground;
uiColors.button = {
background:
uiColors.button.background || codesandboxColors.button.background,
foreground:
uiColors.button.foreground || codesandboxColors.button.foreground,
};
// Step 3. Infer values that are not defined by vscode theme
// Step 3.1
// As all VSCode themes are built for a code editor,
// the design decisions made in them might not work well
// for an interface like ours which has other ui elements as well.
// To make sure the UI looks great, we change some of these design decisions
// made by the theme author
const decreaseContrast = type === 'dark' ? lighten : darken;
const mutedForeground = withContrast(
uiColors.input.placeholderForeground,
uiColors.sideBar.background,
type
);
if (uiColors.sideBar.border === uiColors.sideBar.background) {
uiColors.sideBar.border = decreaseContrast(
uiColors.sideBar.background,
0.25
);
}
if (uiColors.sideBar.hoverBackground === uiColors.sideBar.background) {
uiColors.sideBar.hoverBackground = decreaseContrast(
uiColors.sideBar.background,
0.25
);
}
if (uiColors.list.hoverBackground === uiColors.sideBar.background) {
if (
uiColors.list.inactiveSelectionBackground &&
uiColors.list.hoverBackground !==
uiColors.list.inactiveSelectionBackground
) {
uiColors.list.hoverBackground = uiColors.list.inactiveSelectionBackground;
} else {
// if that didnt work, its math time
uiColors.list.hoverBackground = decreaseContrast(
uiColors.sideBar.background,
0.25
);
}
}
uiColors.list.foreground = uiColors.list.foreground || mutedForeground;
uiColors.list.hoverForeground =
uiColors.list.hoverForeground || uiColors.sideBar.foreground;
uiColors.list.hoverBackground =
uiColors.list.hoverBackground || uiColors.sideBar.hoverBackground;
uiColors.titleBar.activeBackground =
uiColors.titleBar.activeBackground || uiColors.sideBar.background;
uiColors.titleBar.activeForeground =
uiColors.titleBar.activeForeground || uiColors.sideBar.foreground;
uiColors.titleBar.border =
uiColors.titleBar.border || uiColors.sideBar.border;
// Step 3.2
// On the same theme of design decisions for interfaces,
// we add a bunch of extra elements and interaction.
// To make these elements look natural with the theme,
// we infer them from the theme
// const main = Color(uiColors.editor.background).hsl();
// const shade = shades(uiColors.editor.background);
// console.log(uiColors.editor.background);
// const inverse = (num) =>
// main.isLight()
// ? darken(uiColors.editor.background, num)
// : lighten(uiColors.editor.background, num);
const addedColors = {
// shades: shade,
mutedForeground,
// browser: {
// borderWidth: '0px',
// padding: '4px',
// background: main.lightness() > 20 ? shade[900] : shade[700],
// },
// panel: {
// background: uiColors.editor.background,
// },
// panelHeader: {
// inactiveForeground: inverse(3),
// inactiveBackground: inverse(-0.25),
// hoveredBackground: inverse(2),
// hoveredForeground: inverse(-1.5),
// activeBackground: inverse(2),
// activeForeground: inverse(-1.5),
// },
activityBar: {
selectedForeground: uiColors.sideBar.foreground,
inactiveForeground: mutedForeground,
hoverBackground: uiColors.sideBar.border,
},
avatar: { border: uiColors.sideBar.border },
sideBar: { hoverBackground: uiColors.sideBar.border },
button: {
// hoverBackground: `linear-gradient(0deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2)), ${uiColors.button.background}`,
},
secondaryButton: {
background: uiColors.input.background,
foreground: uiColors.input.foreground,
// hoverBackground: `linear-gradient(0deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2)), ${uiColors.sideBar.border}`,
},
dangerButton: {
background: designLanguage.colors.red[300],
foreground: '#FFFFFF',
// hoverBackground: `linear-gradient(0deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2)), ${designLanguage.colors.red[300]}`,
},
icon: {
foreground: uiColors.foreground,
},
// switch: {
// backgroundOff: uiColors.input.background,
// backgroundOn: uiColors.button.background,
// toggle: designLanguage.colors.white,
// },
dialog: {
background: uiColors.quickInput.background,
foreground: uiColors.quickInput.foreground,
border: uiColors.sideBar.border,
},
menuList: {
background: uiColors.sideBar.background,
// foreground: uiColors.mutedForeground,
border: uiColors.sideBar.border,
hoverBackground: uiColors.sideBar.border,
hoverForeground: designLanguage.colors.white,
},
};
uiColors = deepmerge(uiColors, addedColors);
// if (uiColors.switch.backgroundOff === uiColors.sideBar.background) {
// uiColors.switch.backgroundOff = uiColors.sideBar.border;
// }
// if (uiColors.switch.toggle === uiColors.switch.backgroundOff) {
// // default is white, we make it a little darker
// uiColors.switch.toggle = designLanguage.colors.gray[200];
// }
// // ensure enough contrast from inactive state
uiColors.activityBar.selectedForeground = withContrast(
uiColors.activityBar.selectedForeground,
uiColors.activityBar.inactiveForeground,
type,
'icon'
);
const colors = {};
Object.keys(uiColors).forEach((c) => {
if (typeof uiColors[c] === 'object') {
Object.keys(uiColors[c]).forEach((d) => {
colors[`${c}.${d}`] = uiColors[c][d];
});
} else {
colors[`${c}`] = uiColors[c];
}
});
return colors;
};
export default polyfillTheme;
const guessType = (theme) => {
if (theme.name && theme.name.toLowerCase().includes('light')) return 'light';
return Color(theme.colors['editor.background']).isLight() ? 'light' : 'dark';
};
const lighten = (color, value) => Color(color).lighten(value).hex();
const shades = (color) => {
let old = [];
const hsl = Color(color).hsl();
const isLight = hsl.isLight();
for (var i = 0; i < 10.1; i = i + 0.5) {
old.push([
(isLight ? i : 10 - i) * 100,
hsl
.lightness(i * 10)
.hex()
.toString(),
]);
}
return Object.fromEntries(old);
};
const darken = (color, value) => Color(color).darken(value).hex();
const withContrast = (color, background, type, contrastType = 'text') => {
const contrastRatio = { text: 4.5, icon: 1.6 };
const contrast = contrastRatio[contrastType];
if (Color(color).contrast(Color(background)) > contrast) return color;
// can't fix that
if (color === '#FFFFFF' || color === '#000000') return color;
// recursively increase contrast
const increaseContrast = type === 'dark' ? lighten : darken;
return withContrast(
increaseContrast(color, 0.1),
background,
type,
contrastType
);
}; | the_stack |
export as namespace ejs;
/**
* Version of EJS.
*/
export const VERSION: string;
/**
* Name for detection of EJS.
*/
export const name: 'ejs';
/**
* Get the path to the included file from the parent file path and the
* specified path.
*
* @param name specified path
* @param filename parent file path
* @param isDir whether the parent file path is a directory
*/
export function resolveInclude(name: string, filename: string, isDir?: boolean): string;
/**
* Compile the given `str` of ejs into a template function.
*/
export function compile(template: string, opts: Options & { async: true; client?: false }): AsyncTemplateFunction;
export function compile(template: string, opts: Options & { async: true; client: true }): AsyncClientFunction;
export function compile(template: string, opts?: Options & { async?: false; client?: false }): TemplateFunction;
export function compile(template: string, opts?: Options & { async?: false; client: true }): ClientFunction;
export function compile(template: string, opts?: Options): TemplateFunction | AsyncTemplateFunction;
/**
* Render the given `template` of ejs.
*
* If you would like to include options but not data, you need to explicitly
* call this function with `data` being an empty object or `null`.
*/
export function render(template: string, data?: Data, opts?: Options & { async: false }): string;
export function render(template: string, data: Data | undefined, opts: Options & { async: true }): Promise<string>;
export function render(template: string, data: Data | undefined, opts: Options & { async?: never }): string;
export function render(template: string, data?: Data, opts?: Options): string | Promise<string>;
/**
* Callback for receiving data from `renderFile`.
*
* @param err error, if any resulted from the rendering process
* @param str output string, is `undefined` if there is an error
*/
export type RenderFileCallback<T> = (err: Error | null, str: string) => T;
/**
* Render an EJS file at the given `path` and callback `cb(err, str)`.
*
* If you would like to include options but not data, you need to explicitly
* call this function with `data` being an empty object or `null`.
*/
export function renderFile<T>(path: string, cb: RenderFileCallback<T>): T;
export function renderFile<T>(path: string, data: Data, cb: RenderFileCallback<T>): T;
export function renderFile<T>(path: string, data: Data, opts: Options, cb: RenderFileCallback<T>): T;
export function renderFile(path: string, data?: Data, opts?: Options): Promise<string>;
/**
* Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
*/
export function clearCache(): void;
/**
* EJS template function cache. This can be a LRU object from lru-cache
* NPM module. By default, it is `utils.cache`, a simple in-process
* cache that grows continuously.
*/
export let cache: Cache;
/**
* Custom file loader. Useful for template preprocessing or restricting access
* to a certain part of the filesystem.
*
* @param path the path of the file to be read
* @return the contents of the file as a string or object that implements the toString() method
*
* @default fs.readFileSync
*/
export type fileLoader = (path: string) => string | { toString(): string };
export let fileLoader: fileLoader;
/**
* Name of the object containing the locals.
*
* This variable is overridden by {@link Options}`.localsName` if it is not
* `undefined`.
*
* @default 'locals'
*/
export let localsName: string;
/**
* The opening delimiter for all statements. This allows you to clearly delinate
* the difference between template code and existing delimiters. (It is recommended
* to synchronize this with the closeDelimiter property.)
*
* @default '<'
*/
export let openDelimiter: string;
/**
* The closing delimiter for all statements. This allows to to clearly delinate
* the difference between template code and existing delimiters. (It is recommended
* to synchronize this with the openDelimiter property.)
*
* @default '>'
*/
export let closeDelimiter: string;
/**
* The delimiter used in template compilation.
*
* @default '%'
*/
export let delimiter: string | undefined;
/**
* Promise implementation -- defaults to the native implementation if available
* This is mostly just for testability
*
* @default Promise
*/
export let promiseImpl: PromiseConstructorLike | undefined;
/**
* Escape characters reserved in XML.
*
* This is simply an export of `utils.escapeXML`.
*
* If `markup` is `undefined` or `null`, the empty string is returned.
*/
export function escapeXML(markup?: any): string;
export class Template {
/**
* The EJS template source text.
*/
readonly templateText: string;
/**
* The compiled JavaScript function source, or the empty string
* if the template hasn't been compiled yet.
*/
readonly source: string;
constructor(text: string, opts?: Options);
/**
* Compiles the EJS template.
*/
compile(): TemplateFunction | AsyncTemplateFunction | ClientFunction | AsyncClientFunction;
}
export namespace Template {
enum modes {
EVAL = 'eval',
ESCAPED = 'escaped',
RAW = 'raw',
COMMENT = 'comment',
LITERAL = 'literal',
}
}
export interface Data {
[name: string]: any;
}
/**
* This type of function is returned from `compile`, when
* `Options.client` is false.
*
* @param data an object of data to be passed into the template.
* @return Return type depends on `Options.async`.
*/
export type TemplateFunction = (data?: Data) => string;
/**
* This type of function is returned from `compile`, when
* `Options.client` is false.
*
* @param data an object of data to be passed into the template.
* @return Return type depends on `Options.async`.
*/
export type AsyncTemplateFunction = (data?: Data) => Promise<string>;
/**
* This type of function is returned from `compile`, when
* `Options.client` is true.
*
*
* This is also used internally to generate a `TemplateFunction`.
*
* @param locals an object of data to be passed into the template.
* The name of this variable is adjustable through `localsName`.
*
* @param escape callback used to escape variables
* @param include callback used to include files at runtime with `include()`
* @param rethrow callback used to handle and rethrow errors
*
* @return Return type depends on `Options.async`.
*/
export type ClientFunction = (
locals?: Data,
escape?: EscapeCallback,
include?: IncludeCallback,
rethrow?: RethrowCallback,
) => string;
/**
* This type of function is returned from `compile`, when
* `Options.client` is true.
*
*
* This is also used internally to generate a `TemplateFunction`.
*
* @param locals an object of data to be passed into the template.
* The name of this variable is adjustable through `localsName`.
*
* @param escape callback used to escape variables
* @param include callback used to include files at runtime with `include()`
* @param rethrow callback used to handle and rethrow errors
*
* @return Return type depends on `Options.async`.
*/
export type AsyncClientFunction = (
locals?: Data,
escape?: EscapeCallback,
include?: IncludeCallback,
rethrow?: RethrowCallback,
) => Promise<string>;
/**
* Escapes a string using HTML/XML escaping rules.
*
* Returns the empty string for `null` or `undefined`.
*
* @param markup Input string
* @return Escaped string
*/
export type EscapeCallback = (markup?: any) => string;
/**
* This type of callback is used when `Options.compileDebug`
* is `true`, and an error in the template is thrown.
*
* By default it is used to rethrow an error in a better-formatted way.
*
* @param err Error object
* @param str full EJS source
* @param filename file name of the EJS source
* @param lineno line number of the error
*/
export type RethrowCallback = (
err: Error,
str: string,
filename: string | null | undefined,
lineno: number,
esc: EscapeCallback,
) => never;
/**
* The callback called by `ClientFunction` to include files at runtime with `include()`
*
* @param path Path to be included
* @param data Data passed to the template
* @return Contents of the file requested
*/
export type IncludeCallback = (path: string, data?: Data) => string;
export interface Options {
/**
* Log the generated JavaScript source for the EJS template to the console.
*
* @default false
*/
debug?: boolean;
/**
* Include additional runtime debugging information in generated template
* functions.
*
* @default true
*/
compileDebug?: boolean;
/**
* Whether or not to use `with () {}` construct in the generated template
* functions. If set to `false`, data is still accessible through the object
* whose name is specified by `ejs.localsName` (defaults to `locals`).
*
* @default true
*/
_with?: boolean;
/**
* Whether to run in strict mode or not.
* Enforces `_with=false`.
*
* @default false
*/
strict?: boolean;
/**
* An array of local variables that are always destructured from `localsName`,
* available even in strict mode.
*
* @default []
*/
destructuredLocals?: string[];
/**
* Remove all safe-to-remove whitespace, including leading and trailing
* whitespace. It also enables a safer version of `-%>` line slurping for all
* scriptlet tags (it does not strip new lines of tags in the middle of a
* line).
*
* @default false
*/
rmWhitespace?: boolean;
/**
* Whether or not to compile a `ClientFunction` that can be rendered
* in the browser without depending on ejs.js. Otherwise, a `TemplateFunction`
* will be compiled.
*
* @default false
*/
client?: boolean;
/**
* The escaping function used with `<%=` construct. It is used in rendering
* and is `.toString()`ed in the generation of client functions.
*
* @default ejs.escapeXML
*/
escape?: EscapeCallback;
/**
* The filename of the template. Required for inclusion and caching unless
* you are using `renderFile`. Also used for error reporting.
*
* @default undefined
*/
filename?: string;
/**
* The path to the project root. When this is set, absolute paths for includes
* (/filename.ejs) will be relative to the project root.
*
* @default undefined
*/
root?: string;
/**
* The opening delimiter for all statements. This allows you to clearly delinate
* the difference between template code and existing delimiters. (It is recommended
* to synchronize this with the closeDelimiter property.)
*
* @default ejs.openDelimiter
*/
openDelimiter?: string;
/**
* The closing delimiter for all statements. This allows to to clearly delinate
* the difference between template code and existing delimiters. (It is recommended
* to synchronize this with the openDelimiter property.)
*
* @default ejs.closeDelimiter
*/
closeDelimiter?: string;
/**
* Character to use with angle brackets for open/close
* @default '%'
*/
delimiter?: string;
/**
* Whether or not to enable caching of template functions. Beware that
* the options of compilation are not checked as being the same, so
* special handling is required if, for example, you want to cache client
* and regular functions of the same file.
*
* Requires `filename` to be set. Only works with rendering function.
*
* @default false
*/
cache?: boolean;
/**
* The Object to which `this` is set during rendering.
*
* @default this
*/
context?: any;
/**
* Whether or not to create an async function instead of a regular function.
* This requires language support.
*
* @default false
*/
async?: boolean;
/**
* Make sure to set this to 'false' in order to skip UglifyJS parsing,
* when using ES6 features (`const`, etc) as UglifyJS doesn't understand them.
* @default true
*/
beautify?: boolean;
/**
* Name to use for the object storing local variables when not using `with` or destructuring.
*
* @default ejs.localsName
*/
localsName?: string;
/** Set to a string (e.g., 'echo' or 'print') for a function to print output inside scriptlet tags. */
outputFunctionName?: string;
/**
* An array of paths to use when resolving includes with relative paths
*/
views?: string[];
}
export interface Cache {
/**
* Cache the intermediate JavaScript function for a template.
*
* @param key key for caching
* @param val cached function
*/
set(key: string, val: TemplateFunction): void;
/**
* Get the cached intermediate JavaScript function for a template.
*
* @param key key for caching
*/
get(key: string): TemplateFunction | undefined;
/**
* Clear the entire cache.
*/
reset(): void;
} | the_stack |
import {ENGINE} from '../engine';
import {Tensor, Tensor3D, Tensor4D, Tensor5D} from '../tensor';
import {convertToTensor} from '../tensor_util_env';
import {TensorLike} from '../types';
import * as util from '../util';
import {batchToSpaceND, spaceToBatchND} from './array_ops';
import * as conv_util from './conv_util';
import {op} from './operation';
/**
* Computes the 2D max pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
function maxPoolImpl_<T extends Tensor3D|Tensor4D>(
x: T|TensorLike, filterSize: [number, number]|number,
strides: [number, number]|number, dilations: [number, number]|number,
pad: 'valid'|'same'|number, dimRoundingMode?: 'floor'|'round'|'ceil'): T {
const $x = convertToTensor(x, 'x', 'maxPool');
let x4D = $x as Tensor4D;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = $x.as4D(1, $x.shape[0], $x.shape[1], $x.shape[2]);
}
if (dilations == null) {
dilations = [1, 1];
}
util.assert(
x4D.rank === 4,
() => `Error in maxPool: input must be rank 4 but got rank ${x4D.rank}.`);
util.assert(
conv_util.eitherStridesOrDilationsAreOne(strides, dilations),
() => 'Error in maxPool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
if (dimRoundingMode != null) {
util.assert(
util.isInt(pad as number),
() => `Error in maxPool: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const convInfo = conv_util.computePool2DInfo(
x4D.shape, filterSize, strides, dilations, pad, dimRoundingMode);
const grad = (dy: Tensor4D, saved: Tensor[]) => {
const [x4D, y] = saved;
return {
x: () => maxPoolBackprop(
dy, x4D as Tensor4D, y as Tensor4D, filterSize, strides, dilations,
pad)
};
};
const res = ENGINE.runKernel((backend, save) => {
const y = backend.maxPool(x4D, convInfo);
save([x4D, y]);
return y;
}, {x: x4D}, grad);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as T;
}
return res as T;
}
/**
* Computes the 2D max pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function maxPool_<T extends Tensor3D|Tensor4D>(
x: T|TensorLike, filterSize: [number, number]|number,
strides: [number, number]|number, pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T {
return maxPoolImpl_(x, filterSize, strides, 1, pad, dimRoundingMode);
}
/**
* Computes the 2D average pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
function avgPoolImpl_<T extends Tensor3D|Tensor4D>(
x: T|TensorLike, filterSize: [number, number]|number,
strides: [number, number]|number, dilations: [number, number]|number,
pad: 'valid'|'same'|number, dimRoundingMode?: 'floor'|'round'|'ceil'): T {
const $x = convertToTensor(x, 'x', 'avgPool', 'float32');
if (dilations == null) {
dilations = [1, 1];
}
util.assert(
conv_util.eitherStridesOrDilationsAreOne(strides, dilations),
() => 'Error in avgPool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
let x4D = $x as Tensor4D;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = $x.as4D(1, $x.shape[0], $x.shape[1], $x.shape[2]);
}
util.assert(
x4D.rank === 4,
() => `Error in avgPool: x must be rank 4 but got rank ${x4D.rank}.`);
if (dimRoundingMode != null) {
util.assert(
util.isInt(pad as number),
() => `Error in avgPool: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const convInfo = conv_util.computePool2DInfo(
x4D.shape, filterSize, strides, dilations, pad, dimRoundingMode);
const grad = (dy: Tensor4D) => {
return {
x: () => avgPoolBackprop(dy, x4D, filterSize, strides, dilations, pad)
};
};
let res = ENGINE.runKernel(
backend => backend.avgPool(x4D, convInfo), {x: x4D}, grad);
res = res.cast($x.dtype);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as T;
}
return res as T;
}
/**
* Computes the 2D average pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function avgPool_<T extends Tensor3D|Tensor4D>(
x: T|TensorLike, filterSize: [number, number]|number,
strides: [number, number]|number, pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T {
return avgPoolImpl_(x, filterSize, strides, 1, pad, dimRoundingMode);
}
/**
* Performs an N-D pooling operation
*
* @param input The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param windowShape The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param poolingType The type of pooling, either 'max' or 'avg'.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilationRate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function pool_<T extends Tensor3D|Tensor4D>(
input: T|TensorLike, windowShape: [number, number]|number,
poolingType: 'avg'|'max', pad: 'valid'|'same'|number,
dilations?: [number, number]|number, strides?: [number, number]|number) {
if (dilations == null) {
dilations = [1, 1];
}
if (strides == null) {
strides = 1;
}
if (pad === 0) {
pad = 'valid';
}
const $x = convertToTensor(input, 'x', 'maxPool');
let x4D = $x as Tensor4D;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = $x.as4D(1, $x.shape[0], $x.shape[1], $x.shape[2]);
}
util.assert(
conv_util.eitherStridesOrDilationsAreOne(strides, dilations),
() => 'Error in pool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
const convInfo = conv_util.computePool2DInfo(
x4D.shape, windowShape, strides, dilations, pad);
const dilation: [number, number] =
[convInfo.dilationHeight, convInfo.dilationWidth];
// The following implementation does batchToSpace(pool(spaceToBatch(x)))
// whenever dilation > 1 since the TF kernels do not support dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L1037
let basePadding: number[][];
if (pad === 'same') {
basePadding = withSpaceToBatchBasePaddings(
[convInfo.filterHeight, convInfo.filterWidth], dilation);
} else {
basePadding = [[0, 0], [0, 0]];
}
const isDilationOne = dilation[0] === 1 && dilation[1] === 1;
const [adjustedPadding, adjustedCrops] = requiredSpaceToBatchPaddings(
[convInfo.inHeight, convInfo.inWidth], dilation, basePadding);
const convertedPad = isDilationOne ? pad : 'valid';
const convertedX =
isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);
const forwardOp = poolingType === 'avg' ?
() => avgPoolImpl_(
convertedX, windowShape, strides, 1 /* dilation */, convertedPad) :
() => maxPoolImpl_(
convertedX, windowShape, strides, 1 /* dilation */, convertedPad);
const y = forwardOp();
const res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as T;
}
return res as T;
}
/**
* Computes the backprop of a 2D max pool.
*
* @param dy The dy error, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param input The original input image, of rank 4, of shape
* [batchSize, height, width, channels].
* @param output The original output image, of rank 4, of shape
* [batchSize, outHeight, outWidth, channels].
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. The
* rounding mode used when computing output dimensions if pad is a
* number. If none is provided, it will not round and error if the output
* is of fractional size.
*/
function maxPoolBackprop(
dy: Tensor4D|TensorLike, input: Tensor4D|TensorLike,
output: Tensor4D|TensorLike, filterSize: [number, number]|number,
strides: [number, number]|number, dilations: [number, number]|number,
pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {
const $dy = convertToTensor(dy, 'dy', 'maxPoolBackprop');
const $input = convertToTensor(input, 'input', 'maxPoolBackprop');
const $output = convertToTensor(output, 'output', 'maxPoolBackprop');
util.assert(
$input.rank === $dy.rank,
() => `Rank of input (${$input.rank}) does not match rank of dy ` +
`(${$dy.rank})`);
if (dilations == null) {
dilations = [1, 1];
}
util.assert(
conv_util.eitherStridesOrDilationsAreOne(strides, dilations),
() =>
'Error in maxPoolBackProp: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
util.assert(
$dy.rank === 4,
() => `Error in maxPoolBackprop: dy must be rank 4 but got rank ` +
`${$dy.rank}.`);
util.assert(
$input.rank === 4,
() => `Error in maxPoolBackprop: input must be rank 4 but got rank ` +
`${$input.rank}.`);
if (dimRoundingMode != null) {
util.assert(
util.isInt(pad as number),
() => `Error in maxPoolBackprop: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const convInfo = conv_util.computePool2DInfo(
$input.shape, filterSize, strides, dilations, pad, dimRoundingMode);
const res = ENGINE.runKernel(
backend => backend.maxPoolBackprop($dy, $input, $output, convInfo),
{$dy, $input});
return res;
}
/**
* Computes the backprop of an 2D avg pool.
*
* @param dy The dy error, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param input The input image, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
*/
function avgPoolBackprop<T extends Tensor3D|Tensor4D>(
dy: T|TensorLike, input: T|TensorLike, filterSize: [number, number]|number,
strides: [number, number]|number, dilations: [number, number]|number,
pad: 'valid'|'same'|number): T {
const $dy = convertToTensor(dy, 'dy', 'avgPoolBackprop');
const $input = convertToTensor(input, 'input', 'avgPoolBackprop');
util.assert(
$input.rank === $dy.rank,
() => `Rank of input (${$input.rank}) does not match rank of dy (${
$dy.rank})`);
if (dilations == null) {
dilations = [1, 1];
}
util.assert(
conv_util.eitherStridesOrDilationsAreOne(strides, dilations),
() =>
'Error in avgPoolBackprop: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
let input4D = $input as Tensor4D;
let dy4D = $dy as Tensor4D;
let reshapedTo4D = false;
if ($input.rank === 3) {
reshapedTo4D = true;
input4D = $input.as4D(1, $input.shape[0], $input.shape[1], $input.shape[2]);
dy4D = $dy.as4D(1, $dy.shape[0], $dy.shape[1], $dy.shape[2]);
}
util.assert(
dy4D.rank === 4,
() => `Error in avgPoolBackprop: dy must be rank 4 but got rank ` +
`${dy4D.rank}.`);
util.assert(
input4D.rank === 4,
() => `Error in avgPoolBackprop: input must be rank 4 but got rank ` +
`${input4D.rank}.`);
const convInfo = conv_util.computePool2DInfo(
input4D.shape, filterSize, strides, dilations, pad);
const res = ENGINE.runKernel(
backend => backend.avgPoolBackprop(dy4D, input4D, convInfo),
{dy4D, input4D});
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]) as T;
}
return res as T;
}
// Helper function to compute crops and paddings for pool with dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/array_ops.py#L2184
function requiredSpaceToBatchPaddings(
inputShape: [number, number], blockShape: [number, number],
basePadding: number[][]) {
const padStart = basePadding.map(b => b[0]);
const origPadEnd = basePadding.map(b => b[1]);
const fullInputShape = inputShape.concat(padStart, origPadEnd);
const padEndExtra = blockShape.map((b, i) => (b - fullInputShape[i] % b) % b);
const padEnd = origPadEnd.map((s, i) => s + padEndExtra[i]);
const paddings = blockShape.map((_, i) => [padStart[i], padEnd[i]]);
const crops = blockShape.map((_, i) => [0, padEndExtra[i]]);
return [paddings, crops];
}
// Helper function to compute base paddings for pool with dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L524
function withSpaceToBatchBasePaddings(
filterShape: [number, number], dilation: [number, number]) {
// Spatial dimensions of the filters and the upsampled filters in which we
// introduce (rate - 1) zeros between consecutive filter values.
const dilatedFilterShape = filterShape.map((s, i) => {
return s + (s - 1) * (dilation[i] - 1);
});
const padExtraShape = dilatedFilterShape.map(s => s - 1);
// When padding is odd, we pad more at end, following the same
// convention as conv2d.
const padExtraStart = padExtraShape.map(s => Math.floor(s / 2));
const padExtraEnd = padExtraShape.map((s, i) => s - padExtraStart[i]);
return padExtraShape.map((_, i) => {
return [padExtraStart[i], padExtraEnd[i]];
});
}
/**
* Computes the 3D average pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.avgPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param dilations The dilation rates:
* `[dilationDepth, dilationHeight, dilationWidth]`
* in which we sample input values across the depth, height and width
* dimensions in dilated pooling.
* Defaults to `[1, 1, 1]`. If `dilations` is a single number,
* then `dilationDepth == dilationHeight == dilationWidth`.
* If it is greater than 1, then all values of `strides` must be 1.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function avgPool3d_<T extends Tensor4D|Tensor5D>(
x: T|TensorLike,
filterSize: [number, number, number]|number,
strides: [number, number, number]|number,
pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil',
dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC',
dilations?: [number, number, number]|number,
): T {
const $x = convertToTensor(x, 'x', 'avgPool3d', 'float32');
let x5D = $x as Tensor5D;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = $x.as5D(1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]);
}
if (dilations == null) {
dilations = [1, 1, 1];
}
util.assert(
x5D.rank === 5,
() => `Error in avgPool3d: x must be rank 5 but got rank ${x5D.rank}.`);
util.assert(
dataFormat === 'NDHWC',
() => `Error in avgPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
util.assert(
conv_util.eitherStridesOrDilationsAreOne(strides, dilations),
() => 'Error in avgPool3d: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
if (dimRoundingMode != null) {
util.assert(
util.isInt(pad as number),
() => `Error in avgPool3d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const convInfo = conv_util.computePool3DInfo(
x5D.shape, filterSize, strides, dilations, pad, dimRoundingMode,
dataFormat);
const grad = (dy: Tensor5D) => {
return {
x: () => avgPool3dBackprop(
dy, x5D, filterSize, strides, dilations, pad, dimRoundingMode)
};
};
let res = ENGINE.runKernel(
backend => backend.avgPool3d(x5D, convInfo), {x: x5D}, grad);
res = res.cast(x5D.dtype);
if (reshapedTo5D) {
return res.as4D(res.shape[1], res.shape[2], res.shape[3], res.shape[4]) as
T;
}
return res as T;
}
/**
* Computes the backprop of a 3d avg pool.
*
* @param dy The dy error, of rank 5 of shape
* [batchSize, depth, height, width, channels].
* assumed.
* @param input The original input image, of rank 5 or rank4 of shape
* [batchSize, depth, height, width, channels].
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dilations The dilation rates:
* `[dilationDepth, dilationHeight, dilationWidth]`
* in which we sample input values across the depth, height and width
* dimensions in dilated pooling.
* Defaults to `[1, 1, 1]`. If `dilations` is a single number,
* then `dilationDepth == dilationHeight == dilationWidth`.
* If it is greater than 1, then all values of `strides` must be 1.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. The
* rounding mode used when computing output dimensions if pad is a
* number. If none is provided, it will not round and error if the output
* is of fractional size.
*/
function avgPool3dBackprop<T extends Tensor4D|Tensor5D>(
dy: T|TensorLike, input: T|TensorLike,
filterSize: [number, number, number]|number,
strides: [number, number, number]|number,
dilations: [number, number, number]|number, pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T {
const $dy = convertToTensor(dy, 'dy', 'avgPool3dBackprop');
const $input = convertToTensor(input, 'input', 'avgPool3dBackprop');
let dy5D = $dy as Tensor5D;
let input5D = $input as Tensor5D;
let reshapedTo5D = false;
if ($input.rank === 4) {
reshapedTo5D = true;
dy5D = $dy.as5D(1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]);
input5D = $input.as5D(
1, $input.shape[0], $input.shape[1], $input.shape[2], $input.shape[3]);
}
util.assert(
dy5D.rank === 5,
() => `Error in avgPool3dBackprop: dy must be rank 5 but got rank ` +
`${dy5D.rank}.`);
util.assert(
input5D.rank === 5,
() => `Error in avgPool3dBackprop: input must be rank 5 but got rank ` +
`${input5D.rank}.`);
if (dilations == null) {
dilations = [1, 1, 1];
}
util.assert(
conv_util.eitherStridesOrDilationsAreOne(strides, dilations),
() => 'Error in avgPool3dBackprop: Either strides or dilations ' +
`must be 1. Got strides ${strides} and dilations '${dilations}'`);
if (dimRoundingMode != null) {
util.assert(
util.isInt(pad as number),
() => `Error in maxPool3dBackprop: pad must be an integer when ` +
`using, dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const convInfo = conv_util.computePool3DInfo(
input5D.shape, filterSize, strides, dilations, pad, dimRoundingMode);
const res = ENGINE.runKernel(
backend => backend.avgPool3dBackprop(dy5D, input5D, convInfo),
{dy5D, input5D});
if (reshapedTo5D) {
return res.as4D(res.shape[1], res.shape[2], res.shape[3], res.shape[4]) as
T;
}
return res as T;
}
/**
* Computes the 3D max pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.maxPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode The rounding mode used when computing output
* dimensions if pad is a number. If none is provided, it will not round
* and error if the output is of fractional size.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param dilations The dilation rates:
* `[dilationDepth, dilationHeight, dilationWidth]`
* in which we sample input values across the depth, height and width
* dimensions in dilated pooling.
* Defaults to `[1, 1, 1]`. If `dilations` is a single number,
* then `dilationDepth == dilationHeight == dilationWidth`.
* If it is greater than 1, then all values of `strides` must be 1.
*/
/** @doc {heading: 'Operations', subheading: 'Convolution'} */
function maxPool3d_<T extends Tensor4D|Tensor5D>(
x: T|TensorLike, filterSize: [number, number, number]|number,
strides: [number, number, number]|number, pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil',
dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC',
dilations?: [number, number, number]|number): T {
const $x = convertToTensor(x, 'x', 'maxPool3d');
let x5D = $x as Tensor5D;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = $x.as5D(1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]);
}
if (dilations == null) {
dilations = [1, 1, 1];
}
util.assert(
x5D.rank === 5,
() => `Error in maxPool3d: x must be rank 5 but got rank ${x5D.rank}.`);
util.assert(
dataFormat === 'NDHWC',
() => `Error in maxPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
util.assert(
conv_util.eitherStridesOrDilationsAreOne(strides, dilations),
() => 'Error in maxPool3d: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
if (dimRoundingMode != null) {
util.assert(
util.isInt(pad as number),
() => `Error in maxPool3d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const convInfo = conv_util.computePool3DInfo(
x5D.shape, filterSize, strides, dilations, pad, dimRoundingMode,
dataFormat);
const grad = (dy: Tensor5D, saved: Tensor[]) => {
const [x5D, y] = saved;
return {
x: () => maxPool3dBackprop(
dy, x5D as Tensor5D, y as Tensor5D, filterSize, strides, dilations,
pad, dimRoundingMode)
};
};
const res = ENGINE.runKernel((backend, save) => {
const y = backend.maxPool3d(x5D, convInfo);
save([x5D, y]);
return y;
}, {x: x5D}, grad);
if (reshapedTo5D) {
return res.as4D(res.shape[1], res.shape[2], res.shape[3], res.shape[4]) as
T;
}
return res as T;
}
/**
* Computes the backprop of a 3d max pool.
*
* @param dy The dy error, of rank 5 of shape
* [batchSize, depth, height, width, channels].
* assumed.
* @param input The original input image, of rank 5 or rank 4 of shape
* [batchSize, depth, height, width, channels].
* @param output The original output image, of rank 5 of shape
* [batchSize, outDepth, outHeight, outWidth, channels].
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dilations The dilation rates:
* `[dilationDepth, dilationHeight, dilationWidth]`
* in which we sample input values across the depth, height and width
* dimensions in dilated pooling.
* Defaults to `[1, 1, 1]`. If `dilations` is a single number,
* then `dilationDepth == dilationHeight == dilationWidth`.
* If it is greater than 1, then all values of `strides` must be 1.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. The
* rounding mode used when computing output dimensions if pad is a
* number. If none is provided, it will not round and error if the output
* is of fractional size.
*/
function maxPool3dBackprop<T extends Tensor4D|Tensor5D>(
dy: T|TensorLike, input: T|TensorLike, output: T|TensorLike,
filterSize: [number, number, number]|number,
strides: [number, number, number]|number,
dilations: [number, number, number]|number, pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T {
const $dy = convertToTensor(dy, 'dy', 'maxPool3dBackprop');
const $input = convertToTensor(input, 'input', 'maxPool3dBackprop');
const $output = convertToTensor(output, 'output', 'maxPool3dBackprop');
let dy5D = $dy as Tensor5D;
let input5D = $input as Tensor5D;
let output5D = $output as Tensor5D;
let reshapedTo5D = false;
if ($input.rank === 4) {
reshapedTo5D = true;
dy5D = $dy.as5D(1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]);
input5D = $input.as5D(
1, $input.shape[0], $input.shape[1], $input.shape[2], $input.shape[3]);
output5D = $output.as5D(
1, $output.shape[0], $output.shape[1], $output.shape[2],
$output.shape[3]);
}
util.assert(
dy5D.rank === 5,
() => `Error in maxPool3dBackprop: dy must be rank 5 but got rank ` +
`${dy5D.rank}.`);
util.assert(
input5D.rank === 5,
() => `Error in maxPool3dBackprop: input must be rank 5 but got rank ` +
`${input5D.rank}.`);
util.assert(
output5D.rank === 5,
() => `Error in maxPool3dBackprop: output must be rank 5 but got rank ` +
`${output5D.rank}.`);
if (dilations == null) {
dilations = [1, 1, 1];
}
util.assert(
conv_util.eitherStridesOrDilationsAreOne(strides, dilations),
() => 'Error in maxPool3dBackprop: Either strides or dilations ' +
`must be 1. Got strides ${strides} and dilations '${dilations}'`);
if (dimRoundingMode != null) {
util.assert(
util.isInt(pad as number),
() => `Error in maxPool3dBackprop: pad must be an integer when ` +
`using, dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const convInfo = conv_util.computePool3DInfo(
input5D.shape, filterSize, strides, dilations, pad, dimRoundingMode);
const res = ENGINE.runKernel(
backend => backend.maxPool3dBackprop(dy5D, input5D, output5D, convInfo),
{dy5D, input5D});
if (reshapedTo5D) {
return res.as4D(res.shape[1], res.shape[2], res.shape[3], res.shape[4]) as
T;
}
return res as T;
}
export const maxPool = op({maxPool_});
export const avgPool = op({avgPool_});
export const pool = op({pool_});
export const maxPool3d = op({maxPool3d_});
export const avgPool3d = op({avgPool3d_}); | the_stack |
import { inspect } from '../jsutils/inspect';
import { devAssert } from '../jsutils/devAssert';
import { keyValMap } from '../jsutils/keyValMap';
import { isObjectLike } from '../jsutils/isObjectLike';
import { parseValue } from '../language/parser';
import type { GraphQLSchemaValidationOptions } from '../type/schema';
import type {
GraphQLType,
GraphQLNamedType,
GraphQLFieldConfig,
GraphQLFieldConfigMap,
} from '../type/definition';
import { GraphQLSchema } from '../type/schema';
import { GraphQLDirective } from '../type/directives';
import { specifiedScalarTypes } from '../type/scalars';
import { introspectionTypes, TypeKind } from '../type/introspection';
import {
isInputType,
isOutputType,
GraphQLList,
GraphQLNonNull,
GraphQLScalarType,
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLUnionType,
GraphQLEnumType,
GraphQLInputObjectType,
assertNullableType,
assertObjectType,
assertInterfaceType,
} from '../type/definition';
import type {
IntrospectionQuery,
IntrospectionDirective,
IntrospectionField,
IntrospectionInputValue,
IntrospectionType,
IntrospectionScalarType,
IntrospectionObjectType,
IntrospectionInterfaceType,
IntrospectionUnionType,
IntrospectionEnumType,
IntrospectionInputObjectType,
IntrospectionTypeRef,
IntrospectionNamedTypeRef,
} from './getIntrospectionQuery';
import { valueFromAST } from './valueFromAST';
/**
* Build a GraphQLSchema for use by client tools.
*
* Given the result of a client running the introspection query, creates and
* returns a GraphQLSchema instance which can be then used with all graphql-js
* tools, but cannot be used to execute a query, as introspection does not
* represent the "resolver", "parse" or "serialize" functions or any other
* server-internal mechanisms.
*
* This function expects a complete introspection result. Don't forget to check
* the "errors" field of a server response before calling this function.
*/
export function buildClientSchema(
introspection: IntrospectionQuery,
options?: GraphQLSchemaValidationOptions,
): GraphQLSchema {
devAssert(
isObjectLike(introspection) && isObjectLike(introspection.__schema),
`Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${inspect(
introspection,
)}.`,
);
// Get the schema from the introspection result.
const schemaIntrospection = introspection.__schema;
// Iterate through all types, getting the type definition for each.
const typeMap = keyValMap(
schemaIntrospection.types,
(typeIntrospection) => typeIntrospection.name,
(typeIntrospection) => buildType(typeIntrospection),
);
// Include standard types only if they are used.
for (const stdType of [...specifiedScalarTypes, ...introspectionTypes]) {
if (typeMap[stdType.name]) {
typeMap[stdType.name] = stdType;
}
}
// Get the root Query, Mutation, and Subscription types.
const queryType = schemaIntrospection.queryType
? getObjectType(schemaIntrospection.queryType)
: null;
const mutationType = schemaIntrospection.mutationType
? getObjectType(schemaIntrospection.mutationType)
: null;
const subscriptionType = schemaIntrospection.subscriptionType
? getObjectType(schemaIntrospection.subscriptionType)
: null;
// Get the directives supported by Introspection, assuming empty-set if
// directives were not queried for.
const directives = schemaIntrospection.directives
? schemaIntrospection.directives.map(buildDirective)
: [];
// Then produce and return a Schema with these types.
return new GraphQLSchema({
description: schemaIntrospection.description,
query: queryType,
mutation: mutationType,
subscription: subscriptionType,
types: Object.values(typeMap),
directives,
assumeValid: options?.assumeValid,
});
// Given a type reference in introspection, return the GraphQLType instance.
// preferring cached instances before building new instances.
function getType(typeRef: IntrospectionTypeRef): GraphQLType {
if (typeRef.kind === TypeKind.LIST) {
const itemRef = typeRef.ofType;
if (!itemRef) {
throw new Error('Decorated type deeper than introspection query.');
}
return new GraphQLList(getType(itemRef));
}
if (typeRef.kind === TypeKind.NON_NULL) {
const nullableRef = typeRef.ofType;
if (!nullableRef) {
throw new Error('Decorated type deeper than introspection query.');
}
const nullableType = getType(nullableRef);
return new GraphQLNonNull(assertNullableType(nullableType));
}
return getNamedType(typeRef);
}
function getNamedType(typeRef: IntrospectionNamedTypeRef): GraphQLNamedType {
const typeName = typeRef.name;
if (!typeName) {
throw new Error(`Unknown type reference: ${inspect(typeRef)}.`);
}
const type = typeMap[typeName];
if (!type) {
throw new Error(
`Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`,
);
}
return type;
}
function getObjectType(
typeRef: IntrospectionNamedTypeRef<IntrospectionObjectType>,
): GraphQLObjectType {
return assertObjectType(getNamedType(typeRef));
}
function getInterfaceType(
typeRef: IntrospectionNamedTypeRef<IntrospectionInterfaceType>,
): GraphQLInterfaceType {
return assertInterfaceType(getNamedType(typeRef));
}
// Given a type's introspection result, construct the correct
// GraphQLType instance.
function buildType(type: IntrospectionType): GraphQLNamedType {
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain
if (type != null && type.name != null && type.kind != null) {
switch (type.kind) {
case TypeKind.SCALAR:
return buildScalarDef(type);
case TypeKind.OBJECT:
return buildObjectDef(type);
case TypeKind.INTERFACE:
return buildInterfaceDef(type);
case TypeKind.UNION:
return buildUnionDef(type);
case TypeKind.ENUM:
return buildEnumDef(type);
case TypeKind.INPUT_OBJECT:
return buildInputObjectDef(type);
}
}
const typeStr = inspect(type);
throw new Error(
`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`,
);
}
function buildScalarDef(
scalarIntrospection: IntrospectionScalarType,
): GraphQLScalarType {
return new GraphQLScalarType({
name: scalarIntrospection.name,
description: scalarIntrospection.description,
specifiedByURL: scalarIntrospection.specifiedByURL,
});
}
function buildImplementationsList(
implementingIntrospection:
| IntrospectionObjectType
| IntrospectionInterfaceType,
): Array<GraphQLInterfaceType> {
// TODO: Temporary workaround until GraphQL ecosystem will fully support
// 'interfaces' on interface types.
if (
implementingIntrospection.interfaces === null &&
implementingIntrospection.kind === TypeKind.INTERFACE
) {
return [];
}
if (!implementingIntrospection.interfaces) {
const implementingIntrospectionStr = inspect(implementingIntrospection);
throw new Error(
`Introspection result missing interfaces: ${implementingIntrospectionStr}.`,
);
}
return implementingIntrospection.interfaces.map(getInterfaceType);
}
function buildObjectDef(
objectIntrospection: IntrospectionObjectType,
): GraphQLObjectType {
return new GraphQLObjectType({
name: objectIntrospection.name,
description: objectIntrospection.description,
interfaces: () => buildImplementationsList(objectIntrospection),
fields: () => buildFieldDefMap(objectIntrospection),
});
}
function buildInterfaceDef(
interfaceIntrospection: IntrospectionInterfaceType,
): GraphQLInterfaceType {
return new GraphQLInterfaceType({
name: interfaceIntrospection.name,
description: interfaceIntrospection.description,
interfaces: () => buildImplementationsList(interfaceIntrospection),
fields: () => buildFieldDefMap(interfaceIntrospection),
});
}
function buildUnionDef(
unionIntrospection: IntrospectionUnionType,
): GraphQLUnionType {
if (!unionIntrospection.possibleTypes) {
const unionIntrospectionStr = inspect(unionIntrospection);
throw new Error(
`Introspection result missing possibleTypes: ${unionIntrospectionStr}.`,
);
}
return new GraphQLUnionType({
name: unionIntrospection.name,
description: unionIntrospection.description,
types: () => unionIntrospection.possibleTypes.map(getObjectType),
});
}
function buildEnumDef(
enumIntrospection: IntrospectionEnumType,
): GraphQLEnumType {
if (!enumIntrospection.enumValues) {
const enumIntrospectionStr = inspect(enumIntrospection);
throw new Error(
`Introspection result missing enumValues: ${enumIntrospectionStr}.`,
);
}
return new GraphQLEnumType({
name: enumIntrospection.name,
description: enumIntrospection.description,
values: keyValMap(
enumIntrospection.enumValues,
(valueIntrospection) => valueIntrospection.name,
(valueIntrospection) => ({
description: valueIntrospection.description,
deprecationReason: valueIntrospection.deprecationReason,
}),
),
});
}
function buildInputObjectDef(
inputObjectIntrospection: IntrospectionInputObjectType,
): GraphQLInputObjectType {
if (!inputObjectIntrospection.inputFields) {
const inputObjectIntrospectionStr = inspect(inputObjectIntrospection);
throw new Error(
`Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`,
);
}
return new GraphQLInputObjectType({
name: inputObjectIntrospection.name,
description: inputObjectIntrospection.description,
fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields),
});
}
function buildFieldDefMap(
typeIntrospection: IntrospectionObjectType | IntrospectionInterfaceType,
): GraphQLFieldConfigMap<unknown, unknown> {
if (!typeIntrospection.fields) {
throw new Error(
`Introspection result missing fields: ${inspect(typeIntrospection)}.`,
);
}
return keyValMap(
typeIntrospection.fields,
(fieldIntrospection) => fieldIntrospection.name,
buildField,
);
}
function buildField(
fieldIntrospection: IntrospectionField,
): GraphQLFieldConfig<unknown, unknown> {
const type = getType(fieldIntrospection.type);
if (!isOutputType(type)) {
const typeStr = inspect(type);
throw new Error(
`Introspection must provide output type for fields, but received: ${typeStr}.`,
);
}
if (!fieldIntrospection.args) {
const fieldIntrospectionStr = inspect(fieldIntrospection);
throw new Error(
`Introspection result missing field args: ${fieldIntrospectionStr}.`,
);
}
return {
description: fieldIntrospection.description,
deprecationReason: fieldIntrospection.deprecationReason,
type,
args: buildInputValueDefMap(fieldIntrospection.args),
};
}
function buildInputValueDefMap(
inputValueIntrospections: ReadonlyArray<IntrospectionInputValue>,
) {
return keyValMap(
inputValueIntrospections,
(inputValue) => inputValue.name,
buildInputValue,
);
}
function buildInputValue(inputValueIntrospection: IntrospectionInputValue) {
const type = getType(inputValueIntrospection.type);
if (!isInputType(type)) {
const typeStr = inspect(type);
throw new Error(
`Introspection must provide input type for arguments, but received: ${typeStr}.`,
);
}
const defaultValue =
inputValueIntrospection.defaultValue != null
? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type)
: undefined;
return {
description: inputValueIntrospection.description,
type,
defaultValue,
deprecationReason: inputValueIntrospection.deprecationReason,
};
}
function buildDirective(
directiveIntrospection: IntrospectionDirective,
): GraphQLDirective {
if (!directiveIntrospection.args) {
const directiveIntrospectionStr = inspect(directiveIntrospection);
throw new Error(
`Introspection result missing directive args: ${directiveIntrospectionStr}.`,
);
}
if (!directiveIntrospection.locations) {
const directiveIntrospectionStr = inspect(directiveIntrospection);
throw new Error(
`Introspection result missing directive locations: ${directiveIntrospectionStr}.`,
);
}
return new GraphQLDirective({
name: directiveIntrospection.name,
description: directiveIntrospection.description,
isRepeatable: directiveIntrospection.isRepeatable,
locations: directiveIntrospection.locations.slice(),
args: buildInputValueDefMap(directiveIntrospection.args),
});
}
} | the_stack |
import React, { Component, useEffect, useState } from 'react';
import {
Alert,
Button,
FlatList,
PermissionsAndroid,
Platform,
StyleSheet,
Text,
View,
} from 'react-native';
import Slider from '@react-native-community/slider';
import RtcEngine, {
AudioEffectPreset,
AudioEqualizationBandFrequency,
AudioProfile,
AudioReverbType,
AudioScenario,
ChannelProfile,
ClientRole,
RtcEngineContext,
VoiceBeautifierPreset,
} from 'react-native-agora';
import VoiceChangeConfig, {
FreqOptions,
ReverbKeyOptions,
} from '../config/VoiceChangeConfig';
const config = require('../../../agora.config.json');
interface State {
channelId?: string;
isJoin: boolean;
remoteUids: Array<number>;
uidMySelf?: number;
selectedVoiceToolBtn?: number;
isEnableSlider1: boolean;
isEnableSlider2: boolean;
sliderTitle1?: string;
sliderTitle2?: string;
minimumValue1?: number;
maximumValue1?: number;
minimumValue2?: number;
maximumValue2?: number;
sliderValue1?: number;
sliderValue2?: number;
currentAudioEffectPreset?: AudioEffectPreset;
selectedFreq: { text: string; type: AudioEqualizationBandFrequency };
selectedReverbKey: {
text: string;
type: AudioReverbType;
min: number;
max: number;
};
bandGainValue: number;
reverbValue?: number;
}
export default class VoiceChange extends Component<{}, State, any> {
_engine?: RtcEngine;
constructor(props: {}) {
super(props);
this.state = {
isJoin: false,
remoteUids: [],
isEnableSlider1: false,
isEnableSlider2: false,
selectedFreq: FreqOptions[0],
selectedReverbKey: ReverbKeyOptions[0],
bandGainValue: 0,
};
}
componentWillUnmount() {
this._engine?.destroy();
}
_initEngine = async () => {
if (Platform.OS === 'android') {
await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
PermissionsAndroid.PERMISSIONS.CAMERA,
]);
}
this._engine = await RtcEngine.createWithContext(
new RtcEngineContext(config.appId)
);
this._addListeners();
// Before calling the method, you need to set the profile
// parameter of setAudioProfile to AUDIO_PROFILE_MUSIC_HIGH_QUALITY(4)
// or AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO(5), and to set
// scenario parameter to AUDIO_SCENARIO_GAME_STREAMING(3)
await this._engine.setAudioProfile(
AudioProfile.MusicHighQualityStereo,
AudioScenario.GameStreaming
);
// make myself a broadcaster
await this._engine.setChannelProfile(ChannelProfile.LiveBroadcasting);
await this._engine?.setClientRole(ClientRole.Broadcaster);
// disable video module
await this._engine?.disableVideo();
// Set audio route to speaker
await this._engine.setDefaultAudioRoutetoSpeakerphone(true);
// start joining channel
// 1. Users can only see each other after they join the
// same channel successfully using the same app id.
// 2. If app certificate is turned on at dashboard, token is needed
// when joining channel. The channel name and uid used to calculate
// the token has to match the ones used for channel join
await this._engine.joinChannel(
config.token,
config.channelId,
null,
0,
undefined
);
};
_addListeners = () => {
this._engine?.addListener('Warning', (warningCode) => {
console.info('Warning', warningCode);
});
this._engine?.addListener('Error', (errorCode) => {
console.info('Error', errorCode);
});
this._engine?.addListener('JoinChannelSuccess', (channel, uid, elapsed) => {
console.info('JoinChannelSuccess', channel, uid, elapsed);
// RtcLocalView.SurfaceView must render after engine init and channel join
this.setState({ isJoin: true, uidMySelf: uid });
});
this._engine?.addListener('UserJoined', async (uid, elapsed) => {
console.info('UserJoined', uid, elapsed);
this.setState({ remoteUids: [...this.state.remoteUids, uid] });
});
this._engine?.addListener('UserOffline', (uid, reason) => {
console.info('UserOffline', uid, reason);
this.setState({
remoteUids: this.state.remoteUids.filter((value) => value !== uid),
});
});
};
onPressBFButtonn = async (
type: VoiceBeautifierPreset | AudioEffectPreset,
index: number
) => {
switch (index) {
case 0:
case 1:
await this._engine?.setVoiceBeautifierPreset(
type as VoiceBeautifierPreset
);
this.updateSliderUI(AudioEffectPreset.AudioEffectOff);
break;
case 2:
case 3:
case 4:
case 5:
await this._engine?.setAudioEffectPreset(type as AudioEffectPreset);
this.updateSliderUI(type as AudioEffectPreset);
break;
default:
break;
}
};
updateSliderUI = (type: AudioEffectPreset) => {
this.setState({ currentAudioEffectPreset: type });
switch (type) {
case AudioEffectPreset.RoomAcoustics3DVoice:
this.setState({
isEnableSlider1: true,
isEnableSlider2: false,
sliderTitle1: 'Cycle',
minimumValue1: 1,
maximumValue1: 3,
});
break;
case AudioEffectPreset.PitchCorrection:
this.setState({
isEnableSlider1: true,
isEnableSlider2: true,
sliderTitle1: 'Tonic Mode',
sliderTitle2: 'Tonic Pitch',
minimumValue1: 1,
maximumValue1: 3,
minimumValue2: 1,
maximumValue2: 12,
});
break;
default:
this.setState({
isEnableSlider1: false,
isEnableSlider2: false,
});
break;
}
};
onAudioEffectUpdate = ({
value1,
value2,
}: {
value1?: number;
value2?: number;
}) => {
this.setState(
{
sliderValue1: value1 ? value1 : this.state.sliderValue1,
sliderValue2: value2 ? value2 : this.state.sliderValue2,
},
async () => {
const {
isEnableSlider1,
isEnableSlider2,
sliderValue1,
sliderValue2,
minimumValue1,
minimumValue2,
currentAudioEffectPreset,
} = this.state;
await this._engine?.setAudioEffectParameters(
currentAudioEffectPreset!,
isEnableSlider1 ? sliderValue1 ?? minimumValue1! : 0,
isEnableSlider2 ? sliderValue2 ?? minimumValue2! : 0
);
}
);
};
onPressChangeFreq = () => {
Alert.alert(
'Set Band Frequency',
undefined,
FreqOptions.map((selectedFreq) => ({
text: selectedFreq.text,
onPress: () => {
this.setState({ selectedFreq }, async () => {
await this._engine?.setLocalVoiceEqualization(
this.state.selectedFreq.type,
this.state.bandGainValue
);
});
},
}))
);
};
onPressChangeReverbKey = () => {
Alert.alert(
'Set Reverb Key',
undefined,
ReverbKeyOptions.map((selectedReverbKey) => ({
text: selectedReverbKey.text,
onPress: async () => {
this.setState({ selectedReverbKey });
},
}))
);
};
keyExtractor = (_item: any, index: number) => `${_item}${index}`;
render() {
const { isJoin } = this.state;
return (
<View style={styles.container}>
{!isJoin && <Button onPress={this._initEngine} title="Join channel" />}
{isJoin && this._renderUserUid()}
{isJoin && this._renderToolContainer()}
</View>
);
}
_renderUserUid = () => {
const { remoteUids, uidMySelf } = this.state;
return (
<FlatList
data={[uidMySelf!, ...remoteUids]}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
/>
);
};
renderItem = ({ item, index }: { item: number; index: number }) => {
return (
<View style={styles.listItem}>
<Text>
{`AUDIO ONLY ${index ? 'REMOTE' : 'LOCAL'} UID: `}
<Text style={styles.boldTxt}>{item}</Text>
</Text>
</View>
);
};
_renderToolContainer = () => {
const {
selectedVoiceToolBtn,
isEnableSlider1,
isEnableSlider2,
sliderTitle1,
sliderTitle2,
minimumValue1,
maximumValue1,
minimumValue2,
maximumValue2,
selectedFreq,
selectedReverbKey,
} = this.state;
return (
<View style={styles.toolContainer}>
<Text style={styles.boldTxt}>Voice Beautifier & Effects Preset</Text>
<View style={styles.voiceToolContainer}>
{VoiceChangeConfig.map(({ alertTitle, options }, index) => (
<CusBtn
key={alertTitle}
isOff={selectedVoiceToolBtn !== index}
alertTitle={alertTitle}
options={options}
onPress={(type: VoiceBeautifierPreset | AudioEffectPreset) => {
this.setState({ selectedVoiceToolBtn: index });
this.onPressBFButtonn(type, index);
}}
/>
))}
</View>
<View>
{isEnableSlider1 && (
<View>
<Text>{sliderTitle1}</Text>
<Slider
minimumValue={minimumValue1}
maximumValue={maximumValue1}
onValueChange={(value1) => this.onAudioEffectUpdate({ value1 })}
/>
</View>
)}
{isEnableSlider2 && (
<View>
<Text>{sliderTitle2}</Text>
<Slider
minimumValue={minimumValue2}
maximumValue={maximumValue2}
onValueChange={(value2) => this.onAudioEffectUpdate({ value2 })}
/>
</View>
)}
</View>
<Text style={styles.boldTxt}>Voice Beautifier & Effects Preset</Text>
<View>
<View style={styles.customToolItem}>
<Text>Pitch</Text>
<Slider
style={styles.slider}
minimumValue={0.5}
maximumValue={2}
onValueChange={async (value) => {
await this._engine?.setLocalVoicePitch(value);
}}
/>
</View>
<View style={styles.customToolItem}>
<Text>BandFreq</Text>
<Button
title={selectedFreq.text}
onPress={this.onPressChangeFreq}
/>
</View>
<View style={styles.customToolItem}>
<Text>BandGain</Text>
<Slider
style={styles.slider}
minimumValue={0}
maximumValue={9}
onValueChange={(bandGainValue) => {
this.setState({ bandGainValue }, async () => {
await this._engine?.setLocalVoiceEqualization(
this.state.selectedFreq.type,
this.state.bandGainValue
);
});
}}
/>
</View>
<View style={styles.customToolItem}>
<Text>ReverbKey</Text>
<Button
title={selectedReverbKey.text}
onPress={this.onPressChangeReverbKey}
/>
</View>
<View style={styles.customToolItem}>
<Text>ReverbValue</Text>
<Slider
style={styles.slider}
minimumValue={selectedReverbKey.min}
maximumValue={selectedReverbKey.max}
onValueChange={(reverbValue) => {
this.setState({ reverbValue }, async () => {
await this._engine?.setLocalVoiceReverb(
this.state.selectedReverbKey.type,
this.state.reverbValue!
);
});
}}
/>
</View>
</View>
</View>
);
};
}
const CusBtn = ({
isOff = true,
alertTitle,
options,
onPress,
}: {
isOff: boolean;
alertTitle: string;
options: Array<{
text: string;
type: VoiceBeautifierPreset | AudioEffectPreset;
}>;
onPress: Function;
}) => {
const [isEnable, setIsEnable] = useState(!isOff);
const [title, setTitle] = useState('Off');
useEffect(() => {
setIsEnable(!isOff);
}, [isOff]);
const customOnPress = () => {
Alert.alert(
alertTitle,
undefined,
options.map(({ text, type }) => ({
text,
onPress: () => {
setIsEnable(true);
setTitle(text);
onPress && onPress(type);
},
}))
);
};
return <Button title={isEnable ? title : 'Off'} onPress={customOnPress} />;
};
const styles = StyleSheet.create({
container: {
flex: 1,
paddingBottom: 40,
},
toolBarTitle: {
marginTop: 48,
fontSize: 18,
fontWeight: 'bold',
},
boldTxt: {
fontWeight: 'bold',
fontSize: 20,
},
listItem: {
width: '100%',
justifyContent: 'center',
alignItems: 'center',
marginTop: 8,
},
toolContainer: {
flex: 5,
paddingHorizontal: 16,
},
voiceToolContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
},
slider: {
width: '50%',
},
customToolItem: {
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginTop: 8,
},
}); | the_stack |
import { Buffer } from '@stacks/common';
import * as blockstack from 'blockstack';
import * as bitcoin from 'bitcoinjs-lib';
import * as process from 'process';
import * as fs from 'fs';
import * as winston from 'winston';
import cors from 'cors';
import * as crypto from 'crypto';
import * as bip39 from 'bip39';
import express from 'express';
import * as path from 'path';
import { prompt } from 'inquirer';
import fetch from 'node-fetch';
import {
makeSTXTokenTransfer,
makeContractDeploy,
makeContractCall,
callReadOnlyFunction,
broadcastTransaction,
estimateTransfer,
estimateContractDeploy,
estimateContractFunctionCall,
SignedTokenTransferOptions,
ContractDeployOptions,
SignedContractCallOptions,
ReadOnlyFunctionOptions,
ContractCallPayload,
ClarityValue,
ClarityAbi,
getAbi,
validateContractCall,
PostConditionMode,
cvToString,
StacksTransaction,
TxBroadcastResult,
getAddressFromPrivateKey,
TransactionVersion,
TransactionSigner,
publicKeyToString,
pubKeyfromPrivKey,
createStacksPrivateKey,
AnchorMode,
} from '@stacks/transactions';
import { buildPreorderNameTx, buildRegisterNameTx } from '@stacks/bns';
import { StacksMainnet, StacksTestnet } from '@stacks/network';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const c32check = require('c32check');
import { UserData } from '@stacks/auth';
import crossfetch from 'cross-fetch';
import { StackingClient, StackerInfo } from '@stacks/stacking';
import { FaucetsApi, AccountsApi, Configuration } from '@stacks/blockchain-api-client';
import { GaiaHubConfig } from '@stacks/storage';
import {
getOwnerKeyInfo,
getPaymentKeyInfo,
getStacksWalletKeyInfo,
getApplicationKeyInfo,
extractAppKey,
STX_WALLET_COMPATIBLE_SEED_STRENGTH,
PaymentKeyInfoType,
OwnerKeyInfoType,
StacksKeyInfoType,
} from './keys';
import {
CLI_ARGS,
getCLIOpts,
CLIOptAsString,
CLIOptAsStringArray,
CLIOptAsBool,
checkArgs,
loadConfig,
makeCommandUsageString,
makeAllCommandsList,
USAGE,
DEFAULT_CONFIG_PATH,
DEFAULT_CONFIG_TESTNET_PATH,
ID_ADDRESS_PATTERN,
STACKS_ADDRESS_PATTERN,
} from './argparse';
import { encryptBackupPhrase, decryptBackupPhrase } from './encrypt';
import { CLINetworkAdapter, CLI_NETWORK_OPTS, getNetwork, NameInfoType } from './network';
import { gaiaAuth, gaiaConnect, gaiaUploadProfileAll, getGaiaAddressFromProfile } from './data';
import {
JSONStringify,
canonicalPrivateKey,
decodePrivateKey,
makeProfileJWT,
getNameInfoEasy,
getpass,
getBackupPhrase,
mkdirs,
IDAppKeys,
getIDAppKeys,
makePromptsFromArgList,
parseClarityFunctionArgAnswers,
ClarityFunctionArg,
generateExplorerTxPageUrl,
isTestnetAddress,
} from './utils';
import { handleAuth, handleSignIn } from './auth';
import { generateNewAccount, generateWallet, getAppPrivateKey } from '@stacks/wallet-sdk';
import { getMaxIDSearchIndex, setMaxIDSearchIndex, getPrivateKeyAddress } from './common';
// global CLI options
let txOnly = false;
let estimateOnly = false;
let safetyChecks = true;
let receiveFeesPeriod = 52595;
let gracePeriod = 5000;
let noExit = false;
let BLOCKSTACK_TEST = !!process.env.BLOCKSTACK_TEST;
/*
* Sign a profile.
* @path (string) path to the profile
* @privateKey (string) the owner key (must be single-sig)
*/
// TODO: fix, network is never used
// @ts-ignore
function profileSign(network: CLINetworkAdapter, args: string[]): Promise<string> {
const profilePath = args[0];
const profileData = JSON.parse(fs.readFileSync(profilePath).toString());
return Promise.resolve().then(() => makeProfileJWT(profileData, args[1]));
}
/*
* Verify a profile with an address or public key
* @path (string) path to the profile
* @publicKeyOrAddress (string) public key or address
*/
function profileVerify(network: CLINetworkAdapter, args: string[]): Promise<string> {
const profilePath = args[0];
let publicKeyOrAddress = args[1];
// need to coerce mainnet
if (publicKeyOrAddress.match(ID_ADDRESS_PATTERN)) {
publicKeyOrAddress = network.coerceMainnetAddress(publicKeyOrAddress.slice(3));
}
const profileString = fs.readFileSync(profilePath).toString();
return Promise.resolve().then(() => {
let profileToken = null;
try {
const profileTokens = JSON.parse(profileString);
profileToken = profileTokens[0].token;
} catch (e) {
// might be a raw token
profileToken = profileString;
}
if (!profileToken) {
throw new Error(`Data at ${profilePath} does not appear to be a signed profile`);
}
const profile = blockstack.extractProfile(profileToken, publicKeyOrAddress);
return JSONStringify(profile);
});
}
/*
* Store a signed profile for a name or an address.
* * verify that the profile was signed by the name's owner address
* * verify that the private key matches the name's owner address
*
* Assumes that the URI records are all Gaia hubs
*
* @nameOrAddress (string) name or address that owns the profile
* @path (string) path to the signed profile token
* @privateKey (string) owner private key for the name
* @gaiaUrl (string) this is the write endpoint of the Gaia hub to use
*/
function profileStore(network: CLINetworkAdapter, args: string[]): Promise<string> {
const nameOrAddress = args[0];
const signedProfilePath = args[1];
const privateKey = decodePrivateKey(args[2]);
const gaiaHubUrl = args[3];
const signedProfileData = fs.readFileSync(signedProfilePath).toString();
const ownerAddress = getPrivateKeyAddress(network, privateKey);
const ownerAddressMainnet = network.coerceMainnetAddress(ownerAddress);
let nameInfoPromise: Promise<NameInfoType | null>;
let name = '';
if (nameOrAddress.startsWith('ID-')) {
// ID-address
nameInfoPromise = Promise.resolve().then(() => {
return {
address: nameOrAddress.slice(3),
};
});
} else {
// name; find the address
nameInfoPromise = getNameInfoEasy(network, nameOrAddress);
name = nameOrAddress;
}
const verifyProfilePromise = profileVerify(network, [
signedProfilePath,
`ID-${ownerAddressMainnet}`,
]);
return Promise.all([nameInfoPromise, verifyProfilePromise])
.then(([nameInfo, _verifiedProfile]: [NameInfoType | null, any]) => {
if (
safetyChecks &&
(!nameInfo ||
network.coerceAddress(nameInfo.address) !== network.coerceAddress(ownerAddress))
) {
throw new Error(
'Name owner address either could not be found, or does not match ' +
`private key address ${ownerAddress}`
);
}
return gaiaUploadProfileAll(network, [gaiaHubUrl], signedProfileData, args[2], name);
})
.then((gaiaUrls: { dataUrls?: string[] | null; error?: string | null }) => {
if (gaiaUrls.hasOwnProperty('error')) {
return JSONStringify({ dataUrls: gaiaUrls.dataUrls!, error: gaiaUrls.error! }, true);
} else {
return JSONStringify({ profileUrls: gaiaUrls.dataUrls! });
}
});
}
/*
* Get the app private key(s) from a backup phrase
* and an index of the enumerated accounts
* args:
* @mnemonic (string) the 12-word phrase
* @index (number) the index of the account
* @appOrigin (string) the application's origin URL
*/
async function getAppKeys(network: CLINetworkAdapter, args: string[]): Promise<string> {
const mnemonic = await getBackupPhrase(args[0]);
const index = parseInt(args[1]);
if (index <= 0) throw new Error('index must be greater than 0');
const appDomain = args[2];
let wallet = await generateWallet({ secretKey: mnemonic, password: '' });
for (let i = 0; i < index; i++) {
wallet = generateNewAccount(wallet);
}
const account = wallet.accounts[index - 1];
const privateKey = getAppPrivateKey({ account, appDomain });
const address = getAddressFromPrivateKey(
privateKey,
network.isMainnet() ? TransactionVersion.Mainnet : TransactionVersion.Testnet
);
return JSON.stringify({ keyInfo: { privateKey, address } });
}
/*
* Get the owner private key(s) from a backup phrase
* args:
* @mnemonic (string) the 12-word phrase
* @max_index (integer) (optional) the profile index maximum
*/
async function getOwnerKeys(network: CLINetworkAdapter, args: string[]): Promise<string> {
const mnemonic = await getBackupPhrase(args[0]);
let maxIndex = 1;
if (args.length > 1 && !!args[1]) {
maxIndex = parseInt(args[1]);
}
const keyInfo: OwnerKeyInfoType[] = [];
for (let i = 0; i < maxIndex; i++) {
keyInfo.push(await getOwnerKeyInfo(network, mnemonic, i));
}
return JSONStringify(keyInfo);
}
/*
* Get the payment private key from a backup phrase
* args:
* @mnemonic (string) the 12-word phrase
*/
async function getPaymentKey(network: CLINetworkAdapter, args: string[]): Promise<string> {
const mnemonic = await getBackupPhrase(args[0]);
// keep the return value consistent with getOwnerKeys
const keyObj = await getPaymentKeyInfo(network, mnemonic);
const keyInfo: PaymentKeyInfoType[] = [];
keyInfo.push(keyObj);
return JSONStringify(keyInfo);
}
/*
* Get the payment private key from a backup phrase used by the Stacks wallet
* args:
* @mnemonic (string) the 24-word phrase
*/
async function getStacksWalletKey(network: CLINetworkAdapter, args: string[]): Promise<string> {
const mnemonic = await getBackupPhrase(args[0]);
const derivationPath: string | undefined = args[1] || undefined;
// keep the return value consistent with getOwnerKeys
const keyObj = await getStacksWalletKeyInfo(network, mnemonic, derivationPath);
const keyInfo: StacksKeyInfoType[] = [];
keyInfo.push(keyObj);
return JSONStringify(keyInfo);
}
/*
* Make a private key and output it
* args:
* @mnemonic (string) OPTIONAL; the 12-word phrase
*/
async function makeKeychain(network: CLINetworkAdapter, args: string[]): Promise<string> {
let mnemonic: string;
if (args[0]) {
mnemonic = await getBackupPhrase(args[0]);
} else {
// eslint-disable-next-line @typescript-eslint/await-thenable
mnemonic = await bip39.generateMnemonic(
STX_WALLET_COMPATIBLE_SEED_STRENGTH,
crypto.randomBytes
);
}
const derivationPath: string | undefined = args[1] || undefined;
const stacksKeyInfo = await getStacksWalletKeyInfo(network, mnemonic, derivationPath);
return JSONStringify({
mnemonic: mnemonic,
keyInfo: stacksKeyInfo,
});
}
/*
* Get an address's tokens and their balances.
* Takes either a Bitcoin or Stacks address
* args:
* @address (string) the address
*/
function balance(network: CLINetworkAdapter, args: string[]): Promise<string> {
let address = args[0];
if (BLOCKSTACK_TEST) {
// force testnet address if we're in testnet mode
address = network.coerceAddress(address);
}
// temporary hack to use network config from stacks-transactions lib
const txNetwork = network.isMainnet()
? new StacksMainnet({ url: network.legacyNetwork.blockstackAPIUrl })
: new StacksTestnet({ url: network.legacyNetwork.blockstackAPIUrl });
return fetch(txNetwork.getAccountApiUrl(address))
.then(response => {
if (response.status === 404) {
return Promise.reject({
status: response.status,
error: response.statusText,
});
}
return response.json();
})
.then(response => {
const res = {
balance: BigInt(response.balance).toString(10),
locked: BigInt(response.locked).toString(10),
unlock_height: response.unlock_height,
nonce: response.nonce,
};
return Promise.resolve(JSONStringify(res));
})
.catch(error => error);
}
/*
* Get a page of the account's history
* args:
* @address (string) the account address
* @page (int) the page of the history to fetch (optional)
*/
function getAccountHistory(network: CLINetworkAdapter, args: string[]): Promise<string> {
const address = c32check.c32ToB58(args[0]);
if (args.length >= 2 && !!args[1]) {
const page = parseInt(args[1]);
return Promise.resolve()
.then(() => {
return network.getAccountHistoryPage(address, page);
})
.then(accountStates =>
JSONStringify(
accountStates.map((s: any) => {
const new_s = {
address: c32check.b58ToC32(s.address),
credit_value: s.credit_value.toString(),
debit_value: s.debit_value.toString(),
};
return new_s;
})
)
);
} else {
// all pages
let history: any[] = [];
function getAllAccountHistoryPages(page: number): Promise<any[]> {
return network.getAccountHistoryPage(address, page).then((results: any[]) => {
if (results.length == 0) {
return history;
} else {
history = history.concat(results);
return getAllAccountHistoryPages(page + 1);
}
});
}
return getAllAccountHistoryPages(0).then((accountStates: any[]) =>
JSONStringify(
accountStates.map((s: any) => {
const new_s = {
address: c32check.b58ToC32(s.address),
credit_value: s.credit_value.toString(),
debit_value: s.debit_value.toString(),
};
return new_s;
})
)
);
}
}
// /*
// * Get the account's state(s) at a particular block height
// * args:
// * @address (string) the account address
// * @blockHeight (int) the height at which to query
// */
// function getAccountAt(network: CLINetworkAdapter, args: string[]) : Promise<string> {
// const address = c32check.c32ToB58(args[0]);
// const blockHeight = parseInt(args[1]);
// return Promise.resolve().then(() => {
// return network.getAccountAt(address, blockHeight);
// })
// .then(accountStates => accountStates.map((s : any) => {
// const new_s = {
// address: c32check.b58ToC32(s.address),
// credit_value: s.credit_value.toString(),
// debit_value: s.debit_value.toString()
// };
// return new_s;
// }))
// .then(history => JSONStringify(history));
// }
// /*
// * Sends BTC from one private key to another address
// * args:
// * @recipientAddress (string) the recipient's address
// * @amount (string) the amount of BTC to send
// * @privateKey (string) the private key that owns the BTC
// */
// function sendBTC(network: CLINetworkAdapter, args: string[]) : Promise<string> {
// const destinationAddress = args[0];
// const amount = parseInt(args[1]);
// const paymentKeyHex = decodePrivateKey(args[2]);
// if (amount <= 5500) {
// throw new Error('Invalid amount (must be greater than 5500)');
// }
// let paymentKey;
// if (typeof paymentKeyHex === 'string') {
// // single-sig
// paymentKey = blockstack.PubkeyHashSigner.fromHexString(paymentKeyHex);
// }
// else {
// // multi-sig or segwit
// paymentKey = paymentKeyHex;
// }
// const txPromise = blockstack.transactions.makeBitcoinSpend(destinationAddress, paymentKey, amount, !hasKeys(paymentKeyHex))
// .catch((e : Error) => {
// if (e.name === 'InvalidAmountError') {
// return JSONStringify({
// 'status': false,
// 'error': e.message
// }, true);
// }
// else {
// throw e;
// }
// });
// if (txOnly) {
// return txPromise;
// }
// else {
// return txPromise.then((tx : string) => {
// return network.broadcastTransaction(tx);
// })
// .then((txid : string) => {
// return txid;
// });
// }
// }
/*
* Send tokens from one account private key to another account's address.
* args:
* @recipientAddress (string) the recipient's account address
* @tokenAmount (int) the number of tokens to send
* @fee (int) the transaction fee to be paid
* @nonce (int) integer nonce needs to be incremented after each transaction from an account
* @privateKey (string) the hex-encoded private key to use to send the tokens
* @memo (string) OPTIONAL: a 34-byte memo to include
*/
async function sendTokens(network: CLINetworkAdapter, args: string[]): Promise<string> {
const recipientAddress = args[0];
const tokenAmount = BigInt(args[1]);
const fee = BigInt(args[2]);
const nonce = BigInt(args[3]);
const privateKey = args[4];
let memo = '';
if (args.length > 4 && !!args[5]) {
memo = args[5];
}
// temporary hack to use network config from stacks-transactions lib
const txNetwork = network.isMainnet()
? new StacksMainnet({ url: network.legacyNetwork.blockstackAPIUrl })
: new StacksTestnet({ url: network.legacyNetwork.blockstackAPIUrl });
const options: SignedTokenTransferOptions = {
recipient: recipientAddress,
amount: tokenAmount,
senderKey: privateKey,
fee,
nonce,
memo,
network: txNetwork,
anchorMode: AnchorMode.Any,
};
const tx: StacksTransaction = await makeSTXTokenTransfer(options);
if (estimateOnly) {
return estimateTransfer(tx, txNetwork).then(cost => {
return cost.toString(10);
});
}
if (txOnly) {
return Promise.resolve(tx.serialize().toString('hex'));
}
return broadcastTransaction(tx, txNetwork)
.then((response: TxBroadcastResult) => {
if (response.hasOwnProperty('error')) {
return response;
}
return {
txid: `0x${tx.txid()}`,
transaction: generateExplorerTxPageUrl(tx.txid(), txNetwork),
};
})
.catch(error => {
return error.toString();
});
}
/*
* Depoly a Clarity smart contract.
* args:
* @source (string) path to the contract source file
* @contractName (string) the name of the contract
* @fee (int) the transaction fee to be paid
* @nonce (int) integer nonce needs to be incremented after each transaction from an account
* @privateKey (string) the hex-encoded private key to use to send the tokens
*/
async function contractDeploy(network: CLINetworkAdapter, args: string[]): Promise<string> {
const sourceFile = args[0];
const contractName = args[1];
const fee = BigInt(args[2]);
const nonce = BigInt(args[3]);
const privateKey = args[4];
const source = fs.readFileSync(sourceFile).toString();
// temporary hack to use network config from stacks-transactions lib
const txNetwork = network.isMainnet()
? new StacksMainnet({ url: network.legacyNetwork.blockstackAPIUrl })
: new StacksTestnet({ url: network.legacyNetwork.blockstackAPIUrl });
const options: ContractDeployOptions = {
contractName,
codeBody: source,
senderKey: privateKey,
fee,
nonce,
network: txNetwork,
postConditionMode: PostConditionMode.Allow,
anchorMode: AnchorMode.Any,
};
const tx = await makeContractDeploy(options);
if (estimateOnly) {
return estimateContractDeploy(tx, txNetwork).then(cost => {
return cost.toString(10);
});
}
if (txOnly) {
return Promise.resolve(tx.serialize().toString('hex'));
}
return broadcastTransaction(tx, txNetwork)
.then(response => {
if (response.hasOwnProperty('error')) {
return response;
}
return {
txid: `0x${tx.txid()}`,
transaction: generateExplorerTxPageUrl(tx.txid(), txNetwork),
};
})
.catch(error => {
return error.toString();
});
}
/*
* Call a Clarity smart contract function.
* args:
* @contractAddress (string) the address of the contract
* @contractName (string) the name of the contract
* @functionName (string) the name of the function to call
* @fee (int) the transaction fee to be paid
* @nonce (int) integer nonce needs to be incremented after each transaction from an account
* @privateKey (string) the hex-encoded private key to use to send the tokens
*/
async function contractFunctionCall(network: CLINetworkAdapter, args: string[]): Promise<string> {
const contractAddress = args[0];
const contractName = args[1];
const functionName = args[2];
const fee = BigInt(args[3]);
const nonce = BigInt(args[4]);
const privateKey = args[5];
// temporary hack to use network config from stacks-transactions lib
const txNetwork = network.isMainnet()
? new StacksMainnet({ url: network.legacyNetwork.blockstackAPIUrl })
: new StacksTestnet({ url: network.legacyNetwork.blockstackAPIUrl });
let abi: ClarityAbi;
let abiArgs: ClarityFunctionArg[];
let functionArgs: ClarityValue[] = [];
return getAbi(contractAddress, contractName, txNetwork)
.then(responseAbi => {
abi = responseAbi;
const filtered = abi.functions.filter(fn => fn.name === functionName);
if (filtered.length === 1) {
abiArgs = filtered[0].args;
return makePromptsFromArgList(abiArgs);
} else {
return null;
}
})
.then(prompts => prompt(prompts!))
.then(answers => {
functionArgs = parseClarityFunctionArgAnswers(answers, abiArgs);
const options: SignedContractCallOptions = {
contractAddress,
contractName,
functionName,
functionArgs,
senderKey: privateKey,
fee,
nonce,
network: txNetwork,
postConditionMode: PostConditionMode.Allow,
anchorMode: AnchorMode.Any,
};
return makeContractCall(options);
})
.then(tx => {
if (!validateContractCall(tx.payload as ContractCallPayload, abi)) {
throw new Error('Failed to validate function arguments against ABI');
}
if (estimateOnly) {
return estimateContractFunctionCall(tx, txNetwork).then(cost => {
return cost.toString(10);
});
}
if (txOnly) {
return Promise.resolve(tx.serialize().toString('hex'));
}
return broadcastTransaction(tx, txNetwork)
.then(response => {
if (response.hasOwnProperty('error')) {
return response;
}
return {
txid: `0x${tx.txid()}`,
transaction: generateExplorerTxPageUrl(tx.txid(), txNetwork),
};
})
.catch(error => {
return error.toString();
});
});
}
/*
* Call a read-only Clarity smart contract function.
* args:
* @contractAddress (string) the address of the contract
* @contractName (string) the name of the contract
* @functionName (string) the name of the function to call
* @senderAddress (string) the sender address
*/
async function readOnlyContractFunctionCall(
network: CLINetworkAdapter,
args: string[]
): Promise<string> {
const contractAddress = args[0];
const contractName = args[1];
const functionName = args[2];
const senderAddress = args[3];
// temporary hack to use network config from stacks-transactions lib
const txNetwork = network.isMainnet()
? new StacksMainnet({ url: network.legacyNetwork.blockstackAPIUrl })
: new StacksTestnet({ url: network.legacyNetwork.blockstackAPIUrl });
let abi: ClarityAbi;
let abiArgs: ClarityFunctionArg[];
let functionArgs: ClarityValue[] = [];
return getAbi(contractAddress, contractName, txNetwork)
.then(responseAbi => {
abi = responseAbi;
const filtered = abi.functions.filter(fn => fn.name === functionName);
if (filtered.length === 1) {
abiArgs = filtered[0].args;
return makePromptsFromArgList(abiArgs);
} else {
return null;
}
})
.then(prompts => prompt(prompts!))
.then(answers => {
functionArgs = parseClarityFunctionArgAnswers(answers, abiArgs);
const options: ReadOnlyFunctionOptions = {
contractAddress,
contractName,
functionName,
functionArgs,
senderAddress,
network: txNetwork,
};
return callReadOnlyFunction(options);
})
.then(returnValue => {
return cvToString(returnValue);
})
.catch(error => {
return error.toString();
});
}
// /*
// * Get the number of confirmations of a txid.
// * args:
// * @txid (string) the transaction ID as a hex string
// */
// function getConfirmations(network: CLINetworkAdapter, args: string[]) : Promise<string> {
// const txid = args[0];
// return Promise.all([network.getBlockHeight(), network.getTransactionInfo(txid)])
// .then(([blockHeight, txInfo]) => {
// return JSONStringify({
// 'blockHeight': txInfo.block_height,
// 'confirmations': blockHeight - txInfo.block_height + 1
// });
// })
// .catch((e) => {
// if (e.message.toLowerCase() === 'unconfirmed transaction') {
// return JSONStringify({
// 'blockHeight': 'unconfirmed',
// 'confirmations': 0
// });
// }
// else {
// throw e;
// }
// });
// }
/*
* Get the address of a private key
* args:
* @private_key (string) the hex-encoded private key or key bundle
*/
function getKeyAddress(network: CLINetworkAdapter, args: string[]): Promise<string> {
const privateKey = decodePrivateKey(args[0]);
return Promise.resolve().then(() => {
const addr = getPrivateKeyAddress(network, privateKey);
return JSONStringify({
BTC: addr,
STACKS: c32check.b58ToC32(addr),
});
});
}
/*
* Get a file from Gaia.
* args:
* @username (string) the blockstack ID of the user who owns the data
* @origin (string) the application origin
* @path (string) the file to read
* @appPrivateKey (string) OPTIONAL: the app private key to decrypt/verify with
* @decrypt (string) OPTINOAL: if '1' or 'true', then decrypt
* @verify (string) OPTIONAL: if '1' or 'true', then search for and verify a signature file
* along with the data
*/
function gaiaGetFile(network: CLINetworkAdapter, args: string[]): Promise<string | Buffer> {
const username = args[0];
const origin = args[1];
const path = args[2];
let appPrivateKey = args[3];
let decrypt = false;
let verify = false;
if (!!appPrivateKey && args.length > 4 && !!args[4]) {
decrypt = args[4].toLowerCase() === 'true' || args[4].toLowerCase() === '1';
}
if (!!appPrivateKey && args.length > 5 && !!args[5]) {
verify = args[5].toLowerCase() === 'true' || args[5].toLowerCase() === '1';
}
if (!appPrivateKey) {
// make a fake private key (it won't be used)
appPrivateKey = 'fda1afa3ff9ef25579edb5833b825ac29fae82d03db3f607db048aae018fe882';
}
// force mainnet addresses
blockstack.config.network.layer1 = bitcoin.networks.bitcoin;
return gaiaAuth(network, appPrivateKey, null)
.then((_userData: UserData) =>
blockstack.getFile(path, {
decrypt: decrypt,
verify: verify,
app: origin,
username: username,
})
)
.then((data: ArrayBuffer | Buffer | string) => {
if (data instanceof ArrayBuffer) {
return Buffer.from(data);
} else {
return data;
}
});
}
/*
* Put a file into a Gaia hub
* args:
* @hubUrl (string) the URL to the write endpoint of the gaia hub
* @appPrivateKey (string) the private key used to authenticate to the gaia hub
* @dataPath (string) the path (on disk) to the data to store
* @gaiaPath (string) the path (in Gaia) where the data will be stored
* @encrypt (string) OPTIONAL: if '1' or 'true', then encrypt the file
* @sign (string) OPTIONAL: if '1' or 'true', then sign the file and store the signature too.
*/
function gaiaPutFile(network: CLINetworkAdapter, args: string[]): Promise<string> {
const hubUrl = args[0];
const appPrivateKey = args[1];
const dataPath = args[2];
const gaiaPath = path.normalize(args[3].replace(/^\/+/, ''));
let encrypt = false;
let sign = false;
if (args.length > 4 && !!args[4]) {
encrypt = args[4].toLowerCase() === 'true' || args[4].toLowerCase() === '1';
}
if (args.length > 5 && !!args[5]) {
sign = args[5].toLowerCase() === 'true' || args[5].toLowerCase() === '1';
}
const data = fs.readFileSync(dataPath);
// force mainnet addresses
// TODO
blockstack.config.network.layer1 = bitcoin.networks.bitcoin;
return gaiaAuth(network, appPrivateKey, hubUrl)
.then((_userData: UserData) => {
return blockstack.putFile(gaiaPath, data, { encrypt: encrypt, sign: sign });
})
.then((url: string) => {
return JSONStringify({ urls: [url] });
});
}
/*
* Delete a file in a Gaia hub
* args:
* @hubUrl (string) the URL to the write endpoint of the gaia hub
* @appPrivateKey (string) the private key used to authenticate to the gaia hub
* @gaiaPath (string) the path (in Gaia) to delete
* @wasSigned (string) OPTIONAL: if '1' or 'true'. Delete the signature file as well.
*/
function gaiaDeleteFile(network: CLINetworkAdapter, args: string[]): Promise<string> {
const hubUrl = args[0];
const appPrivateKey = args[1];
const gaiaPath = path.normalize(args[2].replace(/^\/+/, ''));
let wasSigned = false;
if (args.length > 3 && !!args[3]) {
wasSigned = args[3].toLowerCase() === 'true' || args[3].toLowerCase() === '1';
}
// force mainnet addresses
// TODO
blockstack.config.network.layer1 = bitcoin.networks.bitcoin;
return gaiaAuth(network, appPrivateKey, hubUrl)
.then((_userData: UserData) => {
return blockstack.deleteFile(gaiaPath, { wasSigned: wasSigned });
})
.then(() => {
return JSONStringify('ok');
});
}
/*
* List files in a Gaia hub
* args:
* @hubUrl (string) the URL to the write endpoint of the gaia hub
* @appPrivateKey (string) the private key used to authenticate to the gaia hub
*/
function gaiaListFiles(network: CLINetworkAdapter, args: string[]): Promise<string> {
const hubUrl = args[0];
const appPrivateKey = args[1];
// force mainnet addresses
// TODO
let count = 0;
blockstack.config.network.layer1 = bitcoin.networks.bitcoin;
return gaiaAuth(network, canonicalPrivateKey(appPrivateKey), hubUrl)
.then((_userData: UserData) => {
return blockstack.listFiles((name: string) => {
// print out incrementally
console.log(name);
count += 1;
return true;
});
})
.then(() => JSONStringify(count));
}
/*
* Group array items into batches
*/
function batchify<T>(input: T[], batchSize: number = 50): T[][] {
const output = [];
let currentBatch = [];
for (let i = 0; i < input.length; i++) {
currentBatch.push(input[i]);
if (currentBatch.length >= batchSize) {
output.push(currentBatch);
currentBatch = [];
}
}
if (currentBatch.length > 0) {
output.push(currentBatch);
}
return output;
}
/*
* Dump all files from a Gaia hub bucket to a directory on disk.
* args:
* @nameOrIDAddress (string) the name or ID address that owns the bucket to dump
* @appOrigin (string) the application for which to dump data
* @hubUrl (string) the URL to the write endpoint of the gaia hub
* @mnemonic (string) the 12-word phrase or ciphertext
* @dumpDir (string) the directory to hold the dumped files
*/
function gaiaDumpBucket(network: CLINetworkAdapter, args: string[]): Promise<string> {
const nameOrIDAddress = args[0];
const appOrigin = args[1];
const hubUrl = args[2];
const mnemonicOrCiphertext = args[3];
let dumpDir = args[4];
if (dumpDir.length === 0) {
throw new Error('Invalid directory (not given)');
}
if (dumpDir[0] !== '/') {
// relative path. make absolute
const cwd = fs.realpathSync('.');
dumpDir = path.normalize(`${cwd}/${dumpDir}`);
}
mkdirs(dumpDir);
function downloadFile(hubConfig: GaiaHubConfig, fileName: string): Promise<void> {
const gaiaReadUrl = `${hubConfig.url_prefix.replace(/\/+$/, '')}/${hubConfig.address}`;
const fileUrl = `${gaiaReadUrl}/${fileName}`;
const destPath = `${dumpDir}/${fileName.replace(/\//g, '\\x2f')}`;
console.log(`Download ${fileUrl} to ${destPath}`);
return fetch(fileUrl)
.then((resp: any) => {
if (resp.status !== 200) {
throw new Error(`Bad status code for ${fileUrl}: ${resp.status}`);
}
// javascript can be incredibly stupid at fetching data despite being a Web language...
const contentType = resp.headers.get('Content-Type');
if (
contentType === null ||
contentType.startsWith('text') ||
contentType === 'application/json'
) {
return resp.text();
} else {
return resp.arrayBuffer();
}
})
.then((filebytes: Buffer | ArrayBuffer) => {
return new Promise((resolve, reject) => {
try {
fs.writeFileSync(destPath, Buffer.from(filebytes), { encoding: null, mode: 0o660 });
resolve();
} catch (e) {
reject(e);
}
});
});
}
// force mainnet addresses
// TODO: better way of doing this
blockstack.config.network.layer1 = bitcoin.networks.bitcoin;
const fileNames: string[] = [];
let gaiaHubConfig: GaiaHubConfig;
let appPrivateKey: string;
let ownerPrivateKey: string;
return getIDAppKeys(network, nameOrIDAddress, appOrigin, mnemonicOrCiphertext)
.then((keyInfo: IDAppKeys) => {
appPrivateKey = keyInfo.appPrivateKey;
ownerPrivateKey = keyInfo.ownerPrivateKey;
return gaiaAuth(network, appPrivateKey, hubUrl, ownerPrivateKey);
})
.then((_userData: UserData) => {
return gaiaConnect(network, hubUrl, appPrivateKey);
})
.then((hubConfig: GaiaHubConfig) => {
gaiaHubConfig = hubConfig;
return blockstack.listFiles(name => {
fileNames.push(name);
return true;
});
})
.then((fileCount: number) => {
console.log(`Download ${fileCount} files...`);
const fileBatches: string[][] = batchify(fileNames);
let filePromiseChain: Promise<any> = Promise.resolve();
for (let i = 0; i < fileBatches.length; i++) {
const filePromises = fileBatches[i].map(fileName => downloadFile(gaiaHubConfig, fileName));
const batchPromise = Promise.all(filePromises);
filePromiseChain = filePromiseChain.then(() => batchPromise);
}
return filePromiseChain.then(() => JSONStringify(fileCount));
});
}
/*
* Restore all of the files in a Gaia bucket dump to a new Gaia hub
* args:
* @nameOrIDAddress (string) the name or ID address that owns the bucket to dump
* @appOrigin (string) the origin of the app for which to restore data
* @hubUrl (string) the URL to the write endpoint of the new gaia hub
* @mnemonic (string) the 12-word phrase or ciphertext
* @dumpDir (string) the directory to hold the dumped files
*/
function gaiaRestoreBucket(network: CLINetworkAdapter, args: string[]): Promise<string> {
const nameOrIDAddress = args[0];
const appOrigin = args[1];
const hubUrl = args[2];
const mnemonicOrCiphertext = args[3];
let dumpDir = args[4];
if (dumpDir.length === 0) {
throw new Error('Invalid directory (not given)');
}
if (dumpDir[0] !== '/') {
// relative path. make absolute
const cwd = fs.realpathSync('.');
dumpDir = path.normalize(`${cwd}/${dumpDir}`);
}
const fileList = fs.readdirSync(dumpDir);
const fileBatches = batchify(fileList, 10);
let appPrivateKey: string;
let ownerPrivateKey: string;
// force mainnet addresses
// TODO better way of doing this
blockstack.config.network.layer1 = bitcoin.networks.bitcoin;
return getIDAppKeys(network, nameOrIDAddress, appOrigin, mnemonicOrCiphertext)
.then((keyInfo: IDAppKeys) => {
appPrivateKey = keyInfo.appPrivateKey;
ownerPrivateKey = keyInfo.ownerPrivateKey;
return gaiaAuth(network, appPrivateKey, hubUrl, ownerPrivateKey);
})
.then((_userData: UserData) => {
let uploadPromise: Promise<any> = Promise.resolve();
for (let i = 0; i < fileBatches.length; i++) {
const uploadBatchPromises = fileBatches[i].map((fileName: string) => {
const filePath = path.join(dumpDir, fileName);
const dataBuf = fs.readFileSync(filePath);
const gaiaPath = fileName.replace(/\\x2f/g, '/');
return blockstack
.putFile(gaiaPath, dataBuf, { encrypt: false, sign: false })
.then((url: string) => {
console.log(`Uploaded ${fileName} to ${url}`);
});
});
uploadPromise = uploadPromise.then(() => Promise.all(uploadBatchPromises));
}
return uploadPromise;
})
.then(() => JSONStringify(fileList.length));
}
/*
* Set the Gaia hub for an application for a blockstack ID.
* args:
* @blockstackID (string) the blockstack ID of the user
* @profileHubUrl (string) the URL to the write endpoint of the user's profile gaia hub
* @appOrigin (string) the application's Origin
* @hubUrl (string) the URL to the write endpoint of the app's gaia hub
* @mnemonic (string) the 12-word backup phrase, or the ciphertext of it
*/
async function gaiaSetHub(network: CLINetworkAdapter, args: string[]): Promise<string> {
network.setCoerceMainnetAddress(true);
const blockstackID = args[0];
const ownerHubUrl = args[1];
const appOrigin = args[2];
const hubUrl = args[3];
const mnemonicPromise = getBackupPhrase(args[4]);
const nameInfoPromise = getNameInfoEasy(network, blockstackID).then(
(nameInfo: NameInfoType | null) => {
if (!nameInfo) {
throw new Error('Name not found');
}
return nameInfo;
}
);
const profilePromise = blockstack.lookupProfile(blockstackID);
const [nameInfo, nameProfile, mnemonic]: [NameInfoType, any, string] = await Promise.all([
nameInfoPromise,
profilePromise,
mnemonicPromise,
]);
if (!nameProfile) {
throw new Error('No profile found');
}
if (!nameInfo) {
throw new Error('Name not found');
}
if (!nameInfo.zonefile) {
throw new Error('No zone file found');
}
if (!nameProfile.apps) {
nameProfile.apps = {};
}
// get owner ID-address
const ownerAddress = network.coerceMainnetAddress(nameInfo.address);
const idAddress = `ID-${ownerAddress}`;
// get owner and app key info
const appKeyInfo = await getApplicationKeyInfo(network, mnemonic, idAddress, appOrigin);
const ownerKeyInfo = await getOwnerKeyInfo(network, mnemonic, appKeyInfo.ownerKeyIndex);
// do we already have an address set for this app?
let existingAppAddress: string | null = null;
let appPrivateKey: string;
try {
existingAppAddress = getGaiaAddressFromProfile(network, nameProfile, appOrigin);
appPrivateKey = extractAppKey(network, appKeyInfo, existingAppAddress);
} catch (e) {
console.log(`No profile application entry for ${appOrigin}`);
appPrivateKey = extractAppKey(network, appKeyInfo);
}
appPrivateKey = `${canonicalPrivateKey(appPrivateKey)}01`;
const appAddress = network.coerceMainnetAddress(getPrivateKeyAddress(network, appPrivateKey));
if (existingAppAddress && appAddress !== existingAppAddress) {
throw new Error(`BUG: ${existingAppAddress} !== ${appAddress}`);
}
const profile = nameProfile;
const ownerPrivateKey = ownerKeyInfo.privateKey;
const ownerGaiaHubPromise = gaiaConnect(network, ownerHubUrl, ownerPrivateKey);
const appGaiaHubPromise = gaiaConnect(network, hubUrl, appPrivateKey);
const [ownerHubConfig, appHubConfig]: [GaiaHubConfig, GaiaHubConfig] = await Promise.all([
ownerGaiaHubPromise,
appGaiaHubPromise,
]);
if (!ownerHubConfig.url_prefix) {
throw new Error('Invalid owner hub config: no url_prefix defined');
}
if (!appHubConfig.url_prefix) {
throw new Error('Invalid app hub config: no url_prefix defined');
}
const gaiaReadUrl = appHubConfig.url_prefix.replace(/\/+$/, '');
const newAppEntry: Record<string, string> = {};
newAppEntry[appOrigin] = `${gaiaReadUrl}/${appAddress}/`;
const apps = Object.assign({}, profile.apps ? profile.apps : {}, newAppEntry);
profile.apps = apps;
// sign the new profile
const signedProfile = makeProfileJWT(profile, ownerPrivateKey);
const profileUrls: {
dataUrls?: string[] | null;
error?: string | null;
} = await gaiaUploadProfileAll(
network,
[ownerHubUrl],
signedProfile,
ownerPrivateKey,
blockstackID
);
if (profileUrls.error) {
return JSONStringify({
error: profileUrls.error,
});
} else {
return JSONStringify({
profileUrls: profileUrls.dataUrls!,
});
}
}
/*
* Convert an address between mainnet and testnet, and between
* base58check and c32check.
* args:
* @address (string) the input address. can be in any format
*/
function addressConvert(network: CLINetworkAdapter, args: string[]): Promise<string> {
const addr = args[0];
let b58addr: string;
let testnetb58addr: string;
if (addr.match(STACKS_ADDRESS_PATTERN)) {
b58addr = c32check.c32ToB58(addr);
} else if (addr.match(/[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+/)) {
b58addr = addr;
} else {
throw new Error(`Unrecognized address ${addr}`);
}
if (isTestnetAddress(b58addr)) {
testnetb58addr = b58addr;
} else if (network.isTestnet()) {
testnetb58addr = network.coerceAddress(b58addr);
}
return Promise.resolve().then(() => {
const mainnetb58addr = network.coerceMainnetAddress(b58addr);
const result: any = {
mainnet: {
STACKS: c32check.b58ToC32(mainnetb58addr),
BTC: mainnetb58addr,
},
testnet: undefined,
};
if (testnetb58addr) {
result.testnet = {
STACKS: c32check.b58ToC32(testnetb58addr),
BTC: testnetb58addr,
};
}
return JSONStringify(result);
});
}
/*
* Run an authentication daemon on a given port.
* args:
* @gaiaHubUrl (string) the write endpoint of your app Gaia hub, where app data will be stored
* @mnemonic (string) your 12-word phrase, optionally encrypted. If encrypted, then
* a password will be prompted.
* @profileGaiaHubUrl (string) the write endpoint of your profile Gaia hub, where your profile
* will be stored (optional)
* @port (number) the port to listen on (optional)
*/
function authDaemon(network: CLINetworkAdapter, args: string[]): Promise<string> {
const gaiaHubUrl = args[0];
const mnemonicOrCiphertext = args[1];
let port = 3000; // default port
let profileGaiaHub = gaiaHubUrl;
if (args.length > 2 && !!args[2]) {
profileGaiaHub = args[2];
}
if (args.length > 3 && !!args[3]) {
port = parseInt(args[3]);
}
if (port < 0 || port > 65535) {
return Promise.resolve().then(() => JSONStringify({ error: 'Invalid port' }));
}
const mnemonicPromise = getBackupPhrase(mnemonicOrCiphertext);
return mnemonicPromise
.then((mnemonic: string) => {
noExit = true;
// load up all of our identity addresses, profiles, profile URLs, and Gaia connections
const authServer = express();
authServer.use(cors());
authServer.get(/^\/auth\/*$/, (req: express.Request, res: express.Response) => {
void handleAuth(network, mnemonic, gaiaHubUrl, profileGaiaHub, port, req, res);
});
authServer.get(/^\/signin\/*$/, (req: express.Request, res: express.Response) => {
void handleSignIn(network, mnemonic, gaiaHubUrl, profileGaiaHub, req, res);
});
authServer.listen(port, () => console.log(`Authentication server started on ${port}`));
return 'Press Ctrl+C to exit';
})
.catch((e: Error) => {
return JSONStringify({ error: e.message });
});
}
/*
* Encrypt a backup phrase
* args:
* @backup_phrase (string) the 12-word phrase to encrypt
* @password (string) the password (will be interactively prompted if not given)
*/
// TODO: fix: network is never used
// @ts-ignore
function encryptMnemonic(network: CLINetworkAdapter, args: string[]): Promise<string> {
const mnemonic = args[0];
if (mnemonic.split(/ +/g).length !== 12) {
throw new Error('Invalid backup phrase: must be 12 words');
}
const passwordPromise: Promise<string> = new Promise((resolve, reject) => {
let pass = '';
if (args.length === 2 && !!args[1]) {
pass = args[1];
resolve(pass);
} else {
if (!process.stdin.isTTY) {
// password must be given as an argument
const errMsg = 'Password argument required on non-interactive mode';
reject(new Error(errMsg));
} else {
// prompt password
getpass('Enter password: ', (pass1: string) => {
getpass('Enter password again: ', (pass2: string) => {
if (pass1 !== pass2) {
const errMsg = 'Passwords do not match';
reject(new Error(errMsg));
} else {
resolve(pass1);
}
});
});
}
}
});
return passwordPromise
.then((pass: string) => encryptBackupPhrase(mnemonic, pass))
.then((cipherTextBuffer: Buffer) => cipherTextBuffer.toString('base64'))
.catch((e: Error) => {
return JSONStringify({ error: e.message });
});
}
/* Decrypt a backup phrase
* args:
* @encrypted_backup_phrase (string) the encrypted base64-encoded backup phrase
* @password 9string) the password (will be interactively prompted if not given)
*/
// TODO: fix: network is never used
// @ts-ignore
function decryptMnemonic(network: CLINetworkAdapter, args: string[]): Promise<string> {
const ciphertext = args[0];
const passwordPromise: Promise<string> = new Promise((resolve, reject) => {
if (args.length === 2 && !!args[1]) {
const pass = args[1];
resolve(pass);
} else {
if (!process.stdin.isTTY) {
// password must be given
reject(new Error('Password argument required in non-interactive mode'));
} else {
// prompt password
getpass('Enter password: ', p => {
resolve(p);
});
}
}
});
return passwordPromise
.then((pass: string) => decryptBackupPhrase(Buffer.from(ciphertext, 'base64'), pass))
.catch((e: Error) => {
return JSONStringify({
error:
'Failed to decrypt (wrong password or corrupt ciphertext), ' + `details: ${e.message}`,
});
});
}
async function stackingStatus(network: CLINetworkAdapter, args: string[]): Promise<string> {
const stxAddress = args[0];
const txNetwork = network.isMainnet() ? new StacksMainnet() : new StacksTestnet();
const stacker = new StackingClient(stxAddress, txNetwork);
return stacker
.getStatus()
.then((status: StackerInfo) => {
if (status.stacked) {
return {
amount_microstx: status.details.amount_microstx,
first_reward_cycle: status.details.first_reward_cycle,
lock_period: status.details.lock_period,
unlock_height: status.details.unlock_height,
pox_address: {
version: status.details.pox_address.version.toString('hex'),
hashbytes: status.details.pox_address.hashbytes.toString('hex'),
},
};
} else {
return 'Account not actively participating in Stacking';
}
})
.catch((error: any) => {
return error.toString();
});
}
async function canStack(network: CLINetworkAdapter, args: string[]): Promise<string> {
const amount = BigInt(args[0]);
const cycles = Number(args[1]);
const poxAddress = args[2];
const stxAddress = args[3];
const txNetwork = network.isMainnet() ? new StacksMainnet() : new StacksTestnet();
const apiConfig = new Configuration({
fetchApi: crossfetch,
basePath: txNetwork.coreApiUrl,
});
const accounts = new AccountsApi(apiConfig);
const balancePromise = accounts.getAccountBalance({
principal: stxAddress,
});
const stacker = new StackingClient(stxAddress, txNetwork);
const poxInfoPromise = stacker.getPoxInfo();
const stackingEligiblePromise = stacker.canStack({ poxAddress, cycles });
return Promise.all([balancePromise, poxInfoPromise, stackingEligiblePromise])
.then(([balance, poxInfo, stackingEligible]) => {
const minAmount = BigInt(poxInfo.min_amount_ustx);
const balanceBN = BigInt(balance.stx.balance);
if (minAmount > amount) {
throw new Error(
`Stacking amount less than required minimum of ${minAmount.toString()} microstacks`
);
}
if (amount > balanceBN) {
throw new Error(
`Stacking amount greater than account balance of ${balanceBN.toString()} microstacks`
);
}
if (!stackingEligible.eligible) {
throw new Error(`Account cannot participate in stacking. ${stackingEligible.reason}`);
}
return stackingEligible;
})
.catch(error => {
return error;
});
}
async function stack(network: CLINetworkAdapter, args: string[]): Promise<string> {
const amount = BigInt(args[0]);
const cycles = Number(args[1]);
const poxAddress = args[2];
const privateKey = args[3];
// let fee = new BN(0);
// let nonce = new BN(0);
// if (args.length > 3 && !!args[4]) {
// fee = new BN(args[4]);
// }
// if (args.length > 4 && !!args[5]) {
// nonce = new BN(args[5]);
// }
const txNetwork = network.isMainnet() ? new StacksMainnet() : new StacksTestnet();
const txVersion = txNetwork.isMainnet() ? TransactionVersion.Mainnet : TransactionVersion.Testnet;
const apiConfig = new Configuration({
fetchApi: crossfetch,
basePath: txNetwork.coreApiUrl,
});
const accounts = new AccountsApi(apiConfig);
const stxAddress = getAddressFromPrivateKey(privateKey, txVersion);
const balancePromise = accounts.getAccountBalance({
principal: stxAddress,
});
const stacker = new StackingClient(stxAddress, txNetwork);
const poxInfoPromise = stacker.getPoxInfo();
const coreInfoPromise = stacker.getCoreInfo();
const stackingEligiblePromise = stacker.canStack({ poxAddress, cycles });
return Promise.all([balancePromise, poxInfoPromise, coreInfoPromise, stackingEligiblePromise])
.then(([balance, poxInfo, coreInfo, stackingEligible]) => {
const minAmount = BigInt(poxInfo.min_amount_ustx);
const balanceBN = BigInt(balance.stx.balance);
const burnChainBlockHeight = coreInfo.burn_block_height;
const startBurnBlock = burnChainBlockHeight + 3;
if (minAmount > amount) {
throw new Error(
`Stacking amount less than required minimum of ${minAmount.toString()} microstacks`
);
}
if (amount > balanceBN) {
throw new Error(
`Stacking amount greater than account balance of ${balanceBN.toString()} microstacks`
);
}
if (!stackingEligible.eligible) {
throw new Error(`Account cannot participate in stacking. ${stackingEligible.reason}`);
}
return stacker.stack({
amountMicroStx: amount,
poxAddress,
cycles,
privateKey,
burnBlockHeight: startBurnBlock,
});
})
.then((response: TxBroadcastResult) => {
if (response.hasOwnProperty('error')) {
return response;
}
return {
txid: `0x${response.txid}`,
transaction: generateExplorerTxPageUrl(response.txid, txNetwork),
};
})
.catch(error => {
return error;
});
}
async function register(network: CLINetworkAdapter, args: string[]): Promise<string> {
const fullyQualifiedName = args[0];
const privateKey = args[1];
const salt = args[2];
const zonefile = args[3];
const publicKey = publicKeyToString(pubKeyfromPrivKey(privateKey));
const txNetwork = network.isMainnet() ? new StacksMainnet() : new StacksTestnet();
const unsignedTransaction = await buildRegisterNameTx({
fullyQualifiedName,
publicKey,
salt,
zonefile,
network: txNetwork,
});
const signer = new TransactionSigner(unsignedTransaction);
signer.signOrigin(createStacksPrivateKey(privateKey));
return broadcastTransaction(signer.transaction, txNetwork)
.then((response: TxBroadcastResult) => {
if (response.hasOwnProperty('error')) {
return response;
}
return {
txid: `0x${response.txid}`,
transaction: generateExplorerTxPageUrl(response.txid, txNetwork),
};
})
.catch(error => {
return error;
});
}
async function preorder(network: CLINetworkAdapter, args: string[]): Promise<string> {
const fullyQualifiedName = args[0];
const privateKey = args[1];
const salt = args[2];
const stxToBurn = args[3];
const publicKey = publicKeyToString(pubKeyfromPrivKey(privateKey));
const txNetwork = network.isMainnet() ? new StacksMainnet() : new StacksTestnet();
const unsignedTransaction = await buildPreorderNameTx({
fullyQualifiedName,
publicKey,
salt,
stxToBurn,
network: txNetwork,
});
const signer = new TransactionSigner(unsignedTransaction);
signer.signOrigin(createStacksPrivateKey(privateKey));
return broadcastTransaction(signer.transaction, txNetwork)
.then((response: TxBroadcastResult) => {
if (response.hasOwnProperty('error')) {
return response;
}
return {
txid: `0x${response.txid}`,
transaction: generateExplorerTxPageUrl(response.txid, txNetwork),
};
})
.catch(error => {
return error;
});
}
function faucetCall(_: CLINetworkAdapter, args: string[]): Promise<string> {
const address = args[0];
// console.log(address);
const apiConfig = new Configuration({
fetchApi: crossfetch,
basePath: 'https://stacks-node-api.testnet.stacks.co',
});
const faucets = new FaucetsApi(apiConfig);
return faucets
.runFaucetStx({ address })
.then((faucetTx: any) => {
return JSONStringify({
txid: faucetTx.txId!,
transaction: generateExplorerTxPageUrl(
faucetTx.txId!.replace(/^0x/, ''),
new StacksTestnet()
),
});
})
.catch((error: any) => error.toString());
}
/* Print out all documentation on usage in JSON
*/
type DocsArgsType = {
name: string;
type: string;
value: string;
format: string;
};
type FormattedDocsType = {
command: string;
args: DocsArgsType[];
usage: string;
group: string;
};
function printDocs(_network: CLINetworkAdapter, _args: string[]): Promise<string> {
return Promise.resolve().then(() => {
const formattedDocs: FormattedDocsType[] = [];
const commandNames: string[] = Object.keys(CLI_ARGS.properties);
for (let i = 0; i < commandNames.length; i++) {
const commandName = commandNames[i];
const args: DocsArgsType[] = [];
const usage = CLI_ARGS.properties[commandName].help;
const group = CLI_ARGS.properties[commandName].group;
for (let j = 0; j < CLI_ARGS.properties[commandName].items.length; j++) {
const argItem = CLI_ARGS.properties[commandName].items[j];
args.push({
name: argItem.name,
type: argItem.type,
value: argItem.realtype,
format: argItem.pattern ? argItem.pattern : '.+',
} as DocsArgsType);
}
formattedDocs.push({
command: commandName,
args: args,
usage: usage,
group: group,
} as FormattedDocsType);
}
return JSONStringify(formattedDocs);
});
}
type CommandFunction = (network: CLINetworkAdapter, args: string[]) => Promise<string | Buffer>;
/*
* Decrypt a backup phrase
* args:
* @p
/*
* Global set of commands
*/
const COMMANDS: Record<string, CommandFunction> = {
authenticator: authDaemon,
// 'announce': announce,
balance: balance,
can_stack: canStack,
call_contract_func: contractFunctionCall,
call_read_only_contract_func: readOnlyContractFunctionCall,
convert_address: addressConvert,
decrypt_keychain: decryptMnemonic,
deploy_contract: contractDeploy,
docs: printDocs,
encrypt_keychain: encryptMnemonic,
gaia_deletefile: gaiaDeleteFile,
gaia_dump_bucket: gaiaDumpBucket,
gaia_getfile: gaiaGetFile,
gaia_listfiles: gaiaListFiles,
gaia_putfile: gaiaPutFile,
gaia_restore_bucket: gaiaRestoreBucket,
gaia_sethub: gaiaSetHub,
get_address: getKeyAddress,
get_account_history: getAccountHistory,
get_app_keys: getAppKeys,
get_owner_keys: getOwnerKeys,
get_payment_key: getPaymentKey,
get_stacks_wallet_key: getStacksWalletKey,
make_keychain: makeKeychain,
profile_sign: profileSign,
profile_store: profileStore,
profile_verify: profileVerify,
// 'send_btc': sendBTC,
register: register,
tx_preorder: preorder,
send_tokens: sendTokens,
stack: stack,
stacking_status: stackingStatus,
faucet: faucetCall,
};
/*
* CLI main entry point
*/
export function CLIMain() {
const argv = process.argv;
const opts = getCLIOpts(argv);
const cmdArgs: any = checkArgs(
CLIOptAsStringArray(opts, '_') ? CLIOptAsStringArray(opts, '_')! : []
);
if (!cmdArgs.success) {
if (cmdArgs.error) {
console.log(cmdArgs.error);
}
if (cmdArgs.usage) {
if (cmdArgs.command) {
console.log(makeCommandUsageString(cmdArgs.command));
console.log('Use "help" to list all commands.');
} else {
console.log(USAGE);
console.log(makeAllCommandsList());
}
}
process.exit(1);
} else {
txOnly = CLIOptAsBool(opts, 'x');
estimateOnly = CLIOptAsBool(opts, 'e');
safetyChecks = !CLIOptAsBool(opts, 'U');
receiveFeesPeriod = opts['N'] ? parseInt(CLIOptAsString(opts, 'N')!) : receiveFeesPeriod;
gracePeriod = opts['G'] ? parseInt(CLIOptAsString(opts, 'N')!) : gracePeriod;
const maxIDSearchIndex = opts['M']
? parseInt(CLIOptAsString(opts, 'M')!)
: getMaxIDSearchIndex();
setMaxIDSearchIndex(maxIDSearchIndex);
const debug = CLIOptAsBool(opts, 'd');
const consensusHash = CLIOptAsString(opts, 'C');
const integration_test = CLIOptAsBool(opts, 'i');
const testnet = CLIOptAsBool(opts, 't');
const localnet = CLIOptAsBool(opts, 'l');
const magicBytes = CLIOptAsString(opts, 'm');
const apiUrl = CLIOptAsString(opts, 'H');
const transactionBroadcasterUrl = CLIOptAsString(opts, 'T');
const nodeAPIUrl = CLIOptAsString(opts, 'I');
const utxoUrl = CLIOptAsString(opts, 'X');
const bitcoindUsername = CLIOptAsString(opts, 'u');
const bitcoindPassword = CLIOptAsString(opts, 'p');
if (integration_test) {
BLOCKSTACK_TEST = integration_test;
}
const configPath = CLIOptAsString(opts, 'c')
? CLIOptAsString(opts, 'c')
: testnet
? DEFAULT_CONFIG_TESTNET_PATH
: DEFAULT_CONFIG_PATH;
const namespaceBurnAddr = CLIOptAsString(opts, 'B');
const feeRate = CLIOptAsString(opts, 'F') ? parseInt(CLIOptAsString(opts, 'F')!) : 0;
const priceToPay = CLIOptAsString(opts, 'P') ? CLIOptAsString(opts, 'P') : '0';
const priceUnits = CLIOptAsString(opts, 'D');
const networkType = testnet ? 'testnet' : localnet ? 'localnet' : 'mainnet';
const configData = loadConfig(configPath!, networkType);
if (debug) {
configData.logConfig.level = 'debug';
} else {
configData.logConfig.level = 'info';
}
if (bitcoindUsername) {
configData.bitcoindUsername = bitcoindUsername;
}
if (bitcoindPassword) {
configData.bitcoindPassword = bitcoindPassword;
}
if (utxoUrl) {
configData.utxoServiceUrl = utxoUrl;
}
winston.configure({
level: configData.logConfig.level,
transports: [new winston.transports.Console(configData.logConfig)],
});
const cliOpts: CLI_NETWORK_OPTS = {
consensusHash: consensusHash ? consensusHash : null,
feeRate: feeRate ? feeRate : null,
namespaceBurnAddress: namespaceBurnAddr ? namespaceBurnAddr : null,
priceToPay: priceToPay ? priceToPay : null,
priceUnits: priceUnits ? priceUnits : null,
receiveFeesPeriod: receiveFeesPeriod ? receiveFeesPeriod : null,
gracePeriod: gracePeriod ? gracePeriod : null,
altAPIUrl: apiUrl ? apiUrl : configData.blockstackAPIUrl,
altTransactionBroadcasterUrl: transactionBroadcasterUrl
? transactionBroadcasterUrl
: configData.broadcastServiceUrl,
nodeAPIUrl: nodeAPIUrl ? nodeAPIUrl : configData.blockstackNodeUrl,
};
// wrap command-line options
const wrappedNetwork = getNetwork(
configData,
!!BLOCKSTACK_TEST || !!integration_test || !!testnet || !!localnet
);
const blockstackNetwork = new CLINetworkAdapter(wrappedNetwork, cliOpts);
if (magicBytes) {
// blockstackNetwork.MAGIC_BYTES = magicBytes;
}
// blockstack.config.network = blockstackNetwork;
blockstack.config.logLevel = 'error';
if (cmdArgs.command === 'help') {
console.log(makeCommandUsageString(cmdArgs.args[0]));
process.exit(0);
}
const method = COMMANDS[cmdArgs.command];
let exitcode = 0;
method(blockstackNetwork, cmdArgs.args)
.then((result: string | Buffer) => {
try {
// if this is a JSON object with 'status', set the exit code
if (result instanceof Buffer) {
return result;
} else {
const resJson: any = JSON.parse(result);
if (resJson.hasOwnProperty('status') && !resJson.status) {
exitcode = 1;
}
return result;
}
} catch (e) {
return result;
}
})
.then((result: string | Buffer) => {
if (result instanceof Buffer) {
process.stdout.write(result);
} else {
console.log(result);
}
})
.then(() => {
if (!noExit) {
process.exit(exitcode);
}
})
.catch((e: Error) => {
console.error(e.stack);
console.error(e.message);
if (!noExit) {
process.exit(1);
}
});
}
}
/* test only exports */
export const testables =
process.env.NODE_ENV === 'test'
? {
addressConvert,
contractFunctionCall,
makeKeychain,
getStacksWalletKey,
register,
preorder,
}
: undefined; | the_stack |
import {
DataState,
PipelineExampleNames,
pipelineTestData,
} from '../../../../../test-data/pipeline-data';
import { PipelineKind, PipelineRunKind } from '../../../../../types';
import { preferredNameAnnotation, TektonResourceLabel, VolumeTypes } from '../../../const';
import { CommonPipelineModalFormikValues } from '../types';
import {
convertPipelineToModalData,
getPipelineName,
getPipelineRunData,
getPipelineRunFromForm,
migratePipelineRun,
} from '../utils';
const samplePipeline = pipelineTestData[PipelineExampleNames.SIMPLE_PIPELINE].pipeline;
const samplePipelineRun =
pipelineTestData[PipelineExampleNames.SIMPLE_PIPELINE].pipelineRuns[DataState.SUCCESS];
const pipelineRunData = (pipeline: PipelineKind): PipelineRunKind => ({
apiVersion: pipeline.apiVersion,
kind: 'PipelineRun',
metadata: {
namespace: pipeline.metadata.namespace,
name: expect.stringMatching(new RegExp(`${pipeline.metadata.name}-[a-z0-9]{6}`)),
labels: { [TektonResourceLabel.pipeline]: pipeline.metadata.name },
},
spec: {
pipelineRef: { name: pipeline.metadata.name },
},
});
describe('PipelineAction testing migratePipelineRun', () => {
it('expect migratePipelineRun to do nothing when there is no migration needed', () => {
// Same instance should be returned if there was no need for a migration
expect(migratePipelineRun(samplePipelineRun)).toEqual(samplePipelineRun);
});
it('expect migratePipelineRun to handle serviceAccount to serviceAccountName migration (Operator 0.9.x)', () => {
type OldPipelineRun = PipelineRunKind & {
spec: {
serviceAccount: string;
};
};
const serviceAccountValue = 'serviceAccountValue';
const plr: OldPipelineRun = {
...samplePipelineRun,
spec: {
...samplePipelineRun.spec,
serviceAccount: serviceAccountValue,
},
};
const result: PipelineRunKind = migratePipelineRun(plr);
// Should be a new instance
expect(result).not.toEqual(plr);
// The value should have moved
expect(result.spec.serviceAccountName).toEqual(serviceAccountValue);
expect((result as OldPipelineRun).spec.serviceAccount).toBeUndefined();
// Should still have other spec properties
expect(result.spec.pipelineRef).toEqual(samplePipelineRun.spec.pipelineRef);
});
});
describe('getPipelineName', () => {
it('should return null if no argument is provided', () => {
expect(getPipelineName()).toBeNull();
});
it('should return the name from the pipeline metadata if both pipeline and latestRun are provided', () => {
expect(getPipelineName(samplePipeline, samplePipelineRun)).toEqual(
samplePipeline.metadata.name,
);
});
it('should return the name from the pipeline metadata if only pipeline is provided', () => {
expect(getPipelineName(samplePipeline)).toEqual(samplePipeline.metadata.name);
});
it('should return the name from the pipelineRef, if only latestRun is provided and pipelineRef exists', () => {
const pipelineRunWithPipelineRef =
pipelineTestData[PipelineExampleNames.EMBEDDED_PIPELINE_SPEC].pipelineRuns[DataState.SKIPPED];
expect(getPipelineName(undefined, pipelineRunWithPipelineRef)).toEqual(
pipelineRunWithPipelineRef.spec.pipelineRef.name,
);
});
it('should return the name from the latestRun metadata, if only latestRun is provided and annotation does not include the name', () => {
const pipelineRunWithPipelineSpec =
pipelineTestData[PipelineExampleNames.EMBEDDED_PIPELINE_SPEC].pipelineRuns[
DataState.IN_PROGRESS
];
expect(getPipelineName(undefined, pipelineRunWithPipelineSpec)).toEqual(
pipelineRunWithPipelineSpec.metadata.name,
);
});
it('should return the name from the annotations, if only latestRun is provided and annotation includes the name', () => {
const pipelineRunWithAnnotations =
pipelineTestData[PipelineExampleNames.EMBEDDED_PIPELINE_SPEC].pipelineRuns[DataState.SUCCESS];
expect(getPipelineName(undefined, pipelineRunWithAnnotations)).toEqual(
pipelineRunWithAnnotations.metadata.annotations?.[preferredNameAnnotation],
);
});
});
describe('PipelineAction testing getPipelineRunData', () => {
it('expect null to be returned when no arguments are passed', () => {
// Suppress the error log when we don't have pipeline or pipeline run
jest.spyOn(console, 'error').mockImplementation(jest.fn());
const runData = getPipelineRunData();
expect(runData).toBeNull();
// eslint-disable-next-line no-console
(console.error as any).mockRestore();
});
it('expect pipeline run data to be returned when only Pipeline argument is passed', () => {
const runData = getPipelineRunData(samplePipeline);
expect(runData).toMatchObject(pipelineRunData(samplePipeline));
});
it('expect pipeline run data to be returned when only PipelineRun argument is passed', () => {
const runData = getPipelineRunData(null, samplePipelineRun);
expect(runData).toMatchObject(pipelineRunData(samplePipeline));
});
it('expect pipeline run data with generateName if options argument is requests this', () => {
const runData = getPipelineRunData(samplePipeline, null, { generateName: true });
expect(runData).toMatchObject({
...pipelineRunData(samplePipeline),
metadata: { generateName: `${samplePipeline.metadata.name}-` },
});
});
it('should set the annotation for preferredName if the latestRun have neither this annotation nor pipelineRef', () => {
const pipelineRun =
pipelineTestData[PipelineExampleNames.EMBEDDED_PIPELINE_SPEC].pipelineRuns[
DataState.IN_PROGRESS
];
const runData = getPipelineRunData(null, pipelineRun);
expect(runData.metadata.annotations).toMatchObject({
[preferredNameAnnotation]: pipelineRun.metadata.name,
});
});
it('should not set the label for pipeline name if pipeline is not passed and latestRun does not have a pipelineRef', () => {
const pipelineRun =
pipelineTestData[PipelineExampleNames.EMBEDDED_PIPELINE_SPEC].pipelineRuns[
DataState.IN_PROGRESS
];
const runData = getPipelineRunData(null, pipelineRun);
expect(runData.metadata.labels?.[TektonResourceLabel.pipeline]).toBeUndefined();
});
it('should set the label for pipeline name if pipeline is passed', () => {
const runData = getPipelineRunData(samplePipeline);
expect(runData.metadata.labels).toMatchObject({
[TektonResourceLabel.pipeline]: samplePipeline.metadata.name,
});
});
it('should set the label for pipeline name if only latestRun is passed and latestRun has a pipelineRef', () => {
const pipelineRun =
pipelineTestData[PipelineExampleNames.EMBEDDED_PIPELINE_SPEC].pipelineRuns[DataState.SKIPPED];
const runData = getPipelineRunData(null, pipelineRun);
expect(runData.metadata.labels).toMatchObject({
[TektonResourceLabel.pipeline]: pipelineRun.spec.pipelineRef.name,
});
});
it('should not set pipelineRef in the spec if pipeline is not passed and latestRun does not have a pipelineRef', () => {
const pipelineRun =
pipelineTestData[PipelineExampleNames.EMBEDDED_PIPELINE_SPEC].pipelineRuns[
DataState.IN_PROGRESS
];
const runData = getPipelineRunData(null, pipelineRun);
expect(runData.spec.pipelineRef).toBeUndefined();
});
it('should set pipelineRef in the spec if pipeline is passed', () => {
const runData = getPipelineRunData(samplePipeline);
expect(runData.spec.pipelineRef).toMatchObject(samplePipelineRun.spec.pipelineRef);
});
it('should set pipelineRef in the spec if only latestRun is passed and latestRun has a pipelineRef', () => {
const pipelineRun =
pipelineTestData[PipelineExampleNames.EMBEDDED_PIPELINE_SPEC].pipelineRuns[DataState.SKIPPED];
const runData = getPipelineRunData(null, pipelineRun);
expect(runData.spec.pipelineRef).toMatchObject(pipelineRun.spec.pipelineRef);
});
});
describe('PipelineAction testing getPipelineRunFromForm', () => {
it('expect pipeline run data to have a name by default', () => {
const formValues: CommonPipelineModalFormikValues = {
namespace: 'corazon',
parameters: [],
resources: [],
workspaces: [],
};
const labels: { [key: string]: string } = {
anotherlabel: 'another-label-value',
};
const runData = getPipelineRunFromForm(samplePipeline, formValues, labels);
expect(runData).toMatchObject(pipelineRunData(samplePipeline));
});
it('expect pipeline run data to have a generateName if generator option is true', () => {
const formValues: CommonPipelineModalFormikValues = {
namespace: samplePipeline.metadata.namespace,
parameters: [],
resources: [],
workspaces: [],
};
const labels: { [key: string]: string } = {
anotherlabel: 'another-label-value',
};
const runData = getPipelineRunFromForm(samplePipeline, formValues, labels, null, {
generateName: true,
});
const pipelinerun = pipelineRunData(samplePipeline);
expect(runData).toEqual({
...pipelinerun,
metadata: {
namespace: pipelinerun.metadata.namespace,
generateName: `${samplePipeline.metadata.name}-`,
labels: { ...pipelinerun.metadata.labels, ...labels },
annotations: {},
},
spec: {
pipelineRef: { name: samplePipeline.metadata.name },
params: [],
resources: [],
status: null,
workspaces: [],
},
});
});
it('expect pipeline run data to have a parameters if the form data contains parameters', () => {
const formValues: CommonPipelineModalFormikValues = {
namespace: 'corazon',
parameters: [
{
name: 'ParameterA',
default: 'Default value',
description: 'Description',
value: 'Updated value',
},
],
resources: [],
workspaces: [],
};
const labels: { [key: string]: string } = {
anotherlabel: 'another-label-value',
};
const runData = getPipelineRunFromForm(samplePipeline, formValues, labels);
const pipelinerun = getPipelineRunData(samplePipeline);
expect(runData).toMatchObject({
...pipelinerun,
metadata: { annotations: {}, labels },
spec: {
pipelineRef: { name: samplePipeline.metadata.name },
params: [
{
name: 'ParameterA',
value: 'Updated value',
},
],
resources: [],
status: null,
workspaces: [],
},
});
});
it('expect pipeline run data to have a resources if the form data contains resources', () => {
const formValues: CommonPipelineModalFormikValues = {
namespace: 'corazon',
parameters: [],
resources: [
{
name: 'ResourceA',
selection: 'SelectionA',
data: {
type: 'Git',
params: {},
secrets: {},
},
},
],
workspaces: [],
};
const labels: { [key: string]: string } = {
anotherlabel: 'another-label-value',
};
const runData = getPipelineRunFromForm(samplePipeline, formValues, labels);
const pipelinerun = getPipelineRunData(samplePipeline);
expect(runData).toMatchObject({
...pipelinerun,
metadata: { annotations: {}, labels },
spec: {
pipelineRef: { name: samplePipeline.metadata.name },
params: [],
resources: [
{
name: 'ResourceA',
resourceRef: {
name: 'SelectionA',
},
},
],
status: null,
workspaces: [],
},
});
});
});
describe('convertPipelineToModalData', () => {
const workspacePipeline = pipelineTestData[PipelineExampleNames.WORKSPACE_PIPELINE].pipeline;
it('expect to return workspaces', () => {
expect(convertPipelineToModalData(workspacePipeline).workspaces).toHaveLength(3);
});
it('expect to return workspaces with type EmptyDirectory, if preselect PVC argument is not passed', () => {
const { workspaces } = convertPipelineToModalData(workspacePipeline);
expect(
workspaces.filter((workspace) => workspace.type === VolumeTypes.EmptyDirectory),
).toHaveLength(2);
expect(
workspaces.filter((workspace) => workspace.type === VolumeTypes.NoWorkspace),
).toHaveLength(1);
});
it('expect to return workspaces with type PVC, if preselect PVC argument is passed', () => {
const { workspaces } = convertPipelineToModalData(workspacePipeline, false, 'test-pvc');
expect(
workspaces.filter((workspace) => workspace.type === VolumeTypes.EmptyDirectory),
).toHaveLength(0);
expect(workspaces.filter((workspace) => workspace.type === VolumeTypes.PVC)).toHaveLength(2);
expect(
workspaces.filter((workspace) => workspace.type === VolumeTypes.NoWorkspace),
).toHaveLength(1);
});
}); | the_stack |
import { Type } from '@angular/core';
import {
async,
ComponentFixture,
fakeAsync,
tick,
} from '@angular/core/testing';
import {
FormsModule,
ReactiveFormsModule,
} from '@angular/forms';
import { By } from '@angular/platform-browser';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { KEYS } from '@terminus/ngx-tools/keycodes';
import {
createComponent as createComponentInner,
createKeyboardEvent,
dispatchEvent,
dispatchKeyboardEvent,
dispatchMouseEvent,
typeInElement,
} from '@terminus/ngx-tools/testing';
import { TsOptionModule } from '@terminus/ui/option';
import * as testComponents from '@terminus/ui/select/testing';
// eslint-disable-next-line no-duplicate-imports
import {
createKeydownEvent,
getAllOptionInstances,
getFilterInputElement,
getOptgroupElement,
getOptionElement,
getOptionInstance,
getSelectElement,
getSelectInstance,
getSelectTriggerElement,
openSelect,
} from '@terminus/ui/select/testing';
import { TsSelectModule } from './select.module';
/**
* Create test component
*
* @param component
*/
function createComponent<T>(component: Type<T>): ComponentFixture<T> {
const moduleImports = [
FormsModule,
ReactiveFormsModule,
TsSelectModule,
TsOptionModule,
NoopAnimationsModule,
];
return createComponentInner(component, undefined, moduleImports);
}
describe(`TsSelectComponent`, function() {
test(`should exist`, function() {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.ts-select'))).toBeTruthy();
});
/**
* STANDARD SELECT MODE
*/
describe(`standard select mode`, function() {
test(`should select an option via the arrow key when in single select mode unless option is disabled`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
const event = createKeydownEvent(KEYS.DOWN_ARROW);
trigger.dispatchEvent(event);
const options = getAllOptionInstances(fixture);
const option = options[0];
const selected = getSelectInstance(fixture).selectionModel.selected;
expect(selected.length).toEqual(1);
expect(selected[0].viewValue).toEqual(option.viewValue);
trigger.dispatchEvent(event);
expect(selected.length).toEqual(1);
expect(selected[0].viewValue).toEqual(option.viewValue);
expect.assertions(4);
});
test(`should allow a value seeded by a FormControl`, done => {
const fixture = createComponent(testComponents.SeededFormControl);
fixture.detectChanges();
fixture.whenStable().then(() => {
const selected = getSelectInstance(fixture).selectionModel.selected;
expect(selected.length).toEqual(1);
expect(selected[0].viewValue).toEqual('Florida');
done();
});
});
test(`should allow a value seeded by an ngModel`, async(() => {
const fixture = createComponent(testComponents.SeededNgModel);
fixture.detectChanges();
fixture.whenStable().then(() => {
const selected = getSelectInstance(fixture).selectionModel.selected;
expect(selected.length).toEqual(1);
expect(selected[0].viewValue).toEqual('Florida');
});
}));
test(`should fallback to a passed in value if no ngControl is used`, async(() => {
const fixture = createComponent(testComponents.SeededFallbackValue);
fixture.detectChanges();
fixture.whenStable().then(() => {
const selected = getSelectInstance(fixture).selectionModel.selected;
expect(selected.length).toEqual(1);
expect(selected[0].viewValue).toEqual('Florida');
});
}));
test(`should emit events for selections and changes`, () => {
const fixture = createComponent<testComponents.SelectionChangeEventEmitters>(testComponents.SelectionChangeEventEmitters);
fixture.detectChanges();
fixture.componentInstance.selected = jest.fn();
fixture.componentInstance.change = jest.fn();
const trigger = getSelectTriggerElement(fixture);
const event = createKeydownEvent(KEYS.DOWN_ARROW);
trigger.dispatchEvent(event);
// NOTE: Ideally we would verify what was passed through the emitter but doing so causes a memory error with Jest.
expect(fixture.componentInstance.selected).toHaveBeenCalled();
expect(fixture.componentInstance.change).toHaveBeenCalled();
});
test(`should support custom option template`, () => {
const fixture = createComponent(testComponents.CustomOptionTemplate);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const option = getOptionElement(fixture, 0, 1);
expect(option.innerHTML).toEqual(expect.stringContaining('bar'));
});
test(`should support a custom trigger`, done => {
const fixture = createComponent(testComponents.CustomOptionTemplate);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
expect(trigger.innerHTML).toEqual(expect.stringContaining('My custom'));
done();
});
});
test(`should support custom 'blank' option choice`, () => {
const fixture = createComponent(testComponents.CustomBlankOption);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const options = getAllOptionInstances(fixture);
const option = options[0];
expect(option.viewValue).toEqual('FOO');
});
test(`should style disabled and selected options`, fakeAsync(function() {
const fixture = createComponent(testComponents.SeededFormControl);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
tick(1000);
fixture.detectChanges();
const disabledOption = getOptionElement(fixture, 0, 1);
const activeOption = getOptionElement(fixture, 0, 4);
expect(disabledOption.classList.contains('ts-option--disabled')).toEqual(true);
expect(activeOption.classList.contains('ts-selected')).toEqual(true);
}));
test(`should support optgroups`, () => {
const fixture = createComponent(testComponents.Optgroups);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const group = getOptgroupElement(fixture);
const groupDisabled = getOptgroupElement(fixture, 0, 1);
const label = group.querySelector('label');
// Existence
expect(group).toBeTruthy();
// Role
expect(group.getAttribute('role')).toEqual('group');
// Labeledby
expect(group.getAttribute('aria-labelledby')).toEqual(label?.id);
// Disabled
expect(groupDisabled.getAttribute('aria-disabled')).toEqual('true');
});
describe(`delimiter`, function() {
test(`should allow custom delimiters`, fakeAsync(function() {
const fixture = createComponent(testComponents.CustomDelimiter);
fixture.detectChanges();
fixture.whenStable().then(() => {
const trigger = getSelectTriggerElement(fixture);
trigger.click();
fixture.detectChanges();
const valueSpan = trigger.querySelector('.ts-select-value-text');
expect(valueSpan!.textContent!.trim()).toEqual('Florida- Texas');
});
expect.assertions(1);
}));
test(`should fall back to the default delimiter if a non-string value is passed in`, () => {
const fixture = createComponent<testComponents.CustomDelimiter>(testComponents.CustomDelimiter);
fixture.componentInstance.delimiter = 1 as any;
fixture.detectChanges();
fixture.whenStable().then(() => {
const trigger = getSelectTriggerElement(fixture);
trigger.click();
fixture.detectChanges();
const valueSpan = trigger.querySelector('.ts-select-value-text');
expect(valueSpan!.textContent!.trim()).toEqual('Florida, Texas');
});
expect.assertions(1);
});
});
test(`should not open when disabled`, () => {
const fixture = createComponent<testComponents.Disabled>(testComponents.Disabled);
fixture.detectChanges();
fixture.componentInstance.wasOpened = jest.fn();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const instance = getSelectInstance(fixture);
expect(fixture.componentInstance.wasOpened).not.toHaveBeenCalled();
expect(instance.panelOpen).toEqual(false);
});
test(`should update when options change`, async(() => {
const fixture = createComponent<testComponents.SelectOptionChange>(testComponents.SelectOptionChange);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
let selected = getSelectInstance(fixture).selectionModel.selected.map(v => v.viewValue);
expect(selected).toEqual(['Florida', 'Texas']);
fixture.componentInstance.updateOptions();
selected = getSelectInstance(fixture).selectionModel.selected.map(v => v.viewValue);
expect(selected).toEqual(['Florida', 'Texas']);
expect.assertions(2);
});
}));
// NOTE: This method is called from outside the component so we have to test by calling it directly
test(`should set the disabled state when called`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
instance['changeDetectorRef'].markForCheck = jest.fn();
instance.stateChanges.next = jest.fn();
instance.setDisabledState(true);
expect(instance['changeDetectorRef'].markForCheck).toHaveBeenCalled();
expect(instance.stateChanges.next).toHaveBeenCalled();
expect(instance.isDisabled).toEqual(true);
});
test(`should support a custom tabindex`, () => {
const fixture = createComponent(testComponents.Tabindex);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
expect(trigger.getAttribute('tabindex')).toEqual('4');
});
describe(`open()`, function() {
test(`should do nothing if disabled`, () => {
const fixture = createComponent(testComponents.Basic);
const instance = getSelectInstance(fixture);
instance.isDisabled = true;
fixture.detectChanges();
instance.open();
fixture.detectChanges();
expect(instance.panelOpen).toEqual(false);
});
test(`should do nothing if no options exist`, () => {
const fixture = createComponent<testComponents.Basic>(testComponents.Basic);
fixture.componentInstance.options.length = 0;
const instance = getSelectInstance(fixture);
fixture.detectChanges();
instance.open();
fixture.detectChanges();
expect(instance.panelOpen).toEqual(false);
});
test(`should do nothing if the panel is already open`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
instance.open();
fixture.detectChanges();
expect(instance.panelOpen).toEqual(true);
instance['changeDetectorRef'].markForCheck = jest.fn();
instance.open();
fixture.detectChanges();
expect(instance.panelOpen).toEqual(true);
expect(instance['changeDetectorRef'].markForCheck).not.toHaveBeenCalled();
});
// TODO: getComputedStyle no longer seems to work
// test(`should set the overlay element font size to match the trigger`, async(() => {
// const fixture = createComponent(testComponents.Basic);
// const instance = getSelectInstance(fixture);
// fixture.detectChanges();
// instance.trigger.nativeElement.style.fontSize = '5px';
//
// instance.open();
// fixture.detectChanges();
//
// fixture.whenStable().then(() => {
// expect(instance.panelOpen).toEqual(true);
// expect(instance.triggerFontSize).toEqual(5);
// expect(getComputedStyle(instance.overlayDir.overlayRef.overlayElement)['font-size']).toEqual('5px');
// });
// }));
});
describe(`handleOpenKeydown`, function() {
test(`should focus the first item if HOME is used`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
const element = getSelectElement(fixture);
const options = getAllOptionInstances(fixture);
instance.open();
fixture.detectChanges();
// Move down the list so that the first item is no longer focused
dispatchKeyboardEvent(element, 'keydown', KEYS.DOWN_ARROW);
dispatchKeyboardEvent(element, 'keydown', KEYS.DOWN_ARROW);
fixture.detectChanges();
const eventHome = dispatchKeyboardEvent(element, 'keydown', KEYS.HOME);
fixture.detectChanges();
expect(options[0].active).toEqual(true);
expect(eventHome.defaultPrevented).toEqual(true);
});
test(`should focus the last item if END is used`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
const element = getSelectElement(fixture);
const options = getAllOptionInstances(fixture);
instance.open();
fixture.detectChanges();
const event = createKeydownEvent(KEYS.DOWN_ARROW);
// Move down the list so that the first item is no longer focused
element.dispatchEvent(event);
element.dispatchEvent(event);
fixture.detectChanges();
const eventEnd = dispatchKeyboardEvent(element, 'keydown', KEYS.END);
fixture.detectChanges();
expect(options[options.length - 1].active).toEqual(true);
expect(eventEnd.defaultPrevented).toEqual(true);
});
test(`should close the panel if ALT + ARROW is used`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
const element = getSelectElement(fixture);
instance.open();
fixture.detectChanges();
expect(instance.panelOpen).toEqual(true);
const event = createKeyboardEvent('keydown', KEYS.DOWN_ARROW);
Object.defineProperty(event, 'altKey', { get: () => true });
dispatchEvent(element, event);
fixture.detectChanges();
expect(instance.panelOpen).toEqual(false);
expect(event.defaultPrevented).toEqual(true);
});
test(`should select an item if SPACE is used`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
const element = getSelectElement(fixture);
instance.open();
fixture.detectChanges();
const event = createKeydownEvent(KEYS.DOWN_ARROW);
// Move down the list so that the first item is no longer focused
element.dispatchEvent(event);
element.dispatchEvent(event);
element.dispatchEvent(event);
fixture.detectChanges();
const eventSpace = dispatchKeyboardEvent(element, 'keydown', KEYS.SPACE);
fixture.detectChanges();
expect(instance.value).toEqual('California');
expect(eventSpace.defaultPrevented).toEqual(true);
});
test(`should select an item if ENTER is used`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
const element = getSelectElement(fixture);
instance.open();
fixture.detectChanges();
const eventDown = createKeydownEvent(KEYS.DOWN_ARROW);
// Move down the list so that the first item is no longer focused
element.dispatchEvent(eventDown);
element.dispatchEvent(eventDown);
element.dispatchEvent(eventDown);
fixture.detectChanges();
const event = dispatchKeyboardEvent(element, 'keydown', KEYS.ENTER);
fixture.detectChanges();
expect(instance.value).toEqual('California');
expect(event.defaultPrevented).toEqual(true);
});
});
});
describe('with ngModel using compareWith', function() {
describe('comparing by value', function() {
test('should have a selection', async(() => {
const fixture = createComponent(testComponents.CustomCompareFn);
fixture.detectChanges();
fixture.whenStable().then(() => {
const selections = getSelectInstance(fixture).selectionModel.selected;
expect(selections.length).toEqual(1);
expect(selections[0].value.value).toEqual('pizza-1');
expect.assertions(2);
});
}));
test('should update when making a new selection', async(() => {
const fixture = createComponent<testComponents.CustomCompareFn>(testComponents.CustomCompareFn);
fixture.detectChanges();
const options = getAllOptionInstances(fixture);
getOptionInstance(fixture, 0, options.length - 1).selectViaInteraction();
fixture.detectChanges();
const getterValue = getSelectInstance(fixture).selected;
const selectedOption = getterValue[0] ? getterValue[0] : getterValue;
expect(fixture.componentInstance.selectedFood.value).toEqual('tacos-2');
expect(selectedOption.value.value).toEqual('tacos-2');
}));
});
describe('comparing by reference', function() {
test('should initialize with no selection despite having a value', async(() => {
const fixture = createComponent<testComponents.CustomCompareFn>(testComponents.CustomCompareFn);
fixture.detectChanges();
fixture.componentInstance.useCompareByReference();
fixture.detectChanges();
expect(fixture.componentInstance.selectedFood.value).toBe('pizza-1');
expect(getSelectInstance(fixture).selected).toBeUndefined();
}));
test('should log a warning when using a non-function comparator', async(() => {
const fixture = createComponent<testComponents.CustomCompareFn>(testComponents.CustomCompareFn);
fixture.detectChanges();
window.console.warn = jest.fn();
fixture.componentInstance.useNullComparator();
fixture.detectChanges();
expect(window.console.warn).toHaveBeenCalledWith(expect.stringContaining('TsSelectComponent: '));
}));
});
test(`should defer optionSelection stream if no options exist`, async(() => {
const fixture = createComponent<testComponents.DeferOptionSelectionStream>(testComponents.DeferOptionSelectionStream);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
expect(instance.selected).toBeFalsy();
fixture.componentInstance.updateOptions();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(instance.selected).toBeTruthy();
expect.assertions(2);
});
}));
describe(`trigger`, function() {
test(`should fallback to placeholder when empty`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
getSelectInstance(fixture).placeholder = 'foo';
fixture.detectChanges();
expect(trigger.textContent?.trim()).toEqual('foo');
});
});
});
/**
* MULTIPLE MODE
*/
describe(`multi-select`, function() {
/*
* test(`should toggle all enabled items when toggle all is clicked and show a selected count`, () => {
* jest.useFakeTimers();
* const fixture = createComponent(testComponents.OptgroupsMultiple);
* fixture.detectChanges();
* const trigger = getSelectTriggerElement(fixture);
* dispatchMouseEvent(trigger, 'click');
* fixture.detectChanges();
* const select = getSelectInstance(fixture);
*
* expect(select.selectionModel.selected.length).toEqual(0);
*
* const toggle = getToggleAllElement(fixture);
* dispatchMouseEvent(toggle, 'click');
* const group1 = getOptgroupElement(fixture)!;
* dispatchMouseEvent(group1, 'click');
* jest.advanceTimersByTime(1000);
* fixture.detectChanges();
*
* expect(select.selectionModel.selected.length).toEqual(2);
*
* let count = toggle.querySelector('.ts-select-panel__count');
* expect((count && count.textContent) ? count.textContent.trim() : '').toEqual('2 selected');
*
* dispatchMouseEvent(toggle, 'click');
* fixture.detectChanges();
* expect(select.selectionModel.selected.length).toEqual(0);
*
* count = toggle.querySelector('.ts-select-panel__count');
* expect(count).toBeNull();
* expect.assertions(5);
* jest.runAllTimers();
* });
*/
describe(`handleOpenKeydown`, function() {
test(`should select OR deselect all items with CTRL + A`, () => {
const fixture = createComponent(testComponents.OptgroupsMultiple);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
const element = getSelectElement(fixture);
openSelect(fixture);
const event = createKeyboardEvent('keydown', KEYS.A, element);
Object.defineProperty(event, 'ctrlKey', { get: () => true });
dispatchEvent(element, event);
fixture.detectChanges();
// Only two items are not disabled or within a disabled group
expect(instance.selectionModel.selected.length).toEqual(2);
expect(event.defaultPrevented).toEqual(true);
dispatchEvent(element, event);
fixture.detectChanges();
expect(instance.selectionModel.selected.length).toEqual(0);
});
test(`should select the next item with SHIFT+ARROW`, function() {
const fixture = createComponent(testComponents.NoGroupsMultiple);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
const element = getSelectElement(fixture);
instance.open();
fixture.detectChanges();
const eventDown = createKeydownEvent(KEYS.DOWN_ARROW);
// Move focus past disabled item for testing ease
element.dispatchEvent(eventDown);
element.dispatchEvent(eventDown);
element.dispatchEvent(eventDown);
fixture.detectChanges();
const event = createKeydownEvent(KEYS.DOWN_ARROW);
Object.defineProperty(event, 'shiftKey', { get: () => true });
element.dispatchEvent(event);
fixture.detectChanges();
expect(instance.value).toEqual(['Florida']);
const event2 = createKeyboardEvent('keydown', KEYS.UP_ARROW);
Object.defineProperty(event2, 'shiftKey', { get: () => true });
element.dispatchEvent(event2);
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(instance.value).toEqual(['Florida', 'California']);
});
});
});
describe(`optgroup`, function() {
test(`should toggle all child options if not disabled`, () => {
const fixture = createComponent(testComponents.OptgroupsMultiple);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const group = getOptgroupElement(fixture);
const select = getSelectInstance(fixture);
const label = group.querySelector('label');
expect(select.selectionModel.selected.length).toEqual(0);
dispatchMouseEvent(label as Node, 'click');
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(select.selectionModel.selected.length).toEqual(2);
});
});
});
});
test(`should be able to hide the required marker`, function() {
const fixture = createComponent<testComponents.HideRequired>(testComponents.HideRequired);
fixture.detectChanges();
let marker = fixture.debugElement.query(By.css('.ts-form-field-required-marker'));
expect(marker).toBeTruthy();
fixture.componentInstance.hideRequired = true;
fixture.detectChanges();
marker = fixture.debugElement.query(By.css('.ts-form-field-required-marker'));
expect(marker).toBeFalsy();
});
test(`should support a custom hint`, function() {
const fixture = createComponent(testComponents.Hint);
fixture.detectChanges();
const hintElement = fixture.debugElement.query(By.css('.ts-form-field__hint-wrapper'));
const contents = fixture.debugElement.query(By.css('.c-input__hint'));
expect(hintElement).toBeTruthy();
expect(contents.nativeElement.textContent.trim()).toEqual('foo');
});
describe(`ID`, function() {
test(`should support a custom ID`, () => {
const fixture = createComponent(testComponents.Id);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
expect(trigger.getAttribute('id')).toEqual('foo');
});
test(`should fall back to the UID if no ID is passed in`, () => {
const fixture = createComponent<testComponents.Id>(testComponents.Id);
fixture.componentInstance.myId = undefined as any;
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
expect(trigger.getAttribute('id')).toEqual(expect.stringContaining('ts-select-'));
});
});
describe(`label`, function() {
test(`should support a custom label`, () => {
const fixture = createComponent(testComponents.Label);
fixture.detectChanges();
const label = fixture.debugElement.query(By.css('.ts-form-field__label'));
expect(label.nativeElement.textContent.trim()).toEqual('foo bar');
});
test(`should trigger change detection and alert consumers when the label is changed`, () => {
const fixture = createComponent<testComponents.Label>(testComponents.Label);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
instance['changeDetectorRef'].detectChanges = jest.fn();
instance.labelChanges.next = jest.fn();
fixture.componentInstance.myLabel = 'bing baz';
fixture.detectChanges();
const label = fixture.debugElement.query(By.css('.ts-form-field__label'));
expect(label.nativeElement.textContent.trim()).toEqual('bing baz');
expect(instance['changeDetectorRef'].detectChanges).toHaveBeenCalled();
expect(instance.labelChanges.next).toHaveBeenCalled();
});
});
test(`should show error immediately if validating on change`, function() {
const fixture = createComponent(testComponents.ValidateOnChange);
fixture.detectChanges();
const messageContainer = fixture.debugElement.query(By.css('.c-validation-message'));
expect(messageContainer.nativeElement.textContent.trim()).toEqual('Required');
});
describe(`toggle()`, function() {
test(`should close the panel if it is open`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
trigger.click();
fixture.detectChanges();
const instance = getSelectInstance(fixture);
expect(instance.panelOpen).toEqual(true);
instance.toggle();
fixture.detectChanges();
expect(instance.panelOpen).toEqual(false);
});
});
describe(`onSelect`, function() {
test(`should reset selection values when a null value is selected`, () => {
const fixture = createComponent<testComponents.NullSelection>(testComponents.NullSelection);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
const trigger = getSelectTriggerElement(fixture);
expect(fixture.componentInstance.myCtrl.value).toEqual('bar');
const option = getOptionElement(fixture, 0, 1);
option.click();
fixture.detectChanges();
expect(fixture.componentInstance.myCtrl.value).toBeNull();
expect(instance.selected).toBeFalsy();
expect(trigger.textContent.trim()).not.toContain('Null');
});
});
describe(`keyManager`, function() {
test(`should close the panel and focus the select if the user TABs out`, () => {
// NOTE: `dispatchKeyboardEvent` suddenly stopped working for this test during the Angular v8 upgrade
const event = document.createEvent('KeyboardEvent');
event.initEvent('keydown', true, false);
Object.defineProperties(event, {
keyCode: { get: () => KEYS.TAB.keyCode },
key: { get: () => KEYS.TAB.code },
});
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
const element = getSelectElement(fixture);
instance.focus = jest.fn();
instance.open();
fixture.detectChanges();
expect(instance.panelOpen).toEqual(true);
element.dispatchEvent(event);
fixture.detectChanges();
expect(instance.panelOpen).toEqual(false);
expect(instance.focus).toHaveBeenCalled();
expect.assertions(3);
});
});
describe(`propogateChanges`, function() {
test(`should use fallback value if the option has no value`, () => {
const fixture = createComponent<testComponents.Basic>(testComponents.Basic);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
fixture.componentInstance.change = jest.fn();
instance['propagateChanges']('foo');
fixture.detectChanges();
expect(fixture.componentInstance.change).toHaveBeenCalledWith(expect.objectContaining({ value: 'foo' }));
});
});
describe(`getPanelScrollTop`, function() {
test(`should fallback to 0 if the panel is not found`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
instance.panel = undefined as any;
expect(instance['getPanelScrollTop']()).toEqual(0);
});
});
describe(`option`, function() {
test(`should throw error if template is used but no option is passed in`, () => {
const create = () => {
const fixture = createComponent(testComponents.OptionError);
fixture.detectChanges();
};
expect(create).toThrowError(`TsOptionComponent: The full 'option' object must be passed in when using a custom template.`);
});
describe(`Id`, function() {
test(`should support custom IDs`, () => {
const fixture = createComponent(testComponents.OptionId);
fixture.detectChanges();
const option = getOptionInstance(fixture, 0, 1);
expect(option.id).toEqual('Alabama');
});
test(`should fall back to UID`, () => {
const fixture = createComponent(testComponents.OptionId);
fixture.detectChanges();
const option = getOptionInstance(fixture, 0, 1);
option.id = undefined as any;
fixture.detectChanges();
expect(option.id).toEqual(expect.stringContaining('ts-option-'));
});
});
describe(`getLabel`, function() {
test(`should return the viewValue`, () => {
const fixture = createComponent(testComponents.OptionId);
fixture.detectChanges();
const option = getOptionInstance(fixture, 0, 1);
expect(option.getLabel()).toEqual('Alabama');
});
});
describe(`checkbox`, function() {
test(`should have checkbox in front of each option item`, fakeAsync(() => {
const fixture = createComponent(testComponents.OptgroupsMultiple);
fixture.detectChanges();
fixture.detectChanges();
const opt = getOptionElement(fixture, 0, 1);
expect(opt.querySelector('ts-checkbox')).toBeTruthy();
}));
});
describe(`handleKeydown`, function() {
test(`should select via interaction when SPACE is used`, () => {
const fixture = createComponent(testComponents.OptionId);
fixture.detectChanges();
const option = getOptionInstance(fixture, 0, 1);
const event = createKeyboardEvent('keydown', KEYS.SPACE);
option.selectViaInteraction = jest.fn();
option.handleKeydown(event);
expect(option.selectViaInteraction).toHaveBeenCalled();
expect(event.defaultPrevented).toEqual(true);
});
test(`should select via interaction when ENTER is used`, () => {
const fixture = createComponent(testComponents.OptionId);
fixture.detectChanges();
const option = getOptionInstance(fixture, 0, 1);
const event = createKeyboardEvent('keydown', KEYS.ENTER);
option.selectViaInteraction = jest.fn();
option.handleKeydown(event);
expect(option.selectViaInteraction).toHaveBeenCalled();
expect(event.defaultPrevented).toEqual(true);
});
test(`should return if isDisabled true`, () => {
const fixture = createComponent(testComponents.Basic);
getSelectInstance(fixture).isDisabled = true;
fixture.detectChanges();
const option = getOptionInstance(fixture, 0, 1);
const event = createKeyboardEvent('keydown', KEYS.ENTER);
const instance = getSelectInstance(fixture);
option.selectViaInteraction = jest.fn();
instance.open = jest.fn();
instance.handleKeydown(event);
expect(option.selectViaInteraction).not.toHaveBeenCalled();
});
test(`should open the panel if allow multiple`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const option = getOptionInstance(fixture, 0, 1);
const event = createKeyboardEvent('keydown', KEYS.ENTER);
const instance = getSelectInstance(fixture);
option.selectViaInteraction = jest.fn();
instance.open = jest.fn();
instance.handleKeydown(event);
expect(instance.open).toHaveBeenCalled();
});
});
describe(`option`, function() {
test(`should retrieve the option object`, () => {
const fixture = createComponent(testComponents.OptionId);
fixture.detectChanges();
const option = getOptionInstance(fixture, 0, 1);
expect(option.option).toEqual(expect.objectContaining({ name: 'Alabama' }));
});
});
describe(`deselect`, function() {
test(`should emit event not from user interaction`, () => {
const fixture = createComponent<testComponents.OptionId>(testComponents.OptionId);
fixture.detectChanges();
const option = getOptionInstance(fixture, 0, 2);
option.select();
fixture.detectChanges();
option['emitSelectionChangeEvent'] = jest.fn();
option.deselect();
fixture.detectChanges();
expect(option['emitSelectionChangeEvent'].mock.calls.length).toEqual(1);
// Verify it was not called with the boolean
expect(option['emitSelectionChangeEvent'].mock.calls[0]).toEqual([]);
});
});
});
describe(`optgroup`, function() {
test(`should support a custom ID`, () => {
const fixture = createComponent(testComponents.OptgroupIDs);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const group = getOptgroupElement(fixture);
expect(group.getAttribute('id')).toEqual('Group A');
});
test(`should fall back to the UID if no valid ID is passed in`, () => {
const fixture = createComponent(testComponents.OptgroupBadIDs);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const group = getOptgroupElement(fixture);
expect(group.getAttribute('id')).toEqual(expect.stringContaining('ts-select-optgroup-'));
});
});
describe(`trigger`, function() {
test(`should support a custom ID`, () => {
const fixture = createComponent(testComponents.CustomTrigger);
fixture.detectChanges();
const instance = getSelectInstance(fixture);
expect(instance.customTrigger?.id).toEqual('foo');
});
test(`should fall back to the UID if no valid ID is passed in`, () => {
const fixture = createComponent<testComponents.CustomTrigger>(testComponents.CustomTrigger);
fixture.detectChanges();
fixture.componentInstance.myId = undefined as any;
fixture.detectChanges();
const instance = getSelectInstance(fixture);
expect(instance.customTrigger?.id).toEqual(expect.stringContaining('ts-select-trigger-'));
});
});
describe(`Select Panel`, function() {
test(`should close with esc or alt+up`, () => {
// NOTE: `dispatchKeyboardEvent` suddenly stopped working for this test during the Angular v8 upgrade
const event = document.createEvent('KeyboardEvent');
event.initEvent('keydown', true, false);
Object.defineProperties(event, {
keyCode: { get: () => KEYS.ESCAPE.keyCode },
key: { get: () => KEYS.ESCAPE.code },
});
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const instance = getSelectInstance(fixture);
expect(instance.panelOpen).toEqual(true);
trigger.dispatchEvent(event);
fixture.detectChanges();
expect(instance.panelOpen).toEqual(false);
});
test(`should close with alt+up or alt+down`, () => {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const instance = getSelectInstance(fixture);
// open
expect(instance.panelOpen).toEqual(true);
let event = createKeyboardEvent('keydown', KEYS.DOWN_ARROW);
Object.defineProperty(event, 'altKey', { get: () => true });
dispatchEvent(getSelectElement(fixture), event);
fixture.detectChanges();
// closed
expect(instance.panelOpen).toEqual(false);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
// open again
expect(instance.panelOpen).toEqual(true);
event = createKeyboardEvent('keydown', KEYS.UP_ARROW);
Object.defineProperty(event, 'altKey', { get: () => true });
dispatchEvent(getSelectElement(fixture), event);
fixture.detectChanges();
// closed again
expect(instance.panelOpen).toEqual(false);
expect.assertions(4);
});
});
describe('isFilterable', function() {
test(`should filter options`, () => {
const fixture = createComponent<testComponents.Filterable>(testComponents.Filterable);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const instance = getSelectInstance(fixture);
// open
expect(instance.panelOpen).toEqual(true);
const input = getFilterInputElement(fixture);
const options = getAllOptionInstances(fixture);
expect(options.length).toBe(fixture.componentInstance.options.length);
typeInElement('geo', input);
expect(fixture.componentInstance.options.length).toBe(0);
typeInElement('', input);
expect(fixture.componentInstance.options.length).toBe(options.length);
typeInElement('arizona', input);
expect(fixture.componentInstance.options.length).toBe(3);
expect.assertions(5);
});
test('should allow space as part of filter and not select an option', () => {
const fixture = createComponent<testComponents.Filterable>(testComponents.Filterable);
fixture.detectChanges();
const trigger = getSelectTriggerElement(fixture);
dispatchMouseEvent(trigger, 'click');
fixture.detectChanges();
const instance = getSelectInstance(fixture);
expect(instance.panelOpen).toEqual(true);
const input = getFilterInputElement(fixture);
const options = getAllOptionInstances(fixture);
expect(options.length).toBe(fixture.componentInstance.options.length);
typeInElement('something', input);
dispatchKeyboardEvent(input, 'keydown', KEYS.SPACE, input);
expect(fixture.componentInstance.options.length).toBe(0);
expect.assertions(3);
});
});
describe(`allow refresh requests`, function() {
test(`should show the refresh trigger and emit the event on selection`, function() {
const fixture = createComponent<testComponents.TriggerRefresh>(testComponents.TriggerRefresh);
fixture.detectChanges();
openSelect(fixture);
const refreshTrigger = fixture.debugElement.query(By.css('.ts-select-panel__refresh'));
expect(refreshTrigger).toBeTruthy();
expect(fixture.componentInstance.hasRequested).toEqual(false);
refreshTrigger.nativeElement.click();
fixture.detectChanges();
expect(fixture.componentInstance.hasRequested).toEqual(true);
});
});
describe(`showRefineSearchMessage`, function() {
test(`should not show the message by default`, function() {
const fixture = createComponent(testComponents.Basic);
const refineDom = fixture.debugElement.query(By.css('.ts-select-panel__refine'));
expect(refineDom).toBeFalsy();
});
test(`should show the message with a count if defined`, function() {
const fixture = createComponent<testComponents.TooManyResults>(testComponents.TooManyResults);
fixture.detectChanges();
openSelect(fixture);
let refineDom = fixture.debugElement.query(By.css('.ts-select-panel__refine'));
expect(refineDom.nativeElement.textContent.trim()).toEqual('Narrow your search to reveal hidden results.');
fixture.componentInstance.total = 99;
fixture.detectChanges();
refineDom = fixture.debugElement.query(By.css('.ts-select-panel__refine'));
expect(refineDom.nativeElement.textContent.trim()).toEqual('Narrow your search to reveal 99 hidden results.');
});
});
describe(`noValidationOrHint`, () => {
test(`should not have validation or hint added if set to true`, () => {
const fixture = createComponent(testComponents.NoValidationOrHint);
fixture.detectChanges();
const validationBlock = fixture.debugElement.query(By.css('.ts-form-field__subscript-wrapper'));
expect(validationBlock).toBeFalsy();
});
});
}); | the_stack |
import MathHelper from './MathHelper';
// import Vector2 from './Vector2';
import Vertex from './Vertex';
import Edge from './Edge';
// import Ring from './Ring';
import Atom from './Atom';
/**
* A class representing the molecular graph.
*
* @property {Vertex[]} vertices The vertices of the graph.
* @property {Edge[]} edges The edges of this graph.
* @property {Object} vertexIdsToEdgeId A map mapping vertex ids to the edge between the two vertices. The key is defined as vertexAId + '_' + vertexBId.
* @property {Boolean} isometric A boolean indicating whether or not the SMILES associated with this graph is isometric.
*/
class Graph {
public vertices: any;
public edges: any;
public vertexIdsToEdgeId: any;
public isomeric: any;
public _time: any;
/**
* The constructor of the class Graph.
*
* @param {Object} parseTree A SMILES parse tree.
* @param {Boolean} [isomeric=false] A boolean specifying whether or not the SMILES is isomeric.
*/
constructor(parseTree, isomeric = false) {
this.vertices = Array();
this.edges = Array();
this.vertexIdsToEdgeId = {};
this.isomeric = isomeric;
// Used for the bridge detection algorithm
this._time = 0;
this._init(parseTree);
}
/**
* PRIVATE FUNCTION. Initializing the graph from the parse tree.
*
* @param {Object} node The current node in the parse tree.
* @param {Number} parentVertexId=null The id of the previous vertex.
* @param {Boolean} isBranch=false Whether or not the bond leading to this vertex is a branch bond. Branches are represented by parentheses in smiles (e.g. CC(O)C).
*/
_init(node, order = 0, parentVertexId = null, isBranch = false) {
// Create a new vertex object
let atom = new Atom(node.atom.element ? node.atom.element : node.atom, node.bond);
atom.branchBond = node.branchBond;
atom.ringbonds = node.ringbonds;
atom.bracket = node.atom.element ? node.atom : null;
let vertex = new Vertex(atom);
let parentVertex = this.vertices[parentVertexId];
this.addVertex(vertex);
// Add the id of this node to the parent as child
if (parentVertexId !== null) {
vertex.setParentVertexId(parentVertexId);
vertex.value.addNeighbouringElement(parentVertex.value.element);
parentVertex.addChild(vertex.id);
parentVertex.value.addNeighbouringElement(atom.element);
// In addition create a spanningTreeChildren property, which later will
// not contain the children added through ringbonds
parentVertex.spanningTreeChildren.push(vertex.id);
// Add edge between this node and its parent
let edge = new Edge(parentVertexId, vertex.id, 1);
// let vertexId = null;
if (isBranch) {
edge.setBondType(vertex.value.branchBond || '-');
// vertexId = vertex.id;
edge.setBondType(vertex.value.branchBond || '-');
// vertexId = vertex.id;
} else {
edge.setBondType(parentVertex.value.bondType || '-');
// vertexId = parentVertex.id;
}
// let edgeId =
this.addEdge(edge);
}
let offset = node.ringbondCount + 1;
if (atom.bracket) {
offset += atom.bracket.hcount;
}
let stereoHydrogens = 0;
if (atom.bracket && atom.bracket.chirality) {
atom.isStereoCenter = true;
stereoHydrogens = atom.bracket.hcount;
for (var i = 0; i < stereoHydrogens; i++) {
this._init({
atom: 'H',
isBracket: 'false',
branches: Array(),
branchCount: 0,
ringbonds: Array(),
ringbondCount: false,
next: null,
hasNext: false,
bond: '-'
}, i, vertex.id, true);
}
}
for (var i = 0; i < node.branchCount; i++) {
this._init(node.branches[i], i + offset, vertex.id, true);
}
if (node.hasNext) {
this._init(node.next, node.branchCount + offset, vertex.id);
}
}
/**
* Clears all the elements in this graph (edges and vertices).
*/
clear() {
this.vertices = Array();
this.edges = Array();
this.vertexIdsToEdgeId = {};
}
/**
* Add a vertex to the graph.
*
* @param {Vertex} vertex A new vertex.
* @returns {Number} The vertex id of the new vertex.
*/
addVertex(vertex) {
vertex.id = this.vertices.length;
this.vertices.push(vertex);
return vertex.id;
}
/**
* Add an edge to the graph.
*
* @param {Edge} edge A new edge.
* @returns {Number} The edge id of the new edge.
*/
addEdge(edge) {
let source = this.vertices[edge.sourceId];
let target = this.vertices[edge.targetId];
edge.id = this.edges.length;
this.edges.push(edge);
this.vertexIdsToEdgeId[edge.sourceId + '_' + edge.targetId] = edge.id;
this.vertexIdsToEdgeId[edge.targetId + '_' + edge.sourceId] = edge.id;
edge.isPartOfAromaticRing = source.value.isPartOfAromaticRing && target.value.isPartOfAromaticRing;
source.value.bondCount += edge.weight;
target.value.bondCount += edge.weight;
source.edges.push(edge.id);
target.edges.push(edge.id);
return edge.id;
}
/**
* Returns the edge between two given vertices.
*
* @param {Number} vertexIdA A vertex id.
* @param {Number} vertexIdB A vertex id.
* @returns {(Edge|null)} The edge or, if no edge can be found, null.
*/
getEdge(vertexIdA, vertexIdB) {
let edgeId = this.vertexIdsToEdgeId[vertexIdA + '_' + vertexIdB];
return edgeId === undefined ? null : this.edges[edgeId];
}
/**
* Returns the ids of edges connected to a vertex.
*
* @param {Number} vertexId A vertex id.
* @returns {Number[]} An array containing the ids of edges connected to the vertex.
*/
getEdges(vertexId) {
let edgeIds = Array();
let vertex = this.vertices[vertexId];
for (var i = 0; i < vertex.neighbours.length; i++) {
edgeIds.push(this.vertexIdsToEdgeId[vertexId + '_' + vertex.neighbours[i]]);
}
return edgeIds;
}
/**
* Check whether or not two vertices are connected by an edge.
*
* @param {Number} vertexIdA A vertex id.
* @param {Number} vertexIdB A vertex id.
* @returns {Boolean} A boolean indicating whether or not two vertices are connected by an edge.
*/
hasEdge(vertexIdA, vertexIdB) {
return this.vertexIdsToEdgeId[vertexIdA + '_' + vertexIdB] !== undefined
}
/**
* Returns an array containing the vertex ids of this graph.
*
* @returns {Number[]} An array containing all vertex ids of this graph.
*/
getVertexList() {
let arr = [this.vertices.length];
for (var i = 0; i < this.vertices.length; i++) {
arr[i] = this.vertices[i].id;
}
return arr;
}
/**
* Returns an array containing source, target arrays of this graphs edges.
*
* @returns {Array[]} An array containing source, target arrays of this graphs edges. Example: [ [ 2, 5 ], [ 6, 9 ] ].
*/
getEdgeList() {
let arr = Array(this.edges.length);
for (var i = 0; i < this.edges.length; i++) {
arr[i] = [this.edges[i].sourceId, this.edges[i].targetId];
}
return arr;
}
/**
* Get the adjacency matrix of the graph.
*
* @returns {Array[]} The adjancency matrix of the molecular graph.
*/
getAdjacencyMatrix() {
let length = this.vertices.length;
let adjacencyMatrix = Array(length);
for (var i = 0; i < length; i++) {
adjacencyMatrix[i] = new Array(length);
adjacencyMatrix[i].fill(0);
}
for (var i = 0; i < this.edges.length; i++) {
let edge = this.edges[i];
adjacencyMatrix[edge.sourceId][edge.targetId] = 1;
adjacencyMatrix[edge.targetId][edge.sourceId] = 1;
}
return adjacencyMatrix;
}
/**
* Get the adjacency matrix of the graph with all bridges removed (thus the components). Thus the remaining vertices are all part of ring systems.
*
* @returns {Array[]} The adjancency matrix of the molecular graph with all bridges removed.
*/
getComponentsAdjacencyMatrix() {
let length = this.vertices.length;
let adjacencyMatrix = Array(length);
let bridges = this.getBridges();
for (var i = 0; i < length; i++) {
adjacencyMatrix[i] = new Array(length);
adjacencyMatrix[i].fill(0);
}
for (var i = 0; i < this.edges.length; i++) {
let edge = this.edges[i];
adjacencyMatrix[edge.sourceId][edge.targetId] = 1;
adjacencyMatrix[edge.targetId][edge.sourceId] = 1;
}
for (var i = 0; i < bridges.length; i++) {
adjacencyMatrix[bridges[i][0]][bridges[i][1]] = 0;
adjacencyMatrix[bridges[i][1]][bridges[i][0]] = 0;
}
return adjacencyMatrix;
}
/**
* Get the adjacency matrix of a subgraph.
*
* @param {Number[]} vertexIds An array containing the vertex ids contained within the subgraph.
* @returns {Array[]} The adjancency matrix of the subgraph.
*/
getSubgraphAdjacencyMatrix(vertexIds) {
let length = vertexIds.length;
let adjacencyMatrix = Array(length);
for (var i = 0; i < length; i++) {
adjacencyMatrix[i] = new Array(length);
adjacencyMatrix[i].fill(0);
for (var j = 0; j < length; j++) {
if (i === j) {
continue;
}
if (this.hasEdge(vertexIds[i], vertexIds[j])) {
adjacencyMatrix[i][j] = 1;
}
}
}
return adjacencyMatrix;
}
/**
* Get the distance matrix of the graph.
*
* @returns {Array[]} The distance matrix of the graph.
*/
getDistanceMatrix() {
let length = this.vertices.length;
let adja = this.getAdjacencyMatrix();
let dist = Array(length);
for (var i = 0; i < length; i++) {
dist[i] = Array(length);
dist[i].fill(Infinity);
}
for (var i = 0; i < length; i++) {
for (var j = 0; j < length; j++) {
if (adja[i][j] === 1) {
dist[i][j] = 1;
}
}
}
for (var k = 0; k < length; k++) {
for (var i = 0; i < length; i++) {
for (var j = 0; j < length; j++) {
if (dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j]
}
}
}
}
return dist;
}
/**
* Get the distance matrix of a subgraph.
*
* @param {Number[]} vertexIds An array containing the vertex ids contained within the subgraph.
* @returns {Array[]} The distance matrix of the subgraph.
*/
getSubgraphDistanceMatrix(vertexIds) {
let length = vertexIds.length;
let adja = this.getSubgraphAdjacencyMatrix(vertexIds);
let dist = Array(length);
for (var i = 0; i < length; i++) {
dist[i] = Array(length);
dist[i].fill(Infinity);
}
for (var i = 0; i < length; i++) {
for (var j = 0; j < length; j++) {
if (adja[i][j] === 1) {
dist[i][j] = 1;
}
}
}
for (var k = 0; k < length; k++) {
for (var i = 0; i < length; i++) {
for (var j = 0; j < length; j++) {
if (dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j]
}
}
}
}
return dist;
}
/**
* Get the adjacency list of the graph.
*
* @returns {Array[]} The adjancency list of the graph.
*/
getAdjacencyList() {
let length = this.vertices.length;
let adjacencyList = Array(length);
for (var i = 0; i < length; i++) {
adjacencyList[i] = [];
for (var j = 0; j < length; j++) {
if (i === j) {
continue;
}
if (this.hasEdge(this.vertices[i].id, this.vertices[j].id)) {
adjacencyList[i].push(j);
}
}
}
return adjacencyList;
}
/**
* Get the adjacency list of a subgraph.
*
* @param {Number[]} vertexIds An array containing the vertex ids contained within the subgraph.
* @returns {Array[]} The adjancency list of the subgraph.
*/
getSubgraphAdjacencyList(vertexIds) {
let length = vertexIds.length;
let adjacencyList = Array(length);
for (var i = 0; i < length; i++) {
adjacencyList[i] = Array();
for (var j = 0; j < length; j++) {
if (i === j) {
continue;
}
if (this.hasEdge(vertexIds[i], vertexIds[j])) {
adjacencyList[i].push(j);
}
}
}
return adjacencyList;
}
/**
* Returns an array containing the edge ids of bridges. A bridge splits the graph into multiple components when removed.
*
* @returns {Number[]} An array containing the edge ids of the bridges.
*/
getBridges() {
let length = this.vertices.length;
let visited = new Array(length);
let disc = new Array(length);
let low = new Array(length);
let parent = new Array(length);
let adj = this.getAdjacencyList();
let outBridges = Array();
visited.fill(false);
parent.fill(null);
this._time = 0;
for (var i = 0; i < length; i++) {
if (!visited[i]) {
this._bridgeDfs(i, visited, disc, low, parent, adj, outBridges);
}
}
return outBridges;
}
/**
* Traverses the graph in breadth-first order.
*
* @param {Number} startVertexId The id of the starting vertex.
* @param {Function} callback The callback function to be called on every vertex.
*/
traverseBF(startVertexId, callback) {
let length = this.vertices.length;
let visited = new Array(length);
visited.fill(false);
var queue = [startVertexId];
while (queue.length > 0) {
// JavaScripts shift() is O(n) ... bad JavaScript, bad!
let u = queue.shift();
let vertex = this.vertices[u];
callback(vertex);
for (var i = 0; i < vertex.neighbours.length; i++) {
let v = vertex.neighbours[i]
if (!visited[v]) {
visited[v] = true;
queue.push(v);
}
}
}
}
/**
* Get the depth of a subtree in the direction opposite to the vertex specified as the parent vertex.
*
* @param {Number} vertexId A vertex id.
* @param {Number} parentVertexId The id of a neighbouring vertex.
* @returns {Number} The depth of the sub-tree.
*/
getTreeDepth(vertexId, parentVertexId) {
if (vertexId === null || parentVertexId === null) {
return 0;
}
let neighbours = this.vertices[vertexId].getSpanningTreeNeighbours(parentVertexId);
let max = 0;
for (var i = 0; i < neighbours.length; i++) {
let childId = neighbours[i];
let d = this.getTreeDepth(childId, vertexId);
if (d > max) {
max = d;
}
}
return max + 1;
}
/**
* Traverse a sub-tree in the graph.
*
* @param {Number} vertexId A vertex id.
* @param {Number} parentVertexId A neighbouring vertex.
* @param {Function} callback The callback function that is called with each visited as an argument.
* @param {Number} [maxDepth=999999] The maximum depth of the recursion.
* @param {Boolean} [ignoreFirst=false] Whether or not to ignore the starting vertex supplied as vertexId in the callback.
* @param {Number} [depth=1] The current depth in the tree.
* @param {Uint8Array} [visited=null] An array holding a flag on whether or not a node has been visited.
*/
traverseTree(vertexId, parentVertexId, callback, maxDepth = 999999, ignoreFirst = false, depth = 1, visited = null) {
if (visited === null) {
visited = new Uint8Array(this.vertices.length);
}
if (depth > maxDepth + 1 || visited[vertexId] === 1) {
return;
}
visited[vertexId] = 1;
let vertex = this.vertices[vertexId];
let neighbours = vertex.getNeighbours(parentVertexId);
if (!ignoreFirst || depth > 1) {
callback(vertex);
}
for (var i = 0; i < neighbours.length; i++) {
this.traverseTree(neighbours[i], vertexId, callback, maxDepth, ignoreFirst, depth + 1, visited);
}
}
/**
* Positiones the (sub)graph using Kamada and Kawais algorithm for drawing general undirected graphs. https://pdfs.semanticscholar.org/b8d3/bca50ccc573c5cb99f7d201e8acce6618f04.pdf
* There are undocumented layout parameters. They are undocumented for a reason, so be very careful.
*
* @param {Number[]} vertexIds An array containing vertexIds to be placed using the force based layout.
* @param {Vector2} center The center of the layout.
* @param {Number} startVertexId A vertex id. Should be the starting vertex - e.g. the first to be positioned and connected to a previously place vertex.
* @param {Ring} ring The bridged ring associated with this force-based layout.
*/
kkLayout(vertexIds, center, startVertexId, ring, bondLength,
threshold = 0.1, innerThreshold = 0.1, maxIteration = 2000,
maxInnerIteration = 50, maxEnergy = 1e9) {
let edgeStrength = bondLength;
// Add vertices that are directly connected to the ring
var i = vertexIds.length;
while (i--) {
let vertex = this.vertices[vertexIds[i]];
var j = vertex.neighbours.length;
}
let matDist = this.getSubgraphDistanceMatrix(vertexIds);
let length = vertexIds.length;
// Initialize the positions. Place all vertices on a ring around the center
let radius = MathHelper.polyCircumradius(500, length);
let angle = MathHelper.centralAngle(length);
let a = 0.0;
let arrPositionX = new Float32Array(length);
let arrPositionY = new Float32Array(length);
let arrPositioned = Array(length);
i = length;
while (i--) {
let vertex = this.vertices[vertexIds[i]];
if (!vertex.positioned) {
arrPositionX[i] = center.x + Math.cos(a) * radius;
arrPositionY[i] = center.y + Math.sin(a) * radius;
} else {
arrPositionX[i] = vertex.position.x;
arrPositionY[i] = vertex.position.y;
}
arrPositioned[i] = vertex.positioned;
a += angle;
}
// Create the matrix containing the lengths
let matLength = Array(length);
i = length;
while (i--) {
matLength[i] = new Array(length);
var j = length;
while (j--) {
matLength[i][j] = bondLength * matDist[i][j];
}
}
// Create the matrix containing the spring strenghts
let matStrength = Array(length);
i = length;
while (i--) {
matStrength[i] = Array(length);
var j = length;
while (j--) {
matStrength[i][j] = edgeStrength * Math.pow(matDist[i][j], -2.0);
}
}
// Create the matrix containing the energies
let matEnergy = Array(length);
let arrEnergySumX = new Float32Array(length);
let arrEnergySumY = new Float32Array(length);
i = length;
while (i--) {
matEnergy[i] = Array(length);
}
i = length;
let ux, uy, dEx, dEy, vx, vy, denom;
while (i--) {
ux = arrPositionX[i];
uy = arrPositionY[i];
dEx = 0.0;
dEy = 0.0;
let j = length;
while (j--) {
if (i === j) {
continue;
}
vx = arrPositionX[j];
vy = arrPositionY[j];
denom = 1.0 / Math.sqrt((ux - vx) * (ux - vx) + (uy - vy) * (uy - vy));
matEnergy[i][j] = [
matStrength[i][j] * ((ux - vx) - matLength[i][j] * (ux - vx) * denom),
matStrength[i][j] * ((uy - vy) - matLength[i][j] * (uy - vy) * denom)
]
matEnergy[j][i] = matEnergy[i][j];
dEx += matEnergy[i][j][0];
dEy += matEnergy[i][j][1];
}
arrEnergySumX[i] = dEx;
arrEnergySumY[i] = dEy;
}
// Utility functions, maybe inline them later
let energy = function (index) {
return [arrEnergySumX[index] * arrEnergySumX[index] + arrEnergySumY[index] * arrEnergySumY[index], arrEnergySumX[index], arrEnergySumY[index]];
}
let highestEnergy = function () {
let maxEnergy = 0.0;
let maxEnergyId = 0;
let maxDEX = 0.0;
let maxDEY = 0.0
i = length;
while (i--) {
let [delta, dEX, dEY] = energy(i);
if (delta > maxEnergy && arrPositioned[i] === false) {
maxEnergy = delta;
maxEnergyId = i;
maxDEX = dEX;
maxDEY = dEY;
}
}
return [maxEnergyId, maxEnergy, maxDEX, maxDEY];
}
let update = function (index, dEX, dEY) {
let dxx = 0.0;
let dyy = 0.0;
let dxy = 0.0;
let ux = arrPositionX[index];
let uy = arrPositionY[index];
let arrL = matLength[index];
let arrK = matStrength[index];
i = length;
while (i--) {
if (i === index) {
continue;
}
let vx = arrPositionX[i];
let vy = arrPositionY[i];
let l = arrL[i];
let k = arrK[i];
let m = (ux - vx) * (ux - vx);
let denom = 1.0 / Math.pow(m + (uy - vy) * (uy - vy), 1.5);
dxx += k * (1 - l * (uy - vy) * (uy - vy) * denom);
dyy += k * (1 - l * m * denom);
dxy += k * (l * (ux - vx) * (uy - vy) * denom);
}
// Prevent division by zero
if (dxx === 0) {
dxx = 0.1;
}
if (dyy === 0) {
dyy = 0.1;
}
if (dxy === 0) {
dxy = 0.1;
}
let dy = (dEX / dxx + dEY / dxy);
dy /= (dxy / dxx - dyy / dxy); // had to split this onto two lines because the syntax highlighter went crazy.
let dx = -(dxy * dy + dEX) / dxx;
arrPositionX[index] += dx;
arrPositionY[index] += dy;
// Update the energies
let arrE = matEnergy[index];
dEX = 0.0;
dEY = 0.0;
ux = arrPositionX[index];
uy = arrPositionY[index];
let vx, vy, prevEx, prevEy, denom;
i = length;
while (i--) {
if (index === i) {
continue;
}
vx = arrPositionX[i];
vy = arrPositionY[i];
// Store old energies
prevEx = arrE[i][0];
prevEy = arrE[i][1];
denom = 1.0 / Math.sqrt((ux - vx) * (ux - vx) + (uy - vy) * (uy - vy));
dx = arrK[i] * ((ux - vx) - arrL[i] * (ux - vx) * denom);
dy = arrK[i] * ((uy - vy) - arrL[i] * (uy - vy) * denom);
arrE[i] = [dx, dy];
dEX += dx;
dEY += dy;
arrEnergySumX[i] += dx - prevEx;
arrEnergySumY[i] += dy - prevEy;
}
arrEnergySumX[index] = dEX;
arrEnergySumY[index] = dEY;
}
// Setting up variables for the while loops
let maxEnergyId = 0;
let dEX = 0.0;
let dEY = 0.0;
let delta = 0.0;
let iteration = 0;
let innerIteration = 0;
while (maxEnergy > threshold && maxIteration > iteration) {
iteration++;
[maxEnergyId, maxEnergy, dEX, dEY] = highestEnergy();
delta = maxEnergy;
innerIteration = 0;
while (delta > innerThreshold && maxInnerIteration > innerIteration) {
innerIteration++;
update(maxEnergyId, dEX, dEY);
[delta, dEX, dEY] = energy(maxEnergyId);
}
}
i = length;
while (i--) {
let index = vertexIds[i];
let vertex = this.vertices[index];
vertex.position.x = arrPositionX[i];
vertex.position.y = arrPositionY[i];
vertex.positioned = true;
vertex.forcePositioned = true;
}
}
/**
* PRIVATE FUNCTION used by getBridges().
*/
_bridgeDfs(u, visited, disc, low, parent, adj, outBridges) {
visited[u] = true;
disc[u] = low[u] = ++this._time;
for (var i = 0; i < adj[u].length; i++) {
let v = adj[u][i];
if (!visited[v]) {
parent[v] = u;
this._bridgeDfs(v, visited, disc, low, parent, adj, outBridges);
low[u] = Math.min(low[u], low[v]);
// If low > disc, we have a bridge
if (low[v] > disc[u]) {
outBridges.push([u, v]);
}
} else if (v !== parent[u]) {
low[u] = Math.min(low[u], disc[v]);
}
}
}
/**
* Returns the connected components of the graph.
*
* @param {Array[]} adjacencyMatrix An adjacency matrix.
* @returns {Set[]} Connected components as sets.
*/
static getConnectedComponents(adjacencyMatrix) {
let length = adjacencyMatrix.length;
let visited = new Array(length);
let components = new Array();
// let count = 0;
visited.fill(false);
for (var u = 0; u < length; u++) {
if (!visited[u]) {
let component = Array();
visited[u] = true;
component.push(u);
// count++;
Graph._ccGetDfs(u, visited, adjacencyMatrix, component);
if (component.length > 1) {
components.push(component);
}
}
}
return components;
}
/**
* Returns the number of connected components for the graph.
*
* @param {Array[]} adjacencyMatrix An adjacency matrix.
* @returns {Number} The number of connected components of the supplied graph.
*/
static getConnectedComponentCount(adjacencyMatrix) {
let length = adjacencyMatrix.length;
let visited = new Array(length);
let count = 0;
visited.fill(false);
for (var u = 0; u < length; u++) {
if (!visited[u]) {
visited[u] = true;
count++;
Graph._ccCountDfs(u, visited, adjacencyMatrix);
}
}
return count;
}
/**
* PRIVATE FUNCTION used by getConnectedComponentCount().
*/
static _ccCountDfs(u, visited, adjacencyMatrix) {
for (var v = 0; v < adjacencyMatrix[u].length; v++) {
let c = adjacencyMatrix[u][v];
if (!c || visited[v] || u === v) {
continue;
}
visited[v] = true;
Graph._ccCountDfs(v, visited, adjacencyMatrix);
}
}
/**
* PRIVATE FUNCTION used by getConnectedComponents().
*/
static _ccGetDfs(u, visited, adjacencyMatrix, component) {
for (var v = 0; v < adjacencyMatrix[u].length; v++) {
let c = adjacencyMatrix[u][v];
if (!c || visited[v] || u === v) {
continue;
}
visited[v] = true;
component.push(v);
Graph._ccGetDfs(v, visited, adjacencyMatrix, component);
}
}
}
export default Graph; | the_stack |
import { Plugin } from "@webiny/plugins/types";
import { TenancyContext } from "@webiny/api-tenancy/types";
import { SecurityPermission } from "@webiny/api-security/types";
import { FileManagerContext } from "@webiny/api-file-manager/types";
import { I18NContext } from "@webiny/api-i18n/types";
import { Topic } from "@webiny/pubsub/types";
import { UpgradePlugin } from "@webiny/api-upgrade/types";
interface FbFormTriggerData {
urls?: string[];
[key: string]: any;
}
interface FbSubmissionData {
[key: string]: any;
}
interface FbFormFieldValidator {
name: string;
message: any;
settings: {
/**
* In.
*/
values?: string[];
/**
* gte, lte, max, min
*/
value?: string;
/**
* Pattern.
*/
preset?: string;
[key: string]: any;
};
}
export interface FbFormFieldValidatorPlugin extends Plugin {
type: "fb-form-field-validator";
validator: {
name: string;
validate: (value: any, validator: FbFormFieldValidator) => Promise<any>;
};
}
export interface FbFormFieldPatternValidatorPlugin extends Plugin {
type: "fb-form-field-validator-pattern";
pattern: {
name: string;
regex: string;
flags: string;
};
}
export interface FbFormTriggerHandlerParams {
addLog: (log: Record<string, any>) => void;
trigger: FbFormTriggerData;
data: FbSubmissionData;
form: FbForm;
}
/**
* Used to define custom business logic that gets executed upon successful form submission (e.g. send data to a specific e-mail address).
* @see https://docs.webiny.com/docs/webiny-apps/form-builder/development/plugins-reference/api#form-trigger-handler
*/
export interface FbFormTriggerHandlerPlugin extends Plugin {
type: "form-trigger-handler";
trigger: string;
handle: (args: FbFormTriggerHandlerParams) => Promise<void>;
}
export interface FbFormFieldOption {
label?: string;
value?: string;
}
export interface FbFormField {
_id: string;
fieldId: string;
type: string;
name: string;
label: string;
placeholderText?: string;
helpText?: string;
options: FbFormFieldOption[];
validation: FbFormFieldValidator[];
settings?: Record<string, any>;
}
export interface FbForm {
id: string;
tenant: string;
locale: string;
createdBy: CreatedBy;
ownedBy: OwnedBy;
savedOn: string;
createdOn: string;
name: string;
slug: string;
version: number;
locked: boolean;
published: boolean;
publishedOn: string | null;
status: string;
fields: FbFormField[];
layout: string[][];
stats: Omit<FbFormStats, "conversionRate">;
settings: Record<string, any>;
triggers: Record<string, any> | null;
formId: string;
webinyVersion: string;
}
export interface CreatedBy {
id: string;
displayName: string | null;
type: string;
}
export type OwnedBy = CreatedBy;
interface FormCreateInput {
name: string;
}
interface FormUpdateInput {
name: string;
fields: Record<string, any>[];
layout: string[][];
settings: Record<string, any>;
triggers: Record<string, any>;
}
export interface FbFormStats {
submissions: number;
views: number;
conversionRate: number;
}
interface FbListSubmissionsOptions {
limit?: number;
after?: string;
sort?: string[];
}
export interface FbListSubmissionsMeta {
cursor: string | null;
hasMoreItems: boolean;
totalCount: number;
}
export interface FormBuilderGetFormOptions {
auth?: boolean;
}
export interface FormBuilderGetFormRevisionsOptions {
auth?: boolean;
}
export interface FormsCRUD {
getForm(id: string, options?: FormBuilderGetFormOptions): Promise<FbForm>;
getFormStats(id: string): Promise<FbFormStats>;
listForms(): Promise<FbForm[]>;
createForm(data: FormCreateInput): Promise<FbForm>;
updateForm(id: string, data: Partial<FormUpdateInput>): Promise<FbForm>;
deleteForm(id: string): Promise<boolean>;
publishForm(id: string): Promise<FbForm>;
unpublishForm(id: string): Promise<FbForm>;
createFormRevision(fromRevisionId: string): Promise<FbForm>;
incrementFormViews(id: string): Promise<boolean>;
incrementFormSubmissions(id: string): Promise<boolean>;
getFormRevisions(id: string, options?: FormBuilderGetFormRevisionsOptions): Promise<FbForm[]>;
getPublishedFormRevisionById(revisionId: string): Promise<FbForm>;
getLatestPublishedFormRevision(formId: string): Promise<FbForm>;
deleteFormRevision(id: string): Promise<boolean>;
}
export interface SubmissionsCRUD {
getSubmissionsByIds(form: string | FbForm, submissionIds: string[]): Promise<FbSubmission[]>;
listFormSubmissions(
formId: string,
options: FbListSubmissionsOptions
): Promise<[FbSubmission[], FbListSubmissionsMeta]>;
createFormSubmission(
formId: string,
reCaptchaResponseToken: string,
data: any,
meta: any
): Promise<FbSubmission>;
updateSubmission(formId: string, data: FbSubmission): Promise<boolean>;
deleteSubmission(formId: string, submissionId: string): Promise<boolean>;
}
export interface BeforeInstallTopic {
tenant: string;
locale: string;
}
export interface AfterInstallTopic {
tenant: string;
locale: string;
}
export interface SystemCRUD {
/**
* @internal
*/
getSystem(): Promise<System | null>;
getSystemVersion(): Promise<string | null>;
setSystemVersion(version: string): Promise<void>;
installSystem(args: { domain?: string }): Promise<void>;
upgradeSystem(version: string, data?: Record<string, any>): Promise<boolean>;
/**
* Events
*/
onBeforeInstall: Topic<BeforeInstallTopic>;
onAfterInstall: Topic<AfterInstallTopic>;
}
export interface FbSubmission {
id: string;
locale: string;
ownedBy: OwnedBy;
data: Record<string, any>;
meta: Record<string, any>;
form: {
id: string;
parent: string;
name: string;
version: number;
fields: Record<string, any>[];
layout: string[][];
};
logs: Record<string, any>[];
createdOn: string;
savedOn: string;
webinyVersion: string;
tenant: string;
}
export interface SubmissionInput {
data: Record<string, any>;
meta: Record<string, any>;
reCaptchaResponseToken: string;
}
export interface SubmissionUpdateData {
logs: Record<string, any>;
}
/**
* @category Settings
* @category DataModel
*/
export interface Settings {
domain: string;
reCaptcha: {
enabled: boolean;
siteKey: string;
secretKey: string;
};
tenant: string;
locale: string;
}
export interface SettingsCRUDGetParams {
auth?: boolean;
throwOnNotFound?: boolean;
}
export interface SettingsCRUD {
getSettings(params?: SettingsCRUDGetParams): Promise<Settings | null>;
createSettings(data: Partial<Settings>): Promise<Settings>;
updateSettings(data: Partial<Settings>): Promise<Settings>;
deleteSettings(): Promise<void>;
}
export interface FbFormPermission extends SecurityPermission {
name: "fb.form";
rwd: string;
pw: string;
own: boolean;
submissions: boolean;
}
export interface FbFormSettingsPermission extends SecurityPermission {
name: "fb.settings";
}
/**
* The object representing form builder internals.
*/
export interface FormBuilder extends SystemCRUD, SettingsCRUD, FormsCRUD, SubmissionsCRUD {
storageOperations: FormBuilderStorageOperations;
}
export interface FormBuilderContext extends TenancyContext, I18NContext, FileManagerContext {
/**
*
*/
formBuilder: FormBuilder;
}
/**
* @category System
* @category DataModel
*/
export interface System {
version?: string;
tenant: string;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
* @category System
*/
export interface FormBuilderStorageOperationsGetSystemParams {
tenant: string;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
* @category System
*/
export interface FormBuilderStorageOperationsCreateSystemParams {
system: System;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
* @category System
*/
export interface FormBuilderStorageOperationsUpdateSystemParams {
original: System;
system: System;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
* @category Settings
*/
export interface FormBuilderStorageOperationsGetSettingsParams {
tenant: string;
locale: string;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
* @category Settings
*/
export interface FormBuilderStorageOperationsCreateSettingsParams {
settings: Settings;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
* @category Settings
*/
export interface FormBuilderStorageOperationsUpdateSettingsParams {
original: Settings;
settings: Settings;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
* @category Settings
*/
export interface FormBuilderStorageOperationsDeleteSettingsParams {
settings: Settings;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsGetFormParams {
where: {
id?: string;
formId?: string;
version?: number;
published?: boolean;
latest?: boolean;
tenant: string;
locale: string;
};
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsListFormsParams {
where: {
id?: string;
version?: number;
slug?: string;
published?: boolean;
ownedBy?: string;
latest?: boolean;
tenant: string;
locale: string;
};
after: string | null;
limit: number;
sort: string[];
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsListFormRevisionsParamsWhere {
id?: string;
formId?: string;
version_not?: number;
publishedOn_not?: string | null;
tenant: string;
locale: string;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsListFormRevisionsParams {
where: FormBuilderStorageOperationsListFormRevisionsParamsWhere;
sort?: string[];
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsListFormsResponse {
items: FbForm[];
meta: {
hasMoreItems: boolean;
cursor: string | null;
totalCount: number;
};
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsCreateFormParams {
input: Record<string, any>;
form: FbForm;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsCreateFormFromParams {
original: FbForm;
latest: FbForm;
form: FbForm;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsUpdateFormParams {
input?: Record<string, any>;
original: FbForm;
form: FbForm;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsDeleteFormParams {
form: FbForm;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsDeleteFormRevisionParams {
/**
* Method always receives all the revisions of given form ordered by version_DESC.
*/
revisions: FbForm[];
/**
* Previous revision of the current form. Always the first lesser available version.
*/
previous: FbForm | null;
form: FbForm;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsPublishFormParams {
original: FbForm;
form: FbForm;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsUnpublishFormParams {
original: FbForm;
form: FbForm;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsGetSubmissionParams {
where: {
id: string;
formId: string;
tenant: string;
locale: string;
};
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsListSubmissionsParams {
where: {
id_in?: string[];
formId: string;
locale: string;
tenant: string;
};
after?: string | null;
limit?: number;
sort?: string[];
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsCreateSubmissionParams {
input: Record<string, any>;
form: FbForm;
submission: FbSubmission;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsUpdateSubmissionParams {
input: Record<string, any>;
form: FbForm;
original: FbSubmission;
submission: FbSubmission;
}
/**
* @category StorageOperations
* @category StorageOperationsParams
*/
export interface FormBuilderStorageOperationsDeleteSubmissionParams {
form: FbForm;
submission: FbSubmission;
}
/**
* @category StorageOperations
*/
export interface FormBuilderSystemStorageOperations {
getSystem(params: FormBuilderStorageOperationsGetSystemParams): Promise<System | null>;
createSystem(params: FormBuilderStorageOperationsCreateSystemParams): Promise<System>;
updateSystem(params: FormBuilderStorageOperationsUpdateSystemParams): Promise<System>;
}
/**
* @category StorageOperations
*/
export interface FormBuilderSettingsStorageOperations {
getSettings(params: FormBuilderStorageOperationsGetSettingsParams): Promise<Settings | null>;
createSettings(params: FormBuilderStorageOperationsCreateSettingsParams): Promise<Settings>;
updateSettings(params: FormBuilderStorageOperationsUpdateSettingsParams): Promise<Settings>;
deleteSettings(params: FormBuilderStorageOperationsDeleteSettingsParams): Promise<void>;
}
/**
* @category StorageOperations
*/
export interface FormBuilderFormStorageOperations {
getForm(params: FormBuilderStorageOperationsGetFormParams): Promise<FbForm | null>;
listForms(
params: FormBuilderStorageOperationsListFormsParams
): Promise<FormBuilderStorageOperationsListFormsResponse>;
listFormRevisions(
params: FormBuilderStorageOperationsListFormRevisionsParams
): Promise<FbForm[]>;
createForm(params: FormBuilderStorageOperationsCreateFormParams): Promise<FbForm>;
createFormFrom(params: FormBuilderStorageOperationsCreateFormFromParams): Promise<FbForm>;
updateForm(params: FormBuilderStorageOperationsUpdateFormParams): Promise<FbForm>;
/**
* Delete all form revisions + latest + published.
*/
deleteForm(params: FormBuilderStorageOperationsDeleteFormParams): Promise<FbForm>;
/**
* Delete the single form revision.
*/
deleteFormRevision(
params: FormBuilderStorageOperationsDeleteFormRevisionParams
): Promise<FbForm>;
publishForm(params: FormBuilderStorageOperationsPublishFormParams): Promise<FbForm>;
unpublishForm(params: FormBuilderStorageOperationsUnpublishFormParams): Promise<FbForm>;
}
/**
* @category StorageOperations
*/
export interface FormBuilderStorageOperationsListSubmissionsResponse {
items: FbSubmission[];
meta: FbListSubmissionsMeta;
}
/**
* @category StorageOperations
*/
export interface FormBuilderSubmissionStorageOperations {
getSubmission(
params: FormBuilderStorageOperationsGetSubmissionParams
): Promise<FbSubmission | null>;
listSubmissions(
params: FormBuilderStorageOperationsListSubmissionsParams
): Promise<FormBuilderStorageOperationsListSubmissionsResponse>;
createSubmission(
params: FormBuilderStorageOperationsCreateSubmissionParams
): Promise<FbSubmission>;
updateSubmission(
params: FormBuilderStorageOperationsUpdateSubmissionParams
): Promise<FbSubmission>;
deleteSubmission(
params: FormBuilderStorageOperationsDeleteSubmissionParams
): Promise<FbSubmission>;
}
/**
* @category StorageOperations
*/
export interface FormBuilderStorageOperations
extends FormBuilderSystemStorageOperations,
FormBuilderSettingsStorageOperations,
FormBuilderFormStorageOperations,
FormBuilderSubmissionStorageOperations {
beforeInit?: (context: FormBuilderContext) => Promise<void>;
init?: (context: FormBuilderContext) => Promise<void>;
/**
* An upgrade to run if necessary.
*/
upgrade?: UpgradePlugin | null;
} | the_stack |
import { ClientError, gql, GraphQLClient } from 'graphql-request';
import fetch, { Response } from 'node-fetch';
import readLine from 'readline';
import HttpAgent from 'agentkeepalive';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { SocksProxyAgent } from 'socks-proxy-agent';
import { HttpProxyAgent } from 'http-proxy-agent';
import { getAgent, AgentOptions } from '@teambit/toolbox.network.agent';
import { Network } from '../network';
import { getHarmonyVersion } from '../../../bootstrap';
import { BitId, BitIds } from '../../../bit-id';
import Component from '../../../consumer/component';
import { ListScopeResult } from '../../../consumer/component/components-list';
import DependencyGraph from '../../graph/scope-graph';
import { LaneData } from '../../lanes/lanes';
import { ComponentLog } from '../../models/model-component';
import { ScopeDescriptor } from '../../scope';
import globalFlags from '../../../cli/global-flags';
import { getSync, list } from '../../../api/consumer/lib/global-config';
import {
CFG_HTTPS_PROXY,
CFG_PROXY,
CFG_USER_TOKEN_KEY,
CFG_PROXY_CA,
CFG_PROXY_CERT,
CFG_PROXY_KEY,
CFG_PROXY_NO_PROXY,
CFG_PROXY_STRICT_SSL,
CFG_FETCH_RETRIES,
CFG_FETCH_RETRY_FACTOR,
CFG_FETCH_RETRY_MINTIMEOUT,
CFG_FETCH_RETRY_MAXTIMEOUT,
CFG_FETCH_TIMEOUT,
CFG_LOCAL_ADDRESS,
CFG_MAX_SOCKETS,
CFG_NETWORK_CONCURRENCY,
} from '../../../constants';
import logger from '../../../logger/logger';
import { ObjectItemsStream, ObjectList } from '../../objects/object-list';
import { FETCH_OPTIONS } from '../../../api/scope/lib/fetch';
import { remoteErrorHandler } from '../remote-error-handler';
import { PushOptions } from '../../../api/scope/lib/put';
import { HttpInvalidJsonResponse } from '../exceptions/http-invalid-json-response';
import RemovedObjects from '../../removed-components';
import { GraphQLClientError } from '../exceptions/graphql-client-error';
import loader from '../../../cli/loader';
import { UnexpectedNetworkError } from '../exceptions';
export enum Verb {
WRITE = 'write',
READ = 'read',
}
export type ProxyConfig = {
ca?: string;
cert?: string;
httpProxy?: string;
httpsProxy?: string;
key?: string;
noProxy?: boolean | string;
strictSSL?: boolean;
};
export type NetworkConfig = {
fetchRetries?: number;
fetchRetryFactor?: number;
fetchRetryMintimeout?: number;
fetchRetryMaxtimeout?: number;
fetchTimeout?: number;
localAddress?: string;
maxSockets?: number;
networkConcurrency?: number;
};
type Agent = HttpsProxyAgent | HttpAgent | HttpAgent.HttpsAgent | HttpProxyAgent | SocksProxyAgent | undefined;
/**
* fetched from HTTP Authorization header.
* (see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization)
*/
export type AuthData = { type: string; credentials: string };
export const DEFAULT_AUTH_TYPE = 'Bearer';
export class Http implements Network {
constructor(
private graphClient: GraphQLClient,
private _token: string | undefined | null,
private url: string,
private scopeName: string,
private proxyConfig?: ProxyConfig,
private agent?: Agent,
private localScopeName?: string,
private networkConfig?: NetworkConfig
) {}
static getToken() {
const processToken = globalFlags.token;
const token = processToken || getSync(CFG_USER_TOKEN_KEY);
if (!token) return null;
return token;
}
static async getProxyConfig(checkProxyUriDefined = true): Promise<ProxyConfig> {
const obj = await list();
const httpProxy = obj[CFG_PROXY];
const httpsProxy = obj[CFG_HTTPS_PROXY] ?? obj[CFG_PROXY];
// If check is true, return the proxy config only case there is actual proxy server defined
if (checkProxyUriDefined && !httpProxy && !httpsProxy) {
return {};
}
return {
ca: obj[CFG_PROXY_CA],
cert: obj[CFG_PROXY_CERT],
httpProxy,
httpsProxy,
key: obj[CFG_PROXY_KEY],
noProxy: obj[CFG_PROXY_NO_PROXY],
strictSSL: obj[CFG_PROXY_STRICT_SSL],
};
}
static async getNetworkConfig(): Promise<NetworkConfig> {
const obj = await list();
return {
fetchRetries: obj[CFG_FETCH_RETRIES],
fetchRetryFactor: obj[CFG_FETCH_RETRY_FACTOR],
fetchRetryMintimeout: obj[CFG_FETCH_RETRY_MINTIMEOUT],
fetchRetryMaxtimeout: obj[CFG_FETCH_RETRY_MAXTIMEOUT],
fetchTimeout: obj[CFG_FETCH_TIMEOUT],
localAddress: obj[CFG_LOCAL_ADDRESS],
maxSockets: obj[CFG_MAX_SOCKETS],
networkConcurrency: obj[CFG_NETWORK_CONCURRENCY],
};
}
static async getAgent(uri: string, agentOpts: AgentOptions): Promise<Agent> {
const agent = await getAgent(uri, agentOpts);
return agent;
}
get token() {
if (this._token === undefined) return this._token;
return Http.getToken();
}
close(): void {}
async describeScope(): Promise<ScopeDescriptor> {
const SCOPE_QUERY = gql`
{
scope {
name
}
}
`;
const data = await this.graphClientRequest(SCOPE_QUERY, Verb.READ);
return {
name: data.scope.name,
};
}
async deleteMany(ids: string[], force: boolean, context: Record<string, any>, idsAreLanes: boolean) {
const route = 'api/scope/delete';
logger.debug(`Http.delete, url: ${this.url}/${route}`);
const body = JSON.stringify({
ids,
force,
lanes: idsAreLanes,
});
const headers = this.getHeaders({ 'Content-Type': 'application/json', 'x-verb': 'write' });
const opts = this.addAgentIfExist({
method: 'post',
body,
headers,
});
const res = await fetch(`${this.url}/${route}`, opts);
await this.throwForNonOkStatus(res);
const results = await this.getJsonResponse(res);
return RemovedObjects.fromObjects(results);
}
async pushMany(objectList: ObjectList, pushOptions: PushOptions): Promise<string[]> {
const route = 'api/scope/put';
logger.debug(`Http.pushMany, url: ${this.url}/${route} total objects ${objectList.count()}`);
const body = objectList.toTar();
const headers = this.getHeaders({ 'push-options': JSON.stringify(pushOptions), 'x-verb': Verb.WRITE });
const opts = this.addAgentIfExist({
method: 'post',
body,
headers,
});
const res = await fetch(`${this.url}/${route}`, opts);
await this.throwForNonOkStatus(res);
const ids = await this.getJsonResponse(res);
return ids;
}
async pushToCentralHub(
objectList: ObjectList,
options: Record<string, any> = {}
): Promise<{
successIds: string[];
failedScopes: string[];
exportId: string;
errors: { [scopeName: string]: string };
}> {
const route = 'api/put';
logger.debug(`Http.pushToCentralHub, started. url: ${this.url}/${route}. total objects ${objectList.count()}`);
const pack = objectList.toTar();
const opts = this.addAgentIfExist({
method: 'post',
body: pack,
headers: this.getHeaders({ 'push-options': JSON.stringify(options), 'x-verb': Verb.WRITE }),
});
const res = await fetch(`${this.url}/${route}`, opts);
logger.debug(
`Http.pushToCentralHub, completed. url: ${this.url}/${route}, status ${res.status} statusText ${res.statusText}`
);
const results = await this.readPutCentralStream(res.body);
if (!results.data) throw new Error(`HTTP results are missing "data" property`);
if (results.data.isError) {
throw new UnexpectedNetworkError(results.message);
}
await this.throwForNonOkStatus(res);
return results.data;
}
async action<Options, Result>(name: string, options: Options): Promise<Result> {
const route = 'api/scope/action';
logger.debug(`Http.action, url: ${this.url}/${route}`);
const body = JSON.stringify({
name,
options,
});
const headers = this.getHeaders({ 'Content-Type': 'application/json', 'x-verb': Verb.WRITE });
const opts = this.addAgentIfExist({
method: 'post',
body,
headers,
});
const res = await fetch(`${this.url}/${route}`, opts);
await this.throwForNonOkStatus(res);
const results = await this.getJsonResponse(res);
return results;
}
async fetch(ids: string[], fetchOptions: FETCH_OPTIONS): Promise<ObjectItemsStream> {
const route = 'api/scope/fetch';
const scopeData = `scopeName: ${this.scopeName}, url: ${this.url}/${route}`;
logger.debug(`Http.fetch, ${scopeData}`);
const body = JSON.stringify({
ids,
fetchOptions,
});
const headers = this.getHeaders({ 'Content-Type': 'application/json', 'x-verb': Verb.READ });
const opts = this.addAgentIfExist({
method: 'post',
body,
headers,
});
const res = await fetch(`${this.url}/${route}`, opts);
logger.debug(`Http.fetch got a response, ${scopeData}, status ${res.status}, statusText ${res.statusText}`);
await this.throwForNonOkStatus(res);
const objectListReadable = ObjectList.fromTarToObjectStream(res.body);
return objectListReadable;
}
private async getJsonResponse(res: Response) {
try {
return await res.json();
} catch (err: any) {
logger.error('failed response', res);
throw new HttpInvalidJsonResponse(res.url);
}
}
private async throwForNonOkStatus(res: Response) {
if (res.ok) return;
let jsonResponse;
try {
jsonResponse = await res.json();
} catch (e: any) {
// the response is not json, ignore the body.
}
logger.error(`parsed error from HTTP, url: ${res.url}`, jsonResponse);
const error = jsonResponse?.error?.code ? jsonResponse?.error : jsonResponse;
if (error && !error.message && jsonResponse.message) error.message = jsonResponse.message;
const err = remoteErrorHandler(
error?.code,
error,
res.url,
`url: ${res.url}. status: ${res.status}. text: ${res.statusText}`
);
throw err;
}
private async graphClientRequest(query: string, verb: string = Verb.READ, variables?: Record<string, any>) {
logger.debug(`http.graphClientRequest, scope "${this.scopeName}", url "${this.url}", query ${query}`);
try {
this.graphClient.setHeader('x-verb', verb);
return await this.graphClient.request(query, variables);
} catch (err: any) {
if (err instanceof ClientError) {
throw new GraphQLClientError(err, this.url, this.scopeName);
}
// should not be here. it's just in case
throw err;
}
}
private async readPutCentralStream(body: NodeJS.ReadableStream): Promise<any> {
const readline = readLine.createInterface({
input: body,
crlfDelay: Infinity,
});
let results: Record<string, any> = {};
readline.on('line', (line) => {
const json = JSON.parse(line);
if (json.end) results = json;
loader.start(json.message);
});
return new Promise((resolve, reject) => {
readline.on('close', () => {
resolve(results);
});
readline.on('error', (err) => {
logger.error('readLine failed with error', err);
reject(new Error(`readline failed with error, ${err?.message}`));
});
});
}
async list(namespacesUsingWildcards?: string | undefined): Promise<ListScopeResult[]> {
const LIST_LEGACY = gql`
query listLegacy($namespaces: String) {
scope {
_legacyList(namespaces: $namespaces) {
id
deprecated
}
}
}
`;
const data = await this.graphClientRequest(LIST_LEGACY, Verb.READ, {
namespaces: namespacesUsingWildcards,
});
data.scope._legacyList.forEach((comp) => {
comp.id = BitId.parse(comp.id);
});
return data.scope._legacyList;
}
async show(bitId: BitId): Promise<Component | null | undefined> {
const SHOW_COMPONENT = gql`
query showLegacy($id: String!) {
scope {
_getLegacy(id: $id)
}
}
`;
const data = await this.graphClientRequest(SHOW_COMPONENT, Verb.READ, {
id: bitId.toString(),
});
return Component.fromString(data.scope._getLegacy);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async deprecateMany(ids: string[]): Promise<Record<string, any>[]> {
throw new Error(
`deprecation of a remote component has been disabled. deprecate locally with an updated version of bit and then tag and export`
);
// const DEPRECATE_COMPONENTS = gql`
// mutation deprecate($bitIds: [String!]!) {
// deprecate(bitIds: $bitIds) {
// bitIds
// missingComponents
// }
// }
// `;
// const res = await this.graphClientRequest(DEPRECATE_COMPONENTS, Verb.WRITE, {
// bitIds: ids,
// });
// return res.deprecate;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async undeprecateMany(ids: string[]): Promise<Record<string, any>[]> {
throw new Error(
`un-deprecation of a remote component has been disabled. undeprecate locally with an updated version of bit and then tag and export`
);
// const UNDEPRECATE_COMPONENTS = gql`
// mutation deprecate($bitIds: [String!]!) {
// undeprecate(bitIds: $bitIds) {
// bitIds
// missingComponents
// }
// }
// `;
// const res = await this.graphClientRequest(UNDEPRECATE_COMPONENTS, Verb.WRITE, {
// bitIds: ids,
// });
// return res.undeprecate;
}
async log(id: BitId): Promise<ComponentLog[]> {
const GET_LOG_QUERY = gql`
query getLogs($id: String!) {
scope {
getLogs(id: $id) {
message
username
email
date
hash
tag
}
}
}
`;
const data = await this.graphClientRequest(GET_LOG_QUERY, Verb.READ, {
id: id.toString(),
});
return data.scope.getLogs;
}
async latestVersions(bitIds: BitIds): Promise<string[]> {
const GET_LATEST_VERSIONS = gql`
query getLatestVersions($ids: [String]!) {
scope {
_legacyLatestVersions(ids: $ids)
}
}
`;
const data = await this.graphClientRequest(GET_LATEST_VERSIONS, Verb.READ, {
ids: bitIds.map((id) => id.toString()),
});
return data.scope._legacyLatestVersions;
}
async graph(bitId?: BitId): Promise<DependencyGraph> {
const GRAPH_QUERY = gql`
query graph($ids: [String], $filter: String) {
graph(ids: $ids, filter: $filter) {
nodes {
id
component {
id {
name
version
scope
}
}
}
edges {
sourceId
targetId
dependencyLifecycleType
}
}
}
`;
const { graph } = await this.graphClientRequest(GRAPH_QUERY, Verb.READ, {
ids: bitId ? [bitId.toString()] : [],
});
const nodes = graph.nodes.map((node) => ({ idStr: node.id, bitId: new BitId(node.component.id) }));
const edges = graph.edges.map((edge) => ({
src: edge.sourceId,
target: edge.targetId,
depType: edge.dependencyLifecycleType === 'DEV' ? 'devDependencies' : 'dependencies',
}));
const oldGraph = DependencyGraph.buildFromNodesAndEdges(nodes, edges);
return new DependencyGraph(oldGraph);
}
// TODO: ran (TBD)
async listLanes(name?: string | undefined, mergeData?: boolean | undefined): Promise<LaneData[]> {
const LIST_LANES = gql`
query listLanes() {
lanes {
list()
}
}
`;
const res = await this.graphClientRequest(LIST_LANES, Verb.READ, {
mergeData,
});
return res.lanes.list;
}
private getHeaders(headers: { [key: string]: string } = {}) {
const authHeader = this.token ? getAuthHeader(this.token) : {};
const localScope = this.localScopeName ? { 'x-request-scope': this.localScopeName } : {};
return Object.assign(
headers,
authHeader,
localScope,
{ connection: 'keep-alive' },
{ 'x-client-version': this.getClientVersion() }
);
}
private getClientVersion(): string {
return getHarmonyVersion();
}
private addAgentIfExist(opts: { [key: string]: any } = {}): Record<string, any> {
const optsWithAgent = this.agent ? Object.assign({}, opts, { agent: this.agent }) : opts;
return optsWithAgent;
}
static async connect(host: string, scopeName: string, localScopeName?: string) {
const token = Http.getToken();
const headers = token ? getAuthHeader(token) : {};
const proxyConfig = await Http.getProxyConfig();
const networkConfig = await Http.getNetworkConfig();
const agent = await Http.getAgent(host, {
...proxyConfig,
localAddress: networkConfig.localAddress,
maxSockets: networkConfig.maxSockets,
});
const graphQlUrl = `${host}/graphql`;
const graphQlFetcher = await getFetcherWithAgent(graphQlUrl);
const graphClient = new GraphQLClient(graphQlUrl, { headers, fetch: graphQlFetcher });
return new Http(graphClient, token, host, scopeName, proxyConfig, agent, localScopeName, networkConfig);
}
}
export function getAuthHeader(token: string) {
return {
Authorization: `${DEFAULT_AUTH_TYPE} ${token}`,
};
}
/**
* Read the proxy config from the global config, and wrap fetch with fetch with proxy
*/
export async function getFetcherWithAgent(uri: string) {
const proxyConfig = await Http.getProxyConfig();
const networkConfig = await Http.getNetworkConfig();
const agent = await Http.getAgent(uri, {
...proxyConfig,
localAddress: networkConfig.localAddress,
maxSockets: networkConfig.maxSockets,
});
const fetcher = agent ? wrapFetcherWithAgent(agent) : fetch;
return fetcher;
}
/**
* return a fetch wrapper with the proxy agent inside
* @param proxyAgent
*/
export function wrapFetcherWithAgent(agent: Agent) {
return (url, opts) => {
const actualOpts = Object.assign({}, opts, { agent });
return fetch(url, actualOpts);
};
}
export function getProxyAgent(proxy: string): HttpsProxyAgent {
const proxyAgent = new HttpsProxyAgent(proxy);
return proxyAgent;
}
export function getAuthDataFromHeader(authorizationHeader: string | undefined): AuthData | undefined {
if (!authorizationHeader) return undefined;
const authorizationSplit = authorizationHeader.split(' ');
if (authorizationSplit.length !== 2) {
throw new Error(
`fatal: HTTP Authorization header "${authorizationHeader}" is invalid. it should have exactly one space`
);
}
return { type: authorizationSplit[0], credentials: authorizationSplit[1] };
} | the_stack |
import {Entity} from './Entity';
import {System} from './System';
import {Class} from '../utils/Class';
import {Query} from './Query';
import {Subscription} from './Subscription';
import {Signal} from '../utils/Signal';
/**
* Engine represents game state, and provides entities update loop on top of systems.
*/
export class Engine {
/**
* Signal dispatches when new entity were added to engine
*/
public onEntityAdded: Signal<(entity: Entity) => void> = new Signal();
/**
* Signal dispatches when entity was removed from engine
*/
public onEntityRemoved: Signal<(entity: Entity) => void> = new Signal();
private _entityMap: Map<number, Entity> = new Map();
private _entities: Entity[] = [];
private _systems: System[] = [];
private _queries: Query[] = [];
private _subscriptions: Subscription<any>[] = [];
private _sharedConfig: Entity = new Entity();
/**
* Gets a list of entities added to engine
*/
public get entities(): ReadonlyArray<Entity> {
return Array.from(this._entities);
}
/**
* Gets a list of systems added to engine
*/
public get systems(): ReadonlyArray<System> {
return this._systems;
}
/**
* Gets a list of queries added to engine
*/
public get queries(): ReadonlyArray<Query> {
return this._queries;
}
public constructor() {
this.connectEntity(this._sharedConfig);
}
/**
* @internal
*/
public get subscriptions(): ReadonlyArray<Subscription<any>> {
return this._subscriptions;
}
/**
* Gets a shared config entity, that's accessible from every system added to engine
*
* @return {Entity}
*/
public get sharedConfig(): Entity {
return this._sharedConfig;
}
/**
* Adds an entity to engine.
* If entity is already added to engine - it does nothing.
*
* @param entity Entity to add to engine
* @see onEntityAdded
*/
public addEntity(entity: Entity): Engine {
if (this._entityMap.has(entity.id)) return this;
this._entities.push(entity);
this._entityMap.set(entity.id, entity);
this.onEntityAdded.emit(entity);
this.connectEntity(entity);
return this;
}
/**
* Remove entity from engine
* If engine not contains entity - it does nothing.
*
* @param entity Entity to remove from engine
* @see onEntityRemoved
*/
public removeEntity(entity: Entity): Engine {
if (!this._entityMap.has(entity.id)) return this;
const index = this._entities.indexOf(entity);
this._entities.splice(index, 1);
this._entityMap.delete(entity.id);
this.onEntityRemoved.emit(entity);
this.disconnectEntity(entity);
return this;
}
/**
* Removes a system from engine
* Avoid remove the system during update cycle, do it only if your sure what your are doing.
* Note: {@link IterativeSystem} has aware guard during update loop, if system removed - updating is being stopped.
*
* @param system System to remove
*/
public removeSystem(system: System): Engine {
const index = this._systems.indexOf(system);
if (index === -1) return this;
this._systems.splice(index, 1);
system.onRemovedFromEngine();
system.setEngine(undefined);
return this;
}
/**
* Gets an entity by its id
*
* @param {number} id Entity identifier
* @return {Entity | undefined} corresponding entity or undefined if it's not found.
*/
public getEntityById(id: number): Entity | undefined {
return this._entityMap.get(id);
}
/**
* Gets a system of the specific class
*
* @param systemClass Class of the system that should be found
*/
public getSystem<T extends System>(systemClass: Class<T>): T | undefined {
return this._systems.find(value => value instanceof systemClass) as T;
}
/**
* Remove all systems
*/
public removeAllSystems(): void {
const systems = this._systems;
this._systems = [];
for (const system of systems) {
system.onRemovedFromEngine();
}
}
/**
* Remove all queries.
* After remove all queries will be cleared.
*/
public removeAllQueries(): void {
const queries = this._queries;
this._queries = [];
for (const query of queries) {
this.disconnectQuery(query);
query.clear();
}
}
/**
* Remove all entities.
* onEntityRemoved will be fired for every entity.
*/
public removeAllEntities(): void {
this.removeAllEntitiesInternal(false);
}
/**
* Removes all entities, queries and systems.
* All entities will be removed silently, {@link onEntityRemoved} event will not be fired.
* Queries will be cleared.
*/
public clear(): void {
this.removeAllEntitiesInternal(true);
this.removeAllSystems();
this.removeAllQueries();
}
/**
* Updates the engine. This cause updating all the systems in the engine in the order of priority they've been added.
*
* @param dt Delta time in seconds
*/
public update(dt: number): void {
for (const system of this._systems) {
system.update(dt);
}
}
/**
* Adds a query to engine. It matches all available in engine entities with query.
*
* When any entity will be added, removed, their components will be modified - this query will be updated,
* until not being removed from engine.
*
* @param query Entity match query
*/
public addQuery(query: Query): Engine {
this.connectQuery(query);
query.matchEntities(this.entities);
this._queries[this._queries.length] = query;
return this;
}
/**
* Adds a system to engine, and set it's priority inside of engine update loop.
*
* @param system System to add to the engine
* @param priority Value indicating the priority of updating system in update loop. Lower priority
* means sooner update.
*/
public addSystem(system: System, priority: number = 0): Engine {
system.setPriority(priority);
if (this._systems.length === 0) {
this._systems[0] = system;
} else {
const index = this._systems.findIndex(value => value.priority > priority);
if (index === -1) {
this._systems[this._systems.length] = system;
} else {
this._systems.splice(index, 0, system);
}
}
system.setEngine(this);
system.onAddedToEngine();
return this;
}
/**
* Removes a query and clear it.
*
* @param query Entity match query
*/
public removeQuery(query: Query) {
const index = this._queries.indexOf(query);
if (index == -1) return undefined;
this._queries.splice(index, 1);
this.disconnectQuery(query);
query.clear();
return this;
}
/**
* Subscribe to any message of the {@link messageType}.
* Those messages can be dispatched from any system attached to the engine
*
* @param {Class<T> | T} messageType - Message type (can be class or any instance, for example string or number)
* @param {(value: T) => void} handler - Handler for the message
*/
public subscribe<T>(messageType: Class<T> | T, handler: (value: T) => void): void {
this.addSubscription(messageType, handler);
}
/**
* Unsubscribe from messages of specific type
*
* @param {Class<T>} messageType - Message type
* @param {(value: T) => void} handler - Specific handler that must be unsubscribed, if not defined then all handlers
* related to this message type will be unsubscribed.
*/
public unsubscribe<T>(messageType: Class<T> | T, handler?: (value: T) => void): void {
this.removeSubscription(messageType, handler);
}
/**
* Unsubscribe from all type of messages
*/
public unsubscribeAll(): void {
this._subscriptions.length = 0;
}
/**
* @internal
*/
public addSubscription<T>(messageType: Class<T> | T, handler: (value: T) => void): Subscription<T> {
for (const subscription of this._subscriptions) {
if (subscription.equals(messageType, handler)) return subscription;
}
const subscription = new Subscription<T>(messageType, handler);
this._subscriptions.push(subscription);
return subscription;
}
/**
* @internal
*/
public removeSubscription<T>(messageType: Class<T> | T, handler: ((value: T) => void) | undefined): void {
let i = this._subscriptions.length;
while (--i >= 0) {
const subscription = this._subscriptions[i];
if (subscription.equals(messageType, handler)) {
this._subscriptions.splice(i, 1);
if (handler !== undefined) return;
}
}
}
/**
* @internal
*/
public dispatch<T>(message: T) {
for (const subscription of this._subscriptions) {
if ((typeof subscription.messageType === 'function' && message instanceof subscription.messageType) || message === subscription.messageType) {
subscription.handler(message);
}
}
}
private connectEntity(entity: Entity) {
entity.onComponentAdded.connect(this.onComponentAdded, Number.POSITIVE_INFINITY);
entity.onComponentRemoved.connect(this.onComponentRemoved, Number.POSITIVE_INFINITY);
entity.onInvalidationRequested.connect(this.onInvalidationRequested, Number.NEGATIVE_INFINITY);
}
private disconnectEntity(entity: Entity) {
entity.onComponentAdded.disconnect(this.onComponentAdded);
entity.onComponentRemoved.disconnect(this.onComponentRemoved);
entity.onInvalidationRequested.disconnect(this.onInvalidationRequested);
}
private connectQuery(query: Query) {
this.onEntityAdded.connect(query.entityAdded);
this.onEntityRemoved.connect(query.entityRemoved);
}
private disconnectQuery(query: Query) {
this.onEntityAdded.disconnect(query.entityAdded);
this.onEntityRemoved.disconnect(query.entityRemoved);
}
private removeAllEntitiesInternal(silently: boolean): void {
const entities = this._entities;
this._entities = [];
this._entityMap.clear();
for (const entity of entities) {
if (!silently) {
this.onEntityRemoved.emit(entity);
}
this.disconnectEntity(entity);
}
}
private onComponentAdded = <T>(entity: Entity, component: NonNullable<T>, componentClass?: Class<NonNullable<T>>) => {
this._queries.forEach(value => value.entityComponentAdded(entity, component, componentClass));
};
private onInvalidationRequested = (entity: Entity) => {
this._queries.forEach(value => value.validateEntity(entity));
};
private onComponentRemoved = <T>(entity: Entity, component: NonNullable<T>, componentClass?: Class<NonNullable<T>>) => {
this._queries.forEach(value => value.entityComponentRemoved(entity, component, componentClass));
};
} | the_stack |
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as secretsmanager from '@aws-cdk/aws-secretsmanager';
import * as cdk from '@aws-cdk/core';
import { Construct } from 'constructs';
import { IDatabaseCluster } from './cluster-ref';
import { IEngine } from './engine';
import { IDatabaseInstance } from './instance';
import { engineDescription } from './private/util';
import { CfnDBProxy, CfnDBProxyTargetGroup } from './rds.generated';
/**
* SessionPinningFilter
*
* @see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy.html#rds-proxy-pinning
*/
export class SessionPinningFilter {
/**
* You can opt out of session pinning for the following kinds of application statements:
*
* - Setting session variables and configuration settings.
*/
public static readonly EXCLUDE_VARIABLE_SETS = new SessionPinningFilter('EXCLUDE_VARIABLE_SETS');
/**
* custom filter
*/
public static of(filterName: string): SessionPinningFilter {
return new SessionPinningFilter(filterName);
}
private constructor(
/**
* Filter name
*/
public readonly filterName: string,
) {}
}
/**
* Proxy target: Instance or Cluster
*
* A target group is a collection of databases that the proxy can connect to.
* Currently, you can specify only one RDS DB instance or Aurora DB cluster.
*/
export class ProxyTarget {
/**
* From instance
*
* @param instance RDS database instance
*/
public static fromInstance(instance: IDatabaseInstance): ProxyTarget {
return new ProxyTarget(instance, undefined);
}
/**
* From cluster
*
* @param cluster RDS database cluster
*/
public static fromCluster(cluster: IDatabaseCluster): ProxyTarget {
return new ProxyTarget(undefined, cluster);
}
private constructor(
private readonly dbInstance: IDatabaseInstance | undefined,
private readonly dbCluster: IDatabaseCluster | undefined) {
}
/**
* Bind this target to the specified database proxy.
*/
public bind(proxy: DatabaseProxy): ProxyTargetConfig {
const engine: IEngine | undefined = this.dbInstance?.engine ?? this.dbCluster?.engine;
if (!engine) {
const errorResource = this.dbCluster ?? this.dbInstance;
throw new Error(`Could not determine engine for proxy target '${errorResource?.node.path}'. ` +
'Please provide it explicitly when importing the resource');
}
const engineFamily = engine.engineFamily;
if (!engineFamily) {
throw new Error(`Engine '${engineDescription(engine)}' does not support proxies`);
}
// allow connecting to the Cluster/Instance from the Proxy
this.dbCluster?.connections.allowDefaultPortFrom(proxy, 'Allow connections to the database Cluster from the Proxy');
this.dbInstance?.connections.allowDefaultPortFrom(proxy, 'Allow connections to the database Instance from the Proxy');
return {
engineFamily,
dbClusters: this.dbCluster ? [this.dbCluster] : undefined,
dbInstances: this.dbInstance ? [this.dbInstance] : undefined,
};
}
}
/**
* The result of binding a `ProxyTarget` to a `DatabaseProxy`.
*/
export interface ProxyTargetConfig {
/**
* The engine family of the database instance or cluster this proxy connects with.
*/
readonly engineFamily: string;
/**
* The database instances to which this proxy connects.
* Either this or `dbClusters` will be set and the other `undefined`.
* @default - `undefined` if `dbClusters` is set.
*/
readonly dbInstances?: IDatabaseInstance[];
/**
* The database clusters to which this proxy connects.
* Either this or `dbInstances` will be set and the other `undefined`.
* @default - `undefined` if `dbInstances` is set.
*/
readonly dbClusters?: IDatabaseCluster[];
}
/**
* Options for a new DatabaseProxy
*/
export interface DatabaseProxyOptions {
/**
* The identifier for the proxy.
* This name must be unique for all proxies owned by your AWS account in the specified AWS Region.
* An identifier must begin with a letter and must contain only ASCII letters, digits, and hyphens;
* it can't end with a hyphen or contain two consecutive hyphens.
*
* @default - Generated by CloudFormation (recommended)
*/
readonly dbProxyName?: string;
/**
* The duration for a proxy to wait for a connection to become available in the connection pool.
* Only applies when the proxy has opened its maximum number of connections and all connections are busy with client
* sessions.
*
* Value must be between 1 second and 1 hour, or `Duration.seconds(0)` to represent unlimited.
*
* @default cdk.Duration.seconds(120)
*/
readonly borrowTimeout?: cdk.Duration;
/**
* One or more SQL statements for the proxy to run when opening each new database connection.
* Typically used with SET statements to make sure that each connection has identical settings such as time zone
* and character set.
* For multiple statements, use semicolons as the separator.
* You can also include multiple variables in a single SET statement, such as SET x=1, y=2.
*
* not currently supported for PostgreSQL.
*
* @default - no initialization query
*/
readonly initQuery?: string;
/**
* The maximum size of the connection pool for each target in a target group.
* For Aurora MySQL, it is expressed as a percentage of the max_connections setting for the RDS DB instance or Aurora DB
* cluster used by the target group.
*
* 1-100
*
* @default 100
*/
readonly maxConnectionsPercent?: number;
/**
* Controls how actively the proxy closes idle database connections in the connection pool.
* A high value enables the proxy to leave a high percentage of idle connections open.
* A low value causes the proxy to close idle client connections and return the underlying database connections
* to the connection pool.
* For Aurora MySQL, it is expressed as a percentage of the max_connections setting for the RDS DB instance
* or Aurora DB cluster used by the target group.
*
* between 0 and MaxConnectionsPercent
*
* @default 50
*/
readonly maxIdleConnectionsPercent?: number;
/**
* Each item in the list represents a class of SQL operations that normally cause all later statements in a session
* using a proxy to be pinned to the same underlying database connection.
* Including an item in the list exempts that class of SQL operations from the pinning behavior.
*
* @default - no session pinning filters
*/
readonly sessionPinningFilters?: SessionPinningFilter[];
/**
* Whether the proxy includes detailed information about SQL statements in its logs.
* This information helps you to debug issues involving SQL behavior or the performance and scalability of the proxy connections.
* The debug information includes the text of SQL statements that you submit through the proxy.
* Thus, only enable this setting when needed for debugging, and only when you have security measures in place to safeguard any sensitive
* information that appears in the logs.
*
* @default false
*/
readonly debugLogging?: boolean;
/**
* Whether to require or disallow AWS Identity and Access Management (IAM) authentication for connections to the proxy.
*
* @default false
*/
readonly iamAuth?: boolean;
/**
* The number of seconds that a connection to the proxy can be inactive before the proxy disconnects it.
* You can set this value higher or lower than the connection timeout limit for the associated database.
*
* @default cdk.Duration.minutes(30)
*/
readonly idleClientTimeout?: cdk.Duration;
/**
* A Boolean parameter that specifies whether Transport Layer Security (TLS) encryption is required for connections to the proxy.
* By enabling this setting, you can enforce encrypted TLS connections to the proxy.
*
* @default true
*/
readonly requireTLS?: boolean;
/**
* IAM role that the proxy uses to access secrets in AWS Secrets Manager.
*
* @default - A role will automatically be created
*/
readonly role?: iam.IRole;
/**
* The secret that the proxy uses to authenticate to the RDS DB instance or Aurora DB cluster.
* These secrets are stored within Amazon Secrets Manager.
* One or more secrets are required.
*/
readonly secrets: secretsmanager.ISecret[];
/**
* One or more VPC security groups to associate with the new proxy.
*
* @default - No security groups
*/
readonly securityGroups?: ec2.ISecurityGroup[];
/**
* The subnets used by the proxy.
*
* @default - the VPC default strategy if not specified.
*/
readonly vpcSubnets?: ec2.SubnetSelection;
/**
* The VPC to associate with the new proxy.
*/
readonly vpc: ec2.IVpc;
}
/**
* Construction properties for a DatabaseProxy
*/
export interface DatabaseProxyProps extends DatabaseProxyOptions {
/**
* DB proxy target: Instance or Cluster
*/
readonly proxyTarget: ProxyTarget
}
/**
* Properties that describe an existing DB Proxy
*/
export interface DatabaseProxyAttributes {
/**
* DB Proxy Name
*/
readonly dbProxyName: string;
/**
* DB Proxy ARN
*/
readonly dbProxyArn: string;
/**
* Endpoint
*/
readonly endpoint: string;
/**
* The security groups of the instance.
*/
readonly securityGroups: ec2.ISecurityGroup[];
}
/**
* DB Proxy
*/
export interface IDatabaseProxy extends cdk.IResource {
/**
* DB Proxy Name
*
* @attribute
*/
readonly dbProxyName: string;
/**
* DB Proxy ARN
*
* @attribute
*/
readonly dbProxyArn: string;
/**
* Endpoint
*
* @attribute
*/
readonly endpoint: string;
/**
* Grant the given identity connection access to the proxy.
*
* @param grantee the Principal to grant the permissions to
* @param dbUser the name of the database user to allow connecting as to the proxy
*
* @default - if the Proxy had been provided a single Secret value,
* the user will be taken from that Secret
*/
grantConnect(grantee: iam.IGrantable, dbUser?: string): iam.Grant;
}
/**
* Represents an RDS Database Proxy.
*
*/
abstract class DatabaseProxyBase extends cdk.Resource implements IDatabaseProxy {
public abstract readonly dbProxyName: string;
public abstract readonly dbProxyArn: string;
public abstract readonly endpoint: string;
public grantConnect(grantee: iam.IGrantable, dbUser?: string): iam.Grant {
if (!dbUser) {
throw new Error('For imported Database Proxies, the dbUser is required in grantConnect()');
}
const scopeStack = cdk.Stack.of(this);
const proxyGeneratedId = scopeStack.splitArn(this.dbProxyArn, cdk.ArnFormat.COLON_RESOURCE_NAME).resourceName;
const userArn = scopeStack.formatArn({
service: 'rds-db',
resource: 'dbuser',
resourceName: `${proxyGeneratedId}/${dbUser}`,
arnFormat: cdk.ArnFormat.COLON_RESOURCE_NAME,
});
return iam.Grant.addToPrincipal({
grantee,
actions: ['rds-db:connect'],
resourceArns: [userArn],
});
}
}
/**
* RDS Database Proxy
*
* @resource AWS::RDS::DBProxy
*/
export class DatabaseProxy extends DatabaseProxyBase
implements ec2.IConnectable, secretsmanager.ISecretAttachmentTarget {
/**
* Import an existing database proxy.
*/
public static fromDatabaseProxyAttributes(
scope: Construct,
id: string,
attrs: DatabaseProxyAttributes,
): IDatabaseProxy {
class Import extends DatabaseProxyBase {
public readonly dbProxyName = attrs.dbProxyName;
public readonly dbProxyArn = attrs.dbProxyArn;
public readonly endpoint = attrs.endpoint;
}
return new Import(scope, id);
}
/**
* DB Proxy Name
*
* @attribute
*/
public readonly dbProxyName: string;
/**
* DB Proxy ARN
*
* @attribute
*/
public readonly dbProxyArn: string;
/**
* Endpoint
*
* @attribute
*/
public readonly endpoint: string;
/**
* Access to network connections.
*/
public readonly connections: ec2.Connections;
private readonly secrets: secretsmanager.ISecret[];
private readonly resource: CfnDBProxy;
constructor(scope: Construct, id: string, props: DatabaseProxyProps) {
super(scope, id, { physicalName: props.dbProxyName || id });
const role = props.role || new iam.Role(this, 'IAMRole', {
assumedBy: new iam.ServicePrincipal('rds.amazonaws.com'),
});
for (const secret of props.secrets) {
secret.grantRead(role);
}
const securityGroups = props.securityGroups ?? [
new ec2.SecurityGroup(this, 'ProxySecurityGroup', {
description: 'SecurityGroup for Database Proxy',
vpc: props.vpc,
}),
];
this.connections = new ec2.Connections({ securityGroups });
const bindResult = props.proxyTarget.bind(this);
if (props.secrets.length < 1) {
throw new Error('One or more secrets are required.');
}
this.secrets = props.secrets;
this.resource = new CfnDBProxy(this, 'Resource', {
auth: props.secrets.map(_ => {
return {
authScheme: 'SECRETS',
iamAuth: props.iamAuth ? 'REQUIRED' : 'DISABLED',
secretArn: _.secretArn,
};
}),
dbProxyName: this.physicalName,
debugLogging: props.debugLogging,
engineFamily: bindResult.engineFamily,
idleClientTimeout: props.idleClientTimeout?.toSeconds(),
requireTls: props.requireTLS ?? true,
roleArn: role.roleArn,
vpcSecurityGroupIds: cdk.Lazy.list({ produce: () => this.connections.securityGroups.map(_ => _.securityGroupId) }),
vpcSubnetIds: props.vpc.selectSubnets(props.vpcSubnets).subnetIds,
});
this.dbProxyName = this.resource.ref;
this.dbProxyArn = this.resource.attrDbProxyArn;
this.endpoint = this.resource.attrEndpoint;
let dbInstanceIdentifiers: string[] | undefined;
if (bindResult.dbInstances) {
// support for only single instance
dbInstanceIdentifiers = [bindResult.dbInstances[0].instanceIdentifier];
}
let dbClusterIdentifiers: string[] | undefined;
if (bindResult.dbClusters) {
dbClusterIdentifiers = bindResult.dbClusters.map((c) => c.clusterIdentifier);
}
if (!!dbInstanceIdentifiers && !!dbClusterIdentifiers) {
throw new Error('Cannot specify both dbInstanceIdentifiers and dbClusterIdentifiers');
}
const proxyTargetGroup = new CfnDBProxyTargetGroup(this, 'ProxyTargetGroup', {
targetGroupName: 'default',
dbProxyName: this.dbProxyName,
dbInstanceIdentifiers,
dbClusterIdentifiers,
connectionPoolConfigurationInfo: toConnectionPoolConfigurationInfo(props),
});
bindResult.dbClusters?.forEach((c) => proxyTargetGroup.node.addDependency(c));
}
/**
* Renders the secret attachment target specifications.
*/
public asSecretAttachmentTarget(): secretsmanager.SecretAttachmentTargetProps {
return {
targetId: this.dbProxyName,
targetType: secretsmanager.AttachmentTargetType.RDS_DB_PROXY,
};
}
public grantConnect(grantee: iam.IGrantable, dbUser?: string): iam.Grant {
if (!dbUser) {
if (this.secrets.length > 1) {
throw new Error('When the Proxy contains multiple Secrets, you must pass a dbUser explicitly to grantConnect()');
}
// 'username' is the field RDS uses here,
// see https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy.html#rds-proxy-secrets-arns
dbUser = this.secrets[0].secretValueFromJson('username').toString();
}
return super.grantConnect(grantee, dbUser);
}
}
/**
* ConnectionPoolConfiguration (L2 => L1)
*/
function toConnectionPoolConfigurationInfo(
props: DatabaseProxyProps,
): CfnDBProxyTargetGroup.ConnectionPoolConfigurationInfoFormatProperty {
return {
connectionBorrowTimeout: props.borrowTimeout?.toSeconds(),
initQuery: props.initQuery,
maxConnectionsPercent: props.maxConnectionsPercent,
maxIdleConnectionsPercent: props.maxIdleConnectionsPercent,
sessionPinningFilters: props.sessionPinningFilters?.map(_ => _.filterName),
};
} | the_stack |
import {
Connection,
InitializeResult,
CompletionItem,
CompletionParams,
} from 'vscode-languageserver/node'
import { TextDocuments } from 'vscode-languageserver/lib/common/server'
import { CompletionTriggerKind } from 'vscode-languageserver-protocol/lib/common/protocol'
import { TextDocument } from 'vscode-languageserver-textdocument'
import { CodeAction, TextDocumentEdit, TextEdit, Position, CodeActionKind } from 'vscode-languageserver-types'
import cache from './cache'
import { complete } from './complete'
import createDiagnostics from './createDiagnostics'
import createConnection from './createConnection'
import yargs from 'yargs'
import SettingStore from './SettingStore'
import { Schema } from './database_libs/AbstractClient'
import getDatabaseClient from './database_libs/getDatabaseClient'
import initializeLogging from './initializeLogging'
import { lint, LintResult } from 'sqlint'
import log4js from 'log4js'
import { RequireSqlite3Error } from './database_libs/Sqlite3Client'
import * as fs from 'fs'
import { RawConfig } from 'sqlint'
export type ConnectionMethod = 'node-ipc' | 'stdio'
type Args = {
method?: ConnectionMethod
}
const TRIGGER_CHARATER = '.'
export function createServerWithConnection(connection: Connection) {
initializeLogging()
const logger = log4js.getLogger()
let documents = new TextDocuments(TextDocument)
documents.listen(connection);
let schema: Schema = { tables: [], functions: [] }
let hasConfigurationCapability = false
let rootPath = ''
let lintConfig: RawConfig | null | undefined
// Read schema file
function readJsonSchemaFile(filePath: string) {
logger.info(`loading schema file: ${filePath}`)
const data = fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
try {
schema = JSON.parse(data);
}
catch (e: any) {
logger.error("failed to read schema file " + e.message)
connection.sendNotification('sqlLanguageServer.error', {
message: "Failed to read schema file: " + filePath + " error: " + e.message
})
throw e
}
}
function readAndMonitorJsonSchemaFile(filePath: string) {
fs.watchFile(filePath, (_curr, _prev) => {
logger.info(`change detected, reloading schema file: ${filePath}`)
readJsonSchemaFile(filePath)
})
// The readJsonSchemaFile function can throw exceptions so
// read file only after setting up monitoring
readJsonSchemaFile(filePath)
}
async function makeDiagnostics(document: TextDocument) {
const hasRules = lintConfig?.hasOwnProperty('rules')
const diagnostics = createDiagnostics(
document.uri,
document.getText(),
hasRules ? lintConfig : null
)
connection.sendDiagnostics(diagnostics)
}
documents.onDidChangeContent(async (params) => {
logger.debug(`onDidChangeContent: ${params.document.uri}, ${params.document.version}`)
makeDiagnostics(params.document)
})
connection.onInitialize((params): InitializeResult => {
const capabilities = params.capabilities
// JupyterLab sends didChangeConfiguration information
// using both the workspace.configuration and
// workspace.didChangeConfiguration
hasConfigurationCapability = !!capabilities.workspace && (
!!capabilities.workspace.configuration ||
!!capabilities.workspace.didChangeConfiguration);
logger.debug(`onInitialize: ${params.rootPath}`)
rootPath = params.rootPath || ''
return {
capabilities: {
textDocumentSync: 1,
completionProvider: {
resolveProvider: true,
triggerCharacters: [TRIGGER_CHARATER],
},
renameProvider: true,
codeActionProvider: true,
executeCommandProvider: {
commands: [
'sqlLanguageServer.switchDatabaseConnection',
'sqlLanguageServer.fixAllFixableProblems'
]
}
}
}
})
connection.onInitialized(async () => {
SettingStore.getInstance().on('change', async () => {
logger.debug('onInitialize: receive change event from SettingStore')
try {
try {
connection.sendNotification('sqlLanguageServer.finishSetup', {
personalConfig: SettingStore.getInstance().getPersonalConfig(),
config: SettingStore.getInstance().getSetting()
})
} catch (e) {
logger.error(e)
}
var setting = SettingStore.getInstance().getSetting()
if (setting.adapter == 'json') {
// Loading schema from json file
var path = setting.filename || ""
if (path == "") {
logger.error("filename must be provided")
connection.sendNotification('sqlLanguageServer.error', {
message: "filename must be provided"
})
throw "filename must be provided"
}
readAndMonitorJsonSchemaFile(path)
}
else {
// Else get schema form database client
try {
const client = getDatabaseClient(
SettingStore.getInstance().getSetting()
)
schema = await client.getSchema()
logger.debug("get schema")
logger.debug(JSON.stringify(schema))
} catch (e) {
logger.error("failed to get schema info")
if (e instanceof RequireSqlite3Error) {
connection.sendNotification('sqlLanguageServer.error', {
message: "Need to rebuild sqlite3 module."
})
}
throw e
}
}
} catch (e) {
logger.error(e)
}
})
const connections = hasConfigurationCapability && (
await connection.workspace.getConfiguration({
section: 'sqlLanguageServer',
})
)?.connections || []
if (connections.length > 0) {
SettingStore.getInstance().setSettingFromWorkspaceConfig(connections)
} else if (rootPath) {
SettingStore.getInstance().setSettingFromFile(
`${process.env.HOME}/.config/sql-language-server/.sqllsrc.json`,
`${rootPath}/.sqllsrc.json`,
rootPath || ''
)
}
})
connection.onDidChangeConfiguration(change => {
logger.debug('onDidChangeConfiguration', JSON.stringify(change))
if (!hasConfigurationCapability) {
return
}
const connections = change.settings?.sqlLanguageServer?.connections ?? []
if (connections.length > 0) {
SettingStore.getInstance().setSettingFromWorkspaceConfig(connections)
}
// On configuration changes we retrieve the lint config
const lint = change.settings?.sqlLanguageServer?.lint
lintConfig = lint
if (lint?.rules) {
documents.all().forEach(v => {
makeDiagnostics(v)
})
}
})
connection.onCompletion((docParams: CompletionParams): CompletionItem[] => {
// Make sure the client does not send use completion request for characters
// other than the dot which we asked for.
if (docParams.context?.triggerKind == CompletionTriggerKind.TriggerCharacter) {
if (docParams.context?.triggerCharacter != TRIGGER_CHARATER) {
return []
}
}
let text = documents.get(docParams.textDocument.uri)?.getText()
if (!text) {
return []
}
logger.debug(text || '')
let pos = { line: docParams.position.line, column: docParams.position.character }
var setting = SettingStore.getInstance().getSetting()
const candidates = complete(text, pos, schema, setting.jupyterLabMode).candidates
if (logger.isDebugEnabled()) logger.debug('onCompletion returns: ' + JSON.stringify(candidates))
return candidates
})
connection.onCodeAction(params => {
const lintResult = cache.findLintCacheByRange(params.textDocument.uri, params.range)
if (!lintResult) {
return []
}
const document = documents.get(params.textDocument.uri)
if (!document) {
return []
}
const text = document.getText()
if (!text) {
return []
}
function toPosition(text: string, offset: number) {
const lines = text.slice(0, offset).split('\n')
return Position.create(lines.length - 1, lines[lines.length - 1].length)
}
const fixes = Array.isArray(lintResult.lint.fix) ? lintResult.lint.fix : [lintResult.lint.fix]
if (fixes.length === 0) {
return []
}
const action = CodeAction.create(`fix: ${lintResult.diagnostic.message}`, {
documentChanges: [
TextDocumentEdit.create({ uri: params.textDocument.uri, version: document.version }, fixes.map(v => {
const edit = v.range.startOffset === v.range.endOffset
? TextEdit.insert(toPosition(text, v.range.startOffset), v.text)
: TextEdit.replace({
start: toPosition(text, v.range.startOffset),
end: toPosition(text, v.range.endOffset)
}, v.text)
return edit
}))
]
}, CodeActionKind.QuickFix)
action.diagnostics = params.context.diagnostics
return [action]
})
connection.onCompletionResolve((item: CompletionItem): CompletionItem => {
return item
})
connection.onExecuteCommand((request) => {
logger.debug(`received executeCommand request: ${request.command}, ${request.arguments}`)
if (
request.command === 'switchDatabaseConnection' ||
request.command === 'sqlLanguageServer.switchDatabaseConnection'
) {
try {
SettingStore.getInstance().changeConnection(
request.arguments && request.arguments[0] || ''
)
} catch (e: any) {
connection.sendNotification('sqlLanguageServer.error', {
message: e.message
})
}
} else if (
request.command === 'fixAllFixableProblems' ||
request.command === 'sqlLanguageServer.fixAllFixableProblems'
) {
const uri = request.arguments ? request.arguments[0] : null
if (!uri) {
connection.sendNotification('sqlLanguageServer.error', {
message: 'fixAllFixableProblems: Need to specify uri'
})
return
}
const document = documents.get(uri)
const text = document?.getText()
if (!text) {
logger.debug('Failed to get text')
return
}
const result: LintResult[] = JSON.parse(lint({ formatType: 'json', text, fix: true }))
if (result.length === 0 && result[0].fixedText) {
logger.debug("There's no fixable problems")
return
}
logger.debug('Fix all fixable problems', text, result[0].fixedText)
connection.workspace.applyEdit({
documentChanges: [
TextDocumentEdit.create({ uri, version: document!.version }, [
TextEdit.replace({
start: Position.create(0, 0),
end: Position.create(Number.MAX_VALUE, Number.MAX_VALUE)
}, result[0].fixedText!)
])
]
})
}
})
connection.listen()
logger.info('start sql-languager-server')
return connection
}
export function createServer() {
let connection: Connection = createConnection((yargs.argv as Args).method || 'node-ipc')
return createServerWithConnection(connection)
} | the_stack |
import { createSelector } from 'reselect'
import flatMap from 'lodash/flatMap'
import isEmpty from 'lodash/isEmpty'
import mapValues from 'lodash/mapValues'
import uniq from 'lodash/uniq'
import { getFileMetadata } from './fileFields'
import { getInitialRobotState, getRobotStateTimeline } from './commands'
import { selectors as dismissSelectors } from '../../dismiss'
import {
selectors as labwareDefSelectors,
LabwareDefByDefURI,
} from '../../labware-defs'
import { selectors as ingredSelectors } from '../../labware-ingred/selectors'
import { selectors as stepFormSelectors } from '../../step-forms'
import { selectors as uiLabwareSelectors } from '../../ui/labware'
import {
DEFAULT_MM_FROM_BOTTOM_ASPIRATE,
DEFAULT_MM_FROM_BOTTOM_DISPENSE,
DEFAULT_MM_TOUCH_TIP_OFFSET_FROM_TOP,
DEFAULT_MM_BLOWOUT_OFFSET_FROM_TOP,
} from '../../constants'
import {
ModuleEntity,
PipetteEntity,
LabwareEntities,
PipetteEntities,
Timeline,
} from '@opentrons/step-generation'
import {
FilePipette,
FileLabware,
FileModule,
} from '@opentrons/shared-data/protocol/types/schemaV4'
import { Command } from '@opentrons/shared-data/protocol/types/schemaV5Addendum'
import { Selector } from '../../types'
import { PDProtocolFile } from '../../file-types'
// TODO: BC: 2018-02-21 uncomment this assert, causes test failures
// assert(!isEmpty(process.env.OT_PD_VERSION), 'Could not find application version!')
if (isEmpty(process.env.OT_PD_VERSION))
console.warn('Could not find application version!')
const applicationVersion: string = process.env.OT_PD_VERSION || ''
// Internal release date: this should never be read programatically,
// it just helps us humans quickly identify what build a user was using
// when we look at saved protocols (without requiring us to trace thru git logs)
const _internalAppBuildDate = process.env.OT_PD_BUILD_DATE
// A labware definition is considered "in use" and should be included in
// the protocol file if it either...
// 1. is present on the deck in initial deck setup
// 2. OR is a tiprack def assigned to a pipette, even if it's not on the deck
export const getLabwareDefinitionsInUse = (
labware: LabwareEntities,
pipettes: PipetteEntities,
allLabwareDefsByURI: LabwareDefByDefURI
): LabwareDefByDefURI => {
const labwareDefURIsOnDeck: string[] = Object.keys(labware).map(
(labwareId: string) => labware[labwareId].labwareDefURI
)
const tiprackDefURIsInUse: string[] = Object.keys(pipettes)
.map(id => pipettes[id])
.map((pipetteEntity: PipetteEntity) => pipetteEntity.tiprackDefURI)
const labwareDefURIsInUse = uniq([
...tiprackDefURIsInUse,
...labwareDefURIsOnDeck,
])
return labwareDefURIsInUse.reduce<LabwareDefByDefURI>(
(acc, labwareDefURI: string) => ({
...acc,
[labwareDefURI]: allLabwareDefsByURI[labwareDefURI],
}),
{}
)
}
// NOTE: V3 commands are a subset of V4 commands.
// 'airGap' is specified in the V3 schema but was never implemented, so it doesn't count.
const _isV3Command = (command: Command): boolean =>
command.command === 'aspirate' ||
command.command === 'dispense' ||
command.command === 'blowout' ||
command.command === 'touchTip' ||
command.command === 'pickUpTip' ||
command.command === 'dropTip' ||
command.command === 'moveToSlot' ||
command.command === 'delay'
// This is a HACK to allow PD to not have to export protocols under the not-yet-released
// v6 schema with the dispenseAirGap command, by replacing all dispenseAirGaps with dispenses
// Once we have v6 in the wild, just use the ordinary getRobotStateTimeline and
// delete this getRobotStateTimelineWithoutAirGapDispenseCommand.
export const getRobotStateTimelineWithoutAirGapDispenseCommand: Selector<Timeline> = createSelector(
getRobotStateTimeline,
robotStateTimeline => {
const timeline = robotStateTimeline.timeline.map(frame => ({
...frame,
commands: frame.commands.map(command => {
if (command.command === 'dispenseAirGap') {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return { ...command, command: 'dispense' } as Command
}
return command
}),
}))
return { ...robotStateTimeline, timeline }
}
)
/** If there are any module entities or and v4-specific commands,
** export as a v4 protocol. Otherwise, export as v3.
**
** NOTE: In real life, you shouldn't be able to have v4 atomic commands
** without having module entities b/c this will produce "no module for this step"
** form/timeline errors. Checking for v4 commands should be redundant,
** we do it just in case non-V3 commands somehow sneak in despite having no modules. */
export const getRequiresAtLeastV4: Selector<boolean> = createSelector(
getRobotStateTimelineWithoutAirGapDispenseCommand,
stepFormSelectors.getModuleEntities,
(robotStateTimeline, moduleEntities) => {
const noModules = isEmpty(moduleEntities)
const hasOnlyV3Commands = robotStateTimeline.timeline.every(timelineFrame =>
timelineFrame.commands.every(command => _isV3Command(command))
)
const isV3 = noModules && hasOnlyV3Commands
return !isV3
}
)
// Note: though airGap is supported in the v4 executor, we want to simplify things
// for users in terms of managing robot stack upgrades, so we will force v5
const _requiresV5 = (command: Command): boolean =>
command.command === 'moveToWell' || command.command === 'airGap'
export const getRequiresAtLeastV5: Selector<boolean> = createSelector(
getRobotStateTimelineWithoutAirGapDispenseCommand,
robotStateTimeline => {
return robotStateTimeline.timeline.some(timelineFrame =>
timelineFrame.commands.some(command => _requiresV5(command))
)
}
)
export const getExportedFileSchemaVersion: Selector<number> = createSelector(
getRequiresAtLeastV4,
getRequiresAtLeastV5,
(requiresV4, requiresV5) => {
if (requiresV5) {
return 5
} else if (requiresV4) {
return 4
} else {
return 3
}
}
)
// @ts-expect-error(IL, 2020-03-02): presence of non-v3 commands should make 'isV4Protocol' true
export const createFile: Selector<PDProtocolFile> = createSelector(
getFileMetadata,
getInitialRobotState,
getRobotStateTimelineWithoutAirGapDispenseCommand,
dismissSelectors.getAllDismissedWarnings,
ingredSelectors.getLiquidGroupsById,
ingredSelectors.getLiquidsByLabwareId,
stepFormSelectors.getSavedStepForms,
stepFormSelectors.getOrderedStepIds,
stepFormSelectors.getLabwareEntities,
stepFormSelectors.getModuleEntities,
stepFormSelectors.getPipetteEntities,
uiLabwareSelectors.getLabwareNicknamesById,
labwareDefSelectors.getLabwareDefsByURI,
getRequiresAtLeastV4,
getRequiresAtLeastV5,
(
fileMetadata,
initialRobotState,
robotStateTimeline,
dismissedWarnings,
ingredients,
ingredLocations,
savedStepForms,
orderedStepIds,
labwareEntities,
moduleEntities,
pipetteEntities,
labwareNicknamesById,
labwareDefsByURI,
requiresAtLeastV4Protocol,
requiresAtLeastV5Protocol
) => {
const { author, description, created } = fileMetadata
const name = fileMetadata.protocolName || 'untitled'
const lastModified = fileMetadata.lastModified
const pipettes = mapValues(
initialRobotState.pipettes,
(
pipette: typeof initialRobotState.pipettes[keyof typeof initialRobotState.pipettes],
pipetteId: string
): FilePipette => ({
mount: pipette.mount,
name: pipetteEntities[pipetteId].name,
})
)
const labware: Record<string, FileLabware> = mapValues(
initialRobotState.labware,
(
l: typeof initialRobotState.labware[keyof typeof initialRobotState.labware],
labwareId: string
): FileLabware => ({
slot: l.slot,
displayName: labwareNicknamesById[labwareId],
definitionId: labwareEntities[labwareId].labwareDefURI,
})
)
const modules: Record<string, FileModule> = mapValues(
moduleEntities,
(moduleEntity: ModuleEntity, moduleId: string): FileModule => ({
slot: initialRobotState.modules[moduleId].slot,
model: moduleEntity.model,
})
)
// TODO: Ian 2018-07-10 allow user to save steps in JSON file, even if those
// step never have saved forms.
// (We could just export the `steps` reducer, but we've sunset it)
const savedOrderedStepIds = orderedStepIds.filter(
stepId => savedStepForms[stepId]
)
const labwareDefinitions = getLabwareDefinitionsInUse(
labwareEntities,
pipetteEntities,
labwareDefsByURI
)
const commands: Command[] = flatMap(
robotStateTimeline.timeline,
timelineFrame => timelineFrame.commands
)
const protocolFile = {
metadata: {
protocolName: name,
author,
description,
created,
lastModified,
// TODO LATER
category: null,
subcategory: null,
tags: [],
},
designerApplication: {
name: 'opentrons/protocol-designer',
version: applicationVersion,
data: {
_internalAppBuildDate,
defaultValues: {
// TODO: Ian 2019-06-13 load these into redux and always get them from redux, not constants.js
// This `defaultValues` key is not yet read by anything, but is populated here for auditability
// and so that later we can do #3587 without a PD migration
aspirate_mmFromBottom: DEFAULT_MM_FROM_BOTTOM_ASPIRATE,
dispense_mmFromBottom: DEFAULT_MM_FROM_BOTTOM_DISPENSE,
touchTip_mmFromTop: DEFAULT_MM_TOUCH_TIP_OFFSET_FROM_TOP,
blowout_mmFromTop: DEFAULT_MM_BLOWOUT_OFFSET_FROM_TOP,
},
pipetteTiprackAssignments: mapValues(
pipetteEntities,
(
p: typeof pipetteEntities[keyof typeof pipetteEntities]
): string | null | undefined => p.tiprackDefURI
),
dismissedWarnings,
ingredients,
ingredLocations,
savedStepForms,
orderedStepIds: savedOrderedStepIds,
},
},
robot: {
model: 'OT-2 Standard',
},
pipettes,
labware,
labwareDefinitions,
}
if (requiresAtLeastV5Protocol) {
return {
...protocolFile,
$otSharedSchema: '#/protocol/schemas/5',
schemaVersion: 5,
modules,
commands,
}
} else if (requiresAtLeastV4Protocol) {
return {
...protocolFile,
$otSharedSchema: '#/protocol/schemas/4',
schemaVersion: 4,
modules,
commands,
}
} else {
return { ...protocolFile, schemaVersion: 3, commands }
}
}
) | the_stack |
import * as crypto from 'crypto';
import * as dateFormat from 'date-and-time';
import * as http from 'http';
import * as url from 'url';
import {encodeURI, qsStringify, objectEntries} from './util';
interface GetCredentialsResponse {
client_email?: string;
}
export interface AuthClient {
sign(blobToSign: string): Promise<string>;
getCredentials(): Promise<GetCredentialsResponse>;
}
export interface BucketI {
name: string;
}
export interface FileI {
name: string;
}
export interface Query {
[key: string]: string;
}
export interface GetSignedUrlConfigInternal {
expiration: number;
accessibleAt?: Date;
method: string;
extensionHeaders?: http.OutgoingHttpHeaders;
queryParams?: Query;
cname?: string;
contentMd5?: string;
contentType?: string;
bucket: string;
file?: string;
}
interface SignedUrlQuery {
generation?: number;
'response-content-type'?: string;
'response-content-disposition'?: string;
}
interface V2SignedUrlQuery extends SignedUrlQuery {
GoogleAccessId: string;
Expires: number;
Signature: string;
}
export interface SignerGetSignedUrlConfig {
method: 'GET' | 'PUT' | 'DELETE' | 'POST';
expires: string | number | Date;
accessibleAt?: string | number | Date;
virtualHostedStyle?: boolean;
version?: 'v2' | 'v4';
cname?: string;
extensionHeaders?: http.OutgoingHttpHeaders;
queryParams?: Query;
contentMd5?: string;
contentType?: string;
}
export type SignerGetSignedUrlResponse = string;
export type GetSignedUrlResponse = [SignerGetSignedUrlResponse];
export interface GetSignedUrlCallback {
(err: Error | null, url?: string): void;
}
type ValueOf<T> = T[keyof T];
type HeaderValue = ValueOf<http.OutgoingHttpHeaders>;
/*
* Default signing version for getSignedUrl is 'v2'.
*/
const DEFAULT_SIGNING_VERSION = 'v2';
const SEVEN_DAYS = 604800;
/**
* @const {string}
* @private
*/
export const PATH_STYLED_HOST = 'https://storage.googleapis.com';
export class URLSigner {
private authClient: AuthClient;
private bucket: BucketI;
private file?: FileI;
constructor(authClient: AuthClient, bucket: BucketI, file?: FileI) {
this.bucket = bucket;
this.file = file;
this.authClient = authClient;
}
getSignedUrl(
cfg: SignerGetSignedUrlConfig
): Promise<SignerGetSignedUrlResponse> {
const expiresInSeconds = this.parseExpires(cfg.expires);
const method = cfg.method;
const accessibleAtInSeconds = this.parseAccessibleAt(cfg.accessibleAt);
if (expiresInSeconds < accessibleAtInSeconds) {
throw new Error('An expiration date cannot be before accessible date.');
}
let customHost: string | undefined;
// Default style is `path`.
const isVirtualHostedStyle = cfg.virtualHostedStyle || false;
if (cfg.cname) {
customHost = cfg.cname;
} else if (isVirtualHostedStyle) {
customHost = `https://${this.bucket.name}.storage.googleapis.com`;
}
const secondsToMilliseconds = 1000;
const config: GetSignedUrlConfigInternal = Object.assign({}, cfg, {
method,
expiration: expiresInSeconds,
accessibleAt: new Date(secondsToMilliseconds * accessibleAtInSeconds),
bucket: this.bucket.name,
file: this.file ? encodeURI(this.file.name, false) : undefined,
});
if (customHost) {
config.cname = customHost;
}
const version = cfg.version || DEFAULT_SIGNING_VERSION;
let promise: Promise<SignedUrlQuery>;
if (version === 'v2') {
promise = this.getSignedUrlV2(config);
} else if (version === 'v4') {
promise = this.getSignedUrlV4(config);
} else {
throw new Error(
`Invalid signed URL version: ${version}. Supported versions are 'v2' and 'v4'.`
);
}
return promise.then(query => {
query = Object.assign(query, cfg.queryParams);
const signedUrl = new url.URL(config.cname || PATH_STYLED_HOST);
signedUrl.pathname = this.getResourcePath(
!!config.cname,
this.bucket.name,
config.file
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
signedUrl.search = qsStringify(query as any);
return signedUrl.href;
});
}
private getSignedUrlV2(
config: GetSignedUrlConfigInternal
): Promise<SignedUrlQuery> {
const canonicalHeadersString = this.getCanonicalHeaders(
config.extensionHeaders || {}
);
const resourcePath = this.getResourcePath(
false,
config.bucket,
config.file
);
const blobToSign = [
config.method,
config.contentMd5 || '',
config.contentType || '',
config.expiration,
canonicalHeadersString + resourcePath,
].join('\n');
const sign = async () => {
const authClient = this.authClient;
try {
const signature = await authClient.sign(blobToSign);
const credentials = await authClient.getCredentials();
return {
GoogleAccessId: credentials.client_email!,
Expires: config.expiration,
Signature: signature,
} as V2SignedUrlQuery;
} catch (err) {
const signingErr = new SigningError(err.message);
signingErr.stack = err.stack;
throw signingErr;
}
};
return sign();
}
private getSignedUrlV4(
config: GetSignedUrlConfigInternal
): Promise<SignedUrlQuery> {
config.accessibleAt = config.accessibleAt
? config.accessibleAt
: new Date();
const millisecondsToSeconds = 1.0 / 1000.0;
const expiresPeriodInSeconds =
config.expiration - config.accessibleAt.valueOf() * millisecondsToSeconds;
// v4 limit expiration to be 7 days maximum
if (expiresPeriodInSeconds > SEVEN_DAYS) {
throw new Error(
`Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`
);
}
const extensionHeaders = Object.assign({}, config.extensionHeaders);
const fqdn = new url.URL(config.cname || PATH_STYLED_HOST);
extensionHeaders.host = fqdn.host;
if (config.contentMd5) {
extensionHeaders['content-md5'] = config.contentMd5;
}
if (config.contentType) {
extensionHeaders['content-type'] = config.contentType;
}
let contentSha256: string;
const sha256Header = extensionHeaders['x-goog-content-sha256'];
if (sha256Header) {
if (
typeof sha256Header !== 'string' ||
!/[A-Fa-f0-9]{40}/.test(sha256Header)
) {
throw new Error(
'The header X-Goog-Content-SHA256 must be a hexadecimal string.'
);
}
contentSha256 = sha256Header;
}
const signedHeaders = Object.keys(extensionHeaders)
.map(header => header.toLowerCase())
.sort()
.join(';');
const extensionHeadersString = this.getCanonicalHeaders(extensionHeaders);
const datestamp = dateFormat.format(config.accessibleAt, 'YYYYMMDD', true);
const credentialScope = `${datestamp}/auto/storage/goog4_request`;
const sign = async () => {
const credentials = await this.authClient.getCredentials();
const credential = `${credentials.client_email}/${credentialScope}`;
const dateISO = dateFormat.format(
config.accessibleAt ? config.accessibleAt : new Date(),
'YYYYMMDD[T]HHmmss[Z]',
true
);
const queryParams: Query = {
'X-Goog-Algorithm': 'GOOG4-RSA-SHA256',
'X-Goog-Credential': credential,
'X-Goog-Date': dateISO,
'X-Goog-Expires': expiresPeriodInSeconds.toString(10),
'X-Goog-SignedHeaders': signedHeaders,
...(config.queryParams || {}),
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const canonicalQueryParams = this.getCanonicalQueryParams(queryParams);
const canonicalRequest = this.getCanonicalRequest(
config.method,
this.getResourcePath(!!config.cname, config.bucket, config.file),
canonicalQueryParams,
extensionHeadersString,
signedHeaders,
contentSha256
);
const hash = crypto
.createHash('sha256')
.update(canonicalRequest)
.digest('hex');
const blobToSign = [
'GOOG4-RSA-SHA256',
dateISO,
credentialScope,
hash,
].join('\n');
try {
const signature = await this.authClient.sign(blobToSign);
const signatureHex = Buffer.from(signature, 'base64').toString('hex');
const signedQuery: Query = Object.assign({}, queryParams, {
'X-Goog-Signature': signatureHex,
});
return signedQuery;
} catch (err) {
const signingErr = new SigningError(err.message);
signingErr.stack = err.stack;
throw signingErr;
}
};
return sign();
}
/**
* Create canonical headers for signing v4 url.
*
* The canonical headers for v4-signing a request demands header names are
* first lowercased, followed by sorting the header names.
* Then, construct the canonical headers part of the request:
* <lowercasedHeaderName> + ":" + Trim(<value>) + "\n"
* ..
* <lowercasedHeaderName> + ":" + Trim(<value>) + "\n"
*
* @param headers
* @private
*/
getCanonicalHeaders(headers: http.OutgoingHttpHeaders) {
// Sort headers by their lowercased names
const sortedHeaders = objectEntries(headers)
// Convert header names to lowercase
.map<[string, HeaderValue]>(([headerName, value]) => [
headerName.toLowerCase(),
value,
])
.sort((a, b) => a[0].localeCompare(b[0]));
return sortedHeaders
.filter(([, value]) => value !== undefined)
.map(([headerName, value]) => {
// - Convert Array (multi-valued header) into string, delimited by
// ',' (no space).
// - Trim leading and trailing spaces.
// - Convert sequential (2+) spaces into a single space
const canonicalValue = `${value}`.trim().replace(/\s{2,}/g, ' ');
return `${headerName}:${canonicalValue}\n`;
})
.join('');
}
getCanonicalRequest(
method: string,
path: string,
query: string,
headers: string,
signedHeaders: string,
contentSha256?: string
) {
return [
method,
path,
query,
headers,
signedHeaders,
contentSha256 || 'UNSIGNED-PAYLOAD',
].join('\n');
}
getCanonicalQueryParams(query: Query) {
return objectEntries(query)
.map(([key, value]) => [encodeURI(key, true), encodeURI(value, true)])
.sort((a, b) => (a[0] < b[0] ? -1 : 1))
.map(([key, value]) => `${key}=${value}`)
.join('&');
}
getResourcePath(cname: boolean, bucket: string, file?: string): string {
if (cname) {
return '/' + (file || '');
} else if (file) {
return `/${bucket}/${file}`;
} else {
return `/${bucket}`;
}
}
parseExpires(
expires: string | number | Date,
current: Date = new Date()
): number {
const expiresInMSeconds = new Date(expires).valueOf();
if (isNaN(expiresInMSeconds)) {
throw new Error('The expiration date provided was invalid.');
}
if (expiresInMSeconds < current.valueOf()) {
throw new Error('An expiration date cannot be in the past.');
}
return Math.round(expiresInMSeconds / 1000); // The API expects seconds.
}
parseAccessibleAt(accessibleAt?: string | number | Date): number {
const accessibleAtInMSeconds = new Date(
accessibleAt || new Date()
).valueOf();
if (isNaN(accessibleAtInMSeconds)) {
throw new Error('The accessible at date provided was invalid.');
}
return Math.floor(accessibleAtInMSeconds / 1000); // The API expects seconds.
}
}
/**
* Custom error type for errors related to getting signed errors and policies.
*
* @private
*/
export class SigningError extends Error {
name = 'SigningError';
} | the_stack |
import { TestBed, fakeAsync } from '@angular/core/testing';
import { provideMockActions } from '@ngrx/effects/testing';
import { hot, cold, getTestScheduler } from 'jasmine-marbles';
import { RouterTestingModule } from '@angular/router/testing';
import { StoreModule } from '@ngrx/store';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { Observable } from 'rxjs';
import { ReportEffects } from './reports';
import * as Actions from '../actions/reports';
import {
IRelatedField,
IField,
INewReport,
IReportDetailed,
INestedRelatedField,
IAggregate,
} from '../models/api';
import { ApiService } from '../api.service';
import { reducers, metaReducers } from '../reducers';
import { initialState } from './mockStoreInit';
describe('Report Effects', () => {
let effects: ReportEffects;
let actions: Observable<any>;
let service: jasmine.SpyObj<ApiService>;
const makeTestbedConfig = state => ({
imports: [
RouterTestingModule.withRoutes([]),
StoreModule.forRoot(reducers, { metaReducers, initialState: state }),
MatSnackBarModule,
],
providers: [
ReportEffects,
provideMockActions(() => actions),
{
provide: ApiService,
// Next line mocks all the functions provided in api.service.ts
useValue: jasmine.createSpyObj(
'ApiService',
Object.getOwnPropertyNames(ApiService.prototype)
),
},
],
});
describe('using default initial state', () => {
beforeEach(() => {
TestBed.configureTestingModule(makeTestbedConfig(initialState));
effects = TestBed.get(ReportEffects);
service = TestBed.get(ApiService);
});
it('GetFields should get fields from a related field', () => {
const relatedField: IRelatedField = {
field_name: 'scheduledreport',
verbose_name: 'scheduledreport_set',
path: '',
help_text: '',
model_id: 24,
parent_model_name: 'scheduledreport',
parent_model_app_label: false,
included_model: true,
};
actions = hot('a-', { a: new Actions.GetFields(relatedField) });
const responseFields: IField[] = [
{
name: 'last_run_at',
field: 'last_run_at',
field_verbose: 'last run at',
field_type: 'DateTimeField',
is_default: true,
field_choices: [],
can_filter: true,
path: 'scheduledreport__',
path_verbose: 'scheduledreport',
help_text: '',
},
];
const response = cold('-b', { b: responseFields });
service.getFields.and.returnValue(response);
const expected = cold('-c', {
c: new Actions.GetFieldsSuccess(responseFields),
});
expect(effects.getFields$).toBeObservable(expected);
});
it('GetRelatedFields should get fields from a related field', () => {
const relatedField: INestedRelatedField = {
field_name: 'scheduledreport',
verbose_name: 'scheduledreport_set',
path: '',
help_text: '',
model_id: 24,
parent_model_name: 'scheduledreport',
parent_model_app_label: false,
included_model: true,
children: [],
id: 0,
};
actions = hot('a-', { a: new Actions.GetRelatedFields(relatedField) });
const responseFields: IRelatedField[] = [
{
field_name: 'last_run_at',
verbose_name: 'last run at',
path: 'scheduledreport__',
help_text: '',
model_id: 5,
parent_model_name: 'scheduledreport__',
parent_model_app_label: false,
included_model: true,
},
];
const response = cold('-b', { b: responseFields });
service.getRelatedFields.and.returnValue(response);
const expected = cold('-c', {
c: new Actions.GetRelatedFieldsSuccess({
parentId: relatedField.id,
relatedFields: responseFields,
}),
});
expect(effects.getRelatedFields$).toBeObservable(expected);
});
it('DeleteReport should delete the current report', () => {
actions = hot('a-', { a: new Actions.DeleteReport(4) });
const response = cold('-b', { b: { id: 4 } });
service.deleteReport.and.returnValue(response);
const expected = cold('-c', { c: new Actions.DeleteReportSuccess(4) });
expect(effects.deleteReport$).toBeObservable(expected);
});
it('GeneratePreview should get a preview of the currently selected report', () => {
actions = hot('a-', { a: new Actions.GeneratePreview() });
const reportPreview = {
data: [['place', 10], ['user', 4]],
meta: { titles: ['model', 'id'] },
};
const response = cold('-b', { b: reportPreview });
service.generatePreview.and.returnValue(response);
const expected = cold('-c', {
c: new Actions.GeneratePreviewSuccess(reportPreview),
});
expect(effects.generatePreview$).toBeObservable(expected);
});
it('EditReport should save the changes to the current report', () => {
actions = hot('a-', { a: new Actions.EditReport() });
// prettier-ignore
const savedReport = {"id":4,"name":"afasdf","description":"adgsasfg","modified":"2018-01-18","root_model":5,"root_model_name":"content type","displayfield_set":[{"id":1,"path":"","path_verbose":"","field":"model","field_verbose":"python model class name","name":"model","sort":null,"sort_reverse":false,"width":15,"aggregate":"" as IAggregate,"position":0,"total":false,"group":false,"report":4,"display_format":null,"field_type":"CharField"},{"id":2,"path":"","path_verbose":"","field":"id","field_verbose":"ID","name":"id","sort":null,"sort_reverse":false,"width":15,"aggregate":"" as IAggregate,"position":1,"total":false,"group":false,"report":4,"display_format":null,"field_type":"AutoField"}],"distinct":false,"user_created":1,"user_modified":null,"filterfield_set":[],"report_file":null,"report_file_creation":null}
const response = cold('-b', { b: savedReport });
service.editReport.and.returnValue(response);
const expected = cold('-c', {
c: new Actions.EditReportSuccess(savedReport),
});
expect(effects.editReport$).toBeObservable(expected);
});
it('CreateReport should make an api call and return a success', () => {
const newReport: INewReport = {
name: 'testy',
description: 'descy',
root_model: 2,
};
actions = hot('a-', { a: new Actions.CreateReport(newReport) });
// prettier-ignore
const newReportDetailed: IReportDetailed = {"id":8,"name":"asdad","description":"asdadc","modified":"2018-01-24","root_model":1,"root_model_name":"log entry","displayfield_set":[],"distinct":false,"user_created":1,"user_modified":null,"filterfield_set":[],"report_file":null,"report_file_creation":null}
const response = cold('-b', { b: newReportDetailed });
service.submitNewReport.and.returnValue(response);
const expected = cold('-c', {
c: new Actions.CreateReportSuccess(newReportDetailed),
});
expect(effects.createReport$).toBeObservable(expected);
});
});
describe('with async === false', () => {
const state = Object.assign({}, initialState, {
config: { async_report: false },
});
const reportId = state.reports.selectedReport.id;
beforeEach(() => {
TestBed.configureTestingModule(makeTestbedConfig(state));
effects = TestBed.get(ReportEffects);
service = TestBed.get(ApiService);
});
it('ExportReport should dispatch a download action', () => {
const type = 'csv';
actions = hot('a', { a: new Actions.ExportReport(type) });
const expected = hot('c', {
c: new Actions.DownloadExportedReport(
`api/report/${reportId}/download_file/${type}/`
),
});
expect(effects.exportReport$).toBeObservable(expected);
});
});
describe('with async === true', () => {
const state = Object.assign({}, initialState, {
config: { async_report: true },
});
const reportId = state.reports.selectedReport.id;
const taskId = '12345';
beforeEach(() => {
TestBed.configureTestingModule(makeTestbedConfig(state));
effects = TestBed.get(ReportEffects);
service = TestBed.get(ApiService);
});
it('ExportReport should start the task', () => {
const type = 'csv';
actions = hot('a-', { a: new Actions.ExportReport(type) });
const response = cold('-b', { b: { task_id: taskId } });
service.exportReport.and.returnValue(response);
const expected = cold('-c', {
c: new Actions.CheckExportStatus({ reportId, taskId }),
});
expect(effects.exportReport$).toBeObservable(expected);
});
it("CheckExportStatus should dispatch another CheckExportStatus action if the download isn't ready", () => {
actions = hot('a', {
a: new Actions.CheckExportStatus({ reportId, taskId }),
});
const response = cold('-b', { b: { state: 'newp' } });
const expected = cold('---c', {
c: new Actions.CheckExportStatus({ reportId, taskId }),
});
service.checkStatus.and.returnValue(response);
const actual = effects.checkExportStatus$({
delayTime: 20,
scheduler: getTestScheduler(),
});
expect(actual).toBeObservable(expected);
});
it('CheckExportStatus should dispatch a download request if the download is ready', fakeAsync(() => {
const link = 'place/download';
actions = hot('a', {
a: new Actions.CheckExportStatus({ reportId, taskId }),
});
const response = cold('-b', { b: { state: 'SUCCESS', link } });
const expected = cold('---c', {
c: new Actions.DownloadExportedReport(link),
});
service.checkStatus.and.returnValue(response);
const actual = effects.checkExportStatus$({
delayTime: 20,
scheduler: getTestScheduler(),
});
expect(actual).toBeObservable(expected);
}));
});
}); | the_stack |
namespace correction {
function textToCharTransforms(text: string, transformId?: number) {
let perCharTransforms: Transform[] = [];
for(let i=0; i < text.kmwLength(); i++) {
let char = text.kmwCharAt(i); // is SMP-aware
let transform: Transform = {
insert: char,
deleteLeft: 0,
id: transformId
};
perCharTransforms.push(transform);
}
return perCharTransforms;
}
export class TrackedContextSuggestion {
suggestion: Suggestion;
tokenWidth: number;
}
export class TrackedContextToken {
raw: string;
replacementText: string;
transformDistributions: Distribution<Transform>[] = [];
replacements: TrackedContextSuggestion[];
activeReplacementId: number = -1;
get isNew(): boolean {
return this.transformDistributions.length == 0;
}
get currentText(): string {
if(this.replacementText === undefined || this.replacementText === null) {
return this.raw;
} else {
return this.replacementText;
}
}
get replacement(): TrackedContextSuggestion {
let replacementId = this.activeReplacementId;
return this.replacements.find(function(replacement) {
return replacement.suggestion.id == replacementId;
});
}
revert() {
delete this.activeReplacementId;
}
}
export class TrackedContextState {
// Stores the source Context (as a debugging reference). Not currently utilized.
taggedContext: Context;
model: LexicalModel;
tokens: TrackedContextToken[];
/**
* How many tokens were removed from the start of the best-matching ancestor.
* Useful for restoring older states, e.g., when the user moves the caret backwards, we can recover the context at that position.
*/
indexOffset: number;
// Tracks all search spaces starting at the current token.
// In the lm-layer's current form, this should only ever have one entry.
// Leaves 'design space' for if/when we add support for phrase-level corrections/predictions.
searchSpace: SearchSpace[] = [];
constructor(source: TrackedContextState);
constructor(model: LexicalModel);
constructor(obj: TrackedContextState | LexicalModel) {
if(obj instanceof TrackedContextState) {
let source = obj;
// Be sure to deep-copy the tokens! Pointer-aliasing is bad here.
this.tokens = source.tokens.map(function(token) {
let copy = new TrackedContextToken();
copy.raw = token.raw;
copy.replacements = token.replacements
copy.activeReplacementId = token.activeReplacementId;
copy.transformDistributions = token.transformDistributions;
if(token.replacementText) {
copy.replacementText = token.replacementText;
}
return copy;
});
this.searchSpace = obj.searchSpace;
this.indexOffset = 0;
this.model = obj.model;
} else {
let lexicalModel = obj;
this.tokens = [];
this.indexOffset = Number.MIN_SAFE_INTEGER;
this.model = lexicalModel;
if(lexicalModel && lexicalModel.traverseFromRoot) {
this.searchSpace = [new SearchSpace(lexicalModel)];
}
}
}
get head(): TrackedContextToken {
return this.tokens[0];
}
get tail(): TrackedContextToken {
return this.tokens[this.tokens.length - 1];
}
popHead() {
this.tokens.splice(0, 2);
this.indexOffset -= 1;
}
pushTail(token: TrackedContextToken) {
if(this.model && this.model.traverseFromRoot) {
this.searchSpace = [new SearchSpace(this.model)]; // yeah, need to update SearchSpace for compatibility
} else {
this.searchSpace = [];
}
this.tokens.push(token);
let state = this;
if(state.searchSpace.length > 0) {
token.transformDistributions.forEach(distrib => state.searchSpace[0].addInput(distrib));
}
}
pushWhitespaceToTail(transformDistribution: Distribution<Transform> = null) {
let whitespaceToken = new TrackedContextToken();
// Track the Transform that resulted in the whitespace 'token'.
// Will be needed for phrase-level correction/prediction.
whitespaceToken.transformDistributions = [transformDistribution];
whitespaceToken.raw = null;
this.tokens.push(whitespaceToken);
}
/**
* Used for 14.0's backspace workaround, which flattens all previous Distribution<Transform>
* entries because of limitations with direct use of backspace transforms.
* @param tokenText
* @param transformId
*/
replaceTailForBackspace(tokenText: USVString, transformId: number) {
this.tokens.pop();
// It's a backspace transform; time for special handling!
//
// For now, with 14.0, we simply compress all remaining Transforms for the token into
// multiple single-char transforms. Probabalistically modeling BKSP is quite complex,
// so we simplify by assuming everything remaining after a BKSP is 'true' and 'intended' text.
//
// Note that we cannot just use a single, monolithic transform at this point b/c
// of our current edit-distance optimization strategy; diagonalization is currently...
// not very compatible with that.
let backspacedTokenContext: Distribution<Transform>[] = textToCharTransforms(tokenText, transformId).map(function(transform) {
return [{sample: transform, p: 1.0}];
});
let compactedToken = new TrackedContextToken();
compactedToken.raw = tokenText;
compactedToken.transformDistributions = backspacedTokenContext;
this.pushTail(compactedToken);
}
updateTail(transformDistribution: Distribution<Transform>, tokenText?: USVString) {
let editedToken = this.tail;
// Preserve existing text if new text isn't specified.
tokenText = tokenText || (tokenText === '' ? '' : editedToken.raw);
if(transformDistribution && transformDistribution.length > 0) {
editedToken.transformDistributions.push(transformDistribution);
if(this.searchSpace) {
this.searchSpace.forEach(space => space.addInput(transformDistribution));
}
}
// Replace old token's raw-text with new token's raw-text.
editedToken.raw = tokenText;
}
toRawTokenization() {
let sequence: USVString[] = [];
for(let token of this.tokens) {
// Hide any tokens representing wordbreaks. (Thinking ahead to phrase-level possibilities)
if(token.currentText !== null) {
sequence.push(token.currentText);
}
}
return sequence;
}
}
class CircularArray<Item> {
static readonly DEFAULT_ARRAY_SIZE = 5;
private circle: Item[];
private currentHead: number=0;
private currentTail: number=0;
constructor(size: number = CircularArray.DEFAULT_ARRAY_SIZE) {
this.circle = Array(size);
}
get count(): number {
let diff = this.currentHead - this.currentTail;
if(diff < 0) {
diff = diff + this.circle.length;
}
return diff;
}
get maxCount(): number {
return this.circle.length;
}
get oldest(): Item {
if(this.count == 0) {
return undefined;
}
return this.item(0);
}
get newest(): Item {
if(this.count == 0) {
return undefined;
}
return this.item(this.count - 1);
}
enqueue(item: Item): Item {
var prevItem = null;
let nextHead = (this.currentHead + 1) % this.maxCount;
if(nextHead == this.currentTail) {
prevItem = this.circle[this.currentTail];
this.currentTail = (this.currentTail + 1) % this.maxCount;
}
this.circle[this.currentHead] = item;
this.currentHead = nextHead;
return prevItem;
}
dequeue(): Item {
if(this.currentTail == this.currentHead) {
return null;
} else {
let item = this.circle[this.currentTail];
this.currentTail = (this.currentTail + 1) % this.maxCount;
return item;
}
}
popNewest(): Item {
if(this.currentTail == this.currentHead) {
return null;
} else {
let item = this.circle[this.currentHead];
this.currentHead = (this.currentHead - 1 + this.maxCount) % this.maxCount;
return item;
}
}
/**
* Returns items contained within the circular array, ordered from 'oldest' to 'newest' -
* the same order in which the items will be dequeued.
* @param index
*/
item(index: number) {
if(index >= this.count) {
throw "Invalid array index";
}
let mappedIndex = (this.currentTail + index) % this.maxCount;
return this.circle[mappedIndex];
}
}
export class ContextTracker extends CircularArray<TrackedContextState> {
static attemptMatchContext(tokenizedContext: USVString[],
matchState: TrackedContextState,
transformDistribution?: Distribution<Transform>,): TrackedContextState {
// Map the previous tokenized state to an edit-distance friendly version.
let matchContext: USVString[] = matchState.toRawTokenization();
// Inverted order, since 'match' existed before our new context.
let mapping = ClassicalDistanceCalculation.computeDistance(matchContext.map(value => ({key: value})),
tokenizedContext.map(value => ({key: value})),
1);
let editPath = mapping.editPath();
let poppedHead = false;
let pushedTail = false;
// Matters greatly when starting from a nil context.
if(editPath.length > 1) {
// First entry: may not be an 'insert' or a 'transpose' op.
// 'insert' allowed if the next token is 'substitute', as this may occur with an edit path of length 2.
if((editPath[0] == 'insert' && !(editPath[1] == 'substitute' && editPath.length == 2)) || editPath[0].indexOf('transpose') >= 0) {
return null;
} else if(editPath[0] == 'delete') {
poppedHead = true; // a token from the previous state has been wholly removed.
}
}
// Last entry: may not be a 'delete' or a 'transpose' op.
let tailIndex = editPath.length -1;
let ignorePenultimateMatch = false;
if(editPath[tailIndex] == 'delete' || editPath[0].indexOf('transpose') >= 0) {
return null;
} else if(editPath[tailIndex] == 'insert') {
pushedTail = true;
} else if(tailIndex > 0 && editPath[tailIndex-1] == 'insert' && editPath[tailIndex] == 'substitute') {
// Tends to happen when accepting suggestions.
pushedTail = true;
ignorePenultimateMatch = true;
}
// Now to check everything in-between: should be exclusively 'match'es.
for(let index = 1; index < editPath.length - (ignorePenultimateMatch ? 2 : 1); index++) {
if(editPath[index] != 'match') {
return null;
}
}
// If we've made it here... success! We have a context match!
let state: TrackedContextState;
if(pushedTail) {
// On suggestion acceptance, we should update the previous final token.
// We do it first so that the acceptance is replicated in the new TrackedContextState
// as well.
if(ignorePenultimateMatch) {
// For this case, we were likely called by ModelCompositor.acceptSuggestion(), which
// would have marked the accepted suggestion.
matchState.tail.replacementText = tokenizedContext[tokenizedContext.length-2];
}
state = new TrackedContextState(matchState);
} else {
// Since we're continuing a previously-cached context, we can reuse the same SearchSpace
// to continue making predictions.
state = matchState;
}
const hasDistribution = transformDistribution && Array.isArray(transformDistribution);
let primaryInput = hasDistribution ? transformDistribution[0].sample : null;
if(primaryInput && primaryInput.insert == "" && primaryInput.deleteLeft == 0 && !primaryInput.deleteRight) {
primaryInput = null;
}
const isBackspace = primaryInput && primaryInput.insert == "" && primaryInput.deleteLeft > 0 && !primaryInput.deleteRight;
const finalToken = tokenizedContext[tokenizedContext.length-1];
/* Assumption: This is an adequate check for its two sub-branches.
*
* Basis:
* - Assumption: one keystroke may only cause a single token to rotate out of context.
* - That is, no "reasonable" keystroke would emit enough code points to 'bump' two words simultaneously.
* - ... This one may need to be loosened a bit... but it should be enough for initial correction testing as-is.
* - Assumption: one keystroke may only cause a single token to be appended to the context
* - That is, no "reasonable" keystroke would emit a Transform adding two separate word tokens
* - For languages using whitespace to word-break, said keystroke would have to include said whitespace to break the assumption.
*/
// If there is/was more than one context token available...
if(editPath.length > 1) {
// We're removing a context token, but at least one remains.
if(poppedHead) {
state.popHead();
}
// We're adding an additional context token.
if(pushedTail) {
// ASSUMPTION: any transform that triggers this case is a pure-whitespace Transform, as we
// need a word-break before beginning a new word's context.
// Worth note: when invalid, the lm-layer already has problems in other aspects too.
state.pushWhitespaceToTail(transformDistribution);
let emptyToken = new TrackedContextToken();
emptyToken.raw = '';
// Continuing the earlier assumption, that 'pure-whitespace Transform' does not emit any initial characters
// for the new word (token), so the input keystrokes do not correspond to the new text token.
emptyToken.transformDistributions = [];
state.pushTail(emptyToken);
} else { // We're editing the final context token.
// TODO: Assumption: we didn't 'miss' any inputs somehow.
// As is, may be prone to fragility should the lm-layer's tracked context 'desync' from its host's.
if(isBackspace) {
state.replaceTailForBackspace(finalToken, primaryInput.id);
} else {
state.updateTail(primaryInput ? transformDistribution : null, finalToken);
}
}
// There is only one word in the context.
} else {
// TODO: Assumption: we didn't 'miss' any inputs somehow.
// As is, may be prone to fragility should the lm-layer's tracked context 'desync' from its host's.
if(editPath[tailIndex] == 'insert') {
// Construct appropriate initial token.
let token = new TrackedContextToken();
token.raw = tokenizedContext[0];
token.transformDistributions = [transformDistribution];
state.pushTail(token);
} else { // Edit the lone context token.
// Consider backspace entry for this case?
if(isBackspace) {
state.replaceTailForBackspace(finalToken, primaryInput.id);
} else {
state.updateTail(primaryInput ? transformDistribution : null, finalToken);
}
}
}
return state;
}
static modelContextState(tokenizedContext: USVString[], lexicalModel: LexicalModel): TrackedContextState {
let baseTokens = tokenizedContext.map(function(entry) {
let token = new TrackedContextToken();
token.raw = entry;
if(token.raw) {
token.transformDistributions = textToCharTransforms(token.raw).map(function(transform) {
return [{sample: transform, p: 1.0}];
});
} else {
// Helps model context-final wordbreaks.
token.transformDistributions = [];
}
return token;
});
// And now build the final context state object, which includes whitespace 'tokens'.
let state = new TrackedContextState(lexicalModel);
if(baseTokens.length > 0) {
state.pushTail(baseTokens.splice(0, 1)[0]);
}
while(baseTokens.length > 0) {
state.pushWhitespaceToTail();
state.pushTail(baseTokens.splice(0, 1)[0]);
}
if(state.tokens.length == 0) {
let token = new TrackedContextToken();
token.raw = '';
state.pushTail(token);
}
return state;
}
/**
* Compares the current, post-input context against the most recently-seen contexts from previous prediction calls, returning
* the most information-rich `TrackedContextState` possible. If a match is found, the state will be annotated with the
* input information provided to previous prediction calls and persisted correction-search calculations for re-use.
*
* @param model
* @param context
* @param mainTransform
* @param transformDistribution
*/
analyzeState(model: LexicalModel,
context: Context,
transformDistribution?: Distribution<Transform>): TrackedContextState {
if(!model.traverseFromRoot) {
// Assumption: LexicalModel provides a valid traverseFromRoot function. (Is technically optional)
// Without it, no 'corrections' may be made; the model can only be used to predict, not correct.
throw "This lexical model does not provide adequate data for correction algorithms and context reuse";
}
let tokenizedContext = models.tokenize(model.wordbreaker || wordBreakers.default, context);
if(tokenizedContext.left.length > 0) {
for(let i = this.count - 1; i >= 0; i--) {
let resultState = ContextTracker.attemptMatchContext(tokenizedContext.left, this.item(i), transformDistribution);
if(resultState) {
resultState.taggedContext = context;
if(resultState != this.item(i)) {
this.enqueue(resultState);
}
return resultState;
}
}
}
// Else: either empty OR we've detected a 'new context'. Initialize from scratch; no prior input information is
// available. Only the results of the prior inputs are known.
//
// Assumption: as a caret needs to move to context before any actual transform distributions occur,
// this state is only reached on caret moves; thus, transformDistribution is actually just a single null transform.
let state = ContextTracker.modelContextState(tokenizedContext.left, model);
state.taggedContext = context;
this.enqueue(state);
return state;
}
}
} | the_stack |
import { Compiler } from '@0x/sol-compiler';
import * as fs from 'fs';
import * as path from 'path';
import { promisify } from 'util';
import {
ArrayTypeNameNode,
AstNode,
ContractKind,
EnumValueNode,
FunctionKind,
isArrayTypeNameNode,
isContractDefinitionNode,
isEnumDefinitionNode,
isEventDefinitionNode,
isFunctionDefinitionNode,
isMappingTypeNameNode,
isSourceUnitNode,
isStructDefinitionNode,
isUserDefinedTypeNameNode,
isVariableDeclarationNode,
MappingTypeNameNode,
ParameterListNode,
SourceUnitNode,
splitAstNodeSrc,
StateMutability,
StorageLocation,
TypeNameNode,
VariableDeclarationNode,
Visibility,
} from './sol_ast';
export { ContractKind, FunctionKind, StateMutability, StorageLocation, Visibility } from './sol_ast';
export interface DocumentedItem {
doc: string;
line: number;
file: string;
}
export interface EnumValueDocs extends DocumentedItem {
value: number;
}
export interface ParamDocs extends DocumentedItem {
type: string;
indexed: boolean;
storageLocation: StorageLocation;
order: number;
}
export interface ParamDocsMap {
[name: string]: ParamDocs;
}
export interface EnumValueDocsMap {
[name: string]: EnumValueDocs;
}
export interface MethodDocs extends DocumentedItem {
name: string;
contract: string;
stateMutability: string;
visibility: Visibility;
isAccessor: boolean;
kind: FunctionKind;
parameters: ParamDocsMap;
returns: ParamDocsMap;
}
export interface EnumDocs extends DocumentedItem {
contract: string;
values: EnumValueDocsMap;
}
export interface StructDocs extends DocumentedItem {
contract: string;
fields: ParamDocsMap;
}
export interface EventDocs extends DocumentedItem {
contract: string;
name: string;
parameters: ParamDocsMap;
}
export interface ContractDocs extends DocumentedItem {
kind: ContractKind;
inherits: string[];
methods: MethodDocs[];
events: EventDocs[];
enums: {
[typeName: string]: EnumDocs;
};
structs: {
[typeName: string]: StructDocs;
};
}
export interface SolidityDocs {
contracts: {
[typeName: string]: ContractDocs;
};
}
interface SolcOutput {
sources: { [file: string]: { id: number; ast: SourceUnitNode } };
contracts: {
[file: string]: {
[contract: string]: {
metadata: string;
};
};
};
}
interface ContractMetadata {
sources: { [file: string]: { content: string } };
settings: { remappings: string[] };
}
interface SourceData {
path: string;
content: string;
}
interface Natspec {
comment: string;
dev: string;
params: { [name: string]: string };
returns: { [name: string]: string };
}
/**
* Extract documentation, as JSON, from contract files.
*/
export async function extractDocsAsync(contractPaths: string[], roots: string[] = []): Promise<SolidityDocs> {
const outputs = await compileAsync(contractPaths);
const sourceContents = (await Promise.all(outputs.map(getSourceContentsFromCompilerOutputAsync))).map(sources =>
rewriteSourcePaths(sources, roots),
);
const docs = createEmptyDocs();
outputs.forEach((output, outputIdx) => {
for (const file of Object.keys(output.contracts)) {
const fileDocs = extractDocsFromFile(
output.sources[file].ast,
sourceContents[outputIdx][output.sources[file].id],
);
mergeDocs(docs, fileDocs);
}
});
return docs;
}
async function compileAsync(files: string[]): Promise<SolcOutput[]> {
const compiler = new Compiler({
contracts: files,
compilerSettings: {
outputSelection: {
'*': {
'*': ['metadata'],
'': ['ast'],
},
},
},
});
return (compiler.getCompilerOutputsAsync() as any) as Promise<SolcOutput[]>;
}
async function getSourceContentsFromCompilerOutputAsync(output: SolcOutput): Promise<SourceData[]> {
const sources: SourceData[] = [];
for (const [importFile, fileOutput] of Object.entries(output.contracts)) {
if (importFile in sources) {
continue;
}
for (const contractOutput of Object.values(fileOutput)) {
const metadata = JSON.parse(contractOutput.metadata || '{}') as ContractMetadata;
let filePath = importFile;
if (!path.isAbsolute(filePath)) {
const { remappings } = metadata.settings;
let longestPrefix = '';
let longestPrefixReplacement = '';
for (const remapping of remappings) {
const [from, to] = remapping.substr(1).split('=');
if (longestPrefix.length < from.length) {
if (filePath.startsWith(from)) {
longestPrefix = from;
longestPrefixReplacement = to;
}
}
}
filePath = filePath.slice(longestPrefix.length);
filePath = path.join(longestPrefixReplacement, filePath);
}
const content = await promisify(fs.readFile)(filePath, { encoding: 'utf-8' });
sources[output.sources[importFile].id] = {
path: path.relative('.', filePath),
content,
};
}
}
return sources;
}
function rewriteSourcePaths(sources: SourceData[], roots: string[]): SourceData[] {
const _roots = roots.map(root => root.split('='));
return sources.map(s => {
let longestPrefix = '';
let longestPrefixReplacement = '';
for (const [from, to] of _roots) {
if (from.length > longestPrefix.length) {
if (s.path.startsWith(from)) {
longestPrefix = from;
longestPrefixReplacement = to || '';
}
}
}
return {
...s,
path: `${longestPrefixReplacement}${s.path.substr(longestPrefix.length)}`,
};
});
}
function mergeDocs(dst: SolidityDocs, ...srcs: SolidityDocs[]): SolidityDocs {
if (srcs.length === 0) {
return dst;
}
for (const src of srcs) {
dst.contracts = {
...dst.contracts,
...src.contracts,
};
}
return dst;
}
function createEmptyDocs(): SolidityDocs {
return { contracts: {} };
}
function extractDocsFromFile(ast: SourceUnitNode, source: SourceData): SolidityDocs {
const HIDDEN_VISIBILITIES = [Visibility.Private, Visibility.Internal];
const docs = createEmptyDocs();
const visit = (node: AstNode, currentContractName?: string) => {
const { offset } = splitAstNodeSrc(node.src);
if (isSourceUnitNode(node)) {
for (const child of node.nodes) {
visit(child);
}
} else if (isContractDefinitionNode(node)) {
const natspec = getNatspecBefore(source.content, offset);
docs.contracts[node.name] = {
file: source.path,
line: getAstNodeLineNumber(node, source.content),
doc: natspec.dev || natspec.comment,
kind: node.contractKind,
inherits: node.baseContracts.map(c => normalizeType(c.baseName.typeDescriptions.typeString)),
methods: [],
events: [],
enums: {},
structs: {},
};
for (const child of node.nodes) {
visit(child, node.name);
}
} else if (!currentContractName) {
return;
} else if (isVariableDeclarationNode(node)) {
if (HIDDEN_VISIBILITIES.includes(node.visibility)) {
return;
}
if (!node.stateVariable) {
return;
}
const natspec = getNatspecBefore(source.content, offset);
docs.contracts[currentContractName].methods.push({
file: source.path,
line: getAstNodeLineNumber(node, source.content),
doc: getDocStringAround(source.content, offset),
name: node.name,
contract: currentContractName,
kind: FunctionKind.Function,
visibility: Visibility.External,
parameters: extractAcessorParameterDocs(node.typeName, natspec, source),
returns: extractAccesorReturnDocs(node.typeName, natspec, source),
stateMutability: StateMutability.View,
isAccessor: true,
});
} else if (isFunctionDefinitionNode(node)) {
const natspec = getNatspecBefore(source.content, offset);
docs.contracts[currentContractName].methods.push({
file: source.path,
line: getAstNodeLineNumber(node, source.content),
doc: natspec.dev || natspec.comment || getCommentsBefore(source.content, offset),
name: node.name,
contract: currentContractName,
kind: node.kind,
visibility: node.visibility,
parameters: extractFunctionParameterDocs(node.parameters, natspec, source),
returns: extractFunctionReturnDocs(node.returnParameters, natspec, source),
stateMutability: node.stateMutability,
isAccessor: false,
});
} else if (isStructDefinitionNode(node)) {
const natspec = getNatspecBefore(source.content, offset);
docs.contracts[currentContractName].structs[node.canonicalName] = {
contract: currentContractName,
file: source.path,
line: getAstNodeLineNumber(node, source.content),
doc: natspec.dev || natspec.comment || getCommentsBefore(source.content, offset),
fields: extractStructFieldDocs(node.members, natspec, source),
};
} else if (isEnumDefinitionNode(node)) {
const natspec = getNatspecBefore(source.content, offset);
docs.contracts[currentContractName].enums[node.canonicalName] = {
contract: currentContractName,
file: source.path,
line: getAstNodeLineNumber(node, source.content),
doc: natspec.dev || natspec.comment || getCommentsBefore(source.content, offset),
values: extractEnumValueDocs(node.members, natspec, source),
};
} else if (isEventDefinitionNode(node)) {
const natspec = getNatspecBefore(source.content, offset);
docs.contracts[currentContractName].events.push({
contract: currentContractName,
file: source.path,
line: getAstNodeLineNumber(node, source.content),
doc: natspec.dev || natspec.comment || getCommentsBefore(source.content, offset),
name: node.name,
parameters: extractFunctionParameterDocs(node.parameters, natspec, source),
});
}
};
visit(ast);
return docs;
}
function extractAcessorParameterDocs(typeNameNode: TypeNameNode, natspec: Natspec, source: SourceData): ParamDocsMap {
const params: ParamDocsMap = {};
const lineNumber = getAstNodeLineNumber(typeNameNode, source.content);
if (isMappingTypeNameNode(typeNameNode)) {
// Handle mappings.
let node = typeNameNode;
let order = 0;
do {
const paramName = `${Object.keys(params).length}`;
params[paramName] = {
file: source.path,
line: lineNumber,
doc: natspec.params[paramName] || '',
type: normalizeType(node.keyType.typeDescriptions.typeString),
indexed: false,
storageLocation: StorageLocation.Default,
order: order++,
};
node = node.valueType as MappingTypeNameNode;
} while (isMappingTypeNameNode(node));
} else if (isArrayTypeNameNode(typeNameNode)) {
// Handle arrays.
let node = typeNameNode;
let order = 0;
do {
const paramName = `${Object.keys(params).length}`;
params[paramName] = {
file: source.path,
line: lineNumber,
doc: natspec.params[paramName] || '',
type: 'uint256',
indexed: false,
storageLocation: StorageLocation.Default,
order: order++,
};
node = node.baseType as ArrayTypeNameNode;
} while (isArrayTypeNameNode(node));
}
return params;
}
function extractAccesorReturnDocs(typeNameNode: TypeNameNode, natspec: Natspec, source: SourceData): ParamDocsMap {
let type = typeNameNode.typeDescriptions.typeString;
let storageLocation = StorageLocation.Default;
if (isMappingTypeNameNode(typeNameNode)) {
// Handle mappings.
let node = typeNameNode;
while (isMappingTypeNameNode(node.valueType)) {
node = node.valueType;
}
type = node.valueType.typeDescriptions.typeString;
storageLocation = type.startsWith('struct') ? StorageLocation.Memory : StorageLocation.Default;
} else if (isArrayTypeNameNode(typeNameNode)) {
// Handle arrays.
type = typeNameNode.baseType.typeDescriptions.typeString;
storageLocation = type.startsWith('struct') ? StorageLocation.Memory : StorageLocation.Default;
} else if (isUserDefinedTypeNameNode(typeNameNode)) {
storageLocation = typeNameNode.typeDescriptions.typeString.startsWith('struct')
? StorageLocation.Memory
: StorageLocation.Default;
}
return {
'0': {
storageLocation,
type: normalizeType(type),
file: source.path,
line: getAstNodeLineNumber(typeNameNode, source.content),
doc: natspec.returns['0'] || '',
indexed: false,
order: 0,
},
};
}
function extractFunctionParameterDocs(
paramListNodes: ParameterListNode,
natspec: Natspec,
source: SourceData,
): ParamDocsMap {
const params: ParamDocsMap = {};
for (const param of paramListNodes.parameters) {
params[param.name] = {
file: source.path,
line: getAstNodeLineNumber(param, source.content),
doc: natspec.params[param.name] || '',
type: normalizeType(param.typeName.typeDescriptions.typeString),
indexed: param.indexed,
storageLocation: param.storageLocation,
order: 0,
};
}
return params;
}
function extractFunctionReturnDocs(
paramListNodes: ParameterListNode,
natspec: Natspec,
source: SourceData,
): ParamDocsMap {
const returns: ParamDocsMap = {};
let order = 0;
for (const [idx, param] of Object.entries(paramListNodes.parameters)) {
returns[param.name || idx] = {
file: source.path,
line: getAstNodeLineNumber(param, source.content),
doc: natspec.returns[param.name || idx] || '',
type: normalizeType(param.typeName.typeDescriptions.typeString),
indexed: false,
storageLocation: param.storageLocation,
order: order++,
};
}
return returns;
}
function extractStructFieldDocs(
fieldNodes: VariableDeclarationNode[],
natspec: Natspec,
source: SourceData,
): ParamDocsMap {
const fields: ParamDocsMap = {};
let order = 0;
for (const field of fieldNodes) {
const { offset } = splitAstNodeSrc(field.src);
fields[field.name] = {
file: source.path,
line: getAstNodeLineNumber(field, source.content),
doc: natspec.params[field.name] || getDocStringAround(source.content, offset),
type: normalizeType(field.typeName.typeDescriptions.typeString),
indexed: false,
storageLocation: field.storageLocation,
order: order++,
};
}
return fields;
}
function extractEnumValueDocs(valuesNodes: EnumValueNode[], natspec: Natspec, source: SourceData): EnumValueDocsMap {
const values: EnumValueDocsMap = {};
for (const value of valuesNodes) {
const { offset } = splitAstNodeSrc(value.src);
values[value.name] = {
file: source.path,
line: getAstNodeLineNumber(value, source.content),
doc: natspec.params[value.name] || getDocStringAround(source.content, offset),
value: Object.keys(values).length,
};
}
return values;
}
function offsetToLineIndex(code: string, offset: number): number {
let currentOffset = 0;
let lineIdx = 0;
while (currentOffset <= offset) {
const lineEnd = code.indexOf('\n', currentOffset);
if (lineEnd === -1) {
return lineIdx;
}
currentOffset = lineEnd + 1;
++lineIdx;
}
return lineIdx - 1;
}
function offsetToLine(code: string, offset: number): string {
let lineEnd = code.substr(offset).search(/\r?\n/);
lineEnd = lineEnd === -1 ? code.length - offset : lineEnd;
let lineStart = code.lastIndexOf('\n', offset);
lineStart = lineStart === -1 ? 0 : lineStart;
return code.substr(lineStart, offset - lineStart + lineEnd).trim();
}
function getPrevLine(code: string, offset: number): [string | undefined, number] {
const lineStart = code.lastIndexOf('\n', offset);
if (lineStart <= 0) {
return [undefined, 0];
}
const prevLineStart = code.lastIndexOf('\n', lineStart - 1);
if (prevLineStart === -1) {
return [code.substr(0, lineStart).trim(), 0];
}
return [code.substring(prevLineStart + 1, lineStart).trim(), prevLineStart + 1];
}
function getAstNodeLineNumber(node: AstNode, code: string): number {
return offsetToLineIndex(code, splitAstNodeSrc(node.src).offset) + 1;
}
function getNatspecBefore(code: string, offset: number): Natspec {
const natspec = { comment: '', dev: '', params: {}, returns: {} };
// Walk backwards through the lines until there is no longer a natspec
// comment.
let currentDirectivePayloads = [];
let currentLine: string | undefined;
let currentOffset = offset;
while (true) {
[currentLine, currentOffset] = getPrevLine(code, currentOffset);
if (currentLine === undefined) {
break;
}
const m = /^\/\/\/\s*(?:@(\w+\b)\s*)?(.*?)$/.exec(currentLine);
if (!m) {
break;
}
const directive = m[1];
let directiveParam: string | undefined;
let rest = m[2] || '';
// Parse directives that take a parameter.
if (directive === 'param' || directive === 'return') {
const m2 = /^(\w+\b)(.*)$/.exec(rest);
if (m2) {
directiveParam = m2[1];
rest = m2[2] || '';
}
}
currentDirectivePayloads.push(rest);
if (directive !== undefined) {
const fullPayload = currentDirectivePayloads
.reverse()
.map(s => s.trim())
.join(' ');
switch (directive) {
case 'dev':
natspec.dev = fullPayload;
break;
case 'param':
if (directiveParam) {
natspec.params = {
...natspec.params,
[directiveParam]: fullPayload,
};
}
break;
case 'return':
if (directiveParam) {
natspec.returns = {
...natspec.returns,
[directiveParam]: fullPayload,
};
}
break;
default:
break;
}
currentDirectivePayloads = [];
}
}
if (currentDirectivePayloads.length > 0) {
natspec.comment = currentDirectivePayloads
.reverse()
.map(s => s.trim())
.join(' ');
}
return natspec;
}
function getTrailingCommentAt(code: string, offset: number): string {
const m = /\/\/\s*(.+)\s*$/.exec(offsetToLine(code, offset));
return m ? m[1] : '';
}
function getCommentsBefore(code: string, offset: number): string {
let currentOffset = offset;
const comments = [];
do {
let prevLine;
[prevLine, currentOffset] = getPrevLine(code, currentOffset);
if (prevLine === undefined) {
break;
}
const m = /^\s*\/\/\s*(.+)\s*$/.exec(prevLine);
if (m && !m[1].startsWith('solhint')) {
comments.push(m[1].trim());
} else {
break;
}
} while (currentOffset > 0);
return comments.reverse().join(' ');
}
function getDocStringBefore(code: string, offset: number): string {
const natspec = getNatspecBefore(code, offset);
return natspec.dev || natspec.comment || getCommentsBefore(code, offset);
}
function getDocStringAround(code: string, offset: number): string {
const natspec = getNatspecBefore(code, offset);
return natspec.dev || natspec.comment || getDocStringBefore(code, offset) || getTrailingCommentAt(code, offset);
}
function normalizeType(type: string): string {
const m = /^(?:\w+ )?(.*)$/.exec(type);
if (!m) {
return type;
}
return m[1];
}
// tslint:disable-next-line: max-file-line-count | the_stack |
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/dist/src/signer-with-address";
import { constants, id } from "../src/index";
const { WAD } = constants;
import ERC20MockArtifact from "../artifacts/contracts/mocks/ERC20Mock.sol/ERC20Mock.json";
import ERC20RewardsMockArtifact from "../artifacts/contracts/mocks/ERC20RewardsMock.sol/ERC20RewardsMock.json";
import { ERC20Mock as ERC20 } from "../typechain/ERC20Mock";
import { ERC20RewardsMock as ERC20Rewards } from "../typechain/ERC20RewardsMock";
import { BigNumber } from "ethers";
import { ethers, waffle } from "hardhat";
import { expect } from "chai";
const { deployContract, loadFixture } = waffle;
function almostEqual(x: BigNumber, y: BigNumber, p: BigNumber) {
// Check that abs(x - y) < p:
const diff = x.gt(y) ? BigNumber.from(x).sub(y) : BigNumber.from(y).sub(x); // Not sure why I have to convert x and y to BigNumber
expect(diff.div(p)).to.eq(0); // Hack to avoid silly conversions. BigNumber truncates decimals off.
}
describe("ERC20Rewards", async function () {
this.timeout(0);
let ownerAcc: SignerWithAddress;
let owner: string;
let user1: string;
let user1Acc: SignerWithAddress;
let user2: string;
let user2Acc: SignerWithAddress;
let governance: ERC20;
let rewards: ERC20Rewards;
const ZERO_ADDRESS = "0x" + "0".repeat(40);
async function fixture() {} // For now we just use this to snapshot and revert the state of the blockchain
before(async () => {
await loadFixture(fixture); // This snapshots the blockchain as a side effect
const signers = await ethers.getSigners();
ownerAcc = signers[0];
owner = ownerAcc.address;
user1Acc = signers[1];
user1 = user1Acc.address;
user2Acc = signers[2];
user2 = user2Acc.address;
});
after(async () => {
await loadFixture(fixture); // We advance the time to test maturity features, this rolls it back after the tests
});
beforeEach(async () => {
governance = (await deployContract(ownerAcc, ERC20MockArtifact, [
"Governance Token",
"GOV",
])) as ERC20;
rewards = (await deployContract(ownerAcc, ERC20RewardsMockArtifact, [
"Token with rewards",
"REW",
18,
])) as ERC20Rewards;
await rewards.grantRoles(
[
id(rewards.interface, "setRewardsToken(address)"),
id(rewards.interface, "setRewards(uint32,uint32,uint96)"),
],
owner
);
});
it("mints, transfers, burns", async () => {
expect(await rewards.mint(user1, 1))
.to.emit(rewards, "Transfer")
.withArgs(ZERO_ADDRESS, user1, 1);
expect(await rewards.connect(user1Acc).transfer(user2, 1))
.to.emit(rewards, "Transfer")
.withArgs(user1, user2, 1);
expect(await rewards.connect(user2Acc).burn(user2, 1))
.to.emit(rewards, "Transfer")
.withArgs(user2, ZERO_ADDRESS, 1);
});
it("doesn't set a period where end < start", async () => {
await expect(rewards.setRewards(2, 1, 3)).to.be.revertedWith(
"Incorrect input"
);
});
it("sets a rewards token and program", async () => {
await expect(rewards.setRewards(1, 2, 3)).to.be.revertedWith(
"Rewards token not set"
);
await expect(rewards.setRewardsToken(governance.address))
.to.emit(rewards, "RewardsTokenSet")
.withArgs(governance.address);
await expect(rewards.setRewardsToken(rewards.address)).to.be.revertedWith(
"Rewards token already set"
);
await expect(rewards.setRewards(1, 2, 3))
.to.emit(rewards, "RewardsSet")
.withArgs(1, 2, 3);
const rewardsPeriod = await rewards.rewardsPeriod();
expect(rewardsPeriod.start).to.equal(1);
expect(rewardsPeriod.end).to.equal(2);
expect((await rewards.rewardsPerToken()).rate).to.equal(3);
});
describe("with a rewards program", async () => {
let snapshotId: string;
let timestamp: number;
let start: number;
let length: number;
let mid: number;
let end: number;
let rate: BigNumber;
before(async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
start = timestamp + 1000000;
length = 2000000;
mid = start + length / 2;
end = start + length;
rate = WAD.div(length);
});
beforeEach(async () => {
await rewards.setRewardsToken(governance.address);
await rewards.setRewards(start, end, rate);
await governance.mint(rewards.address, WAD);
await rewards.mint(user1, WAD); // So that total supply is not zero
});
describe("before the program", async () => {
it("allows to change the program", async () => {
expect(await rewards.setRewards(4, 5, 6))
.to.emit(rewards, "RewardsSet")
.withArgs(4, 5, 6);
});
it("doesn't update rewards per token", async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
await rewards.mint(user1, WAD);
expect((await rewards.rewardsPerToken()).accumulated).to.equal(0);
});
it("doesn't update user rewards", async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
await rewards.mint(user1, WAD);
expect((await rewards.rewards(user1)).accumulated).to.equal(0);
});
});
describe("during the program", async () => {
beforeEach(async () => {
snapshotId = await ethers.provider.send("evm_snapshot", []);
await ethers.provider.send("evm_mine", [mid]);
});
afterEach(async () => {
await ethers.provider.send("evm_revert", [snapshotId]);
});
it("doesn't allow to change the program", async () => {
await expect(rewards.setRewards(4, 5, 6)).to.be.revertedWith(
"Ongoing rewards"
);
});
it("updates rewards per token on mint", async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
await rewards.mint(user1, WAD);
almostEqual(
(await rewards.rewardsPerToken()).accumulated,
BigNumber.from(timestamp - start).mul(rate), // ... * 1e18 / totalSupply = ... * WAD / WAD
BigNumber.from(timestamp - start)
.mul(rate)
.div(100000)
);
});
it("updates user rewards on mint", async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
await rewards.mint(user1, WAD);
const rewardsPerToken = (await rewards.rewardsPerToken()).accumulated;
almostEqual(
(await rewards.rewards(user1)).accumulated,
rewardsPerToken, // (... - paidRewardPerToken[user]) * userBalance / 1e18 = (... - 0) * WAD / WAD
rewardsPerToken.div(100000)
);
});
it("updates rewards per token on burn", async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
await rewards.burn(user1, WAD);
almostEqual(
(await rewards.rewardsPerToken()).accumulated,
BigNumber.from(timestamp - start).mul(rate), // ... * 1e18 / totalSupply = ... * WAD / WAD
BigNumber.from(timestamp - start)
.mul(rate)
.div(100000)
);
});
it("updates user rewards on burn", async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
await rewards.burn(user1, WAD);
const rewardsPerToken = (await rewards.rewardsPerToken()).accumulated;
almostEqual(
(await rewards.rewards(user1)).accumulated,
rewardsPerToken, // (... - paidRewardPerToken[user]) * userBalance / 1e18 = (... - 0) * WAD / WAD
rewardsPerToken.div(100000)
);
});
it("updates user rewards on transfer", async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
await rewards.connect(user1Acc).transfer(user2, WAD);
const rewardsPerToken = (await rewards.rewardsPerToken()).accumulated;
almostEqual(
(await rewards.rewards(user1)).accumulated,
rewardsPerToken, // (... - paidRewardPerToken[user]) * userBalance / 1e18 = (... - 0) * WAD / WAD
rewardsPerToken.div(100000)
);
expect((await rewards.rewards(user2)).accumulated).to.equal(0);
expect(await rewards.connect(user2Acc).claim(user2)) // No time has passed, so user2 doesn't get to claim anything
.to.emit(rewards, "Claimed")
.withArgs(user2, 0);
});
it("allows to claim", async () => {
expect(await rewards.connect(user1Acc).claim(user1))
.to.emit(rewards, "Claimed")
.withArgs(user1, await governance.balanceOf(user1));
expect(await governance.balanceOf(user1)).to.equal(
(await rewards.rewardsPerToken()).accumulated
); // See previous test
expect((await rewards.rewards(user1)).accumulated).to.equal(0);
expect((await rewards.rewards(user1)).checkpoint).to.equal(
(await rewards.rewardsPerToken()).accumulated
);
});
});
describe("after the program", async () => {
beforeEach(async () => {
snapshotId = await ethers.provider.send("evm_snapshot", []);
await ethers.provider.send("evm_mine", [end + 1000000]);
});
afterEach(async () => {
await ethers.provider.send("evm_revert", [snapshotId]);
});
it("allows to change the program", async () => {
expect(await rewards.setRewards(4, 5, 6))
.to.emit(rewards, "RewardsSet")
.withArgs(4, 5, 6);
});
it("doesn't update rewards per token past the end date", async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
await rewards.mint(user1, WAD);
expect((await rewards.rewardsPerToken()).accumulated).to.equal(
BigNumber.from(length).mul(rate)
); // Total supply has been WAD for the whole program, but rewardsPerToken is scaled 1e18 up
});
it("doesn't update user rewards", async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
await rewards.mint(user1, WAD);
expect((await rewards.rewards(user1)).accumulated).to.equal(
BigNumber.from(length).mul(rate)
); // The guy got all the rewards == length * rate
});
});
});
}); | the_stack |
import * as cdk from '@aws-cdk/core';
import * as kms from '@aws-cdk/aws-kms';
import * as iam from '@aws-cdk/aws-iam';
import * as lambda from '@aws-cdk/aws-lambda';
import * as s3 from '@aws-cdk/aws-s3';
import * as sns from '@aws-cdk/aws-sns';
import * as dynamodb from '@aws-cdk/aws-dynamodb';
import * as events from '@aws-cdk/aws-events';
import * as sqs from '@aws-cdk/aws-sqs';
import { CfnOutput } from '@aws-cdk/core';
import { LambdaToDynamoDBProps, LambdaToDynamoDB } from '@aws-solutions-constructs/aws-lambda-dynamodb';
import { EventsRuleToLambdaProps, EventsRuleToLambda } from '@aws-solutions-constructs/aws-events-rule-lambda';
import { EventsRuleToSns, EventsRuleToSnsProps } from '@aws-solutions-constructs/aws-events-rule-sns';
import { EventsRuleToSqs, EventsRuleToSqsProps } from '@aws-solutions-constructs/aws-events-rule-sqs';
import { LimitMonitorStackProps } from '../bin/limit-monitor';
import { ArnPrincipal, Effect } from '@aws-cdk/aws-iam';
export class LimitMonitorStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props: LimitMonitorStackProps) {
super(scope, id, props);
new cdk.CfnParameter(this, 'SNSEmail', {
description: 'The email address to subscribe for SNS limit alert messages, leave blank if SNS alerts not needed.',
type: "String"
});
const accountList = new cdk.CfnParameter(this, 'AccountList', {
description: 'List of comma-separated and double-quoted account numbers to monitor. If you leave this parameter blank, ' +
'the solution will only monitor limits in the primary account. If you enter multiple secondary account IDs, you must also provide the primary account ID in this parameter.',
type: "String",
allowedPattern: '^"\\d{12}"(,"\\d{12}")*$|(^\\s*)$'
});
const snsEvents = new cdk.CfnParameter(this, 'SNSEvents', {
description: 'List of alert levels to send email notifications. Must be double-quoted and comma separated. To disable email notifications, leave this blank.',
type: "String",
default: '"WARN","ERROR"'
});
const slackEvents = new cdk.CfnParameter(this, 'SlackEvents', {
description: 'List of alert levels to send Slack notifications. Must be double-quoted and comma separated. To disable slack notifications, leave this blank.',
type: "String",
default: '"WARN","ERROR"'
});
new cdk.CfnParameter(this, 'SlackHookURL', {
description: 'SSM parameter key for incoming Slack web hook URL. Leave blank if you do not wish to receive Slack notifications.',
type: "String"
});
new cdk.CfnParameter(this, 'SlackChannel', {
description: 'SSM parameter key for the Slack channel. Leave blank if you do not wish to receive Slack notifications.',
type: "String"
});
const metricsMapping = new cdk.CfnMapping(this, "MetricsMap")
metricsMapping.setValue("Send-Data", "SendAnonymousData", "Yes")
const refreshRateMapping = new cdk.CfnMapping(this, "RefreshRate")
refreshRateMapping.setValue("CronSchedule", "Default", "rate(1 day)")
const sourceCodeMapping = new cdk.CfnMapping(this, "SourceCode")
sourceCodeMapping.setValue("General", "S3Bucket", props.solutionBucket)
sourceCodeMapping.setValue("General", "KeyPrefix", props.solutionName + '/' + props.solutionVersion)
sourceCodeMapping.setValue("General", "TemplateBucket", props.solutionTemplateBucket)
const eventsMapping = new cdk.CfnMapping(this, "EventsMap")
eventsMapping.setValue("Checks", "Services", '"AutoScaling","CloudFormation","DynamoDB","EBS","EC2","ELB","IAM","Kinesis","RDS","Route53","SES","VPC"')
new cdk.CfnCondition(this, 'SingleAccnt', {
expression: cdk.Fn.conditionEquals('', accountList),
});
new cdk.CfnCondition(this, 'SNSTrue', {
expression: cdk.Fn.conditionNot(cdk.Fn.conditionEquals('', snsEvents)),
});
const slackTrue = new cdk.CfnCondition(this, 'SlackTrue', {
expression: cdk.Fn.conditionNot(cdk.Fn.conditionEquals('', slackEvents)),
});
new cdk.CfnCondition(this, 'AnonymousMetric', {
expression: cdk.Fn.conditionEquals('Yes', cdk.Fn.findInMap('MetricsMap', 'Send-Data', 'SendAnonymousData')),
});
const slackNotifierPolicyName = 'Limit-Monitor-Policy-' + cdk.Aws.STACK_NAME + '-' + cdk.Aws.REGION
const cwLogsPS = new iam.PolicyStatement({
actions: ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
effect: Effect.ALLOW,
resources: [`arn:${cdk.Aws.PARTITION}:logs:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:log-group:/aws/lambda/*`],
sid: 'default'
})
const slackNotifierLambdaRole = new iam.Role(this, 'SlackNotifierRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
path: '/',
inlinePolicies: {
[slackNotifierPolicyName]: new iam.PolicyDocument({
statements: [
cwLogsPS,
new iam.PolicyStatement({
actions: ['ssm:GetParameter'],
effect: Effect.ALLOW,
resources: [`arn:${cdk.Aws.PARTITION}:ssm:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:*`]
})
]
})
}
});
const cfn_nag_w11 = {
"cfn_nag": {
"rules_to_suppress": [
{
"id": "W11",
"reason": "Override the IAM role to allow support:* for logs:PutLogEvents resource on its permissions policy"
}
]
}
}
const slackNotifierLambdaRole_cfn_ref = slackNotifierLambdaRole.node.defaultChild as iam.CfnRole
slackNotifierLambdaRole_cfn_ref.overrideLogicalId('SlackNotifierRole')
slackNotifierLambdaRole_cfn_ref.addOverride('Condition', 'SlackTrue')
slackNotifierLambdaRole_cfn_ref.cfnOptions.metadata = cfn_nag_w11
const solutionSourceCodeBucket = s3.Bucket.fromBucketAttributes(this, 'SolutionSourceCodeBucket', {
bucketName: cdk.Fn.findInMap('SourceCode', 'General', 'S3Bucket') + '-' + cdk.Aws.REGION
});
const slackNotifierLambdaSourceCodeS3Key = cdk.Fn.findInMap('SourceCode', "General", "KeyPrefix") + '/' + 'limtr-slack-service.zip'
const taSlackEventsRuleToLambdaProps: EventsRuleToLambdaProps = {
lambdaFunctionProps: {
description: 'Serverless Limit Monitor - Lambda function to send notifications on slack',
environment: {
SLACK_HOOK: cdk.Fn.sub('SlackHookURL'),
SLACK_CHANNEL: cdk.Fn.sub('SlackChannel'),
LOG_LEVEL: 'INFO'
},
runtime: lambda.Runtime.NODEJS_12_X,
code: lambda.Code.fromBucket(solutionSourceCodeBucket, slackNotifierLambdaSourceCodeS3Key),
handler: 'index.handler',
role: slackNotifierLambdaRole,
timeout: cdk.Duration.seconds(300)
},
eventRuleProps: {
description: 'Limit Monitor Solution - Rule for TA Slack events',
schedule: events.Schedule.expression('rate(24 hours)'),
enabled: true
}
};
const taSlackEventRuleToLambdaConstruct = new EventsRuleToLambda(this, 'TASlackEventRule', taSlackEventsRuleToLambdaProps);
const cfn_nag_w89_w92 = {
cfn_nag: {
rules_to_suppress: [
{
id: "W89",
reason: "Not a valid use case to deploy in VPC",
},
{
id: "W92",
reason: "ReservedConcurrentExecutions not needed",
}
],
},
};
const lambdaSlackNotifier_cfn_ref = taSlackEventRuleToLambdaConstruct.lambdaFunction.node.defaultChild as lambda.CfnFunction
lambdaSlackNotifier_cfn_ref.overrideLogicalId('SlackNotifier')
lambdaSlackNotifier_cfn_ref.addOverride('Condition', 'SlackTrue')
const lambdaSlackNotifier_cfn_permission = taSlackEventRuleToLambdaConstruct.lambdaFunction.permissionsNode.tryFindChild('LambdaInvokePermission') as lambda.CfnPermission
if (lambdaSlackNotifier_cfn_permission != undefined) {
lambdaSlackNotifier_cfn_permission.overrideLogicalId('SlackNotifierInvokePermission')
lambdaSlackNotifier_cfn_permission.addOverride('Condition', 'SlackTrue')
}
lambdaSlackNotifier_cfn_ref.cfnOptions.metadata = cfn_nag_w89_w92
const taslackrule_cfn_ref = taSlackEventRuleToLambdaConstruct.eventsRule.node.defaultChild as events.CfnRule
taslackrule_cfn_ref.overrideLogicalId('TASlackRule')
taslackrule_cfn_ref.addOverride('Condition', 'SlackTrue')
taslackrule_cfn_ref.addOverride('Properties.Targets.0.Id', 'LimitMonitorSlackTarget')
taslackrule_cfn_ref.addOverride('Properties.EventPattern', {
"Fn::Join": [
"",
[
"{\"account\":[",
{
"Fn::If": [
"SingleAccnt",
{
"Fn::Join": [
"",
[
"\"",
{
"Ref": "AWS::AccountId"
},
"\""
]
]
},
{
"Ref": "AccountList"
}
]
},
"],",
"\"source\":[\"aws.trustedadvisor\", \"limit-monitor-solution\"],",
"\"detail-type\":[\"Trusted Advisor Check Item Refresh Notification\", \"Limit Monitor Checks\"],",
"\"detail\":{",
"\"status\":[",
{
"Ref": "SlackEvents"
},
"],",
"\"check-item-detail\":{",
"\"Service\":[",
{
"Fn::FindInMap": [
"EventsMap",
"Checks",
"Services"
]
},
"]",
"}",
"}",
"}"
]
]
})
taslackrule_cfn_ref.addPropertyDeletionOverride('ScheduleExpression')
/*
* Create cloudformation resources for email notifications
* [key policy, kms key, key alias, sns topic, cw event rule]
*/
const LimitMonitorEncrypKeyPS = new iam.PolicyStatement({
actions: [
"kms:Encrypt",
"kms:Decrypt"
],
sid: 'default',
resources: ['*'],
effect: Effect.ALLOW,
principals: [new ArnPrincipal(`arn:${this.partition}:iam::${this.account}:root`)]
});
const limitMonitorEncrypKeyPD = new iam.PolicyDocument()
limitMonitorEncrypKeyPD.addStatements(LimitMonitorEncrypKeyPS)
const limitMonitorEncryptionKey = new kms.Key(this, "LimitMonitorEncryptionKey", {
description: 'Key for SNS and SQS',
enabled: true,
enableKeyRotation: true,
policy: limitMonitorEncrypKeyPD
})
/*
* Create cloudformation resources for TA SQS Event Rule to SQS using aws-events-rule-sqs construct pattern
*/
const taSQSRuleEventsRuleToSqsProps: EventsRuleToSqsProps = {
queueProps: {
encryption: sqs.QueueEncryption.KMS,
encryptionMasterKey: limitMonitorEncryptionKey,
visibilityTimeout: cdk.Duration.seconds(60),
retentionPeriod: cdk.Duration.seconds(86400) //1 day retention
},
deadLetterQueueProps: {
encryption: sqs.QueueEncryption.KMS,
encryptionMasterKey: limitMonitorEncryptionKey,
retentionPeriod: cdk.Duration.seconds(604800) //7 day retention
},
deployDeadLetterQueue: true,
enableEncryptionWithCustomerManagedKey: false,
maxReceiveCount: 3,
eventRuleProps: {
description: 'Limit Monitor Solution - Rule for TA SQS events',
schedule: events.Schedule.expression('rate(24 hours)'),
enabled: true
}
};
const taSQSRuleEventsRuleToSqsConstruct = new EventsRuleToSqs(this, 'TASQSRule', taSQSRuleEventsRuleToSqsProps);
const taevent_queue_cfn_ref = taSQSRuleEventsRuleToSqsConstruct.sqsQueue.node.defaultChild as sqs.CfnQueue
taevent_queue_cfn_ref.overrideLogicalId('EventQueue')
if (taSQSRuleEventsRuleToSqsConstruct.deadLetterQueue != undefined) {
const taevent_deadletterqueue_cfn_ref = taSQSRuleEventsRuleToSqsConstruct.deadLetterQueue.queue.node.defaultChild as sqs.CfnQueue
taevent_deadletterqueue_cfn_ref.overrideLogicalId('DeadLetterQueue')
}
const tasqsrule_cfn_ref = taSQSRuleEventsRuleToSqsConstruct.eventsRule.node.defaultChild as events.CfnRule
tasqsrule_cfn_ref.overrideLogicalId('TASQSRule')
tasqsrule_cfn_ref.addOverride('Properties.EventPattern', {
"Fn::Join": [
"",
[
"{\"account\":[",
{
"Fn::If": [
"SingleAccnt",
{
"Fn::Join": [
"",
[
"\"",
{
"Ref": "AWS::AccountId"
},
"\""
]
]
},
{
"Ref": "AccountList"
}
]
},
"],",
"\"source\":[\"aws.trustedadvisor\", \"limit-monitor-solution\"],",
"\"detail-type\":[\"Trusted Advisor Check Item Refresh Notification\", \"Limit Monitor Checks\"],",
"\"detail\":{",
"\"status\":[",
"\"OK\",\"WARN\",\"ERROR\"",
"],",
"\"check-item-detail\":{",
"\"Service\":[",
{
"Fn::FindInMap": [
"EventsMap",
"Checks",
"Services"
]
},
"]",
"}",
"}",
"}"
]
]
})
tasqsrule_cfn_ref.addPropertyDeletionOverride('ScheduleExpression')
tasqsrule_cfn_ref.addOverride('Properties.Targets.0.Id', 'LimitMonitorSQSTarget')
//Start QueuePollSchedule event rule to Limit Summarizer Lambda construct
const limitSummarizerRoleSQSPS = new iam.PolicyStatement({
actions: ["sqs:DeleteMessage", "sqs:ReceiveMessage"],
effect: Effect.ALLOW,
resources: [taSQSRuleEventsRuleToSqsConstruct.sqsQueue.queueArn]
})
const limitSummarizerRoleDynamoDBPS = new iam.PolicyStatement({
actions: ["dynamodb:GetItem", "dynamodb:PutItem"],
effect: Effect.ALLOW,
resources: [`arn:${cdk.Aws.PARTITION}:dynamodb:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:table/*`]
})
const limitSummarizerRoleKMSPS = new iam.PolicyStatement({
actions: ["kms:GenerateDataKey*", "kms:Decrypt", "kms:Encrypt"],
resources: [limitMonitorEncryptionKey.keyArn],
effect: Effect.ALLOW
})
const limitSummarizerPolicyName = 'Limit-Monitor-Policy-' + cdk.Aws.STACK_NAME + '-' + cdk.Aws.REGION
const limitSummarizerLambdaRole = new iam.Role(this, 'LimitSummarizerRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
path: '/',
inlinePolicies: {
[limitSummarizerPolicyName]: new iam.PolicyDocument({
statements: [
cwLogsPS,
limitSummarizerRoleSQSPS,
limitSummarizerRoleDynamoDBPS,
limitSummarizerRoleKMSPS
]
})
}
});
const limitSummarizerLambdaRole_cfn_ref = limitSummarizerLambdaRole.node.defaultChild as iam.CfnRole
limitSummarizerLambdaRole_cfn_ref.overrideLogicalId('LimitSummarizerRole')
limitSummarizerLambdaRole_cfn_ref.cfnOptions.metadata = cfn_nag_w11
const limitSummarizerLambdaSourceCodeS3Key = cdk.Fn.join("/", [cdk.Fn.findInMap('SourceCode', 'General', 'KeyPrefix'), 'limtr-report-service.zip'])
const sendAnonymousData = cdk.Fn.findInMap('MetricsMap', 'Send-Data', 'SendAnonymousData')
const queuePollScheduleEventsRuleToLambdaProps: EventsRuleToLambdaProps = {
lambdaFunctionProps: {
description: 'Serverless Limit Monitor - Lambda function to summarize service limit usage',
environment: {
//LIMIT_REPORT_TBL: limitSummarizerLambdaToDynamoDb.dynamoTable.tableName,
SQS_URL: taSQSRuleEventsRuleToSqsConstruct.sqsQueue.queueUrl,
MAX_MESSAGES: '10', //100 messages can be read with each invocation, change as needed
MAX_LOOPS: '10',
ANONYMOUS_DATA: sendAnonymousData,
SOLUTION: props.solutionId, //'SO0005'
LOG_LEVEL: 'INFO' //change to WARN, ERROR or DEBUG as needed
},
runtime: lambda.Runtime.NODEJS_12_X,
code: lambda.Code.fromBucket(solutionSourceCodeBucket, limitSummarizerLambdaSourceCodeS3Key),
handler: 'index.handler',
role: limitSummarizerLambdaRole,
timeout: cdk.Duration.seconds(300)
},
eventRuleProps: {
description: 'Limit Monitor Solution - Schedule to poll SQS queue',
schedule: events.Schedule.expression('rate(5 minutes)'),
enabled: true
}
};
const queuePollScheduleEventsRuleToLambdaConstruct = new EventsRuleToLambda(this, 'QueuePollSchedule', queuePollScheduleEventsRuleToLambdaProps);
const lambdaLimitSummarizer_cfn_ref = queuePollScheduleEventsRuleToLambdaConstruct.lambdaFunction.node.defaultChild as lambda.CfnFunction
lambdaLimitSummarizer_cfn_ref.cfnOptions.metadata = cfn_nag_w89_w92
lambdaLimitSummarizer_cfn_ref.overrideLogicalId('LimitSummarizer')
const lambdaLimitSummarizer_cfn_permission = queuePollScheduleEventsRuleToLambdaConstruct.lambdaFunction.permissionsNode.tryFindChild('LambdaInvokePermission') as lambda.CfnPermission
if (lambdaLimitSummarizer_cfn_permission != undefined) {
lambdaLimitSummarizer_cfn_permission.overrideLogicalId('SummarizerInvokePermission')
}
const queuepollschedulerule_cfn_ref = queuePollScheduleEventsRuleToLambdaConstruct.eventsRule.node.defaultChild as events.CfnRule
queuepollschedulerule_cfn_ref.overrideLogicalId('QueuePollSchedule')
// Start creating TARefresher (Trust Advisor Refresher) Cloudformation Resources
// TA Refresher policy documents
const taRefresherRoleSupportPS = new iam.PolicyStatement({
effect: Effect.ALLOW,
actions: ['support:*'],
resources: ['*']
})
const taRefresherRoleServiceQuotasPS = new iam.PolicyStatement({
effect: Effect.ALLOW,
actions: ['servicequotas:GetAWSDefaultServiceQuota'],
resources: ['*']
})
const taRefresherPolicyName = 'Limit-Monitor-Refresher-Policy-' + cdk.Aws.STACK_NAME
// TA Refresher iam role
const taRefresherLambdaRole = new iam.Role(this, 'TARefresherRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
path: '/',
inlinePolicies: {
[taRefresherPolicyName]: new iam.PolicyDocument({
statements: [
cwLogsPS,
taRefresherRoleSupportPS,
taRefresherRoleServiceQuotasPS
]
})
}
});
const cfn_nag_f3_w11 = {
"cfn_nag": {
"rules_to_suppress": [
{
"id": "F3",
"reason": "Override the IAM role to allow support:* resource on its permissions policy"
},
{
"id": "W11",
"reason": "Override the IAM role to allow Resource:* for logs:PutLogEvents, resource on its permissions policy"
}
]
}
}
const taRefresherLambdaRole_cfn_ref = taRefresherLambdaRole.node.defaultChild as iam.CfnRole
taRefresherLambdaRole_cfn_ref.overrideLogicalId('TARefresherRole')
taRefresherLambdaRole_cfn_ref.cfnOptions.metadata = cfn_nag_f3_w11
const taRefresherLambdaSourceCodeS3Key = cdk.Fn.join("/", [cdk.Fn.findInMap('SourceCode', 'General', 'KeyPrefix'), 'limtr-refresh-service.zip'])
const refreshRateCronSchedule = cdk.Fn.findInMap('RefreshRate', 'CronSchedule', 'Default')
// TA Refresher event rule to lambda construct
const taRefresherEventsRuleToLambdaProps: EventsRuleToLambdaProps = {
lambdaFunctionProps: {
description: 'Serverless Limit Monitor - Lambda function to summarize service limits',
environment: {
AWS_SERVICES: cdk.Fn.findInMap('EventsMap', 'Checks', 'Services'),
LOG_LEVEL: 'INFO' //change to WARN, ERROR or DEBUG as needed
},
runtime: lambda.Runtime.NODEJS_12_X,
code: lambda.Code.fromBucket(solutionSourceCodeBucket, taRefresherLambdaSourceCodeS3Key),
handler: 'index.handler',
role: taRefresherLambdaRole,
timeout: cdk.Duration.seconds(300)
},
eventRuleProps: {
description: 'Limit Monitor Solution - Schedule to refresh TA checks',
schedule: events.Schedule.expression(refreshRateCronSchedule),
enabled: true
}
};
const taRefresherEventsRuleToLambdaConstruct = new EventsRuleToLambda(this, 'TARefreshSchedule', taRefresherEventsRuleToLambdaProps);
const lambdaTaRefresher_cfn_ref = taRefresherEventsRuleToLambdaConstruct.lambdaFunction.node.defaultChild as lambda.CfnFunction
lambdaTaRefresher_cfn_ref.cfnOptions.metadata = cfn_nag_w89_w92
lambdaTaRefresher_cfn_ref.overrideLogicalId('TARefresher')
const lambdaTaRefresher_cfn_permission = taRefresherEventsRuleToLambdaConstruct.lambdaFunction.permissionsNode.tryFindChild('LambdaInvokePermission') as lambda.CfnPermission
if (lambdaTaRefresher_cfn_permission != undefined) {
lambdaTaRefresher_cfn_permission.overrideLogicalId('TARefresherInvokePermission')
}
const taRefresherrule_cfn_ref = taRefresherEventsRuleToLambdaConstruct.eventsRule.node.defaultChild as events.CfnRule
taRefresherrule_cfn_ref.overrideLogicalId('TARefreshSchedule')
//Start aws-lambda-dynamoDB construct reference.
const limitSummarizerLambdaToDynamoDBProps: LambdaToDynamoDBProps = {
existingLambdaObj: queuePollScheduleEventsRuleToLambdaConstruct.lambdaFunction,
dynamoTableProps: {
partitionKey: {
name: 'MessageId',
type: dynamodb.AttributeType.STRING
},
sortKey: {
name: 'TimeStamp',
type: dynamodb.AttributeType.STRING
},
billingMode: dynamodb.BillingMode.PROVISIONED,
readCapacity: 2,
writeCapacity: 2,
timeToLiveAttribute: 'ExpiryTime'
},
tablePermissions: "ReadWrite"
};
const limitSummarizerLambdaToDynamoDb = new LambdaToDynamoDB(this, 'SummaryDDB', limitSummarizerLambdaToDynamoDBProps);
const summaryDDB_cfn_ref = limitSummarizerLambdaToDynamoDb.dynamoTable.node.defaultChild as dynamodb.CfnTable
summaryDDB_cfn_ref.overrideLogicalId('SummaryDDB')
summaryDDB_cfn_ref.addPropertyOverride("SSESpecification", {
"SSEEnabled": true
})
queuePollScheduleEventsRuleToLambdaConstruct.lambdaFunction.addEnvironment("LIMIT_REPORT_TBL", limitSummarizerLambdaToDynamoDb.dynamoTable.tableName)
/*
*Start LimtrHelper lambda function
*/
const limtrHelperRoleEventsPS = new iam.PolicyStatement()
limtrHelperRoleEventsPS.effect = iam.Effect.ALLOW
limtrHelperRoleEventsPS.addActions("events:PutPermission", "events:RemovePermission")
limtrHelperRoleEventsPS.addResources(`arn:${cdk.Aws.PARTITION}:events:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:event-bus/default`)
const limtrHelperRoleSSMPS = new iam.PolicyStatement()
limtrHelperRoleSSMPS.effect = iam.Effect.ALLOW
limtrHelperRoleSSMPS.addActions("ssm:GetParameters", "ssm:PutParameter")
limtrHelperRoleSSMPS.addResources(`arn:${cdk.Aws.PARTITION}:ssm:${cdk.Aws.REGION}:${cdk.Aws.ACCOUNT_ID}:parameter/*`)
const limtrHelperPolicy = new iam.PolicyDocument();
limtrHelperPolicy.addStatements(cwLogsPS)
limtrHelperPolicy.addStatements(limtrHelperRoleEventsPS)
limtrHelperPolicy.addStatements(limtrHelperRoleSSMPS)
const limtrHelperPolicyPolicyName = 'Custom_Limtr_Helper_Permissions'
const limtrHelperLambdaRole = new iam.Role(this, 'LimtrHelperRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
path: '/',
inlinePolicies: {
[limtrHelperPolicyPolicyName]: limtrHelperPolicy
}
});
const limtrHelperLambdaRole_cfn_ref = limtrHelperLambdaRole.node.defaultChild as iam.CfnRole
limtrHelperLambdaRole_cfn_ref.overrideLogicalId('LimtrHelperRole')
limtrHelperLambdaRole_cfn_ref.cfnOptions.metadata = cfn_nag_w11
const LimtrHelperLambdaSourceCodeS3Key = cdk.Fn.join("/", [cdk.Fn.findInMap('SourceCode', 'General', 'KeyPrefix'), 'limtr-helper-service.zip'])
const LimtrHelperFunction = new lambda.Function(this, 'LimtrHelperFunction', {
description: 'This function generates UUID, establishes cross account trust on CloudWatch Event Bus and sends anonymous metric',
environment: {
LOG_LEVEL: 'INFO'
},
runtime: lambda.Runtime.NODEJS_12_X,
code: lambda.Code.fromBucket(solutionSourceCodeBucket, LimtrHelperLambdaSourceCodeS3Key),
handler: 'index.handler',
role: limtrHelperLambdaRole,
timeout: cdk.Duration.seconds(300)
})
const limtrhelperlambda_cfn_ref = LimtrHelperFunction.node.defaultChild as lambda.CfnFunction
limtrhelperlambda_cfn_ref.cfnOptions.metadata = cfn_nag_w89_w92
limtrhelperlambda_cfn_ref.overrideLogicalId('LimtrHelperFunction')
const lm_encrypkey_cfn_ref = limitMonitorEncryptionKey.node.defaultChild as cdk.CfnResource
lm_encrypkey_cfn_ref.overrideLogicalId('LimitMonitorEncryptionKey')
const limitMonitorEncryptionKeyAlias = new kms.Alias(this, "LimitMonitorEncryptionKeyAlias", {
aliasName: "alias/limit-monitor-encryption-key",
targetKey: limitMonitorEncryptionKey
})
const lm_encrypkeyalias_cfn_ref = limitMonitorEncryptionKeyAlias.node.defaultChild as cdk.CfnResource
lm_encrypkeyalias_cfn_ref.overrideLogicalId('LimitMonitorEncryptionKeyAlias')
const snsTopic = new sns.Topic(this, 'SNSTopic', {
masterKey: limitMonitorEncryptionKey
})
const sns_topic_cfn_ref = snsTopic.node.defaultChild as sns.CfnTopic
sns_topic_cfn_ref.overrideLogicalId('SNSTopic')
sns_topic_cfn_ref.addOverride('Condition', 'SNSTrue')
sns_topic_cfn_ref.addOverride('Properties.Subscription', [{
"Protocol": "email",
"Endpoint": {
"Fn::Sub": "${SNSEmail}"
}
}])
/*
* Use aws-events-rule-sns construct
*/
const taSNSEventsRuleToSnsProps: EventsRuleToSnsProps = {
existingTopicObj: snsTopic,
enableEncryptionWithCustomerManagedKey: false,
eventRuleProps: {
description: 'Limit Monitor Solution - Rule for TA SNS events',
enabled: true,
schedule: events.Schedule.expression('rate(24 hours)'),
},
encryptionKey: limitMonitorEncryptionKey
};
const taSNSEventsRuleToSnsTopicConstruct = new EventsRuleToSns(this, 'TASNSRule', taSNSEventsRuleToSnsProps);
const tasnsrule_cfn_ref = taSNSEventsRuleToSnsTopicConstruct.eventsRule.node.defaultChild as events.CfnRule
tasnsrule_cfn_ref.overrideLogicalId('TASNSRule')
tasnsrule_cfn_ref.addOverride('Condition', 'SlackTrue')
//add additional details to the event rule target created by default by the construct
tasnsrule_cfn_ref.addOverride('Properties.Targets.0.Id', 'LimitMonitorSNSTarget')
tasnsrule_cfn_ref.addOverride('Properties.Targets.0.InputTransformer', {
"InputPathsMap": {
"limitdetails": "$.detail.check-item-detail",
"time": "$.time",
"account": "$.account"
},
"InputTemplate": "\"AWS-Account : <account> || Timestamp : <time> || Limit-Details : <limitdetails>\""
})
tasnsrule_cfn_ref.addOverride("Properties.EventPattern", {
"Fn::Join": [
"",
[
"{\"account\":[",
{
"Fn::If": [
"SingleAccnt",
{
"Fn::Join": [
"",
[
"\"",
{
"Ref": "AWS::AccountId"
},
"\""
]
]
},
{
"Ref": "AccountList"
}
]
},
"],",
"\"source\":[\"aws.trustedadvisor\", \"limit-monitor-solution\"],",
"\"detail-type\":[\"Trusted Advisor Check Item Refresh Notification\", \"Limit Monitor Checks\"],",
"\"detail\":{",
"\"status\":[",
{
"Ref": "SNSEvents"
},
"],",
"\"check-item-detail\":{",
"\"Service\":[",
{
"Fn::FindInMap": [
"EventsMap",
"Checks",
"Services"
]
},
"]",
"}",
"}",
"}"
]
]
})
tasnsrule_cfn_ref.addPropertyDeletionOverride('ScheduleExpression')
/*
* Custom resource: CreateUUID
*/
const createUUID = new cdk.CustomResource(this, 'CreateUUID', {
resourceType: 'Custom::UUID',
serviceToken: LimtrHelperFunction.functionArn
})
queuePollScheduleEventsRuleToLambdaConstruct.lambdaFunction.addEnvironment('UUID', createUUID.getAttString('UUID'))
/*
* Custom resource: EstablishTrust
*/
let customServiceEstablishTrust = new cdk.CustomResource(this, 'EstablishTrust', {
resourceType: 'Custom::CrossAccntTrust',
serviceToken: LimtrHelperFunction.functionArn
})
const custom_service_establishtrust_cfn_ref = customServiceEstablishTrust.node.defaultChild as cdk.CfnCustomResource
custom_service_establishtrust_cfn_ref.addPropertyOverride('SUB_ACCOUNTS', accountList.valueAsString)
/*
* Custom resource: SSMParameter
*/
let customServiceSSMParameter = new cdk.CustomResource(this, 'SSMParameter', {
resourceType: 'Custom::SSMParameter',
serviceToken: LimtrHelperFunction.functionArn
})
const custom_service_ssmparameter = customServiceSSMParameter.node.defaultChild as cdk.CfnCustomResource
custom_service_ssmparameter.addOverride('Condition', 'SlackTrue')
custom_service_ssmparameter.addPropertyOverride('SLACK_HOOK_KEY', cdk.Fn.sub('SlackHookURL'))
custom_service_ssmparameter.addPropertyOverride('SLACK_CHANNEL_KEY', cdk.Fn.sub('SlackChannel'))
/*
* Custom resource: AccountAnonymousData
*/
let customServiceAcctAnonymousData = new cdk.CustomResource(this, 'AccountAnonymousData', {
resourceType: 'Custom::AnonymousData',
serviceToken: LimtrHelperFunction.functionArn
})
const custom_service_acct_anonymous_Data = customServiceAcctAnonymousData.node.defaultChild as cdk.CfnCustomResource
custom_service_acct_anonymous_Data.addOverride('Condition', 'AnonymousMetric'),
custom_service_acct_anonymous_Data.addPropertyOverride('SOLUTION', 'SO0005')
custom_service_acct_anonymous_Data.addPropertyOverride('UUID', createUUID.getAttString('UUID'))
custom_service_acct_anonymous_Data.addPropertyOverride('SNS_EVENTS', [cdk.Fn.conditionIf('SNSTrue', 'true', 'false')])
custom_service_acct_anonymous_Data.addPropertyOverride('SLACK_EVENTS', [cdk.Fn.conditionIf('SlackTrue', 'true', 'false')])
custom_service_acct_anonymous_Data.addPropertyOverride('SUB_ACCOUNTS', accountList.valueAsString)
custom_service_acct_anonymous_Data.addPropertyOverride('VERSION', props.solutionVersion)
custom_service_acct_anonymous_Data.addPropertyOverride('TA_REFRESH_RATE', refreshRateCronSchedule)
/*
* Custom resource: DeploymentData
*/
let customServiceDeploymentData = new cdk.CustomResource(this, 'DeploymentData', {
resourceType: 'Custom::DeploymentData',
serviceToken: LimtrHelperFunction.functionArn
})
const custom_service_deployment_data = customServiceDeploymentData.node.defaultChild as cdk.CfnCustomResource
custom_service_deployment_data.addPropertyOverride('SOLUTION', 'SO0005')
custom_service_deployment_data.addPropertyOverride('UUID', createUUID.getAttString('UUID'))
custom_service_deployment_data.addPropertyOverride('VERSION', props.solutionVersion)
custom_service_deployment_data.addPropertyOverride('ANONYMOUS_DATA', sendAnonymousData)
/*
* CFN Stack: invoke limit check cfn stack
*/
const templateS3Bucket = cdk.Fn.findInMap("SourceCode", "General", "TemplateBucket")
const limitCheckStackS3Key = cdk.Fn.findInMap("SourceCode", "General", "KeyPrefix") + "/service-quotas-checks.template"
new cdk.CfnStack(this, "limitCheckStack", {
templateUrl: "https://s3.amazonaws.com/" + templateS3Bucket + "/" + limitCheckStackS3Key
})
/*
* CFN Outputs
*/
new CfnOutput(this, 'ServiceChecks', {
value: cdk.Fn.findInMap('EventsMap', 'Checks', 'Services'),
description: 'Service limits monitored in the account'
})
new CfnOutput(this, 'Accounts', {
value: accountList.valueAsString,
description: 'Accounts to be monitored for service limits'
})
new CfnOutput(this, 'SlackChannelKey', {
condition: slackTrue,
value: cdk.Fn.sub('SlackChannel'),
description: 'SSM parameter for Slack Channel, change the value for your slack workspace'
})
new CfnOutput(this, 'SlackHookKey', {
condition: slackTrue,
value: cdk.Fn.sub('SlackHookURL'),
description: 'SSM parameter for Slack Web Hook, change the value for your slack workspace'
})
new CfnOutput(this, 'UUID', {
value: createUUID.getAttString('UUID'),
description: 'UUID for the deployment'
})
const stack = cdk.Stack.of(this)
stack.templateOptions.metadata = {
"AWS::CloudFormation::Interface": {
"ParameterGroups": [
{
"Label": {
"default": "Account Configuration"
},
"Parameters": [
"AccountList"
]
},
{
"Label": {
"default": "Notification Configuration"
},
"Parameters": [
"SNSEvents",
"SNSEmail",
"SlackEvents",
"SlackHookURL",
"SlackChannel"
]
}
],
"ParameterLabels": {
"SNSEmail": {
"default": "Email Address"
},
"AccountList": {
"default": "Account List"
},
"SNSEvents": {
"default": "Email Notification Level"
},
"SlackEvents": {
"default": "Slack Notification Level"
},
"SlackHookURL": {
"default": "Slack Hook Url Key Name"
},
"SlackChannel": {
"default": "Slack Channel Key Name"
}
}
}
}
stack.templateOptions.templateFormatVersion = "2010-09-09"
}
} | the_stack |
* @packageDocumentation
* @hidden
*/
import { JSB } from 'internal:constants';
import { Camera, Model } from 'cocos/core/renderer/scene';
import { UIStaticBatch } from '../components';
import { Material } from '../../core/assets/material';
import { RenderRoot2D, Renderable2D, UIComponent } from '../framework';
import { Texture, Device, Attribute, Sampler, DescriptorSetInfo, Buffer,
BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../../core/gfx';
import { Pool, RecyclePool } from '../../core/memop';
import { CachedArray } from '../../core/memop/cached-array';
import { RenderScene } from '../../core/renderer/scene/render-scene';
import { Root } from '../../core/root';
import { Node } from '../../core/scene-graph';
import { MeshBuffer } from './mesh-buffer';
import { Stage, StencilManager } from './stencil-manager';
import { DrawBatch2D, DrawCall } from './draw-batch';
import * as VertexFormat from './vertex-format';
import { legacyCC } from '../../core/global-exports';
import { ModelLocalBindings, UBOLocal } from '../../core/pipeline/define';
import { SpriteFrame } from '../assets';
import { TextureBase } from '../../core/assets/texture-base';
import { sys } from '../../core/platform/sys';
import { Mat4 } from '../../core/math';
import { IBatcher } from './i-batcher';
const _dsInfo = new DescriptorSetInfo(null!);
const m4_1 = new Mat4();
/**
* @zh
* UI 渲染流程
*/
export class Batcher2D implements IBatcher {
get currBufferBatch () {
if (this._currMeshBuffer) return this._currMeshBuffer;
// create if not set
this._currMeshBuffer = this.acquireBufferBatch();
return this._currMeshBuffer;
}
set currBufferBatch (buffer: MeshBuffer | null) {
if (buffer) {
this._currMeshBuffer = buffer;
}
}
get batches () {
return this._batches;
}
/**
* Acquire a new mesh buffer if the vertex layout differs from the current one.
* @param attributes
*/
public acquireBufferBatch (attributes: Attribute[] = VertexFormat.vfmtPosUvColor) {
const strideBytes = attributes === VertexFormat.vfmtPosUvColor ? 36 /* 9x4 */ : VertexFormat.getAttributeStride(attributes);
if (!this._currMeshBuffer || (this._currMeshBuffer.vertexFormatBytes) !== strideBytes) {
this._requireBufferBatch(attributes);
return this._currMeshBuffer;
}
return this._currMeshBuffer;
}
public registerCustomBuffer (attributes: MeshBuffer | Attribute[], callback: ((...args: number[]) => void) | null) {
let batch: MeshBuffer;
if (attributes instanceof MeshBuffer) {
batch = attributes;
} else {
batch = this._bufferBatchPool.add();
batch.initialize(attributes, callback || this._recreateMeshBuffer.bind(this, attributes));
}
const strideBytes = batch.vertexFormatBytes;
let buffers = this._customMeshBuffers.get(strideBytes);
if (!buffers) { buffers = []; this._customMeshBuffers.set(strideBytes, buffers); }
buffers.push(batch);
return batch;
}
public unRegisterCustomBuffer (buffer: MeshBuffer) {
const buffers = this._customMeshBuffers.get(buffer.vertexFormatBytes);
if (buffers) {
for (let i = 0; i < buffers.length; i++) {
if (buffers[i] === buffer) {
buffers.splice(i, 1);
break;
}
}
}
// release the buffer to recycle pool --
const idx = this._bufferBatchPool.data.indexOf(buffer);
if (idx !== -1) {
buffer.reset();
this._bufferBatchPool.removeAt(idx);
}
// ---
}
set currStaticRoot (value: UIStaticBatch | null) {
this._currStaticRoot = value;
}
set currIsStatic (value: boolean) {
this._currIsStatic = value;
}
public device: Device;
private _screens: RenderRoot2D[] = [];
private _drawBatchPool: Pool<DrawBatch2D>;
private _bufferBatchPool: RecyclePool<MeshBuffer> = new RecyclePool(() => new MeshBuffer(this), 128);
private _meshBuffers: Map<number, MeshBuffer[]> = new Map();
private _customMeshBuffers: Map<number, MeshBuffer[]> = new Map();
private _meshBufferUseCount: Map<number, number> = new Map();
private _batches: CachedArray<DrawBatch2D>;
private _emptyMaterial = new Material();
private _currScene: RenderScene | null = null;
private _currMaterial: Material = this._emptyMaterial;
private _currTexture: Texture | null = null;
private _currSampler: Sampler | null = null;
private _currMeshBuffer: MeshBuffer | null = null;
private _currStaticRoot: UIStaticBatch | null = null;
private _currComponent: Renderable2D | null = null;
private _currTransform: Node | null = null;
private _currTextureHash = 0;
private _currSamplerHash = 0;
private _currBlendTargetHash = 0;
private _currLayer = 0;
private _currDepthStencilStateStage: any | null = null;
private _currIsStatic = false;
private _currOpacity = 1;
private _currBatch!: DrawBatch2D;
// DescriptorSet Cache Map
private _descriptorSetCache = new DescriptorSetCache();
constructor (private _root: Root) {
this.device = _root.device;
this._batches = new CachedArray(64);
this._drawBatchPool = new Pool(() => new DrawBatch2D(), 128);
this._currBatch = this._drawBatchPool.alloc();
}
public initialize () {
return true;
}
public destroy () {
for (let i = 0; i < this._batches.length; i++) {
if (this._batches.array[i]) {
this._batches.array[i].destroy(this);
}
}
this._batches.destroy();
for (const size of this._meshBuffers.keys()) {
const buffers = this._meshBuffers.get(size);
if (buffers) {
buffers.forEach((buffer) => buffer.destroy());
}
}
if (this._drawBatchPool) {
this._drawBatchPool.destroy((obj) => {
obj.destroy(this);
});
}
this._descriptorSetCache.destroy();
this._meshBuffers.clear();
StencilManager.sharedManager!.destroy();
}
/**
* @en
* Add the managed Canvas.
*
* @zh
* 添加屏幕组件管理。
*
* @param comp - 屏幕组件。
*/
public addScreen (comp: RenderRoot2D) {
this._screens.push(comp);
this._screens.sort(this._screenSort);
}
public getFirstRenderCamera (node: Node): Camera | null {
if (node.scene && node.scene.renderScene) {
const cameras = node.scene.renderScene.cameras;
for (let i = 0; i < cameras.length; i++) {
const camera = cameras[i];
if (camera.visibility & node.layer) {
return camera;
}
}
}
return null;
}
/**
* @zh
* Removes the Canvas from the list.
*
* @param comp - 被移除的屏幕。
*/
public removeScreen (comp: RenderRoot2D) {
const idx = this._screens.indexOf(comp);
if (idx === -1) {
return;
}
this._screens.splice(idx, 1);
}
public sortScreens () {
this._screens.sort(this._screenSort);
}
public update () {
const screens = this._screens;
for (let i = 0; i < screens.length; ++i) {
const screen = screens[i];
if (!screen.enabledInHierarchy) {
continue;
}
this._currOpacity = 1;
this._recursiveScreenNode(screen.node);
}
let batchPriority = 0;
if (this._batches.length) {
for (let i = 0; i < this._batches.length; ++i) {
const batch = this._batches.array[i];
if (!batch.renderScene) continue;
if (batch.model) {
const subModels = batch.model.subModels;
for (let j = 0; j < subModels.length; j++) {
subModels[j].priority = batchPriority++;
}
} else {
for (let i = 0; i < batch.drawCalls.length; i++) {
batch.drawCalls[i].descriptorSet = this._descriptorSetCache.getDescriptorSet(batch, batch.drawCalls[i]);
}
}
batch.renderScene.addBatch(batch);
}
}
}
public uploadBuffers () {
if (this._batches.length > 0) {
const buffers = this._meshBuffers;
buffers.forEach((value, key) => {
value.forEach((bb) => {
bb.uploadBuffers();
bb.reset();
});
});
const customs = this._customMeshBuffers;
customs.forEach((value, key) => {
value.forEach((bb) => {
bb.uploadBuffers();
bb.reset();
});
});
this._descriptorSetCache.update();
}
}
public reset () {
for (let i = 0; i < this._batches.length; ++i) {
const batch = this._batches.array[i];
if (batch.isStatic) {
continue;
}
batch.clear();
this._drawBatchPool.free(batch);
}
DrawBatch2D.drawcallPool.reset();
this._currLayer = 0;
this._currMaterial = this._emptyMaterial;
this._currTexture = null;
this._currSampler = null;
this._currComponent = null;
this._currTransform = null;
this._currScene = null;
this._currMeshBuffer = null;
this._currOpacity = 1;
this._meshBufferUseCount.clear();
this._batches.clear();
StencilManager.sharedManager!.reset();
this._descriptorSetCache.reset();
}
/**
* @en
* Render component data submission process of UI.
* The submitted vertex data is the UI for world coordinates.
* For example: The UI components except Graphics and UIModel.
*
* @zh
* UI 渲染组件数据提交流程(针对提交的顶点数据是世界坐标的提交流程,例如:除 Graphics 和 UIModel 的大部分 ui 组件)。
* 此处的数据最终会生成需要提交渲染的 model 数据。
*
* @param comp - 当前执行组件。
* @param frame - 当前执行组件贴图。
* @param assembler - 当前组件渲染数据组装器。
*/
public commitComp (comp: Renderable2D, frame: TextureBase | SpriteFrame | null, assembler: any, transform: Node | null) {
const renderComp = comp;
let texture;
let samp;
let textureHash = 0;
let samplerHash = 0;
if (frame) {
texture = frame.getGFXTexture();
samp = frame.getGFXSampler();
textureHash = frame.getHash();
samplerHash = samp.hash;
} else {
texture = null;
samp = null;
}
const renderScene = renderComp._getRenderScene();
const mat = renderComp.getRenderMaterial(0);
renderComp.stencilStage = StencilManager.sharedManager!.stage;
const blendTargetHash = renderComp.blendHash;
const depthStencilStateStage = renderComp.stencilStage;
if (this._currScene !== renderScene || this._currLayer !== comp.node.layer || this._currMaterial !== mat
|| this._currBlendTargetHash !== blendTargetHash || this._currDepthStencilStateStage !== depthStencilStateStage
|| this._currTextureHash !== textureHash || this._currSamplerHash !== samplerHash || this._currTransform !== transform) {
this.autoMergeBatches(this._currComponent!);
this._currBatch = this._drawBatchPool.alloc();
this._currScene = renderScene;
this._currComponent = renderComp;
this._currTransform = transform;
this._currMaterial = mat!;
this._currTexture = texture;
this._currSampler = samp;
this._currTextureHash = textureHash;
this._currSamplerHash = samplerHash;
this._currBlendTargetHash = blendTargetHash;
this._currDepthStencilStateStage = depthStencilStateStage;
this._currLayer = comp.node.layer;
}
if (assembler) {
assembler.fillBuffers(renderComp, this);
}
}
/**
* @en
* Render component data submission process of UI.
* The submitted vertex data is the UI for local coordinates.
* For example: The UI components of Graphics and UIModel.
*
* @zh
* UI 渲染组件数据提交流程(针对例如: Graphics 和 UIModel 等数据量较为庞大的 ui 组件)。
*
* @param comp - 当前执行组件。
* @param model - 提交渲染的 model 数据。
* @param mat - 提交渲染的材质。
*/
public commitModel (comp: UIComponent | Renderable2D, model: Model | null, mat: Material | null) {
// if the last comp is spriteComp, previous comps should be batched.
if (this._currMaterial !== this._emptyMaterial) {
this.autoMergeBatches(this._currComponent!);
}
let depthStencil;
let dssHash = 0;
if (mat) {
// Notice: A little hack, if not this two stage, not need update here, while control by stencilManger
if (comp.stencilStage === Stage.ENABLED || comp.stencilStage === Stage.DISABLED) {
comp.stencilStage = StencilManager.sharedManager!.stage;
}
depthStencil = StencilManager.sharedManager!.getStencilStage(comp.stencilStage, mat);
dssHash = StencilManager.sharedManager!.getStencilHash(comp.stencilStage);
}
const stamp = legacyCC.director.getTotalFrames();
if (model) {
model.updateTransform(stamp);
model.updateUBOs(stamp);
}
for (let i = 0; i < model!.subModels.length; i++) {
const curDrawBatch = this._drawBatchPool.alloc();
const subModel = model!.subModels[i];
curDrawBatch.renderScene = comp._getRenderScene();
curDrawBatch.visFlags = comp.node.layer;
curDrawBatch.model = model;
curDrawBatch.bufferBatch = null;
curDrawBatch.texture = null;
curDrawBatch.sampler = null;
curDrawBatch.useLocalData = null;
if (!depthStencil) { depthStencil = null; }
curDrawBatch.fillPasses(mat, depthStencil, dssHash, null, 0, subModel.patches, this);
curDrawBatch.inputAssembler = subModel.inputAssembler;
curDrawBatch.model!.visFlags = curDrawBatch.visFlags;
curDrawBatch.fillDrawCallAssembler();
curDrawBatch.drawCalls[0].descriptorSet = subModel.descriptorSet;
this._batches.push(curDrawBatch);
}
// reset current render state to null
this._currMaterial = this._emptyMaterial;
this._currScene = null;
this._currComponent = null;
this._currTransform = null;
this._currTexture = null;
this._currSampler = null;
this._currTextureHash = 0;
this._currLayer = 0;
}
/**
* @en
* Submit separate render data.
* This data does not participate in the batch.
*
* @zh
* 提交独立渲染数据.
* @param comp 静态组件
*/
public commitStaticBatch (comp: UIStaticBatch) {
this._batches.concat(comp.drawBatchList);
this.finishMergeBatches();
}
/**
* @en
* End a section of render data and submit according to the batch condition.
*
* @zh
* 根据合批条件,结束一段渲染数据并提交。
*/
public autoMergeBatches (renderComp?: Renderable2D) {
const buffer = this.currBufferBatch;
const ia = buffer?.recordBatch();
const mat = this._currMaterial;
if (!ia || !mat || !buffer) {
return;
}
let blendState;
let depthStencil;
let dssHash = 0;
let bsHash = 0;
if (renderComp) {
blendState = renderComp.blendHash === -1 ? null : renderComp.getBlendState();
bsHash = renderComp.blendHash;
if (renderComp.customMaterial !== null) {
depthStencil = StencilManager.sharedManager!.getStencilStage(renderComp.stencilStage, mat);
} else {
depthStencil = StencilManager.sharedManager!.getStencilStage(renderComp.stencilStage);
}
dssHash = StencilManager.sharedManager!.getStencilHash(renderComp.stencilStage);
}
const curDrawBatch = this._currStaticRoot ? this._currStaticRoot._requireDrawBatch() : this._currBatch;
curDrawBatch.renderScene = this._currScene;
curDrawBatch.visFlags = this._currLayer;
curDrawBatch.bufferBatch = buffer;
curDrawBatch.texture = this._currTexture!;
curDrawBatch.sampler = this._currSampler;
curDrawBatch.inputAssembler = ia;
curDrawBatch.useLocalData = this._currTransform;
curDrawBatch.textureHash = this._currTextureHash;
curDrawBatch.samplerHash = this._currSamplerHash;
curDrawBatch.fillPasses(this._currMaterial, depthStencil, dssHash, blendState, bsHash, null, this);
curDrawBatch.fillDrawCallAssembler();
this._batches.push(curDrawBatch);
buffer.vertexStart = buffer.vertexOffset;
buffer.indicesStart = buffer.indicesOffset;
buffer.byteStart = buffer.byteOffset;
// HACK: After sharing buffer between drawcalls, the performance degradation a lots on iOS 14 or iPad OS 14 device
// TODO: Maybe it can be removed after Apple fixes it?
// @ts-expect-error Property '__isWebIOS14OrIPadOS14Env' does not exist on 'sys'
if (sys.__isWebIOS14OrIPadOS14Env && !this._currIsStatic) {
this._currMeshBuffer = null;
}
}
/**
* @en
* Force changes to current batch data and merge
*
* @zh
* 强行修改当前批次数据并合并。
*
* @param material - 当前批次的材质。
* @param sprite - 当前批次的精灵帧。
*/
public forceMergeBatches (material: Material, frame: TextureBase | SpriteFrame | null, renderComp: Renderable2D) {
this._currMaterial = material;
if (frame) {
this._currTexture = frame.getGFXTexture();
this._currSampler = frame.getGFXSampler();
this._currTextureHash = frame.getHash();
this._currSamplerHash = this._currSampler.hash;
} else {
this._currTexture = this._currSampler = null;
this._currTextureHash = this._currSamplerHash = 0;
}
this._currLayer = renderComp.node.layer;
this._currScene = renderComp._getRenderScene();
this.autoMergeBatches(renderComp);
}
/**
* @en
* Forced to merge the data of the previous batch to start a new batch.
*
* @zh
* 强制合并上一个批次的数据,开启新一轮合批。
*/
public finishMergeBatches () {
this.autoMergeBatches();
this._currMaterial = this._emptyMaterial;
this._currTexture = null;
this._currComponent = null;
this._currTransform = null;
this._currTextureHash = 0;
this._currSamplerHash = 0;
this._currLayer = 0;
}
/**
* @en
* Force to change the current material.
*
* @zh
* 强制刷新材质。
*/
public flushMaterial (mat: Material) {
this._currMaterial = mat;
}
public walk (node: Node, level = 0) {
const len = node.children.length;
this._preProcess(node);
if (len > 0 && !node._static) {
const children = node.children;
for (let i = 0; i < children.length; ++i) {
this._currOpacity = node._uiProps.opacity;
const child = children[i];
this.walk(child, level);
}
}
this._postProcess(node);
level += 1;
}
private _preProcess (node: Node) {
const render = node._uiProps.uiComp;
const localAlpha = node._uiProps.localOpacity;
node._uiProps.opacity = this._currOpacity * localAlpha;
if (!node._uiProps.uiTransformComp) {
return;
}
if (render && render.enabledInHierarchy) {
render.updateAssembler(this);
}
}
private _postProcess (node: Node) {
const render = node._uiProps.uiComp;
if (render && render.enabledInHierarchy) {
render.postUpdateAssembler(this);
}
}
private _recursiveScreenNode (screen: Node) {
this.walk(screen);
this.autoMergeBatches(this._currComponent!);
}
private _createMeshBuffer (attributes: Attribute[]): MeshBuffer {
const batch = this._bufferBatchPool.add();
batch.initialize(attributes, this._recreateMeshBuffer.bind(this, attributes));
const strideBytes = VertexFormat.getAttributeStride(attributes);
let buffers = this._meshBuffers.get(strideBytes);
if (!buffers) { buffers = []; this._meshBuffers.set(strideBytes, buffers); }
buffers.push(batch);
return batch;
}
private _recreateMeshBuffer (attributes, vertexCount, indexCount) {
this.autoMergeBatches();
this._requireBufferBatch(attributes, vertexCount, indexCount);
}
private _requireBufferBatch (attributes: Attribute[], vertexCount?: number, indexCount?: number) {
const strideBytes = VertexFormat.getAttributeStride(attributes);
let buffers = this._meshBuffers.get(strideBytes);
if (!buffers) { buffers = []; this._meshBuffers.set(strideBytes, buffers); }
let meshBufferUseCount = this._meshBufferUseCount.get(strideBytes) || 0;
// @ts-expect-error Property '__isWebIOS14OrIPadOS14Env' does not exist on 'sys'
if (vertexCount && indexCount || sys.__isWebIOS14OrIPadOS14Env) {
// useCount++ when _recreateMeshBuffer
meshBufferUseCount++;
}
this._currMeshBuffer = buffers[meshBufferUseCount];
if (!this._currMeshBuffer) {
this._currMeshBuffer = this._createMeshBuffer(attributes);
}
this._meshBufferUseCount.set(strideBytes, meshBufferUseCount);
if (vertexCount && indexCount) {
this._currMeshBuffer.request(vertexCount, indexCount);
}
}
private _screenSort (a: RenderRoot2D, b: RenderRoot2D) {
return a.node.getSiblingIndex() - b.node.getSiblingIndex();
}
private _releaseDescriptorSetCache (textureHash: number) {
this._descriptorSetCache.releaseDescriptorSetCache(textureHash);
}
}
class LocalDescriptorSet {
private _descriptorSet: DescriptorSet | null = null;
private _transform: Node | null = null;
private _textureHash = 0;
private _samplerHash = 0;
private _localBuffer: Buffer | null = null;
private _transformUpdate = true;
private declare _localData;
public get descriptorSet (): DescriptorSet | null {
return this._descriptorSet;
}
constructor () {
const device = legacyCC.director.root.device;
this._localData = new Float32Array(UBOLocal.COUNT);
this._localBuffer = device.createBuffer(new BufferInfo(
BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST,
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
UBOLocal.SIZE,
UBOLocal.SIZE,
));
}
public initialize (batch) {
const device = legacyCC.director.root.device;
this._transform = batch.useLocalData;
this._textureHash = batch.textureHash;
this._samplerHash = batch.samplerHash;
_dsInfo.layout = batch.passes[0].localSetLayout;
this._descriptorSet = device.createDescriptorSet(_dsInfo);
this._descriptorSet!.bindBuffer(UBOLocal.BINDING, this._localBuffer!);
const binding = ModelLocalBindings.SAMPLER_SPRITE;
this._descriptorSet!.bindTexture(binding, batch.texture!);
this._descriptorSet!.bindSampler(binding, batch.sampler!);
this._descriptorSet!.update();
this._transformUpdate = true;
}
public updateTransform (transform: Node) {
if (transform === this._transform) return;
this._transform = transform;
this._transformUpdate = true;
this.uploadLocalData();
}
public updateLocal () {
if (!this._transform) return;
this.uploadLocalData();
}
public equals (transform, textureHash, samplerHash) {
return this._transform === transform && this._textureHash === textureHash && this._samplerHash === samplerHash;
}
public reset () {
this._transform = null;
this._textureHash = 0;
this._samplerHash = 0;
}
public destroy () {
if (this._localBuffer) {
this._localBuffer.destroy();
this._localBuffer = null;
}
if (this._descriptorSet) {
this._descriptorSet.destroy();
this._descriptorSet = null;
}
this._localData = null;
}
private uploadLocalData () {
const node = this._transform!;
// @ts-expect-error TS2445
if (node.hasChangedFlags || node._dirtyFlags) {
node.updateWorldTransform();
}
if (this._transformUpdate) {
// @ts-expect-error TS2445
const worldMatrix = node._mat;
Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET);
Mat4.inverseTranspose(m4_1, worldMatrix);
if (!JSB) {
// fix precision lost of webGL on android device
// scale worldIT mat to around 1.0 by product its sqrt of determinant.
const det = Mat4.determinant(m4_1);
const factor = 1.0 / Math.sqrt(det);
Mat4.multiplyScalar(m4_1, m4_1, factor);
}
Mat4.toArray(this._localData, m4_1, UBOLocal.MAT_WORLD_IT_OFFSET);
this._localBuffer!.update(this._localData);
this._transformUpdate = false;
}
}
}
class DescriptorSetCache {
private _descriptorSetCache = new Map<number, DescriptorSet>();
private _dsCacheHashByTexture = new Map<number, number>();
private _localDescriptorSetCache: LocalDescriptorSet[] = [];
private _localCachePool: Pool<LocalDescriptorSet>;
constructor () {
this._localCachePool = new Pool(() => new LocalDescriptorSet(), 16);
}
public getDescriptorSet (batch: DrawBatch2D, drawCall: DrawCall): DescriptorSet {
const root = legacyCC.director.root;
let hash;
if (batch.useLocalData) {
const caches = this._localDescriptorSetCache;
for (let i = 0, len = caches.length; i < len; i++) {
const cache: LocalDescriptorSet = caches[i];
if (cache.equals(batch.useLocalData, batch.textureHash, batch.samplerHash)) {
return cache.descriptorSet!;
}
}
const localDs = this._localCachePool.alloc();
localDs.initialize(batch);
this._localDescriptorSetCache.push(localDs);
return localDs.descriptorSet!;
} else {
hash = batch.textureHash ^ batch.samplerHash ^ drawCall.bufferHash;
if (this._descriptorSetCache.has(hash)) {
return this._descriptorSetCache.get(hash)!;
} else {
const device = legacyCC.director.root.device;
_dsInfo.layout = batch.passes[0].localSetLayout;
const descriptorSet = root.device.createDescriptorSet(_dsInfo) as DescriptorSet;
const binding = ModelLocalBindings.SAMPLER_SPRITE;
descriptorSet.bindTexture(binding, batch.texture!);
descriptorSet.bindSampler(binding, batch.sampler!);
descriptorSet.update();
this._descriptorSetCache.set(hash, descriptorSet);
this._dsCacheHashByTexture.set(batch.textureHash, hash);
return descriptorSet;
}
}
}
public update () {
const caches = this._localDescriptorSetCache;
caches.forEach((value) => {
value.updateLocal();
});
}
public reset () {
const caches = this._localDescriptorSetCache;
caches.forEach((value) => {
this._localCachePool.free(value);
});
this._localDescriptorSetCache.length = 0;
}
public releaseDescriptorSetCache (textureHash) {
const key = this._dsCacheHashByTexture.get(textureHash);
if (key && this._descriptorSetCache.has(key)) {
this._descriptorSetCache.get(key)!.destroy();
this._descriptorSetCache.delete(key);
this._dsCacheHashByTexture.delete(textureHash);
}
}
public destroy () {
this._descriptorSetCache.forEach((value, key, map) => {
value.destroy();
});
this._descriptorSetCache.clear();
this._dsCacheHashByTexture.clear();
this._localDescriptorSetCache.length = 0;
this._localCachePool.destroy((obj) => { obj.destroy(); });
}
} | the_stack |
import { ApolloServer } from "apollo-server-lambda";
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context as AWSContext } from "aws-lambda";
import http from "http";
import { get, set } from "lodash";
import { xml2js } from "xml-js";
import { Context, Scope } from ".";
import directives from "./directives";
import policyManager, { internalPolicies } from "./policies";
import Policy from "./policies/policy";
import scalars from "./scalars";
const colors = require('colors/safe');
/**
* Options for http server
*/
interface Options {
/** env for debug log */
env: "development" | "production";
}
/**
* Yap api gateway
*/
export default class Yap {
/** policies */
public policy: { [key: string]: Policy[] } = {};
/**
* Instance of lambda server
*/
public lambdaServer: ApolloServer;
/**
* httpServer
*/
public server: http.Server | null = null;
/**
* Instance of async lambda server handler
*/
private lambdaServerHandler: (
context: Context,
awsContext: AWSContext,
) => Promise<APIGatewayProxyResult>;
/**
* Creates YAP instance
* @param args Graph QL Type definitions, resolvers. Policy XML definitions and custom policy handlers
*/
constructor(args: {
/**
* Graph QL type definitions as string
*/
typeDefs: string | string[],
/**
* Graph QL Directives
*/
schemaDirectives?: { [key: string]: any},
/**
* Graph QL resolvers
*/
resolvers: any,
/**
* XML Definitions of policies
*/
policies?: string,
/**
* Custom policy handlers
*/
customPolicies?: Policy[],
}) {
const { resolvers, policies, customPolicies } = args;
let { typeDefs, schemaDirectives } = args;
if (customPolicies) {
customPolicies.map((policy) => policyManager.addPolicy(policy));
}
if (policies) {
this.loadPolicies(policies);
}
if(typeof typeDefs === "string") {
typeDefs = [scalars.typeDefs, typeDefs];
}
if(!schemaDirectives) {
schemaDirectives = {};
}
for(const [ directiveKey, directive] of Object.entries(directives)) {
typeDefs.push(directive.definition);
schemaDirectives[directiveKey] = directive.directive;
}
this.lambdaServer = new ApolloServer({ typeDefs, resolvers: { ...scalars.resolvers, ...resolvers }, schemaDirectives });
const awsHandler = this.lambdaServer.createHandler();
this.lambdaServerHandler = (context: Context,
awsContext: AWSContext) => new Promise((resolve, reject) => {
try {
awsHandler(
context.request as APIGatewayProxyEvent,
context as any,
(error?: Error | null | string, result?: APIGatewayProxyResult) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
} catch (callError) {
reject(callError);
}
});
}
/**
* Request handler for AWS Labdas
* @param awsEvent - AWS lambda event
*/
public async handler(awsEvent: APIGatewayProxyEvent, awsContext: AWSContext): Promise<APIGatewayProxyResult> {
const context = { request: awsEvent, LastError: undefined, response: { statusCode: 200, body: 'OK' } };
try {
await this.applyPolicies(Scope.inbound, context);
const response = await this.lambdaServerHandler(context, awsContext);
context.response = response;
await this.applyPolicies(Scope.outbound, context);
} catch (error) {
try {
context.LastError = error;
await this.applyPolicies(Scope.onerror, context);
set(context, 'response.statusCode', get(context, 'response.statusCode', 500));
set(context, 'response.body', get(context, 'response.body', error));
} catch (applyOnErrorPoliciesError) {
set(context, 'response.statusCode', get(context, 'response.statusCode', 500));
set(context, 'response.body', get(context, 'response.body', applyOnErrorPoliciesError));
}
}
return context.response;
}
/**
* Listen for connections.
*
* A node `http.Server` is returned, with this
* application (which is a `Function`) as its
* callback. If you wish to create both an HTTP
* and HTTPS server you may do so with the "http"
* and "https" modules as shown here:
*
* var http = require('http')
* , https = require('https')
* , yap = require('yap')
* , app = new Yap();
*
* http.createServer(app).listen(80);
* https.createServer({ ... }, app).listen(443);
*
* @return {http.Server}
* @public
*/
public listen(port: number, options?: Options): http.Server {
this.server = http.createServer(async (req: any, res: any) => {
let body: any = [];
req.on('data', (chunk: string) => {
body.push(chunk);
});
req.on('end', () => {
body = Buffer.concat(body).toString();
});
const event: any = {
httpMethod: req.method,
...req,
body,
};
const queryResponse = await this.handler(event, {
callbackWaitsForEmptyEventLoop: false,
functionName: "1",
functionVersion: "1",
invokedFunctionArn: "1",
memoryLimitInMB: "100",
awsRequestId: "1",
logGroupName: "1",
logStreamName: "1",
getRemainingTimeInMillis: () => 1,
done: (error?: Error, result?: any) => void 0,
fail: (error: Error | string) => void 0,
succeed: (messageOrObject: any) => void 0,
});
res.writeHead(queryResponse.statusCode, queryResponse.headers);
res.write(queryResponse.body);
if (options && options.env === "development") {
console.info(
(queryResponse.statusCode < 400 ? colors.green.bold(req.method) : colors.red.bold(req.method))
+ ' ' + req.url + ' - ' + queryResponse.statusCode);
}
res.end();
});
return this.server.listen(port) as http.Server;
}
/**
* Close server
*/
public close() {
if (this.server) {
return this.server.close();
}
}
/**
* Apply policies
*/
public async applyPolicies(scope: Scope, context: Context): Promise<boolean> {
if (this.policy[scope]) {
for (const policyElement of this.policy[scope]) {
await policyManager.apply({ policyElement, context, scope });
}
}
return true;
}
/**
* Deletes policy with id from server
* @param id id of policy
*/
public deletePolicy(id: string) {
for (const [scope, policies] of Object.entries(this.policy)) {
for (let i = 0; i < policies.length; i++) {
if (this.policy[scope][i].name === id) {
policies.splice(i, 1);
policyManager.deletePolicy(id);
break;
}
}
}
}
/**
* Validates policy definition and policies. By default validating only internal policies
* @param parsedPolicies Parsed policy XML
* @param validateAllPolicies should validate all policies including custom policies
*/
public validatePolicies(parsedPolicies: object, validateAllPolicies?: boolean) {
//avoid double parsing
let errors: string[] = [];
const policiesContainer = get(parsedPolicies, 'elements[0]');
if (!policiesContainer
|| policiesContainer.name !== "policies"
|| !(policiesContainer.elements instanceof Array)
|| !policiesContainer.elements.length) {
errors.push('policies-ERR-001: XML should contain root element <policies> with scopes');
} else {
for (const policy of policiesContainer.elements) {
if (Object.values(Scope).indexOf(policy.name) === -1) {
errors.push(`policies-ERR-002: XML tag <policies/> must only contains `
+ `<inbound />, <outbound />, <on-error /> XML Tag, found <${policy.name}>`);
} else {
if (!(policy.elements instanceof Array)) {
errors.push(
`policies-ERR-003: XML tag <policies/> should contains at least one policy. Tag <${policy.name}> have no elements`);
} else {
for (const policyElement of policy.elements) {
const policyInstance = policyManager.getPolicy(policyElement.name);
if (!policyInstance) {
errors.push(`policies-ERR-004: XML tag <${policy.name}> contains unknown policy <${policyElement.name}>. `
+ `Please, load definition for this policy before loading of XML`);
} else {
if (validateAllPolicies || internalPolicies.indexOf(policyInstance.id) > -1) {
const policyInstanceErrors = policyInstance.validate(policyElement);
if (policyInstanceErrors.length) {
errors = [...errors, ...policyInstanceErrors];
}
}
}
}
}
}
}
}
return errors;
}
/**
* Loads policies from XML file
* Use @validatePolicies to validate XML string first
* @param xml policy in a format of XML
*/
public loadPolicies(xml: string) {
const parsedXML = xml2js(xml);
const validationResult = this.validatePolicies(parsedXML, false);
if (validationResult.length) {
throw new Error(`Error validating policies. Please, fix errors in XML: \n ${validationResult.join('\n')}`);
}
this.policy = {};
for (const entry of parsedXML.elements[0].elements) {
this.policy[entry.name] = entry.elements;
}
}
} | the_stack |
import chai, {expect} from 'chai';
import chaiAsPromised from 'chai-as-promised';
import chaiDom from 'chai-dom';
chai.use(chaiDom);
chai.use(chaiAsPromised);
import {readFileSync} from 'fs';
import {resolve} from 'path';
import ace from 'brace';
import fetchMock from 'fetch-mock';
import {OutputArea} from '../../src/ts/areas';
import * as Strings from '../../src/ts/strings';
import {DownloadRequest} from '../../src/ts/comms';
import {widgetFactory} from '../../src/ts/widget';
import {ServerWorker} from '../../src/ts/server';
import {RunProgram} from '../../src/ts/server-types';
import {getElemsByTag, getElemById, getElemsByClass}
from '../../src/ts/dom-utils';
/**
* Helper function to fill DOM from a file
*
* @param {string} filename - The filename to use
*/
function fillDOM(filename: string): void {
global.document = window.document;
const htmlString = readFileSync(resolve(__dirname, '../html/html/' +
filename), 'utf8');
document.documentElement.innerHTML = htmlString;
}
/**
* Clears the DOM
*
*/
function clearDOM(): void {
document.documentElement.innerHTML = '';
}
/**
* Helper function to trigger an event
*
* @param {HTMLElement} element - The element to trigger the event on
* @param {string} eventName - The event name to trigger
*/
function triggerEvent(element: HTMLElement, eventName: string): void {
const event = document.createEvent('HTMLEvents');
event.initEvent(eventName, false, true);
element.dispatchEvent(event);
}
describe('Widget', () => {
let inTest: Array<HTMLElement>;
let root: HTMLElement;
const baseURL = 'https://cloudchecker-staging.learn.r53.adacore.com';
describe('Single Widget', () => {
before(() => {
fillDOM('single.html');
inTest = getElemsByTag(document, 'widget');
widgetFactory(inTest as Array<HTMLDivElement>);
root = inTest[0];
});
after(() => {
clearDOM();
});
it('should have a single widget on the page', () => {
expect(inTest).to.have.length(1);
});
it('should have one tab with active status', () => {
const tabs = getElemById(root.id + '.tab');
const headers = getElemsByTag(tabs, 'button');
expect(headers).to.have.length(1);
expect(headers[0]).to.have.class('active');
});
it('should have lab setting false', () => {
const lab = root.dataset.lab;
expect(lab).to.equal('False');
});
it('should not have a lab area', () => {
expect(() => {
getElemById(root.id + '.lab-area');
}).to.throw();
});
it('should not have a cli area', () => {
expect(() => {
getElemById(root.id + '.cli');
}).to.throw();
});
describe('Action Buttons', () => {
let buttonGroup: HTMLElement;
let outputDiv: HTMLElement;
let runButton: HTMLButtonElement;
const identifier = 123;
before(() => {
buttonGroup = getElemById(root.id + '.button-group');
outputDiv = getElemById(root.id + '.output-area');
// stub scrollIntoView function beacuse JSDOM doesn't have it
// eslint-disable-next-line max-len
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
window.HTMLElement.prototype.scrollIntoView = (arg: any): void => {};
});
it('should have a single run button', () => {
const buttons = getElemsByTag(buttonGroup, 'button');
expect(buttons).to.have.length(1);
runButton = buttons[0] as HTMLButtonElement;
const mode = runButton.dataset.mode;
expect(mode).to.equal('run');
});
describe('Normal Behavior', () => {
let editor: ace.Editor;
const consoleMsg = 'This is a console message';
const clickableInfoMsg = 'test.adb:1:2: info: This is an info message';
const clickableStdoutMsg = 'test.adb:2:3: Clickable stdout message';
const raisedMsg = 'raised TEST_ERROR : test.adb:3 explicit raise';
before(async () => {
const editorDiv = getElemById(root.id + '.editor');
editor = ace.edit(editorDiv);
fetchMock.post(baseURL + '/run_program/', {
body: {
'identifier': identifier.toString(),
'message': 'Pending',
},
});
fetchMock.post(baseURL + '/check_output/', {
body: {
'completed': false,
'message': 'PENDING',
'output': [
{
'msg': {
'data': consoleMsg,
'type': 'console',
},
},
],
'status': 0,
},
}, {
repeat: 1,
});
fetchMock.post(baseURL + '/check_output/', {
body: {
'completed': false,
'message': 'PENDING',
'output': [
{
'msg': {
'data': clickableInfoMsg,
'type': 'stdout',
},
},
],
'status': 0,
},
}, {
repeat: 1,
overwriteRoutes: false,
});
fetchMock.post(baseURL + '/check_output/', {
body: {
'completed': true,
'message': 'SUCCESS',
'output': [
{
'msg': {
'data': clickableStdoutMsg,
'type': 'stdout',
},
}, {
'msg': {
'data': raisedMsg,
'type': 'stderr',
},
},
],
'status': 0,
},
}, {
repeat: 1,
overwriteRoutes: false,
});
runButton.click();
await ServerWorker.delay(3 * 250);
await fetchMock.flush(true);
});
after(() => {
fetchMock.reset();
});
it('should trigger a run program post when clicked', () => {
const runProgram = fetchMock.calls(baseURL + '/run_program/');
expect(runProgram).to.have.length(1);
const expectSwitches = {
'Builder': ['-test'],
'Compiler': ['-test'],
};
const request =
JSON.parse(runProgram[0][1]['body'] as string) as RunProgram.TS;
expect(request.files).to.have.length(1);
expect(request.mode).to.equal('run');
expect(request.switches).to.deep.equal(expectSwitches);
expect(request.name).to.equal('Test.Single');
expect(request.lab).to.be.false;
});
it('should have an output area with the received data', () => {
const fakeOutputAreaDiv = document.createElement('div');
const fakeOutputArea = new OutputArea(fakeOutputAreaDiv);
fakeOutputArea.add(['output_info', 'console_output'],
Strings.CONSOLE_OUTPUT_LABEL + ':');
fakeOutputArea.addConsole(consoleMsg);
fakeOutputArea.addInfo(clickableInfoMsg);
fakeOutputArea.addMsg(clickableStdoutMsg);
fakeOutputArea.addMsg(raisedMsg);
expect(outputDiv).to.have.html(fakeOutputAreaDiv.innerHTML);
});
it('should have a clickable info div', () => {
const infoMsg = getElemsByClass(outputDiv, 'output_msg_info');
// remove active class from header before click to see if click cb
// worked properly
const header = getElemById(root.id + '.tab.test.adb');
header.classList.remove('active');
infoMsg[0].click();
expect(header).to.have.class('active');
expect(editor.getCursorPosition()).to.deep.equal({
row: 0, column: 1});
});
});
describe('Error Behavior', () => {
let fakeDiv: HTMLDivElement;
let fakeOA: OutputArea;
let realDiv: HTMLElement;
beforeEach(() => {
fakeDiv = document.createElement('div') as HTMLDivElement;
fakeOA = new OutputArea(fakeDiv);
fakeOA.add(['output_info', 'console_output'],
Strings.CONSOLE_OUTPUT_LABEL + ':');
realDiv = getElemById(root.id + '.output-area');
});
afterEach(() => {
fetchMock.reset();
});
it('should handle an error if ServerWorker throws', async () => {
fetchMock.post(baseURL + '/run_program/', {
body: {
'identifier': '',
'message': 'Pending',
},
});
fakeOA.addError(Strings.MACHINE_BUSY_LABEL);
runButton.click();
await fetchMock.flush(true);
expect(fakeDiv.innerHTML).to.equal(realDiv.innerHTML);
});
it('should handle an error if response has lab ref', async () => {
fetchMock.post(baseURL + '/run_program/', {
body: {
'identifier': '1234',
'message': 'Pending',
},
});
fetchMock.post(baseURL + '/check_output/', {
body: {
'completed': false,
'message': 'PENDING',
'output': [
{
'msg': {
'data': 'test data',
'type': 'console',
},
'ref': '0',
},
],
'status': 0,
},
});
fakeOA.addError(Strings.MACHINE_BUSY_LABEL);
runButton.click();
await ServerWorker.delay(2 * 250);
await fetchMock.flush(true);
expect(fakeDiv.innerHTML).to.equal(realDiv.innerHTML);
});
it('should report internal errors normally', async () => {
fetchMock.post(baseURL + '/run_program/', {
body: {
'identifier': '1234',
'message': 'Pending',
},
});
fetchMock.post(baseURL + '/check_output/', {
body: {
'completed': true,
'message': 'PENDING',
'output': [
{
'msg': {
'data': 'There was an error.',
'type': 'internal_error',
},
},
],
'status': -1,
},
});
fakeOA.addLine(
'There was an error. ' + Strings.INTERNAL_ERROR_MESSAGE);
fakeOA.addError(Strings.EXIT_STATUS_LABEL +
': ' + -1);
runButton.click();
await ServerWorker.delay(2 * 250);
await fetchMock.flush(true);
expect(fakeDiv.innerHTML).to.equal(realDiv.innerHTML);
});
it('should throw an error when msg has a bad type', async () => {
fetchMock.post(baseURL + '/run_program/', {
body: {
'identifier': '1234',
'message': 'Pending',
},
});
fetchMock.post(baseURL + '/check_output/', {
body: {
'completed': false,
'message': 'PENDING',
'output': [
{
'msg': {
'data': 'Test message',
'type': 'blahblahblah',
},
},
],
'status': 0,
},
});
fakeOA.addLine('Test message');
fakeOA.addError(Strings.MACHINE_BUSY_LABEL);
runButton.click();
await ServerWorker.delay(2 * 250);
await fetchMock.flush(true);
expect(fakeDiv.innerHTML).to.equal(realDiv.innerHTML);
});
});
});
describe('Settings Bar', () => {
let editor: ace.Editor;
before(() => {
const editorDiv = getElemById(root.id + '.editor');
editor = ace.edit(editorDiv);
});
it('should have a checkbox that switches editor theme', () => {
const box = getElemById(root.id + '.settings-bar.theme-setting') as
HTMLInputElement;
const origTheme = editor.getTheme();
box.checked = !box.checked;
triggerEvent(box, 'change');
expect(editor.getTheme()).to.not.equal(origTheme);
});
it('should have a checkbox that switches tab setting', () => {
// const box = getElemById(root.id + '.settings-bar.tab-setting') as
// HTMLInputElement;
// expect.fail('Test not implemented.');
});
it('should have a button that resets the editor', () => {
const btn = getElemById(root.id + '.settings-bar.reset-btn') as
HTMLButtonElement;
const session = editor.getSession();
const origContent = session.getValue();
session.doc.insert({row: 0, column: 0}, '\n');
expect(session.getValue()).to.not.equal(origContent);
// overwrite window.confirm because jsdom doesn't implement this
window.confirm = (): boolean => true;
btn.click();
expect(session.getValue()).to.equal(origContent);
});
describe('Download Button', () => {
let btn: HTMLButtonElement;
before(() => {
btn = getElemById(root.id + '.settings-bar.download-btn') as
HTMLButtonElement;
// stub this because JSDOM doesn't have it
// eslint-disable-next-line max-len
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars
global.URL.createObjectURL = (object: any): string => {
return '#';
};
// eslint-disable-next-line max-len
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
global.URL.revokeObjectURL = (url: any): void => {};
});
afterEach(() => {
fetchMock.reset();
});
it('should have a button that downloads the project', async () => {
const filename = 'test.zip';
const blob = new Blob(['test'], {type: 'text/plain;charset=utf-8'});
fetchMock.post(baseURL + '/download/', {
body: blob,
headers: {
'Content-Disposition': 'attachment; filename=' + filename,
},
},
{
sendAsJson: false,
});
btn.click();
await fetchMock.flush(true);
const downloadRequest = fetchMock.calls(baseURL + '/download/');
expect(downloadRequest).to.have.length(1);
const expectSwitches = {
'Builder': ['-test'],
'Compiler': ['-test'],
};
const request =
JSON.parse(downloadRequest[0][1]['body'] as string) as
DownloadRequest;
expect(request.files).to.have.length(1);
expect(request.switches).to.deep.equal(expectSwitches);
expect(request.name).to.equal('Test.Single');
});
it('should handle an exception', async () => {
fetchMock.post(baseURL + '/download/', 500);
const fakeDiv = document.createElement('div');
const fakeOA = new OutputArea(fakeDiv);
fakeOA.addError(Strings.MACHINE_BUSY_LABEL);
const realOA = getElemById(root.id + '.output-area');
btn.click();
await fetchMock.flush(true);
expect(realOA.innerHTML).to.equal(fakeDiv.innerHTML);
});
});
});
});
describe('Lab Widget', () => {
before(() => {
fillDOM('lab.html');
inTest = getElemsByTag(document, 'widget');
widgetFactory(inTest as Array<HTMLDivElement>);
root = inTest[0];
});
after(() => {
clearDOM();
});
it('should have a single LabWidget on the page', () => {
expect(inTest).to.have.length(1);
});
it('should have lab setting true', () => {
const lab = root.dataset.lab;
expect(lab).to.equal('True');
});
it('should have a lab area', () => {
expect(() => {
getElemById(root.id + '.lab-area');
}).not.to.throw();
});
it('should have a shadow file', () => {
expect(root).to.have.descendants('.shadow-file').and.have.length(1);
});
describe('Action Buttons', () => {
let buttonGroup: HTMLElement;
let outputDiv: HTMLElement;
let submitButton: HTMLButtonElement;
before(() => {
buttonGroup = getElemById(root.id + '.button-group');
outputDiv = getElemById(root.id + '.output-area');
});
it('should have a single submit button', () => {
const buttons = getElemsByTag(buttonGroup, 'button');
expect(buttons).to.have.length(1);
submitButton = buttons[0] as HTMLButtonElement;
const mode = submitButton.dataset.mode;
expect(mode).to.equal('submit');
});
describe('Normal Behavior', () => {
const identifier = 123;
const consoleMsg = 'General message';
before(async () => {
fetchMock.post(baseURL + '/run_program/', {
body: {
'identifier': identifier.toString(),
'message': 'Pending',
},
});
fetchMock.post(baseURL + '/check_output/', {
body: {
'completed': true,
'message': 'SUCCESS',
'output': [
{
'msg': {
'data': consoleMsg,
'type': 'console',
},
}, {
'msg': {
'data': 'test ref 0',
'type': 'console',
},
'ref': '0',
}, {
'msg': {
'data': {
'cases': {
'0': {
'actual': 'actual',
'in': [],
'out': 'out',
'status': 'Success',
},
},
'success': true,
},
'type': 'lab',
},
},
],
'status': 0,
},
});
submitButton.click();
await ServerWorker.delay(3 * 250);
await fetchMock.flush(true);
});
after(() => {
fetchMock.reset();
});
it('should trigger a submit post when clicked', () => {
const submission = fetchMock.calls(baseURL + '/run_program/');
expect(submission).to.have.length(1);
const request = JSON.parse(submission[0][1]['body'] as string) as
RunProgram.TS;
expect(request.files).to.have.length(2);
expect(request.mode).to.equal('submit');
expect(request.name).to.equal('Test.Lab');
expect(request.lab).to.be.true;
});
it('should have an output area with the received data', () => {
const fakeOutputAreaDiv = document.createElement('div');
const fakeOutputArea = new OutputArea(fakeOutputAreaDiv);
fakeOutputArea.add(['output_info', 'console_output'],
Strings.CONSOLE_OUTPUT_LABEL + ':');
fakeOutputArea.addConsole(consoleMsg);
fakeOutputArea.addLabStatus(true);
expect(outputDiv).to.have.html(fakeOutputAreaDiv.innerHTML);
});
});
});
});
}); | the_stack |
import * as http from "http";
import { Counter, ParsedServerInput } from "tsrpc-base-client";
import { ApiReturn, BaseServiceType, ServiceProto, TsrpcError, TsrpcErrorType } from 'tsrpc-proto';
import { HttpUtil } from '../../models/HttpUtil';
import { TSRPC_VERSION } from "../../models/version";
import { BaseServer, BaseServerOptions, defaultBaseServerOptions, ServerStatus } from '../base/BaseServer';
import { ApiCallHttp } from './ApiCallHttp';
import { HttpConnection } from './HttpConnection';
import { MsgCallHttp } from "./MsgCallHttp";
/**
* TSRPC Server, based on HTTP connection.
* @typeParam ServiceType - `ServiceType` from generated `proto.ts`
*/
export class HttpServer<ServiceType extends BaseServiceType = any> extends BaseServer<ServiceType>{
readonly ApiCallClass = ApiCallHttp;
readonly MsgCallClass = MsgCallHttp;
readonly options!: HttpServerOptions<ServiceType>;
constructor(proto: ServiceProto<ServiceType>, options?: Partial<HttpServerOptions<ServiceType>>) {
super(proto, {
...defaultHttpServerOptions,
...options
});
// 确保 jsonHostPath 以 / 开头和结尾
this.options.jsonHostPath = this.options.jsonHostPath ?
(this.options.jsonHostPath.startsWith('/') ? '' : '/') + this.options.jsonHostPath + (this.options.jsonHostPath.endsWith('/') ? '' : '/')
: '/';
}
/** Native `http.Server` of NodeJS */
httpServer?: http.Server;
/**
* {@inheritDoc BaseServer.start}
*/
start(): Promise<void> {
if (this.httpServer) {
throw new Error('Server already started');
}
return new Promise(rs => {
this._status = ServerStatus.Opening;
this.logger.log(`Starting HTTP server ...`);
this.httpServer = http.createServer((httpReq, httpRes) => {
if (this.status !== ServerStatus.Opened) {
httpRes.statusCode = 503;
httpRes.end();
return;
}
let ip = HttpUtil.getClientIp(httpReq);
httpRes.statusCode = 200;
httpRes.setHeader('X-Powered-By', `TSRPC ${TSRPC_VERSION}`);
if (this.options.cors) {
httpRes.setHeader('Access-Control-Allow-Origin', this.options.cors);
httpRes.setHeader('Access-Control-Allow-Headers', 'Content-Type,*');
if (httpReq.method === 'OPTIONS') {
httpRes.writeHead(200);
httpRes.end();
return;
}
};
let chunks: Buffer[] = [];
httpReq.on('data', data => {
chunks.push(data);
});
let conn: HttpConnection<ServiceType> | undefined;
httpReq.on('end', async () => {
let isJSON = this.options.jsonEnabled && httpReq.headers["content-type"]?.toLowerCase() === 'application/json'
&& httpReq.method === 'POST' && httpReq.url?.startsWith(this.options.jsonHostPath);
conn = new HttpConnection({
server: this,
id: '' + this._connIdCounter.getNext(),
ip: ip,
httpReq: httpReq,
httpRes: httpRes,
isJSON: isJSON
});
await this.flows.postConnectFlow.exec(conn, conn.logger);
let buf = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
if (isJSON) {
this._onRecvJSON(conn, chunks.toString())
}
else {
this._onRecvBuffer(conn, buf);
}
});
// 处理连接异常关闭的情况
httpRes.on('close', async () => {
// 客户端Abort
if (httpReq.aborted) {
if (conn) {
if (conn.call) {
conn.call.logger.log('[ReqAborted]');
}
else {
conn.logger.log('[ReqAborted]');
}
}
else {
this.logger.log('[ReqAborted]', {
url: httpReq.url,
method: httpReq.method,
ip: ip,
chunksLength: chunks.length,
chunksSize: chunks.sum(v => v.byteLength),
reqComplete: httpReq.complete,
headers: httpReq.rawHeaders
});
}
}
// 非Abort,异常中断:直到连接关闭,Client也未end(Conn未生成)
else if (!conn) {
this.logger.warn('Socket closed before request end', {
url: httpReq.url,
method: httpReq.method,
ip: ip,
chunksLength: chunks.length,
chunksSize: chunks.sum(v => v.byteLength),
reqComplete: httpReq.complete,
headers: httpReq.rawHeaders
});
}
// 有Conn,但连接非正常end:直到连接关闭,也未调用过 httpRes.end 方法
else if (!httpRes.writableEnded) {
(conn.call?.logger || conn.logger).warn('Socket closed without response')
}
// Post Flow
if (conn) {
await this.flows.postDisconnectFlow.exec({ conn: conn }, conn.logger)
}
});
});
if (this.options.socketTimeout) {
this.httpServer.timeout = this.options.socketTimeout;
}
if (this.options.keepAliveTimeout) {
this.httpServer.keepAliveTimeout = this.options.keepAliveTimeout;
}
this.httpServer.listen(this.options.port, () => {
this._status = ServerStatus.Opened;
this.logger.log(`Server started at ${this.options.port}.`);
rs();
})
});
}
protected async _onRecvJSON(conn: HttpConnection<ServiceType>, jsonStr: string) {
// 1. 根据 URL 判断 service
let serviceName = conn.httpReq.url!.substr(this.options.jsonHostPath.length);
let service = this.serviceMap.apiName2Service[serviceName] ?? this.serviceMap.msgName2Service[serviceName];
if (!service) {
conn.httpRes.statusCode = 404;
this._returnJSON(conn, {
isSucc: false,
err: {
message: 'Service Not Found: ' + serviceName,
type: TsrpcErrorType.ServerError,
code: 'URL_ERR'
}
});
return;
}
// 2. 解析 JSON 字符串
let req: any;
try {
req = JSON.parse(jsonStr);
}
catch (e: any) {
conn.logger.error(`Parse JSON Error: ${e.message}, jsonStr=` + JSON.stringify(jsonStr));
conn.httpRes.statusCode = 500;
this._returnJSON(conn, {
isSucc: false,
err: {
message: e.message,
type: TsrpcErrorType.ServerError,
code: 'JSON_ERR'
}
});
return;
}
// 3. Prune
if (this.options.jsonPrune) {
let opPrune = this.tsbuffer.prune(req, service.type === 'api' ? service.reqSchemaId : service.msgSchemaId);
if (!opPrune.isSucc) {
conn.httpRes.statusCode = 400;
this._returnJSON(conn, {
isSucc: false,
err: {
message: opPrune.errMsg,
type: TsrpcErrorType.ServerError,
code: 'REQ_VALIDATE_ERR'
}
})
return;
}
req = opPrune.pruneOutput;
}
// 4. MakeCall
let call = this._makeCall(conn, service.type === 'api' ? {
type: 'api',
service: service,
req: req
} : {
type: 'msg',
service: service,
msg: req
});
// 5. onApi / onMsg
if (call.type === 'api') {
++this._pendingApiCallNum;
await this._onApiCall(call);
if (--this._pendingApiCallNum === 0) {
this._gracefulStop?.rs();
}
}
else {
await this._onMsgCall(call);
}
}
protected _returnJSON(conn: HttpConnection<ServiceType>, ret: ApiReturn<any>) {
conn.httpRes.end(JSON.stringify(ret.isSucc ? ret : {
isSucc: false,
err: ret instanceof TsrpcError ? { ...ret.err } : ret.err
}))
}
/**
* {@inheritDoc BaseServer.stop}
*/
async stop(): Promise<void> {
if (!this.httpServer) {
return;
}
this.logger.log('Stopping server...');
return new Promise<void>((rs) => {
this._status = ServerStatus.Closing;
// 立即close,不再接受新请求
// 等所有连接都断开后rs
this.httpServer?.close(err => {
this._status = ServerStatus.Closed;
this.httpServer = undefined;
if (err) {
this.logger.error(err);
}
this.logger.log('Server stopped');
rs();
});
})
}
// HTTP Server 一个conn只有一个call,对应关联之
protected _makeCall(conn: HttpConnection<ServiceType>, input: ParsedServerInput): ApiCallHttp | MsgCallHttp {
let call = super._makeCall(conn, input) as ApiCallHttp | MsgCallHttp;
conn.call = call;
return call;
}
}
export interface HttpServerOptions<ServiceType extends BaseServiceType> extends BaseServerOptions<ServiceType> {
/** Which port the HTTP server listen to */
port: number,
/**
* Passed to the `timeout` property to the native `http.Server` of NodeJS, in milliseconds.
* `0` and `undefined` will disable the socket timeout behavior.
* NOTICE: this `socketTimeout` be `undefined` only means disabling of the socket timeout, the `apiTimeout` is still working.
* `socketTimeout` should always greater than `apiTimeout`.
* @defaultValue `undefined`
* @see {@link https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_server_timeout}
*/
socketTimeout?: number,
/**
* Passed to the `keepAliveTimeout` property to the native `http.Server` of NodeJS, in milliseconds.
* It means keep-alive timeout of HTTP socket connection.
* @defaultValue 5000 (from NodeJS)
* @see {@link https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_server_keepalivetimeout}
*/
keepAliveTimeout?: number,
/**
* Response header value of `Access-Control-Allow-Origin`.
* If this has any value, it would also set `Access-Control-Allow-Headers` as `*`.
* `undefined` means no CORS header.
* @defaultValue `*`
*/
cors?: string,
/**
* Whether to enable JSON compatible mode.
* When it is true, it can be compatible with typical HTTP JSON request (like RESTful API).
*
* @remarks
* The JSON request methods are:
*
* 1. Add `Content-type: application/json` to request header.
* 2. HTTP request is: `POST /{jsonUrlPath}/{apiName}`.
* 3. POST body is JSON string.
* 4. The response body is JSON string also.
*
* NOTICE: Buffer type are not supported due to JSON not support them.
* For security and efficient reason, we strongly recommend you use binary encoded transportation.
*
* @defaultValue `false`
*/
jsonEnabled: boolean,
/**
* Actual URL path is `${jsonHostPath}/${apiName}`.
* For example, if `jsonHostPath` is `'/api'`, then you can send `POST /api/a/b/c/Test` to call API `a/b/c/Test`.
* @defaultValue `'/'`
*/
jsonHostPath: string,
/**
* Whether to automatically delete excess properties that not defined in the protocol.
* It would affect API request and response.
* For security reason, it is strongly recommend you to set to `true`.
* @defaultValue `true`
* @internal
*/
jsonPrune: boolean
}
export const defaultHttpServerOptions: HttpServerOptions<any> = {
...defaultBaseServerOptions,
port: 3000,
cors: '*',
jsonEnabled: false,
jsonHostPath: '/',
jsonPrune: true
// TODO: keep-alive time (to SLB)
}
// TODO JSON | the_stack |
* Defines the portion of the cell which is to be used as a connectable
* region. Default is 0.3. Possible values are 0 < x <= 1.
*/
export const DEFAULT_HOTSPOT = 0.3;
/**
* Defines the minimum size in pixels of the portion of the cell which is
* to be used as a connectable region. Default is 8.
*/
export const MIN_HOTSPOT_SIZE = 8;
/**
* Defines the maximum size in pixels of the portion of the cell which is
* to be used as a connectable region. Use 0 for no maximum. Default is 0.
*/
export const MAX_HOTSPOT_SIZE = 0;
/**
* Defines the exact rendering hint.
*
* Defines the faster rendering hint.
*
* Defines the fastest rendering hint.
*/
export const enum RENDERING_HINT {
EXACT = 'exact',
FASTER = 'faster',
FASTEST = 'fastest',
};
/**
* - DIALECT.SVG: Defines the SVG display dialect name.
*
* - DIALECT.MIXEDHTML: Defines the mixed HTML display dialect name.
*
* - DIALECT.PREFERHTML: Defines the preferred HTML display dialect name.
*
* - DIALECT.STRICTHTML: Defines the strict HTML display dialect.
*/
export const enum DIALECT {
SVG = 'svg',
MIXEDHTML = 'mixedHtml',
PREFERHTML = 'preferHtml',
STRICTHTML = 'strictHtml',
};
/**
* Defines the SVG namespace.
*/
export const NS_SVG = 'http://www.w3.org/2000/svg';
/**
* Defines the XLink namespace.
*/
export const NS_XLINK = 'http://www.w3.org/1999/xlink';
/**
* Defines the color to be used to draw shadows in shapes and windows.
* Default is gray.
*/
export const SHADOWCOLOR = 'gray';
/**
* Specifies the x-offset of the shadow. Default is 2.
*/
export const SHADOW_OFFSET_X = 2;
/**
* Specifies the y-offset of the shadow. Default is 3.
*/
export const SHADOW_OFFSET_Y = 3;
/**
* Defines the opacity for shadows. Default is 1.
*/
export const SHADOW_OPACITY = 1;
export const enum NODETYPE {
ELEMENT = 1,
ATTRIBUTE = 2,
TEXT = 3,
CDATA = 4,
ENTITY_REFERENCE = 5,
ENTITY = 6,
PROCESSING_INSTRUCTION = 7,
COMMENT = 8,
DOCUMENT = 9,
DOCUMENTTYPE = 10,
DOCUMENT_FRAGMENT = 11,
NOTATION = 12,
}
/**
* Defines the vertical offset for the tooltip.
* Default is 16.
*/
export const TOOLTIP_VERTICAL_OFFSET = 16;
/**
* Specifies the default valid color. Default is #0000FF.
*/
export const DEFAULT_VALID_COLOR = '#00FF00';
/**
* Specifies the default invalid color. Default is #FF0000.
*/
export const DEFAULT_INVALID_COLOR = '#FF0000';
/**
* Specifies the default highlight color for shape outlines.
* Default is #0000FF. This is used in {@link EdgeHandler}.
*/
export const OUTLINE_HIGHLIGHT_COLOR = '#00FF00';
/**
* Defines the strokewidth to be used for shape outlines.
* Default is 5. This is used in {@link EdgeHandler}.
*/
export const OUTLINE_HIGHLIGHT_STROKEWIDTH = 5;
/**
* Defines the strokewidth to be used for the highlights.
* Default is 3.
*/
export const HIGHLIGHT_STROKEWIDTH = 3;
/**
* Size of the constraint highlight (in px). Default is 2.
*/
export const HIGHLIGHT_SIZE = 2;
/**
* Opacity (in %) used for the highlights (including outline).
* Default is 100.
*/
export const HIGHLIGHT_OPACITY = 100;
/**
* - CURSOR_MOVABLE_VERTEX: Defines the cursor for a movable vertex. Default is 'move'.
*
* - CURSOR_MOVABLE_EDGE: Defines the cursor for a movable edge. Default is 'move'.
*
* - CURSOR_LABEL_HANDLE: Defines the cursor for a movable label. Default is 'default'.
*
* - CURSOR_TERMINAL_HANDLE: Defines the cursor for a terminal handle. Default is 'pointer'.
*
* - CURSOR_BEND_HANDLE: Defines the cursor for a movable bend. Default is 'crosshair'.
*
* - CURSOR_VIRTUAL_BEND_HANDLE: Defines the cursor for a movable bend. Default is 'crosshair'.
*
* - CURSOR_CONNECT: Defines the cursor for a connectable state. Default is 'pointer'.
*/
export const enum CURSOR {
MOVABLE_VERTEX = 'move',
MOVABLE_EDGE = 'move',
LABEL_HANDLE = 'default',
TERMINAL_HANDLE = 'pointer',
BEND_HANDLE = 'crosshair',
VIRTUAL_BEND_HANDLE = 'crosshair',
CONNECT = 'pointer',
};
/**
* Defines the color to be used for the cell highlighting.
* Use 'none' for no color. Default is #00FF00.
*/
export const HIGHLIGHT_COLOR = '#00FF00';
/**
* Defines the color to be used for highlighting a target cell for a new
* or changed connection. Note that this may be either a source or
* target terminal in the graph. Use 'none' for no color.
* Default is #0000FF.
*/
export const CONNECT_TARGET_COLOR = '#0000FF';
/**
* Defines the color to be used for highlighting a invalid target cells
* for a new or changed connections. Note that this may be either a source
* or target terminal in the graph. Use 'none' for no color. Default is
* #FF0000.
*/
export const INVALID_CONNECT_TARGET_COLOR = '#FF0000';
/**
* Defines the color to be used for the highlighting target parent cells
* (for drag and drop). Use 'none' for no color. Default is #0000FF.
*/
export const DROP_TARGET_COLOR = '#0000FF';
/**
* Defines the color to be used for the coloring valid connection
* previews. Use 'none' for no color. Default is #FF0000.
*/
export const VALID_COLOR = '#00FF00';
/**
* Defines the color to be used for the coloring invalid connection
* previews. Use 'none' for no color. Default is #FF0000.
*/
export const INVALID_COLOR = '#FF0000';
/**
* Defines the color to be used for the selection border of edges. Use
* 'none' for no color. Default is #00FF00.
*/
export const EDGE_SELECTION_COLOR = '#00FF00';
/**
* Defines the color to be used for the selection border of vertices. Use
* 'none' for no color. Default is #00FF00.
*/
export const VERTEX_SELECTION_COLOR = '#00FF00';
/**
* Defines the strokewidth to be used for vertex selections.
* Default is 1.
*/
export const VERTEX_SELECTION_STROKEWIDTH = 1;
/**
* Defines the strokewidth to be used for edge selections.
* Default is 1.
*/
export const EDGE_SELECTION_STROKEWIDTH = 1;
/**
* Defines the dashed state to be used for the vertex selection
* border. Default is true.
*/
export const VERTEX_SELECTION_DASHED = true;
/**
* Defines the dashed state to be used for the edge selection
* border. Default is true.
*/
export const EDGE_SELECTION_DASHED = true;
/**
* Defines the color to be used for the guidelines in mxGraphHandler.
* Default is #FF0000.
*/
export const GUIDE_COLOR = '#FF0000';
/**
* Defines the strokewidth to be used for the guidelines in mxGraphHandler.
* Default is 1.
*/
export const GUIDE_STROKEWIDTH = 1;
/**
* Defines the color to be used for the outline rectangle
* border. Use 'none' for no color. Default is #0099FF.
*/
export const OUTLINE_COLOR = '#0099FF';
/**
* Defines the strokewidth to be used for the outline rectangle
* stroke width. Default is 3.
*/
export const OUTLINE_STROKEWIDTH = 3;
/**
* Defines the default size for handles. Default is 6.
*/
export const HANDLE_SIZE = 6;
/**
* Defines the default size for label handles. Default is 4.
*/
export const LABEL_HANDLE_SIZE = 4;
/**
* Defines the color to be used for the handle fill color. Use 'none' for
* no color. Default is #00FF00 (green).
*/
export const HANDLE_FILLCOLOR = '#00FF00';
/**
* Defines the color to be used for the handle stroke color. Use 'none' for
* no color. Default is black.
*/
export const HANDLE_STROKECOLOR = 'black';
/**
* Defines the color to be used for the label handle fill color. Use 'none'
* for no color. Default is yellow.
*/
export const LABEL_HANDLE_FILLCOLOR = 'yellow';
/**
* Defines the color to be used for the connect handle fill color. Use
* 'none' for no color. Default is #0000FF (blue).
*/
export const CONNECT_HANDLE_FILLCOLOR = '#0000FF';
/**
* Defines the color to be used for the locked handle fill color. Use
* 'none' for no color. Default is #FF0000 (red).
*/
export const LOCKED_HANDLE_FILLCOLOR = '#FF0000';
/**
* Defines the color to be used for the outline sizer fill color. Use
* 'none' for no color. Default is #00FFFF.
*/
export const OUTLINE_HANDLE_FILLCOLOR = '#00FFFF';
/**
* Defines the color to be used for the outline sizer stroke color. Use
* 'none' for no color. Default is #0033FF.
*/
export const OUTLINE_HANDLE_STROKECOLOR = '#0033FF';
/**
* Defines the default family for all fonts. Default is Arial,Helvetica.
*/
export const DEFAULT_FONTFAMILY = 'Arial,Helvetica';
/**
* Defines the default size (in px). Default is 11.
*/
export const DEFAULT_FONTSIZE = 11;
/**
* Defines the default value for the <STYLE_TEXT_DIRECTION> if no value is
* defined for it in the style. Default value is an empty string which means
* the default system setting is used and no direction is set.
*/
export const DEFAULT_TEXT_DIRECTION = '';
/**
* Defines the default line height for text labels. Default is 1.2.
*/
export const LINE_HEIGHT = 1.2;
/**
* Defines the CSS value for the word-wrap property. Default is "normal".
* Change this to "break-word" to allow long words to be able to be broken
* and wrap onto the next line.
*/
export const WORD_WRAP = 'normal';
/**
* Specifies if absolute line heights should be used (px) in CSS. Default
* is false. Set this to true for backwards compatibility.
*/
export const ABSOLUTE_LINE_HEIGHT = false;
/**
* Defines the default style for all fonts. Default is 0. This can be set
* to any combination of font styles as follows.
*
* ```javascript
* mxConstants.DEFAULT_FONTSTYLE = mxConstants.FONT_BOLD | mxConstants.FONT_ITALIC;
* ```
*/
export const DEFAULT_FONTSTYLE = 0;
/**
* Defines the default start size for swimlanes. Default is 40.
*/
export const DEFAULT_STARTSIZE = 40;
/**
* Defines the default size for all markers. Default is 6.
*/
export const DEFAULT_MARKERSIZE = 6;
/**
* Defines the default width and height for images used in the
* label shape. Default is 24.
*/
export const DEFAULT_IMAGESIZE = 24;
/**
* Defines the length of the horizontal segment of an Entity Relation.
* This can be overridden using <'segment'> style.
* Default is 30.
*/
export const ENTITY_SEGMENT = 30;
/**
* Defines the rounding factor for rounded rectangles in percent between
* 0 and 1. Values should be smaller than 0.5. Default is 0.15.
*/
export const RECTANGLE_ROUNDING_FACTOR = 0.15;
/**
* Defines the size of the arcs for rounded edges. Default is 20.
*/
export const LINE_ARCSIZE = 20;
/**
* Defines the spacing between the arrow shape and its terminals. Default is 0.
*/
export const ARROW_SPACING = 0;
/**
* Defines the width of the arrow shape. Default is 30.
*/
export const ARROW_WIDTH = 30;
/**
* Defines the size of the arrowhead in the arrow shape. Default is 30.
*/
export const ARROW_SIZE = 30;
/**
* Defines the rectangle for the A4 portrait page format. The dimensions
* of this page format are 826x1169 pixels.
*/
export const PAGE_FORMAT_A4_PORTRAIT = [0, 0, 827, 1169];
/**
* Defines the rectangle for the A4 portrait page format. The dimensions
* of this page format are 826x1169 pixels.
*/
export const PAGE_FORMAT_A4_LANDSCAPE = [0, 0, 1169, 827];
/**
* Defines the rectangle for the Letter portrait page format. The
* dimensions of this page format are 850x1100 pixels.
*/
export const PAGE_FORMAT_LETTER_PORTRAIT = [0, 0, 850, 1100];
/**
* Defines the rectangle for the Letter portrait page format. The dimensions
* of this page format are 850x1100 pixels.
*/
export const PAGE_FORMAT_LETTER_LANDSCAPE = [0, 0, 1100, 850];
/**
* Defines the value for none. Default is "none".
*/
export const NONE = 'none';
/**
* - FONT_BOLD: Constant for bold fonts. Default is 1.
*
* - FONT_ITALIC: Constant for italic fonts. Default is 2.
*
* - FONT_UNDERLINE: Constant for underlined fonts. Default is 4.
*
* - FONT_STRIKETHROUGH: Constant for strikthrough fonts. Default is 8.
*/
export const enum FONT {
BOLD = 1,
ITALIC = 2,
UNDERLINE = 4,
STRIKETHROUGH = 8,
};
/**
* - ARROW_CLASSIC: Constant for classic arrow markers.
*
* - ARROW_CLASSIC_THIN: Constant for thin classic arrow markers.
*
* - ARROW_BLOCK: Constant for block arrow markers.
*
* - ARROW_BLOCK_THIN: Constant for thin block arrow markers.
*
* - ARROW_OPEN: Constant for open arrow markers.
*
* - ARROW_OPEN_THIN: Constant for thin open arrow markers.
*
* - ARROW_OVAL: Constant for oval arrow markers.
*
* - ARROW_DIAMOND: Constant for diamond arrow markers.
*
* - ARROW_DIAMOND_THIN: Constant for thin diamond arrow markers.
*/
export const enum ARROW {
CLASSIC = 'classic',
CLASSIC_THIN = 'classicThin',
BLOCK = 'block',
BLOCK_THIN = 'blockThin',
OPEN = 'open',
OPEN_THIN = 'openThin',
OVAL = 'oval',
DIAMOND = 'diamond',
DIAMOND_THIN = 'diamondThin',
};
/**
* - ALIGN_LEFT: Constant for left horizontal alignment. Default is left.
*
* - ALIGN_CENTER: Constant for center horizontal alignment. Default is center.
*
* - ALIGN_RIGHT: Constant for right horizontal alignment. Default is right.
*
* - ALIGN_TOP: Constant for top vertical alignment. Default is top.
*
* - ALIGN_MIDDLE: Constant for middle vertical alignment. Default is middle.
*
* - ALIGN_BOTTOM: Constant for bottom vertical alignment. Default is bottom.
*/
export const enum ALIGN {
LEFT = 'left',
CENTER = 'center',
RIGHT = 'right',
TOP = 'top',
MIDDLE = 'middle',
BOTTOM = 'bottom',
};
export const enum DIRECTION {
NORTH = 'north',
SOUTH = 'south',
EAST = 'east',
WEST = 'west',
}
/**
* Constant for text direction default. Default is an empty string. Use
* this value to use the default text direction of the operating system.
*
* Constant for text direction automatic. Default is auto. Use this value
* to find the direction for a given text with {@link Text#getAutoDirection}.
*
* Constant for text direction left to right. Default is ltr. Use this
* value for left to right text direction.
*
* Constant for text direction right to left. Default is rtl. Use this
* value for right to left text direction.
*/
export const enum TEXT_DIRECTION {
DEFAULT = '',
AUTO = 'auto',
LTR = 'ltr',
RTL = 'rtl',
};
/**
* - DIRECTION_MASK_NONE: Constant for no direction.
*
* - DIRECTION_MASK_WEST: Bitwise mask for west direction.
*
* - DIRECTION_MASK_NORTH: Bitwise mask for north direction.
*
* - DIRECTION_MASK_SOUTH: Bitwise mask for south direction.
*
* - DIRECTION_MASK_EAST: Bitwise mask for east direction.
*
* - DIRECTION_MASK_ALL: Bitwise mask for all directions.
*/
export const DIRECTION_MASK = {
NONE: 0,
WEST: 1,
NORTH: 2,
SOUTH: 4,
EAST: 8,
ALL: 15,
};
/**
* Default is horizontal.
*/
export const enum ELBOW {
VERTICAL = 'vertical',
HORIZONTAL = 'horizontal',
};
/**
* Can be used as a string value for the STYLE_EDGE style.
*/
export const enum EDGESTYLE {
ELBOW = 'elbowEdgeStyle',
ENTITY_RELATION = 'entityRelationEdgeStyle',
LOOP = 'loopEdgeStyle',
SIDETOSIDE = 'sideToSideEdgeStyle',
TOPTOBOTTOM = 'topToBottomEdgeStyle',
ORTHOGONAL = 'orthogonalEdgeStyle',
SEGMENT = 'segmentEdgeStyle',
};
/**
* Can be used as a string value for the STYLE_PERIMETER style.
*/
export const enum PERIMETER {
ELLIPSE = 'ellipsePerimeter',
RECTANGLE = 'rectanglePerimeter',
RHOMBUS = 'rhombusPerimeter',
HEXAGON = 'hexagonPerimeter',
TRIANGLE = 'trianglePerimeter'
};
export const enum SHAPE {
/**
* Name under which {@link RectangleShape} is registered in {@link CellRenderer}.
* Default is rectangle.
*/
RECTANGLE = 'rectangle',
/**
* Name under which {@link Ellipse} is registered in {@link CellRenderer}.
* Default is ellipse.
*/
ELLIPSE = 'ellipse',
/**
* Name under which {@link DoubleEllipse} is registered in {@link CellRenderer}.
* Default is doubleEllipse.
*/
DOUBLE_ELLIPSE = 'doubleEllipse',
/**
* Name under which {@link Rhombus} is registered in {@link CellRenderer}.
* Default is rhombus.
*/
RHOMBUS = 'rhombus',
/**
* Name under which {@link Line} is registered in {@link CellRenderer}.
* Default is line.
*/
LINE = 'line',
/**
* Name under which {@link ImageShape} is registered in {@link CellRenderer}.
* Default is image.
*/
IMAGE = 'image',
/**
* Name under which {@link Arrow} is registered in {@link CellRenderer}.
* Default is arrow.
*/
ARROW = 'arrow',
/**
* Name under which {@link ArrowConnector} is registered in {@link CellRenderer}.
* Default is arrowConnector.
*/
ARROW_CONNECTOR = 'arrowConnector',
/**
* Name under which {@link Label} is registered in {@link CellRenderer}.
* Default is label.
*/
LABEL = 'label',
/**
* Name under which {@link Cylinder} is registered in {@link CellRenderer}.
* Default is cylinder.
*/
CYLINDER = 'cylinder',
/**
* Name under which {@link Swimlane} is registered in {@link CellRenderer}.
* Default is swimlane.
*/
SWIMLANE = 'swimlane',
/**
* Name under which {@link Connector} is registered in {@link CellRenderer}.
* Default is connector.
*/
CONNECTOR = 'connector',
/**
* Name under which {@link Actor} is registered in {@link CellRenderer}.
* Default is actor.
*/
ACTOR = 'actor',
/**
* Name under which {@link Cloud} is registered in {@link CellRenderer}.
* Default is cloud.
*/
CLOUD = 'cloud',
/**
* Name under which {@link Triangle} is registered in {@link CellRenderer}.
* Default is triangle.
*/
TRIANGLE = 'triangle',
/**
* Name under which {@link Hexagon} is registered in {@link CellRenderer}.
* Default is hexagon.
*/
HEXAGON = 'hexagon',
}; | the_stack |
import L2Object from "./L2Object";
import { Sex } from "../enums/Sex";
import { Race } from "../enums/Race";
import Vector from "../mmocore/Vector";
import L2ObjectCollection from "./L2ObjectCollection";
import L2Buff from "./L2Buff";
import { Console } from "console";
export default abstract class L2Creature extends L2Object {
private _hp!: number;
private _mp!: number;
private _maxHp!: number;
private _maxMp!: number;
private _isRunning!: boolean;
private _isSitting!: boolean;
private _isFishing!: boolean;
private _hpPercent!: number;
private _mpPercent!: number;
private _dx!: number;
private _dy!: number;
private _dz!: number;
private _pAtk!: number;
private _pAtkSpd!: number;
private _mAtk!: number;
private _mAtkSpd!: number;
private _isDead = false;
private _runSpeed!: number;
private _walkSpeed!: number;
private _speedMultiplier!: number;
private _atkSpdMultiplier!: number;
private _swimRunSpeed!: number;
private _swimWalkSpeed!: number;
private _flyRunSpeed!: number;
private _flyWalkSpeed!: number;
private _title!: string;
private _isInCombat!: boolean;
private _isNoble!: boolean;
private _isHero!: boolean;
private _isAttackable!: boolean;
private _isTargetable!: boolean;
private _target!: L2Object | null;
private _sex!: Sex;
private _recommHave!: number;
private _classId!: number;
private _className!: string;
private _baseClassId!: number;
private _baseClassName!: string;
private _race!: Race;
private _isMoving = false;
private _movingDistance: number = 0;
private _isReady = true;
private _karma!: number;
private _buffs: L2ObjectCollection<L2Buff> = new L2ObjectCollection();
public get Buffs(): L2ObjectCollection<L2Buff> {
return this._buffs;
}
public set Buffs(value: L2ObjectCollection<L2Buff>) {
this._buffs = value;
}
public get Race(): Race {
return this._race;
}
public set Race(value: Race) {
this._race = value;
}
public get BaseClassName(): string {
return this._baseClassName;
}
public set BaseClassName(value: string) {
this._baseClassName = value;
}
public get BaseClassId(): number {
return this._baseClassId;
}
public set BaseClassId(value: number) {
this._baseClassId = value;
}
public get ClassId(): number {
return this._classId;
}
public set ClassId(value: number) {
this._classId = value;
}
public get ClassName(): string {
return this._className;
}
public set ClassName(value: string) {
this._className = value;
}
public get IsReady(): boolean {
return this._isReady;
}
public set IsReady(value: boolean) {
this._isReady = value;
}
public get Sex(): Sex {
return this._sex;
}
public set Sex(value: Sex) {
this._sex = value;
}
public get Title(): string {
return this._title;
}
public set Title(value: string) {
this._title = value;
}
public get IsTargetable(): boolean {
return this._isTargetable;
}
public set IsTargetable(value: boolean) {
this._isTargetable = value;
}
public get Target(): L2Object | null {
return this._target;
}
public set Target(value: L2Object | null) {
this._target = value;
}
public get IsAttackable(): boolean {
return this._isAttackable;
}
public set IsAttackable(value: boolean) {
this._isAttackable = value;
}
public get FlyWalkSpeed(): number {
return this._flyWalkSpeed;
}
public set FlyWalkSpeed(value: number) {
this._flyWalkSpeed = value;
}
public get FlyRunSpeed(): number {
return this._flyRunSpeed;
}
public set FlyRunSpeed(value: number) {
this._flyRunSpeed = value;
}
public get SwimWalkSpeed(): number {
return this._swimWalkSpeed;
}
public set SwimWalkSpeed(value: number) {
this._swimWalkSpeed = value;
}
public get SwimRunSpeed(): number {
return this._swimRunSpeed;
}
public set SwimRunSpeed(value: number) {
this._swimRunSpeed = value;
}
public get Hp(): number {
return this._hp;
}
public set Hp(value: number) {
this._hp = value;
this._hpPercent = (100 * this._hp) / this._maxHp;
this._isDead = value === 0;
}
public get Mp(): number {
return this._mp;
}
public set Mp(value: number) {
this._mp = value;
this._mpPercent = (100 * this._mp) / this._maxMp;
}
public get MaxHp(): number {
return this._maxHp;
}
public set MaxHp(value: number) {
this._maxHp = value;
this._hpPercent = (100 * this._hp) / this._maxHp;
}
public get MaxMp(): number {
return this._maxMp;
}
public set MaxMp(value: number) {
this._maxMp = value;
this._mpPercent = (100 * this._mp) / this._maxMp;
}
public get IsRunning(): boolean {
return this._isRunning;
}
public set IsRunning(value: boolean) {
this._isRunning = value;
}
public get IsSitting(): boolean {
return this._isSitting;
}
public set IsSitting(value: boolean) {
this._isSitting = value;
}
public get IsFishing(): boolean {
return this._isFishing;
}
public set IsFishing(value: boolean) {
this._isFishing = value;
}
public get HpPercent(): number {
return this._hpPercent;
}
public set HpPercent(value: number) {
this._hpPercent = value;
}
public get MpPercent(): number {
return this._mpPercent;
}
public set MpPercent(value: number) {
this._mpPercent = value;
}
public get Dx(): number {
return this._dx;
}
public set Dx(value: number) {
this._dx = value;
}
public get Dy(): number {
return this._dy;
}
public set Dy(value: number) {
this._dy = value;
}
public get Dz(): number {
return this._dz;
}
public set Dz(value: number) {
this._dz = value;
}
public get IsDead(): boolean {
return this._isDead;
}
public set IsDead(value: boolean) {
this._isDead = value;
}
public get RunSpeed(): number {
return this._runSpeed;
}
public set RunSpeed(value: number) {
this._runSpeed = value;
}
public get WalkSpeed(): number {
return this._walkSpeed;
}
public set WalkSpeed(value: number) {
this._walkSpeed = value;
}
public get SpeedMultiplier(): number {
return this._speedMultiplier;
}
public set SpeedMultiplier(value: number) {
this._speedMultiplier = value;
}
public get AtkSpdMultiplier(): number {
return this._atkSpdMultiplier;
}
public set AtkSpdMultiplier(value: number) {
this._atkSpdMultiplier = value;
}
public get PAtk(): number {
return this._pAtk;
}
public set PAtk(value: number) {
this._pAtk = value;
}
public get PAtkSpd(): number {
return this._pAtkSpd;
}
public set PAtkSpd(value: number) {
this._pAtkSpd = value;
}
public get MAtk(): number {
return this._mAtk;
}
public set MAtk(value: number) {
this._mAtk = value;
}
public get MAtkSpd(): number {
return this._mAtkSpd;
}
public set MAtkSpd(value: number) {
this._mAtkSpd = value;
}
public get RecommHave(): number {
return this._recommHave;
}
public set RecommHave(value: number) {
this._recommHave = value;
}
public get Karma(): number {
return this._karma;
}
public set Karma(value: number) {
this._karma = value;
}
public get IsInCombat(): boolean {
return this._isInCombat;
}
public set IsInCombat(value: boolean) {
this._isInCombat = value;
}
public get IsNoble(): boolean {
return this._isNoble;
}
public set IsNoble(value: boolean) {
this._isNoble = value;
}
public get IsHero(): boolean {
return this._isHero;
}
public set IsHero(value: boolean) {
this._isHero = value;
}
public get IsMoving(): boolean {
return this._isMoving;
}
public set IsMoving(isMoving: boolean) {
const wasMoving = this._isMoving;
this._isMoving = isMoving;
if (!isMoving) {
this._movingDistance = 0;
}
if (isMoving !== wasMoving) {
this.fire(`${isMoving ? "Start" : "Stop"}Moving`, { creature: this });
}
}
/**
* @returns Distance length that was requested to move
*/
public get MovingDistance(): number {
return this._movingDistance;
}
public set MovingDistance(value: number) {
this._movingDistance = value;
}
public get CurrentSpeed(): number {
return this.IsRunning
? this.RunSpeed * (this.SpeedMultiplier > 0 ? this.SpeedMultiplier : 1)
: this.WalkSpeed * (this.SpeedMultiplier > 0 ? this.SpeedMultiplier : 1);
}
private _moveInterval!: ReturnType<typeof setInterval> | null;
public setMovingTo(
x: number,
y: number,
z: number,
dx: number,
dy: number,
dz: number,
heading?: number
): void {
if (this._moveInterval) {
clearInterval(this._moveInterval);
// Trigger event as we might changed direction
if (this.IsMoving) {
this.IsMoving = false;
}
}
this.Dx = dx;
this.Dy = dy;
this.Dz = dz;
this.X = x;
this.Y = y;
this.Z = z;
if (!heading) {
let angleTarget = Math.atan2(dy - y, dx - x) * (180 / Math.PI);
if (angleTarget < 0)
angleTarget = 360 + angleTarget;
this.Heading = Math.floor(angleTarget * 182.044444444);
} else {
this.Heading = heading;
}
this.IsMoving = true;
const movingVector: Vector = new Vector(dx - this.X, dy - this.Y);
this._movingDistance = movingVector.length();
let ticks = Math.ceil(this._movingDistance / (this.CurrentSpeed / 10));
movingVector.normalize();
// TODO: Improve this as it will drift for larger movements
this._moveInterval = setInterval(() => {
// Check if movement was not cancelled by the server
if (!this.IsMoving) {
if (this._moveInterval) clearInterval(this._moveInterval);
this._moveInterval = null;
return;
}
const dx = Math.floor(movingVector.X * (this.CurrentSpeed / 10));
const dy = Math.floor(movingVector.Y * (this.CurrentSpeed / 10));
this._movingDistance -= Math.sqrt(dx*dx + dy*dy);
this.X += dx;
this.Y += dy;
ticks--;
if (ticks <= 0) {
this.X = this.Dx;
this.Y = this.Dy;
this._movingDistance = 0;
this.IsMoving = false;
if (this._moveInterval) clearInterval(this._moveInterval);
this._moveInterval = null;
}
}, 100).unref();
}
private th!: ReturnType<typeof setTimeout> | null;
public set HiTime(value: number) {
this.IsReady = false;
if (this.th) {
clearTimeout(this.th);
this.th = null;
}
this.th = setTimeout(() => {
this.IsReady = true;
}, value).unref();
}
} | the_stack |
import { Mimetype } from './GuacCommon';
import { Tunnel } from './Tunnel';
import { OutputStream } from './OutputStream';
import { InputStream } from './InputStream';
import { Status } from './Status';
import { Display } from './Display';
import { AudioPlayer } from './AudioPlayer';
import { VideoPlayer } from './VideoPlayer';
import { VisibleLayer } from './VisibleLayer';
import { Mouse } from './Mouse';
import * as Guacamole from './Object';
export {};
export namespace Client {
export {};
export type State =
| 0 // IDLE
| 1 // CONNECTING
| 2 // WAITING
| 3 // CONNECTED
| 4 // DISCONNECTING
| 5; // DISCONNECTED
interface ExportLayerBase {
height: number;
width: number;
url?: string | undefined;
}
type ExportLayer =
| ExportLayerBase
| (ExportLayerBase & {
x: number;
y: number;
z: number;
alpha: number;
matrix: unknown;
parent: unknown;
});
export interface ExportedState {
currentState: State;
currentTimestamp: number;
layers: { [key: number]: ExportLayer };
}
}
/**
* Guacamole protocol client. Given a Guacamole.Tunnel,
* automatically handles incoming and outgoing Guacamole instructions via the
* provided tunnel, updating its display using one or more canvas elements.
*/
export class Client {
/**
* @param tunnel The tunnel to use to send and receive Guacamole instructions.
*/
constructor(tunnel: Tunnel);
/**
* Sends a disconnect instruction to the server and closes the tunnel.
*/
disconnect(): void;
/**
* @description
* Connects the underlying tunnel of this Guacamole.Client, passing the
* given arbitrary data to the tunnel during the connection process.
*
* @param data Arbitrary connection data to be sent to the underlying
* tunnel during the connection process.
* @throws {Guacamole.Status} If an error occurs during connection.
*/
connect(data?: any): void;
/**
* Opens a new argument value stream for writing, having the given
* parameter name and mimetype, requesting that the connection parameter
* with the given name be updated to the value described by the contents
* of the following stream. The instruction necessary to create this stream
* will automatically be sent.
*
* @param mimetype The mimetype of the data being sent.
* @param name The name of the connection parameter to attempt to update.
*/
createArgumentValueStream(mimetype: Mimetype, name: string): OutputStream;
/**
* Opens a new audio stream for writing, where audio data having the give
* mimetype will be sent along the returned stream. The instruction
* necessary to create this stream will automatically be sent.
*
* @param mimetype The mimetype of the audio data that will be sent along the returned stream.
*/
createAudioStream(mimetype: Mimetype): OutputStream;
/**
* Opens a new clipboard object for writing, having the given mimetype. The
* instruction necessary to create this stream will automatically be sent.
*
* @param mimetype The mimetype of the data being sent.
* @param name The name of the pipe.
*/
createClipboardStream(mimetype: Mimetype, name: string): OutputStream;
/**
* Opens a new file for writing, having the given index, mimetype and
* filename. The instruction necessary to create this stream will
* automatically be sent.
*
* @param mimetype The mimetype of the file being sent.
* @param filename The filename of the file being sent.
*/
createFileStream(mimetype: Mimetype, filename: string): OutputStream;
/**
* Creates a new output stream associated with the given object and having
* the given mimetype and name. The legality of a mimetype and name is
* dictated by the object itself. The instruction necessary to create this
* stream will automatically be sent.
*
* @param index The index of the object for which the output stream is being created.
* @param mimetype The mimetype of the data which will be sent to the output stream.
* @param name The defined name of an output stream within the given object.
* @returns An output stream which will write blobs to the named output stream of the given object.
*/
createObjectOutputStream(index: number, mimetype: Mimetype, name: string): OutputStream;
/**
* Allocates an available stream index and creates a new
* Guacamole.OutputStream using that index, associating the resulting
* stream with this Guacamole.Client. Note that this stream will not yet
* exist as far as the other end of the Guacamole connection is concerned.
* Streams exist within the Guacamole protocol only when referenced by an
* instruction which creates the stream, such as a "clipboard", "file", or
* "pipe" instruction.
*
* @returns A new Guacamole.OutputStream with a newly-allocated index and associated with this Guacamole.Client.
*/
createOutputStream(): OutputStream;
/**
* Opens a new pipe for writing, having the given name and mimetype. The
* instruction necessary to create this stream will automatically be sent.
*
* @param mimetype The mimetype of the data being sent.
* @param name The name of the pipe.
*/
createPipeStream(mimetype: Mimetype, name: string): OutputStream;
/**
* Marks a currently-open stream as complete. The other end of the
* Guacamole connection will be notified via an "end" instruction that the
* stream is closed, and the index will be made available for reuse in
* future streams.
*
* @param index The index of the stream to end.
*/
endStream(index: number): void;
/**
* Produces an opaque representation of Guacamole.Client state which can be
* later imported through a call to importState(). This object is
* effectively an independent, compressed snapshot of protocol and display
* state. Invoking this function implicitly flushes the display.
*
* @param callback
* Callback which should be invoked once the state object is ready. The
* state object will be passed to the callback as the sole parameter.
* This callback may be invoked immediately, or later as the display
*/
exportState(callback: (state: Client.ExportedState) => void): void;
/**
* Returns the underlying display of this Guacamole.Client. The display
* contains an Element which can be added to the DOM, causing the
* display to become visible.
*
* @return The underlying display of this Guacamole.Client.
*/
getDisplay(): Display;
/**
* Restores Guacamole.Client protocol and display state based on an opaque
* object from a prior call to exportState(). The Guacamole.Client instance
* used to export that state need not be the same as this instance.
*
* @param state An opaque representation of Guacamole.Client state from a prior call to exportState().
*
* @param callback The function to invoke when state has finished being imported. This
* may happen immediately, or later as images within the provided state object are loaded.
*/
importState(state: Client.ExportedState, callback?: () => void): void;
/**
* Requests read access to the input stream having the given name. If
* successful, a new input stream will be created.
*
* @param index The index of the object from which the input stream is being requested.
* @param name The name of the input stream to request.
*/
requestObjectInputStream(index: number, name: string): OutputStream;
/**
* Acknowledge receipt of a blob on the stream with the given index.
*
* @param index The index of the stream associated with the received blob.
* @param message A human-readable message describing the error or status.
* @param code The error code, if any, or 0 for success.
*/
sendAck(index: number, message: string, code: number): void;
/**
* Given the index of a file, writes a blob of data to that file.
*
* @param index The index of the file to write to.
* @param data Base64-encoded data to write to the file.
*/
sendBlob(index: number, data64: string): void;
/**
* Sends a key event having the given properties as if the user
* pressed or released a key.
*
* @param pressed Whether the key is pressed (1) or released (0).
* @param keysym The keysym of the key being pressed or released.
*/
sendKeyEvent(pressed: 0 | 1, keysym: number): void;
/**
* Sends a mouse event having the properties provided by the given mouse state.
*
* @param mouseState The state of the mouse to send in the mouse event.
*/
sendMouseState(state: Mouse.State): void;
/**
* Sends the current size of the screen.
*
* @param width The width of the screen.
* @param height The height of the screen.
*/
sendSize(width: number, height: number): void;
/**
* Fired whenever the state of this Guacamole.Client changes.
*
* @event
* @param state The new state of the client.
*/
onstatechange: null | ((state: Client.State) => void);
/**
* Fired when the remote client sends a name update.
*
* @event
* @param name The new name of this client.
*/
onname: null | ((name: string) => void);
/**
* Fired when an error is reported by the remote client, and the connection
* is being closed.
*
* @event
* @param status A status object which describes the error.
*/
onerror: null | ((status: Status) => void);
/**
* Fired when a audio stream is created. The stream provided to this event
* handler will contain its own event handlers for received data.
*
* @event
* @param audioStream The stream that will receive audio data from the server.
* @param mimetype The mimetype of the audio data which will be received.
* @return
* An object which implements the Guacamole.AudioPlayer interface and
* has been initialied to play the data in the provided stream, or null
* if the built-in audio players of the Guacamole client should be used.
*/
onaudio: null | ((audioStream: InputStream, mimetype: Mimetype) => AudioPlayer | null);
/**
* Fired when a video stream is created. The stream provided to this event
* handler will contain its own event handlers for received data.
*
* @event
* @param videoStream The stream that will receive video data from the server.
* @param layer
* The destination layer on which the received video data should be
* played. It is the responsibility of the Guacamole.VideoPlayer
* implementation to play the received data within this layer.
* @param mimetype
* The mimetype of the video data which will be received.
* @return
* An object which implements the Guacamole.VideoPlayer interface and
* has been initialied to play the data in the provided stream, or null
* if the built-in video players of the Guacamole client should be used.
*/
onvideo: null | ((videoStream: InputStream, layer: VisibleLayer, mimetype: Mimetype) => VideoPlayer | null);
/**
* Fired when the current value of a connection parameter is being exposed
* by the server.
*
* @event
* @param stream The stream that will receive connection parameter data from the server.
* @param mimetype The mimetype of the data which will be received.
* @param name The name of the connection parameter whose value is being exposed.
*/
onargv: null | ((parameterStream: InputStream, mimetype: Mimetype, name: string) => void);
/**
* Fired when the clipboard of the remote client is changing.
*
* @event
* @param stream The stream that will receive clipboard data from the server.
* @param mimetype The mimetype of the data which will be received.
*/
onclipboard: null | ((clipboardStream: InputStream, mimetype: Mimetype) => void);
/**
* Fired when a file stream is created. The stream provided to this event
* handler will contain its own event handlers for received data.
*
* @event
* @param stream The stream that will receive data from the server.
* @param mimetype The mimetype of the file received.
* @param filename The name of the file received.
*/
onfile: null | ((fileStream: InputStream, mimetype: Mimetype, name: string) => void);
/**
* Fired when a filesystem object is created. The object provided to this
* event handler will contain its own event handlers and functions for
* requesting and handling data.
*
* @event
* @param object The created filesystem object.
* @param name The name of the filesystem.
*/
onfilesystem: null | ((object: Guacamole.Object, name: string) => void);
/**
* Fired when a pipe stream is created. The stream provided to this event
* handler will contain its own event handlers for received data;
*
* @event
* @param stream The stream that will receive data from the server.
* @param mimetype The mimetype of the data which will be received.
* @param name The name of the pipe.
*/
onpipe: null | ((pipeStream: InputStream, mimetype: Mimetype, name: string) => void);
/**
* Fired whenever a sync instruction is received from the server, indicating
* that the server is finished processing any input from the client and
* has sent any results.
*
* @event
* @param timestamp The timestamp associated with the sync instruction.
*/
onsync: null | ((timestramp: number) => void);
} | the_stack |
// ====================================================
// GraphQL fragment: FeedGroup
// ====================================================
export interface FeedGroup_user {
__typename: "User";
id: number;
label: string;
name: string;
href: string | null;
}
export interface FeedGroup_owner_User {
__typename: "User";
id: number;
label: string;
name: string;
href: string | null;
}
export interface FeedGroup_owner_Group {
__typename: "Group";
id: number;
label: string;
href: string | null;
name: string;
}
export type FeedGroup_owner = FeedGroup_owner_User | FeedGroup_owner_Group;
export interface FeedGroup_item_Channel_owner_User {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_item_Channel_owner_Group {
__typename: "Group";
id: number;
name: string;
}
export type FeedGroup_item_Channel_owner = FeedGroup_item_Channel_owner_User | FeedGroup_item_Channel_owner_Group;
export interface FeedGroup_item_Channel {
__typename: "Channel";
id: number;
truncatedTitle: string;
href: string | null;
visibility: string;
label: string;
owner: FeedGroup_item_Channel_owner;
}
export interface FeedGroup_item_User {
__typename: "User";
id: number;
label: string;
name: string;
href: string | null;
}
export interface FeedGroup_item_Connectable {
__typename: "Connectable";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_item_Attachment {
__typename: "Attachment";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_item_Embed {
__typename: "Embed";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_item_Text {
__typename: "Text";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_item_Image {
__typename: "Image";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_item_Link {
__typename: "Link";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_item_Comment {
__typename: "Comment";
id: number;
body: string | null;
href: string | null;
}
export interface FeedGroup_item_Group {
__typename: "Group";
id: number;
label: string;
name: string;
href: string | null;
}
export type FeedGroup_item = FeedGroup_item_Channel | FeedGroup_item_User | FeedGroup_item_Connectable | FeedGroup_item_Attachment | FeedGroup_item_Embed | FeedGroup_item_Text | FeedGroup_item_Image | FeedGroup_item_Link | FeedGroup_item_Comment | FeedGroup_item_Group;
export interface FeedGroup_target_Channel_owner_User {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_target_Channel_owner_Group {
__typename: "Group";
id: number;
name: string;
}
export type FeedGroup_target_Channel_owner = FeedGroup_target_Channel_owner_User | FeedGroup_target_Channel_owner_Group;
export interface FeedGroup_target_Channel {
__typename: "Channel";
id: number;
truncatedTitle: string;
href: string | null;
visibility: string;
label: string;
owner: FeedGroup_target_Channel_owner;
}
export interface FeedGroup_target_User {
__typename: "User";
id: number;
label: string;
name: string;
href: string | null;
}
export interface FeedGroup_target_Connectable {
__typename: "Connectable";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_target_Attachment {
__typename: "Attachment";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_target_Embed {
__typename: "Embed";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_target_Text {
__typename: "Text";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_target_Image {
__typename: "Image";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_target_Link {
__typename: "Link";
id: number;
label: string;
href: string | null;
}
export interface FeedGroup_target_Comment {
__typename: "Comment";
id: number;
body: string | null;
href: string | null;
}
export interface FeedGroup_target_Group {
__typename: "Group";
id: number;
label: string;
name: string;
href: string | null;
}
export type FeedGroup_target = FeedGroup_target_Channel | FeedGroup_target_User | FeedGroup_target_Connectable | FeedGroup_target_Attachment | FeedGroup_target_Embed | FeedGroup_target_Text | FeedGroup_target_Image | FeedGroup_target_Link | FeedGroup_target_Comment | FeedGroup_target_Group;
export interface FeedGroup_objects_Comment {
__typename: "Comment";
}
export interface FeedGroup_objects_Attachment_counts {
__typename: "BlockCounts";
comments: number | null;
}
export interface FeedGroup_objects_Attachment_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Attachment_connection_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Attachment_connection {
__typename: "Connection";
created_at: string | null;
user: FeedGroup_objects_Attachment_connection_user | null;
}
export interface FeedGroup_objects_Attachment_source {
__typename: "ConnectableSource";
url: string | null;
}
export interface FeedGroup_objects_Attachment {
__typename: "Attachment";
href: string | null;
counts: FeedGroup_objects_Attachment_counts | null;
id: number;
title: string;
src: string | null;
src_1x: string | null;
src_2x: string | null;
src_3x: string | null;
file_extension: string | null;
updated_at: string | null;
user: FeedGroup_objects_Attachment_user | null;
/**
* Returns the outer channel if we are inside of one
*/
connection: FeedGroup_objects_Attachment_connection | null;
source: FeedGroup_objects_Attachment_source | null;
}
export interface FeedGroup_objects_Channel_counts {
__typename: "ChannelCounts";
contents: number | null;
}
export interface FeedGroup_objects_Channel_owner_Group {
__typename: "Group";
id: number;
name: string;
visibility: string;
}
export interface FeedGroup_objects_Channel_owner_User {
__typename: "User";
id: number;
name: string;
}
export type FeedGroup_objects_Channel_owner = FeedGroup_objects_Channel_owner_Group | FeedGroup_objects_Channel_owner_User;
export interface FeedGroup_objects_Channel_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Channel_connection_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Channel_connection {
__typename: "Connection";
created_at: string | null;
user: FeedGroup_objects_Channel_connection_user | null;
}
export interface FeedGroup_objects_Channel_source {
__typename: "ConnectableSource";
url: string | null;
}
export interface FeedGroup_objects_Channel {
__typename: "Channel";
href: string | null;
id: number;
truncatedTitle: string;
visibility: string;
updated_at: string | null;
counts: FeedGroup_objects_Channel_counts | null;
owner: FeedGroup_objects_Channel_owner;
label: string;
title: string;
user: FeedGroup_objects_Channel_user | null;
/**
* Returns the outer channel if we are inside of one
*/
connection: FeedGroup_objects_Channel_connection | null;
source: FeedGroup_objects_Channel_source | null;
}
export interface FeedGroup_objects_Embed_counts {
__typename: "BlockCounts";
comments: number | null;
}
export interface FeedGroup_objects_Embed_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Embed_connection_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Embed_connection {
__typename: "Connection";
created_at: string | null;
user: FeedGroup_objects_Embed_connection_user | null;
}
export interface FeedGroup_objects_Embed_source {
__typename: "ConnectableSource";
url: string | null;
}
export interface FeedGroup_objects_Embed {
__typename: "Embed";
href: string | null;
counts: FeedGroup_objects_Embed_counts | null;
id: number;
title: string;
src: string | null;
src_1x: string | null;
src_2x: string | null;
src_3x: string | null;
updated_at: string | null;
user: FeedGroup_objects_Embed_user | null;
/**
* Returns the outer channel if we are inside of one
*/
connection: FeedGroup_objects_Embed_connection | null;
source: FeedGroup_objects_Embed_source | null;
}
export interface FeedGroup_objects_Image_counts {
__typename: "BlockCounts";
comments: number | null;
}
export interface FeedGroup_objects_Image_original_dimensions {
__typename: "Dimensions";
width: number | null;
height: number | null;
}
export interface FeedGroup_objects_Image_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Image_connection_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Image_connection {
__typename: "Connection";
created_at: string | null;
user: FeedGroup_objects_Image_connection_user | null;
}
export interface FeedGroup_objects_Image_source {
__typename: "ConnectableSource";
url: string | null;
}
export interface FeedGroup_objects_Image {
__typename: "Image";
href: string | null;
counts: FeedGroup_objects_Image_counts | null;
id: number;
title: string;
src: string | null;
src_1x: string | null;
src_2x: string | null;
src_3x: string | null;
original_dimensions: FeedGroup_objects_Image_original_dimensions | null;
updated_at: string | null;
user: FeedGroup_objects_Image_user | null;
/**
* Returns the outer channel if we are inside of one
*/
connection: FeedGroup_objects_Image_connection | null;
source: FeedGroup_objects_Image_source | null;
}
export interface FeedGroup_objects_Link_counts {
__typename: "BlockCounts";
comments: number | null;
}
export interface FeedGroup_objects_Link_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Link_connection_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Link_connection {
__typename: "Connection";
created_at: string | null;
user: FeedGroup_objects_Link_connection_user | null;
}
export interface FeedGroup_objects_Link_source {
__typename: "ConnectableSource";
url: string | null;
}
export interface FeedGroup_objects_Link {
__typename: "Link";
href: string | null;
counts: FeedGroup_objects_Link_counts | null;
title: string;
src: string | null;
src_1x: string | null;
src_2x: string | null;
src_3x: string | null;
external_url: string | null;
updated_at: string | null;
user: FeedGroup_objects_Link_user | null;
/**
* Returns the outer channel if we are inside of one
*/
connection: FeedGroup_objects_Link_connection | null;
id: number;
source: FeedGroup_objects_Link_source | null;
}
export interface FeedGroup_objects_Text_counts {
__typename: "BlockCounts";
comments: number | null;
}
export interface FeedGroup_objects_Text_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Text_connection_user {
__typename: "User";
id: number;
name: string;
}
export interface FeedGroup_objects_Text_connection {
__typename: "Connection";
created_at: string | null;
user: FeedGroup_objects_Text_connection_user | null;
}
export interface FeedGroup_objects_Text_source {
__typename: "ConnectableSource";
url: string | null;
}
export interface FeedGroup_objects_Text {
__typename: "Text";
href: string | null;
counts: FeedGroup_objects_Text_counts | null;
id: number;
title: string;
content: string;
updated_at: string | null;
user: FeedGroup_objects_Text_user | null;
/**
* Returns the outer channel if we are inside of one
*/
connection: FeedGroup_objects_Text_connection | null;
source: FeedGroup_objects_Text_source | null;
}
export interface FeedGroup_objects_Group {
__typename: "Group";
id: number;
name: string;
href: string | null;
visibility: string;
label: string;
initials: string;
avatar: string | null;
}
export interface FeedGroup_objects_User {
__typename: "User";
id: number;
name: string;
href: string | null;
label: string;
initials: string;
avatar: string | null;
}
export type FeedGroup_objects = FeedGroup_objects_Comment | FeedGroup_objects_Attachment | FeedGroup_objects_Channel | FeedGroup_objects_Embed | FeedGroup_objects_Image | FeedGroup_objects_Link | FeedGroup_objects_Text | FeedGroup_objects_Group | FeedGroup_objects_User;
export interface FeedGroup {
__typename: "DeedGroup";
id: string;
key: string;
length: number;
user: FeedGroup_user | null;
owner: FeedGroup_owner;
action: string;
item: FeedGroup_item | null;
item_phrase: string;
connector: string | null;
target: FeedGroup_target | null;
target_phrase: string;
created_at: string | null;
is_private: boolean;
objects: FeedGroup_objects[] | null;
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages a Policy Assignment to a Resource.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleVirtualNetwork = azure.network.getVirtualNetwork({
* name: "production",
* resourceGroupName: "networking",
* });
* const exampleDefinition = new azure.policy.Definition("exampleDefinition", {
* policyType: "Custom",
* mode: "All",
* policyRule: ` {
* "if": {
* "not": {
* "field": "location",
* "equals": "westeurope"
* }
* },
* "then": {
* "effect": "Deny"
* }
* }
* `,
* });
* const exampleResourcePolicyAssignment = new azure.core.ResourcePolicyAssignment("exampleResourcePolicyAssignment", {
* resourceId: exampleVirtualNetwork.then(exampleVirtualNetwork => exampleVirtualNetwork.id),
* policyDefinitionId: exampleDefinition.id,
* });
* ```
*
* ## Import
*
* Resource Policy Assignments can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:core/resourcePolicyAssignment:ResourcePolicyAssignment example "{resource}/providers/Microsoft.Authorization/policyAssignments/assignment1"
* ```
*
* where `{resource}` is a Resource ID in the form `/subscriptions/00000000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Network/virtualNetworks/network1`.
*/
export class ResourcePolicyAssignment extends pulumi.CustomResource {
/**
* Get an existing ResourcePolicyAssignment resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ResourcePolicyAssignmentState, opts?: pulumi.CustomResourceOptions): ResourcePolicyAssignment {
return new ResourcePolicyAssignment(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:core/resourcePolicyAssignment:ResourcePolicyAssignment';
/**
* Returns true if the given object is an instance of ResourcePolicyAssignment. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is ResourcePolicyAssignment {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === ResourcePolicyAssignment.__pulumiType;
}
/**
* A description which should be used for this Policy Assignment.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* The Display Name for this Policy Assignment.
*/
public readonly displayName!: pulumi.Output<string | undefined>;
/**
* Specifies if this Policy should be enforced or not?
*/
public readonly enforce!: pulumi.Output<boolean | undefined>;
/**
* An `identity` block as defined below.
*/
public readonly identity!: pulumi.Output<outputs.core.ResourcePolicyAssignmentIdentity | undefined>;
/**
* The Azure Region where the Policy Assignment should exist. Changing this forces a new Policy Assignment to be created.
*/
public readonly location!: pulumi.Output<string>;
/**
* A JSON mapping of any Metadata for this Policy.
*/
public readonly metadata!: pulumi.Output<string>;
/**
* The name which should be used for this Policy Assignment. Changing this forces a new Resource Policy Assignment to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* One or more `nonComplianceMessage` blocks as defined below.
*/
public readonly nonComplianceMessages!: pulumi.Output<outputs.core.ResourcePolicyAssignmentNonComplianceMessage[] | undefined>;
/**
* Specifies a list of Resource Scopes (for example a Subscription, or a Resource Group) within this Management Group which are excluded from this Policy.
*/
public readonly notScopes!: pulumi.Output<string[] | undefined>;
/**
* A JSON mapping of any Parameters for this Policy. Changing this forces a new Management Group Policy Assignment to be created.
*/
public readonly parameters!: pulumi.Output<string | undefined>;
/**
* The ID of the Policy Definition or Policy Definition Set. Changing this forces a new Policy Assignment to be created.
*/
public readonly policyDefinitionId!: pulumi.Output<string>;
/**
* The ID of the Resource (or Resource Scope) where this should be applied. Changing this forces a new Resource Policy Assignment to be created.
*/
public readonly resourceId!: pulumi.Output<string>;
/**
* Create a ResourcePolicyAssignment resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: ResourcePolicyAssignmentArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: ResourcePolicyAssignmentArgs | ResourcePolicyAssignmentState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as ResourcePolicyAssignmentState | undefined;
inputs["description"] = state ? state.description : undefined;
inputs["displayName"] = state ? state.displayName : undefined;
inputs["enforce"] = state ? state.enforce : undefined;
inputs["identity"] = state ? state.identity : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["metadata"] = state ? state.metadata : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["nonComplianceMessages"] = state ? state.nonComplianceMessages : undefined;
inputs["notScopes"] = state ? state.notScopes : undefined;
inputs["parameters"] = state ? state.parameters : undefined;
inputs["policyDefinitionId"] = state ? state.policyDefinitionId : undefined;
inputs["resourceId"] = state ? state.resourceId : undefined;
} else {
const args = argsOrState as ResourcePolicyAssignmentArgs | undefined;
if ((!args || args.policyDefinitionId === undefined) && !opts.urn) {
throw new Error("Missing required property 'policyDefinitionId'");
}
if ((!args || args.resourceId === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceId'");
}
inputs["description"] = args ? args.description : undefined;
inputs["displayName"] = args ? args.displayName : undefined;
inputs["enforce"] = args ? args.enforce : undefined;
inputs["identity"] = args ? args.identity : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["metadata"] = args ? args.metadata : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["nonComplianceMessages"] = args ? args.nonComplianceMessages : undefined;
inputs["notScopes"] = args ? args.notScopes : undefined;
inputs["parameters"] = args ? args.parameters : undefined;
inputs["policyDefinitionId"] = args ? args.policyDefinitionId : undefined;
inputs["resourceId"] = args ? args.resourceId : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(ResourcePolicyAssignment.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering ResourcePolicyAssignment resources.
*/
export interface ResourcePolicyAssignmentState {
/**
* A description which should be used for this Policy Assignment.
*/
description?: pulumi.Input<string>;
/**
* The Display Name for this Policy Assignment.
*/
displayName?: pulumi.Input<string>;
/**
* Specifies if this Policy should be enforced or not?
*/
enforce?: pulumi.Input<boolean>;
/**
* An `identity` block as defined below.
*/
identity?: pulumi.Input<inputs.core.ResourcePolicyAssignmentIdentity>;
/**
* The Azure Region where the Policy Assignment should exist. Changing this forces a new Policy Assignment to be created.
*/
location?: pulumi.Input<string>;
/**
* A JSON mapping of any Metadata for this Policy.
*/
metadata?: pulumi.Input<string>;
/**
* The name which should be used for this Policy Assignment. Changing this forces a new Resource Policy Assignment to be created.
*/
name?: pulumi.Input<string>;
/**
* One or more `nonComplianceMessage` blocks as defined below.
*/
nonComplianceMessages?: pulumi.Input<pulumi.Input<inputs.core.ResourcePolicyAssignmentNonComplianceMessage>[]>;
/**
* Specifies a list of Resource Scopes (for example a Subscription, or a Resource Group) within this Management Group which are excluded from this Policy.
*/
notScopes?: pulumi.Input<pulumi.Input<string>[]>;
/**
* A JSON mapping of any Parameters for this Policy. Changing this forces a new Management Group Policy Assignment to be created.
*/
parameters?: pulumi.Input<string>;
/**
* The ID of the Policy Definition or Policy Definition Set. Changing this forces a new Policy Assignment to be created.
*/
policyDefinitionId?: pulumi.Input<string>;
/**
* The ID of the Resource (or Resource Scope) where this should be applied. Changing this forces a new Resource Policy Assignment to be created.
*/
resourceId?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a ResourcePolicyAssignment resource.
*/
export interface ResourcePolicyAssignmentArgs {
/**
* A description which should be used for this Policy Assignment.
*/
description?: pulumi.Input<string>;
/**
* The Display Name for this Policy Assignment.
*/
displayName?: pulumi.Input<string>;
/**
* Specifies if this Policy should be enforced or not?
*/
enforce?: pulumi.Input<boolean>;
/**
* An `identity` block as defined below.
*/
identity?: pulumi.Input<inputs.core.ResourcePolicyAssignmentIdentity>;
/**
* The Azure Region where the Policy Assignment should exist. Changing this forces a new Policy Assignment to be created.
*/
location?: pulumi.Input<string>;
/**
* A JSON mapping of any Metadata for this Policy.
*/
metadata?: pulumi.Input<string>;
/**
* The name which should be used for this Policy Assignment. Changing this forces a new Resource Policy Assignment to be created.
*/
name?: pulumi.Input<string>;
/**
* One or more `nonComplianceMessage` blocks as defined below.
*/
nonComplianceMessages?: pulumi.Input<pulumi.Input<inputs.core.ResourcePolicyAssignmentNonComplianceMessage>[]>;
/**
* Specifies a list of Resource Scopes (for example a Subscription, or a Resource Group) within this Management Group which are excluded from this Policy.
*/
notScopes?: pulumi.Input<pulumi.Input<string>[]>;
/**
* A JSON mapping of any Parameters for this Policy. Changing this forces a new Management Group Policy Assignment to be created.
*/
parameters?: pulumi.Input<string>;
/**
* The ID of the Policy Definition or Policy Definition Set. Changing this forces a new Policy Assignment to be created.
*/
policyDefinitionId: pulumi.Input<string>;
/**
* The ID of the Resource (or Resource Scope) where this should be applied. Changing this forces a new Resource Policy Assignment to be created.
*/
resourceId: pulumi.Input<string>;
} | the_stack |
import hyphenate from 'hyphenate';
import _ from 'lodash';
import {action, makeObservable, observable, runInAction} from 'mobx';
import {Dict, EmptyObjectPatch} from 'tslang';
import {parseRef, parseSearch} from './@utils';
import {HistorySnapshot, IHistory, getActiveHistoryEntry} from './history';
import {RouteBuilder} from './route-builder';
import {
GeneralParamDict,
NextRouteMatch,
RouteMatch,
RouteMatchEntry,
RouteMatchOptions,
RouteMatchShared,
RouteMatchSharedToParamDict,
RouteSource,
RouteSourceQuery,
} from './route-match';
import {RootRouteSchema, RouteSchema, RouteSchemaDict} from './schema';
export type SegmentMatcherCallback = (key: string) => string;
const DEFAULT_SEGMENT_MATCHER_CALLBACK: SegmentMatcherCallback = key =>
hyphenate(key, {lowerCase: true});
type RouteQuerySchemaType<TRouteSchema> = TRouteSchema extends {
$query: infer TQuerySchema;
}
? TQuerySchema
: {};
type FilterRouteMatchNonStringSegment<TRouteSchema, T> = TRouteSchema extends {
$match: infer TMatch;
}
? TMatch extends string
? never
: T
: never;
interface RouteSchemaChildrenSection<TRouteSchemaDict> {
$children: TRouteSchemaDict;
}
type NestedRouteSchemaDictType<TRouteSchema> =
TRouteSchema extends RouteSchemaChildrenSection<infer TNestedRouteSchemaDict>
? TNestedRouteSchemaDict
: {};
interface RouteSchemaExtensionSection<TRouteMatchExtension> {
$extension: TRouteMatchExtension;
}
interface RouteSchemaMetadataSection<TMetadata> {
$metadata: TMetadata;
}
type RouteMatchMetadataType<TRouteSchema, TUpperMetadata> =
TRouteSchema extends RouteSchemaMetadataSection<infer TMetadata>
? TMetadata & TUpperMetadata
: TUpperMetadata;
type RouteMatchExtensionType<TRouteSchema> =
TRouteSchema extends RouteSchemaExtensionSection<infer TRouteMatchExtension>
? TRouteMatchExtension
: {};
type RouteMatchSegmentType<
TRouteSchemaDict,
TSegmentKey extends string,
TQueryKey extends string,
TSpecificGroupName extends string | undefined,
TGroupName extends string,
TMetadata extends object,
> = {
[K in Extract<keyof TRouteSchemaDict, string>]: RouteMatchType<
TRouteSchemaDict[K],
TSegmentKey | FilterRouteMatchNonStringSegment<TRouteSchemaDict[K], K>,
| TQueryKey
| Extract<keyof RouteQuerySchemaType<TRouteSchemaDict[K]>, string>,
TSpecificGroupName,
TGroupName,
TMetadata
>;
};
type __RouteMatchType<
TRouteSchema,
TSegmentKey extends string,
TQueryKey extends string,
TSpecificGroupName extends string | undefined,
TGroupName extends string,
TParamDict extends Dict<string | undefined>,
TMetadata extends object,
> = RouteMatch<
TParamDict,
__NextRouteMatchType<
TRouteSchema,
TSegmentKey,
TQueryKey,
TSpecificGroupName,
TGroupName,
TParamDict
>,
TSpecificGroupName,
TGroupName,
RouteMatchMetadataType<TRouteSchema, TMetadata>
> &
RouteMatchSegmentType<
NestedRouteSchemaDictType<TRouteSchema>,
TSegmentKey,
TQueryKey,
TSpecificGroupName,
TGroupName,
RouteMatchMetadataType<TRouteSchema, TMetadata>
> &
RouteMatchExtensionType<TRouteSchema>;
export type RouteMatchType<
TRouteSchema,
TSegmentKey extends string,
TQueryKey extends string,
TSpecificGroupName extends string | undefined,
TGroupName extends string,
TMetadata extends object,
> = __RouteMatchType<
TRouteSchema,
TSegmentKey,
TQueryKey,
TSpecificGroupName,
TGroupName,
Record<TQueryKey, string | undefined> & Record<TSegmentKey, string>,
TMetadata
>;
type NextRouteMatchSegmentType<
TRouteSchemaDict,
TSegmentKey extends string,
TQueryKey extends string,
TSpecificGroupName extends string | undefined,
TGroupName extends string,
> = {
[K in Extract<keyof TRouteSchemaDict, string>]: NextRouteMatchType<
TRouteSchemaDict[K],
TSegmentKey | FilterRouteMatchNonStringSegment<TRouteSchemaDict[K], K>,
| TQueryKey
| Extract<keyof RouteQuerySchemaType<TRouteSchemaDict[K]>, string>,
TSpecificGroupName,
TGroupName
>;
};
type __NextRouteMatchType<
TRouteSchema,
TSegmentKey extends string,
TQueryKey extends string,
TSpecificGroupName extends string | undefined,
TGroupName extends string,
TParamDict extends Dict<string | undefined>,
> = NextRouteMatch<TParamDict, TSpecificGroupName, TGroupName> &
NextRouteMatchSegmentType<
NestedRouteSchemaDictType<TRouteSchema>,
TSegmentKey,
TQueryKey,
TSpecificGroupName,
TGroupName
>;
type NextRouteMatchType<
TRouteSchema,
TSegmentKey extends string,
TQueryKey extends string,
TSpecificGroupName extends string | undefined,
TGroupName extends string,
> = __NextRouteMatchType<
TRouteSchema,
TSegmentKey,
TQueryKey,
TSpecificGroupName,
TGroupName,
Record<TQueryKey, string | undefined> & Record<TSegmentKey, string>
>;
export type RootRouteMatchType<
TRouteSchema,
TSpecificGroupName extends string | undefined,
TGroupName extends string,
TMetadata extends object = {},
> = RouteMatchType<
TRouteSchema,
never,
Extract<keyof RouteQuerySchemaType<TRouteSchema>, string>,
TSpecificGroupName,
TGroupName,
TMetadata
>;
export type RouterOnLeave = (path: string) => void;
export type RouterOnNavigateComplete = () => void;
export interface RouterHistoryEntryData {
navigateCompleteListener?: RouterOnNavigateComplete;
}
export interface RouterOptions {
/**
* A function to perform default schema field name to segment string
* transformation.
*/
segmentMatcher?: SegmentMatcherCallback;
}
export interface RouterNavigateOptions {
/**
* The callback that will be called after a route completed (after all the hooks).
*/
onComplete?: RouterOnNavigateComplete;
}
export type RouterHistory = IHistory<unknown, RouterHistoryEntryData>;
type RouterHistorySnapshot = HistorySnapshot<unknown, RouterHistoryEntryData>;
interface InterUpdateData {
reversedLeavingMatches: RouteMatch[];
enteringAndUpdatingMatchSet: Set<RouteMatch>;
previousMatchSet: Set<RouteMatch>;
descendantUpdatingMatchSet: Set<RouteMatch>;
}
export class Router<TGroupName extends string = string> {
/** @internal */
readonly _history: RouterHistory;
/** @internal */
readonly _groupToRouteMatchMap = new Map<string | undefined, RouteMatch>();
/** @internal */
private _segmentMatcher: SegmentMatcherCallback;
/** @internal */
private _snapshot: RouterHistorySnapshot | undefined;
/** @internal */
private _nextSnapshot: RouterHistorySnapshot | undefined;
/** @internal */
private _source: RouteSource = observable({
groupToMatchToMatchEntryMapMap: new Map(),
queryMap: new Map(),
pathMap: new Map(),
});
/** @internal */
@observable
private _matchingSource: RouteSource = observable({
groupToMatchToMatchEntryMapMap: new Map(),
queryMap: new Map(),
pathMap: new Map(),
});
/** @internal */
private _changing = Promise.resolve();
/** @internal */
@observable
private _routing = 0;
/** @internal */
private _beforeLeaveHookCalledMatchSet = new Set<RouteMatch | undefined>();
constructor(history: RouterHistory, {segmentMatcher}: RouterOptions = {}) {
makeObservable(this);
this._history = history;
this._segmentMatcher = segmentMatcher || DEFAULT_SEGMENT_MATCHER_CALLBACK;
history.listen(this._onHistoryChange);
}
get $routing(): boolean {
return this._routing > 0;
}
get $current(): RouteBuilder<TGroupName> {
return new RouteBuilder(this, 'current');
}
get $next(): RouteBuilder<TGroupName> {
return new RouteBuilder(this, 'next');
}
get $groups(): TGroupName[] {
return Array.from(this._groupToRouteMatchMap.keys()).filter(
(group): group is TGroupName => !!group,
);
}
$route<TPrimaryRouteSchema extends RootRouteSchema>(
schema: TPrimaryRouteSchema,
): RootRouteMatchType<TPrimaryRouteSchema, undefined, TGroupName>;
$route<
TRouteSchema extends RootRouteSchema,
TSpecificGroupName extends TGroupName,
>(
group: TSpecificGroupName,
schema: TRouteSchema,
): RootRouteMatchType<TRouteSchema, TSpecificGroupName, TGroupName>;
$route(
groupOrSchema: TGroupName | RootRouteSchema,
schemaOrUndefined?: RootRouteSchema,
): RouteMatch {
let group: TGroupName | undefined;
let schema: RootRouteSchema;
if (typeof groupOrSchema === 'string') {
group = groupOrSchema;
schema = schemaOrUndefined!;
} else {
group = undefined;
schema = groupOrSchema;
}
let [routeMatch] = this._buildRouteMatch(group, '', undefined, undefined, {
$exact: true,
$match: '',
...schema,
});
this._groupToRouteMatchMap.set(group, routeMatch);
return routeMatch;
}
$ref(): string {
return this.$current.$ref();
}
$href(): string {
return this.$current.$href();
}
$<TRouteMatchShared extends RouteMatchShared>(
route: TRouteMatchShared,
params?: Partial<RouteMatchSharedToParamDict<TRouteMatchShared>> &
EmptyObjectPatch,
): RouteBuilder<TGroupName>;
$(part: string): RouteBuilder<TGroupName>;
$(route: RouteMatchShared | string, params?: GeneralParamDict): RouteBuilder {
let buildingPart =
typeof route === 'string'
? route
: {
route,
params,
};
return new RouteBuilder(this, 'current', [buildingPart]);
}
$scratch(): RouteBuilder<TGroupName> {
return new RouteBuilder(this, 'none');
}
$push(ref: string, options?: RouterNavigateOptions): void {
this.$current.$(ref).$push(options);
}
$replace(ref: string, options?: RouterNavigateOptions): void {
this.$current.$(ref).$replace(options);
}
/** @internal */
_push(ref: string, {onComplete}: RouterNavigateOptions = {}): void {
this._history
.push(ref, {navigateCompleteListener: onComplete})
.catch(console.error);
}
/** @internal */
_replace(ref: string, {onComplete}: RouterNavigateOptions = {}): void {
this._history
.replace(ref, {navigateCompleteListener: onComplete})
.catch(console.error);
}
/** @internal */
private _onHistoryChange = (snapshot: RouterHistorySnapshot): void => {
this._nextSnapshot = snapshot;
if (!this.$routing) {
this._beforeLeaveHookCalledMatchSet.clear();
}
runInAction(() => {
this._routing++;
});
this._changing = this._changing
.then(() => this._asyncOnHistoryChange(snapshot))
.finally(() => {
runInAction(() => {
this._routing--;
});
})
.catch(console.error);
};
/** @internal */
private _asyncOnHistoryChange = async (
nextSnapshot: RouterHistorySnapshot,
): Promise<void> => {
if (this._isNextSnapshotOutDated(nextSnapshot)) {
return;
}
let {ref, data} = getActiveHistoryEntry(nextSnapshot);
let navigateCompleteListener = data && data.navigateCompleteListener;
let {pathname, search} = parseRef(ref);
let snapshot = this._snapshot;
if (snapshot && _.isEqual(snapshot, nextSnapshot)) {
return;
}
let queryMap = parseSearch(search);
let pathMap = new Map<string | undefined, string>();
pathMap.set(undefined, pathname || '/');
let groups = this.$groups;
// Extract group route paths in query
for (let group of groups) {
let key = `_${group}`;
if (!queryMap.has(key)) {
continue;
}
let path = queryMap.get(key);
if (path) {
pathMap.set(group, path);
}
queryMap.delete(key);
}
// Match parallel routes
let groupToMatchEntriesMap = new Map<
string | undefined,
RouteMatchEntry[]
>();
let groupToRouteMatchMap = this._groupToRouteMatchMap;
for (let [group, path] of pathMap) {
let routeMatch = groupToRouteMatchMap.get(group)!;
let routeMatchEntries = this._match([routeMatch], path) || [];
if (!routeMatchEntries.length) {
continue;
}
let [{match}] = routeMatchEntries;
if (match.$group !== group) {
continue;
}
groupToMatchEntriesMap.set(group, routeMatchEntries);
}
// Check primary match parallel options
let groupToMatchToMatchEntryMapMap = new Map<
string | undefined,
Map<RouteMatch, RouteMatchEntry>
>();
let primaryMatchEntries = groupToMatchEntriesMap.get(undefined);
{
let primaryMatch =
primaryMatchEntries?.[primaryMatchEntries.length - 1].match;
let options = primaryMatch?._parallel;
let {groups = [], matches = []} = options || {};
for (let [group, entries] of groupToMatchEntriesMap) {
if (
!group ||
!options ||
groups.includes(group) ||
entries.some(({match}) => matches.includes(match))
) {
groupToMatchToMatchEntryMapMap.set(
group,
new Map(
entries.map((entry): [RouteMatch, RouteMatchEntry] => [
entry.match,
entry,
]),
),
);
}
}
}
let matchingSource = this._matchingSource;
runInAction(() => {
matchingSource.groupToMatchToMatchEntryMapMap =
groupToMatchToMatchEntryMapMap;
matchingSource.pathMap = pathMap;
let matchingQueryKeyToIdMap = new Map(
_.flatMap(
Array.from(groupToRouteMatchMap.values()).reverse(),
route => [...route.$next.$rest._queryKeyToIdMap],
),
);
matchingSource.queryMap = new Map(
_.compact(
Array.from(queryMap).map(
([key, value]): [string, RouteSourceQuery] | undefined =>
matchingQueryKeyToIdMap.has(key)
? [key, {id: matchingQueryKeyToIdMap.get(key)!, value}]
: undefined,
),
),
);
});
let generalGroups = [undefined, ...groups];
let interUpdateDataArray = await Promise.all(
generalGroups.map(async group =>
this._beforeUpdate(
nextSnapshot,
group,
groupToMatchToMatchEntryMapMap.get(group),
),
),
);
if (interUpdateDataArray.some(data => !data)) {
return;
}
await Promise.all(
interUpdateDataArray.map(data => this._willUpdate(data!)),
);
this._update(generalGroups);
this._snapshot = nextSnapshot;
await Promise.all(
interUpdateDataArray.map(data => this._afterUpdate(data!)),
);
if (navigateCompleteListener) {
navigateCompleteListener();
}
};
/** @internal */
private async _beforeUpdate(
nextSnapshot: RouterHistorySnapshot,
group: string | undefined,
matchToMatchEntryMap: Map<RouteMatch, RouteMatchEntry> | undefined,
): Promise<InterUpdateData | undefined> {
if (!matchToMatchEntryMap) {
matchToMatchEntryMap = new Map();
}
// Prepare previous/next match set
let previousMatchToMatchEntryMap =
this._source.groupToMatchToMatchEntryMapMap.get(group);
if (!previousMatchToMatchEntryMap) {
previousMatchToMatchEntryMap = new Map();
runInAction(() => {
this._source.groupToMatchToMatchEntryMapMap.set(
group,
previousMatchToMatchEntryMap!,
);
});
}
let previousMatchSet = new Set(previousMatchToMatchEntryMap.keys());
let matchSet = new Set(matchToMatchEntryMap.keys());
let leavingMatchSet = new Set(previousMatchSet);
for (let match of matchSet) {
leavingMatchSet.delete(match);
}
let reversedLeavingMatches = Array.from(leavingMatchSet).reverse();
let enteringAndUpdatingMatchSet = new Set(matchSet);
let descendantUpdatingMatchSet = new Set<RouteMatch>();
for (let match of previousMatchSet) {
if (!enteringAndUpdatingMatchSet.has(match)) {
continue;
}
let nextMatch = match.$next;
if (
_.isEqual(match._pathSegments, nextMatch._pathSegments) &&
match.$exact === nextMatch.$exact
) {
if (match._rest === nextMatch._rest) {
enteringAndUpdatingMatchSet.delete(match);
} else {
descendantUpdatingMatchSet.add(match);
}
}
}
let beforeLeaveHookCalledMatchSet = this._beforeLeaveHookCalledMatchSet;
for (let match of reversedLeavingMatches) {
if (beforeLeaveHookCalledMatchSet.has(match)) {
continue;
}
let result = await match._beforeLeave();
if (this._isNextSnapshotOutDated(nextSnapshot)) {
return undefined;
}
if (!result) {
this._revert();
return undefined;
}
beforeLeaveHookCalledMatchSet.add(match);
}
for (let match of enteringAndUpdatingMatchSet) {
let update = previousMatchSet.has(match);
let result = update
? await match._beforeUpdate(descendantUpdatingMatchSet.has(match))
: await match._beforeEnter();
if (this._isNextSnapshotOutDated(nextSnapshot)) {
return undefined;
}
if (!result) {
this._revert();
return undefined;
}
}
return {
reversedLeavingMatches,
enteringAndUpdatingMatchSet,
previousMatchSet,
descendantUpdatingMatchSet,
};
}
/** @internal */
private async _willUpdate({
reversedLeavingMatches,
enteringAndUpdatingMatchSet,
previousMatchSet,
descendantUpdatingMatchSet,
}: InterUpdateData): Promise<void> {
for (let match of reversedLeavingMatches) {
await match._willLeave();
}
for (let match of enteringAndUpdatingMatchSet) {
let update = previousMatchSet.has(match);
if (update) {
await match._willUpdate(descendantUpdatingMatchSet.has(match));
} else {
await match._willEnter();
}
}
}
/** @internal */
@action
private _update(generalGroups: (string | undefined)[]): void {
let source = this._source;
let matchingSource = this._matchingSource;
source.queryMap = matchingSource.queryMap;
for (let group of generalGroups) {
let path = matchingSource.pathMap.get(group)!;
if (path) {
source.pathMap.set(group, path);
} else {
source.pathMap.delete(group);
}
let matchToMatchEntryMap =
matchingSource.groupToMatchToMatchEntryMapMap.get(group)!;
source.groupToMatchToMatchEntryMapMap.set(group, matchToMatchEntryMap);
}
}
/** @internal */
private async _afterUpdate({
reversedLeavingMatches,
enteringAndUpdatingMatchSet,
previousMatchSet,
descendantUpdatingMatchSet,
}: InterUpdateData): Promise<void> {
for (let match of reversedLeavingMatches) {
await match._afterLeave();
}
for (let match of enteringAndUpdatingMatchSet) {
let update = previousMatchSet.has(match);
if (update) {
await match._afterUpdate(descendantUpdatingMatchSet.has(match));
} else {
await match._afterEnter();
}
}
}
/** @internal */
private _isNextSnapshotOutDated(snapshot: RouterHistorySnapshot): boolean {
return this._nextSnapshot !== snapshot;
}
/** @internal */
private _revert(): void {
let snapshot = this._snapshot;
if (snapshot) {
this._history.restore(snapshot).catch(console.error);
} else {
this._history.replace('/').catch(console.error);
}
}
/** @internal */
private _match(
routeMatches: RouteMatch[],
upperRest: string,
): RouteMatchEntry[] | undefined {
for (let routeMatch of routeMatches) {
let {matched, exactlyMatched, segment, rest} =
routeMatch._match(upperRest);
if (!matched) {
continue;
}
if (rest === '') {
return [
{
match: routeMatch,
segment: segment!,
exact: exactlyMatched,
rest,
},
];
}
let result = this._match(routeMatch._children || [], rest);
if (!result) {
continue;
}
return [
{
match: routeMatch,
segment: segment!,
exact: exactlyMatched,
rest,
},
...result,
];
}
return undefined;
}
/** @internal */
private _buildRouteMatches(
group: string | undefined,
schemaDict: RouteSchemaDict,
parent: RouteMatch,
matchingParent: NextRouteMatch,
): [RouteMatch[], NextRouteMatch[]] {
return Object.entries(schemaDict).reduce<[RouteMatch[], NextRouteMatch[]]>(
([routeMatches, nextRouteMatches], [routeName, schema]) => {
if (typeof schema === 'boolean') {
schema = {};
}
let [routeMatch, nextRouteMatch] = this._buildRouteMatch(
group,
routeName,
parent,
matchingParent,
schema,
);
(parent as any)[routeName] = routeMatch;
(matchingParent as any)[routeName] = nextRouteMatch;
return [
[...routeMatches, routeMatch],
[...nextRouteMatches, nextRouteMatch],
];
},
[[], []],
);
}
/** @internal */
private _buildRouteMatch(
group: string | undefined,
routeName: string,
parent: RouteMatch | undefined,
matchingParent: NextRouteMatch | undefined,
{
$match: match = this._segmentMatcher(routeName),
$exact: exact = false,
$query: queryDict,
$children: children,
$extension: extension,
$metadata: metadata,
}: RouteSchema,
): [RouteMatch, NextRouteMatch] {
let source = this._source;
let matchingSource = this._matchingSource;
let history = this._history;
let query = new Map(Object.entries(queryDict ?? {}));
let options: RouteMatchOptions = {
match,
query,
exact,
group,
metadata,
};
let routeMatch = new RouteMatch(
routeName,
this as Router,
source,
parent,
extension,
history,
options,
);
let nextRouteMatch = new NextRouteMatch(
routeName,
this as Router,
matchingSource,
matchingParent,
routeMatch,
history,
options,
);
(routeMatch as any).$next = nextRouteMatch;
if (children) {
let [childRouteMatches, childNextRouteMatches] = this._buildRouteMatches(
group,
children,
routeMatch,
nextRouteMatch,
);
routeMatch._children = childRouteMatches;
nextRouteMatch._children = childNextRouteMatches;
}
return [routeMatch, nextRouteMatch];
}
} | the_stack |
import { Package } from "../common/npmPackage";
import { fatal, exec, execNoError } from "./utils";
import { MonoRepo, MonoRepoKind } from "../common/monoRepo";
import * as semver from "semver";
export class VersionBag {
private versionData: { [key: string]: string } = {};
public add(pkg: Package, version: string) {
const existing = this.internalAdd(pkg, version);
if (existing) {
fatal(`Inconsistent version for ${pkg.name} ${version} && ${existing}`);
}
}
protected internalAdd(pkg: Package, version: string, override: boolean = false) {
const entryName = VersionBag.getEntryName(pkg);
const existing = this.versionData[entryName];
if (existing !== version) {
if (existing) {
if (!override) {
return existing;
}
console.log(` Overriding ${entryName} ${existing} -> ${version}`);
}
this.versionData[entryName] = version;
return existing;
}
}
public get(pkgOrMonoRepoName: Package | string) {
let entryName = typeof pkgOrMonoRepoName === "string" ? pkgOrMonoRepoName : VersionBag.getEntryName(pkgOrMonoRepoName);
return this.versionData[entryName];
}
public [Symbol.iterator]() {
return Object.entries(this.versionData)[Symbol.iterator]();
}
protected static getEntryName(pkg: Package) {
return pkg.monoRepo ? MonoRepoKind[pkg.monoRepo.kind] : pkg.name;
}
}
/**
* Keep track of all the dependency version information and detect conflicting dependencies.
* Provide functionality to collect the dependencies information from published package as well.
*/
export class ReferenceVersionBag extends VersionBag {
private readonly referenceData = new Map<string, { reference: string, published: boolean }>();
private readonly nonDevDep = new Set<string>();
private readonly publishedPackage = new Set<string>();
private readonly publishedPackageRange = new Set<string>();
constructor(private readonly repoRoot: string, private readonly fullPackageMap: Map<string, Package>, public readonly repoVersions: VersionBag) {
super();
}
/**
* Add package and version to the version bag, with option reference to indicate where the reference comes from
* Will error if there is a conflicting dependency versions, if the references are from the local repo, other wise warn.
*
* @param pkg
* @param version
* @param newReference
*/
public add(pkg: Package, version: string, dev: boolean = false, newReference?: string, published: boolean = false) {
const entryName = VersionBag.getEntryName(pkg);
// Override existing we haven't seen a non-dev dependency yet, and it is not a published version or it is not a dev dependency
const override = !this.nonDevDep.has(entryName) && (!published || !dev);
const existing = this.internalAdd(pkg, version, override);
if (!dev) {
if (existing) {
const existingReference = this.referenceData.get(entryName);
const message = `Inconsistent dependency to ${pkg.name}\n ${version.padStart(10)} in ${newReference}\n ${existing.padStart(10)} in ${existingReference?.reference}`;
if (existingReference?.reference && this.publishedPackage.has(existingReference.reference) && newReference && this.publishedPackage.has(newReference)) {
// only warn if the conflict is between two published references (since we can't change it anyways).
console.warn(`WARNING: ${message}`);
} else {
fatal(message);
}
}
this.nonDevDep.add(entryName);
} else if (existing) {
console.log(` Ignored mismatched dev dependency ${pkg.name}@${version} vs ${existing}`);
// Don't replace the existing reference if it is an ignored dev dependency
return;
}
if (newReference) {
this.referenceData.set(entryName, { reference: newReference, published });
}
}
private async getPublishedMatchingVersion(rangeSpec: string, reference: string | undefined) {
const ret = await execNoError(`npm view "${rangeSpec}" version --json`, this.repoRoot);
if (!ret) {
if (reference) {
fatal(`Unable to get published version for ${rangeSpec} referenced from ${reference}.`);
}
// If a reference is not given, we can just skip it if it doesn't exist
return undefined;
}
let publishedVersions: string | string[];
try {
publishedVersions = JSON.parse(ret);
} catch (e) {
if (reference) {
fatal(`Unable to parse published version for ${rangeSpec} referenced from ${reference}.\nOutput: ${ret}`);
}
// If a reference is not given, we can just skip it if it doesn't exist
return undefined;
}
return Array.isArray(publishedVersions) ? publishedVersions.sort(semver.rcompare)[0] : publishedVersions;
}
private async getPublishedDependencies(versionSpec: string, dev: boolean) {
const dep = dev ? "devDependencies" : "dependencies";
const retDep = await exec(`npm view ${versionSpec} ${dep} --json`, this.repoRoot, "look up dependencies");
// detect if there are no dependencies
if (retDep.trim() === "") { return undefined; }
try {
return JSON.parse(retDep);
} catch (e) {
fatal(`Unable to parse dependencies for ${versionSpec}.\nOutput: ${retDep}`);
}
}
public static checkPrivate(pkg: Package, dep: Package, dev: boolean) {
if (dep.packageJson.private) {
if (!pkg.packageJson.private && !dev) {
fatal(`Private package not a dev dependency\n ${pkg.name}@${pkg.version}\n ${dep.name}@${dep.version}`)
}
if (!MonoRepo.isSame(pkg.monoRepo, dep.monoRepo)) {
fatal(`Private package not in the same monorepo\n ${pkg.name}@${pkg.version}\n ${dep.name}@${dep.version}`)
}
return true;
}
return false;
}
/**
* Given a package a version range, ask NPM for a list of version that satisfies it, and find the latest version.
* That version is added to the version bag, and will error on conflict.
* It then ask NPM for the list of dependency for the matched version, and collect the version as well.
*
* @param pkg - the package to begin collection information
* @param versionRange - the version range to match
* @param repoRoot - where the repo root is
* @param fullPackageMap - map of all the package in the repo
* @param reference - reference of this dependency for error reporting in case of conflict
*/
public async collectPublishedPackageDependencies(
pkg: Package,
versionRange: string,
dev: boolean,
reference?: string
) {
const entryName = VersionBag.getEntryName(pkg);
const rangeSpec = `${pkg.name}@${versionRange}`;
// Check if we already checked this published package range
if (this.publishedPackageRange.has(rangeSpec)) {
return;
}
this.publishedPackageRange.add(rangeSpec);
let matchedVersion: string | undefined = this.get(entryName);
if (!matchedVersion || !semver.satisfies(matchedVersion, versionRange)) {
matchedVersion = await this.getPublishedMatchingVersion(rangeSpec, reference);
if (!matchedVersion) {
return;
}
}
console.log(` Found ${rangeSpec} => ${matchedVersion}`);
this.add(pkg, matchedVersion, dev, reference, true);
// Get the dependencies
const versionSpec = `${pkg.name}@${matchedVersion}`;
if (this.publishedPackage.has(versionSpec)) {
return;
}
this.publishedPackage.add(versionSpec);
const pending: Promise<void>[] = [];
const addPublishedDependencies = async (dev: boolean) => {
const dep = await this.getPublishedDependencies(versionSpec, dev);
// Add it to pending for processing
for (const d in dep) {
const depPkg = this.fullPackageMap.get(d);
if (depPkg) {
if (ReferenceVersionBag.checkPrivate(pkg, depPkg, dev)) {
continue;
}
pending.push(this.collectPublishedPackageDependencies(depPkg, dep[d], dev, versionSpec));
}
}
}
await Promise.all([addPublishedDependencies(true), addPublishedDependencies(false)]);
await Promise.all(pending);
}
public printRelease() {
console.log("Release Versions:");
for (const [name] of this.repoVersions) {
const depVersion = this.get(name) ?? "undefined";
const state = this.needRelease(name) ? "(new)" : this.needBump(name) ? "(current)" : "(old)";
console.log(`${name.padStart(40)}: ${depVersion.padStart(10)} ${state}`);
}
console.log();
}
public printPublished(name: string) {
console.log(`Current Versions from ${name}:`);
for (const [name] of this.repoVersions) {
const depVersion = this.get(name) ?? "undefined";
console.log(`${name.padStart(40)}: ${depVersion.padStart(10)} ${depVersion === "undefined" ? "" : this.needRelease(name) ? "(local)" : "(published)"}`);
}
console.log();
}
public needBump(name: string) {
return this.repoVersions.get(name) === this.get(name);
}
public needRelease(name: string) {
if (this.needBump(name)) {
const data = this.referenceData.get(name)!;
return !data || !data.published;
}
return false;
}
}
export function getRepoStateChange(oldVersions: VersionBag, newVersions: VersionBag) {
let repoState = "";
for (const [name, newVersion] of newVersions) {
const oldVersion = oldVersions.get(name) ?? "undefined";
if (oldVersion !== newVersion) {
repoState += `\n${name.padStart(40)}: ${oldVersion.padStart(10)} -> ${newVersion.padEnd(10)}`;
} else {
repoState += `\n${name.padStart(40)}: ${newVersion.padStart(10)} (unchanged)`;
}
}
return repoState;
} | the_stack |
import { deepClone } from "@cds/core/internal";
import actions from "actions";
import LoadingWrapper from "components/LoadingWrapper";
import SearchFilter from "components/SearchFilter/SearchFilter";
import {
Context,
InstalledPackageReference,
InstalledPackageStatus,
InstalledPackageStatus_StatusReason,
InstalledPackageSummary,
PackageAppVersion,
VersionReference,
} from "gen/kubeappsapis/core/packages/v1alpha1/packages";
import { Plugin } from "gen/kubeappsapis/core/plugins/v1alpha1/plugins";
import context from "jest-plugin-context";
import qs from "qs";
import React from "react";
import { act } from "react-dom/test-utils";
import * as ReactRedux from "react-redux";
import { MemoryRouter } from "react-router";
import { Kube } from "shared/Kube";
import { defaultStore, getStore, initialState, mountWrapper } from "shared/specs/mountWrapper";
import { FetchError, IStoreState } from "shared/types";
import Alert from "../js/Alert";
import AppList from "./AppList";
import AppListItem from "./AppListItem";
import CustomResourceListItem from "./CustomResourceListItem";
let spyOnUseDispatch: jest.SpyInstance;
const opActions = { ...actions.operators };
const appActions = { ...actions.apps };
beforeEach(() => {
actions.operators = {
...actions.operators,
getResources: jest.fn(),
};
actions.apps = {
...actions.apps,
fetchApps: jest.fn(),
};
const mockDispatch = jest.fn();
spyOnUseDispatch = jest.spyOn(ReactRedux, "useDispatch").mockReturnValue(mockDispatch);
Kube.canI = jest.fn().mockReturnValue({
then: jest.fn(f => f(true)),
});
});
afterEach(() => {
actions.operators = { ...opActions };
actions.apps = { ...appActions };
spyOnUseDispatch.mockRestore();
});
context("when changing props", () => {
it("should fetch apps in the new namespace", async () => {
const fetchApps = jest.fn();
const getCustomResources = jest.fn();
actions.apps.fetchApps = fetchApps;
actions.operators.getResources = getCustomResources;
mountWrapper(defaultStore, <AppList />);
expect(fetchApps).toHaveBeenCalledWith("default-cluster", "default");
expect(getCustomResources).toHaveBeenCalledWith("default-cluster", "default");
});
it("should update the search filter", () => {
jest.spyOn(qs, "parse").mockReturnValue({
q: "foo",
});
const wrapper = mountWrapper(
defaultStore,
<MemoryRouter initialEntries={["/foo?q=foo"]}>
<AppList />
</MemoryRouter>,
);
expect(wrapper.find(SearchFilter).prop("value")).toEqual("foo");
});
it("should list apps in all namespaces", () => {
jest.spyOn(qs, "parse").mockReturnValue({
allns: "yes",
});
const wrapper = mountWrapper(
defaultStore,
<MemoryRouter initialEntries={["/foo?allns=yes"]}>
<AppList />
</MemoryRouter>,
);
expect(wrapper.find("input[type='checkbox']")).toBeChecked();
});
it("should fetch apps in all namespaces", async () => {
const fetchApps = jest.fn();
const getCustomResources = jest.fn();
actions.apps.fetchApps = fetchApps;
actions.operators.getResources = getCustomResources;
const wrapper = mountWrapper(defaultStore, <AppList />);
act(() => {
wrapper.find("input[type='checkbox']").simulate("change");
});
expect(fetchApps).toHaveBeenCalledWith("default-cluster", "");
expect(getCustomResources).toHaveBeenCalledWith("default-cluster", "");
});
it("should hide the all-namespace switch if the user doesn't have permissions", async () => {
Kube.canI = jest.fn().mockReturnValue({
then: jest.fn((f: any) => f(false)),
});
const wrapper = mountWrapper(defaultStore, <AppList />);
expect(wrapper.find("input[type='checkbox']")).not.toExist();
});
describe("when store changes", () => {
let spyOnUseState: jest.SpyInstance;
afterEach(() => {
spyOnUseState.mockRestore();
});
it("should not set all-ns prop when getting changes in the namespace", async () => {
const setAllNS = jest.fn();
const useState = jest.fn();
spyOnUseState = jest
.spyOn(React, "useState")
/* @ts-expect-error: Argument of type '(init: any) => any[]' is not assignable to parameter of type '() => [unknown, Dispatch<unknown>]' */
.mockImplementation((init: any) => {
if (init === false) {
// Mocking the result of setAllNS
return [false, setAllNS];
}
return [init, useState];
});
mountWrapper(
defaultStore,
<MemoryRouter initialEntries={["/foo?allns=yes"]}>
<AppList />
</MemoryRouter>,
);
expect(setAllNS).not.toHaveBeenCalledWith(false);
});
});
});
context("while fetching apps", () => {
const state = deepClone(initialState) as IStoreState;
state.apps.isFetching = true;
it("behaves as loading component", () => {
const wrapper = mountWrapper(getStore(state), <AppList />);
expect(wrapper.find(LoadingWrapper)).toExist();
});
it("behaves as loading component (for operators)", () => {
const stateOp = deepClone(initialState) as IStoreState;
state.operators.isFetching = true;
const wrapper = mountWrapper(getStore(stateOp), <AppList />);
expect(wrapper.find(LoadingWrapper)).toExist();
});
it("renders a Application header (while fetching)", () => {
const wrapper = mountWrapper(getStore(state), <AppList />);
expect(wrapper.find("h1").text()).toContain("Applications");
});
it("shows the search filter and deploy button (while fetching)", () => {
const wrapper = mountWrapper(getStore(state), <AppList />);
expect(wrapper.find("SearchFilter")).toExist();
expect(wrapper.find("Link")).toExist();
});
});
context("when fetched but not apps available", () => {
it("renders a welcome message", () => {
const wrapper = mountWrapper(defaultStore, <AppList />);
expect(wrapper.find(".applist-empty").text()).toContain("Welcome To Kubeapps");
});
it("shows the search filter and deploy button (no apps available)", () => {
const wrapper = mountWrapper(defaultStore, <AppList />);
expect(wrapper.find("SearchFilter")).toExist();
expect(wrapper.find("Link")).toExist();
});
});
context("when an error is present", () => {
const state = deepClone(initialState) as IStoreState;
state.apps.error = new FetchError("Boom!");
it("renders a generic error message", () => {
const wrapper = mountWrapper(getStore(state), <AppList />);
expect(wrapper.find(Alert)).toExist();
expect(wrapper.find(Alert).html()).toContain("Boom!");
});
it("renders a Application header (when error)", () => {
const wrapper = mountWrapper(getStore(state), <AppList />);
expect(wrapper.find("h1").text()).toContain("Applications");
});
});
context("when apps available", () => {
const state = deepClone(initialState) as IStoreState;
beforeEach(() => {
state.apps.listOverview = [
{
name: "foo",
installedPackageRef: {
identifier: "bar/foo",
pkgVersion: "1.0.0",
context: { cluster: "", namespace: "foobar" } as Context,
plugin: { name: "my.plugin", version: "0.0.1" } as Plugin,
} as InstalledPackageReference,
status: {
ready: true,
reason: InstalledPackageStatus_StatusReason.STATUS_REASON_INSTALLED,
userReason: "deployed",
} as InstalledPackageStatus,
latestMatchingVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
latestVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
currentVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
pkgVersionReference: { version: "1" } as VersionReference,
} as InstalledPackageSummary,
];
});
afterEach(() => {
jest.restoreAllMocks();
});
it("renders a CardGrid with the available Apps", () => {
const wrapper = mountWrapper(getStore(state), <AppList />);
const itemList = wrapper.find(AppListItem);
expect(itemList).toExist();
expect(itemList.key()).toBe("foobar-bar/foo");
});
it("filters apps", () => {
state.apps.listOverview = [
{
name: "foo",
installedPackageRef: {
identifier: "foo/bar",
pkgVersion: "1.0.0",
context: { cluster: "", namespace: "fooNs" } as Context,
plugin: { name: "my.plugin", version: "0.0.1" } as Plugin,
} as InstalledPackageReference,
status: {
ready: true,
reason: InstalledPackageStatus_StatusReason.STATUS_REASON_INSTALLED,
userReason: "deployed",
} as InstalledPackageStatus,
latestMatchingVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
latestVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
currentVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
pkgVersionReference: { version: "1" } as VersionReference,
} as InstalledPackageSummary,
{
name: "bar",
installedPackageRef: {
identifier: "foobar/bar",
pkgVersion: "1.0.0",
context: { cluster: "", namespace: "fooNs" } as Context,
plugin: { name: "my.plugin", version: "0.0.1" } as Plugin,
} as InstalledPackageReference,
status: {
ready: true,
reason: InstalledPackageStatus_StatusReason.STATUS_REASON_INSTALLED,
userReason: "deployed",
} as InstalledPackageStatus,
latestMatchingVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
latestVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
currentVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
pkgVersionReference: { version: "1" } as VersionReference,
} as InstalledPackageSummary,
];
jest.spyOn(qs, "parse").mockReturnValue({
q: "bar",
});
const wrapper = mountWrapper(
getStore(state),
<MemoryRouter initialEntries={["/foo?q=bar"]}>
<AppList />
</MemoryRouter>,
);
expect(wrapper.find(AppListItem).key()).toBe("fooNs-foobar/bar");
});
it("filters apps (same name, different ns)", () => {
state.apps.listOverview = [
{
name: "foo",
installedPackageRef: {
identifier: "foo/bar",
pkgVersion: "1.0.0",
context: { cluster: "", namespace: "fooNs" } as Context,
plugin: { name: "my.plugin", version: "0.0.1" } as Plugin,
} as InstalledPackageReference,
status: {
ready: true,
reason: InstalledPackageStatus_StatusReason.STATUS_REASON_INSTALLED,
userReason: "deployed",
} as InstalledPackageStatus,
latestMatchingVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
latestVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
currentVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
pkgVersionReference: { version: "1" } as VersionReference,
} as InstalledPackageSummary,
{
name: "bar",
installedPackageRef: {
identifier: "foobar/bar",
pkgVersion: "1.0.0",
context: { cluster: "", namespace: "fooNs" } as Context,
plugin: { name: "my.plugin", version: "0.0.1" } as Plugin,
} as InstalledPackageReference,
status: {
ready: true,
reason: InstalledPackageStatus_StatusReason.STATUS_REASON_INSTALLED,
userReason: "deployed",
} as InstalledPackageStatus,
latestMatchingVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
latestVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
currentVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
pkgVersionReference: { version: "1" } as VersionReference,
} as InstalledPackageSummary,
{
name: "bar",
installedPackageRef: {
identifier: "foobar/bar",
pkgVersion: "1.0.0",
context: { cluster: "", namespace: "barNs" } as Context,
plugin: { name: "my.plugin", version: "0.0.1" } as Plugin,
} as InstalledPackageReference,
status: {
ready: true,
reason: InstalledPackageStatus_StatusReason.STATUS_REASON_INSTALLED,
userReason: "deployed",
} as InstalledPackageStatus,
latestMatchingVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
latestVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
currentVersion: { appVersion: "0.1.0", pkgVersion: "1.0.0" } as PackageAppVersion,
pkgVersionReference: { version: "1" } as VersionReference,
} as InstalledPackageSummary,
];
jest.spyOn(qs, "parse").mockReturnValue({
q: "bar",
});
const wrapper = mountWrapper(
getStore(state),
<MemoryRouter initialEntries={["/foo?q=bar"]}>
<AppList />
</MemoryRouter>,
);
expect(wrapper.find(AppListItem).first().key()).toBe("fooNs-foobar/bar");
expect(wrapper.find(AppListItem).last().key()).toBe("barNs-foobar/bar");
});
});
context("when custom resources available", () => {
const state = deepClone(initialState) as IStoreState;
const cr = { kind: "KubeappsCluster", metadata: { name: "foo-cluster" } } as any;
const csv = {
metadata: {
name: "foo",
},
spec: {
customresourcedefinitions: {
owned: [
{
kind: "KubeappsCluster",
},
],
},
},
} as any;
beforeEach(() => {
state.operators.resources = [cr];
state.operators.csvs = [csv];
});
afterEach(() => {
jest.restoreAllMocks();
});
it("renders a CardGrid with the available resources", () => {
const wrapper = mountWrapper(getStore(state), <AppList />);
const itemList = wrapper.find(CustomResourceListItem);
expect(itemList).toExist();
expect(itemList.key()).toBe("foo-cluster");
});
it("filters out items", () => {
jest.spyOn(qs, "parse").mockReturnValue({
q: "nop",
});
const wrapper = mountWrapper(
getStore(state),
<MemoryRouter initialEntries={["/foo?q=nop"]}>
<AppList />
</MemoryRouter>,
);
const itemList = wrapper.find(CustomResourceListItem);
expect(itemList).not.toExist();
});
}); | the_stack |
import { Map } from 'immutable'
import { connect } from 'react-redux'
import { getTranslate } from 'react-localize-redux'
import { push } from 'connected-react-router'
import { withRouter } from 'react-router-dom'
import { withStyles } from '@material-ui/core/styles'
import Badge from '@material-ui/core/Badge'
import Drawer from '@material-ui/core/Drawer'
import Hidden from '@material-ui/core/Hidden'
import IconButton from '@material-ui/core/IconButton'
import Link from '@material-ui/core/Link'
import Menu from '@material-ui/core/Menu'
import MenuIcon from '@material-ui/icons/Menu'
import MenuItem from '@material-ui/core/MenuItem'
import React, { Component } from 'react'
import SvgAccountCircle from '@material-ui/icons/AccountCircle'
import SvgShoppingBasket from '@material-ui/icons/ShoppingBasketOutlined'
import Tooltip from '@material-ui/core/Tooltip'
import { authorizeActions } from 'store/actions'
import { globalActions } from 'src/store/actions'
import AddToCart from 'containers/addToCart'
import AppBar from 'src/components/appBar'
import EditProfile from 'src/components/editProfile'
import Toolbar from 'src/components/toolbar'
import * as addToCartActions from 'store/actions/addToCartActions'
import * as checkoutActions from 'store/actions/checkoutActions'
import clsx from 'clsx'
import * as userActions from 'store/actions/userActions'
import { ITopAppBarComponentProps } from './ITopAppBarComponentProps'
import { ITopAppBarComponentState } from './ITopAppBarComponentState'
// - Import API
// - Import actions
const styles = (theme: any) => ({
title: {
fontSize: 26,
color: '#F62F5E'
},
placeholder: {
height: 70,
backgroundColor: '#ffffff',
[theme.breakpoints.up('sm')]: {
height: 80
}
},
toolbar: {
justifyContent: 'flex-start'
},
left: {
flex: 1
},
leftLinkActive: {
color: theme.palette.common.white
},
right: {
flex: 1,
display: 'flex',
justifyContent: 'flex-end'
},
center: {
flex: 1,
display: 'flex',
justifyContent: 'center'
},
rightLink: {
fontSize: 17,
color: theme.palette.common.black,
marginLeft: theme.spacing(10),
textTransform: 'capitalize',
'&:hover': {
cursor: 'pointer',
color: '#F62F5E',
textDecoration: 'none'
}
},
linkSecondary: {
color: theme.palette.secondary.main
},
cartIcon: {
position: 'relative',
left: 32,
top: -5
},
drawerPaper: {
border: 'none',
bottom: '0',
transitionProperty: 'top, bottom, width',
transitionDuration: '.2s, .2s, .35s',
transitionTimingFunction: 'linear, linear, ease',
width: 260,
boxShadow:
'0 10px 30px -12px rgba(0, 0, 0, 0.42), 0 4px 25px 0px rgba(0, 0, 0, 0.12), 0 8px 10px -5px rgba(0, 0, 0, 0.2)',
position: 'fixed',
display: 'block',
top: '0',
height: '100vh',
right: '0',
left: 'auto',
visibility: 'visible',
overflowY: 'visible',
borderTop: 'none',
textAlign: 'left',
paddingRight: '0px',
paddingLeft: '0',
transition: 'all 0.33s cubic-bezier(0.685, 0.0473, 0.346, 1)'
},
appResponsive: {
margin: '20px 10px'
},
drawerLink: {
width: '100%',
float: 'left',
position: 'relative',
display: 'block',
fontSize: 17,
color: theme.palette.common.black,
padding: 15,
textTransform: 'capitalize',
'&:hover': {
cursor: 'pointer',
color: '#F62F5E',
textDecoration: 'none'
},
'&:after': {
width: '100%',
content: '""',
display: 'block',
height: '1px',
backgroundColor: '#e5e5e5',
}
}
})
/**
* Create component class
*/
export class TopAppBarComponent extends Component<
ITopAppBarComponentProps,
ITopAppBarComponentState
> {
static propTypes = {
/**
* List of users
*/
}
/**
* Component constructor
* @param {object} props is an object properties of component
*/
constructor(props: ITopAppBarComponentProps) {
super(props)
// Defaul state
this.state = {
/**
* If true Cart will be open
*/
openCart: false,
/**
* User avatar popover is open if true
*/
openAvatarMenu: false,
/**
* drawer menu is open if true
*/
mobileOpen: false
}
// Binding functions to `this`
this.handleCloseCart = this.handleCloseCart.bind(this)
this.handleCartTouchTap = this.handleCartTouchTap.bind(this)
this.handleSearchTouchTap = this.handleSearchTouchTap.bind(this)
this.handleAvatarTouchTap = this.handleAvatarTouchTap.bind(this)
this.handleMyAccountTouchTap = this.handleMyAccountTouchTap.bind(this)
this.handleDrawerToggle = this.handleDrawerToggle.bind(this)
}
/**
* Handle touch on user avatar for popover
*
*/
handleAvatarTouchTap = (event: any) => {
event.preventDefault()
if (this.props.authed) {
this.setState({
openAvatarMenu: true,
anchorEl: event.currentTarget
})
} else {
this.props.goTo!(`/login`)
}
}
/**
* Handle logout user
*
*/
handleLogout = () => {
this.props.logout!()
this.setState({
openAvatarMenu: false,
anchorEl: null
})
this.props.clearData!()
this.props.clearActiveState!()
this.props.clearCart!()
}
/**
* Handle close popover
*
*/
handleRequestClose = () => {
this.setState({
openAvatarMenu: false,
anchorEl: null
})
}
/**
* Handle Drawer popover
*
*/
handleDrawerToggle = () => {
this.setState({ mobileOpen: !this.state.mobileOpen })
}
/**
* Handle cart touch
*
*/
handleCartTouchTap = (event: any) => {
// This prevents ghost click.
event.preventDefault()
this.setState({
openCart: true,
anchorEl: event.currentTarget
})
}
/**
* Handle my account touch
*
*/
handleMyAccountTouchTap = (event: any) => {
// This prevents ghost click.
event.preventDefault()
this.setState({
openAvatarMenu: false,
anchorEl: null
})
this.props.openEditor!()
}
/**
* Handle search touch
*
*/
handleSearchTouchTap = (event: any) => {}
/**
* Handle close notification menu
*
*/
handleCloseCart = () => {
this.setState({
openCart: false
})
}
/**
* Reneder component DOM
* @return {react element} return the DOM which rendered by component
*/
render() {
const {
classes,
translate,
goTo,
editProfileOpen,
} = this.props
return (
<div>
<AppBar>
<Toolbar className={classes.toolbar}>
<div className={classes.left}>
<Link
variant='h6'
underline='none'
className={classes.title}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/`)
}}
>
{'shopmate'}
</Link>
</div>
<Hidden mdDown implementation='css'>
<div className={classes.center}>
<Link
color='inherit'
variant='h6'
underline='none'
className={classes.rightLink}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/productsbycat1/1`)
}}
>
{'French'}
</Link>
<Link
color='inherit'
variant='h6'
underline='none'
className={classes.rightLink}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/productsbycat2/2`)
}}
>
{'Italian'}
</Link>
<Link
color='inherit'
variant='h6'
underline='none'
className={classes.rightLink}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/productsbycat3/4`)
}}
>
{'Animal'}
</Link>
<Link
variant='h6'
underline='none'
className={clsx(classes.rightLink)}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/productsbycat4/5`)
}}
>
{'Flower'}
</Link>
<Link
variant='h6'
underline='none'
className={clsx(classes.rightLink)}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/productsbycat5/6`)
}}
>
{'Christmas'}
</Link>
<Link
variant='h6'
underline='none'
className={clsx(classes.rightLink)}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/products`)
}}
>
{'Products'}
</Link>
</div>
</Hidden>
<div className={classes.right}>
{this.props.cartItemsCount! > 0 ? (
<Tooltip title={translate!('header.cartTooltip')}>
<IconButton
disableRipple
onClick={this.handleCartTouchTap}
>
<Badge
color='secondary'
badgeContent={this.props.cartItemsCount}
invisible={true}
className={classes.margin}
>
<SvgShoppingBasket color='primary' />
</Badge>
</IconButton>
</Tooltip>
) : (
<Tooltip title={translate!('header.cartTooltip')}>
<IconButton
disableRipple
onClick={this.handleCartTouchTap}
>
<SvgShoppingBasket />
</IconButton>
</Tooltip>
)}
<IconButton disableRipple onClick={this.handleAvatarTouchTap}>
<SvgAccountCircle />
</IconButton>
<Menu
open={this.state.openAvatarMenu}
anchorEl={this.state.anchorEl!}
anchorOrigin={{
vertical: 'top',
horizontal: 'right'
}}
transformOrigin={{
vertical: 'top',
horizontal: 'right'
}}
onClose={this.handleRequestClose}
>
<MenuItem
id={'MyAccount'}
style={{ backgroundColor: 'white', fontSize: '14px' }}
onClick={this.handleMyAccountTouchTap}
>
{' '}
{translate!('header.myAccount')}{' '}
</MenuItem>
<MenuItem
id={'logout'}
style={{ fontSize: '14px' }}
onClick={this.handleLogout.bind(this)}
>
{' '}
{translate!('header.logout')}{' '}
</MenuItem>
</Menu>
{editProfileOpen ? (
<EditProfile
avatar={
'https://firebasestorage.googleapis.com/v0/b/open-social-33d92.appspot.com/o/images%2F751145a1-9488-46fd-a97e-04018665a6d3.JPG?alt=media&token=1a1d5e21-5101-450e-9054-ea4a20e06c57'
}
banner={
'https://firebasestorage.googleapis.com/v0/b/open-social-33d92.appspot.com/o/images%2F751145a1-9488-46fd-a97e-04018665a6d3.JPG?alt=media&token=1a1d5e21-5101-450e-9054-ea4a20e06c57'
}
fullName={'this.props.fullName'}
/>
) : (
''
)}
<AddToCart
open={this.state.openCart ? true : false}
anchorEl={this.state.anchorEl}
onRequestClose={this.handleCloseCart}
/>
<Hidden lgUp>
<IconButton
color='secondary'
aria-label='open drawer'
onClick={this.handleDrawerToggle}
>
<MenuIcon />
</IconButton>
</Hidden>
</div>
</Toolbar>
<Hidden lgUp implementation='css'>
<Drawer
variant='temporary'
anchor={'right'}
open={this.state.mobileOpen}
classes={{
paper: classes.drawerPaper
}}
onClose={this.handleDrawerToggle}
>
<div className={classes.appResponsive}>
<Link
color='inherit'
variant='h6'
underline='none'
className={classes.drawerLink}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/productsbycat1/1`)
}}
>
{'French'}
</Link>
<Link
color='inherit'
variant='h6'
underline='none'
className={classes.drawerLink}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/productsbycat2/2`)
}}
>
{'Italian'}
</Link>
<Link
color='inherit'
variant='h6'
underline='none'
className={classes.drawerLink}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/productsbycat3/4`)
}}
>
{'Animal'}
</Link>
<Link
variant='h6'
underline='none'
className={clsx(classes.drawerLink)}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/productsbycat4/5`)
}}
>
{'Flower'}
</Link>
<Link
variant='h6'
underline='none'
className={clsx(classes.drawerLink)}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/productsbycat5/6`)
}}
>
{'Christmas'}
</Link>
<Link
variant='h6'
underline='none'
className={clsx(classes.drawerLink)}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/products`)
}}
>
{'Products'}
</Link>
</div>
</Drawer>
</Hidden>
</AppBar>
</div>
)
}
}
/**
* Map dispatch to props
* @param {func} dispatch is the function to dispatch action to reducers
* @param {object} ownProps is the props belong to component
* @return {object} props of component
*/
const mapDispatchToProps = (
dispatch: Function,
ownProps: ITopAppBarComponentProps
) => {
return {
goTo: (url: string) => dispatch(push(url)),
logout: () => dispatch(authorizeActions.dbLogout()),
openEditor: () => dispatch(userActions.openEditProfile()),
clearData: () => {
dispatch(globalActions.clearTemp())
},
clearActiveState: () => dispatch(checkoutActions.setActiveStep(0)),
clearCart: () => dispatch(addToCartActions.clearCart())
}
}
/**
* Map state to props
* @param {object} state is the obeject from redux store
* @param {object} ownProps is the props belong to component
* @return {object} props of component
*/
const mapStateToProps = (
state: Map<string, any>,
ownProps: ITopAppBarComponentProps
) => {
const uid = state.getIn(['authorize', 'uid'], 0)
// const userCartItems: Map<string, any> = state.getIn([
// 'addToCart',
// 'cartProducts'
// ])
var cartItemsCount
let userCartItems: Map<string, Map<string, any>> = state.getIn([
'addToCart',
'cartProducts'
])
userCartItems.forEach((userCartItem: Map<string, any>) => {
cartItemsCount = userCartItem.count()
})
const editProfileOpen = state.getIn(['user', 'openEditProfile'])
const authed = state.getIn(['authorize', 'authed'])
return {
uid,
cartItemsCount,
translate: getTranslate(state.get('locale')),
editProfileOpen,
authed
}
}
export default withRouter<any>(
connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles as any, { withTheme: true })(
TopAppBarComponent as any
) as any)
) as typeof TopAppBarComponent | the_stack |
import { getValue, init, publish, subscribe } from '@virtuoso.dev/urx'
import { AANode, ranges, walk } from '../src/AATree'
import { initialSizeState, offsetOf, rangesWithinOffsets, sizeStateReducer, sizeSystem } from '../src/sizeSystem'
function toKV<T>(tree: AANode<T>) {
return walk(tree).map((node) => [node.k, node.v] as [number, T])
}
const mockLogger = function () {
void 0
}
describe('size state reducer', () => {
describe('insert', () => {
it('sets the initial insert as a baseline', () => {
const state = initialSizeState()
const { sizeTree, offsetTree } = sizeStateReducer(state, [[{ startIndex: 0, endIndex: 0, size: 1 }], [], mockLogger])
expect(toKV(sizeTree)).toEqual([[0, 1]])
expect(offsetTree).toEqual([{ offset: 0, index: 0, size: 1 }])
})
it('punches the initial range', () => {
const state = initialSizeState()
const { sizeTree, offsetTree } = sizeStateReducer(state, [
[
{ startIndex: 0, endIndex: 0, size: 1 },
{ startIndex: 3, endIndex: 7, size: 2 },
{ startIndex: 9, endIndex: 10, size: 2 },
],
[],
mockLogger,
])
expect(toKV(sizeTree)).toEqual([
[0, 1],
[3, 2],
[8, 1],
[9, 2],
[11, 1],
])
expect(offsetTree).toEqual([
{ offset: 0, index: 0, size: 1 },
{ offset: 3, index: 3, size: 2 },
{ offset: 13, index: 8, size: 1 },
{ offset: 14, index: 9, size: 2 },
{ offset: 18, index: 11, size: 1 },
])
})
it('does not change the ranges if size is the same', () => {
const state = initialSizeState()
const { offsetTree, sizeTree } = sizeStateReducer(state, [
[
{ startIndex: 0, endIndex: 0, size: 1 },
{ startIndex: 3, endIndex: 8, size: 1 },
],
[],
mockLogger,
])
expect(toKV(sizeTree)).toEqual([[0, 1]])
expect(offsetTree).toEqual([{ offset: 0, index: 0, size: 1 }])
})
it('keeps default size if reinserted in the beginning', () => {
const state = initialSizeState()
const { offsetTree, sizeTree } = sizeStateReducer(state, [
[
{ startIndex: 0, endIndex: 0, size: 1 },
{ startIndex: 0, endIndex: 0, size: 2 },
],
[],
mockLogger,
])
expect(toKV(sizeTree)).toEqual([
[0, 2],
[1, 1],
])
expect(offsetTree).toEqual([
{ offset: 0, index: 0, size: 2 },
{ offset: 2, index: 1, size: 1 },
])
})
it('joins to previous range', () => {
let state = initialSizeState()
state = sizeStateReducer(state, [
[
{ startIndex: 0, endIndex: 0, size: 1 },
{ startIndex: 2, endIndex: 4, size: 2 },
],
[],
mockLogger,
])
state = sizeStateReducer(state, [[{ startIndex: 5, endIndex: 9, size: 2 }], [], mockLogger])
const { sizeTree, offsetTree } = state
expect(toKV(sizeTree)).toEqual([
[0, 1],
[2, 2],
[10, 1],
])
expect(offsetTree).toEqual([
{ offset: 0, index: 0, size: 1 },
{ offset: 2, index: 2, size: 2 },
{ offset: 18, index: 10, size: 1 },
])
})
it('joins to next range', () => {
const state = initialSizeState()
const { sizeTree, offsetTree } = sizeStateReducer(state, [
[
{ startIndex: 0, endIndex: 0, size: 1 },
{ startIndex: 5, endIndex: 9, size: 2 },
{ startIndex: 2, endIndex: 4, size: 2 },
],
[],
mockLogger,
])
expect(toKV(sizeTree)).toEqual([
[0, 1],
[2, 2],
[10, 1],
])
expect(offsetTree).toEqual([
{ offset: 0, index: 0, size: 1 },
{ offset: 2, index: 2, size: 2 },
{ offset: 18, index: 10, size: 1 },
])
})
})
it('partially punches existing range', () => {
const state = initialSizeState()
const { sizeTree, offsetTree } = sizeStateReducer(state, [
[
{ startIndex: 0, endIndex: 0, size: 1 },
{ startIndex: 5, endIndex: 9, size: 2 },
{ startIndex: 7, endIndex: 11, size: 3 },
],
[],
mockLogger,
])
expect(toKV(sizeTree)).toEqual([
[0, 1],
[5, 2],
[7, 3],
[12, 1],
])
expect(offsetTree).toEqual([
{ offset: 0, index: 0, size: 1 },
{ offset: 5, index: 5, size: 2 },
{ offset: 9, index: 7, size: 3 },
{ offset: 24, index: 12, size: 1 },
])
})
it('removes obsolete ranges', () => {
const state = initialSizeState()
const { sizeTree, offsetTree } = sizeStateReducer(state, [
[
{ startIndex: 0, endIndex: 0, size: 1 },
{ startIndex: 5, endIndex: 9, size: 2 },
{ startIndex: 7, endIndex: 11, size: 3 },
{ startIndex: 3, endIndex: 12, size: 1 },
],
[],
mockLogger,
])
expect(toKV(sizeTree)).toEqual([[0, 1]])
expect(offsetTree).toEqual([{ index: 0, size: 1, offset: 0 }])
})
it('handles subsequent insertions correctly (bug)', () => {
const state = initialSizeState()
let nextState = sizeStateReducer(state, [[{ startIndex: 0, endIndex: 0, size: 158 }], [], mockLogger])
expect(ranges(nextState.sizeTree)).toEqual([{ start: 0, end: Infinity, value: 158 }])
nextState = sizeStateReducer(nextState, [[{ startIndex: 1, endIndex: 1, size: 206 }], [], mockLogger])
expect(ranges(nextState.sizeTree)).toEqual([
{ start: 0, end: 0, value: 158 },
{ start: 1, end: 1, value: 206 },
{ start: 2, end: Infinity, value: 158 },
])
nextState = sizeStateReducer(nextState, [[{ startIndex: 3, endIndex: 3, size: 182 }], [], mockLogger])
expect(ranges(nextState.sizeTree)).toEqual([
{ start: 0, end: 0, value: 158 },
{ start: 1, end: 1, value: 206 },
{ start: 2, end: 2, value: 158 },
{ start: 3, end: 3, value: 182 },
{ start: 4, end: Infinity, value: 158 },
])
nextState = sizeStateReducer(nextState, [
[
{
startIndex: 4,
endIndex: 4,
size: 206,
},
],
[],
mockLogger,
])
expect(ranges(nextState.sizeTree)).toEqual([
{ start: 0, end: 0, value: 158 },
{ start: 1, end: 1, value: 206 },
{ start: 2, end: 2, value: 158 },
{ start: 3, end: 3, value: 182 },
{ start: 4, end: 4, value: 206 },
{ start: 5, end: Infinity, value: 158 },
])
})
it('handles subsequent insertions correctly (bug #2)', () => {
const state = initialSizeState()
const { sizeTree } = sizeStateReducer(state, [
[
{ startIndex: 0, endIndex: 0, size: 206 },
{ startIndex: 0, endIndex: 0, size: 230 },
{ startIndex: 1, endIndex: 1, size: 158 },
{ startIndex: 3, endIndex: 3, size: 182 },
{ startIndex: 4, endIndex: 4, size: 158 },
{ startIndex: 5, endIndex: 5, size: 158 },
{ startIndex: 6, endIndex: 6, size: 230 },
],
[],
mockLogger,
])
expect(ranges(sizeTree)).toEqual([
{ start: 0, end: 0, value: 230 },
{ start: 1, end: 1, value: 158 },
{ start: 2, end: 2, value: 206 },
{ start: 3, end: 3, value: 182 },
{ start: 4, end: 5, value: 158 },
{ start: 6, end: 6, value: 230 },
{ start: 7, end: Infinity, value: 206 },
])
})
it('finds the offset of a given index (simple tree)', () => {
let state = initialSizeState()
state = sizeStateReducer(state, [[{ startIndex: 0, endIndex: 0, size: 30 }], [], mockLogger])
expect(offsetOf(10, state.offsetTree)).toBe(300)
})
it('finds the offset of a given index (complex tree)', () => {
let state = initialSizeState()
state = sizeStateReducer(state, [[{ startIndex: 0, endIndex: 0, size: 30 }], [], mockLogger])
state = sizeStateReducer(state, [[{ startIndex: 0, endIndex: 4, size: 20 }], [], mockLogger])
expect(offsetOf(10, state.offsetTree)).toBe(250)
})
it('builds correct index tree', () => {
let state = initialSizeState()
for (let index = 0; index < 5; index++) {
state = sizeStateReducer(state, [[{ startIndex: index, endIndex: index, size: index % 2 ? 50 : 30 }], [], mockLogger])
}
const { sizeTree, offsetTree } = state
expect(toKV(sizeTree)).toHaveLength(5)
expect(offsetTree).toHaveLength(5)
})
it('builds correct index tree (reverse)', () => {
let state = initialSizeState()
for (let index = 4; index >= 0; index--) {
state = sizeStateReducer(state, [[{ startIndex: index, endIndex: index, size: index % 2 ? 50 : 30 }], [], mockLogger])
}
const { offsetTree, sizeTree } = state
expect(toKV(sizeTree)).toHaveLength(5)
expect(offsetTree).toHaveLength(5)
})
describe('group indices', () => {
it('merges groups and items if a single size is reported', () => {
let state = initialSizeState()
state = sizeStateReducer(state, [[{ startIndex: 0, endIndex: 1, size: 30 }], [0, 6, 11], mockLogger])
expect(toKV(state.sizeTree)).toEqual([[0, 30]])
expect(state.offsetTree).toEqual([{ index: 0, size: 30, offset: 0 }])
})
it('fills in the group sizes when 2 item sizes is reported', () => {
let state = initialSizeState()
state = sizeStateReducer(state, [
[
{ startIndex: 0, endIndex: 0, size: 30 },
{ startIndex: 1, endIndex: 1, size: 20 },
],
[0, 6, 11],
mockLogger,
])
expect(toKV(state.sizeTree)).toEqual([
[0, 30],
[1, 20],
[6, 30],
[7, 20],
[11, 30],
[12, 20],
])
expect(state.offsetTree).toEqual([
{ offset: 0, index: 0, size: 30 },
{ offset: 30, index: 1, size: 20 },
{ offset: 130, index: 6, size: 30 },
{ offset: 160, index: 7, size: 20 },
{ offset: 240, index: 11, size: 30 },
{ offset: 270, index: 12, size: 20 },
])
})
})
})
describe('size engine', () => {
it('publishes list refreshes', () => {
const { sizeRanges, totalCount, listRefresh } = init(sizeSystem)
publish(totalCount, 10)
const sub = jest.fn()
subscribe(listRefresh, sub)
expect(sub).toHaveBeenCalledTimes(0)
publish(sizeRanges, [{ startIndex: 0, endIndex: 0, size: 1 }])
expect(sub).toHaveBeenCalledTimes(1)
expect(sub).toHaveBeenCalledWith(true)
publish(sizeRanges, [{ startIndex: 0, endIndex: 0, size: 1 }])
expect(sub).toHaveBeenCalledTimes(2)
expect(sub).toHaveBeenCalledWith(false)
})
describe('group indices', () => {
it('starts with dummy valued groupOffsetTree', () => {
const { groupIndices, sizes } = init(sizeSystem)
publish(groupIndices, [0, 6, 11])
expect(getValue(sizes).groupIndices).toEqual([0, 6, 11])
expect(toKV(getValue(sizes).groupOffsetTree)).toEqual([
[0, 0],
[6, 1],
[11, 2],
])
})
it('creates correct groupOffsetTree when group and item size is known', () => {
const { sizeRanges, groupIndices, sizes } = init(sizeSystem)
publish(groupIndices, [0, 6, 11])
publish(sizeRanges, [
{ startIndex: 0, endIndex: 0, size: 30 },
{ startIndex: 1, endIndex: 5, size: 20 },
])
publish(sizeRanges, [])
expect(toKV(getValue(sizes).groupOffsetTree)).toEqual([
[0, 0],
[6, 130],
[11, 240],
])
})
it('extends existing sizes when new groups are pushed', () => {
const { sizeRanges, groupIndices, sizes } = init(sizeSystem)
publish(groupIndices, [0, 6, 11])
publish(sizeRanges, [
{ startIndex: 0, endIndex: 0, size: 30 },
{ startIndex: 1, endIndex: 5, size: 20 },
])
publish(sizeRanges, [])
expect(toKV(getValue(sizes).groupOffsetTree)).toEqual([
[0, 0],
[6, 130],
[11, 240],
])
publish(groupIndices, [0, 6, 11, 15, 20])
expect(toKV(getValue(sizes).groupOffsetTree)).toEqual([
[0, 0],
[6, 130],
[11, 240],
[15, 330],
[20, 430], // this should be 440, but updatin the group does not propagade the known group size to newly introduced groups.
])
})
it('creates correct groupOffsetTree when groups are the same as items', () => {
const { sizeRanges, groupIndices, sizes } = init(sizeSystem)
publish(groupIndices, [0, 6, 11])
publish(sizeRanges, [{ startIndex: 0, endIndex: 1, size: 20 }])
publish(sizeRanges, [])
expect(toKV(getValue(sizes).groupOffsetTree)).toEqual([
[0, 0],
[6, 120],
[11, 220],
])
})
})
describe('unshifting', () => {
it('unshifts known sizes and offsets', () => {
const { sizes, sizeRanges, unshiftWith } = init(sizeSystem)
publish(sizeRanges, [
{ startIndex: 0, endIndex: 0, size: 30 },
{ startIndex: 1, endIndex: 5, size: 20 },
])
expect(toKV(getValue(sizes).sizeTree)).toEqual([
[0, 30],
[1, 20],
[6, 30],
])
expect(getValue(sizes).offsetTree).toEqual([
{ offset: 0, index: 0, size: 30 },
{ offset: 30, index: 1, size: 20 },
{ offset: 130, index: 6, size: 30 },
])
publish(unshiftWith, 5)
expect(toKV(getValue(sizes).sizeTree)).toEqual([
[0, 30],
[6, 20],
[11, 30],
])
expect(getValue(sizes).offsetTree).toEqual([
{ offset: 0, index: 0, size: 30 },
{ offset: 180, index: 6, size: 20 },
{ offset: 280, index: 11, size: 30 },
])
})
it('decreasing the first item index unshifts items', () => {
const { unshiftWith, firstItemIndex } = init(sizeSystem)
const sub = jest.fn()
subscribe(unshiftWith, sub)
publish(firstItemIndex, 150)
publish(firstItemIndex, 100)
expect(sub).toHaveBeenCalledTimes(1)
expect(sub).toHaveBeenCalledWith(50)
})
})
it('trims the sizes when total count decreases', () => {
const { sizeRanges, totalCount, sizes } = init(sizeSystem)
publish(totalCount, 5)
publish(sizeRanges, [{ startIndex: 0, endIndex: 0, size: 1 }])
publish(sizeRanges, [{ startIndex: 3, endIndex: 3, size: 3 }])
publish(sizeRanges, [{ startIndex: 4, endIndex: 4, size: 2 }])
publish(totalCount, 4)
expect(getValue(sizes)).toMatchObject({ lastIndex: 4, lastOffset: 6, lastSize: 1 })
})
it('trims the sizes when total count decreases (case 2)', () => {
const { sizeRanges, totalCount, sizes } = init(sizeSystem)
publish(totalCount, 9)
publish(sizeRanges, [{ startIndex: 0, endIndex: 0, size: 1 }])
publish(sizeRanges, [{ startIndex: 3, endIndex: 6, size: 3 }])
publish(totalCount, 5)
expect(getValue(sizes)).toMatchObject({ lastIndex: 5, lastOffset: 9, lastSize: 1 })
})
it('trims the sizes when total count decreases (case 3)', () => {
const { sizeRanges, totalCount, sizes } = init(sizeSystem)
publish(totalCount, 9)
publish(sizeRanges, [{ startIndex: 0, endIndex: 0, size: 1 }])
publish(sizeRanges, [{ startIndex: 3, endIndex: 6, size: 3 }])
publish(totalCount, 3)
expect(getValue(sizes)).toMatchObject({ lastIndex: 0, lastOffset: 0, lastSize: 1 })
})
})
describe('ranges within offsets', () => {
const offsetTree = [
{ offset: 0, index: 0, size: 1 },
{ offset: 3, index: 3, size: 2 },
{ offset: 13, index: 8, size: 1 },
{ offset: 14, index: 9, size: 2 },
{ offset: 18, index: 11, size: 1 },
]
it('gets the items in the given offset', () => {
expect(rangesWithinOffsets(offsetTree, 8, 15)).toEqual([
{ start: 3, end: 7, value: { offset: 3, index: 3, size: 2 } },
{ start: 8, end: 8, value: { offset: 13, index: 8, size: 1 } },
{ start: 9, end: Infinity, value: { offset: 14, index: 9, size: 2 } },
])
})
it('gets the items in the given offset with minimum index constraint', () => {
expect(rangesWithinOffsets(offsetTree, 8, 15, 8)).toEqual([
{ start: 8, end: 8, value: { offset: 13, index: 8, size: 1 } },
{ start: 9, end: Infinity, value: { offset: 14, index: 9, size: 2 } },
])
})
})
/*
describe.only('benchmarks', () => {
const COUNT = 20000
const JAGGED = 4
it('handles jagged list', () => {
const t0 = performance.now()
const { sizeRanges, totalCount } = init(sizeSystem)
publish(totalCount, COUNT)
publish(sizeRanges, [{ startIndex: 0, endIndex: 0, size: 2 }])
for (let index = 1; index < COUNT; index += JAGGED) {
publish(sizeRanges, [{ startIndex: index, endIndex: index, size: 1 }])
}
const t1 = performance.now()
console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to build jagged list:')
expect(true).toBeTruthy()
})
it('handles jagged reverse list', () => {
const t0 = performance.now()
const { sizeRanges, totalCount } = init(sizeSystem)
publish(totalCount, COUNT)
publish(sizeRanges, [{ startIndex: 0, endIndex: 0, size: 2 }])
let count = 0
for (let index = COUNT - 1; index > 0; index -= JAGGED) {
count++
publish(sizeRanges, [{ startIndex: index, endIndex: index, size: 1 }])
}
const t1 = performance.now()
console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to build reverse jagged list, average', ((t1 - t0) / count).toFixed(5))
expect(true).toBeTruthy()
})
})
*/ | the_stack |
module Music {
export enum WaveType {
Sine = 0,
HalfSine = 1,
AbsSign = 2,
PulseSign = 3,
SineEven = 4,
AbsSineEven = 5,
Square = 6,
DerivedSquare = 7
}
export enum KeyState {
Off,
Attack,
Sustain,
Decay,
Release
}
export class OscDesc {
public Tremolo: boolean = false;
public Vibrato: boolean = false;
public SoundSustaining: boolean = true;
public KeyScaling: boolean = false;
public Multiplication: number = 1.0;
public KeyScaleLevel: number = 0.0;
public OutputLevel: number = 1.0;
public AttackRate: number = 0;
public DecayRate: number = 0;
public SustainLevel: number = 0;
public ReleaseRate: number = 0;
public WaveForm: WaveType = WaveType.Sine;
public Wave: number[] = [];
}
export class OscState {
public Config: OscDesc = new OscDesc();
public State: KeyState = KeyState.Off;
public Volume: number = 0;
public EnvelopeStep: number = 0;
public Angle: number = 0;
}
class Channel {
public A: OscState = new OscState();
public B: OscState = new OscState();
public Additive: boolean = false;
public Feedback: number = 0;
public FreqNum: number = 0.0;
public BlockNum: number = 0.0;
public Output0: number = 0.0;
public Output1: number = 0.0;
public M1: number = 0.0;
public M2: number = 0.0;
public FeedbackFactor: number = 0.0;
public ProcessFunc: (c: Channel) => number;
}
export class OPL implements Sounds.PlayerAudioSource {
private channels: Channel[];
private sampleRate: number = 44100;
private src: Player = null;
private timeSinceNote: number = 0;
private noteTickRate: number = 5 / 1000.0;
private time: number = 0.0;
private synthTime: number = 0.0;
private timePassed: number = 0.0;
private VMin: number = -96.0;
private VMax: number = 0.0;
private node: ScriptProcessorNode;
private waves: number[][] = [];
private sampleCount: number = 1024;
constructor(llap: Sounds.LowLevelAudioProvider) {
this.channels = [];
var waveSin: number[] = [];
var waveHalfSin: number[] = [];
var waveAbsSign: number[] = [];
var wavePulseSign: number[] = [];
var waveSineEven: number[] = [];
var waveAbsSineEven: number[] = [];
var waveSquare: number[] = [];
var waveDerivedSquare: number[] = [];
for (var i = 0; i < this.sampleCount; i++) {
var angle = 2 * Math.PI * i / this.sampleCount;
var s = Math.sin(angle);
waveSin.push(s);
waveHalfSin.push(Math.max(s, 0.0));
waveAbsSign.push(Math.abs(s));
wavePulseSign.push(angle % 6.28 < 1.57 ? s : 0.0);
waveSineEven.push(angle % 12.56 < 6.28 ? s : 0.0);
waveAbsSineEven.push(angle % 12.56 < 6.28 ? Math.abs(s) : 0.0);
waveSquare.push(s > 0.0 ? 1.0 : 0.0);
waveDerivedSquare.push(s > 0.0 ? 1.0 : 0.0);
}
this.waves.push(waveSin);
this.waves.push(waveHalfSin);
this.waves.push(waveAbsSign);
this.waves.push(wavePulseSign);
this.waves.push(waveSineEven);
this.waves.push(waveAbsSineEven);
this.waves.push(waveSquare);
this.waves.push(waveDerivedSquare);
for (var i = 0; i < 15; i++) {
this.channels.push(new Channel());
this.channels[i].ProcessFunc = this.processChannelOutputFM;
}
this.sampleRate = 44100;
llap.runPlayer(this, false);
}
public setSource(mp: Player) {
this.src = mp;
for (var i = 0; i < this.channels.length; i++) {
this.stopNote(i);
}
}
public setChannelConfig(n: number, a: OscDesc, b: OscDesc, isAdditive: boolean, feedbackAmt: number) {
if (n >= this.channels.length) {
return;
}
a.Wave = this.waves[a.WaveForm];
b.Wave = this.waves[b.WaveForm];
this.channels[n].A.Config = a;
this.channels[n].B.Config = b;
this.channels[n].Additive = isAdditive;
this.channels[n].Feedback = feedbackAmt;
var v = 0.0;
var feedbackFactor = feedbackAmt > 0 ? Math.pow(2.0, feedbackAmt + 8) : 0;
var radiansPerWave = 2 * Math.PI;
var dbuPerWave = 1024 * 16.0;
var volAsDbu = 1.0 * 0x4000 * 0x10000 * 1.0 / 0x4000;
var m2 = radiansPerWave * volAsDbu / dbuPerWave;
var m1 = m2 / 2.0 / 0x10000;
this.channels[n].M1 = m1;
this.channels[n].M2 = m2;
this.channels[n].FeedbackFactor = feedbackFactor;
this.channels[n].ProcessFunc = isAdditive ? this.processChannelOutputAdditive : this.processChannelOutputFM;
}
public setChannelVolume(n: number, v: number) {
if (n >= this.channels.length) {
return;
}
this.channels[n].B.Config.OutputLevel = v;
}
public startNote(channel: number, freqNum: number, blockNum: number): void {
var chan = this.channels[channel];
function configureOSC(osc: OscState) {
if (chan.FreqNum == freqNum && chan.BlockNum == blockNum && osc.State == KeyState.Sustain) {
return;
}
osc.State = KeyState.Attack;
osc.EnvelopeStep = 0;
}
configureOSC(chan.A);
configureOSC(chan.B);
chan.FreqNum = freqNum;
chan.BlockNum = blockNum;
}
public stopNote(channel: number) {
var chan = this.channels[channel];
function configureOSC(osc: OscState) {
if (osc.State == KeyState.Off) {
return;
}
osc.State = KeyState.Release;
}
configureOSC(chan.A);
configureOSC(chan.B);
}
public fillAudioBuffer(buffer: Float32Array): boolean {
var synthOut = 0.0;
var gain = this.src !== null ? this.src.getGain() : 0.0;
if (this.src == null) {
for (var i = 0; i < buffer.length; i++) {
buffer[i] = 0;
}
return true;
}
this.timePassed = 1.0 / this.sampleRate;
for (var i = 0; i < buffer.length; i++) {
this.timeSinceNote += this.timePassed;
if (this.timeSinceNote > this.noteTickRate) {
this.src.readNote();
this.timeSinceNote -= this.noteTickRate;
}
this.time += this.timePassed;
this.synthTime += this.timePassed;
while (this.synthTime >= OPLConstants.SampleTime) {
synthOut = 0.0;
for (var j = 0; j < this.channels.length; j++) {
synthOut += this.channels[j].ProcessFunc.call(this, this.channels[j]);
}
this.synthTime -= OPLConstants.SampleTime;
}
buffer[i] = synthOut / 2.0 * gain;
}
return true;
}
private processChannelOutputAdditive(c: Channel): number {
var a = this.processOsc(c.A, c.FreqNum, c.BlockNum, (c.Output0 + c.Output1) * c.FeedbackFactor * c.M1);
var b = this.processOsc(c.B, c.FreqNum, c.BlockNum, 0.0);
c.Output1 = c.Output0;
c.Output0 = a;
return a + b;
}
private processChannelOutputFM(c: Channel): number {
var a = this.processOsc(c.A, c.FreqNum, c.BlockNum, (c.Output0 + c.Output1) * c.FeedbackFactor * c.M1);
var b = this.processOsc(c.B, c.FreqNum, c.BlockNum, a * c.M2);
c.Output1 = c.Output0;
c.Output0 = a;
return b;
}
private processOsc(osc: OscState, freqNum: number, blockNum: number, modulator: number): number {
var state = osc.State;
var conf = osc.Config;
if (state == KeyState.Off) {
return 0.0;
}
//TODO: Proper KEYBOARD SPLIT SECTION Implementation - pg.43
//Actual OutputLevel
//Actual KSR/KSS etc
//Feedback modulation
//Tremelo
//Vibrato
var keyScaleNum = blockNum * 2 + (freqNum >> 7);
var rof = conf.KeyScaling ? keyScaleNum : Math.floor(keyScaleNum / 4);
function getRate(n: number) {
return Math.min(n > 0 ? rof + n * 4 : 0, 63);
}
switch (osc.State) {
case KeyState.Attack:
var rate = getRate(conf.AttackRate);
var timeToAttack = OPLConstants.AttackRates[rate];
if (timeToAttack == 0) {
osc.Volume = this.VMax;
osc.EnvelopeStep = 0;
osc.State = KeyState.Decay;
} else if (timeToAttack == null) {
osc.State = KeyState.Off;
} else {
var p = 3.0;
var steps = Math.floor(timeToAttack / 1000.0 / OPLConstants.SampleTime);
osc.Volume = -96.0 * Math.pow((steps - osc.EnvelopeStep) / steps, p);
osc.EnvelopeStep++;
if (osc.EnvelopeStep >= steps) {
osc.EnvelopeStep = 0;
osc.Volume = this.VMax;
osc.State = KeyState.Decay;
}
}
break;
case KeyState.Decay:
var rate = getRate(conf.DecayRate);
var timeToDecay = OPLConstants.DecayRates[rate];
if (timeToDecay === 0) {
osc.Volume = conf.SustainLevel;
osc.EnvelopeStep = 0;
osc.State = KeyState.Sustain;
} else if (timeToDecay !== null) {
var steps = Math.floor(timeToDecay / 1000.0 / OPLConstants.SampleTime);
var decreaseAmt = conf.SustainLevel / steps;
osc.Volume += decreaseAmt;
osc.EnvelopeStep++;
if (osc.EnvelopeStep >= steps) {
osc.EnvelopeStep = 0;
osc.State = KeyState.Sustain;
}
}
break;
case KeyState.Sustain:
if (!conf.SoundSustaining) {
osc.State = KeyState.Release;
}
break;
case KeyState.Release:
var rate = getRate(conf.ReleaseRate);
var timeToRelease = OPLConstants.DecayRates[rate];
var steps = Math.floor(timeToRelease / 1000.0 / OPLConstants.SampleTime);
var decreaseAmt = (this.VMin - conf.SustainLevel) / steps;
osc.Volume += decreaseAmt;
osc.EnvelopeStep++;
if (osc.EnvelopeStep == steps) {
osc.Volume = this.VMin;
osc.State = KeyState.Off;
}
break;
}
var ksDamping: number = 0;
if (osc.Config.KeyScaleLevel > 0) {
var kslm = OPLConstants.KeyScaleMultipliers[conf.KeyScaleLevel];
ksDamping = -kslm * OPLConstants.KeyScaleLevels[blockNum][freqNum >> 6];
}
var freq = OPLConstants.FreqStarts[blockNum] + OPLConstants.FreqSteps[blockNum] * freqNum;
freq *= (conf.Multiplication == 0 ? 0.5 : conf.Multiplication);
var vib = conf.Vibrato ? Math.cos(this.time * 2 * Math.PI) * 0.00004 + 1.0 : 1.0;
osc.Angle += OPLConstants.SampleTime * 2 * Math.PI * freq * vib;
var angle = osc.Angle + modulator;
var a2 = Math.abs(angle) % (2 * Math.PI);
var wave = conf.Wave[Math.floor(a2 * this.sampleCount / 2 / Math.PI)];
var tremolo = conf.Tremolo ? Math.abs(Math.cos(this.time * Math.PI * 3.7)) * 1 : 0.0;
return wave * Math.pow(10.0, (osc.Volume + conf.OutputLevel + tremolo + ksDamping) / 10.0);
}
}
} | the_stack |
import { JoinType, QueryType, WhereType } from "./querybuilder.ts";
import { testQueryBuilder } from "./testutils.ts";
import { Q, QueryOperator } from "./q.ts";
// Where
testQueryBuilder(
"basic `where`",
(query) => query.where("email", "a@b.com"),
{
wheres: [{
type: WhereType.Default,
column: "email",
expression: Q.eq("a@b.com"),
}],
},
);
testQueryBuilder(
"`where` with custom expression",
(query) => query.where("age", Q.gt(16)),
{
wheres: [{
type: WhereType.Default,
column: "age",
expression: Q.gt(16),
}],
},
);
testQueryBuilder(
"multiple `where` clauses",
(query) =>
query
.where("email", Q.eq("a@b.com"))
.where("age", Q.gt(16))
.where("is_active", Q.eq(true))
.where("birthday", Q.eq(new Date("7 July, 2020"))),
{
wheres: [{
type: WhereType.Default,
column: "email",
expression: Q.eq("a@b.com"),
}, {
type: WhereType.Default,
column: "age",
expression: Q.gt(16),
}, {
type: WhereType.Default,
column: "is_active",
expression: Q.eq(true),
}, {
type: WhereType.Default,
column: "birthday",
expression: {
operator: QueryOperator.Equal,
value: new Date("7 July, 2020"),
},
}],
},
);
testQueryBuilder(
"`or`",
(query) => query.or("email", Q.eq("a@b.com")),
{
wheres: [{
type: WhereType.Or,
column: "email",
expression: Q.eq("a@b.com"),
}],
},
);
testQueryBuilder(
"`not`",
(query) => query.not("email", Q.eq("a@b.com")),
{
wheres: [{
type: WhereType.Not,
column: "email",
expression: Q.eq("a@b.com"),
}],
},
);
testQueryBuilder(
"`or` and `not`",
(query) =>
query
.where("email", Q.eq("a@b.com"))
.or("name", Q.like("%john%"))
.not("age", Q.gt(16)),
{
wheres: [{
type: WhereType.Default,
column: "email",
expression: Q.eq("a@b.com"),
}, {
type: WhereType.Or,
column: "name",
expression: Q.like("%john%"),
}, {
type: WhereType.Not,
column: "age",
expression: Q.gt(16),
}],
},
);
testQueryBuilder(
"`distinct` should enable distinct select",
(query) => query.distinct(),
{ isDistinct: true },
);
// Count
testQueryBuilder(
"`count` should count records with given conditions",
(query) => query.count("name"),
{ counts: [{ columns: ["name"], distinct: false }] },
);
testQueryBuilder(
"`count` should count with alias",
(query) => query.count("name", "count"),
{ counts: [{ columns: ["name"], as: "count", distinct: false }] },
);
testQueryBuilder(
"`countDistinct` should count with distinct",
(query) => query.countDistinct("name"),
{ counts: [{ columns: ["name"], distinct: true }] },
);
testQueryBuilder(
"`countDistinct` should count with distinct and alias",
(query) => query.countDistinct("name", "count"),
{ counts: [{ columns: ["name"], as: "count", distinct: true }] },
);
// Pagination
testQueryBuilder(
"`limit` should set the record limit",
(query) => query.limit(10),
{ limit: 10 },
);
testQueryBuilder(
"`offset` should set the number of records to skip",
(query) => query.offset(5),
{ offset: 5 },
);
testQueryBuilder(
"`limit` and `offset`",
(query) => query.limit(7).offset(14),
{ limit: 7, offset: 14 },
);
testQueryBuilder(
"`first` should be the shortcut for limit(1)",
(query) => query.first(),
{ limit: 1 },
);
// Select
testQueryBuilder(
"`select` should add the list of all selected columns",
(query) => query.select("email"),
{ columns: ["email"] },
);
testQueryBuilder(
"`select` multiple columns",
(query) => query.select("email").select("age").select("is_active"),
{ columns: ["email", "age", "is_active"] },
);
testQueryBuilder(
"`select` multiple columns with a single method",
(query) => query.select("email", "age", "is_active"),
{ columns: ["email", "age", "is_active"] },
);
testQueryBuilder(
"`select` multiple columns with aliases",
(query) => query.select(["email", "my_email"], ["age", "my_age"]),
{ columns: [["email", "my_email"], ["age", "my_age"]] },
);
// Group by
testQueryBuilder(
"`groupBy` should add the list of all grouped columns",
(query) => query.groupBy("email"),
{ groupBy: ["email"] },
);
testQueryBuilder(
"`groupBy` multiple columns",
(query) => query.groupBy("email").groupBy("age").groupBy("is_active"),
{ groupBy: ["email", "age", "is_active"] },
);
testQueryBuilder(
"`groupBy` multiple columns with a single method",
(query) => query.groupBy("email", "age", "is_active"),
{ groupBy: ["email", "age", "is_active"] },
);
// Having
testQueryBuilder(
"basic `having`",
(query) => query.having("email", "a@b.com"),
{
havings: [{
column: "email",
expression: Q.eq("a@b.com"),
type: WhereType.Default,
}],
},
);
testQueryBuilder(
"`having` with custom expression",
(query) => query.having("age", Q.gt(16)),
{
havings: [{
column: "age",
expression: Q.gt(16),
type: WhereType.Default,
}],
},
);
testQueryBuilder(
"multiple `having` clauses",
(query) =>
query
.having("email", Q.eq("a@b.com"))
.having("age", Q.gt(16))
.having("is_active", Q.eq(true))
.having("birthday", Q.eq(new Date("7 July, 2020"))),
{
havings: [{
column: "email",
expression: Q.eq("a@b.com"),
type: WhereType.Default,
}, {
column: "age",
expression: Q.gt(16),
type: WhereType.Default,
}, {
column: "is_active",
expression: Q.eq(true),
type: WhereType.Default,
}, {
column: "birthday",
expression: Q.eq(new Date("7 July, 2020")),
type: WhereType.Default,
}],
},
);
// Joins
testQueryBuilder(
"basic `innerJoin`",
(query) => query.innerJoin("companies", "users.company_id", "companies.id"),
{
joins: [{
type: JoinType.Inner,
table: "companies",
columnA: "users.company_id",
columnB: "companies.id",
}],
},
);
testQueryBuilder(
"basic `fullJoin`",
(query) => query.fullJoin("companies", "users.company_id", "companies.id"),
{
joins: [{
type: JoinType.Full,
table: "companies",
columnA: "users.company_id",
columnB: "companies.id",
}],
},
);
testQueryBuilder(
"basic `leftJoin`",
(query) => query.leftJoin("companies", "users.company_id", "companies.id"),
{
joins: [{
type: JoinType.Left,
table: "companies",
columnA: "users.company_id",
columnB: "companies.id",
}],
},
);
testQueryBuilder(
"basic `rightJoin`",
(query) => query.rightJoin("companies", "users.company_id", "companies.id"),
{
joins: [{
type: JoinType.Right,
table: "companies",
columnA: "users.company_id",
columnB: "companies.id",
}],
},
);
// Order by
testQueryBuilder(
"`order` should order the result",
(query) => query.order("age"),
{ orders: [{ column: "age", order: "ASC" }] },
);
testQueryBuilder(
"`order` should order the result with custom direction",
(query) => query.order("age", "DESC"),
{ orders: [{ column: "age", order: "DESC" }] },
);
testQueryBuilder(
"multiple `order`",
(query) => query.order("age", "DESC").order("created_at"),
{
orders: [{
column: "age",
order: "DESC",
}, {
column: "created_at",
order: "ASC",
}],
},
);
// Delete
testQueryBuilder(
"basic `delete`",
(query) => query.where("email", Q.eq("a@b.com")).delete(),
{
wheres: [{
type: WhereType.Default,
column: "email",
expression: Q.eq("a@b.com"),
}],
type: QueryType.Delete,
},
);
// Update
// TODO: throw an error if the `update` method gets called without any values
// TODO: throw an error if the `update` method gets called with an empty object
testQueryBuilder(
"basic `update`",
(query) =>
query
.where("email", Q.eq("a@b.com"))
.update({
name: "John",
age: 16,
is_active: true,
birthday: new Date("7 July, 2020"),
}),
{
wheres: [{
type: WhereType.Default,
column: "email",
expression: Q.eq("a@b.com"),
}],
values: {
name: "John",
age: 16,
is_active: true,
birthday: new Date("7 July, 2020"),
},
type: QueryType.Update,
},
);
// Insert
// TODO: throw an error if the `insert` method gets called without any values
// TODO: throw an error if the `insert` method gets called with an empty object
// TODO: throw an error if the `insert` method gets called with an empty array
// TODO: throw an error if the `insert` method gets called with an empty array of objects
testQueryBuilder(
"basic `insert`",
(query) =>
query.insert({
name: "John",
age: 16,
is_active: true,
birthday: new Date("7 July, 2020"),
}),
{
values: {
name: "John",
age: 16,
is_active: true,
birthday: new Date("7 July, 2020"),
},
type: QueryType.Insert,
},
);
testQueryBuilder(
"`insert` with multiple values",
(query) =>
query
.insert([{
name: "John",
age: 16,
is_active: true,
birthday: new Date("7 July, 2020"),
}, {
name: "Doe",
age: 17,
is_active: false,
birthday: new Date("8 July, 2020"),
}]),
{
values: [{
name: "John",
age: 16,
is_active: true,
birthday: new Date("7 July, 2020"),
}, {
name: "Doe",
age: 17,
is_active: false,
birthday: new Date("8 July, 2020"),
}],
type: QueryType.Insert,
},
);
testQueryBuilder(
"`insert` with returning all columns",
(query) => query.insert({ email: "a@b.com" }).returning("*"),
{
values: { email: "a@b.com" },
returning: ["*"],
type: QueryType.Insert,
},
);
testQueryBuilder(
"`insert` with returning several columns",
(query) => query.insert({ email: "a@b.com" }).returning("email", "age"),
{
values: { email: "a@b.com" },
returning: ["email", "age"],
type: QueryType.Insert,
},
);
// Replace
// TODO: throw an error if the `replace` method gets called without any values
// TODO: throw an error if the `replace` method gets called with an empty object
// TODO: throw an error if the `replace` method gets called with an empty array
// TODO: throw an error if the `replace` method gets called with an empty array of objects
testQueryBuilder(
"basic `replace`",
(query) =>
query.replace({
name: "John",
age: 16,
is_active: true,
birthday: new Date("7 July, 2020"),
}),
{
values: {
name: "John",
age: 16,
is_active: true,
birthday: new Date("7 July, 2020"),
},
type: QueryType.Replace,
},
);
testQueryBuilder(
"`replace` with returning all columns",
(query) => query.replace({ email: "a@b.com" }).returning("*"),
{
values: { email: "a@b.com" },
returning: ["*"],
type: QueryType.Replace,
},
);
testQueryBuilder(
"`replace` with returning several columns",
(query) => query.replace({ email: "a@b.com" }).returning("email", "age"),
{
values: { email: "a@b.com" },
returning: ["email", "age"],
type: QueryType.Replace,
},
); | the_stack |
import * as sinon from 'sinon'
import { clientHandler } from './client-handler'
import * as utils from './utils'
import * as assert from 'assert'
function getRecordData (clientExpression: string, recordName: string) {
return clientHandler.getClients(clientExpression).map((client) => client.record.records[recordName])
}
function getListData (clientExpression: string, listName: string) {
return clientHandler.getClients(clientExpression).map((client) => client.record.lists[listName])
}
const assert2 = {
deleted (clientExpression: string, recordName: string, called: boolean) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
if (called) {
sinon.assert.calledOnce(recordData.deleteCallback)
recordData.deleteCallback.resetHistory()
} else {
sinon.assert.notCalled(recordData.deleteCallback)
}
recordData.deleteCallback.resetHistory()
})
},
discarded (clientExpression: string, recordName: string, called: boolean) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
if (called) {
sinon.assert.calledOnce(recordData.discardCallback)
recordData.discardCallback.resetHistory()
} else {
sinon.assert.notCalled(recordData.discardCallback)
}
})
},
receivedUpdate (clientExpression: string, recordName: string, data: string) {
data = utils.parseData(data)
getRecordData(clientExpression, recordName).forEach((recordData) => {
sinon.assert.calledOnce(recordData.subscribeCallback)
sinon.assert.calledWith(recordData.subscribeCallback, data)
recordData.subscribeCallback.resetHistory()
})
},
receivedUpdateForPath (clientExpression: string, recordName: string, path: string, data: string) {
data = utils.parseData(data)
getRecordData(clientExpression, recordName).forEach((recordData) => {
sinon.assert.calledOnce(recordData.subscribePathCallbacks[path])
sinon.assert.calledWith(recordData.subscribePathCallbacks[path], data)
recordData.subscribePathCallbacks[path].resetHistory()
})
},
receivedNoUpdate (clientExpression: string, recordName: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
sinon.assert.notCalled(recordData.subscribeCallback)
})
},
receivedNoUpdateForPath (clientExpression: string, recordName: string, path: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
sinon.assert.notCalled(recordData.subscribePathCallbacks[path])
})
},
receivedRecordError (clientExpression: string, error: string, recordName: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
sinon.assert.calledWith(recordData.errorCallback, error)
recordData.errorCallback.resetHistory()
})
},
hasData (clientExpression: string, recordName: string, data: string) {
data = utils.parseData(data)
getRecordData(clientExpression, recordName).forEach((recordData) => {
assert.deepEqual(recordData.record.get(), data)
})
},
hasProviders (clientExpression: string, recordName: string, without: boolean) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
assert.deepEqual(recordData.record.hasProvider, !without)
})
},
hasDataAtPath (clientExpression: string, recordName: string, path: string, data: string) {
data = utils.parseData(data)
getRecordData(clientExpression, recordName).forEach((recordData) => {
assert.deepEqual(recordData.record.get(path), data)
})
},
writeAckSuccess (clientExpression: string, recordName: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
if (!recordData) { return }
sinon.assert.calledOnce(recordData.setCallback)
sinon.assert.calledWith(recordData.setCallback, null)
recordData.setCallback.resetHistory()
})
clientHandler.getClients(clientExpression).forEach((client) => {
if (!client.record.writeAcks) { return }
sinon.assert.calledOnce(client.record.writeAcks[recordName])
sinon.assert.calledWith(client.record.writeAcks[recordName], null)
client.record.writeAcks[recordName].resetHistory()
})
},
writeAckError (clientExpression: string, recordName: string, errorMessage: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
if (!recordData) { return }
sinon.assert.calledOnce(recordData.setCallback)
sinon.assert.calledWith(recordData.setCallback, errorMessage)
recordData.setCallback.resetHistory()
})
clientHandler.getClients(clientExpression).forEach((client) => {
if (!client.record.writeAcks) { return }
sinon.assert.calledOnce(client.record.writeAcks[recordName])
sinon.assert.calledWith(client.record.writeAcks[recordName], errorMessage)
client.record.writeAcks[recordName].resetHistory()
})
},
snapshotSuccess (clientExpression: string, recordName: string, data: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
sinon.assert.calledOnce(client.record.snapshotCallback)
sinon.assert.calledWith(client.record.snapshotCallback, null, utils.parseData(data))
client.record.snapshotCallback.resetHistory()
})
},
snapshotError (clientExpression: string, recordName: string, data: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
sinon.assert.calledOnce(client.record.snapshotCallback)
sinon.assert.calledWith(client.record.snapshotCallback, data.replace(/"/g, ''))
client.record.snapshotCallback.resetHistory()
})
},
headSuccess (clientExpression: string, recordName: string, data: number) {
clientHandler.getClients(clientExpression).forEach((client) => {
sinon.assert.calledOnce(client.record.headCallback)
sinon.assert.calledWith(client.record.headCallback, null, data)
client.record.headCallback.resetHistory()
})
},
headError (clientExpression: string, recordName: string, data: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
sinon.assert.calledOnce(client.record.headCallback)
sinon.assert.calledWith(client.record.headCallback, data.replace(/"/g, ''))
client.record.snapshotCallback.resetHistory()
})
},
has (clientExpression: string, recordName: string, expected: boolean) {
clientHandler.getClients(clientExpression).forEach((client) => {
sinon.assert.calledOnce(client.record.hasCallback)
sinon.assert.calledWith(client.record.hasCallback, null, expected)
client.record.hasCallback.resetHistory()
})
},
hasEntries (clientExpression: string, listName: string, data: string) {
data = utils.parseData(data)
getListData(clientExpression, listName).forEach((listData) => {
assert.deepEqual(listData.list.getEntries(), data)
})
},
addedNotified (clientExpression: string, listName: string, entryName: string) {
getListData(clientExpression, listName).forEach((listData) => {
sinon.assert.calledWith(listData.addedCallback, entryName)
})
},
removedNotified (clientExpression: string, listName: string, entryName: string) {
getListData(clientExpression, listName).forEach((listData) => {
sinon.assert.calledWith(listData.removedCallback, entryName)
})
},
movedNotified (clientExpression: string, listName: string, entryName: string) {
getListData(clientExpression, listName).forEach((listData) => {
sinon.assert.calledWith(listData.movedNotified, entryName)
})
},
listChanged (clientExpression: string, listName: string, data: string) {
data = utils.parseData(data)
getListData(clientExpression, listName).forEach((listData) => {
// sinon.assert.calledOnce( listData.subscribeCallback );
sinon.assert.calledWith(listData.subscribeCallback, data)
})
},
anonymousRecordContains (clientExpression: string, data: string) {
data = utils.parseData(data)
clientHandler.getClients(clientExpression).forEach((client) => {
assert.deepEqual(client.record.anonymousRecord.get(), data)
})
}
}
export const record = {
assert: assert2,
getRecord (clientExpression: string, recordName: string) {
const clients = clientHandler.getClients(clientExpression)
clients.forEach((client) => {
const recordData = {
record: client.client.record.getRecord(recordName),
discardCallback: sinon.spy(),
deleteSuccessCallback: sinon.spy(),
deleteCallback: sinon.spy(),
callbackError: sinon.spy(),
subscribeCallback: sinon.spy(),
errorCallback: sinon.spy(),
setCallback: undefined,
subscribePathCallbacks: {}
}
recordData.record.on('delete', recordData.deleteCallback)
recordData.record.on('error', recordData.errorCallback)
recordData.record.on('discard', recordData.discardCallback)
client.record.records[recordName] = recordData
})
},
subscribe (clientExpression: string, recordName: string, immediate: boolean) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
recordData.record.subscribe(recordData.subscribeCallback, !!immediate)
})
},
unsubscribe (clientExpression: string, recordName: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
recordData.record.unsubscribe(recordData.subscribeCallback)
})
},
subscribeWithPath (clientExpression: string, recordName: string, path: string, immediate: boolean) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
recordData.subscribePathCallbacks[path] = sinon.spy()
recordData.record.subscribe(path, recordData.subscribePathCallbacks[path], !!immediate)
})
},
unsubscribeFromPath (clientExpression: string, recordName: string, path: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
recordData.record.unsubscribe(path, recordData.subscribePathCallbacks[path])
})
},
discard (clientExpression: string, recordName: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
recordData.record.discard()
})
},
delete (clientExpression: string, recordName: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
recordData.record.delete(recordData.deleteSuccessCallback)
})
},
setupWriteAck (clientExpression: string, recordName: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
client.record.records[recordName].setCallback = sinon.spy()
})
},
set (clientExpression: string, recordName: string, data: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
if (recordData.setCallback) {
recordData.record.set(utils.parseData(data), recordData.setCallback)
} else {
recordData.record.set(utils.parseData(data))
}
})
},
setWithPath (clientExpression: string, recordName: string, path: string, data: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
if (recordData.setCallback) {
recordData.record.set(path, utils.parseData(data), recordData.setCallback)
} else {
recordData.record.set(path, utils.parseData(data))
}
})
},
erase (clientExpression: string, recordName: string, path: string) {
getRecordData(clientExpression, recordName).forEach((recordData) => {
if (recordData.setCallback) {
recordData.record.erase(path, recordData.setCallback)
} else {
recordData.record.erase(path)
}
})
},
setData (clientExpression: string, recordName: string, data: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
client.client.record.setData(recordName, utils.parseData(data))
})
},
setDataWithWriteAck (clientExpression: string, recordName: string, data: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
if (!client.record.writeAcks) {
client.record.writeAcks = {}
}
client.record.writeAcks[recordName] = sinon.spy()
client.client.record.setData(recordName, utils.parseData(data), client.record.writeAcks[recordName])
})
},
setDataWithPath (clientExpression: string, recordName: string, path: string, data: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
client.client.record.setData(recordName, path, utils.parseData(data))
})
},
snapshot (clientExpression: string, recordName: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
client.client.record.snapshot(recordName, client.record.snapshotCallback)
})
},
has (clientExpression: string, recordName: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
client.client.record.has(recordName, client.record.hasCallback)
})
},
head (clientExpression: string, recordName: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
client.client.record.head(recordName, client.record.headCallback)
})
},
/** ******************************************************************************************************************************
*********************************************************** Lists ************************************************************
********************************************************************************************************************************/
getList (clientExpression: string, listName: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
const listData = {
list: client.client.record.getList(listName),
discardCallback: sinon.spy(),
deleteCallback: sinon.spy(),
callbackError: sinon.spy(),
subscribeCallback: sinon.spy(),
addedCallback: sinon.spy(),
removedCallback: sinon.spy(),
movedCallback: sinon.spy()
}
listData.list.on('discard', listData.discardCallback)
listData.list.on('delete', listData.deleteCallback)
listData.list.on('entry-added', listData.addedCallback)
listData.list.on('entry-removed', listData.removedCallback)
listData.list.on('entry-moved', listData.movedCallback)
listData.list.subscribe(listData.subscribeCallback)
client.record.lists[listName] = listData
})
},
setEntries (clientExpression: string, listName: string, data: string) {
const entries = utils.parseData(data)
getListData(clientExpression, listName).forEach((listData) => {
listData.list.setEntries(entries)
})
},
addEntry (clientExpression: string, listName: string, entryName: string) {
getListData(clientExpression, listName).forEach((listData) => {
listData.list.addEntry(entryName)
})
},
removeEntry (clientExpression: string, listName: string, entryName: string) {
getListData(clientExpression, listName).forEach((listData) => {
listData.list.removeEntry(entryName)
})
},
/** ******************************************************************************************************************************
*********************************************************** ANONYMOUS RECORDS ************************************************************
********************************************************************************************************************************/
getAnonymousRecord (clientExpression: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
client.record.anonymousRecord = client.client.record.getAnonymousRecord()
})
},
setName (clientExpression: string, recordName: string) {
clientHandler.getClients(clientExpression).forEach((client) => {
client.record.anonymousRecord.setName(recordName)
})
}
} | the_stack |
import {
ArrayLiteralExpression,
ArrowFunction,
CallExpression,
ClassDeclaration,
Expression,
Identifier,
Node,
ObjectLiteralExpression,
Project,
PropertyAccessExpression,
SourceFile,
SpreadElement,
Type,
TypeChecker
} from 'ts-morph';
import { resolve, sep } from 'path';
import { evaluate } from 'ts-evaluator';
import { getSourceFileOrThrow } from './get-source-file-from-paths';
import { EMPTY_PATH } from '../generation/constants';
import { error } from '../utils/common.utils';
import { mergeRouteTrees } from './merge-route-trees';
import { logParsingWarning } from './log-parsing-worning';
export const getRouteModuleForRootExpressions: (
routerModuleClass: ClassDeclaration
) => ArrayLiteralExpression | null = (routerModuleClass: ClassDeclaration): ArrayLiteralExpression | null => {
const refs = routerModuleClass.findReferencesAsNodes();
// todo add check for Router.RouterModule.for....
const forRootExpressions = getRouterModuleCallExpressions(refs, 'forRoot');
if (forRootExpressions.length > 1) {
throw error('You have more than one RouterModule.forRoot expression');
}
const forRootExpression = forRootExpressions[0];
return findRouterModuleArgumentValue(forRootExpression);
};
const findRouterModuleArgumentValue = (routerExpr: CallExpression): ArrayLiteralExpression | null => {
const args = routerExpr.getArguments();
if (args.length === 0) {
const filePath = routerExpr.getSourceFile().getFilePath();
throw error(`RouterModule in ${filePath} hasn't arguments`);
}
const firstArg = args[0];
if (Node.isArrayLiteralExpression(firstArg)) {
return firstArg;
} else if (Node.isIdentifier(firstArg)) {
return tryFindVariableValue(firstArg, Node.isArrayLiteralExpression);
}
// todo for spread forRoot(...array)
return null;
};
const tryFindPropertyAccessExpressionValue = <T extends Node>(
expression: PropertyAccessExpression,
valueTypeChecker: (node: Node) => node is T
) => {
const id = expression.getNameNode();
return tryFindVariableValue(id, valueTypeChecker);
};
const tryFindVariableValue = <T extends Node>(
id: Identifier,
valueTypeChecker: (node: Node) => node is T
): T | null => {
const defs = id.getDefinitionNodes();
for (const def of defs) {
// expression.expression1.varName
if (Node.isInitializerExpressionGetable(def)) {
const initializer = def.getInitializer();
if (initializer && valueTypeChecker(initializer)) {
return initializer;
}
}
}
return null;
};
export const getRouterModuleCallExpressions: (
routeModules: Node[],
expression: RouterKit.Parse.RouterExpression
) => CallExpression[] = (routeModules: Node[], expression: RouterKit.Parse.RouterExpression): CallExpression[] => {
return routeModules
.map(ref => ref.getParent() as PropertyAccessExpression)
.filter(node => Node.isPropertyAccessExpression(node))
.filter(node => {
if (Node.hasName(node)) {
return node.getName() === expression;
}
return false;
})
.map(node => node.getParent() as CallExpression)
.filter(node => Node.isCallExpression(node));
};
export const parseRoutes = (
routes: ArrayLiteralExpression,
routerType: Type,
parsedModules: Set<Type>,
project: Project
): RouterKit.Parse.RouteTree => {
let root: RouterKit.Parse.RouteTree = {};
const elements = routes.getElements();
for (const el of elements) {
let parsedRoute: RouterKit.Parse.RouteTree | null = null;
if (Node.isObjectLiteralExpression(el)) {
parsedRoute = parseRoute(el, routerType, parsedModules, project);
} else if (Node.isIdentifier(el)) {
const value = tryFindVariableValue(el, Node.isObjectLiteralExpression);
if (value) {
parsedRoute = parseRoute(value, routerType, parsedModules, project);
}
}
if (parsedRoute) {
root = mergeRouteTrees(root, parsedRoute);
}
}
return root;
};
const parseRoute = (
route: ObjectLiteralExpression,
routerType: Type,
parsedModules: Set<Type>,
project: Project
): RouterKit.Parse.RouteTree | null => {
const root: RouterKit.Parse.RouteTree = {};
const typeChecker = project.getTypeChecker();
const path = readPath(route, typeChecker);
const routeName = path === '' ? EMPTY_PATH : path;
root[routeName] = {};
const sourceFile = route.getSourceFile();
const loadChildren = readLoadChildrenWithFullModulePath(route, sourceFile, typeChecker);
if (loadChildren) {
const lazyModule = getLazyModuleDeclaration(project, loadChildren);
const lazyModuleRouteTree = createModuleRouteTree(project, lazyModule, parsedModules, routerType);
root[routeName] = { ...lazyModuleRouteTree };
} else {
root[routeName] = readChildren(route, routerType, parsedModules, project);
}
return root;
};
const getLazyModuleDeclaration = (project: Project, loadChildren: RouterKit.Parse.LoadChildren): ClassDeclaration => {
const { path, moduleName } = loadChildren;
const pathWithExtension = path.endsWith('.ts') ? path : `${path}.ts`;
const sourceFile = getSourceFileOrThrow(project, pathWithExtension);
return sourceFile.getClassOrThrow(moduleName);
};
export const createProjectRouteTree = (
project: Project,
appModule: ClassDeclaration,
forRootExpr: ArrayLiteralExpression,
routerType: Type
): RouterKit.Parse.RouteTree => {
let routeTree: RouterKit.Parse.RouteTree = {};
const parsedModules = new Set<Type>();
const eagersTree = createModuleRouteTree(project, appModule, parsedModules, routerType);
routeTree = mergeRouteTrees(routeTree, eagersTree);
const parsedRoot = parseRoutes(forRootExpr, routerType, parsedModules, project);
return mergeRouteTrees(parsedRoot, routeTree);
};
const createModuleRouteTree = (
project: Project,
module: ClassDeclaration,
parsedModules: Set<Type>,
routerType: Type
): RouterKit.Parse.RouteTree => {
let root: RouterKit.Parse.RouteTree = {};
const eagerForChildExpr = findRouteChildren(routerType, module, parsedModules);
for (const forChildExpr of eagerForChildExpr) {
const routes = findRouterModuleArgumentValue(forChildExpr);
if (routes) {
const parsed = parseRoutes(routes, routerType, parsedModules, project);
root = mergeRouteTrees(root, parsed);
}
}
return root;
};
/**
* Get Module Declaration, parse imports, find route modules and parse them
*/
export const findRouteChildren = (
routerType: Type,
rootModule: ClassDeclaration,
parsedModules: Set<Type>
): CallExpression[] => {
const routerModules: CallExpression[] = [];
const modules = [rootModule];
while (modules.length) {
const currentModule = modules.shift() as ClassDeclaration;
if (currentModule !== rootModule && parsedModules.has(currentModule.getType())) {
continue;
}
const imports = getImportsFromModuleDeclaration(currentModule);
const { routerExpressions, moduleDeclarations } = divideRouterExpressionsAndModulesDeclarations(
imports,
routerType
);
if (!routerExpressions.length) {
parsedModules.add(currentModule.getType());
}
routerModules.push(...routerExpressions);
modules.unshift(...moduleDeclarations);
}
return routerModules;
};
// todo need refactoring
const divideRouterExpressionsAndModulesDeclarations = (
modules: Node[],
routerType: Type
): {
routerExpressions: CallExpression[];
moduleDeclarations: ClassDeclaration[];
} => {
const routerExpressions: CallExpression[] = [];
const moduleDeclarations: ClassDeclaration[] = [];
const isRouterType = isClassHasTheSameType.bind(null, routerType);
for (const node of modules) {
if (Node.isSpreadElement(node)) {
getModulesFromSpreadOperator(node).forEach(el => modules.push(el));
continue;
}
const parsedNode = getModuleDeclarationOrCallExpressionById(node, isRouterType);
if (parsedNode) {
Node.isCallExpression(parsedNode) ? routerExpressions.push(parsedNode) : moduleDeclarations.push(parsedNode);
}
}
return {
routerExpressions,
moduleDeclarations
};
};
const getModulesFromSpreadOperator = (node: SpreadElement): Node[] => {
const expression = node.getExpression();
if (!Node.isIdentifier(expression)) {
logParsingWarning(node);
return [];
}
const modules = tryFindVariableValue(node.getExpression() as Identifier, Node.isArrayLiteralExpression);
return modules ? modules.getElements() : [];
};
const getModuleDeclarationOrCallExpressionById = (
node: Node,
isRouter: (clazz: ClassDeclaration) => boolean
): ClassDeclaration | CallExpression | null => {
if (Node.isIdentifier(node)) {
const decl = findModuleDeclarationOrExpressionByIdentifier(node);
if (decl) {
if (Node.isClassDeclaration(decl)) {
return decl;
} else if (Node.isCallExpression(decl)) {
return getModuleDeclarationOrRouterExpressionFromCall(decl, isRouter);
}
}
} else if (Node.isCallExpression(node)) {
return getModuleDeclarationOrRouterExpressionFromCall(node, isRouter);
}
return null;
};
const getModuleDeclarationOrRouterExpressionFromCall = (
call: CallExpression,
isRouter: (clazz: ClassDeclaration) => boolean
): CallExpression | ClassDeclaration | null => {
const decl = getModuleDeclarationFromExpression(call);
if (decl) {
return isRouter(decl) ? call : decl;
}
return null;
};
const isClassHasTheSameType = (type: Type, clazz: ClassDeclaration): boolean => {
const classType = clazz.getType();
return classType === type;
};
/*
* return class from Module.forRoot/Module.forChild expressions
*/
export const getModuleDeclarationFromExpression = (callExpr: CallExpression): ClassDeclaration | null => {
const expr = callExpr.getExpression();
if (Node.isPropertyAccessExpression(expr)) {
const name = expr.getName();
if (name === 'forRoot' || 'forChild') {
const moduleName = expr.getExpression();
if (Node.isIdentifier(moduleName)) {
return findClassDeclarationByIdentifier(moduleName);
} else if (Node.isPropertyAccessExpression(moduleName)) {
return getClassIdentifierFromPropertyAccessExpression(moduleName);
}
}
}
console.error(`Can't find module name in expression: ${callExpr.getText()}`);
return null;
};
const getClassIdentifierFromPropertyAccessExpression = (node: PropertyAccessExpression): ClassDeclaration | null => {
const name = node.getNameNode();
if (Node.isIdentifier(name)) {
return findClassDeclarationByIdentifier(name);
} else {
throw error(`Can't parse PropertyAccessExpression ${node.getText()}`);
}
};
const getImportsFromModuleDeclaration = (module: ClassDeclaration): Node[] => {
const decorator = module.getDecorator('NgModule');
if (!decorator) {
return [];
}
const arg = decorator.getArguments()?.[0];
if (!arg) {
return [];
}
return parseImports(arg)?.getElements() || [];
};
const parseImports = (importsArg: Node): ArrayLiteralExpression | null => {
if (Node.isObjectLiteralExpression(importsArg)) {
const imports = getPropertyValue(importsArg, 'imports');
if (!imports) {
return null;
}
if (Node.isIdentifier(imports)) {
return tryFindVariableValue(imports, Node.isArrayLiteralExpression);
} else if (Node.isArrayLiteralExpression(imports)) {
return imports;
} // todo find other cases (imports: [...imports]
}
return null;
};
const readPath = (node: ObjectLiteralExpression, typeChecker: TypeChecker): string => {
const expression = getPropertyValue(node, 'path');
if (expression) {
const path = evaluateExpression(expression, typeChecker);
return typeof path === 'string' ? path : '/';
}
return '/';
};
const readChildren = (
node: ObjectLiteralExpression,
routerType: Type,
parsedModules: Set<Type>,
project: Project
): RouterKit.Parse.RouteTree => {
let root: RouterKit.Parse.RouteTree = {};
const expression = getPropertyValue(node, 'children');
if (expression && Node.isArrayLiteralExpression(expression)) {
const routes = parseRoutes(expression, routerType, parsedModules, project);
root = mergeRouteTrees(root, routes);
} // todo case, where children is a variable
return root;
};
export const readLoadChildrenWithFullModulePath = (
node: ObjectLiteralExpression,
currentSourceFile: SourceFile,
typeChecker: TypeChecker
): RouterKit.Parse.LoadChildren | null => {
const loadChildren = readLoadChildren(node, typeChecker);
if (!loadChildren) {
return null;
}
const { path } = loadChildren;
if (!path.startsWith(`.${sep}`)) {
return loadChildren;
}
const currentFilePath = currentSourceFile.getFilePath();
const reducedPath = currentFilePath.split(sep);
const currentDir = reducedPath.slice(0, reducedPath.length - 1).join(sep);
const fullPathToLazyModule = resolve(currentDir, path);
return { ...loadChildren, path: fullPathToLazyModule };
};
const readLoadChildren = (
node: ObjectLiteralExpression,
typeChecker: TypeChecker
): RouterKit.Parse.LoadChildren | null => {
const expression = getPropertyValue(node, 'loadChildren');
if (!expression) {
return null;
}
if (Node.isStringLiteral(expression)) {
return getOldLoadChildrenSyntaxPath(expression.getLiteralValue());
}
if (Node.isArrowFunction(expression)) {
const body = expression.getBody();
if (Node.isCallExpression(body)) {
return parseLoadChildrenFunction(body);
}
}
// loadChildren: 'foo' + '/' + 'bar'
const path = evaluateExpression(node, typeChecker);
return path ? getOldLoadChildrenSyntaxPath(path) : null;
};
const getOldLoadChildrenSyntaxPath = (str: string): RouterKit.Parse.LoadChildren | null => {
const [path, module] = str.split('#');
if (typeof path === 'string' && module) {
return { path, moduleName: module };
}
return null;
};
const parseLoadChildrenFunction = (fnNode: CallExpression): RouterKit.Parse.LoadChildren | null => {
const parsedLoadChildren: Partial<RouterKit.Parse.LoadChildren> = {};
const accessExpression = fnNode.getExpression();
if (Node.isPropertyAccessExpression(accessExpression)) {
const impExpr = accessExpression.getExpression();
if (Node.isCallExpression(impExpr)) {
const impArg = impExpr.getArguments()?.[0];
if (Node.isStringLiteral(impArg)) {
parsedLoadChildren.path = impArg.getLiteralText();
}
}
}
const args = fnNode.getArguments()?.[0];
if (args && Node.isArrowFunction(args)) {
return parseLazyModuleArrowFn(args);
}
const { path, moduleName } = parsedLoadChildren;
if (typeof path === 'string' && moduleName) {
return { path, moduleName };
}
return null;
};
const parseLazyModuleArrowFn = (node: ArrowFunction): RouterKit.Parse.LoadChildren | null => {
const body = node.getBody();
if (Node.isPropertyAccessExpression(body)) {
const module = body.getNameNode();
const clazz = findClassDeclarationByIdentifier(module);
if (clazz) {
return {
path: clazz.getSourceFile().getFilePath(),
moduleName: module.getText()
};
}
}
return null;
};
const evaluateExpression = (node: Expression, morphTypeChecker: TypeChecker): string | null => {
const compilerNode = node.compilerNode;
const typeChecker = morphTypeChecker.compilerObject;
// todo wait evaluate update
const result = evaluate({
node: compilerNode as any,
typeChecker: typeChecker as any
});
return result.success ? (result.value as string) : null;
};
const getPropertyValue = (node: ObjectLiteralExpression, property: string): Expression | null => {
const objectProperty = node.getProperty(property);
if (objectProperty && Node.isPropertyAssignment(objectProperty)) {
const initializer = objectProperty.getInitializer();
if (initializer && Node.isIdentifier(initializer)) {
return tryFindVariableValue(initializer, Node.isExpression);
} else if (initializer && Node.isPropertyAccessExpression(initializer)) {
return tryFindPropertyAccessExpressionValue(initializer, Node.isExpression);
}
return initializer || null;
}
return null;
};
export const getAppModule = (project: Project, path: string): ClassDeclaration => {
const sourceFile = project.getSourceFileOrThrow(path);
let bootstrapId: Identifier | undefined;
function findBootstrapModule(node: Node): void {
if (Node.isIdentifier(node) && node.getText() === 'bootstrapModule') {
bootstrapId = node;
} else {
node.forEachChild(findBootstrapModule);
}
}
sourceFile.forEachChild(findBootstrapModule);
if (!bootstrapId) {
throw error(`Can't find bootstrapModule expression in ${path}`);
}
const parent = bootstrapId?.getParentOrThrow();
const callExpresion = parent.getParentOrThrow();
if (Node.isCallExpression(callExpresion)) {
const module = callExpresion.getArguments()?.[0];
// todo when module is not class token
const declaration = findClassDeclarationByIdentifier(module as Identifier);
if (!declaration) {
throw error(`Can't find AppModule!`);
}
return declaration;
}
throw error(`Can't find AppModule!`);
};
/*
* return module declaration(class declarations) by id
* example:
* imports: [BrowserModule] => export class BrowserModule node
* or return module expression
* example:
* imports [ module ] => const module = ModuleName.forRoot/ModuleName.forChild node
*/
const findModuleDeclarationOrExpressionByIdentifier = (id: Identifier): ClassDeclaration | CallExpression | null => {
// todo decide what to do if there are more then one declaration
const decl = id.getDefinitionNodes()?.[0];
if (decl) {
if (Node.isClassDeclaration(decl)) {
return decl;
} else if (Node.isVariableDeclaration(decl)) {
return decl.getInitializer() as CallExpression;
}
}
return null;
};
const findClassDeclarationByIdentifier = (id: Identifier): ClassDeclaration | null => {
const decls = id.getDefinitionNodes();
const classDeclarations = decls.filter(node => Node.isClassDeclaration(node));
if (classDeclarations.length) {
return classDeclarations[0] as ClassDeclaration;
}
return null;
}; | the_stack |
import * as fs from 'fs';
import '../../../testing/to-be-similar-gql-doc';
import { parseImportLine, processImport } from '../../src';
import { mergeTypeDefs } from '@graphql-tools/merge';
import { Kind, print } from 'graphql';
const importSchema = (schema: string, schemas?: Record<string, string>) => {
const document = processImport(schema, __dirname, schemas);
return print(
mergeTypeDefs(
document.definitions.map(definition => ({ kind: Kind.DOCUMENT, definitions: [definition] })),
{
sort: true,
useSchemaDefinition: false,
}
)
);
};
const parseSDL = (content: string) =>
content
.split('\n')
.map(str => str.trim())
.filter(str => str.startsWith('# import ') || str.startsWith('#import '))
.map(str => parseImportLine(str.replace('#', '').trim()));
describe('importSchema', () => {
test('parseImportLine: parse single import', () => {
expect(parseImportLine(`import A from "schema.graphql"`)).toEqual({
imports: ['A'],
from: 'schema.graphql',
});
});
test('parseImportLine: optional semicolon', () => {
expect(parseImportLine(`import A from "schema.graphql";`)).toEqual({
imports: ['A'],
from: 'schema.graphql',
});
});
test('parseImportLine: invalid', () => {
expect(() => parseImportLine(`import from "schema.graphql"`)).toThrow();
});
test('parseImportLine: invalid 2', () => {
expect(() => parseImportLine(`import A from ""`)).toThrow();
});
test('parseImportLine: invalid 3', () => {
expect(() => parseImportLine(`import A. from ""`)).toThrow();
});
test('parseImportLine: invalid 4', () => {
expect(() => parseImportLine(`import A.* from ""`)).toThrow();
});
test('parseImportLine: parse multi import', () => {
expect(parseImportLine(`import A, B from "schema.graphql"`)).toEqual({
imports: ['A', 'B'],
from: 'schema.graphql',
});
});
test('parseImportLine: parse multi import (weird spacing)', () => {
expect(parseImportLine(`import A ,B from "schema.graphql"`)).toEqual({
imports: ['A', 'B'],
from: 'schema.graphql',
});
});
test('parseImportLine: different path', () => {
expect(parseImportLine(`import A from "../new/schema.graphql"`)).toEqual({
imports: ['A'],
from: '../new/schema.graphql',
});
});
test('parseImportLine: module in node_modules', () => {
expect(parseImportLine(`import A from "module-name"`)).toEqual({
imports: ['A'],
from: 'module-name',
});
});
test('parseImportLine: specific field', () => {
expect(parseImportLine(`import A.b from "module-name"`)).toEqual({
imports: ['A.b'],
from: 'module-name',
});
});
test('parseImportLine: multiple specific fields', () => {
expect(parseImportLine(`import A.b, G.q from "module-name"`)).toEqual({
imports: ['A.b', 'G.q'],
from: 'module-name',
});
});
test('parseImportLine: default import', () => {
expect(parseImportLine(`import "module-name"`)).toEqual({
imports: ['*'],
from: 'module-name',
});
});
test('parseSDL: non-import comment', () => {
expect(parseSDL(`#important: comment`)).toEqual([]);
});
test('parse: multi line import', () => {
const sdl = /* GraphQL */ `
# import A from 'a.graphql'
# import * from "b.graphql"
`;
expect(parseSDL(sdl)).toEqual([
{
imports: ['A'],
from: 'a.graphql',
},
{
imports: ['*'],
from: 'b.graphql',
},
]);
});
test('Module in node_modules', () => {
const b = `\
# import lower from './lower.graphql'
type B {
id: ID!
nickname: String! @lower
}
`;
const lower = `\
directive @lower on FIELD_DEFINITION
`;
const expectedSDL = /* GraphQL */ `
type A {
id: ID!
author: B!
}
type B {
id: ID!
nickname: String! @lower
}
directive @lower on FIELD_DEFINITION
`;
const moduleDir = 'node_modules/graphql-import-test';
if (!fs.existsSync(moduleDir)) {
fs.mkdirSync(moduleDir);
}
fs.writeFileSync(moduleDir + '/b.graphql', b);
fs.writeFileSync(moduleDir + '/lower.graphql', lower);
expect(importSchema('./fixtures/import-module/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: imports only', () => {
const expectedSDL = /* GraphQL */ `
type Query {
first: String
second: Float
third: String
}
`;
expect(importSchema('./fixtures/imports-only/all.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: import .gql extension', () => {
const expectedSDL = /* GraphQL */ `
type A {
id: ID!
}
`;
expect(importSchema('./fixtures/import-gql/a.gql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: import duplicate', () => {
const expectedSDL = /* GraphQL */ `
type Query {
first: String
second: Float
third: String
}
`;
expect(importSchema('./fixtures/import-duplicate/all.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: import nested', () => {
const expectedSDL = /* GraphQL */ `
type Query {
first: String
second: Float
third: String
}
`;
expect(importSchema('./fixtures/import-nested/all.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: field types', () => {
const expectedSDL = /* GraphQL */ `
type A {
first: String
second: Float
b: B
}
type B {
c: C
hello: String!
}
type C {
id: ID!
}
`;
expect(importSchema('./fixtures/field-types/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: enums', () => {
const expectedSDL = /* GraphQL */ `
type A {
first: String
second: Float
b: B
}
enum B {
B1
B2
B3
}
`;
expect(importSchema('./fixtures/enums/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: import all', () => {
const expectedSDL = /* GraphQL */ `
type A {
first: String
second: Float
b: B
}
type B {
hello: String!
c1: C1
c2: C2
}
type C1 {
id: ID!
}
type C2 {
id: ID!
}
`;
expect(importSchema('./fixtures/import-all/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: import all from objects', () => {
const expectedSDL = /* GraphQL */ `
type A {
first: String
second: Float
b: B
}
type B {
hello: String!
c1: C1
c2: C2
}
type C1 {
id: ID!
}
type C2 {
id: ID!
}
`;
expect(importSchema(`./fixtures/import-all-from-objects/a.graphql`)).toBeSimilarGqlDoc(expectedSDL);
});
test(`importSchema: single object schema`, () => {
const expectedSDL = /* GraphQL */ `
type A {
field: String
}
`;
expect(importSchema('./fixtures/single-object/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test(`importSchema: import all mix 'n match`, () => {
const expectedSDL = /* GraphQL */ `
scalar Date
type A {
first: String
second: Float
b: B
date: Date
}
type C1 {
id: ID!
}
type C2 {
id: ID!
}
type B {
hello: String!
c1: C1
c2: C2
}
`;
expect(importSchema('./fixtures/mix-n-match/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test(`importSchema: import all mix 'n match 2`, () => {
const expectedSDL = /* GraphQL */ `
type A {
first: String
second: Float
b: B
}
type B {
hello: String!
c1: C1
c2: C2
}
type C1 {
id: ID!
}
type C2 {
id: ID!
}
`;
expect(importSchema('./fixtures/mix-n-match2/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test(`importSchema: import all - include Query/Mutation/Subscription type`, () => {
const expectedSDL = /* GraphQL */ `
type Query {
greet: String!
}
type A {
first: String
second: Float
b: B
}
type B {
hello: String!
c1: C1
c2: C2
}
type C1 {
id: ID!
}
type C2 {
id: ID!
}
`;
expect(importSchema('./fixtures/include-root-types/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: scalar', () => {
const expectedSDL = /* GraphQL */ `
type A {
b: B
}
scalar B
`;
expect(importSchema('./fixtures/scalar/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: directive', () => {
const expectedSDL = /* GraphQL */ `
type A {
first: String @upper
second: String @withB @deprecated
}
scalar B
directive @upper on FIELD_DEFINITION
directive @withB(argB: B) on FIELD_DEFINITION
`;
expect(importSchema('./fixtures/directive/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: key directive', () => {
const expectedSDL = /* GraphQL */ `
scalar UPC
type Product @key(fields: "upc") {
upc: UPC!
name: String
}
`;
expect(importSchema('./fixtures/directive/c.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
// TODO: later
test.skip('importSchema: multiple key directive', () => {
const expectedSDL = /* GraphQL */ `
scalar UPC
scalar SKU
type Product @key(fields: "upc") @key(fields: "sku") {
upc: UPC!
sku: SKU!
name: String
}
`;
expect(importSchema('./fixtures/directive/e.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: external directive', () => {
const expectedSDL = /* GraphQL */ `
type Review @key(fields: "id") {
product: Product @provides(fields: "name")
}
extend type Product @key(fields: "upc") {
upc: String @external
name: String @external
}
`;
expect(importSchema('./fixtures/directive/f.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: requires directive', () => {
const expectedSDL = /* GraphQL */ `
type Review {
id: ID
}
extend type User @key(fields: "id") {
id: ID! @external
email: String @external
reviews: [Review] @requires(fields: "email")
}
`;
expect(importSchema('./fixtures/directive/g.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: interfaces', () => {
const expectedSDL = /* GraphQL */ `
type A implements B {
first: String
second: Float
}
interface B {
second: Float
c: [C!]!
}
type C {
c: ID!
}
`;
expect(importSchema('./fixtures/interfaces/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: interfaces-many', () => {
const expectedSDL = /* GraphQL */ `
type A implements B {
first: String
second: Float
}
interface B {
second: Float
c: [C!]!
}
type C implements D1 & D2 {
c: ID!
}
interface D1 {
d1: ID!
}
interface D2 {
d2: ID!
}
`;
expect(importSchema('./fixtures/interfaces-many/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: interfaces-implements', () => {
const expectedSDL = /* GraphQL */ `
type A implements B {
id: ID!
}
interface B {
id: ID!
}
type B1 implements B {
id: ID!
}
`;
expect(importSchema('./fixtures/interfaces-implements/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: interfaces-implements-many', () => {
const expectedSDL = /* GraphQL */ `
type A implements B {
id: ID!
}
interface B {
id: ID!
}
type B1 implements B {
id: ID!
}
type B2 implements B {
id: ID!
}
`;
expect(importSchema('./fixtures/interfaces-implements-many/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: input types', () => {
const expectedSDL = /* GraphQL */ `
type A {
first(b: B): String
second: Float
}
input B {
hello: [C!]!
}
input C {
id: ID!
}
`;
expect(importSchema('./fixtures/input-types/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('importSchema: complex test', () => {
try {
const a = importSchema('./fixtures/complex/a.graphql');
expect(a).toBeTruthy();
} catch (e: any) {
expect(e).toBeFalsy();
}
});
test('circular imports', () => {
const expectedSDL = /* GraphQL */ `
type A {
first: String
second: Float
b: B
}
type C1 {
id: ID!
}
type C2 {
id: ID!
}
type B {
hello: String!
c1: C1
c2: C2
a: A
}
`;
const actualSDL = importSchema('./fixtures/circular/a.graphql');
expect(actualSDL).toBeSimilarGqlDoc(expectedSDL);
});
test('related types', () => {
const expectedSDL = /* GraphQL */ `
type A {
first: String
second: Float
b: B
}
type B {
hello: String!
c1: C
}
type C {
field: String
}
`;
const actualSDL = importSchema('./fixtures/related-types/a.graphql');
expect(actualSDL).toBeSimilarGqlDoc(expectedSDL);
});
test('relative paths', () => {
const expectedSDL = /* GraphQL */ `
type Query {
feed: [Post!]!
}
type Mutation {
createDraft(title: String!, text: String): Post
publish(id: ID!): Post
}
type Post implements Node {
id: ID!
isPublished: Boolean!
title: String!
text: String!
}
interface Node {
id: ID!
}
`;
const actualSDL = importSchema('./fixtures/relative-paths/src/schema.graphql');
expect(actualSDL).toBeSimilarGqlDoc(expectedSDL);
});
test('root field imports', () => {
const expectedSDL = /* GraphQL */ `
type Query {
posts(filter: PostFilter): [Post]
}
type Dummy {
field: String
}
type Post {
field1: String
}
input PostFilter {
field3: Int
}
`;
const actualSDL = importSchema('./fixtures/root-fields/a.graphql');
expect(actualSDL).toBeSimilarGqlDoc(expectedSDL);
});
test('extend root field', () => {
const expectedSDL = /* GraphQL */ `
extend type Query {
me: User
}
type User @key(fields: "id") {
id: ID!
name: String
}
`;
const actualSDL = importSchema('./fixtures/root-fields/c.graphql');
expect(actualSDL).toBeSimilarGqlDoc(expectedSDL);
});
test('extend root field imports', () => {
const expectedSDL = /* GraphQL */ `
extend type Query {
me: User
post: Post
}
type Post {
id: ID!
}
type User @key(fields: "id") {
id: ID!
name: String
}
`;
const actualSDL = importSchema('./fixtures/root-fields/d.graphql');
expect(actualSDL).toBeSimilarGqlDoc(expectedSDL);
});
test('merged root field imports', () => {
const expectedSDL = /* GraphQL */ `
type Query {
helloA: String
posts(filter: PostFilter): [Post]
hello: String
}
type Dummy {
field: String
field2: String
}
type Post {
field1: String
}
input PostFilter {
field3: Int
}
`;
const actualSDL = importSchema('./fixtures/merged-root-fields/a.graphql');
expect(actualSDL).toBeSimilarGqlDoc(expectedSDL);
});
test('global schema modules', () => {
const shared = `
type Shared {
first: String
}
`;
const expectedSDL = /* GraphQL */ `
type A {
first: String
second: Shared
}
type Shared {
first: String
}
`;
expect(importSchema('./fixtures/global/a.graphql', { shared })).toBeSimilarGqlDoc(expectedSDL);
});
test('missing type on type', () => {
try {
importSchema('./fixtures/type-not-found/a.graphql');
throw new Error();
} catch (e: any) {
expect(e.message).toBe(`Couldn't find type Post in any of the schemas.`);
}
});
test('missing type on interface', () => {
try {
importSchema('./fixtures/type-not-found/b.graphql');
throw new Error();
} catch (e: any) {
expect(e.message).toBe(`Couldn't find type Post in any of the schemas.`);
}
});
test('missing type on input type', () => {
try {
importSchema('./fixtures/type-not-found/c.graphql');
throw new Error();
} catch (e: any) {
expect(e.message).toBe(`Couldn't find type Post in any of the schemas.`);
}
});
test('missing interface type', () => {
try {
importSchema('./fixtures/type-not-found/d.graphql');
throw new Error();
} catch (e: any) {
expect(e.message).toBe(`Couldn't find type MyInterface in any of the schemas.`);
}
});
test('missing union type', () => {
try {
importSchema('./fixtures/type-not-found/e.graphql');
throw new Error();
} catch (e: any) {
expect(e.message).toBe(`Couldn't find type C in any of the schemas.`);
}
});
test('missing type on input type', () => {
try {
importSchema('./fixtures/type-not-found/f.graphql');
throw new Error();
} catch (e: any) {
expect(e.message).toBe(`Couldn't find type Post in any of the schemas.`);
}
});
test('missing type on directive', () => {
try {
importSchema('./fixtures/type-not-found/g.graphql');
throw new Error();
} catch (e: any) {
expect(e.message).toBe(`Couldn't find type first in any of the schemas.`);
}
});
test('import with collision', () => {
// Local type gets preference over imported type
const expectedSDL = /* GraphQL */ `
type User {
id: ID!
name: String!
intro: String
}
`;
expect(importSchema('./fixtures/collision/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('merged custom root fields imports', () => {
const expectedSDL = /* GraphQL */ `
type Query {
helloA: String
posts(filter: PostFilter): [Post]
hello: String
}
type Dummy {
field: String
field2: String
}
type Post {
field1: String
}
input PostFilter {
field3: Int
}
`;
const actualSDL = importSchema('./fixtures/merged-root-fields/a.graphql');
expect(actualSDL).toBeSimilarGqlDoc(expectedSDL);
});
test('respect schema definition', () => {
const expectedSDL = /* GraphQL */ `
schema {
query: MyQuery
mutation: MyMutation
}
type MyQuery {
b: String
}
type MyMutation {
c: String
}
`;
const actualSDL = importSchema('./fixtures/schema-definition/a.graphql');
expect(actualSDL).toBeSimilarGqlDoc(expectedSDL);
});
test('import schema with shadowed type', () => {
const expectedSDL = /* GraphQL */ `
type Query {
b: B!
}
type B {
x: X
}
scalar X
`;
expect(importSchema('./fixtures/import-shadowed/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('import specific types', () => {
const expectedSDL = /* GraphQL */ `
type User implements B {
b: String!
c: [C!]!
}
interface B {
B: String!
}
type C {
c: String
}
`;
expect(importSchema('./fixtures/specific/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('imports missing named imports for file imported multiple time without duplicates', () => {
const expectedSDL = /* GraphQL */ `
type Query {
a: B
b: B
c: B
}
type Mutation {
a: B
b: B
c: B
}
type B {
x: String
}
`;
expect(importSchema('fixtures/multiple-imports/schema.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('imports multiple imports at least 3 levels deep with transitive dependencies', () => {
const expectedSDL = /* GraphQL */ `
type Product {
price: Int
}
type Products {
items: [Product]
}
type Account {
id: ID
cart: Cart
}
type Cart {
total: Int
products: Products
}
type Query {
user: User
}
type User {
account: Account
}
`;
expect(importSchema('fixtures/multiple-levels/level1.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('imports dependencies at least 3 levels deep with transitive dependencies while using master schemata', () => {
const expectedSDL = /* GraphQL */ `
type Account {
id: ID
cart: Cart
}
type Cart {
products: Products
total: Int
}
type PaginatedWrapper {
user: User
}
type Product {
price: Int
}
type Products {
items: [Product]
}
type Query {
pagination: PaginatedWrapper
}
type User {
account: Account
}
`;
expect(importSchema('fixtures/multiple-levels-master-schema/level1.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
test('imports dependencies with transitive dependencies while using master schemata with directories', () => {
const expectedSDL = /* GraphQL */ `
type Model1 {
data: String!
}
type Model10 {
data: String!
}
type Model2 {
data: String!
}
type Model3 {
data: String!
}
type Model4 {
data: String!
}
type Model5 {
data: String!
}
type Model6 {
data: String!
}
type Model7 {
data: String!
}
type Model8 {
data: String!
}
type Model9 {
data: String!
}
type Mutation {
createModel1(data: String!): Model1!
createModel10(data: String!): Model10!
createModel2(data: String!): Model2!
createModel3(data: String!): Model3!
createModel4(data: String!): Model4!
createModel5(data: String!): Model5!
createModel6(data: String!): Model6!
createModel7(data: String!): Model7!
createModel8(data: String!): Model8!
createModel9(data: String!): Model9!
}
type Query {
query_model_1: Model1
query_model_10: Model10
query_model_2: Model2
query_model_3: Model3
query_model_4: Model4
query_model_5: Model5
query_model_6: Model6
query_model_7: Model7
query_model_8: Model8
query_model_9: Model9
}
`;
expect(importSchema('fixtures/multiple-directories-with-master-schema/index.graphql')).toBeSimilarGqlDoc(
expectedSDL
);
});
test('imports multi-level types without direct references', () => {
const expectedSDL = /* GraphQL */ `
type Level1 {
id: ID!
}
type Level2 {
id: ID!
level1: Level1
}
type Level3 {
id: ID!
level2: Level2
}
type Query {
level: Level3
}
`;
expect(importSchema('fixtures/deep/a.graphql')).toBeSimilarGqlDoc(expectedSDL);
});
it('should get types with specific imports and multiple interfaces', async () => {
const document = importSchema('./fixtures/types-with-many-interfaces/a.graphql');
expect(document).toBeSimilarGqlDoc(/* GraphQL */ `
type Query {
test: Foo
}
type Foo {
field: Imported
}
interface AnotherInterface {
field: String
}
interface Imported {
anotherField: String
}
type Implementation implements Imported & AnotherInterface {
field: String
anotherField: String
localField: String
}
`);
});
}); | the_stack |
import type { IconTree } from './icon-types';
/**
* The icon for `ab.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const ab: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M5 15v2c0 1.054.95 2 2 2h3v2H7a4 4 0 0 1-4-4v-2h2zm13-5l4.4 11h-2.155l-1.201-3h-4.09l-1.199 3h-2.154L16 10h2zm-1 2.885L15.753 16h2.492L17 12.885zM3 3h6a3 3 0 0 1 2.235 5A3 3 0 0 1 9 13H3V3zm6 6H5v2h4a1 1 0 0 0 0-2zm8-6a4 4 0 0 1 4 4v2h-2V7a2 2 0 0 0-2-2h-3V3h3zM9 5H5v2h4a1 1 0 1 0 0-2z',
},
},
];
/**
* The icon for `add-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const addFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M11 11V5h2v6h6v2h-6v6h-2v-6H5v-2z' } },
];
/**
* The icon for `add-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const addLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M11 11V5h2v6h6v2h-6v6h-2v-6H5v-2z' } },
];
/**
* The icon for `alert-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const alertLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
fillRule: 'nonzero',
d: 'M12.866 3l9.526 16.5a1 1 0 0 1-.866 1.5H2.474a1 1 0 0 1-.866-1.5L11.134 3a1 1 0 0 1 1.732 0zm-8.66 16h15.588L12 5.5 4.206 19zM11 16h2v2h-2v-2zm0-7h2v5h-2V9z',
},
},
];
/**
* The icon for `align-bottom.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const alignBottom: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: { d: 'M3 19h18v2H3v-2zm5-6h3l-4 4-4-4h3V3h2v10zm10 0h3l-4 4-4-4h3V3h2v10z' },
},
];
/**
* The icon for `align-center.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const alignCenter: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M3 4h18v2H3V4zm2 15h14v2H5v-2zm-2-5h18v2H3v-2zm2-5h14v2H5V9z' } },
];
/**
* The icon for `align-justify.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const alignJustify: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M3 4h18v2H3V4zm0 15h18v2H3v-2zm0-5h18v2H3v-2zm0-5h18v2H3V9z' } },
];
/**
* The icon for `align-left.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const alignLeft: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M3 4h18v2H3V4zm0 15h14v2H3v-2zm0-5h18v2H3v-2zm0-5h14v2H3V9z' } },
];
/**
* The icon for `align-right.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const alignRight: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M3 4h18v2H3V4zm4 15h14v2H7v-2zm-4-5h18v2H3v-2zm4-5h14v2H7V9z' } },
];
/**
* The icon for `align-top.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const alignTop: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: { d: 'M3 3h18v2H3V3zm5 8v10H6V11H3l4-4 4 4H8zm10 0v10h-2V11h-3l4-4 4 4h-3z' },
},
];
/**
* The icon for `align-vertically.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const alignVertically: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M3 11h18v2H3v-2zm15 7v3h-2v-3h-3l4-4 4 4h-3zM8 18v3H6v-3H3l4-4 4 4H8zM18 6h3l-4 4-4-4h3V3h2v3zM8 6h3l-4 4-4-4h3V3h2v3z',
},
},
];
/**
* The icon for `apps-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const appsLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M6.75 2.5A4.25 4.25 0 0 1 11 6.75V11H6.75a4.25 4.25 0 1 1 0-8.5zM9 9V6.75A2.25 2.25 0 1 0 6.75 9H9zm-2.25 4H11v4.25A4.25 4.25 0 1 1 6.75 13zm0 2A2.25 2.25 0 1 0 9 17.25V15H6.75zm10.5-12.5a4.25 4.25 0 1 1 0 8.5H13V6.75a4.25 4.25 0 0 1 4.25-4.25zm0 6.5A2.25 2.25 0 1 0 15 6.75V9h2.25zM13 13h4.25A4.25 4.25 0 1 1 13 17.25V13zm2 2v2.25A2.25 2.25 0 1 0 17.25 15H15z',
},
},
];
/**
* The icon for `arrow-down-s-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const arrowDownSFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M12 16l-6-6h12z' } },
];
/**
* The icon for `arrow-go-back-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const arrowGoBackFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M8 7v4L2 6l6-5v4h5a8 8 0 1 1 0 16H4v-2h9a6 6 0 1 0 0-12H8z' } },
];
/**
* The icon for `arrow-go-forward-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const arrowGoForwardFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M16 7h-5a6 6 0 1 0 0 12h9v2h-9a8 8 0 1 1 0-16h5V1l6 5-6 5V7z' } },
];
/**
* The icon for `arrow-left-s-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const arrowLeftSFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M8 12l6-6v12z' } },
];
/**
* The icon for `arrow-right-s-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const arrowRightSFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M16 12l-6 6V6z' } },
];
/**
* The icon for `arrow-up-s-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const arrowUpSFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M12 8l6 6H6z' } },
];
/**
* The icon for `asterisk.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const asterisk: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M13 3v7.267l6.294-3.633 1 1.732-6.293 3.633 6.293 3.635-1 1.732L13 13.732V21h-2v-7.268l-6.294 3.634-1-1.732L9.999 12 3.706 8.366l1-1.732L11 10.267V3z',
},
},
];
/**
* The icon for `attachment-2.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const attachment2: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M14.828 7.757l-5.656 5.657a1 1 0 1 0 1.414 1.414l5.657-5.656A3 3 0 1 0 12 4.929l-5.657 5.657a5 5 0 1 0 7.071 7.07L19.071 12l1.414 1.414-5.657 5.657a7 7 0 1 1-9.9-9.9l5.658-5.656a5 5 0 0 1 7.07 7.07L12 16.244A3 3 0 1 1 7.757 12l5.657-5.657 1.414 1.414z',
},
},
];
/**
* The icon for `bold.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const bold: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M8 11h4.5a2.5 2.5 0 1 0 0-5H8v5zm10 4.5a4.5 4.5 0 0 1-4.5 4.5H6V4h6.5a4.5 4.5 0 0 1 3.256 7.606A4.498 4.498 0 0 1 18 15.5zM8 13v5h5.5a2.5 2.5 0 1 0 0-5H8z',
},
},
];
/**
* The icon for `braces-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const bracesLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M4 18v-3.7a1.5 1.5 0 0 0-1.5-1.5H2v-1.6h.5A1.5 1.5 0 0 0 4 9.7V6a3 3 0 0 1 3-3h1v2H7a1 1 0 0 0-1 1v4.1A2 2 0 0 1 4.626 12 2 2 0 0 1 6 13.9V18a1 1 0 0 0 1 1h1v2H7a3 3 0 0 1-3-3zm16-3.7V18a3 3 0 0 1-3 3h-1v-2h1a1 1 0 0 0 1-1v-4.1a2 2 0 0 1 1.374-1.9A2 2 0 0 1 18 10.1V6a1 1 0 0 0-1-1h-1V3h1a3 3 0 0 1 3 3v3.7a1.5 1.5 0 0 0 1.5 1.5h.5v1.6h-.5a1.5 1.5 0 0 0-1.5 1.5z',
},
},
];
/**
* The icon for `bring-forward.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const bringForward: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M14 3c.552 0 1 .448 1 1v5h5c.552 0 1 .448 1 1v10c0 .552-.448 1-1 1H10c-.552 0-1-.448-1-1v-5H4c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h10zm-1 2H5v8h8V5z',
},
},
];
/**
* The icon for `bring-to-front.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const bringToFront: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M11 3c.552 0 1 .448 1 1v2h5c.552 0 1 .448 1 1v5h2c.552 0 1 .448 1 1v7c0 .552-.448 1-1 1h-7c-.552 0-1-.448-1-1v-2H7c-.552 0-1-.448-1-1v-5H4c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h7zm5 5H8v8h8V8z',
},
},
];
/**
* The icon for `chat-new-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const chatNewLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M14 3v2H4v13.385L5.763 17H20v-7h2v8a1 1 0 0 1-1 1H6.455L2 22.5V4a1 1 0 0 1 1-1h11zm5 0V0h2v3h3v2h-3v3h-2V5h-3V3h3z',
},
},
];
/**
* The icon for `checkbox-circle-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const checkboxCircleLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm-.997-4L6.76 11.757l1.414-1.414 2.829 2.829 5.656-5.657 1.415 1.414L11.003 16z',
},
},
];
/**
* The icon for `clipboard-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const clipboardFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M6 4v4h12V4h2.007c.548 0 .993.445.993.993v16.014a.994.994 0 0 1-.993.993H3.993A.994.994 0 0 1 3 21.007V4.993C3 4.445 3.445 4 3.993 4H6zm2-2h8v4H8V2z',
},
},
];
/**
* The icon for `clipboard-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const clipboardLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M7 4V2h10v2h3.007c.548 0 .993.445.993.993v16.014a.994.994 0 0 1-.993.993H3.993A.994.994 0 0 1 3 21.007V4.993C3 4.445 3.445 4 3.993 4H7zm0 2H5v14h14V6h-2v2H7V6zm2-2v2h6V4H9z',
},
},
];
/**
* The icon for `close-circle-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const closeCircleLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm0-9.414l2.828-2.829 1.415 1.415L13.414 12l2.829 2.828-1.415 1.415L12 13.414l-2.828 2.829-1.415-1.415L10.586 12 7.757 9.172l1.415-1.415L12 10.586z',
},
},
];
/**
* The icon for `close-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const closeFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 10.586l4.95-4.95 1.414 1.414-4.95 4.95 4.95 4.95-1.414 1.414-4.95-4.95-4.95 4.95-1.414-1.414 4.95-4.95-4.95-4.95L7.05 5.636z',
},
},
];
/**
* The icon for `close-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const closeLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 10.586l4.95-4.95 1.414 1.414-4.95 4.95 4.95 4.95-1.414 1.414-4.95-4.95-4.95 4.95-1.414-1.414 4.95-4.95-4.95-4.95L7.05 5.636z',
},
},
];
/**
* The icon for `code-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const codeLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M23 12l-7.071 7.071-1.414-1.414L20.172 12l-5.657-5.657 1.414-1.414L23 12zM3.828 12l5.657 5.657-1.414 1.414L1 12l7.071-7.071 1.414 1.414L3.828 12z',
},
},
];
/**
* The icon for `code-view.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const codeView: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M16.95 8.464l1.414-1.414 4.95 4.95-4.95 4.95-1.414-1.414L20.485 12 16.95 8.464zm-9.9 0L3.515 12l3.535 3.536-1.414 1.414L.686 12l4.95-4.95L7.05 8.464z',
},
},
];
/**
* The icon for `delete-bin-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const deleteBinFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M17 6h5v2h-2v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V8H2V6h5V3a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v3zm-8 5v6h2v-6H9zm4 0v6h2v-6h-2zM9 4v2h6V4H9z',
},
},
];
/**
* The icon for `delete-bin-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const deleteBinLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M17 6h5v2h-2v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V8H2V6h5V3a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v3zm1 2H6v12h12V8zm-9 3h2v6H9v-6zm4 0h2v6h-2v-6zM9 4v2h6V4H9z',
},
},
];
/**
* The icon for `delete-column.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const deleteColumn: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 3c.552 0 1 .448 1 1v8c.835-.628 1.874-1 3-1 2.761 0 5 2.239 5 5s-2.239 5-5 5c-1.032 0-1.99-.313-2.787-.848L13 20c0 .552-.448 1-1 1H6c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h6zm-1 2H7v14h4V5zm8 10h-6v2h6v-2z',
},
},
];
/**
* The icon for `delete-row.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const deleteRow: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M20 5c.552 0 1 .448 1 1v6c0 .552-.448 1-1 1 .628.835 1 1.874 1 3 0 2.761-2.239 5-5 5s-5-2.239-5-5c0-1.126.372-2.165 1-3H4c-.552 0-1-.448-1-1V6c0-.552.448-1 1-1h16zm-7 10v2h6v-2h-6zm6-8H5v4h14V7z',
},
},
];
/**
* The icon for `double-quotes-l.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const doubleQuotesL: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311 1.804.167 3.226 1.648 3.226 3.489a3.5 3.5 0 0 1-3.5 3.5c-1.073 0-2.099-.49-2.748-1.179zm10 0C13.553 16.227 13 15 13 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311 1.804.167 3.226 1.648 3.226 3.489a3.5 3.5 0 0 1-3.5 3.5c-1.073 0-2.099-.49-2.748-1.179z',
},
},
];
/**
* The icon for `double-quotes-r.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const doubleQuotesR: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M19.417 6.679C20.447 7.773 21 9 21 10.989c0 3.5-2.457 6.637-6.03 8.188l-.893-1.378c3.335-1.804 3.987-4.145 4.247-5.621-.537.278-1.24.375-1.929.311-1.804-.167-3.226-1.648-3.226-3.489a3.5 3.5 0 0 1 3.5-3.5c1.073 0 2.099.49 2.748 1.179zm-10 0C10.447 7.773 11 9 11 10.989c0 3.5-2.457 6.637-6.03 8.188l-.893-1.378c3.335-1.804 3.987-4.145 4.247-5.621-.537.278-1.24.375-1.929.311C4.591 12.322 3.17 10.841 3.17 9a3.5 3.5 0 0 1 3.5-3.5c1.073 0 2.099.49 2.748 1.179z',
},
},
];
/**
* The icon for `download-2-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const download2Fill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: { d: 'M4 19h16v-7h2v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-8h2v7zM14 9h5l-7 7-7-7h5V3h4v6z' },
},
];
/**
* The icon for `drag-drop-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const dragDropLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
fillRule: 'nonzero',
d: 'M16 13l6.964 4.062-2.973.85 2.125 3.681-1.732 1-2.125-3.68-2.223 2.15L16 13zm-2-7h2v2h5a1 1 0 0 1 1 1v4h-2v-3H10v10h4v2H9a1 1 0 0 1-1-1v-5H6v-2h2V9a1 1 0 0 1 1-1h5V6zM4 14v2H2v-2h2zm0-4v2H2v-2h2zm0-4v2H2V6h2zm0-4v2H2V2h2zm4 0v2H6V2h2zm4 0v2h-2V2h2zm4 0v2h-2V2h2z',
},
},
];
/**
* The icon for `emphasis-cn.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const emphasisCn: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 19a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3zm-5.5 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3zm11 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3zM13 2v2h6v2h-1.968a18.222 18.222 0 0 1-3.621 6.302 14.685 14.685 0 0 0 5.327 3.042l-.536 1.93A16.685 16.685 0 0 1 12 13.726a16.696 16.696 0 0 1-6.202 3.547l-.536-1.929a14.7 14.7 0 0 0 5.327-3.042 18.077 18.077 0 0 1-2.822-4.3h2.24A16.031 16.031 0 0 0 12 10.876a16.168 16.168 0 0 0 2.91-4.876L5 6V4h6V2h2z',
},
},
];
/**
* The icon for `emphasis.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const emphasis: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 19a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3zm-5.5 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3zm11 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3zM18 3v2H8v4h9v2H8v4h10v2H6V3h12z',
},
},
];
/**
* The icon for `english-input.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const englishInput: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M14 10h2v.757a4.5 4.5 0 0 1 7 3.743V20h-2v-5.5c0-1.43-1.175-2.5-2.5-2.5S16 13.07 16 14.5V20h-2V10zm-2-6v2H4v5h8v2H4v5h8v2H2V4h10z',
},
},
];
/**
* The icon for `error-warning-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const errorWarningLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm-1-5h2v2h-2v-2zm0-8h2v6h-2V7z',
},
},
];
/**
* The icon for `external-link-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const externalLinkFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M10 6v2H5v11h11v-5h2v6a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h6zm11-3v9l-3.794-3.793-5.999 6-1.414-1.414 5.999-6L12 3h9z',
},
},
];
/**
* The icon for `file-copy-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const fileCopyLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M7 6V3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1h-3v3c0 .552-.45 1-1.007 1H4.007A1.001 1.001 0 0 1 3 21l.003-14c0-.552.45-1 1.007-1H7zM5.003 8L5 20h10V8H5.003zM9 6h8v10h2V4H9v2z',
},
},
];
/**
* The icon for `flow-chart.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const flowChart: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M6 21.5c-1.933 0-3.5-1.567-3.5-3.5s1.567-3.5 3.5-3.5c1.585 0 2.924 1.054 3.355 2.5H15v-2h2V9.242L14.757 7H9V9H3V3h6v2h5.757L18 1.756 22.243 6 19 9.241V15L21 15v6h-6v-2H9.355c-.43 1.446-1.77 2.5-3.355 2.5zm0-5c-.828 0-1.5.672-1.5 1.5s.672 1.5 1.5 1.5 1.5-.672 1.5-1.5-.672-1.5-1.5-1.5zm13 .5h-2v2h2v-2zM18 4.586L16.586 6 18 7.414 19.414 6 18 4.586zM7 5H5v2h2V5z',
},
},
];
/**
* The icon for `font-color.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const fontColor: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M15.246 14H8.754l-1.6 4H5l6-15h2l6 15h-2.154l-1.6-4zm-.8-2L12 5.885 9.554 12h4.892zM3 20h18v2H3v-2z',
},
},
];
/**
* The icon for `font-size-2.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const fontSize2: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M10 6v15H8V6H2V4h14v2h-6zm8 8v7h-2v-7h-3v-2h8v2h-3z' } },
];
/**
* The icon for `font-size.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const fontSize: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M11.246 15H4.754l-2 5H.6L7 4h2l6.4 16h-2.154l-2-5zm-.8-2L8 6.885 5.554 13h4.892zM21 12.535V12h2v8h-2v-.535a4 4 0 1 1 0-6.93zM19 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z',
},
},
];
/**
* The icon for `format-clear.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const formatClear: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12.651 14.065L11.605 20H9.574l1.35-7.661-7.41-7.41L4.93 3.515 20.485 19.07l-1.414 1.414-6.42-6.42zm-.878-6.535l.27-1.53h-1.8l-2-2H20v2h-5.927L13.5 9.257 11.773 7.53z',
},
},
];
/**
* The icon for `fullscreen-exit-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const fullscreenExitLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: { d: 'M18 7h4v2h-6V3h2v4zM8 9H2V7h4V3h2v6zm10 8v4h-2v-6h6v2h-4zM8 15v6H6v-4H2v-2h6z' },
},
];
/**
* The icon for `fullscreen-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const fullscreenLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M20 3h2v6h-2V5h-4V3h4zM4 3h4v2H4v4H2V3h2zm16 16v-4h2v6h-6v-2h4zM4 19h4v2H2v-6h2v4z',
},
},
];
/**
* The icon for `functions.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const functions: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M5 18l7.68-6L5 6V4h14v2H8.263L16 12l-7.737 6H19v2H5v-2z' } },
];
/**
* The icon for `gallery-upload-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const galleryUploadLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M8 1v4H4v14h16V3h1.008c.548 0 .992.445.992.993v16.014a1 1 0 0 1-.992.993H2.992A.993.993 0 0 1 2 20.007V3.993A1 1 0 0 1 2.992 3H6V1h2zm4 7l4 4h-3v4h-2v-4H8l4-4zm6-7v4h-8V3h6V1h2z',
},
},
];
/**
* The icon for `h-1.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const h1: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: { d: 'M13 20h-2v-7H4v7H2V4h2v7h7V4h2v16zm8-12v12h-2v-9.796l-2 .536V8.67L19.5 8H21z' },
},
];
/**
* The icon for `h-2.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const h2: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M4 4v7h7V4h2v16h-2v-7H4v7H2V4h2zm14.5 4c2.071 0 3.75 1.679 3.75 3.75 0 .857-.288 1.648-.772 2.28l-.148.18L18.034 18H22v2h-7v-1.556l4.82-5.546c.268-.307.43-.709.43-1.148 0-.966-.784-1.75-1.75-1.75-.918 0-1.671.707-1.744 1.606l-.006.144h-2C14.75 9.679 16.429 8 18.5 8z',
},
},
];
/**
* The icon for `h-3.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const h3: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M22 8l-.002 2-2.505 2.883c1.59.435 2.757 1.89 2.757 3.617 0 2.071-1.679 3.75-3.75 3.75-1.826 0-3.347-1.305-3.682-3.033l1.964-.382c.156.806.866 1.415 1.718 1.415.966 0 1.75-.784 1.75-1.75s-.784-1.75-1.75-1.75c-.286 0-.556.069-.794.19l-1.307-1.547L19.35 10H15V8h7zM4 4v7h7V4h2v16h-2v-7H4v7H2V4h2z',
},
},
];
/**
* The icon for `h-4.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const h4: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M13 20h-2v-7H4v7H2V4h2v7h7V4h2v16zm9-12v8h1.5v2H22v2h-2v-2h-5.5v-1.34l5-8.66H22zm-2 3.133L17.19 16H20v-4.867z',
},
},
];
/**
* The icon for `h-5.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const h5: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M22 8v2h-4.323l-.464 2.636c.33-.089.678-.136 1.037-.136 2.21 0 4 1.79 4 4s-1.79 4-4 4c-1.827 0-3.367-1.224-3.846-2.897l1.923-.551c.24.836 1.01 1.448 1.923 1.448 1.105 0 2-.895 2-2s-.895-2-2-2c-.63 0-1.193.292-1.56.748l-1.81-.904L16 8h6zM4 4v7h7V4h2v16h-2v-7H4v7H2V4h2z',
},
},
];
/**
* The icon for `h-6.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const h6: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M21.097 8l-2.598 4.5c2.21 0 4.001 1.79 4.001 4s-1.79 4-4 4-4-1.79-4-4c0-.736.199-1.426.546-2.019L18.788 8h2.309zM4 4v7h7V4h2v16h-2v-7H4v7H2V4h2zm14.5 10.5c-1.105 0-2 .895-2 2s.895 2 2 2 2-.895 2-2-.895-2-2-2z',
},
},
];
/**
* The icon for `hashtag.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const hashtag: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M7.784 14l.42-4H4V8h4.415l.525-5h2.011l-.525 5h3.989l.525-5h2.011l-.525 5H20v2h-3.784l-.42 4H20v2h-4.415l-.525 5h-2.011l.525-5H9.585l-.525 5H7.049l.525-5H4v-2h3.784zm2.011 0h3.99l.42-4h-3.99l-.42 4z',
},
},
];
/**
* The icon for `heading.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const heading: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M17 11V4h2v17h-2v-8H7v8H5V4h2v7z' } },
];
/**
* The icon for `image-add-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const imageAddLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M21 15v3h3v2h-3v3h-2v-3h-3v-2h3v-3h2zm.008-12c.548 0 .992.445.992.993V13h-2V5H4v13.999L14 9l3 3v2.829l-3-3L6.827 19H14v2H2.992A.993.993 0 0 1 2 20.007V3.993A1 1 0 0 1 2.992 3h18.016zM8 7a2 2 0 1 1 0 4 2 2 0 0 1 0-4z',
},
},
];
/**
* The icon for `image-edit-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const imageEditLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M20 3c.552 0 1 .448 1 1v1.757l-2 2V5H5v8.1l4-4 4.328 4.329-1.415 1.413L9 11.93l-4 3.999V19h10.533l.708.001 1.329-1.33L18.9 19h.1v-2.758l2-2V20c0 .552-.448 1-1 1H4c-.55 0-1-.45-1-1V4c0-.552.448-1 1-1h16zm1.778 4.808l1.414 1.414L15.414 17l-1.416-.002.002-1.412 7.778-7.778zM15.5 7c.828 0 1.5.672 1.5 1.5s-.672 1.5-1.5 1.5S14 9.328 14 8.5 14.672 7 15.5 7z',
},
},
];
/**
* The icon for `image-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const imageLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M4.828 21l-.02.02-.021-.02H2.992A.993.993 0 0 1 2 20.007V3.993A1 1 0 0 1 2.992 3h18.016c.548 0 .992.445.992.993v16.014a1 1 0 0 1-.992.993H4.828zM20 15V5H4v14L14 9l6 6zm0 2.828l-6-6L6.828 19H20v-1.172zM8 11a2 2 0 1 1 0-4 2 2 0 0 1 0 4z',
},
},
];
/**
* The icon for `indent-decrease.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const indentDecrease: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M3 4h18v2H3V4zm0 15h18v2H3v-2zm8-5h10v2H11v-2zm0-5h10v2H11V9zm-8 3.5L7 9v7l-4-3.5z',
},
},
];
/**
* The icon for `indent-increase.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const indentIncrease: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M3 4h18v2H3V4zm0 15h18v2H3v-2zm8-5h10v2H11v-2zm0-5h10v2H11V9zm-4 3.5L3 16V9l4 3.5z',
},
},
];
/**
* The icon for `information-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const informationLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zM11 7h2v2h-2V7zm0 4h2v6h-2v-6z',
},
},
];
/**
* The icon for `input-cursor-move.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const inputCursorMove: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M8 21v-2h3V5H8V3h8v2h-3v14h3v2H8zM18.05 7.05L23 12l-4.95 4.95-1.414-1.414L20.172 12l-3.536-3.536L18.05 7.05zm-12.1 0l1.414 1.414L3.828 12l3.536 3.536L5.95 16.95 1 12l4.95-4.95z',
},
},
];
/**
* The icon for `insert-column-left.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const insertColumnLeft: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M20 3c.552 0 1 .448 1 1v16c0 .552-.448 1-1 1h-6c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h6zm-1 2h-4v14h4V5zM6 7c2.761 0 5 2.239 5 5s-2.239 5-5 5-5-2.239-5-5 2.239-5 5-5zm1 2H5v1.999L3 11v2l2-.001V15h2v-2.001L9 13v-2l-2-.001V9z',
},
},
];
/**
* The icon for `insert-column-right.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const insertColumnRight: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M10 3c.552 0 1 .448 1 1v16c0 .552-.448 1-1 1H4c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h6zM9 5H5v14h4V5zm9 2c2.761 0 5 2.239 5 5s-2.239 5-5 5-5-2.239-5-5 2.239-5 5-5zm1 2h-2v1.999L15 11v2l2-.001V15h2v-2.001L21 13v-2l-2-.001V9z',
},
},
];
/**
* The icon for `insert-row-bottom.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const insertRowBottom: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 13c2.761 0 5 2.239 5 5s-2.239 5-5 5-5-2.239-5-5 2.239-5 5-5zm1 2h-2v1.999L9 17v2l2-.001V21h2v-2.001L15 19v-2l-2-.001V15zm7-12c.552 0 1 .448 1 1v6c0 .552-.448 1-1 1H4c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h16zM5 5v4h14V5H5z',
},
},
];
/**
* The icon for `insert-row-top.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const insertRowTop: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M20 13c.552 0 1 .448 1 1v6c0 .552-.448 1-1 1H4c-.552 0-1-.448-1-1v-6c0-.552.448-1 1-1h16zm-1 2H5v4h14v-4zM12 1c2.761 0 5 2.239 5 5s-2.239 5-5 5-5-2.239-5-5 2.239-5 5-5zm1 2h-2v1.999L9 5v2l2-.001V9h2V6.999L15 7V5l-2-.001V3z',
},
},
];
/**
* The icon for `italic.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const italic: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M15 20H7v-2h2.927l2.116-12H9V4h8v2h-2.927l-2.116 12H15z' } },
];
/**
* The icon for `layout-column-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const layoutColumnLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
fillRule: 'nonzero',
d: 'M11 5H5v14h6V5zm2 0v14h6V5h-6zM4 3h16a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z',
},
},
];
/**
* The icon for `line-height.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const lineHeight: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M11 4h10v2H11V4zM6 7v4H4V7H1l4-4 4 4H6zm0 10h3l-4 4-4-4h3v-4h2v4zm5 1h10v2H11v-2zm-2-7h12v2H9v-2z',
},
},
];
/**
* The icon for `link-m.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const linkM: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M17.657 14.828l-1.414-1.414L17.657 12A4 4 0 1 0 12 6.343l-1.414 1.414-1.414-1.414 1.414-1.414a6 6 0 0 1 8.485 8.485l-1.414 1.414zm-2.829 2.829l-1.414 1.414a6 6 0 1 1-8.485-8.485l1.414-1.414 1.414 1.414L6.343 12A4 4 0 1 0 12 17.657l1.414-1.414 1.414 1.414zm0-9.9l1.415 1.415-7.071 7.07-1.415-1.414 7.071-7.07z',
},
},
];
/**
* The icon for `link-unlink-m.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const linkUnlinkM: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M17.657 14.828l-1.414-1.414L17.657 12A4 4 0 1 0 12 6.343l-1.414 1.414-1.414-1.414 1.414-1.414a6 6 0 0 1 8.485 8.485l-1.414 1.414zm-2.829 2.829l-1.414 1.414a6 6 0 1 1-8.485-8.485l1.414-1.414 1.414 1.414L6.343 12A4 4 0 1 0 12 17.657l1.414-1.414 1.414 1.414zm0-9.9l1.415 1.415-7.071 7.07-1.415-1.414 7.071-7.07zM5.775 2.293l1.932-.518L8.742 5.64l-1.931.518-1.036-3.864zm9.483 16.068l1.931-.518 1.036 3.864-1.932.518-1.035-3.864zM2.293 5.775l3.864 1.036-.518 1.931-3.864-1.035.518-1.932zm16.068 9.483l3.864 1.035-.518 1.932-3.864-1.036.518-1.931z',
},
},
];
/**
* The icon for `link-unlink.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const linkUnlink: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M17 17h5v2h-3v3h-2v-5zM7 7H2V5h3V2h2v5zm11.364 8.536L16.95 14.12l1.414-1.414a5 5 0 1 0-7.071-7.071L9.879 7.05 8.464 5.636 9.88 4.222a7 7 0 0 1 9.9 9.9l-1.415 1.414zm-2.828 2.828l-1.415 1.414a7 7 0 0 1-9.9-9.9l1.415-1.414L7.05 9.88l-1.414 1.414a5 5 0 1 0 7.071 7.071l1.414-1.414 1.415 1.414zm-.708-10.607l1.415 1.415-7.071 7.07-1.415-1.414 7.071-7.07z',
},
},
];
/**
* The icon for `link.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const link: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M18.364 15.536L16.95 14.12l1.414-1.414a5 5 0 1 0-7.071-7.071L9.879 7.05 8.464 5.636 9.88 4.222a7 7 0 0 1 9.9 9.9l-1.415 1.414zm-2.828 2.828l-1.415 1.414a7 7 0 0 1-9.9-9.9l1.415-1.414L7.05 9.88l-1.414 1.414a5 5 0 1 0 7.071 7.071l1.414-1.414 1.415 1.414zm-.708-10.607l1.415 1.415-7.071 7.07-1.415-1.414 7.071-7.07z',
},
},
];
/**
* The icon for `list-check-2.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const listCheck2: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M11 4h10v2H11V4zm0 4h6v2h-6V8zm0 6h10v2H11v-2zm0 4h6v2h-6v-2zM3 4h6v6H3V4zm2 2v2h2V6H5zm-2 8h6v6H3v-6zm2 2v2h2v-2H5z',
},
},
];
/**
* The icon for `list-check.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const listCheck: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M8 4h13v2H8V4zm-5-.5h3v3H3v-3zm0 7h3v3H3v-3zm0 7h3v3H3v-3zM8 11h13v2H8v-2zm0 7h13v2H8v-2z',
},
},
];
/**
* The icon for `list-ordered.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const listOrdered: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M8 4h13v2H8V4zM5 3v3h1v1H3V6h1V4H3V3h2zM3 14v-2.5h2V11H3v-1h3v2.5H4v.5h2v1H3zm2 5.5H3v-1h2V18H3v-1h3v4H3v-1h2v-.5zM8 11h13v2H8v-2zm0 7h13v2H8v-2z',
},
},
];
/**
* The icon for `list-unordered.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const listUnordered: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M8 4h13v2H8V4zM4.5 6.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm0 7a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm0 6.9a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zM8 11h13v2H8v-2zm0 7h13v2H8v-2z',
},
},
];
/**
* The icon for `mark-pen-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const markPenLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M15.243 4.515l-6.738 6.737-.707 2.121-1.04 1.041 2.828 2.829 1.04-1.041 2.122-.707 6.737-6.738-4.242-4.242zm6.364 3.535a1 1 0 0 1 0 1.414l-7.779 7.779-2.12.707-1.415 1.414a1 1 0 0 1-1.414 0l-4.243-4.243a1 1 0 0 1 0-1.414l1.414-1.414.707-2.121 7.779-7.779a1 1 0 0 1 1.414 0l5.657 5.657zm-6.364-.707l1.414 1.414-4.95 4.95-1.414-1.414 4.95-4.95zM4.283 16.89l2.828 2.829-1.414 1.414-4.243-1.414 2.828-2.829z',
},
},
];
/**
* The icon for `markdown-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const markdownFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M3 3h18a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zm4 12.5v-4l2 2 2-2v4h2v-7h-2l-2 2-2-2H5v7h2zm11-3v-4h-2v4h-2l3 3 3-3h-2z',
},
},
];
/**
* The icon for `markdown-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const markdownLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
fillRule: 'nonzero',
d: 'M3 3h18a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zm1 2v14h16V5H4zm3 10.5H5v-7h2l2 2 2-2h2v7h-2v-4l-2 2-2-2v4zm11-3h2l-3 3-3-3h2v-4h2v4z',
},
},
];
/**
* The icon for `merge-cells-horizontal.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const mergeCellsHorizontal: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M20 3c.552 0 1 .448 1 1v16c0 .552-.448 1-1 1H4c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h16zm-9 2H5v5.999h2V9l3 3-3 3v-2H5v6h6v-2h2v2h6v-6h-2v2l-3-3 3-3v1.999h2V5h-6v2h-2V5zm2 8v2h-2v-2h2zm0-4v2h-2V9h2z',
},
},
];
/**
* The icon for `merge-cells-vertical.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const mergeCellsVertical: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M21 20c0 .552-.448 1-1 1H4c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h16c.552 0 1 .448 1 1v16zm-2-9V5h-5.999v2H15l-3 3-3-3h2V5H5v6h2v2H5v6h6v-2H9l3-3 3 3h-1.999v2H19v-6h-2v-2h2zm-8 2H9v-2h2v2zm4 0h-2v-2h2v2z',
},
},
];
/**
* The icon for `mind-map.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const mindMap: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M18 3c1.657 0 3 1.343 3 3s-1.343 3-3 3h-3c-1.306 0-2.417-.834-2.829-2H11c-1.1 0-2 .9-2 2v.171c1.166.412 2 1.523 2 2.829 0 1.306-.834 2.417-2 2.829V15c0 1.1.9 2 2 2h1.17c.412-1.165 1.524-2 2.83-2h3c1.657 0 3 1.343 3 3s-1.343 3-3 3h-3c-1.306 0-2.417-.834-2.829-2H11c-2.21 0-4-1.79-4-4H5c-1.657 0-3-1.343-3-3s1.343-3 3-3h2c0-2.21 1.79-4 4-4h1.17c.412-1.165 1.524-2 2.83-2h3zm0 14h-3c-.552 0-1 .448-1 1s.448 1 1 1h3c.552 0 1-.448 1-1s-.448-1-1-1zM8 11H5c-.552 0-1 .448-1 1s.448 1 1 1h3c.552 0 1-.448 1-1s-.448-1-1-1zm10-6h-3c-.552 0-1 .448-1 1s.448 1 1 1h3c.552 0 1-.448 1-1s-.448-1-1-1z',
},
},
];
/**
* The icon for `more-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const moreFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M5 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm14 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-7 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z',
},
},
];
/**
* The icon for `node-tree.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const nodeTree: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M10 2c.552 0 1 .448 1 1v4c0 .552-.448 1-1 1H8v2h5V9c0-.552.448-1 1-1h6c.552 0 1 .448 1 1v4c0 .552-.448 1-1 1h-6c-.552 0-1-.448-1-1v-1H8v6h5v-1c0-.552.448-1 1-1h6c.552 0 1 .448 1 1v4c0 .552-.448 1-1 1h-6c-.552 0-1-.448-1-1v-1H7c-.552 0-1-.448-1-1V8H4c-.552 0-1-.448-1-1V3c0-.552.448-1 1-1h6zm9 16h-4v2h4v-2zm0-8h-4v2h4v-2zM9 4H5v2h4V4z',
},
},
];
/**
* The icon for `number-0.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const number0: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 1.5c1.321 0 2.484.348 3.447.994.963.645 1.726 1.588 2.249 2.778.522 1.19.804 2.625.804 4.257v4.942c0 1.632-.282 3.068-.804 4.257-.523 1.19-1.286 2.133-2.25 2.778-.962.646-2.125.994-3.446.994-1.321 0-2.484-.348-3.447-.994-.963-.645-1.726-1.588-2.249-2.778-.522-1.19-.804-2.625-.804-4.257V9.529c0-1.632.282-3.068.804-4.257.523-1.19 1.286-2.133 2.25-2.778C9.515 1.848 10.678 1.5 12 1.5zm0 2c-.916 0-1.694.226-2.333.655-.637.427-1.158 1.07-1.532 1.92-.412.94-.635 2.108-.635 3.454v4.942c0 1.346.223 2.514.635 3.453.374.851.895 1.494 1.532 1.921.639.429 1.417.655 2.333.655.916 0 1.694-.226 2.333-.655.637-.427 1.158-1.07 1.532-1.92.412-.94.635-2.108.635-3.454V9.529c0-1.346-.223-2.514-.635-3.453-.374-.851-.895-1.494-1.532-1.921C13.694 3.726 12.916 3.5 12 3.5z',
},
},
];
/**
* The icon for `number-1.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const number1: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M14 1.5V22h-2V3.704L7.5 4.91V2.839l5-1.339z' } },
];
/**
* The icon for `number-2.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const number2: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M16 7.5a4 4 0 1 0-8 0H6a6 6 0 1 1 10.663 3.776l-7.32 8.723L18 20v2H6v-1.127l9.064-10.802A3.982 3.982 0 0 0 16 7.5z',
},
},
];
/**
* The icon for `number-3.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const number3: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M18 2v1.362L12.809 9.55a6.501 6.501 0 1 1-7.116 8.028l1.94-.486A4.502 4.502 0 0 0 16.5 16a4.5 4.5 0 0 0-6.505-4.03l-.228.122-.69-1.207L14.855 4 6.5 4V2H18z',
},
},
];
/**
* The icon for `number-4.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const number4: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: { d: 'M16 1.5V16h3v2h-3v4h-2v-4H4v-1.102L14 1.5h2zM14 16V5.171L6.968 16H14z' },
},
];
/**
* The icon for `number-5.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const number5: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M18 2v2H9.3l-.677 6.445a6.5 6.5 0 1 1-2.93 7.133l1.94-.486A4.502 4.502 0 0 0 16.5 16a4.5 4.5 0 0 0-4.5-4.5c-2.022 0-3.278.639-3.96 1.53l-1.575-1.182L7.5 2H18z',
},
},
];
/**
* The icon for `number-6.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const number6: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M14.886 2l-4.438 7.686A6.5 6.5 0 1 1 6.4 12.7L12.576 2h2.31zM12 11.5a4.5 4.5 0 1 0 0 9 4.5 4.5 0 0 0 0-9z',
},
},
];
/**
* The icon for `number-7.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const number7: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M19 2v1.5L10.763 22H8.574l8.013-18H6V2z' } },
];
/**
* The icon for `number-8.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const number8: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 1.5a5.5 5.5 0 0 1 3.352 9.86C17.24 12.41 18.5 14.32 18.5 16.5c0 3.314-2.91 6-6.5 6s-6.5-2.686-6.5-6c0-2.181 1.261-4.09 3.147-5.141A5.5 5.5 0 0 1 12 1.5zm0 11c-2.52 0-4.5 1.828-4.5 4 0 2.172 1.98 4 4.5 4s4.5-1.828 4.5-4c0-2.172-1.98-4-4.5-4zm0-9a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7z',
},
},
];
/**
* The icon for `number-9.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const number9: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 1.5a6.5 6.5 0 0 1 5.619 9.77l-6.196 10.729H9.114l4.439-7.686A6.5 6.5 0 1 1 12 1.5zm0 2a4.5 4.5 0 1 0 0 9 4.5 4.5 0 0 0 0-9z',
},
},
];
/**
* The icon for `omega.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const omega: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
fillRule: 'nonzero',
d: 'M14 20v-2.157c1.863-1.192 3.5-3.875 3.5-6.959 0-3.073-2-6.029-5.5-6.029s-5.5 2.956-5.5 6.03c0 3.083 1.637 5.766 3.5 6.958V20H3v-2h4.76C5.666 16.505 4 13.989 4 10.884 4 6.247 7.5 3 12 3s8 3.247 8 7.884c0 3.105-1.666 5.621-3.76 7.116H21v2h-7z',
},
},
];
/**
* The icon for `organization-chart.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const organizationChart: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M15 3c.552 0 1 .448 1 1v4c0 .552-.448 1-1 1h-2v2h4c.552 0 1 .448 1 1v3h2c.552 0 1 .448 1 1v4c0 .552-.448 1-1 1h-6c-.552 0-1-.448-1-1v-4c0-.552.448-1 1-1h2v-2H8v2h2c.552 0 1 .448 1 1v4c0 .552-.448 1-1 1H4c-.552 0-1-.448-1-1v-4c0-.552.448-1 1-1h2v-3c0-.552.448-1 1-1h4V9H9c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h6zM9 17H5v2h4v-2zm10 0h-4v2h4v-2zM14 5h-4v2h4V5z',
},
},
];
/**
* The icon for `page-separator.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const pageSeparator: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M17 21v-4H7v4H5v-5a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v5h-2zM7 3v4h10V3h2v5a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V3h2zM2 9l4 3-4 3V9zm20 0v6l-4-3 4-3z',
},
},
];
/**
* The icon for `paragraph.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const paragraph: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: { d: 'M12 6v15h-2v-5a6 6 0 1 1 0-12h10v2h-3v15h-2V6h-3zm-2 0a4 4 0 1 0 0 8V6z' },
},
];
/**
* The icon for `pencil-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const pencilFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M12.9 6.858l4.242 4.243L7.242 21H3v-4.243l9.9-9.9zm1.414-1.414l2.121-2.122a1 1 0 0 1 1.414 0l2.829 2.829a1 1 0 0 1 0 1.414l-2.122 2.121-4.242-4.242z',
},
},
];
/**
* The icon for `pencil-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const pencilLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M15.728 9.686l-1.414-1.414L5 17.586V19h1.414l9.314-9.314zm1.414-1.414l1.414-1.414-1.414-1.414-1.414 1.414 1.414 1.414zM7.242 21H3v-4.243L16.435 3.322a1 1 0 0 1 1.414 0l2.829 2.829a1 1 0 0 1 0 1.414L7.243 21z',
},
},
];
/**
* The icon for `pinyin-input.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const pinyinInput: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M17.934 3.036l1.732 1L18.531 6H21v2h-2v4h2v2h-2v7h-2v-7h-3.084c-.325 2.862-1.564 5.394-3.37 7.193l-1.562-1.27c1.52-1.438 2.596-3.522 2.917-5.922L10 14v-2l2-.001V8h-2V6h2.467l-1.133-1.964 1.732-1L14.777 6h1.444l1.713-2.964zM5 13.803l-2 .536v-2.071l2-.536V8H3V6h2V3h2v3h2v2H7v3.197l2-.536v2.07l-2 .536V18.5A2.5 2.5 0 0 1 4.5 21H3v-2h1.5a.5.5 0 0 0 .492-.41L5 18.5v-4.697zM17 8h-3v4h3V8z',
},
},
];
/**
* The icon for `question-mark.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const questionMark: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M12 19c.828 0 1.5.672 1.5 1.5S12.828 22 12 22s-1.5-.672-1.5-1.5.672-1.5 1.5-1.5zm0-17c3.314 0 6 2.686 6 6 0 2.165-.753 3.29-2.674 4.923C13.399 14.56 13 15.297 13 17h-2c0-2.474.787-3.695 3.031-5.601C15.548 10.11 16 9.434 16 8c0-2.21-1.79-4-4-4S8 5.79 8 8v1H6V8c0-3.314 2.686-6 6-6z',
},
},
];
/**
* The icon for `rounded-corner.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const roundedCorner: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M21 19v2h-2v-2h2zm-4 0v2h-2v-2h2zm-4 0v2h-2v-2h2zm-4 0v2H7v-2h2zm-4 0v2H3v-2h2zm16-4v2h-2v-2h2zM5 15v2H3v-2h2zm0-4v2H3v-2h2zm11-8c2.687 0 4.882 2.124 4.995 4.783L21 8v5h-2V8c0-1.591-1.255-2.903-2.824-2.995L16 5h-5V3h5zM5 7v2H3V7h2zm0-4v2H3V3h2zm4 0v2H7V3h2z',
},
},
];
/**
* The icon for `scissors-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const scissorsFill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M9.683 7.562L12 9.88l6.374-6.375a2 2 0 0 1 2.829 0l.707.707L9.683 16.438a4 4 0 1 1-2.121-2.121L9.88 12 7.562 9.683a4 4 0 1 1 2.121-2.121zM6 8a2 2 0 1 0 0-4 2 2 0 0 0 0 4zm0 12a2 2 0 1 0 0-4 2 2 0 0 0 0 4zm9.535-6.587l6.375 6.376-.707.707a2 2 0 0 1-2.829 0l-4.96-4.961 2.12-2.122z',
},
},
];
/**
* The icon for `send-backward.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const sendBackward: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M14 3c.552 0 1 .448 1 1v5h5c.552 0 1 .448 1 1v10c0 .552-.448 1-1 1H10c-.552 0-1-.448-1-1v-5H4c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h10zm-1 2H5v8h4v-3c0-.552.448-1 1-1h3V5z',
},
},
];
/**
* The icon for `send-to-back.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const sendToBack: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M11 3c.552 0 1 .448 1 1v2h5c.552 0 1 .448 1 1v5h2c.552 0 1 .448 1 1v7c0 .552-.448 1-1 1h-7c-.552 0-1-.448-1-1v-2H7c-.552 0-1-.448-1-1v-5H4c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h7zm5 5h-4v3c0 .552-.448 1-1 1H8v4h4v-3c0-.552.448-1 1-1h3V8z',
},
},
];
/**
* The icon for `separator.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const separator: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M2 11h2v2H2v-2zm4 0h12v2H6v-2zm14 0h2v2h-2v-2z' } },
];
/**
* The icon for `single-quotes-l.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const singleQuotesL: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M9.583 17.321C8.553 16.227 8 15 8 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311 1.804.167 3.226 1.648 3.226 3.489a3.5 3.5 0 0 1-3.5 3.5c-1.073 0-2.099-.49-2.748-1.179z',
},
},
];
/**
* The icon for `single-quotes-r.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const singleQuotesR: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M14.417 6.679C15.447 7.773 16 9 16 10.989c0 3.5-2.457 6.637-6.03 8.188l-.893-1.378c3.335-1.804 3.987-4.145 4.247-5.621-.537.278-1.24.375-1.929.311C9.591 12.322 8.17 10.841 8.17 9a3.5 3.5 0 0 1 3.5-3.5c1.073 0 2.099.49 2.748 1.179z',
},
},
];
/**
* The icon for `sort-asc.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const sortAsc: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: { d: 'M19 3l4 5h-3v12h-2V8h-3l4-5zm-5 15v2H3v-2h11zm0-7v2H3v-2h11zm-2-7v2H3V4h9z' },
},
];
/**
* The icon for `sort-desc.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const sortDesc: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: { d: 'M20 4v12h3l-4 5-4-5h3V4h2zm-8 14v2H3v-2h9zm2-7v2H3v-2h11zm0-7v2H3V4h11z' },
},
];
/**
* The icon for `space.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const space: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M4 9v4h16V9h2v5a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V9h2z' } },
];
/**
* The icon for `spam-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const spamLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
fillRule: 'nonzero',
d: 'M17.5 2.5L23 12l-5.5 9.5h-11L1 12l5.5-9.5h11zm-1.153 2H7.653L3.311 12l4.342 7.5h8.694l4.342-7.5-4.342-7.5zM11 15h2v2h-2v-2zm0-8h2v6h-2V7z',
},
},
];
/**
* The icon for `split-cells-horizontal.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const splitCellsHorizontal: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M20 3c.552 0 1 .448 1 1v16c0 .552-.448 1-1 1H4c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h16zm-9 2H5v14h6v-4h2v4h6V5h-6v4h-2V5zm4 4l3 3-3 3v-2H9v2l-3-3 3-3v2h6V9z',
},
},
];
/**
* The icon for `split-cells-vertical.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const splitCellsVertical: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0H24V24H0z' } },
{
tag: 'path',
attr: {
d: 'M20 3c.552 0 1 .448 1 1v16c0 .552-.448 1-1 1H4c-.552 0-1-.448-1-1V4c0-.552.448-1 1-1h16zm-1 2H5v5.999L9 11v2H5v6h14v-6h-4v-2l4-.001V5zm-7 1l3 3h-2v6h2l-3 3-3-3h2V9H9l3-3z',
},
},
];
/**
* The icon for `strikethrough-2.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const strikethrough2: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M13 9h-2V6H5V4h14v2h-6v3zm0 6v5h-2v-5h2zM3 11h18v2H3v-2z' } },
];
/**
* The icon for `strikethrough.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const strikethrough: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M17.154 14c.23.516.346 1.09.346 1.72 0 1.342-.524 2.392-1.571 3.147C14.88 19.622 13.433 20 11.586 20c-1.64 0-3.263-.381-4.87-1.144V16.6c1.52.877 3.075 1.316 4.666 1.316 2.551 0 3.83-.732 3.839-2.197a2.21 2.21 0 0 0-.648-1.603l-.12-.117H3v-2h18v2h-3.846zm-4.078-3H7.629a4.086 4.086 0 0 1-.481-.522C6.716 9.92 6.5 9.246 6.5 8.452c0-1.236.466-2.287 1.397-3.153C8.83 4.433 10.271 4 12.222 4c1.471 0 2.879.328 4.222.984v2.152c-1.2-.687-2.515-1.03-3.946-1.03-2.48 0-3.719.782-3.719 2.346 0 .42.218.786.654 1.099.436.313.974.562 1.613.75.62.18 1.297.414 2.03.699z',
},
},
];
/**
* The icon for `subscript-2.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const subscript2: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M11 6v13H9V6H3V4h14v2h-6zm8.55 10.58a.8.8 0 1 0-1.32-.36l-1.154.33A2.001 2.001 0 0 1 19 14a2 2 0 0 1 1.373 3.454L18.744 19H21v1h-4v-1l2.55-2.42z',
},
},
];
/**
* The icon for `subscript.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const subscript: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M5.596 4L10.5 9.928 15.404 4H18l-6.202 7.497L18 18.994V19h-2.59l-4.91-5.934L5.59 19H3v-.006l6.202-7.497L3 4h2.596zM21.55 16.58a.8.8 0 1 0-1.32-.36l-1.155.33A2.001 2.001 0 0 1 21 14a2 2 0 0 1 1.373 3.454L20.744 19H23v1h-4v-1l2.55-2.42z',
},
},
];
/**
* The icon for `subtract-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const subtractLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M5 11h14v2H5z' } },
];
/**
* The icon for `superscript-2.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const superscript2: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M11 7v13H9V7H3V5h12v2h-4zm8.55-.42a.8.8 0 1 0-1.32-.36l-1.154.33A2.001 2.001 0 0 1 19 4a2 2 0 0 1 1.373 3.454L18.744 9H21v1h-4V9l2.55-2.42z',
},
},
];
/**
* The icon for `superscript.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const superscript: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M5.596 5l4.904 5.928L15.404 5H18l-6.202 7.497L18 19.994V20h-2.59l-4.91-5.934L5.59 20H3v-.006l6.202-7.497L3 5h2.596zM21.55 6.58a.8.8 0 1 0-1.32-.36l-1.155.33A2.001 2.001 0 0 1 21 4a2 2 0 0 1 1.373 3.454L20.744 9H23v1h-4V9l2.55-2.42z',
},
},
];
/**
* The icon for `table-2.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const table2: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
fillRule: 'nonzero',
d: 'M13 10v4h6v-4h-6zm-2 0H5v4h6v-4zm2 9h6v-3h-6v3zm-2 0v-3H5v3h6zm2-14v3h6V5h-6zm-2 0H5v3h6V5zM4 3h16a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z',
},
},
];
/**
* The icon for `table-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const tableLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M4 8h16V5H4v3zm10 11v-9h-4v9h4zm2 0h4v-9h-4v9zm-8 0v-9H4v9h4zM3 3h18a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z',
},
},
];
/**
* The icon for `text-direction-l.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const textDirectionL: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M11 5v10H9v-4a4 4 0 1 1 0-8h8v2h-2v10h-2V5h-2zM9 5a2 2 0 1 0 0 4V5zm8 12v-2.5l4 3.5-4 3.5V19H5v-2h12z',
},
},
];
/**
* The icon for `text-direction-r.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const textDirectionR: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M11 5v10H9v-4a4 4 0 1 1 0-8h8v2h-2v10h-2V5h-2zM9 5a2 2 0 1 0 0 4V5zM7 17h12v2H7v2.5L3 18l4-3.5V17z',
},
},
];
/**
* The icon for `text-spacing.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const textSpacing: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M7 17h10v-2.5l3.5 3.5-3.5 3.5V19H7v2.5L3.5 18 7 14.5V17zm6-11v9h-2V6H5V4h14v2h-6z',
},
},
];
/**
* The icon for `text-wrap.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const textWrap: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M15 18h1.5a2.5 2.5 0 1 0 0-5H3v-2h13.5a4.5 4.5 0 1 1 0 9H15v2l-4-3 4-3v2zM3 4h18v2H3V4zm6 14v2H3v-2h6z',
},
},
];
/**
* The icon for `text.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const text: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M13 6v15h-2V6H5V4h14v2z' } },
];
/**
* The icon for `translate-2.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const translate2: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M18.5 10l4.4 11h-2.155l-1.201-3h-4.09l-1.199 3h-2.154L16.5 10h2zM10 2v2h6v2h-1.968a18.222 18.222 0 0 1-3.62 6.301 14.864 14.864 0 0 0 2.336 1.707l-.751 1.878A17.015 17.015 0 0 1 9 13.725a16.676 16.676 0 0 1-6.201 3.548l-.536-1.929a14.7 14.7 0 0 0 5.327-3.042A18.078 18.078 0 0 1 4.767 8h2.24A16.032 16.032 0 0 0 9 10.877a16.165 16.165 0 0 0 2.91-4.876L2 6V4h6V2h2zm7.5 10.885L16.253 16h2.492L17.5 12.885z',
},
},
];
/**
* The icon for `translate.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const translate: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M5 15v2a2 2 0 0 0 1.85 1.995L7 19h3v2H7a4 4 0 0 1-4-4v-2h2zm13-5l4.4 11h-2.155l-1.201-3h-4.09l-1.199 3h-2.154L16 10h2zm-1 2.885L15.753 16h2.492L17 12.885zM8 2v2h4v7H8v3H6v-3H2V4h4V2h2zm9 1a4 4 0 0 1 4 4v2h-2V7a2 2 0 0 0-2-2h-3V3h3zM6 6H4v3h2V6zm4 0H8v3h2V6z',
},
},
];
/**
* The icon for `underline.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const underline: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{ tag: 'path', attr: { d: 'M8 3v9a4 4 0 1 0 8 0V3h2v9a6 6 0 1 1-12 0V3h2zM4 20h16v2H4v-2z' } },
];
/**
* The icon for `upload-2-fill.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const upload2Fill: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: { d: 'M4 19h16v-7h2v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-8h2v7zM14 9v6h-4V9H5l7-7 7 7h-5z' },
},
];
/**
* The icon for `video-line.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const videoLine: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M3 3.993C3 3.445 3.445 3 3.993 3h16.014c.548 0 .993.445.993.993v16.014a.994.994 0 0 1-.993.993H3.993A.994.994 0 0 1 3 20.007V3.993zM5 5v14h14V5H5zm5.622 3.415l4.879 3.252a.4.4 0 0 1 0 .666l-4.88 3.252a.4.4 0 0 1-.621-.332V8.747a.4.4 0 0 1 .622-.332z',
},
},
];
/**
* The icon for `wubi-input.svg` created by [RemixIcons](https://remixicons.com).
* 
*/
export const wubiInput: IconTree[] = [
{ tag: 'path', attr: { fill: 'none', d: 'M0 0h24v24H0z' } },
{
tag: 'path',
attr: {
d: 'M3 21v-2h3.662l1.234-7H5v-2h3.249l.881-5H4V3h16v2h-8.839l-.882 5H18v9h3v2H3zm13-9H9.927l-1.235 7H16v-7z',
},
},
]; | the_stack |
import { getMeshUuid } from '../../connection_manager';
import { registerActionMap } from './api_protocol_base.js';
import { System } from '../../api/system.js';
import * as log from '../../log';
import {
Acker,
APIHandlerMap,
APIMessage,
APIPayloadAck,
Cookie,
Entity,
FileStatInfo,
Identity,
Nacker,
NackerError,
NackerErrorString,
PreloadScript,
StartManifest
} from '../../../shapes';
import { DownloadResult } from '../../../browser/preload_scripts';
const successAck: APIPayloadAck = { success: true };
const ReadRegistryValuePolicyDelegate = {
//checkPermissions(ApiPolicyDelegateArgs): boolean;
checkPermissions: (args: any): boolean => {
// permissionSettings has following format
// { "enabled": true, "registryKeys": [ "HKEY_CURRENT_USER\\Software\\OpenFin\\RVM" ] }
let permitted = false; // default to false
if (args.payload && args.permissionSettings && args.permissionSettings.enabled === true) {
if (Array.isArray(args.permissionSettings.registryKeys)) {
let fullPath = args.payload.rootKey;
if (args.payload.subkey) {
fullPath = fullPath.concat('\\' + args.payload.subkey);
}
if (args.payload.value) {
fullPath = fullPath.concat('\\' + args.payload.value);
}
permitted = args.permissionSettings.registryKeys.some((specKey: string) => fullPath.startsWith(specKey));
}
}
log.writeToLog(1, `ReadRegistryValueDelegate returning ${permitted}`, true);
return permitted;
}
};
export const SystemApiMap: APIHandlerMap = {
'clear-cache': { apiFunc: clearCache, apiPath: '.clearCache' },
'create-proxy-socket': createProxySocket,
'authenticate-proxy-socket': authenticateProxySocket,
'convert-options': convertOptions,
'delete-cache-request': { apiFunc: deleteCacheRequest, apiPath: '.deleteCacheOnExit' },
'download-asset': { apiFunc: downloadAsset, apiPath: '.downloadAsset', defaultPermission: false },
'download-preload-scripts': { apiFunc: downloadPreloadScripts, apiPath: '.downloadPreloadScripts'},
'download-runtime': { apiFunc: downloadRuntime, apiPath: '.downloadRuntime' },
'entity-exists': entityExists,
'exit-desktop': { apiFunc: exitDesktop, apiPath: '.exit' },
'flush-cookie-store': { apiFunc: flushCookieStore, apiPath: '.flushCookieStore' },
'generate-guid': generateGuid,
'get-all-applications': getAllApplications,
'get-all-external-applications': getAllExternalApplications,
'get-all-external-windows': {
apiFunc: getAllExternalWindows,
apiPath: '.getAllExternalWindows',
defaultPermission: false
},
'get-all-windows': getAllWindows,
'get-app-asset-info': getAppAssetInfo,
'get-command-line-arguments': { apiFunc: getCommandLineArguments, apiPath: '.getCommandLineArguments' },
'get-config': { apiFunc: getConfig, apiPath: '.getConfig' },
'get-crash-reporter-state': getCrashReporterState,
'get-device-id': { apiFunc: getDeviceId, apiPath: '.getDeviceId' },
'get-device-user-id': { apiFunc: getDeviceUserId, apiPath: '.getDeviceUserId' },
'get-entity-info': getEntityInfo,
'get-environment-variable': { apiFunc: getEnvironmentVariable, apiPath: '.getEnvironmentVariable' },
'get-focused-window': getFocusedWindow,
'get-focused-external-window': getFocusedExternalWindow,
'get-host-specs': { apiFunc: getHostSpecs, apiPath: '.getHostSpecs' },
'get-installed-runtimes': {apiFunc: getInstalledRuntimes, apiPath: '.getInstalledRuntimes' },
'get-machine-id': { apiFunc: getMachineId, apiPath: '.getMachineId' },
'get-min-log-level': getMinLogLevel,
'get-monitor-info': { apiFunc: getMonitorInfo, apiPath: '.getMonitorInfo' },
'get-mouse-position': { apiFunc: getMousePosition, apiPath: '.getMousePosition' },
'get-nearest-display-root': getNearestDisplayRoot,
'get-proxy-settings': getProxySettings,
'get-remote-config': { apiFunc: getRemoteConfig, apiPath: '.getRemoteConfig' },
'get-runtime-info': getRuntimeInfo,
'get-rvm-info': getRvmInfo,
'get-service-configuration': getServiceConfiguration,
'get-preload-scripts': getPreloadScripts,
'get-version': getVersion,
'launch-external-process': { apiFunc: launchExternalProcess, apiPath: '.launchExternalProcess', defaultPermission: false },
'list-logs': { apiFunc: listLogs, apiPath: '.getLogList' },
'monitor-external-process': { apiFunc: monitorExternalProcess, apiPath: '.monitorExternalProcess' },
'open-url-with-browser': openUrlWithBrowser,
'process-snapshot': { apiFunc: processSnapshot, apiPath: '.getProcessList' },
'raise-event': raiseEvent,
'raise-many-events': raiseManyEvents,
'read-registry-value': {
apiFunc: readRegistryValue,
apiPath: '.readRegistryValue',
apiPolicyDelegate: ReadRegistryValuePolicyDelegate,
defaultPermission: false
},
'release-external-process': { apiFunc: releaseExternalProcess, apiPath: '.releaseExternalProcess' },
'resolve-uuid': resolveUuid,
'resource-fetch-authenticate': { apiFunc: authenticateResourceFetch },
//'set-clipboard': setClipboard, -> moved to clipboard.ts
'get-cookies': { apiFunc: getCookies, apiPath: '.getCookies' },
'set-cookie': setCookie,
'set-min-log-level': setMinLogLevel,
'show-developer-tools': showDeveloperTools,
'start-crash-reporter': startCrashReporter,
'terminate-external-process': { apiFunc: terminateExternalProcess, apiPath: '.terminateExternalProcess', defaultPermission: false },
'update-proxy': updateProxy,
'view-log': { apiFunc: viewLog, apiPath: '.getLog' },
'write-to-log': writeToLog
};
export function init(): void {
registerActionMap(SystemApiMap, 'System');
}
function didFail(e: any): boolean {
return e !== undefined && e.constructor === Error;
}
const dosURL = 'https://openfin.co/documentation/desktop-owner-settings/';
async function getServiceConfiguration(identity: Identity, message: APIMessage) {
const { name } = message.payload;
const response = await System.getServiceConfiguration();
if (didFail(response)) {
throw response;
}
if (!Array.isArray(response)) {
throw new Error(`Settings in desktop owner settings are not configured correctly, please see
${dosURL} for configuration information`);
}
const config = response.find(service => service.name === name);
if (!config) {
throw new Error(`Service configuration for ${name} not available`);
}
return config;
}
function readRegistryValue(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
const { payload: { rootKey, subkey, value } } = message;
dataAck.data = System.readRegistryValue(rootKey, subkey, value);
ack(dataAck);
}
function setMinLogLevel(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const { payload: { level } } = message;
const response = System.setMinLogLevel(level);
if (didFail(response)) {
nack(response);
} else {
ack(successAck);
}
}
function getMinLogLevel(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const response = System.getMinLogLevel();
if (didFail(response)) {
nack(response);
} else {
const dataAck = Object.assign({}, successAck);
dataAck.data = response;
ack(dataAck);
}
}
function startCrashReporter(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
const { payload } = message;
dataAck.data = System.startCrashReporter(identity, payload);
ack(dataAck);
}
function getCrashReporterState(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getCrashReporterState();
ack(dataAck);
}
function getAppAssetInfo(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const options = message.payload;
System.getAppAssetInfo(identity, options, (data: any) => {
const dataAck = Object.assign({}, successAck);
delete data.path; // remove path due to security concern
dataAck.data = data;
ack(dataAck);
}, nack);
}
function getDeviceUserId(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getDeviceUserId();
ack(dataAck);
}
function raiseEvent(identity: Identity, message: APIMessage, ack: Acker): void {
const { payload: { eventName, eventArgs } } = message;
System.raiseEvent(eventName, eventArgs);
ack(successAck);
}
function raiseManyEvents(identity: Identity, message: APIMessage): void {
const { payload } = message;
return System.raiseManyEvents(payload);
}
function convertOptions(identity: Identity, message: APIMessage, ack: Acker): void {
const { payload } = message;
const dataAck = Object.assign({}, successAck);
dataAck.data = System.convertOptions(payload);
ack(dataAck);
}
function generateGuid(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.generateGUID();
ack(dataAck);
}
function showDeveloperTools(identity: Identity, message: APIMessage, ack: Acker): void {
const { payload: { uuid, name } } = message;
System.showDeveloperTools(uuid, name);
ack(successAck);
}
function clearCache(identity: Identity, message: APIMessage, ack: Acker, nack: NackerError): void {
const { payload } = message;
System.clearCache(identity, payload, (err: Error) => {
if (!err) {
ack(successAck);
} else {
nack(err);
}
});
}
function createProxySocket(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const { payload } = message;
System.createProxySocket(payload, ack, nack);
}
function authenticateProxySocket(identity: Identity, message: APIMessage): void {
const { payload } = message;
System.authenticateProxySocket(payload);
}
function deleteCacheRequest(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
// deleteCacheOnRestart has been deprecated; redirects to deleteCacheOnExit
System.deleteCacheOnExit(() => ack(successAck), nack);
}
function exitDesktop(identity: Identity, message: APIMessage, ack: Acker): void {
ack(successAck);
System.exit();
}
function getAllApplications(identity: Identity, message: APIMessage, ack: Acker): void {
const { locals } = message;
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getAllApplications();
if (locals && locals.aggregate) {
const { aggregate } = locals;
dataAck.data = [...dataAck.data, ...aggregate];
}
ack(dataAck);
}
function getAllExternalApplications(identity: Identity, message: APIMessage, ack: Acker): void {
const { locals } = message;
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getAllExternalApplications();
if (locals && locals.aggregate) {
const { aggregate } = locals;
const currentApplication = getMeshUuid();
const filteredAggregate = aggregate.filter((result: Entity) => (result.uuid !== currentApplication));
const filteredAggregateSet = [...new Set(filteredAggregate)];
dataAck.data = [...dataAck.data, ...filteredAggregateSet];
}
ack(dataAck);
}
function getAllExternalWindows(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getAllExternalWindows();
ack(dataAck);
}
function getAllWindows(identity: Identity, message: APIMessage, ack: Acker): void {
const { locals } = message;
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getAllWindows();
if (locals && locals.aggregate) {
const { aggregate } = locals;
dataAck.data = [...dataAck.data, ...aggregate];
}
ack(dataAck);
}
function getCommandLineArguments(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getCommandLineArguments();
ack(dataAck);
}
function getConfig(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = (<StartManifest>System.getConfig()).data;
ack(dataAck);
}
function getDeviceId(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getDeviceId();
ack(dataAck);
}
function getEntityInfo(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): Identity {
const { payload: { uuid, name } } = message;
return System.getEntityInfo({ uuid, name });
}
function getFocusedWindow(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
const {locals} = message;
if (locals && locals.aggregate) {
const found = locals.aggregate.find((x: any) => !!x);
if (found) {
dataAck.data = found;
return ack(dataAck);
}
}
dataAck.data = System.getFocusedWindow();
ack(dataAck);
}
function getFocusedExternalWindow(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getFocusedExternalWindow();
ack(dataAck);
}
function getRemoteConfig(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const { payload: { url } } = message;
System.getRemoteConfig(url, (data: any) => {
const dataAck = Object.assign({}, successAck);
dataAck.data = data;
ack(dataAck);
}, nack);
}
function getEnvironmentVariable(identity: Identity, message: APIMessage, ack: Acker): void {
const { payload: { environmentVariables } } = message;
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getEnvironmentVariable(environmentVariables);
ack(dataAck);
}
function viewLog(identity: Identity, message: APIMessage, ack: Acker, nack: NackerErrorString): void {
const { payload: { name = '' } = {} } = message;
System.getLog(name, (err: undefined | string, contents: string) => {
if (!err) {
const dataAck = Object.assign({}, successAck);
dataAck.data = contents;
ack(dataAck);
} else {
nack(err);
}
});
}
function listLogs(identity: Identity, message: APIMessage, ack: Acker, nack: NackerErrorString): void {
System.getLogList((err: undefined | string, logList: FileStatInfo[]) => {
if (!err) {
const dataAck = Object.assign({}, successAck);
dataAck.data = logList;
ack(dataAck);
} else {
nack(err);
}
});
}
function getMonitorInfo(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getMonitorInfo();
ack(dataAck);
}
function getMousePosition(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getMousePosition();
ack(dataAck);
}
function processSnapshot(identity: Identity, message: APIMessage, ack: Acker): void {
const { locals } = message;
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getProcessList();
if (locals && locals.aggregate) {
const { aggregate } = locals;
const aggregateSet = [...new Set(aggregate)];
dataAck.data = [...dataAck.data, ...aggregateSet];
}
ack(dataAck);
}
function getProxySettings(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getProxySettings();
ack(dataAck);
}
function getVersion(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getVersion();
ack(dataAck);
}
function getRuntimeInfo(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getRuntimeInfo(identity);
ack(dataAck);
}
function getRvmInfo(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
System.getRvmInfo(identity, (data: any) => {
const dataAck = Object.assign({}, successAck);
dataAck.data = data;
ack(dataAck);
}, nack);
}
function getInstalledRuntimes(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker) : void {
System.getInstalledRuntimes(identity, (data: any) => {
const dataAck = Object.assign({}, successAck);
dataAck.data = data;
ack(dataAck);
}, nack);
}
function launchExternalProcess(identity: Identity, message: APIMessage, ack: Acker, nack: NackerError): void {
const { payload } = message;
System.launchExternalProcess(identity, payload, (err: undefined | Error, res: any) => {
if (!err) {
const dataAck = Object.assign({}, successAck);
dataAck.data = res;
ack(dataAck);
} else {
nack(err);
}
});
}
function writeToLog(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const { payload = {} } = message;
const { level: logLevel = '', message: logMessage = '' } = payload;
const err = System.log(logLevel, logMessage);
if (err) {
nack(err);
} else {
ack(successAck);
}
}
function openUrlWithBrowser(identity: Identity, message: APIMessage, ack: Acker): void {
const { payload: { url } } = message;
System.openUrlWithBrowser(url);
ack(successAck);
}
function releaseExternalProcess(identity: Identity, message: APIMessage, ack: Acker): void {
const { payload: { uuid } } = message;
System.releaseExternalProcess(uuid);
ack(successAck);
}
function monitorExternalProcess(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const { payload } = message;
System.monitorExternalProcess(identity, payload, (data: any) => {
const dataAck = Object.assign({}, successAck);
dataAck.data = data;
ack(dataAck);
}, nack);
}
function setCookie(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const { payload } = message;
System.setCookie(payload, () => ack(successAck), nack);
}
function getCookies(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const { payload } = message;
System.getCookies(payload, (data: Cookie[]) => {
const dataAck = Object.assign({}, successAck);
dataAck.data = data;
ack(dataAck);
}, nack);
}
function flushCookieStore(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
System.flushCookieStore(() => ack(successAck));
}
function terminateExternalProcess(identity: Identity, message: APIMessage, ack: Acker): void {
const { payload = {} } = message;
const { uuid, timeout, child } = payload;
const dataAck = Object.assign({}, successAck);
dataAck.data = System.terminateExternalProcess(uuid, timeout, child);
ack(dataAck);
}
function updateProxy(identity: Identity, message: APIMessage, ack: Acker, nack: NackerErrorString): void {
const { payload: { type, proxyAddress, proxyPort } } = message;
const err = System.updateProxySettings(type, proxyAddress, proxyPort);
if (!err) {
ack(successAck);
} else {
nack(err);
}
}
function getNearestDisplayRoot(identity: Identity, message: APIMessage, ack: Acker): void {
const { payload } = message;
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getNearestDisplayRoot(payload);
ack(dataAck);
}
function downloadAsset(identity: Identity, message: APIMessage, ack: Acker, nack: NackerError): void {
const { payload } = message;
System.downloadAsset(identity, payload, (err: void | Error) => {
if (!err) {
ack(successAck);
} else {
nack(err);
}
});
}
function downloadPreloadScripts(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const { payload: { scripts } } = message;
System.downloadPreloadScripts(identity, scripts)
.then((downloadResults: DownloadResult[]) => {
const dataAck = Object.assign({}, successAck);
dataAck.data = downloadResults;
ack(dataAck);
})
.catch(nack);
}
function downloadRuntime(identity: Identity, message: APIMessage, ack: Acker, nack: NackerError): void {
const { payload } = message;
System.downloadRuntime(identity, payload, (err: void | Error) => {
if (err) {
nack(err);
} else {
ack(successAck);
}
});
}
function getHostSpecs(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getHostSpecs();
ack(dataAck);
}
function getMachineId(identity: Identity, message: APIMessage, ack: Acker): void {
const dataAck = Object.assign({}, successAck);
dataAck.data = System.getMachineId();
ack(dataAck);
}
function resolveUuid(identity: Identity, message: APIMessage, ack: Acker, nack: NackerError): void {
const { payload: { entityKey } } = message;
System.resolveUuid(identity, entityKey, (err: null | Error, entity: Entity) => {
if (err) {
nack(err);
} else {
const dataAck = Object.assign({}, successAck);
dataAck.data = entity;
ack(dataAck);
}
});
}
function getPreloadScripts(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
System.getPreloadScripts(identity)
.then((preloadScripts: PreloadScript[]) => {
const dataAck = Object.assign({}, successAck);
dataAck.data = preloadScripts;
ack(dataAck);
})
.catch(nack);
}
function authenticateResourceFetch(identity: Identity, message: APIMessage, ack: Acker): void {
const { payload } = message;
const dataAck = Object.assign({}, successAck);
dataAck.data = System.authenticateResourceFetch(identity, payload);
ack(dataAck);
}
function entityExists(identity: Identity, message: APIMessage, ack: Acker, nack: Nacker): void {
const { payload } = message;
const dataAck = Object.assign({}, successAck);
dataAck.data = System.entityExists(payload);
ack(dataAck);
} | the_stack |
* @module Rendering
*/
import { assert, Id64String } from "@itwin/core-bentley";
import {
AnyCurvePrimitive, Arc3d, Loop, Path, Point2d, Point3d, Polyface, Range3d, SolidPrimitive, Transform,
} from "@itwin/core-geometry";
import { AnalysisStyle, ColorDef, Feature, Frustum, GeometryClass, GraphicParams, LinePixels, Npc } from "@itwin/core-common";
import { IModelConnection } from "../IModelConnection";
import { Viewport } from "../Viewport";
import { RenderGraphic } from "./RenderGraphic";
import { GraphicPrimitive } from "./GraphicPrimitive";
/**
* Describes the type of a [[GraphicBuilder]], which defines the coordinate system in which the builder's geometry is defined and
* controls the behavior of the [[RenderGraphic]] produced by the builder.
* @note For those types for which depth-testing is disabled, the order in which the individual geometric primitives are drawn determines which geometry draws on top of other geometry.
* - Within a [[GraphicList]], each [[RenderGraphic]] is rendered in the order in which it appears in the list; and
* - Within a single [[RenderGraphic]], each geometric primitive is rendered in the ordered in which it was added to the GraphicBuilder.
* @public
* @extensions
*/
export enum GraphicType {
/**
* Renders behind all other graphics. For example, the border of a [[SheetViewState]] is of this type.
* Coordinates: [[CoordSystem.View]].
* [[RenderMode]]: [[RenderMode.SmoothShade]].
* Lighting: none.
* Depth-testing: disabled.
* @see [[Decorations.viewBackground]]
*/
ViewBackground,
/** Used for the scene itself, dynamics, and 'normal' decorations. */
/**
* Renders as if it were part of the scene. All of the [[ViewFlags]] applied to the view's normal geometry also applies to these types of decorations.
* Coordinates: [[CoordSystem.World]].
* Lighting and [[RenderMode]]: from view.
* Depth-testing: enabled.
* @see [[Decorations.normal]].
*/
Scene,
/** Renders within the scene. Coordinates: world. RenderMode: smooth. Lighting: default. Z-testing: enabled */
/** Renders within the scene, but ignores the view's [[ViewFlags]].
* Coordinates: [[CoordSystem.World]].
* Lighting: default.
* [[RenderMode]]: [[RenderMode.SmoothShade]].
* Depth-testing: enabled.
* @see [[Decorations.world]].
*/
WorldDecoration,
/**
* Renders as an overlay on top of the scene. These decorations differ from [[GraphicType.WorldDecoration]] only in that depth-testing is disabled.
* For example, the ACS triad and [[WindowAreaTool]] decorations are of this type.
* Coordinates: [[CoordSystem.World]].
* [[RenderMode]]: [[RenderMode.SmoothShade]]
* Lighting: default.
* Depth-testing: disabled.
* Renders atop the scene. Coordinates: world. RenderMode: smooth. Lighting: none. Z-testing: disabled
* @note Overlay decorations typically employ some degree of transparency to ensure that they do not fully obscure the scene.
* @see [[Decorations.worldOverlay]]
*/
WorldOverlay,
/**
* Renders as an overlay on top of the scene. These decorations differ from [[GraphicType.WorldOverlay]] only in that their geometry is defined in view coordinates rather than world.
* Coordinates: [[CoordSystem.View]].
* [[RenderMode]]: [[RenderMode.SmoothShade]]
* Lighting: default.
* Depth-testing: disabled.
* @note For more flexibility in defining view overlay decorations, consider using a [[CanvasDecorationList]].
* @see [[Decorations.viewOverlay]]
*/
ViewOverlay,
}
/** Options used when constructing a `Batch` - that is, a [[RenderGraphic]] with an associated [FeatureTable]($common) describing individual [Feature]($common)s within the
* graphic. Individual features can be resymbolized in a variety of ways including flashing and hiliting.
* For example, to prevent graphics produced by [[readElementGraphics]] from being hilited when their corresponding element is in the [[SelectionSet]],
* pass `{ noHilite: true }` to [[readElementGraphics]].
* @public
* @extensions
*/
export interface BatchOptions {
/** Identifies the [[Tile]] associated with the batch, chiefly for debugging purposes.
* @beta
*/
tileId?: string;
/** If true, features within the batch will not be flashed on mouseover. */
noFlash?: boolean;
/** If true, features within the batch will not be hilited when their corresponding element is in the [[SelectionSet]]. */
noHilite?: boolean;
/** If true, features within the batch will not be emphasized when the corresponding [[Feature]] is emphasized using [FeatureOverrides]($common). */
noEmphasis?: boolean;
/** If true, the contents of the batch will only be drawn by [[Viewport.readPixels]], not [[Viewport.renderFrame]], causing them to be locatable but invisible. */
locateOnly?: boolean;
}
/** Options used as part of [[GraphicBuilderOptions]] to describe a [pickable]($docs/learning/frontend/ViewDecorations#pickable-view-graphic-decorations) [[RenderGraphic]].
* @public
* @extensions
*/
export interface PickableGraphicOptions extends BatchOptions {
/** A unique identifier for the graphic.
* @see [[IModelConnection.transientIds]] to obtain a unique Id in the context of an iModel.
* @see [[GraphicBuilder.activatePickableId]] or [[GraphicBuilder.activateFeature]] to change the pickable object while adding geometry.
*/
id: Id64String;
/** Optional Id of the subcategory with which the graphic should be associated. */
subCategoryId?: Id64String;
/** Optional geometry class for the graphic - defaults to [GeometryClass.Primary]($common). */
geometryClass?: GeometryClass;
/** The optional Id of the model with which the graphic should be associated. */
modelId?: Id64String;
}
/** Options for creating a [[GraphicBuilder]] used by functions like [[DecorateContext.createGraphic]] and [[RenderSystem.createGraphic]].
* @see [[ViewportGraphicBuilderOptions]] to create a graphic builder for a [[Viewport]].
* @see [[CustomGraphicBuilderOptions]] to create a graphic builder unassociated with any [[Viewport]].
* @public
* @extensions
*/
export interface GraphicBuilderOptions {
/** The type of graphic to produce. */
type: GraphicType;
/** The local-to-world transform in which the builder's geometry is to be defined - by default, an identity transform. */
placement?: Transform;
/** If the graphic is to be pickable, specifies the pickable Id and other options. */
pickable?: PickableGraphicOptions;
/** If true, the order in which geometry is added to the builder is preserved.
* This is useful for overlay and background graphics because they draw without using the depth buffer. For example, to draw an overlay containing a red shape with a white outline,
* you would add the shape to the GraphicBuilder first, followed by the outline, to ensure the outline draws "in front of" the shape.
* It defaults to true for overlays and background graphics, and false for other graphic types.
* It is not useful for other types of graphics and imposes a performance penalty due to increased number of draw calls.
* For overlay and background graphics that do not need to draw in any particular order, the performance penalty can be eliminated by setting this to `false`.
*/
preserveOrder?: boolean;
/** Controls whether normals are generated for surfaces. Normals allow 3d geometry to receive lighting; without them the geometry will be unaffected by lighting.
* By default, normals are generated only for graphics of type [[GraphicType.Scene]]; or for any type of graphic if [[GraphicBuilder.wantEdges]] is true, because
* normals are required to prevent z-fighting between surfaces and their edges. This default can be overridden by explicitly specifying `true` or `false`.
* @see [[GraphicType]] for a description of whether and how different types of graphics are affected by lighting.
*/
wantNormals?: boolean;
/** Controls whether edges are generated for surfaces.
* Edges are only displayed if [ViewFlags.renderMode]($common) is not [RenderMode.SmoothShade]($common) or [ViewFlags.visibleEdges]($common) is `true`.
* Since all decoration graphics except [[GraphicType.Scene]] are drawn in smooth shaded mode with no visible edges, by default edges are only produced for scene graphics, and
* - if a [[Viewport]] is supplied with the options - only if [ViewFlags.edgesRequired]($common) is true for the viewport.
* That default can be overridden by explicitly specifying `true` or `false`. This can be useful for non-scene decorations contained in a [[GraphicBranch]] that applies [ViewFlagOverrides]($common)
* that change the edge display settings; or for scene decorations that might be cached for reuse after the viewport's edge settings are changed.
* @note Edges will tend to z-fight with their surfaces unless the graphic is [[pickable]].
*/
generateEdges?: boolean;
/** If defined, specifies a point about which the graphic will rotate such that it always faces the viewer.
* This can be particular useful for planar regions to create a billboarding effect - e.g., to implement [[Marker]]-like WebGL decorations.
* The graphic's [[placement]] transform is not applied to the point.
* @note This has no effect for graphics displayed in a 2d view.
*/
viewIndependentOrigin?: Point3d;
}
/** Options for creating a [[GraphicBuilder]] to produce a [[RenderGraphic]] to be displayed in a specific [[Viewport]].
* The level of detail of the graphic will be computed from the position of its geometry within the viewport's [Frustum]($common).
* Default values for [[GraphicBuilderOptions.wantNormals]] and [[GraphicBuilderOptions.generateEdges]] will be determined by the viewport's [ViewFlags]($common).
* The [[GraphicBuilder.iModel]] will be set to the viewport's [[IModelConnection]].
* @public
* @extensions
*/
export interface ViewportGraphicBuilderOptions extends GraphicBuilderOptions {
/** The viewport in which the resultant [[RenderGraphic]] is to be drawn. */
viewport: Viewport;
/** If true, [[ViewState.getAspectRatioSkew]] will be taken into account when computing the level of detail for the produced graphics. */
applyAspectRatioSkew?: boolean;
iModel?: never;
computeChordTolerance?: never;
}
/** Arguments used to compute the chord tolerance (level of detail) of the [[RenderGraphic]]s produced by a [[GraphicBuilder]].
* Generally, the chord tolerance should be roughly equivalent to the size in meters of one pixel on screen where the graphic is to be displayed.
* For [[GraphicType.ViewOverlay]] and [[GraphicType.ViewBackground]], which already define their geometry in pixels, the chord tolerance should typically be 1.
* @see [[CustomGraphicBuilderOptions.computeChordTolerance]].
* @public
* @extensions
*/
export interface ComputeChordToleranceArgs {
/** The graphic builder being used to produce the graphics. */
readonly graphic: GraphicBuilder;
/** A function that computes a range enclosing all of the geometry that was added to the builder. */
readonly computeRange: () => Range3d;
}
/** Options for creating a [[GraphicBuilder]] to produce a [[RenderGraphic]] that is not associated with any particular [[Viewport]] and may not be associated with
* any particular [[IModelConnection]].
* This is primarily useful when the same graphic is to be saved and reused for display in multiple viewports and for which a chord tolerance can be computed
* independently of each viewport's [Frustum]($common).
* @public
* @extensions
*/
export interface CustomGraphicBuilderOptions extends GraphicBuilderOptions {
/** Optionally, the IModelConnection with which the graphic is associated. */
iModel?: IModelConnection;
/** A function that can compute the level of detail for the graphics produced by the builder. */
computeChordTolerance: (args: ComputeChordToleranceArgs) => number;
applyAspectRatioSkew?: never;
viewport?: never;
}
/** Provides methods for constructing a [[RenderGraphic]] from geometric primitives.
* GraphicBuilder is primarily used for creating [[Decorations]] to be displayed inside a [[Viewport]].
*
* The typical process for constructing a [[RenderGraphic]] proceeds as follows:
* 1. Use [[DecorateContext.createGraphic]] or [[RenderSystem.createGraphic]] to obtain a builder.
* 2. Set up the symbology using [[GraphicBuilder.activateGraphicParams]] or [[GraphicBuilder.setSymbology]].
* 3. Add one or more geometric primitives using methods like [[GraphicBuilder.addShape]] and [[GraphicBuilder.addLineString]], possibly setting new symbology in between.
* 4. Use [[GraphicBuilder.finish]] to produce the finished [[RenderGraphic]].
*
* @note Most of the methods which add geometry to the builder take ownership of their inputs rather than cloning them.
* So, for example, if you pass an array of points to addLineString(), you should not subsequently modify that array.
*
* @public
* @extensions
*/
export abstract class GraphicBuilder {
/** The local coordinate system transform applied to this builder's geometry.
* @see [[GraphicBuilderOptions.placement]].
*/
public readonly placement: Transform;
/** The iModel associated with this builder, if any. */
public readonly iModel?: IModelConnection;
/** The type of graphic to be produced by this builder.
* @see [[GraphicBuilderOptions.type]].
*/
public readonly type: GraphicType;
/** If the graphic is to be pickable, specifies the pickable Id and other options. */
public readonly pickable?: Readonly<PickableGraphicOptions>;
/** If true, the order in which geometry is added to the builder is preserved.
* @see [[GraphicBuilderOptions.preserveOrder]] for more details.
*/
public readonly preserveOrder: boolean;
/** Controls whether normals are generated for surfaces.
* @note Normals are required for proper edge display, so by default they are always produced if [[wantEdges]] is `true`.
* @see [[GraphicBuilderOptions.wantNormals]] for more details.
*/
public readonly wantNormals: boolean;
/** Controls whether edges are generated for surfaces.
* @see [[GraphicBuilderOptions.generateEdges]] for more details.
*/
public readonly wantEdges: boolean;
/** @alpha */
public readonly analysisStyle?: AnalysisStyle;
protected readonly _computeChordTolerance: (args: ComputeChordToleranceArgs) => number;
protected readonly _options: CustomGraphicBuilderOptions | ViewportGraphicBuilderOptions;
/** @internal */
protected constructor(options: ViewportGraphicBuilderOptions | CustomGraphicBuilderOptions) {
// Stored for potential use later in creating a new GraphicBuilder from this one (see PrimitiveBuilder.finishGraphic).
this._options = options;
const vp = options.viewport;
this.placement = options.placement ?? Transform.createIdentity();
this.iModel = vp?.iModel ?? options.iModel;
this.type = options.type;
this.pickable = options.pickable;
this.wantEdges = options.generateEdges ?? (this.type === GraphicType.Scene && (!vp || vp.viewFlags.edgesRequired()));
this.wantNormals = options.wantNormals ?? (this.wantEdges || this.type === GraphicType.Scene);
this.preserveOrder = options.preserveOrder ?? (this.isOverlay || this.isViewBackground);
if (!options.viewport) {
this._computeChordTolerance = options.computeChordTolerance;
return;
}
this.analysisStyle = options.viewport.displayStyle.settings.analysisStyle;
this._computeChordTolerance = (args: ComputeChordToleranceArgs) => {
let pixelSize = 1;
if (!this.isViewCoordinates) {
// Compute the horizontal distance in meters between two adjacent pixels at the center of the geometry.
pixelSize = options.viewport.getPixelSizeAtPoint(args.computeRange().center);
pixelSize = options.viewport.target.adjustPixelSizeForLOD(pixelSize);
// Aspect ratio skew > 1.0 stretches the view in Y. In that case use the smaller vertical pixel distance for our stroke tolerance.
const skew = options.applyAspectRatioSkew ? options.viewport.view.getAspectRatioSkew() : 0;
if (skew > 1)
pixelSize /= skew;
}
return pixelSize * 0.25;
};
}
/** The Id to be associated with the graphic for picking.
* @see [[GraphicBuilderOptions.pickable]] for more options.
* @deprecated This provides only the **first** pickable Id for this graphic - you should keep track of the **current** pickable Id yourself.
*/
public get pickId(): Id64String | undefined {
return this.pickable?.id;
}
/** Whether the builder's geometry is defined in [[CoordSystem.View]] coordinates.
* @see [[isWorldCoordinates]].
*/
public get isViewCoordinates(): boolean {
return this.type === GraphicType.ViewBackground || this.type === GraphicType.ViewOverlay;
}
/** Whether the builder's geometry is defined in [[CoordSystem.World]] coordinates.
* @see [[isViewCoordinates]].
*/
public get isWorldCoordinates(): boolean {
return !this.isViewCoordinates;
}
/** True if the builder produces a graphic of [[GraphicType.Scene]]. */
public get isSceneGraphic(): boolean {
return this.type === GraphicType.Scene;
}
/** True if the builder produces a graphic of [[GraphicType.ViewBackground]]. */
public get isViewBackground(): boolean {
return this.type === GraphicType.ViewBackground;
}
/** True if the builder produces a graphic of [[GraphicType.WorldOverlay]] or [[GraphicType.ViewOerlay]]. */
public get isOverlay(): boolean {
return this.type === GraphicType.ViewOverlay || this.type === GraphicType.WorldOverlay;
}
/**
* Processes the accumulated symbology and geometry to produce a renderable graphic.
* This function can only be called once; after the [[RenderGraphic]] has been extracted the [[GraphicBuilder]] should no longer be used.
*/
public abstract finish(): RenderGraphic;
/** Sets the current active symbology for this builder. Any new geometry subsequently added to the builder will be drawn using the specified symbology.
* @param graphicParams The symbology to apply to subsequent geometry.
* @see [[GraphicBuilder.setSymbology]] for a convenient way to set common symbology options.
*/
public abstract activateGraphicParams(graphicParams: GraphicParams): void;
/** Called by [[activateFeature]] after validation to change the [Feature]($common) to be associated with subsequently-added geometry.
* This default implementation does nothing.
*/
protected _activateFeature(_feature: Feature): void { }
/** Change the [Feature]($common) to be associated with subsequently-added geometry. This permits multiple features to be batched together into a single graphic
* for more efficient rendering.
* @note This method has no effect if [[GraphicBuilderOptions.pickable]] was not supplied to the GraphicBuilder's constructor.
*/
public activateFeature(feature: Feature): void {
assert(undefined !== this._options.pickable, "GraphicBuilder.activateFeature has no effect if PickableGraphicOptions were not supplied");
if (this._options.pickable)
this._activateFeature(feature);
}
/** Change the pickable Id to be associated with subsequently-added geometry. This permits multiple pickable objects to be batched together into a single graphic
* for more efficient rendering. This method calls [[activateFeature]], using the subcategory Id and [GeometryClass]($common) specified in [[GraphicBuilder.pickable]]
* at construction, if any.
* @note This method has no effect if [[GraphicBuilderOptions.pickable]] was not supplied to the GraphicBuilder's constructor.
*/
public activatePickableId(id: Id64String): void {
const pick = this._options.pickable;
this.activateFeature(new Feature(id, pick?.subCategoryId, pick?.geometryClass));
}
/**
* Appends a 3d line string to the builder.
* @param points Array of vertices in the line string.
*/
public abstract addLineString(points: Point3d[]): void;
/**
* Appends a 2d line string to the builder.
* @param points Array of vertices in the line string.
* @param zDepth Z value in local coordinates to use for each point.
*/
public abstract addLineString2d(points: Point2d[], zDepth: number): void;
/**
* Appends a 3d point string to the builder. The points are drawn disconnected, with a diameter in pixels defined by the builder's active [[GraphicParams.rasterWidth]].
* @param points Array of vertices in the point string.
*/
public abstract addPointString(points: Point3d[]): void;
/**
* Appends a 2d point string to the builder. The points are drawn disconnected, with a diameter in pixels defined by the builder's active [[GraphicParams.rasterWidth]].
* @param points Array of vertices in the point string.
* @param zDepth Z value in local coordinates to use for each point.
*/
public abstract addPointString2d(points: Point2d[], zDepth: number): void;
/**
* Appends a closed 3d planar region to the builder.
* @param points Array of vertices of the shape.
*/
public abstract addShape(points: Point3d[]): void;
/**
* Appends a closed 2d region to the builder.
* @param points Array of vertices of the shape.
* @param zDepth Z value in local coordinates to use for each point.
*/
public abstract addShape2d(points: Point2d[], zDepth: number): void;
/**
* Appends a 3d open arc or closed ellipse to the builder.
* @param arc Description of the arc or ellipse.
* @param isEllipse If true, and if the arc defines a full sweep, then draw as a closed ellipse instead of an arc.
* @param filled If true, and isEllipse is also true, then draw ellipse filled.
*/
public abstract addArc(arc: Arc3d, isEllipse: boolean, filled: boolean): void;
/**
* Appends a 2d open arc or closed ellipse to the builder.
* @param arc Description of the arc or ellipse.
* @param isEllipse If true, and if the arc defines a full sweep, then draw as a closed ellipse instead of an arc.
* @param filled If true, and isEllipse is also true, then draw ellipse filled.
* @param zDepth Z value in local coordinates to use for each point in the arc or ellipse.
*/
public abstract addArc2d(ellipse: Arc3d, isEllipse: boolean, filled: boolean, zDepth: number): void;
/** Append a 3d open path to the builder. */
public abstract addPath(path: Path): void;
/** Append a 3d planar region to the builder. */
public abstract addLoop(loop: Loop): void;
/** Append a [CurvePrimitive]($core-geometry) to the builder. */
public addCurvePrimitive(curve: AnyCurvePrimitive): void {
switch (curve.curvePrimitiveType) {
case "lineString":
this.addLineString(curve.points);
break;
case "lineSegment":
this.addLineString([curve.startPoint(), curve.endPoint()]);
break;
case "arc":
this.addArc(curve, false, false);
break;
default:
const path = new Path();
if (path.tryAddChild(curve))
this.addPath(path);
break;
}
}
/** Append a mesh to the builder.
* @param meshData Describes the mesh
* @param filled If the mesh describes a planar region, indicates whether its interior area should be drawn with fill in [[RenderMode.Wireframe]].
*/
public abstract addPolyface(meshData: Polyface, filled: boolean): void;
/** Append a solid primitive to the builder. */
public abstract addSolidPrimitive(solidPrimitive: SolidPrimitive): void;
/** Append any primitive to the builder.
* @param primitive The graphic primitive to append.
*/
public addPrimitive(primitive: GraphicPrimitive): void {
switch (primitive.type) {
case "linestring":
this.addLineString(primitive.points);
break;
case "linestring2d":
this.addLineString2d(primitive.points, primitive.zDepth);
break;
case "pointstring":
this.addPointString(primitive.points);
break;
case "pointstring2d":
this.addPointString2d(primitive.points, primitive.zDepth);
break;
case "shape":
this.addShape(primitive.points);
break;
case "shape2d":
this.addShape2d(primitive.points, primitive.zDepth);
break;
case "arc":
this.addArc(primitive.arc, true === primitive.isEllipse, true === primitive.filled);
break;
case "arc2d":
this.addArc2d(primitive.arc, true === primitive.isEllipse, true === primitive.filled, primitive.zDepth);
break;
case "path":
this.addPath(primitive.path);
break;
case "loop":
this.addLoop(primitive.loop);
break;
case "polyface":
this.addPolyface(primitive.polyface, true === primitive.filled);
break;
case "solidPrimitive":
this.addSolidPrimitive(primitive.solidPrimitive);
break;
}
}
/** Add Range3d edges. Useful for debugging. */
public addRangeBox(range: Range3d) {
this.addFrustum(Frustum.fromRange(range));
}
/** Add Frustum edges. Useful for debugging. */
public addFrustum(frustum: Frustum) {
this.addRangeBoxFromCorners(frustum.points);
}
/** Add range edges from corner points */
public addRangeBoxFromCorners(p: Point3d[]) {
this.addLineString([
p[Npc.LeftBottomFront],
p[Npc.LeftTopFront],
p[Npc.RightTopFront],
p[Npc.RightBottomFront],
p[Npc.RightBottomRear],
p[Npc.RightTopRear],
p[Npc.LeftTopRear],
p[Npc.LeftBottomRear],
p[Npc.LeftBottomFront].clone(),
p[Npc.RightBottomFront].clone(),
]);
this.addLineString([p[Npc.LeftTopFront].clone(), p[Npc.LeftTopRear].clone()]);
this.addLineString([p[Npc.RightTopFront].clone(), p[Npc.RightTopRear].clone()]);
this.addLineString([p[Npc.LeftBottomRear].clone(), p[Npc.RightBottomRear].clone()]);
}
/** Sets the current active symbology for this builder. Any new geometry subsequently added will be drawn using the specified symbology.
* @param lineColor The color in which to draw lines.
* @param fillColor The color in which to draw filled regions.
* @param lineWidth The width in pixels to draw lines. The renderer will clamp this value to an integer in the range [1, 32].
* @param linePixels The pixel pattern in which to draw lines.
* @see [[GraphicBuilder.activateGraphicParams]] for additional symbology options.
*/
public setSymbology(lineColor: ColorDef, fillColor: ColorDef, lineWidth: number, linePixels = LinePixels.Solid) {
this.activateGraphicParams(GraphicParams.fromSymbology(lineColor, fillColor, lineWidth, linePixels));
}
/** Set the current active symbology for this builder to be a blanking fill before adding a planar region.
* A planar region drawn with blanking fill renders behind other geometry in the same graphic.
* Blanking fill is not affected by the fill [[ViewFlags]] being disabled.
* An example would be to add a line to a graphic containing a shape with blanking fill so that the line is always shown in front of the fill.
* @param fillColor The color in which to draw filled regions.
*/
public setBlankingFill(fillColor: ColorDef) { this.activateGraphicParams(GraphicParams.fromBlankingFill(fillColor)); }
} | the_stack |
declare namespace lunr {
const version: string;
/**
* A function for splitting a string into tokens ready to be inserted into
* the search index. Uses `lunr.tokenizer.seperator` to split strings, change
* the value of this property to change how strings are split into tokens.
*
* @param obj The string to convert into tokens
* @see lunr.tokenizer.seperator
*/
function tokenizer(obj: any): string[];
type TokenizerFunction = (obj: any) => string[];
namespace tokenizer {
/**
* The sperator used to split a string into tokens. Override this property to change the behaviour of
* `lunr.tokenizer` behaviour when tokenizing strings. By default this splits on whitespace and hyphens.
*
* @see lunr.tokenizer
*
* (Note: this is misspelled in the original API, kept for compatibility sake)
*/
const seperator: RegExp | string;
const label: string;
const registeredFunctions: {[label: string]: TokenizerFunction};
/**
* Register a tokenizer function.
*
* Functions that are used as tokenizers should be registered if they are to be used with a serialised index.
*
* Registering a function does not add it to an index, functions must still be associated with a specific index for them to be used when indexing and searching documents.
*
* @param fn The function to register.
* @param label The label to register this function with
*/
function registerFunction(fn: TokenizerFunction, label: string): void;
/**
* Loads a previously serialised tokenizer.
*
* A tokenizer function to be loaded must already be registered with lunr.tokenizer.
* If the serialised tokenizer has not been registered then an error will be thrown.
*
* @param label The label of the serialised tokenizer.
*/
function load(label: string): TokenizerFunction;
}
/**
* lunr.stemmer is an english language stemmer, this is a JavaScript implementation of
* the PorterStemmer taken from http://tartaurs.org/~martin
*
* @param token The string to stem
*/
function stemmer(token: string): string;
/**
* lunr.stopWordFilter is an English language stop word list filter, any words contained
* in the list will not be passed through the filter.
*
* This is intended to be used in the Pipeline. If the token does not pass the filter then
* undefined will be returned.
*
* @param token The token to pass through the filter
*/
function stopWordFilter(token: string): string;
namespace stopWordFilter {
const stopWords: SortedSet<string>;
}
/**
* lunr.trimmer is a pipeline function for trimming non word characters from the beginning
* and end of tokens before they enter the index.
*
* This implementation may not work correctly for non latin characters and should either
* be removed or adapted for use with languages with non-latin characters.
* @param token The token to pass through the filter
*/
function trimmer(token: string): string;
/**
* lunr.EventEmitter is an event emitter for lunr. It manages adding and removing event handlers
* and triggering events and their handlers.
*/
class EventEmitter {
/**
* Can bind a single function to many different events in one call.
*
* @param eventName The name(s) of events to bind this function to.
* @param handler The function to call when an event is fired. Binds a handler
* function to a specific event(s).
*/
addListener(eventName: string, handler: Function): void;
addListener(eventName: string, eventName2: string, handler: Function): void;
addListener(eventName: string, eventName2: string, eventName3: string, handler: Function): void;
addListener(eventName: string, eventName2: string, eventName3: string, eventName4: string, handler: Function): void;
addListener(eventName: string, eventName2: string, eventName3: string, eventName4: string, eventName5: string, handler: Function): void;
/**
* Removes a handler function from a specific event.
*
* @param eventName The name of the event to remove this function from.
* @param handler The function to remove from an event.
*/
removeListener(eventName: string, handler: Function): void;
/**
* Calls all functions bound to the given event.
*
* Additional data can be passed to the event handler as arguments to emit after the event name.
*
* @param eventName The name of the event to emit.
*/
emit(eventName: string, ...args: any[]): void;
/**
* Checks whether a handler has ever been stored against an event.
*
* @param eventName The name of the event to check.
*/
hasHandler(eventName: string): boolean;
}
type IPipelineFunction = (token: string, tokenIndex?: number, tokens?: string[]) => string;
/**
* lunr.Pipelines maintain an ordered list of functions to be applied to all tokens in documents
* entering the search index and queries being ran against the index.
*
* An instance of lunr.Index created with the lunr shortcut will contain a pipeline with a stop
* word filter and an English language stemmer. Extra functions can be added before or after either
* of these functions or these default functions can be removed.
*
* When run the pipeline will call each function in turn, passing a token, the index of that token
* in the original list of all tokens and finally a list of all the original tokens.
*
* The output of functions in the pipeline will be passed to the next function in the pipeline.
* To exclude a token from entering the index the function should return undefined, the rest of
* the pipeline will not be called with this token.
*
* For serialisation of pipelines to work, all functions used in an instance of a pipeline should
* be registered with lunr.Pipeline. Registered functions can then be loaded. If trying to load a
* serialised pipeline that uses functions that are not registered an error will be thrown.
*
* If not planning on serialising the pipeline then registering pipeline functions is not necessary.
*/
class Pipeline {
registeredFunctions: {[label: string]: Function};
/**
* Register a function with the pipeline.
*
* Functions that are used in the pipeline should be registered if the pipeline needs to be
* serialised, or a serialised pipeline needs to be loaded.
*
* Registering a function does not add it to a pipeline, functions must still be added to instances
* of the pipeline for them to be used when running a pipeline.
*
* @param fn The function to check for.
* @param label The label to register this function with
*/
registerFunction(fn: IPipelineFunction, label: string): void;
/**
* Warns if the function is not registered as a Pipeline function.
*
* @param fn The function to check for.
*/
warnIfFunctionNotRegistered(fn: IPipelineFunction): void;
/**
* Adds new functions to the end of the pipeline.
*
* Logs a warning if the function has not been registered.
*
* @param functions Any number of functions to add to the pipeline.
*/
add(...functions: IPipelineFunction[]): void;
/**
* Adds a single function after a function that already exists in the pipeline.
*
* Logs a warning if the function has not been registered.
*
* @param existingFn A function that already exists in the pipeline.
* @param newFn The new function to add to the pipeline.
*/
after(existingFn: IPipelineFunction, newFn: IPipelineFunction): void;
/**
* Adds a single function before a function that already exists in the pipeline.
*
* Logs a warning if the function has not been registered.
*
* @param existingFn A function that already exists in the pipeline.
* @param newFn The new function to add to the pipeline.
*/
before(existingFn: IPipelineFunction, newFn: IPipelineFunction): void;
/**
* Removes a function from the pipeline.
*
* @param fn The function to remove from the pipeline.
*/
remove(fn: IPipelineFunction): void;
/**
* Runs the current list of functions that make up the pipeline against
* the passed tokens.
*
* @param tokens The tokens to run through the pipeline.
*/
run(tokens: string[]): string[];
/**
* Resets the pipeline by removing any existing processors.
*/
reset(): void;
/**
* Returns a representation of the pipeline ready for serialisation.
*/
toJSON(): any;
/**
* Loads a previously serialised pipeline.
*
* All functions to be loaded must already be registered with lunr.Pipeline. If any function from
* the serialised data has not been registered then an error will be thrown.
*
* @param serialised The serialised pipeline to load.
*/
static load(serialised: any): Pipeline;
}
/**
* lunr.Vectors implement vector related operations for a series of elements.
*/
class Vector {
list: Node;
/**
* Calculates the magnitude of this vector.
*/
magnitude(): number;
/**
* Calculates the dot product of this vector and another vector.
* @param otherVector The vector to compute the dot product with.
*/
dot(otherVector: Vector): number;
/**
* Calculates the cosine similarity between this vector and another vector.
*
* @param otherVector The other vector to calculate the
*/
similarity(otherVector: Vector): number;
}
/**
* lunr.Vector.Node is a simple struct for each node in a lunr.Vector.
*/
class Node {
/**
* The index of the node in the vector.
*/
idx: number;
/**
* The data at this node in the vector.
*/
val: number;
/**
* The node directly after this node in the vector.
*/
next: Node;
/**
* @param idx The index of the node in the vector.
* @param val The data at this node in the vector.
* @param next The node directly after this node in the vector.
*/
constructor(idx: number, val: number, next: Node);
}
/**
* lunr.SortedSets are used to maintain an array of unique values in a sorted order.
*/
class SortedSet<T> {
elements: T[];
length: number;
/**
* Inserts new items into the set in the correct position to maintain the order.
*
* @param values The objects to add to this set.
*/
add(...values: T[]): void;
/**
* Converts this sorted set into an array.
*/
toArray(): T[];
/**
* Creates a new array with the results of calling a provided function on
* every element in this sorted set.
*
* Delegates to Array.prototype.map and has the same signature.
*
* @param fn The function that is called on each element of the
* @param ctx An optional object that can be used as the context
*/
map(fn: Function, ctx: any): T[];
/**
* Executes a provided function once per sorted set element.
*
* Delegates to Array.prototype.forEach and has the same signature.
*
* @param fn The function that is called on each element of the
* @param ctx An optional object that can be used as the context
*/
forEach(fn: Function, ctx: any): any;
/**
* Returns the index at which a given element can be found in the sorted
* set, or -1 if it is not present.
*
* @param elem The object to locate in the sorted set.
* @param start An optional index at which to start searching from
* @param end An optional index at which to stop search from within
*/
indexOf(elem: T, start?: number, end?: number): number;
/**
* Returns the position within the sorted set that an element should be
* inserted at to maintain the current order of the set.
*
* This function assumes that the element to search for does not already exist
* in the sorted set.
*
* @param elem - The elem to find the position for in the set
* @param start - An optional index at which to start searching from
* @param end - An optional index at which to stop search from within
*/
locationFor(elem: T, start?: number, end?: number): number;
/**
* Creates a new lunr.SortedSet that contains the elements in the
* intersection of this set and the passed set.
*
* @param otherSet The set to intersect with this set.
*/
intersect(otherSet: SortedSet<T>): SortedSet<T>;
/**
* Creates a new lunr.SortedSet that contains the elements in the union of this
* set and the passed set.
*
* @param otherSet The set to union with this set.
*/
union(otherSet: SortedSet<T>): SortedSet<T>;
/**
* Makes a copy of this set
*/
clone(): SortedSet<T>;
/**
* Returns a representation of the sorted set ready for serialisation.
*/
toJSON(): any;
/**
* Loads a previously serialised sorted set.
*
* @param serialisedData The serialised set to load.
*/
static load<T>(serialisedData: T[]): SortedSet<T>;
}
interface IndexField {
/**
* The name of the field within the document that
*/
name: string;
/**
* An optional boost that can be applied to terms in this field.
*/
boost: number;
}
interface IndexSearchResult {
ref: any;
score: number;
}
/**
* lunr.Index is object that manages a search index. It contains the indexes and stores
* all the tokens and document lookups. It also provides the main user facing API for
* the library.
*/
class Index {
eventEmitter: EventEmitter;
documentStore: Store<string>;
tokenStore: TokenStore;
corpusTokens: SortedSet<string>;
pipeline: Pipeline;
_fields: IndexField[];
_ref: string;
_idfCache: {[key: string]: string};
/**
* Bind a handler to events being emitted by the index.
*
* The handler can be bound to many events at the same time.
*
* @param eventName The name(s) of events to bind the function to.
* @param handler The function to call when an event is fired. Binds a handler
* function to a specific event(s).
*/
on(eventName: string, handler: Function): void;
on(eventName: string, eventName2: string, handler: Function): void;
on(eventName: string, eventName2: string, eventName3: string, handler: Function): void;
on(eventName: string, eventName2: string, eventName3: string, eventName4: string, handler: Function): void;
on(eventName: string, eventName2: string, eventName3: string, eventName4: string, eventName5: string, handler: Function): void;
/**
* Removes a handler from an event being emitted by the index.
*
* @param eventName The name of events to remove the function from.
* @param handler The serialised set to load.
*/
off(eventName: string, handler: Function): void;
/**
* Adds a field to the list of fields that will be searchable within documents in the index.
*
* An optional boost param can be passed to affect how much tokens in this field rank in
* search results, by default the boost value is 1.
*
* Fields should be added before any documents are added to the index, fields that are added
* after documents are added to the index will only apply to new documents added to the index.
*
* @param fieldName The name of the field within the document that
* @param options An optional boost that can be applied to terms in this field.
*/
field(fieldName: string, options?: {boost?: number}): Index;
/**
* Sets the property used to uniquely identify documents added to the index, by default this
* property is 'id'.
*
* This should only be changed before adding documents to the index, changing the ref property
* without resetting the index can lead to unexpected results.
*
* @refName The property to use to uniquely identify the
*/
ref(refName: string): Index;
/**
* Add a document to the index.
*
* This is the way new documents enter the index, this function will run the fields from the
* document through the index's pipeline and then add it to the index, it will then show up
* in search results.
*
* An 'add' event is emitted with the document that has been added and the index the document
* has been added to. This event can be silenced by passing false as the second argument to add.
*
* @param doc The document to add to the index.
* @param emitEvent Whether or not to emit events, default true.
*/
add(doc: any, emitEvent?: boolean): void;
/**
* Removes a document from the index.
*
* To make sure documents no longer show up in search results they can be removed from the
* index using this method.
*
* The document passed only needs to have the same ref property value as the document that was
* added to the index, they could be completely different objects.
*
* A 'remove' event is emitted with the document that has been removed and the index the
* document has been removed from. This event can be silenced by passing false as the second
* argument to remove.
*
* @param doc The document to remove from the index.
* @param emitEvent Whether to emit remove events, defaults to true
*/
remove(doc: any, emitEvent?: boolean): void;
/**
* Updates a document in the index.
*
* When a document contained within the index gets updated, fields changed, added or removed,
* to make sure it correctly matched against search queries, it should be updated in the index.
*
* This method is just a wrapper around [[remove]] and [[add]].
*
* An 'update' event is emitted with the document that has been updated and the index.
* This event can be silenced by passing false as the second argument to update. Only an
* update event will be fired, the 'add' and 'remove' events of the underlying calls are
* silenced.
*
* @param doc The document to update in the index.
* @param emitEvent Whether to emit update events, defaults to true
*/
update(doc: any, emitEvent?: boolean): void;
/**
* Calculates the inverse document frequency for a token within the index.
*
* @param token The token to calculate the idf of.
*/
idf(token: string): string;
/**
* Searches the index using the passed query.
*
* Queries should be a string, multiple words are allowed and will lead to an AND based
* query, e.g. idx.search('foo bar') will run a search for documents containing both
* 'foo' and 'bar'.
*
* All query tokens are passed through the same pipeline that document tokens are passed
* through, so any language processing involved will be run on every query term.
*
* Each query term is expanded, so that the term 'he' might be expanded to 'hello'
* and 'help' if those terms were already included in the index.
*
* Matching documents are returned as an array of objects, each object contains the
* matching document ref, as set for this index, and the similarity score for this
* document against the query.
*
* @param query The query to search the index with.
*/
search(query: string): IndexSearchResult[];
/**
* Generates a vector containing all the tokens in the document matching the
* passed documentRef.
*
* The vector contains the tf-idf score for each token contained in the document with
* the passed documentRef. The vector will contain an element for every token in the
* indexes corpus, if the document does not contain that token the element will be 0.
*
* @param documentRef The ref to find the document with.
*/
documentVector(documentRef: string): Vector;
/**
* Returns a representation of the index ready for serialisation.
*/
toJSON(): any;
/**
* Applies a plugin to the current index.
*
* A plugin is a function that is called with the index as its context. Plugins can be
* used to customise or extend the behaviour the index in some way. A plugin is just a
* function, that encapsulated the custom behaviour that should be applied to the index.
*
* The plugin function will be called with the index as its argument, additional arguments
* can also be passed when calling use. The function will be called with the index as
* its context.
*
* Example:
*
* ```javascript
* var myPlugin = function(idx, arg1, arg2) {
* // `this` is the index to be extended
* // apply any extensions etc here.
* };
*
* var idx = lunr(function() {
* this.use(myPlugin, 'arg1', 'arg2');
* });
* ```
*
* @param plugin The plugin to apply.
*/
use(plugin: Function, ...args: any[]): void;
/**
* Loads a previously serialised index.
*
* Issues a warning if the index being imported was serialised by a different version
* of lunr.
*
* @param serialisedData The serialised set to load.
*/
static load(serialisedData: any): Index;
}
/**
* lunr.Store is a simple key-value store used for storing sets of tokens for documents
* stored in index.
*/
class Store<T> {
store: {[id: string]: SortedSet<T>};
length: number;
/**
* Stores the given tokens in the store against the given id.
*
* @param id The key used to store the tokens against.
* @param tokens The tokens to store against the key.
*/
set(id: string, tokens: SortedSet<T>): void;
/**
* Retrieves the tokens from the store for a given key.
*
* @param id The key to lookup and retrieve from the store.
*/
get(id: string): SortedSet<T>;
/**
* Checks whether the store contains a key.
*
* @param id The id to look up in the store.
*/
has(id: string): boolean;
/**
* Removes the value for a key in the store.
*
* @param id The id to remove from the store.
*/
remove(id: string): void;
/**
* Returns a representation of the store ready for serialisation.
*/
toJSON(): any;
/**
* Loads a previously serialised store.
*
* @param serialisedData The serialised store to load.
*/
static load(serialisedData: any): Store<any>;
}
interface TokenDocument {
ref: number;
tf: number;
}
/**
* lunr.TokenStore is used for efficient storing and lookup of the reverse index of token
* to document ref.
*/
class TokenStore {
root: {[token: string]: TokenStore};
docs: {[ref: string]: TokenDocument};
length: number;
/**
* Adds a new token doc pair to the store.
*
* By default this function starts at the root of the current store, however it can
* start at any node of any token store if required.
*
* @param token The token to store the doc under
* @param doc The doc to store against the token
* @param root An optional node at which to start looking for the
*/
add(token: string, doc: TokenDocument, root?: TokenStore): void;
/**
* Checks whether this key is contained within this lunr.TokenStore.
*
* @param token The token to check for
*/
has(token: string): boolean;
/**
* Retrieve a node from the token store for a given token.
*
* @param token The token to get the node for.
*/
getNode(token: string): TokenStore;
/**
* Retrieve the documents for a node for the given token.
*
* By default this function starts at the root of the current store, however it can
* start at any node of any token store if required.
*
* @param token The token to get the documents for.
* @param root An optional node at which to start.
*/
get(token: string, root: TokenStore): {[ref: string]: TokenDocument};
count(token: string, root: TokenStore): number;
/**
* Remove the document identified by ref from the token in the store.
*
* @param token The token to get the documents for.
* @param ref The ref of the document to remove from this token.
*/
remove(token: string, ref: string): void;
/**
* Find all the possible suffixes of the passed token using tokens currently in
* the store.
*
* @param token The token to expand.
*/
expand(token: string, memo?: string[]): string[];
/**
* Returns a representation of the token store ready for serialisation.
*/
toJSON(): any;
/**
* Loads a previously serialised token store.
*
* @param serialisedData The serialised token store to load.
*/
static load(serialisedData: any): TokenStore;
}
/**
* A namespace containing utils for the rest of the lunr library
*/
namespace utils {
/**
* Print a warning message to the console.
*
* @param message The message to be printed.
*/
function warn(message: any): void;
/**
* Convert an object to a string.
*
* In the case of `null` and `undefined` the function returns
* the empty string, in all other cases the result of calling
* `toString` on the passed object is returned.
*
* @param obj The object to convert to a string.
* @return string representation of the passed object.
*/
function asString(obj: any): string;
}
}
/**
* Convenience function for instantiating a new lunr index and configuring it with the default
* pipeline functions and the passed config function.
*
* When using this convenience function a new index will be created with the following functions
* already in the pipeline:
*
* * lunr.StopWordFilter - filters out any stop words before they enter the index
*
* * lunr.stemmer - stems the tokens before entering the index.
*
* Example:
*
* ```javascript
* var idx = lunr(function () {
* this.field('title', 10);
* this.field('tags', 100);
* this.field('body');
*
* this.ref('cid');
*
* this.pipeline.add(function () {
* // some custom pipeline function
* });
* });
* ```
*/
declare function lunr(config: Function): lunr.Index;
export = lunr;
export as namespace lunr; | the_stack |
import * as AEL from "adaptive-expressions";
class EvaluationContext {
private static readonly _reservedFields = ["$data", "$when", "$root", "$index"];
private _stateStack: Array<{ $data: any, $index: any }> = [];
private _$data: any;
$root: any;
$index: number;
constructor(context?: IEvaluationContext) {
if (context !== undefined) {
this.$root = context.$root;
}
}
isReservedField(name: string): boolean {
return EvaluationContext._reservedFields.indexOf(name) >= 0;
}
saveState() {
this._stateStack.push(
{
$data: this.$data,
$index: this.$index
});
}
restoreLastState() {
if (this._stateStack.length === 0) {
throw new Error("There is no evaluation context state to restore.");
}
let savedContext = this._stateStack.pop();
this.$data = savedContext.$data;
this.$index = savedContext.$index;
}
get $data(): any {
return this._$data !== undefined ? this._$data : this.$root;
}
set $data(value: any) {
this._$data = value;
}
}
class TemplateObjectMemory implements AEL.MemoryInterface {
private _memory: AEL.MemoryInterface;
$root: any;
$data: any;
$index: any;
constructor() {
this._memory = new AEL.SimpleObjectMemory(this);
}
getValue(path: string): any {
let actualPath = (path.length > 0 && path[0] !== "$") ? "$data." + path : path;
return this._memory.getValue(actualPath);
}
setValue(path: string, input: any) {
this._memory.setValue(path, input);
}
version(): string {
return this._memory.version();
}
}
/**
* Holds global settings that can be used to customize the way templates are expanded.
*/
export class GlobalSettings {
/**
* Callback invoked when expression evaluation needs the value of a field in the source data object
* and that field is undefined or null. By default, expression evaluation will substitute an undefined
* field with its binding expression (e.g. `${field}`). This callback makes it possible to customize that
* behavior.
*
* **Example**
* Given this data object:
*
* ```json
* {
* firstName: "David"
* }
* ```
*
* The expression `${firstName} ${lastName}` will evaluate to "David ${lastName}" because the `lastName`
* field is undefined.
*
* Now let's set the callback:
* ```typescript
* GlobalSettings.getUndefinedFieldValueSubstitutionString = (path: string) => { return "<undefined value>"; }
* ```
*
* With that, the above expression will evaluate to "David <undefined value>"
*/
static getUndefinedFieldValueSubstitutionString?: (path: string) => string | undefined = undefined;
}
/**
* Holds the context used to expand a template.
*/
export interface IEvaluationContext {
/**
* The root data object the template will bind to. Expressions that refer to $root in the template payload
* map to this field. Initially, $data also maps to $root.
*/
$root: any
}
/**
* Represents a template that can be bound to data.
*/
export class Template {
private static prepare(node: any): any {
if (typeof node === "string") {
return Template.parseInterpolatedString(node);
}
else if (typeof node === "object" && node !== null) {
if (Array.isArray(node)) {
let result: any[] = [];
for (let item of node) {
result.push(Template.prepare(item));
}
return result;
}
else {
let keys = Object.keys(node);
let result = {};
for (let key of keys) {
result[key] = Template.prepare(node[key]);
}
return result;
}
}
else {
return node;
}
}
private static internalTryEvaluateExpression(expression: AEL.Expression, context: EvaluationContext, allowSubstitutions: boolean): { value: any; error: string } {
let memory = new TemplateObjectMemory();
memory.$root = context.$root;
memory.$data = context.$data;
memory.$index = context.$index;
let options: AEL.Options | undefined = undefined;
if (allowSubstitutions) {
options = new AEL.Options();
options.nullSubstitution = (path: string) => {
let substitutionValue: string | undefined = undefined;
if (GlobalSettings.getUndefinedFieldValueSubstitutionString) {
substitutionValue = GlobalSettings.getUndefinedFieldValueSubstitutionString(path);
}
return substitutionValue ? substitutionValue : "${" + path + "}";
}
}
// The root of an expression coming from an interpolated string is of type Concat.
// In that case, and if the caller allows it, we're doing our own concatenation
// in order to catch each individual expression evaluation error and substitute in
// the final string
if (expression.type === AEL.ExpressionType.Concat && allowSubstitutions) {
let result = "";
for (let childExpression of expression.children) {
let evaluationResult: { value: any; error: string };
try {
evaluationResult = childExpression.tryEvaluate(memory, options);
}
catch (ex) {
// We'll swallow all exceptions here
evaluationResult = {
value: undefined,
error: ex
};
}
if (evaluationResult.error) {
evaluationResult.value = "${" + childExpression.toString() + "}";
}
result += evaluationResult.value.toString();
}
return { value: result, error: undefined };
}
return expression.tryEvaluate(memory, options);
}
/**
* Parses an interpolated string into an Expression object ready to evaluate.
*
* @param interpolatedString The interpolated string to parse. Example: "Hello ${name}"
* @returns An Expression object if the provided interpolated string contained at least one expression (e.g. "${expression}"); the original string otherwise.
*/
public static parseInterpolatedString(interpolatedString: string): AEL.Expression | string {
let lookup: AEL.EvaluatorLookup = (type: string) => {
let standardFunction = AEL.ExpressionFunctions.standardFunctions.get(type);
if (standardFunction) {
return standardFunction;
}
else {
return new AEL.ExpressionEvaluator(
type,
(expression: AEL.Expression, state: AEL.MemoryInterface, options: AEL.Options) => { throw new Error("Unknown function " + type); },
AEL.ReturnType.String);
}
}
// If there is at least one expression start marker, let's attempt to convert into an expression
if (interpolatedString.indexOf("${") >= 0) {
let parsedExpression = AEL.Expression.parse("`" + interpolatedString + "`", lookup);
if (parsedExpression.type === "concat") {
if (parsedExpression.children.length === 1 && !(parsedExpression.children[0] instanceof AEL.Constant)) {
// The concat contains a single child that isn't a constant, thus the original
// string was a single expression. When evaluated, we want it to produce the type
// of that single expression
return parsedExpression.children[0];
}
else if (parsedExpression.children.length === 2) {
let firstChild = parsedExpression.children[0];
if (firstChild instanceof AEL.Constant && firstChild.value === "" && !(parsedExpression.children[1] instanceof AEL.Constant)) {
// The concat contains 2 children, and the first one is an empty string constant and the second isn't a constant.
// From version 4.10.3, AEL always inserts an empty string constant in all concat expression. Thus the original
// string was a single expression in this case as well. When evaluated, we want it to produce the type
// of that single expression.
return parsedExpression.children[1];
}
}
// Otherwise, we want the expression to produce a string
return parsedExpression;
}
}
// If the original string didn't contain any expression, return i as is
return interpolatedString;
}
/**
* Tries to evaluate the provided expression using the provided context.
*
* @param expression The expression to evaluate.
* @param context The context (data) used to evaluate the expression.
* @param allowSubstitutions Indicates if the expression evaluator should substitute undefined value with a default
* string or the value returned by the GlobalSettings.getUndefinedFieldValueSubstitutionString callback.
* @returns An object representing the result of the evaluation. If the evaluation succeeded, the value property
* contains the actual evaluation result, and the error property is undefined. If the evaluation fails, the error
* property contains a message detailing the error that occurred.
*/
public static tryEvaluateExpression(expression: AEL.Expression, context: IEvaluationContext, allowSubstitutions: boolean): { value: any; error: string } {
return Template.internalTryEvaluateExpression(expression, new EvaluationContext(context), allowSubstitutions);
}
private _context: EvaluationContext;
private _preparedPayload: any;
private expandSingleObject(node: object): any {
let result = {};
let keys = Object.keys(node);
for (let key of keys) {
if (!this._context.isReservedField(key)) {
let value = this.internalExpand(node[key]);
if (value !== undefined) {
result[key] = value;
}
}
}
return result;
}
private internalExpand(node: any): any {
let result: any;
this._context.saveState();
if (Array.isArray(node)) {
let itemArray: any[] = [];
for (let item of node) {
let expandedItem = this.internalExpand(item);
if (expandedItem !== null) {
if (Array.isArray(expandedItem)) {
itemArray = itemArray.concat(expandedItem);
}
else {
itemArray.push(expandedItem);
}
}
}
result = itemArray;
}
else if (node instanceof AEL.Expression) {
let evaluationResult = Template.internalTryEvaluateExpression(node, this._context, true);
if (!evaluationResult.error) {
result = evaluationResult.value;
}
else {
throw new Error(evaluationResult.error);
}
}
else if (typeof node === "object" && node !== null) {
let when = node["$when"];
let dataContext = node["$data"];
let dataContextIsArray: boolean = false;
let dataContexts: any[];
if (dataContext === undefined) {
dataContexts = [ undefined ];
}
else {
if (dataContext instanceof AEL.Expression) {
let evaluationResult = Template.internalTryEvaluateExpression(dataContext, this._context, true);
if (!evaluationResult.error) {
dataContext = evaluationResult.value;
}
else {
throw new Error(evaluationResult.error);
}
}
if (Array.isArray(dataContext)) {
dataContexts = dataContext;
dataContextIsArray = true;
}
else {
dataContexts = [ dataContext ];
}
}
result = [];
for (let i = 0; i < dataContexts.length; i++) {
if (dataContextIsArray) {
this._context.$index = i;
}
if (dataContexts[i] !== undefined) {
this._context.$data = dataContexts[i];
}
let dropObject = false;
if (when instanceof AEL.Expression) {
let evaluationResult = Template.internalTryEvaluateExpression(when, this._context, false);
let whenValue: boolean = false;
// If $when fails to evaluate or evaluates to anything but a boolean, consider it is false
if (!evaluationResult.error) {
whenValue = typeof evaluationResult.value === "boolean" && evaluationResult.value;
}
dropObject = !whenValue;
}
if (!dropObject) {
let expandedObject = this.expandSingleObject(node);
if (expandedObject !== null) {
result.push(expandedObject);
}
}
}
if (result.length === 0) {
result = null;
}
else if (result.length === 1) {
result = result[0];
}
}
else {
result = node;
}
this._context.restoreLastState();
return result;
}
/**
* Initializes a new Template instance based on the provided payload.
* Once created, the instance can be bound to different data objects
* in a loop.
*
* @param payload The template payload.
*/
constructor(payload: any) {
this._preparedPayload = Template.prepare(payload);
}
/**
* Expands the template using the provided context. Template expansion involves
* evaluating the expressions used in the original template payload, as well as
* repeating (expanding) parts of that payload that are bound to arrays.
*
* Example:
*
* ```typescript
* let context = {
* $root: {
* firstName: "John",
* lastName: "Doe",
* children: [
* { fullName: "Jane Doe", age: 9 },
* { fullName: "Alex Doe", age: 12 }
* ]
* }
* }
*
* let templatePayload = {
* type: "AdaptiveCard",
* version: "1.2",
* body: [
* {
* type: "TextBlock",
* text: "${firstName} ${lastName}"
* },
* {
* type: "TextBlock",
* $data: "${children}",
* text: "${fullName} (${age})"
* }
* ]
* }
*
* let template = new Template(templatePayload);
*
* let expandedTemplate = template.expand(context);
* ```
*
* With the above code, the value of `expandedTemplate` will be
*
* ```json
* {
* type: "AdaptiveCard",
* version: "1.2",
* body: [
* {
* type: "TextBlock",
* text: "John Doe"
* },
* {
* type: "TextBlock",
* text: "Jane Doe (9)"
* },
* {
* type: "TextBlock",
* text: "Alex Doe (12)"
* }
* ]
* }
* ```
*
* @param context The context to bind the template to.
* @returns A value representing the expanded template. The type of that value
* is dependent on the type of the original template payload passed to the constructor.
*/
expand(context: IEvaluationContext): any {
this._context = new EvaluationContext(context);
return this.internalExpand(this._preparedPayload);
}
} | the_stack |
import assert from 'assert'
import { Patch, applyLensToPatch, PatchOp, expandPatch } from '../src/patch'
import { applyLensToDoc } from '../src/doc'
import { updateSchema, schemaForLens } from '../src/json-schema'
import { LensSource } from '../src/lens-ops'
import {
renameProperty,
addProperty,
inside,
map,
hoistProperty,
plungeProperty,
wrapProperty,
headProperty,
convertValue,
} from '../src/helpers'
import { reverseLens } from '../src/reverse'
import { ReplaceOperation } from 'fast-json-patch'
import { JSONSchema7 } from 'json-schema'
export interface ProjectV1 {
title: string
tasks: { title: string }[]
complete: boolean
metadata: {
createdAt: number
updatedAt: number
}
}
export interface ProjectV2 {
name: string
description: string
issues: { title: string }[]
status: string
metadata: {
createdAt: number
updatedAt: number
}
}
const lensSource: LensSource = [
renameProperty('title', 'name'),
addProperty({ name: 'description', type: 'string', default: '' }),
convertValue(
'complete',
[
{ false: 'todo', true: 'done' },
{ todo: false, inProgress: false, done: true },
],
'boolean',
'string'
),
]
const projectV1Schema = <const>{
$schema: 'http://json-schema.org/draft-07/schema',
type: 'object' as const,
additionalProperties: false,
properties: {
title: { type: 'string' as const },
tasks: {
type: 'array' as const,
items: {
type: 'object',
properties: {
title: { type: 'string' },
},
},
},
complete: { type: 'boolean' as const },
metadata: {
type: 'object',
properties: {
createdAt: { type: 'number', default: 123 },
updatedAt: { type: 'number', default: 123 },
},
},
},
}
// ======================================
// Try sending a patch through the lens
// ======================================
describe('field rename', () => {
it('converts upwards', () => {
// Generate an edit from V1: setting the title field
// (todo: try the json patch library's observer as an ergonomic interface?)
const editTitleV1: Patch = [
{
op: 'replace' as const,
path: '/title',
value: 'new title',
},
]
// test the converted patch
assert.deepEqual(applyLensToPatch(lensSource, editTitleV1, projectV1Schema), [
{ op: 'replace', path: '/name', value: 'new title' },
])
})
it('does not rename another property that starts with same string', () => {
const editTitleBla: Patch = [
{
op: 'replace' as const,
path: '/title_bla',
value: 'new title',
},
]
assert.deepEqual(applyLensToPatch(lensSource, editTitleBla, projectV1Schema), editTitleBla)
})
it('converts downwards', () => {
// We can also use the left lens to convert a v2 patch into a v1 patch
const editNameV2: Patch = [
{
op: 'replace' as const,
path: '/name',
value: 'new name',
},
]
assert.deepEqual(
applyLensToPatch(
reverseLens(lensSource),
editNameV2,
updateSchema(projectV1Schema, lensSource)
),
[{ op: 'replace', path: '/title', value: 'new name' }]
)
})
it('works with whole doc conversion too', () => {
// fills in default values for missing fields
assert.deepEqual(applyLensToDoc(lensSource, { title: 'hello' }, projectV1Schema), {
complete: '',
description: '',
name: 'hello',
tasks: [],
metadata: {
createdAt: 123,
updatedAt: 123,
},
})
})
})
describe('add field', () => {
it('becomes an empty patch when reversed', () => {
const editDescription: Patch = [
{
op: 'replace' as const,
path: '/description',
value: 'going swimmingly',
},
]
assert.deepEqual(
applyLensToPatch(
reverseLens(lensSource),
editDescription,
updateSchema(projectV1Schema, lensSource)
),
[]
)
})
})
// ======================================
// Demo more complex conversions than a rename: todo boolean case
// ======================================
describe('value conversion', () => {
it('converts from a boolean to a string enum', () => {
const setComplete: Patch = [
{
op: 'replace' as const,
path: '/complete',
value: true,
},
]
assert.deepEqual(applyLensToPatch(lensSource, setComplete, projectV1Schema), [
{ op: 'replace', path: '/complete', value: 'done' },
])
})
it('reverse converts from a string enum to a boolean', () => {
const setStatus: Patch = [
{
op: 'replace' as const,
path: '/complete',
value: 'inProgress',
},
]
assert.deepEqual(
applyLensToPatch(
reverseLens(lensSource),
setStatus,
updateSchema(projectV1Schema, lensSource)
),
[{ op: 'replace', path: '/complete', value: false }]
)
})
it('handles a value conversion and a rename in the same lens', () => {
const lensSource = [
renameProperty('complete', 'status'),
convertValue(
'status',
[
{ false: 'todo', true: 'done' },
{ todo: false, inProgress: false, done: true },
],
'boolean',
'string'
),
]
const setComplete: Patch = [
{
op: 'replace' as const,
path: '/complete',
value: true,
},
]
assert.deepEqual(applyLensToPatch(lensSource, setComplete, projectV1Schema), [
{ op: 'replace', path: '/status', value: 'done' },
])
})
})
describe('nested objects', () => {
describe('singly nested object', () => {
// renaming metadata/basic/title to metadata/basic/name. a more sugary syntax:
// in("metadata", rename("title", "name", "string"))
const lensSource: LensSource = [inside('metadata', [renameProperty('title', 'name')])]
const docSchema = {
$schema: 'http://json-schema.org/draft-07/schema',
type: 'object' as const,
additionalProperties: false,
properties: {
metadata: {
type: 'object' as const,
properties: {
title: { type: 'string' as const },
},
},
otherparent: {
type: 'object' as const,
properties: {
title: { type: 'string' as const, default: '' },
},
},
},
}
it('renames a field correctly', () => {
const setDescription: Patch = [
{
op: 'replace' as const,
path: '/metadata/title',
value: 'hello',
},
]
assert.deepEqual(applyLensToPatch(lensSource, setDescription, docSchema), [
{ op: 'replace' as const, path: '/metadata/name', value: 'hello' },
])
})
it('works with whole doc conversion', () => {
assert.deepEqual(applyLensToDoc(lensSource, { metadata: { title: 'hello' } }, docSchema), {
metadata: { name: 'hello' },
otherparent: { title: '' },
})
})
it("doesn't rename another field", () => {
const randomPatch: Patch = [
{
op: 'replace' as const,
path: '/otherparent/title',
value: 'hello',
},
]
assert.deepEqual(applyLensToPatch(lensSource, randomPatch, docSchema), randomPatch)
})
it('renames a field in the left direction', () => {
const setDescription: Patch = [
{
op: 'replace' as const,
path: '/metadata/name',
value: 'hello',
},
]
const updatedSchema = updateSchema(docSchema, lensSource)
assert.deepEqual(applyLensToPatch(reverseLens(lensSource), setDescription, updatedSchema), [
{ op: 'replace' as const, path: '/metadata/title', value: 'hello' },
])
})
it('renames the field when a whole object is set in a patch', () => {
const setDescription: Patch = [
{
op: 'replace' as const,
path: '/metadata',
value: { title: 'hello' },
},
]
assert.deepEqual(applyLensToPatch(lensSource, setDescription, docSchema), [
{
op: 'replace' as const,
path: '/metadata',
value: {},
},
{
op: 'replace' as const,
path: '/metadata/name',
value: 'hello',
},
])
})
})
})
describe('arrays', () => {
// renaming tasks/n/title to tasks/n/name
const lensSource: LensSource = [inside('tasks', [map([renameProperty('title', 'name')])])]
it('renames a field in an array element', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[
{
op: 'replace' as const,
path: '/tasks/23/title',
value: 'hello',
},
],
projectV1Schema
),
[{ op: 'replace' as const, path: '/tasks/23/name', value: 'hello' }]
)
})
it('renames a field in the left direction', () => {
assert.deepEqual(
applyLensToPatch(
reverseLens(lensSource),
[
{
op: 'replace' as const,
path: '/tasks/23/name',
value: 'hello',
},
],
updateSchema(projectV1Schema, lensSource)
),
[{ op: 'replace' as const, path: '/tasks/23/title', value: 'hello' }]
)
})
})
describe('hoist (object)', () => {
const lensSource: LensSource = [hoistProperty('metadata', 'createdAt')]
it('pulls a field up to its parent', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[
{
op: 'replace' as const,
path: '/metadata/createdAt',
value: 'July 7th, 2020',
},
],
projectV1Schema
),
[{ op: 'replace' as const, path: '/createdAt', value: 'July 7th, 2020' }]
)
})
})
describe('plunge (object)', () => {
const lensSource: LensSource = [plungeProperty('metadata', 'title')]
// currently does not pass - strange ordering issue with fields in the object
it.skip('pushes a field into a child with applyLensToDoc', () => {
assert.deepEqual(
applyLensToDoc(
[{op: "plunge", host: "tags", name: "color"}],
{
// this currently throws an error but works if we re-order color and tags in the object below
color: "orange",
tags: {}
}
),
{ tags: { color: 'orange' } }
)
})
it('pushes a field into its child', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[
{
op: 'replace' as const,
path: '/title',
value: 'Fun project',
},
],
projectV1Schema
),
[{ op: 'replace' as const, path: '/metadata/title', value: 'Fun project' }]
)
})
})
describe('wrap (scalar to array)', () => {
const docSchema: JSONSchema7 = {
$schema: 'http://json-schema.org/draft-07/schema',
type: 'object' as const,
additionalProperties: false,
properties: {
assignee: { type: ['string' as const, 'null' as const] },
},
}
const lensSource: LensSource = [wrapProperty('assignee')]
it('converts head replace value into 0th element writes into its child', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[
{
op: 'replace' as const,
path: '/assignee',
value: 'July 7th, 2020',
},
],
docSchema
),
[{ op: 'replace' as const, path: '/assignee/0', value: 'July 7th, 2020' }]
)
})
it('converts head add value into 0th element writes into its child', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[
{
op: 'add' as const,
path: '/assignee',
value: 'July 7th, 2020',
},
],
docSchema
),
[{ op: 'add' as const, path: '/assignee/0', value: 'July 7th, 2020' }]
)
})
// todo: many possible options for how to handle this.
// Consider other options:
// https://github.com/inkandswitch/cambria/blob/default/conversations/converting-scalar-to-arrays.md
it('converts head null write into a remove the first element op', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[
{
op: 'replace' as const,
path: '/assignee',
value: null,
},
],
docSchema
),
[{ op: 'remove' as const, path: '/assignee/0' }]
)
})
it('handles a wrap followed by a rename', () => {
const lensSource: LensSource = [
wrapProperty('assignee'),
renameProperty('assignee', 'assignees'),
]
assert.deepEqual(
applyLensToPatch(
lensSource,
[
{
op: 'replace' as const,
path: '/assignee',
value: 'pvh',
},
],
docSchema
),
[{ op: 'replace' as const, path: '/assignees/0', value: 'pvh' }]
)
})
it('converts nested values into 0th element writes into its child', () => {
const docSchema: JSONSchema7 = {
$schema: 'http://json-schema.org/draft-07/schema',
type: 'object' as const,
additionalProperties: false,
properties: {
assignee: { type: ['object', 'null'], properties: { name: { type: 'string' } } },
},
}
assert.deepEqual(
applyLensToPatch(
lensSource,
[
{
op: 'replace' as const,
path: '/assignee/name',
value: 'Orion',
},
],
docSchema
),
[{ op: 'replace' as const, path: '/assignee/0/name', value: 'Orion' }]
)
})
describe('reverse direction', () => {
// this duplicates the tests of head;
// and is just a sanity check that the reverse isn't totally broken.
// (could be also tested independently, but this is a nice backup)
it('converts array first element write into a write on the scalar', () => {
assert.deepEqual(
applyLensToPatch(
reverseLens(lensSource),
[{ op: 'replace' as const, path: '/assignee/0', value: 'July 7th, 2020' }],
updateSchema(docSchema, lensSource)
),
[
{
op: 'replace' as const,
path: '/assignee',
value: 'July 7th, 2020',
},
]
)
})
})
})
describe('head (array to nullable scalar)', () => {
const docSchema = <const>{
$schema: 'http://json-schema.org/draft-07/schema',
type: 'object' as const,
additionalProperties: false,
properties: {
assignee: { type: 'array', items: { type: 'string' } },
},
}
const lensSource: LensSource = [headProperty('assignee')]
it('converts head set value into 0th element writes into its child', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[
{
op: 'replace' as const,
path: '/assignee/0',
value: 'Peter',
},
],
docSchema
),
[{ op: 'replace' as const, path: '/assignee', value: 'Peter' }]
)
})
it('converts a write on other elements to a no-op', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[
{
op: 'replace' as const,
path: '/assignee/1',
value: 'Peter',
},
],
docSchema
),
[]
)
})
it('converts array first element delete into a null write on the scalar', () => {
assert.deepEqual(
applyLensToPatch(lensSource, [{ op: 'remove' as const, path: '/assignee/0' }], docSchema),
[{ op: 'replace' as const, path: '/assignee', value: null }]
)
})
it('preserves the rest of the path after the array index', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[{ op: 'replace' as const, path: '/assignee/0/age', value: 23 }],
docSchema
),
[{ op: 'replace' as const, path: '/assignee/age', value: 23 }]
)
})
it('preserves the rest of the path after the array index with nulls', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[{ op: 'replace' as const, path: '/assignee/0/age', value: null }],
docSchema
),
[{ op: 'replace' as const, path: '/assignee/age', value: null }]
)
})
it('preserves the rest of the path after the array index with removes', () => {
assert.deepEqual(
applyLensToPatch(lensSource, [{ op: 'remove' as const, path: '/assignee/0/age' }], docSchema),
[{ op: 'remove' as const, path: '/assignee/age' }]
)
})
it('correctly handles a sequence of array writes', () => {
assert.deepEqual(
applyLensToPatch(
lensSource,
[
// set array to ['geoffrey', 'orion']
{ op: 'add' as const, path: '/assignee/0', value: 'geoffrey' },
{ op: 'add' as const, path: '/assignee/1', value: 'orion' },
// remove geoffrey from the array
// in our current naive json patch observer, this comes out as below.
// (this isn't a good patch format given crdt problems, but it's convenient for now
// because the patch itself gives us the new head value)
{ op: 'remove' as const, path: '/assignee/1' },
{ op: 'replace' as const, path: '/assignee/0', value: 'orion' },
],
docSchema
),
[
{
op: 'add' as const,
path: '/assignee',
value: 'geoffrey',
},
{
op: 'replace' as const,
path: '/assignee',
value: 'orion',
},
]
)
})
describe('reverse direction', () => {
// this duplicates the tests of wrap;
// and is just a sanity check that the reverse isn't totally broken.
// (could be also tested independently, but this is a nice backup)
const docSchema: JSONSchema7 = {
$schema: 'http://json-schema.org/draft-07/schema',
type: 'object' as const,
additionalProperties: false,
properties: {
assignee: { type: ['string', 'null'] },
},
}
it('converts head set value into 0th element writes into its child', () => {
assert.deepEqual(
applyLensToPatch(
reverseLens(lensSource),
[
{
op: 'replace' as const,
path: '/assignee',
value: 'July 7th, 2020',
},
],
docSchema
),
[{ op: 'replace' as const, path: '/assignee/0', value: 'July 7th, 2020' }]
)
})
})
})
describe('patch expander', () => {
it('expands a patch that sets an object', () => {
const setObject: PatchOp = {
op: 'replace' as const,
path: '/obj',
value: { a: { b: 5 } },
}
assert.deepEqual(expandPatch(setObject), [
{
op: 'replace' as const,
path: '/obj',
value: {},
},
{
op: 'replace' as const,
path: '/obj/a',
value: {},
},
{
op: 'replace' as const,
path: '/obj/a/b',
value: 5,
},
])
})
it('works with multiple keys', () => {
const setObject: PatchOp = {
op: 'replace' as const,
path: '/obj',
value: { a: { b: 5, c: { d: 6 } } },
}
assert.deepEqual(expandPatch(setObject), [
{
op: 'replace' as const,
path: '/obj',
value: {},
},
{
op: 'replace' as const,
path: '/obj/a',
value: {},
},
{
op: 'replace' as const,
path: '/obj/a/b',
value: 5,
},
{
op: 'replace' as const,
path: '/obj/a/c',
value: {},
},
{
op: 'replace' as const,
path: '/obj/a/c/d',
value: 6,
},
])
})
it('expands a patch that sets an array', () => {
const setObject: PatchOp = {
op: 'replace' as const,
path: '/obj',
value: ['hello', 'world'],
}
assert.deepEqual(expandPatch(setObject), [
{
op: 'replace' as const,
path: '/obj',
value: [],
},
{
op: 'replace' as const,
path: '/obj/0',
value: 'hello',
},
{
op: 'replace' as const,
path: '/obj/1',
value: 'world',
},
])
// deepEqual returns true for {} === []; so we need to double check ourselves
const op = expandPatch(setObject)[0] as ReplaceOperation<any>
assert(Array.isArray(op.value))
})
it('works recursively with objects and arrays', () => {
const setObject: PatchOp = {
op: 'replace' as const,
path: '',
value: { tasks: [{ name: 'hello' }, { name: 'world' }] },
}
assert.deepEqual(expandPatch(setObject), [
{
op: 'replace' as const,
path: '',
value: {},
},
{
op: 'replace' as const,
path: '/tasks',
value: [],
},
{
op: 'replace' as const,
path: '/tasks/0',
value: {},
},
{
op: 'replace' as const,
path: '/tasks/0/name',
value: 'hello',
},
{
op: 'replace' as const,
path: '/tasks/1',
value: {},
},
{
op: 'replace' as const,
path: '/tasks/1/name',
value: 'world',
},
])
})
})
describe('default value initialization', () => {
// one lens that creates objects inside of arrays and other objects
const v1Lens: LensSource = [
addProperty({ name: 'tags', type: 'array', items: { type: 'object' }, default: [] }),
inside('tags', [
map([
addProperty({ name: 'name', type: 'string', default: '' }),
addProperty({ name: 'color', type: 'string', default: '#ffffff' }),
]),
]),
addProperty({ name: 'metadata', type: 'object', default: {} }),
inside('metadata', [
addProperty({ name: 'title', type: 'string', default: '' }),
addProperty({ name: 'flags', type: 'object', default: {} }),
inside('flags', [addProperty({ name: 'O_CREATE', type: 'boolean', default: true })]),
]),
addProperty({
name: 'assignee',
type: ['string', 'null'],
}),
]
const v1Schema = schemaForLens(v1Lens)
it('fills in defaults on a patch that adds a new array item', () => {
const patchOp: PatchOp = {
op: 'add',
path: '/tags/123',
value: { name: 'bug' },
}
assert.deepEqual(applyLensToPatch([], [patchOp], v1Schema), [
{
op: 'add',
path: '/tags/123',
value: {},
},
{
op: 'add',
path: '/tags/123/name',
value: '',
},
{
op: 'add',
path: '/tags/123/color',
value: '#ffffff',
},
{
op: 'add',
path: '/tags/123/name',
value: 'bug',
},
])
})
it("doesn't expand a patch on an object key that already exists", () => {
const patchOp: PatchOp = {
op: 'add',
path: '/tags/123/name',
value: 'bug',
}
assert.deepEqual(applyLensToPatch([], [patchOp], v1Schema), [patchOp])
})
it('recursively fills in defaults from the root', () => {
const patchOp: PatchOp = {
op: 'add',
path: '',
value: {},
}
assert.deepEqual(applyLensToPatch([], [patchOp], v1Schema), [
{
op: 'add',
path: '',
value: {},
},
{
op: 'add',
path: '/tags',
value: [],
},
{
op: 'add',
path: '/metadata',
value: {},
},
{
op: 'add',
path: '/metadata/title',
value: '',
},
{
op: 'add',
path: '/metadata/flags',
value: {},
},
{
op: 'add',
path: '/metadata/flags/O_CREATE',
value: true,
},
{
op: 'add',
path: '/assignee',
value: null,
},
])
})
it('works correctly when properties are spread across multiple lenses', () => {
const v1Tov2Lens = [
renameProperty('tags', 'labels'),
inside('labels', [
map([addProperty({ name: 'important', type: 'boolean', default: false })]),
]),
]
const patchOp: PatchOp = {
op: 'add',
path: '/tags/123',
value: { name: 'bug' },
}
assert.deepEqual(applyLensToPatch(v1Tov2Lens, [patchOp], v1Schema), [
{
op: 'add',
path: '/labels/123',
value: {},
},
{
op: 'add',
path: '/labels/123/name',
value: '',
},
{
op: 'add',
path: '/labels/123/color',
value: '#ffffff',
},
{
op: 'add',
path: '/labels/123/important',
value: false,
},
{
op: 'add',
path: '/labels/123/name',
value: 'bug',
},
])
})
})
describe('inferring schemas from documents', () => {
const doc = {
name: 'hello',
details: {
age: 23,
height: 64,
},
}
it('infers a schema when converting a doc', () => {
const lens = [inside('details', [renameProperty('height', 'heightInches')])]
assert.deepEqual(applyLensToDoc(lens, doc), {
...doc,
details: {
age: 23,
heightInches: 64,
},
})
})
// We should do more here, but this is the bare minimum test of whether schema inference
// is actually working at all.
// If our lens tries to rename a nonexistent field, it should throw an error.
it("throws if the lens doesn't match the doc's inferred schema", () => {
const lens = [renameProperty('nonexistent', 'ghost')]
assert.throws(
() => {
applyLensToDoc(lens, doc)
},
{
message: /Cannot rename property/,
}
)
})
}) | the_stack |
// Fixture taken from https://github.com/RyanCavanaugh/koany/blob/master/koany.tsx
interface Garden {
colors: Gardens.RockColor[];
shapes: Gardens.RockShape[];
}
namespace Gardens {
export enum RockShape {
Empty,
Circle,
Triangle,
Square,
Max
}
export const RockShapes = [RockShape.Circle, RockShape.Triangle, RockShape.Square];
export const RockShapesAndEmpty = RockShapes.concat(RockShape.Empty);
export enum RockColor {
Empty,
White,
Red,
Black,
Max
}
export const RockColors = [RockColor.White, RockColor.Red, RockColor.Black];
export const RockColorsAndEmpty = RockColors.concat(RockColor.Empty);
export const Size = 9;
// 012
// 345
// 678
export const adjacencies = [
[1, 3], [0, 4, 2], [1, 5],
[0, 4, 6], [3, 1, 7, 5], [2, 4, 8],
[3, 7], [6, 4, 8], [7, 5]
];
}
module Koan {
export enum DescribeContext {
// every "white stone" is ...
Singular,
// all "white stones" are
Plural,
// every stone in the top row is "white"
Adjectival
}
export enum PartType {
Selector,
Aspect
}
export enum StateTestResult {
Fail = 0,
WeakPass = 1,
Pass = 2
}
/// A general format for producing a Statement
export interface StatementTemplate<T> {
holes: PartType[];
describe(args: T): string;
test(g: Garden, args: T): StateTestResult;
}
/// A completed rule that can be used to test a Garden
export interface ProducedStatement<T> {
test(g: Garden): StateTestResult;
description: string;
children: T;
hasPassedAndFailed(): boolean;
}
function rnd(max: number) {
return Math.floor(Math.random() * max);
}
function randomColor(): Gardens.RockColor {
return Math.floor(Math.random() * (Gardens.RockColor.Max - 1)) + 1
}
function randomShape(): Gardens.RockShape {
return Math.floor(Math.random() * (Gardens.RockShape.Max - 1)) + 1
}
/* New Impl Here */
interface SelectorSpec<T> {
childTypes?: PartType[];
precedence: number;
weight: number;
test(args: T, g: Garden, index: number): string|number|boolean;
describe(args: T, context: DescribeContext): string;
isAllValues(values: Array<string>|Array<number>): boolean;
}
interface ProducedSelector {
test(g: Garden, index: number): string|number|boolean;
getDescription(plural: DescribeContext): string;
seenAllValues(): boolean;
}
export function buildSelector<T>(spec: SelectorSpec<T>, args: T): ProducedSelector {
let seenResults: { [s: string]: boolean;} = {};
return {
test: (g: Garden, index: number) => {
var result = spec.test(args, g, index);
seenResults[result + ''] = true;
return result;
},
getDescription: (context) => {
return spec.describe(args, context);
},
seenAllValues: () => {
return spec.isAllValues(Object.keys(seenResults));
}
}
}
export var SelectorTemplates: Array<SelectorSpec<{}>> = [];
module LetsMakeSomeSelectors {
// Is rock
SelectorTemplates.push({
test: (args, g, i) => g.colors[i] !== Gardens.RockColor.Empty,
describe: (args, context) => {
switch(context) {
case DescribeContext.Plural:
return 'Stones';
case DescribeContext.Adjectival:
return 'not empty';
case DescribeContext.Singular:
return 'Stone';
}
},
isAllValues: items => items.length === 2,
precedence: 0,
weight: 1
});
// Is of a certain color and/or shape
Gardens.RockColorsAndEmpty.forEach(color => {
let colorName = Gardens.RockColor[color];
let colorWeight = color === Gardens.RockColor.Empty ? 1 : 0.33;
Gardens.RockShapesAndEmpty.forEach(shape => {
let shapeName = Gardens.RockShape[shape];
let shapeWeight = shape === Gardens.RockShape.Empty ? 1 : 0.33;
SelectorTemplates.push({
test: (args, g, i) => {
if(color === Gardens.RockColor.Empty) {
if (shape === Gardens.RockShape.Empty) {
return g.colors[i] === Gardens.RockColor.Empty;
} else {
return g.shapes[i] === shape;
}
} else {
if (shape === Gardens.RockShape.Empty) {
return g.colors[i] === color;
} else {
return g.shapes[i] === shape && g.colors[i] === color;
}
}
},
describe: (args, context) => {
if(color === Gardens.RockColor.Empty) {
if (shape === Gardens.RockShape.Empty) {
switch(context) {
case DescribeContext.Plural:
return 'Empty Cells';
case DescribeContext.Adjectival:
return 'Empty';
case DescribeContext.Singular:
return 'Empty Cell';
}
} else {
switch(context) {
case DescribeContext.Plural:
return shapeName + 's';
case DescribeContext.Adjectival:
return 'a ' + shapeName;
case DescribeContext.Singular:
return shapeName;
}
}
} else {
if (shape === Gardens.RockShape.Empty) {
switch(context) {
case DescribeContext.Plural:
return colorName + ' Stones';
case DescribeContext.Adjectival:
return colorName;
case DescribeContext.Singular:
return colorName + ' Stone';
}
} else {
switch(context) {
case DescribeContext.Plural:
return colorName + ' ' + shapeName + 's';
case DescribeContext.Adjectival:
return 'a ' + colorName + ' ' + shapeName;
case DescribeContext.Singular:
return colorName + ' ' + shapeName;
}
}
}
},
isAllValues: items => items.length === 2,
precedence: 3,
weight: (shapeWeight + colorWeight === 2) ? 0.3 : shapeWeight * colorWeight
});
});
});
// [?] in the [top|middle|bottom] [row|column]
[0, 1, 2].forEach(rowCol => {
[true, false].forEach(isRow => {
var name = (isRow ? ['top', 'middle', 'bottom'] : ['left', 'middle', 'right'])[rowCol] + ' ' + (isRow ? 'row' : 'column');
var spec: SelectorSpec<[ProducedSelector]> = {
childTypes: [PartType.Selector],
test: (args, g, i) => {
var c = isRow ? Math.floor(i / 3) : i % 3;
if (c === rowCol) {
return args[0].test(g, i);
} else {
return false;
}
},
describe: (args, plural) => args[0].getDescription(plural) + ' in the ' + name,
isAllValues: items => items.length === 2,
precedence: 4,
weight: 1 / 6
};
SelectorTemplates.push(spec);
});
});
// [?] next to a [?]
SelectorTemplates.push({
childTypes: [PartType.Selector, PartType.Selector],
test: (args, g, i) => {
if (args[0].test(g, i)) {
return Gardens.adjacencies[i].some(x => !!args[1].test(g, x));
} else {
return false;
}
},
describe: (args, plural) => {
return args[0].getDescription(plural) + ' next to a ' + args[1].getDescription(DescribeContext.Singular);
},
isAllValues: items => items.length === 2,
precedence: 4,
weight: 1
} as SelectorSpec<[ProducedSelector, ProducedSelector]>);
}
export function buildStatement<T>(s: StatementTemplate<T>, args: T): ProducedStatement<T> {
let hasPassed = false;
let hasFailed = false;
let result: ProducedStatement<T> = {
children: args,
description: s.describe(args),
test: (g) => {
let r = s.test(g, args);
if (r === StateTestResult.Pass) {
hasPassed = true;
} else if(r === StateTestResult.Fail) {
hasFailed = true;
}
return r;
},
hasPassedAndFailed: () => {
return hasPassed && hasFailed && (args as any as ProducedSelector[]).every(c => c.seenAllValues());
}
};
return result;
}
export let StatementList: StatementTemplate<any>[] = [];
module LetsMakeSomeStatements {
// Every [?] is a [?]
StatementList.push({
holes: [PartType.Selector, PartType.Selector],
test: (g: Garden, args: [ProducedSelector, ProducedSelector]) => {
let didAnyTests = false;
for (var i = 0; i < Gardens.Size; i++) {
if (args[0].test(g, i)) {
if(!args[1].test(g, i)) return StateTestResult.Fail;
didAnyTests = true;
}
}
return didAnyTests ? StateTestResult.Pass : StateTestResult.WeakPass;
},
describe: args => {
return 'Every ' + args[0].getDescription(DescribeContext.Singular) + ' is ' + args[1].getDescription(DescribeContext.Adjectival);
}
});
// There is exactly 1 [?]
StatementList.push({
holes: [PartType.Selector],
test: (g: Garden, args: [ProducedSelector, ProducedSelector]) => {
var count = 0;
for (var i = 0; i < Gardens.Size; i++) {
if (args[0].test(g, i)) count++;
}
return count === 1 ? StateTestResult.Pass : StateTestResult.Fail;
},
describe: args => {
return 'There is exactly one ' + args[0].description;
}
});
// There are more [?] than [?]
StatementList.push({
holes: [PartType.Selector, PartType.Selector],
test: (g: Garden, args: [ProducedSelector, ProducedSelector]) => {
var p1c = 0, p2c = 0;
for (var i = 0; i < Gardens.Size; i++) {
if (args[0].test(g, i)) p1c++;
if (args[1].test(g, i)) p2c++;
}
if(p1c > p2c && p2c > 0) {
return StateTestResult.Pass;
} else if(p1c > p2c) {
return StateTestResult.WeakPass;
} else {
return StateTestResult.Fail;
}
},
describe: args => {
return 'There are more ' + args[0].descriptionPlural + ' than ' + args[1].descriptionPlural;
}
});
}
function randomElementOf<T>(arr: T[]): T {
if (arr.length === 0) {
return undefined;
} else {
return arr[Math.floor(Math.random() * arr.length)];
}
}
function randomWeightedElementOf<T extends { weight: number }>(arr: T[]): T {
var totalWeight = arr.reduce((acc, v) => acc + v.weight, 0);
var rnd = Math.random() * totalWeight;
for (var i = 0; i < arr.length; i++) {
rnd -= arr[i].weight;
if (rnd <= 0) return arr[i];
}
// Got destroyed by floating error, just try again
return randomWeightedElementOf(arr);
}
export function buildRandomNewSelector(maxPrecedence = 1000000): ProducedSelector {
var choices = SelectorTemplates;
let initial = randomWeightedElementOf(choices.filter(p => p.precedence <= maxPrecedence));
// Fill in the holes
if (initial.childTypes) {
var fills = initial.childTypes.map(h => {
if (h === PartType.Selector) {
return buildRandomNewSelector(initial.precedence - 1);
} else {
throw new Error('Only know how to fill Selector holes')
}
});
return buildSelector(initial, fills);
} else {
return buildSelector(initial, []);
}
}
export function makeEmptyGarden(): Garden {
var g = {} as Garden;
g.colors = [];
g.shapes = [];
for (var i = 0; i < Gardens.Size; i++) {
g.colors.push(Gardens.RockColor.Empty);
g.shapes.push(Gardens.RockShape.Empty);
}
return g;
}
export function gardenToString(g: Garden): string {
return g.colors.join('') + g.shapes.join('');
}
export function makeRandomGarden(): Garden {
var g = makeEmptyGarden();
blitRandomGardenPair(g, g);
return g;
}
export function cloneGarden(g: Garden): Garden {
var result: Garden = {
colors: g.colors.slice(0),
shapes: g.shapes.slice(0)
};
return result;
}
export function clearGarden(g: Garden) {
for (var i = 0; i < Gardens.Size; i++) {
g.colors[i] = Gardens.RockColor.Empty;
g.shapes[i] = Gardens.RockShape.Empty;
}
}
export function blitRandomGardenPair(g1: Garden, g2: Garden): void {
let placeCount = 0;
for (var i = 0; i < Gardens.Size; i++) {
if (rnd(7) === 0) {
g1.colors[i] = g2.colors[i] = randomColor();
g1.shapes[i] = g2.shapes[i] = randomShape();
} else {
placeCount++;
g1.colors[i] = g2.colors[i] = Gardens.RockColor.Empty;
g1.shapes[i] = g2.shapes[i] = Gardens.RockShape.Empty;
}
}
if (placeCount === 0) blitRandomGardenPair(g1, g2);
}
export function blitNumberedGarden(g: Garden, stoneCount: number, n: number): void {
clearGarden(g);
let cellNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8];
for (let i = 0; i < stoneCount; i++) {
let cellNum = getValue(cellNumbers.length);
let cell = cellNumbers.splice(cellNum, 1)[0];
g.colors[cell] = getValue(3) + 1;
g.shapes[cell] = getValue(3) + 1;
}
function getValue(max: number) {
let result = n % max;
n = (n - result) / max;
return result;
}
}
export function mutateGarden(g: Garden): void {
while (true) {
var op = rnd(5);
let x = rnd(Gardens.Size);
let y = rnd(Gardens.Size);
switch (op) {
case 0: // Swap two non-identical cells
if (g.colors[x] !== g.colors[y] || g.shapes[x] !== g.shapes[y]) {
var tmp: any = g.colors[x];
g.colors[x] = g.colors[y];
g.colors[y] = tmp;
tmp = g.shapes[x];
g.shapes[x] = g.shapes[y];
g.shapes[y] = tmp;
return;
}
break;
case 1: // Add a stone
if (g.colors[x] === Gardens.RockColor.Empty) {
g.colors[x] = randomColor();
g.shapes[x] = randomShape();
return;
}
break;
case 2: // Remove a stone
if (g.colors.filter(x => x !== Gardens.RockColor.Empty).length === 1) continue;
if (g.colors[x] !== Gardens.RockColor.Empty) {
g.colors[x] = Gardens.RockColor.Empty;
g.shapes[x] = Gardens.RockShape.Empty;
return;
}
break;
case 3: // Change a color
let c = randomColor();
if (g.colors[x] !== Gardens.RockColor.Empty && g.colors[x] !== c) {
g.colors[x] = c;
return;
}
break;
case 4: // Change a shape
let s = randomShape();
if (g.shapes[x] !== Gardens.RockShape.Empty && g.shapes[x] !== s) {
g.shapes[x] = s;
return;
}
break;
}
}
}
}
class Indexion {
sizes: number[];
constructor(...sizes: number[]) {
this.sizes = sizes;
}
public getValues(index: number): number[] {
let result = new Array<number>(this.sizes.length);
this.fillValues(index, result);
return result;
}
public fillValues(index: number, result: number[]): void {
for (var i = 0; i < this.sizes.length; i++) {
result[i] = index % this.sizes[i];
index -= result[i];
index /= this.sizes[i];
}
}
public valuesToIndex(values: number[]): number {
var result = 0;
var factor = 1;
for (var i = 0; i < this.sizes.length; i++) {
result += values[i] * this.sizes[i] * factor;
factor *= this.sizes[i];
}
return result;
}
public getAdjacentIndices(index: number): number[][] {
var baseline = this.getValues(index);
var results: number[][] = [];
for (var i = 0; i < this.sizes.length; i++) {
if(baseline[i] > 0) {
baseline[i]--;
results.push(baseline.slice());
baseline[i]++;
}
if(baseline[i] < this.sizes[i] - 1) {
baseline[i]++;
results.push(baseline.slice());
baseline[i]--;
}
}
return results;
}
public distance(index1: number, index2: number): number {
let delta = 0;
for (var i = 0; i < this.sizes.length; i++) {
var a = index1 % this.sizes[i];
var b = index2 % this.sizes[i];
delta += Math.abs(b - a);
index1 -= a;
index2 -= b;
index1 /= this.sizes[i];
index2 /= this.sizes[i];
}
return delta;
}
}
function makeNewExample() {
while (true) {
var p1 = Koan.buildSelector(Koan.SelectorTemplates[12], []);
var p2 = Koan.buildSelector(Koan.SelectorTemplates[14], []);
var test = Koan.buildStatement(Koan.StatementList[0], [p1, p2]);
var examples: Garden[] = [];
console.log('Attempt to generate examples for "' + test.description + '"');
var maxGarden = /*(9 * 9) + (9 * 9 * 9 * 8) + */(9 * 9 * 9 * 8 * 9 * 7);
let g = Koan.makeEmptyGarden();
let passCount = 0, failCount = 0;
let resultLookup: boolean[] = [];
let lastResult: boolean = undefined;
for (var i = 0; i < maxGarden; i++) {
Koan.blitNumberedGarden(g, 3, i);
let result = test.test(g);
if(result === Koan.StateTestResult.Pass) {
resultLookup[i] = true;
passCount++;
if (lastResult !== true && examples.length < 10) examples.push(Koan.cloneGarden(g));
lastResult = true;
} else if (result === Koan.StateTestResult.Fail) {
resultLookup[i] = false;
failCount++;
if (lastResult !== false && examples.length < 10) examples.push(Koan.cloneGarden(g));
lastResult = false;
}
if (examples.length === 10) break;
}
console.log('Rule passes ' + passCount + ' and fails ' + failCount);
/*
if (!test.hasPassedAndFailed()) {
console.log('Rule has unreachable, contradictory, or tautological clauses');
continue;
}
if (passCount === 0 || failCount === 0) {
console.log('Rule is always true or always false');
continue;
}
*/
var h = document.createElement('h2');
h.innerText = test.description;
document.body.appendChild(h);
return { test: test, examples: examples };
}
}
let list: Garden[] = [];
let test: Koan.ProducedStatement<any>;
window.onload = function() {
let rule = makeNewExample();
let garden = Koan.makeRandomGarden();
list = rule.examples;
test = rule.test;
function renderList() {
function makeGarden(g: Garden, i: number) {
return <GardenDisplay
garden={g}
key={i + Koan.gardenToString(g)}
test={test}
leftButton='✗'
rightButton='✎'
onLeftButtonClicked={() => {
console.log(list.indexOf(g));
list.splice(list.indexOf(g), 1);
renderList();
}}
onRightButtonClicked={() => {
garden = g;
renderEditor();
}}
/>;
}
let gardenList = <div>{list.map(makeGarden)}</div>;
React.render(gardenList, document.getElementById('results'));
}
let i = 0;
function renderEditor() {
i++;
let editor = <GardenEditor key={i} test={rule.test} garden={garden} onSaveClicked={(garden) => {
list.push(garden);
renderList();
}} />;
React.render(editor, document.getElementById('editor'));
}
renderList();
renderEditor();
}
function classNames(nameMap: any): string {
return Object.keys(nameMap).filter(k => nameMap[k]).join(' ');
}
interface GardenCellProps extends React.Props<{}> {
color: Gardens.RockColor;
shape: Gardens.RockShape;
index: number;
movable?: boolean;
onEdit?(newColor: Gardens.RockColor, newShape: Gardens.RockShape): void;
}
interface GardenCellState {
isDragging?: boolean;
}
class GardenCell extends React.Component<GardenCellProps, GardenCellState> {
state: GardenCellState = {};
ignoreNextEdit = false;
render() {
var classes = ['cell', 'index_' + this.props.index];
if (this.state.isDragging) {
// Render as blank
} else {
classes.push(Gardens.RockColor[this.props.color], Gardens.RockShape[this.props.shape]);
}
if (this.props.movable) classes.push('movable');
let events: React.HTMLAttributes = {
onDragStart: (e) => {
this.ignoreNextEdit = false;
e.dataTransfer.dropEffect = 'copyMove';
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('shape', this.props.shape.toString());
e.dataTransfer.setData('color', this.props.color.toString());
let drag = document.getElementById(getGardenName(this.props.color, this.props.shape));
let xfer: any = (e.nativeEvent as DragEvent).dataTransfer;
xfer.setDragImage(drag, drag.clientWidth * 0.5, drag.clientHeight * 0.5);
this.setState({ isDragging: true });
},
onDragEnter: (e) => {
e.dataTransfer.dropEffect = 'move';
e.preventDefault();
},
onDragOver: (e) => {
e.dataTransfer.dropEffect = 'move';
e.preventDefault();
},
onDragEnd: (e) => {
this.setState({ isDragging: false });
if (!this.ignoreNextEdit) {
this.props.onEdit && this.props.onEdit(undefined, undefined);
}
},
draggable: true
}
let handleDrop = (event: React.DragEvent) => {
if(this.props.onEdit) {
if (this.state.isDragging) {
// Dragged to self, don't do anything
this.ignoreNextEdit = true;
} else {
let shape: Gardens.RockShape = +event.dataTransfer.getData('shape');
let color: Gardens.RockColor = +event.dataTransfer.getData('color');
this.props.onEdit(color, shape);
}
}
}
return <span className={classes.join(' ')} onDrop={handleDrop} {...this.props.movable ? events : {}} />;
}
}
interface GardenDisplayProps extends React.Props<GardenDisplay> {
garden?: Garden;
test?: Koan.ProducedStatement<any>;
leftButton?: string;
rightButton?: string;
onLeftButtonClicked?(): void;
onRightButtonClicked?(): void;
editable?: boolean;
onChanged?(newGarden: Garden): void;
}
interface GardenDisplayState {
garden?: Garden;
}
class GardenDisplay extends React.Component<GardenDisplayProps, GardenDisplayState> {
state = {
garden: Koan.cloneGarden(this.props.garden)
};
leftClicked = () => {
this.props.onLeftButtonClicked && this.props.onLeftButtonClicked();
};
rightClicked = () => {
this.props.onRightButtonClicked && this.props.onRightButtonClicked();
};
render() {
let g = this.state.garden;
let pass = (this.props.test && this.props.test.test(this.state.garden));
let classes = {
garden: true,
unknown: pass === undefined,
pass: pass === Koan.StateTestResult.Pass || pass === Koan.StateTestResult.WeakPass,
fail: pass === Koan.StateTestResult.Fail,
editable: this.props.editable
};
var children = g.colors.map((_, i) => (
<GardenCell
key={i}
color={g.colors[i]}
shape={g.shapes[i]}
index={i}
movable={this.props.editable}
onEdit={(newColor, newShape) => {
if(this.props.editable) {
let newGarden = Koan.cloneGarden(this.state.garden);
newGarden.colors[i] = newColor;
newGarden.shapes[i] = newShape;
this.setState({ garden: newGarden });
this.props.onChanged && this.props.onChanged(newGarden);
}
}}
/>));
return <div className="gardenDisplay">
<div className={classNames(classes)}>{children}</div>
<span className="infoRow">
{this.props.leftButton && <div className="button left" onClick={this.leftClicked}>{this.props.leftButton}</div>}
<div className={"passfail " + (pass ? 'pass' : 'fail')}>{pass ? '✓' : '🚫'}</div>
{this.props.rightButton && <div className="button right" onClick={this.rightClicked}>{this.props.rightButton}</div>}
</span>
</div>;
}
}
interface GardenEditorProps extends React.Props<GardenEditor> {
onSaveClicked?(garden: Garden): void;
test?: Koan.ProducedStatement<any>;
garden?: Garden;
}
interface GardenEditorState {
garden?: Garden;
pass?: boolean;
}
class GardenEditor extends React.Component<GardenEditorProps, {}> {
state = { garden: this.props.garden };
save = () => {
this.props.onSaveClicked && this.props.onSaveClicked(this.state.garden);
};
render() {
return <div className="editor">
<GardenDisplay garden={this.state.garden} test={this.props.test} editable onChanged={g => this.setState({ garden: g }) } />
<StonePalette />
<div className="button save" onClick={this.save}>{'💾'}</div>
</div>;
}
}
class StonePalette extends React.Component<{}, {}> {
render() {
let items: JSX.Element[] = [];
Gardens.RockColors.forEach(color => {
Gardens.RockShapes.forEach(shape => {
let name = getGardenName(color, shape);
let extraProps = { id: name, key: name };
let index = items.length;
items.push(<GardenCell
color={color}
shape={shape}
index={index}
movable
{...extraProps} />)
});
});
return <div className="palette">{items}</div>;
}
}
function getGardenName(color: Gardens.RockColor, shape: Gardens.RockShape) {
return 'draggable.' + Gardens.RockShape[shape] + '.' + Gardens.RockColor[color];
} | the_stack |
import React, { useEffect } from "react";
import Chart from "chart.js";
import { SiteVariablesPrepared } from "@fluentui/react-northstar";
import { TeamsTheme } from "../../../themes";
import { IChartData } from "../ChartTypes";
import {
tooltipTrigger,
tooltipAxisXLine,
chartConfig,
axesConfig,
setTooltipColorScheme,
usNumberFormat,
} from "../ChartUtils";
import { ChartContainer } from "./ChartContainer";
import { buildPattern, chartBarDataPointPatterns } from "../ChartPatterns";
import { getText } from "../../../translations";
export const BarChart = ({
title,
data,
siteVariables,
stacked,
}: {
title: string;
data: IChartData;
siteVariables: SiteVariablesPrepared;
stacked?: boolean;
}) => {
const { colorScheme, theme, colors, t } = siteVariables;
const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
const chartRef = React.useRef<Chart | undefined>();
const chartId = React.useMemo(
() => Math.random().toString(36).substr(2, 9),
[]
);
const chartDataPointColors = React.useMemo(
() => [
colors.brand["600"],
colors.brand["200"],
colors.brand["800"],
colors.grey["400"],
colors.grey["500"],
colorScheme.default.borderHover,
],
[theme]
);
const createDataPoints = (): Chart.ChartDataSets[] =>
Array.from(data.datasets, (set, i) => {
let dataPointConfig = {
label: getText(t.locale, set.label),
data: set.data,
borderWidth: 0,
borderSkipped: false,
borderColor: colorScheme.default.background,
hoverBorderColor: chartDataPointColors[i],
backgroundColor: chartDataPointColors[i],
hoverBorderWidth: 0,
hoverBackgroundColor: chartDataPointColors[i],
pointBorderColor: colorScheme.default.background,
pointBackgroundColor: colorScheme.default.foreground3,
pointHoverBackgroundColor: colorScheme.default.foreground3,
pointHoverBorderColor: chartDataPointColors[i],
pointHoverBorderWidth: 0,
borderCapStyle: "round",
borderJoinStyle: "round",
pointBorderWidth: 0,
pointRadius: 0,
pointHoverRadius: 0,
};
if (theme === TeamsTheme.HighContrast) {
dataPointConfig = {
...dataPointConfig,
borderWidth: 1,
hoverBorderColor: colorScheme.default.borderHover,
hoverBorderWidth: 3,
pointBorderColor: colorScheme.default.border,
pointHoverBorderColor: colorScheme.default.borderHover,
pointHoverRadius: 0,
borderColor: colorScheme.brand.background,
backgroundColor: buildPattern({
...chartBarDataPointPatterns(colorScheme)[i],
backgroundColor: colorScheme.default.background,
patternColor: colorScheme.brand.background,
}),
hoverBackgroundColor: buildPattern({
...chartBarDataPointPatterns(colorScheme)[i],
backgroundColor: colorScheme.default.background,
patternColor: colorScheme.default.borderHover,
}),
};
}
return dataPointConfig as any;
});
useEffect(() => {
let selectedIndex = -1;
let selectedDataSet = 0;
if (!canvasRef.current) return;
const ctx = canvasRef.current.getContext("2d");
if (!ctx) return;
const config: any = chartConfig({ type: "bar" });
config.options.hover.mode = "nearest";
config.options.scales.xAxes[0].gridLines.offsetGridLines =
data.datasets.length > 1 && !stacked ? true : false;
if (stacked) {
config.options.scales.yAxes[0].stacked = true;
config.options.scales.xAxes[0].stacked = true;
config.options.tooltips.callbacks.title = (tooltipItems: any) => {
let total = 0;
data.datasets.map((dataset) => {
const value = dataset.data[tooltipItems[0].index];
if (typeof value === "number") {
return (total += value);
}
});
return `${((tooltipItems[0].yLabel / total) * 100).toPrecision(
2
)}% (${usNumberFormat(tooltipItems[0].yLabel)})`;
};
}
chartRef.current = new Chart(ctx, {
...(config as any),
data: {
labels: Array.isArray(data.labels)
? data.labels.map((label) => getText(t.locale, label))
: getText(t.locale, data.labels),
datasets: [],
},
plugins: [
{
afterDatasetsDraw: ({ ctx, tooltip, chart }: any) => {
tooltipAxisXLine({
chart,
ctx,
tooltip,
});
},
},
],
});
const chart: any = chartRef.current;
/**
* Keyboard manipulations
*/
function meta() {
return chart.getDatasetMeta(selectedDataSet);
}
function removeFocusStyleOnClick() {
// Remove focus state style if selected by mouse
if (canvasRef.current) {
canvasRef.current.style.boxShadow = "none";
}
}
function removeDataPointsHoverStates() {
if (selectedIndex > -1) {
meta().controller.removeHoverStyle(
meta().data[selectedIndex],
0,
selectedIndex
);
}
}
function hoverDataPoint(pointID: number) {
meta().controller.setHoverStyle(
meta().data[pointID],
selectedDataSet,
pointID
);
}
function showFocusedDataPoint() {
hoverDataPoint(selectedIndex);
tooltipTrigger({
chart: chartRef.current as any,
data,
set: selectedDataSet,
index: selectedIndex,
siteVariables,
});
document
.getElementById(
`${chartId}-tooltip-${selectedDataSet}-${selectedIndex}`
)
?.focus();
}
function resetChartStates() {
removeDataPointsHoverStates();
const activeElements = chart.tooltip._active;
const requestedElem = chart.getDatasetMeta(selectedDataSet).data[
selectedIndex
];
activeElements.find((v: any, i: number) => {
if (requestedElem._index === v._index) {
activeElements.splice(i, 1);
return true;
}
});
for (let i = 0; i < activeElements.length; i++) {
if (requestedElem._index === activeElements[i]._index) {
activeElements.splice(i, 1);
break;
}
}
if (siteVariables.theme === TeamsTheme.HighContrast) {
(chartRef.current as any).data.datasets.map(
(dataset: any, i: number) => {
dataset.borderColor = siteVariables.colorScheme.default.border;
dataset.borderWidth = 2;
dataset.backgroundColor = buildPattern({
...chartBarDataPointPatterns(colorScheme)[i],
backgroundColor: colorScheme.default.background,
patternColor: colorScheme.brand.background,
});
}
);
chart.update();
}
chart.tooltip._active = activeElements;
chart.tooltip.update(true);
chart.draw();
}
function changeFocus(e: KeyboardEvent) {
removeDataPointsHoverStates();
switch (e.key) {
case "ArrowRight":
e.preventDefault();
selectedIndex = (selectedIndex + 1) % meta().data.length;
break;
case "ArrowLeft":
e.preventDefault();
selectedIndex = (selectedIndex || meta().data.length) - 1;
break;
case "ArrowUp":
e.preventDefault();
if (data.datasets.length > 1) {
selectedDataSet += 1;
if (selectedDataSet === data.datasets.length) {
selectedDataSet = 0;
}
}
break;
case "ArrowDown":
e.preventDefault();
if (data.datasets.length > 1) {
selectedDataSet -= 1;
if (selectedDataSet < 0) {
selectedDataSet = data.datasets.length - 1;
}
}
break;
}
showFocusedDataPoint();
}
canvasRef.current.addEventListener("click", removeFocusStyleOnClick);
canvasRef.current.addEventListener("keydown", changeFocus);
canvasRef.current.addEventListener("focusout", resetChartStates);
return () => {
if (!chartRef.current) return;
if (canvasRef.current) {
canvasRef.current.removeEventListener("click", removeFocusStyleOnClick);
canvasRef.current.removeEventListener("keydown", changeFocus);
canvasRef.current.removeEventListener("focusout", resetChartStates);
}
chartRef.current.destroy();
};
}, []);
/**
* Theme updates
*/
useEffect(() => {
if (!chartRef.current) return;
if (!canvasRef.current) return;
const ctx = canvasRef.current.getContext("2d");
if (!ctx) return;
// Apply new colors scheme for data points
chartRef.current.data.datasets = createDataPoints();
// Update tooltip colors scheme
setTooltipColorScheme({
chart: chartRef.current,
siteVariables,
chartDataPointColors,
patterns: chartBarDataPointPatterns,
});
// Update axeses
axesConfig({ chart: chartRef.current, ctx, colorScheme });
chartRef.current.update();
}, [theme]);
function onLegendClick(datasetIndex: number) {
if (!chartRef.current) return;
chartRef.current.data.datasets![datasetIndex].hidden = !chartRef.current
.data.datasets![datasetIndex].hidden;
chartRef.current.update();
}
return (
<ChartContainer
siteVariables={siteVariables}
data={data}
chartDataPointColors={chartDataPointColors}
patterns={chartBarDataPointPatterns}
onLegendClick={onLegendClick}
>
<canvas
id={chartId}
ref={canvasRef}
tabIndex={0}
style={{
userSelect: "none",
}}
aria-label={title}
>
{data.datasets.map((set, setKey) =>
(set.data as number[]).forEach((item: number, itemKey: number) => (
// Generated tooltips for screen readers
<div key={itemKey} id={`${chartId}-tooltip-${setKey}-${itemKey}`}>
<p>{item}</p>
<span>
{getText(t.locale, set.label)}: {set.data[itemKey]}
</span>
</div>
))
)}
</canvas>
</ChartContainer>
);
}; | the_stack |
import {
DisassemblyItem,
DisassemblyOutput,
MemorySection,
MemorySectionType,
SpectrumSpecificDisassemblyFlags,
processMessages,
intToX2,
intToX4,
toSbyte,
FloatNumber,
} from "./disassembly-helper";
import { CancellationToken } from "../utils/cancellation";
/**
* Number of disassembler items to process in a batch before
* allowing the event loop
*/
const DISASSEMBLER_BATCH = 2000;
/**
* Spectrum disassembly item
*/
interface ISpectrumDisassemblyItem {
item?: DisassemblyItem;
carryOn: boolean;
}
/**
* This class implements the Z80 disassembler
*/
export class Z80Disassembler {
private _output = new DisassemblyOutput();
private _offset = 0;
private _opOffset = 0;
private _currentOpCodes = "";
private _displacement: number | undefined;
private _opCode = 0;
private _indexMode = 0;
private _overflow = false;
private _spectMode = SpectrumSpecificMode.None;
private _seriesCount = 0;
private _lineCount = 0;
private _cancellationToken: CancellationToken | null = null;
/**
* Gets the contents of the memory
*/
readonly memoryContents: Uint8Array;
/**
* Memory sections used by the disassembler
*/
readonly memorySections: MemorySection[];
/**
* The ZX Spectrum specific disassembly flags for each bank
*/
readonly disassemblyFlags: Map<number, SpectrumSpecificDisassemblyFlags>;
/**
* Indicates if ZX Spectrum Next extended instruction disassembly is allowed
*/
readonly extendedInstructionsAllowed: boolean;
/**
* Initializes a new instance of the disassembler
* @param memorySections Memory map for disassembly
* @param memoryContents The contents of the memory to disassemble
* @param disasmFlags Optional flags to be used with the disassembly
* @param extendedSet True, if NEXT operation disassembly is allowed; otherwise, false
*/
constructor(
memorySections: MemorySection[],
memoryContents: Uint8Array,
disasmFlags?: Map<number, SpectrumSpecificDisassemblyFlags>,
extendedSet = false
) {
this.memorySections = memorySections;
this.memoryContents = memoryContents;
this.disassemblyFlags = disasmFlags
? disasmFlags
: new Map<number, SpectrumSpecificDisassemblyFlags>();
this.extendedInstructionsAllowed = extendedSet;
}
/**
* Disassembles the memory from the specified start address with the given endAddress
* @param startAddress The start address of the disassembly
* @param endAddress The end address of the disassembly
* @param cancellationToken Cancellation token to abort disassembly
* @param batchPause Optional break after a disassembly batch
* @returns The disassembly output, if finished; or null, if cancelled
*/
async disassemble(
startAddress = 0x0000,
endAddress = 0xffff,
cancellationToken?: CancellationToken
): Promise<DisassemblyOutput | null> {
this._cancellationToken = cancellationToken ?? null;
this._output = new DisassemblyOutput();
if (endAddress > this.memoryContents.length) {
endAddress = this.memoryContents.length - 1;
}
const refSection = new MemorySection(startAddress, endAddress);
this._lineCount = 0;
// --- Let's go through the memory sections
for (const section of this.memorySections) {
const toDisassemble = section.intersect(refSection);
if (!toDisassemble) {
continue;
}
switch (section.sectionType) {
case MemorySectionType.Disassemble:
await this._disassembleSection(toDisassemble);
break;
case MemorySectionType.ByteArray:
await this._generateByteArray(toDisassemble);
break;
case MemorySectionType.WordArray:
await this._generateWordArray(toDisassemble);
break;
case MemorySectionType.Skip:
this._generateSkipOutput(toDisassemble);
break;
case MemorySectionType.Rst28Calculator:
await this._generateRst28ByteCodeOutput(toDisassemble);
break;
}
if (this._cancellationToken?.cancelled) {
return null;
}
}
return this._output;
}
/**
* Allows the event loop to execute when a batch has ended
*/
private async allowEventLoop(): Promise<void> {
if (this._lineCount++ % DISASSEMBLER_BATCH === 0) {
await processMessages();
}
}
/**
* Creates disassembler output for the specified section
* @param section Section information
*/
private async _disassembleSection(section: MemorySection): Promise<void> {
this._offset = section.startAddress;
this._overflow = false;
const endOffset = section.endAddress;
let isSpectrumSpecific = false;
while (this._offset <= endOffset && !this._overflow) {
await this.allowEventLoop();
if (this._cancellationToken?.cancelled) {
return;
}
if (isSpectrumSpecific) {
const spectItem = this._disassembleSpectrumSpecificOperation();
isSpectrumSpecific = spectItem.carryOn;
if (spectItem && spectItem.item) {
this._output.addItem(spectItem.item);
}
} else {
// --- Disassemble the current item
const item = this._disassembleOperation();
if (item) {
this._output.addItem(item);
isSpectrumSpecific = this._shouldEnterSpectrumSpecificMode(item);
}
}
}
this._labelFixup();
}
/**
* Generates byte array output for the specified section
* @param section Section information
*/
private async _generateByteArray(section: MemorySection): Promise<void> {
const length = section.endAddress - section.startAddress + 1;
for (let i = 0; i < length; i += 8) {
let bytes: string[] = [];
for (let j = 0; j < 8; j++) {
if (i + j >= length) {
break;
}
bytes.push(
`#${intToX2(this.memoryContents[section.startAddress + i + j])}`
);
}
await this.allowEventLoop();
if (this._cancellationToken?.cancelled) {
return;
}
const startAddress = (section.startAddress + i) & 0xffff;
this._output.addItem({
address: startAddress,
instruction: ".defb " + bytes.join(", "),
});
}
}
/**
* Generates word array output for the specified section
* @param section Section information
*/
private async _generateWordArray(section: MemorySection): Promise<void> {
const length = section.endAddress - section.startAddress + 1;
for (let i = 0; i < length; i += 8) {
if (i + 1 >= length) {
break;
}
let words: string[] = [];
for (let j = 0; j < 8; j += 2) {
if (i + j + 1 >= length) {
break;
}
const value =
this.memoryContents[section.startAddress + i + j * 2] +
(this.memoryContents[section.startAddress + i + j * 2 + 1] << 8);
words.push(`#${intToX4(value & 0xffff)}`);
}
await this.allowEventLoop();
if (this._cancellationToken?.cancelled) {
return;
}
const startAddress = (section.startAddress + i) & 0xffff;
this._output.addItem({
address: startAddress,
instruction: ".defw " + words.join(", "),
});
}
if (length % 2 === 1) {
this._generateByteArray(
new MemorySection(section.endAddress, section.endAddress)
);
}
}
/**
* Generates skip output for the specified section
* @param section Section information
*/
private _generateSkipOutput(section: MemorySection): void {
this._output.addItem({
address: section.startAddress,
instruction: `.skip ${intToX4(
section.endAddress - section.startAddress + 1
)}H`,
});
}
/**
* Disassembles a single instruction
*/
private _disassembleOperation(): DisassemblyItem {
this._opOffset = this._offset;
this._currentOpCodes = "";
this._displacement = undefined;
this._indexMode = 0; // No index
let decodeInfo: string | undefined;
const address = this._offset & 0xffff;
// --- We should generate a normal instruction disassembly
this._opCode = this._fetch();
if (this._opCode === 0xed) {
// --- Decode extended instruction set
this._opCode = this._fetch();
decodeInfo =
!this.extendedInstructionsAllowed && z80NextSet[this._opCode]
? "nop"
: extendedInstructions[this._opCode] ?? "nop";
} else if (this._opCode === 0xcb) {
// --- Decode bit operations
this._opCode = this._fetch();
if (this._opCode < 0x40) {
switch (this._opCode >> 3) {
case 0x00:
decodeInfo = "rlc ^s";
break;
case 0x01:
decodeInfo = "rrc ^s";
break;
case 0x02:
decodeInfo = "rl ^s";
break;
case 0x03:
decodeInfo = "rr ^s";
break;
case 0x04:
decodeInfo = "sla ^s";
break;
case 0x05:
decodeInfo = "sra ^s";
break;
case 0x06:
decodeInfo = "sll ^s";
break;
case 0x07:
decodeInfo = "srl ^s";
break;
}
} else if (this._opCode < 0x80) {
decodeInfo = "bit ^b,^s";
} else if (this._opCode < 0xc0) {
decodeInfo = "res ^b,^s";
} else {
decodeInfo = "set ^b,^s";
}
} else if (this._opCode === 0xdd) {
// --- Decode IX-indexed operations
this._indexMode = 1; // IX
this._opCode = this._fetch();
decodeInfo = this._disassembleIndexedOperation();
} else if (this._opCode === 0xfd) {
// --- Decode IY-indexed operations
this._indexMode = 2; // IY
this._opCode = this._fetch();
decodeInfo = this._disassembleIndexedOperation();
} else {
// --- Decode standard operations
decodeInfo = standardInstructions[this._opCode];
}
return this._decodeInstruction(address, decodeInfo);
}
/**
* Gets the operation map for an indexed operation
*/
private _disassembleIndexedOperation(): string | undefined {
if (this._opCode !== 0xcb) {
let decodeInfo =
indexedInstrcutions[this._opCode] ?? standardInstructions[this._opCode];
if (decodeInfo && decodeInfo.indexOf("^D") >= 0) {
// --- The instruction used displacement, get it
this._displacement = this._fetch();
}
return decodeInfo;
}
this._displacement = this._fetch();
this._opCode = this._fetch();
if (this._opCode < 0x40) {
let pattern = "";
switch (this._opCode >> 3) {
case 0x00:
pattern = "rlc (^X^D)";
break;
case 0x01:
pattern = "rrc (^X^D)";
break;
case 0x02:
pattern = "rl (^X^D)";
break;
case 0x03:
pattern = "rr (^X^D)";
break;
case 0x04:
pattern = "sla (^X^D)";
break;
case 0x05:
pattern = "sra (^X^D)";
break;
case 0x06:
pattern = "sll (^X^D)";
break;
case 0x07:
pattern = "srl (^X^D)";
break;
}
if ((this._opCode & 0x07) !== 0x06) {
pattern += ",^s";
}
return pattern;
} else if (this._opCode < 0x80) {
return "bit ^b,(^X^D)";
} else if (this._opCode < 0xc0) {
return (this._opCode & 0x07) === 0x06
? "res ^b,(^X^D)"
: "res ^b,(^X^D),^s";
}
return (this._opCode & 0x07) === 0x06
? "set ^b,(^X^D)"
: "set ^b,(^X^D),^s";
}
/**
* Fetches the next byte to disassemble
*/
private _fetch(): number {
if (this._offset >= this.memoryContents.length) {
this._offset = 0;
this._overflow = true;
}
const value = this.memoryContents[this._offset++];
this._currentOpCodes += `${intToX2(value)} `;
return value;
}
/**
* Fetches the next word to disassemble
*/
private _fetchWord(): number {
const l = this._fetch();
const h = this._fetch();
return ((h << 8) | l) & 0xffff;
}
/**
* Decodes the specified instruction
* @param address Instruction address
* @param opInfo Operation inforamtion
*/
private _decodeInstruction(
address: number,
opInfo: string | undefined
): DisassemblyItem {
// --- By default, unknown codes are NOP operations
const disassemblyItem: DisassemblyItem = {
address,
opCodes: this._currentOpCodes,
instruction: "nop",
};
let pattern = opInfo ?? "";
// --- We have a real operation, it's time to decode it
let pragmaCount = 0;
disassemblyItem.instruction = pattern;
if (disassemblyItem.instruction) {
do {
const pragmaIndex = disassemblyItem.instruction.indexOf("^");
if (pragmaIndex < 0) {
break;
}
pragmaCount++;
this._processPragma(disassemblyItem, pragmaIndex);
} while (pragmaCount < 4);
}
// --- We've fully processed the instruction
disassemblyItem.opCodes = this._currentOpCodes;
return disassemblyItem;
}
/**
* Processes pragma informations within an operation map
* @param disassemblyItem Disassembly item to process
* @param pragmaIndex Index of the pragma within the instruction string
*/
private _processPragma(
disassemblyItem: DisassemblyItem,
pragmaIndex: number
): void {
const instruction = disassemblyItem.instruction;
if (!instruction || pragmaIndex >= instruction.length) {
return;
}
const pragma = instruction[pragmaIndex + 1];
let replacement = "";
let symbolPresent = false;
let symbolValue = 0x000;
switch (pragma) {
case "b":
// --- #b: bit index defined on bit 3, 4 and 5 in bit operations
var bit = (this._opCode & 0x38) >> 3;
replacement = bit.toString();
break;
case "r":
// --- #r: relative label (8 bit offset)
var distance = this._fetch();
var labelAddr = (this._opOffset + 2 + toSbyte(distance)) & 0xffff;
this._output.createLabel(labelAddr, this._opOffset);
replacement = `L${intToX4(labelAddr)}`;
symbolPresent = true;
disassemblyItem.hasLabelSymbol = true;
symbolValue = labelAddr;
break;
case "L":
// --- #L: absolute label (16 bit address)
var target = this._fetchWord();
this._output.createLabel(target, this._opOffset);
replacement = `L${intToX4(target)}`;
symbolPresent = true;
disassemblyItem.hasLabelSymbol = true;
symbolValue = target;
break;
case "s":
// --- #q: 8-bit registers named on bit 0, 1 and 2 (B, C, ..., (HL), A)
var regsIndex = this._opCode & 0x07;
replacement = q8Regs[regsIndex];
break;
case "B":
// --- #B: 8-bit value from the code
var value = this._fetch();
replacement = `#${intToX2(value)}`;
symbolPresent = true;
symbolValue = value;
break;
case "W":
// --- #W: 16-bit word from the code
var word = this._fetchWord();
replacement = `#${intToX4(word)}`;
symbolPresent = true;
symbolValue = word;
break;
case "X":
// --- #X: Index register (IX or IY) according to current index mode
replacement = this._indexMode === 1 ? "ix" : "iy";
break;
case "l":
// --- #l: Lowest 8 bit index register (XL or YL) according to current index mode
replacement = this._indexMode === 1 ? "xl" : "yl";
break;
case "h":
// --- #h: Highest 8 bit index register (XH or YH) according to current index mode
replacement = this._indexMode === 1 ? "xh" : "yh";
break;
case "D":
// --- #D: Index operation displacement
if (this._displacement) {
replacement =
toSbyte(this._displacement) < 0
? `-#${intToX2(0x100 - this._displacement)}`
: `+#${intToX2(this._displacement)}`;
}
break;
}
if (symbolPresent && replacement && replacement.length > 0) {
disassemblyItem.tokenPosition = pragmaIndex;
disassemblyItem.tokenLength = replacement.length;
disassemblyItem.hasSymbol = true;
disassemblyItem.symbolValue = symbolValue;
}
disassemblyItem.instruction =
instruction.substring(0, pragmaIndex) +
(replacement ? replacement : "") +
instruction.substring(pragmaIndex + 2);
}
/**
* Fixes the labels within the disassembly output
*/
private _labelFixup(): void {
for (const label of this._output.labels) {
const outputItem = this._output.get(label[0]);
if (outputItem) {
outputItem.hasLabel = true;
}
}
}
/**
* Generates bytecode output for the specified memory section
* @param section Section information
*/
private async _generateRst28ByteCodeOutput(
section: MemorySection
): Promise<void> {
this._spectMode = SpectrumSpecificMode.Spectrum48Rst28;
this._seriesCount = 0;
let addr = (this._offset = section.startAddress);
while (addr <= section.endAddress) {
await this.allowEventLoop();
if (this._cancellationToken?.cancelled) {
return;
}
this._currentOpCodes = "";
const opCode = this._fetch();
const entry = this._disassembleCalculatorEntry(addr, opCode);
if (entry.item) {
this._output.addItem(entry.item);
}
addr = this._offset;
}
}
/**
* Disassemble a calculator entry
* @param address Address of calculator entry
* @param calcCode Calculator entry code
*/
private _disassembleCalculatorEntry(
address: number,
calcCode: number
): ISpectrumDisassemblyItem {
// --- Create the default disassembly item
const result = {
item: <DisassemblyItem>{ address, lastAddress: address },
carryOn: false,
};
result.item.instruction = `.defb #${intToX2(calcCode)}`;
const opCodes: number[] = [calcCode];
result.carryOn = true;
// --- If we're in series mode, obtain the subsequent series value
if (this._seriesCount > 0) {
let lenght = (calcCode >> 6) + 1;
if ((calcCode & 0x3f) === 0) {
lenght++;
}
for (let i = 0; i < lenght; i++) {
const nextByte = this._fetch();
opCodes.push(nextByte);
}
let instruction = ".defb ";
for (let i = 0; i < opCodes.length; i++) {
if (i > 0) {
instruction += ", ";
}
instruction += `#${intToX2(opCodes[i])}`;
}
result.item.instruction = instruction;
result.item.hardComment = `(${FloatNumber.FromCompactBytes(
opCodes
).toFixed(6)})`;
this._seriesCount--;
return result;
}
// --- Generate the output according the calculation op code
switch (calcCode) {
case 0x00:
case 0x33:
case 0x35:
const jump = this._fetch();
opCodes.push(jump);
const jumpAddr = (this._offset - 1 + toSbyte(jump)) & 0xffff;
this._output.createLabel(jumpAddr);
result.item.instruction = `.defb #${intToX2(calcCode)}, #${intToX2(
jump
)}`;
result.item.hardComment = `(${calcOps[calcCode]}: L${intToX4(
jumpAddr
)})`;
result.carryOn = calcCode !== 0x33;
break;
case 0x34:
this._seriesCount = 1;
result.item.hardComment = "(stk-data)";
break;
case 0x38:
result.item.hardComment = "(end-calc)";
result.carryOn = false;
break;
case 0x86:
case 0x88:
case 0x8c:
this._seriesCount = calcCode - 0x80;
result.item.hardComment = `(series-0${(calcCode - 0x80).toString(16)})`;
break;
case 0xa0:
case 0xa1:
case 0xa2:
case 0xa3:
case 0xa4:
const constNo = calcCode - 0xa0;
result.item.hardComment = this._getIndexedCalcOp(0x3f, constNo);
break;
case 0xc0:
case 0xc1:
case 0xc2:
case 0xc3:
case 0xc4:
case 0xc5:
const stNo = calcCode - 0xc0;
result.item.hardComment = this._getIndexedCalcOp(0x40, stNo);
break;
case 0xe0:
case 0xe1:
case 0xe2:
case 0xe3:
case 0xe4:
case 0xe5:
const getNo = calcCode - 0xe0;
result.item.hardComment = this._getIndexedCalcOp(0x41, getNo);
break;
default:
const comment = calcOps[calcCode] ?? `calc code: #${intToX2(calcCode)}`;
result.item.hardComment = `(${comment})`;
break;
}
return result;
}
/**
* Gets the indexed operation
* @param opCode operation code
* @param index operation index
*/
private _getIndexedCalcOp(opCode: number, index: number): string {
const ops = calcOps[opCode];
if (ops) {
const values = ops.split("|");
if (index >= 0 && values.length > index) {
return `(${values[index]})`;
}
}
return `calc code: ${opCode}/${index}`;
}
/**
* Checks if the disassembler should enter into Spectrum-specific mode after
* the specified disassembly item.
* @param item Item used to check the Spectrum-specific mode
* @returns True, to move to the Spectrum-specific mode; otherwise, false
*/
private _shouldEnterSpectrumSpecificMode(item: DisassemblyItem): boolean {
// --- Check if we find flags for the bank of the disassembly item
const bank = item.address >> 14;
const flags = this.disassemblyFlags.get(bank);
if (!flags || flags === SpectrumSpecificDisassemblyFlags.None) {
return false;
}
// --- Check for Spectrum 48K RST #08
if (
(flags & SpectrumSpecificDisassemblyFlags.Spectrum48Rst08) !== 0 &&
item.opCodes &&
item.opCodes.trim() === "CF"
) {
this._spectMode = SpectrumSpecificMode.Spectrum48Rst08;
item.hardComment = "(Report error)";
return true;
}
// --- Check for Spectrum 48K RST #28
if (
(flags & SpectrumSpecificDisassemblyFlags.Spectrum48Rst28) !== 0 &&
item.opCodes &&
(item.opCodes.trim() === "EF" || // --- RST #28
item.opCodes.trim() === "CD 5E 33" || // --- CALL 335E
item.opCodes.trim() === "CD 62 33")
) {
// --- CALL 3362
this._spectMode = SpectrumSpecificMode.Spectrum48Rst28;
this._seriesCount = 0;
item.hardComment = "(Invoke Calculator)";
return true;
}
// --- Check for Spectrum 128K RST #28
if (
(flags & SpectrumSpecificDisassemblyFlags.Spectrum128Rst28) !== 0 &&
item.opCodes &&
item.opCodes.trim() === "EF"
) {
this._spectMode = SpectrumSpecificMode.Spectrum128Rst8;
item.hardComment = "(Call Spectrum 48 ROM)";
return true;
}
return false;
}
/**
* Disassembles the subsequent operation as Spectrum-specific operation
*/
private _disassembleSpectrumSpecificOperation(): ISpectrumDisassemblyItem {
if (this._spectMode === SpectrumSpecificMode.None) {
return {
item: undefined,
carryOn: false,
};
}
const result: ISpectrumDisassemblyItem = {
carryOn: false,
};
// --- Handle Spectrum 48 RST #08
if (this._spectMode === SpectrumSpecificMode.Spectrum48Rst08) {
// --- The next byte is the operation code
const address = this._offset;
const errorCode = this._fetch();
this._spectMode = SpectrumSpecificMode.None;
result.item = <DisassemblyItem>{
address,
//lastAddress: (this._offset - 1) & 0xffff,
instruction: `.defb #${intToX2(errorCode)}`,
hardComment: `(error code: #${intToX2(errorCode)})`,
};
}
// --- Handle Spectrum 48 RST #28
if (this._spectMode === SpectrumSpecificMode.Spectrum48Rst28) {
const address = this._offset & 0xffff;
const calcCode = this._fetch();
const entry = this._disassembleCalculatorEntry(address, calcCode);
result.item = entry.item;
}
// --- Handle Spectrum 128 RST #08
if (this._spectMode === SpectrumSpecificMode.Spectrum128Rst8) {
// --- The next byte is the operation code
const address = this._offset & 0xffff;
const callAddress = this._fetchWord();
this._spectMode = SpectrumSpecificMode.None;
result.item = <DisassemblyItem>{
address,
//lastAddress: (this._offset - 1) & 0xffff,
instruction: `.defw #${intToX4(callAddress)}`,
};
}
if (!result.carryOn) {
this._spectMode = SpectrumSpecificMode.None;
}
return result;
}
}
/**
* 8-bit register pairs for the ^s pragma
*/
export const q8Regs: string[] = ["b", "c", "d", "e", "h", "l", "(hl)", "a"];
/**
* Disassembly keywords that cannot be used as label names or other symbols
*/
export const disasmKeywords: string[] = [
"A",
"B",
"C",
"D",
"E",
"H",
"L",
"F",
"BC",
"DE",
"HL",
"AF",
"IX",
"IY",
"SP",
"IR",
"PC",
"NZ",
"Z",
"NC",
"PO",
"PE",
"P",
"M",
"ADD",
"ADC",
"AND",
"BIT",
"CALL",
"CCF",
"CP",
"CPD",
"CPDR",
"CPI",
"CPIR",
"CPL",
"DAA",
"DEC",
"DI",
"DJNZ",
"EI",
"EX",
"EXX",
"LD",
"LDD",
"LDDR",
"LDI",
"LDIR",
"IM",
"IN",
"INC",
"IND",
"INDR",
"INI",
"INIR",
"JR",
"JP",
"NEG",
"OR",
"OTDR",
"OTIR",
"OUT",
"OUTI",
"OUTD",
"POP",
"PUSH",
"RES",
"RET",
"RETI",
"RETN",
"RL",
"RLA",
"RLCA",
"RLC",
"RLD",
"RR",
"RRA",
"RRC",
"RRCA",
"RRD",
"RST",
"SBC",
"SCF",
"SET",
"SLA",
"SLL",
"SRA",
"SRL",
"SUB",
"XOR",
];
/**
* Disassembly stumps for standard instrcutions
*/
export const standardInstructions: string[] = [
/* 0x00 */ "nop",
/* 0x01 */ "ld bc,^W",
/* 0x02 */ "ld (bc),a",
/* 0x03 */ "inc bc",
/* 0x04 */ "inc b",
/* 0x05 */ "dec b",
/* 0x06 */ "ld b,^B",
/* 0x07 */ "rlca",
/* 0x08 */ "ex af,af'",
/* 0x09 */ "add hl,bc",
/* 0x0a */ "ld a,(bc)",
/* 0x0b */ "dec bc",
/* 0x0c */ "inc c",
/* 0x0d */ "dec c",
/* 0x0e */ "ld c,^B",
/* 0x0f */ "rrca",
/* 0x10 */ "djnz ^r",
/* 0x11 */ "ld de,^W",
/* 0x12 */ "ld (de),a",
/* 0x13 */ "inc de",
/* 0x14 */ "inc d",
/* 0x15 */ "dec d",
/* 0x16 */ "ld d,^B",
/* 0x17 */ "rla",
/* 0x18 */ "jr ^r",
/* 0x19 */ "add hl,de",
/* 0x1a */ "ld a,(de)",
/* 0x1b */ "dec de",
/* 0x1c */ "inc e",
/* 0x1d */ "dec e",
/* 0x1e */ "ld e,^B",
/* 0x1f */ "rra",
/* 0x20 */ "jr nz,^r",
/* 0x21 */ "ld hl,^W",
/* 0x22 */ "ld (^W),hl",
/* 0x23 */ "inc hl",
/* 0x24 */ "inc h",
/* 0x25 */ "dec h",
/* 0x26 */ "ld h,^B",
/* 0x27 */ "daa",
/* 0x28 */ "jr z,^r",
/* 0x29 */ "add hl,hl",
/* 0x2a */ "ld hl,(^W)",
/* 0x1b */ "dec hl",
/* 0x1c */ "inc l",
/* 0x1d */ "dec l",
/* 0x2e */ "ld l,^B",
/* 0x2f */ "cpl",
/* 0x30 */ "jr nc,^r",
/* 0x31 */ "ld sp,^W",
/* 0x32 */ "ld (^W),a",
/* 0x33 */ "inc sp",
/* 0x34 */ "inc (hl)",
/* 0x35 */ "dec (hl)",
/* 0x36 */ "ld (hl),^B",
/* 0x37 */ "scf",
/* 0x38 */ "jr c,^r",
/* 0x39 */ "add hl,sp",
/* 0x3a */ "ld a,(^W)",
/* 0x3b */ "dec sp",
/* 0x3c */ "inc a",
/* 0x3d */ "dec a",
/* 0x3e */ "ld a,^B",
/* 0x3f */ "ccf",
/* 0x40 */ "ld b,b",
/* 0x41 */ "ld b,c",
/* 0x42 */ "ld b,d",
/* 0x43 */ "ld b,e",
/* 0x44 */ "ld b,h",
/* 0x45 */ "ld b,l",
/* 0x46 */ "ld b,(hl)",
/* 0x47 */ "ld b,a",
/* 0x48 */ "ld c,b",
/* 0x49 */ "ld c,c",
/* 0x4a */ "ld c,d",
/* 0x4b */ "ld c,e",
/* 0x4c */ "ld c,h",
/* 0x4d */ "ld c,l",
/* 0x4e */ "ld c,(hl)",
/* 0x4f */ "ld c,a",
/* 0x50 */ "ld d,b",
/* 0x51 */ "ld d,c",
/* 0x52 */ "ld d,d",
/* 0x53 */ "ld d,e",
/* 0x54 */ "ld d,h",
/* 0x55 */ "ld d,l",
/* 0x56 */ "ld d,(hl)",
/* 0x57 */ "ld d,a",
/* 0x58 */ "ld e,b",
/* 0x59 */ "ld e,c",
/* 0x5a */ "ld e,d",
/* 0x5b */ "ld e,e",
/* 0x5c */ "ld e,h",
/* 0x5d */ "ld e,l",
/* 0x5e */ "ld e,(hl)",
/* 0x5f */ "ld e,a",
/* 0x60 */ "ld h,b",
/* 0x61 */ "ld h,c",
/* 0x62 */ "ld h,d",
/* 0x63 */ "ld h,e",
/* 0x64 */ "ld h,h",
/* 0x65 */ "ld h,l",
/* 0x66 */ "ld h,(hl)",
/* 0x67 */ "ld h,a",
/* 0x68 */ "ld l,b",
/* 0x69 */ "ld l,c",
/* 0x6a */ "ld l,d",
/* 0x6b */ "ld l,e",
/* 0x6c */ "ld l,h",
/* 0x6d */ "ld l,l",
/* 0x6e */ "ld l,(hl)",
/* 0x6f */ "ld l,a",
/* 0x70 */ "ld (hl),b",
/* 0x71 */ "ld (hl),c",
/* 0x72 */ "ld (hl),d",
/* 0x73 */ "ld (hl),e",
/* 0x74 */ "ld (hl),h",
/* 0x75 */ "ld (hl),l",
/* 0x76 */ "halt",
/* 0x77 */ "ld (hl),a",
/* 0x78 */ "ld a,b",
/* 0x79 */ "ld a,c",
/* 0x7a */ "ld a,d",
/* 0x7b */ "ld a,e",
/* 0x7c */ "ld a,h",
/* 0x7d */ "ld a,l",
/* 0x7e */ "ld a,(hl)",
/* 0x7f */ "ld a,a",
/* 0x80 */ "add a,b",
/* 0x81 */ "add a,c",
/* 0x82 */ "add a,d",
/* 0x83 */ "add a,e",
/* 0x84 */ "add a,h",
/* 0x85 */ "add a,l",
/* 0x86 */ "add a,(hl)",
/* 0x87 */ "add a,a",
/* 0x88 */ "adc a,b",
/* 0x89 */ "adc a,c",
/* 0x8a */ "adc a,d",
/* 0x8b */ "adc a,e",
/* 0x8c */ "adc a,h",
/* 0x8d */ "adc a,l",
/* 0x8e */ "adc a,(hl)",
/* 0x8f */ "adc a,a",
/* 0x90 */ "sub b",
/* 0x91 */ "sub c",
/* 0x92 */ "sub d",
/* 0x93 */ "sub e",
/* 0x94 */ "sub h",
/* 0x95 */ "sub l",
/* 0x96 */ "sub (hl)",
/* 0x97 */ "sub a",
/* 0x98 */ "sbc a,b",
/* 0x99 */ "sbc a,c",
/* 0x9a */ "sbc a,d",
/* 0x9b */ "sbc a,e",
/* 0x9c */ "sbc a,h",
/* 0x9d */ "sbc a,l",
/* 0x9e */ "sbc a,(hl)",
/* 0x9f */ "sbc a,a",
/* 0xa0 */ "and b",
/* 0xa1 */ "and c",
/* 0xa2 */ "and d",
/* 0xa3 */ "and e",
/* 0xa4 */ "and h",
/* 0xa5 */ "and l",
/* 0xa6 */ "and (hl)",
/* 0xa7 */ "and a",
/* 0xa8 */ "xor b",
/* 0xa9 */ "xor c",
/* 0xaa */ "xor d",
/* 0xab */ "xor e",
/* 0xac */ "xor h",
/* 0xad */ "xor l",
/* 0xae */ "xor (hl)",
/* 0xaf */ "xor a",
/* 0xb0 */ "or b",
/* 0xb1 */ "or c",
/* 0xb2 */ "or d",
/* 0xb3 */ "or e",
/* 0xb4 */ "or h",
/* 0xb5 */ "or l",
/* 0xb6 */ "or (hl)",
/* 0xb7 */ "or a",
/* 0xb8 */ "cp b",
/* 0xb9 */ "cp c",
/* 0xba */ "cp d",
/* 0xbb */ "cp e",
/* 0xbc */ "cp h",
/* 0xbd */ "cp l",
/* 0xbe */ "cp (hl)",
/* 0xbf */ "cp a",
/* 0xc0 */ "ret nz",
/* 0xc1 */ "pop bc",
/* 0xc2 */ "jp nz,^L",
/* 0xc3 */ "jp ^L",
/* 0xc4 */ "call nz,^L",
/* 0xc5 */ "push bc",
/* 0xc6 */ "add a,^B",
/* 0xc7 */ "rst #00",
/* 0xc8 */ "ret z",
/* 0xc9 */ "ret",
/* 0xca */ "jp z,^L",
/* 0xcb */ "",
/* 0xcc */ "call z,^L",
/* 0xcd */ "call ^L",
/* 0xce */ "adc a,^B",
/* 0xcf */ "rst #08",
/* 0xd0 */ "ret nc",
/* 0xd1 */ "pop de",
/* 0xd2 */ "jp nc,^L",
/* 0xd3 */ "out (^B),a",
/* 0xd4 */ "call nc,^L",
/* 0xd5 */ "push de",
/* 0xd6 */ "sub ^B",
/* 0xd7 */ "rst #10",
/* 0xd8 */ "ret c",
/* 0xd9 */ "exx",
/* 0xda */ "jp c,^L",
/* 0xdb */ "in a,(^B)",
/* 0xdc */ "call c,^L",
/* 0xdd */ "",
/* 0xde */ "sbc a,^B",
/* 0xdf */ "rst #18",
/* 0xe0 */ "ret po",
/* 0xe1 */ "pop hl",
/* 0xe2 */ "jp po,^L",
/* 0xe3 */ "ex (sp),hl",
/* 0xe4 */ "call po,^L",
/* 0xe5 */ "push hl",
/* 0xe6 */ "and ^B",
/* 0xe7 */ "rst #20",
/* 0xe8 */ "ret pe",
/* 0xe9 */ "jp (hl)",
/* 0xea */ "jp pe,^L",
/* 0xeb */ "ex de,hl",
/* 0xec */ "call pe,^L",
/* 0xed */ "",
/* 0xee */ "xor ^B",
/* 0xef */ "rst #28",
/* 0xf0 */ "ret p",
/* 0xf1 */ "pop af",
/* 0xf2 */ "jp p,^L",
/* 0xf3 */ "di",
/* 0xf4 */ "call p,^L",
/* 0xf5 */ "push af",
/* 0xf6 */ "or ^B",
/* 0xf7 */ "rst #30",
/* 0xf8 */ "ret m",
/* 0xf9 */ "ld sp,hl",
/* 0xfa */ "jp m,^L",
/* 0xfb */ "ei",
/* 0xfc */ "call m,^L",
/* 0xfd */ "",
/* 0xfe */ "cp ^B",
/* 0xff */ "rst #38",
];
/**
* Extended instructions available for ZX Spectrum Next only
*/
export const z80NextSet: { [key: number]: boolean } = {
0x23: true,
0x24: true,
0x27: true,
0x28: true,
0x29: true,
0x2a: true,
0x2b: true,
0x2c: true,
0x30: true,
0x31: true,
0x32: true,
0x33: true,
0x34: true,
0x35: true,
0x36: true,
0x8a: true,
0x90: true,
0x91: true,
0x92: true,
0x93: true,
0x94: true,
0x95: true,
0x98: true,
0xa4: true,
0xa5: true,
0xac: true,
0xb4: true,
0xb7: true,
0xbc: true,
};
export const extendedInstructions: { [key: number]: string } = {
0x23: "swapnib",
0x24: "mirror a",
0x27: "test ^B",
0x28: "bsla de,b",
0x29: "bsra de,b",
0x2a: "bsrl de,b",
0x2b: "bsrf de,b",
0x2c: "brlc de,b",
0x30: "mul d,e",
0x31: "add hl,a",
0x32: "add de,a",
0x33: "add bc,a",
0x34: "add hl,^W",
0x35: "add de,^W",
0x36: "add bc,^W",
0x40: "in b,(c)",
0x41: "out (c),b",
0x42: "sbc hl,bc",
0x43: "ld (^W),bc",
0x44: "neg",
0x45: "retn",
0x46: "im 0",
0x47: "ld i,a",
0x48: "in c,(c)",
0x49: "out (c),c",
0x4a: "adc hl,bc",
0x4b: "ld bc,(^W)",
0x4c: "neg",
0x4d: "reti",
0x4e: "im 0",
0x4f: "ld r,a",
0x50: "in d,(c)",
0x51: "out (c),d",
0x52: "sbc hl,de",
0x53: "ld (^W),de",
0x54: "neg",
0x55: "retn",
0x56: "im 1",
0x57: "ld a,i",
0x58: "in e,(c)",
0x59: "out (c),e",
0x5a: "adc hl,de",
0x5b: "ld de,(^W)",
0x5c: "neg",
0x5d: "retn",
0x5e: "im 2",
0x5f: "ld a,r",
0x60: "in h,(c)",
0x61: "out (c),h",
0x62: "sbc hl,hl",
0x63: "ld (^W),hl",
0x64: "neg",
0x65: "retn",
0x66: "im 0",
0x67: "rrd",
0x68: "in l,(c)",
0x69: "out (c),l",
0x6a: "adc hl,hl",
0x6b: "ld hl,(^W)",
0x6c: "neg",
0x6d: "retn",
0x6e: "im 0",
0x6f: "rld",
0x70: "in (c)",
0x71: "out (c),0",
0x72: "sbc hl,sp",
0x73: "ld (^W),sp",
0x74: "neg",
0x75: "retn",
0x76: "im 1",
0x78: "in a,(c)",
0x79: "out (c),a",
0x7a: "adc hl,sp",
0x7b: "ld sp,(^W)",
0x7c: "neg",
0x7d: "retn",
0x7e: "im 2",
0x8a: "push ^W", // BIG ENDIAN!
0x90: "outinb",
0x91: "nextreg ^B,^B",
0x92: "nextreg ^B,a",
0x93: "pixeldn",
0x94: "pixelad",
0x95: "setae",
0x98: "jp (c)",
0xa0: "ldi",
0xa1: "cpi",
0xa2: "ini",
0xa3: "outi",
0xa4: "ldix",
0xa5: "ldws",
0xa8: "ldd",
0xa9: "cpd",
0xaa: "ind",
0xab: "outd",
0xac: "lddx",
0xb0: "ldir",
0xb1: "cpir",
0xb2: "inir",
0xb3: "otir",
0xb4: "ldirx",
0xb7: "ldpirx",
0xb8: "lddr",
0xb9: "cpdr",
0xba: "indr",
0xbb: "otdr",
0xbc: "lddrx",
};
export const indexedInstrcutions: { [key: number]: string } = {
0x09: "add ^X,bc",
0x19: "add ^X,de",
0x21: "ld ^X,^W",
0x22: "ld (^W),^X",
0x23: "inc ^X",
0x24: "inc ^h",
0x25: "dec ^h",
0x26: "ld ^h,^B",
0x29: "add ^X,^X",
0x2a: "ld ^X,(^W)",
0x2b: "dec ^X",
0x2c: "inc ^l",
0x2d: "dec ^l",
0x2e: "ld ^l,^B",
0x34: "inc (^X^D)",
0x35: "dec (^X^D)",
0x36: "ld (^X^D),^B",
0x39: "add ^X,sp",
0x44: "ld b,^h",
0x45: "ld b,^l",
0x46: "ld b,(^X^D)",
0x4c: "ld c,^h",
0x4d: "ld c,^l",
0x4e: "ld c,(^X^D)",
0x54: "ld d,^h",
0x55: "ld d,^l",
0x56: "ld d,(^X^D)",
0x5c: "ld e,^h",
0x5d: "ld e,^l",
0x5e: "ld e,(^X^D)",
0x60: "ld ^h,b",
0x61: "ld ^h,c",
0x62: "ld ^h,d",
0x63: "ld ^h,e",
0x64: "ld ^h,^h",
0x65: "ld ^h,^l",
0x66: "ld h,(^X^D)",
0x67: "ld ^h,a",
0x68: "ld ^l,b",
0x69: "ld ^l,c",
0x6a: "ld ^l,d",
0x6b: "ld ^l,e",
0x6c: "ld ^l,^h",
0x6d: "ld ^l,^l",
0x6e: "ld l,(^X^D)",
0x6f: "ld ^l,a",
0x70: "ld (^X^D),b",
0x71: "ld (^X^D),c",
0x72: "ld (^X^D),d",
0x73: "ld (^X^D),e",
0x74: "ld (^X^D),h",
0x75: "ld (^X^D),l",
0x77: "ld (^X^D),a",
0x7c: "ld a,^h",
0x7d: "ld a,^l",
0x7e: "ld a,(^X^D)",
0x84: "add a,^h",
0x85: "add a,^l",
0x86: "add a,(^X^D)",
0x8c: "adc a,^h",
0x8d: "adc a,^l",
0x8e: "adc a,(^X^D)",
0x94: "sub ^h",
0x95: "sub ^l",
0x96: "sub (^X^D)",
0x9c: "sbc a,^h",
0x9d: "sbc a,^l",
0x9e: "sbc a,(^X^D)",
0xa4: "and ^h",
0xa5: "and ^l",
0xa6: "and (^X^D)",
0xac: "xor ^h",
0xad: "xor ^l",
0xae: "xor (^X^D)",
0xb4: "or ^h",
0xb5: "or ^l",
0xb6: "or (^X^D)",
0xbc: "cp ^h",
0xbd: "cp ^l",
0xbe: "cp (^X^D)",
0xe1: "pop ^X",
0xe3: "ex (sp),^X",
0xe5: "push ^X",
0xe9: "jp (^X)",
0xf9: "ld sp,^X",
};
/**
* RST 28 calculations
*/
export const calcOps: { [key: number]: string } = {
0x00: "jump-true",
0x01: "exchange",
0x02: "delete",
0x03: "subtract",
0x04: "multiply",
0x05: "division",
0x06: "to-power",
0x07: "or",
0x08: "no-&-no",
0x09: "no-l-eql",
0x0a: "no-gr-eq",
0x0b: "nos-neql",
0x0c: "no-grtr",
0x0d: "no-less",
0x0e: "nos-eql",
0x0f: "addition",
0x10: "str-&-no",
0x11: "str-l-eql",
0x12: "str-gr-eq",
0x13: "strs-neql",
0x14: "str-grtr",
0x15: "str-less",
0x16: "strs-eql",
0x17: "strs-add",
0x18: "val$",
0x19: "usr-$",
0x1a: "read-in",
0x1b: "negate",
0x1c: "code",
0x1d: "val",
0x1e: "len",
0x1f: "sin",
0x20: "cos",
0x21: "tan",
0x22: "asn",
0x23: "acs",
0x24: "atn",
0x25: "ln",
0x26: "exp",
0x27: "int",
0x28: "sqr",
0x29: "sgn",
0x2a: "abs",
0x2b: "peek",
0x2c: "in",
0x2d: "usr-no",
0x2e: "str$",
0x2f: "chr$",
0x30: "not",
0x31: "duplicate",
0x32: "n-mod-m",
0x33: "jump",
0x34: "stk-data",
0x35: "dec-jr-nz",
0x36: "less-0",
0x37: "greater-0",
0x38: "end-calc",
0x39: "get-argt",
0x3a: "truncate",
0x3b: "fp-calc-2",
0x3c: "e-to-fp",
0x3d: "re-stack",
0x3e: "series-06|series-08|series-0C",
0x3f: "stk-zero|stk-one|stk-half|stk-pi-half|stk-ten",
0x40: "st-mem-0|st-mem-1|st-mem-2|st-mem-3|st-mem-4|st-mem-5",
0x41: "get-mem-0|get-mem-1|get-mem-2|get-mem-3|get-mem-4|get-mem-5",
};
/**
* Spectrum-specific disassembly mode
*/
export enum SpectrumSpecificMode {
None = 0,
Spectrum48Rst08,
Spectrum48Rst28,
Spectrum128Rst8,
} | the_stack |
import type { CSSProperties } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Button, Col, message, Modal, Row, Space, Spin, Tooltip } from 'antd';
import { select, mouse } from 'd3-selection';
import { DATA_SOURCE_ENUM, HBASE_FIELD_TYPES, HDFS_FIELD_TYPES } from '@/constant';
import Resize from '../resize';
import { MinusOutlined, EditOutlined } from '@ant-design/icons';
import type { IDataColumnsProps, ISourceMapProps, ITargetMapProps } from '@/interface';
import { isNumber, isObject, isUndefined } from 'lodash';
import Api from '@/api';
import ScrollText from '../scrollText';
import { isHdfsType } from '@/utils/is';
import ConstModal from './modals/constModal';
import KeyModal from './modals/keyModal';
import BatchModal from './modals/batchModal';
import { Utils } from '@dtinsight/dt-utils/lib';
import './keymap.scss';
export const OPERATOR_TYPE = {
ADD: 'add',
REMOVE: 'remove',
EDIT: 'edit',
// replace is different from edit, which is change the whole columns
REPLACE: 'replace',
} as const;
export interface IKeyMapProps {
source: IDataColumnsProps[];
target: IDataColumnsProps[];
}
interface IKeyMapComponentProps {
/**
* 第一步所填写的信息
*/
sourceMap: ISourceMapProps;
/**
* 第二步所填写的信息
*/
targetMap: ITargetMapProps;
/**
* 用户自定义添加的列
*/
userColumns?: IKeyMapProps;
/**
* 是否只读,用于预览数据
*/
readonly?: boolean;
/**
* @deprecated
*/
isNativeHive?: boolean;
/**
* 改变表的列的回调函数
* @param column 做出改变的列
* @param operator 表示当前改变的策略,支持新增、删除、编辑、替换
* @param sourceOrTarget 区分改变源表列还是目标表列
*/
onColsChanged?: (
column: IDataColumnsProps | IDataColumnsProps[],
operator: Valueof<typeof OPERATOR_TYPE>,
sourceOrTarget: 'source' | 'target',
) => void;
/**
* 当字段映射关系发生改变的回调函数
*/
onLinesChanged?: (lines: IKeyMapProps) => void;
/**
* 下一步或上一步的回调函数
* @param next 为 true 时表示下一步,否则为上一步
*/
onNext?: (next: boolean) => void;
}
export const isValidFormatType = (type: any) => {
if (!type) return false;
const typeStr = type.toUpperCase();
return typeStr === 'STRING' || typeStr === 'VARCHAR' || typeStr === 'VARCHAR2';
};
function isFieldMatch(source: any, target: any) {
/**
* TODO 目前从接口返回的keymap字段与sourceMap, targetMap中不一致
*/
if (isObject(source as any) && isObject(target as any)) {
const sourceVal = source.key || source.index;
const tagetVal = target.key || target.index;
return sourceVal === tagetVal;
}
if (isObject(source as any) && !isObject(target as any)) {
const sourceVal = source.key || source.index;
return sourceVal === target;
}
if (!isObject(source as any) && isObject(target as any)) {
const targetVal = target.key || target.index;
return source === targetVal;
}
return source === target;
}
/**
* 获取批量添加的默认值
*/
function getBatIntVal(
type: DATA_SOURCE_ENUM | undefined,
typeCol: IDataColumnsProps[] | undefined,
) {
const isNotHBase = type !== DATA_SOURCE_ENUM.HBASE;
let initialVal = '';
if (isNotHBase) {
typeCol?.forEach((item) => {
const itemKey = Utils.checkExist(item.key) ? item.key : undefined;
const field = Utils.checkExist(item.index) ? item.index : itemKey;
if (field !== undefined) {
initialVal += `${field}:${item.type},\n`;
}
});
} else {
typeCol?.forEach((item) => {
const field = Utils.checkExist(item.key) ? item.key : undefined;
if (field !== undefined) initialVal += `${item.cf || '-'}:${field}:${item.type},\n`;
});
}
return initialVal;
}
export default function KeyMap({
sourceMap,
targetMap,
userColumns,
isNativeHive = false,
readonly,
onColsChanged,
onNext,
onLinesChanged,
}: IKeyMapComponentProps) {
const [loading, setLoading] = useState(false);
// 前两步选择的表获取字段
const [tableColumns, setTableCols] = useState<IKeyMapProps>({
source: [],
target: [],
});
const [canvasInfo, setCanvasInfo] = useState({
h: 40, // 字段一行高度
w: 230, // 字段的宽度
W: 600, // step容器大小
padding: 10, // 绘制拖拽点左右边距
});
// 连线数据
const [lines, setLines] = useState<IKeyMapProps>({
source: sourceMap.column || [],
target: targetMap.column || [],
});
const [btnTypes, setBtnTypes] = useState({ rowMap: false, nameMap: false });
const [visibleConst, setConstVisible] = useState(false);
const [keyModal, setKeyModal] = useState<{
visible: boolean;
isReader: boolean;
editField: IDataColumnsProps | undefined;
source: IDataColumnsProps | undefined;
operation: Valueof<typeof OPERATOR_TYPE>;
}>({
visible: false,
// 区分源表还是目标表
isReader: false,
editField: undefined,
source: undefined,
operation: OPERATOR_TYPE.ADD,
});
const [batchModal, setBatchModal] = useState<{
visible: boolean;
isReader: boolean;
defaultValue?: string;
}>({
visible: false,
// 区分源表还是目标表
isReader: false,
defaultValue: undefined,
});
// 列族,只有 HDFS 才有
const [families, setFamilies] = useState<{ source: string[]; target: string[] }>({
source: [],
target: [],
});
// step 容器
const $canvas = useRef<SVGSVGElement>(null);
// 拖动的线
const $activeLine = useRef<SVGLineElement>(null);
const { h, w, W, padding } = canvasInfo;
const loadColumnFamily = () => {
if (sourceSrcType === DATA_SOURCE_ENUM.HBASE) {
Api.getHBaseColumnFamily({
sourceId: sourceMap.sourceId,
tableName: sourceMap.table,
}).then((res) => {
if (res.code === 1) {
setFamilies((f) => ({ ...f, source: res.data || [] }));
}
});
}
if (targetSrcType === DATA_SOURCE_ENUM.HBASE) {
Api.getHBaseColumnFamily({
sourceId: targetMap.sourceId,
tableName: targetMap?.table,
}).then((res) => {
if (res.code === 1) {
setFamilies((f) => ({ ...f, target: res.data || [] }));
}
});
}
};
const handleResize = () => {
setCanvasInfo((f) => ({ ...f, W: getCanvasW() }));
};
const handleAddLines = (source: IDataColumnsProps, target: IDataColumnsProps) => {
setLines((ls) => {
// avoid to add lines from an already exist source or target
if (ls.source.some((l) => isFieldMatch(l, source))) return ls;
if (ls.target.some((l) => isFieldMatch(l, target))) return ls;
return {
source: [...ls.source, source],
target: [...ls.target, target],
};
});
};
const handleRemoveLines = (source: IDataColumnsProps, target: IDataColumnsProps) => {
setLines((ls) => {
const nextSource = ls.source.filter((s) => !isFieldMatch(s, source));
const nextTarget = ls.target.filter((s) => !isFieldMatch(s, target));
return {
source: nextSource,
target: nextTarget,
};
});
};
const handleRowMapClick = () => {
const { rowMap, nameMap } = btnTypes;
if (!rowMap) {
const source: IDataColumnsProps[] = [];
const target: IDataColumnsProps[] = [];
sourceCol.forEach((o, i) => {
if (targetCol[i]) {
source.push(o);
target.push(targetCol[i]);
}
});
setLines({ source, target });
} else {
setLines({ source: [], target: [] });
}
setBtnTypes({
rowMap: !rowMap,
nameMap: nameMap ? !nameMap : nameMap,
});
};
// 同名映射
const handleNameMapClick = () => {
const { nameMap, rowMap } = btnTypes;
if (!nameMap) {
const source: IDataColumnsProps[] = [];
const target: IDataColumnsProps[] = [];
sourceCol.forEach((o) => {
const name = o.key.toString().toUpperCase();
const idx = targetCol.findIndex((col) => {
const sourceName = col.key.toString().toUpperCase();
return sourceName === name;
});
if (idx !== -1) {
source.push(o);
target.push(targetCol[idx]);
}
});
setLines({ source, target });
} else {
setLines({ source: [], target: [] });
}
setBtnTypes({
nameMap: !nameMap,
rowMap: rowMap ? !rowMap : rowMap,
});
};
// 拷贝源表列
const handleCopySourceCols = () => {
if (isHdfsType(targetSrcType)) {
const serverParams: any = {};
sourceCol.forEach((item) => {
serverParams[item.key || item.index!] = item.type;
});
Api.convertToHiveColumns({
columns: serverParams,
}).then((res: any) => {
if (res.code === 1) {
const params: any = [];
Object.getOwnPropertyNames(res.data).forEach((key: any) => {
params.push({
key,
type: res.data[key],
});
});
onColsChanged?.(params, OPERATOR_TYPE.ADD, 'target');
}
});
} else if (sourceCol && sourceCol.length > 0) {
const params = sourceCol.map((item) => {
return {
key: !isUndefined(item.key) ? item.key : item.index!,
type: item.type,
};
});
onColsChanged?.(params, OPERATOR_TYPE.ADD, 'target');
}
};
// 拷贝目标表列
const handleCopyTargetCols = () => {
if (targetCol && targetCol.length > 0) {
const params = targetCol.map((item, index) => {
return {
key: item.key || index.toString(),
type: item.type,
};
});
onColsChanged?.(params, OPERATOR_TYPE.ADD, 'target');
}
};
const initEditKeyRow = (
isReader: boolean,
sourceCol: IDataColumnsProps | undefined,
field: IDataColumnsProps | undefined,
) => {
setKeyModal({
visible: true,
isReader,
editField: field,
source: sourceCol,
operation: OPERATOR_TYPE.EDIT,
});
};
const initAddKeyRow = (isReader: boolean) => {
setKeyModal({
visible: true,
isReader,
editField: undefined,
source: undefined,
operation: OPERATOR_TYPE.ADD,
});
};
const handleKeyModalSubmit = (values: IDataColumnsProps) => {
onColsChanged?.(
Object.assign(keyModal.editField || {}, values),
keyModal.operation,
keyModal.isReader ? 'source' : 'target',
);
handleHideKeyModal();
};
const handleHideKeyModal = () => {
setKeyModal({
visible: false,
isReader: false,
operation: OPERATOR_TYPE.ADD,
editField: undefined,
source: undefined,
});
};
const handleOpenBatchModal = (isReader: boolean = true) => {
const srcType = isReader ? sourceSrcType : targetSrcType;
const cols = isReader ? sourceCol : targetCol;
setBatchModal({
visible: true,
isReader,
defaultValue: getBatIntVal(srcType, cols),
});
};
// const importSourceFields = () => {
// setBatchModal({
// visible: true,
// isReader: true,
// defaultValue: getBatIntVal(sourceSrcType, sourceCol),
// });
// };
// const importFields = () => {
// setBatchModal({
// visible: true,
// isReader: false,
// defaultValue: getBatIntVal(targetSrcType, targetCol),
// });
// };
const handleHideBatchModal = () => {
setBatchModal({
visible: false,
isReader: false,
defaultValue: '',
});
};
// 批量添加源表字段
const handleBatchAddSourceFields = (batchText: string) => {
if (!batchText) {
handleHideBatchModal();
return;
}
const arr = batchText.split(',');
const params: IDataColumnsProps[] = [];
switch (sourceSrcType) {
case DATA_SOURCE_ENUM.FTP:
case DATA_SOURCE_ENUM.HDFS:
case DATA_SOURCE_ENUM.S3: {
for (let i = 0; i < arr.length; i += 1) {
const item = arr[i].replace(/\n/, '');
if (item) {
const map = item.split(':');
if (map.length < 1) {
break;
}
const key = parseInt(Utils.trim(map[0]), 10);
const type = map[1] ? Utils.trim(map[1]).toUpperCase() : null;
if (!Number.isNaN(key) && isNumber(key)) {
if (type && HDFS_FIELD_TYPES.includes(type)) {
if (!params.find((pa) => pa.key === key)) {
params.push({
key,
type,
});
}
} else {
message.error(`索引 ${key} 的数据类型错误!`);
return;
}
} else {
message.error(`索引名称 ${key} 应该为整数数字!`);
return;
}
}
}
break;
}
case DATA_SOURCE_ENUM.HBASE: {
for (let i = 0; i < arr.length; i += 1) {
const item = arr[i].replace(/\n/, '');
if (item) {
const map = item.split(':');
if (map.length < 2) {
break;
}
const cf = Utils.trim(map[0]);
const name = Utils.trim(map[1]);
const type = Utils.trim(map[2]);
if (!HBASE_FIELD_TYPES.includes(type)) {
message.error(`字段${name}的数据类型错误!`);
return;
}
params.push({
cf,
key: name,
type,
});
}
}
break;
}
default:
break;
}
onColsChanged?.(params, OPERATOR_TYPE.REPLACE, 'source');
handleHideBatchModal();
};
// 批量添加目标表字段
const handleBatchAddTargetFields = (batchText: string) => {
const str = Utils.trim(batchText);
const arr = str.split(',');
const params: any = [];
switch (targetSrcType) {
case DATA_SOURCE_ENUM.FTP:
case DATA_SOURCE_ENUM.HDFS:
case DATA_SOURCE_ENUM.S3: {
for (let i = 0; i < arr.length; i += 1) {
const item = arr[i];
if (item) {
const map = item.split(':');
const key = Utils.trim(map[0]);
const type = Utils.trim(map[1].toUpperCase());
if (HDFS_FIELD_TYPES.includes(type)) {
params.push({
key,
type,
});
} else {
message.error(`字段${key}的数据类型错误!`);
return;
}
}
}
break;
}
case DATA_SOURCE_ENUM.HBASE: {
for (let i = 0; i < arr.length; i += 1) {
const item = arr[i];
if (item) {
const map = item.split(':');
const cf = Utils.trim(map[0]);
const name = Utils.trim(map[1]);
const type = Utils.trim(map[2]);
if (!HBASE_FIELD_TYPES.includes(type)) {
message.error(`字段${name}的数据类型错误!`);
return;
}
params.push({
cf,
key: name,
type,
});
}
}
break;
}
default:
break;
}
onColsChanged?.(params, OPERATOR_TYPE.REPLACE, 'target');
handleHideBatchModal();
};
const handleSubmit = () => {
const { source, target } = lines;
if (source.length === 0 && target.length === 0) {
message.error('尚未配置数据同步的字段映射!');
return;
}
const isCarbonDataCheckPartition = () => {
if (targetSrcType === DATA_SOURCE_ENUM.CARBONDATA && !isNativeHive) {
const hasPartiton = targetCol.find((col) => col.isPart);
const keymapPartition = target.find((col) => col.isPart);
if (hasPartiton && !keymapPartition) {
message.error('目标字段中的分区字段必须添加映射!');
return false;
}
}
return true;
};
// 如果Carbondata作为目标数据源,且目标字段中有分区字段,分区字段必须添加映射,否则error
if (!isCarbonDataCheckPartition()) {
return;
}
// 针对Hbase增加keyrow检验项
if (targetSrcType === DATA_SOURCE_ENUM.HBASE) {
if (!checkHBaseRowKey()) {
return;
}
}
onNext?.(true);
};
const checkHBaseRowKey = () => {
const { rowkey } = targetMap;
const { source } = lines;
if (rowkey) {
const arr: any = [];
if (sourceSrcType === DATA_SOURCE_ENUM.HBASE) {
const regx = /([\w]+:[\w]+)/g;
const matchRes = rowkey.match(regx) || '';
for (let i = 0; i < matchRes.length; i += 1) {
const val = matchRes[i].split(':');
if (val && val.length === 2) {
const res = source.find(
(item) => item.cf === val[0] && item.key === val[1],
);
if (!res) {
message.error('目标表rowkey在源表中并不存在!');
return false;
}
}
}
} else {
// 正则提取
const regx = /\$\(([\w]+)\)/g;
let temp: any;
// eslint-disable-next-line no-cond-assign
while ((temp = regx.exec(rowkey)) !== null) {
arr.push(temp[1]);
}
// 验证字段
for (let i = 0; i < arr.length; i += 1) {
let res: IDataColumnsProps | undefined;
if (isObject(source[0])) {
res = source.find((item) => {
const name = item.key !== undefined ? item.key : item.index;
return `${name}` === `${arr[i]}` ? item : undefined;
});
} else {
res = source.find((item) => item === arr[i]);
}
if (!res) {
message.error(`目标表rowkey: ${arr[i]}在源表中并不存在!!`);
return false;
}
}
}
return true;
}
message.error('目标表rowkey不能为空!');
return false;
};
const keymapHelpModal = () => {
Modal.info({
title: '快速配置字段映射',
content: (
<div>
<img
style={{
width: '100%',
height: 400,
}}
src="images/keymap_help.jpg"
/>
</div>
),
width: 850,
okText: '了解',
});
};
const dragSvg = () => {
renderDags(
$canvas.current,
(tableColumns?.source || []).concat(userColumns?.source || []),
(tableColumns?.target || []).concat(userColumns?.target || []),
canvasInfo,
);
renderLines($canvas.current, lines, canvasInfo);
bindEvents(
$canvas.current,
$activeLine.current,
canvasInfo,
handleAddLines,
handleRemoveLines,
);
};
const renderSource = () => {
const colStyle: CSSProperties = {
left: padding,
top: padding,
width: w,
height: h,
};
const renderTableRow = (sourceType?: DATA_SOURCE_ENUM, col?: IDataColumnsProps) => {
const removeOption = (
<div
className="remove-cell"
onClick={() => col && onColsChanged?.(col, OPERATOR_TYPE.REMOVE, 'source')}
>
<Tooltip title="删除当前列">
<MinusOutlined />
</Tooltip>
</div>
);
const editOption = (
<div className="edit-cell" onClick={() => initEditKeyRow(true, undefined, col)}>
<Tooltip title="编辑当前列">
<EditOutlined />
</Tooltip>
</div>
);
const cellOperation = (remove: any, edit: any) => (
<div>
{remove}
{edit}
</div>
);
// eslint-disable-next-line no-nested-ternary
const typeValue = col
? col.value
? `常量(${col.type})`
: `${col.type ? col.type.toUpperCase() : ''}${
col.format ? `(${col.format})` : ''
}`
: '';
const type = col ? <ScrollText value={typeValue} /> : '类型';
switch (sourceType) {
case DATA_SOURCE_ENUM.HDFS:
case DATA_SOURCE_ENUM.S3: {
const name: any = col ? (
<ScrollText
value={
// eslint-disable-next-line no-nested-ternary
col.index !== undefined
? col.index
: col.value
? `'${col.key}'`
: col.key
}
/>
) : (
'索引位'
);
return (
<div>
<div className="cell">{name}</div>
<div className="cell" title={typeValue}>
{type}
</div>
{sourceMap.fileType !== 'orc' ? (
<div className="cell">
{col ? cellOperation(removeOption, editOption) : '操作'}
</div>
) : (
''
)}
</div>
);
}
case DATA_SOURCE_ENUM.HBASE: {
const name: any = col ? (
<ScrollText value={col.value ? `'${col.key}'` : col.key} />
) : (
'列名/行健'
);
const cf = col ? col.cf : '列族';
// 仅允许常量删除操作
const opt =
col && col.key === 'rowkey'
? cellOperation(null, editOption)
: cellOperation(removeOption, editOption);
return (
<div className="four-cells">
<div className="cell" title={cf}>
{cf || '-'}
</div>
<div className="cell">{name}</div>
<div className="cell" title={typeValue}>
{type}
</div>
<div className="cell">{col ? opt : '操作'}</div>
</div>
);
}
case DATA_SOURCE_ENUM.MAXCOMPUTE:
case DATA_SOURCE_ENUM.HIVE1X:
case DATA_SOURCE_ENUM.HIVE:
case DATA_SOURCE_ENUM.HIVE3X: {
const name: any = col ? (
<ScrollText value={col.value ? `'${col.key}'` : col.key} />
) : (
'字段名称'
);
// 仅允许常量删除操作
const opt =
col && col.value
? cellOperation(removeOption, editOption)
: cellOperation(null, editOption);
return (
<div>
<div className="cell">{name}</div>
<div className="cell" title={typeValue}>
{type}
</div>
<div className="cell">{col ? opt : '操作'}</div>
</div>
);
}
case DATA_SOURCE_ENUM.IMPALA: {
const name: any = col ? (
<ScrollText value={col.value ? `'${col.key}'` : col.key} />
) : (
'字段名称'
);
// 仅允许常量删除操作
const opt =
col && col.value
? cellOperation(removeOption, editOption)
: cellOperation(null, editOption);
return (
<div>
<div className="cell">{name}</div>
<div className="cell" title={typeValue}>
{type}
{col && col.isPart && (
<img
src="images/primary-key.svg"
style={{
float: 'right',
marginTop: '-26px',
}}
/>
)}
</div>
<div className="cell">{col ? opt : '操作'}</div>
</div>
);
}
case DATA_SOURCE_ENUM.FTP: {
const name: any = col ? (
<ScrollText
value={
// eslint-disable-next-line no-nested-ternary
col.index !== undefined
? col.index
: col.value
? `'${col.key}'`
: col.key
}
/>
) : (
'字段序号'
);
return (
<div>
<div className="cell">{name}</div>
<div className="cell" title={typeValue}>
{type}
</div>
<div className="cell">
{col ? cellOperation(removeOption, editOption) : '操作'}
</div>
</div>
);
}
default: {
// 常量都允许删除和编辑
const canFormat = isValidFormatType(col && col.type) || col?.value;
const opt = (
<div>
{col && col.value ? removeOption : ''}
{canFormat ? editOption : ''}
</div>
);
const name: any = col ? (
<ScrollText value={col.value ? `'${col.key}'` : col.key} />
) : (
'字段名称'
);
return (
<div>
<div className="cell">{name}</div>
<div className="cell" title={typeValue}>
{type}
</div>
<div className="cell">{col ? opt : '操作'}</div>
</div>
);
}
}
};
const renderTableFooter = (sourceType?: DATA_SOURCE_ENUM) => {
if (readonly) return '';
let footerContent = null;
const btnAddConst = (
<span className="col-plugin" onClick={() => setConstVisible(true)}>
+添加常量
</span>
);
switch (sourceType) {
case DATA_SOURCE_ENUM.HBASE:
footerContent = (
<span>
<span className="col-plugin" onClick={() => initAddKeyRow(true)}>
+添加字段
</span>
<span className="col-plugin" onClick={() => handleOpenBatchModal()}>
+文本模式
</span>
</span>
);
break;
case DATA_SOURCE_ENUM.HDFS:
case DATA_SOURCE_ENUM.S3: {
footerContent =
sourceMap.fileType !== 'orc' ? (
<span>
<span className="col-plugin" onClick={() => initAddKeyRow(true)}>
+添加字段
</span>
<span className="col-plugin" onClick={() => handleOpenBatchModal()}>
+文本模式
</span>
</span>
) : null;
break;
}
case DATA_SOURCE_ENUM.FTP: {
footerContent = (
<span>
<span className="col-plugin" onClick={() => initAddKeyRow(true)}>
+添加字段
</span>
<span className="col-plugin" onClick={() => handleOpenBatchModal()}>
+文本模式
</span>
</span>
);
break;
}
default: {
footerContent = null;
break;
}
}
return (
<div
className="m-col absolute"
style={{
left: padding,
top: padding + h * (sourceCol.length + 1),
width: w,
height: h,
zIndex: 2,
}}
>
{footerContent}
{btnAddConst}
</div>
);
};
return (
<div className="sourceLeft">
<div className="m-col title absolute" style={colStyle}>
{renderTableRow(sourceSrcType)}
</div>
{sourceCol.map((col, i) => (
<div
style={{
width: w,
height: h,
left: padding,
top: padding + h * (i + 1),
}}
className="m-col absolute"
key={`sourceLeft-${i}`}
>
{renderTableRow(sourceSrcType, col)}
</div>
))}
{renderTableFooter(sourceSrcType)}
</div>
);
};
const renderTarget = () => {
const colStyle: CSSProperties = {
left: W - (padding + w),
top: padding,
width: w,
height: h,
};
const renderTableRow = (
targetType?: DATA_SOURCE_ENUM,
col?: IDataColumnsProps,
i?: number,
) => {
const operations = (
<div>
<div
className="remove-cell"
onClick={() => col && onColsChanged?.(col, OPERATOR_TYPE.REMOVE, 'target')}
>
<Tooltip title="删除当前列">
<MinusOutlined />
</Tooltip>
</div>
<div
className="edit-cell"
onClick={() => i !== undefined && initEditKeyRow(false, sourceCol[i], col)}
>
<Tooltip title="编辑当前列">
<EditOutlined />
</Tooltip>
</div>
</div>
);
switch (targetType) {
case DATA_SOURCE_ENUM.HDFS:
case DATA_SOURCE_ENUM.S3: {
const name = col ? <ScrollText value={col.key} /> : '字段名称';
const type = col ? col.type.toUpperCase() : '类型';
return (
<div>
<div className="cell">{name}</div>
<div className="cell" title={type}>
{type}
</div>
<div className="cell">{col ? operations : '操作'}</div>
</div>
);
}
case DATA_SOURCE_ENUM.HBASE: {
const name = col ? col.cf : '列族';
const column: any = col ? <ScrollText value={col.key} /> : '列名';
const type: any = col ? <ScrollText value={col.type.toUpperCase()} /> : '类型';
return (
<div className="four-cells">
<div className="cell">{name}</div>
<div className="cell" title={column}>
{column}
</div>
<div className="cell" title={type}>
{type}
</div>
<div className="cell">{col ? operations : '操作'}</div>
</div>
);
}
case DATA_SOURCE_ENUM.FTP: {
const column = col ? <ScrollText value={col.key} /> : '字段名称';
const type = col ? col.type.toUpperCase() : '类型';
return (
<div>
<div
className="cell"
title={col ? col.key.toString() : (column as string)}
>
{column}
</div>
<div className="cell" title={type}>
{type}
</div>
<div className="cell">{col ? operations : '操作'}</div>
</div>
);
}
case DATA_SOURCE_ENUM.IMPALA: {
const typeText = col
? `${col.type.toUpperCase()}${col.isPart ? '(分区字段)' : ''}`
: '类型';
const fieldName = col ? <ScrollText value={col.key} /> : '字段名称';
return (
<div>
<div
className="cell"
title={col ? col.key.toString() : (fieldName as string)}
>
{fieldName}
</div>
<div className="cell" title={typeText}>
{typeText}
{col && col.isPart && (
<img
src="images/primary-key.svg"
style={{
float: 'right',
marginTop: '-26px',
}}
/>
)}
</div>
</div>
);
}
default: {
const typeText = col
? `${col.type.toUpperCase()}${col.isPart ? '(分区字段)' : ''}`
: '类型';
const fieldName: any = col ? <ScrollText value={col.key} /> : '字段名称';
return (
<div>
<div className="cell" title={fieldName}>
{fieldName}
</div>
<div className="cell" title={typeText}>
{typeText}
</div>
</div>
);
}
}
};
const renderTableFooter = (targetType?: DATA_SOURCE_ENUM) => {
if (readonly) return '';
let footerContent = null;
switch (targetType) {
case DATA_SOURCE_ENUM.HBASE:
footerContent = (
<div>
<span className="col-plugin" onClick={() => initAddKeyRow(false)}>
+添加字段
</span>
<span
className="col-plugin"
onClick={() => handleOpenBatchModal(false)}
>
+文本模式
</span>
</div>
);
break;
case DATA_SOURCE_ENUM.HDFS: {
footerContent = (
<div>
<span className="col-plugin" onClick={() => initAddKeyRow(false)}>
+添加字段
</span>
<span
className="col-plugin"
onClick={() => handleOpenBatchModal(false)}
>
+文本模式
</span>
</div>
);
break;
}
case DATA_SOURCE_ENUM.FTP: {
footerContent = (
<div>
<span className="col-plugin" onClick={() => initAddKeyRow(false)}>
+添加字段
</span>
<span
className="col-plugin"
onClick={() => handleOpenBatchModal(false)}
>
+文本模式
</span>
</div>
);
break;
}
case DATA_SOURCE_ENUM.S3: {
footerContent = (
<div>
<span className="col-plugin" onClick={() => initAddKeyRow(false)}>
+添加字段
</span>
<span
className="col-plugin"
onClick={() => handleOpenBatchModal(false)}
>
+文本模式
</span>
</div>
);
break;
}
default: {
footerContent = null;
break;
}
}
return footerContent ? (
<div
className="m-col footer absolute"
style={{
top: padding + h * (targetCol.length + 1),
left: W - (padding + w),
width: w,
height: h,
zIndex: 2,
}}
>
{footerContent}
</div>
) : (
''
);
};
return (
<div className="targetRight">
<div className="m-col title absolute" style={colStyle}>
{renderTableRow(targetSrcType)}
</div>
{targetCol.map((col, i) => {
return (
<div
key={`targetRight-${i}`}
className="m-col absolute"
style={{
width: w,
height: h,
top: padding + h * (i + 1),
left: W - (padding + w),
}}
>
{renderTableRow(targetSrcType, col, i)}
</div>
);
})}
{renderTableFooter(targetSrcType)}
</div>
);
};
const renderKeyModal = () => {
const { operation, isReader, visible } = keyModal;
const dataType = isReader ? sourceSrcType : targetSrcType;
let title = '添加HDFS字段';
if (operation === 'add') {
if (dataType === DATA_SOURCE_ENUM.HBASE) {
title = '添加HBase字段';
} else if (dataType === DATA_SOURCE_ENUM.FTP) {
title = '添加FTP字段';
} else if (dataType === DATA_SOURCE_ENUM.S3) {
title = '添加AWS S3字段';
}
} else if (operation === 'edit') {
title = '修改HDFS字段';
if (dataType === DATA_SOURCE_ENUM.HBASE) {
title = '修改HBase字段';
} else if (dataType === DATA_SOURCE_ENUM.FTP) {
title = '添加FTP字段';
} else if (dataType === DATA_SOURCE_ENUM.S3) {
title = '添加AWS S3字段';
} else {
title = '修改字段';
}
}
return (
<KeyModal
title={title}
visible={visible}
keyModal={keyModal}
dataType={dataType}
sourceColumnFamily={families.source}
targetColumnFamily={families.target}
onOk={handleKeyModalSubmit}
onCancel={handleHideKeyModal}
/>
);
};
const renderBatchModal = () => {
let sPlaceholder;
let sDesc;
let tPlaceholder;
let tDesc;
switch (sourceSrcType) {
case DATA_SOURCE_ENUM.FTP:
case DATA_SOURCE_ENUM.HDFS:
case DATA_SOURCE_ENUM.S3: {
sPlaceholder = '0: STRING,\n1: INTEGER,...';
sDesc = 'index: type, index: type';
break;
}
case DATA_SOURCE_ENUM.HBASE: {
sPlaceholder = 'cf1: field1: STRING,\ncf1: field2: INTEGER,...';
sDesc = 'columnFamily: fieldName: type,';
break;
}
default: {
break;
}
}
switch (targetSrcType) {
case DATA_SOURCE_ENUM.FTP:
case DATA_SOURCE_ENUM.HDFS:
case DATA_SOURCE_ENUM.S3: {
tPlaceholder = 'field1: STRING,\nfield2: INTEGER,...';
tDesc = 'fieldName: type, fieldName: type';
break;
}
case DATA_SOURCE_ENUM.HBASE: {
tPlaceholder = 'cf1: field1: STRING,\ncf2: field2: INTEGER,...';
tDesc = 'columnFamily: fieldName: type,';
break;
}
default: {
break;
}
}
return (
<>
<BatchModal
title="批量添加源表字段"
desc={sDesc}
columnFamily={families.source}
sourceType={sourceSrcType}
placeholder={sPlaceholder}
defaultValue={batchModal.defaultValue}
visible={batchModal.visible && batchModal.isReader}
onOk={handleBatchAddSourceFields}
onCancel={handleHideBatchModal}
/>
<BatchModal
title="批量添加目标字段"
desc={tDesc}
columnFamily={families.target}
placeholder={tPlaceholder}
sourceType={targetSrcType}
defaultValue={batchModal.defaultValue}
visible={batchModal.visible && !batchModal.isReader}
onOk={handleBatchAddTargetFields}
onCancel={handleHideBatchModal}
/>
</>
);
};
const getTableCols = () => {
// ES 数据源:
// - tableName 字段取自 indexType,
// - schema 字段取自 index
const ES_DATASOURCE = [DATA_SOURCE_ENUM.ES, DATA_SOURCE_ENUM.ES6, DATA_SOURCE_ENUM.ES7];
const sourceSchema = ES_DATASOURCE.includes(sourceMap.type!)
? sourceMap.index
: sourceMap.schema;
const sourceTable = ES_DATASOURCE.includes(sourceMap.type!)
? sourceMap.indexType
: sourceMap.table;
// Hive,Impala 作为结果表时,需要获取分区字段
const sourceType = sourceMap.type!;
const sourcePart =
+sourceType === DATA_SOURCE_ENUM.HIVE1X ||
+sourceType === DATA_SOURCE_ENUM.HIVE ||
+sourceType === DATA_SOURCE_ENUM.HIVE3X ||
+sourceType === DATA_SOURCE_ENUM.SPARKTHRIFT;
const targetSchema = ES_DATASOURCE.includes(targetMap.type!)
? targetMap.index
: targetMap.schema;
const targetTable = ES_DATASOURCE.includes(targetMap.type!)
? targetMap.indexType
: targetMap.table;
// Hive 作为结果表时,需要获取分区字段
const targetType = targetMap.type!;
const targetPart =
+targetType === DATA_SOURCE_ENUM.HIVE1X ||
+targetType === DATA_SOURCE_ENUM.HIVE ||
+targetType === DATA_SOURCE_ENUM.HIVE3X ||
+targetType === DATA_SOURCE_ENUM.SPARKTHRIFT;
// table 和 schema 至少有一者必存在
if (!sourceTable && !sourceSchema) return;
if (!targetTable && !targetSchema) return;
setLoading(true);
Promise.all([
Api.getOfflineTableColumn({
sourceId: sourceMap.sourceId,
schema: sourceSchema,
tableName: Array.isArray(sourceTable) ? sourceTable[0] : sourceTable,
isIncludePart: sourcePart,
}),
Api.getOfflineTableColumn({
sourceId: targetMap.sourceId,
schema: targetSchema,
tableName: targetTable,
isIncludePart: targetPart,
}),
])
.then((results) => {
if (results.every((res) => res.code === 1)) {
const sourceMapCol = sourceMap.column || [];
const targetMapCol = targetMap.column || [];
// TODO: 暂时无法解决没有连线的自定义列或常量保存的问题
// 取当前选中数据源的表字段和已连线的字段的并集作为 keymap 的数据
// 因为可能存在常量或自定义列不存在在「数据源的表字段」中,需要从已连线的字段中获取
const nextSource: IDataColumnsProps[] = results[0].data;
sourceMapCol.forEach((col) => {
if (!nextSource.find((s) => s.key === col.key)) {
nextSource.push(col);
}
});
// same as source
const nextTarget: IDataColumnsProps[] = results[1].data;
targetMapCol.forEach((col) => {
if (!nextTarget.find((s) => s.key === col.key)) {
nextTarget.push(col);
}
});
setTableCols({ source: nextSource, target: nextTarget });
}
})
.finally(() => {
setLoading(false);
});
};
useEffect(() => {
getTableCols();
}, []);
useEffect(() => {
// 设置step容器大小
setCanvasInfo((f) => ({ ...f, W: getCanvasW() }));
loadColumnFamily();
}, []);
useEffect(() => {
select($canvas.current).selectAll('.dl, .dr, .lines').remove();
dragSvg();
}, [lines, canvasInfo, tableColumns, userColumns]);
useEffect(() => {
onLinesChanged?.(lines);
}, [lines]);
const sourceCol = useMemo(
() => (tableColumns?.source || []).concat(userColumns?.source || []),
[tableColumns, userColumns],
);
const targetCol = useMemo(
() => (tableColumns?.target || []).concat(userColumns?.target || []),
[tableColumns, userColumns],
);
const sourceSrcType = useMemo(() => sourceMap?.type, [sourceMap]);
const targetSrcType = useMemo(() => targetMap?.type, [targetMap]);
const H = useMemo(
() => h * (Math.max(targetCol.length, sourceCol.length) + 1),
[sourceCol.length, targetCol.length],
);
return (
<Resize onResize={handleResize}>
<div className="mx-20px">
<p className="text-xs text-center">
您要配置来源表与目标表的字段映射关系,通过连线将待同步的字段左右相连,也可以通过同行映射、同名映射批量完成映射
{!lines.source.length && (
<a onClick={keymapHelpModal}>如何快速配置字段映射?</a>
)}
</p>
{/* {targetSrcType === DATA_SOURCE_ENUM.HBASE ? (
<Row>
<Col span={21} style={{ textAlign: 'center' }}>
<div
className="m-keymapbox"
style={{
width: W + 200,
height: h - 18,
marginTop: 18,
zIndex: 3,
display: 'inline-block',
}}
>
<div
className="pa"
style={{
left: W - (padding + w) + 100,
}}
>
<span>rowkey</span>:
{isFocus ? (
<Input.TextArea
autoFocus={isFocus}
style={focusSty}
defaultValue={get(targetMap, 'type.rowkey', '')}
placeholder={rowkeyTxt}
onChange={this.debounceRowkeyChange}
onFocus={() => {
this.setState({
isFocus: true,
});
}}
onBlur={this.handleBlurRowkeyCheck}
autoSize={{
minRows: 4,
maxRows: 12,
}}
/>
) : (
<Input
autoFocus={isFocus}
style={focusSty}
defaultValue={get(targetMap, 'type.rowkey', '')}
placeholder={rowkeyTxt}
onChange={this.debounceRowkeyChange}
onFocus={() => {
this.setState({
isFocus: true,
});
}}
onBlur={this.handleBlurRowkeyCheck}
/>
)}
</div>
</div>
</Col>
</Row>
) : null} */}
<Spin spinning={loading}>
<Row gutter={12}>
<Col span={readonly ? 24 : 21} className="text-center">
<div
className="m-keymapbox"
style={{
width: W,
minHeight: H + 20,
}}
>
{renderSource()}
{renderTarget()}
<svg
ref={$canvas}
width={W - 30 > w * 2 ? W - w * 2 + 30 : 0}
height={H}
className="m-keymapcanvas"
style={{ left: w, top: padding }}
>
<defs>
<marker
id="arrow"
markerUnits="strokeWidth"
markerWidth="12"
markerHeight="12"
viewBox="0 0 12 12"
refX="6"
refY="6"
orient="auto"
>
<path
d="M2,3 L9,6 L2,9 L2,6 L2,3"
fill="currentColor"
/>
</marker>
</defs>
<g>
<line
ref={$activeLine}
x1="-10"
y1="-10"
x2="-10"
y2="-10"
stroke="currentColor"
strokeWidth="2"
markerEnd="url(#arrow)"
/>
</g>
</svg>
</div>
</Col>
<Col span={3}>
{!readonly ? (
<div className="m-buttons">
<Button
type={btnTypes.rowMap ? 'primary' : 'default'}
onClick={handleRowMapClick}
>
{btnTypes.rowMap ? '取消同行映射' : '同行映射'}
</Button>
<br />
<Button
disabled={isHdfsType(sourceSrcType)}
type={btnTypes.nameMap ? 'primary' : 'default'}
onClick={handleNameMapClick}
>
{btnTypes.nameMap ? '取消同名映射' : '同名映射'}
</Button>
<br />
{isHdfsType(targetSrcType) ? (
<>
<Button onClick={handleCopySourceCols}>
拷贝源字段
</Button>
<br />
</>
) : (
''
)}
{isHdfsType(sourceSrcType) ? (
<Button onClick={handleCopyTargetCols}>拷贝目标字段</Button>
) : (
''
)}
</div>
) : null}
</Col>
</Row>
</Spin>
{renderKeyModal()}
{renderBatchModal()}
<ConstModal
visible={visibleConst}
onOk={(col) => {
onColsChanged?.(col, OPERATOR_TYPE.ADD, 'source');
setConstVisible(false);
}}
onCancel={() => setConstVisible(false)}
/>
{!readonly && (
<div className="steps-action" style={{ marginTop: 80 }}>
<Space>
<Button onClick={() => onNext?.(false)}>上一步</Button>
<Button type="primary" onClick={handleSubmit}>
下一步
</Button>
</Space>
</div>
)}
</div>
</Resize>
);
}
/**
* 获取step容器的大小,最小为450,其他情况为panel大小的5/6;
*/
function getCanvasW() {
let w = 450;
const canvas = document.querySelector('.dt-datasync-content');
if (canvas) {
const newW = (canvas.getBoundingClientRect().width / 6) * 5;
if (newW > w) w = newW;
}
return w;
}
/**
* 绘制字段旁边的拖拽点
*/
const renderDags = (
container: SVGSVGElement | null,
sourceCol: IDataColumnsProps[],
targetCol: IDataColumnsProps[],
canvasInfo: { w: number; h: number; W: number; padding: number },
) => {
const { w, h, W, padding } = canvasInfo;
select(container)
.append('g')
.attr('class', 'dl')
.selectAll('g')
.data(sourceCol)
.enter()
.append('g')
.attr('class', 'col-dag-l')
.append('circle')
.attr('class', 'dag-circle')
.attr('cx', () => padding)
.attr('cy', (_, i) => h * (i + 1.5))
.attr('r', 5)
.attr('stroke-width', 2)
.attr('stroke', '#fff')
.attr('fill', 'currentColor');
select(container)
.append('g')
.attr('class', 'dr')
.selectAll('g')
.data(targetCol)
.enter()
.append('g')
.attr('class', 'col-dag-r')
.append('circle')
.attr('class', 'dag-circle')
/**
* W-w*2代表绘制区域的宽度
*/
.attr('cx', () => W - w * 2 - padding)
.attr('cy', (_, i) => h * (i + 1.5))
.attr('r', 5)
.attr('stroke-width', 2)
.attr('stroke', '#fff')
.attr('fill', 'currentColor');
};
function renderLines(
container: SVGSVGElement | null,
keymap: { source: IDataColumnsProps[]; target: IDataColumnsProps[] },
canvasInfo: { w: number; h: number; W: number; padding: number },
) {
const { w, h, W, padding } = canvasInfo;
const { source, target } = keymap;
const $dagL = select(container).selectAll<SVGGElement, IDataColumnsProps>('.col-dag-l');
const $dagR = select(container).selectAll<SVGGElement, IDataColumnsProps>('.col-dag-r');
const posArr: {
s: { x: number; y: number };
e: { x: number; y: number };
dl: IDataColumnsProps;
dr: IDataColumnsProps;
}[] = [];
/**
* source中的元素 keyObj 类型:
* if(sourceSrcType === 1, 2, 3) string
* if( === 6) { index, type }
*/
source.forEach((keyObj, ii) => {
$dagL.each((dl, i) => {
let sx: number;
let sy: number;
let ex: number;
let ey: number;
if (isFieldMatch(dl, keyObj)) {
sx = padding;
sy = (i + 1.5) * h;
$dagR.each((dr, j) => {
/**
* target[ii] 类型:
* if(targetSrcType === 1, 2, 3) string
* if( === 6) obj{ key, type }
*/
if (isFieldMatch(dr, target[ii])) {
ex = W - w * 2 - padding;
ey = (j + 1.5) * h;
posArr.push({
s: { x: sx, y: sy },
e: { x: ex, y: ey },
dl: keyObj,
dr: target[ii],
});
}
});
}
});
});
const mapline = select(container)
.append('g')
.attr('class', 'lines')
.selectAll('g')
.data(posArr)
.enter()
.append('g')
.attr('class', 'mapline');
mapline
.append('line')
.attr('x1', (d) => d.s.x)
.attr('y1', (d) => d.s.y)
.attr('x2', (d) => d.e.x)
.attr('y2', (d) => d.e.y)
.attr('stroke', 'currentColor')
.attr('stroke-width', 2)
.attr('marker-end', 'url(#arrow)');
}
function bindEvents(
container: SVGSVGElement | null,
lineContainer: SVGGElement | null,
canvasInfo: { w: number; h: number; W: number; padding: number },
onAddKeys?: (source: IDataColumnsProps, target: IDataColumnsProps) => void,
onDeleteKeys?: (source: IDataColumnsProps, target: IDataColumnsProps) => void,
) {
const { w, h, W, padding } = canvasInfo;
const $line = select(lineContainer);
const $dagL = select(container).selectAll<SVGGElement, IDataColumnsProps>('.col-dag-l');
let isMouseDown = false;
let sourceKeyObj: IDataColumnsProps | undefined;
let targetKeyObj: IDataColumnsProps | undefined;
$dagL.on('mousedown', (d, i) => {
const sx = padding;
const sy = (i + 1.5) * h;
$line.attr('x1', sx).attr('y1', sy).attr('x2', sx).attr('y2', sy);
sourceKeyObj = d;
isMouseDown = true;
});
const $canvas = select(container);
$canvas
.on('mousemove', () => {
if (isMouseDown) {
const xy = mouse($canvas.node()!);
const [ex, ey] = xy;
const threholdX = W - w * 2 - padding * 2;
if (ex < threholdX) {
$line.attr('x2', xy[0]).attr('y2', xy[1]);
} else {
const $y = (Math.floor(ey / h) + 0.5) * h;
const $x = threholdX + padding;
$line.attr('x2', $x).attr('y2', $y);
}
}
})
.on('mouseup', () => {
if (isMouseDown) {
const xy = mouse($canvas.node()!);
const [ex, ey] = xy;
const threholdX = W - w * 2 - padding * 2;
if (ex < threholdX) resetActiveLine(lineContainer);
else {
const tidx = Math.floor(ey / h) - 1;
const $dagR = select(container).selectAll('.col-dag-r');
$dagR.each((d: any, i: any) => {
if (i === tidx) {
targetKeyObj = d;
}
});
}
}
if (sourceKeyObj && targetKeyObj) {
/**
* 存储连线
*/
onAddKeys?.(sourceKeyObj, targetKeyObj);
resetActiveLine(lineContainer);
}
isMouseDown = false;
});
$canvas
.selectAll<
SVGGElement,
{
s: { x: number; y: number };
e: { x: number; y: number };
dl: IDataColumnsProps;
dr: IDataColumnsProps;
}
>('.mapline')
.on('mouseover', (_, i, nodes) => {
select(nodes[i]).select('line').attr('stroke-width', 3).attr('stroke', '#2491F7');
})
.on('mouseout', (_, i, nodes) => {
select(nodes[i]).select('line').attr('stroke-width', 2).attr('stroke', '#2491F7');
})
.on('click', (d) => {
/**
* 删除连线
*/
onDeleteKeys?.(d.dl, d.dr);
});
}
function resetActiveLine(container: SVGGElement | null) {
select(container).attr('x1', -10).attr('y1', -10).attr('x2', -10).attr('y2', -10);
} | the_stack |
export interface HeaderFromValue {
/**
* Name of the header
*/
name: string;
/**
* Value of the header
*/
value: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/syntax-defs.html#headerfromenv
*/
export interface HeaderFromEnv {
/**
* Name of the header
*/
name: string;
/**
* Name of the environment variable which holds the value of the header
*/
value_from_env: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/custom-types.html#objectfield
*/
export interface ObjectField {
/**
* Description of the Input object type
*/
description?: string;
/**
* Name of the Input object type
*/
name: string;
/**
* GraphQL type of the Input object type
*/
type: string;
}
/**
* Type used in exported 'metadata.json' and replace metadata endpoint
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/manage-metadata.html#replace-metadata
*/
export interface HasuraMetadataV2 {
actions?: Action[];
allowlist?: AllowList[];
cron_triggers?: CronTrigger[];
custom_types?: CustomTypes;
functions?: CustomFunction[];
query_collections?: QueryCollectionEntry[];
remote_schemas?: RemoteSchema[];
tables: TableEntry[];
version: number;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/actions.html#args-syntax
*/
export interface Action {
/**
* Comment
*/
comment?: string;
/**
* Definition of the action
*/
definition: ActionDefinition;
/**
* Name of the action
*/
name: string;
/**
* Permissions of the action
*/
permissions?: Permissions;
}
/**
* Definition of the action
*
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/actions.html#actiondefinition
*/
export interface ActionDefinition {
arguments?: InputArgument[];
forward_client_headers?: boolean;
/**
* A String value which supports templating environment variables enclosed in {{ and }}.
* Template example: https://{{ACTION_API_DOMAIN}}/create-user
*/
handler: string;
headers?: Header[];
kind?: string;
output_type?: string;
type?: ActionDefinitionType;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/actions.html#inputargument
*/
export interface InputArgument {
name: string;
type: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/syntax-defs.html#headerfromvalue
*
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/syntax-defs.html#headerfromenv
*/
export interface Header {
/**
* Name of the header
*/
name: string;
/**
* Value of the header
*/
value?: string;
/**
* Name of the environment variable which holds the value of the header
*/
value_from_env?: string;
}
export declare enum ActionDefinitionType {
Mutation = 'mutation',
Query = 'query',
}
/**
* Permissions of the action
*/
export interface Permissions {
role: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/query-collections.html#add-collection-to-allowlist-syntax
*/
export interface AllowList {
/**
* Name of a query collection to be added to the allow-list
*/
collection: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/scheduled-triggers.html#create-cron-trigger
*/
export interface CronTrigger {
/**
* Custom comment.
*/
comment?: string;
/**
* List of headers to be sent with the webhook
*/
headers: Header[];
/**
* Flag to indicate whether a trigger should be included in the metadata. When a cron
* trigger is included in the metadata, the user will be able to export it when the metadata
* of the graphql-engine is exported.
*/
include_in_metadata: boolean;
/**
* Name of the cron trigger
*/
name: string;
/**
* Any JSON payload which will be sent when the webhook is invoked.
*/
payload?: {
[key: string]: any;
};
/**
* Retry configuration if scheduled invocation delivery fails
*/
retry_conf?: RetryConfST;
/**
* Cron expression at which the trigger should be invoked.
*/
schedule: string;
/**
* URL of the webhook
*/
webhook: string;
}
/**
* Retry configuration if scheduled invocation delivery fails
*
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/scheduled-triggers.html#retryconfst
*/
export interface RetryConfST {
/**
* Number of times to retry delivery.
* Default: 0
*/
num_retries?: number;
/**
* Number of seconds to wait between each retry.
* Default: 10
*/
retry_interval_seconds?: number;
/**
* Number of seconds to wait for response before timing out.
* Default: 60
*/
timeout_seconds?: number;
/**
* Number of seconds between scheduled time and actual delivery time that is acceptable. If
* the time difference is more than this, then the event is dropped.
* Default: 21600 (6 hours)
*/
tolerance_seconds?: number;
}
export interface CustomTypes {
enums?: EnumType[];
input_objects?: InputObjectType[];
objects?: ObjectType[];
scalars?: ScalarType[];
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/custom-types.html#enumtype
*/
export interface EnumType {
/**
* Description of the Enum type
*/
description?: string;
/**
* Name of the Enum type
*/
name: string;
/**
* Values of the Enum type
*/
values: EnumValue[];
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/custom-types.html#enumvalue
*/
export interface EnumValue {
/**
* Description of the Enum value
*/
description?: string;
/**
* If set to true, the enum value is marked as deprecated
*/
is_deprecated?: boolean;
/**
* Value of the Enum type
*/
value: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/custom-types.html#inputobjecttype
*/
export interface InputObjectType {
/**
* Description of the Input object type
*/
description?: string;
/**
* Fields of the Input object type
*/
fields: InputObjectField[];
/**
* Name of the Input object type
*/
name: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/custom-types.html#inputobjectfield
*/
export interface InputObjectField {
/**
* Description of the Input object type
*/
description?: string;
/**
* Name of the Input object type
*/
name: string;
/**
* GraphQL type of the Input object type
*/
type: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/custom-types.html#objecttype
*/
export interface ObjectType {
/**
* Description of the Input object type
*/
description?: string;
/**
* Fields of the Input object type
*/
fields: InputObjectField[];
/**
* Name of the Input object type
*/
name: string;
/**
* Relationships of the Object type to tables
*/
relationships?: CustomTypeObjectRelationship[];
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/custom-types.html#objectrelationship
*/
export interface CustomTypeObjectRelationship {
/**
* Mapping of fields of object type to columns of remote table
*/
field_mapping: {
[key: string]: string;
};
/**
* Name of the relationship, shouldn’t conflict with existing field names
*/
name: string;
/**
* The table to which relationship is defined
*/
remote_table: QualifiedTable | string;
/**
* Type of the relationship
*/
type: CustomTypeObjectRelationshipType;
}
export interface QualifiedTable {
name: string;
schema: string;
}
/**
* Type of the relationship
*/
export declare enum CustomTypeObjectRelationshipType {
Array = 'array',
Object = 'object',
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/custom-types.html#scalartype
*/
export interface ScalarType {
/**
* Description of the Scalar type
*/
description?: string;
/**
* Name of the Scalar type
*/
name: string;
}
/**
* A custom SQL function to add to the GraphQL schema with configuration.
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/custom-functions.html#args-syntax
*/
export interface CustomFunction {
/**
* Configuration for the SQL function
*/
configuration?: FunctionConfiguration;
/**
* Name of the SQL function
*/
function: QualifiedFunction | string;
}
/**
* Configuration for the SQL function
*
* Configuration for a CustomFunction
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/custom-functions.html#function-configuration
*/
export interface FunctionConfiguration {
/**
* Function argument which accepts session info JSON
* Currently, only functions which satisfy the following constraints can be exposed over the
* GraphQL API (terminology from Postgres docs):
* - Function behaviour: ONLY `STABLE` or `IMMUTABLE`
* - Return type: MUST be `SETOF <table-name>`
* - Argument modes: ONLY `IN`
*/
session_argument?: string;
}
export interface QualifiedFunction {
name: string;
schema: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/query-collections.html#args-syntax
*/
export interface QueryCollectionEntry {
/**
* Comment
*/
comment?: string;
/**
* List of queries
*/
definition: Definition;
/**
* Name of the query collection
*/
name: string;
}
/**
* List of queries
*/
export interface Definition {
queries: QueryCollection[];
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/syntax-defs.html#collectionquery
*/
export interface QueryCollection {
name: string;
query: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/remote-schemas.html#add-remote-schema
*/
export interface RemoteSchema {
/**
* Comment
*/
comment?: string;
/**
* Name of the remote schema
*/
definition: RemoteSchemaDef;
/**
* Name of the remote schema
*/
name: string;
}
/**
* Name of the remote schema
*
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/syntax-defs.html#remoteschemadef
*/
export interface RemoteSchemaDef {
forward_client_headers?: boolean;
headers?: Header[];
timeout_seconds?: number;
url?: string;
url_from_env?: string;
}
/**
* Representation of a table in metadata, 'tables.yaml' and 'metadata.json'
*/
export interface TableEntry {
array_relationships?: ArrayRelationship[];
computed_fields?: ComputedField[];
/**
* Configuration for the table/view
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/table-view.html#table-config
*/
configuration?: TableConfig;
delete_permissions?: DeletePermissionEntry[];
event_triggers?: EventTrigger[];
insert_permissions?: InsertPermissionEntry[];
is_enum?: boolean;
object_relationships?: ObjectRelationship[];
remote_relationships?: RemoteRelationship[];
select_permissions?: SelectPermissionEntry[];
table: QualifiedTable;
update_permissions?: UpdatePermissionEntry[];
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/relationship.html#create-array-relationship-syntax
*/
export interface ArrayRelationship {
/**
* Comment
*/
comment?: string;
/**
* Name of the new relationship
*/
name: string;
/**
* Use one of the available ways to define an array relationship
*/
using: ArrRelUsing;
}
/**
* Use one of the available ways to define an array relationship
*
* Use one of the available ways to define an object relationship
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/relationship.html#arrrelusing
*/
export interface ArrRelUsing {
/**
* The column with foreign key constraint
*/
foreign_key_constraint_on?: ArrRelUsingFKeyOn;
/**
* Manual mapping of table and columns
*/
manual_configuration?: ArrRelUsingManualMapping;
}
/**
* The column with foreign key constraint
*
* The column with foreign key constraint
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/relationship.html#arrrelusingfkeyon
*/
export interface ArrRelUsingFKeyOn {
column: string;
table: QualifiedTable | string;
}
/**
* Manual mapping of table and columns
*
* Manual mapping of table and columns
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/relationship.html#arrrelusingmanualmapping
*/
export interface ArrRelUsingManualMapping {
/**
* Mapping of columns from current table to remote table
*/
column_mapping: {
[key: string]: string;
};
/**
* The table to which the relationship has to be established
*/
remote_table: QualifiedTable | string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/computed-field.html#args-syntax
*/
export interface ComputedField {
/**
* Comment
*/
comment?: string;
/**
* The computed field definition
*/
definition: ComputedFieldDefinition;
/**
* Name of the new computed field
*/
name: string;
}
/**
* The computed field definition
*
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/computed-field.html#computedfielddefinition
*/
export interface ComputedFieldDefinition {
/**
* The SQL function
*/
function: QualifiedFunction | string;
/**
* Name of the argument which accepts the Hasura session object as a JSON/JSONB value. If
* omitted, the Hasura session object is not passed to the function
*/
session_argument?: string;
/**
* Name of the argument which accepts a table row type. If omitted, the first argument is
* considered a table argument
*/
table_argument?: string;
}
/**
* Configuration for the table/view
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/table-view.html#table-config
*/
export interface TableConfig {
/**
* Customise the column names
*/
custom_column_names?: {
[key: string]: string;
};
/**
* Customise the root fields
*/
custom_root_fields?: CustomRootFields;
}
/**
* Customise the root fields
*
* Customise the root fields
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/table-view.html#custom-root-fields
*/
export interface CustomRootFields {
/**
* Customise the `delete_<table-name>` root field
*/
delete?: string;
/**
* Customise the `delete_<table-name>_by_pk` root field
*/
delete_by_pk?: string;
/**
* Customise the `insert_<table-name>` root field
*/
insert?: string;
/**
* Customise the `insert_<table-name>_one` root field
*/
insert_one?: string;
/**
* Customise the `<table-name>` root field
*/
select?: string;
/**
* Customise the `<table-name>_aggregate` root field
*/
select_aggregate?: string;
/**
* Customise the `<table-name>_by_pk` root field
*/
select_by_pk?: string;
/**
* Customise the `update_<table-name>` root field
*/
update?: string;
/**
* Customise the `update_<table-name>_by_pk` root field
*/
update_by_pk?: string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/permission.html#create-delete-permission-syntax
*/
export interface DeletePermissionEntry {
/**
* Comment
*/
comment?: string;
/**
* The permission definition
*/
permission: DeletePermission;
/**
* Role
*/
role: string;
}
/**
* The permission definition
*
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/permission.html#deletepermission
*/
export interface DeletePermission {
/**
* Only the rows where this precondition holds true are updatable
*/
filter?: {
[key: string]:
| number
| {
[key: string]: any;
}
| string;
};
}
/**
* NOTE: The metadata type doesn't QUITE match the 'create' arguments here
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/event-triggers.html#create-event-trigger
*/
export interface EventTrigger {
/**
* The SQL function
*/
definition: EventTriggerDefinition;
/**
* The SQL function
*/
headers?: Header[];
/**
* Name of the event trigger
*/
name: string;
/**
* The SQL function
*/
retry_conf: RetryConf;
/**
* The SQL function
*/
webhook?: string;
webhook_from_env?: string;
}
/**
* The SQL function
*/
export interface EventTriggerDefinition {
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/event-triggers.html#operationspec
*/
delete?: OperationSpec;
enable_manual: boolean;
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/event-triggers.html#operationspec
*/
insert?: OperationSpec;
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/event-triggers.html#operationspec
*/
update?: OperationSpec;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/event-triggers.html#operationspec
*/
export interface OperationSpec {
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/event-triggers.html#eventtriggercolumns
*/
columns: string[] | Columns;
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/event-triggers.html#eventtriggercolumns
*/
payload?: string[] | Columns;
}
export declare enum Columns {
Empty = '*',
}
/**
* The SQL function
*
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/event-triggers.html#retryconf
*/
export interface RetryConf {
/**
* Number of seconds to wait between each retry.
* Default: 10
*/
interval_sec?: number;
/**
* Number of times to retry delivery.
* Default: 0
*/
num_retries?: number;
/**
* Number of seconds to wait for response before timing out.
* Default: 60
*/
timeout_sec?: number;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/permission.html#args-syntax
*/
export interface InsertPermissionEntry {
/**
* Comment
*/
comment?: string;
/**
* The permission definition
*/
permission: InsertPermission;
/**
* Role
*/
role: string;
}
/**
* The permission definition
*
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/permission.html#insertpermission
*/
export interface InsertPermission {
/**
* When set to true the mutation is accessible only if x-hasura-use-backend-only-permissions
* session variable exists
* and is set to true and request is made with x-hasura-admin-secret set if any auth is
* configured
*/
backend_only?: boolean;
/**
* This expression has to hold true for every new row that is inserted
*/
check?: {
[key: string]:
| number
| {
[key: string]: any;
}
| string;
};
/**
* Can insert into only these columns (or all when '*' is specified)
*/
columns: string[] | Columns;
/**
* Preset values for columns that can be sourced from session variables or static values
*/
set?: {
[key: string]: string;
};
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/relationship.html#args-syntax
*/
export interface ObjectRelationship {
/**
* Comment
*/
comment?: string;
/**
* Name of the new relationship
*/
name: string;
/**
* Use one of the available ways to define an object relationship
*/
using: ObjRelUsing;
}
/**
* Use one of the available ways to define an object relationship
*
* Use one of the available ways to define an object relationship
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/relationship.html#objrelusing
*/
export interface ObjRelUsing {
/**
* The column with foreign key constraint
*/
foreign_key_constraint_on?: string;
/**
* Manual mapping of table and columns
*/
manual_configuration?: ObjRelUsingManualMapping;
}
/**
* Manual mapping of table and columns
*
* Manual mapping of table and columns
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/relationship.html#objrelusingmanualmapping
*/
export interface ObjRelUsingManualMapping {
/**
* Mapping of columns from current table to remote table
*/
column_mapping: {
[key: string]: string;
};
/**
* The table to which the relationship has to be established
*/
remote_table: QualifiedTable | string;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/remote-relationships.html#args-syntax
*/
export interface RemoteRelationship {
/**
* Definition object
*/
definition: RemoteRelationshipDef;
/**
* Name of the remote relationship
*/
name: string;
}
/**
* Definition object
*/
export interface RemoteRelationshipDef {
/**
* Column(s) in the table that is used for joining with remote schema field.
* All join keys in remote_field must appear here.
*/
hasura_fields: string[];
/**
* The schema tree ending at the field in remote schema which needs to be joined with.
*/
remote_field: {
[key: string]: RemoteField;
};
/**
* Name of the remote schema to join with
*/
remote_schema: string;
}
export interface RemoteField {
arguments: {
[key: string]: string;
};
/**
* A recursive tree structure that points to the field in the remote schema that needs to be
* joined with.
* It is recursive because the remote field maybe nested deeply in the remote schema.
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/remote-relationships.html#remotefield
*/
field?: {
[key: string]: RemoteField;
};
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/permission.html#create-select-permission-syntax
*/
export interface SelectPermissionEntry {
/**
* Comment
*/
comment?: string;
/**
* The permission definition
*/
permission: SelectPermission;
/**
* Role
*/
role: string;
}
/**
* The permission definition
*
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/permission.html#selectpermission
*/
export interface SelectPermission {
/**
* Toggle allowing aggregate queries
*/
allow_aggregations?: boolean;
/**
* Only these columns are selectable (or all when '*' is specified)
*/
columns: string[] | Columns;
/**
* Only these computed fields are selectable
*/
computed_fields?: string[];
/**
* Only the rows where this precondition holds true are selectable
*/
filter?: {
[key: string]:
| number
| {
[key: string]: any;
}
| string;
};
/**
* The maximum number of rows that can be returned
*/
limit?: number;
}
/**
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/permission.html#create-update-permission-syntax
*/
export interface UpdatePermissionEntry {
/**
* Comment
*/
comment?: string;
/**
* The permission definition
*/
permission: UpdatePermission;
/**
* Role
*/
role: string;
}
/**
* The permission definition
*
*
* https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/permission.html#updatepermission
*/
export interface UpdatePermission {
/**
* Postcondition which must be satisfied by rows which have been updated
*/
check?: {
[key: string]:
| number
| {
[key: string]: any;
}
| string;
};
/**
* Only these columns are selectable (or all when '*' is specified)
*/
columns: string[] | Columns;
/**
* Only the rows where this precondition holds true are updatable
*/
filter?: {
[key: string]:
| number
| {
[key: string]: any;
}
| string;
};
/**
* Preset values for columns that can be sourced from session variables or static values
*/
set?: {
[key: string]: string;
};
}
export declare class Convert {
static toPGColumn(json: string): string;
static pGColumnToJson(value: string): string;
static toComputedFieldName(json: string): string;
static computedFieldNameToJson(value: string): string;
static toRoleName(json: string): string;
static roleNameToJson(value: string): string;
static toTriggerName(json: string): string;
static triggerNameToJson(value: string): string;
static toRemoteRelationshipName(json: string): string;
static remoteRelationshipNameToJson(value: string): string;
static toRemoteSchemaName(json: string): string;
static remoteSchemaNameToJson(value: string): string;
static toCollectionName(json: string): string;
static collectionNameToJson(value: string): string;
static toGraphQLName(json: string): string;
static graphQLNameToJson(value: string): string;
static toGraphQLType(json: string): string;
static graphQLTypeToJson(value: string): string;
static toRelationshipName(json: string): string;
static relationshipNameToJson(value: string): string;
static toActionName(json: string): string;
static actionNameToJson(value: string): string;
static toWebhookURL(json: string): string;
static webhookURLToJson(value: string): string;
static toTableName(json: string): QualifiedTable | string;
static tableNameToJson(value: QualifiedTable | string): string;
static toQualifiedTable(json: string): QualifiedTable;
static qualifiedTableToJson(value: QualifiedTable): string;
static toTableConfig(json: string): TableConfig;
static tableConfigToJson(value: TableConfig): string;
static toTableEntry(json: string): TableEntry;
static tableEntryToJson(value: TableEntry): string;
static toCustomRootFields(json: string): CustomRootFields;
static customRootFieldsToJson(value: CustomRootFields): string;
static toCustomColumnNames(
json: string
): {
[key: string]: string;
};
static customColumnNamesToJson(value: { [key: string]: string }): string;
static toFunctionName(json: string): QualifiedFunction | string;
static functionNameToJson(value: QualifiedFunction | string): string;
static toQualifiedFunction(json: string): QualifiedFunction;
static qualifiedFunctionToJson(value: QualifiedFunction): string;
static toCustomFunction(json: string): CustomFunction;
static customFunctionToJson(value: CustomFunction): string;
static toFunctionConfiguration(json: string): FunctionConfiguration;
static functionConfigurationToJson(value: FunctionConfiguration): string;
static toObjectRelationship(json: string): ObjectRelationship;
static objectRelationshipToJson(value: ObjectRelationship): string;
static toObjRelUsing(json: string): ObjRelUsing;
static objRelUsingToJson(value: ObjRelUsing): string;
static toObjRelUsingManualMapping(json: string): ObjRelUsingManualMapping;
static objRelUsingManualMappingToJson(
value: ObjRelUsingManualMapping
): string;
static toArrayRelationship(json: string): ArrayRelationship;
static arrayRelationshipToJson(value: ArrayRelationship): string;
static toArrRelUsing(json: string): ArrRelUsing;
static arrRelUsingToJson(value: ArrRelUsing): string;
static toArrRelUsingFKeyOn(json: string): ArrRelUsingFKeyOn;
static arrRelUsingFKeyOnToJson(value: ArrRelUsingFKeyOn): string;
static toArrRelUsingManualMapping(json: string): ArrRelUsingManualMapping;
static arrRelUsingManualMappingToJson(
value: ArrRelUsingManualMapping
): string;
static toColumnPresetsExpression(
json: string
): {
[key: string]: string;
};
static columnPresetsExpressionToJson(value: {
[key: string]: string;
}): string;
static toInsertPermissionEntry(json: string): InsertPermissionEntry;
static insertPermissionEntryToJson(value: InsertPermissionEntry): string;
static toInsertPermission(json: string): InsertPermission;
static insertPermissionToJson(value: InsertPermission): string;
static toSelectPermissionEntry(json: string): SelectPermissionEntry;
static selectPermissionEntryToJson(value: SelectPermissionEntry): string;
static toSelectPermission(json: string): SelectPermission;
static selectPermissionToJson(value: SelectPermission): string;
static toUpdatePermissionEntry(json: string): UpdatePermissionEntry;
static updatePermissionEntryToJson(value: UpdatePermissionEntry): string;
static toUpdatePermission(json: string): UpdatePermission;
static updatePermissionToJson(value: UpdatePermission): string;
static toDeletePermissionEntry(json: string): DeletePermissionEntry;
static deletePermissionEntryToJson(value: DeletePermissionEntry): string;
static toDeletePermission(json: string): DeletePermission;
static deletePermissionToJson(value: DeletePermission): string;
static toComputedField(json: string): ComputedField;
static computedFieldToJson(value: ComputedField): string;
static toComputedFieldDefinition(json: string): ComputedFieldDefinition;
static computedFieldDefinitionToJson(value: ComputedFieldDefinition): string;
static toEventTrigger(json: string): EventTrigger;
static eventTriggerToJson(value: EventTrigger): string;
static toEventTriggerDefinition(json: string): EventTriggerDefinition;
static eventTriggerDefinitionToJson(value: EventTriggerDefinition): string;
static toEventTriggerColumns(json: string): string[] | Columns;
static eventTriggerColumnsToJson(value: string[] | Columns): string;
static toOperationSpec(json: string): OperationSpec;
static operationSpecToJson(value: OperationSpec): string;
static toHeaderFromValue(json: string): HeaderFromValue;
static headerFromValueToJson(value: HeaderFromValue): string;
static toHeaderFromEnv(json: string): HeaderFromEnv;
static headerFromEnvToJson(value: HeaderFromEnv): string;
static toRetryConf(json: string): RetryConf;
static retryConfToJson(value: RetryConf): string;
static toCronTrigger(json: string): CronTrigger;
static cronTriggerToJson(value: CronTrigger): string;
static toRetryConfST(json: string): RetryConfST;
static retryConfSTToJson(value: RetryConfST): string;
static toRemoteSchema(json: string): RemoteSchema;
static remoteSchemaToJson(value: RemoteSchema): string;
static toRemoteSchemaDef(json: string): RemoteSchemaDef;
static remoteSchemaDefToJson(value: RemoteSchemaDef): string;
static toRemoteRelationship(json: string): RemoteRelationship;
static remoteRelationshipToJson(value: RemoteRelationship): string;
static toRemoteRelationshipDef(json: string): RemoteRelationshipDef;
static remoteRelationshipDefToJson(value: RemoteRelationshipDef): string;
static toRemoteField(
json: string
): {
[key: string]: RemoteField;
};
static remoteFieldToJson(value: { [key: string]: RemoteField }): string;
static toInputArguments(
json: string
): {
[key: string]: string;
};
static inputArgumentsToJson(value: { [key: string]: string }): string;
static toQueryCollectionEntry(json: string): QueryCollectionEntry;
static queryCollectionEntryToJson(value: QueryCollectionEntry): string;
static toQueryCollection(json: string): QueryCollection;
static queryCollectionToJson(value: QueryCollection): string;
static toAllowList(json: string): AllowList;
static allowListToJson(value: AllowList): string;
static toCustomTypes(json: string): CustomTypes;
static customTypesToJson(value: CustomTypes): string;
static toInputObjectType(json: string): InputObjectType;
static inputObjectTypeToJson(value: InputObjectType): string;
static toInputObjectField(json: string): InputObjectField;
static inputObjectFieldToJson(value: InputObjectField): string;
static toObjectType(json: string): ObjectType;
static objectTypeToJson(value: ObjectType): string;
static toObjectField(json: string): ObjectField;
static objectFieldToJson(value: ObjectField): string;
static toCustomTypeObjectRelationship(
json: string
): CustomTypeObjectRelationship;
static customTypeObjectRelationshipToJson(
value: CustomTypeObjectRelationship
): string;
static toScalarType(json: string): ScalarType;
static scalarTypeToJson(value: ScalarType): string;
static toEnumType(json: string): EnumType;
static enumTypeToJson(value: EnumType): string;
static toEnumValue(json: string): EnumValue;
static enumValueToJson(value: EnumValue): string;
static toAction(json: string): Action;
static actionToJson(value: Action): string;
static toActionDefinition(json: string): ActionDefinition;
static actionDefinitionToJson(value: ActionDefinition): string;
static toInputArgument(json: string): InputArgument;
static inputArgumentToJson(value: InputArgument): string;
static toHasuraMetadataV2(json: string): HasuraMetadataV2;
static hasuraMetadataV2ToJson(value: HasuraMetadataV2): string;
} | the_stack |
import { ActorDirMode } from '../../game/Actor';
import {WORLD_SCALE, getHtmlColor, SPEED_ADJUSTMENT } from '../../utils/lba';
import { Resource } from '../load';
import { getPalette, getText, getSceneMap } from '..';
import { initHeroFlags, parseStaticFlags } from './scene2';
import { LBA1_ISLAND } from '../../game/scenery/island/data/sceneMapping';
// LBA1 does not have a scene map, so lets fake one
export const parseSceneMapLBA1 = () => {
const map = [];
for (let i = 0; i < 120; i += 1) {
map.push({
isIsland: LBA1_ISLAND.includes(i) ? true : false,
sceneryIndex: i,
libraryIndex: i
});
}
return map;
};
export const parseSceneLBA1 = async (resource: Resource, index) => {
const sceneMap = await getSceneMap();
const buffer = resource.getEntry(index);
const data = new DataView(buffer);
const textBankId = data.getInt8(0);
const sceneData = {
index,
textBankId,
textIndex: (textBankId * 2) + 6,
gameOverScene: data.getInt8(1),
unknown1: data.getUint16(2, true),
unknown2: data.getUint16(4, true),
isOutsideScene: false,
buffer,
actors: [],
palette: null,
texts: null,
...sceneMap[index]
};
const [palette, texts] = await Promise.all([
getPalette(),
getText(sceneData.textIndex),
]);
sceneData.palette = palette;
sceneData.texts = texts;
let offset = 6;
offset = loadAmbience(sceneData, offset);
offset = loadHero(sceneData, offset);
offset = loadActors(sceneData, offset);
offset = loadZones(sceneData, offset);
loadPoints(sceneData, offset);
return sceneData;
};
function loadAmbience(scene, offset) {
const data = new DataView(scene.buffer, offset, offset + 49);
let innerOffset = 0;
scene.ambience = {
lightingAlpha: data.getInt16(innerOffset, true),
lightingBeta: data.getInt16(innerOffset + 2, true),
samples: [],
sampleMinDelay: data.getInt16(innerOffset + 28, true),
sampleMinDelayRnd: data.getInt16(innerOffset + 30, true),
sampleElapsedTime: 0,
musicIndex: data.getInt8(innerOffset + 32),
};
// converting to LBA2 angle values
scene.ambience.lightingAlpha = (scene.ambience.lightingAlpha + 0x100) * 0x1000 / 0x400;
scene.ambience.lightingBeta = (scene.ambience.lightingBeta) * 0x1000 / 0x400;
innerOffset = 4;
for (let i = 0; i < 4; i += 1) {
scene.ambience.samples.push({
ambience: data.getInt16(innerOffset, true),
repeat: data.getInt16(innerOffset + 2, true),
round: data.getInt16(innerOffset + 4, true),
frequency: 0x1000,
volume: 1,
});
innerOffset += 6;
}
return offset + 33;
}
function loadHero(scene, offset) {
const data = new DataView(scene.buffer);
const hero = {
sceneIndex: scene.index,
entityIndex: 0,
bodyIndex: 0,
pos: [
((0x8000 - data.getInt16(offset + 4, true)) + 256) * WORLD_SCALE,
data.getInt16(offset + 2, true) * WORLD_SCALE,
(data.getInt16(offset, true) + 256) * WORLD_SCALE
],
index: 0,
textColor: getHtmlColor(scene.palette, (12 * 16) + 12),
angle: 0,
speed: 30 * SPEED_ADJUSTMENT,
dirMode: ActorDirMode.MANUAL,
flags: initHeroFlags(),
moveScriptSize: 0,
moveScript: null,
lifeScriptSize: 0,
lifeScript: null
};
offset += 6;
hero.moveScriptSize = data.getInt16(offset, true);
offset += 2;
if (hero.moveScriptSize > 0) {
hero.moveScript = new DataView(scene.buffer, offset, hero.moveScriptSize);
}
offset += hero.moveScriptSize;
hero.lifeScriptSize = data.getInt16(offset, true);
offset += 2;
if (hero.lifeScriptSize > 0) {
hero.lifeScript = new DataView(scene.buffer, offset, hero.lifeScriptSize);
}
offset += hero.lifeScriptSize;
scene.actors.push(hero);
return offset;
}
function loadActors(scene, offset) {
const data = new DataView(scene.buffer);
const numActors = data.getInt16(offset, true);
offset += 2;
for (let i = 1; i < numActors; i += 1) {
const actor = {
sceneIndex: scene.index,
index: i,
dirMode: ActorDirMode.NO_MOVE,
flags: null,
entityIndex: -1,
bodyIndex: -1,
animIndex: -1,
spriteIndex: -1,
pos: null,
hitStrength: 0,
extraType: -1,
angle: 0,
speed: 0,
info0: -1,
info1: -1,
info2: -1,
info3: -1,
followActor: -1,
extraAmount: -1,
textColor: null,
spriteAnim3D: null,
spriteSizeHit: -1,
armour: -1,
life: -1,
moveScriptSize: 0,
moveScript: null,
lifeScriptSize: 0,
lifeScript: null
};
const staticFlags = data.getUint16(offset, true);
actor.flags = parseStaticFlags(staticFlags);
offset += 2;
actor.entityIndex = data.getInt16(offset, true);
offset += 2;
actor.bodyIndex = data.getUint8(offset);
offset += 1;
actor.animIndex = data.getInt8(offset);
offset += 1;
actor.spriteIndex = data.getInt16(offset, true);
offset += 2;
actor.pos = [
((0x8000 - data.getInt16(offset + 4, true)) + 256) * WORLD_SCALE,
data.getInt16(offset + 2, true) * WORLD_SCALE,
(data.getInt16(offset, true) + 256) * WORLD_SCALE
];
offset += 6;
actor.hitStrength = data.getInt8(offset);
offset += 1;
actor.extraType = data.getInt16(offset, true);
actor.extraType &= ~1;
offset += 2;
actor.angle = data.getInt16(offset, true);
offset += 2;
actor.speed = data.getInt16(offset, true) * SPEED_ADJUSTMENT;
offset += 2;
actor.dirMode = data.getInt16(offset, true);
offset += 2;
actor.info0 = data.getInt16(offset, true);
offset += 2;
actor.info1 = data.getInt16(offset, true);
offset += 2;
actor.info2 = data.getInt16(offset, true);
offset += 2;
actor.info3 = data.getInt16(offset, true);
if (actor.dirMode === ActorDirMode.FOLLOW ||
actor.dirMode === ActorDirMode.SAME_XZ) {
actor.followActor = actor.info3;
}
offset += 2;
actor.extraAmount = data.getInt8(offset);
offset += 1;
const textColor = data.getInt8(offset);
offset += 1;
actor.textColor = getHtmlColor(scene.palette, (textColor * 16) + 12);
actor.armour = data.getUint8(offset);
offset += 1;
actor.life = data.getUint8(offset);
offset += 1;
actor.moveScriptSize = data.getInt16(offset, true);
offset += 2;
if (actor.moveScriptSize > 0) {
actor.moveScript = new DataView(scene.buffer, offset, actor.moveScriptSize);
}
offset += actor.moveScriptSize;
actor.lifeScriptSize = data.getInt16(offset, true);
offset += 2;
if (actor.lifeScriptSize > 0) {
actor.lifeScript = new DataView(scene.buffer, offset, actor.lifeScriptSize);
}
offset += actor.lifeScriptSize;
scene.actors.push(actor);
}
return offset;
}
function loadZones(scene, offset) {
const data = new DataView(scene.buffer);
scene.zones = [];
const numZones = data.getInt16(offset, true);
offset += 2;
for (let i = 0; i < numZones; i += 1) {
const zone = {
sceneIndex: scene.index,
index: i,
type: 0,
box: {xMin: 0, xMax: 0, yMin: 0, yMax: 0, zMin: 0, zMax: 0},
info0: -1,
info1: -1,
info2: -1,
info3: -1,
info4: -1,
info5: -1,
info6: -1,
info7: -1,
param: -1,
pos: null
};
// xMin and xMax are inverted because x axis is inverted
zone.box.xMax = ((0x8000 - data.getInt16(offset + 4, true)) + 256) * WORLD_SCALE;
zone.box.yMin = data.getInt16(offset + 2, true) * WORLD_SCALE;
zone.box.zMin = (data.getInt16(offset, true) + 256) * WORLD_SCALE;
zone.box.xMin = ((0x8000 - data.getInt16(offset + 10, true)) + 256) * WORLD_SCALE;
zone.box.yMax = data.getInt16(offset + 8, true) * WORLD_SCALE;
zone.box.zMax = (data.getInt16(offset + 6, true) + 256) * WORLD_SCALE;
offset += 12;
zone.type = data.getInt16(offset, true);
zone.param = data.getInt16(offset + 2, true);
zone.info0 = data.getInt16(offset + 4, true);
zone.info1 = data.getInt16(offset + 6, true);
zone.info2 = data.getInt16(offset + 8, true);
zone.info3 = data.getInt16(offset + 10, true);
offset += 12;
// set the ladder like on LBA2
if (zone.type === 6 && !zone.info1) {
zone.info1 = 1;
}
// normalising position
zone.pos = [
zone.box.xMin + ((zone.box.xMax - zone.box.xMin) / 2),
zone.box.yMin + ((zone.box.yMax - zone.box.yMin) / 2),
zone.box.zMin + ((zone.box.zMax - zone.box.zMin) / 2)
];
scene.zones.push(zone);
}
return offset;
}
function loadPoints(scene, offset) {
const data = new DataView(scene.buffer);
scene.points = [];
const numPoints = data.getInt16(offset, true);
offset += 2;
for (let i = 0; i < numPoints; i += 1) {
const point = {
sceneIndex: scene.index,
index: i,
pos: [
((0x8000 - data.getInt16(offset + 4, true)) + 512) * WORLD_SCALE,
data.getInt16(offset + 2, true) * WORLD_SCALE,
data.getInt16(offset, true) * WORLD_SCALE
]
};
offset += 6;
scene.points.push(point);
}
return offset;
} | the_stack |
import React from 'react';
import { render, act } from '@testing-library/react';
import 'jest-styled-components';
import { Grommet, Image, Box, InfiniteScrollProps } from '../..';
import { InfiniteScroll } from '..';
type InfiniteScrollItemType = InfiniteScrollProps['items'] extends (infer U)[]
? U
: never;
const simpleItems = (value: number) =>
Array(value)
.fill(``)
.map((_, i) => `item ${i + 1}`);
const createPageItems = (allChildren: HTMLElement[]) => {
const unfiltered = Array.from(allChildren);
// Removing any children which are serving as refs
return unfiltered.filter((childItem) => childItem.outerHTML.includes('item'));
};
describe('InfiniteScroll', () => {
const items: InfiniteScrollProps['items'] = [];
while (items.length < 4) items.push(items.length);
test('basic', () => {
const { container } = render(
<Grommet>
<InfiniteScroll />
<InfiniteScroll items={items}>
{(
item: InfiniteScrollItemType,
index: number,
ref: React.MutableRefObject<HTMLInputElement>,
) => (
<div ref={ref} key={index}>
{item}
</div>
)}
</InfiniteScroll>
<InfiniteScroll items={items}>
{(item: InfiniteScrollItemType, index: number) => (
<div key={index}>{item}</div>
)}
</InfiniteScroll>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('step', () => {
const { container } = render(
<Grommet>
<InfiniteScroll items={items} step={2}>
{(item: InfiniteScrollItemType, index: number) => (
<div key={index}>{item}</div>
)}
</InfiniteScroll>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('show', () => {
const { container } = render(
<Grommet>
<InfiniteScroll items={items} step={2} show={3}>
{(item: InfiniteScrollItemType, index: number) => (
<div key={index}>{item}</div>
)}
</InfiniteScroll>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('renderMarker', () => {
const { container } = render(
<Grommet>
<InfiniteScroll
items={items}
step={2}
renderMarker={(m) => <div>{m}</div>}
>
{(item: InfiniteScrollItemType, index: number) => (
<div key={index}>{item}</div>
)}
</InfiniteScroll>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('replace', () => {
const { container } = render(
<Grommet>
<InfiniteScroll items={items} step={2} replace>
{(item: InfiniteScrollItemType, index: number) => (
<div key={index}>{item}</div>
)}
</InfiniteScroll>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test(`should render expected items when supplied
assortment of mixed items`, () => {
const lorem = `Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod temporincididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.`;
const mixedItems: InfiniteScrollProps['items'] = [];
// Generate large array of mixed items to test different elements on a page
for (let i = 0; i < 200; i += 1) {
switch (i % 5) {
case 0:
mixedItems.push(<Box>Hello World</Box>);
break;
case 1:
mixedItems.push(`This is a string at index ${i}`);
break;
case 2:
mixedItems.push(
<Image
a11yTitle="Gremlin"
src="https://v2.grommet.io/img/stak-hurrah.svg"
/>,
);
break;
case 3:
switch (i % 4) {
case 0:
mixedItems.push(lorem);
break;
case 1:
mixedItems.push(lorem.slice(140));
break;
case 2:
mixedItems.push(lorem + lorem);
break;
case 3:
mixedItems.push(lorem.slice(i, Math.min(i * 3, lorem.length)));
break;
default:
break;
}
break;
case 4:
mixedItems.push(i * 186282);
break;
default:
break;
}
}
const { container } = render(
<Grommet>
<InfiniteScroll items={mixedItems}>
{(item: InfiniteScrollItemType, index: number) => (
<div key={index}>{item}</div>
)}
</InfiniteScroll>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
});
describe('Number of Items Rendered', () => {
test(`Should render items equal to the length of
step when step < items.length`, () => {
const step = 50;
const { container } = render(
<Grommet>
<InfiniteScroll items={simpleItems(1000)} step={step}>
{(item: InfiniteScrollItemType, index: number) => (
<Box key={index}>{item}</Box>
)}
</InfiniteScroll>
</Grommet>,
);
// @ts-ignore
const pageItems = createPageItems(container.firstChild.children);
const expectedItems = step;
expect(pageItems.length).toEqual(expectedItems);
});
test(`Should render items equal to the length of
step when step = array.length`, () => {
const step = 200;
const { container } = render(
<Grommet>
<InfiniteScroll items={simpleItems(200)} step={step}>
{(item: InfiniteScrollItemType, index: number) => (
<Box key={index}>{item}</Box>
)}
</InfiniteScroll>
</Grommet>,
);
// @ts-ignore
const pageItems = createPageItems(container.firstChild.children);
const expectedItems = step;
expect(pageItems.length).toEqual(expectedItems);
});
test(`Should render items equal to the length of
item array when step > array`, () => {
const numItems = 1000;
const { container } = render(
<Grommet>
<InfiniteScroll items={simpleItems(numItems)} step={1050}>
{(item: InfiniteScrollItemType, index: number) => (
<Box key={index}>{item}</Box>
)}
</InfiniteScroll>
</Grommet>,
);
// @ts-ignore
const pageItems = createPageItems(container.firstChild.children);
const expectedItems = numItems;
expect(pageItems.length).toEqual(expectedItems);
});
test(`Should only contain unique items (i.e no duplicates)`, () => {
const step = 25;
const numItems = 200;
const { container } = render(
<Grommet>
<InfiniteScroll items={simpleItems(numItems)} step={step}>
{(item: InfiniteScrollItemType, index: number) => (
<Box key={index}>{item}</Box>
)}
</InfiniteScroll>
</Grommet>,
);
// @ts-ignore
const pageItems = createPageItems(container.firstChild.children);
const distinctItems = new Set(pageItems);
/* Expected number of items should be at the show value rounded
up to the next step increment/ */
const expectedItems = step;
/* If the number of distinct items is equivalent to the length
of results, then we have unique items. */
expect(distinctItems.size).toEqual(expectedItems);
expect(container.firstChild).toMatchSnapshot();
});
});
describe('show scenarios', () => {
test(`When show, show item should be visible in window`, () => {
jest.useFakeTimers('modern');
// Mock scrollIntoView since JSDOM doesn't do layout.
// https://github.com/jsdom/jsdom/issues/1695#issuecomment-449931788
window.HTMLElement.prototype.scrollIntoView = jest.fn();
const { container } = render(
<Grommet>
<InfiniteScroll items={simpleItems(300)} show={105}>
{(item: InfiniteScrollItemType, index: number) => (
<Box key={index}>{item}</Box>
)}
</InfiniteScroll>
</Grommet>,
);
// advance timers so InfiniteScroll can scroll to show index
act(() => {
jest.advanceTimersByTime(200);
});
// item(104) = 'item 105' because indexing starts at 0.
// Need to modify this next selection to only be concerned with the
// visible window.
// @ts-ignore
const renderedItems = container.firstChild.children.item(104).outerHTML;
expect(renderedItems).toContain('item 105');
});
test(`When show, should only contain unique
items (i.e no duplicates)`, () => {
const step = 25;
const numItems = 200;
const showIndex = 67;
const { container } = render(
<Grommet>
<InfiniteScroll
items={simpleItems(numItems)}
show={showIndex}
step={step}
>
{(item: InfiniteScrollItemType, index: number) => (
<Box key={index}>{item}</Box>
)}
</InfiniteScroll>
</Grommet>,
);
// @ts-ignore
const pageItems = createPageItems(container.firstChild.children);
const distinctItems = new Set(pageItems);
/* Expected number of items should be at the show value rounded
up to the next step increment/ */
const expectedItems = Math.ceil(showIndex / step) * step;
/* If the number of distinct items is equivalent to the length
of results, then we have unique items. */
expect(distinctItems.size).toEqual(expectedItems);
expect(container.firstChild).toMatchSnapshot();
});
test(`should display specified item when show is greater than step`, () => {
const step = 8;
const numItems = 200;
const showIndex = 41;
const { container, getByText } = render(
<Grommet>
<InfiniteScroll
items={simpleItems(numItems)}
show={showIndex}
step={step}
>
{(item: InfiniteScrollItemType, index: number) => (
<Box key={index}>{item}</Box>
)}
</InfiniteScroll>
</Grommet>,
);
// Check to see that expected item exists
const expectedItem = getByText('item 42').innerHTML;
expect(expectedItem).toMatch(simpleItems(numItems)[showIndex]);
// Check to see that we have the total number of items we expect
// @ts-ignore
const pageItems = createPageItems(container.firstChild.children);
/* Expected number of items should be at the show value rounded
up to the next step increment/ */
const expectedItems = Math.ceil(showIndex / step) * step;
expect(pageItems.length).toEqual(expectedItems);
});
test(`should display specified item when show is less than step`, () => {
const step = 30;
const numItems = 200;
const showIndex = 26;
const { container, getByText } = render(
<Grommet>
<InfiniteScroll
items={simpleItems(numItems)}
show={showIndex}
step={step}
>
{(item: InfiniteScrollItemType, index: number) => (
<Box key={index}>{item}</Box>
)}
</InfiniteScroll>
</Grommet>,
);
// Check to see that expected item exists
const expectedItem = getByText('item 27').innerHTML;
expect(expectedItem).toMatch(simpleItems(numItems)[showIndex]);
// Check to see that we have the total number of items we expect
// @ts-ignore
const pageItems = createPageItems(container.firstChild.children);
/* Expected number of items should be at the show value rounded
up to the next step increment/ */
const expectedItems = Math.ceil(showIndex / step) * step;
expect(pageItems.length).toEqual(expectedItems);
});
test(`should display specified item when show is
greater than step and replace is true`, () => {
const step = 18;
const numItems = 200;
const showIndex = 88;
const { container, getByText } = render(
<Grommet>
<InfiniteScroll
items={simpleItems(numItems)}
replace
show={showIndex}
step={step}
>
{(item: InfiniteScrollItemType, index: number) => (
<Box key={index}>{item}</Box>
)}
</InfiniteScroll>
</Grommet>,
);
// Check to see that expected item exists
const expectedItem = getByText('item 89').innerHTML;
expect(expectedItem).toMatch(simpleItems(numItems)[showIndex]);
// Check to see that our replace items have been removed from the DOM.
expect(container.firstChild).not.toContain('item 7');
/* Check to see that we have the total number of items we expect.
* When replace is true, the expected number of items should be less
* than or equal to the step * 2.
*/
/*
* The following needs to be uncommented to for this test to pass.
*/
// const pageItems = createPageItems(container.firstChild.children);
// const expectedItems = step * 2;
// expect(pageItems.length).toBeLessThanOrEqual(expectedItems);
});
test(`should display specified item when show is
less than step and replace is true`, () => {
const step = 30;
const numItems = 200;
const showIndex = 26;
const { container, getByText } = render(
<Grommet>
<InfiniteScroll
items={simpleItems(numItems)}
replace
show={showIndex}
step={step}
>
{(item: InfiniteScrollItemType, index: number) => (
<Box key={index}>{item}</Box>
)}
</InfiniteScroll>
</Grommet>,
);
// Check to see that expected item exists
const expectedItem = getByText('item 27').innerHTML;
expect(expectedItem).toMatch(simpleItems(numItems)[showIndex]);
/* Check to see that we have the total number of items we expect.
* When replace is true, the expected number of items should be less
* than or equal to the step * 2.
*/
// @ts-ignore
const pageItems = createPageItems(container.firstChild.children);
const expectedItems = step * 2;
expect(pageItems.length).toBeLessThanOrEqual(expectedItems);
});
}); | the_stack |
'use strict';
import * as chai from 'chai';
import * as fs from 'fs-extra-promise';
import 'mocha';
import * as path from 'path';
import * as request from 'request';
import { Container } from 'typescript-ioc';
import { SDK } from '../../src/admin/config/sdk';
import { ApiConfig } from '../../src/config/api';
import { Configuration } from '../../src/configuration';
import { generateSecurityToken, getSwaggerHost, getSwaggerUrl } from '../../src/utils/config';
const expect = chai.expect;
// tslint:disable:no-unused-expression
let config: Configuration;
let adminRequest: any;
let adminToken: string;
let configToken: string;
let sdk: SDK = null;
const adminUser = {
email: 'test@mail.com',
login: 'admin',
name: 'Admin user',
password: '123test',
roles: ['admin', 'config']
};
const configUser = {
email: 'test@mail.com',
login: 'config',
name: 'Config user',
password: '123test',
roles: ['config']
};
const simpleUser = {
email: 'test@mail.com',
login: 'simple',
name: 'Simple user',
password: '123test',
roles: [] as Array<string>
};
const getIdFromResponse = (response: any) => {
const location = response.headers['location'];
expect(location).to.exist;
const parts = location ? location.split('/') : [];
return parts.length > 0 ? parts[parts.length - 1] : null;
};
const createUsers = () => {
return Promise.all([sdk.users.addUser(adminUser), sdk.users.addUser(configUser), sdk.users.addUser(simpleUser)]);
};
async function initialize() {
adminRequest = request.defaults({ baseUrl: `http://localhost:${config.gateway.admin.protocol.http.listenPort}` });
sdk = await SDK.initialize({
defaultHost: getSwaggerHost(config.gateway),
swaggerUrl: getSwaggerUrl(config.gateway),
token: generateSecurityToken(config.gateway)
});
await createUsers();
}
describe('Gateway Admin Tasks', () => {
before(async () => {
config = Container.get(Configuration);
if (config.loaded) {
await initialize();
} else {
await new Promise<void>((resolve, reject) => {
config.on('load', () => {
initialize().then(resolve).catch(reject);
});
config.on('error', (err) => {
reject(err);
});
});
}
});
describe('/healthcheck', () => {
it('should return OK', (done) => {
adminRequest.get('/healthcheck', (error: any, response: any, body: any) => {
expect(error).to.not.exist;
expect(response.statusCode).to.equal(200);
expect(body).to.equal('OK');
done();
});
});
});
describe('/users', () => {
it('should reject unauthenticated requests', (done) => {
adminRequest.get('/users/admin', (error: any, response: any, body: any) => {
expect(response.statusCode).to.equal(401);
done();
});
});
it('should be able to sign admin users in', (done) => {
const form = {
'login': 'admin',
'password': '123test'
};
adminRequest.post({
form: form,
url: '/users/authentication'
}, (error: any, response: any, body: any) => {
expect(response.statusCode).to.equal(200);
adminToken = body;
done();
});
});
it('should be able to sign in editor users', (done) => {
const form = {
'login': 'config',
'password': '123test'
};
adminRequest.post({
form: form,
url: '/users/authentication'
}, (error: any, response: any, body: any) => {
expect(response.statusCode).to.equal(200);
configToken = body;
done();
});
});
it('should be able to sign in simple users', (done) => {
const form = {
'login': 'simple',
'password': '123test'
};
adminRequest.post({
form: form,
url: '/users/authentication'
}, (error: any, response: any, body: any) => {
expect(response.statusCode).to.equal(200);
done();
});
});
});
describe('/apis', () => {
const apiMock = {
description: 'API mock',
name: 'apiMock',
path: 'newApi',
proxy: {
target: { host: 'http://test.com' }
},
version: '1.0'
} as ApiConfig;
it('should be able to create a new API', (done) => {
adminRequest.post('/apis', {
body: apiMock,
headers: { 'authorization': `Bearer ${configToken}` },
json: true
}, (error: any, response: any, body: any) => {
expect(error).to.not.exist;
expect(response.statusCode).to.equal(201);
apiMock.id = getIdFromResponse(response);
expect(apiMock.id).to.exist;
done();
});
});
it('should reject unauthenticated request to admin apis', (done) => {
adminRequest.post('/apis', {
body: apiMock, json: true
}, (error: any, response: any, body: any) => {
expect(error).to.not.exist;
expect(response.statusCode).to.equal(401);
done();
});
});
it('should reject an invalid API', (done) => {
adminRequest.post('/apis', {
body: {},
headers: { 'authorization': `Bearer ${configToken}` },
json: true
}, (error: any, response: any, body: any) => {
expect(error).to.not.exist;
expect(response.statusCode).to.equal(403);
done();
});
});
it('should be able to list all APIs', (done) => {
adminRequest.get({
headers: { 'authorization': `Bearer ${configToken}` },
url: '/apis'
}, (error: any, response: any, body: any) => {
expect(error).to.not.exist;
expect(response.statusCode).to.equal(200);
done();
});
});
it('should be able to update an API', (done) => {
apiMock.description = 'Updated api';
adminRequest.put(`/apis/${apiMock.id}`, {
body: apiMock,
headers: { 'authorization': `Bearer ${configToken}` },
json: true
}, (error: any, response: any, body: any) => {
expect(error).to.not.exist;
expect(response.statusCode).to.equal(204);
done();
});
});
it('should be able to get an API', (done) => {
adminRequest.get({
headers: { 'authorization': `Bearer ${configToken}` },
url: `/apis/${apiMock.id}`
}, (error: any, response: any, body: any) => {
expect(error).to.not.exist;
expect(response.statusCode).to.equal(200);
const api = JSON.parse(body);
expect(api.description).to.equal('Updated api');
done();
});
});
it('should be able to delete an API', (done) => {
adminRequest.delete({
headers: { 'authorization': `Bearer ${configToken}` },
url: `/apis/${apiMock.id}`
}, (error: any, response: any, body: any) => {
expect(error).to.not.exist;
expect(response.statusCode).to.equal(204);
done();
});
});
});
describe('/users', () => {
it('should reject requests with low privileges', (done) => {
adminRequest.delete({
headers: { 'authorization': `Bearer ${configToken}` },
url: `/users/simple`
}, (error: any, response: any, body: any) => {
expect(error).to.not.exist;
expect(response.statusCode).to.equal(403);
done();
});
});
it('should be able to add users', (done) => {
const simpleUser2 = {
email: 'test2@mail.com',
login: 'simple2',
name: 'Simple user 2',
password: '123test',
roles: [] as Array<string>
};
adminRequest.post({
body: simpleUser2,
headers: { 'authorization': `Bearer ${adminToken}` },
json: true,
url: `/users`
}, (error: any, response: any, body: any) => {
expect(error).to.not.exist;
expect(response.statusCode).to.equal(201);
done();
});
});
});
describe('users SDK', () => {
it('should be able to change password', () => {
return sdk.users.changeUserPassword(simpleUser.login, 'newPassword');
});
it('should be able to update user properties', async () => {
const updatedUser = Object.assign({}, simpleUser);
updatedUser.name = 'New updated Name';
await sdk.users.updateUser(simpleUser.login, updatedUser);
const user = await sdk.users.getUser(simpleUser.login);
expect(user.name).to.equals('New updated Name');
});
it('should be able to create new user', async () => {
const newUser = Object.assign({}, simpleUser);
newUser.login = simpleUser.login + '_sdk';
await sdk.users.addUser(newUser);
});
it('should be able to remove users', async () => {
await sdk.users.removeUser(simpleUser.login + '_sdk');
});
it('should be able to list users', async () => {
const users = await sdk.users.list({});
const logins = users.map(user => user.login);
expect(logins).to.have.length(4);
expect(logins).to.have.members(['admin', 'config', 'simple', 'simple2']);
});
});
describe('gateway SDK', () => {
it('should be able to set configuration for gateway', async () => {
const newConfig = fs.readJSONSync(path.join(process.cwd(), 'test/data/tree-gateway.json')).gateway;
await sdk.gateway.updateConfig(newConfig);
await timeout(5000); // wait gateway restart after a gateway config change
});
it('should be able to retrieve configuration for gateway', async () => {
const dbConfig = await sdk.gateway.getConfig();
expect(dbConfig.logger.level).to.equals('debug');
});
it('should be able to remove configuration for gateway', async () => {
await sdk.gateway.removeConfig();
await timeout(5000); // wait gateway restart after a gateway config change
});
});
function timeout(ms: number) {
return new Promise<void>(resolve => setTimeout(resolve, ms));
}
}); | the_stack |
import { ChronoGraph } from "../../src/chrono/Graph.js"
declare const StartTest : any
StartTest(t => {
t.it('Should not recalculate nodes outside of affected scope', async t => {
const graph : ChronoGraph = ChronoGraph.new()
const box1 = graph.variable(0)
const box2 = graph.variable(0)
const box1p2 = graph.identifier(function * () {
return (yield box1) + (yield box2)
})
const box3 = graph.variable(1)
const res = graph.identifier(function * () {
return (yield box1p2) + (yield box3)
})
// ----------------
const calculation1Spy = t.spyOn(box1p2, 'calculation')
const calculation2Spy = t.spyOn(res, 'calculation')
graph.commit()
t.is(graph.read(box1p2), 0, "Correct result calculated")
t.is(graph.read(res), 1, "Correct result calculated")
t.expect(calculation1Spy).toHaveBeenCalled(1)
t.expect(calculation2Spy).toHaveBeenCalled(1)
// ----------------
calculation1Spy.reset()
calculation2Spy.reset()
graph.write(box1, 10)
graph.commit()
t.is(graph.read(box1p2), 10, "Correct result calculated")
t.is(graph.read(res), 11, "Correct result calculated")
t.expect(calculation1Spy).toHaveBeenCalled(1)
t.expect(calculation2Spy).toHaveBeenCalled(1)
// ----------------
calculation1Spy.reset()
calculation2Spy.reset()
graph.write(box3, 2)
graph.commit()
t.is(graph.read(box1p2), 10, "Correct result calculated")
t.is(graph.read(res), 12, "Correct result calculated")
t.expect(calculation1Spy).toHaveBeenCalled(0)
t.expect(calculation2Spy).toHaveBeenCalled(1)
})
t.it('Should eliminate unchanged subtrees', async t => {
const graph : ChronoGraph = ChronoGraph.new()
const i1 = graph.variableNamed('i1', 0)
const i2 = graph.variableNamed('i2', 10)
const c1 = graph.identifierNamed('c1', function* () {
return (yield i1) + (yield i2)
})
const c2 = graph.identifierNamed('c2', function* () {
return (yield i1) + (yield c1)
})
const c3 = graph.identifierNamed('c3', function* () {
return (yield c1)
})
const c4 = graph.identifierNamed('c4', function* () {
return (yield c3)
})
const c5 = graph.identifierNamed('c5', function* () {
return (yield c3)
})
const c6 = graph.identifierNamed('c6', function* () {
return (yield c5) + (yield i2)
})
// ----------------
const nodes = [ i1, i2, c1, c2, c3, c4, c5, c6 ]
const spies = nodes.map(identifier => t.spyOn(identifier, 'calculation'))
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 0, 10, 10, 10, 10, 10, 10, 20 ], "Correct result calculated")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 1, 1, 1, 1, 1, 1 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i1, 5)
graph.write(i2, 5)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 5, 5, 10, 15, 10, 10, 10, 15 ], "Correct result calculated")
const expectedCalls = [ 0, 0, 1, 1, 0, 0, 0, 1 ]
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled(expectedCalls[ index ]))
})
t.it('Should determine all potentially changed nodes', async t => {
const graph : ChronoGraph = ChronoGraph.new()
const atom0 = graph.variable(0)
const atom1 = graph.identifier(function * () {
return (yield atom0) + 1
})
const atom2 = graph.identifier(function * () {
return (yield atom1) + 1
})
const atom3 = graph.identifier(function * () {
return (yield atom0) + (yield atom2)
})
graph.commit()
t.is(graph.read(atom2), 2, "Correct result calculated for atom2")
t.is(graph.read(atom3), 2, "Correct result calculated for atom3")
graph.write(atom0, 1)
graph.commit()
t.is(graph.read(atom2), 3, "Correct result calculated for atom2")
t.is(graph.read(atom3), 4, "Correct result calculated for atom3")
})
t.it('Should preserve dependencies from eliminated subtrees #1', async t => {
const graph : ChronoGraph = ChronoGraph.new()
const i1 = graph.variableNamed('i1', 0)
const i2 = graph.variableNamed('i2', 10)
const c1 = graph.identifierNamed('c1', function* () {
return (yield i1) + (yield i2)
})
const c2 = graph.identifierNamed('c2', function* () {
return (yield c1) + 1
})
const c3 = graph.identifierNamed('c3', function* () {
return (yield c1) + 2
})
// ----------------
const nodes = [ i1, i2, c1, c2, c3 ]
const spies = nodes.map(identifier => t.spyOn(identifier, 'calculation'))
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 0, 10, 10, 11, 12 ], "Correct result calculated #1")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 1, 1, 1 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i1, 5)
graph.write(i2, 5)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 5, 5, 10, 11, 12 ], "Correct result calculated #2")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 1, 0, 0 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i1, 3)
graph.write(i2, 7)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 3, 7, 10, 11, 12 ], "Correct result calculated #3")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 1, 0, 0 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i1, 7)
graph.write(i2, 7)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 7, 7, 14, 15, 16 ], "Correct result calculated #4")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 1, 1, 1 ][ index ]))
})
t.it('Should preserve dependencies from eliminated subtrees #2', async t => {
const graph : ChronoGraph = ChronoGraph.new()
const i1 = graph.variableNamed('i1', 0)
const i2 = graph.variableNamed('i2', 10)
const i3 = graph.variableNamed('i3', 20)
const dispatcher = graph.variableNamed('d', i3)
const c1 = graph.identifierNamed('c1', function* () {
return (yield i1) + (yield i2)
})
const c2 = graph.identifierNamed('c2', function* () {
return (yield c1) + 1
})
const c3 = graph.identifierNamed('c3', function* () {
return (yield (yield dispatcher))
})
// ----------------
const nodes = [ i1, i2, i3, c1, c2, c3 ]
const spies = nodes.map(identifier => t.spyOn(identifier, 'calculation'))
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 0, 10, 20, 10, 11, 20 ], "Correct result calculated #1")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 1, 1 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
// the order of writes matters
graph.write(dispatcher, c2)
graph.write(i1, 5)
graph.write(i2, 5)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 5, 5, 20, 10, 11, 11 ], "Correct result calculated #2")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 0, 1 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i1, 7)
graph.write(i2, 7)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 7, 7, 20, 14, 15, 15 ], "Correct result calculated #4")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 1, 1 ][ index ]))
})
t.it('Should preserve dependencies from shadowed entries #1', async t => {
const graph : ChronoGraph = ChronoGraph.new()
const i1 = graph.variableNamed('i1', 1)
const i2 = graph.variableNamed('i2', 2)
const i3 = graph.variableNamed('i3', 3)
const c1 = graph.identifierNamed('c1', function* () {
return (yield i1) + (yield i2)
})
const c2 = graph.identifierNamed('c2', function* () {
return (yield i3) + (yield i2)
})
// ----------------
const nodes = [ i1, i2, i3, c1, c2 ]
const spies = nodes.map(identifier => t.spyOn(identifier, 'calculation'))
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 1, 2, 3, 3, 5 ], "Correct result calculated #1")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 1 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i1, 2)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 2, 2, 3, 4, 5 ], "Correct result calculated #2")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 0 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i2, 3)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 2, 3, 3, 5, 6 ], "Correct result calculated #3")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 1 ][ index ]))
})
t.it('Should preserve dependencies from shadowed entries #2', async t => {
const graph : ChronoGraph = ChronoGraph.new()
const i1 = graph.variableNamed('i1', 1)
const i2 = graph.variableNamed('i2', 2)
const i3 = graph.variableNamed('i3', 3)
const dispatcher = graph.variableNamed('d', i3)
const c1 = graph.identifierNamed('c1', function* () {
return (yield i1) + (yield i2)
})
const c2 = graph.identifierNamed('c2', function* () {
return yield (yield dispatcher)
})
// ----------------
const nodes = [ i1, i2, i3, c1, c2 ]
const spies = nodes.map(identifier => t.spyOn(identifier, 'calculation'))
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 1, 2, 3, 3, 3 ], "Correct result calculated - step 1")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 1 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i1, 2)
graph.write(dispatcher, i2)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 2, 2, 3, 4, 2 ], "Correct result calculated - step 2")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 1 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i1, 3)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 3, 2, 3, 5, 2 ], "Correct result calculated - step 3")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 0 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i2, 3)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 3, 3, 3, 6, 3 ], "Correct result calculated - step 4")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 1 ][ index ]))
})
t.it('Should preserve dependencies from shadowed entries #3', async t => {
const graph : ChronoGraph = ChronoGraph.new()
const i1 = graph.variableNamed('i1', 0)
const i2 = graph.variableNamed('i2', 1)
const c1 = graph.identifierNamed('c1', function* () {
return (yield i1)
})
const c2 = graph.identifierNamed('c2', function* () {
return (yield i2)
})
const c3 = graph.identifierNamed('c3', function* () {
return (yield c1) + (yield c2)
})
// ----------------
const nodes = [ i1, i2, c1, c2, c3 ]
const spies = nodes.map(identifier => t.spyOn(identifier, 'calculation'))
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 0, 1, 0, 1, 1 ], "Correct result calculated - step 1")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 1, 1, 1 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i2, 2)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 0, 2, 0, 2, 2 ], "Correct result calculated - step 2")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 0, 1, 1 ][ index ]))
// ----------------
spies.forEach(spy => spy.reset())
graph.write(i1, 1)
graph.commit()
t.isDeeply(nodes.map(node => graph.read(node)), [ 1, 2, 1, 2, 3 ], "Correct result calculated - step 3")
spies.forEach((spy, index) => t.expect(spy).toHaveBeenCalled([ 0, 0, 1, 0, 1 ][ index ]))
})
}) | the_stack |
import {SecurityException} from '../exception/security_exception';
import * as KeyManager from '../internal/key_manager';
import {PbAesCtrHmacAeadKey, PbAesCtrHmacAeadKeyFormat, PbAesCtrKey, PbAesCtrKeyFormat, PbAesCtrParams, PbHashType, PbHmacKey, PbHmacKeyFormat, PbHmacParams, PbKeyData, PbMessage} from '../internal/proto';
import * as Registry from '../internal/registry';
import {Constructor} from '../internal/util';
import {aesCtrHmacFromRawKeys} from '../subtle/encrypt_then_authenticate';
import * as Random from '../subtle/random';
import * as Validators from '../subtle/validators';
import {Aead} from './internal/aead';
/**
* @final
*/
class AesCtrHmacAeadKeyFactory implements KeyManager.KeyFactory {
private static readonly VERSION: number = 0;
private static readonly MIN_KEY_SIZE: number = 16;
private static readonly MIN_IV_SIZE: number = 12;
private static readonly MAX_IV_SIZE: number = 16;
private static readonly MIN_TAG_SIZE: number = 10;
private static readonly MAX_TAG_SIZE = new Map([
[PbHashType.SHA1, 20], [PbHashType.SHA256, 32], [PbHashType.SHA512, 64]
]);
/**
* @override
*/
newKey(keyFormat: PbMessage|Uint8Array) {
let keyFormatProto: PbAesCtrHmacAeadKeyFormat;
if (keyFormat instanceof Uint8Array) {
try {
keyFormatProto = PbAesCtrHmacAeadKeyFormat.deserializeBinary(keyFormat);
} catch (e) {
throw new SecurityException(
'Could not parse the given Uint8Array as a serialized proto of ' +
AesCtrHmacAeadKeyManager.KEY_TYPE);
}
if (!keyFormatProto || !keyFormatProto.getAesCtrKeyFormat() ||
!keyFormatProto.getHmacKeyFormat()) {
throw new SecurityException(
'Could not parse the given Uint8Array as a serialized proto of ' +
AesCtrHmacAeadKeyManager.KEY_TYPE);
}
} else if (keyFormat instanceof PbAesCtrHmacAeadKeyFormat) {
keyFormatProto = keyFormat;
} else {
throw new SecurityException('Expected AesCtrHmacAeadKeyFormat-proto');
}
const {aesCtrParams, aesCtrKeySize} =
this.validateAesCtrKeyFormat(keyFormatProto.getAesCtrKeyFormat());
const aesCtrKey = (new PbAesCtrKey())
.setVersion(AesCtrHmacAeadKeyFactory.VERSION)
.setParams(aesCtrParams)
.setKeyValue(Random.randBytes(aesCtrKeySize));
const {hmacParams, hmacKeySize} =
this.validateHmacKeyFormat(keyFormatProto.getHmacKeyFormat());
const hmacKey = (new PbHmacKey())
.setVersion(AesCtrHmacAeadKeyFactory.VERSION)
.setParams(hmacParams)
.setKeyValue(Random.randBytes(hmacKeySize));
const aesCtrHmacAeadKey =
(new PbAesCtrHmacAeadKey()).setAesCtrKey(aesCtrKey).setHmacKey(hmacKey);
return aesCtrHmacAeadKey;
}
/**
* @override
*/
newKeyData(serializedKeyFormat: Uint8Array) {
const key = (this.newKey(serializedKeyFormat));
const keyData =
(new PbKeyData())
.setTypeUrl(AesCtrHmacAeadKeyManager.KEY_TYPE)
.setValue(key.serializeBinary())
.setKeyMaterialType(PbKeyData.KeyMaterialType.SYMMETRIC);
return keyData;
}
// helper functions
/**
* Checks the parameters and size of a given keyFormat.
*
*/
validateAesCtrKeyFormat(keyFormat: null|PbAesCtrKeyFormat):
{aesCtrParams: PbAesCtrParams, aesCtrKeySize: number, ivSize: number} {
if (!keyFormat) {
throw new SecurityException(
'Invalid AES CTR HMAC key format: key format undefined');
}
const aesCtrKeySize = keyFormat.getKeySize();
Validators.validateAesKeySize(aesCtrKeySize);
const aesCtrParams = keyFormat.getParams();
if (!aesCtrParams) {
throw new SecurityException(
'Invalid AES CTR HMAC key format: params undefined');
}
const ivSize = aesCtrParams.getIvSize();
if (ivSize < AesCtrHmacAeadKeyFactory.MIN_IV_SIZE ||
ivSize > AesCtrHmacAeadKeyFactory.MAX_IV_SIZE) {
throw new SecurityException(
'Invalid AES CTR HMAC key format: IV size is out of range: ' +
ivSize);
}
return {aesCtrParams, aesCtrKeySize, ivSize};
}
/**
* Checks the parameters and size of a given keyFormat.
*
*/
validateHmacKeyFormat(keyFormat: null|PbHmacKeyFormat): {
hmacParams: PbHmacParams,
hmacKeySize: number,
hashType: string,
tagSize: number,
} {
if (!keyFormat) {
throw new SecurityException(
'Invalid AES CTR HMAC key format: key format undefined');
}
const hmacKeySize = keyFormat.getKeySize();
if (hmacKeySize < AesCtrHmacAeadKeyFactory.MIN_KEY_SIZE) {
throw new SecurityException(
'Invalid AES CTR HMAC key format: HMAC key is too small: ' +
keyFormat.getKeySize());
}
const hmacParams = keyFormat.getParams();
if (!hmacParams) {
throw new SecurityException(
'Invalid AES CTR HMAC key format: params undefined');
}
const tagSize = hmacParams.getTagSize();
if (tagSize < AesCtrHmacAeadKeyFactory.MIN_TAG_SIZE) {
throw new SecurityException(
'Invalid HMAC params: tag size ' + tagSize + ' is too small.');
}
if (!AesCtrHmacAeadKeyFactory.MAX_TAG_SIZE.has(hmacParams.getHash())) {
throw new SecurityException('Unknown hash type.');
} else if (
tagSize >
AesCtrHmacAeadKeyFactory.MAX_TAG_SIZE.get(hmacParams.getHash())!) {
throw new SecurityException(
'Invalid HMAC params: tag size ' + tagSize + ' is out of range.');
}
let hashType: string;
switch (hmacParams.getHash()) {
case PbHashType.SHA1:
hashType = 'SHA-1';
break;
case PbHashType.SHA256:
hashType = 'SHA-256';
break;
case PbHashType.SHA512:
hashType = 'SHA-512';
break;
default:
hashType = 'UNKNOWN HASH';
}
return {hmacParams, hmacKeySize, hashType, tagSize};
}
}
/**
* @final
*/
export class AesCtrHmacAeadKeyManager implements KeyManager.KeyManager<Aead> {
private static readonly SUPPORTED_PRIMITIVE = Aead;
static KEY_TYPE: string =
'type.googleapis.com/google.crypto.tink.AesCtrHmacAeadKey';
private static readonly VERSION: number = 0;
private readonly keyFactory = new AesCtrHmacAeadKeyFactory();
/**
* @override
*/
async getPrimitive(
primitiveType: Constructor<Aead>, key: PbKeyData|PbMessage) {
if (primitiveType != this.getPrimitiveType()) {
throw new SecurityException(
'Requested primitive type which is not ' +
'supported by this key manager.');
}
let deserializedKey: PbAesCtrHmacAeadKey;
if (key instanceof PbKeyData) {
if (!this.doesSupport(key.getTypeUrl())) {
throw new SecurityException(
'Key type ' + key.getTypeUrl() +
' is not supported. This key manager supports ' +
this.getKeyType() + '.');
}
try {
deserializedKey = PbAesCtrHmacAeadKey.deserializeBinary(key.getValue());
} catch (e) {
throw new SecurityException(
'Could not parse the key in key data as a serialized proto of ' +
AesCtrHmacAeadKeyManager.KEY_TYPE);
}
if (deserializedKey === null || deserializedKey === undefined) {
throw new SecurityException(
'Could not parse the key in key data as a serialized proto of ' +
AesCtrHmacAeadKeyManager.KEY_TYPE);
}
} else if (key instanceof PbAesCtrHmacAeadKey) {
deserializedKey = key;
} else {
throw new SecurityException(
'Given key type is not supported. ' +
'This key manager supports ' + this.getKeyType() + '.');
}
const {aesCtrKeyValue, ivSize} =
this.validateAesCtrKey(deserializedKey.getAesCtrKey());
const {hmacKeyValue, hashType, tagSize} =
this.validateHmacKey(deserializedKey.getHmacKey());
return await aesCtrHmacFromRawKeys(
aesCtrKeyValue, ivSize, hashType, hmacKeyValue, tagSize);
}
/**
* @override
*/
doesSupport(keyType: string) {
return keyType === this.getKeyType();
}
/**
* @override
*/
getKeyType() {
return AesCtrHmacAeadKeyManager.KEY_TYPE;
}
/**
* @override
*/
getPrimitiveType() {
return AesCtrHmacAeadKeyManager.SUPPORTED_PRIMITIVE;
}
/**
* @override
*/
getVersion() {
return AesCtrHmacAeadKeyManager.VERSION;
}
/**
* @override
*/
getKeyFactory() {
return this.keyFactory;
}
// helper functions
/**
* Checks the parameters and size of a given AES-CTR key.
*
*/
private validateAesCtrKey(key: null|PbAesCtrKey):
{aesCtrKeyValue: Uint8Array, ivSize: number} {
if (!key) {
throw new SecurityException(
'Invalid AES CTR HMAC key format: key undefined');
}
Validators.validateVersion(key.getVersion(), this.getVersion());
const keyFormat = (new PbAesCtrKeyFormat())
.setParams(key.getParams())
.setKeySize(key.getKeyValue_asU8().length);
const {ivSize} = this.keyFactory.validateAesCtrKeyFormat(keyFormat);
return {aesCtrKeyValue: key.getKeyValue_asU8(), ivSize};
}
/**
* Checks the parameters and size of a given HMAC key.
*
*/
private validateHmacKey(key: null|PbHmacKey):
{hmacKeyValue: Uint8Array, hashType: string, tagSize: number} {
if (!key) {
throw new SecurityException(
'Invalid AES CTR HMAC key format: key undefined');
}
Validators.validateVersion(key.getVersion(), this.getVersion());
const keyFormat = (new PbHmacKeyFormat())
.setParams(key.getParams())
.setKeySize(key.getKeyValue_asU8().length);
const {hashType, tagSize} =
this.keyFactory.validateHmacKeyFormat(keyFormat);
return {hmacKeyValue: key.getKeyValue_asU8(), hashType, tagSize};
}
static register() {
Registry.registerKeyManager(new AesCtrHmacAeadKeyManager());
}
} | the_stack |
import {forEach} from "./Enumeration/Enumerator";
import {areEqual} from "../Compare";
import {ArgumentNullException} from "../Exceptions/ArgumentNullException";
import {InvalidOperationException} from "../Exceptions/InvalidOperationException";
import {DisposableBase} from "../Disposable/DisposableBase";
import {ICollection} from "./ICollection";
import {IEnumerator} from "./Enumeration/IEnumerator";
import {IEnumerateEach} from "./Enumeration/IEnumerateEach";
import {Action, ActionWithIndex, EqualityComparison, PredicateWithIndex} from "../FunctionTypes";
import {IEnumerableOrArray} from "./IEnumerableOrArray";
import {ArrayLikeWritable} from "./Array/ArrayLikeWritable";
import {LinqEnumerable} from "../../System.Linq/Linq";
import {isCommonJS, isNodeJS, isRequireJS} from "../Environment";
import __extendsImport from "../../extends";
//noinspection JSUnusedLocalSymbols
const __extends = __extendsImport;
//noinspection SpellCheckingInspection
const
NAME = "CollectionBase",
CMDC = "Cannot modify a disposed collection.",
CMRO = "Cannot modify a read-only collection.";
const
LINQ_PATH = "../../System.Linq/Linq";
export abstract class CollectionBase<T>
extends DisposableBase implements ICollection<T>, IEnumerateEach<T>
{
protected constructor(
source?:IEnumerableOrArray<T>|IEnumerator<T>,
protected _equalityComparer:EqualityComparison<T> = areEqual)
{
super(NAME);
this._importEntries(source);
this._updateRecursion = 0;
this._modifiedCount = 0;
this._version = 0;
}
protected abstract getCount():number;
get count():number
{
return this.getCount();
}
protected getIsReadOnly():boolean
{
return false;
}
//noinspection JSUnusedGlobalSymbols
get isReadOnly():boolean
{
return this.getIsReadOnly();
}
protected assertModifiable():true|never
{
this.throwIfDisposed(CMDC);
if(this.getIsReadOnly())
throw new InvalidOperationException(CMRO);
return true;
}
protected _version:number; // Provides an easy means of tracking changes and invalidating enumerables.
protected assertVersion(version:number):true|never
{
if(version!==this._version)
throw new InvalidOperationException("Collection was modified.");
return true;
}
/*
* Note: Avoid changing modified count by any means but ++;
* If setting modified count by the result of a closure it may be a negative number or NaN and ruin the pattern.
*/
private _modifiedCount:number;
private _updateRecursion:number;
protected _onModified():void {}
protected _signalModification(increment?:boolean):boolean
{
const _ = this;
if(increment) _._modifiedCount++;
if(_._modifiedCount && !this._updateRecursion)
{
_._modifiedCount = 0;
_._version++;
try
{
_._onModified();
}
catch(ex)
{
// Avoid fatal errors which may have been caused by consumer.
console.error(ex);
}
return true;
}
return false;
}
protected _incrementModified():void { this._modifiedCount++; }
//noinspection JSUnusedGlobalSymbols
get isUpdating():boolean { return this._updateRecursion!=0; }
/**
* Takes a closure that if returning true will propagate an update signal.
* Multiple update operations can be occurring at once or recursively and the onModified signal will only occur once they're done.
* @param closure
* @returns {boolean}
*/
handleUpdate(closure?:() => boolean):boolean
{
if(!closure) return false;
const _ = this;
_.assertModifiable();
_._updateRecursion++;
let updated:boolean = false;
try
{
if(updated = closure())
_._modifiedCount++;
}
finally
{
_._updateRecursion--;
}
_._signalModification();
return updated;
}
protected abstract _addInternal(entry:T):boolean;
/*
* Note: for a slight amount more code, we avoid creating functions/closures.
* Calling handleUpdate is the correct pattern, but if possible avoid creating another function scope.
*/
/**
* Adds an entry to the collection.
* @param entry
*/
add(entry:T):this
{
const _ = this;
_.assertModifiable();
_._updateRecursion++;
try
{ if(_._addInternal(entry)) _._modifiedCount++; }
finally
{ _._updateRecursion--; }
_._signalModification();
return _;
}
protected abstract _removeInternal(entry:T, max?:number):number;
/**
* Removes entries from the collection allowing for a limit.
* For example if the collection not a distinct set, more than one entry could be removed.
* @param entry The entry to remove.
* @param max Limit of entries to remove. Will remove all matches if no max specified.
* @returns {number} The number of entries removed.
*/
remove(entry:T, max:number = Infinity):number
{
const _ = this;
_.assertModifiable();
_._updateRecursion++;
let n:number = NaN;
try
{ if(n = _._removeInternal(entry, max)) _._modifiedCount++; }
finally
{ _._updateRecursion--; }
_._signalModification();
return n;
}
protected abstract _clearInternal():number;
/**
* Clears the contents of the collection resulting in a count of zero.
* @returns {number}
*/
clear():number
{
const _ = this;
_.assertModifiable();
_._updateRecursion++;
let n:number = NaN;
try
{ if(n = _._clearInternal()) _._modifiedCount++; }
finally
{ _._updateRecursion--; }
_._signalModification();
return n;
}
protected _onDispose():void
{
super._onDispose();
this._clearInternal();
this._version = 0;
this._updateRecursion = 0;
this._modifiedCount = 0;
const l = this._linq;
this._linq = void 0;
if(l) l.dispose();
}
protected _importEntries(entries:IEnumerableOrArray<T>|IEnumerator<T>|null|undefined):number
{
let added = 0;
if(entries)
{
if((entries) instanceof (Array))
{
// Optimize for avoiding a new closure.
for(let e of entries)
{
if(this._addInternal(e)) added++;
}
}
else
{
forEach(entries, e =>
{
if(this._addInternal(e)) added++;
});
}
}
return added;
}
/**
* Safely imports any array enumerator, or enumerable.
* @param entries
* @returns {number}
*/
importEntries(entries:IEnumerableOrArray<T>|IEnumerator<T>):number
{
const _ = this;
if(!entries) return 0;
_.assertModifiable();
_._updateRecursion++;
let n:number = NaN;
try
{ if(n = _._importEntries(entries)) _._modifiedCount++; }
finally
{ _._updateRecursion--; }
_._signalModification();
return n;
}
// Fundamentally the most important part of the collection.
/**
* Returns a enumerator for this collection.
*/
abstract getEnumerator():IEnumerator<T>;
/**
* Returns an array filtered by the provided predicate.
* Provided for similarity to JS Array.
* @param predicate
* @returns {[]}
*/
filter(predicate:PredicateWithIndex<T>):T[]
{
if(!predicate) throw new ArgumentNullException('predicate');
let count = !this.getCount();
let result:T[] = [];
if(count)
{
this.forEach((e, i) =>
{
if(predicate(e, i))
result.push(e);
});
}
return result;
}
/**
* Returns true the first time predicate returns true. Otherwise false.
* Useful for searching through a collection.
* @param predicate
* @returns {any}
*/
any(predicate?:PredicateWithIndex<T>):boolean
{
let count = this.getCount();
if(!count) return false;
if(!predicate) return Boolean(count);
let found:boolean = false;
this.forEach((e, i) => !(found = predicate(e, i)));
return found;
}
/**
* Returns true the first time predicate returns true. Otherwise false.
* See '.any(predicate)'. As this method is just just included to have similarity with a JS Array.
* @param predicate
* @returns {any}
*/
some(predicate?:PredicateWithIndex<T>):boolean
{
return this.any(predicate);
}
/**
* Returns true if the equality comparer resolves true on any element in the collection.
* @param entry
* @returns {boolean}
*/
contains(entry:T):boolean
{
const equals = this._equalityComparer;
return this.any(e => equals(entry, e));
}
/**
* Special implementation of 'forEach': If the action returns 'false' the enumeration will stop.
* @param action
* @param useCopy
*/
forEach(action:ActionWithIndex<T>, useCopy?:boolean):number
forEach(action:PredicateWithIndex<T>, useCopy?:boolean):number
forEach(action:ActionWithIndex<T> | PredicateWithIndex<T>, useCopy?:boolean):number
{
if(this.wasDisposed)
return 0;
if(useCopy)
{
const a = this.toArray();
try
{
return forEach(a, action);
}
finally
{
a.length = 0;
}
}
else
{
return forEach(this.getEnumerator(), action);
}
}
/**
* Copies all values to numerically indexable object.
* @param target
* @param index
* @returns {TTarget}
*/
copyTo<TTarget extends ArrayLikeWritable<T>>(
target:TTarget,
index:number = 0):TTarget
{
if(!target) throw new ArgumentNullException('target');
const count = this.getCount();
if(count)
{
const newLength = count + index;
if(target.length<newLength) target.length = newLength;
const e = this.getEnumerator();
while(e.moveNext()) // Disposes when finished.
{
target[index++] = <any>e.current;
}
}
return target;
}
/**
* Returns an array of the collection contents.
* @returns {any[]|Array}
*/
toArray():T[]
{
const count = this.getCount();
return count
? this.copyTo(count>65536 ? new Array<T>(count) : [])
: [];
}
private _linq?:LinqEnumerable<T>;
/**
* .linq will return an LinqEnumerable if .linqAsync() has completed successfully or the default module loader is NodeJS+CommonJS.
* @returns {LinqEnumerable}
*/
get linq():LinqEnumerable<T>
{
this.throwIfDisposed();
let e = this._linq;
if(!e)
{
let r:any;
try { r = eval('require'); } catch (ex) {}
this._linq = e = r && r(LINQ_PATH).default.from(this);
if(!e)
{
throw isRequireJS
? `using .linq to load and initialize a LinqEnumerable is currently only supported within a NodeJS environment.
Import System.Linq/Linq and use Enumerable.from(e) instead.
You can also preload the Linq module as a dependency or use .linqAsync(callback) for AMD/RequireJS.`
: "There was a problem importing System.Linq/Linq"
}
}
return e;
}
/**
* .linqAsync() is for use with deferred loading.
* Ensures an instance of the Linq extensions is available and then passes it to the callback.
* Returns an LinqEnumerable if one is already available, otherwise undefined.
* Passing no parameters will still initiate loading and initializing the LinqEnumerable which can be useful for pre-loading.
* Any call to .linqAsync() where an LinqEnumerable is returned can be assured that any subsequent calls to .linq will return the same instance.
* @param callback
* @returns {LinqEnumerable}
*/
linqAsync(callback?:Action<LinqEnumerable<T>>):LinqEnumerable<T>|undefined
{
this.throwIfDisposed();
let e = this._linq;
if(!e)
{
if(isRequireJS)
{
eval("require")([LINQ_PATH], (linq:any) =>
{
// Could end up being called more than once, be sure to check for ._linq before setting...
e = this._linq;
if(!e) this._linq = e = linq.default.from(this);
if(!e) throw "There was a problem importing System.Linq/Linq";
if(callback) callback(e);
callback = void 0; // In case this is return synchronously..
});
}
else if(isNodeJS && isCommonJS)
{
e = this.linq;
}
else
{
throw "Cannot find a compatible loader for importing System.Linq/Linq";
}
}
if(e && callback) callback(e);
return e;
}
} | the_stack |
import { UnitRecord } from '../DayFunctions';
import { Functions as fn } from '../Functions';
import { Locale, Locales } from '../Locale';
// tslint:disable: no-magic-numbers
const unitToWordSingular: UnitRecord<string> = {
millis: 'Millisekunde',
second: 'Sekunde',
minute: 'Minute',
hour: 'Stunde',
day: 'Tag',
week: 'Woche',
month: 'Monat',
quarter: 'Quartal',
year: 'Jahr'
};
const unitToWordPlural: UnitRecord<string> = {
millis: 'Millisekunden',
second: 'Sekunden',
minute: 'Minuten',
hour: 'Stunden',
day: 'Tage',
week: 'Wochen',
month: 'Monate',
quarter: 'Viertel',
year: 'Jahre'
};
const de: Locale =
{
weekStartsOn: 1,
firstWeekContainsDate: 4,
suffix: (value: number) => value + '.',
am: '',
pm: '',
formatLT: 'HH:mm',
formatLTS: 'HH:mm:ss',
formatL: 'DD.MM.Y',
formatl: 'D.M.Y',
formatLL: 'D. MMMM Y',
formatll: 'D. MMM Y',
formatLLL: 'D. MMMM Y HH:mm',
formatlll: 'D. MMM Y HH:mm',
formatLLLL: 'dddd, D. MMMM Y HH:mm',
formatllll: 'ddd, D. MMM Y HH:mm',
identifierTime: (short) => short ? 'lll' : 'LLL',
identifierDay: (short) => short ? 'll' : 'LL',
identifierWeek: (short) => 'wo [Woche in] Y',
identifierMonth: (short) => short ? 'MMM Y' : 'MMMM Y',
identifierQuarter: (short) => 'Qo [Quartal] Y',
identifierYear: (short) => 'Y',
patternNone: () => `Nicht wiederholend`,
patternDaily: () => `Täglich`,
patternWeekly: (day) => `Wöchentlich am ${de.weekdays[0][day.day]}`,
patternMonthlyWeek: (day) => `Monatlich am ${day.weekspanOfMonth + 1}. ${de.weekdays[0][day.day]}`,
patternAnnually: (day) => `Jährlich am ${day.dayOfMonth}. ${de.months[0][day.month]}`,
patternAnnuallyMonthWeek: (day) => `Jährlich am ${day.weekspanOfMonth + 1}. ${de.weekdays[0][day.day]} im ${de.months[0][day.month]}`,
patternWeekday: () => 'Jeden Werktag (Montag bis Freitag)',
patternMonthly: (day) => `Monatlich am ${day.dayOfMonth}. Tag`,
patternLastDay: () => `Am letzten Tag im Monat`,
patternLastDayOfMonth: (day) => `Am letzten Tag im ${de.months[0][day.month]}`,
patternLastWeekday: (day) => `Am letzten ${de.weekdays[0][day.day]} im ${de.months[0][day.month]}`,
patternCustom: () => `Benutzerdefiniert...`,
scheduleStartingOn: (start) => `Startend am ${fn.padNumber(start.dayOfMonth, 2)}. ${de.months[0][start.month]} ${start.year}`,
scheduleEndingOn: (end) => `und endend am ${fn.padNumber(end.dayOfMonth, 2)}. ${de.months[0][end.month]} ${end.year}`,
scheduleEndsOn: (end) => `Bis zum ${fn.padNumber(end.dayOfMonth, 2)}. ${de.months[0][end.month]} ${end.year}`,
scheduleThing: (thing, start) => start
? 'Wird das ' + thing + ' stattfinden'
: ' wird das ' + thing + ' stattfinden',
scheduleAtTimes: ' um ',
scheduleDuration: (duration, unit) => ' mit einer Dauer von ' + duration + ' ' + (unit ? (duration !== 1 ? unitToWordPlural[unit] : unitToWordSingular[unit]) + ' ' : ''),
scheduleExcludes: ' mit Ausnahme vom ',
scheduleIncludes: ' mit Einnahme vom ',
scheduleCancels: ' mit einer Aussetzung am ',
ruleDayOfWeek: {
// jeden 2nd Tag der Woche
every: (every) => `jeden ${de.suffix(every)} Tag der Woche`,
// startend am the 5th Tag der Woche
offset: (offset) => `startend am the ${de.suffix(offset)} Tag der Woche`,
// am 1st, 2nd, and 4th Tag der Woche
oneOf: (values) => `am ${de.list(values.map(de.suffix))} Tag der Woche`
},
ruleLastDayOfMonth: {
// jeden 3rd letzten Tag des Monats
every: (every) => `jeden ${de.suffix(every)} letzten Tag des Monats`,
// startend am the 2nd letzten Tag des Monats
offset: (offset) => `startend am the ${de.suffix(offset)} letzten Tag des Monats`,
// am 1st, 2nd, and 3rd letzten Tag des Monats
oneOf: (values) => `am ${de.list(values.map(de.suffix))} letzten Tag des Monats`
},
ruleDayOfMonth: {
// jeden 3rd Tag des Monats
every: (every) => `jeden ${de.suffix(every)} Tag des Monats`,
// startend am the 2nd Tag des Monats
offset: (offset) => `startend am the ${de.suffix(offset)} Tag des Monats`,
// am 1st, 2nd, and 3rd Tag des Monats
oneOf: (values) => `am ${de.list(values.map(de.suffix))} Tag des Monats`
},
ruleDayOfYear: {
// jeden 3rd Tag des Jahres
every: (every) => `jeden ${de.suffix(every)} Tag des Jahres`,
// startend am the 2nd Tag des Jahres
offset: (offset) => `startend am the ${de.suffix(offset + 1)} Tag des Jahres`,
// am 1st, 2nd, and 3rd Tag des Jahres
oneOf: (values) => `am ${de.list(values.map(de.suffix))} Tag des Jahres`
},
ruleYear: {
// jeden 3rd year
every: (every) => `jeden ${de.suffix(every)} Jahr`,
// startend in 2018
offset: (offset) => `startend in ${offset}`,
// in 2019, 2020, and 2021
oneOf: (values) => `in ${de.list(values.map(x => x.toString()))}`
},
ruleMonth: {
// jeden 3rd month
every: (every) => `jeden ${de.suffix(every)} Monat`,
// startend in Februar
offset: (offset) => `startend in ${de.months[0][offset]}`,
// in Februar, Mai, and Juni
oneOf: (values) => `in ${de.list(values.map(x => de.months[0][x]))}`
},
ruleDay: {
// jeden 2nd Tag der Woche
every: (every) => `jeden ${de.suffix(every)} Tag der Woche`,
// startend am Tuesday
offset: (offset) => `startend am ${de.weekdays[0][offset]}`,
// on Monday, Wednesday, and Friday
oneOf: (values) => `on ${de.list(values.map(v => de.weekdays[0][v]))}`
},
ruleWeek: {
// jeden 3rd Woche des Jahres
every: (every) => `jeden ${de.suffix(every)} Woche des Jahres`,
// startend am the 2nd Woche des Jahres
offset: (offset) => `startend am the ${de.suffix(offset)} Woche des Jahres`,
// am 1st, 2nd, and 3rd Woche des Jahres
oneOf: (values) => `am ${de.list(values.map(de.suffix))} Woche des Jahres`
},
ruleWeekOfYear: {
// jeden 3rd Woche des Jahres
every: (every) => `jeden ${de.suffix(every)} Woche des Jahres`,
// startend am the 2nd Woche des Jahres
offset: (offset) => `startend am the ${de.suffix(offset)} Woche des Jahres`,
// am 1st, 2nd, and 3rd Woche des Jahres
oneOf: (values) => `am ${de.list(values.map(de.suffix))} Woche des Jahres`
},
ruleWeekspanOfYear: {
// jeden 3rd Wochenspanne des Jahres
every: (every) => `jeden ${de.suffix(every + 1)} Wochenspanne des Jahres`,
// startend am the 2nd Wochenspanne des Jahres
offset: (offset) => `startend am the ${de.suffix(offset + 1)} Wochenspanne des Jahres`,
// am 1st, 2nd, and 3rd Wochenspanne des Jahres
oneOf: (values) => `am ${de.list(values.map(x => de.suffix(x + 1)))} Wochenspanne des Jahres`
},
ruleFullWeekOfYear: {
// jeden 3rd vollen Woche des Jahres
every: (every) => `jeden ${de.suffix(every)} vollen Woche des Jahres`,
// startend am the 2nd vollen Woche des Jahres
offset: (offset) => `startend am the ${de.suffix(offset)} vollen Woche des Jahres`,
// am 1st, 2nd, and 3rd vollen Woche des Jahres
oneOf: (values) => `am ${de.list(values.map(de.suffix))} vollen Woche des Jahres`
},
ruleLastWeekspanOfYear: {
// jeden 3rd last Wochenspanne des Jahres
every: (every) => `jeden ${de.suffix(every + 1)} last Wochenspanne des Jahres`,
// startend am the 2nd last Wochenspanne des Jahres
offset: (offset) => `startend am the ${de.suffix(offset + 1)} last Wochenspanne des Jahres`,
// am 1st, 2nd, and 3rd last Wochenspanne des Jahres
oneOf: (values) => `am ${de.list(values.map(x => de.suffix(x + 1)))} last Wochenspanne des Jahres`
},
ruleLastFullWeekOfYear: {
// jeden 3rd letzte volle Woche des Jahres
every: (every) => `jeden ${de.suffix(every)} letzte volle Woche des Jahres`,
// startend am the 2nd letzte volle Woche des Jahres
offset: (offset) => `startend am the ${de.suffix(offset)} letzte volle Woche des Jahres`,
// am 1st, 2nd, and 3rd letzte volle Woche des Jahres
oneOf: (values) => `am ${de.list(values.map(de.suffix))} letzte volle Woche des Jahres`
},
ruleWeekOfMonth: {
// jeden 3rd week des Monats
every: (every) => `jeden ${de.suffix(every)} Woche des Monats`,
// startend am the 2nd week des Monats
offset: (offset) => `startend am the ${de.suffix(offset)} Woche des Monats`,
// am 1st, 2nd, and 3rd week des Monats
oneOf: (values) => `am ${de.list(values.map(de.suffix))} Woche des Monats`
},
ruleFullWeekOfMonth: {
// jeden 3rd vollen Woche des Monats
every: (every) => `jeden ${de.suffix(every)} vollen Woche des Monats`,
// startend am the 2nd vollen Woche des Monats
offset: (offset) => `startend am the ${de.suffix(offset)} vollen Woche des Monats`,
// am 1st, 2nd, and 3rd vollen Woche des Monats
oneOf: (values) => `am ${de.list(values.map(de.suffix))} vollen Woche des Monats`
},
ruleWeekspanOfMonth: {
// jeden 3rd weekspan des Monats
every: (every) => `jeden ${de.suffix(every + 1)} Wochenspanne des Monats`,
// startend am the 2nd weekspan des Monats
offset: (offset) => `startend am the ${de.suffix(offset + 1)} Wochenspanne des Monats`,
// am 1st, 2nd, and 3rd weekspan des Monats
oneOf: (values) => `am ${de.list(values.map(x => de.suffix(x + 1)))} Wochenspanne des Monats`
},
ruleLastFullWeekOfMonth: {
// jeden 3rd letzte volle week des Monats
every: (every) => `jeden ${de.suffix(every)} letzte volle week des Monats`,
// startend am the 2nd letzte volle week des Monats
offset: (offset) => `startend am the ${de.suffix(offset)} letzte volle week des Monats`,
// am 1st, 2nd, and 3rd vollen Woche des Monats
oneOf: (values) => `am ${de.list(values.map(de.suffix))} letzte volle week des Monats`
},
ruleLastWeekspanOfMonth: {
// jeden 3rd letzten Wochenspanne des Monats
every: (every) => `jeden ${de.suffix(every + 1)} letzten Wochenspanne des Monats`,
// startend am the 2nd letzten Wochenspanne des Monats
offset: (offset) => `startend am the ${de.suffix(offset + 1)} letzten Wochenspanne des Monats`,
// am 1st, 2nd, and 3rd letzten Wochenspanne des Monats
oneOf: (values) => `am ${de.list(values.map(x => de.suffix(x + 1)))} letzten Wochenspanne des Monats`
},
summaryDay: (short, dayOfWeek, year) => (dayOfWeek ? (short ? 'ddd, ' : 'dddd, ') : '') + (short ? 'MMM ' : 'MMMM ') + 'Do' + (year ? ' Y' : ''),
summaryWeek: (short, dayOfWeek, year) => (dayOfWeek ? (short ? 'ddd, ' : 'dddd, ') : '') + (short ? 'MMM ' : 'MMMM ') + 'Do' + (year ? ' Y' : ''),
summaryMonth: (short, dayOfWeek, year) => (short ? 'MMM' : 'MMMM') + (year ? ' YYYY' : ''),
summaryYear: (short, dayOfWeek, year) => (year ? 'YYYY' : ''),
list: (items) => {
const last: number = items.length - 1;
let out: string = items[0];
for (let i = 1; i < last; i++) {
out += ', ' + items[i];
}
if (last > 0) {
out += ' und ' + items[last];
}
return out;
},
months: [
['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
['Jan', 'Feb', 'Mrz', 'Apr', 'Mai', 'Juni', 'Juli', 'Aug', 'Sept', 'Okt', 'Nov', 'Dez'],
['Jan', 'Feb', 'Mrz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
['J', 'F', 'Mä', 'A', 'Ma', 'Ju', 'Jl', 'Ag', 'S', 'O', 'N', 'D']
],
weekdays: [
['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
],
};
export default de;
Locales.add(['de', 'de-at', 'de-de', 'de-li', 'de-lu', 'de-ch'], de); | the_stack |
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ExcelExportService } from '@slickgrid-universal/excel-export';
import { SlickCompositeEditorComponent } from '@slickgrid-universal/composite-editor-component';
import {
AngularGridInstance,
AutocompleteOption,
Column,
CompositeEditorModalType,
EditCommand,
Editors,
FieldType,
Filters,
formatNumber,
Formatter,
Formatters,
GridOption,
GridStateChange,
LongTextEditorOption,
OnCompositeEditorChangeEventArgs,
SlickGrid,
SlickNamespace,
SortComparers,
} from '../modules/angular-slickgrid';
import './grid-composite-editor.component.scss';
const NB_ITEMS = 500;
const URL_COUNTRIES_COLLECTION = 'assets/data/countries.json';
// using external SlickGrid JS libraries
declare const Slick: SlickNamespace;
/**
* Check if the current item (cell) is editable or not
* @param {*} dataContext - item data context object
* @param {*} columnDef - column definition
* @param {*} grid - slickgrid grid object
* @returns {boolean} isEditable
*/
function checkItemIsEditable(dataContext: any, columnDef: Column, grid: SlickGrid) {
const gridOptions = grid && grid.getOptions && grid.getOptions();
const hasEditor = columnDef.editor;
const isGridEditable = gridOptions.editable;
let isEditable = !!(isGridEditable && hasEditor);
if (dataContext && columnDef && gridOptions && gridOptions.editable) {
switch (columnDef.id) {
case 'finish':
// case 'percentComplete':
isEditable = !!dataContext?.completed;
break;
// case 'completed':
// case 'duration':
// case 'title':
// case 'product':
// case 'origin':
// isEditable = dataContext.percentComplete < 50;
// break;
}
}
return isEditable;
}
const customEditableInputFormatter: Formatter = (_row, _cell, value, columnDef, _dataContext, grid) => {
const gridOptions = grid && grid.getOptions && grid.getOptions();
const isEditableLine = gridOptions.editable && columnDef.editor;
value = (value === null || value === undefined) ? '' : value;
return isEditableLine ? { text: value, addClasses: 'editable-field', toolTip: 'Click to Edit' } : value;
};
// you can create custom validator to pass to an inline editor
const myCustomTitleValidator = (value: any, args: any) => {
if ((value === null || value === undefined || !value.length) && (args.compositeEditorOptions && args.compositeEditorOptions.modalType === 'create' || args.compositeEditorOptions.modalType === 'edit')) {
// we will only check if the field is supplied when it's an inline editing OR a composite editor of type create/edit
return { valid: false, msg: 'This is a required field.' };
} else if (!/^(task\s\d+)*$/i.test(value)) {
return { valid: false, msg: 'Your title is invalid, it must start with "Task" followed by a number.' };
}
return { valid: true, msg: '' };
};
@Component({
templateUrl: './grid-composite-editor.component.html',
styleUrls: ['./grid-composite-editor.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class GridCompositeEditorComponent implements OnInit {
title = 'Example 30: Composite Editor Modal';
subTitle = `Composite Editor allows you to Create, Clone, Edit, Mass Update & Mass Selection Changes inside a nice Modal Window.
<br>The modal is simply populated by looping through your column definition list and also uses a lot of the same logic as inline editing (see <a href="https://github.com/ghiscoding/aurelia-slickgrid/wiki/Composite-Editor-Modal" target="_blank">Composite Editor - Wiki</a>.)`;
angularGrid!: AngularGridInstance;
compositeEditorInstance!: SlickCompositeEditorComponent;
gridOptions!: GridOption;
columnDefinitions: Column[] = [];
dataset: any[] = [];
editQueue: any[] = [];
editedItems: any = {};
isGridEditable = true;
isCompositeDisabled = false;
isMassSelectionDisabled = true;
complexityLevelList = [
{ value: 0, label: 'Very Simple' },
{ value: 1, label: 'Simple' },
{ value: 2, label: 'Straightforward' },
{ value: 3, label: 'Complex' },
{ value: 4, label: 'Very Complex' },
];
constructor(private http: HttpClient) {
this.compositeEditorInstance = new SlickCompositeEditorComponent();
}
angularGridReady(angularGrid: AngularGridInstance) {
this.angularGrid = angularGrid;
}
ngOnInit(): void {
this.prepareGrid();
// mock a dataset
this.dataset = this.loadData(NB_ITEMS);
}
prepareGrid() {
this.columnDefinitions = [
{
id: 'title', name: 'Title', field: 'title', sortable: true, type: FieldType.string, minWidth: 75,
filterable: true, columnGroup: 'Common Factor',
filter: { model: Filters.compoundInputText },
formatter: Formatters.multiple, params: { formatters: [Formatters.uppercase, Formatters.bold] },
editor: {
model: Editors.longText, massUpdate: false, required: true, alwaysSaveOnEnterKey: true,
maxLength: 12,
editorOptions: {
cols: 45,
rows: 6,
buttonTexts: {
cancel: 'Close',
save: 'Done'
}
} as LongTextEditorOption,
validator: myCustomTitleValidator,
},
},
{
id: 'duration', name: 'Duration', field: 'duration', sortable: true, filterable: true, minWidth: 75,
type: FieldType.number, columnGroup: 'Common Factor',
formatter: (_row, _cell, value) => {
if (value === null || value === undefined || value === '') {
return '';
}
return value > 1 ? `${value} days` : `${value} day`;
},
editor: { model: Editors.float, massUpdate: true, decimal: 2, valueStep: 1, minValue: 0, maxValue: 10000, alwaysSaveOnEnterKey: true, required: true },
},
{
id: 'cost', name: 'Cost', field: 'cost', width: 90, minWidth: 70,
sortable: true, filterable: true, type: FieldType.number, columnGroup: 'Analysis',
filter: { model: Filters.compoundInputNumber },
formatter: Formatters.dollar,
},
{
id: 'percentComplete', name: '% Complete', field: 'percentComplete', minWidth: 100,
type: FieldType.number,
sortable: true, filterable: true, columnGroup: 'Analysis',
filter: { model: Filters.compoundSlider, operator: '>=' },
editor: {
model: Editors.slider,
massUpdate: true, minValue: 0, maxValue: 100,
},
},
// {
// id: 'percentComplete2', name: '% Complete', field: 'analysis.percentComplete', minWidth: 100,
// type: FieldType.number,
// sortable: true, filterable: true, columnGroup: 'Analysis',
// // filter: { model: Filters.compoundSlider, operator: '>=' },
// formatter: Formatters.complex,
// exportCustomFormatter: Formatters.complex, // without the Editing cell Formatter
// editor: {
// model: Editors.singleSelect,
// serializeComplexValueFormat: 'flat', // if we keep "object" as the default it will apply { value: 2, label: 2 } which is not what we want in this case
// collection: Array.from(Array(101).keys()).map(k => ({ value: k, label: k })),
// collectionOptions: {
// addCustomFirstEntry: { value: '', label: '--none--' }
// },
// collectionOverride: (_collectionInput, args) => {
// const originalCollection = args.originalCollections || [];
// const duration = args?.dataContext?.duration ?? args?.compositeEditorOptions?.formValues?.duration;
// if (duration === 10) {
// return originalCollection.filter(itemCollection => +itemCollection.value !== 1);
// }
// return originalCollection;
// },
// massUpdate: true, minValue: 0, maxValue: 100,
// },
// },
{
id: 'complexity', name: 'Complexity', field: 'complexity', minWidth: 100,
type: FieldType.number,
sortable: true, filterable: true, columnGroup: 'Analysis',
formatter: (_row, _cell, value) => this.complexityLevelList[value].label,
exportCustomFormatter: (_row, _cell, value) => this.complexityLevelList[value].label,
filter: {
model: Filters.multipleSelect,
collection: this.complexityLevelList
},
editor: {
model: Editors.singleSelect,
collection: this.complexityLevelList,
massUpdate: true
},
},
{
id: 'start', name: 'Start', field: 'start', sortable: true, minWidth: 100,
formatter: Formatters.dateUs, columnGroup: 'Period',
exportCustomFormatter: Formatters.dateUs,
type: FieldType.date, outputType: FieldType.dateUs, saveOutputType: FieldType.dateUtc,
filterable: true, filter: { model: Filters.compoundDate },
editor: { model: Editors.date, massUpdate: true, params: { hideClearButton: false } },
},
{
id: 'completed', name: 'Completed', field: 'completed', width: 80, minWidth: 75, maxWidth: 100,
sortable: true, filterable: true, columnGroup: 'Period',
formatter: Formatters.multiple,
params: { formatters: [Formatters.checkmark, Formatters.center] },
exportWithFormatter: false,
filter: {
collection: [{ value: '', label: '' }, { value: true, label: 'True' }, { value: false, label: 'False' }],
model: Filters.singleSelect
},
editor: { model: Editors.checkbox, massUpdate: true, },
// editor: { model: Editors.singleSelect, collection: [{ value: true, label: 'Yes' }, { value: false, label: 'No' }], },
},
{
id: 'finish', name: 'Finish', field: 'finish', sortable: true, minWidth: 100,
formatter: Formatters.dateUs, columnGroup: 'Period',
type: FieldType.date, outputType: FieldType.dateUs, saveOutputType: FieldType.dateUtc,
filterable: true, filter: { model: Filters.compoundDate },
exportCustomFormatter: Formatters.dateUs,
editor: {
model: Editors.date,
editorOptions: { minDate: 'today' },
massUpdate: true,
validator: (value, args) => {
const dataContext = args && args.item;
if (dataContext && (dataContext.completed && !value)) {
return { valid: false, msg: 'You must provide a "Finish" date when "Completed" is checked.' };
}
return { valid: true, msg: '' };
}
},
},
{
id: 'product', name: 'Product', field: 'product',
filterable: true, columnGroup: 'Item',
minWidth: 100,
exportWithFormatter: true,
dataKey: 'id',
labelKey: 'itemName',
formatter: Formatters.complexObject,
exportCustomFormatter: Formatters.complex, // without the Editing cell Formatter
type: FieldType.object,
sortComparer: SortComparers.objectString,
editor: {
model: Editors.autoComplete,
alwaysSaveOnEnterKey: true,
massUpdate: true,
// example with a Remote API call
editorOptions: {
minLength: 1,
source: (request, response) => {
// const items = require('c://TEMP/items.json');
const products = this.mockProducts();
response(products.filter(product => product.itemName.toLowerCase().includes(request.term.toLowerCase())));
},
renderItem: {
// layout: 'twoRows',
// templateCallback: (item: any) => this.renderItemCallbackWith2Rows(item),
layout: 'fourCorners',
templateCallback: (item: any) => this.renderItemCallbackWith4Corners(item),
},
} as AutocompleteOption,
},
filter: {
model: Filters.inputText,
// placeholder: '🔎︎ search city',
type: FieldType.string,
queryField: 'product.itemName',
}
},
{
id: 'origin', name: 'Country of Origin', field: 'origin',
formatter: Formatters.complexObject, columnGroup: 'Item',
exportCustomFormatter: Formatters.complex, // without the Editing cell Formatter
dataKey: 'code',
labelKey: 'name',
type: FieldType.object,
sortComparer: SortComparers.objectString,
filterable: true,
sortable: true,
minWidth: 100,
editor: {
model: Editors.autoComplete,
massUpdate: true,
customStructure: { label: 'name', value: 'code' },
collectionAsync: this.http.get(URL_COUNTRIES_COLLECTION),
},
filter: {
model: Filters.inputText,
type: 'string',
queryField: 'origin.name',
}
},
{
id: 'action', name: 'Action', field: 'action', width: 70, minWidth: 70, maxWidth: 70,
excludeFromExport: true,
formatter: () => `<div class="button-style margin-auto" style="width: 35px;"><span class="fa fa-chevron-down text-primary"></span></div>`,
cellMenu: {
hideCloseButton: false,
width: 175,
commandTitle: 'Commands',
commandItems: [
{
command: 'edit',
title: 'Edit Row',
iconCssClass: 'fa fa-pencil',
positionOrder: 66,
action: () => this.openCompositeModal('edit'),
},
{
command: 'clone',
title: 'Clone Row',
iconCssClass: 'fa fa-clone',
positionOrder: 66,
action: () => this.openCompositeModal('clone'),
},
'divider',
{
command: 'delete-row', title: 'Delete Row', positionOrder: 64,
iconCssClass: 'fa fa-times color-danger', cssClass: 'red', textCssClass: 'text-italic color-danger-light',
// only show command to 'Delete Row' when the task is not completed
itemVisibilityOverride: (args) => {
return !args.dataContext?.completed;
},
action: (_event, args) => {
const dataContext = args.dataContext;
const row = args?.row ?? 0;
if (confirm(`Do you really want to delete row (${row + 1}) with "${dataContext.title}"`)) {
this.angularGrid.gridService.deleteItemById(dataContext.id);
}
}
},
],
}
},
];
this.gridOptions = {
enableAddRow: true, // <-- this flag is required to work with the (create & clone) modal types
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true,
autoCommitEdit: true,
editable: true,
autoAddCustomEditorFormatter: customEditableInputFormatter,
autoResize: {
container: '#demo-container',
rightPadding: 10
},
enableAutoSizeColumns: true,
enableAutoResize: true,
showCustomFooter: true,
enablePagination: true,
pagination: {
pageSize: 10,
pageSizes: [10, 200, 250, 500, 5000]
},
enableExcelExport: true,
excelExportOptions: {
exportWithFormatter: false
},
registerExternalResources: [new ExcelExportService(), this.compositeEditorInstance],
enableFiltering: true,
rowSelectionOptions: {
// True (Single Selection), False (Multiple Selections)
selectActiveRow: false
},
createPreHeaderPanel: true,
showPreHeaderPanel: true,
preHeaderPanelHeight: 28,
enableCheckboxSelector: true,
enableRowSelection: true,
multiSelect: false,
checkboxSelector: {
hideInFilterHeaderRow: false,
hideInColumnTitleRow: true,
},
enableCompositeEditor: true,
editCommandHandler: (item, column, editCommand) => {
// composite editors values are saved as array, so let's convert to array in any case and we'll loop through these values
const prevSerializedValues = Array.isArray(editCommand.prevSerializedValue) ? editCommand.prevSerializedValue : [editCommand.prevSerializedValue];
const serializedValues = Array.isArray(editCommand.serializedValue) ? editCommand.serializedValue : [editCommand.serializedValue];
const editorColumns = this.columnDefinitions.filter((col) => col.editor !== undefined);
const modifiedColumns: Column[] = [];
prevSerializedValues.forEach((_val, index) => {
const prevSerializedValue = prevSerializedValues[index];
const serializedValue = serializedValues[index];
if (prevSerializedValue !== serializedValue) {
const finalColumn = Array.isArray(editCommand.prevSerializedValue) ? editorColumns[index] : column;
this.editedItems[this.gridOptions.datasetIdPropertyName || 'id'] = item; // keep items by their row indexes, if the row got edited twice then we'll keep only the last change
this.angularGrid.slickGrid.invalidate();
editCommand.execute();
this.renderUnsavedCellStyling(item, finalColumn, editCommand);
modifiedColumns.push(finalColumn);
}
});
// queued editor only keeps 1 item object even when it's a composite editor,
// so we'll push only 1 change at the end but with all columns modified
// this way we can undo the entire row change (for example if user changes 3 field in the editor modal, then doing a undo last change will undo all 3 in 1 shot)
this.editQueue.push({ item, columns: modifiedColumns, editCommand });
},
// when using the cellMenu, you can change some of the default options and all use some of the callback methods
enableCellMenu: true,
};
}
loadData(count: number) {
// mock data
const tmpArray: any[] = [];
for (let i = 0; i < count; i++) {
const randomItemId = Math.floor(Math.random() * this.mockProducts().length);
const randomYear = 2000 + Math.floor(Math.random() * 10);
const randomFinishYear = (new Date().getFullYear()) + Math.floor(Math.random() * 10); // use only years not lower than 3 years ago
const randomMonth = Math.floor(Math.random() * 11);
const randomDay = Math.floor((Math.random() * 29));
const randomTime = Math.floor((Math.random() * 59));
const randomFinish = new Date(randomFinishYear, (randomMonth + 1), randomDay, randomTime, randomTime, randomTime);
const randomPercentComplete = Math.floor(Math.random() * 100) + 15; // make it over 15 for E2E testing purposes
const percentCompletion = randomPercentComplete > 100 ? (i > 5 ? 100 : 88) : randomPercentComplete; // don't use 100 unless it's over index 5, for E2E testing purposes
const isCompleted = percentCompletion === 100;
tmpArray[i] = {
id: i,
title: 'Task ' + i,
duration: Math.floor(Math.random() * 100) + 10,
percentComplete: percentCompletion,
analysis: {
percentComplete: percentCompletion,
},
complexity: i % 3 ? 0 : 2,
start: new Date(randomYear, randomMonth, randomDay, randomDay, randomTime, randomTime, randomTime),
finish: (isCompleted || (i % 3 === 0 && (randomFinish > new Date() && i > 3)) ? (isCompleted ? new Date() : randomFinish) : ''), // make sure the random date is earlier than today and it's index is bigger than 3
cost: (i % 33 === 0) ? null : Math.round(Math.random() * 10000) / 100,
completed: (isCompleted || (i % 3 === 0 && (randomFinish > new Date() && i > 3))),
product: { id: this.mockProducts()[randomItemId]?.id, itemName: this.mockProducts()[randomItemId]?.itemName, },
origin: (i % 2) ? { code: 'CA', name: 'Canada' } : { code: 'US', name: 'United States' },
};
if (!(i % 8)) {
delete tmpArray[i].finish; // also test with undefined properties
delete tmpArray[i].percentComplete; // also test with undefined properties
}
}
return tmpArray;
}
// --
// event handlers
// ---------------
handleValidationError(_e: Event, args: any) {
if (args.validationResults) {
let errorMsg = args.validationResults.msg || '';
if (args.editor && (args.editor instanceof Slick.CompositeEditor)) {
if (args.validationResults.errors) {
errorMsg += '\n';
for (const error of args.validationResults.errors) {
const columnName = error.editor.args.column.name;
errorMsg += `${columnName.toUpperCase()}: ${error.msg}`;
}
}
console.log(errorMsg);
}
} else {
alert(args.validationResults.msg);
}
return false;
}
handleItemDeleted(_e: Event, args: any) {
console.log('item deleted with id:', args.itemId);
}
handleOnBeforeEditCell(e: Event, args: any) {
const { column, item, grid } = args;
if (column && item) {
if (!checkItemIsEditable(item, column, grid)) {
e.stopImmediatePropagation();
return false;
}
}
return true;
}
handleOnCellChange(_e: Event, args: any) {
const dataContext = args?.item;
// when the field "completed" changes to false, we also need to blank out the "finish" date
if (dataContext && !dataContext.completed) {
dataContext.finish = null;
this.angularGrid.gridService.updateItem(dataContext);
}
}
handleOnCellClicked(e: Event, args: any) {
console.log(e, args);
// if (eventData.target.classList.contains('fa-question-circle-o')) {
// alert('please HELP!!!');
// } else if (eventData.target.classList.contains('fa-chevron-down')) {
// alert('do something else...');
// }
}
handleOnCompositeEditorChange(_e: Event, args: OnCompositeEditorChangeEventArgs) {
const columnDef = args.column;
const formValues = args.formValues;
// you can dynamically change a select dropdown collection,
// if you need to re-render the editor for the list to be reflected
// if (columnDef.id === 'duration') {
// const editor = this.compositeEditorInstance.editors['percentComplete2'] as SelectEditor;
// const newCollection = editor.finalCollection;
// editor.renderDomElement(newCollection);
// }
// you can change any other form input values when certain conditions are met
if (columnDef.id === 'percentComplete' && formValues.percentComplete === 100) {
this.compositeEditorInstance.changeFormInputValue('completed', true);
this.compositeEditorInstance.changeFormInputValue('finish', new Date());
// this.compositeEditorInstance.changeFormInputValue('product', { id: 0, itemName: 'Sleek Metal Computer' });
// you can even change a value that is not part of the form (but is part of the grid)
// but you will have to bypass the error thrown by providing `true` as the 3rd argument
// this.compositeEditorInstance.changeFormInputValue('cost', 9999.99, true);
}
// you can also change some editor options (not all Editors supports this functionality, so far only these Editors AutoComplete, Date MultipleSelect & SingleSelect)
/*
if (columnDef.id === 'completed') {
this.compositeEditorInstance.changeFormEditorOption('percentComplete', 'filter', formValues.completed);
this.compositeEditorInstance.changeFormEditorOption('product', 'minLength', 3);
}
*/
}
handlePaginationChanged() {
this.removeAllUnsavedStylingFromCell();
this.renderUnsavedStylingOnAllVisibleCells();
}
handleOnGridStateChanged(gridStateChanges: GridStateChange) {
if (Array.isArray(gridStateChanges.gridState?.rowSelection?.dataContextIds)) {
this.isMassSelectionDisabled = gridStateChanges.gridState?.rowSelection?.dataContextIds.length === 0;
}
}
openCompositeModal(modalType: CompositeEditorModalType) {
// open the editor modal and we can also provide a header title with optional parsing pulled from the dataContext, via template {{ }}
// for example {{title}} => display the item title, or even complex object works {{product.itemName}} => display item product name
let modalTitle = '';
switch (modalType) {
case 'create':
modalTitle = 'Inserting New Task';
break;
case 'clone':
modalTitle = 'Clone - {{title}}';
break;
case 'edit':
modalTitle = 'Editing - {{title}} (<span class="text-muted">id:</span> <span class="text-primary">{{id}}</span>)'; // 'Editing - {{title}} ({{product.itemName}})'
break;
case 'mass-update':
modalTitle = 'Mass Update All Records';
break;
case 'mass-selection':
modalTitle = 'Update Selected Records';
break;
}
this.compositeEditorInstance?.openDetails({
headerTitle: modalTitle,
modalType,
insertOptions: { highlightRow: false }, // disable highlight to avoid flaky tests in Cypress
// showCloseButtonOutside: true,
// backdrop: null,
// viewColumnLayout: 2, // responsive layout, choose from 'auto', 1, 2, or 3 (defaults to 'auto')
showFormResetButton: true,
// showResetButtonOnEachEditor: true,
onClose: () => Promise.resolve(confirm('You have unsaved changes, are you sure you want to close this window?')),
onError: (error) => alert(error.message),
onSave: (formValues, _selection, dataContext) => {
const serverResponseDelay = 50;
// simulate a backend server call which will reject if the "% Complete" is below 50%
// when processing a mass update or mass selection
if (modalType === 'mass-update' || modalType === 'mass-selection') {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (formValues.percentComplete >= 50) {
resolve(true);
} else {
reject('Unfortunately we only accept a minimum of 50% Completion...');
}
}, serverResponseDelay);
});
} else {
// also simulate a server cal for any other modal type (create/clone/edit)
// we'll just apply the change without any rejection from the server and
// note that we also have access to the "dataContext" which is only available for these modal
console.log(`${modalType} item data context`, dataContext);
return new Promise(resolve => setTimeout(() => resolve(true), serverResponseDelay));
}
}
});
}
toggleGridEditReadonly() {
// first need undo all edits
this.undoAllEdits();
// then change a single grid options to make the grid non-editable (readonly)
this.isGridEditable = !this.isGridEditable;
this.isCompositeDisabled = !this.isGridEditable;
if (!this.isGridEditable) {
this.isMassSelectionDisabled = true;
}
// dynamically change SlickGrid editable grid option
this.angularGrid.slickGrid.setOptions({ editable: this.isGridEditable });
}
removeUnsavedStylingFromCell(_item: any, column: Column, row: number) {
// remove unsaved css class from that cell
this.angularGrid.slickGrid.removeCellCssStyles(`unsaved_highlight_${[column.id]}${row}`);
}
removeAllUnsavedStylingFromCell() {
for (const lastEdit of this.editQueue) {
const lastEditCommand = lastEdit?.editCommand;
if (lastEditCommand) {
// remove unsaved css class from that cell
for (const lastEditColumn of lastEdit.columns) {
this.removeUnsavedStylingFromCell(lastEdit.item, lastEditColumn, lastEditCommand.row);
}
}
}
}
renderUnsavedStylingOnAllVisibleCells() {
for (const lastEdit of this.editQueue) {
if (lastEdit) {
const { item, columns, editCommand } = lastEdit;
if (Array.isArray(columns)) {
columns.forEach((col) => {
this.renderUnsavedCellStyling(item, col, editCommand);
});
}
}
}
}
renderUnsavedCellStyling(item: any, column: Column, editCommand: EditCommand) {
if (editCommand && item && column) {
const row = this.angularGrid.dataView.getRowByItem(item) as number;
if (row >= 0) {
const hash = { [row]: { [column.id]: 'unsaved-editable-field' } };
this.angularGrid.slickGrid.setCellCssStyles(`unsaved_highlight_${[column.id]}${row}`, hash);
}
}
}
saveAll() {
// Edit Queue (array increases every time a cell is changed, regardless of item object)
console.log(this.editQueue);
// Edit Items only keeps the merged data (an object with row index as the row properties)
// if you change 2 different cells on 2 different cells then this editedItems will only contain 1 property
// example: editedItems = { 0: { title: task 0, duration: 50, ... }}
// ...means that row index 0 got changed and the final merged object is { title: task 0, duration: 50, ... }
console.log(this.editedItems);
// console.log(`We changed ${Object.keys(this.editedItems).length} rows`);
// since we saved, we can now remove all the unsaved color styling and reset our array/object
this.removeAllUnsavedStylingFromCell();
this.editQueue = [];
this.editedItems = {};
}
undoLastEdit(showLastEditor = false) {
const lastEdit = this.editQueue.pop();
const lastEditCommand = lastEdit?.editCommand;
if (lastEdit && lastEditCommand && Slick.GlobalEditorLock.cancelCurrentEdit()) {
lastEditCommand.undo();
// remove unsaved css class from that cell
for (const lastEditColumn of lastEdit.columns) {
this.removeUnsavedStylingFromCell(lastEdit.item, lastEditColumn, lastEditCommand.row);
}
this.angularGrid.slickGrid.invalidate();
// optionally open the last cell editor associated
if (showLastEditor) {
this.angularGrid.slickGrid.gotoCell(lastEditCommand.row, lastEditCommand.cell, false);
}
}
}
undoAllEdits() {
for (const lastEdit of this.editQueue) {
const lastEditCommand = lastEdit?.editCommand;
if (lastEditCommand && Slick.GlobalEditorLock.cancelCurrentEdit()) {
lastEditCommand.undo();
// remove unsaved css class from that cell
for (const lastEditColumn of lastEdit.columns) {
this.removeUnsavedStylingFromCell(lastEdit.item, lastEditColumn, lastEditCommand.row);
}
}
}
this.angularGrid.slickGrid.invalidate(); // re-render the grid only after every cells got rolled back
this.editQueue = [];
}
mockProducts() {
return [
{
id: 0,
itemName: 'Sleek Metal Computer',
itemNameTranslated: 'some fantastic sleek metal computer description',
listPrice: 2100.23,
itemTypeName: 'I',
image: 'http://i.stack.imgur.com/pC1Tv.jpg',
icon: `fa ${this.getRandomIcon(0)}`,
},
{
id: 1,
itemName: 'Tasty Granite Table',
itemNameTranslated: 'an extremely huge and heavy table',
listPrice: 3200.12,
itemTypeName: 'I',
image: 'https://i.imgur.com/Fnm7j6h.jpg',
icon: `fa ${this.getRandomIcon(1)}`,
},
{
id: 2,
itemName: 'Awesome Wooden Mouse',
itemNameTranslated: 'super old mouse',
listPrice: 15.00,
itemTypeName: 'I',
image: 'https://i.imgur.com/RaVJuLr.jpg',
icon: `fa ${this.getRandomIcon(2)}`,
},
{
id: 3,
itemName: 'Gorgeous Fresh Shirt',
itemNameTranslated: 'what a gorgeous shirt seriously',
listPrice: 25.76,
itemTypeName: 'I',
image: 'http://i.stack.imgur.com/pC1Tv.jpg',
icon: `fa ${this.getRandomIcon(3)}`,
},
{
id: 4,
itemName: 'Refined Cotton Table',
itemNameTranslated: 'super light table that will fall apart amazingly fast',
listPrice: 13.35,
itemTypeName: 'I',
image: 'https://i.imgur.com/Fnm7j6h.jpg',
icon: `fa ${this.getRandomIcon(4)}`,
},
{
id: 5,
itemName: 'Intelligent Wooden Pizza',
itemNameTranslated: 'wood not included',
listPrice: 23.33,
itemTypeName: 'I',
image: 'https://i.imgur.com/RaVJuLr.jpg',
icon: `fa ${this.getRandomIcon(5)}`,
},
{
id: 6,
itemName: 'Licensed Cotton Chips',
itemNameTranslated: 'not sure what that is',
listPrice: 71.21,
itemTypeName: 'I',
image: 'http://i.stack.imgur.com/pC1Tv.jpg',
icon: `fa ${this.getRandomIcon(6)}`,
},
{
id: 7,
itemName: 'Ergonomic Rubber Soap',
itemNameTranslated: `so good you'll want to use it every night`,
listPrice: 2.43,
itemTypeName: 'I',
image: 'https://i.imgur.com/Fnm7j6h.jpg',
icon: `fa ${this.getRandomIcon(7)}`,
},
{
id: 8,
itemName: 'Handcrafted Steel Car',
itemNameTranslated: `aka tesla truck`,
listPrice: 31288.39,
itemTypeName: 'I',
image: 'https://i.imgur.com/RaVJuLr.jpg',
icon: `fa ${this.getRandomIcon(8)}`,
},
];
}
/** List of icons that are supported in this lib Material Design Icons */
getRandomIcon(iconIndex?: number) {
const icons = [
'fa-500px',
'fa-address-book',
'fa-address-book-o',
'fa-address-card',
'fa-address-card-o',
'fa-adjust',
'fa-adn',
'fa-align-center',
'fa-align-justify',
'fa-align-left',
'fa-align-right',
'fa-amazon',
'fa-ambulance',
'fa-american-sign-language-interpreting',
'fa-anchor',
'fa-android',
'fa-angellist',
'fa-angle-double-down',
'fa-angle-double-left',
'fa-angle-double-right',
'fa-angle-double-up',
'fa-angle-down',
'fa-angle-left',
'fa-angle-right',
'fa-angle-up',
'fa-apple',
'fa-archive',
'fa-area-chart',
'fa-arrow-circle-down',
'fa-arrow-circle-left',
'fa-arrow-circle-o-down',
'fa-arrow-circle-o-left',
'fa-arrow-circle-o-right',
'fa-arrow-circle-o-up',
'fa-arrow-circle-right',
'fa-arrow-circle-up',
'fa-arrow-down',
'fa-arrow-left',
'fa-arrow-right',
'fa-arrow-up',
'fa-arrows',
'fa-arrows-alt',
'fa-arrows-h',
'fa-arrows-v',
'fa-assistive-listening-systems',
'fa-asterisk',
'fa-at',
'fa-audio-description',
'fa-backward',
'fa-balance-scale',
'fa-ban',
'fa-bandcamp',
'fa-bank (alias)',
'fa-bar-chart',
'fa-barcode',
'fa-bars',
'fa-bath',
'fa-battery-empty',
'fa-battery-full',
'fa-battery-half',
'fa-battery-quarter',
'fa-battery-three-quarters',
'fa-bed',
'fa-beer',
'fa-behance',
'fa-behance-square',
'fa-bell',
'fa-bell-o',
'fa-bell-slash',
'fa-bell-slash-o',
'fa-bicycle',
'fa-binoculars',
'fa-birthday-cake',
'fa-bitbucket',
'fa-bitbucket-square',
];
const randomNumber = Math.floor((Math.random() * icons.length - 1));
return icons[iconIndex ?? randomNumber];
}
renderItemCallbackWith2Rows(item: any): string {
return `<div class="autocomplete-container-list">
<div class="autocomplete-left">
<!--<img src="http://i.stack.imgur.com/pC1Tv.jpg" width="50" />-->
<span class="fa ${item.icon}"></span>
</div>
<div>
<span class="autocomplete-top-left">
<span class="mdfai ${item.itemTypeName === 'I' ? 'fa-info-circle' : 'fa-copy'}"></span>
${item.itemName}
</span>
<div>
</div>
<div>
<div class="autocomplete-bottom-left">${item.itemNameTranslated}</div>
</div>`;
}
renderItemCallbackWith4Corners(item: any): string {
return `<div class="autocomplete-container-list">
<div class="autocomplete-left">
<!--<img src="http://i.stack.imgur.com/pC1Tv.jpg" width="50" />-->
<span class="fa ${item.icon}"></span>
</div>
<div>
<span class="autocomplete-top-left">
<span class="fa ${item.itemTypeName === 'I' ? 'fa-info-circle' : 'fa-copy'}"></span>
${item.itemName}
</span>
<span class="autocomplete-top-right">${formatNumber(item.listPrice, 2, 2, false, '$')}</span>
<div>
</div>
<div>
<div class="autocomplete-bottom-left">${item.itemNameTranslated}</div>
<span class="autocomplete-bottom-right">Type: <b>${item.itemTypeName === 'I' ? 'Item' : item.itemTypeName === 'C' ? 'PdCat' : 'Cat'}</b></span>
</div>`;
}
} | the_stack |
import {
ITypeSyncer,
IPackageJSONService,
ITypeDefinitionSource,
ITypeDefinition,
IPackageFile,
ISyncOptions,
IDependenciesSection,
IPackageVersion,
ISyncResult,
ISyncedFile,
IPackageSource,
IPackageInfo,
ISyncedTypeDefinition,
IConfigService,
IDependencySection,
ICLIArguments,
} from './types'
import {
filterMap,
mergeObjects,
typed,
orderObject,
uniq,
flatten,
memoizeAsync,
ensureWorkspacesArray,
untyped,
} from './util'
import { IGlobber } from './globber'
import { satisfies } from 'semver'
/**
* Creates a type syncer.
*
* @param packageJSONservice
* @param typeDefinitionSource
*/
export function createTypeSyncer(
packageJSONService: IPackageJSONService,
typeDefinitionSource: ITypeDefinitionSource,
packageSource: IPackageSource,
configService: IConfigService,
globber: IGlobber
): ITypeSyncer {
const fetchPackageInfo = memoizeAsync(packageSource.fetch)
return {
sync,
}
/**
* Syncs typings in the specified package.json.
*/
async function sync(
filePath: string,
flags: ICLIArguments['flags']
): Promise<ISyncResult> {
const dryRun = !!flags.dry
const [file, allTypings, syncOpts] = await Promise.all([
packageJSONService.readPackageFile(filePath),
typeDefinitionSource.fetch(),
configService.readConfig(filePath, flags),
])
const subPackages = await Promise.all(
[
...ensureWorkspacesArray(file.packages),
...ensureWorkspacesArray(file.workspaces),
].map(globber.globPackageFiles)
)
.then(flatten)
.then(uniq)
const syncedFiles: Array<ISyncedFile> = await Promise.all([
syncFile(filePath, file, allTypings, syncOpts, dryRun),
...subPackages.map((p) =>
syncFile(p, null, allTypings, syncOpts, dryRun)
),
])
return {
syncedFiles,
}
}
/**
* Syncs a single file.
*
* @param filePath
* @param file
* @param allTypings
* @param opts
*/
async function syncFile(
filePath: string,
file: IPackageFile | null,
allTypings: Array<ITypeDefinition>,
opts: ISyncOptions,
dryRun: boolean
): Promise<ISyncedFile> {
const { ignoreDeps, ignorePackages } = opts
const packageFile =
file || (await packageJSONService.readPackageFile(filePath))
const allPackages = flatten(
filterMap(Object.values(IDependencySection), (dep) => {
if (ignoreDeps?.includes(dep)) {
return false
}
const section = getDependenciesBySection(packageFile, dep)
return getPackagesFromSection(section, ignorePackages)
})
)
const allPackageNames = uniq(allPackages.map((p) => p.name))
const newTypings = filterNewTypings(allPackageNames, allTypings)
// This is pushed to in the inner `map`, because packages that have DT-typings
// *as well* as internal typings should be exclused.
const used: Array<ReturnType<typeof filterNewTypings>[0]> = []
const devDepsToAdd = await Promise.all(
newTypings.map(async (t) => {
// Fetch the code package from the source.
const typePackageInfoPromise = fetchPackageInfo(typed(t.typingsName))
const codePackageInfo = await fetchPackageInfo(t.codePackageName)
const codePackage = allPackages.find(
(p) => p.name === t.codePackageName
)!
// Find the closest matching code package version relative to what's in our package.json
const closestMatchingCodeVersion = getClosestMatchingVersion(
codePackageInfo,
codePackage.version
)
// If the closest matching version contains internal typings, don't include it.
if (closestMatchingCodeVersion.containsInternalTypings) {
return {}
}
// Look for the closest matching typings package.
const typePackageInfo = await typePackageInfoPromise
// Gets the closest matching typings version, or the newest one.
const closestMatchingTypingsVersion = getClosestMatchingVersion(
typePackageInfo,
codePackage.version
)
const version = closestMatchingTypingsVersion.version
const semverRangeSpecifier = getSemverRangeSpecifier(
codePackage.version
)
used.push(t)
return {
[typed(t.typingsName)]: semverRangeSpecifier + version,
}
})
).then(mergeObjects)
const devDeps = packageFile.devDependencies || /* istanbul ignore next */ {}
const unused = getUnusedTypings(allPackageNames, devDeps, allTypings)
if (!dryRun) {
await packageJSONService.writePackageFile(filePath, {
...packageFile,
devDependencies: orderObject({
...devDepsToAdd,
...removeUnusedTypings(devDeps, unused),
}),
} as IPackageFile)
}
return {
filePath,
newTypings: used,
removedTypings: unused,
package: packageFile,
}
}
}
/**
* Removes unused typings from the devDependencies section.
*
* @param allPackageNames
* @param devDependencies
*/
function removeUnusedTypings(
devDependencies: IDependenciesSection,
unusedTypings: Array<ISyncedTypeDefinition & { typingsPackageName: string }>
): IDependenciesSection {
const result: IDependenciesSection = {}
for (let packageName in devDependencies) {
const version = devDependencies[packageName]
if (unusedTypings.some((t) => t.typingsPackageName === packageName)) {
continue
}
result[packageName] = version
}
return result
}
/**
* Removes unused typings from the devDependencies section.
*
* @param allPackageNames
* @param devDependencies
*/
function getUnusedTypings(
allPackageNames: string[],
devDependencies: IDependenciesSection,
allTypings: Array<ITypeDefinition>
) {
const result: Array<
ISyncedTypeDefinition & { typingsPackageName: string }
> = []
for (let packageName in devDependencies) {
if (packageName.startsWith('@types/')) {
const codePackageName = untyped(packageName)
// Make sure the corresponding code package is in `allPackages`.
const hasCodePackageForTyping = allPackageNames.some(
(p) => p === codePackageName
)
if (!hasCodePackageForTyping) {
const typingsNameForCodePackage = getTypingsName(codePackageName)
const typeDef = allTypings.find(
(t) => t.typingsName === typingsNameForCodePackage
)
if (typeDef && !typeDef.isGlobal) {
result.push({
codePackageName,
typingsPackageName: packageName,
...typeDef,
})
}
}
}
}
return result
}
/**
* Gets the closest matching package version info.
*
* @param packageInfo
* @param version
*/
function getClosestMatchingVersion(packageInfo: IPackageInfo, version: string) {
return (
packageInfo.versions.find((v) => satisfies(v.version, version)) ||
packageInfo.versions[0]
)
}
/**
* Returns an array of new typings as well as the code package name that was matched to it.
*
* @param allPackageNames Used to filter the typings that are new.
* @param allTypings All typings available
*/
function filterNewTypings(
allPackageNames: Array<string>,
allTypings: Array<ITypeDefinition>
): Array<ITypeDefinition & { codePackageName: string }> {
const existingTypings = allPackageNames.filter((x) => x.startsWith('@types/'))
return filterMap(allPackageNames, (p) => {
let typingsName = getTypingsName(p)
const typingsForPackage = allTypings.find(
(x) => x.typingsName === typingsName
)
if (!typingsForPackage) {
// No typings available.
return false
}
const fullTypingsPackage = typed(typingsForPackage.typingsName)
const alreadyHasTyping = existingTypings.some(
(t) => t === fullTypingsPackage
)
if (alreadyHasTyping) {
return false
}
return {
...typingsForPackage,
codePackageName: p,
}
})
}
/**
* Gets the typings name for the specified package name.
* For example, `koa` would be `koa`, but `@koa/router` would be `koa__router`.
*
* @param packageName the package name to generate the typings name for
*/
function getTypingsName(packageName: string) {
const scopeInfo = getPackageScope(packageName)
let typingsName = packageName
if (scopeInfo && scopeInfo[0] !== 'types') {
typingsName = `${scopeInfo[0]}__${scopeInfo[1]}`
}
return typingsName
}
/**
* If a package is scoped, returns the scope + package as a tuple, otherwise null.
*
* @param packageName Package name to check scope for.
*/
function getPackageScope(packageName: string): [string, string] | null {
const EXPR = /^\@([^\/]+)\/(.*)$/i
const matches = EXPR.exec(packageName)
if (!matches) {
return null
}
return [matches[1], matches[2]]
}
/**
* Get packages from a dependency section
*
* @param section
* @param ignorePackages
*/
function getPackagesFromSection(
section: IDependenciesSection,
ignorePackages?: string[]
): IPackageVersion[] {
return filterMap(Object.keys(section), (name) => {
if (ignorePackages?.includes(name)) {
return false
}
return { name, version: section[name] }
})
}
/**
* Get dependencies from a package section
*
* @param file Package file
* @param section Package section, eg: dev, peer
*/
function getDependenciesBySection(
file: IPackageFile,
section: IDependencySection
): IDependenciesSection {
const dependenciesSection = (() => {
switch (section) {
case IDependencySection.deps:
return file.dependencies
case IDependencySection.dev:
return file.devDependencies
case IDependencySection.optional:
return file.optionalDependencies
case IDependencySection.peer:
return file.peerDependencies
}
})()
return dependenciesSection ?? {}
}
const CARET = '^'.charCodeAt(0)
const TILDE = '~'.charCodeAt(0)
/**
* Gets the semver range specifier (~, ^)
* @param version
*/
function getSemverRangeSpecifier(version: string): string {
if (version.charCodeAt(0) === CARET) {
return '^'
}
if (version.charCodeAt(0) === TILDE) {
return '~'
}
return ''
} | the_stack |
import * as DiscoveryEntry from "../../../generated/joynr/types/DiscoveryEntry";
import * as DiscoveryEntryWithMetaInfo from "../../../generated/joynr/types/DiscoveryEntryWithMetaInfo";
import DiscoveryError from "../../../generated/joynr/types/DiscoveryError";
import * as Version from "../../../generated/joynr/types/Version";
import LoggingManager from "../../system/LoggingManager";
import { Deferred } from "../../util/UtilInternal";
import * as UtilInternal from "../../util/UtilInternal";
import DiscoveryException from "../../exceptions/DiscoveryException";
import NoCompatibleProviderFoundException from "../../exceptions/NoCompatibleProviderFoundException";
import LongTimer from "../../util/LongTimer";
import { DiscoveryStub } from "../interface/DiscoveryStub";
import DiscoveryQosGen = require("../../../generated/joynr/types/DiscoveryQos");
import DiscoveryQos = require("../../proxy/DiscoveryQos");
import ApplicationException = require("../../exceptions/ApplicationException");
import * as ArbitrationStrategyCollection from "../../../joynr/types/ArbitrationStrategyCollection";
import { FIXED_PARTICIPANT_PARAMETER } from "../../types/ArbitrationConstants";
import { isEqual } from "lodash";
const log = LoggingManager.getLogger("joynr.capabilities.arbitration.Arbitrator");
function addToListIfNotExisting(list: Version[], providerVersion: Version): void {
for (let j = 0; j < list.length; ++j) {
if (
list[j].majorVersion === providerVersion.majorVersion &&
list[j].minorVersion === providerVersion.minorVersion
) {
return;
}
}
list.push(providerVersion);
}
class Arbitrator {
private started: boolean = true;
private arbitrationId: number = 0;
private pendingArbitrations: Record<string, Deferred> = {};
private capabilityDiscoveryStub: DiscoveryStub;
private staticCapabilities?: DiscoveryEntryWithMetaInfo[];
/**
* An arbitrator looks up all capabilities for given domains and an interface and uses the provides arbitraionStrategy passed in the
* discoveryQos to choose one or more for the calling proxy
*
* @constructor
*
* @param capabilityDiscoveryStub the capability discovery
* @param staticCapabilities the capabilities the arbitrator will use to resolve capabilities in case of static arbitration
*/
public constructor(capabilityDiscoveryStub: DiscoveryStub, staticCapabilities?: DiscoveryEntryWithMetaInfo[]) {
this.staticCapabilities = staticCapabilities;
this.capabilityDiscoveryStub = capabilityDiscoveryStub;
}
/**
* Starts the arbitration process
*
* @param settings the settings object
* @param settings.domains the domains to discover the provider
* @param settings.interfaceName the interfaceName to discover the provider
* @param settings.discoveryQos
* @param [settings.staticArbitration] shall the arbitrator use staticCapabilities or contact the discovery provider
* @param [settings.proxyVersion] the version of the proxy object
*
* @returns Promise
* - resolved with an array of arbitrated capabilities
* - rejected with either DiscoveryException or NoCompatibleProviderFoundException
*/
public async startArbitration(settings: {
domains: string[];
interfaceName: string;
discoveryQos: DiscoveryQos;
staticArbitration?: boolean;
proxyVersion: Version;
gbids?: string[];
}): Promise<any[]> {
if (!this.started) {
return Promise.reject(new Error("Arbitrator is already shut down"));
}
this.arbitrationId++;
log.debug(
`Arbitration started for domains ${settings.domains}, interface ${settings.interfaceName}, gbids ${
settings.gbids
}.`
);
if (settings.staticArbitration && this.staticCapabilities) {
return this.discoverStaticCapabilities(
settings.domains,
settings.interfaceName,
settings.discoveryQos,
settings.proxyVersion
);
} else {
return this.discoverCapabilitiesWrapper(settings);
}
}
/**
* checks if the provided discoveryEntry supports onChange subscriptions if required
*
* @param discoveryEntry - the discovery entry to check
* @param providerMustSupportOnChange - filter only entries supporting onChange subscriptions
*/
private static checkSupportsOnChangeSubscriptions(
discoveryEntry: DiscoveryEntry,
providerMustSupportOnChange: boolean
): boolean {
if (providerMustSupportOnChange === undefined || !providerMustSupportOnChange) {
return true;
}
if (discoveryEntry.qos === undefined) {
return false;
}
return discoveryEntry.qos.supportsOnChangeSubscriptions;
}
private discoverCapabilitiesWrapper(settings: {
domains: string[];
interfaceName: string;
discoveryQos: DiscoveryQos;
staticArbitration?: boolean;
proxyVersion: Version;
gbids?: string[];
}): Promise<DiscoveryEntryWithMetaInfo[]> {
const id = this.arbitrationId;
const deferred = UtilInternal.createDeferred();
this.pendingArbitrations[id] = deferred;
this.discoverCapabilities({
capabilityDiscoveryStub: this.capabilityDiscoveryStub,
domains: settings.domains,
interfaceName: settings.interfaceName,
discoveryQos: settings.discoveryQos,
proxyVersion: settings.proxyVersion,
gbids: settings.gbids || []
})
.then(args => {
delete this.pendingArbitrations[id];
deferred.resolve(args);
})
.catch(error => {
delete this.pendingArbitrations[id];
deferred.reject(error);
});
return deferred.promise;
}
/**
* Tries to discover capabilities with given domains, interfaceName and discoveryQos within the localCapDir as long as the deferred's state is pending
*
* @param capabilityDiscoveryStub - the capabilites discovery module
* @param domains - the domains
* @param interfaceName - the interfaceName
* @param applicationDiscoveryQos
* @param proxyVersion
* @param gbids global backend identifiers of backends to look for capabilities
* @returns a Promise/A+ object, that will provide an array of discovered capabilities
*/
private async discoverCapabilities({
capabilityDiscoveryStub,
domains,
interfaceName,
discoveryQos,
proxyVersion,
gbids
}: {
capabilityDiscoveryStub: DiscoveryStub;
domains: string[];
interfaceName: string;
discoveryQos: DiscoveryQos;
proxyVersion: Version;
gbids: string[];
}): Promise<DiscoveryEntryWithMetaInfo[]> {
// discover caps from local capabilities directory
let incompatibleVersionsFound: Version[] = [];
const arbitrationDeadline = Date.now() + discoveryQos.discoveryTimeoutMs;
const discoveryRetryDelayMs = discoveryQos.discoveryRetryDelayMs;
let errorMsg: string | null = null;
let firstLoop = true;
let participantId: string;
const isArbitrationStrategyFixedParticipant = isEqual(
discoveryQos.arbitrationStrategy,
ArbitrationStrategyCollection.FixedParticipant
);
participantId = "";
if (isArbitrationStrategyFixedParticipant) {
if (!discoveryQos.additionalParameters.hasOwnProperty(FIXED_PARTICIPANT_PARAMETER)) {
throw new Error(
"parameter FIXED_PARTICIPANT_PARAMETER does not exist in DiscoveryQos.additionalParameters"
);
}
participantId = discoveryQos.additionalParameters[FIXED_PARTICIPANT_PARAMETER];
}
do {
if (!firstLoop) {
// eslint-disable-next-line promise/avoid-new
await new Promise(resolve => {
LongTimer.setTimeout(resolve, discoveryRetryDelayMs);
});
}
firstLoop = false;
incompatibleVersionsFound = [];
let discoveredCaps: DiscoveryEntryWithMetaInfo[];
try {
if (isArbitrationStrategyFixedParticipant) {
discoveredCaps = [];
discoveredCaps.push(
await capabilityDiscoveryStub.lookupByParticipantId(
participantId,
new DiscoveryQosGen({
discoveryScope: discoveryQos.discoveryScope,
cacheMaxAge: discoveryQos.cacheMaxAgeMs,
discoveryTimeout: arbitrationDeadline - Date.now(),
providerMustSupportOnChange: discoveryQos.providerMustSupportOnChange
}),
gbids
)
);
if (discoveredCaps.length > 0) {
if (discoveredCaps[0].interfaceName !== interfaceName) {
const errorMsg = `Interface "${
discoveredCaps[0].interfaceName
}" of discovered provider does not match proxy's interface "${interfaceName}".`;
log.error(errorMsg);
return Promise.reject(errorMsg);
}
}
} else {
discoveredCaps = await capabilityDiscoveryStub.lookup(
domains,
interfaceName,
new DiscoveryQosGen({
discoveryScope: discoveryQos.discoveryScope,
cacheMaxAge: discoveryQos.cacheMaxAgeMs,
discoveryTimeout: arbitrationDeadline - Date.now(),
providerMustSupportOnChange: discoveryQos.providerMustSupportOnChange
}),
gbids
);
}
const versionCompatibleCaps: DiscoveryEntryWithMetaInfo[] = [];
for (let i = 0; i < discoveredCaps.length; i++) {
const providerVersion = discoveredCaps[i].providerVersion;
if (
Arbitrator.checkSupportsOnChangeSubscriptions(
discoveredCaps[i],
discoveryQos.providerMustSupportOnChange
)
) {
if (
providerVersion.majorVersion === proxyVersion.majorVersion &&
providerVersion.minorVersion >= proxyVersion.minorVersion
) {
versionCompatibleCaps.push(discoveredCaps[i]);
} else {
addToListIfNotExisting(incompatibleVersionsFound, providerVersion);
}
}
}
// filter caps according to chosen arbitration strategy
const arbitratedCaps = discoveryQos.arbitrationStrategy(versionCompatibleCaps);
if (arbitratedCaps.length > 0) {
// report the discovered & arbitrated caps
return arbitratedCaps;
}
} catch (error) {
if (error instanceof ApplicationException) {
errorMsg = `Discovery failed due to ${error.error.name}`;
if (
error.error !== DiscoveryError.NO_ENTRY_FOR_PARTICIPANT &&
error.error !== DiscoveryError.NO_ENTRY_FOR_SELECTED_BACKENDS
) {
log.error(
`Discovery attempt for domains ${domains}, interface ${interfaceName}, gbids ${gbids} failed due to DiscoveryError: ${
error.error.name
}. Attempting no retry`
);
break;
} else {
log.info(
`Discovery attempt for domains ${domains}, interface ${interfaceName}, gbids ${gbids} failed due to DiscoveryError: ${
error.error.name
}. Attempting retry in ${discoveryQos.discoveryRetryDelayMs} ms`
);
}
} else if (error.message) {
log.info(
`Discovery attempt for domains ${domains}, interface ${interfaceName} failed due to DiscoveryError: ${
error.name
}. Attempting retry in ${discoveryQos.discoveryRetryDelayMs} ms`
);
errorMsg = `${error.name} : ${error.message}`;
}
}
} while (arbitrationDeadline - (Date.now() + discoveryRetryDelayMs) > 0);
if (incompatibleVersionsFound.length > 0) {
let message: string;
if (gbids && gbids.length > 0) {
message = `no compatible provider found within discovery timeout for domains "${JSON.stringify(
domains
)}", interface "${interfaceName}", gbids "${JSON.stringify(gbids)}" with discoveryQos "${JSON.stringify(
discoveryQos
)}"`;
} else {
message = `no compatible provider found within discovery timeout for domains "${JSON.stringify(
domains
)}", interface "${interfaceName}" with discoveryQos "${JSON.stringify(discoveryQos)}"`;
}
return Promise.reject(
new NoCompatibleProviderFoundException({
detailMessage: message,
discoveredVersions: incompatibleVersionsFound,
interfaceName
})
);
} else {
let message: string;
if (gbids && gbids.length > 0) {
message = `no provider found within discovery timeout for domains "${JSON.stringify(
domains
)}", interface "${interfaceName}", gbids "${JSON.stringify(gbids)}" with discoveryQos "${JSON.stringify(
discoveryQos
)}"${errorMsg !== undefined ? `. Error: ${errorMsg}` : ""}`;
} else {
message = `no provider found within discovery timeout for domains "${JSON.stringify(
domains
)}", interface "${interfaceName}" with discoveryQos "${JSON.stringify(discoveryQos)}"${
errorMsg !== undefined ? `. Error: ${errorMsg}` : ""
}`;
}
return Promise.reject(
new DiscoveryException({
detailMessage: message
})
);
}
}
private async discoverStaticCapabilities(
domains: string[],
interfaceName: string,
discoveryQos: DiscoveryQos,
proxyVersion: Version
): Promise<any[]> {
try {
const arbitratedCaps = [];
if (this.staticCapabilities === undefined) {
return Promise.reject(new Error("Exception while arbitrating: static capabilities are missing"));
} else {
for (let i = 0; i < this.staticCapabilities.length; ++i) {
const capability = this.staticCapabilities[i];
if (
domains.indexOf(capability.domain) !== -1 &&
interfaceName === capability.interfaceName &&
capability.providerVersion.majorVersion === proxyVersion.majorVersion &&
capability.providerVersion.minorVersion >= proxyVersion.minorVersion &&
Arbitrator.checkSupportsOnChangeSubscriptions(
capability,
discoveryQos.providerMustSupportOnChange
)
) {
arbitratedCaps.push(capability);
}
}
return discoveryQos.arbitrationStrategy(arbitratedCaps);
}
} catch (e) {
return Promise.reject(new Error(`Exception while arbitrating: ${e}`));
}
}
/**
* Shutdown the Arbitrator
*/
public shutdown(): void {
for (const id in this.pendingArbitrations) {
if (this.pendingArbitrations.hasOwnProperty(id)) {
const pendingArbitration = this.pendingArbitrations[id];
pendingArbitration.reject(new Error("Arbitration is already shut down"));
}
}
this.pendingArbitrations = {};
this.started = false;
}
}
export = Arbitrator; | the_stack |
import _ from 'lodash';
import rxmq, { Rx } from 'ecc-messagebus';
import {
isRootOrObjectRule,
MAPPING_RULE_TYPE_COMPLEX,
MAPPING_RULE_TYPE_COMPLEX_URI,
MAPPING_RULE_TYPE_DIRECT,
MAPPING_RULE_TYPE_OBJECT,
MAPPING_RULE_TYPE_ROOT,
MAPPING_RULE_TYPE_URI,
MESSAGES,
} from './utils/constants';
import EventEmitter from './utils/EventEmitter';
import { isDebugMode } from './utils/isDebugMode';
import React, {useState} from "react";
import silkApi, {HttpResponsePromise} from '../api/silkRestApi'
import {IPartialAutoCompleteResult, IValidationResult} from "./components/AutoSuggestion/AutoSuggestion";
import {ITransformedSuggestion} from "./containers/SuggestionNew/suggestion.typings";
const silkStore = rxmq.channel('silk.api');
export const errorChannel = rxmq.channel('errors');
let rootId = null;
const vocabularyCache = {};
interface IApiDetails {
baseUrl?: string,
project?: string,
transformTask?: string,
}
let _setApiDetails: React.Dispatch<React.SetStateAction<IApiDetails>> | undefined = undefined
let _apiDetails: IApiDetails = {};
export const setApiDetails = (data: IApiDetails) => {
const details = {...data}
if(_setApiDetails) {
_setApiDetails(details)
}
_apiDetails = details;
};
export const getApiDetails = (): IApiDetails => _apiDetails;
/** API details hook. Makes sure that a component gets the API details. */
export const useApiDetails = () => {
const [apiDetails, setApiDetails] = useState<IApiDetails>({})
_setApiDetails = setApiDetails
if(apiDetails.baseUrl === undefined && typeof _apiDetails.baseUrl === "string") {
setApiDetails(_apiDetails)
}
return apiDetails;
}
/** Make sure all API details are set. */
export function getDefinedApiDetails() {
const apiDetails = getApiDetails()
if(typeof apiDetails.baseUrl !== "string" || !apiDetails.project || !apiDetails.transformTask) {
throw new Error("Requested API details, but API details are not set!")
}
return {
baseUrl: apiDetails.baseUrl as string,
project: apiDetails.project as string,
transformTask: apiDetails.transformTask as string,
}
}
const mapPeakResult = (returned) => {
const resultStatus = _.get(returned, 'body.status.id')
if (resultStatus !== 'success' && resultStatus !== 'empty') {
return {
title: 'Could not load preview',
detail: _.get(
returned,
'body.status.msg',
'No details available'
),
};
}
return {
example: returned.body,
};
};
const editMappingRule = (payload, id, parent) => {
if (id) {
return silkStore.request({
topic: 'transform.task.rule.put',
data: {
...getApiDetails(),
ruleId: id,
payload,
},
});
}
return silkStore.request({
topic: 'transform.task.rule.rules.append',
data: {
...getApiDetails(),
ruleId: parent,
payload,
},
});
};
function findRule(curr, id, isObjectMapping, breadcrumbs) {
const element = {
...curr,
breadcrumbs,
};
if (element.id === id || _.get(element, 'rules.uriRule.id') === id) {
return element;
} else if (_.has(element, 'rules.propertyRules')) {
let result: any = null;
const bc = [
...breadcrumbs,
{
id: element.id,
type: _.get(element, 'rules.typeRules[0].typeUri', false),
property: _.get(element, 'mappingTarget.uri', false),
},
];
_.forEach(element.rules.propertyRules, child => {
if (result === null) {
result = findRule(child, id, isObjectMapping, bc);
}
});
if (
isObjectMapping &&
result !== null &&
!isRootOrObjectRule(result.type)
) {
result = element;
}
return result;
}
return null;
}
const handleCreatedSelectBoxValue = (data, path): any => {
if (_.has(data, [path, 'value'])) {
return _.get(data, [path, 'value']);
}
// the select boxes return an empty array when the user delete the existing text,
// instead of returning an empty string
if (_.isEmpty(_.get(data, [path]))) {
return '';
}
return _.get(data, [path]);
};
export interface IMetaData {
// A human-readable label
label: string
// An optional description
description?: string
}
/** The value type of a target property, e.g. string, int, language tag etc. */
export interface IValueType {
/** Node type ID, e.g. "uri", "lang", "StringValueType" etc. */
nodeType: string
/** If this is a custom data type, this specifies the URI of the data type. */
uri?: string
/** If this is a language tagged property, this specifies the language. */
lang?: string
}
/** The target of a mapping rule. */
export interface IMappingTarget {
/** Target URI, not necessarily a URI, this depends on the target dataset, e.g. this could be any string when writing to JSON. */
uri: string
/** The value type, e.g. string, int, URI etc. */
valueType: IValueType
/** Special attribute which only has relevance when mapping to XML. If true this will become an attribute. */
isAttribute?: boolean
/** If true the generated property will have a reversed direction. This only applies to graph datasets, i.e. RDF. */
isBackwardProperty?: boolean
}
/** The base interface for all mapping rules. */
export interface ITransformRule {
/** The (unique) ID of the mapping rule. */
id?: string
/** The type of the mapping. */
type?: MappingType
/** Meta data of the mapping rule. */
metadata: IMetaData
}
/** Interface of a value mapping. */
export interface IValueMapping extends ITransformRule {
/** The mapping target. */
mappingTarget: IMappingTarget
/** The source (Silk) path expression. */
sourcePath?: string
}
export interface IObjectMapping extends ITransformRule {
/** The mapping target. */
mappingTarget: IMappingTarget
/** The source (Silk) path expression. */
sourcePath?: string
/** The child mapping rules of this object mapping. */
rules: any // TODO: Improve type
}
interface IProps {
comment?: string
label: string
isAttribute: boolean
type: MappingType
sourceProperty: string
id: string
}
type MappingType = "direct" | "complex" | "object" | "uri" | "complexUri"
/** Construct the payload for a value mapping. */
const prepareValueMappingPayload = (data: IProps) => {
const payload: IValueMapping = {
metadata: {
description: data.comment,
label: data.label,
},
mappingTarget: {
uri: handleCreatedSelectBoxValue(data, 'targetProperty'),
valueType: handleCreatedSelectBoxValue(data, 'valueType'),
isAttribute: data.isAttribute,
},
};
if (data.type === MAPPING_RULE_TYPE_DIRECT) {
payload.sourcePath = data.sourceProperty
? handleCreatedSelectBoxValue(data, 'sourceProperty')
: '';
}
if (!data.id) {
payload.type = data.type;
}
return payload;
};
const prepareObjectMappingPayload = data => {
const typeRules = _.map(data.targetEntityType, typeRule => {
const value = _.get(typeRule, 'value', typeRule);
return {
type: 'type',
typeUri: value,
};
});
const payload: IObjectMapping = {
metadata: {
description: data.comment,
label: data.label,
},
mappingTarget: {
uri: handleCreatedSelectBoxValue(data, 'targetProperty'),
isBackwardProperty: data.entityConnection,
valueType: {
nodeType: 'UriValueType',
},
isAttribute: data.isAttribute
},
sourcePath: data.sourceProperty
? handleCreatedSelectBoxValue(data, 'sourceProperty')
: '',
rules: {
uriRule: data.pattern
? {
type: MAPPING_RULE_TYPE_URI,
pattern: data.pattern,
}
// URI pattern should be reset when set to null
: data.pattern === null ? null : undefined,
typeRules,
},
};
if (!data.id) {
payload.type = MAPPING_RULE_TYPE_OBJECT;
payload.rules.propertyRules = [];
}
return payload;
};
const generateRule = (rule, parentId) =>
createGeneratedMappingAsync({
...rule,
parentId,
}).catch(e => Rx.Observable.return({error: e, rule}));
const createGeneratedRules = ({rules, parentId}) =>
Rx.Observable.from(rules)
.flatMapWithMaxConcurrent(5, rule =>
Rx.Observable.defer(() => generateRule(rule, parentId)))
.reduce((all, result, idx) => {
const total = _.size(rules);
const count = idx + 1;
EventEmitter.emit(MESSAGES.RULE.SUGGESTIONS.PROGRESS, {
progressNumber: _.round(count / total * 100, 0),
lastUpdate: `Saved ${count} of ${total} rules.`,
});
all.push(result);
return all;
}, [])
.map(createdRules => {
const failedRules = _.filter(createdRules, 'error');
if (_.size(failedRules)) {
const error: Error & {failedRules?: any[]} = new Error('Could not create rules.');
error.failedRules = failedRules;
throw error;
}
return createdRules;
});
// PUBLIC API
export const orderRulesAsync = ({id, childrenRules}) => {
silkStore
.request({
topic: 'transform.task.rule.rules.reorder',
data: {id, childrenRules, ...getApiDetails()},
})
.map(() => {
EventEmitter.emit(MESSAGES.RELOAD);
});
};
export const generateRuleAsync = (correspondences, parentId, uriPrefix) => {
return silkStore
.request({
topic: 'transform.task.rule.generate',
data: {...getApiDetails(), correspondences, parentId, uriPrefix},
})
.map(returned => {
return {
rules: _.get(returned, ['body'], []),
parentId,
};
})
.flatMap(createGeneratedRules)
.map(() => {
EventEmitter.emit(MESSAGES.RULE_VIEW.CLOSE, {id: 0});
EventEmitter.emit(MESSAGES.RELOAD, true);
});
};
/** Updates an entry in the vocabulary cache, but only if it exists. */
export const updateVocabularyCacheEntry = (uri: string, label: string | undefined, description: string | undefined) => {
if (vocabularyCache[uri]) {
vocabularyCache[uri].label = label
vocabularyCache[uri].description = description
}
}
export const getVocabInfoAsync = (uri, field) => {
const path = [uri, field];
if (_.has(vocabularyCache, path)) {
return Rx.Observable.just({
info: _.get(vocabularyCache, path),
});
}
return silkStore
.request({
topic: 'transform.task.targetVocabulary.typeOrProperty',
data: {...getApiDetails(), uri},
})
.catch(() => Rx.Observable.just({}))
.map(returned => {
const info = _.get(
returned,
['body', 'genericInfo', field],
null
);
_.set(vocabularyCache, path, info);
return {
info,
};
});
};
interface ISuggestAsyncProps {
// Restrict matching by a list of target class URIs
targetClassUris: string[]
// (Root / object) rule ID this matching is done for
ruleId: string
// If the matching should be done from source view, else it will be from vocabulary view
matchFromDataset: boolean
// The max. number of returned candidates per source path / property. Defaults to 1.
nrCandidates?: number
// Optional list of target vocabulary URIs / IDs to restrict the vocabularies to match against.
targetVocabularies?: string[]
}
// Fetches vocabulary matching results from the DI matchVocabularyClassDataset endpoint
const fetchVocabularyMatchingResults = (data: ISuggestAsyncProps) => {
return silkStore
.request({
topic: 'transform.task.rule.suggestions',
data: {...getApiDetails(), ...data},
})
.catch(err => {
// It comes always {title: "Not Found", detail: "Not Found"} when the endpoint is not found.
// see: SilkErrorHandler.scala
const errorBody = _.get(err, 'response.body');
if (err.status === 404 && errorBody.title === 'Not Found' && errorBody.detail === 'Not Found') {
return Rx.Observable.return(null);
}
errorBody.code = err.status;
return Rx.Observable.return({error: errorBody});
})
.map(returned => {
const data = _.get(returned, 'body.matches', {});
const error = _.get(returned, 'error', []);
if (error) {
return {
error,
};
}
return {
data
}
})
}
/** Fetches (unused) source value paths to prevent showing matches of already mapped source paths. */
const fetchValueSourcePaths = (data: ISuggestAsyncProps) => {
return silkStore
.request({
// call the silk endpoint valueSourcePathsInfo
topic: 'transform.task.rule.valueSourcePathsInfo',
data: {...getApiDetails(), ...data},
})
.catch(err => {
let errorBody = _.get(err, 'response.body');
if(errorBody) {
errorBody.code = err.status;
} else if(err.detail && !err.status) {
errorBody = {title: "There has been a connection problem.", detail: err.detail, cause: null}
} else {
return Rx.Observable.return({});
}
return Rx.Observable.return({error: errorBody});
})
.map(returned => {
const data = _.get(returned, 'body', []);
const error = _.get(returned, 'error', []);
if (error) {
return {
error,
};
}
return {
data
};
})
}
/** Empty matching results in case no matching is executed. */
const emptyMatchResult = new Promise(resolve =>
resolve({data: []})
)
/** Fetches all suggestions. */
export const getSuggestionsAsync = (data: ISuggestAsyncProps,
executeVocabularyMatching: boolean = true) => {
const vocabularyMatches = executeVocabularyMatching ? fetchVocabularyMatchingResults(data) : emptyMatchResult
return Rx.Observable.forkJoin(
vocabularyMatches, fetchValueSourcePaths(data),
(vocabDatasetsResponse, sourcePaths) => {
const suggestions: ITransformedSuggestion[] = [];
if (vocabDatasetsResponse.data) {
vocabDatasetsResponse.data.map(match => {
const {uri: sourceUri, description, label, candidates, graph} = match;
suggestions.push({
uri: sourceUri,
candidates,
description,
label,
graph,
});
});
}
if (data.matchFromDataset && sourcePaths.data) {
sourcePaths.data.forEach(sourcePath => {
const existingSuggestion = suggestions.find(suggestion => suggestion.uri === sourcePath.path);
if (!existingSuggestion) {
suggestions.push({
uri: sourcePath.path,
candidates: [],
alreadyMapped: sourcePath.alreadyMapped,
pathType: sourcePath.pathType,
objectInfo: sourcePath.objectInfo
});
} else {
existingSuggestion.pathType = sourcePath.pathType
existingSuggestion.alreadyMapped = sourcePath.alreadyMapped
}
});
}
return {
suggestions,
warnings: _.filter([vocabDatasetsResponse.error, sourcePaths.error], e => !_.isUndefined(e)),
};
}
);
};
export const childExampleAsync = data => {
const {ruleType, rawRule, id, objectPath} = data;
const getRule = (rawRule, type) => {
switch (type) {
case MAPPING_RULE_TYPE_DIRECT:
case MAPPING_RULE_TYPE_COMPLEX:
return prepareValueMappingPayload(rawRule);
case MAPPING_RULE_TYPE_OBJECT:
return prepareObjectMappingPayload(rawRule);
case MAPPING_RULE_TYPE_URI:
case MAPPING_RULE_TYPE_COMPLEX_URI:
return rawRule;
default:
throw new Error('Rule send to rule.child.example type must be in ("value","object","uri","complexURI")');
}
};
const rule = getRule(rawRule, ruleType);
if (rule && id) {
return silkStore
.request({
topic: 'transform.task.rule.child.peak',
data: {...getApiDetails(), id, rule, objectPath},
})
.map(mapPeakResult);
}
return Rx.Observable();
};
export const ruleExampleAsync = data => {
const {id} = data;
if (id) {
return silkStore
.request({
topic: 'transform.task.rule.peak',
data: {...getApiDetails(), id},
})
.map(mapPeakResult);
}
return Rx.Observable();
};
export const getHierarchyAsync = () => {
return silkStore
.request({
topic: 'transform.task.rules.get',
data: {
...getApiDetails(),
},
})
.map(returned => {
const rules = returned.body;
if (!_.isString(rootId)) {
rootId = rules.id;
}
return {
hierarchy: rules,
};
});
};
export const getEditorHref = ruleId => {
const { transformTask, baseUrl, project } = getApiDetails();
const inlineView = (window.location !== window.parent.location) ? "true" : "false"
return ruleId ? `${baseUrl}/transform/${project}/${transformTask}/editor/${ruleId}?inlineView=${inlineView}` : null;
};
export const getRuleAsync = (id, isObjectMapping = false) => {
return silkStore
.request({
topic: 'transform.task.rules.get',
data: {...getApiDetails()},
})
.map(returned => {
const rules = returned.body;
const searchId = id || rules.id;
if (!_.isString(rootId)) {
rootId = rules.id;
}
const rule = findRule(
_.cloneDeep(rules),
searchId,
isObjectMapping,
[]
);
return {rule: rule || rules};
});
};
export const autocompleteAsync = data => {
const {entity, input, ruleId = rootId} = data;
let channel = 'transform.task.rule.completions.';
switch (entity) {
case 'propertyType':
channel += 'valueTypes';
break;
case 'targetProperty':
channel += 'targetProperties';
break;
case 'targetEntityType':
channel += 'targetTypes';
break;
case 'sourcePath':
channel += 'sourcePaths';
break;
default:
isDebugMode(`No autocomplete defined for ${entity}`);
}
return silkStore
.request({
topic: channel,
data: {...getApiDetails(), term: input, ruleId},
})
.map(returned => {
return {options: returned.body}
});
};
export const createMappingAsync = (data, isObject = false) => {
const payload = isObject ? prepareObjectMappingPayload(data) : prepareValueMappingPayload(data);
return editMappingRule(payload, data.id, data.parentId || rootId);
};
export const updateObjectMappingAsync = data => {
return editMappingRule(data, data.id, data.parentId || rootId);
};
export const createGeneratedMappingAsync = data => {
return editMappingRule(data, false, data.parentId || rootId);
};
export const ruleRemoveAsync = id => {
return silkStore
.request({
topic: 'transform.task.rule.delete',
data: {
...getApiDetails(),
ruleId: id,
},
})
.map(
() => {
EventEmitter.emit(MESSAGES.RELOAD, true);
},
err => {
// TODO: Beautify
}
);
};
export const copyRuleAsync = data => {
const {baseUrl, project, transformTask} = getApiDetails();
return silkStore
.request({
topic: 'transform.task.rule.copy',
data: {
baseUrl,
project,
transformTask,
id: data.id || MAPPING_RULE_TYPE_ROOT,
queryParameters: data.queryParameters,
appendTo: data.id, // the rule the copied rule should be appended to
},
})
.map(returned => returned.body.id);
};
export const schemaExampleValuesAsync = (ruleId: string) => {
const {baseUrl, project, transformTask} = getApiDetails();
return silkStore
.request({
topic: 'transform.task.rule.example',
data: {
baseUrl,
project,
transformTask,
ruleId,
},
})
.map(returned => returned.body);
};
export const prefixesAsync = () => {
const {baseUrl, project} = getApiDetails();
return silkStore
.request({
topic: 'transform.task.prefixes',
data: {
baseUrl,
project,
},
})
.map(returned => returned.body);
};
const getValuePathSuggestion = (ruleId:string, inputString: string, cursorPosition:number): HttpResponsePromise<any> => {
const { baseUrl, transformTask, project } = getDefinedApiDetails();
return silkApi.getSuggestionsForAutoCompletion(
baseUrl,
project,
transformTask,
ruleId,
inputString,
cursorPosition
);
}
// Fetches (partial) auto-complete suggestions for the value path
export const fetchValuePathSuggestions = (ruleId: string | undefined, inputString: string, cursorPosition: number): Promise<IPartialAutoCompleteResult | undefined> => {
return new Promise((resolve, reject) => {
if(!ruleId) {
resolve(undefined)
} else {
getValuePathSuggestion(ruleId, inputString, cursorPosition)
.then((suggestions) => resolve(suggestions?.data))
.catch((err) => reject(err))
}
})
}
// Fetches (partial) auto-complete suggestions for a path expression inside a URI pattern
export const fetchUriPatternAutoCompletions = (ruleId: string | undefined, inputString: string, cursorPosition: number, objectContextPath?: string): Promise<IPartialAutoCompleteResult | undefined> => {
return new Promise((resolve, reject) => {
if(!ruleId) {
resolve(undefined)
} else {
const {baseUrl, transformTask, project} = getDefinedApiDetails();
silkApi.getUriTemplateSuggestionsForAutoCompletion(
baseUrl,
project,
transformTask,
ruleId,
inputString,
cursorPosition,
objectContextPath
).then((suggestions) => resolve(suggestions?.data))
.catch((err) => reject(err));
}
})
}
const pathValidation = (inputString:string) => {
const {baseUrl, project} = getDefinedApiDetails()
return silkApi.validatePathExpression(baseUrl,project,inputString)
}
const uriPatternValidation = (inputString:string) => {
const {baseUrl, project} = getDefinedApiDetails()
return silkApi.validateUriPattern(baseUrl,project,inputString)
}
// Checks if the value path syntax is valid
export const checkValuePathValidity = (inputString): Promise<IValidationResult | undefined> => {
return new Promise((resolve, reject) => {
pathValidation(inputString)
.then((response) => {
const payload = response?.data
resolve(payload)
})
.catch((err) => {
reject(err)
})
})
}
// Checks if the value path syntax is valid
export const checkUriPatternValidity = (uriPattern: string): Promise<IValidationResult | undefined> => {
return new Promise((resolve, reject) => {
uriPatternValidation(uriPattern)
.then((response) => {
const payload = response?.data
resolve(payload)
})
.catch((err) => {
reject(err)
})
})
}
const exportFunctions = {
getHierarchyAsync,
getRuleAsync,
createMappingAsync,
getApiDetails,
setApiDetails
}
export default exportFunctions | the_stack |
import * as coreClient from "@azure/core-client";
/** The properties for the table query response. */
export interface TableQueryResponse {
/** The metadata response of the table. */
odataMetadata?: string;
/** List of tables. */
value?: TableResponseProperties[];
}
/** The properties for the table response. */
export interface TableResponseProperties {
/** The name of the table. */
name?: string;
/** The odata type of the table. */
odataType?: string;
/** The id of the table. */
odataId?: string;
/** The edit link of the table. */
odataEditLink?: string;
}
/** Table Service error. */
export interface TableServiceError {
/** The odata error. */
odataError?: TableServiceErrorOdataError;
}
/** The odata error. */
export interface TableServiceErrorOdataError {
/** The service error code. The error codes possible are listed in: https://docs.microsoft.com/rest/api/storageservices/table-service-error-codes */
code?: string;
/** The service error message. */
message?: TableServiceErrorOdataErrorMessage;
}
/** The service error message. */
export interface TableServiceErrorOdataErrorMessage {
/** Language code of the error message. */
lang?: string;
/** The error message. */
value?: string;
}
/** The properties for creating a table. */
export interface TableProperties {
/** The name of the table to create. */
name?: string;
}
/** The properties for the table entity query response. */
export interface TableEntityQueryResponse {
/** The metadata response of the table. */
odataMetadata?: string;
/** List of table entities. */
value?: { [propertyName: string]: any }[];
}
/** A signed identifier. */
export interface SignedIdentifier {
/** A unique id. */
id: string;
/** The access policy. */
accessPolicy?: AccessPolicy;
}
/** An Access policy. */
export interface AccessPolicy {
/** The start datetime from which the policy is active. */
start?: string;
/** The datetime that the policy expires. */
expiry?: string;
/** The permissions for the acl policy. */
permission?: string;
}
/** Table Service Properties. */
export interface TableServiceProperties {
/** Azure Analytics Logging settings. */
logging?: Logging;
/** A summary of request statistics grouped by API in hourly aggregates for tables. */
hourMetrics?: Metrics;
/** A summary of request statistics grouped by API in minute aggregates for tables. */
minuteMetrics?: Metrics;
/** The set of CORS rules. */
cors?: CorsRule[];
}
/** Azure Analytics Logging settings. */
export interface Logging {
/** The version of Analytics to configure. */
version: string;
/** Indicates whether all delete requests should be logged. */
delete: boolean;
/** Indicates whether all read requests should be logged. */
read: boolean;
/** Indicates whether all write requests should be logged. */
write: boolean;
/** The retention policy. */
retentionPolicy: RetentionPolicy;
}
/** The retention policy. */
export interface RetentionPolicy {
/** Indicates whether a retention policy is enabled for the service. */
enabled: boolean;
/** Indicates the number of days that metrics or logging or soft-deleted data should be retained. All data older than this value will be deleted. */
days?: number;
}
/** A summary of request statistics grouped by API */
export interface Metrics {
/** The version of Analytics to configure. */
version?: string;
/** Indicates whether metrics are enabled for the Table service. */
enabled: boolean;
/** Indicates whether metrics should generate summary statistics for called API operations. */
includeAPIs?: boolean;
/** The retention policy. */
retentionPolicy?: RetentionPolicy;
}
/** CORS is an HTTP feature that enables a web application running under one domain to access resources in another domain. Web browsers implement a security restriction known as same-origin policy that prevents a web page from calling APIs in a different domain; CORS provides a secure way to allow one domain (the origin domain) to call APIs in another domain. */
export interface CorsRule {
/** The origin domains that are permitted to make a request against the service via CORS. The origin domain is the domain from which the request originates. Note that the origin must be an exact case-sensitive match with the origin that the user age sends to the service. You can also use the wildcard character '*' to allow all origin domains to make requests via CORS. */
allowedOrigins: string;
/** The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma separated) */
allowedMethods: string;
/** The request headers that the origin domain may specify on the CORS request. */
allowedHeaders: string;
/** The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer. */
exposedHeaders: string;
/** The maximum amount time that a browser should cache the preflight OPTIONS request. */
maxAgeInSeconds: number;
}
/** Stats for the service. */
export interface TableServiceStats {
/** Geo-Replication information for the Secondary Storage Service. */
geoReplication?: GeoReplication;
}
/** Geo-Replication information for the Secondary Storage Service */
export interface GeoReplication {
/** The status of the secondary location. */
status: GeoReplicationStatusType;
/** A GMT date/time value, to the second. All primary writes preceding this value are guaranteed to be available for read operations at the secondary. Primary writes after this point in time may or may not be available for reads. */
lastSyncTime: Date;
}
/** The response for a single table. */
export type TableResponse = TableResponseProperties & {
/** The metadata response of the table. */
odataMetadata?: string;
};
/** Defines headers for Table_query operation. */
export interface TableQueryHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
/** This header contains the continuation token value. */
xMsContinuationNextTableName?: string;
}
/** Defines headers for Table_query operation. */
export interface TableQueryExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Table_create operation. */
export interface TableCreateHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
/** Indicates whether the Prefer request header was honored. If the response does not include this header, then the Prefer header was not honored. If this header is returned, its value will either be return-content or return-no-content. */
preferenceApplied?: string;
}
/** Defines headers for Table_create operation. */
export interface TableCreateExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Table_delete operation. */
export interface TableDeleteHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
}
/** Defines headers for Table_delete operation. */
export interface TableDeleteExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Table_queryEntities operation. */
export interface TableQueryEntitiesHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
/** This header contains the continuation token value for partition key. */
xMsContinuationNextPartitionKey?: string;
/** This header contains the continuation token value for row key. */
xMsContinuationNextRowKey?: string;
}
/** Defines headers for Table_queryEntities operation. */
export interface TableQueryEntitiesExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Table_queryEntitiesWithPartitionAndRowKey operation. */
export interface TableQueryEntitiesWithPartitionAndRowKeyHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated */
etag?: string;
/** This header contains the continuation token value for partition key. */
xMsContinuationNextPartitionKey?: string;
/** This header contains the continuation token value for row key. */
xMsContinuationNextRowKey?: string;
}
/** Defines headers for Table_queryEntitiesWithPartitionAndRowKey operation. */
export interface TableQueryEntitiesWithPartitionAndRowKeyExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Table_updateEntity operation. */
export interface TableUpdateEntityHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
/** UTC date/time value generated by the service that indicates the time at which the entity was last updated. */
etag?: string;
}
/** Defines headers for Table_updateEntity operation. */
export interface TableUpdateEntityExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Table_mergeEntity operation. */
export interface TableMergeEntityHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
/** UTC date/time value generated by the service that indicates the time at which the entity was last updated. */
etag?: string;
}
/** Defines headers for Table_mergeEntity operation. */
export interface TableMergeEntityExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Table_deleteEntity operation. */
export interface TableDeleteEntityHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
}
/** Defines headers for Table_deleteEntity operation. */
export interface TableDeleteEntityExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Table_insertEntity operation. */
export interface TableInsertEntityHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
/** UTC date/time value generated by the service that indicates the time at which the entity was last updated. */
etag?: string;
/** Indicates whether the Prefer request header was honored. If the response does not include this header, then the Prefer header was not honored. If this header is returned, its value will either be return-content or return-no-content. */
preferenceApplied?: string;
/** Indicates the content type of the payload. The value depends on the value specified for the Accept request header. */
contentType?: string;
}
/** Defines headers for Table_insertEntity operation. */
export interface TableInsertEntityExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Table_getAccessPolicy operation. */
export interface TableGetAccessPolicyHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
}
/** Defines headers for Table_getAccessPolicy operation. */
export interface TableGetAccessPolicyExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Table_setAccessPolicy operation. */
export interface TableSetAccessPolicyHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
}
/** Defines headers for Table_setAccessPolicy operation. */
export interface TableSetAccessPolicyExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Service_setProperties operation. */
export interface ServiceSetPropertiesHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
}
/** Defines headers for Service_setProperties operation. */
export interface ServiceSetPropertiesExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Service_getProperties operation. */
export interface ServiceGetPropertiesHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
}
/** Defines headers for Service_getProperties operation. */
export interface ServiceGetPropertiesExceptionHeaders {
errorCode?: string;
}
/** Defines headers for Service_getStatistics operation. */
export interface ServiceGetStatisticsHeaders {
/** If a client request id header is sent in the request, this header will be present in the response with the same value. */
clientRequestId?: string;
/** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */
requestId?: string;
/** Indicates the version of the Table service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */
version?: string;
/** UTC date/time value generated by the service that indicates the time at which the response was initiated. */
date?: Date;
}
/** Defines headers for Service_getStatistics operation. */
export interface ServiceGetStatisticsExceptionHeaders {
errorCode?: string;
}
/** Parameter group */
export interface QueryOptions {
/** Specifies the media type for the response. */
format?: OdataMetadataFormat;
/** Maximum number of records to return. */
top?: number;
/** Select expression using OData notation. Limits the columns on each record to just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". */
select?: string;
/** OData filter expression. */
filter?: string;
}
/** Known values of {@link OdataMetadataFormat} that the service accepts. */
export enum KnownOdataMetadataFormat {
ApplicationJsonOdataNometadata = "application/json;odata=nometadata",
ApplicationJsonOdataMinimalmetadata = "application/json;odata=minimalmetadata",
ApplicationJsonOdataFullmetadata = "application/json;odata=fullmetadata"
}
/**
* Defines values for OdataMetadataFormat. \
* {@link KnownOdataMetadataFormat} can be used interchangeably with OdataMetadataFormat,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **application\/json;odata=nometadata** \
* **application\/json;odata=minimalmetadata** \
* **application\/json;odata=fullmetadata**
*/
export type OdataMetadataFormat = string;
/** Known values of {@link ResponseFormat} that the service accepts. */
export enum KnownResponseFormat {
ReturnNoContent = "return-no-content",
ReturnContent = "return-content"
}
/**
* Defines values for ResponseFormat. \
* {@link KnownResponseFormat} can be used interchangeably with ResponseFormat,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **return-no-content** \
* **return-content**
*/
export type ResponseFormat = string;
/** Known values of {@link GeoReplicationStatusType} that the service accepts. */
export enum KnownGeoReplicationStatusType {
Live = "live",
Bootstrap = "bootstrap",
Unavailable = "unavailable"
}
/**
* Defines values for GeoReplicationStatusType. \
* {@link KnownGeoReplicationStatusType} can be used interchangeably with GeoReplicationStatusType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **live** \
* **bootstrap** \
* **unavailable**
*/
export type GeoReplicationStatusType = string;
/** Optional parameters. */
export interface TableQueryOptionalParams extends coreClient.OperationOptions {
/** Parameter group */
queryOptions?: QueryOptions;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** A table query continuation token from a previous call. */
nextTableName?: string;
}
/** Contains response data for the query operation. */
export type TableQueryOperationResponse = TableQueryHeaders &
TableQueryResponse;
/** Optional parameters. */
export interface TableCreateOptionalParams extends coreClient.OperationOptions {
/** Parameter group */
queryOptions?: QueryOptions;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** Specifies whether the response should include the inserted entity in the payload. Possible values are return-no-content and return-content. */
responsePreference?: ResponseFormat;
}
/** Contains response data for the create operation. */
export type TableCreateResponse = TableCreateHeaders & TableResponse;
/** Optional parameters. */
export interface TableDeleteOptionalParams extends coreClient.OperationOptions {
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
}
/** Contains response data for the delete operation. */
export type TableDeleteResponse = TableDeleteHeaders;
/** Optional parameters. */
export interface TableQueryEntitiesOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
queryOptions?: QueryOptions;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
/** An entity query continuation token from a previous call. */
nextPartitionKey?: string;
/** An entity query continuation token from a previous call. */
nextRowKey?: string;
}
/** Contains response data for the queryEntities operation. */
export type TableQueryEntitiesResponse = TableQueryEntitiesHeaders &
TableEntityQueryResponse;
/** Optional parameters. */
export interface TableQueryEntitiesWithPartitionAndRowKeyOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
queryOptions?: QueryOptions;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
}
/** Contains response data for the queryEntitiesWithPartitionAndRowKey operation. */
export type TableQueryEntitiesWithPartitionAndRowKeyResponse = TableQueryEntitiesWithPartitionAndRowKeyHeaders & {
[propertyName: string]: any;
};
/** Optional parameters. */
export interface TableUpdateEntityOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
queryOptions?: QueryOptions;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
/** The properties for the table entity. */
tableEntityProperties?: { [propertyName: string]: any };
/** Match condition for an entity to be updated. If specified and a matching entity is not found, an error will be raised. To force an unconditional update, set to the wildcard character (*). If not specified, an insert will be performed when no existing entity is found to update and a replace will be performed if an existing entity is found. */
ifMatch?: string;
}
/** Contains response data for the updateEntity operation. */
export type TableUpdateEntityResponse = TableUpdateEntityHeaders;
/** Optional parameters. */
export interface TableMergeEntityOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
queryOptions?: QueryOptions;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
/** The properties for the table entity. */
tableEntityProperties?: { [propertyName: string]: any };
/** Match condition for an entity to be updated. If specified and a matching entity is not found, an error will be raised. To force an unconditional update, set to the wildcard character (*). If not specified, an insert will be performed when no existing entity is found to update and a merge will be performed if an existing entity is found. */
ifMatch?: string;
}
/** Contains response data for the mergeEntity operation. */
export type TableMergeEntityResponse = TableMergeEntityHeaders;
/** Optional parameters. */
export interface TableDeleteEntityOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
queryOptions?: QueryOptions;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
}
/** Contains response data for the deleteEntity operation. */
export type TableDeleteEntityResponse = TableDeleteEntityHeaders;
/** Optional parameters. */
export interface TableInsertEntityOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
queryOptions?: QueryOptions;
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** Specifies whether the response should include the inserted entity in the payload. Possible values are return-no-content and return-content. */
responsePreference?: ResponseFormat;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
/** The properties for the table entity. */
tableEntityProperties?: { [propertyName: string]: any };
}
/** Contains response data for the insertEntity operation. */
export type TableInsertEntityResponse = TableInsertEntityHeaders & {
[propertyName: string]: any;
};
/** Optional parameters. */
export interface TableGetAccessPolicyOptionalParams
extends coreClient.OperationOptions {
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
}
/** Contains response data for the getAccessPolicy operation. */
export type TableGetAccessPolicyResponse = TableGetAccessPolicyHeaders &
SignedIdentifier[];
/** Optional parameters. */
export interface TableSetAccessPolicyOptionalParams
extends coreClient.OperationOptions {
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
/** The acls for the table. */
tableAcl?: SignedIdentifier[];
}
/** Contains response data for the setAccessPolicy operation. */
export type TableSetAccessPolicyResponse = TableSetAccessPolicyHeaders;
/** Optional parameters. */
export interface ServiceSetPropertiesOptionalParams
extends coreClient.OperationOptions {
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
}
/** Contains response data for the setProperties operation. */
export type ServiceSetPropertiesResponse = ServiceSetPropertiesHeaders;
/** Optional parameters. */
export interface ServiceGetPropertiesOptionalParams
extends coreClient.OperationOptions {
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
}
/** Contains response data for the getProperties operation. */
export type ServiceGetPropertiesResponse = ServiceGetPropertiesHeaders &
TableServiceProperties;
/** Optional parameters. */
export interface ServiceGetStatisticsOptionalParams
extends coreClient.OperationOptions {
/** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when analytics logging is enabled. */
requestId?: string;
/** The timeout parameter is expressed in seconds. */
timeout?: number;
}
/** Contains response data for the getStatistics operation. */
export type ServiceGetStatisticsResponse = ServiceGetStatisticsHeaders &
TableServiceStats;
/** Optional parameters. */
export interface GeneratedClientOptionalParams
extends coreClient.ServiceClientOptions {
/** Specifies the version of the operation to use for this request. */
version?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import {PageConfig} from 'rcre';
import chalk from 'chalk';
import {get, isEqual, find} from 'lodash';
import format from 'pretty-format';
import {Store} from 'redux';
import {RCRETestUtil} from './RCRETestUtil';
export interface StepItem {
// 是否启用
enable?: boolean;
// 定位的name
name?: string;
// 定位的type
type?: string;
// 第index个
index?: number;
// 写入的值
value?: any;
// 开启此选项,会关闭对trigger事件的校验,完全手动控制组件的交互
manual?: boolean;
event?: {
eventName: string;
args: Object;
}[];
}
const printFunctionFormatPlugin = {
test: (value: any) => typeof value === 'function',
print: (value: any) => value.toString()
};
export type StepCommand = 'submit' | 'checkForm';
export type Step = (StepItem | StepCommand | StepContainer | undefined);
export interface StepContainer {
container: string;
steps: Step[];
}
export type StepList = (StepContainer | StepCommand)[];
export interface RobotOptions {
// 运行结束后验证输入和state中的值
// default: true
disableCheckStateResult?: boolean;
// 验证表单项的状态
// default: true
disableValidateForm?: boolean;
// 输出日志
verbose?: boolean;
}
export class AutomaticRobot {
public test: RCRETestUtil;
public options: RobotOptions;
constructor(config: PageConfig<any>, globals: object = {}, store?: Store<any>) {
this.test = new RCRETestUtil(config, globals);
this.options = {};
}
public setOptions(options: RobotOptions = {}) {
Object.assign(this.options, options);
}
public async submitForm(preventSubmit: boolean) {
this.test.wrapper.update();
await this.test.waitForDataProviderComplete();
let form = this.test.getRootForm();
let state = form.state();
let valid = state.valid;
if (!valid) {
let errorFormItems: string[][] = [];
Object.keys(state.control).forEach(key => {
if (!state.control[key].valid) {
errorFormItems.push([key, state.control[key].errorMsg]);
}
});
throw new Error('Form is not valid, invalid formItems: ' + JSON.stringify(errorFormItems));
}
return await this.test.triggerFormSubmit(form, preventSubmit);
}
private async execScripts(scripts: StepList) {
let index = 0;
while (index < scripts.length) {
let item = scripts[index];
// 触发表单提交
if (typeof item === 'string' && item === 'submit') {
this.test.wrapper.update();
let form = this.test.getRootForm();
let state = form.state();
let valid = state.valid;
if (!valid) {
let errorFormItems: string[] = [];
Object.keys(state.control).forEach(key => {
if (!state.control[key].valid) {
errorFormItems.push(key);
}
});
throw new Error('Form is not valid, invalid formItems: ' + errorFormItems.join(','));
}
await this.test.triggerFormSubmit(form);
console.log('submit finished');
index++;
continue;
}
if (typeof item === 'string' && item === 'checkForm') {
this.checkState(scripts);
index++;
continue;
}
if (!item) {
index++;
continue;
}
let container = item.container;
this.test.setContainer(container);
if (this.options.verbose) {
console.log(chalk.blue('enter container: ' + chalk.bold(container)));
}
let steps = item.steps;
if (!Array.isArray(steps)) {
throw new Error('container->steps is not array');
}
let stepIndex = 0;
while (stepIndex < steps.length) {
let stepItem = steps[stepIndex];
if (typeof stepItem === 'string' && stepItem === 'submit') {
stepIndex++;
continue;
}
if (typeof stepItem === 'string' && stepItem === 'checkForm') {
if (this.options.verbose) {
console.log(chalk.bold(chalk.green('rechecking form status...')));
}
this.checkState(scripts);
stepIndex++;
continue;
}
if (!stepItem) {
stepIndex++;
continue;
}
if (stepItem.hasOwnProperty('container')) {
stepItem = stepItem as StepContainer;
await this.execScripts([stepItem]);
stepIndex++;
continue;
}
stepItem = stepItem as StepItem;
if (stepItem.enable === false) {
stepIndex++;
continue;
}
let name = stepItem.name;
let type = stepItem.type;
let component;
if (name) {
component = this.test.getComponentByName(name, stepItem.index || 0);
} else if (type) {
component = this.test.getComponentByType(type, stepItem.index || 0);
} else {
throw new Error('steps: items should have name or type property');
}
if (name && stepItem.hasOwnProperty('value')) {
let existValue = this.test.getComponentNameValue(component);
if (isEqual(existValue, stepItem.value)) {
if (this.options.verbose) {
console.log(chalk.gray(`found component[name=${name}] have exist value. skip..`));
}
stepIndex++;
continue;
}
}
if ('value' in stepItem) {
if (this.options.verbose) {
if (name) {
console.log(chalk.red(`start to setData, name: ${chalk.bold(name)}`));
} else if (type) {
console.log(chalk.red(`start to setData, type: ${chalk.bold(type)}`));
}
}
this.test.setData(component, stepItem.value);
let isValid = this.test.isNameValid(component);
if (this.options.verbose) {
if (name) {
console.log(chalk.green(`component value check success. name: ${chalk.bold(name)}, index: ${index}`));
} else if (type) {
console.log(chalk.green(`component value check success. type: ${chalk.bold(type)}, index: ${index}`));
}
}
if (!isValid) {
throw new Error('StepItem: item value is not valid. \n' + format(stepItem, {
plugins: [printFunctionFormatPlugin]
}));
}
}
let componentInfo = this.test.getComponentInfo(component);
if (componentInfo.trigger && stepItem.manual && this.options.verbose) {
console.log(chalk.cyan(`trigger check closed, enter manual mode`));
}
// 手动模式关闭检测功能
if (componentInfo.trigger && !stepItem.manual) {
if (!stepItem.event) {
throw new Error(`StepItem: if the component contains a trigger attribute, then the test must have an events attribute to cover.
stepItem: ${format(stepItem, {
plugins: [printFunctionFormatPlugin]
})}
info: ${format(componentInfo.trigger, {
plugins: [printFunctionFormatPlugin]
})}`);
}
let stepItemEvent = stepItem.event;
let triggerList = componentInfo.trigger.filter((eventItem: any) => {
let match = find(stepItemEvent, se => se.eventName === eventItem.event);
if (match) {
return false;
}
return true;
});
if (triggerList.length > 0) {
throw new Error('StepItem: trigger event did not fully covered');
}
}
if (Array.isArray(stepItem.event)) {
for (let i = 0; i < stepItem.event.length; i ++) {
if (this.options.verbose) {
if (name) {
console.log(chalk.blue(`simulate event, name: ${name}, index: ${index}, eventName: ${stepItem.event[i].eventName}, args: ${JSON.stringify(stepItem.event[i].args)}`));
} else if (type) {
console.log(chalk.blue(`simulate event, type: ${type}, index: ${index}, eventName: ${stepItem.event[i].eventName}, args: ${JSON.stringify(stepItem.event[i].args)}`));
}
}
await this.test.simulate(component, stepItem.event[i].eventName, stepItem.event[i].args);
}
}
if (stepItem.name && stepItem.hasOwnProperty('value')) {
let state = this.test.getState();
let stateValue = get(state.container, '[' + container + '][' + stepItem.name + ']');
if (!isEqual(stateValue, stepItem.value) && !this.options.disableCheckStateResult) {
throw new Error(`CheckState failed: ${stepItem.name} is not equal; state: ${stateValue}, expect: ${stepItem.value}`);
}
component = this.test.getComponentByName(stepItem.name, stepItem.index || 0);
let formState = this.test.getComponentFormStatus(component);
if (formState && !this.options.disableValidateForm) {
let formItemStatus = this.test.getFormItemState(formState.name, stepItem.name);
if (formItemStatus && !formItemStatus.valid) {
throw new Error(`CheckState failed: ${stepItem.name}'s form status is not valid. errmsg: ${formItemStatus.errorMsg}`);
}
}
}
if (this.options.verbose) {
console.log(chalk.green('item check success.'));
}
await this.test.waitForDataProviderComplete();
stepIndex++;
}
index++;
}
}
private checkState(scripts: StepList) {
let state = this.test.getState();
let container = state.container;
let index = 0;
while (index < scripts.length) {
let item = scripts[index];
if (typeof item === 'string') {
index++;
continue;
}
if (!item) {
index++;
continue;
}
let model = item.container;
this.test.setContainer(model);
let steps = item.steps;
let stepIndex = 0;
while (stepIndex < steps.length) {
let stepItem = steps[stepIndex];
if (typeof stepItem === 'string') {
stepIndex++;
continue;
}
if (!stepItem) {
stepIndex++;
continue;
}
if (stepItem.hasOwnProperty('container')) {
stepItem = stepItem as StepContainer;
this.checkState([stepItem]);
stepIndex++;
continue;
}
stepItem = stepItem as StepItem;
if (stepItem.enable === false) {
stepIndex++;
continue;
}
// 这种的情况没有任何可以测试的数据
if (!stepItem.name && stepItem.type && !stepItem.event) {
continue;
}
let component;
if (stepItem.type) {
component = this.test.getComponentByType(stepItem.type, stepItem.index || 0);
}
if (stepItem.name) {
let stateValue = container[model][stepItem.name];
if (stateValue !== stepItem.value && !this.options.disableCheckStateResult) {
throw new Error(`CheckState failed: ${stepItem.name} is not equal; state: ${stateValue}, expect: ${stepItem.value}`);
}
component = this.test.getComponentByName(stepItem.name, stepItem.index || 0);
let formState = this.test.getComponentFormStatus(component);
if (formState && !this.options.disableValidateForm) {
let formItemStatus = this.test.getFormItemState(formState.name, stepItem.name);
if (!formItemStatus.valid) {
throw new Error(`CheckState failed: ${stepItem.name}'s form status is not valid. errmsg: ${formItemStatus.errorMsg}`);
}
}
}
stepIndex++;
}
index++;
}
}
async run(scripts: StepList) {
if (scripts.length === 0) {
return;
}
await this.execScripts(scripts);
}
} | the_stack |
import * as am5 from "@amcharts/amcharts5";
import * as am5xy from "@amcharts/amcharts5/xy";
import am5themes_Animated from "@amcharts/amcharts5/themes/Animated";
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
const root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
const chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: true,
panY: true,
wheelY: "zoomXY"
}));
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
const xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
maxDeviation:1,
renderer: am5xy.AxisRendererX.new(root, {
pan:"zoom"
}),
tooltip: am5.Tooltip.new(root, {})
}));
xAxis.children.moveValue(am5.Label.new(root, {
text: "GDP per Capita, USD",
x: am5.p50,
centerX: am5.p50
}), xAxis.children.length - 1);
const yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
maxDeviation:1,
renderer: am5xy.AxisRendererY.new(root, {
pan:"zoom"
}),
tooltip: am5.Tooltip.new(root, {})
}));
yAxis.children.moveValue(am5.Label.new(root, {
rotation: -90,
text: "Life expectancy, years",
y: am5.p50,
centerX: am5.p50
}), 0);
// Create series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
const series = chart.series.push(am5xy.LineSeries.new(root, {
calculateAggregates: true,
xAxis: xAxis,
yAxis: yAxis,
valueYField: "y",
valueXField: "x",
valueField: "value",
tooltip: am5.Tooltip.new(root, {
pointerOrientation: "horizontal",
labelText: "[bold]{title}[/]\nLife expectancy: {valueY.formatNumber('#.0')}\nGDP: {valueX.formatNumber('#,###.')}\nPopulation: {value.formatNumber('#,###.')}"
})
}));
series.strokes.template.set("visible", false);
// Add bullet
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Bullets
const circleTemplate: am5.Template<am5.Circle> = am5.Template.new({});
circleTemplate.adapters.add("fill", (fill, target: any) => {
let dataItem = target.dataItem;
if (dataItem) {
return am5.Color.fromString(dataItem.dataContext.color);
}
return fill
});
series.bullets.push(() => {
const bulletCircle = am5.Circle.new(root, {
radius: 5,
fill: series.get("fill"),
fillOpacity: 0.8
}, circleTemplate);
return am5.Bullet.new(root, {
sprite: bulletCircle
});
});
// Add heat rule
// https://www.amcharts.com/docs/v5/concepts/settings/heat-rules/
series.set("heatRules", [{
target: circleTemplate,
min: 3,
max: 60,
dataField: "value",
key: "radius"
}]);
// Set data
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Setting_data
series.data.setAll([
{
"title": "Afghanistan",
"id": "AF",
"color": "#eea638",
"continent": "asia",
"x": 1349.69694102398,
"y": 60.524,
"value": 33397058
},
{
"title": "Albania",
"id": "AL",
"color": "#d8854f",
"continent": "europe",
"x": 6969.30628256456,
"y": 77.185,
"value": 3227373
},
{
"title": "Algeria",
"id": "DZ",
"color": "#de4c4f",
"continent": "africa",
"x": 6419.12782939372,
"y": 70.874,
"value": 36485828
},
{
"title": "Angola",
"id": "AO",
"color": "#de4c4f",
"continent": "africa",
"x": 5838.15537582502,
"y": 51.498,
"value": 20162517
},
{
"title": "Argentina",
"id": "AR",
"color": "#86a965",
"continent": "south_america",
"x": 15714.1031814398,
"y": 76.128,
"value": 41118986
},
{
"title": "Armenia",
"id": "AM",
"color": "#d8854f",
"continent": "europe",
"x": 5059.0879636443,
"y": 74.469,
"value": 3108972
},
{
"title": "Australia",
"id": "AU",
"color": "#8aabb0",
"continent": "australia",
"x": 36064.7372768548,
"y": 82.364,
"value": 22918688
},
{
"title": "Austria",
"id": "AT",
"color": "#d8854f",
"continent": "europe",
"x": 36731.6287741081,
"y": 80.965,
"value": 8428915
},
{
"title": "Azerbaijan",
"id": "AZ",
"color": "#d8854f",
"continent": "europe",
"x": 9291.02626998762,
"y": 70.686,
"value": 9421233
},
{
"title": "Bahrain",
"id": "BH",
"color": "#eea638",
"continent": "asia",
"x": 24472.896235865,
"y": 76.474,
"value": 1359485
},
{
"title": "Bangladesh",
"id": "BD",
"color": "#eea638",
"continent": "asia",
"x": 1792.55023464123,
"y": 70.258,
"value": 152408774
},
{
"title": "Belarus",
"id": "BY",
"color": "#d8854f",
"continent": "europe",
"x": 13515.1610255056,
"y": 69.829,
"value": 9527498
},
{
"title": "Belgium",
"id": "BE",
"color": "#d8854f",
"continent": "europe",
"x": 32585.0119650436,
"y": 80.373,
"value": 10787788
},
{
"title": "Benin",
"id": "BJ",
"color": "#de4c4f",
"continent": "africa",
"x": 1464.13825459126,
"y": 59.165,
"value": 9351838
},
{
"title": "Bhutan",
"id": "BT",
"color": "#eea638",
"continent": "asia",
"x": 6130.86235464324,
"y": 67.888,
"value": 750443
},
{
"title": "Bolivia",
"id": "BO",
"color": "#86a965",
"continent": "south_america",
"x": 4363.43264453337,
"y": 66.969,
"value": 10248042
},
{
"title": "Bosnia and Herzegovina",
"id": "BA",
"color": "#d8854f",
"continent": "europe",
"x": 7664.15281166303,
"y": 76.211,
"value": 3744235
},
{
"title": "Botswana",
"id": "BW",
"color": "#de4c4f",
"continent": "africa",
"x": 14045.9403255843,
"y": 47.152,
"value": 2053237
},
{
"title": "Brazil",
"id": "BR",
"color": "#86a965",
"continent": "south_america",
"x": 10383.5405937283,
"y": 73.667,
"value": 198360943
},
{
"title": "Brunei",
"id": "BN",
"color": "#eea638",
"continent": "asia",
"x": 45658.2532642054,
"y": 78.35,
"value": 412892
},
{
"title": "Bulgaria",
"id": "BG",
"color": "#d8854f",
"continent": "europe",
"x": 11669.7223127119,
"y": 73.448,
"value": 7397873
},
{
"title": "Burkina Faso",
"id": "BF",
"color": "#de4c4f",
"continent": "africa",
"x": 1363.77981282077,
"y": 55.932,
"value": 17481984
},
{
"title": "Burundi",
"id": "BI",
"color": "#de4c4f",
"continent": "africa",
"x": 484.090924612833,
"y": 53.637,
"value": 8749387
},
{
"title": "Cambodia",
"id": "KH",
"color": "#eea638",
"continent": "asia",
"x": 2076.68958647462,
"y": 71.577,
"value": 14478320
},
{
"title": "Cameroon",
"id": "CM",
"color": "#de4c4f",
"continent": "africa",
"x": 2094.09541317011,
"y": 54.61,
"value": 20468943
},
{
"title": "Canada",
"id": "CA",
"color": "#a7a737",
"continent": "north_america",
"x": 35992.8327204722,
"y": 81.323,
"value": 34674708
},
{
"title": "Cape Verde",
"id": "CV",
"color": "#de4c4f",
"continent": "africa",
"x": 3896.04113919638,
"y": 74.771,
"value": 505335
},
{
"title": "Central African Rep.",
"id": "CF",
"color": "#de4c4f",
"continent": "africa",
"x": 718.264633200085,
"y": 49.517,
"value": 4575586
},
{
"title": "Chad",
"id": "TD",
"color": "#de4c4f",
"continent": "africa",
"x": 1768.88201756553,
"y": 50.724,
"value": 11830573
},
{
"title": "Chile",
"id": "CL",
"color": "#86a965",
"continent": "south_america",
"x": 15403.7608144625,
"y": 79.691,
"value": 17423214
},
{
"title": "China",
"id": "CN",
"color": "#eea638",
"continent": "asia",
"x": 9501.57424554247,
"y": 75.178,
"value": 1353600687
},
{
"title": "Colombia",
"id": "CO",
"color": "#86a965",
"continent": "south_america",
"x": 8035.65638212719,
"y": 73.835,
"value": 47550708
},
{
"title": "Comoros",
"id": "KM",
"color": "#de4c4f",
"continent": "africa",
"x": 1027.40854349726,
"y": 60.661,
"value": 773344
},
{
"title": "Congo, Dem. Rep.",
"id": "CD",
"color": "#de4c4f",
"continent": "africa",
"x": 403.164594003407,
"y": 49.643,
"value": 69575394
},
{
"title": "Congo, Rep.",
"id": "CG",
"color": "#de4c4f",
"continent": "africa",
"x": 4106.51173855966,
"y": 58.32,
"value": 4233063
},
{
"title": "Costa Rica",
"id": "CR",
"color": "#a7a737",
"continent": "north_america",
"x": 10827.6787293035,
"y": 79.712,
"value": 4793725
},
{
"title": "Cote d'Ivoire",
"id": "CI",
"color": "#de4c4f",
"continent": "africa",
"x": 1491.51631215108,
"y": 50.367,
"value": 20594615
},
{
"title": "Croatia",
"id": "HR",
"color": "#d8854f",
"continent": "europe",
"x": 13388.9902780816,
"y": 76.881,
"value": 4387376
},
{
"title": "Cuba",
"id": "CU",
"color": "#a7a737",
"continent": "north_america",
"x": 10197.4191892126,
"y": 79.088,
"value": 11249266
},
{
"title": "Cyprus",
"id": "CY",
"color": "#d8854f",
"continent": "europe",
"x": 23092.089792339,
"y": 79.674,
"value": 1129166
},
{
"title": "Czech Rep.",
"id": "CZ",
"color": "#d8854f",
"continent": "europe",
"x": 22565.2975367042,
"y": 77.552,
"value": 10565678
},
{
"title": "Denmark",
"id": "DK",
"color": "#d8854f",
"continent": "europe",
"x": 32731.2903910132,
"y": 79.251,
"value": 5592738
},
{
"title": "Djibouti",
"id": "DJ",
"color": "#de4c4f",
"continent": "africa",
"x": 2244.60241376688,
"y": 61.319,
"value": 922708
},
{
"title": "Dominican Rep.",
"id": "DO",
"color": "#a7a737",
"continent": "north_america",
"x": 6978.89657264408,
"y": 73.181,
"value": 10183339
},
{
"title": "Ecuador",
"id": "EC",
"color": "#86a965",
"continent": "south_america",
"x": 7903.09487034651,
"y": 76.195,
"value": 14864987
},
{
"title": "Egypt",
"id": "EG",
"color": "#de4c4f",
"continent": "africa",
"x": 6013.821462967,
"y": 70.933,
"value": 83958369
},
{
"title": "El Salvador",
"id": "SV",
"color": "#a7a737",
"continent": "north_america",
"x": 5833.63022804714,
"y": 72.361,
"value": 6264129
},
{
"title": "Equatorial Guinea",
"id": "GQ",
"color": "#de4c4f",
"continent": "africa",
"x": 13499.2115504397,
"y": 52.562,
"value": 740471
},
{
"title": "Eritrea",
"id": "ER",
"color": "#de4c4f",
"continent": "africa",
"x": 613.716963797415,
"y": 62.329,
"value": 5580862
},
{
"title": "Estonia",
"id": "EE",
"color": "#d8854f",
"continent": "europe",
"x": 18858.0538247661,
"y": 74.335,
"value": 1339762
},
{
"title": "Ethiopia",
"id": "ET",
"color": "#de4c4f",
"continent": "africa",
"x": 958.694705985043,
"y": 62.983,
"value": 86538534
},
{
"title": "Fiji",
"id": "FJ",
"color": "#8aabb0",
"continent": "australia",
"x": 4195.03497178682,
"y": 69.626,
"value": 875822
},
{
"title": "Finland",
"id": "FI",
"color": "#d8854f",
"continent": "europe",
"x": 31551.9534459533,
"y": 80.362,
"value": 5402627
},
{
"title": "France",
"id": "FR",
"color": "#d8854f",
"continent": "europe",
"x": 29896.4182238854,
"y": 81.663,
"value": 63457777
},
{
"title": "Gabon",
"id": "GA",
"color": "#de4c4f",
"continent": "africa",
"x": 13853.4616556007,
"y": 63.115,
"value": 1563873
},
{
"title": "Gambia",
"id": "GM",
"color": "#de4c4f",
"continent": "africa",
"x": 747.68096900917,
"y": 58.59,
"value": 1824777
},
{
"title": "Georgia",
"id": "GE",
"color": "#d8854f",
"continent": "europe",
"x": 4943.23814339098,
"y": 74.162,
"value": 4304363
},
{
"title": "Germany",
"id": "DE",
"color": "#d8854f",
"continent": "europe",
"x": 34131.8745974324,
"y": 80.578,
"value": 81990837
},
{
"title": "Ghana",
"id": "GH",
"color": "#de4c4f",
"continent": "africa",
"x": 1728.47847396661,
"y": 60.979,
"value": 25545939
},
{
"title": "Greece",
"id": "GR",
"color": "#d8854f",
"continent": "europe",
"x": 21811.3302462212,
"y": 80.593,
"value": 11418878
},
{
"title": "Guatemala",
"id": "GT",
"color": "#a7a737",
"continent": "north_america",
"x": 5290.75202738533,
"y": 71.77,
"value": 15137569
},
{
"title": "Guinea",
"id": "GN",
"color": "#de4c4f",
"continent": "africa",
"x": 965.699260160386,
"y": 55.865,
"value": 10480710
},
{
"title": "Guinea-Bissau",
"id": "GW",
"color": "#de4c4f",
"continent": "africa",
"x": 593.074251034428,
"y": 54.054,
"value": 1579632
},
{
"title": "Guyana",
"id": "GY",
"color": "#86a965",
"continent": "south_america",
"x": 4265.10644905906,
"y": 66.134,
"value": 757623
},
{
"title": "Haiti",
"id": "HT",
"color": "#a7a737",
"continent": "north_america",
"x": 1180.36719611488,
"y": 62.746,
"value": 10255644
},
{
"title": "Honduras",
"id": "HN",
"color": "#a7a737",
"continent": "north_america",
"x": 3615.1565803195,
"y": 73.503,
"value": 7912032
},
{
"title": "Hong Kong, China",
"id": "HK",
"color": "#eea638",
"continent": "asia",
"x": 43854.4129062733,
"y": 83.199,
"value": 7196450
},
{
"title": "Hungary",
"id": "HU",
"color": "#d8854f",
"continent": "europe",
"x": 17065.6047342876,
"y": 74.491,
"value": 9949589
},
{
"title": "Iceland",
"id": "IS",
"color": "#d8854f",
"continent": "europe",
"x": 34371.1793657215,
"y": 81.96,
"value": 328290
},
{
"title": "India",
"id": "IN",
"color": "#eea638",
"continent": "asia",
"x": 3229.14788745778,
"y": 66.168,
"value": 1258350971
},
{
"title": "Indonesia",
"id": "ID",
"color": "#eea638",
"continent": "asia",
"x": 4379.69981934714,
"y": 70.624,
"value": 244769110
},
{
"title": "Iran",
"id": "IR",
"color": "#eea638",
"continent": "asia",
"x": 12325.1280322371,
"y": 73.736,
"value": 75611798
},
{
"title": "Iraq",
"id": "IQ",
"color": "#eea638",
"continent": "asia",
"x": 4160.84708826172,
"y": 69.181,
"value": 33703068
},
{
"title": "Ireland",
"id": "IE",
"color": "#d8854f",
"continent": "europe",
"x": 35856.1099094562,
"y": 80.531,
"value": 4579498
},
{
"title": "Israel",
"id": "IL",
"color": "#eea638",
"continent": "asia",
"x": 27321.205182135,
"y": 81.641,
"value": 7694670
},
{
"title": "Italy",
"id": "IT",
"color": "#d8854f",
"continent": "europe",
"x": 25811.7393303661,
"y": 82.235,
"value": 60964145
},
{
"title": "Jamaica",
"id": "JM",
"color": "#a7a737",
"continent": "north_america",
"x": 6945.70274711582,
"y": 73.338,
"value": 2761331
},
{
"title": "Japan",
"id": "JP",
"color": "#eea638",
"continent": "asia",
"x": 31273.9932002261,
"y": 83.418,
"value": 126434653
},
{
"title": "Jordan",
"id": "JO",
"color": "#eea638",
"continent": "asia",
"x": 5242.51826246118,
"y": 73.7,
"value": 6457260
},
{
"title": "Kazakhstan",
"id": "KZ",
"color": "#eea638",
"continent": "asia",
"x": 11982.6526657273,
"y": 66.394,
"value": 16381297
},
{
"title": "Kenya",
"id": "KE",
"color": "#de4c4f",
"continent": "africa",
"x": 1517.69754383602,
"y": 61.115,
"value": 42749418
},
{
"title": "Korea, Dem. Rep.",
"id": "KP",
"color": "#eea638",
"continent": "asia",
"x": 1540.44018783769,
"y": 69.701,
"value": 24553672
},
{
"title": "Korea, Rep.",
"id": "KR",
"color": "#eea638",
"continent": "asia",
"x": 26199.4035642374,
"y": 81.294,
"value": 48588326
},
{
"title": "Kuwait",
"id": "KW",
"color": "#eea638",
"continent": "asia",
"x": 42045.05923634,
"y": 74.186,
"value": 2891553
},
{
"title": "Kyrgyzstan",
"id": "KG",
"color": "#eea638",
"continent": "asia",
"x": 2078.20824171434,
"y": 67.37,
"value": 5448085
},
{
"title": "Laos",
"id": "LA",
"color": "#eea638",
"continent": "asia",
"x": 2807.04752629832,
"y": 67.865,
"value": 6373934
},
{
"title": "Latvia",
"id": "LV",
"color": "#d8854f",
"continent": "europe",
"x": 15575.2762808015,
"y": 72.045,
"value": 2234572
},
{
"title": "Lebanon",
"id": "LB",
"color": "#eea638",
"continent": "asia",
"x": 13711.975683994,
"y": 79.716,
"value": 4291719
},
{
"title": "Lesotho",
"id": "LS",
"color": "#de4c4f",
"continent": "africa",
"x": 1970.47114938861,
"y": 48.947,
"value": 2216850
},
{
"title": "Liberia",
"id": "LR",
"color": "#de4c4f",
"continent": "africa",
"x": 499.809082037359,
"y": 60.23,
"value": 4244684
},
{
"title": "Libya",
"id": "LY",
"color": "#de4c4f",
"continent": "africa",
"x": 9136.34462458268,
"y": 75.13,
"value": 6469497
},
{
"title": "Lithuania",
"id": "LT",
"color": "#d8854f",
"continent": "europe",
"x": 18469.9748244583,
"y": 71.942,
"value": 3292454
},
{
"title": "Macedonia, FYR",
"id": "MK",
"color": "#d8854f",
"continent": "europe",
"x": 8918.81131421927,
"y": 75.041,
"value": 2066785
},
{
"title": "Madagascar",
"id": "MG",
"color": "#de4c4f",
"continent": "africa",
"x": 981.478674981018,
"y": 64.28,
"value": 21928518
},
{
"title": "Malawi",
"id": "MW",
"color": "#de4c4f",
"continent": "africa",
"x": 848.191013907702,
"y": 54.798,
"value": 15882815
},
{
"title": "Malaysia",
"id": "MY",
"color": "#eea638",
"continent": "asia",
"x": 14202.2119391177,
"y": 74.836,
"value": 29321798
},
{
"title": "Mali",
"id": "ML",
"color": "#de4c4f",
"continent": "africa",
"x": 1070.55152828447,
"y": 54.622,
"value": 16318897
},
{
"title": "Mauritania",
"id": "MR",
"color": "#de4c4f",
"continent": "africa",
"x": 1898.35192059663,
"y": 61.39,
"value": 3622961
},
{
"title": "Mauritius",
"id": "MU",
"color": "#de4c4f",
"continent": "africa",
"x": 13082.7750766535,
"y": 73.453,
"value": 1313803
},
{
"title": "Mexico",
"id": "MX",
"color": "#a7a737",
"continent": "north_america",
"x": 12030.3862129571,
"y": 77.281,
"value": 116146768
},
{
"title": "Moldova",
"id": "MD",
"color": "#d8854f",
"continent": "europe",
"x": 2963.99305976246,
"y": 68.779,
"value": 3519266
},
{
"title": "Mongolia",
"id": "MN",
"color": "#eea638",
"continent": "asia",
"x": 4300.13326887206,
"y": 67.286,
"value": 2844081
},
{
"title": "Montenegro",
"id": "ME",
"color": "#d8854f",
"continent": "europe",
"x": 10064.1609429569,
"y": 74.715,
"value": 632796
},
{
"title": "Morocco",
"id": "MA",
"color": "#de4c4f",
"continent": "africa",
"x": 4514.51993561297,
"y": 70.714,
"value": 32598536
},
{
"title": "Mozambique",
"id": "MZ",
"color": "#de4c4f",
"continent": "africa",
"x": 1058.44192915498,
"y": 49.91,
"value": 24475186
},
{
"title": "Myanmar",
"id": "MM",
"color": "#eea638",
"continent": "asia",
"x": 1657.04593430092,
"y": 65.009,
"value": 48724387
},
{
"title": "Namibia",
"id": "NA",
"color": "#de4c4f",
"continent": "africa",
"x": 5535.83674233219,
"y": 64.014,
"value": 2364433
},
{
"title": "Nepal",
"id": "NP",
"color": "#eea638",
"continent": "asia",
"x": 1264.49264527071,
"y": 67.989,
"value": 31011137
},
{
"title": "Netherlands",
"id": "NL",
"color": "#d8854f",
"continent": "europe",
"x": 36257.0874018501,
"y": 80.906,
"value": 16714228
},
{
"title": "New Zealand",
"id": "NZ",
"color": "#8aabb0",
"continent": "australia",
"x": 25223.5351395532,
"y": 80.982,
"value": 4461257
},
{
"title": "Nicaragua",
"id": "NI",
"color": "#a7a737",
"continent": "north_america",
"x": 3098.48351674394,
"y": 74.515,
"value": 5954898
},
{
"title": "Niger",
"id": "NE",
"color": "#de4c4f",
"continent": "africa",
"x": 706.79424834157,
"y": 57.934,
"value": 16644339
},
{
"title": "Nigeria",
"id": "NG",
"color": "#de4c4f",
"continent": "africa",
"x": 2483.98940927953,
"y": 52.116,
"value": 166629383
},
{
"title": "Norway",
"id": "NO",
"color": "#d8854f",
"continent": "europe",
"x": 47383.6245293861,
"y": 81.367,
"value": 4960482
},
{
"title": "Oman",
"id": "OM",
"color": "#eea638",
"continent": "asia",
"x": 26292.8480723207,
"y": 76.287,
"value": 2904037
},
{
"title": "Pakistan",
"id": "PK",
"color": "#eea638",
"continent": "asia",
"x": 2681.12078190231,
"y": 66.42,
"value": 179951140
},
{
"title": "Panama",
"id": "PA",
"color": "#a7a737",
"continent": "north_america",
"x": 13607.1433621853,
"y": 77.342,
"value": 3624991
},
{
"title": "Papua New Guinea",
"id": "PG",
"color": "#8aabb0",
"continent": "australia",
"x": 2391.5795121997,
"y": 62.288,
"value": 7170112
},
{
"title": "Paraguay",
"id": "PY",
"color": "#86a965",
"continent": "south_america",
"x": 4467.15872465943,
"y": 72.181,
"value": 6682943
},
{
"title": "Peru",
"id": "PE",
"color": "#86a965",
"continent": "south_america",
"x": 9277.57076044381,
"y": 74.525,
"value": 29733829
},
{
"title": "Philippines",
"id": "PH",
"color": "#eea638",
"continent": "asia",
"x": 3677.10197520058,
"y": 68.538,
"value": 96471461
},
{
"title": "Poland",
"id": "PL",
"color": "#d8854f",
"continent": "europe",
"x": 17851.9477668397,
"y": 76.239,
"value": 38317090
},
{
"title": "Portugal",
"id": "PT",
"color": "#d8854f",
"continent": "europe",
"x": 19576.4108427574,
"y": 79.732,
"value": 10699333
},
{
"title": "Romania",
"id": "RO",
"color": "#d8854f",
"continent": "europe",
"x": 11058.1809744544,
"y": 73.718,
"value": 21387517
},
{
"title": "Russia",
"id": "RU",
"color": "#d8854f",
"continent": "europe",
"x": 15427.6167470064,
"y": 67.874,
"value": 142703181
},
{
"title": "Rwanda",
"id": "RW",
"color": "#de4c4f",
"continent": "africa",
"x": 1223.52570881561,
"y": 63.563,
"value": 11271786
},
{
"title": "Saudi Arabia",
"id": "SA",
"color": "#eea638",
"continent": "asia",
"x": 26259.6213479005,
"y": 75.264,
"value": 28705133
},
{
"title": "Senegal",
"id": "SN",
"color": "#de4c4f",
"continent": "africa",
"x": 1753.48800936096,
"y": 63.3,
"value": 13107945
},
{
"title": "Serbia",
"id": "RS",
"color": "#d8854f",
"continent": "europe",
"x": 9335.95911484282,
"y": 73.934,
"value": 9846582
},
{
"title": "Sierra Leone",
"id": "SL",
"color": "#de4c4f",
"continent": "africa",
"x": 1072.95787930719,
"y": 45.338,
"value": 6126450
},
{
"title": "Singapore",
"id": "SG",
"color": "#eea638",
"continent": "asia",
"x": 49381.9560054179,
"y": 82.155,
"value": 5256278
},
{
"title": "Slovak Republic",
"id": "SK",
"color": "#d8854f",
"continent": "europe",
"x": 20780.9857840812,
"y": 75.272,
"value": 5480332
},
{
"title": "Slovenia",
"id": "SI",
"color": "#d8854f",
"continent": "europe",
"x": 23986.8506836646,
"y": 79.444,
"value": 2040057
},
{
"title": "Solomon Islands",
"id": "SB",
"color": "#8aabb0",
"continent": "australia",
"x": 2024.23067334134,
"y": 67.465,
"value": 566481
},
{
"title": "Somalia",
"id": "SO",
"color": "#de4c4f",
"continent": "africa",
"x": 953.275713662563,
"y": 54,
"value": 9797445
},
{
"title": "South Africa",
"id": "ZA",
"color": "#de4c4f",
"continent": "africa",
"x": 9657.25275417241,
"y": 56.271,
"value": 50738255
},
{
"title": "South Sudan",
"id": "SS",
"color": "#de4c4f",
"continent": "africa",
"x": 1433.03720057714,
"y": 54.666,
"value": 10386101
},
{
"title": "Spain",
"id": "ES",
"color": "#d8854f",
"continent": "europe",
"x": 26457.7572559653,
"y": 81.958,
"value": 46771596
},
{
"title": "Sri Lanka",
"id": "LK",
"color": "#eea638",
"continent": "asia",
"x": 5182.66658831813,
"y": 74.116,
"value": 21223550
},
{
"title": "Sudan",
"id": "SD",
"color": "#de4c4f",
"continent": "africa",
"x": 2917.61641581811,
"y": 61.875,
"value": 35335982
},
{
"title": "Suriname",
"id": "SR",
"color": "#86a965",
"continent": "south_america",
"x": 8979.80549248675,
"y": 70.794,
"value": 534175
},
{
"title": "Swaziland",
"id": "SZ",
"color": "#de4c4f",
"continent": "africa",
"x": 4979.704126513,
"y": 48.91,
"value": 1220408
},
{
"title": "Sweden",
"id": "SE",
"color": "#d8854f",
"continent": "europe",
"x": 34530.2628238397,
"y": 81.69,
"value": 9495392
},
{
"title": "Switzerland",
"id": "CH",
"color": "#d8854f",
"continent": "europe",
"x": 37678.3928108684,
"y": 82.471,
"value": 7733709
},
{
"title": "Syria",
"id": "SY",
"color": "#eea638",
"continent": "asia",
"x": 4432.01553897559,
"y": 71,
"value": 21117690
},
{
"title": "Taiwan",
"id": "TW",
"color": "#eea638",
"continent": "asia",
"x": 32840.8623523232,
"y": 79.45,
"value": 23114000
},
{
"title": "Tajikistan",
"id": "TJ",
"color": "#eea638",
"continent": "asia",
"x": 1952.10042735043,
"y": 67.118,
"value": 7078755
},
{
"title": "Tanzania",
"id": "TZ",
"color": "#de4c4f",
"continent": "africa",
"x": 1330.05614548839,
"y": 60.885,
"value": 47656367
},
{
"title": "Thailand",
"id": "TH",
"color": "#eea638",
"continent": "asia",
"x": 8451.15964058768,
"y": 74.225,
"value": 69892142
},
{
"title": "Timor-Leste",
"id": "TL",
"color": "#eea638",
"continent": "asia",
"x": 3466.08281224683,
"y": 67.033,
"value": 1187194
},
{
"title": "Togo",
"id": "TG",
"color": "#de4c4f",
"continent": "africa",
"x": 975.396852535221,
"y": 56.198,
"value": 6283092
},
{
"title": "Trinidad and Tobago",
"id": "TT",
"color": "#a7a737",
"continent": "north_america",
"x": 17182.0954558471,
"y": 69.761,
"value": 1350999
},
{
"title": "Tunisia",
"id": "TN",
"color": "#de4c4f",
"continent": "africa",
"x": 7620.47056462131,
"y": 75.632,
"value": 10704948
},
{
"title": "Turkey",
"id": "TR",
"color": "#d8854f",
"continent": "europe",
"x": 9287.29312549815,
"y": 74.938,
"value": 74508771
},
{
"title": "Turkmenistan",
"id": "TM",
"color": "#eea638",
"continent": "asia",
"x": 7921.2740619558,
"y": 65.299,
"value": 5169660
},
{
"title": "Uganda",
"id": "UG",
"color": "#de4c4f",
"continent": "africa",
"x": 1251.09807015907,
"y": 58.668,
"value": 35620977
},
{
"title": "Ukraine",
"id": "UA",
"color": "#d8854f",
"continent": "europe",
"x": 6389.58597273257,
"y": 68.414,
"value": 44940268
},
{
"title": "United Arab Emirates",
"id": "AE",
"color": "#eea638",
"continent": "asia",
"x": 31980.24143802,
"y": 76.671,
"value": 8105873
},
{
"title": "United Kingdom",
"id": "GB",
"color": "#d8854f",
"continent": "europe",
"x": 31295.1431522074,
"y": 80.396,
"value": 62798099
},
{
"title": "United States",
"id": "US",
"color": "#a7a737",
"continent": "north_america",
"x": 42296.2316492477,
"y": 78.797,
"value": 315791284
},
{
"title": "Uruguay",
"id": "UY",
"color": "#86a965",
"continent": "south_america",
"x": 13179.2310803465,
"y": 77.084,
"value": 3391428
},
{
"title": "Uzbekistan",
"id": "UZ",
"color": "#eea638",
"continent": "asia",
"x": 3117.27386553102,
"y": 68.117,
"value": 28077486
},
{
"title": "Venezuela",
"id": "VE",
"color": "#86a965",
"continent": "south_america",
"x": 11685.1771941737,
"y": 74.477,
"value": 29890694
},
{
"title": "West Bank and Gaza",
"id": "PS",
"color": "#eea638",
"continent": "asia",
"x": 4328.39115760087,
"y": 73.018,
"value": 4270791
},
{
"title": "Vietnam",
"id": "VN",
"color": "#eea638",
"continent": "asia",
"x": 3073.64961158389,
"y": 75.793,
"value": 89730274
},
{
"title": "Yemen, Rep.",
"id": "YE",
"color": "#eea638",
"continent": "asia",
"x": 2043.7877761328,
"y": 62.923,
"value": 25569263
},
{
"title": "Zambia",
"id": "ZM",
"color": "#de4c4f",
"continent": "africa",
"x": 1550.92385858124,
"y": 57.037,
"value": 13883577
},
{
"title": "Zimbabwe",
"id": "ZW",
"color": "#de4c4f",
"continent": "africa",
"x": 545.344601005788,
"y": 58.142,
"value": 13013678
}
]);
const background = series.get("tooltip").get("background");
background.set("stroke", root.interfaceColors.get("alternativeBackground"));
background.adapters.add("fill", (fill, target) => {
let dataItem = target.dataItem;
if (dataItem && dataItem.dataContext) {
return am5.Color.fromString(dataItem.dataContext.color);
}
return fill
});
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
chart.set("cursor", am5xy.XYCursor.new(root, {
xAxis: xAxis,
yAxis: yAxis,
snapToSeries: [series]
}));
// Add scrollbars
// https://www.amcharts.com/docs/v5/charts/xy-chart/scrollbars/
chart.set("scrollbarX", am5.Scrollbar.new(root, {
orientation: "horizontal"
}));
chart.set("scrollbarY", am5.Scrollbar.new(root, {
orientation: "vertical"
}));
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/#Forcing_appearance_animation
series.appear(1000);
chart.appear(1000, 100); | the_stack |
import clone = require('clone');
import sprintf = require('sprintf');
import agile_keychain_crypto = require('./agile_keychain_crypto');
import asyncutil = require('./base/asyncutil');
import collectionutil = require('./base/collectionutil');
import dateutil = require('./base/dateutil');
import err_util = require('./base/err_util');
import event_stream = require('./base/event_stream');
import key_agent = require('./key_agent');
import sha1 = require('./crypto/sha1');
import stringutil = require('./base/stringutil');
// typedef for item type codes
export interface ItemType extends String {}
/** Constants for the different types of item
* that a vault may contain.
*
* Item type codes are taken from 1Password v4
*/
export class ItemTypes {
// The most common type, for logins and other web forms
static LOGIN = <ItemType>'webforms.WebForm';
// Other item types
static CREDIT_CARD = <ItemType>'wallet.financial.CreditCard';
static ROUTER = <ItemType>'wallet.computer.Router';
static SECURE_NOTE = <ItemType>'securenotes.SecureNote';
static PASSWORD = <ItemType>'passwords.Password';
static EMAIL_ACCOUNT = <ItemType>'wallet.onlineservices.Email.v2';
static BANK_ACCOUNT = <ItemType>'wallet.financial.BankAccountUS';
static DATABASE = <ItemType>'wallet.computer.Database';
static DRIVERS_LICENSE = <ItemType>'wallet.government.DriversLicense';
static MEMBERSHIP = <ItemType>'wallet.membership.Membership';
static HUNTING_LICENSE = <ItemType>'wallet.government.HuntingLicense';
static PASSPORT = <ItemType>'wallet.government.Passport';
static REWARD_PROGRAM = <ItemType>'wallet.membership.RewardProgram';
static SERVER = <ItemType>'wallet.computer.UnixServer';
static SOCIAL_SECURITY = <ItemType>'wallet.government.SsnUS';
static SOFTWARE_LICENSE = <ItemType>'wallet.computer.License';
static IDENTITY = <ItemType>'identities.Identity';
// Non-item types
static FOLDER = <ItemType>'system.folder.Regular';
static SAVED_SEARCH = <ItemType>'system.folder.SavedSearch';
// Marker type used to deleted items. The ID is preserved
// but the type is set to Tombstone and all other data
// is removed
static TOMBSTONE = <ItemType>'system.Tombstone';
}
/** Map of item type codes to human-readable item type names */
export var ITEM_TYPES: ItemTypeMap = {
'webforms.WebForm': {
name: 'Login',
shortAlias: 'login',
},
'wallet.financial.CreditCard': {
name: 'Credit Card',
shortAlias: 'card',
},
'wallet.computer.Router': {
name: 'Wireless Router',
shortAlias: 'router',
},
'securenotes.SecureNote': {
name: 'Secure Note',
shortAlias: 'note',
},
'passwords.Password': {
name: 'Password',
shortAlias: 'pass',
},
'wallet.onlineservices.Email.v2': {
name: 'Email Account',
shortAlias: 'email',
},
'system.folder.Regular': {
name: 'Folder',
shortAlias: 'folder',
},
'system.folder.SavedSearch': {
name: 'Smart Folder',
shortAlias: 'smart-folder',
},
'wallet.financial.BankAccountUS': {
name: 'Bank Account',
shortAlias: 'bank',
},
'wallet.computer.Database': {
name: 'Database',
shortAlias: 'db',
},
'wallet.government.DriversLicense': {
name: "Driver's License",
shortAlias: 'driver',
},
'wallet.membership.Membership': {
name: 'Membership',
shortAlias: 'membership',
},
'wallet.government.HuntingLicense': {
name: 'Outdoor License',
shortAlias: 'outdoor',
},
'wallet.government.Passport': {
name: 'Passport',
shortAlias: 'passport',
},
'wallet.membership.RewardProgram': {
name: 'Reward Program',
shortAlias: 'reward',
},
'wallet.computer.UnixServer': {
name: 'Unix Server',
shortAlias: 'server',
},
'wallet.government.SsnUS': {
name: 'Social Security Number',
shortAlias: 'social',
},
'wallet.computer.License': {
name: 'Software License',
shortAlias: 'software',
},
'identities.Identity': {
name: 'Identity',
shortAlias: 'id',
},
// internal entry type created for items
// that have been removed from the trash
'system.Tombstone': {
name: 'Tombstone',
shortAlias: 'tombstone',
},
};
export interface ItemState {
uuid: string;
revision: string;
deleted: boolean;
}
/** A convenience interface for passing around an item
* and its contents together.
*/
export interface ItemAndContent {
item: Item;
content: ItemContent;
}
export interface ItemTypeInfo {
name: string;
shortAlias: string;
}
export interface ItemTypeMap {
// map of ItemType -> ItemTypeInfo
[index: string]: ItemTypeInfo;
}
export class UnsavedItemError extends err_util.BaseError {
constructor() {
super('Item has not been saved to a store');
}
}
/** Represents the content of an item, usually stored
* encrypted in a vault.
*
* ItemContent and its dependent fields are plain interfaces
* to facilitate easy (de-)serialization.
*/
export interface ItemContent {
sections: ItemSection[];
urls: ItemUrl[];
notes: string;
formFields: WebFormField[];
htmlMethod: string;
htmlAction: string;
htmlId: string;
}
/** Utility functions for creating and extracting
* data from ItemContent instances.
*/
export let ContentUtil = {
/** Creates a new ItemContent instance with all
* fields set to default values.
*/
empty(): ItemContent {
return {
sections: [],
urls: [],
notes: '',
formFields: [],
htmlMethod: '',
htmlAction: '',
htmlId: '',
};
},
/** Returns the account name associated with this item.
*
* The field used for the account name depends on the item
* type. For logins, this is the 'username' field.
*
* Returns an empty string if the item has no associated account.
*/
account(content: ItemContent): string {
let field = ContentUtil.accountField(content);
return field ? field.value : '';
},
accountField(content: ItemContent): WebFormField {
let accountFields = content.formFields.filter(
field => field.designation === 'username'
);
return accountFields.length > 0 ? accountFields[0] : null;
},
/** Returns the primary password associated with this item.
*
* This depends upon the item type. For logins, this is
* the 'password' field.
*
* Returns an empty password if the item has no associated
* account.
*/
password(content: ItemContent): string {
let field = ContentUtil.passwordField(content);
return field ? field.value : '';
},
passwordField(content: ItemContent): WebFormField {
var passFields = content.formFields.filter(
field => field.designation === 'password'
);
return passFields.length > 0 ? passFields[0] : null;
},
};
/** Represents a single item in a 1Password vault. */
export class Item {
// store which this item belongs to, or null
// if the item has not yet been saved
private store: Store;
/** Identifies the version of an item. This is an opaque
* string which is set when an item is saved to a store.
* It will change each time an item is saved.
*/
revision: string;
/** Identifies the previous version of an item. This is
* an opaque string which is set to the current revision
* just prior to a new version being saved to a store
* which supports item history. It will be updated
* each time an item is saved.
*/
parentRevision: string;
/** Unique ID for this item within the vault */
uuid: string;
/** ID of the folder that this item currently belongs to */
folderUuid: string;
faveIndex: number;
trashed: boolean;
updatedAt: Date;
createdAt: Date;
/** Item type code for this item. This is one of the values
* in the ItemTypes class.
*/
typeName: ItemType;
/** Main title for this item. */
title: string;
/** Additional metadata (eg. tags)
* which is stored unencrypted for this item.
*/
openContents: ItemOpenContents;
/** List of URLs that this item is associated with. */
locations: string[];
/** The account name or number that this item is associated with */
account: string;
/** The decrypted content of the item, either set
* via setContent() or decrypted on-demand by
* getContent()
*/
private content: ItemContent;
/** Create a new item. @p store is the store
* to associate the new item with. This can
* be changed later via saveTo().
*
* When importing an existing item or loading
* an existing item from the store, @p uuid may be non-null.
* Otherwise a random new UUID will be allocated for
* the item.
*/
constructor(store?: Store, uuid?: string) {
this.store = store;
this.uuid = uuid || agile_keychain_crypto.newUUID();
this.trashed = false;
this.typeName = ItemTypes.LOGIN;
this.folderUuid = '';
this.locations = [];
this.title = '';
}
/** Retrieves and decrypts the content of a 1Password item.
*
* In the Agile Keychain format, items are stored in two parts.
* The overview data is stored in both contents.js and replicated
* in the <UUID>.1password file for the item and is unencrypted.
*
* The item content is stored in the <UUID>.1password file and
* is encrypted using the store's master key.
*
* The item's store must be unlocked using Store.unlock() before
* item content can be retrieved.
*/
getContent(): Promise<ItemContent> {
if (this.content) {
return Promise.resolve(this.content);
} else if (!this.store) {
this.content = ContentUtil.empty();
return Promise.resolve(this.content);
}
return this.store.getContent(this);
}
setContent(content: ItemContent) {
this.content = content;
}
/** Return the raw decrypted JSON data for an item.
* This is only available for saved items.
*/
getRawDecryptedData(): Promise<string> {
if (!this.store) {
return Promise.reject<string>(new UnsavedItemError());
}
return this.store.getRawDecryptedData(this);
}
/** Save this item to its associated store */
save(): Promise<void> {
if (!this.store) {
return Promise.reject<void>(new UnsavedItemError());
}
return this.saveTo(this.store);
}
/** Save this item to the specified store */
saveTo(store: Store): Promise<void> {
if (!this.content && !this.isSaved()) {
return Promise.reject<void>(
new Error('Unable to save new item, no content set')
);
}
this.store = store;
return this.store.saveItem(this);
}
/** Remove the item from the store.
* This erases all of the item's data and leaves behind a 'tombstone'
* entry for syncing purposes.
*/
remove(): Promise<void> {
if (!this.store) {
return Promise.reject<void>(new UnsavedItemError());
}
this.typeName = ItemTypes.TOMBSTONE;
this.title = 'Unnamed';
this.trashed = true;
this.setContent(ContentUtil.empty());
this.folderUuid = '';
this.locations = [];
this.faveIndex = null;
this.openContents = null;
return this.store.saveItem(this);
}
/** Returns true if this is a 'tombstone' entry remaining from
* a deleted item. When an item is deleted, all of the properties except
* the UUID are erased and the item's type is changed to 'system.Tombstone'.
*
* These 'tombstone' markers are preserved so that deletions are synced between
* different 1Password clients.
*/
isTombstone(): boolean {
return this.typeName == ItemTypes.TOMBSTONE;
}
/** Returns true if this is a regular item - ie. not a folder,
* tombstone or saved search.
*/
isRegularItem(): boolean {
return !stringutil.startsWith(<string>this.typeName, 'system.');
}
/** Returns a shortened version of the item's UUID, suitable for disambiguation
* between different items with the same type and title.
*/
shortID(): string {
return this.uuid.slice(0, 4);
}
/** Returns the human-readable type name for this item's type. */
typeDescription(): string {
if (ITEM_TYPES[<string>this.typeName]) {
return ITEM_TYPES[<string>this.typeName].name;
} else {
return <string>this.typeName;
}
}
/** Returns true if this item has been saved to a store. */
isSaved(): boolean {
return this.store && this.updatedAt != null;
}
/** Set the last-modified time for the item to the current time.
* If the created time for the item has not been initialized, it
* is also set to the current time.
*/
updateTimestamps() {
if (!this.createdAt) {
this.createdAt = new Date();
}
// update last-modified time
var prevDate = this.updatedAt;
this.updatedAt = new Date();
// ensure that last-modified time always advances by at least one
// second from the previous time on save.
//
// This is required to ensure the 'updatedAt' time saved in contents.js
// changes since it only stores second-level resolution
if (prevDate && this.updatedAt.getTime() - prevDate.getTime() < 1000) {
this.updatedAt = new Date(prevDate.getTime() + 1000);
}
}
/** Returns the main URL associated with this item or an empty
* string if there are no associated URLs.
*/
primaryLocation(): string {
if (this.locations.length > 0) {
return this.locations[0];
} else {
return '';
}
}
/** Update item overview metadata to match the complete
* content of an item.
*
* This updates the URL list for an item.
*/
updateOverviewFromContent(content: ItemContent) {
this.locations = [];
content.urls.forEach(url => {
this.locations.push(url.url);
});
this.account = ContentUtil.account(content);
}
}
/** Content of an item which is usually stored unencrypted
* as part of the overview data.
*/
export interface ItemOpenContents {
tags: string[];
/** Indicates where this item will be displayed.
* Known values are 'Always' (show everywhere)
* and 'Never' (never shown in browser)
*/
scope: string;
}
/** A group of fields in an item. */
export interface ItemSection {
/** Internal name of the section. */
name: string;
/** User-visible title for the section. */
title: string;
fields: ItemField[];
}
/** A specific property/attribute of an item.
*
* Each field has a data type, an internal name/ID for the field,
* a user-visible title and a current value.
*/
export interface ItemField {
kind: FieldType;
name: string;
title: string;
value: any;
}
export function fieldValueString(field: ItemField) {
switch (field.kind) {
case FieldType.Date:
return dateutil.dateFromUnixTimestamp(field.value).toString();
case FieldType.MonthYear:
var month = field.value % 100;
var year = (field.value / 100) % 100;
return sprintf('%02d/%d', month, year);
default:
return field.value;
}
}
/** Type of input field in a web form. */
export enum FormFieldType {
Text,
Password,
Email,
Checkbox,
Input,
}
/** Saved value of an input field in a web form. */
export interface WebFormField {
value: string;
/** 'id' attribute of the <input> element */
id: string;
/** Name of the field. For web forms this is the 'name'
* attribute of the <input> element.
*/
name: string;
/** Type of input element used for this form field */
type: FormFieldType;
/** Purpose of the field. Known values are 'username', 'password' */
designation: string;
}
/** Entry in an item's 'Websites' list. */
export interface ItemUrl {
label: string;
url: string;
}
/** Type of data stored in a field.
* The set of types comes originally from those used
* in the 1Password Agile Keychain format.
*/
export enum FieldType {
Text,
Password,
Address,
Date,
MonthYear,
URL,
CreditCardType,
PhoneNumber,
Gender,
Email,
Menu,
}
export interface ListItemsOptions {
/** Include 'tombstone' items which are left in the store
* when an item is removed.
*/
includeTombstones?: boolean;
}
/** Specifies where an update came from when saving an item.
*/
export enum ChangeSource {
/** Indicates a change resulting from a sync with another store. */
Sync,
/** Indicates a local change. */
Local,
}
/** Interface for a store of encrypted items.
*
* A Store consists of a set of Item(s), identified by unique ID,
* plus a set of encryption keys used to encrypt the contents of
* those items.
*
* Items are versioned with an implementation-specific revision.
* Stores may keep only the last revision of an item or they
* may keep previous revisions as well.
*/
export interface Store {
/** Emits events when items are updated in the store. */
onItemUpdated: event_stream.EventStream<Item>;
/** Emits events when keys are updated in the store. */
onKeysUpdated?: event_stream.EventStream<key_agent.Key[]>;
/** Unlock the vault */
unlock(password: string): Promise<void>;
/** List the states (ID, last update time and whether deleted)
* of all items in the store.
*/
listItemStates(): Promise<ItemState[]>;
/** List all of the items in the store */
listItems(opts?: ListItemsOptions): Promise<Item[]>;
/** Load the item with a specific ID.
*
* If a revision is specified, load a specific version of an item,
* otherwise load the current version of the item.
*
* loadItem() should report an error if the item has been deleted.
* Deleted items are only available as tombstone entries in the
* list returned by listItemStates().
*/
loadItem(uuid: string, revision?: string): Promise<ItemAndContent>;
/** Save changes to the overview data and item content
* back to the store. The @p source specifies whether
* this update is a result of syncing changes
* with another store or a local modification.
*
* Saving an item assigns a new revision to it.
*/
saveItem(item: Item, source?: ChangeSource): Promise<void>;
/** Fetch and decrypt the item's secure contents. */
getContent(item: Item): Promise<ItemContent>;
/** Fetch and decrypt item's secure contents and return
* as a raw string - ie. without parsing the data and converting
* to an ItemContent instance.
*/
getRawDecryptedData(item: Item): Promise<string>;
/** Retrieve the master encryption keys for this store. */
listKeys(): Promise<key_agent.Key[]>;
/** Update the encryption keys in this store. */
saveKeys(keys: key_agent.Key[], hint: string): Promise<void>;
/** Permanently delete all data from the store.
*/
clear(): Promise<void>;
/** Return the user-provided password hint. */
passwordHint(): Promise<string>;
}
/** Represents a pair of revision strings for
* the same revision of an item in the local and cloud
* stores.
*
* Item revision formats are specific to the store
* implementation, so the same revision of an item
* that is synced between two stores (eg. a local
* store in IndexedDB in the browser and a cloud store
* in Dropbox) will have different revision strings.
*/
export interface RevisionPair {
/** The revision of the item in the local store. */
local: string;
/** The corresponding revision of the item in the
* external store.
*/
external: string;
}
/** SyncableStore provides methods for storing metadata
* to enable syncing this store with other stores.
*/
export interface SyncableStore extends Store {
/** Stores which revision of an item in a store (identified by @p storeID) was
* last synced with this store.
*/
setLastSyncedRevision(
item: Item,
storeID: string,
revision?: RevisionPair
): Promise<void>;
/** Retrieves the revision of an item in a store (identified by @p storeID)
* which was last synced with this store.
*/
getLastSyncedRevision(uuid: string, storeID: string): Promise<RevisionPair>;
/** Retrieve a map of (item ID -> last-synced revision) for
* all items in the store which have previously been synced with
* @p storeID.
*/
lastSyncRevisions(storeID: string): Promise<Map<string, RevisionPair>>;
}
/** Copy an item and its contents, using @p uuid as the ID for
* the new item. If new item is associated with @p store.
*
* The returned item will have {itemAndContent.item.revision} as
* its parentRevision and a null revision property.
*/
export function cloneItem(
itemAndContent: ItemAndContent,
uuid: string,
store?: Store
) {
let item = itemAndContent.item;
// item ID and sync data
let clonedItem = new Item(store, uuid);
clonedItem.parentRevision = item.revision;
// core metadata
clonedItem.folderUuid = item.uuid;
clonedItem.faveIndex = item.faveIndex;
clonedItem.trashed = item.trashed;
clonedItem.updatedAt = item.updatedAt;
clonedItem.createdAt = item.createdAt;
clonedItem.typeName = item.typeName;
clonedItem.title = item.title;
clonedItem.openContents = item.openContents;
clonedItem.locations = <string[]>clone(item.locations);
clonedItem.account = item.account;
// item content
let clonedContent = <ItemContent>clone(itemAndContent.content);
clonedItem.setContent(clonedContent);
return { item: clonedItem, content: clonedContent };
}
/** Generate a content-based revision ID for an item.
* Revision IDs are a hash of the item's parent revision,
* plus all of its current content.
*/
export function generateRevisionId(item: ItemAndContent) {
var contentMetadata = {
uuid: item.item.uuid,
parentRevision: item.item.parentRevision,
title: item.item.title,
updatedAt: item.item.updatedAt,
createdAt: item.item.createdAt,
typeName: item.item.typeName,
openContents: item.item.openContents,
folderUuid: item.item.folderUuid,
faveIndex: item.item.faveIndex,
trashed: item.item.trashed,
content: item.content,
};
var contentString = JSON.stringify(contentMetadata);
var hasher = new sha1.SHA1();
var srcBuf = collectionutil.bufferFromString(contentString);
var digest = new Int32Array(5);
hasher.hash(srcBuf, digest);
return collectionutil.hexlify(digest);
}
/** Provides a default implementation of ItemStore.listItemStates() using
* ItemStore.listItems(). Since listItemStates() returns a subset of
* the information returned by listItems(), stores may be able to
* provide more efficient implementations.
*/
export function itemStates(store: Store): Promise<ItemState[]> {
return store.listItems({ includeTombstones: true }).then(items =>
items.map(item => ({
uuid: item.uuid,
revision: item.revision,
deleted: item.isTombstone(),
}))
);
}
/** Decrypt the encryption keys for @p store and add
* the keys to @p agent.
*/
export function unlockStore(
store: Store,
agent: key_agent.KeyAgent,
password: string
): Promise<void> {
return store
.listKeys()
.then(keys => {
if (keys.length == 0) {
throw new Error(
'Unable to unlock store: No encryption keys have been saved'
);
}
return key_agent.decryptKeys(keys, password);
})
.then(keys => {
let savedKeys: Promise<void>[] = [];
keys.forEach(key => {
savedKeys.push(agent.addKey(key.id, key.key));
});
return asyncutil.eraseResult(Promise.all(savedKeys));
});
} | the_stack |
import { Command, flags } from "@oclif/command";
import chalk from "chalk";
import fs from "fs";
import inquirer from "inquirer";
import path from "path";
import cliAPI, { successOnly } from "../lib/cli-api";
import {
defaultConfigPath,
DEFAULT_SITE,
NPM_BINARY_NAME,
} from "../lib/config";
import { print, println } from "../lib/print";
import { Manifest } from "../lib/types";
import { copy, runCmd } from "../lib/util";
import { bump } from "./bump";
import { doPublish } from "./publish";
import { release, ReleaseDestination } from "./release";
interface PackageOptions {
name: string;
description: string;
typescript: boolean;
bundler?: string;
}
interface PackageJson {
name: string;
version: string;
description: string;
}
const defaultName = (dir?: string) => {
return path
.basename(path.resolve(process.cwd(), dir || ""))
.replace(/[^\w\d\s]/g, " ")
.replace(/(:?^|\s)(\w)/g, (c) => c.toUpperCase());
};
const packageName = (name: string) =>
name.toLowerCase().trim().replace(/\s+/g, "-");
const getAppDir = (name: string, dir?: string) => {
if (dir && dir.length) {
if (path.isAbsolute(dir)) {
return dir;
}
return path.join(process.cwd(), dir);
}
return path.join(process.cwd(), name);
};
const defaultPackageOptions = (name: string) => ({
name: packageName(name),
description: "A Quip Live App",
typescript: true,
use_color_theme: true,
});
const defaultManifestOptions = (
dir?: string,
opts?: { name?: string; id?: string }
) => ({
name: defaultName(dir),
...(opts || {}),
});
export default class Init extends Command {
static description = "Initialize a new Live App Project";
static flags = {
help: flags.help({ char: "h" }),
["dry-run"]: flags.boolean({
char: "d",
hidden: true,
description:
"Print what this would do, but don't create any files.",
}),
"no-create": flags.boolean({
description:
"only create a local app (don't create an app in the dev console or assign an ID)",
}),
"no-release": flags.boolean({
description:
'don\'t release the initial version (leave app uninstallable and in the "unreleased" state)',
}),
dir: flags.string({
char: "d",
description:
"specify directory to create app in (defaults to the name provided)",
}),
site: flags.string({
char: "s",
description:
"use a specific quip site rather than the standard quip.com login",
default: DEFAULT_SITE,
}),
json: flags.boolean({
char: "j",
description:
"output responses in JSON (must provide --name and --id)",
dependsOn: ["name", "id"],
}),
name: flags.string({
char: "n",
description: "set the name of the application",
}),
id: flags.string({
char: "i",
description: "set the ID of the application",
}),
config: flags.string({
hidden: true,
description: "Use a custom config file (default ~/.quiprc)",
default: () => defaultConfigPath(),
}),
};
private promptInitialAppConfig_ = async (
specifiedDir?: string,
defaults?: { name?: string; id?: string }
) => {
println("Creating a new Quip Live App");
const validateNumber: (input: any) => true | string = (val) =>
!isNaN(parseInt(val, 10)) || "Please enter a number";
const defaultManifest = defaultManifestOptions(specifiedDir, defaults);
const manifestOptions: Manifest = await inquirer.prompt([
{
type: "input",
name: "name",
message:
"What is the name of this app?\n(This is what users will see when inserting your app)\n",
default: defaultManifest.name,
},
{
type: "list",
name: "toolbar_color",
message: "Choose a toolbar color",
choices: ["red", "orange", "yellow", "green", "blue", "violet"],
},
]);
const defaultPackage = defaultPackageOptions(manifestOptions.name);
const packageOptions: PackageOptions = await inquirer.prompt([
{
type: "input",
name: "name",
message: "Choose a package name",
default: defaultPackage.name,
filter: (val) => val.toLowerCase(),
},
{
type: "input",
name: "description",
message: "What does this app do?\n",
default: defaultPackage.description,
},
{
type: "confirm",
name: "typescript",
message: "Use Typescript?",
default: defaultPackage.typescript,
},
{
type: "confirm",
name: "use_color_theme",
message: "Use Color Theme?",
default: defaultPackage.use_color_theme,
},
]);
const { addManifestConfig } = await inquirer.prompt([
{
type: "confirm",
name: "addManifestConfig",
message:
"Would you like to customize your manifest.json now?\n(see: https://corp.quip.com/dev/liveapps/documentation#app-manifest)\n",
default: true,
},
]);
if (addManifestConfig) {
const extraManifestOptions = await inquirer.prompt([
{
type: "confirm",
name: "disable_app_level_comments",
message: "Disable commenting at the app level?",
default: false,
},
{
type: "list",
name: "sizing_mode",
message:
"Choose a sizing mode\n(see: https://corp.quip.com/dev/liveapps/recipes#specifying-the-size-of-your-app)",
choices: ["fill_container", "fit_content", "scale"],
},
{
type: "number",
name: "initial_height",
message:
"Specify an initial height for your app\nThis will be the height of the app while it is loading.\n",
default: 300,
validate: validateNumber,
filter: Number,
},
]);
Object.assign(manifestOptions, extraManifestOptions);
}
packageOptions.bundler = "webpack";
manifestOptions.description = packageOptions.description;
const appDir = getAppDir(packageOptions.name, specifiedDir);
return {
appDir,
packageOptions,
manifestOptions,
};
};
private copyTemplate_ = (
packageOptions: PackageOptions,
dest: string,
dryRun: boolean
) => {
const { typescript, bundler } = packageOptions;
// get lib path
const templateName = `${typescript ? "ts" : "js"}_${
bundler || "webpack"
}`;
const templatePath = path.join(
__dirname,
"../../templates",
templateName
);
const options = {
dereference: true,
// For use during local developement. Do not copy .git and boilerplate node_modules
filter: (fileName: string) =>
!fileName.match(/(?:\.git\/|templates\/[\w_]+\/node_modules)/),
};
if (dryRun) {
println(`Would intialize ${templateName} on ${dest}`);
return;
} else {
return copy(templatePath, dest, options);
}
};
private mutatePackage_ = (
packageOptions: Pick<
Partial<PackageJson>,
"name" | "description" | "version"
>,
dir: string
): Promise<PackageJson> => {
const packagePath = path.join(dir, "package.json");
return this.mutateJsonConfig_<PackageJson>(packagePath, packageOptions);
};
private mutateManifest_ = (
manifestOptions: Partial<Manifest>,
dir: string
) => {
const manifestPath = path.join(dir, "manifest.json");
return this.mutateJsonConfig_(manifestPath, manifestOptions);
};
private mutateJsonConfig_ = async <T extends PackageJson | Manifest>(
configPath: string,
updates: Partial<T>
): Promise<T> => {
const config = JSON.parse(fs.readFileSync(configPath).toString());
Object.assign(config, updates);
await fs.promises.writeFile(
configPath,
JSON.stringify(config, null, 4)
);
return config;
};
async run() {
const { flags } = this.parse(Init);
const dryRun = flags["dry-run"];
const fetch = await cliAPI(flags.config, flags.site);
const shouldCreate = !flags["no-create"];
if (shouldCreate) {
const ok = await successOnly(fetch("ok"), false);
if (!ok) {
println(
chalk`{red Refusing to create an app since we can't contact Quip servers.}`
);
process.exit(1);
}
}
let config:
| {
appDir: string;
packageOptions: PackageOptions;
manifestOptions: Partial<Manifest>;
}
| undefined;
if (flags.name && flags.json && flags.id) {
const manifestOptions = defaultManifestOptions(flags.dir, {
name: flags.name,
id: flags.id,
});
const packageOptions = defaultPackageOptions(manifestOptions.name);
config = {
appDir: getAppDir(packageOptions.name, flags.dir),
manifestOptions,
packageOptions,
};
} else {
// initial app options from user
config = await this.promptInitialAppConfig_(flags.dir, {
name: flags.name,
id: flags.id,
});
}
const { packageOptions, manifestOptions, appDir } = config;
await this.copyTemplate_(packageOptions, appDir, dryRun);
if (dryRun) {
println("Would update package.json with", packageOptions);
println("Would update manifest.json with", manifestOptions);
return;
}
let pkg = await this.mutatePackage_(packageOptions, appDir);
let manifest = await this.mutateManifest_(manifestOptions, appDir);
let success = true;
if (!flags["no-create"]) {
// create app
println(chalk`{green Creating app in dev console...}`);
const createdApp = await successOnly(
fetch<Manifest>("apps", "post"),
false
);
if (!createdApp) {
return;
}
// update manifest
manifest = await this.mutateManifest_(
{
id: createdApp.id,
version_number: createdApp.version_number,
version_name: createdApp.version_name,
},
appDir
);
println(
chalk`{magenta App created: ${createdApp.id}, v${createdApp.version_name} (${createdApp.version_number})}`
);
// npm install
println(chalk`{green installing dependencies...}`);
await runCmd(appDir, NPM_BINARY_NAME, "install");
// bump the version since we already have a version 0 in the console
println(chalk`{green bumping version...}`);
await bump(appDir, "minor", { silent: flags.json });
// npm run build
println(chalk`{green building app...}`);
await runCmd(appDir, NPM_BINARY_NAME, "run", "build");
// then publish the new version
println(chalk`{green uploading bundle...}`);
const newManifest = await doPublish(
manifest,
path.join(appDir, "manifest.json"),
"node_modules",
flags.config,
flags.site,
flags.json
);
success = !!newManifest;
if (success && !flags["no-release"]) {
println(
chalk`{green releasing build ${
newManifest!.version_number
} as initial beta...}`
);
await release({
manifest: newManifest!,
destination: ReleaseDestination.BETA,
build: newManifest!.version_number,
site: flags.site,
config: flags.config,
json: flags.json,
});
}
if (flags.json) {
if (success) {
print(JSON.stringify(newManifest));
} else {
process.exit(1);
}
}
} else if (flags.json && success) {
print(JSON.stringify(manifest));
}
if (!flags.json && success) {
println(
chalk`{magenta Live App Project initialized: ${manifest.name} (${pkg.name})}`
);
}
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.