text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import S3 from 'aws-sdk/clients/s3';
import { createHmac } from 'crypto';
import { DefaultImageRequest, ImageEdits, ImageFormatTypes, ImageHandlerError, ImageHandlerEvent, ImageRequestInfo, Headers, RequestTypes, StatusCodes } from './lib';
import { SecretProvider } from './secret-provider';
import { ThumborMapper } from './thumbor-mapper';
type OriginalImageInfo = Partial<{
contentType: string;
expires: string;
lastModified: string;
cacheControl: string;
originalImage: Buffer;
}>;
export class ImageRequest {
private static readonly DEFAULT_REDUCTION_EFFORT = 4;
constructor(private readonly s3Client: S3, private readonly secretProvider: SecretProvider) {}
/**
* Initializer function for creating a new image request, used by the image handler to perform image modifications.
* @param event Lambda request body.
* @returns Initialized image request information.
*/
public async setup(event: ImageHandlerEvent): Promise<ImageRequestInfo> {
try {
await this.validateRequestSignature(event);
let imageRequestInfo: ImageRequestInfo = <ImageRequestInfo>{};
imageRequestInfo.requestType = this.parseRequestType(event);
imageRequestInfo.bucket = this.parseImageBucket(event, imageRequestInfo.requestType);
imageRequestInfo.key = this.parseImageKey(event, imageRequestInfo.requestType);
imageRequestInfo.edits = this.parseImageEdits(event, imageRequestInfo.requestType);
const originalImage = await this.getOriginalImage(imageRequestInfo.bucket, imageRequestInfo.key);
imageRequestInfo = { ...imageRequestInfo, ...originalImage };
imageRequestInfo.headers = this.parseImageHeaders(event, imageRequestInfo.requestType);
// If the original image is SVG file and it has any edits but no output format, change the format to WebP.
if (imageRequestInfo.contentType === 'image/svg+xml' && imageRequestInfo.edits && Object.keys(imageRequestInfo.edits).length > 0 && !imageRequestInfo.edits.toFormat) {
imageRequestInfo.outputFormat = ImageFormatTypes.PNG;
}
/* Decide the output format of the image.
* 1) If the format is provided, the output format is the provided format.
* 2) If headers contain "Accept: image/webp", the output format is webp.
* 3) Use the default image format for the rest of cases.
*/
if (imageRequestInfo.contentType !== 'image/svg+xml' || imageRequestInfo.edits.toFormat || imageRequestInfo.outputFormat) {
const outputFormat = this.getOutputFormat(event, imageRequestInfo.requestType);
// if webp check reduction effort, if invalid value, use 4 (default in sharp)
if (outputFormat === ImageFormatTypes.WEBP && imageRequestInfo.requestType === RequestTypes.DEFAULT) {
const decoded = this.decodeRequest(event);
if (typeof decoded.reductionEffort !== 'undefined') {
const reductionEffort = Math.trunc(decoded.reductionEffort);
const isValid = !isNaN(reductionEffort) && reductionEffort >= 0 && reductionEffort <= 6;
imageRequestInfo.reductionEffort = isValid ? reductionEffort : ImageRequest.DEFAULT_REDUCTION_EFFORT;
}
}
if (imageRequestInfo.edits && imageRequestInfo.edits.toFormat) {
imageRequestInfo.outputFormat = imageRequestInfo.edits.toFormat;
} else if (outputFormat) {
imageRequestInfo.outputFormat = outputFormat;
}
}
// Fix quality for Thumbor and Custom request type if outputFormat is different from quality type.
if (imageRequestInfo.outputFormat) {
const requestType = [RequestTypes.CUSTOM, RequestTypes.THUMBOR];
const acceptedValues = [ImageFormatTypes.JPEG, ImageFormatTypes.PNG, ImageFormatTypes.WEBP, ImageFormatTypes.TIFF, ImageFormatTypes.HEIF];
imageRequestInfo.contentType = `image/${imageRequestInfo.outputFormat}`;
if (requestType.includes(imageRequestInfo.requestType) && acceptedValues.includes(imageRequestInfo.outputFormat)) {
const qualityKey = Object.keys(imageRequestInfo.edits).filter(key => acceptedValues.includes(key as ImageFormatTypes))[0];
if (qualityKey && qualityKey !== imageRequestInfo.outputFormat) {
imageRequestInfo.edits[imageRequestInfo.outputFormat] = imageRequestInfo.edits[qualityKey];
delete imageRequestInfo.edits[qualityKey];
}
}
}
return imageRequestInfo;
} catch (error) {
console.error(error);
throw error;
}
}
/**
* Gets the original image from an Amazon S3 bucket.
* @param bucket The name of the bucket containing the image.
* @param key The key name corresponding to the image.
* @returns The original image or an error.
*/
public async getOriginalImage(bucket: string, key: string): Promise<OriginalImageInfo> {
try {
const result: OriginalImageInfo = {};
const imageLocation = { Bucket: bucket, Key: key };
const originalImage = await this.s3Client.getObject(imageLocation).promise();
const imageBuffer = Buffer.from(originalImage.Body as Uint8Array);
if (originalImage.ContentType) {
// If using default S3 ContentType infer from hex headers
if (['binary/octet-stream', 'application/octet-stream'].includes(originalImage.ContentType)) {
result.contentType = this.inferImageType(imageBuffer);
} else {
result.contentType = originalImage.ContentType;
}
} else {
result.contentType = 'image';
}
if (originalImage.Expires) {
result.expires = new Date(originalImage.Expires).toUTCString();
}
if (originalImage.LastModified) {
result.lastModified = new Date(originalImage.LastModified).toUTCString();
}
result.cacheControl = originalImage.CacheControl ?? 'max-age=31536000,public';
result.originalImage = imageBuffer;
return result;
} catch (error) {
let status = StatusCodes.INTERNAL_SERVER_ERROR;
let message = error.message;
if (error.code === 'NoSuchKey') {
status = StatusCodes.NOT_FOUND;
message = `The image ${key} does not exist or the request may not be base64 encoded properly.`;
}
throw new ImageHandlerError(status, error.code, message);
}
}
/**
* Parses the name of the appropriate Amazon S3 bucket to source the original image from.
* @param event Lambda request body.
* @param requestType Image handler request type.
* @returns The name of the appropriate Amazon S3 bucket.
*/
public parseImageBucket(event: ImageHandlerEvent, requestType: RequestTypes): string {
if (requestType === RequestTypes.DEFAULT) {
// Decode the image request
const request = this.decodeRequest(event);
if (request.bucket !== undefined) {
// Check the provided bucket against the allowed list
const sourceBuckets = this.getAllowedSourceBuckets();
if (sourceBuckets.includes(request.bucket) || request.bucket.match(new RegExp('^' + sourceBuckets[0] + '$'))) {
return request.bucket;
} else {
throw new ImageHandlerError(
StatusCodes.FORBIDDEN,
'ImageBucket::CannotAccessBucket',
'The bucket you specified could not be accessed. Please check that the bucket is specified in your SOURCE_BUCKETS.'
);
}
} else {
// Try to use the default image source bucket env var
const sourceBuckets = this.getAllowedSourceBuckets();
return sourceBuckets[0];
}
} else if (requestType === RequestTypes.THUMBOR || requestType === RequestTypes.CUSTOM) {
// Use the default image source bucket env var
const sourceBuckets = this.getAllowedSourceBuckets();
return sourceBuckets[0];
} else {
throw new ImageHandlerError(
StatusCodes.NOT_FOUND,
'ImageBucket::CannotFindBucket',
'The bucket you specified could not be found. Please check the spelling of the bucket name in your request.'
);
}
}
/**
* Parses the edits to be made to the original image.
* @param event Lambda request body.
* @param requestType Image handler request type.
* @returns The edits to be made to the original image.
*/
public parseImageEdits(event: ImageHandlerEvent, requestType: RequestTypes): ImageEdits {
if (requestType === RequestTypes.DEFAULT) {
const decoded = this.decodeRequest(event);
return decoded.edits;
} else if (requestType === RequestTypes.THUMBOR) {
const thumborMapping = new ThumborMapper();
return thumborMapping.mapPathToEdits(event.path);
} else if (requestType === RequestTypes.CUSTOM) {
const thumborMapping = new ThumborMapper();
const parsedPath = thumborMapping.parseCustomPath(event.path);
return thumborMapping.mapPathToEdits(parsedPath);
} else {
throw new ImageHandlerError(
StatusCodes.BAD_REQUEST,
'ImageEdits::CannotParseEdits',
'The edits you provided could not be parsed. Please check the syntax of your request and refer to the documentation for additional guidance.'
);
}
}
/**
* Parses the name of the appropriate Amazon S3 key corresponding to the original image.
* @param event Lambda request body.
* @param requestType Type of the request.
* @returns The name of the appropriate Amazon S3 key.
*/
public parseImageKey(event: ImageHandlerEvent, requestType: RequestTypes): string {
if (requestType === RequestTypes.DEFAULT) {
// Decode the image request and return the image key
const { key } = this.decodeRequest(event);
return key;
}
if (requestType === RequestTypes.THUMBOR || requestType === RequestTypes.CUSTOM) {
let { path } = event;
if (requestType === RequestTypes.CUSTOM) {
const { REWRITE_MATCH_PATTERN, REWRITE_SUBSTITUTION } = process.env;
if (typeof REWRITE_MATCH_PATTERN === 'string') {
const patternStrings = REWRITE_MATCH_PATTERN.split('/');
const flags = patternStrings.pop();
const parsedPatternString = REWRITE_MATCH_PATTERN.slice(1, REWRITE_MATCH_PATTERN.length - 1 - flags.length);
const regExp = new RegExp(parsedPatternString, flags);
path = path.replace(regExp, REWRITE_SUBSTITUTION);
} else {
path = path.replace(REWRITE_MATCH_PATTERN, REWRITE_SUBSTITUTION);
}
}
return decodeURIComponent(path.replace(/\/\d+x\d+:\d+x\d+\/|(?<=\/)\d+x\d+\/|filters:[^/]+|\/fit-in(?=\/)|^\/+/g, '').replace(/^\/+/, ''));
}
// Return an error for all other conditions
throw new ImageHandlerError(
StatusCodes.NOT_FOUND,
'ImageEdits::CannotFindImage',
'The image you specified could not be found. Please check your request syntax as well as the bucket you specified to ensure it exists.'
);
}
/**
* Determines how to handle the request being made based on the URL path prefix to the image request.
* Categorizes a request as either "image" (uses the Sharp library), "thumbor" (uses Thumbor mapping), or "custom" (uses the rewrite function).
* @param event Lambda request body.
* @returns The request type.
*/
public parseRequestType(event: ImageHandlerEvent): RequestTypes {
const { path } = event;
const matchDefault = /^(\/?)([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
const matchThumbor = /^(\/?)((fit-in)?|(filters:.+\(.?\))?|(unsafe)?)(((.(?!(\.[^.\\/]+$)))*$)|.*(\.jpg$|.\.png$|\.webp$|\.tiff$|\.jpeg$|\.svg$))/i;
const { REWRITE_MATCH_PATTERN, REWRITE_SUBSTITUTION } = process.env;
const definedEnvironmentVariables = REWRITE_MATCH_PATTERN !== '' && REWRITE_SUBSTITUTION !== '' && REWRITE_MATCH_PATTERN !== undefined && REWRITE_SUBSTITUTION !== undefined;
// Check if path is base 64 encoded
let isBase64Encoded = true;
try {
this.decodeRequest(event);
} catch (error) {
console.error(error);
isBase64Encoded = false;
}
if (matchDefault.test(path) && isBase64Encoded) {
// use sharp
return RequestTypes.DEFAULT;
} else if (definedEnvironmentVariables) {
// use rewrite function then thumbor mappings
return RequestTypes.CUSTOM;
} else if (matchThumbor.test(path)) {
// use thumbor mappings
return RequestTypes.THUMBOR;
} else {
throw new ImageHandlerError(
StatusCodes.BAD_REQUEST,
'RequestTypeError',
'The type of request you are making could not be processed. Please ensure that your original image is of a supported file type (jpg, png, tiff, webp, svg) and that your image request is provided in the correct syntax. Refer to the documentation for additional guidance on forming image requests.'
);
}
}
/**
* Parses the headers to be sent with the response.
* @param event Lambda request body.
* @param requestType Image handler request type.
* @returns The headers to be sent with the response.
*/
public parseImageHeaders(event: ImageHandlerEvent, requestType: RequestTypes): Headers {
if (requestType === RequestTypes.DEFAULT) {
const { headers } = this.decodeRequest(event);
if (headers) {
return headers;
}
}
}
/**
* Decodes the base64-encoded image request path associated with default image requests.
* Provides error handling for invalid or undefined path values.
* @param event Lambda request body.
* @returns The decoded from base-64 image request.
*/
public decodeRequest(event: ImageHandlerEvent): DefaultImageRequest {
const { path } = event;
if (path) {
const encoded = path.charAt(0) === '/' ? path.slice(1) : path;
const toBuffer = Buffer.from(encoded, 'base64');
try {
// To support European characters, 'ascii' was removed.
return JSON.parse(toBuffer.toString());
} catch (error) {
throw new ImageHandlerError(
StatusCodes.BAD_REQUEST,
'DecodeRequest::CannotDecodeRequest',
'The image request you provided could not be decoded. Please check that your request is base64 encoded properly and refer to the documentation for additional guidance.'
);
}
} else {
throw new ImageHandlerError(
StatusCodes.BAD_REQUEST,
'DecodeRequest::CannotReadPath',
'The URL path you provided could not be read. Please ensure that it is properly formed according to the solution documentation.'
);
}
}
/**
* Returns a formatted image source bucket allowed list as specified in the SOURCE_BUCKETS environment variable of the image handler Lambda function.
* Provides error handling for missing/invalid values.
* @returns A formatted image source bucket.
*/
public getAllowedSourceBuckets(): string[] {
const { SOURCE_BUCKETS } = process.env;
if (SOURCE_BUCKETS === undefined) {
throw new ImageHandlerError(
StatusCodes.BAD_REQUEST,
'GetAllowedSourceBuckets::NoSourceBuckets',
'The SOURCE_BUCKETS variable could not be read. Please check that it is not empty and contains at least one source bucket, or multiple buckets separated by commas. Spaces can be provided between commas and bucket names, these will be automatically parsed out when decoding.'
);
} else {
return SOURCE_BUCKETS.replace(/\s+/g, '').split(',');
}
}
/**
* Return the output format depending on the accepts headers and request type.
* @param event Lambda request body.
* @param requestType The request type.
* @returns The output format.
*/
public getOutputFormat(event: ImageHandlerEvent, requestType: RequestTypes = undefined): ImageFormatTypes {
const { AUTO_WEBP } = process.env;
if (AUTO_WEBP === 'Yes' && event.headers.Accept && event.headers.Accept.includes('image/webp')) {
return ImageFormatTypes.WEBP;
} else if (requestType === RequestTypes.DEFAULT) {
const decoded = this.decodeRequest(event);
return decoded.outputFormat;
}
return null;
}
/**
* Return the output format depending on first four hex values of an image file.
* @param imageBuffer Image buffer.
* @returns The output format.
*/
public inferImageType(imageBuffer: Buffer): string {
const imageSignature = imageBuffer.slice(0, 4).toString('hex').toUpperCase();
switch (imageSignature) {
case '89504E47':
return 'image/png';
case 'FFD8FFDB':
case 'FFD8FFE0':
case 'FFD8FFEE':
case 'FFD8FFE1':
return 'image/jpeg';
case '52494646':
return 'image/webp';
case '49492A00':
return 'image/tiff';
case '4D4D002A':
return 'image/tiff';
default:
throw new ImageHandlerError(
StatusCodes.INTERNAL_SERVER_ERROR,
'RequestTypeError',
'The file does not have an extension and the file type could not be inferred. Please ensure that your original image is of a supported file type (jpg, png, tiff, webp, svg). Refer to the documentation for additional guidance on forming image requests.'
);
}
}
/**
* Validates the request's signature.
* @param event Lambda request body.
* @returns A promise.
* @throws Throws the error if validation is enabled and the provided signature is invalid.
*/
private async validateRequestSignature(event: ImageHandlerEvent): Promise<void> {
const { ENABLE_SIGNATURE, SECRETS_MANAGER, SECRET_KEY } = process.env;
// Checks signature enabled
if (ENABLE_SIGNATURE === 'Yes') {
const { path, queryStringParameters } = event;
if (!queryStringParameters?.signature) {
throw new ImageHandlerError(StatusCodes.BAD_REQUEST, 'AuthorizationQueryParametersError', 'Query-string requires the signature parameter.');
}
try {
const { signature } = queryStringParameters;
const secret = JSON.parse(await this.secretProvider.getSecret(SECRETS_MANAGER));
const key = secret[SECRET_KEY];
const hash = createHmac('sha256', key).update(path).digest('hex');
// Signature should be made with the full path.
if (signature !== hash) {
throw new ImageHandlerError(StatusCodes.FORBIDDEN, 'SignatureDoesNotMatch', 'Signature does not match.');
}
} catch (error) {
if (error.code === 'SignatureDoesNotMatch') {
throw error;
}
console.error('Error occurred while checking signature.', error);
throw new ImageHandlerError(StatusCodes.INTERNAL_SERVER_ERROR, 'SignatureValidationFailure', 'Signature validation failed.');
}
}
}
} | the_stack |
import { BasicClient } from "../BasicClient";
import { Candle } from "../Candle";
import { CandlePeriod } from "../CandlePeriod";
import { ClientOptions } from "../ClientOptions";
import { CancelableFn } from "../flowcontrol/Fn";
import { throttle } from "../flowcontrol/Throttle";
import { Level2Point } from "../Level2Point";
import { Level2Snapshot } from "../Level2Snapshots";
import { NotImplementedFn } from "../NotImplementedFn";
import { Ticker } from "../Ticker";
import { Trade } from "../Trade";
export class DeribitClient extends BasicClient {
public id: number;
public candlePeriod: CandlePeriod;
protected _send: CancelableFn;
constructor({ wssPath = "wss://www.deribit.com/ws/api/v2", watcherMs }: ClientOptions = {}) {
super(wssPath, "Deribit", undefined, watcherMs);
this.hasTickers = true;
this.hasTrades = true;
this.hasCandles = true;
this.hasLevel2Updates = true;
this.id = 0;
this.candlePeriod = CandlePeriod._1m;
this._send = throttle(this.__send.bind(this), 50);
}
protected _beforeClose() {
this._send.cancel();
}
protected __send(message) {
this._wss.send(message);
}
protected _sendSubTicker(remote_id) {
this._send(
JSON.stringify({
jsonrpc: "2.0",
method: "public/subscribe",
params: {
channels: [`ticker.${remote_id}.raw`],
},
id: ++this.id,
}),
);
}
protected _sendUnsubTicker(remote_id) {
this._send(
JSON.stringify({
jsonrpc: "2.0",
method: "public/unsubscribe",
params: {
channels: [`ticker.${remote_id}.raw`],
},
id: ++this.id,
}),
);
}
protected _sendSubTrades(remote_id) {
this._send(
JSON.stringify({
jsonrpc: "2.0",
method: "public/subscribe",
params: {
channels: [`trades.${remote_id}.raw`],
},
id: ++this.id,
}),
);
}
protected _sendUnsubTrades(remote_id) {
this._send(
JSON.stringify({
jsonrpc: "2.0",
method: "public/unsubscribe",
params: {
channels: [`trades.${remote_id}.raw`],
},
id: ++this.id,
}),
);
}
protected _sendSubCandles(remote_id) {
this._send(
JSON.stringify({
jsonrpc: "2.0",
method: "public/subscribe",
params: {
channels: [`chart.trades.${remote_id}.${candlePeriod(this.candlePeriod)}`],
},
id: ++this.id,
}),
);
}
protected _sendUnsubCandles(remote_id) {
this._send(
JSON.stringify({
jsonrpc: "2.0",
method: "public/unsubscribe",
params: {
channels: [`chart.trades.${remote_id}.${candlePeriod(this.candlePeriod)}`],
},
id: ++this.id,
}),
);
}
protected _sendSubLevel2Updates(remote_id) {
this._send(
JSON.stringify({
jsonrpc: "2.0",
method: "public/subscribe",
params: {
channels: [`book.${remote_id}.raw`],
},
id: ++this.id,
}),
);
}
protected _sendUnsubLevel2Updates(remote_id) {
this._wss.send(
JSON.stringify({
jsonrpc: "2.0",
method: "public/unsubscribe",
params: {
channels: [`book.${remote_id}.raw`],
},
id: ++this.id,
}),
);
}
protected _sendSubLevel2Snapshots = NotImplementedFn;
protected _sendUnsubLevel2Snapshots = NotImplementedFn;
protected _sendSubLevel3Snapshots = NotImplementedFn;
protected _sendUnsubLevel3Snapshots = NotImplementedFn;
protected _sendSubLevel3Updates = NotImplementedFn;
protected _sendUnsubLevel3Updates = NotImplementedFn;
protected _onMessage(raw) {
const msg = JSON.parse(raw);
// console.log(msg);
// Error?
if (!msg.params) {
return;
}
// Everything past here should be a channel message
const channel = msg.params.channel;
if (!channel) {
return;
}
// tickers - ticker.{instrument_name}.{interval}
if (channel.startsWith("ticker")) {
const parts = channel.split(".");
const market = this._tickerSubs.get(parts[1]);
if (!market) return;
const ticker = this._constructTicker(msg, market);
this.emit("ticker", ticker, market);
return;
}
// trades - trades.{instrument_name}.{interval}
if (channel.startsWith("trades")) {
const parts = channel.split(".");
const market = this._tradeSubs.get(parts[1]);
if (!market) return;
// eslint-disable-next-line prefer-const
for (let datum of msg.params.data) {
const trade = this._constructTrade(datum, market);
this.emit("trade", trade, market);
}
return;
}
// candle - chart.trades.{instrument_name}.{resolution}
if (channel.startsWith("chart")) {
const parts = channel.split(".");
const market = this._candleSubs.get(parts[2]);
if (!market) return;
const candle = this._constructCandle(msg.params.data);
this.emit("candle", candle, market);
return;
}
// book - book.{instrument_name}.{interval}
if (channel.startsWith("book")) {
const parts = channel.split(".");
const market = this._level2UpdateSubs.get(parts[1]);
if (!market) return;
// capture snapshot
if (!msg.params.data.prev_change_id) {
const snapshot = this._constructLevel2Snapshot(msg.params.data, market);
this.emit("l2snapshot", snapshot, market);
}
// capture update
else {
const update = this._constructLevel2Update(msg.params.data, market);
this.emit("l2update", update, market);
}
return;
}
}
/**
{
"jsonrpc": "2.0",
"method": "subscription",
"params": {
"channel": "ticker.BTC-PERPETUAL.raw",
"data": {
"timestamp": 1597244851057,
"stats": {
"volume_usd": 404775400.0,
"volume": 35574.05167122,
"price_change": 0.493,
"low": 11131.5,
"high": 11632.5
},
"state": "open",
"settlement_price": 11452.62,
"open_interest": 117979530,
"min_price": 11443.06,
"max_price": 11791.58,
"mark_price": 11617.8,
"last_price": 11618.0,
"instrument_name": "BTC-PERPETUAL",
"index_price": 11609.61,
"funding_8h": 0.00001212,
"estimated_delivery_price": 11609.61,
"current_funding": 0.00020545,
"best_bid_price": 11618.0,
"best_bid_amount": 7460.0,
"best_ask_price": 11618.5,
"best_ask_amount": 497870.0
}
}
}
*/
protected _constructTicker(msg, market) {
const data = msg.params.data;
return new Ticker({
exchange: this.name,
base: market.base,
quote: market.quote,
timestamp: data.timestamp,
last: (data.last_price ? data.last_price : 0).toFixed(8),
open: undefined,
high: (data.stats.high ? data.stats.high : 0).toFixed(8),
low: (data.stats.low ? data.stats.low : 0).toFixed(8),
volume: (data.stats.volume ? data.stats.volume : 0).toFixed(8),
quoteVolume: undefined,
change: undefined,
changePercent: (data.stats.price_change ? data.stats.price_change : 0).toFixed(2),
ask: (data.best_ask_price ? data.best_ask_price : 0).toFixed(8),
askVolume: (data.best_ask_amount ? data.best_ask_amount : 0).toFixed(8),
bid: (data.best_bid_price ? data.best_bid_price : 0).toFixed(8),
bidVolume: (data.best_bid_amount ? data.best_bid_amount : 0).toFixed(8),
});
}
/**
* PERPETUAL
{
"trade_seq": 56761222,
"trade_id": "88095252",
"timestamp": 1597246721811,
"tick_direction": 3,
"price": 11576.0,
"mark_price": 11574.5,
"instrument_name": "BTC-PERPETUAL",
"index_price": 11567.32,
"direction": "buy",
"amount": 4310.0
}
*/
protected _constructTrade(datum, market) {
return new Trade({
exchange: this.name,
base: market.base,
quote: market.quote,
tradeId: datum.trade_id,
side: datum.direction,
unix: datum.timestamp,
price: datum.price.toFixed(8),
amount: datum.amount.toFixed(8),
tradeSeq: datum.trade_seq,
blockTradeId: datum.block_trade_id,
markPrice: datum.mark_price.toFixed(8),
indexPrice: datum.index_price.toFixed(8),
liquidation: datum.liquidation,
iv: datum.iv,
tickDirection: datum.tick_direction,
});
}
/**
{
"volume" : 0.05219351,
"tick" : 1573645080000,
"open" : 8869.79,
"low" : 8788.25,
"high" : 8870.31,
"cost" : 460,
"close" : 8791.25
},
*/
protected _constructCandle(data) {
return new Candle(
data.tick,
data.open.toFixed(8),
data.high.toFixed(8),
data.low.toFixed(8),
data.close.toFixed(8),
data.volume.toFixed(8),
);
}
/**
{
"type" : "snapshot",
"timestamp" : 1554373962454,
"instrument_name" : "BTC-PERPETUAL",
"change_id" : 297217,
"bids" : [
[
"new",
5042.34,
30
],
[
"new",
5041.94,
20
]
],
"asks" : [
[
"new",
5042.64,
40
],
[
"new",
5043.3,
40
]
]
}
*/
protected _constructLevel2Snapshot(data, market) {
const timestampMs = data.timestamp;
const sequenceId = data.change_id;
const asks = data.asks.map(
p => new Level2Point(p[1].toFixed(8), p[2].toFixed(8), undefined, { type: p[0] }),
);
const bids = data.bids.map(
p => new Level2Point(p[1].toFixed(8), p[2].toFixed(8), undefined, { type: p[0] }),
);
return new Level2Snapshot({
exchange: this.name,
base: market.base,
quote: market.quote,
timestampMs,
sequenceId,
asks,
bids,
});
}
/**
{
"type" : "change",
"timestamp" : 1554373911330,
"prev_change_id" : 297217,
"instrument_name" : "BTC-PERPETUAL",
"change_id" : 297218,
"bids" : [
[
"delete",
5041.94,
0
],
[
"delete",
5042.34,
0
]
],
"asks" : [
]
}
*/
protected _constructLevel2Update(data, market) {
const timestampMs = data.timestamp;
const lastSequenceId = data.prev_change_id;
const sequenceId = data.change_id;
const asks = data.asks.map(
p => new Level2Point(p[1].toFixed(8), p[2].toFixed(2), undefined, { type: p[0] }),
);
const bids = data.bids.map(
p => new Level2Point(p[1].toFixed(8), p[2].toFixed(2), undefined, { type: p[0] }),
);
return new Level2Snapshot({
exchange: this.name,
base: market.base,
quote: market.quote,
timestampMs,
sequenceId,
lastSequenceId,
asks,
bids,
});
}
}
function candlePeriod(period) {
switch (period) {
case CandlePeriod._1m:
return "1";
case CandlePeriod._3m:
return "3";
case CandlePeriod._5m:
return "5";
case CandlePeriod._10m:
return "10";
case CandlePeriod._15m:
return "15";
case CandlePeriod._30m:
return "30";
case CandlePeriod._1h:
return "60";
case CandlePeriod._2h:
return "120";
case CandlePeriod._3h:
return "180";
case CandlePeriod._6h:
return "360";
case CandlePeriod._12h:
return "720";
case CandlePeriod._1d:
return "1D";
}
} | the_stack |
module tileworld.ruleediting {
// IMPORTANT: the order of direction-oriented images matches directions from rule.ts
export const moveImages = [leftArrow, upArrow, rightArrow, downArrow, stopSign, uTurn];
export const movedImages = [leftArrowOutline, upArrowOutline, rightArrowOutline, downArrowOutline, restingOutline, allFourOutline, anyOutline];
export const moveText = ["left", "up", "right", "down", "stop", "u-turn"];
export const buttonImages = [leftButton, upButton, rightButton, downButton, AButton];
// this mapping has a level of indirection, allowing reorganization of the UI
export const attrValues = [AttrType.Include, AttrType.Include2, AttrType.Exclude, AttrType.OK ];
export const attrImages = [include, include2, exclude, ok ];
// arguments to instructions here
export const gameImages = [ trophyUp, trophyDown, scoreUp10 ];
export const gameText = [ "win", "lose", "score+10" ];
export const editorRow = 2;
export class RuleDisplay extends RuleVisualsBase {
protected all: AllExport;
private otherCursor: Sprite; // show correspondence between left and right
constructor(p: Project, protected rule: RuleView) {
super(p);
this.all = new AllExport(p);
// linked cursor
this.otherCursor = sprites.create(cursorOut)
this.otherCursor.setFlag(SpriteFlag.Invisible, true)
this.otherCursor.x = 88
this.otherCursor.y = yoff+40
this.otherCursor.z = 50;
}
protected getDir(): number {
return this.rule.getDirFromRule();
}
protected getType(): RuleType {
return this.rule.getRuleType();
}
protected getKind(): number {
const kinds = this.rule.getSpriteKinds();
if (kinds.length > 0)
return kinds[0];
return -1;
}
protected centerImage(): Image {
return ok;
}
protected getDirectionImage(): Image {
const dir = this.rule.getDirFromRule();
return this.getType() == RuleType.ButtonPress ? buttonImages[dir] : moveImages[dir];
}
private otherCursorMove(): void {
if (this.col() >= 5 && this.row() >= editorRow) {
// map from Do section to When section
const row = this.row() - editorRow;
this.otherCursor.setFlag(SpriteFlag.Invisible, false);
// compute mapping from right to left hand side
this.otherCursor.x = this.rowToColCoord(row) * 16 + 8;
this.otherCursor.y = this.rowToRowCoord(row) * 16 + 8 + yoff + (editorRow *16);
} else {
// TOD: map from When section to Do section
this.otherCursor.setFlag(SpriteFlag.Invisible, true);
}
}
protected cursorMove(dir: MoveDirection, pressed: boolean): void {
this.otherCursorMove();
}
protected collideCol: number;
protected collideRow: number;
protected showCollision(col: number, row: number, dir: MoveDirection, arrowImg: Image, rt: RuleType): void {
this.collideCol = col;
this.collideRow = row - editorRow;
this.drawImage(col, row, collisionSprite);
const x = (dir == MoveDirection.Left) ? 7 : (dir == MoveDirection.Right) ? -7 : 0;
const y = (dir == MoveDirection.Up) ? 7 : (dir == MoveDirection.Down) ? -7 : 0;
this.drawImageAbs((col << 4) + x, (row << 4) + yoff + y, arrowImg);
}
protected showRuleType(rt: RuleType, rd: MoveRest, x: number, y: number, center = true): void {
if (center) this.drawImage(x, y, this.centerImage());
if (rt == RuleType.ContextChange) {
this.drawImage(x, y, movedImages[rd])
} else if (rt == RuleType.Collision) {
const ax = rd == MoveDirection.Left ? 1 : (rd == MoveDirection.Right ? -1 : 0)
const ay = rd == MoveDirection.Down ? -1 : (rd == MoveDirection.Up ? 1 : 0)
this.showCollision(x - ax, y - ay, rd, moveImages[rd], rt);
} else if (rt == RuleType.NegationCheck) {
this.drawImage(x, y, negate);
}
}
protected update(): void {
this.collideCol = this.collideRow = -1;
screen.fill(0);
screen.print("When", 0, (editorRow << 4) + 8);
if (this.p.debug)
screen.print(this.rule.getRuleId().toString(), 30, 0);
screen.print("Do", 70, (editorRow << 4) + 8);
// sets collideCol and collideRow
this.showRuleType(this.rule.getRuleType(), this.rule.getDirFromRule(), 2, 2 + editorRow);
this.makeContext();
if (this.getType() != RuleType.NegationCheck)
this.showRuleType(this.rule.getRuleType(), this.rule.getDirFromRule(), 2, 2 + editorRow);
this.showCommands();
if (this.getType() == RuleType.ButtonPress) {
const image = this.getDirectionImage();
if (image)
this.drawImage(0, 3, image);
} else if (this.getType() == RuleType.NegationCheck) {
this.drawImage(0, 3, negate);
}
}
private makeContext(): void {
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (this.active(i, j)) {
this.drawImage(i, j + editorRow, emptyTile);
this.showAttributes(i, j);
}
}
}
}
protected active(col: number, row: number): boolean {
if (this.collideCol != -1) {
return col == 2 && row == 2 || col == this.collideCol && row == this.collideRow;
}
return true;
}
// map from row 0-4 to (col,row) in diamond
protected rowToColCoord(lr: number): number { return lr % 2 == 0 ? 2 : lr; }
protected rowToRowCoord(lr: number): number { return lr == 0 ? 1 : (lr == 4 ? 3 : 2); }
// compute number of commands in each row, for editing
protected commandLengths: number[];
private showCommands(): void {
this.commandLengths = [];
for (let lr = 0; lr < 5; lr++) {
const col = this.rowToColCoord(lr);
const row = this.rowToRowCoord(lr);
const len = this.active(col, row) ? this.showCommandsAt(lr, col, row) : -1;
this.commandLengths.push(len);
}
}
protected instToImage(inst: number, arg: number): Image {
if (inst == 0xff || arg == 0xff)
return emptyTile;
switch (inst) {
case CommandType.Move: return moveImages[arg];
case CommandType.Paint: {
const ret = this.p.backgroundImages()[arg].clone();
ret.drawTransparentImage(smallPaint, 0, 0);
return ret;
}
case CommandType.Sprite: return eat;
case CommandType.Game: return gameImages[arg];
case CommandType.Spawn:
case CommandType.BlockSpriteRules:
{
const ret = this.p.spriteImages()[arg].clone();
ret.drawTransparentImage(inst == CommandType.Spawn ? spawn : exclude, 0, 0);
return ret;
}
case CommandType.Portal: {
const ret = this.p.backgroundImages()[arg].clone();
ret.drawTransparentImage(portal, 0, 0);
return ret;
}
}
return emptyTile;
}
protected tokens: number[];
protected showCommandsAt(crow: number, wcol: number, wrow: number, draw = true): number {
// TODO: need to special case on rule type
// TODO: - collision (no direction expression on central sprite)
// TODO: - negation (no witness)
if (draw) {
// draw the sprite witness, if any
const kind = this.rule.findWitnessColRow(wcol, wrow);
const img = kind == -1 ? genericSprite : this.getWhenDoImage(wcol, wrow);
this.drawImage(5, crow + editorRow, img);
// overlay the direction
if (kind != -1 && (this.getType() != RuleType.Collision || wcol != 2 || wrow != 2)) {
const whendo = this.rule.getWhenDo(wcol, wrow);
this.drawImage(5, crow + editorRow, movedImages[this.rule.getWitnessDirection(whendo)])
}
if (this.p.help) {
// print the rows numbers in the Do section
screen.print((crow +1).toString(), (5 << 4) + 10, ((editorRow + crow) << 4)+13);
// where they lie in the When section
screen.print((crow + 1).toString(), (wcol << 4) + 10, ((editorRow + wrow) << 4) + 13);
}
}
// show the existing commands
const whendo = this.rule.getWhenDo(wcol, wrow);
let col = 6;
const tokens = this.startTokens(wcol, wrow);
if (!draw) {
this.tokens = tokens;
}
let cid = 0
for (; whendo != -1 && cid < this.rule.getCmdsLen(whendo); cid++ , col++) {
this.showCommand(col, crow, whendo, cid, tokens, draw);
}
if (whendo == -1 || cid < MaxCommands && tokens.length > 0) {
this.showCommand(col, crow, whendo, cid, tokens, draw);
return cid + 1;
}
return cid;
}
private showCommand(col: number, row: number,
whendo: number, cid: number, tokens: number[],
draw: boolean): number {
if (whendo == -1) {
if (draw) this.drawImage(col, row + editorRow, emptyTile);
} else {
const inst = this.rule.getCmdInst(whendo, cid);
const arg = this.rule.getCmdArg(whendo, cid);
if (draw) this.drawImage(col, row + editorRow, this.instToImage(inst, arg));
this.updateTokens(tokens, inst);
col++;
}
return col;
}
// what instructions are possible, given rule type and witness
// this defines the menu to present at the top-level
private startTokens(col: number, row: number): number[] {
let tokens: number[] = [];
if (this.rule.findWitnessColRow(col, row) != -1) {
tokens = [CommandType.Move, CommandType.Sprite];
}
tokens = tokens.concat([
CommandType.Paint, CommandType.Spawn,
CommandType.BlockSpriteRules, CommandType.Portal,
CommandType.Game
]);
return tokens;
}
private updateTokens(tokens: number[], inst: number): void {
if (inst == 0xff)
return;
// at-most-once: paint, spawn, destroy
tokens.removeElement(inst);
// always remove move and destroy
tokens.removeElement(CommandType.Move);
tokens.removeElement(CommandType.Sprite);
if (inst == CommandType.Spawn) {
tokens.insertAt(0, CommandType.Move);
}
}
protected getWhenDoImage(col: number, row: number): Image {
const whenDo = this.rule.getWhenDo(col, row);
if (whenDo == -1)
return ok;
// look up includes and excludes
const include = this.attrIndex(whenDo, AttrType.Include);
const include2 = include == -1 ? -1 : this.attrIndex(whenDo, AttrType.Include, include + 1);
const exclude = this.attrIndex(whenDo, AttrType.Exclude);
const exclude2 = exclude == -1 ? -1 : this.attrIndex(whenDo, AttrType.Exclude, exclude + 1);
// favor includes over excludes
const index = include == -1 ? exclude : include;
// do split images when there are multiple includes/excludes
if (include != -1 && include2 != -1)
return utilities.splitImage(this.all.getImage(include), this.all.getImage(include2));
else if (include == -1 && exclude != -1 && exclude2 != -1)
return utilities.splitImage(this.all.getImage(exclude), this.all.getImage(exclude2));
else if (index != -1)
return this.all.getImage(index);
else
return ok;
}
protected showAttributes(col: number, row: number, show = true): void {
const whenDo = this.rule.getWhenDo(col, row);
if (whenDo >= 0) {
this.drawImage(col, row + editorRow, this.getWhenDoImage(col, row));
// show attributes
const begin = 0;
const end = this.p.allCnt() - 1;
const project = this.projectAttrs(whenDo, begin, end);
project.forEach(a => {
const i = attrValues.indexOf(a);
screen.drawTransparentImage(attrImages[i], (col << 4) + 8, ((row + editorRow) << 4) + 8 + yoff);
});
// show direction
if (this.getType() != RuleType.Collision && this.rule.findWitnessColRow(col, row) != -1) {
this.drawImage(col, row + editorRow, movedImages[this.rule.getWitnessDirection(whenDo)])
}
// ginve a peek into attributions under the main menu
if (show && this.col() == col && this.row() - editorRow == row) {
let x = 0;
screen.fillRect(0, 16 + yoff, 160, 16, 0);
this.all.getImages().forEach((image, i) => {
const a = this.all.getSetAttr(this.rule, whenDo, i);
if (a != AttrType.OK) {
this.drawImage(x, 1, image);
this.drawImage(x, 1, attrImages[attrValues.indexOf(a)]);
x++;
}
});
}
}
}
private projectAttrs(whendo: number, begin: number, end: number): number[] {
if (this.rule.whendoTrue(whendo))
return [];
const res: number[] = [];
for (let i = begin; i <= end; i++) {
const a = this.all.getSetAttr(this.rule, whendo, i);
if (a != AttrType.OK && res.indexOf(a) == -1) res.push(a);
}
if (res.length > 0) {
if (res.length == 1 && res.indexOf(AttrType.Exclude) != -1)
return [AttrType.Exclude];
else
return [];
}
return res;
}
private attrIndex(whendo: number, a: AttrType, begin = 0) {
for (let i = begin; i < this.p.allCnt(); i++) {
if (this.all.getSetAttr(this.rule, whendo, i) == a)
return i;
}
return -1;
}
}
} | the_stack |
import { DelimArray } from '@looker/sdk-rtl'
import { TestConfig } from './testUtils'
import { TypescriptGen } from './typescript.gen'
import { EnumType, titleCase } from './sdkModels'
import { trimInputs } from './codeGen'
const config = TestConfig()
const apiTestModel = config.apiTestModel
const gen = new TypescriptGen(apiTestModel)
const indent = ''
describe('typescript generator', () => {
describe('trimInputs tests here instead of CodeGen', () => {
it('trims top level', () => {
const inputs = {
one: undefined,
two: 'assigned',
three: true,
four: false,
five: '',
six: {},
seven: [],
}
const expected = { two: 'assigned', three: true, four: false, six: {} }
const actual = trimInputs(inputs)
expect(actual).toEqual(expected)
})
it('assigns arrays', () => {
const inputs = {
zero: [0, 1, 2, 3],
}
const expected = {
zero: [0, 1, 2, 3],
}
const actual = trimInputs(inputs)
expect(actual).toEqual(expected)
})
it('returns DelimArray', () => {
const inputs = {
ids: new DelimArray<number>([1, 2, 3]),
}
const actual = trimInputs(inputs)
expect(actual).toEqual(inputs)
})
it('trims nested levels', () => {
const inputs = {
zero: [0, 1, 2, 3],
one: undefined,
two: 'assigned',
three: true,
four: false,
five: '',
six: { a: true, b: 0, c: null, d: {} },
}
const expected = {
zero: [0, 1, 2, 3],
two: 'assigned',
three: true,
four: false,
six: { a: true, b: 0 },
}
const actual = trimInputs(inputs)
expect(actual).toEqual(expected)
})
})
it('comment header', () => {
const text = 'line 1\nline 2'
let actual = gen.commentHeader(indent, text)
let expected = `/**
* line 1
* line 2
*/
`
expect(actual).toEqual(expected)
actual = gen.commentHeader(indent, text, ' ')
expected = `/**
line 1
line 2
*/
`
expect(actual).toEqual(expected)
})
it('license comment header', () => {
const text =
'MIT License\n\nCopyright (c) 2021 Looker Data Sciences, Inc.\n\nPermission\n'
const actual = gen.commentHeader('', text, ' ')
const expected = `/*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission
*/
`
expect(actual).toEqual(expected)
})
describe('parameter declarations', () => {
it('required parameter', () => {
const method = apiTestModel.methods.run_query
const param = method.params[0]
const actual = gen.declareParameter(indent, method, param)
expect(actual).toEqual(`query_id: number`)
})
it('intrinsic body', () => {
const method = apiTestModel.methods.parse_saml_idp_metadata
const param = method.params[0]
const actual = gen.declareParameter(indent, method, param)
expect(actual).toEqual(`body: string`)
})
it('optional parameter', () => {
const method = apiTestModel.methods.run_query
const param = method.params[2]
const actual = gen.declareParameter(indent, method, param)
expect(actual).toEqual(`limit?: number`)
})
it('required typed parameter', () => {
const method = apiTestModel.methods.create_query_render_task
const param = method.params[2]
const actual = gen.declareParameter(indent, method, param)
expect(actual).toEqual(`width: number`)
})
it('csv formatted parameter', () => {
const method = apiTestModel.methods.query_task_multi_results
const param = method.params[0]
const actual = gen.declareParameter(indent, method, param)
expect(actual).toEqual(`query_task_ids: DelimArray<string>`)
})
})
describe('makeTheCall', () => {
const fields = 'id,user_id,title,description'
it('handles no params', () => {
const inputs = {}
const method = apiTestModel.methods.run_look
const actual = gen.makeTheCall(method, inputs)
const expected = 'let response = await sdk.ok(sdk.run_look())'
expect(actual).toEqual(expected)
})
it('assigns single param', () => {
const inputs = { look_id: 17 }
const method = apiTestModel.methods.look
const actual = gen.makeTheCall(method, inputs)
const expected = `let response = await sdk.ok(sdk.look(17))`
expect(actual).toEqual(expected)
})
it('assigns simple params', () => {
const inputs = { look_id: 17, fields }
const method = apiTestModel.methods.look
const actual = gen.makeTheCall(method, inputs)
const expected = `let response = await sdk.ok(sdk.look(
17, '${fields}'))`
expect(actual).toEqual(expected)
})
it('assigns a body param', () => {
const body = {
title: 'test title',
description: 'gen test',
query: {
model: 'the_look',
view: 'users',
total: true,
},
}
const inputs = { look_id: 17, body, fields }
const method = apiTestModel.methods.update_look
const actual = gen.makeTheCall(method, inputs)
const expected = `let response = await sdk.ok(sdk.update_look(
17, {
title: 'test title',
description: 'gen test',
query: {
model: 'the_look',
view: 'users',
total: true
}
}, 'id,user_id,title,description'))`
expect(actual).toEqual(expected)
})
it('assigns request params', () => {
const inputs = { look_id: 17, result_format: 'png' }
const method = apiTestModel.methods.run_look
const actual = gen.makeTheCall(method, inputs)
const expected = `let response = await sdk.ok(sdk.run_look(
{
look_id: 17,
result_format: 'png'
}))`
expect(actual).toEqual(expected)
})
it('assigns an enum', () => {
const inputs = {
body: {
query_id: 1,
result_format: 'csv',
},
}
const method = apiTestModel.methods.create_query_task
const actual = gen.makeTheCall(method, inputs)
const expected = `let response = await sdk.ok(sdk.create_query_task(
{
body: {
query_id: 1,
result_format: ResultFormat.csv
}
}))`
expect(actual).toEqual(expected)
})
it('assigns a DelimArray', () => {
const inputs = {
ids: new DelimArray<number>([1, 2, 3]),
}
const method = apiTestModel.methods.all_users
const actual = gen.makeTheCall(method, inputs)
const expected = `let response = await sdk.ok(sdk.all_users(
{
ids: new DelimArray<number>([1,2,3])
}))`
expect(actual).toEqual(expected)
})
it('assigns simple and complex arrays', () => {
const body = {
pivots: ['one', 'two', 'three'],
sorts: ['a'],
source_queries: [
{
name: 'first query',
query_id: 1,
merge_fields: [
{
field_name: 'merge_1',
source_field_name: 'source_1',
},
],
},
{
name: 'second query',
query_id: 2,
merge_fields: [
{
field_name: 'merge_2',
source_field_name: 'source_2',
},
],
},
],
}
const inputs = { body, fields }
const method = apiTestModel.methods.create_merge_query
const actual = gen.makeTheCall(method, inputs)
const expected = `let response = await sdk.ok(sdk.create_merge_query(
{
body: {
pivots: [
'one',
'two',
'three'
],
sorts: ['a'],
source_queries: [
{
merge_fields: [
{
field_name: 'merge_1',
source_field_name: 'source_1'
}
],
name: 'first query',
query_id: 1
},
{
merge_fields: [
{
field_name: 'merge_2',
source_field_name: 'source_2'
}
],
name: 'second query',
query_id: 2
}
]
},
fields: 'id,user_id,title,description'
}))`
expect(actual).toEqual(expected)
})
it('assigns dictionaries', () => {
const query = {
connection_name: 'looker',
model_name: 'the_look',
vis_config: { first: 1, second: 'two' },
}
const inputs = { body: query }
const method = apiTestModel.methods.create_sql_query
const expected = `let response = await sdk.ok(sdk.create_sql_query(
{
connection_name: 'looker',
model_name: 'the_look',
vis_config: {
first: 1,
second: 'two'
}
}))`
const actual = gen.makeTheCall(method, inputs)
expect(actual).toEqual(expected)
})
describe('hashValue', () => {
it('assigns a hash with heterogeneous values', () => {
const token = {
access_token: 'backstage',
token_type: 'test',
expires_in: 10,
}
const oneItem = [1]
const threeItems = ['Abe', 'Zeb', token]
const inputs = {
item: oneItem,
items: threeItems,
first: 1,
second: 'two',
third: false,
token,
}
const expected = `{
item: [1],
items: [
'Abe',
'Zeb',
{
access_token: 'backstage',
token_type: 'test',
expires_in: 10
}
],
first: 1,
second: 'two',
third: false,
token: {
access_token: 'backstage',
token_type: 'test',
expires_in: 10
}
}`
const actual = gen.hashValue('', inputs)
expect(actual).toEqual(expected)
})
})
describe('assignType', () => {
it('assigns a complex type', () => {
const inputs = {
name: 'first query',
query_id: 1,
merge_fields: [
{
field_name: 'merge_1',
source_field_name: 'source_1',
},
],
}
const type = apiTestModel.types.MergeQuerySourceQuery
expect(type).toBeDefined()
const expected = `{
merge_fields: [
{
field_name: 'merge_1',
source_field_name: 'source_1'
}
],
name: 'first query',
query_id: 1
}`
const actual = gen.assignType(gen.indentStr, type, inputs)
expect(actual).toEqual(expected)
})
})
describe('arrayValue', () => {
it('assigns complex arrays', () => {
const sourceQueries = [
{
name: 'first query',
query_id: 1,
merge_fields: [
{
field_name: 'merge_1',
source_field_name: 'source_1',
},
],
},
{
name: 'second query',
query_id: 2,
merge_fields: [
{
field_name: 'merge_2',
source_field_name: 'source_2',
},
],
},
]
const props = apiTestModel.types.WriteMergeQuery.properties
const type = props.source_queries.type
expect(type).toBeDefined()
const actual = gen.arrayValue('', type, sourceQueries)
const expected = `[
{
merge_fields: [
{
field_name: 'merge_1',
source_field_name: 'source_1'
}
],
name: 'first query',
query_id: 1
},
{
merge_fields: [
{
field_name: 'merge_2',
source_field_name: 'source_2'
}
],
name: 'second query',
query_id: 2
}
]`
expect(actual).toEqual(expected)
})
})
})
describe('args locations', () => {
it('path and query args', () => {
const method = apiTestModel.methods.run_query
expect(method.pathArgs).toEqual(['query_id', 'result_format'])
expect(method.bodyArg).toEqual('')
expect(method.queryArgs).toEqual([
'limit',
'apply_formatting',
'apply_vis',
'cache',
'image_width',
'image_height',
'generate_drill_links',
'force_production',
'cache_only',
'path_prefix',
'rebuild_pdts',
'server_table_calcs',
])
expect(method.headerArgs).toEqual([])
expect(method.cookieArgs).toEqual([])
})
it('body for create_query', () => {
const method = apiTestModel.methods.create_query
expect(method.pathArgs).toEqual([])
const body = method.getParams('body')
expect(body.length).toEqual(1)
expect(body[0].type.name).toEqual('Query')
const param = gen.declareParameter(indent, method, body[0])
expect(param).toEqual(`body: Partial<IWriteQuery>`)
expect(method.bodyArg).toEqual('body')
expect(method.queryArgs).toEqual(['fields'])
expect(method.headerArgs).toEqual([])
expect(method.cookieArgs).toEqual([])
})
it('body for create_dashboard', () => {
const method = apiTestModel.methods.create_dashboard
expect(method.pathArgs).toEqual([])
const body = method.getParams('body')
expect(body.length).toEqual(1)
expect(body[0].type.name).toEqual('Dashboard')
const param = gen.declareParameter(indent, method, body[0])
expect(param).toEqual(`body: Partial<IWriteDashboard>`)
expect(method.bodyArg).toEqual('body')
expect(method.queryArgs).toEqual([])
expect(method.headerArgs).toEqual([])
expect(method.cookieArgs).toEqual([])
})
})
describe('httpArgs', () => {
it('add_group_group', () => {
const method = apiTestModel.methods.add_group_group
const args = gen.httpArgs('', method).trim()
expect(args).toEqual('null, body, options')
})
it('create_query', () => {
const method = apiTestModel.methods.create_query
const args = gen.httpArgs('', method).trim()
expect(args).toEqual('{fields}, body, options')
})
it('create_dashboard', () => {
const method = apiTestModel.methods.create_dashboard
const args = gen.httpArgs('', method).trim()
expect(args).toEqual('null, body, options')
})
})
describe('method signature', () => {
// TODO find a new method with an optional body, or modify these tests to use other non-Looker spec input
it('optional body and additional param', () => {
const method = apiTestModel.methods.create_user_credentials_email
expect(method).toBeDefined()
const expected = `/**
* ### Email/password login information for the specified user.
*
* POST /users/{user_id}/credentials_email -> ICredentialsEmail
*
* @param user_id id of user
* @param body Partial<IWriteCredentialsEmail>
* @param fields Requested fields.
* @param options one-time API call overrides
*
*/
async create_user_credentials_email(
user_id: number,
body: Partial<IWriteCredentialsEmail>,
fields?: string, options?: Partial<ITransportSettings>): Promise<SDKResponse<ICredentialsEmail, IError | IValidationError>> {
`
const actual = gen.methodSignature('', method)
expect(actual).toEqual(expected)
})
it('noComment optional body and additional param', () => {
const method = apiTestModel.methods.create_user_credentials_email
expect(method).toBeDefined()
const expected = `async create_user_credentials_email(
user_id: number,
body: Partial<IWriteCredentialsEmail>,
fields?: string, options?: Partial<ITransportSettings>): Promise<SDKResponse<ICredentialsEmail, IError | IValidationError>> {
`
gen.noComment = true
const actual = gen.methodSignature('', method)
gen.noComment = false
expect(actual).toEqual(expected)
})
it('no params', () => {
const method = apiTestModel.methods.all_datagroups
expect(method).toBeDefined()
const expected = `/**
* ### Get information about all datagroups.
*
* GET /datagroups -> IDatagroup[]
*
* @param options one-time API call overrides
*
*/
async all_datagroups(options?: Partial<ITransportSettings>): Promise<SDKResponse<IDatagroup[], IError>> {
`
const actual = gen.methodSignature('', method)
expect(actual).toEqual(expected)
})
})
describe('method body', () => {
it('encodes string path params', () => {
const method = apiTestModel.methods.run_url_encoded_query
const expected = ` model_name = encodeParam(model_name)
view_name = encodeParam(view_name)
result_format = encodeParam(result_format)
`
const actual = gen.encodePathParams('', method)
expect(actual).toEqual(expected)
})
// TODO eventually add method that has a date type path param
it('encodes only string or date path params', () => {
const method = apiTestModel.methods.run_look
// should NOT escape request.look_id (int)
const expected =
' request.result_format = encodeParam(request.result_format)\n'
const actual = gen.encodePathParams('', method)
expect(actual).toEqual(expected)
})
it('assert response is model add_group_group', () => {
const method = apiTestModel.methods.add_group_group
const expected =
// eslint-disable-next-line no-template-curly-in-string
'return this.post<IGroup, IError>(`/groups/${group_id}/groups`, null, body, options)'
const actual = gen.httpCall(indent, method)
expect(actual).toEqual(expected)
})
it('assert response is None delete_group_from_group', () => {
const method = apiTestModel.methods.delete_group_from_group
const expected =
// eslint-disable-next-line no-template-curly-in-string
'return this.delete<void, IError>(`/groups/${group_id}/groups/${deleting_group_id}`, null, null, options)'
const actual = gen.httpCall(indent, method)
expect(actual).toEqual(expected)
})
it('assert response is list active_themes', () => {
const method = apiTestModel.methods.active_themes
const expected = `return this.get<ITheme[], IError>('/themes/active', {name: request.name, ts: request.ts, fields: request.fields}, null, options)`
const actual = gen.httpCall(indent, method)
expect(actual).toEqual(expected)
})
})
describe('accessor syntax', () => {
it.each<[string, string, string]>([
['foo', '', 'foo'],
['foo', 'bar', 'bar.foo'],
['f-o-o', 'bar', "bar['f-o-o']"],
])('name:"%s" prefix:"%s" should be "%s"', (name, prefix, expected) => {
const actual = gen.accessor(name, prefix)
expect(actual).toEqual(expected)
})
})
describe('complete declarations', () => {
it('streaming method', () => {
const method = apiTestModel.methods.logout
const expected = `/**
* ### Logout of the API and invalidate the current access token.
*
* DELETE /logout -> string
*
* @param callback streaming output function
* @param options one-time API call overrides
*
*/
async logout(
callback: (readable: Readable) => Promise<string>,options?: Partial<ITransportSettings>) {
return this.authStream<string>(callback, 'DELETE', '/logout', null, null, options)
}`
const actual = gen.declareStreamer(indent, method)
expect(actual).toEqual(expected)
})
it('method with request body', () => {
const method = apiTestModel.methods.create_dashboard_render_task
const expected = `/**
* ### Create a new task to render a dashboard to a document or image.
*
* Returns a render task object.
* To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task).
* Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results).
*
* POST /render_tasks/dashboards/{dashboard_id}/{result_format} -> IRenderTask
*
* @param request composed interface "IRequestCreateDashboardRenderTask" for complex method parameters
* @param options one-time API call overrides
*
*/
async create_dashboard_render_task(request: IRequestCreateDashboardRenderTask, options?: Partial<ITransportSettings>): Promise<SDKResponse<IRenderTask, IError | IValidationError>> {
request.dashboard_id = encodeParam(request.dashboard_id)
request.result_format = encodeParam(request.result_format)
return this.post<IRenderTask, IError | IValidationError>(\`/render_tasks/dashboards/\${request.dashboard_id}/\${request.result_format}\`, {width: request.width, height: request.height, fields: request.fields, pdf_paper_size: request.pdf_paper_size, pdf_landscape: request.pdf_landscape, long_tables: request.long_tables}, request.body, options)
}`
const actual = gen.declareMethod(indent, method)
expect(actual).toEqual(expected)
})
it('function with request body', () => {
const method = apiTestModel.methods.create_dashboard_render_task
const expected = `/**
* ### Create a new task to render a dashboard to a document or image.
*
* Returns a render task object.
* To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task).
* Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results).
*
* POST /render_tasks/dashboards/{dashboard_id}/{result_format} -> IRenderTask
*
* @param sdk IAPIMethods implementation
* @param request composed interface "IRequestCreateDashboardRenderTask" for complex method parameters
* @param options one-time API call overrides
*
*/
export const create_dashboard_render_task = async (sdk: IAPIMethods, request: IRequestCreateDashboardRenderTask, options?: Partial<ITransportSettings>): Promise<SDKResponse<IRenderTask, IError | IValidationError>> => {
request.dashboard_id = encodeParam(request.dashboard_id)
request.result_format = encodeParam(request.result_format)
return sdk.post<IRenderTask, IError | IValidationError>(\`/render_tasks/dashboards/\${request.dashboard_id}/\${request.result_format}\`, {width: request.width, height: request.height, fields: request.fields, pdf_paper_size: request.pdf_paper_size, pdf_landscape: request.pdf_landscape, long_tables: request.long_tables}, request.body, options)
}`
const actual = gen.declareFunction(indent, method)
expect(actual).toEqual(expected)
})
it('interface with request body', () => {
const method = apiTestModel.methods.create_dashboard_render_task
const expected = `/**
* ### Create a new task to render a dashboard to a document or image.
*
* Returns a render task object.
* To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task).
* Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results).
*
* POST /render_tasks/dashboards/{dashboard_id}/{result_format} -> IRenderTask
*
* @param request composed interface "IRequestCreateDashboardRenderTask" for complex method parameters
* @param options one-time API call overrides
*
*/
create_dashboard_render_task(request: IRequestCreateDashboardRenderTask, options?: Partial<ITransportSettings>): Promise<SDKResponse<IRenderTask, IError | IValidationError>>
`
const actual = gen.declareInterface(indent, method)
expect(actual).toEqual(expected)
})
it('method without request body', () => {
const method = apiTestModel.methods.content_thumbnail
const expected = `/**
* ### Get an image representing the contents of a dashboard or look.
*
* The returned thumbnail is an abstract representation of the contents of a dashbord or look and does not
* reflect the actual data displayed in the respective visualizations.
*
* GET /content_thumbnail/{type}/{resource_id} -> string
*
* @remarks
* **NOTE**: Binary content may be returned by this function.
*
* @param request composed interface "IRequestContentThumbnail" for complex method parameters
* @param options one-time API call overrides
*
*/
async content_thumbnail(request: IRequestContentThumbnail, options?: Partial<ITransportSettings>): Promise<SDKResponse<string, IError>> {
request.type = encodeParam(request.type)
request.resource_id = encodeParam(request.resource_id)
return this.get<string, IError>(\`/content_thumbnail/$\{request.type}/\${request.resource_id}\`, {reload: request.reload, format: request.format, width: request.width, height: request.height}, null, options)
}`
const actual = gen.declareMethod(indent, method)
expect(actual).toEqual(expected)
})
it('function without request body', () => {
const method = apiTestModel.methods.content_thumbnail
const expected = `/**
* ### Get an image representing the contents of a dashboard or look.
*
* The returned thumbnail is an abstract representation of the contents of a dashbord or look and does not
* reflect the actual data displayed in the respective visualizations.
*
* GET /content_thumbnail/{type}/{resource_id} -> string
*
* @remarks
* **NOTE**: Binary content may be returned by this function.
*
* @param sdk IAPIMethods implementation
* @param request composed interface "IRequestContentThumbnail" for complex method parameters
* @param options one-time API call overrides
*
*/
export const content_thumbnail = async (sdk: IAPIMethods, request: IRequestContentThumbnail, options?: Partial<ITransportSettings>): Promise<SDKResponse<string, IError>> => {
request.type = encodeParam(request.type)
request.resource_id = encodeParam(request.resource_id)
return sdk.get<string, IError>(\`/content_thumbnail/$\{request.type}/\${request.resource_id}\`, {reload: request.reload, format: request.format, width: request.width, height: request.height}, null, options)
}`
const actual = gen.declareFunction(indent, method)
expect(actual).toEqual(expected)
})
it('deprecated function', () => {
const method = apiTestModel.methods.vector_thumbnail
const expected = `/**
* ### Get a vector image representing the contents of a dashboard or look.
*
* # DEPRECATED: Use [content_thumbnail()](#!/Content/content_thumbnail)
*
* The returned thumbnail is an abstract representation of the contents of a dashbord or look and does not
* reflect the actual data displayed in the respective visualizations.
*
* GET /vector_thumbnail/{type}/{resource_id} -> string
*
* @deprecated
*
* @param sdk IAPIMethods implementation
* @param type Either dashboard or look
* @param resource_id ID of the dashboard or look to render
* @param reload Whether or not to refresh the rendered image with the latest content
* @param options one-time API call overrides
*
*/
export const vector_thumbnail = async (
sdk: IAPIMethods,
type: string,
resource_id: string,
reload?: string, options?: Partial<ITransportSettings>): Promise<SDKResponse<string, IError>> => {
type = encodeParam(type)
resource_id = encodeParam(resource_id)
return sdk.get<string, IError>(\`/vector_thumbnail/$\{type}/$\{resource_id}\`, {reload}, null, options)
}`
const actual = gen.declareFunction(indent, method)
expect(actual).toEqual(expected)
})
it('interface without request body', () => {
const method = apiTestModel.methods.content_thumbnail
const expected = `/**
* ### Get an image representing the contents of a dashboard or look.
*
* The returned thumbnail is an abstract representation of the contents of a dashbord or look and does not
* reflect the actual data displayed in the respective visualizations.
*
* GET /content_thumbnail/{type}/{resource_id} -> string
*
* @remarks
* **NOTE**: Binary content may be returned by this function.
*
* @param request composed interface "IRequestContentThumbnail" for complex method parameters
* @param options one-time API call overrides
*
*/
content_thumbnail(request: IRequestContentThumbnail, options?: Partial<ITransportSettings>): Promise<SDKResponse<string, IError>>
`
const actual = gen.declareInterface(indent, method)
expect(actual).toEqual(expected)
})
it('interface without initializer', () => {
const method = apiTestModel.methods.fetch_integration_form
const expected = `/**
* Returns the Integration form for presentation to the user.
*
* POST /integrations/{integration_id}/form -> IDataActionForm
*
* @param integration_id Id of integration
* @param body Partial<IDictionary<string>>
* @param options one-time API call overrides
*
*/
fetch_integration_form(
integration_id: string,
body?: Partial<IDictionary<string>>, options?: Partial<ITransportSettings>): Promise<SDKResponse<IDataActionForm, IError | IValidationError>>
`
const actual = gen.declareInterface(indent, method)
expect(actual).toEqual(expected)
})
})
describe('type creation', () => {
it('request type with body', () => {
const method = apiTestModel.methods.create_dashboard_render_task
const type = apiTestModel.getRequestType(method)
expect(type).toBeDefined()
if (type) {
const dashboard_id = type.properties.dashboard_id
const actual_dashboard_id = gen.declareProperty(indent, dashboard_id)
expect(actual_dashboard_id).toEqual(`/**
* Id of dashboard to render. The ID can be a LookML dashboard also.
*/
dashboard_id: string`)
const body = type.properties.body
const actual_body = gen.declareProperty(indent, body)
expect(actual_body).toEqual(`/**
* body parameter for dynamically created request type
*/
body: ICreateDashboardRenderTask`)
}
})
it('with arrays and hashes', () => {
const type = apiTestModel.types.Workspace
const actual = gen.declareType(indent, type)
expect(actual).toEqual(`export interface IWorkspace {
/**
* Operations the current user is able to perform on this object (read-only)
*/
can?: IDictionary<boolean>
/**
* The unique id of this user workspace. Predefined workspace ids include "production" and "dev" (read-only)
*/
id?: string
/**
* The local state of each project in the workspace (read-only)
*/
projects?: IProject[]
}`)
})
it('with refs, arrays and nullable', () => {
const type = apiTestModel.types.ApiVersion
const actual = gen.declareType(indent, type)
expect(actual).toEqual(`export interface IApiVersion {
/**
* Current Looker release version number (read-only)
*/
looker_release_version?: string
current_version?: IApiVersionElement
/**
* Array of versions supported by this Looker instance (read-only)
*/
supported_versions?: IApiVersionElement[]
}`)
})
it('required properties', () => {
const type = apiTestModel.types.CreateQueryTask
const actual = gen.declareType(indent, type)
const name = titleCase('result_format')
expect(actual).toEqual(`export interface ICreateQueryTask {
/**
* Operations the current user is able to perform on this object (read-only)
*/
can?: IDictionary<boolean>
/**
* Id of query to run
*/
query_id: number
/**
* Desired async query result format. Valid values are: "inline_json", "json", "json_detail", "json_fe", "csv", "html", "md", "txt", "xlsx", "gsxml".
*/
result_format: ${name}
/**
* Source of query task
*/
source?: string
/**
* Create the task but defer execution
*/
deferred?: boolean
/**
* Id of look associated with query.
*/
look_id?: number
/**
* Id of dashboard associated with query.
*/
dashboard_id?: string
}`)
})
describe('special symbol names', () => {
interface HiFen {
'a-one': string
'a two': boolean
'a-three': number
}
it('handles special names in json', () => {
const json = `{"a-one":"one", "a two":true, "a-three":3}`
const actual: HiFen = JSON.parse(json)
expect(actual['a-one']).toEqual('one')
expect(actual['a two']).toEqual(true)
expect(actual['a-three']).toEqual(3)
})
it('does not reserve body param array type names', () => {
const actual = gen.reserve('IProjectGeneratorTable[]')
expect(actual).toEqual('IProjectGeneratorTable[]')
})
it('reserves special names in method parameters', () => {
const method = apiTestModel.methods.me
const save = method.params[0].name
method.params[0].name = 'hi-test'
const actual = gen.declareMethod(indent, method)
method.params[0].name = save
const expected = `/**
* ### Get information about the current user; i.e. the user account currently calling the API.
*
* GET /user -> IUser
*
* @param hi-test Requested fields.
* @param options one-time API call overrides
*
*/
async me(
'hi-test'?: string, options?: Partial<ITransportSettings>): Promise<SDKResponse<IUser, IError>> {
return this.get<IUser, IError>('/user', {'hi-test'}, null, options)
}`
expect(actual).toEqual(expected)
})
it('reserves special names in method request objects', () => {
const method = apiTestModel.methods.role_users
const swap = 2
const save = method.params[swap].name
method.params[swap].name = 'direct-association-only'
const actual = gen.declareMethod(indent, method)
method.params[swap].name = save
const expected = `/**
* ### Get information about all the users with the role that has a specific id.
*
* GET /roles/{role_id}/users -> IUser[]
*
* @param request composed interface "IRequestRoleUsers" for complex method parameters
* @param options one-time API call overrides
*
*/
async role_users(request: IRequestRoleUsers, options?: Partial<ITransportSettings>): Promise<SDKResponse<IUser[], IError>> {
return this.get<IUser[], IError>(\`/roles/\${request.role_id}/users\`, {fields: request.fields, 'direct-association-only': request['direct-association-only']}, null, options)
}`
expect(actual).toEqual(expected)
})
})
describe('enums', () => {
it('Result format declaration', () => {
const type =
apiTestModel.types.CreateQueryTask.properties.result_format.type
expect(type instanceof EnumType).toBeTruthy()
const actual = gen.declareType('', type)
expect(actual).toEqual(`/**
* Desired async query result format. Valid values are: "inline_json", "json", "json_detail", "json_fe", "csv", "html", "md", "txt", "xlsx", "gsxml".
*/
export enum ResultFormat {
inline_json = 'inline_json',
json = 'json',
json_detail = 'json_detail',
json_fe = 'json_fe',
csv = 'csv',
html = 'html',
md = 'md',
txt = 'txt',
xlsx = 'xlsx',
gsxml = 'gsxml'
}`)
})
it('Align declaration', () => {
const type =
apiTestModel.types.LookmlModelExploreField.properties.align.type
expect(type instanceof EnumType).toBeTruthy()
const actual = gen.declareType('', type)
expect(actual).toEqual(`/**
* The appropriate horizontal text alignment the values of this field should be displayed in. Valid values are: "left", "right".
*/
export enum Align {
left = 'left',
right = 'right'
}`)
})
it('array of enums', () => {
const type = apiTestModel.types.RequiredResponseWithEnums
const actual = gen.declareType(indent, type)
expect(actual).toEqual(`export interface IRequiredResponseWithEnums {
/**
* Id of query to run
*/
query_id: number
/**
* Desired async query result format. Valid values are: "inline_json", "json", "json_detail", "json_fe", "csv", "html", "md", "txt", "xlsx", "gsxml".
*/
result_format: ResultFormat
/**
* An array of user attribute types that are allowed to be used in filters on this field. Valid values are: "advanced_filter_string", "advanced_filter_number", "advanced_filter_datetime", "string", "number", "datetime", "relative_url", "yesno", "zipcode". (read-only)
*/
an_array_of_enums?: AnArrayOfEnums[]
user: IUserPublic
/**
* Roles assigned to group (read-only)
*/
roles?: IRole[]
}`)
})
})
})
}) | the_stack |
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ComponentRef,
EventEmitter,
Inject,
InjectionToken,
Input,
NgZone,
OnDestroy,
OnInit,
Optional,
Output,
ViewContainerRef
} from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { ComponentPortal } from '@angular/cdk/portal';
import {
BlockScrollStrategy,
Overlay,
OverlayConfig,
OverlayRef,
PositionStrategy,
ScrollStrategy
} from '@angular/cdk/overlay';
import { ESCAPE, UP_ARROW } from '@angular/cdk/keycodes';
import { coerceArray, coerceBooleanProperty } from '@angular/cdk/coercion';
import { OwlDateTimeContainerComponent } from './date-time-picker-container.component';
import { OwlDateTimeInputDirective } from './date-time-picker-input.directive';
import { DateTimeAdapter } from './adapter/date-time-adapter.class';
import {
OWL_DATE_TIME_FORMATS,
OwlDateTimeFormats
} from './adapter/date-time-format.class';
import {
OwlDateTime,
PickerMode,
PickerType,
SelectMode
} from './date-time.class';
import { OwlDialogRef } from '../dialog/dialog-ref.class';
import { OwlDialogService } from '../dialog/dialog.service';
import { merge, Subscription } from 'rxjs';
import { filter, take } from 'rxjs/operators';
/** Injection token that determines the scroll handling while the dtPicker is open. */
export const OWL_DTPICKER_SCROLL_STRATEGY = new InjectionToken<
() => ScrollStrategy
>('owl-dtpicker-scroll-strategy');
/** @docs-private */
export function OWL_DTPICKER_SCROLL_STRATEGY_PROVIDER_FACTORY(
overlay: Overlay
): () => BlockScrollStrategy {
const fn = () => overlay.scrollStrategies.block();
return fn;
}
/** @docs-private */
export const OWL_DTPICKER_SCROLL_STRATEGY_PROVIDER = {
provide: OWL_DTPICKER_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: OWL_DTPICKER_SCROLL_STRATEGY_PROVIDER_FACTORY
};
@Component({
selector: 'owl-date-time',
exportAs: 'owlDateTime',
templateUrl: './date-time-picker.component.html',
styleUrls: ['./date-time-picker.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
preserveWhitespaces: false
})
export class OwlDateTimeComponent<T> extends OwlDateTime<T>
implements OnInit, OnDestroy {
/** Custom class for the picker backdrop. */
@Input()
public backdropClass: string | string[] = [];
/** Custom class for the picker overlay pane. */
@Input()
public panelClass: string | string[] = [];
/** The date to open the calendar to initially. */
private _startAt: T | null;
@Input()
get startAt(): T | null {
// If an explicit startAt is set we start there, otherwise we start at whatever the currently
// selected value is.
if (this._startAt) {
return this._startAt;
}
if (this._dtInput) {
if (this._dtInput.selectMode === 'single') {
return this._dtInput.value || null;
} else if (
this._dtInput.selectMode === 'range' ||
this._dtInput.selectMode === 'rangeFrom'
) {
return this._dtInput.values[0] || null;
} else if (this._dtInput.selectMode === 'rangeTo') {
return this._dtInput.values[1] || null;
}
} else {
return null;
}
}
set startAt(date: T | null) {
this._startAt = this.getValidDate(
this.dateTimeAdapter.deserialize(date)
);
}
/** The end date to set for range calendar. */
private _endAt: T | null;
@Input()
get endAt(): T | null {
if (this._endAt) {
return this._endAt;
}
if (this._dtInput) {
if (this._dtInput.selectMode === 'single') {
return this._dtInput.value || null;
} else if (
this._dtInput.selectMode === 'range' ||
this._dtInput.selectMode === 'rangeFrom'
) {
return this._dtInput.values[1] || null;
}
} else {
return null;
}
}
set endAt(date: T | null) {
this._endAt = this.getValidDate(
this.dateTimeAdapter.deserialize(date)
);
}
/**
* Set the type of the dateTime picker
* 'both' -- show both calendar and timer
* 'calendar' -- show only calendar
* 'timer' -- show only timer
*/
private _pickerType: PickerType = 'both';
@Input()
get pickerType(): PickerType {
return this._pickerType;
}
set pickerType(val: PickerType) {
if (val !== this._pickerType) {
this._pickerType = val;
if (this._dtInput) {
this._dtInput.formatNativeInputValue();
}
}
}
/**
* Whether the picker open as a dialog
*/
_pickerMode: PickerMode = 'popup';
@Input()
get pickerMode() {
return this._pickerMode;
}
set pickerMode(mode: PickerMode) {
if (mode === 'popup') {
this._pickerMode = mode;
} else {
this._pickerMode = 'dialog';
}
}
/** Whether the date time picker should be disabled. */
private _disabled: boolean;
@Input()
get disabled(): boolean {
return this._disabled === undefined && this._dtInput
? this._dtInput.disabled
: !!this._disabled;
}
set disabled(value: boolean) {
value = coerceBooleanProperty(value);
if (value !== this._disabled) {
this._disabled = value;
this.disabledChange.next(value);
}
}
/** Whether the calendar is open. */
private _opened = false;
@Input()
get opened(): boolean {
return this._opened;
}
set opened(val: boolean) {
val ? this.open() : this.close();
}
/**
* The scroll strategy when the picker is open
* Learn more this from https://material.angular.io/cdk/overlay/overview#scroll-strategies
* */
@Input()
public scrollStrategy: ScrollStrategy;
/**
* Callback when the picker is closed
* */
@Output()
afterPickerClosed = new EventEmitter<any>();
/**
* Callback when the picker is open
* */
@Output()
afterPickerOpen = new EventEmitter<any>();
/**
* Emits selected year in multi-year view
* This doesn't imply a change on the selected date.
* */
@Output()
yearSelected = new EventEmitter<T>();
/**
* Emits selected month in year view
* This doesn't imply a change on the selected date.
* */
@Output()
monthSelected = new EventEmitter<T>();
/**
* Emits selected date
* */
@Output()
dateSelected = new EventEmitter<T>();
/**
* Emit when the selected value has been confirmed
* */
public confirmSelectedChange = new EventEmitter<T[] | T>();
/**
* Emits when the date time picker is disabled.
* */
public disabledChange = new EventEmitter<boolean>();
private pickerContainerPortal: ComponentPortal<
OwlDateTimeContainerComponent<T>
>;
private pickerContainer: OwlDateTimeContainerComponent<T>;
private popupRef: OverlayRef;
private dialogRef: OwlDialogRef<OwlDateTimeContainerComponent<T>>;
private dtInputSub = Subscription.EMPTY;
private hidePickerStreamSub = Subscription.EMPTY;
private confirmSelectedStreamSub = Subscription.EMPTY;
private pickerOpenedStreamSub = Subscription.EMPTY;
/** The element that was focused before the date time picker was opened. */
private focusedElementBeforeOpen: HTMLElement | null = null;
private _dtInput: OwlDateTimeInputDirective<T>;
get dtInput() {
return this._dtInput;
}
private _selected: T | null;
get selected() {
return this._selected;
}
set selected(value: T | null) {
this._selected = value;
this.changeDetector.markForCheck();
}
private _selecteds: T[] = [];
get selecteds() {
return this._selecteds;
}
set selecteds(values: T[]) {
this._selecteds = values;
this.changeDetector.markForCheck();
}
/** The minimum selectable date. */
get minDateTime(): T | null {
return this._dtInput && this._dtInput.min;
}
/** The maximum selectable date. */
get maxDateTime(): T | null {
return this._dtInput && this._dtInput.max;
}
get dateTimeFilter(): (date: T | null) => boolean {
return this._dtInput && this._dtInput.dateTimeFilter;
}
get selectMode(): SelectMode {
return this._dtInput.selectMode;
}
get isInSingleMode(): boolean {
return this._dtInput.isInSingleMode;
}
get isInRangeMode(): boolean {
return this._dtInput.isInRangeMode;
}
private readonly defaultScrollStrategy: () => ScrollStrategy;
constructor(
public overlay: Overlay,
private viewContainerRef: ViewContainerRef,
private dialogService: OwlDialogService,
private ngZone: NgZone,
protected changeDetector: ChangeDetectorRef,
@Optional() protected dateTimeAdapter: DateTimeAdapter<T>,
@Inject(OWL_DTPICKER_SCROLL_STRATEGY) defaultScrollStrategy: any,
@Optional()
@Inject(OWL_DATE_TIME_FORMATS)
protected dateTimeFormats: OwlDateTimeFormats,
@Optional()
@Inject(DOCUMENT)
private document: any
) {
super(dateTimeAdapter, dateTimeFormats);
this.defaultScrollStrategy = defaultScrollStrategy;
}
public ngOnInit() {}
public ngOnDestroy(): void {
this.close();
this.dtInputSub.unsubscribe();
this.disabledChange.complete();
if (this.popupRef) {
this.popupRef.dispose();
}
}
public registerInput(input: OwlDateTimeInputDirective<T>): void {
if (this._dtInput) {
throw Error(
'A Owl DateTimePicker can only be associated with a single input.'
);
}
this._dtInput = input;
this.dtInputSub = this._dtInput.valueChange.subscribe(
(value: T[] | T | null) => {
if (Array.isArray(value)) {
this.selecteds = value;
} else {
this.selected = value;
}
}
);
}
public open(): void {
if (this._opened || this.disabled) {
return;
}
if (!this._dtInput) {
throw Error(
'Attempted to open an DateTimePicker with no associated input.'
);
}
if (this.document) {
this.focusedElementBeforeOpen = this.document.activeElement;
}
// reset the picker selected value
if (this.isInSingleMode) {
this.selected = this._dtInput.value;
} else if (this.isInRangeMode) {
this.selecteds = this._dtInput.values;
}
// when the picker is open , we make sure the picker's current selected time value
// is the same as the _startAt time value.
if (this.selected && this.pickerType !== 'calendar' && this._startAt) {
this.selected = this.dateTimeAdapter.createDate(
this.dateTimeAdapter.getYear(this.selected),
this.dateTimeAdapter.getMonth(this.selected),
this.dateTimeAdapter.getDate(this.selected),
this.dateTimeAdapter.getHours(this._startAt),
this.dateTimeAdapter.getMinutes(this._startAt),
this.dateTimeAdapter.getSeconds(this._startAt)
);
}
this.pickerMode === 'dialog' ? this.openAsDialog() : this.openAsPopup();
this.pickerContainer.picker = this;
// Listen to picker container's hidePickerStream
this.hidePickerStreamSub = this.pickerContainer.hidePickerStream.subscribe(
() => {
this.close();
}
);
// Listen to picker container's confirmSelectedStream
this.confirmSelectedStreamSub = this.pickerContainer.confirmSelectedStream.subscribe(
(event: any) => {
this.confirmSelect(event);
}
);
}
/**
* Selects the given date
*/
public select(date: T[] | T): void {
if (Array.isArray(date)) {
this.selecteds = [...date];
} else {
this.selected = date;
}
/**
* Cases in which automatically confirm the select when date or dates are selected:
* 1) picker mode is NOT 'dialog'
* 2) picker type is 'calendar' and selectMode is 'single'.
* 3) picker type is 'calendar' and selectMode is 'range' and
* the 'selecteds' has 'from'(selecteds[0]) and 'to'(selecteds[1]) values.
* 4) selectMode is 'rangeFrom' and selecteds[0] has value.
* 5) selectMode is 'rangeTo' and selecteds[1] has value.
* */
if (
this.pickerMode !== 'dialog' &&
this.pickerType === 'calendar' &&
((this.selectMode === 'single' && this.selected) ||
(this.selectMode === 'rangeFrom' && this.selecteds[0]) ||
(this.selectMode === 'rangeTo' && this.selecteds[1]) ||
(this.selectMode === 'range' &&
this.selecteds[0] &&
this.selecteds[1]))
) {
this.confirmSelect();
}
}
/**
* Emits the selected year in multi-year view
* */
public selectYear(normalizedYear: T): void {
this.yearSelected.emit(normalizedYear);
}
/**
* Emits selected month in year view
* */
public selectMonth(normalizedMonth: T): void {
this.monthSelected.emit(normalizedMonth);
}
/**
* Emits the selected date
* */
public selectDate(normalizedDate: T): void {
this.dateSelected.emit(normalizedDate);
}
/**
* Hide the picker
*/
public close(): void {
if (!this._opened) {
return;
}
if (this.popupRef && this.popupRef.hasAttached()) {
this.popupRef.detach();
}
if (
this.pickerContainerPortal &&
this.pickerContainerPortal.isAttached
) {
this.pickerContainerPortal.detach();
}
if (this.hidePickerStreamSub) {
this.hidePickerStreamSub.unsubscribe();
this.hidePickerStreamSub = null;
}
if (this.confirmSelectedStreamSub) {
this.confirmSelectedStreamSub.unsubscribe();
this.confirmSelectedStreamSub = null;
}
if (this.pickerOpenedStreamSub) {
this.pickerOpenedStreamSub.unsubscribe();
this.pickerOpenedStreamSub = null;
}
if (this.dialogRef) {
this.dialogRef.close();
this.dialogRef = null;
}
const completeClose = () => {
if (this._opened) {
this._opened = false;
const selected = this.selected || this.selecteds;
this.afterPickerClosed.emit(selected);
this.focusedElementBeforeOpen = null;
}
};
if (
this.focusedElementBeforeOpen &&
typeof this.focusedElementBeforeOpen.focus === 'function'
) {
// Because IE moves focus asynchronously, we can't count on it being restored before we've
// marked the datepicker as closed. If the event fires out of sequence and the element that
// we're refocusing opens the datepicker on focus, the user could be stuck with not being
// able to close the calendar at all. We work around it by making the logic, that marks
// the datepicker as closed, async as well.
this.focusedElementBeforeOpen.focus();
setTimeout(completeClose);
} else {
completeClose();
}
}
/**
* Confirm the selected value
*/
public confirmSelect(event?: any): void {
if (this.isInSingleMode) {
const selected =
this.selected || this.startAt || this.dateTimeAdapter.now();
this.confirmSelectedChange.emit(selected);
} else if (this.isInRangeMode) {
this.confirmSelectedChange.emit(this.selecteds);
}
this.close();
return;
}
/**
* Open the picker as a dialog
*/
private openAsDialog(): void {
this.dialogRef = this.dialogService.open(
OwlDateTimeContainerComponent,
{
autoFocus: false,
backdropClass: [
'cdk-overlay-dark-backdrop',
...coerceArray(this.backdropClass)
],
paneClass: ['owl-dt-dialog', ...coerceArray(this.panelClass)],
viewContainerRef: this.viewContainerRef,
scrollStrategy:
this.scrollStrategy || this.defaultScrollStrategy()
}
);
this.pickerContainer = this.dialogRef.componentInstance;
this.dialogRef.afterOpen().subscribe(() => {
this.afterPickerOpen.emit(null);
this._opened = true;
});
this.dialogRef.afterClosed().subscribe(() => this.close());
}
/**
* Open the picker as popup
*/
private openAsPopup(): void {
if (!this.pickerContainerPortal) {
this.pickerContainerPortal = new ComponentPortal<
OwlDateTimeContainerComponent<T>
>(OwlDateTimeContainerComponent, this.viewContainerRef);
}
if (!this.popupRef) {
this.createPopup();
}
if (!this.popupRef.hasAttached()) {
const componentRef: ComponentRef<
OwlDateTimeContainerComponent<T>
> = this.popupRef.attach(this.pickerContainerPortal);
this.pickerContainer = componentRef.instance;
// Update the position once the calendar has rendered.
this.ngZone.onStable
.asObservable()
.pipe(take(1))
.subscribe(() => {
this.popupRef.updatePosition();
});
// emit open stream
this.pickerOpenedStreamSub = this.pickerContainer.pickerOpenedStream
.pipe(take(1))
.subscribe(() => {
this.afterPickerOpen.emit(null);
this._opened = true;
});
}
}
private createPopup(): void {
const overlayConfig = new OverlayConfig({
positionStrategy: this.createPopupPositionStrategy(),
hasBackdrop: true,
backdropClass: [
'cdk-overlay-transparent-backdrop',
...coerceArray(this.backdropClass)
],
scrollStrategy: this.scrollStrategy || this.defaultScrollStrategy(),
panelClass: ['owl-dt-popup', ...coerceArray(this.panelClass)]
});
this.popupRef = this.overlay.create(overlayConfig);
merge(
this.popupRef.backdropClick(),
this.popupRef.detachments(),
this.popupRef
.keydownEvents()
.pipe(
filter(
event =>
event.keyCode === ESCAPE ||
(this._dtInput &&
event.altKey &&
event.keyCode === UP_ARROW)
)
)
).subscribe(() => this.close());
}
/**
* Create the popup PositionStrategy.
* */
private createPopupPositionStrategy(): PositionStrategy {
return this.overlay
.position()
.flexibleConnectedTo(this._dtInput.elementRef)
.withTransformOriginOn('.owl-dt-container')
.withFlexibleDimensions(false)
.withPush(false)
.withPositions([
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top'
},
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom'
},
{
originX: 'end',
originY: 'bottom',
overlayX: 'end',
overlayY: 'top'
},
{
originX: 'end',
originY: 'top',
overlayX: 'end',
overlayY: 'bottom'
},
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'top',
offsetY: -176
},
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'top',
offsetY: -352
}
]);
}
} | the_stack |
import * as assert from 'assert';
import * as Long from 'long';
import {BitsUtil} from '../util/BitsUtil';
import {Data, DataInput, DataOutput, PositionalDataOutput} from './Data';
import {HeapData, HEAP_DATA_OVERHEAD} from './HeapData';
import {SerializationService} from './SerializationService';
const OUTPUT_BUFFER_INITIAL_SIZE = HEAP_DATA_OVERHEAD + BitsUtil.LONG_SIZE_IN_BYTES;
const MASK_1BYTE = (1 << 8) - 1;
/** @internal */
export class ObjectDataOutput implements DataOutput {
protected buffer: Buffer;
protected bigEndian: boolean;
private service: SerializationService;
private pos: number;
constructor(service: SerializationService, isBigEndian: boolean) {
this.buffer = Buffer.allocUnsafe(OUTPUT_BUFFER_INITIAL_SIZE);
this.service = service;
this.bigEndian = isBigEndian;
this.pos = 0;
}
clear(): void {
this.buffer = Buffer.allocUnsafe(this.buffer.length);
this.pos = 0;
}
isBigEndian(): boolean {
return this.bigEndian;
}
position(newPosition?: number): number {
const oldPos = this.pos;
if (Number.isInteger(newPosition)) {
this.pos = newPosition;
}
return oldPos;
}
toBuffer(): Buffer {
return this.buffer.slice(0, this.pos);
}
write(byte: number | Buffer): void {
if (Buffer.isBuffer(byte)) {
this.ensureAvailable(byte.length);
byte.copy(this.buffer, this.pos);
this.pos += byte.length;
} else {
this.ensureAvailable(BitsUtil.BYTE_SIZE_IN_BYTES);
BitsUtil.writeUInt8(this.buffer, this.pos, byte & MASK_1BYTE);
this.pos += BitsUtil.BYTE_SIZE_IN_BYTES;
}
}
writeBoolean(val: boolean): void {
this.write(val ? 1 : 0);
}
writeBooleanArray(val: boolean[] | null): void {
this.writeArray(this.writeBoolean, val);
}
writeByte(byte: number): void {
this.write(byte);
}
writeByteArray(bytes: Buffer): void {
const len = (bytes != null) ? bytes.length : BitsUtil.NULL_ARRAY_LENGTH;
this.writeInt(len);
if (len > 0) {
this.ensureAvailable(len);
bytes.copy(this.buffer, this.pos);
this.pos += len;
}
}
writeChar(char: string): void {
this.ensureAvailable(BitsUtil.CHAR_SIZE_IN_BYTES);
BitsUtil.writeUInt16(this.buffer, this.pos, char.charCodeAt(0), this.isBigEndian());
this.pos += BitsUtil.CHAR_SIZE_IN_BYTES;
}
writeCharArray(chars: string[]): void {
this.writeArray(this.writeChar, chars);
}
writeChars(chars: string): void {
const len = (chars != null) ? chars.length : BitsUtil.NULL_ARRAY_LENGTH;
this.writeInt(len);
for (let i = 0; i < len; i++) {
this.writeChar(chars.charAt(i));
}
}
writeData(data: Data): void {
const buf = (data != null) ? data.toBuffer() : null;
const len = (buf != null) ? buf.length : BitsUtil.NULL_ARRAY_LENGTH;
this.writeInt(len);
for (let i = 0; i < len; i++) {
this.write((buf as any)[i]);
}
}
writeDouble(double: number): void {
this.ensureAvailable(BitsUtil.DOUBLE_SIZE_IN_BYTES);
BitsUtil.writeDouble(this.buffer, this.pos, double, this.isBigEndian());
this.pos += BitsUtil.DOUBLE_SIZE_IN_BYTES;
}
writeDoubleArray(doubles: number[] | null): void {
this.writeArray(this.writeDouble, doubles);
}
writeFloat(float: number): void {
this.ensureAvailable(BitsUtil.FLOAT_SIZE_IN_BYTES);
BitsUtil.writeFloat(this.buffer, this.pos, float, this.isBigEndian());
this.pos += BitsUtil.FLOAT_SIZE_IN_BYTES;
}
writeFloatArray(floats: number[] | null): void {
this.writeArray(this.writeFloat, floats);
}
writeInt(int: number): void {
this.ensureAvailable(BitsUtil.INT_SIZE_IN_BYTES);
BitsUtil.writeInt32(this.buffer, this.pos, int, this.isBigEndian());
this.pos += BitsUtil.INT_SIZE_IN_BYTES;
}
writeIntBE(int: number): void {
this.ensureAvailable(BitsUtil.INT_SIZE_IN_BYTES);
BitsUtil.writeInt32(this.buffer, this.pos, int, true);
this.pos += BitsUtil.INT_SIZE_IN_BYTES;
}
writeIntArray(ints: number[] | null): void {
this.writeArray(this.writeInt, ints);
}
writeLong(long: Long): void {
this.ensureAvailable(BitsUtil.LONG_SIZE_IN_BYTES);
if (this.isBigEndian()) {
BitsUtil.writeInt32(this.buffer, this.pos, long.high, true);
this.pos += BitsUtil.INT_SIZE_IN_BYTES;
BitsUtil.writeInt32(this.buffer, this.pos, long.low, true);
this.pos += BitsUtil.INT_SIZE_IN_BYTES;
} else {
BitsUtil.writeInt32(this.buffer, this.pos, long.low, false);
this.pos += BitsUtil.INT_SIZE_IN_BYTES;
BitsUtil.writeInt32(this.buffer, this.pos, long.high, false);
this.pos += BitsUtil.INT_SIZE_IN_BYTES;
}
}
writeLongArray(longs: Long[] | null): void {
this.writeArray(this.writeLong, longs);
}
writeObject(object: any): void {
this.service.writeObject(this, object);
}
writeShort(short: number): void {
this.ensureAvailable(BitsUtil.SHORT_SIZE_IN_BYTES);
BitsUtil.writeInt16(this.buffer, this.pos, short, this.isBigEndian());
this.pos += BitsUtil.SHORT_SIZE_IN_BYTES;
}
writeShortArray(shorts: number[] | null): void {
this.writeArray(this.writeShort, shorts);
}
writeUTF(val: string | null): void {
this.writeString(val);
}
writeString(val: string | null): void {
const len = (val != null) ? Buffer.byteLength(val, 'utf8') : BitsUtil.NULL_ARRAY_LENGTH;
this.writeInt(len);
if (len === BitsUtil.NULL_ARRAY_LENGTH) {
return;
}
this.ensureAvailable(len);
this.buffer.write(val, this.pos, this.pos + len, 'utf8');
this.pos += len;
}
writeUTFArray(val: string[] | null): void {
this.writeStringArray(val);
}
writeStringArray(val: string[] | null): void {
this.writeArray(this.writeString, val);
}
writeZeroBytes(count: number): void {
for (let i = 0; i < count; i++) {
this.write(0);
}
}
private available(): number {
return this.buffer == null ? 0 : this.buffer.length - this.pos;
}
private ensureAvailable(size: number): void {
if (this.available() < size) {
const newBuffer = Buffer.allocUnsafe(this.pos + size);
this.buffer.copy(newBuffer, 0, 0, this.pos);
this.buffer = newBuffer;
}
}
private writeArray(func: (val: any) => void, arr: any[] | null): void {
const len = (arr != null) ? arr.length : BitsUtil.NULL_ARRAY_LENGTH;
this.writeInt(len);
if (len > 0) {
const boundFunc = func.bind(this);
arr.forEach(boundFunc);
}
}
}
/** @internal */
export class PositionalObjectDataOutput extends ObjectDataOutput implements PositionalDataOutput {
pwrite(position: number, byte: number | Buffer): void {
if (Buffer.isBuffer(byte)) {
byte.copy(this.buffer, position);
} else {
(this.buffer as any)[position] = byte;
}
}
pwriteBoolean(position: number, val: boolean): void {
this.pwrite(position, val ? 1 : 0);
}
pwriteByte(position: number, byte: number): void {
this.pwrite(position, byte);
}
pwriteChar(position: number, char: string): void {
BitsUtil.writeUInt16(this.buffer, position, char.charCodeAt(0), this.isBigEndian());
}
pwriteDouble(position: number, double: number): void {
BitsUtil.writeDouble(this.buffer, position, double, this.isBigEndian());
}
pwriteFloat(position: number, float: number): void {
BitsUtil.writeFloat(this.buffer, position, float, this.isBigEndian());
}
pwriteInt(position: number, int: number): void {
BitsUtil.writeInt32(this.buffer, position, int, this.isBigEndian());
}
pwriteIntBE(position: number, int: number): void {
BitsUtil.writeInt32(this.buffer, position, int, true);
}
pwriteLong(position: number, long: Long): void {
if (this.isBigEndian()) {
BitsUtil.writeInt32(this.buffer, position, long.high, true);
BitsUtil.writeInt32(this.buffer, position + BitsUtil.INT_SIZE_IN_BYTES, long.low, true);
} else {
BitsUtil.writeInt32(this.buffer, position, long.low, false);
BitsUtil.writeInt32(this.buffer, position + BitsUtil.INT_SIZE_IN_BYTES, long.high, false);
}
}
pwriteShort(position: number, short: number): void {
BitsUtil.writeInt16(this.buffer, position, short, this.isBigEndian());
}
}
/** @internal */
export class ObjectDataInput implements DataInput {
private readonly buffer: Buffer;
private readonly offset: number;
private service: SerializationService;
private readonly bigEndian: boolean;
private pos: number;
constructor(buffer: Buffer,
offset: number,
serializationService: SerializationService,
isBigEndian: boolean) {
this.buffer = buffer;
this.offset = offset;
this.service = serializationService;
this.bigEndian = isBigEndian;
this.pos = this.offset;
}
isBigEndian(): boolean {
return this.bigEndian;
}
position(newPosition?: number): number {
const oldPos = this.pos;
if (Number.isInteger(newPosition)) {
this.pos = newPosition;
}
return oldPos;
}
read(pos?: number): number {
this.assertAvailable(BitsUtil.BYTE_SIZE_IN_BYTES, pos);
if (pos === undefined) {
return BitsUtil.readUInt8(this.buffer, this.pos++);
} else {
return BitsUtil.readUInt8(this.buffer, pos);
}
}
readBoolean(pos?: number): boolean {
return this.read(pos) === 1;
}
readBooleanArray(pos?: number): boolean[] | null {
return this.readArray<boolean>(this.readBoolean, pos);
}
readByte(pos?: number): number {
return this.read(pos);
}
readByteArray(pos?: number): Buffer | null {
const backupPos = this.pos;
if (pos !== undefined) {
this.pos = pos;
}
const len = this.readInt();
if (len === BitsUtil.NULL_ARRAY_LENGTH) {
if (pos !== undefined) {
this.pos = backupPos;
}
return null;
}
const buf = this.buffer.slice(this.pos, this.pos + len);
if (pos !== undefined) {
this.pos = backupPos;
} else {
this.pos += len;
}
return buf;
}
readChar(pos?: number): string {
this.assertAvailable(BitsUtil.CHAR_SIZE_IN_BYTES);
let readBytes: any;
if (pos === undefined) {
readBytes = BitsUtil.readUInt16(this.buffer, this.pos, this.isBigEndian());
this.pos += BitsUtil.CHAR_SIZE_IN_BYTES;
} else {
readBytes = BitsUtil.readUInt16(this.buffer, pos, this.isBigEndian());
}
return String.fromCharCode(readBytes);
}
readCharArray(pos?: number): string[] | null {
return this.readArray<string>(this.readChar, pos);
}
readData(): Data | null {
const bytes = this.readByteArray();
const data: Data = bytes === null ? null : new HeapData(Buffer.from(bytes));
return data;
}
readDouble(pos?: number): number {
this.assertAvailable(BitsUtil.DOUBLE_SIZE_IN_BYTES, pos);
let ret: number;
if (pos === undefined) {
ret = BitsUtil.readDouble(this.buffer, this.pos, this.isBigEndian());
this.pos += BitsUtil.DOUBLE_SIZE_IN_BYTES;
} else {
ret = BitsUtil.readDouble(this.buffer, pos, this.isBigEndian());
}
return ret;
}
readDoubleArray(pos?: number): number[] | null {
return this.readArray<number>(this.readDouble, pos);
}
readFloat(pos?: number): number {
this.assertAvailable(BitsUtil.FLOAT_SIZE_IN_BYTES, pos);
let ret: number;
if (pos === undefined) {
ret = BitsUtil.readFloat(this.buffer, this.pos, this.isBigEndian());
this.pos += BitsUtil.FLOAT_SIZE_IN_BYTES;
} else {
ret = BitsUtil.readFloat(this.buffer, pos, this.isBigEndian());
}
return ret;
}
readFloatArray(pos?: number): number[] | null {
return this.readArray<number>(this.readFloat, pos);
}
readInt(pos?: number): number {
this.assertAvailable(BitsUtil.INT_SIZE_IN_BYTES, pos);
let ret: number;
if (pos === undefined) {
ret = BitsUtil.readInt32(this.buffer, this.pos, this.isBigEndian());
this.pos += BitsUtil.INT_SIZE_IN_BYTES;
} else {
ret = BitsUtil.readInt32(this.buffer, pos, this.isBigEndian());
}
return ret;
}
readIntArray(pos?: number): number[] | null {
return this.readArray<number>(this.readInt, pos);
}
readLong(pos?: number): Long {
this.assertAvailable(BitsUtil.LONG_SIZE_IN_BYTES, pos);
let first: number;
let second: number;
if (pos === undefined) {
first = BitsUtil.readInt32(this.buffer, this.pos, this.isBigEndian());
this.pos += BitsUtil.INT_SIZE_IN_BYTES;
second = BitsUtil.readInt32(this.buffer, this.pos, this.isBigEndian());
this.pos += BitsUtil.INT_SIZE_IN_BYTES;
} else {
first = BitsUtil.readInt32(this.buffer, pos, this.isBigEndian());
second = BitsUtil.readInt32(this.buffer, pos + BitsUtil.INT_SIZE_IN_BYTES, this.isBigEndian());
}
if (this.isBigEndian()) {
return new Long(second, first);
} else {
return new Long(first, second);
}
}
readLongArray(pos?: number): Long[] | null {
return this.readArray<Long>(this.readLong, pos);
}
readObject(): any {
return this.service.readObject(this);
}
readShort(pos?: number): number {
this.assertAvailable(BitsUtil.SHORT_SIZE_IN_BYTES, pos);
let ret: number;
if (pos === undefined) {
ret = BitsUtil.readInt16(this.buffer, this.pos, this.isBigEndian());
this.pos += BitsUtil.SHORT_SIZE_IN_BYTES;
} else {
ret = BitsUtil.readInt16(this.buffer, pos, this.isBigEndian());
}
return ret;
}
readShortArray(pos?: number): number[] | null {
return this.readArray<number>(this.readShort, pos);
}
readUnsignedByte(pos?: number): number {
return this.read(pos);
}
readUnsignedShort(pos?: number): number {
return this.readChar(pos).charCodeAt(0);
}
readUTF(pos?: number): string | null {
return this.readString(pos);
}
readString(pos?: number): string | null {
const len = this.readInt(pos);
const readPos = ObjectDataInput.addOrUndefined(pos, 4) || this.pos;
if (len === BitsUtil.NULL_ARRAY_LENGTH) {
return null;
}
const result = this.buffer.toString('utf8', readPos, readPos + len);
if (pos === undefined) {
this.pos += len;
}
return result;
}
readUTFArray(pos?: number): string[] | null {
return this.readStringArray(pos);
}
readStringArray(pos?: number): string[] | null {
return this.readArray<string>(this.readString, pos);
}
reset(): void {
this.pos = 0;
}
skipBytes(count: number): void {
this.pos += count;
}
available(): number {
return this.buffer.length - this.pos;
}
// used in binary compatibility tests
private readRaw(numOfBytes: number): Buffer {
this.assertAvailable(numOfBytes, this.pos);
const raw = this.buffer.slice(this.pos, this.pos + numOfBytes);
this.pos += numOfBytes;
return raw;
}
private readArray<T>(func: () => any, pos?: number): T[] | null {
const backupPos = this.pos;
if (pos !== undefined) {
this.pos = pos;
}
const len = this.readInt();
if (len === BitsUtil.NULL_ARRAY_LENGTH) {
if (pos !== undefined) {
this.pos = backupPos;
}
return null;
}
const arr: T[] = [];
for (let i = 0; i < len; i++) {
arr.push(func.call(this));
}
if (pos !== undefined) {
this.pos = backupPos;
}
return arr;
}
private assertAvailable(numOfBytes: number, pos: number = this.pos): void {
assert(pos >= 0);
assert(pos + numOfBytes <= this.buffer.length);
}
private static addOrUndefined(base: number, adder: number): number {
if (base === undefined) {
return undefined;
} else {
return base + adder;
}
}
} | the_stack |
import { assert, AssertionError } from "chai";
import * as chai from "chai";
import * as chaiAsPromised from "chai-as-promised";
import {
CallbackOptionallyAsync,
ClassTestUI,
Done,
LifecycleSettings,
registerDI,
SuiteSettings,
TestClass,
TestSettings,
TestRunner,
SuiteCallback
} from "./index";
chai.use(chaiAsPromised);
class LoggingClassTestUI extends ClassTestUI {
public log: LoggingClassTestUI.Log;
private readonly logger: LoggingClassTestUI.LoggingRunner;
constructor() {
super(new LoggingClassTestUI.LoggingRunner());
this.log = LoggingClassTestUI.Log.Default;
(this.runner as LoggingClassTestUI.LoggingRunner).ui = this;
this.logger = this.runner as LoggingClassTestUI.LoggingRunner;
}
public get root(): LoggingClassTestUI.ChildInfo[] { return this.logger.peek; }
}
namespace LoggingClassTestUI {
export interface LifecycleInfo {
type: "beforeAll" | "afterAll" | "beforeEach" | "afterEach";
name: string;
callback?: CallbackOptionallyAsync;
settings?: LifecycleSettings;
}
export interface TestInfo {
type: "test";
name: string;
callback?: CallbackOptionallyAsync;
settings?: TestSettings;
}
export interface SuiteInfo {
type: "suite";
name: string;
callback?: (done?: Done) => void;
settings?: SuiteSettings;
children: ChildInfo[];
}
export type ChildInfo = SuiteInfo | TestInfo | LifecycleInfo;
export class LoggingRunner {
public ui: LoggingClassTestUI;
public stack: ChildInfo[][] = [[]];
get peek(): ChildInfo[] { return this.stack[this.stack.length - 1]; }
public suite(name: string, callback: () => void, settings?: SuiteSettings) {
const suite: SuiteInfo = { type: "suite", name, children: [] };
if (settings) { suite.settings = settings; }
if (this.ui.log & LoggingClassTestUI.Log.Callback) { suite.callback = callback; }
this.peek.push(suite);
this.stack.push(suite.children);
try {
callback();
} finally {
this.stack.pop();
}
}
public test(name: string, callback: CallbackOptionallyAsync, settings?: TestSettings) {
const test: TestInfo = { type: "test", name };
if (settings) { test.settings = settings; }
if (this.ui.log & LoggingClassTestUI.Log.Callback) { test.callback = callback; }
this.peek.push(test);
}
public beforeAll(name: string, callback: CallbackOptionallyAsync, settings: LifecycleSettings) {
const before: ChildInfo = { type: "beforeAll", name };
if (settings) { before.settings = settings; }
if (this.ui.log & LoggingClassTestUI.Log.Callback) { before.callback = callback; }
this.peek.push(before);
}
public beforeEach(name: string, callback: CallbackOptionallyAsync, settings: LifecycleSettings) {
if (name === "setup instance" && !(this.ui.log & LoggingClassTestUI.Log.SetupTeardown)) { return; }
const before: ChildInfo = { type: "beforeEach", name };
if (settings) { before.settings = settings; }
if (this.ui.log & LoggingClassTestUI.Log.Callback) { before.callback = callback; }
this.peek.push(before);
}
public afterEach(name: string, callback: CallbackOptionallyAsync, settings: LifecycleSettings) {
if (name === "teardown instance" && !(this.ui.log & LoggingClassTestUI.Log.SetupTeardown)) { return; }
const after: ChildInfo = { type: "afterEach", name };
if (settings) { after.settings = settings; }
if (this.ui.log & LoggingClassTestUI.Log.Callback) { after.callback = callback; }
this.peek.push(after);
}
public afterAll(name: string, callback: CallbackOptionallyAsync, settings: LifecycleSettings) {
const after: ChildInfo = { type: "afterAll", name };
if (settings) { after.settings = settings; }
if (this.ui.log & LoggingClassTestUI.Log.Callback) { after.callback = callback; }
this.peek.push(after);
}
}
export const enum Log {
Default = 0,
SetupTeardown = 1,
Callback = 2,
All = SetupTeardown | Callback
}
}
function cleancov(s: string): string {
return s.replace(/cov_[^.]+[.](f|s)[^+]+[+][+];/g, "");
}
describe("testdeck", function() {
let ui: LoggingClassTestUI;
beforeEach("create ui", function() {
ui = new LoggingClassTestUI();
});
afterEach("clear ui", function() {
ui = null;
});
describe("decorators", function() {
// TODO: `suite("s", () => { it("t", () => {})});`
it("functional usage");
it("plain @suite and @test", function() {
@ui.suite class SimpleSuite {
@ui.test public simpleTest() {}
}
@ui.suite() class SimpleSuite2 {
@ui.test() public simpleTest2() {}
}
assert.deepEqual(ui.root as any, [{
type: "suite",
name: "SimpleSuite",
children: [{
type: "test",
name: "simpleTest",
}]
}, {
type: "suite",
name: "SimpleSuite2",
children: [{
type: "test",
name: "simpleTest2",
}]
}]);
});
it("execution modifier and settings combo", function() {
@ui.suite(ui.slow(10), ui.timeout(20), ui.retries(3))
class SuiteWithTimeouts {
@ui.test(ui.slow(20), ui.timeout(40), ui.retries(5))
public test1() {}
@ui.test
public test2() {}
@ui.test(ui.skip)
public test3() {}
}
@ui.suite
@ui.slow(10)
@ui.timeout(20)
@ui.retries(3)
class SuiteWithTimeoutsAsDecorators {
@ui.test
@ui.slow(5)
@ui.skip
public test1() {}
@ui.test(ui.timeout(10))
@ui.skip(true)
public test2() {}
@ui.test(ui.retries(2))
@ui.skip(false)
public test3() {}
}
@ui.suite
@ui.only
class SuiteOnlyThis {
@ui.test
public test1() {}
@ui.test.skip
public test2() {}
@ui.test.pending()
public test3() {}
@ui.test.only("testXX")
public test4() {}
@ui.test("testYY", ui.only)
public test5() {}
}
@ui.suite.skip
class SkipSuite {}
@ui.suite.pending
class PendingSuite {}
assert.deepEqual(ui.root as any, [{
type: "suite",
name: "SuiteWithTimeouts",
settings: {
slow: 10,
timeout: 20,
retries: 3
},
children: [{
type: "test",
name: "test1",
settings: {
slow: 20,
timeout: 40,
retries: 5
}
}, {
type: "test",
name: "test2"
}, {
type: "test",
name: "test3",
settings: {
execution: "skip"
}
}]
}, {
type: "suite",
name: "SuiteWithTimeoutsAsDecorators",
settings: {
slow: 10,
timeout: 20,
retries: 3
},
children: [{
type: "test",
name: "test1",
settings: {
slow: 5,
execution: "skip"
}
}, {
type: "test",
name: "test2",
settings: {
timeout: 10,
execution: "skip"
}
}, {
type: "test",
name: "test3",
settings: {
retries: 2
}
}]
}, {
type: "suite",
name: "SuiteOnlyThis",
settings: {
execution: "only"
},
children: [{
type: "test",
name: "test1"
}, {
type: "test",
name: "test2",
settings: {
execution: "skip"
}
}, {
type: "test",
name: "test3",
settings: {
execution: "pending"
}
}, {
type: "test",
name: "testXX",
settings: {
execution: "only"
}
}, {
type: "test",
name: "testYY",
settings: {
execution: "only"
}
}]
}, {
type: "suite",
name: "SkipSuite",
settings: {
execution: "skip"
},
children: []
}, {
type: "suite",
name: "PendingSuite",
settings: {
execution: "pending"
},
children: []
}]);
});
it("before and after", function() {
ui.log = LoggingClassTestUI.Log.SetupTeardown;
@ui.suite class SomeSuite {
public static before() {}
public before() {}
public after() {}
public static after() {}
}
assert.deepEqual(ui.root as any, [{
type: "suite",
name: "SomeSuite",
children: [{
type: "beforeAll",
name: "static before"
}, {
type: "beforeEach",
name: "setup instance"
}, {
type: "beforeEach",
name: "before"
}, {
type: "afterEach",
name: "after"
}, {
type: "afterEach",
name: "teardown instance"
}, {
type: "afterAll",
name: "static after"
}]
}]);
});
it("async done callbacks", function() {
ui.log = LoggingClassTestUI.Log.Callback;
@ui.suite class AllSync {
public static before() {}
public before() {}
@ui.test public test() {}
public after() {}
public static after() {}
}
@ui.suite class AllAsync {
public static before(done: Done) {}
public before(done: Done) {}
@ui.test public test(done: Done) {}
public after(done: Done) {}
public static after(done: Done) {}
}
assert.equal(ui.root.length, 2);
const syncSuite = (ui.root[0] as LoggingClassTestUI.SuiteInfo);
const asyncSuite = (ui.root[1] as LoggingClassTestUI.SuiteInfo);
assert.equal(syncSuite.children.length, 5);
assert.equal(asyncSuite.children.length, 5);
syncSuite.children.forEach((child) => assert.equal(child.callback.length, 0));
asyncSuite.children.forEach((child) => assert.equal(child.callback.length, 1));
});
it("named suites and tests", function() {
@ui.suite("My Special Named Suite")
class Suite {
@ui.test("My Special Named Test")
public test() {}
}
assert.deepEqual(ui.root as any, [{
type: "suite",
name: "My Special Named Suite",
children: [{
type: "test",
name: "My Special Named Test"
}]
}]);
});
it("suite can inherit abstract base class, but not another suite", function() {
@ui.suite class Base1 {
@ui.test public test1() {}
}
/* abstract */
class Base2 {
@ui.test public test2() {}
}
assert.throw(function() {
@ui.suite class Derived1 extends Base1 {
@ui.test public test3() {}
}
});
@ui.suite class Derived2 extends Base2 {
@ui.test public test4() {}
}
assert.deepEqual(ui.root as any, [{
type: "suite",
name: "Base1",
children: [{
type: "test",
name: "test1"
}]
}, {
type: "suite",
name: "Derived2",
children: [{
type: "test",
name: "test4"
}, {
type: "test",
name: "test2"
}]
}]);
});
it("params", function() {
@ui.suite
class TestSuite {
@ui.params({ a: 1, b: 2, c: 3 })
@ui.params({ a: 4, b: 5, c: 9 }, "three")
@ui.params.skip({ a: 4, b: 5, c: 6 }, "one")
@ui.params.pending({ a: 4, b: 5, c: 6 }, "two")
@ui.params.only({ a: 4, b: 5, c: 6 })
public test1({ a, b, c }) {}
@ui.params({ a: 1, b: 2, c: 3 })
@ui.params({ a: 4, b: 5, c: 9 })
@ui.params.naming(({ a, b, c }) => `adding ${a} and ${b} must equal ${c}`)
public test2({ a, b, c }) {}
}
assert.deepEqual(ui.root as any, [{
type: "suite",
name: "TestSuite",
children: [{
type: "suite",
name: "test1",
children: [{
type: "test",
name: "test1 0"
}, {
type: "test",
name: "three"
}, {
type: "test",
name: "one",
settings: {
execution: "skip"
}
}, {
type: "test",
name: "two",
settings: {
execution: "pending"
}
}, {
type: "test",
name: "test1 4",
settings: {
execution: "only"
}
}]
}, {
type: "suite",
name: "test2",
children: [{
type: "test",
name: "adding 1 and 2 must equal 3"
}, {
type: "test",
name: "adding 4 and 5 must equal 9"
}]
}]
}]);
});
it("gh-276: regression static after only must not result in error", function() {
ui.log = LoggingClassTestUI.Log.SetupTeardown;
assert.doesNotThrow(function() {
@ui.suite class SomeSuite {
public static after() {}
}
});
});
});
describe("lifecycle hooks", function() {
it("sync tests", function() {
ui.log = LoggingClassTestUI.Log.All;
const cycle: string[] = [];
@ui.suite class MyClass {
constructor() { cycle.push("Constructor"); }
public static before() { cycle.push("Before All"); }
public before() { cycle.push("Before Each"); }
@ui.test public myTest() { cycle.push("Test"); }
public after() { cycle.push("After Each"); }
public static after() { cycle.push("After All"); }
}
const suite = ui.root[0] as LoggingClassTestUI.SuiteInfo;
const callbacks = suite.children.map((c) => c.callback);
assert.equal(callbacks[0].name, "before");
assert.equal(callbacks[0].toString(), 'before() { cycle.push("Before All"); }');
assert.equal(callbacks[1].name, "setupInstance");
assert.equal(callbacks[2].name, "before");
assert.equal(callbacks[2].toString(), 'before() { cycle.push("Before Each"); }');
assert.equal(callbacks[3].name, "myTest");
assert.equal(callbacks[3].toString(), 'myTest() { cycle.push("Test"); }');
assert.equal(callbacks[4].name, "after");
assert.equal(callbacks[4].toString(), 'after() { cycle.push("After Each"); }');
assert.equal(callbacks[5].name, "teardownInstance");
assert.equal(callbacks[6].name, "after");
assert.equal(callbacks[6].toString(), 'after() { cycle.push("After All"); }');
callbacks[0]();
callbacks[1]();
callbacks[2]();
callbacks[3]();
callbacks[4]();
callbacks[5]();
callbacks[6]();
assert.deepEqual(cycle, [
"Before All",
"Constructor",
"Before Each",
"Test",
"After Each",
"After All"
]);
// TODO: Call GC, check if a weak ref to the MyClass will be cleared!
});
it("promise async lifecycle", async function() {
ui.log = LoggingClassTestUI.Log.All;
const cycle: string[] = [];
function ping(): Promise<void> {
return Promise.resolve() as Promise<void>;
}
@ui.suite class MyClass {
constructor() {
cycle.push("Constructor");
}
public static async before() {
cycle.push("Before All");
await ping();
cycle.push("post Before All");
}
public async before() {
cycle.push("Before Each");
await ping();
cycle.push("post Before Each");
}
@ui.test public async myTest() {
cycle.push("Test");
await ping();
cycle.push("post Test");
}
public async after() {
cycle.push("After Each");
await ping();
cycle.push("post After Each");
}
public static async after() {
cycle.push("After All");
await ping();
cycle.push("post After All");
}
}
const suite = ui.root[0] as LoggingClassTestUI.SuiteInfo;
let promise;
promise = suite.children[0].callback();
assert(promise instanceof Promise);
await promise;
suite.children[1].callback();
promise = suite.children[2].callback();
assert(promise instanceof Promise);
await promise;
promise = suite.children[3].callback();
assert(promise instanceof Promise);
await promise;
promise = suite.children[4].callback();
assert(promise instanceof Promise);
await promise;
suite.children[5].callback();
promise = suite.children[6].callback();
assert(promise instanceof Promise);
await promise;
assert.deepEqual(cycle, [
"Before All",
"post Before All",
"Constructor",
"Before Each",
"post Before Each",
"Test",
"post Test",
"After Each",
"post After Each",
"After All",
"post After All"
]);
// TODO: Call GC, check if a weak ref to the MyClass will be cleared!
});
it("callback async lifecycle", async function() {
ui.log = LoggingClassTestUI.Log.All;
const cycle: string[] = [];
function ping(): Promise<void> {
return new Promise<void>((done, err) => setTimeout(done, 0)) as Promise<void>;
}
@ui.suite class MyClass {
constructor() {
cycle.push("Constructor");
}
public static before(done) {
cycle.push("Before All");
setTimeout(() => {
cycle.push("post Before All");
done();
}, 0);
}
public before(done) {
cycle.push("Before Each");
setTimeout(() => {
cycle.push("post Before Each");
done();
}, 0);
}
@ui.test public myTest(done) {
cycle.push("Test");
setTimeout(() => {
cycle.push("post Test");
done();
}, 0);
}
public after(done) {
cycle.push("After Each");
setTimeout(() => {
cycle.push("post After Each");
done();
}, 0);
}
public static after(done) {
cycle.push("After All");
setTimeout(() => {
cycle.push("post After All");
done();
}, 0);
}
}
const suite = ui.root[0] as LoggingClassTestUI.SuiteInfo;
await new Promise((done) => suite.children[0].callback(done));
suite.children[1].callback();
await new Promise((done) => suite.children[2].callback(done));
await new Promise((done) => suite.children[3].callback(done));
await new Promise((done) => suite.children[4].callback(done));
suite.children[5].callback();
await new Promise((done) => suite.children[6].callback(done));
assert.deepEqual(cycle, [
"Before All",
"post Before All",
"Constructor",
"Before Each",
"post Before Each",
"Test",
"post Test",
"After Each",
"post After Each",
"After All",
"post After All"
]);
// TODO: Call GC, check if a weak ref to the MyClass will be cleared!
});
it("throwing tests", function() {
ui.log = LoggingClassTestUI.Log.All;
@ui.suite class Suite {
public static before() { assert.fail(); }
public before() { assert.fail(); }
@ui.test public test() { assert.fail(); }
public after() { assert.fail(); }
public static after() { assert.fail(); }
}
const suite = ui.root[0] as LoggingClassTestUI.SuiteInfo;
assert.throws(suite.children[0].callback);
suite.children[1].callback();
assert.throws(suite.children[2].callback);
assert.throws(suite.children[3].callback);
assert.throws(suite.children[4].callback);
suite.children[5].callback();
assert.throws(suite.children[6].callback);
});
it("throwing async promise", async function() {
ui.log = LoggingClassTestUI.Log.All;
@ui.suite class Suite {
public static before(done) {
setTimeout(function() {
done(new Error("Force fail."));
}, 0);
}
public before(done) {
setTimeout(function() {
done(new Error("Force fail."));
}, 0);
}
@ui.test public test(done) {
setTimeout(function() {
done(new Error("Force fail."));
}, 0);
}
public after(done) {
setTimeout(function() {
done(new Error("Force fail."));
}, 0);
}
public static after(done) {
setTimeout(function() {
done(new Error("Force fail."));
}, 0);
}
}
const suite = ui.root[0] as LoggingClassTestUI.SuiteInfo;
await assert.isRejected(new Promise<void>((resolve, reject) => {
suite.children[0].callback((err?) => err ? reject(err) : resolve());
}) as PromiseLike<any>);
suite.children[1].callback();
await assert.isRejected(new Promise<void>((resolve, reject) => {
suite.children[2].callback((err?) => err ? reject(err) : resolve());
}) as PromiseLike<any>);
await assert.isRejected(new Promise<void>((resolve, reject) => {
suite.children[3].callback((err?) => err ? reject(err) : resolve());
}) as PromiseLike<any>);
await assert.isRejected(new Promise<void>((resolve, reject) => {
suite.children[4].callback((err?) => err ? reject(err) : resolve());
}) as PromiseLike<any>);
suite.children[5].callback();
await assert.isRejected(new Promise<void>((resolve, reject) => {
suite.children[6].callback((err?) => err ? reject(err) : resolve());
}) as PromiseLike<any>);
});
it("throwing async callback", async function() {
ui.log = LoggingClassTestUI.Log.All;
@ui.suite class Suite {
public static async before() {
assert.fail();
}
public async before() {
assert.fail();
}
@ui.test public async test(done) {
assert.fail();
}
public async after(done) {
assert.fail();
}
public static async after(done) {
assert.fail();
}
}
const suite = ui.root[0] as LoggingClassTestUI.SuiteInfo;
await assert.isRejected(suite.children[0].callback() as PromiseLike<void>);
suite.children[1].callback();
await assert.isRejected(suite.children[2].callback() as PromiseLike<void>);
await assert.isRejected(suite.children[3].callback() as PromiseLike<void>);
await assert.isRejected(suite.children[4].callback() as PromiseLike<void>);
suite.children[5].callback();
await assert.isRejected(suite.children[6].callback() as PromiseLike<void>);
});
it("instantiate through dependency injection", function() {
ui.log = LoggingClassTestUI.Log.All;
let x;
let y;
let z;
@ui.suite class XClass {
@ui.test public test() {
assert.equal(this as XClass, x);
}
}
@ui.suite class YClass {
@ui.test public test() {
assert.equal(this as YClass, y);
}
}
@ui.suite class ZClass {
constructor() {
z = this;
}
@ui.test public test() {
assert.equal(this as ZClass, z);
}
}
x = new XClass();
y = new YClass();
registerDI({
handles<T>(cls: TestClass<T>): boolean {
return cls.name.startsWith("X");
},
create<T>(cls: TestClass<T>): T {
return x;
}
});
registerDI({
handles<T>(cls: TestClass<T>): boolean {
return cls.name.startsWith("Y");
},
create<T>(cls: TestClass<T>): T {
return y;
}
});
ui.root
.forEach((suite) => (suite as LoggingClassTestUI.SuiteInfo)
.children
.forEach((c) => c.callback())
);
});
});
describe("regression #248: getters and setters are invoked during initialization of the suite", function() {
it("must not fail on getter or setter during initialization of the test suite", function() {
class Issue248Base {
private readonly mStrings: Set<string>;
constructor() {
this.mStrings = new Set<string>();
}
get strings(): string[] {
return Array.from(this.mStrings);
}
}
@ui.suite
class Issue248Test extends Issue248Base {
constructor() {
super();
}
@ui.test
private testFoo() {
const _ = this.strings;
}
}
});
});
describe("test framework context", function() {
beforeEach(function() {
ui.log = LoggingClassTestUI.Log.All;
});
it("is passed down to sync tests", function() {
let trace: string = "";
@ui.suite
class MySyncTest {
static before() {
trace += `static before(); context: ${this[ClassTestUI.context]};\n`;
}
constructor() {
trace += `constructor(); context: ${this[ClassTestUI.context]};\n`;
}
before(): void {
trace += `before(); context: ${this[ClassTestUI.context]};\n`;
}
@ui.test
myTest1(): void {
trace += `myTest1(); context: ${this[ClassTestUI.context]};\n`;
}
@ui.test
myTest2(): void {
trace += `myTest2(); context: ${this[ClassTestUI.context]};\n`;
}
after(): void {
trace += `after(); context: ${this[ClassTestUI.context]};\n`;
}
static after() {
trace += `static after(); context: ${this[ClassTestUI.context]};\n`;
}
}
const suite = ui.root[0];
if (suite.type !== "suite") throw new AssertionError("Expected a class suite as first root element.");
const suiteBeforeAll = suite.children[0];
if (suiteBeforeAll.type !== "beforeAll" || suiteBeforeAll.name !== "static before") throw new AssertionError("Expected child 0 to be the 'static before'.");
const testInstanceInit = suite.children[1];
if (testInstanceInit.type !== "beforeEach" || testInstanceInit.name !== "setup instance") throw new AssertionError("Expected class 1 to be the 'setup instance' before each.");
const testInstanceBeforeEach = suite.children[2];
if (testInstanceBeforeEach.type !== "beforeEach" || testInstanceBeforeEach.name !== "before") throw new AssertionError("Expected child 2 to be the instance 'before' before-each callback.");
const testMethod1 = suite.children[3];
if (testMethod1.type !== "test" || testMethod1.name !== "myTest1") throw new AssertionError("Expected child 3 to be test method 'myTest1'.");
const testMethod2 = suite.children[4];
if (testMethod2.type !== "test" || testMethod2.name !== "myTest2") throw new AssertionError("Expected child 4 to be test method 'myTest1'.");
const testInstanceAfterEach = suite.children[5];
if (testInstanceAfterEach.type !== "afterEach" || testInstanceAfterEach.name !== "after") throw new AssertionError("Expected child 5 to be the instance 'after' after-each callback.");
const testInstanceTeardown = suite.children[6];
if (testInstanceTeardown.type !== "afterEach" || testInstanceTeardown.name !== "teardown instance") throw new AssertionError("Expected class 6 to be the 'teardown instance' after each.");
const suiteAfterAll = suite.children[7];
if (suiteAfterAll.type !== "afterAll" || suiteAfterAll.name !== "static after") throw new AssertionError("Expected child 7 to be the 'static after'.");
suiteBeforeAll.callback.call("suiteBeforeAll Context");
testInstanceInit.callback.call("testInstanceInit 1 Context");
testInstanceBeforeEach.callback.call("testBeforeEach 1 Context");
testMethod1.callback.call("testMethod 1 Context");
testInstanceAfterEach.callback.call("testAfterEach 1 Context");
testInstanceTeardown.callback.call("testInstanceTeardown 1 Context");
testInstanceInit.callback.call("testInstanceInit 2 Context");
testInstanceBeforeEach.callback.call("testBeforeEach 2 Context");
testMethod2.callback.call("testMethod 2 Context");
testInstanceAfterEach.callback.call("testAfterEach 2 Context");
testInstanceTeardown.callback.call("testInstanceTeardown 2 Context");
suiteAfterAll.callback.call("suiteAfterAll Context");
const expected =
"static before(); context: suiteBeforeAll Context;\n" +
"constructor(); context: testInstanceInit 1 Context;\n" +
"before(); context: testBeforeEach 1 Context;\n" +
"myTest1(); context: testMethod 1 Context;\n" +
"after(); context: testAfterEach 1 Context;\n" +
"constructor(); context: testInstanceInit 2 Context;\n" +
"before(); context: testBeforeEach 2 Context;\n" +
"myTest2(); context: testMethod 2 Context;\n" +
"after(); context: testAfterEach 2 Context;\n" +
"static after(); context: suiteAfterAll Context;\n" +
"";
assert.equal(trace, expected);
});
it("is passed down to async tests", function() {
let trace: string = "";
@ui.suite
class MySyncTest {
static before(done: Done) {
trace += `static before(done); context: ${this[ClassTestUI.context]};\n`;
}
constructor() {
trace += `constructor(); context: ${this[ClassTestUI.context]};\n`;
}
before(done: Done): void {
trace += `before(done); context: ${this[ClassTestUI.context]};\n`;
}
@ui.test
myTest1(done: Done): void {
trace += `myTest1(done); context: ${this[ClassTestUI.context]};\n`;
}
@ui.test
myTest2(done: Done): void {
trace += `myTest2(done); context: ${this[ClassTestUI.context]};\n`;
}
after(done: Done): void {
trace += `after(done); context: ${this[ClassTestUI.context]};\n`;
}
static after(done: Done) {
trace += `static after(done); context: ${this[ClassTestUI.context]};\n`;
}
}
const suite = ui.root[0];
if (suite.type !== "suite") throw new AssertionError("Expected a class suite as first root element.");
const suiteBeforeAll = suite.children[0];
if (suiteBeforeAll.type !== "beforeAll" || suiteBeforeAll.name !== "static before") throw new AssertionError("Expected child 0 to be the 'static before'.");
const testInstanceInit = suite.children[1];
if (testInstanceInit.type !== "beforeEach" || testInstanceInit.name !== "setup instance") throw new AssertionError("Expected class 1 to be the 'setup instance' before each.");
const testInstanceBeforeEach = suite.children[2];
if (testInstanceBeforeEach.type !== "beforeEach" || testInstanceBeforeEach.name !== "before") throw new AssertionError("Expected child 2 to be the instance 'before' before-each callback.");
const testMethod1 = suite.children[3];
if (testMethod1.type !== "test" || testMethod1.name !== "myTest1") throw new AssertionError("Expected child 3 to be test method 'myTest1'.");
const testMethod2 = suite.children[4];
if (testMethod2.type !== "test" || testMethod2.name !== "myTest2") throw new AssertionError("Expected child 4 to be test method 'myTest1'.");
const testInstanceAfterEach = suite.children[5];
if (testInstanceAfterEach.type !== "afterEach" || testInstanceAfterEach.name !== "after") throw new AssertionError("Expected child 5 to be the instance 'after' after-each callback.");
const testInstanceTeardown = suite.children[6];
if (testInstanceTeardown.type !== "afterEach" || testInstanceTeardown.name !== "teardown instance") throw new AssertionError("Expected class 6 to be the 'teardown instance' after each.");
const suiteAfterAll = suite.children[7];
if (suiteAfterAll.type !== "afterAll" || suiteAfterAll.name !== "static after") throw new AssertionError("Expected child 7 to be the 'static after'.");
const ignore = () => {};
suiteBeforeAll.callback.call("suiteBeforeAll Context", ignore);
// TODO: Scramble async tests! Parallel running? Try:
// testInstanceInit (for test 1)
// testInstanceInit (for test 2)
// testInstanceBeforeEach (for test 1)
// testMethod1 (for test 1)
// testInstanceBeforeEach (for test 2)
// testMethod2 (for test 2)
// testInstanceAfterEach (for test 1)
// testInstanceTeardown (for test 1)
// testInstanceAfterEach (for test 2)
// testInstanceTeardown (for test 2)
//
// TODO: We currently make a closure and capture an instance created during before-each,
// but with parallel tests this would fail,
// the test instance should probably be assigned to the test context,
// and cleared from the test context.
// TODO: In the async tests, spend some time awaiting something before calling "done", or try with `@test async myTest()...`
// and check for the context after a while, make sure it is not swapped or cleared before the end of the test execution.
testInstanceInit.callback.call("testInstanceInit 1 Context", ignore);
testInstanceBeforeEach.callback.call("testBeforeEach 1 Context", ignore);
testMethod1.callback.call("testMethod 1 Context", ignore);
testInstanceAfterEach.callback.call("testAfterEach 1 Context", ignore);
testInstanceTeardown.callback.call("testInstanceTeardown 1 Context", ignore);
testInstanceInit.callback.call("testInstanceInit 2 Context", ignore);
testInstanceBeforeEach.callback.call("testBeforeEach 2 Context", ignore);
testMethod2.callback.call("testMethod 2 Context", ignore);
testInstanceAfterEach.callback.call("testAfterEach 2 Context", ignore);
testInstanceTeardown.callback.call("testInstanceTeardown 2 Context", ignore);
suiteAfterAll.callback.call("suiteAfterAll Context", ignore);
const expected =
"static before(done); context: suiteBeforeAll Context;\n" +
"constructor(); context: testInstanceInit 1 Context;\n" +
"before(done); context: testBeforeEach 1 Context;\n" +
"myTest1(done); context: testMethod 1 Context;\n" +
"after(done); context: testAfterEach 1 Context;\n" +
"constructor(); context: testInstanceInit 2 Context;\n" +
"before(done); context: testBeforeEach 2 Context;\n" +
"myTest2(done); context: testMethod 2 Context;\n" +
"after(done); context: testAfterEach 2 Context;\n" +
"static after(done); context: suiteAfterAll Context;\n" +
"";
assert.equal(trace, expected);
});
});
});
declare var setTimeout; | the_stack |
import { AboutApi } from './api/AboutApi';
import { AlfrescoApiActiviti } from './api/AlfrescoApiActiviti';
import { AdminEndpointsApi } from './api/AdminEndpointsApi';
import { AdminGroupsApi } from './api/AdminGroupsApi';
import { AdminTenantsApi } from './api/AdminTenantsApi';
import { AdminUsersApi } from './api/AdminUsersApi';
import { AppsApi } from './api/AppsApi';
import { AppsDefinitionApi } from './api/AppsDefinitionApi';
import { AppsRuntimeApi } from './api/AppsRuntimeApi';
import { CommentsApi } from './api/CommentsApi';
import { ContentApi } from './api/ContentApi';
import { ContentRenditionApi } from './api/ContentRenditionApi';
import { EditorApi } from './api/EditorApi';
import { GroupsApi } from './api/GroupsApi';
import { IDMSyncApi } from './api/IDMSyncApi';
import { IntegrationAccountApi } from './api/IntegrationAccountApi';
import { IntegrationAlfrescoCloudApi } from './api/IntegrationAlfrescoCloudApi';
import { IntegrationAlfrescoOnPremiseApi } from './api/IntegrationAlfrescoOnPremiseApi';
import { IntegrationBoxApi } from './api/IntegrationBoxApi';
import { IntegrationDriveApi } from './api/IntegrationDriveApi';
import { ModelBpmnApi } from './api/ModelBpmnApi';
import { ModelJsonBpmnApi } from './api/ModelJsonBpmnApi';
import { ModelsApi } from './api/ModelsApi';
import { ModelsHistoryApi } from './api/ModelsHistoryApi';
import { ProcessApi } from './api/ProcessApi';
import { ProcessDefinitionsApi } from './api/ProcessDefinitionsApi';
import { ProcessDefinitionsFormApi } from './api/ProcessDefinitionsFormApi';
import { ProcessInstancesApi } from './api/ProcessInstancesApi';
import { ProcessInstancesInformationApi } from './api/ProcessInstancesInformationApi';
import { ProcessInstancesListingApi } from './api/ProcessInstancesListingApi';
import { ProcessInstanceVariablesApi } from './api/ProcessInstanceVariablesApi';
import { ProcessScopeApi } from './api/ProcessScopeApi';
import { ProfileApi } from './api/ProfileApi';
import { ScriptFileApi } from './api/ScriptFileApi';
import { SystemPropertiesApi } from './api/SystemPropertiesApi';
import { TaskApi } from './api/TaskApi';
import { TaskActionsApi } from './api/TaskActionsApi';
import { TaskCheckListApi } from './api/TaskCheckListApi';
import { TaskFormsApi } from './api/TaskFormsApi';
import { TemporaryApi } from './api/TemporaryApi';
import { UserApi } from './api/UserApi';
import { UserFiltersApi } from './api/UserFiltersApi';
import { UsersWorkflowApi } from './api/UsersWorkflowApi';
import { ReportApi } from './api/ReportApi';
import { AlfrescoApiActiviti as _AlfrescoApiActiviti } from './api/AlfrescoApiActiviti';
import { AboutApi as _AboutApi } from './api/AboutApi';
import { AdminEndpointsApi as _AdminEndpointsApi } from './api/AdminEndpointsApi';
import { AdminGroupsApi as _AdminGroupsApi } from './api/AdminGroupsApi';
import { AdminTenantsApi as _AdminTenantsApi } from './api/AdminTenantsApi';
import { AdminUsersApi as _AdminUsersApi } from './api/AdminUsersApi';
import { AppsApi as _AppsApi } from './api/AppsApi';
import { AppsDefinitionApi as _AppsDefinitionApi } from './api/AppsDefinitionApi';
import { AppsRuntimeApi as _AppsRuntimeApi } from './api/AppsRuntimeApi';
import { CommentsApi as _CommentsApi } from './api/CommentsApi';
import { ContentApi as _ContentApi } from './api/ContentApi';
import { ContentRenditionApi as _ContentRenditionApi } from './api/ContentRenditionApi';
import { EditorApi as _EditorApi } from './api/EditorApi';
import { GroupsApi as _GroupsApi } from './api/GroupsApi';
import { IDMSyncApi as _IDMSyncApi } from './api/IDMSyncApi';
import { IntegrationAccountApi as _IntegrationAccountApi } from './api/IntegrationAccountApi';
import { IntegrationAlfrescoCloudApi as _IntegrationAlfrescoCloudApi } from './api/IntegrationAlfrescoCloudApi';
import { IntegrationAlfrescoOnPremiseApi as _IntegrationAlfrescoOnPremiseApi } from './api/IntegrationAlfrescoOnPremiseApi';
import { IntegrationBoxApi as _IntegrationBoxApi } from './api/IntegrationBoxApi';
import { IntegrationDriveApi as _IntegrationDriveApi } from './api/IntegrationDriveApi';
import { ModelBpmnApi as _ModelBpmnApi } from './api/ModelBpmnApi';
import { ModelJsonBpmnApi as _ModelJsonBpmnApi } from './api/ModelJsonBpmnApi';
import { ModelsApi as _ModelsApi } from './api/ModelsApi';
import { ModelsHistoryApi as _ModelsHistoryApi } from './api/ModelsHistoryApi';
import { ProcessApi as _ProcessApi } from './api/ProcessApi';
import { ProcessDefinitionsApi as _ProcessDefinitionsApi } from './api/ProcessDefinitionsApi';
import { ProcessDefinitionsFormApi as _ProcessDefinitionsFormApi } from './api/ProcessDefinitionsFormApi';
import { ProcessInstancesApi as _ProcessInstancesApi } from './api/ProcessInstancesApi';
import { ProcessInstancesInformationApi as _ProcessInstancesInformationApi } from './api/ProcessInstancesInformationApi';
import { ProcessInstancesListingApi as _ProcessInstancesListingApi } from './api/ProcessInstancesListingApi';
import { ProcessInstanceVariablesApi as _ProcessInstanceVariablesApi } from './api/ProcessInstanceVariablesApi';
import { ProcessScopeApi as _ProcessScopeApi } from './api/ProcessScopeApi';
import { ProfileApi as _ProfileApi } from './api/ProfileApi';
import { ScriptFileApi as _ScriptFileApi } from './api/ScriptFileApi';
import { SystemPropertiesApi as _SystemPropertiesApi } from './api/SystemPropertiesApi';
import { TaskApi as _TaskApi } from './api/TaskApi';
import { TaskActionsApi as _TaskActionsApi } from './api/TaskActionsApi';
import { TaskCheckListApi as _TaskCheckListApi } from './api/TaskCheckListApi';
import { TaskFormsApi as _TaskFormsApi } from './api/TaskFormsApi';
import { TemporaryApi as _TemporaryApi } from './api/TemporaryApi';
import { UserApi as _UserApi } from './api/UserApi';
import { UserFiltersApi as _UserFiltersApi } from './api/UserFiltersApi';
import { UsersWorkflowApi as _UsersWorkflowApi } from './api/UsersWorkflowApi';
import { ReportApi as _ReportApi } from './api/ReportApi';
export const APS_LEGACY_APIS = {
AlfrescoApi: AlfrescoApiActiviti,
AboutApi: AboutApi,
AdminEndpointsApi: AdminEndpointsApi,
AdminGroupsApi: AdminGroupsApi,
AdminTenantsApi: AdminTenantsApi,
AdminUsersApi: AdminUsersApi,
AppsApi: AppsApi,
AppsDefinitionApi: AppsDefinitionApi,
AppsRuntimeApi: AppsRuntimeApi,
CommentsApi: CommentsApi,
ContentApi: ContentApi,
ContentRenditionApi: ContentRenditionApi,
EditorApi: EditorApi,
GroupsApi: GroupsApi,
IDMSyncApi: IDMSyncApi,
IntegrationAccountApi: IntegrationAccountApi,
IntegrationAlfrescoCloudApi: IntegrationAlfrescoCloudApi,
IntegrationAlfrescoOnPremiseApi: IntegrationAlfrescoOnPremiseApi,
IntegrationBoxApi: IntegrationBoxApi,
IntegrationDriveApi: IntegrationDriveApi,
ModelBpmnApi: ModelBpmnApi,
ModelJsonBpmnApi: ModelJsonBpmnApi,
ModelsApi: ModelsApi,
ModelsHistoryApi: ModelsHistoryApi,
ProcessApi: ProcessApi,
ProcessDefinitionsApi: ProcessDefinitionsApi,
ProcessDefinitionsFormApi: ProcessDefinitionsFormApi,
ProcessInstancesApi: ProcessInstancesApi,
ProcessInstancesInformationApi: ProcessInstancesInformationApi,
ProcessInstancesListingApi: ProcessInstancesListingApi,
ProcessInstanceVariablesApi: ProcessInstanceVariablesApi,
ProcessScopeApi: ProcessScopeApi,
ProfileApi: ProfileApi,
ScriptFileApi: ScriptFileApi,
SystemPropertiesApi: SystemPropertiesApi,
TaskApi: TaskApi,
TaskActionsApi: TaskActionsApi,
TaskCheckListApi: TaskCheckListApi,
TaskFormsApi: TaskFormsApi,
TemporaryApi: TemporaryApi,
UserApi: UserApi,
UserFiltersApi: UserFiltersApi,
UsersWorkflowApi: UsersWorkflowApi,
ReportApi: ReportApi
};
export namespace Activiti {
export class AlfrescoApi extends _AlfrescoApiActiviti {
}
export class AboutApi extends _AboutApi {
}
export class AdminEndpointsApi extends _AdminEndpointsApi {
}
export class AdminGroupsApi extends _AdminGroupsApi {
}
export class AdminTenantsApi extends _AdminTenantsApi {
}
export class AdminUsersApi extends _AdminUsersApi {
}
export class AppsApi extends _AppsApi {
}
export class AppsDefinitionApi extends _AppsDefinitionApi {
}
export class AppsRuntimeApi extends _AppsRuntimeApi {
}
export class CommentsApi extends _CommentsApi {
}
export class ContentApi extends _ContentApi {
}
export class ContentRenditionApi extends _ContentRenditionApi {
}
export class EditorApi extends _EditorApi {
}
export class GroupsApi extends _GroupsApi {
}
export class IDMSyncApi extends _IDMSyncApi {
}
export class IntegrationAccountApi extends _IntegrationAccountApi {
}
export class IntegrationAlfrescoCloudApi extends _IntegrationAlfrescoCloudApi {
}
export class IntegrationAlfrescoOnPremiseApi extends _IntegrationAlfrescoOnPremiseApi {
}
export class IntegrationBoxApi extends _IntegrationBoxApi {
}
export class IntegrationDriveApi extends _IntegrationDriveApi {
}
export class ModelBpmnApi extends _ModelBpmnApi {
}
export class ModelJsonBpmnApi extends _ModelJsonBpmnApi {
}
export class ModelsApi extends _ModelsApi {
}
export class ModelsHistoryApi extends _ModelsHistoryApi {
}
export class ProcessApi extends _ProcessApi {
}
export class ProcessDefinitionsApi extends _ProcessDefinitionsApi {
}
export class ProcessDefinitionsFormApi extends _ProcessDefinitionsFormApi {
}
export class ProcessInstancesApi extends _ProcessInstancesApi {
}
export class ProcessInstancesInformationApi extends _ProcessInstancesInformationApi {
}
export class ProcessInstancesListingApi extends _ProcessInstancesListingApi {
}
export class ProcessInstanceVariablesApi extends _ProcessInstanceVariablesApi {
}
export class ProcessScopeApi extends _ProcessScopeApi {
}
export class ProfileApi extends _ProfileApi {
}
export class ScriptFileApi extends _ScriptFileApi {
}
export class SystemPropertiesApi extends _SystemPropertiesApi {
}
export class TaskApi extends _TaskApi {
}
export class TaskActionsApi extends _TaskActionsApi {
}
export class TaskCheckListApi extends _TaskCheckListApi {
}
export class TaskFormsApi extends _TaskFormsApi {
}
export class TemporaryApi extends _TemporaryApi {
}
export class UserApi extends _UserApi {
}
export class UserFiltersApi extends _UserFiltersApi {
}
export class UsersWorkflowApi extends _UsersWorkflowApi {
}
export class ReportApi extends _ReportApi {
}
} | the_stack |
import { SpreadsheetHelper } from "../util/spreadsheethelper.spec";
import { defaultData } from '../util/datasource.spec';
import { CellModel, DialogBeforeOpenEventArgs, Spreadsheet, dialog, getCell, SheetModel, ValidationModel } from "../../../src/index";
import { Dialog } from "../../../src/spreadsheet/services/index";
describe('Data validation ->', () => {
let helper: SpreadsheetHelper = new SpreadsheetHelper('spreadsheet');
describe('Public Method ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{
ranges: [{
dataSource: defaultData
}],
}]
}, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('', (done: Function) => {
helper.invoke('addDataValidation', [{ type: 'TextLength', operator: 'LessThanOrEqualTo', value1: '12' }, 'A2:A7']);
const cell: CellModel = helper.getInstance().sheets[0].rows[1].cells[0];
expect(JSON.stringify(cell.validation)).toBe('{"type":"TextLength","operator":"LessThanOrEqualTo","value1":"12"}');
helper.invoke('addInvalidHighlight', ['A2:A7']);
let td: HTMLElement = helper.invoke('getCell', [1, 0]);
expect(td.style.backgroundColor).toBe('rgb(255, 255, 255)');
expect(td.style.color).toBe('rgb(0, 0, 0)');
td = helper.invoke('getCell', [4, 0]);
expect(td.style.backgroundColor).toBe('rgb(255, 255, 0)');
expect(td.style.color).toBe('rgb(255, 0, 0)');
helper.invoke('removeInvalidHighlight', ['A2:A7']);
expect(td.style.backgroundColor).toBe('rgb(255, 255, 255)');
expect(td.style.color).toBe('rgb(0, 0, 0)');
helper.invoke('removeDataValidation', ['A2:A7']);
expect(helper.getInstance().sheets[0].rows[1].cells[0].validation).toBeUndefined();
done();
});
it('Add list validation', (done: Function) => {
helper.invoke('addDataValidation', [{ type: 'List', value1: '12,13,14' }, 'D2']);
const cell: CellModel = helper.getInstance().sheets[0].rows[1].cells[3];
expect(JSON.stringify(cell.validation)).toBe('{"type":"List","value1":"12,13,14"}');
helper.invoke('selectRange', ['D2']);
const td: HTMLElement = helper.invoke('getCell', [1, 3]).children[0];
expect(td.classList).toContain('e-validation-list');
const coords: ClientRect = td.getBoundingClientRect();
helper.triggerMouseAction('mousedown', { x: coords.left, y: coords.top }, document, td);
helper.triggerMouseAction('mousedup', { x: coords.left, y: coords.top }, document, td);
(td.querySelector('.e-dropdownlist') as any).ej2_instances[0].dropDownClick({ preventDefault: function () { }, target: td.children[0] });
setTimeout(() => {
helper.click('.e-ddl.e-popup li:nth-child(2)');
expect(helper.getInstance().sheets[0].rows[1].cells[3].value).toBe(13);
expect(helper.invoke('getCell', [1, 3]).innerText).toBe('13');
helper.editInUI('15');
setTimeout(() => {
expect(helper.getElements('.e-validationerror-dlg').length).toBe(1);
helper.setAnimationToNone('.e-validationerror-dlg');
helper.click('.e-validationerror-dlg .e-footer-content button:nth-child(2)');
done();
});
});
});
});
describe('UI Interaction ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{
ranges: [{
dataSource: defaultData
}],
}]
}, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Add Data validation', (done: Function) => {
helper.invoke('selectRange', ['E3:E2']);
(helper.getElementFromSpreadsheet('.e-tab-header').children[0].children[5] as HTMLElement).click();
helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click();
setTimeout(() => {
helper.click('.e-datavalidation-ddb li:nth-child(1)');
helper.getElements('.e-datavalidation-dlg #minvalue')[0].value = '12';
helper.getElements('.e-datavalidation-dlg #maxvalue')[0].value = '25';
helper.setAnimationToNone('.e-datavalidation-dlg');
helper.getElements('.e-datavalidation-dlg .e-footer-content')[0].children[1].click();
expect(JSON.stringify(helper.getInstance().sheets[0].rows[1].cells[4].validation)).toBe('{"type":"WholeNumber","operator":"Between","value1":"12","value2":"25","ignoreBlank":true,"inCellDropDown":null}');
helper.editInUI('26');
setTimeout(() => {
expect(helper.getElements('.e-validationerror-dlg').length).toBe(1);
helper.setAnimationToNone('.e-validationerror-dlg');
helper.click('.e-validationerror-dlg .e-footer-content button:nth-child(2)');
expect(helper.invoke('getCell', [1, 4]).textContent).toBe('20');
done();
});
});
});
it('Highlight invalid data', (done: Function) => {
helper.invoke('updateCell', [{ value: 26 }, 'E2']);
helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click();
setTimeout(() => {
helper.click('.e-datavalidation-ddb li:nth-child(2)');
expect(helper.invoke('getCell', [1, 4]).style.backgroundColor).toBe('rgb(255, 255, 0)');
expect(helper.invoke('getCell', [1, 4]).style.color).toBe('rgb(255, 0, 0)');
done();
});
});
it('Remove highlight', (done: Function) => {
helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click();
setTimeout(() => {
helper.click('.e-datavalidation-ddb li:nth-child(3)');
expect(helper.invoke('getCell', [1, 4]).style.backgroundColor).toBe('rgb(255, 255, 255)');
expect(helper.invoke('getCell', [1, 4]).style.color).toBe('rgb(0, 0, 0)');
done();
});
});
it('Remove data validation', (done: Function) => {
helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click();
setTimeout(() => {
helper.click('.e-datavalidation-ddb li:nth-child(4)');
expect(helper.getInstance().sheets[0].rows[1].cells[4].validation).toBeUndefined();
helper.editInUI('30');
expect(helper.getElements('.e-validationerror-dlg').length).toBe(0);
done();
});
});
it('Dialog interaction', (done: Function) => {
helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click();
setTimeout(() => {
helper.click('.e-datavalidation-ddb li:nth-child(1)');
setTimeout(() => {
let ddlElem: any = helper.getElements('.e-datavalidation-dlg .e-allow .e-dropdownlist')[0];
ddlElem.ej2_instances[0].dropDownClick({ preventDefault: function () { }, target: ddlElem.parentElement });
setTimeout(() => {
helper.click('.e-ddl.e-popup li:nth-child(5)');
ddlElem = helper.getElements('.e-datavalidation-dlg .e-data .e-dropdownlist')[0];
ddlElem.ej2_instances[0].dropDownClick({ preventDefault: function () { }, target: ddlElem.parentElement });
setTimeout(() => {
helper.click('.e-ddl.e-popup li:nth-child(3)');
helper.triggerKeyNativeEvent(9);
helper.getElements('.e-datavalidation-dlg .e-values .e-input')[0].value = 'dumm';
helper.triggerKeyEvent('keyup', 89, null, null, null, helper.getElements('.e-datavalidation-dlg .e-values e-input')[0]);
helper.setAnimationToNone('.e-datavalidation-dlg');
// helper.click('.e-datavalidation-dlg .e-footer-content button:nth-child(2)'); // This case need to be fixed
// expect(helper.getElements('.e-datavalidation-dlg .e-values .e-dlg-error')[0].textContent).toBe('Please enter a correct value.'); // This case need to be fixed
helper.getElements('.e-datavalidation-dlg .e-values .e-input')[0].value = '3';
helper.click('.e-datavalidation-dlg .e-footer-content button:nth-child(2)');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[1].cells[4].validation)).toBe('{"type":"TextLength","operator":"EqualTo","value1":"3","value2":"","ignoreBlank":true,"inCellDropDown":null}');
done();
});
});
});
});
});
it('Add list validation for range', (done: Function) => {
helper.invoke('addDataValidation', [{ type: 'List', value1: '=G2:G6' }, 'D2']);
const cell: CellModel = helper.getInstance().sheets[0].rows[1].cells[3];
expect(JSON.stringify(cell.validation)).toBe('{"type":"List","value1":"=G2:G6"}');
helper.invoke('selectRange', ['D2']);
const td: HTMLElement = helper.invoke('getCell', [1, 3]).children[0];
expect(td.classList).toContain('e-validation-list');
const coords: ClientRect = td.getBoundingClientRect();
helper.triggerMouseAction('mousedown', { x: coords.left, y: coords.top }, document, td);
helper.triggerMouseAction('mouseup', { x: coords.left, y: coords.top }, document, td);
(td.querySelector('.e-dropdownlist') as any).ej2_instances[0].dropDownClick({ preventDefault: function () { }, target: td.children[0] });
setTimeout(() => {
helper.click('.e-ddl.e-popup li:nth-child(4)');
setTimeout(() => {
expect(helper.getInstance().sheets[0].rows[1].cells[3].value).toBe(11); // Check this now
expect(helper.invoke('getCell', [1, 3]).innerText).toBe('11'); // check this now
helper.editInUI('10');
setTimeout(() => {
expect(helper.getElements('.e-validationerror-dlg').length).toBe(0);
done();
});
});
});
});
it('Add list validation for range of Whole column', (done: Function) => {
helper.invoke('selectRange', ['I1']);
helper.getElementFromSpreadsheet('#' + helper.id + '_datavalidation').click();
setTimeout(() => {
helper.click('.e-datavalidation-ddb li:nth-child(1)');
setTimeout(() => {
let ddlElem: any = helper.getElements('.e-datavalidation-dlg .e-allow .e-dropdownlist')[0];
ddlElem.ej2_instances[0].value = 'List';
ddlElem.ej2_instances[0].dataBind();
helper.getElements('.e-datavalidation-dlg .e-values .e-input')[0].value = '=G:G';
helper.setAnimationToNone('.e-datavalidation-dlg');
helper.click('.e-datavalidation-dlg .e-footer-content button:nth-child(2)');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[0].cells[8].validation)).toBe('{"type":"List","operator":"Between","value1":"=G:G","value2":"","ignoreBlank":true,"inCellDropDown":true}');
const td: HTMLElement = helper.invoke('getCell', [0, 8]).children[0];
(td.querySelector('.e-dropdownlist') as any).ej2_instances[0].dropDownClick({ preventDefault: function () { }, target: td.children[0] });
setTimeout(() => {
expect(helper.getElements('.e-ddl.e-popup ul')[0].textContent).toBe('Discount15711101336129');
helper.click('.e-ddl.e-popup li:nth-child(4)');
done();
});
});
});
});
});
describe('CR-Issues ->', () => {
describe('I282749, I300338, I303567 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{ ranges: [{ dataSource: [{ 'Employee ID': '', 'Employee Name': '', 'Gender': '', 'Department': '',
'Date of Joining': '', 'Salary': '', 'City': '' }] }], selectedRange: 'A1:A10' }],
created: (): void => {
const spreadsheet: Spreadsheet = helper.getInstance();
spreadsheet.cellFormat({ fontWeight: 'bold', textAlign: 'center', verticalAlign: 'middle' }, 'A1:F1');
spreadsheet.cellFormat({ fontWeight: 'bold' }, 'E31:F31');
spreadsheet.cellFormat({ textAlign: 'right' }, 'E31');
spreadsheet.numberFormat('$#,##0.00', 'F2:F31');
spreadsheet.addDataValidation(
{ type: 'List', operator: 'Between', value1: '1,2', value2: '', ignoreBlank: true, inCellDropDown: true,
isHighlighted: true }, 'A2:A100');
}
}, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Cell alignment and filtering issue ~ from 275309 (while applying data validation)', (done: Function) => {
helper.getElement('#' + helper.id + '_sorting').click();
helper.getElement('#' + helper.id + '_applyfilter').click();
helper.invoke('selectRange', ['A2']);
setTimeout((): void => {
let ddl: HTMLElement = helper.invoke('getCell', [1, 0]).querySelector('.e-ddl') as HTMLElement;
helper.triggerMouseAction('mousedown', { x: ddl.getBoundingClientRect().left + 2, y:
ddl.getBoundingClientRect().top + 2 }, ddl, ddl);
let cell: HTMLElement = helper.invoke('getCell', [1, 0]);
helper.triggerMouseAction(
'mouseup', { x: cell.getBoundingClientRect().left + 1, y: cell.getBoundingClientRect().top + 1 },
document, cell);
setTimeout((): void => {
helper.getElement('#' + helper.getElement().id + 'listValid_popup .e-list-item').click();
helper.invoke('selectRange', ['A3']);
setTimeout((): void => {
ddl = helper.invoke('getCell', [2, 0]).querySelector('.e-ddl') as HTMLElement;
helper.triggerMouseAction('mousedown', { x: ddl.getBoundingClientRect().left + 2, y:
ddl.getBoundingClientRect().top + 2 }, ddl, ddl);
cell = helper.invoke('getCell', [2, 0]);
helper.triggerMouseAction(
'mouseup', { x: cell.getBoundingClientRect().left + 1, y: cell.getBoundingClientRect().top + 1 },
document, cell);
setTimeout((): void => {
helper.getElement('#' + helper.getElement().id + 'listValid_popup .e-list-item:last-child').click();
helper.invoke('selectRange', ['A1']);
const filterCell: HTMLElement = helper.invoke('getCell', [0, 0]).querySelector('.e-filter-icon');
helper.triggerMouseAction(
'mousedown', { x: filterCell.getBoundingClientRect().left + 1, y: filterCell.getBoundingClientRect().top + 1 },
null, filterCell);
cell = helper.invoke('getCell', [0, 0]);
helper.triggerMouseAction(
'mouseup', { x: cell.getBoundingClientRect().left + 1, y: cell.getBoundingClientRect().top + 1 },
document, cell);
setTimeout((): void => {
helper.getElement().getElementsByClassName('e-ftrchk')[2].click();
helper.getElement('.e-excelfilter .e-footer-content .e-btn.e-primary').click();
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].selectedRange).toBe('A1:A1');
helper.invoke('selectRange', ['A4']);
setTimeout((): void => {
expect(!!helper.invoke('getCell', [3, 0]).querySelector('.e-validation-list')).toBeTruthy();
expect(!!helper.invoke('getCell', [4, 0]).querySelector('.e-validation-list')).toBeFalsy();
done();
}, 101);
}, 100);
}, 10);
}, 10);
}, 10);
}, 10);
});
});
describe('I301019, I300657 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet(
{ sheets: [{ rows: [{ cells: [{ value: 'Food', validation: { type: 'Decimal', operator: 'NotEqualTo', ignoreBlank: true,
value1: '0' } }] }], selectedRange: 'A1:A1' }] }, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('unexcepted set validations from cellbuilder', (done: Function) => {
helper.getElement('#' + helper.id + '_ribbon .e-tab-header .e-toolbar-item:nth-child(6)').click();
helper.getElement('#' + helper.id + '_datavalidation').click();
helper.getElement('#' + helper.id + '_datavalidation-popup .e-item').click();
setTimeout((): void => { // Data validation model is not set properly in dialog.
let dlg: HTMLElement = helper.getElement().querySelector('.e-datavalidation-dlg') as HTMLElement;
expect(!!dlg).toBeTruthy();
expect((dlg.querySelector('.e-cellrange .e-input') as HTMLInputElement).value).toBe('A1:A1');
expect((dlg.querySelector('.e-ignoreblank .e-checkbox') as HTMLInputElement).checked).toBeTruthy();
(helper.getInstance().serviceLocator.getService(dialog) as Dialog).hide();
setTimeout((): void => {
done();
});
});
});
it('custom message on spreadsheet validation', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
spreadsheet.dialogBeforeOpen = (args: DialogBeforeOpenEventArgs): void => {
if (args.dialogName === 'ValidationErrorDialog') { args.content = 'Invalid value'; }
};
spreadsheet.dataBind();
helper.edit('A1', '0');
setTimeout((): void => {
let dlg: HTMLElement = helper.getElement().querySelector('.e-validationerror-dlg') as HTMLElement;
expect(!!dlg).toBeTruthy();
expect(dlg.querySelector('.e-dlg-content').textContent).toBe('Invalid value');
(spreadsheet.serviceLocator.getService(dialog) as Dialog).hide();
setTimeout((): void => {
done();
});
});
});
});
describe('I275309 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({
created: (): void => {
const spreadsheet: Spreadsheet = helper.getInstance();
spreadsheet.addDataValidation(
{ type: 'List', operator: 'Between', value1: '1', value2:'1', ignoreBlank: true, inCellDropDown: true,
isHighlighted: true }, 'X1:X10');
spreadsheet.addDataValidation(
{ type: 'List', operator: 'Between', value1: '2', value2:'2', ignoreBlank: true, inCellDropDown: true,
isHighlighted: true }, 'Y1:Y10');
spreadsheet.addDataValidation(
{ type: 'List', operator: 'Between', value1: '3', value2:'3', ignoreBlank: true, inCellDropDown: true,
isHighlighted: true }, 'Z1:Z10');
spreadsheet.autoFit('1:100');
}
}, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Dropdownlist added randomly in cells while directly scrolling the spreadsheet', (done: Function) => {
helper.invoke('goTo', ['G1']);
setTimeout((): void => {
helper.invoke('goTo', ['Q1']);
setTimeout((): void => {
helper.invoke('goTo', ['V1']);
helper.invoke('selectRange', ['X1']);
setTimeout((): void => {
expect(!!helper.invoke('getCell', [0, 23]).querySelector('.e-validation-list')).toBeTruthy();
helper.invoke('selectRange', ['Z1']);
setTimeout((): void => {
expect(!!helper.invoke('getCell', [0, 25]).querySelector('.e-validation-list')).toBeTruthy();
helper.invoke('selectRange', ['AA1']);
setTimeout((): void => {
expect(!!helper.invoke('getCell', [0, 26]).querySelector('.e-validation-list')).toBeFalsy();
done();
});
});
});
});
});
});
});
describe('EJ2-56780, EJ2-57644 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{
ranges: [{ dataSource: defaultData }],
rows: [{ cells: [{ index: 8, validation: { type: 'List', value1: '=A2:A5' } }] },
{ index: 5, cells: [{ index: 3, validation: { type: 'List', value1: '1,2' } }] }]
}]
}, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Insert row above and between the cells referred in list validation', (done: Function) => {
helper.setAnimationToNone('#spreadsheet_contextmenu');
const sheet: SheetModel = helper.invoke('getActiveSheet');
// Insert above the cell reference
helper.openAndClickCMenuItem(0, 0, [6, 1], true);
expect(getCell(0, 8, sheet).validation.value1).toBe('=A3:A6');
setTimeout(() => {
// Insert inbetween the cell reference
helper.invoke('selectRange', ['A3']);
helper.openAndClickCMenuItem(2, 0, [6, 2], true);
expect(getCell(0, 8, sheet).validation.value1).toBe('=A3:A7');
helper.invoke('selectRange', ['I1']);
const ddl: any = helper.invoke('getCell', [0, 8]).querySelector('.e-dropdownlist');
ddl.ej2_instances[0].showPopup();
setTimeout(() => {
const popup: HTMLElement = helper.getElement('.e-ddl.e-popup ul');
expect(popup.childElementCount).toBe(5);
expect(popup.children[1].textContent).toBe('');
ddl.ej2_instances[0].hidePopup();
done();
});
});
});
it('Insert before with single column', (done: Function) => {
const validation: string = '{"type":"List","value1":"=A3:A7","ignoreBlank":true,"inCellDropDown":true}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['I1']);
helper.openAndClickCMenuItem(0, 8, [6, 1], null, true);
expect(JSON.stringify(getCell(0, 8, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 9, sheet).validation)).toBe(validation);
expect(getCell(0, 10, sheet)).toBeNull();
done();
});
it('Insert before with single column - Undo & Redo', (done: Function) => {
const validation: string = '{"type":"List","value1":"=A3:A7","ignoreBlank":true,"inCellDropDown":true}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.click('#spreadsheet_undo');
expect(JSON.stringify(getCell(0, 8, sheet).validation)).toBe(validation);
expect(getCell(0, 9, sheet)).toBeNull();
helper.click('#spreadsheet_redo');
expect(JSON.stringify(getCell(0, 8, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 9, sheet).validation)).toBe(validation);
done();
});
it('Insert after with single column', (done: Function) => {
const validation: string = '{"type":"List","value1":"=A3:A7","ignoreBlank":true,"inCellDropDown":true}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['J1']);
helper.openAndClickCMenuItem(0, 9, [6, 2], null, true);
expect(JSON.stringify(getCell(0, 9, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 10, sheet).validation)).toBe(validation);
done();
});
it('Insert after with single column - Undo & Redo', (done: Function) => {
const validation: string = '{"type":"List","value1":"=A3:A7","ignoreBlank":true,"inCellDropDown":true}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.click('#spreadsheet_undo');
expect(JSON.stringify(getCell(0, 9, sheet).validation)).toBe(validation);
expect(getCell(0, 10, sheet)).toBeNull();
helper.click('#spreadsheet_redo');
expect(JSON.stringify(getCell(0, 9, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 10, sheet).validation)).toBe(validation);
done();
});
it('Insert before with mutliple column', (done: Function) => {
const validation: string = '{"type":"List","value1":"=A3:A7","ignoreBlank":true,"inCellDropDown":true}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['K1:M1']);
helper.openAndClickCMenuItem(0, 10, [6, 1], null, true);
expect(JSON.stringify(getCell(0, 10, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 11, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 12, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 13, sheet).validation)).toBe(validation);
done();
});
it('Insert before with mutliple column - Undo & Redo', (done: Function) => {
const validation: string = '{"type":"List","value1":"=A3:A7","ignoreBlank":true,"inCellDropDown":true}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.click('#spreadsheet_undo');
expect(JSON.stringify(getCell(0, 10, sheet).validation)).toBe(validation);
expect(getCell(0, 11, sheet)).toBeNull();
expect(getCell(0, 12, sheet)).toBeNull();
expect(getCell(0, 13, sheet)).toBeNull();
helper.click('#spreadsheet_redo');
expect(JSON.stringify(getCell(0, 10, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 11, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 12, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 13, sheet).validation)).toBe(validation);
done();
});
it('Insert after with mutliple column', (done: Function) => {
const validation: string = '{"type":"List","value1":"=A3:A7","ignoreBlank":true,"inCellDropDown":true}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['L1:N1']);
helper.openAndClickCMenuItem(0, 11, [6, 2], null, true);
expect(JSON.stringify(getCell(0, 13, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 14, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 15, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 16, sheet).validation)).toBe(validation);
done();
});
it('Insert after with mutliple column - Undo & Redo', (done: Function) => {
const validation: string = '{"type":"List","value1":"=A3:A7","ignoreBlank":true,"inCellDropDown":true}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.click('#spreadsheet_undo');
expect(JSON.stringify(getCell(0, 13, sheet).validation)).toBe(validation);
expect(getCell(0, 14, sheet)).toBeNull();
expect(getCell(0, 15, sheet)).toBeNull();
expect(getCell(0, 16, sheet)).toBeNull();
helper.click('#spreadsheet_redo');
expect(JSON.stringify(getCell(0, 13, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 14, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 15, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(0, 16, sheet).validation)).toBe(validation);
done();
});
it('Insert before with mutliple column - not to update case', (done: Function) => {
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['G1:I1']);
helper.openAndClickCMenuItem(0, 6, [6, 1], null, true);
expect(getCell(0, 6, sheet)).toBeNull();
expect(getCell(0, 7, sheet)).toBeNull();
expect(getCell(0, 8, sheet)).toBeNull();
done();
});
it('Insert after with mutliple column - not to update case', (done: Function) => {
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['T1:U1']);
helper.openAndClickCMenuItem(0, 19, [6, 2], null, true);
expect(getCell(0, 21, sheet)).toBeNull();
expect(getCell(0, 22, sheet)).toBeNull();
done();
});
it('Insert above with single row', (done: Function) => {
const validation: string = '{"type":"List","value1":"=A4:A8"}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['A2']);
helper.openAndClickCMenuItem(1, 0, [6, 1], true);
expect(JSON.stringify(getCell(1, 11, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(2, 11, sheet).validation)).toBe(validation);
expect(getCell(3, 11, sheet)).toBeNull();
done();
});
it('Insert above with single row - Undo & Redo', (done: Function) => {
const validationAfterUndo: string = '{"type":"List","value1":"=A3:A7"}';
const validation: string = '{"type":"List","value1":"=A4:A8"}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.click('#spreadsheet_undo');
expect(JSON.stringify(getCell(1, 11, sheet).validation)).toBe(validationAfterUndo);
expect(getCell(2, 11, sheet)).toBeNull();
helper.click('#spreadsheet_redo');
expect(JSON.stringify(getCell(1, 11, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(2, 11, sheet).validation)).toBe(validation);
done();
});
it('Insert below with single row', (done: Function) => {
const validation: string = '{"type":"List","value1":"=A5:A9"}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['A3']);
helper.openAndClickCMenuItem(2, 0, [6, 2], true);
expect(JSON.stringify(getCell(2, 11, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(3, 11, sheet).validation)).toBe(validation);
done();
});
it('Insert below with single row - Undo & Redo', (done: Function) => {
const validationAfterUndo: string = '{"type":"List","value1":"=A4:A8"}';
const validation: string = '{"type":"List","value1":"=A5:A9"}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.click('#spreadsheet_undo');
expect(JSON.stringify(getCell(2, 11, sheet).validation)).toBe(validationAfterUndo);
expect(getCell(3, 11, sheet)).toBeNull();
helper.click('#spreadsheet_redo');
expect(JSON.stringify(getCell(2, 11, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(3, 11, sheet).validation)).toBe(validation);
done();
});
it('Insert above with mutliple row', (done: Function) => {
const validation: string = '{"type":"List","value1":"1,2"}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['A10:A12']);
helper.openAndClickCMenuItem(9, 0, [6, 1], true);
expect(JSON.stringify(getCell(9, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(10, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(11, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(12, 3, sheet).validation)).toBe(validation);
done();
});
it('Insert above with mutliple row - Undo & Redo', (done: Function) => {
const validation: string = '{"type":"List","value1":"1,2"}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.click('#spreadsheet_undo');
expect(JSON.stringify(getCell(9, 3, sheet).validation)).toBe(validation);
expect(getCell(10, 3, sheet).validation).toBeUndefined();
expect(getCell(11, 3, sheet).validation).toBeUndefined();
expect(getCell(12, 3, sheet).validation).toBeUndefined();
helper.click('#spreadsheet_redo');
expect(JSON.stringify(getCell(9, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(10, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(11, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(12, 3, sheet).validation)).toBe(validation);
done();
});
it('Insert below with mutliple row', (done: Function) => {
const validation: string = '{"type":"List","value1":"1,2"}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['A9:A11']);
helper.openAndClickCMenuItem(8, 0, [6, 2], true);
expect(JSON.stringify(getCell(12, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(13, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(14, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(15, 3, sheet).validation)).toBe(validation);
done();
});
it('Insert below with mutliple row - Undo & Redo', (done: Function) => {
const validation: string = '{"type":"List","value1":"1,2"}';
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.click('#spreadsheet_undo');
expect(JSON.stringify(getCell(12, 3, sheet).validation)).toBe(validation);
expect(getCell(13, 3, sheet).validation).toBeUndefined();
expect(getCell(14, 3, sheet).validation).toBeUndefined();
expect(getCell(15, 3, sheet).validation).toBeUndefined();
helper.click('#spreadsheet_redo');
expect(JSON.stringify(getCell(12, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(13, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(14, 3, sheet).validation)).toBe(validation);
expect(JSON.stringify(getCell(15, 3, sheet).validation)).toBe(validation);
done();
});
it('Insert above with mutliple row - not to update case', (done: Function) => {
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['A9:A10']);
helper.openAndClickCMenuItem(8, 0, [6, 1], true);
expect(getCell(8, 3, sheet)).toBeNull();
expect(getCell(9, 3, sheet)).toBeNull();
done();
});
it('Insert below with mutliple row - not to update case', (done: Function) => {
const sheet: SheetModel = helper.invoke('getActiveSheet');
helper.invoke('selectRange', ['A18:A19']);
helper.openAndClickCMenuItem(17, 0, [6, 2], true);
expect(getCell(19, 3, sheet)).toBeNull();
expect(getCell(20, 3, sheet)).toBeNull();
done();
});
it('Clear all on column validation is not working', (done: Function) => {
helper.getInstance().workbookDataValidationModule.validationHandler({
range: 'Sheet1!G:G', rules: {
type: 'List', operator: 'Between', value1: '1', value2: '', ignoreBlank: true, inCellDropDown: true
}
});
helper.invoke('selectRange', ['G3:G5']);
helper.click(`#${helper.id}_clear`);
helper.click('.e-clear-ddb ul li');
const validation: ValidationModel = helper.getInstance().sheets[0].columns[6].validation;
expect(validation.address).toBe('G1:G2 G6:G1048576');
helper.edit('G3', '4');
setTimeout(() => {
expect(helper.getElementFromSpreadsheet('.e-validationerror-dlg')).toBeNull();
helper.edit('G2', '4');
setTimeout(() => {
expect(helper.getElementFromSpreadsheet('.e-validationerror-dlg')).not.toBeNull();
helper.setAnimationToNone('.e-validationerror-dlg');
helper.click('.e-validationerror-dlg .e-footer-content button:nth-child(2)');
// Clearing another range
helper.invoke('selectRange', ['G10:G14']);
helper.click(`#${helper.id}_clear`);
helper.click('.e-clear-ddb ul li');
expect(validation.address).toBe('G1:G2 G6:G9 G15:G1048576');
// Clearing between the range
helper.invoke('selectRange', ['G12:G16']);
helper.click(`#${helper.id}_clear`);
helper.click('.e-clear-ddb ul li');
expect(validation.address).toBe('G1:G2 G6:G9 G17:G1048576');
// Clearing between the range
helper.invoke('selectRange', ['G2:G3']);
helper.click(`#${helper.id}_clear`);
helper.click('.e-clear-ddb ul li');
expect(validation.address).toBe('G1:G1 G6:G9 G17:G1048576');
done();
});
});
});
});
describe('SF-362574->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({
sheets: [{ ranges: [{ dataSource: defaultData }] }]
}, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('IsHighlighted property is enabled if data is filtered', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
spreadsheet.addDataValidation({ type: 'WholeNumber', operator: 'LessThanOrEqualTo', value1: '99999' }, 'E1:E11');
expect(spreadsheet.sheets[0].rows[0].cells[4].validation.isHighlighted).toBeUndefined();
expect(spreadsheet.sheets[0].rows[8].cells[4].validation.isHighlighted).toBeUndefined();
spreadsheet.applyFilter(
[{ value: 310, field: 'F', predicate: 'or', operator: 'equal', type: 'number', matchCase: false, ignoreAccent: false }],
'A1:H11').then((): void => {
expect(spreadsheet.sheets[0].rows[0].cells[4].validation.isHighlighted).toBeUndefined();
expect(spreadsheet.sheets[0].rows[8].cells[4].validation.isHighlighted).toBeUndefined();
setTimeout((): void => {
done();
});
});
});
});
});
}); | the_stack |
import { applyMiddleware } from 'graphql-middleware'
import GraphQLJSON, { GraphQLJSONObject } from 'graphql-type-json'
import {
gql,
PubSub,
withFilter,
ApolloServer,
ForbiddenError,
UserInputError,
ValidationError,
AuthenticationError,
makeExecutableSchema,
GetMiddlewareOptions,
Config as ApolloConfig
} from 'apollo-server-express'
import {
Utils,
plugin,
FieldContract,
ResourceContract,
PluginSetupConfig,
GraphQlQueryContract
} from '@tensei/common'
import { ReferenceType } from '@mikro-orm/core'
import {
getResolvers,
filterOperators,
topLevelOperators,
authorizeResolver
} from './Resolvers'
import {
defineCreateSubscriptionsForResource,
defineDeleteSubscriptionsForResource,
defineUpdateSubscriptionsForResource
} from './Subscriptions'
import { HTML } from './graphiql'
type OmittedApolloConfig = Omit<ApolloConfig, 'typeDefs' | 'resolvers'>
class Graphql {
private appolloConfig: OmittedApolloConfig = {}
private getMiddlewareOptions: GetMiddlewareOptions = {}
private pubsub: PubSub | undefined
schemaString: string = `
scalar Date
scalar JSON
scalar JSONObject
`
private subscriptionsEnabled = false
private getGraphqlFieldDefinitionForCreateInput = (
field: FieldContract,
resource: ResourceContract,
resources: ResourceContract[],
isUpdate?: boolean
) => {
let FieldType = 'String'
let FieldKey = field.databaseField
if (field.property.enum) {
FieldType = `${resource.data.pascalCaseName}${field.pascalCaseName}Enum`
}
if (
['integer', 'bigInteger', 'int', 'number', 'float', 'double'].includes(
field.property.type!
)
) {
FieldType = 'Int'
}
if (field.property.type === 'boolean') {
FieldType = 'Boolean'
}
if (field.property.type === 'boolean') {
FieldType = 'Boolean'
}
if (!field.property.nullable && !isUpdate) {
FieldType = `${FieldType}!`
}
if (
field.relatedProperty.reference === ReferenceType.MANY_TO_ONE ||
field.relatedProperty.reference === ReferenceType.ONE_TO_ONE
) {
FieldType = `ID`
FieldKey = field.databaseField
}
if (
field.relatedProperty.reference === ReferenceType.ONE_TO_MANY ||
field.relatedProperty.reference === ReferenceType.MANY_TO_MANY
) {
FieldType = `[ID]`
FieldKey = field.databaseField
}
if (field.property.type === 'Date') {
FieldType = 'Date'
}
if (field.graphqlType) {
FieldType = field.graphqlType
}
return `
${FieldKey}: ${FieldType}`
}
private getGraphqlFieldDefinition = (
field: FieldContract,
resource: ResourceContract,
resources: ResourceContract[],
config: PluginSetupConfig
) => {
let FieldType = 'String'
let FieldKey = field.databaseField
if (field.property.enum) {
FieldType = `${resource.data.pascalCaseName}${field.pascalCaseName}Enum`
}
if (field.property.type === 'boolean') {
FieldType = 'Boolean'
}
if (['integer', 'bigInteger'].includes(field.property.type!)) {
FieldType = 'Int'
}
if (field.property.primary) {
FieldType = 'ID'
}
if (
field.relatedProperty.reference === ReferenceType.ONE_TO_MANY ||
field.relatedProperty.reference === ReferenceType.MANY_TO_MANY
) {
const relatedResource = resources.find(
resource => resource.data.name === field.name
)
if (relatedResource) {
FieldType = `[${relatedResource.data.pascalCaseName}]`
FieldKey = `${field.databaseField}(offset: Int, limit: Int, where: ${
relatedResource.data.pascalCaseName
}WhereQuery, orderBy: ${
relatedResource.data.pascalCaseName
}QueryOrder${this.getPossibleResourceFilters(relatedResource)})`
}
}
if (field.property.type === 'Date') {
FieldType = 'Date'
}
if (
field.relatedProperty.reference === ReferenceType.MANY_TO_ONE ||
field.relatedProperty.reference === ReferenceType.ONE_TO_ONE
) {
const relatedResource = resources.find(
resource => resource.data.name === field.name
)
if (relatedResource) {
FieldType = `${relatedResource.data.pascalCaseName}`
FieldKey = field.databaseField
}
}
if (
field.property.type === 'json' &&
field.validationRules.includes('array')
) {
FieldType = `[${FieldType}]`
}
if (!field.serialize().isNullable || field.property.primary) {
FieldType = `${FieldType}!`
}
if (field.graphqlType) {
FieldType = field.graphqlType
}
return `
${FieldKey}: ${FieldType}`
}
private defineFetchAllQueryForResource(
resource: ResourceContract,
config: PluginSetupConfig
) {
return `
${resource.data.camelCaseNamePlural}(offset: Int, limit: Int, where: ${
resource.data.pascalCaseName
}WhereQuery, orderBy: ${
resource.data.pascalCaseName
}QueryOrder${this.getPossibleResourceFilters(resource)}): [${
resource.data.pascalCaseName
}]`
}
private defineFetchAllCountQueryForResource(
resource: ResourceContract,
config: PluginSetupConfig
) {
return `
${resource.data.camelCaseNamePlural}Count(offset: Int, limit: Int, where: ${
resource.data.pascalCaseName
}WhereQuery${this.getPossibleResourceFilters(resource)}): Int!`
}
private defineFetchSingleQueryForResource(
resource: ResourceContract,
config: PluginSetupConfig
) {
return `
${resource.data.camelCaseName}(${this.getIdKey(config)}: ID!): ${
resource.data.pascalCaseName
}`
}
getWhereQueryFieldType(
field: FieldContract,
config: PluginSetupConfig,
filter = false
) {
if (field.property.type === 'boolean') {
// return 'boolean_where_query'
}
if (
[
ReferenceType.MANY_TO_MANY,
ReferenceType.ONE_TO_MANY,
ReferenceType.MANY_TO_ONE,
ReferenceType.ONE_TO_ONE
].includes(field.relatedProperty.reference!)
) {
const relatedResource = config.resources.find(
resource => resource.data.pascalCaseName === field.relatedProperty.type
)
return `${relatedResource?.data.pascalCaseName}${
filter ? 'SubscriptionFilter' : 'WhereQuery'
}`
}
if (field.property.primary) {
return `IdWhereQuery`
}
if (field.property.type === 'integer') {
return 'IntegerWhereQuery'
}
return 'StringWhereQuery'
}
getOrderByQueryForResource(
resource: ResourceContract,
config: PluginSetupConfig
) {
return `
input ${resource.data.pascalCaseName}QueryOrder {
${resource
.getFetchApiExposedFields()
.filter(f => !f.relatedProperty.reference && f.isSortable)
.map(field => `${field.databaseField}: QueryOrder`)}
${resource
.getFetchApiExposedFields()
.filter(f => f.relatedProperty.reference && f.isSortable)
.map(field => {
const relatedResource = config.resourcesMap[field.relatedProperty.type!]
return `${field.databaseField}: ${relatedResource.data.pascalCaseName}QueryOrder`
})}
}
`
}
getWhereQueryForResource(
resource: ResourceContract,
config: PluginSetupConfig
) {
return `
input ${resource.data.pascalCaseName}WhereQuery {
${topLevelOperators.map(
operator =>
`${operator}: ${
operator === '_not'
? `${resource.data.pascalCaseName}WhereQuery`
: `[${resource.data.pascalCaseName}WhereQuery]`
}`
)}
${resource
.getFetchApiExposedFields()
.map(
field =>
`${field.databaseField}: ${this.getWhereQueryFieldType(field, config)}`
)}
}
input ${resource.data.pascalCaseName}SubscriptionFilter {
${resource
.getFetchApiExposedFields()
.map(
field =>
`${field.databaseField}: ${this.getWhereQueryFieldType(
field,
config,
true
)}`
)}
}
${
resource.data.filters.length > 0
? `
enum ${resource.data.pascalCaseName}QueryFilterOptions {
${resource.data.filters.map(filter => `${filter.config.shortName}`)}
}
input ${resource.data.pascalCaseName}FilterQuery {
name: ${resource.data.pascalCaseName}QueryFilterOptions
args: JSONObject
}
`
: ''
}
`
}
getFieldsTypeDefinition(resource: ResourceContract) {
return resource.data.fields
.filter(
field =>
!field.property.hidden && !field.serialize().isRelationshipField
)
.map(field => {
return `
${field.databaseField}`
})
}
private setupResourceGraphqlTypes(
resources: ResourceContract[],
config: PluginSetupConfig
) {
resources.forEach(resource => {
this.schemaString = `${this.schemaString}
${resource.data.fields
.filter(field => field.property.enum && !field.property.hidden)
.map(
field => `
enum ${resource.data.pascalCaseName}${
field.pascalCaseName
}Enum {${field.property.items?.map(
option => `
${option}`
)}
}`
)}
type ${resource.data.pascalCaseName} {${resource.data.fields
.filter(
field =>
!field.property.hidden && !field.showHideFieldFromApi.hideOnFetchApi
)
.map(field =>
this.getGraphqlFieldDefinition(field, resource, resources, config)
)}
${resource.data.fields
.filter(field =>
[ReferenceType.MANY_TO_MANY, ReferenceType.ONE_TO_MANY].includes(
field.relatedProperty.reference!
)
)
.map(
field =>
`${field.databaseField}Count(where: ${
field.pascalCaseName
}WhereQuery${this.getPossibleResourceFilters(resource)}): Int`
)}
}
${
!resource.data.hideOnCreateApi
? `
input Create${resource.data.pascalCaseName}Input {${resource.data.fields
.filter(
field =>
!field.property.primary &&
!field.property.hidden &&
!field.showHideFieldFromApi.hideOnCreateApi
)
.map(field =>
this.getGraphqlFieldDefinitionForCreateInput(
field,
resource,
resources
)
)}
}
`
: ''
}
${
!resource.data.hideOnUpdateApi
? `
input Update${resource.data.pascalCaseName}Input {${resource.data.fields
.filter(
field =>
!field.property.primary &&
!field.property.hidden &&
!field.showHideFieldFromApi.hideOnUpdateApi
)
.map(field =>
this.getGraphqlFieldDefinitionForCreateInput(
field,
resource,
resources,
true
)
)}
}
`
: ''
}
${this.getWhereQueryForResource(resource, config)}
${this.getOrderByQueryForResource(resource, config)}
`
})
const resourcesWithQueryTypes = resources.filter(
r => !r.isHiddenOnApi() && !r.data.hideOnFetchApi
)
if (resourcesWithQueryTypes.length > 0) {
this.schemaString = `${
this.schemaString
}type Query {${resourcesWithQueryTypes.map(resource => {
return `${this.defineFetchSingleQueryForResource(
resource,
config
)}${this.defineFetchAllQueryForResource(
resource,
config
)}${this.defineFetchAllCountQueryForResource(resource, config)}`
})}
}
`
} else {
this.schemaString = `${this.schemaString}type Query {_: Boolean}`
}
this.schemaString = `${this.schemaString}
enum QueryOrder {
asc
ascNullsLast
ascNullsFirst
desc
descNullsLast
descNullsFirst
}
`
const createSubscriptions = resources.filter(
r => !r.data.hideOnInsertSubscription
)
const updateSubscriptions = resources.filter(
r => !r.data.hideOnUpdateSubscription
)
const deleteSubscriptions = resources.filter(
r => !r.data.hideOnDeleteSubscription
)
if (
createSubscriptions.length ||
updateSubscriptions.length ||
deleteSubscriptions.length
) {
this.schemaString = `${
this.schemaString
}type Subscription {${createSubscriptions.map(
resource => `${defineCreateSubscriptionsForResource(resource)}`
)}
${updateSubscriptions.map(
resource => `${defineUpdateSubscriptionsForResource(resource)}`
)}
${deleteSubscriptions.map(
resource => `${defineDeleteSubscriptionsForResource(resource)}`
)}
}`
}
this.schemaString = `${this.schemaString}type Mutation {${resources
.filter(r => !r.data.hideOnCreateApi)
.map(resource => {
return `${this.defineCreateMutationForResource(resource, config)}`
})}
${resources
.filter(r => !r.data.hideOnUpdateApi)
.map(resource => {
return `${this.defineUpdateMutationForResource(resource, config)}`
})}
${resources
.filter(r => !r.data.hideOnDeleteApi)
.map(resource => {
return `${this.defineDeleteMutationForResource(resource, config)}`
})}
}
input StringWhereQuery {
${filterOperators.map(operator => {
if (['_in', '_nin'].includes(operator)) {
return `${operator}: [String!]`
}
return `${operator}: String`
})}
}
input IntegerWhereQuery {
${filterOperators.map(operator => {
if (['_in', '_nin'].includes(operator)) {
return `${operator}: [Int!]`
}
return `${operator}: Int`
})}
}
input IdWhereQuery {
${filterOperators.map(operator => {
if (['_in', '_nin'].includes(operator)) {
return `${operator}: [ID!]`
}
return `${operator}: ID`
})}
}
`
return this.schemaString
}
private defineCreateMutationForResource(
resource: ResourceContract,
config: PluginSetupConfig
) {
return `
create${resource.data.pascalCaseName}(object: Create${resource.data.pascalCaseName}Input!): ${resource.data.pascalCaseName}!
createMany${resource.data.pascalCaseNamePlural}(objects: [Create${resource.data.pascalCaseName}Input]!): [${resource.data.pascalCaseName}]!
`
}
private defineUpdateMutationForResource(
resource: ResourceContract,
config: PluginSetupConfig
) {
return `update${resource.data.pascalCaseName}(${this.getIdKey(
config
)}: ID!, object: Update${resource.data.pascalCaseName}Input!): ${
resource.data.pascalCaseName
}!
updateMany${resource.data.pascalCaseNamePlural}(where: ${
resource.data.pascalCaseName
}WhereQuery!, object: Update${
resource.data.pascalCaseName
}Input!${this.getPossibleResourceFilters(resource)}): [${
resource.data.pascalCaseName
}]!
`
}
private defineDeleteMutationForResource(
resource: ResourceContract,
config: PluginSetupConfig
) {
return `delete${resource.data.pascalCaseName}(${this.getIdKey(
config
)}: ID!): ${resource.data.pascalCaseName}
deleteMany${resource.data.pascalCaseNamePlural}(where: ${
resource.data.pascalCaseName
}WhereQuery${this.getPossibleResourceFilters(resource)}): [${
resource.data.pascalCaseName
}]
`
}
private getPossibleResourceFilters(resource: ResourceContract) {
if (resource.data.filters.length === 0) {
return ''
}
return `, filters: [${resource.data.pascalCaseName}FilterQuery]`
}
private getIdKey(config: PluginSetupConfig) {
return 'id'
}
subscriptions(pubsub?: PubSub) {
this.pubsub = pubsub || new PubSub()
this.subscriptionsEnabled = true
return this
}
configure(config: OmittedApolloConfig) {
this.appolloConfig = config
return this
}
middlewareOptions(config: GetMiddlewareOptions) {
this.getMiddlewareOptions = config || {}
return this
}
getResolversFromGraphqlQueries(queries: GraphQlQueryContract[]) {
let resolvers: any = {
Query: {},
Mutation: {}
}
const subscriptions = queries.filter(q => q.config.type === 'SUBSCRIPTION')
if (subscriptions.length !== 0) {
resolvers.Subscription = {}
}
queries.forEach(query => {
if (query.config.type === 'MUTATION') {
resolvers.Mutation[query.config.path] = query.config.handler
}
if (query.config.type === 'CUSTOM') {
resolvers[query.config.path] = (query.config as any).handler()
}
if (query.config.type === 'QUERY') {
resolvers.Query[query.config.path] = query.config.handler
}
if (query.config.type === 'SUBSCRIPTION') {
resolvers.Subscription[query.config.path] = {
subscribe: async (_: any, args: any, ctx: any, info: any) => {
for (const middleware of query.config.middleware) {
// await middleware(_, args, ctx, info)
}
await authorizeResolver(ctx, query.config.authorize)
return withFilter(
() => query.config.handler(_, args, ctx, info) as any,
query.config.filter
)(_, args, ctx, info)
}
}
}
})
return resolvers
}
plugin() {
return plugin('GraphQl')
.extra({
path: this.getMiddlewareOptions.path || 'graphql'
})
.register(async config => {
const { extendGraphQlQueries, currentCtx, databaseConfig } = config
this.setupResourceGraphqlTypes(currentCtx().resources, config)
extendGraphQlQueries(
getResolvers(
((currentCtx()
.resources as unknown) as ResourceContract<'graphql'>[]).filter(
resource => !resource.isHiddenOnApi()
),
{
subscriptionsEnabled: this.subscriptionsEnabled,
database: databaseConfig.type!
}
)
)
})
.boot(async config => {
const {
currentCtx,
app,
graphQlMiddleware,
serverUrl,
resources
} = config
const typeDefs = [
gql(this.schemaString),
...currentCtx().graphQlTypeDefs
]
graphQlMiddleware.unshift(
async (resolve, parent, args, context, info) => {
// set body to equal args
context.body = args
context.isGraphqlRequest = true
context.info = info
// register filters
resources.forEach(resource => {
resource.data.filters.forEach(filter => {
context.manager.addFilter(
filter.config.shortName,
filter.config.cond,
resource.data.pascalCaseName,
filter.config.default
)
})
})
// set filter parameters
resources.forEach(resource => {
resource.data.filters.forEach(filter => {
const filterFromBody = context.body?.filters?.find(
(bodyFitler: any) =>
bodyFitler.name === filter.config.shortName
)
context.manager.setFilterParams(
filter.config.shortName,
filterFromBody?.args || {}
)
})
})
// fork new manager instance for this request
context.manager = context.manager.fork()
context.authenticationError = (message?: string) =>
new AuthenticationError(message || 'Unauthenticated.')
context.forbiddenError = (message?: string) =>
new ForbiddenError(message || 'Forbidden.')
context.validationError = (message?: string) =>
new ValidationError(message || 'Validation failed.')
context.userInputError = (message?: string, properties?: any) =>
new UserInputError(message || 'Invalid user input.', properties)
return resolve(parent, args, context, info)
}
)
const resolvers = {
...this.getResolversFromGraphqlQueries(currentCtx().graphQlQueries),
JSON: GraphQLJSON,
JSONObject: GraphQLJSONObject
}
const schema = makeExecutableSchema({
typeDefs,
resolvers
})
// Add authorizer middleware to all graphql queries
currentCtx().graphQlQueries.forEach(query => {
query.middleware(async (resolve, parent, args, ctx, info) => {
await authorizeResolver(ctx, query.config.authorize)
return resolve(parent, args, ctx, info)
})
})
const querySpecificMiddleware = currentCtx()
.graphQlQueries.map(query => {
if (query.config.middleware.length > 0) {
return query.config.middleware
.map(middleware => {
if (query.config.type === 'QUERY') {
return {
Query: {
[query.config.path]: middleware
}
}
}
if (query.config.type === 'MUTATION') {
return {
Mutation: {
[query.config.path]: middleware
}
}
}
return undefined as any
})
.filter(Boolean)
}
return []
})
.reduce((acc, middleware) => [...acc, ...middleware], [])
const playgroundEndpoint = `${serverUrl}/${
this.getMiddlewareOptions.path || 'graphql'
}`
const graphQlServer = new ApolloServer({
schema: applyMiddleware(
schema,
// Register global middleware by spreading them to the applyMiddleware method.
...currentCtx().graphQlMiddleware,
// Register query specific middleware by mapping through all registered queries, and generating the middleware for it.
...querySpecificMiddleware
),
...this.appolloConfig,
context: (ctx: any) => {
const { orm, resources, db } = currentCtx()
let prepare = async function (this: any, data: any) {
const guessedModelType = Array.isArray(data)
? data[0].constructor.name
: data.constructor.name
// prepare virtual fields
const resource = (resources.find(r => {
return r.data.pascalCaseName === guessedModelType
}) as unknown) as ResourceContract<'graphql'>
if (!resource) {
return data
}
await Utils.graphql.populateFromResolvedNodes(
(resources as unknown) as ResourceContract<'graphql'>[],
this.manager,
orm?.config.get('type')!,
resource,
Utils.graphql.getParsedInfo(this.info),
Array.isArray(data) ? data : [data]
)
return data
}
const manager = orm?.em?.fork()!
return {
...ctx,
...config,
pubsub: this.pubsub,
db,
repositories: db,
manager,
prepare
}
},
uploads: false,
playground: false
})
const path = `/${this.getMiddlewareOptions.path || 'graphql'}`
app.get(path, (request, response, next) => {
return response.send(HTML(path))
})
graphQlServer.applyMiddleware({
app,
...this.getMiddlewareOptions
})
if (this.subscriptionsEnabled) {
graphQlServer.installSubscriptionHandlers(config.server)
}
})
}
}
export const graphql = () => new Graphql() | the_stack |
* @hidden
*/
import { EDITOR, TEST, DEV, DEBUG, JSB, PREVIEW, SUPPORT_JIT } from 'internal:constants';
import { legacyCC } from '../global-exports';
import * as js from '../utils/js';
import * as misc from '../utils/misc';
import { CCClass } from './class';
import * as Attr from './utils/attribute';
import MissingScript from '../components/missing-script';
import { Details } from './deserialize';
import { Platform } from '../../../pal/system-info/enum-type';
import { sys } from '../platform/sys';
import { error } from '../platform/debug';
import { CustomSerializable, DeserializationContext, deserializeTag, SerializationContext, SerializationInput } from './custom-serializable';
import type { deserialize, CCClassConstructor } from './deserialize';
import { CCON } from './ccon';
import { assertIsTrue } from './utils/asserts';
import { reportMissingClass as defaultReportMissingClass } from './report-missing-class';
function compileObjectTypeJit (
sources: string[],
defaultValue: unknown,
accessorToSet: string,
propNameLiteralToSet: string,
assumeHavePropIfIsValue: boolean,
) {
if (defaultValue instanceof legacyCC.ValueType) {
// fast case
if (!assumeHavePropIfIsValue) {
sources.push('if(prop){');
}
// @ts-expect-error Typing
const ctorCode = js.getClassName(defaultValue);
sources.push(`s._deserializeFastDefinedObject(o${accessorToSet},prop,${ctorCode});`);
if (!assumeHavePropIfIsValue) {
sources.push(`}else o${accessorToSet}=null;`);
}
} else {
sources.push(`
if (prop) {
s._deserializeAndAssignField(o, prop, ${propNameLiteralToSet});
} else {
o${accessorToSet}=null;
}
`);
}
}
type ReportMissingClass = deserialize.ReportMissingClass;
type ClassFinder = deserialize.ClassFinder;
type SerializableClassConstructor = deserialize.SerializableClassConstructor;
export type CompiledDeserializeFn = (
deserializer: _Deserializer,
object: Record<string, unknown>,
deserialized: Record<string, unknown>,
constructor: AnyFunction,
) => void;
const compileDeserialize = SUPPORT_JIT ? compileDeserializeJIT : compileDeserializeNative;
const DELIMITER = Attr.DELIMETER;
const POSTFIX_TYPE: `${typeof DELIMITER}type` = `${DELIMITER}type`;
const POSTFIX_EDITOR_ONLY: `${typeof DELIMITER}editorOnly` = `${DELIMITER}editorOnly`;
const POSTFIX_DEFAULT: `${typeof DELIMITER}default` = `${DELIMITER}default`;
const POSTFIX_FORMERLY_SERIALIZED_AS: `${typeof DELIMITER}formerlySerializedAs` = `${DELIMITER}formerlySerializedAs`;
type AttributeName = string;
type AttributeFormerlySerializedAs = `${AttributeName}${typeof POSTFIX_FORMERLY_SERIALIZED_AS}`;
type AttributeDefault = `${AttributeName}${typeof POSTFIX_DEFAULT}`;
type AttributeType = `${AttributeName}${typeof POSTFIX_TYPE}`;
type AttributeEditorOnly = `${AttributeName}${typeof POSTFIX_EDITOR_ONLY}`;
type AttrResult = {
[K: string]: typeof K extends AttributeFormerlySerializedAs ? string :
typeof K extends AttributeDefault ? unknown :
typeof K extends AttributeType ? AnyFunction :
typeof K extends AttributeEditorOnly ? boolean : never;
};
function compileDeserializeJIT (self: _Deserializer, klass: CCClassConstructor<unknown>): CompiledDeserializeFn {
const attrs: AttrResult = Attr.getClassAttrs(klass);
const props = klass.__values__;
// self, obj, serializedData, klass
const sources = [
'var prop;',
];
const fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass));
// sources.push('var vb,vn,vs,vo,vu,vf;'); // boolean, number, string, object, undefined, function
for (let p = 0; p < props.length; p++) {
const propName = props[p];
// @ts-expect-error 2341
if ((PREVIEW || (EDITOR && self._ignoreEditorOnly)) && attrs[propName + POSTFIX_EDITOR_ONLY]) {
continue; // skip editor only if in preview
}
let accessorToSet: string;
let propNameLiteralToSet: string;
if (CCClass.IDENTIFIER_RE.test(propName)) {
propNameLiteralToSet = `"${propName}"`;
accessorToSet = `.${propName}`;
} else {
propNameLiteralToSet = CCClass.escapeForJS(propName);
accessorToSet = `[${propNameLiteralToSet}]`;
}
let accessorToGet = accessorToSet;
if (attrs[propName + POSTFIX_FORMERLY_SERIALIZED_AS]) {
const propNameToRead = attrs[propName + POSTFIX_FORMERLY_SERIALIZED_AS] as string;
if (CCClass.IDENTIFIER_RE.test(propNameToRead)) {
accessorToGet = `.${propNameToRead}`;
} else {
accessorToGet = `[${CCClass.escapeForJS(propNameToRead)}]`;
}
}
sources.push(`prop=d${accessorToGet};`);
sources.push(`if(typeof ${JSB ? '(prop)' : 'prop'}!=="undefined"){`);
// function undefined object(null) string boolean number
const defaultValue = CCClass.getDefault(attrs[propName + POSTFIX_DEFAULT]);
if (fastMode) {
let isPrimitiveType;
const userType = attrs[propName + POSTFIX_TYPE] as AnyFunction | undefined;
if (defaultValue === undefined && userType) {
isPrimitiveType = userType instanceof Attr.PrimitiveType;
} else {
const defaultType = typeof defaultValue;
isPrimitiveType = defaultType === 'string'
|| defaultType === 'number'
|| defaultType === 'boolean';
}
if (isPrimitiveType) {
sources.push(`o${accessorToSet}=prop;`);
} else {
compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, true);
}
} else {
sources.push(`${`if(typeof ${JSB ? '(prop)' : 'prop'}!=="object"){`
+ 'o'}${accessorToSet}=prop;`
+ `}else{`);
compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, false);
sources.push('}');
}
sources.push('}');
}
if (legacyCC.js.isChildClassOf(klass, legacyCC._BaseNode) || legacyCC.js.isChildClassOf(klass, legacyCC.Component)) {
// @ts-expect-error 2341
if (PREVIEW || (EDITOR && self._ignoreEditorOnly)) {
const mayUsedInPersistRoot = js.isChildClassOf(klass, legacyCC.Node);
if (mayUsedInPersistRoot) {
sources.push('d._id&&(o._id=d._id);');
}
} else {
sources.push('d._id&&(o._id=d._id);');
}
}
if (props[props.length - 1] === '_$erialized') {
// deep copy original serialized data
sources.push('o._$erialized=JSON.parse(JSON.stringify(d));');
// parse the serialized data as primitive javascript object, so its __id__ will be dereferenced
sources.push('s._fillPlainObject(o._$erialized,d);');
}
// eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
return Function('s', 'o', 'd', 'k', sources.join('')) as CompiledDeserializeFn;
}
function compileDeserializeNative (_self: _Deserializer, klass: CCClassConstructor<unknown>): CompiledDeserializeFn {
const fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass));
const shouldCopyId = js.isChildClassOf(klass, legacyCC._BaseNode) || js.isChildClassOf(klass, legacyCC.Component);
let shouldCopyRawData = false;
const simpleProps: string[] = [];
let simplePropsToRead = simpleProps;
const advancedProps: string[] = [];
let advancedPropsToRead = advancedProps;
const advancedPropsValueType: any = [];
(() => {
const props: string[] = klass.__values__;
shouldCopyRawData = props[props.length - 1] === '_$erialized';
const attrs = Attr.getClassAttrs(klass);
for (let p = 0; p < props.length; p++) {
const propName = props[p];
let propNameToRead = propName;
if (attrs[propName + POSTFIX_FORMERLY_SERIALIZED_AS]) {
propNameToRead = attrs[propName + POSTFIX_FORMERLY_SERIALIZED_AS];
}
// function undefined object(null) string boolean number
const defaultValue = CCClass.getDefault(attrs[propName + POSTFIX_DEFAULT]);
let isPrimitiveType = false;
if (fastMode) {
const userType = attrs[propName + POSTFIX_TYPE];
if (defaultValue === undefined && userType) {
isPrimitiveType = userType instanceof Attr.PrimitiveType;
} else {
const defaultType = typeof defaultValue;
isPrimitiveType = defaultType === 'string'
|| defaultType === 'number'
|| defaultType === 'boolean';
}
}
if (fastMode && isPrimitiveType) {
if (propNameToRead !== propName && simplePropsToRead === simpleProps) {
simplePropsToRead = simpleProps.slice();
}
simpleProps.push(propName);
if (simplePropsToRead !== simpleProps) {
simplePropsToRead.push(propNameToRead);
}
} else {
if (propNameToRead !== propName && advancedPropsToRead === advancedProps) {
advancedPropsToRead = advancedProps.slice();
}
advancedProps.push(propName);
if (advancedPropsToRead !== advancedProps) {
advancedPropsToRead.push(propNameToRead);
}
advancedPropsValueType.push((defaultValue instanceof legacyCC.ValueType) && defaultValue.constructor);
}
}
})();
return (s, o, d, k) => {
for (let i = 0; i < simpleProps.length; ++i) {
const prop = d[simplePropsToRead[i]];
if (prop !== undefined) {
o[simpleProps[i]] = prop;
}
}
for (let i = 0; i < advancedProps.length; ++i) {
const propName = advancedProps[i];
const prop = d[advancedPropsToRead[i]];
if (prop === undefined) {
continue;
}
if (!fastMode && typeof prop !== 'object') {
o[propName] = prop;
} else {
// fastMode (so will not simpleProp) or object
const valueTypeCtor = advancedPropsValueType[i];
if (valueTypeCtor) {
if (fastMode || prop) {
// @ts-expect-error 2341
s._deserializeFastDefinedObject(o[propName] as Record<PropertyKey, unknown>, prop as SerializedGeneralTypedObject, valueTypeCtor);
} else {
o[propName] = null;
}
} else if (prop) {
// @ts-expect-error 2341
s._deserializeAndAssignField(o, prop, propName);
} else {
o[propName] = null;
}
}
}
if (shouldCopyId && d._id) {
o._id = d._id;
}
if (shouldCopyRawData) {
// deep copy original serialized data
o._$erialized = JSON.parse(JSON.stringify(d));
// parse the serialized data as primitive javascript object, so its __id__ will be dereferenced
// @ts-expect-error 2341
s._fillPlainObject(o._$erialized as Record<PropertyKey, unknown>, d);
}
};
}
type TypedArrayViewConstructorName =
| 'Uint8Array' | 'Int8Array'
| 'Uint16Array' | 'Int16Array'
| 'Uint32Array' | 'Int32Array'
| 'Float32Array' | 'Float64Array';
type SerializedTypedArray = {
__id__: never;
__uuid__: never;
__type__: 'TypedArray';
array: number[];
ctor: TypedArrayViewConstructorName;
};
type SerializedTypedArrayRef = {
__id__: never;
__uuid__: never;
__type__: 'TypedArrayRef';
ctor: TypedArrayViewConstructorName;
offset: number;
length: number;
};
type SerializedGeneralTypedObject = {
__id__: never;
__uuid__: never;
__type__?: NotKnownTypeTag;
} & Record<NotTypeTag, SerializedFieldValue>;
type SerializedObjectReference = {
__type__: never;
__uuid__: never;
__id__: number;
}
type SerializedUUIDReference = {
__type__: never;
__id__: never;
__uuid__: string;
__expectedType__: string;
};
type SerializedObject = SerializedTypedArray | SerializedTypedArrayRef | SerializedGeneralTypedObject;
type SerializedValue = SerializedObject | SerializedValue[] | string | number | boolean | null;
type SerializedPropertyKey = string | number;
type SerializedFieldObjectValue = SerializedObjectReference | SerializedUUIDReference | unknown;
type SerializedFieldValue = string | number | boolean | null | SerializedFieldObjectValue;
type NotA<T, ReservedNames> = T extends ReservedNames ? never : T;
type NotB<T, ReservedNames> = ReservedNames extends T ? never : T;
type FooName<T, ReservedNames> = NotA<T, ReservedNames> & NotB<T, ReservedNames>
type NotTypeTag = FooName<string, '__type__'>;
type NotKnownTypeTag = FooName<string, 'TypedArray' | 'TypedArrayRef'>;
type SerializedData = SerializedObject | SerializedObject[];
class DeserializerPool extends js.Pool<_Deserializer> {
constructor () {
super((deserializer: _Deserializer) => {
deserializer.clear();
}, 1);
}
// @ts-expect-error We only use this signature.
public get (
details: Details,
classFinder: ClassFinder,
reportMissingClass: ReportMissingClass,
customEnv: unknown,
ignoreEditorOnly: boolean | undefined,
) {
const cache = this._get();
if (cache) {
cache.reset(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
return cache;
} else {
return new _Deserializer(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
}
}
}
class _Deserializer {
public static pool: DeserializerPool = new DeserializerPool();
public declare result: Details;
public declare customEnv: unknown;
public deserializedList: Array<Record<PropertyKey, unknown> | undefined>;
public deserializedData: any;
private declare _classFinder: ClassFinder;
private declare _reportMissingClass: ReportMissingClass;
private declare _onDereferenced: ClassFinder['onDereferenced'];
private _ignoreEditorOnly: any;
private declare _mainBinChunk: Uint8Array;
private declare _serializedData: SerializedObject | SerializedObject[];
private declare _context: DeserializationContext;
constructor (result: Details, classFinder: ClassFinder, reportMissingClass: ReportMissingClass, customEnv: unknown, ignoreEditorOnly: unknown) {
this.result = result;
this.customEnv = customEnv;
this.deserializedList = [];
this.deserializedData = null;
this._classFinder = classFinder;
this._reportMissingClass = reportMissingClass;
this._onDereferenced = classFinder?.onDereferenced;
if (DEV) {
this._ignoreEditorOnly = ignoreEditorOnly;
}
}
public reset (result: Details, classFinder: ClassFinder, reportMissingClass: ReportMissingClass, customEnv: unknown, ignoreEditorOnly: unknown) {
this.result = result;
this.customEnv = customEnv;
this._classFinder = classFinder;
this._reportMissingClass = reportMissingClass;
this._onDereferenced = classFinder?.onDereferenced;
if (DEV) {
this._ignoreEditorOnly = ignoreEditorOnly;
}
}
public clear () {
this.result = null!;
this.customEnv = null;
this.deserializedList.length = 0;
this.deserializedData = null;
this._classFinder = null!;
this._reportMissingClass = null!;
this._onDereferenced = null!;
}
public deserialize (serializedData: SerializedData | CCON) {
let fromCCON = false;
let jsonObj: SerializedData;
if (serializedData instanceof CCON) {
fromCCON = true;
jsonObj = serializedData.document as SerializedData;
if (serializedData.chunks.length > 0) {
assertIsTrue(serializedData.chunks.length === 1);
this._mainBinChunk = serializedData.chunks[0];
}
} else {
jsonObj = serializedData;
}
this._serializedData = jsonObj;
this._context = {
fromCCON,
};
const serializedRootObject = Array.isArray(jsonObj) ? jsonObj[0] : jsonObj;
if (EDITOR || TEST) {
this.deserializedData = this._deserializeObject(serializedRootObject, 0, this.deserializedList, `${0}`);
} else {
this.deserializedData = this._deserializeObject(serializedRootObject, 0);
}
this._serializedData = undefined!;
this._mainBinChunk = undefined!;
this._context = undefined!;
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this.deserializedData;
}
/**
* @param serialized - The object to deserialize, must be non-nil.
* @param globalIndex - If the object is deserialized from "root objects" array.
* @param owner - Tracing purpose.
* @param propName - Tracing purpose.
*/
private _deserializeObject (
serialized: SerializedObject,
globalIndex: number,
owner?: Record<PropertyKey, unknown> | unknown[],
propName?: string,
) {
switch (serialized.__type__) {
case 'TypedArray':
return this._deserializeTypedArrayView(serialized);
case 'TypedArrayRef':
return this._deserializeTypedArrayViewRef(serialized);
default:
if (serialized.__type__) { // Typed object (including CCClass)
return this._deserializeTypeTaggedObject(serialized, globalIndex, owner, propName);
} else if (!Array.isArray(serialized)) { // Embedded primitive javascript object
return this._deserializePlainObject(serialized);
} else { // Array
return this._deserializeArray(serialized);
}
}
}
private _deserializeTypedArrayView (value: SerializedTypedArray) {
return globalThis[value.ctor].from(value.array);
}
private _deserializeTypedArrayViewRef (value: SerializedTypedArrayRef) {
const { offset, length, ctor: constructorName } = value;
const obj = new globalThis[constructorName](
this._mainBinChunk.buffer,
this._mainBinChunk.byteOffset + offset,
length,
);
return obj;
}
private _deserializeArray (value: SerializedValue[]) {
const obj = new Array<unknown>(value.length);
let prop: unknown;
for (let i = 0; i < value.length; i++) {
prop = value[i];
if (typeof prop === 'object' && prop) {
const isAssetType = this._deserializeAndAssignField(obj, prop, `${i}`);
if (isAssetType) {
// fill default value for primitive objects (no constructor)
obj[i] = null;
}
} else {
obj[i] = prop;
}
}
return obj;
}
private _deserializePlainObject (value: Record<string, unknown>) {
const obj = {};
this._fillPlainObject(obj, value);
return obj;
}
private _deserializeTypeTaggedObject (
value: SerializedGeneralTypedObject,
globalIndex: number,
owner?: Record<PropertyKey, unknown> | unknown[],
propName?: string,
) {
const type = value.__type__ as unknown as string;
const klass = this._classFinder(type, value, owner, propName);
if (!klass) {
const notReported = this._classFinder === js._getClassById;
if (notReported) {
this._reportMissingClass(type);
}
return null;
}
const createObject = (constructor: deserialize.SerializableClassConstructor) => {
// eslint-disable-next-line new-cap
const obj = new constructor() as Record<string, unknown>;
if (globalIndex >= 0) {
this.deserializedList[globalIndex] = obj;
}
return obj;
};
if (!(EDITOR && legacyCC.js.isChildClassOf(klass, legacyCC.Component))) {
const obj = createObject(klass);
this._deserializeInto(value, obj, klass);
return obj;
} else {
try {
const obj = createObject(klass);
this._deserializeInto(value, obj, klass);
return obj;
} catch (e: unknown) {
if (DEBUG) {
error(`Deserialize ${klass.name} failed, ${(e as { stack: string; }).stack}`);
}
this._reportMissingClass(type);
const obj = createObject(MissingScript);
this._deserializeInto(value, obj, MissingScript);
return obj;
}
}
}
private _deserializeInto (
value: SerializedGeneralTypedObject,
object: Record<PropertyKey, unknown>,
constructor: deserialize.SerializableClassConstructor,
skipCustomized = false,
) {
if (!skipCustomized && (object as Partial<CustomSerializable>)[deserializeTag]) {
this._runCustomizedDeserialize(
value,
object as Record<PropertyKey, unknown> & CustomSerializable,
constructor,
);
return;
}
// cSpell:words Deserializable
type ClassicCustomizedDeserializable = { _deserialize: (content: unknown, deserializer: _Deserializer) => void; };
if ((object as Partial<ClassicCustomizedDeserializable>)._deserialize) {
// TODO: content check?
(object as ClassicCustomizedDeserializable)._deserialize((value as unknown as { content: unknown }).content, this);
return;
}
if (legacyCC.Class._isCCClass(constructor)) {
this._deserializeFireClass(object, value, constructor as CCClassConstructor<unknown>);
} else {
this._deserializeFastDefinedObject(object, value, constructor);
}
}
private _runCustomizedDeserialize (
value: SerializedGeneralTypedObject,
object: Record<PropertyKey, unknown> & CustomSerializable,
constructor: deserialize.SerializableClassConstructor,
) {
const serializationInput: SerializationInput = {
readProperty: (name: string) => {
const serializedField = value[name];
if (typeof serializedField !== 'object' || !serializedField) {
return serializedField as unknown;
} else {
return this._deserializeObjectField(serializedField) as unknown;
}
},
readThis: () => {
this._deserializeInto(value, object, constructor, true);
},
readSuper: () => {
const superConstructor = js.getSuper(constructor);
if (superConstructor) {
this._deserializeInto(value, object, superConstructor);
}
},
};
object[deserializeTag]!(serializationInput, this._context);
}
private _deserializeFireClass (obj: Record<PropertyKey, unknown>, serialized: SerializedGeneralTypedObject, klass: CCClassConstructor<unknown>) {
let deserialize: CompiledDeserializeFn;
// eslint-disable-next-line no-prototype-builtins
if (klass.hasOwnProperty('__deserialize__')) {
deserialize = klass.__deserialize__ as CompiledDeserializeFn;
} else {
deserialize = compileDeserialize(this, klass);
js.value(klass, '__deserialize__', deserialize, true);
}
deserialize(this, obj, serialized, klass);
}
private _deserializeAndAssignField (
obj: Record<PropertyKey, unknown> | unknown[],
serializedField: SerializedFieldObjectValue,
propName: string,
) {
const id = (serializedField as Partial<SerializedObjectReference>).__id__;
if (typeof id === 'number') {
const field = this.deserializedList[id];
if (field) {
obj[propName] = field;
} else {
// TODO: assertion
const source = (this._serializedData as SerializedObject[])[id];
if (EDITOR || TEST) {
obj[propName] = this._deserializeObject(source, id, obj, propName);
} else {
obj[propName] = this._deserializeObject(source, id, undefined, propName);
}
this._onDereferenced?.(this.deserializedList, id, obj, propName);
}
} else {
const uuid = (serializedField as Partial<SerializedUUIDReference>).__uuid__;
if (uuid) {
const expectedType = (serializedField as SerializedUUIDReference).__expectedType__;
this.result.push(obj, propName, uuid, expectedType);
} else if (EDITOR || TEST) {
obj[propName] = this._deserializeObject(serializedField as SerializedObject, -1, obj, propName);
} else {
obj[propName] = this._deserializeObject(serializedField as SerializedObject, -1);
}
}
return false;
}
private _deserializeObjectField (serializedField: SerializedFieldObjectValue) {
const id = (serializedField as Partial<SerializedObjectReference>).__id__;
if (typeof id === 'number') {
const field = this.deserializedList[id];
if (field) {
return field;
} else {
// TODO: assertion
const source = (this._serializedData as SerializedObject[])[id];
const field = this._deserializeObject(source, id, undefined, undefined);
return field;
}
} else {
const uuid = (serializedField as Partial<SerializedUUIDReference>).__uuid__;
if (uuid) {
const _expectedType = (serializedField as SerializedUUIDReference).__expectedType__;
throw new Error(`Asset reference field serialization is currently not supported in custom serialization.`);
} else {
return this._deserializeObject(serializedField as SerializedObject, -1);
}
}
}
private _fillPlainObject (instance: Record<string, unknown>, serialized: Record<string, unknown>) {
for (const propName in serialized) {
// eslint-disable-next-line no-prototype-builtins
if (!serialized.hasOwnProperty(propName)) {
continue;
}
const prop = serialized[propName];
if (typeof prop !== 'object') {
if (propName !== '__type__'/* && k != '__id__' */) {
instance[propName] = prop;
}
} else if (prop) {
const isAssetType = this._deserializeAndAssignField(instance, prop, propName);
if (isAssetType) {
// fill default value for primitive objects (no constructor)
instance[propName] = null;
}
} else {
instance[propName] = null;
}
}
}
private _deserializeFastDefinedObject (
instance: Record<PropertyKey, unknown>,
serialized: SerializedGeneralTypedObject,
klass: SerializableClassConstructor,
) {
if (klass === legacyCC.Vec2) {
type SerializedVec2 = { x?: number; y?: number; };
instance.x = (serialized as SerializedVec2).x || 0;
instance.y = (serialized as SerializedVec2).y || 0;
return;
} else if (klass === legacyCC.Vec3) {
type SerializedVec3 = { x?: number; y?: number; z?: number; };
instance.x = (serialized as SerializedVec3).x || 0;
instance.y = (serialized as SerializedVec3).y || 0;
instance.z = (serialized as SerializedVec3).z || 0;
return;
} else if (klass === legacyCC.Color) {
type SerializedColor = { r?: number; g?: number; b?: number; a?: number; };
instance.r = (serialized as SerializedColor).r || 0;
instance.g = (serialized as SerializedColor).g || 0;
instance.b = (serialized as SerializedColor).b || 0;
const a = (serialized as SerializedColor).a;
instance.a = (a === undefined ? 255 : a);
return;
} else if (klass === legacyCC.Size) {
type SerializedSize = { width?: number; height?: number; };
instance.width = (serialized as SerializedSize).width || 0;
instance.height = (serialized as SerializedSize).height || 0;
return;
}
const attrs = Attr.getClassAttrs(klass);
// @ts-expect-error 2339
const props: string[] = klass.__values__;
if (DEBUG && !props) {
error(`Unable to deserialize ${js.getClassName(klass)}. `
+ 'For non-CCClass types, they can only be marked as serializable by `CCClass.fastDefine`.');
}
for (let i = 0; i < props.length; i++) {
const propName: string = props[i];
let value = serialized[propName];
// eslint-disable-next-line no-prototype-builtins
const exists: boolean = (value !== undefined || serialized.hasOwnProperty(propName));
if (!exists) {
// not serialized,
// recover to default value in ValueType, because eliminated properties equals to
// its default value in ValueType, not default value in user class
value = CCClass.getDefault(attrs[propName + POSTFIX_DEFAULT]);
}
if (typeof value !== 'object') {
instance[propName] = value;
} else if (value) {
this._deserializeAndAssignField(instance, value, propName);
} else {
instance[propName] = null;
}
}
}
}
export function deserializeDynamic (data: SerializedData | CCON, details: Details, options?: {
classFinder?: ClassFinder;
ignoreEditorOnly?: boolean;
createAssetRefs?: boolean;
customEnv?: unknown;
reportMissingClass?: ReportMissingClass;
}) {
options = options || {};
const classFinder = options.classFinder || js._getClassById;
const createAssetRefs = options.createAssetRefs || sys.platform === Platform.EDITOR_CORE;
const customEnv = options.customEnv;
const ignoreEditorOnly = options.ignoreEditorOnly;
const reportMissingClass = options.reportMissingClass ?? legacyCC.deserialize.reportMissingClass;
// var oldJson = JSON.stringify(data, null, 2);
details.init();
const deserializer = _Deserializer.pool.get(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
legacyCC.game._isCloning = true;
const res = deserializer.deserialize(data);
legacyCC.game._isCloning = false;
_Deserializer.pool.put(deserializer);
if (createAssetRefs) {
details.assignAssetsBy(EditorExtends.serialize.asAsset);
}
// var afterJson = JSON.stringify(data, null, 2);
// if (oldJson !== afterJson) {
// throw new Error('JSON SHOULD not changed');
// }
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return res;
}
export function parseUuidDependenciesDynamic (serialized: unknown) {
const depends = [];
const parseDependRecursively = (data: any, out: string[]) => {
if (!data || typeof data !== 'object' || typeof data.__id__ === 'number') { return; }
const uuid = data.__uuid__;
if (Array.isArray(data)) {
for (let i = 0, l = data.length; i < l; i++) {
parseDependRecursively(data[i], out);
}
} else if (uuid) {
out.push(uuid);
} else {
for (const prop in data) {
parseDependRecursively(data[prop], out);
}
}
};
parseDependRecursively(serialized, depends);
return depends;
} | the_stack |
/* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-interface */
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable no-irregular-whitespace */
import {
OAuth2Client,
JWT,
Compute,
UserRefreshClient,
BaseExternalAccountClient,
GaxiosPromise,
GoogleConfigurable,
createAPIRequest,
MethodOptions,
StreamMethodOptions,
GlobalOptions,
GoogleAuth,
BodyResponseCallback,
APIRequestContext,
} from 'googleapis-common';
import {Readable} from 'stream';
export namespace chromemanagement_v1 {
export interface Options extends GlobalOptions {
version: 'v1';
}
interface StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?:
| string
| OAuth2Client
| JWT
| Compute
| UserRefreshClient
| BaseExternalAccountClient
| GoogleAuth;
/**
* V1 error format.
*/
'$.xgafv'?: string;
/**
* OAuth access token.
*/
access_token?: string;
/**
* Data format for response.
*/
alt?: string;
/**
* JSONP
*/
callback?: string;
/**
* Selector specifying which fields to include in a partial response.
*/
fields?: string;
/**
* API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
*/
key?: string;
/**
* OAuth 2.0 token for the current user.
*/
oauth_token?: string;
/**
* Returns response with indentations and line breaks.
*/
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
*/
quotaUser?: string;
/**
* Legacy upload protocol for media (e.g. "media", "multipart").
*/
uploadType?: string;
/**
* Upload protocol for media (e.g. "raw", "multipart").
*/
upload_protocol?: string;
}
/**
* Chrome Management API
*
* The Chrome Management API is a suite of services that allows Chrome administrators to view, manage and gain insights on their Chrome OS and Chrome Browser devices.
*
* @example
* ```js
* const {google} = require('googleapis');
* const chromemanagement = google.chromemanagement('v1');
* ```
*/
export class Chromemanagement {
context: APIRequestContext;
customers: Resource$Customers;
constructor(options: GlobalOptions, google?: GoogleConfigurable) {
this.context = {
_options: options || {},
google,
};
this.customers = new Resource$Customers(this.context);
}
}
/**
* Android app information.
*/
export interface Schema$GoogleChromeManagementV1AndroidAppInfo {
/**
* Output only. Permissions requested by an Android app.
*/
permissions?: Schema$GoogleChromeManagementV1AndroidAppPermission[];
}
/**
* Permission requested by an Android app.
*/
export interface Schema$GoogleChromeManagementV1AndroidAppPermission {
/**
* Output only. The type of the permission.
*/
type?: string | null;
}
/**
* Resource representing app details.
*/
export interface Schema$GoogleChromeManagementV1AppDetails {
/**
* Output only. Android app information.
*/
androidAppInfo?: Schema$GoogleChromeManagementV1AndroidAppInfo;
/**
* Output only. Unique store identifier for the item. Examples: "gmbmikajjgmnabiglmofipeabaddhgne" for the Save to Google Drive Chrome extension, "com.google.android.apps.docs" for the Google Drive Android app.
*/
appId?: string | null;
/**
* Output only. Chrome Web Store app information.
*/
chromeAppInfo?: Schema$GoogleChromeManagementV1ChromeAppInfo;
/**
* Output only. App's description.
*/
description?: string | null;
/**
* Output only. The uri for the detail page of the item.
*/
detailUri?: string | null;
/**
* Output only. App's display name.
*/
displayName?: string | null;
/**
* Output only. First published time.
*/
firstPublishTime?: string | null;
/**
* Output only. Home page or Website uri.
*/
homepageUri?: string | null;
/**
* Output only. A link to an image that can be used as an icon for the product.
*/
iconUri?: string | null;
/**
* Output only. Indicates if the app has to be paid for OR has paid content.
*/
isPaidApp?: boolean | null;
/**
* Output only. Latest published time.
*/
latestPublishTime?: string | null;
/**
* Output only. Format: name=customers/{customer_id\}/apps/{chrome|android|web\}/{app_id\}@{version\}
*/
name?: string | null;
/**
* Output only. The URI pointing to the privacy policy of the app, if it was provided by the developer. Version-specific field that will only be set when the requested app version is found.
*/
privacyPolicyUri?: string | null;
/**
* Output only. The publisher of the item.
*/
publisher?: string | null;
/**
* Output only. Number of reviews received. Chrome Web Store review information will always be for the latest version of an app.
*/
reviewNumber?: string | null;
/**
* Output only. The rating of the app (on 5 stars). Chrome Web Store review information will always be for the latest version of an app.
*/
reviewRating?: number | null;
/**
* Output only. App version. A new revision is committed whenever a new version of the app is published.
*/
revisionId?: string | null;
/**
* Output only. Information about a partial service error if applicable.
*/
serviceError?: Schema$GoogleRpcStatus;
/**
* Output only. App type.
*/
type?: string | null;
}
/**
* Battery info
*/
export interface Schema$GoogleChromeManagementV1BatteryInfo {
/**
* Output only. Design capacity (mAmpere-hours).
*/
designCapacity?: string | null;
/**
* Output only. Designed minimum output voltage (mV)
*/
designMinVoltage?: number | null;
/**
* Output only. The date the battery was manufactured.
*/
manufactureDate?: Schema$GoogleTypeDate;
/**
* Output only. Battery manufacturer.
*/
manufacturer?: string | null;
/**
* Output only. Battery serial number.
*/
serialNumber?: string | null;
/**
* Output only. Technology of the battery. Example: Li-ion
*/
technology?: string | null;
}
/**
* Sampling data for battery.
*/
export interface Schema$GoogleChromeManagementV1BatterySampleReport {
/**
* Output only. Battery charge percentage.
*/
chargeRate?: number | null;
/**
* Output only. Battery current (mA).
*/
current?: string | null;
/**
* Output only. The battery discharge rate measured in mW. Positive if the battery is being discharged, negative if it's being charged.
*/
dischargeRate?: number | null;
/**
* Output only. Battery remaining capacity (mAmpere-hours).
*/
remainingCapacity?: string | null;
/**
* Output only. Timestamp of when the sample was collected on device
*/
reportTime?: string | null;
/**
* Output only. Battery status read from sysfs. Example: Discharging
*/
status?: string | null;
/**
* Output only. Temperature in Celsius degrees.
*/
temperature?: number | null;
/**
* Output only. Battery voltage (millivolt).
*/
voltage?: string | null;
}
/**
* Status data for battery.
*/
export interface Schema$GoogleChromeManagementV1BatteryStatusReport {
/**
* Output only. Battery health.
*/
batteryHealth?: string | null;
/**
* Output only. Cycle count.
*/
cycleCount?: number | null;
/**
* Output only. Full charge capacity (mAmpere-hours).
*/
fullChargeCapacity?: string | null;
/**
* Output only. Timestamp of when the sample was collected on device
*/
reportTime?: string | null;
/**
* Output only. Sampling data for the battery.
*/
sample?: Schema$GoogleChromeManagementV1BatterySampleReport[];
/**
* Output only. Battery serial number.
*/
serialNumber?: string | null;
}
/**
* Describes a browser version and its install count.
*/
export interface Schema$GoogleChromeManagementV1BrowserVersion {
/**
* Output only. The release channel of the installed browser.
*/
channel?: string | null;
/**
* Output only. Count grouped by device_system and major version
*/
count?: string | null;
/**
* Output only. Version of the system-specified operating system.
*/
deviceOsVersion?: string | null;
/**
* Output only. The device operating system.
*/
system?: string | null;
/**
* Output only. The full version of the installed browser.
*/
version?: string | null;
}
/**
* Chrome Web Store app information.
*/
export interface Schema$GoogleChromeManagementV1ChromeAppInfo {
/**
* Output only. Whether the app or extension is built and maintained by Google. Version-specific field that will only be set when the requested app version is found.
*/
googleOwned?: boolean | null;
/**
* Output only. Whether the app or extension is in a published state in the Chrome Web Store.
*/
isCwsHosted?: boolean | null;
/**
* Output only. Whether the app or extension is a theme.
*/
isTheme?: boolean | null;
/**
* Output only. The minimum number of users using this app.
*/
minUserCount?: number | null;
/**
* Output only. Every custom permission requested by the app. Version-specific field that will only be set when the requested app version is found.
*/
permissions?: Schema$GoogleChromeManagementV1ChromeAppPermission[];
/**
* Output only. Every permission giving access to domains or broad host patterns. ( e.g. www.google.com). This includes the matches from content scripts as well as hosts in the permissions node of the manifest. Version-specific field that will only be set when the requested app version is found.
*/
siteAccess?: Schema$GoogleChromeManagementV1ChromeAppSiteAccess[];
/**
* Output only. The app developer has enabled support for their app. Version-specific field that will only be set when the requested app version is found.
*/
supportEnabled?: boolean | null;
}
/**
* Permission requested by a Chrome app or extension.
*/
export interface Schema$GoogleChromeManagementV1ChromeAppPermission {
/**
* Output only. If available, whether this permissions grants the app/extension access to user data.
*/
accessUserData?: boolean | null;
/**
* Output only. If available, a URI to a page that has documentation for the current permission.
*/
documentationUri?: string | null;
/**
* Output only. The type of the permission.
*/
type?: string | null;
}
/**
* Details of an app installation request.
*/
export interface Schema$GoogleChromeManagementV1ChromeAppRequest {
/**
* Output only. Format: app_details=customers/{customer_id\}/apps/chrome/{app_id\}
*/
appDetails?: string | null;
/**
* Output only. Unique store identifier for the app. Example: "gmbmikajjgmnabiglmofipeabaddhgne" for the Save to Google Drive Chrome extension.
*/
appId?: string | null;
/**
* Output only. The uri for the detail page of the item.
*/
detailUri?: string | null;
/**
* Output only. App's display name.
*/
displayName?: string | null;
/**
* Output only. A link to an image that can be used as an icon for the product.
*/
iconUri?: string | null;
/**
* Output only. The timestamp of the most recently made request for this app.
*/
latestRequestTime?: string | null;
/**
* Output only. Total count of requests for this app.
*/
requestCount?: string | null;
}
/**
* Represent one host permission.
*/
export interface Schema$GoogleChromeManagementV1ChromeAppSiteAccess {
/**
* Output only. This can contain very specific hosts, or patterns like "*.com" for instance.
*/
hostMatch?: string | null;
}
/**
* Response containing summary of requested app installations.
*/
export interface Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse {
/**
* Token to specify the next page in the list.
*/
nextPageToken?: string | null;
/**
* Count of requested apps matching request.
*/
requestedApps?: Schema$GoogleChromeManagementV1ChromeAppRequest[];
/**
* Total number of matching app requests.
*/
totalSize?: number | null;
}
/**
* Response containing requested browser versions details and counts.
*/
export interface Schema$GoogleChromeManagementV1CountChromeVersionsResponse {
/**
* List of all browser versions and their install counts.
*/
browserVersions?: Schema$GoogleChromeManagementV1BrowserVersion[];
/**
* Token to specify the next page of the request.
*/
nextPageToken?: string | null;
/**
* Total number browser versions matching request.
*/
totalSize?: number | null;
}
/**
* Response containing details of queried installed apps.
*/
export interface Schema$GoogleChromeManagementV1CountInstalledAppsResponse {
/**
* List of installed apps matching request.
*/
installedApps?: Schema$GoogleChromeManagementV1InstalledApp[];
/**
* Token to specify the next page of the request.
*/
nextPageToken?: string | null;
/**
* Total number of installed apps matching request.
*/
totalSize?: number | null;
}
/**
* CPU specs for a CPU.
*/
export interface Schema$GoogleChromeManagementV1CpuInfo {
/**
* Output only. The CPU architecture.
*/
architecture?: string | null;
/**
* Output only. The max CPU clock speed in kHz.
*/
maxClockSpeed?: number | null;
/**
* Output only. The CPU model name. Example: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
*/
model?: string | null;
}
/**
* Contains samples of the cpu status reports.
*/
export interface Schema$GoogleChromeManagementV1CpuStatusReport {
/**
* Output only. CPU temperature sample info per CPU core in Celsius
*/
cpuTemperatureInfo?: Schema$GoogleChromeManagementV1CpuTemperatureInfo[];
/**
* Output only. Sample of CPU utilization (0-100 percent).
*/
cpuUtilizationPct?: number | null;
/**
* Output only. The timestamp in milliseconds representing time at which this report was sampled.
*/
reportTime?: string | null;
/**
* Output only. Frequency the report is sampled.
*/
sampleFrequency?: string | null;
}
/**
* CPU temperature of a device. Sampled per CPU core in Celsius
*/
export interface Schema$GoogleChromeManagementV1CpuTemperatureInfo {
/**
* Output only. CPU label. Example: Core 0
*/
label?: string | null;
/**
* Output only. CPU temperature in Celsius.
*/
temperatureCelsius?: number | null;
}
/**
* Describes a device reporting Chrome browser information.
*/
export interface Schema$GoogleChromeManagementV1Device {
/**
* Output only. The ID of the device that reported this Chrome browser information.
*/
deviceId?: string | null;
/**
* Output only. The name of the machine within its local network.
*/
machine?: string | null;
}
/**
* Status of the single storage device.
*/
export interface Schema$GoogleChromeManagementV1DiskInfo {
/**
* Output only. Number of bytes read since last boot.
*/
bytesReadThisSession?: string | null;
/**
* Output only. Number of bytes written since last boot.
*/
bytesWrittenThisSession?: string | null;
/**
* Output only. Time spent discarding since last boot. Discarding is writing to clear blocks which are no longer in use. Supported on kernels 4.18+.
*/
discardTimeThisSession?: string | null;
/**
* Output only. Disk health.
*/
health?: string | null;
/**
* Output only. Counts the time the disk and queue were busy, so unlike the fields above, parallel requests are not counted multiple times.
*/
ioTimeThisSession?: string | null;
/**
* Output only. Disk manufacturer.
*/
manufacturer?: string | null;
/**
* Output only. Disk model.
*/
model?: string | null;
/**
* Output only. Time spent reading from disk since last boot.
*/
readTimeThisSession?: string | null;
/**
* Output only. Disk serial number.
*/
serialNumber?: string | null;
/**
* Output only. Disk size.
*/
sizeBytes?: string | null;
/**
* Output only. Disk type: eMMC / NVMe / ATA / SCSI.
*/
type?: string | null;
/**
* Output only. Disk volumes.
*/
volumeIds?: string[] | null;
/**
* Output only. Time spent writing to disk since last boot.
*/
writeTimeThisSession?: string | null;
}
/**
* Information for a display.
*/
export interface Schema$GoogleChromeManagementV1DisplayInfo {
/**
* Output only. Represents the graphics card device id.
*/
deviceId?: string | null;
/**
* Output only. Indicates if display is internal or not.
*/
isInternal?: boolean | null;
/**
* Output only. Refresh rate in Hz.
*/
refreshRate?: number | null;
/**
* Output only. Resolution height in pixels.
*/
resolutionHeight?: number | null;
/**
* Output only. Resolution width in pixels.
*/
resolutionWidth?: number | null;
}
/**
* Response containing a list of devices with queried app installed.
*/
export interface Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse {
/**
* A list of devices which have the app installed. Sorted in ascending alphabetical order on the Device.machine field.
*/
devices?: Schema$GoogleChromeManagementV1Device[];
/**
* Token to specify the next page of the request.
*/
nextPageToken?: string | null;
/**
* Total number of devices matching request.
*/
totalSize?: number | null;
}
/**
* Information of a graphics adapter (GPU).
*/
export interface Schema$GoogleChromeManagementV1GraphicsAdapterInfo {
/**
* Output only. Adapter name. Example: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2).
*/
adapter?: string | null;
/**
* Output only. Represents the graphics card device id.
*/
deviceId?: string | null;
/**
* Output only. Version of the GPU driver.
*/
driverVersion?: string | null;
}
/**
* Information of the graphics subsystem.
*/
export interface Schema$GoogleChromeManagementV1GraphicsInfo {
/**
* Output only. Information about the graphics adapter (GPU).
*/
adapterInfo?: Schema$GoogleChromeManagementV1GraphicsAdapterInfo;
}
/**
* Information of the graphics subsystem.
*/
export interface Schema$GoogleChromeManagementV1GraphicsStatusReport {
/**
* Output only. Information about the displays for the device.
*/
displays?: Schema$GoogleChromeManagementV1DisplayInfo[];
/**
* Output only. Time at which the graphics data was reported.
*/
reportTime?: string | null;
}
/**
* Describes an installed app.
*/
export interface Schema$GoogleChromeManagementV1InstalledApp {
/**
* Output only. Unique identifier of the app. For Chrome apps and extensions, the 32-character id (e.g. ehoadneljpdggcbbknedodolkkjodefl). For Android apps, the package name (e.g. com.evernote).
*/
appId?: string | null;
/**
* Output only. How the app was installed.
*/
appInstallType?: string | null;
/**
* Output only. Source of the installed app.
*/
appSource?: string | null;
/**
* Output only. Type of the app.
*/
appType?: string | null;
/**
* Output only. Count of browser devices with this app installed.
*/
browserDeviceCount?: string | null;
/**
* Output only. Description of the installed app.
*/
description?: string | null;
/**
* Output only. Whether the app is disabled.
*/
disabled?: boolean | null;
/**
* Output only. Name of the installed app.
*/
displayName?: string | null;
/**
* Output only. Homepage uri of the installed app.
*/
homepageUri?: string | null;
/**
* Output only. Count of ChromeOS users with this app installed.
*/
osUserCount?: string | null;
/**
* Output only. Permissions of the installed app.
*/
permissions?: string[] | null;
}
export interface Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse {
/**
* Telemetry devices returned in the response.
*/
devices?: Schema$GoogleChromeManagementV1TelemetryDevice[];
/**
* Token to specify next page in the list.
*/
nextPageToken?: string | null;
}
/**
* Memory information of a device.
*/
export interface Schema$GoogleChromeManagementV1MemoryInfo {
/**
* Output only. Amount of available RAM in bytes.
*/
availableRamBytes?: string | null;
/**
* Output only. Total RAM in bytes.
*/
totalRamBytes?: string | null;
}
/**
* Contains samples of memory status reports.
*/
export interface Schema$GoogleChromeManagementV1MemoryStatusReport {
/**
* Output only. Number of page faults during this collection
*/
pageFaults?: number | null;
/**
* Output only. The timestamp in milliseconds representing time at which this report was sampled.
*/
reportTime?: string | null;
/**
* Output only. Frequency the report is sampled.
*/
sampleFrequency?: string | null;
/**
* Output only. Amount of free RAM in bytes (unreliable due to Garbage Collection).
*/
systemRamFreeBytes?: string | null;
}
/**
* State of visible/configured networks.
*/
export interface Schema$GoogleChromeManagementV1NetworkStatusReport {
/**
* Output only. Gateway IP address.
*/
gatewayIpAddress?: string | null;
/**
* Output only. LAN IP address.
*/
lanIpAddress?: string | null;
/**
* Output only. Time at which the network state was reported.
*/
reportTime?: string | null;
/**
* Output only. Frequency the report is sampled.
*/
sampleFrequency?: string | null;
/**
* Output only. Signal strength for wireless networks measured in decibels.
*/
signalStrengthDbm?: number | null;
}
/**
* Contains information regarding the current OS update status.
*/
export interface Schema$GoogleChromeManagementV1OsUpdateStatus {
/**
* Output only. Timestamp of the last reboot.
*/
lastRebootTime?: string | null;
/**
* Output only. Timestamp of the last update check.
*/
lastUpdateCheckTime?: string | null;
/**
* Output only. Timestamp of the last successful update.
*/
lastUpdateTime?: string | null;
/**
* Output only. New platform version of the os image being downloaded and applied. It is only set when update status is OS_IMAGE_DOWNLOAD_IN_PROGRESS or OS_UPDATE_NEED_REBOOT. Note this could be a dummy "0.0.0.0" for OS_UPDATE_NEED_REBOOT status for some edge cases, e.g. update engine is restarted without a reboot.
*/
newPlatformVersion?: string | null;
/**
* Output only. New requested platform version from the pending updated kiosk app.
*/
newRequestedPlatformVersion?: string | null;
/**
* Output only. Current state of the os update.
*/
updateState?: string | null;
}
/**
* Status data for storage.
*/
export interface Schema$GoogleChromeManagementV1StorageInfo {
/**
* The available space for user data storage in the device in bytes.
*/
availableDiskBytes?: string | null;
/**
* The total space for user data storage in the device in bytes.
*/
totalDiskBytes?: string | null;
/**
* Information for disk volumes
*/
volume?: Schema$GoogleChromeManagementV1StorageInfoDiskVolume[];
}
/**
* Information for disk volumes
*/
export interface Schema$GoogleChromeManagementV1StorageInfoDiskVolume {
/**
* Free storage space in bytes.
*/
storageFreeBytes?: string | null;
/**
* Total storage space in bytes.
*/
storageTotalBytes?: string | null;
/**
* Disk volume id.
*/
volumeId?: string | null;
}
/**
* Status data for storage.
*/
export interface Schema$GoogleChromeManagementV1StorageStatusReport {
/**
* Output only. Reports on disk
*/
disk?: Schema$GoogleChromeManagementV1DiskInfo[];
/**
* Output only. Timestamp of when the sample was collected on device
*/
reportTime?: string | null;
}
/**
* Telemetry data collected from a managed device.
*/
export interface Schema$GoogleChromeManagementV1TelemetryDevice {
/**
* Output only. Information on battery specs for the device.
*/
batteryInfo?: Schema$GoogleChromeManagementV1BatteryInfo[];
/**
* Output only. Battery reports collected periodically.
*/
batteryStatusReport?: Schema$GoogleChromeManagementV1BatteryStatusReport[];
/**
* Output only. Information regarding CPU specs for the device.
*/
cpuInfo?: Schema$GoogleChromeManagementV1CpuInfo[];
/**
* Output only. CPU status reports collected periodically.
*/
cpuStatusReport?: Schema$GoogleChromeManagementV1CpuStatusReport[];
/**
* Output only. Google Workspace Customer whose enterprise enrolled the device.
*/
customer?: string | null;
/**
* Output only. The unique Directory API ID of the device. This value is the same as the Admin Console's Directory API ID in the Chrome OS Devices tab
*/
deviceId?: string | null;
/**
* Output only. Contains information regarding Graphic peripherals for the device.
*/
graphicsInfo?: Schema$GoogleChromeManagementV1GraphicsInfo;
/**
* Output only. Graphics reports collected periodically.
*/
graphicsStatusReport?: Schema$GoogleChromeManagementV1GraphicsStatusReport[];
/**
* Output only. Information regarding memory specs for the device.
*/
memoryInfo?: Schema$GoogleChromeManagementV1MemoryInfo;
/**
* Output only. Memory status reports collected periodically.
*/
memoryStatusReport?: Schema$GoogleChromeManagementV1MemoryStatusReport[];
/**
* Output only. Resource name of the device.
*/
name?: string | null;
/**
* Output only. Network specs collected periodically.
*/
networkStatusReport?: Schema$GoogleChromeManagementV1NetworkStatusReport[];
/**
* Output only. Organization unit ID of the device.
*/
orgUnitId?: string | null;
/**
* Output only. Contains relevant information regarding ChromeOS update status.
*/
osUpdateStatus?: Schema$GoogleChromeManagementV1OsUpdateStatus[];
/**
* Output only. Device serial number. This value is the same as the Admin Console's Serial Number in the Chrome OS Devices tab.
*/
serialNumber?: string | null;
/**
* Output only. Information of storage specs for the device.
*/
storageInfo?: Schema$GoogleChromeManagementV1StorageInfo;
/**
* Output only. Storage reports collected periodically.
*/
storageStatusReport?: Schema$GoogleChromeManagementV1StorageStatusReport[];
}
/**
* The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
*/
export interface Schema$GoogleRpcStatus {
/**
* The status code, which should be an enum value of google.rpc.Code.
*/
code?: number | null;
/**
* A list of messages that carry the error details. There is a common set of message types for APIs to use.
*/
details?: Array<{[key: string]: any}> | null;
/**
* A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
*/
message?: string | null;
}
/**
* Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values * A month and day value, with a zero year, such as an anniversary * A year on its own, with zero month and day values * A year and month value, with a zero day, such as a credit card expiration date Related types are google.type.TimeOfDay and `google.protobuf.Timestamp`.
*/
export interface Schema$GoogleTypeDate {
/**
* Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant.
*/
day?: number | null;
/**
* Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.
*/
month?: number | null;
/**
* Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.
*/
year?: number | null;
}
export class Resource$Customers {
context: APIRequestContext;
apps: Resource$Customers$Apps;
reports: Resource$Customers$Reports;
telemetry: Resource$Customers$Telemetry;
constructor(context: APIRequestContext) {
this.context = context;
this.apps = new Resource$Customers$Apps(this.context);
this.reports = new Resource$Customers$Reports(this.context);
this.telemetry = new Resource$Customers$Telemetry(this.context);
}
}
export class Resource$Customers$Apps {
context: APIRequestContext;
android: Resource$Customers$Apps$Android;
chrome: Resource$Customers$Apps$Chrome;
web: Resource$Customers$Apps$Web;
constructor(context: APIRequestContext) {
this.context = context;
this.android = new Resource$Customers$Apps$Android(this.context);
this.chrome = new Resource$Customers$Apps$Chrome(this.context);
this.web = new Resource$Customers$Apps$Web(this.context);
}
/**
* Generate summary of app installation requests.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/chromemanagement.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const chromemanagement = google.chromemanagement('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [
* 'https://www.googleapis.com/auth/chrome.management.appdetails.readonly',
* ],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await chromemanagement.customers.apps.countChromeAppRequests({
* // Required. Customer id or "my_customer" to use the customer associated to the account making the request.
* customer: 'customers/my-customer',
* // Field used to order results. Supported fields: * request_count * latest_request_time
* orderBy: 'placeholder-value',
* // The ID of the organizational unit.
* orgUnitId: 'placeholder-value',
* // Maximum number of results to return. Maximum and default are 50, anything above will be coerced to 50.
* pageSize: 'placeholder-value',
* // Token to specify the page of the request to be returned.
* pageToken: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "nextPageToken": "my_nextPageToken",
* // "requestedApps": [],
* // "totalSize": 0
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
countChromeAppRequests(
params: Params$Resource$Customers$Apps$Countchromeapprequests,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
countChromeAppRequests(
params?: Params$Resource$Customers$Apps$Countchromeapprequests,
options?: MethodOptions
): GaxiosPromise<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>;
countChromeAppRequests(
params: Params$Resource$Customers$Apps$Countchromeapprequests,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
countChromeAppRequests(
params: Params$Resource$Customers$Apps$Countchromeapprequests,
options:
| MethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>
): void;
countChromeAppRequests(
params: Params$Resource$Customers$Apps$Countchromeapprequests,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>
): void;
countChromeAppRequests(
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>
): void;
countChromeAppRequests(
paramsOrCallback?:
| Params$Resource$Customers$Apps$Countchromeapprequests
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Customers$Apps$Countchromeapprequests;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Customers$Apps$Countchromeapprequests;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://chromemanagement.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl + '/v1/{+customer}/apps:countChromeAppRequests'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['customer'],
pathParams: ['customer'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$GoogleChromeManagementV1CountChromeAppRequestsResponse>(
parameters
);
}
}
}
export interface Params$Resource$Customers$Apps$Countchromeapprequests
extends StandardParameters {
/**
* Required. Customer id or "my_customer" to use the customer associated to the account making the request.
*/
customer?: string;
/**
* Field used to order results. Supported fields: * request_count * latest_request_time
*/
orderBy?: string;
/**
* The ID of the organizational unit.
*/
orgUnitId?: string;
/**
* Maximum number of results to return. Maximum and default are 50, anything above will be coerced to 50.
*/
pageSize?: number;
/**
* Token to specify the page of the request to be returned.
*/
pageToken?: string;
}
export class Resource$Customers$Apps$Android {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Get a specific app for a customer by its resource name.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/chromemanagement.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const chromemanagement = google.chromemanagement('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [
* 'https://www.googleapis.com/auth/chrome.management.appdetails.readonly',
* ],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await chromemanagement.customers.apps.android.get({
* // Required. The app for which details are being queried. Examples: "customers/my_customer/apps/chrome/gmbmikajjgmnabiglmofipeabaddhgne@2.1.2" for the Save to Google Drive Chrome extension version 2.1.2, "customers/my_customer/apps/android/com.google.android.apps.docs" for the Google Drive Android app's latest version.
* name: 'customers/my-customer/apps/android/[^/]+',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "androidAppInfo": {},
* // "appId": "my_appId",
* // "chromeAppInfo": {},
* // "description": "my_description",
* // "detailUri": "my_detailUri",
* // "displayName": "my_displayName",
* // "firstPublishTime": "my_firstPublishTime",
* // "homepageUri": "my_homepageUri",
* // "iconUri": "my_iconUri",
* // "isPaidApp": false,
* // "latestPublishTime": "my_latestPublishTime",
* // "name": "my_name",
* // "privacyPolicyUri": "my_privacyPolicyUri",
* // "publisher": "my_publisher",
* // "reviewNumber": "my_reviewNumber",
* // "reviewRating": {},
* // "revisionId": "my_revisionId",
* // "serviceError": {},
* // "type": "my_type"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
get(
params: Params$Resource$Customers$Apps$Android$Get,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
get(
params?: Params$Resource$Customers$Apps$Android$Get,
options?: MethodOptions
): GaxiosPromise<Schema$GoogleChromeManagementV1AppDetails>;
get(
params: Params$Resource$Customers$Apps$Android$Get,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
get(
params: Params$Resource$Customers$Apps$Android$Get,
options:
| MethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
): void;
get(
params: Params$Resource$Customers$Apps$Android$Get,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
): void;
get(
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
): void;
get(
paramsOrCallback?:
| Params$Resource$Customers$Apps$Android$Get
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$GoogleChromeManagementV1AppDetails>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Customers$Apps$Android$Get;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Customers$Apps$Android$Get;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://chromemanagement.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$GoogleChromeManagementV1AppDetails>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$GoogleChromeManagementV1AppDetails>(
parameters
);
}
}
}
export interface Params$Resource$Customers$Apps$Android$Get
extends StandardParameters {
/**
* Required. The app for which details are being queried. Examples: "customers/my_customer/apps/chrome/gmbmikajjgmnabiglmofipeabaddhgne@2.1.2" for the Save to Google Drive Chrome extension version 2.1.2, "customers/my_customer/apps/android/com.google.android.apps.docs" for the Google Drive Android app's latest version.
*/
name?: string;
}
export class Resource$Customers$Apps$Chrome {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Get a specific app for a customer by its resource name.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/chromemanagement.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const chromemanagement = google.chromemanagement('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [
* 'https://www.googleapis.com/auth/chrome.management.appdetails.readonly',
* ],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await chromemanagement.customers.apps.chrome.get({
* // Required. The app for which details are being queried. Examples: "customers/my_customer/apps/chrome/gmbmikajjgmnabiglmofipeabaddhgne@2.1.2" for the Save to Google Drive Chrome extension version 2.1.2, "customers/my_customer/apps/android/com.google.android.apps.docs" for the Google Drive Android app's latest version.
* name: 'customers/my-customer/apps/chrome/[^/]+',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "androidAppInfo": {},
* // "appId": "my_appId",
* // "chromeAppInfo": {},
* // "description": "my_description",
* // "detailUri": "my_detailUri",
* // "displayName": "my_displayName",
* // "firstPublishTime": "my_firstPublishTime",
* // "homepageUri": "my_homepageUri",
* // "iconUri": "my_iconUri",
* // "isPaidApp": false,
* // "latestPublishTime": "my_latestPublishTime",
* // "name": "my_name",
* // "privacyPolicyUri": "my_privacyPolicyUri",
* // "publisher": "my_publisher",
* // "reviewNumber": "my_reviewNumber",
* // "reviewRating": {},
* // "revisionId": "my_revisionId",
* // "serviceError": {},
* // "type": "my_type"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
get(
params: Params$Resource$Customers$Apps$Chrome$Get,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
get(
params?: Params$Resource$Customers$Apps$Chrome$Get,
options?: MethodOptions
): GaxiosPromise<Schema$GoogleChromeManagementV1AppDetails>;
get(
params: Params$Resource$Customers$Apps$Chrome$Get,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
get(
params: Params$Resource$Customers$Apps$Chrome$Get,
options:
| MethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
): void;
get(
params: Params$Resource$Customers$Apps$Chrome$Get,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
): void;
get(
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
): void;
get(
paramsOrCallback?:
| Params$Resource$Customers$Apps$Chrome$Get
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$GoogleChromeManagementV1AppDetails>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Customers$Apps$Chrome$Get;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Customers$Apps$Chrome$Get;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://chromemanagement.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$GoogleChromeManagementV1AppDetails>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$GoogleChromeManagementV1AppDetails>(
parameters
);
}
}
}
export interface Params$Resource$Customers$Apps$Chrome$Get
extends StandardParameters {
/**
* Required. The app for which details are being queried. Examples: "customers/my_customer/apps/chrome/gmbmikajjgmnabiglmofipeabaddhgne@2.1.2" for the Save to Google Drive Chrome extension version 2.1.2, "customers/my_customer/apps/android/com.google.android.apps.docs" for the Google Drive Android app's latest version.
*/
name?: string;
}
export class Resource$Customers$Apps$Web {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Get a specific app for a customer by its resource name.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/chromemanagement.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const chromemanagement = google.chromemanagement('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [
* 'https://www.googleapis.com/auth/chrome.management.appdetails.readonly',
* ],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await chromemanagement.customers.apps.web.get({
* // Required. The app for which details are being queried. Examples: "customers/my_customer/apps/chrome/gmbmikajjgmnabiglmofipeabaddhgne@2.1.2" for the Save to Google Drive Chrome extension version 2.1.2, "customers/my_customer/apps/android/com.google.android.apps.docs" for the Google Drive Android app's latest version.
* name: 'customers/my-customer/apps/web/[^/]+',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "androidAppInfo": {},
* // "appId": "my_appId",
* // "chromeAppInfo": {},
* // "description": "my_description",
* // "detailUri": "my_detailUri",
* // "displayName": "my_displayName",
* // "firstPublishTime": "my_firstPublishTime",
* // "homepageUri": "my_homepageUri",
* // "iconUri": "my_iconUri",
* // "isPaidApp": false,
* // "latestPublishTime": "my_latestPublishTime",
* // "name": "my_name",
* // "privacyPolicyUri": "my_privacyPolicyUri",
* // "publisher": "my_publisher",
* // "reviewNumber": "my_reviewNumber",
* // "reviewRating": {},
* // "revisionId": "my_revisionId",
* // "serviceError": {},
* // "type": "my_type"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
get(
params: Params$Resource$Customers$Apps$Web$Get,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
get(
params?: Params$Resource$Customers$Apps$Web$Get,
options?: MethodOptions
): GaxiosPromise<Schema$GoogleChromeManagementV1AppDetails>;
get(
params: Params$Resource$Customers$Apps$Web$Get,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
get(
params: Params$Resource$Customers$Apps$Web$Get,
options:
| MethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
): void;
get(
params: Params$Resource$Customers$Apps$Web$Get,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
): void;
get(
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
): void;
get(
paramsOrCallback?:
| Params$Resource$Customers$Apps$Web$Get
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$GoogleChromeManagementV1AppDetails>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$GoogleChromeManagementV1AppDetails>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Customers$Apps$Web$Get;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Customers$Apps$Web$Get;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://chromemanagement.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$GoogleChromeManagementV1AppDetails>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$GoogleChromeManagementV1AppDetails>(
parameters
);
}
}
}
export interface Params$Resource$Customers$Apps$Web$Get
extends StandardParameters {
/**
* Required. The app for which details are being queried. Examples: "customers/my_customer/apps/chrome/gmbmikajjgmnabiglmofipeabaddhgne@2.1.2" for the Save to Google Drive Chrome extension version 2.1.2, "customers/my_customer/apps/android/com.google.android.apps.docs" for the Google Drive Android app's latest version.
*/
name?: string;
}
export class Resource$Customers$Reports {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Generate report of installed Chrome versions.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/chromemanagement.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const chromemanagement = google.chromemanagement('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [
* 'https://www.googleapis.com/auth/chrome.management.reports.readonly',
* ],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await chromemanagement.customers.reports.countChromeVersions({
* // Required. Customer id or "my_customer" to use the customer associated to the account making the request.
* customer: 'customers/my-customer',
* // Query string to filter results, AND-separated fields in EBNF syntax. Note: OR operations are not supported in this filter. Supported filter fields: * last_active_date
* filter: 'placeholder-value',
* // The ID of the organizational unit.
* orgUnitId: 'placeholder-value',
* // Maximum number of results to return. Maximum and default are 100.
* pageSize: 'placeholder-value',
* // Token to specify the page of the request to be returned.
* pageToken: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "browserVersions": [],
* // "nextPageToken": "my_nextPageToken",
* // "totalSize": 0
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
countChromeVersions(
params: Params$Resource$Customers$Reports$Countchromeversions,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
countChromeVersions(
params?: Params$Resource$Customers$Reports$Countchromeversions,
options?: MethodOptions
): GaxiosPromise<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>;
countChromeVersions(
params: Params$Resource$Customers$Reports$Countchromeversions,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
countChromeVersions(
params: Params$Resource$Customers$Reports$Countchromeversions,
options:
| MethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>
): void;
countChromeVersions(
params: Params$Resource$Customers$Reports$Countchromeversions,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>
): void;
countChromeVersions(
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>
): void;
countChromeVersions(
paramsOrCallback?:
| Params$Resource$Customers$Reports$Countchromeversions
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Customers$Reports$Countchromeversions;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Customers$Reports$Countchromeversions;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://chromemanagement.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl + '/v1/{+customer}/reports:countChromeVersions'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['customer'],
pathParams: ['customer'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$GoogleChromeManagementV1CountChromeVersionsResponse>(
parameters
);
}
}
/**
* Generate report of app installations.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/chromemanagement.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const chromemanagement = google.chromemanagement('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [
* 'https://www.googleapis.com/auth/chrome.management.reports.readonly',
* ],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await chromemanagement.customers.reports.countInstalledApps({
* // Required. Customer id or "my_customer" to use the customer associated to the account making the request.
* customer: 'customers/my-customer',
* // Query string to filter results, AND-separated fields in EBNF syntax. Note: OR operations are not supported in this filter. Supported filter fields: * app_name * app_type * install_type * number_of_permissions * total_install_count * latest_profile_active_date * permission_name
* filter: 'placeholder-value',
* // Field used to order results. Supported order by fields: * app_name * app_type * install_type * number_of_permissions * total_install_count
* orderBy: 'placeholder-value',
* // The ID of the organizational unit.
* orgUnitId: 'placeholder-value',
* // Maximum number of results to return. Maximum and default are 100.
* pageSize: 'placeholder-value',
* // Token to specify the page of the request to be returned.
* pageToken: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "installedApps": [],
* // "nextPageToken": "my_nextPageToken",
* // "totalSize": 0
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
countInstalledApps(
params: Params$Resource$Customers$Reports$Countinstalledapps,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
countInstalledApps(
params?: Params$Resource$Customers$Reports$Countinstalledapps,
options?: MethodOptions
): GaxiosPromise<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>;
countInstalledApps(
params: Params$Resource$Customers$Reports$Countinstalledapps,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
countInstalledApps(
params: Params$Resource$Customers$Reports$Countinstalledapps,
options:
| MethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>
): void;
countInstalledApps(
params: Params$Resource$Customers$Reports$Countinstalledapps,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>
): void;
countInstalledApps(
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>
): void;
countInstalledApps(
paramsOrCallback?:
| Params$Resource$Customers$Reports$Countinstalledapps
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Customers$Reports$Countinstalledapps;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Customers$Reports$Countinstalledapps;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://chromemanagement.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl + '/v1/{+customer}/reports:countInstalledApps'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['customer'],
pathParams: ['customer'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$GoogleChromeManagementV1CountInstalledAppsResponse>(
parameters
);
}
}
/**
* Generate report of devices that have a specified app installed.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/chromemanagement.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const chromemanagement = google.chromemanagement('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [
* 'https://www.googleapis.com/auth/chrome.management.reports.readonly',
* ],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await chromemanagement.customers.reports.findInstalledAppDevices({
* // Unique identifier of the app. For Chrome apps and extensions, the 32-character id (e.g. ehoadneljpdggcbbknedodolkkjodefl). For Android apps, the package name (e.g. com.evernote).
* appId: 'placeholder-value',
* // Type of the app.
* appType: 'placeholder-value',
* // Required. Customer id or "my_customer" to use the customer associated to the account making the request.
* customer: 'customers/my-customer',
* // Query string to filter results, AND-separated fields in EBNF syntax. Note: OR operations are not supported in this filter. Supported filter fields: * last_active_date
* filter: 'placeholder-value',
* // Field used to order results. Supported order by fields: * machine * device_id
* orderBy: 'placeholder-value',
* // The ID of the organizational unit.
* orgUnitId: 'placeholder-value',
* // Maximum number of results to return. Maximum and default are 100.
* pageSize: 'placeholder-value',
* // Token to specify the page of the request to be returned.
* pageToken: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "devices": [],
* // "nextPageToken": "my_nextPageToken",
* // "totalSize": 0
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
findInstalledAppDevices(
params: Params$Resource$Customers$Reports$Findinstalledappdevices,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
findInstalledAppDevices(
params?: Params$Resource$Customers$Reports$Findinstalledappdevices,
options?: MethodOptions
): GaxiosPromise<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>;
findInstalledAppDevices(
params: Params$Resource$Customers$Reports$Findinstalledappdevices,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
findInstalledAppDevices(
params: Params$Resource$Customers$Reports$Findinstalledappdevices,
options:
| MethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>
): void;
findInstalledAppDevices(
params: Params$Resource$Customers$Reports$Findinstalledappdevices,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>
): void;
findInstalledAppDevices(
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>
): void;
findInstalledAppDevices(
paramsOrCallback?:
| Params$Resource$Customers$Reports$Findinstalledappdevices
| BodyResponseCallback<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Customers$Reports$Findinstalledappdevices;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params =
{} as Params$Resource$Customers$Reports$Findinstalledappdevices;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://chromemanagement.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl + '/v1/{+customer}/reports:findInstalledAppDevices'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['customer'],
pathParams: ['customer'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$GoogleChromeManagementV1FindInstalledAppDevicesResponse>(
parameters
);
}
}
}
export interface Params$Resource$Customers$Reports$Countchromeversions
extends StandardParameters {
/**
* Required. Customer id or "my_customer" to use the customer associated to the account making the request.
*/
customer?: string;
/**
* Query string to filter results, AND-separated fields in EBNF syntax. Note: OR operations are not supported in this filter. Supported filter fields: * last_active_date
*/
filter?: string;
/**
* The ID of the organizational unit.
*/
orgUnitId?: string;
/**
* Maximum number of results to return. Maximum and default are 100.
*/
pageSize?: number;
/**
* Token to specify the page of the request to be returned.
*/
pageToken?: string;
}
export interface Params$Resource$Customers$Reports$Countinstalledapps
extends StandardParameters {
/**
* Required. Customer id or "my_customer" to use the customer associated to the account making the request.
*/
customer?: string;
/**
* Query string to filter results, AND-separated fields in EBNF syntax. Note: OR operations are not supported in this filter. Supported filter fields: * app_name * app_type * install_type * number_of_permissions * total_install_count * latest_profile_active_date * permission_name
*/
filter?: string;
/**
* Field used to order results. Supported order by fields: * app_name * app_type * install_type * number_of_permissions * total_install_count
*/
orderBy?: string;
/**
* The ID of the organizational unit.
*/
orgUnitId?: string;
/**
* Maximum number of results to return. Maximum and default are 100.
*/
pageSize?: number;
/**
* Token to specify the page of the request to be returned.
*/
pageToken?: string;
}
export interface Params$Resource$Customers$Reports$Findinstalledappdevices
extends StandardParameters {
/**
* Unique identifier of the app. For Chrome apps and extensions, the 32-character id (e.g. ehoadneljpdggcbbknedodolkkjodefl). For Android apps, the package name (e.g. com.evernote).
*/
appId?: string;
/**
* Type of the app.
*/
appType?: string;
/**
* Required. Customer id or "my_customer" to use the customer associated to the account making the request.
*/
customer?: string;
/**
* Query string to filter results, AND-separated fields in EBNF syntax. Note: OR operations are not supported in this filter. Supported filter fields: * last_active_date
*/
filter?: string;
/**
* Field used to order results. Supported order by fields: * machine * device_id
*/
orderBy?: string;
/**
* The ID of the organizational unit.
*/
orgUnitId?: string;
/**
* Maximum number of results to return. Maximum and default are 100.
*/
pageSize?: number;
/**
* Token to specify the page of the request to be returned.
*/
pageToken?: string;
}
export class Resource$Customers$Telemetry {
context: APIRequestContext;
devices: Resource$Customers$Telemetry$Devices;
constructor(context: APIRequestContext) {
this.context = context;
this.devices = new Resource$Customers$Telemetry$Devices(this.context);
}
}
export class Resource$Customers$Telemetry$Devices {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* List all telemetry devices.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/chromemanagement.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const chromemanagement = google.chromemanagement('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [
* 'https://www.googleapis.com/auth/chrome.management.telemetry.readonly',
* ],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await chromemanagement.customers.telemetry.devices.list({
* // Optional. Only include resources that match the filter. Supported filter fields: - org_unit_id - serial_number
* filter: 'placeholder-value',
* // Maximum number of results to return. Maximum and default are 100.
* pageSize: 'placeholder-value',
* // Token to specify next page in the list.
* pageToken: 'placeholder-value',
* // Required. Customer id or "my_customer" to use the customer associated to the account making the request.
* parent: 'customers/my-customer',
* // Required. Read mask to specify which fields to return.
* readMask: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "devices": [],
* // "nextPageToken": "my_nextPageToken"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
list(
params: Params$Resource$Customers$Telemetry$Devices$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Customers$Telemetry$Devices$List,
options?: MethodOptions
): GaxiosPromise<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>;
list(
params: Params$Resource$Customers$Telemetry$Devices$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Customers$Telemetry$Devices$List,
options:
| MethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>
): void;
list(
params: Params$Resource$Customers$Telemetry$Devices$List,
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>
): void;
list(
callback: BodyResponseCallback<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>
): void;
list(
paramsOrCallback?:
| Params$Resource$Customers$Telemetry$Devices$List
| BodyResponseCallback<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Customers$Telemetry$Devices$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Customers$Telemetry$Devices$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://chromemanagement.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+parent}/telemetry/devices').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$GoogleChromeManagementV1ListTelemetryDevicesResponse>(
parameters
);
}
}
}
export interface Params$Resource$Customers$Telemetry$Devices$List
extends StandardParameters {
/**
* Optional. Only include resources that match the filter. Supported filter fields: - org_unit_id - serial_number
*/
filter?: string;
/**
* Maximum number of results to return. Maximum and default are 100.
*/
pageSize?: number;
/**
* Token to specify next page in the list.
*/
pageToken?: string;
/**
* Required. Customer id or "my_customer" to use the customer associated to the account making the request.
*/
parent?: string;
/**
* Required. Read mask to specify which fields to return.
*/
readMask?: string;
}
} | the_stack |
if(!window['keyman']['ui']['name']) {
/********************************/
/* */
/* Button User Interface Code */
/* */
/********************************/
/**
* Do not enclose in an anonymous function, as the compiler may create
* global scope variables to replace true, false, null, whcih can then collide
* with other variables.
* Instead, use the --output-wrapper command during optimization, which will
* add the anonymous function to enclose all code, including those optimized
* variables which would otherwise have global scope.
**/
try {
// Declare KeymanWeb, OnScreen keyboard and Util objects
var keymanweb=window['keyman'],
util=keymanweb['util'],dbg=keymanweb['debug'];
// Disable UI for touch devices
if(util['isTouchDevice']()) throw '';
// User interface global and variables
keymanweb['ui'] = {};
var ui=keymanweb['ui'];
ui['name'] = 'button';
ui.init = false;
ui.KeyboardSelector = null;
ui.KeymanWeb_DefaultKeyboardHelp='<span style="font-size:7.5pt">KeymanWeb is not running. Choose a keyboard from the list</span>';
ui._KeymanWeb_KbdList = null;
ui._KMWSel = null;
ui._IsHelpVisible = false;
ui._DefaultKeyboardID = '';
ui.updateTimer = null;
ui.updateList = true;
/**
* Highlight the currently active keyboard in the list of keyboards
**/
ui._ShowSelected = function()
{
var _rv,kbd=keymanweb['getActiveKeyboard'](),lgc=keymanweb['getActiveLanguage'](),
kList = ui._KeymanWeb_KbdList.childNodes,
_r = /^KMWSel_(.*)\$(.*)$/;
for(var i=1; i<kList.length; i++)
kList[i].childNodes[0].className = '';
for(var i=2; i<kList.length; i++)
{
_rv = _r.exec(kList[i].childNodes[0].id);
if(_rv && (_rv[1] == kbd) && (_rv[2] == lgc)) break;
}
if(i >= kList.length) i=1;
kList[i].childNodes[0].className = 'selected';
}
/**
* Select keyboard by id
*
* @param {Event} _id keyboard selection event
* @return {boolean}
*/
ui._SelectKeyboard = function(_id)
{
if(typeof(_id) == 'object')
{
var t=null;
if((typeof(_id.target) != 'undefined') && _id.target) t=_id.target;
else if((typeof(_id.srcElement) != 'undefined') && _id.srcElement) t=_id.srcElement;
if(t) _id=t.id;
}
var _r=/^KMWSel_(.*)\$(.*)$/;
var _rv=_r.exec(_id),_lgc='',_name='';
if(_rv !== null)
{
_name = _rv[1].split('$')[0]; //new code
_lgc = _id.split('$')[1];
if(ui._KMWSel != null) ui._KMWSel.className = '';
var _k = document.getElementById(_id);
if(_k) _k.className='selected';
ui._KMWSel = _k;
keymanweb['setActiveKeyboard'](_name,_lgc);
}
else
_name=null;
keymanweb['focusLastActiveElement']();
let osk = keymanweb.osk;
if(osk && osk['isEnabled']()) osk['show'](true);
ui._ShowKeyboardButton(_name);
return false;
}
/**
* Set KMW UI activation state on mouse click
*
* @param {Event} e event
*/
ui._SelectorMouseDown = function(e)
{
var x=keymanweb['getLastActiveElement']();
// Set the focus to an input field, to get correct OSK display behaviour
if(!x) ui._FocusFirstInput(); else keymanweb['focusLastActiveElement']();
if(keymanweb['activatingUI']) keymanweb['activatingUI'](1);
}
/**
* Set focus on mouse up
*
* @param {Event} e event
*/
ui._SelectorMouseUp = function(e)
{
var x=keymanweb['getLastActiveElement']();
// Set the focus to an input field, to get correct OSK display behaviour
if(!x) ui._FocusFirstInput(); else keymanweb['focusLastActiveElement']();
}
/**
* Set KMW UI activation state on mouse over
*
* @param {Event} e event
*/
ui._SelectorMouseOver = function(e)
{
// highlight the currently active keyboard
ui._ShowSelected();
if(keymanweb['activatingUI']) keymanweb['activatingUI'](1);
document.getElementById("kmwico_li").className="sfhover";
// Conditionally display keyboard button
ui._ShowKeyboardButton();
}
/**
* Sets the focus to the first input or textarea found on the current page
* to ensure consistent keyboard selection and OSK display behaviour
*/
ui._FocusFirstInput = function()
{
var i,ip=null,tp=null,
iList=document.getElementsByTagName("input"),
tList=document.getElementsByTagName("textarea");
for(i=0; i<iList.length; i++)
if(iList[i].type == 'text') break;
if(i < iList.length) ip=iList[i];
if(tList.length > 0) tp = tList[0];
if((!ip) && (!tp))
return;
else if(ip && !tp)
ip.focus();
else if(tp && !ip)
tp.focus();
else if(ip.offsetTop < tp.offsetTop)
ip.focus();
else if(ip.offsetTop > tp.offsetTop)
tp.focus();
else if(ip.offsetLeft < tp.offsetLeft)
ip.focus();
else
tp.focus();
}
/**
* Clear KMW UI activation state on mouse out
*
* @param {Event} e event
*/
ui._SelectorMouseOut = function(e)
{
if(keymanweb['activatingUI']) keymanweb['activatingUI'](0);
document.getElementById("kmwico_li").className="sfunhover";
}
/**
* Disable the button to show/hide the OSK if no active keyboard or active keyboard is CJK (user cannot hide)
*
* @param {?string=} _name current keyboard name
*/
ui._ShowKeyboardButton = function(_name)
{
var kbdName = keymanweb['getActiveKeyboard'](), kbdId=document.getElementById("KMW_Keyboard");
if(arguments.length > 0) kbdName = _name;
if(kbdId)
{
if((kbdName == '') || keymanweb['isCJK']())
{
kbdId.className='kmw_disabled';
}
else
{
let osk = keymanweb.osk;
kbdId.className = osk && osk['isEnabled']() ? 'kmw_show' : 'kmw_hide';
}
}
}
ui.registerEvents = function() {
let osk = keymanweb.osk;
if(!osk) {
return;
}
/**
* UI Functions called by KeymanWeb or OSK
*/
osk['addEventListener']('show', function(oskPosition) {
var t=keymanweb['getLastActiveElement']();
if(t)
{
if(!oskPosition['userLocated'])
{
oskPosition['x'] = util['getAbsoluteX'](t);
oskPosition['y'] = util['getAbsoluteY'](t)+t.offsetHeight;
}
}
ui._ShowKeyboardButton();
return oskPosition;
});
/* TODO: why is this still needed??? Does it actually do anything?? */
osk['addEventListener']('hide', function(hiddenByUser) {
if((arguments.length > 0) && hiddenByUser)
{
var _a = document.getElementById('KMW_Keyboard');
if(_a) _a.className = 'kmw_hide';
}
});
}
/**
* Show or hide the OSK (always visible for CJK keyboards)
*
* @param {Object} _anchor anchor element (?)
* @return {boolean}
**/
ui._ShowKeymanWebKeyboard = function(_anchor)
{
var kbdId=document.getElementById("KMW_Keyboard");
let osk = keymanweb.osk;
if((kbdId.className!='kmw_disabled') && osk && osk['show'])
{
if(osk['isEnabled']()) osk['hide'](); else osk['show'](true);
}
if(window.event) window.event.returnValue=false;
keymanweb['focusLastActiveElement']();
return false;
}
/**
* Initialize Button User Interface
**/
ui['initialize'] = ui.Initialize = function() {
//Never initialize UI before KMW (parameters will be undefined)
if(!keymanweb['initialized'])
{
window.setTimeout(ui.Initialize,250); return;
}
if(ui.init || util['isTouchDevice']()) return;
ui.init = true;
util['addStyleSheet'](ui._Appearance);
ui._KeymanWeb_KbdList = util['createElement']('ul');
ui._KeymanWeb_KbdList.id = 'KeymanWeb_KbdList';
var _elem = document.getElementById('KeymanWebControl');
if(!_elem)
{
var _elems = document.getElementsByTagName('div');
for(var _i = 0; _i < _elems.length; _i++)
{
if(_elems[_i].className == 'KeymanWebControl')
{
_elem = _elems[_i]; break;
}
}
}
// Insert as first child of body if not defined by user
if(!_elem && (document.body != null))
{
_elem=document.createElement('DIV');
_elem.id='KeymanWebControl';
document.body.insertBefore(_elem,document.body.firstChild);
ui._insertedElem = _elem;
}
var imgPath=util['getOption']('resources')+'ui/button/';
if(_elem)
{
// Append another DIV to follow the main control with clear:both to prevent selection over entire width of window
var dx=document.createElement('DIV'),ds=dx.style;
ds.clear='both';
_elem.parentNode.insertBefore(dx,_elem.nextSibling);
var _btn=util['createElement']('img'), _ul=util['createElement']('ul'),_li0=util['createElement']('li');
_btn.id = 'kmwico_a';
_btn.src = imgPath+'kmw_button.gif';
_btn.onclick = function(){return false;} //may want to use this in iOS *****
_li0.appendChild(_btn);
_li0.id = 'kmwico_li';
_ul.appendChild(_li0);
_ul.id = 'kmwico';
_ul.style.display = 'block';
_elem.appendChild(_ul);
}
// Do not define any UI behaviour if no controller element can be found
else return;
if(!keymanweb['iOS'])
{
var _li = util['createElement']('li');
var _a = util['createElement']('a');
var _img = util['createElement']('img');
_img.src = imgPath+'kbdicon.gif';
_a.appendChild(_img);
var _txt1 = document.createTextNode(' Hide Keyboard');
var _txt2 = document.createTextNode(' Show Keyboard');
var _sp1 = util['createElement']('span');
_sp1.id = 'KMW_KbdVisibleMsg';
_sp1.appendChild(_txt1);
_a.appendChild(_sp1);
var _sp2 = util['createElement']('span');
_sp2.id = 'KMW_KbdHiddenMsg';
_sp2.appendChild(_txt2);
_a.appendChild(_sp2);
_a.onmousedown = ui._ShowKeymanWebKeyboard;
_a.href = '#';
_a.id = 'KMW_Keyboard';
_li.id = 'KMW_ButtonUI_KbdIcon';
_li.appendChild(_a);
ui._KMWSel = _a;
ui._KeymanWeb_KbdList.appendChild(_li);
}
var _li1 = util['createElement']('li');
_li1.id = 'KMW_ButtonUI_KbdList';
var _a1 = util['createElement']('a');
_a1.appendChild(document.createTextNode('(System keyboard)'));
_a1.onclick = ui._SelectKeyboard;
_a1.href = '#';
_a1.id='KMWSel_$';
_a1.className='selected';
_li1.appendChild(_a1);
ui._KMWSel = _a1;
ui._KeymanWeb_KbdList.appendChild(_li1);
var _kbds = keymanweb['getKeyboards'](), _added = [];
ui.updateKeyboardList();
document.getElementById('kmwico_li').appendChild(ui._KeymanWeb_KbdList);
var _sfEl = document.getElementById("kmwico_li");
util['attachDOMEvent'](_sfEl,'mousedown',ui._SelectorMouseDown);
util['attachDOMEvent'](_sfEl,'mouseover',ui._SelectorMouseOver);
util['attachDOMEvent'](_sfEl,'mouseout',ui._SelectorMouseOut);
util['attachDOMEvent'](_sfEl,'mouseup',ui._SelectorMouseUp);
ui.registerEvents();
keymanweb['focusLastActiveElement'](); //TODO: this needs to be extended - if no element is active, try and identify an enabled input element
}
ui.shutdown = function() {
var root = ui._insertedElem;
if(root) {
root.parentNode.removeChild(root);
}
}
/**
* Keyboard registration event handler
*
* Set a timer to update the UI keyboard list on timeout after each keyboard is registered,
* thus updating only once when only if multiple keyboards are registered together
*/
keymanweb['addEventListener']('keyboardregistered',
function(p)
{
ui.updateList = true;
if(ui.updateTimer) clearTimeout(ui.updateTimer);
ui.updateTimer = setTimeout(ui.updateKeyboardList,20);
});
/**
* Update the entire menu when keyboards are registered or deregistered
**/
ui.updateKeyboardList = function()
{
ui.updateList = false;
if(!ui.init) return;
// Clear existing list first (first two nodes must be preserved)
for(var i:number=ui._KeymanWeb_KbdList.childNodes.length; i>2; i--)
ui._KeymanWeb_KbdList.removeChild(ui._KeymanWeb_KbdList.childNodes[i-1]);
var kbds=keymanweb['getKeyboards']();
if(kbds.length > 0)
{
for(var i:number=0; i<kbds.length; i++)
ui.registerKeyboard(kbds[i]['InternalName'],kbds[i]['LanguageName'],kbds[i]['Name'],kbds[i]['LanguageCode'],kbds[i]['RegionCode']);
}
}
/**
* As each keyboard stub is registered, append it to the list
*
* @param {string} Lki internal name
* @param {string} Lkl language name
* @param {string} Lkn keyboard name
* @param {string} Lklc language code
* @param {string} Lkrc region code
**/
ui.registerKeyboard = function(Lki,Lkl,Lkn,Lklc,Lkrc)
{
var _li2 = util['createElement']('li'),
_a2 = util['createElement']('a'),
_t = Lkn.replace(/\s?keyboard/i,'');
if(Lkl)
{
var lg=Lkl.split(',')[0];
if(Lkn.search(lg) == -1)
_t = lg+' ('+_t+')';
}
if(_t.length > 26) _t=_t.substr(0,24)+'\u2026';
_a2.appendChild(document.createTextNode(_t));
_a2.onclick = ui._SelectKeyboard;
_a2.href = '#';
_a2.id='KMWSel_'+Lki+'$'+Lklc;
_li2.appendChild(_a2);
ui._KeymanWeb_KbdList.appendChild(_li2);
}
// Define appearance of this interface
ui._Appearance =
"#kmwico, #kmwkbd {"+
"vertical-align: middle;"+
"} "+
"#KeymanWebControl {float:left;} "+
"#KeymanWebControl * "+
"{"+
"letter-spacing: 0px !important;"+
"line-height: 1li !important;"+
"white-space: nowrap !important;"+
"} "+
"#KeymanWebControl #kmwico img {"+
"vertical-align: top;"+
"padding: 0;"+
"margin: 0;"+
"border: none;"+
"} "+
"#KeymanWebControl #kmwico, #kmwico ul {"+
"padding: 0;"+
"margin: 0;"+
"list-style: none;"+
"} "+
"#KeymanWebControl #kmwico_a {"+
"display: block;"+
//"border: none !important;"+
"width: 22px; height: 23px; "+ /* sizes needed for kmw_button.gif */
"} "+
"#KeymanWebControl #kmwico li { "+
"text-align: left;"+
"} "+
"#KeymanWebControl #kmwico li ul {"+
"display: block;"+
"position: absolute;"+
"left: -5999px;"+
"border: solid 2px #ad4a28;"+
"background: white;"+
"border-radius: 4px;"+
"box-shadow: 4px 4px 2px #666;"+
"z-index: 10011;"+ /* above the osk */
"} "+
"#KeymanWebControl #kmwico li.sfunhover ul {"+
"display: none; left: -5999px;"+
"} "+
"#KeymanWebControl #kmwico li:hover ul, #kmwico li.sfhover ul {"+
"display: block;"+
"left: auto;"+
"} "+
"#KeymanWebControl #kmwico ul li {"+
"float: none;"+
"padding: 0 !important;"+
"margin: 0 !important;"+
"width: 136px !important;"+
"} "+
"#KeymanWebControl #KMW_LanguageName {"+
"font-weight: bold;"+
"} "+
"#KeymanWebControl #kmwico ul li a, #kmwico ul li a:visited {"+
"display: block;"+
"padding: 2px 4px !important;"+
"border: none !important;"+
// "width: auto;"+
"color: #404040;"+
"font-family: Tahoma,Verdana,Arial,sans-serif;"+
"font-size: 8pt;"+
"text-decoration: none;"+
"} "+
"#KeymanWebControl #kmwico ul li a.selected {"+
"font-weight: bold;"+
"color: black;"+
"} "+
"#KeymanWebControl #kmwico ul li a:hover {"+
"color: white;"+
"background-color: #ad4a28;"+
"} "+
"#KeymanWebControl #kmwico ul li a.kmw_disabled, #KeymanWebControl #kmwico ul li a.kmw_disabled:hover {"+
"color: #c0c0c0; cursor: default;"+
"background-color: white;"+
"} "+
"#KeymanWebControl #kmwico ul li a.kmw_show span#KMW_KbdHiddenMsg, #KeymanWebControl #kmwico ul li a.kmw_disabled span#KMW_KbdVisibleMsg {"+
"display: none;"+
"} "+
"#KeymanWebControl #kmwico ul li a.kmw_show span#KMW_KbdVisibleMsg {"+
"display: inline;"+
"} "+
"#KeymanWebControl #kmwico ul li a.kmw_hide span#KMW_KbdHiddenMsg {"+
"display: inline;"+
"} "+
"#KeymanWebControl #kmwico ul li a.kmw_hide span#KMW_KbdVisibleMsg {"+
"display: none;"+
"} "+
"#KeymanWebControl #kmwico ul li#KMW_ButtonUI_KbdIcon {"+
"border-bottom: solid 1px #ad4a28;"+
"} ";
// Initialize after KMW is fully initialized, if UI already loaded
keymanweb['addEventListener']('loaduserinterface',ui.Initialize);
// but also call initialization when script loaded, which is after KMW initialization for asynchronous script loading
ui.Initialize();
} catch(err){}
} | the_stack |
import { SimpleUser, SimpleUserDelegate, SimpleUserOptions } from "../src/platform/web";
import { nameAlice, nameBob, uriAlice, uriBob, webSocketServerAlice, webSocketServerBob } from "./demo-users";
import { getButton, getInput, getVideo } from "./demo-utils";
const connectAlice = getButton("connectAlice");
const connectBob = getButton("connectBob");
const disconnectAlice = getButton("disconnectAlice");
const disconnectBob = getButton("disconnectBob");
const registerAlice = getButton("registerAlice");
const registerBob = getButton("registerBob");
const unregisterAlice = getButton("unregisterAlice");
const unregisterBob = getButton("unregisterBob");
const beginAlice = getButton("beginAlice");
const beginBob = getButton("beginBob");
const endAlice = getButton("endAlice");
const endBob = getButton("endBob");
const holdAlice = getInput("holdAlice");
const holdBob = getInput("holdBob");
const muteAlice = getInput("muteAlice");
const muteBob = getInput("muteBob");
const videoLocalAlice = getVideo("videoLocalAlice");
const videoLocalBob = getVideo("videoLocalBob");
const videoRemoteAlice = getVideo("videoRemoteAlice");
const videoRemoteBob = getVideo("videoRemoteBob");
// New SimpleUser for Alice
const alice = buildUser(
webSocketServerAlice,
uriAlice,
nameAlice,
uriBob,
nameBob,
connectAlice,
disconnectAlice,
registerAlice,
unregisterAlice,
beginAlice,
endAlice,
holdAlice,
muteAlice,
videoLocalAlice,
videoRemoteAlice
);
// New SimpleUser for Bob
const bob = buildUser(
webSocketServerBob,
uriBob,
nameBob,
uriAlice,
nameAlice,
connectBob,
disconnectBob,
registerBob,
unregisterBob,
beginBob,
endBob,
holdBob,
muteBob,
videoLocalBob,
videoRemoteBob
);
if (!alice || !bob) {
console.error("Something went wrong");
}
function buildUser(
webSocketServer: string,
aor: string,
displayName: string,
targetAOR: string,
targetName: string,
connectButton: HTMLButtonElement,
disconnectButton: HTMLButtonElement,
registerButton: HTMLButtonElement,
unregisterButton: HTMLButtonElement,
beginButton: HTMLButtonElement,
endButton: HTMLButtonElement,
holdCheckbox: HTMLInputElement,
muteCheckbox: HTMLInputElement,
videoLocalElement: HTMLVideoElement,
videoRemoteElement: HTMLVideoElement
): SimpleUser {
console.log(`Creating "${name}" <${aor}>...`);
// SimpleUser options
const options: SimpleUserOptions = {
aor,
media: {
constraints: {
// This demo is making "video only" calls
audio: false,
video: true
},
local: {
video: videoLocalElement
},
remote: {
video: videoRemoteElement
}
},
userAgentOptions: {
// logLevel: "debug",
displayName
}
};
// Create SimpleUser
const user = new SimpleUser(webSocketServer, options);
// SimpleUser delegate
const delegate: SimpleUserDelegate = {
onCallAnswered: makeCallAnsweredCallback(user, holdCheckbox, muteCheckbox),
onCallCreated: makeCallCreatedCallback(user, beginButton, endButton, holdCheckbox, muteCheckbox),
onCallReceived: makeCallReceivedCallback(user),
onCallHangup: makeCallHangupCallback(user, beginButton, endButton, holdCheckbox, muteCheckbox),
onCallHold: makeCallHoldCallback(user, holdCheckbox),
onRegistered: makeRegisteredCallback(user, registerButton, unregisterButton),
onUnregistered: makeUnregisteredCallback(user, registerButton, unregisterButton),
onServerConnect: makeServerConnectCallback(user, connectButton, disconnectButton, registerButton, beginButton),
onServerDisconnect: makeServerDisconnectCallback(user, connectButton, disconnectButton, registerButton, beginButton)
};
user.delegate = delegate;
// Setup connect button click listeners
connectButton.addEventListener(
"click",
makeConnectButtonClickListener(user, connectButton, disconnectButton, registerButton, beginButton)
);
// Setup disconnect button click listeners
disconnectButton.addEventListener(
"click",
makeDisconnectButtonClickListener(user, connectButton, disconnectButton, registerButton, beginButton)
);
// Setup register button click listeners
registerButton.addEventListener("click", makeRegisterButtonClickListener(user, registerButton));
// Setup unregister button click listeners
unregisterButton.addEventListener("click", makeUnregisterButtonClickListener(user, unregisterButton));
// Setup begin button click listeners
beginButton.addEventListener("click", makeBeginButtonClickListener(user, targetAOR, targetName));
// Setup end button click listeners
endButton.addEventListener("click", makeEndButtonClickListener(user));
// Setup hold change listeners
holdCheckbox.addEventListener("change", makeHoldCheckboxClickListener(user, holdCheckbox));
// Setup mute change listeners
muteCheckbox.addEventListener("change", makeMuteCheckboxClickListener(user, muteCheckbox));
// Enable connect button
connectButton.disabled = false;
return user;
}
// Helper function to create call anaswered callback
function makeCallAnsweredCallback(
user: SimpleUser,
holdCheckbox: HTMLInputElement,
muteCheckbox: HTMLInputElement
): () => void {
return () => {
console.log(`[${user.id}] call answered`);
holdCheckboxDisabled(false, holdCheckbox);
muteCheckboxDisabled(false, muteCheckbox);
};
}
// Helper function to create call received callback
function makeCallReceivedCallback(user: SimpleUser): () => void {
return () => {
console.log(`[${user.id}] call received`);
user.answer().catch((error: Error) => {
console.error(`[${user.id}] failed to answer call`);
console.error(error);
alert(`[${user.id}] Failed to answer call.\n` + error);
});
};
}
// Helper function to create call created callback
function makeCallCreatedCallback(
user: SimpleUser,
beginButton: HTMLButtonElement,
endButton: HTMLButtonElement,
holdCheckbox: HTMLInputElement,
muteCheckbox: HTMLInputElement
): () => void {
return () => {
console.log(`[${user.id}] call created`);
beginButton.disabled = true;
endButton.disabled = false;
holdCheckboxDisabled(true, holdCheckbox);
muteCheckboxDisabled(true, muteCheckbox);
};
}
// Helper function to create call hangup callback
function makeCallHangupCallback(
user: SimpleUser,
beginButton: HTMLButtonElement,
endButton: HTMLButtonElement,
holdCheckbox: HTMLInputElement,
muteCheckbox: HTMLInputElement
): () => void {
return () => {
console.log(`[${user.id}] call hangup`);
beginButton.disabled = !user.isConnected();
endButton.disabled = true;
holdCheckboxDisabled(true, holdCheckbox);
muteCheckboxDisabled(true, muteCheckbox);
};
}
// Helper function to create call anaswered callback
function makeCallHoldCallback(user: SimpleUser, holdCheckbox: HTMLInputElement): (held: boolean) => void {
return (held: boolean) => {
console.log(`[${user.id}] call hold ${held}`);
holdCheckbox.checked = held;
};
}
// Helper function to create registered callback
function makeRegisteredCallback(
user: SimpleUser,
registerButton: HTMLButtonElement,
unregisterButton: HTMLButtonElement
): () => void {
return () => {
console.log(`[${user.id}] registered`);
registerButton.disabled = true;
unregisterButton.disabled = false;
};
}
// Helper function to create unregistered callback
function makeUnregisteredCallback(
user: SimpleUser,
registerButton: HTMLButtonElement,
unregisterButton: HTMLButtonElement
): () => void {
return () => {
console.log(`[${user.id}] unregistered`);
registerButton.disabled = !user.isConnected();
unregisterButton.disabled = true;
};
}
// Helper function to create network connect callback
function makeServerConnectCallback(
user: SimpleUser,
connectButton: HTMLButtonElement,
disconnectButton: HTMLButtonElement,
registerButton: HTMLButtonElement,
beginButton: HTMLButtonElement
): () => void {
return () => {
console.log(`[${user.id}] connected`);
connectButton.disabled = true;
disconnectButton.disabled = false;
registerButton.disabled = false;
beginButton.disabled = false;
};
}
// Helper function to create network disconnect callback
function makeServerDisconnectCallback(
user: SimpleUser,
connectButton: HTMLButtonElement,
disconnectButton: HTMLButtonElement,
registerButton: HTMLButtonElement,
beginButton: HTMLButtonElement
): () => void {
return (error?: Error) => {
console.log(`[${user.id}] disconnected`);
connectButton.disabled = false;
disconnectButton.disabled = true;
registerButton.disabled = true;
beginButton.disabled = true;
if (error) {
alert(`[${user.id}] Server disconnected.\n` + error.message);
}
};
}
// Helper function to setup click handler for connect button
function makeConnectButtonClickListener(
user: SimpleUser,
connectButton: HTMLButtonElement,
disconnectButton: HTMLButtonElement,
registerButton: HTMLButtonElement,
beginButton: HTMLButtonElement
): () => void {
return () => {
user
.connect()
.then(() => {
connectButton.disabled = true;
disconnectButton.disabled = false;
registerButton.disabled = false;
beginButton.disabled = false;
})
.catch((error: Error) => {
console.error(`[${user.id}] failed to connect`);
console.error(error);
alert(`[${user.id}] Failed to connect.\n` + error);
});
};
}
// Helper function to setup click handler for disconnect button
function makeDisconnectButtonClickListener(
user: SimpleUser,
connectButton: HTMLButtonElement,
disconnectButton: HTMLButtonElement,
registerButton: HTMLButtonElement,
beginButton: HTMLButtonElement
): () => void {
return () => {
user
.disconnect()
.then(() => {
connectButton.disabled = false;
disconnectButton.disabled = true;
registerButton.disabled = true;
beginButton.disabled = true;
})
.catch((error: Error) => {
console.error(`[${user.id}] failed to disconnect`);
console.error(error);
alert(`[${user.id}] Failed to disconnect.\n` + error);
});
};
}
// Helper function to setup click handler for register button
function makeRegisterButtonClickListener(user: SimpleUser, registerButton: HTMLButtonElement): () => void {
return () => {
user
.register(undefined, {
// An example of how to get access to a SIP response message for custom handling
requestDelegate: {
onReject: (response) => {
console.warn(`[${user.id}] REGISTER rejected`);
let message = `Registration of "${user.id}" rejected.\n`;
message += `Reason: ${response.message.reasonPhrase}\n`;
alert(message);
}
}
})
.then(() => {
registerButton.disabled = true;
})
.catch((error: Error) => {
console.error(`[${user.id}] failed to register`);
console.error(error);
alert(`[${user.id}] Failed to register.\n` + error);
});
};
}
// Helper function to setup click handler for unregister button
function makeUnregisterButtonClickListener(user: SimpleUser, unregisterButton: HTMLButtonElement): () => void {
return () => {
user
.unregister()
.then(() => {
unregisterButton.disabled = true;
})
.catch((error: Error) => {
console.error(`[${user.id}] failed to unregister`);
console.error(error);
alert(`[${user.id}] Failed to unregister.\n` + error);
});
};
}
// Helper function to setup click handler for begin button
function makeBeginButtonClickListener(user: SimpleUser, target: string, targetDisplay: string): () => void {
return () => {
user
.call(target, undefined, {
// An example of how to get access to a SIP response message for custom handling
requestDelegate: {
onReject: (response) => {
console.warn(`[${user.id}] INVITE rejected`);
let message = `Session invitation to "${targetDisplay}" rejected.\n`;
message += `Reason: ${response.message.reasonPhrase}\n`;
message += `Perhaps "${targetDisplay}" is not connected or registered?\n`;
message += `Or perhaps "${targetDisplay}" did not grant access to video?\n`;
alert(message);
}
},
withoutSdp: false
})
.catch((error: Error) => {
console.error(`[${user.id}] failed to begin session`);
console.error(error);
alert(`[${user.id}] Failed to begin session.\n` + error);
});
};
}
// Helper function to setup click handler for begin button
function makeEndButtonClickListener(user: SimpleUser): () => void {
return () => {
user.hangup().catch((error: Error) => {
console.error(`[${user.id}] failed to end session`);
console.error(error);
alert(`[${user.id}] Failed to end session.\n` + error);
});
};
}
// Helper function to setup click handler for hold checkbox
function makeHoldCheckboxClickListener(user: SimpleUser, holdCheckbox: HTMLInputElement): () => void {
return () => {
if (holdCheckbox.checked) {
// Checkbox is checked..
user.hold().catch((error: Error) => {
holdCheckbox.checked = false;
console.error(`[${user.id}] failed to hold call`);
console.error(error);
alert("Failed to hold call.\n" + error);
});
} else {
// Checkbox is not checked..
user.unhold().catch((error: Error) => {
holdCheckbox.checked = true;
console.error(`[${user.id}] failed to unhold call`);
console.error(error);
alert("Failed to unhold call.\n" + error);
});
}
};
}
// Hold helper function
const holdCheckboxDisabled = (disabled: boolean, holdCheckbox: HTMLInputElement): void => {
holdCheckbox.checked = false;
holdCheckbox.disabled = disabled;
};
// Helper function to setup click handler for mute checkbox
function makeMuteCheckboxClickListener(user: SimpleUser, muteCheckbox: HTMLInputElement): () => void {
return () => {
if (muteCheckbox.checked) {
// Checkbox is checked..
user.mute();
if (user.isMuted() === false) {
muteCheckbox.checked = false;
console.error(`[${user.id}] failed to mute call`);
alert("Failed to mute call.\n");
}
} else {
// Checkbox is not checked..
user.unmute();
if (user.isMuted() === true) {
muteCheckbox.checked = true;
console.error(`[${user.id}] failed to unmute call`);
alert("Failed to unmute call.\n");
}
}
};
}
// Mute helper function
const muteCheckboxDisabled = (disabled: boolean, muteCheckbox: HTMLInputElement): void => {
muteCheckbox.checked = false;
muteCheckbox.disabled = disabled;
}; | the_stack |
import * as chai from "chai";
import { Workspace } from "../../src/internals/workspace";
import { createProject } from "../../src";
import { FakeMonacoTextEditor } from "../fakes/fakeMonacoTextEditor";
import { FakeMessageBus } from "../fakes/fakeMessageBus";
import { FakeIdGenerator } from "../fakes/fakeIdGenerator";
import { expect } from "chai";
chai.should();
describe("a workspace", () => {
it("is not marked as modified at creation", () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
ws.isModified().should.be.false;
});
it("is marked as modified when propulated from a project", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject({ packageName: "console", files: [{ name: "program.cs", content: "the program" }, { name: "otherFile.cs", content: "other file content" }] });
ws.fromProject(project);
ws.isModified().should.be.true;
});
it("is should have default language", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject({ packageName: "console", files: [{ name: "program.cs", content: "the program" }, { name: "otherFile.cs", content: "other file content" }] });
ws.fromProject(project);
ws.isModified().should.be.true;
let request = ws.toSetWorkspaceRequests();
request.workspace.language.should.be.equal("csharp");
});
it("is retains the language of hte project", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject({ packageName: "console", language: "fsharp", files: [{ name: "program.cs", content: "the program" }, { name: "otherFile.cs", content: "other file content" }] });
ws.fromProject(project);
ws.isModified().should.be.true;
let request = ws.toSetWorkspaceRequests();
request.workspace.language.should.be.equal("fsharp");
});
it("is marked as modified when a document is opened", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject({ packageName: "console", files: [{ name: "program.cs", content: "the program" }, { name: "otherFile.cs", content: "other file content" }] });
ws.fromProject(project);
await ws.openDocument({ fileName: "program.cs" });
ws.isModified().should.be.true;
});
it("is not marked as modified when is exported as setWorkspaceRequest object", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject({ packageName: "console", files: [{ name: "program.cs", content: "the program" }, { name: "otherFile.cs", content: "other file content" }] });
ws.fromProject(project);
ws.isModified().should.be.true;
ws.toSetWorkspaceRequests();
ws.isModified().should.be.false;
});
it("is not marked as modified when a document is opened again", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject({ packageName: "console", files: [{ name: "program.cs", content: "the program" }, { name: "otherFile.cs", content: "other file content" }] });
ws.fromProject(project);
ws.isModified().should.be.true;
let doc = await ws.openDocument({ fileName: "program.cs" });
ws.toSetWorkspaceRequests();
ws.isModified().should.be.false;
doc = await ws.openDocument({ fileName: "program.cs" });
});
it("is marked as modified when a document is opened and the content is changed", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject({ packageName: "console", files: [{ name: "program.cs", content: "the program" }, { name: "otherFile.cs", content: "other file content" }] });
ws.fromProject(project);
let doc = await ws.openDocument({ fileName: "program.cs" });
doc.setContent("modified content");
ws.isModified().should.be.true;
});
it("generates set workspace request object", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject({ packageName: "console", files: [{ name: "program.cs", content: "the program" }, { name: "otherFile.cs", content: "other file content" }] });
ws.fromProject(project);
let doc = await ws.openDocument({ fileName: "program.cs" });
doc.setContent("modified content");
let wsr = ws.toSetWorkspaceRequests();
wsr.should.not.be.null;
wsr.workspace.should.not.be.null;
wsr.workspace.buffers[0].should.not.be.null;
});
it("generates set workspace request object with active bufferId equal to the document currently open in an editor", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject(
{
packageName: "console",
files:
[
{ name: "program.cs", content: "the program" },
{ name: "otherFile.cs", content: "other file content" }
]
});
ws.fromProject(project);
let editorZero = new FakeMonacoTextEditor("0");
let editorOne = new FakeMonacoTextEditor("1");
let programDocument = await ws.openDocument({ fileName: "program.cs", textEditor: editorZero });
let otherFileDocument = await ws.openDocument({ fileName: "otherFile.cs", textEditor: editorOne });
programDocument.setContent("modified content");
let wsr = ws.toSetWorkspaceRequests();
wsr.workspace.should.not.be.null;
wsr.workspace.buffers[0].should.not.be.null;
wsr.workspace.buffers[1].should.not.be.null;
wsr.bufferIds[editorZero.id()].should.be.equal("program.cs");
wsr.bufferIds[editorOne.id()].should.be.equal("otherFile.cs");
});
it("can open a document and set its content", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject(
{
packageName: "console",
files: [
{ name: "program.cs", content: "the program" },
{ name: "otherFile.cs", content: "other file content" }
]
});
ws.fromProject(project);
let doc = await ws.openDocument({ fileName: "program.cs", content: "content override" });
expect(doc).not.to.be.null;
doc.getContent().should.be.equal("content override");
});
it("can open a document in the editor and set its content", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject(
{
packageName: "console",
files: [
{ name: "program.cs", content: "the program" },
{ name: "otherFile.cs", content: "other file content" }
]
});
let editorZero = new FakeMonacoTextEditor("0");
ws.fromProject(project);
let doc = await ws.openDocument({ fileName: "program.cs", textEditor: editorZero, content: "content override" });
expect(doc).not.to.be.null;
doc.getContent().should.be.equal("content override");
doc.currentEditor().should.not.be.null;
doc.currentEditor().id().should.be.equal("0");
editorZero.content.should.be.equal(doc.getContent());
});
it("can open a document in one edtior at a time", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject(
{
packageName: "console",
files: [
{ name: "program.cs", content: "the program" },
{ name: "otherFile.cs", content: "other file content" }
]
});
ws.fromProject(project);
let editorZero = new FakeMonacoTextEditor("0");
let editorOne = new FakeMonacoTextEditor("1");
let doc = await ws.openDocument({ fileName: "program.cs", textEditor: editorZero });
doc.isActiveInEditor().should.be.true;
doc.currentEditor().should.not.be.null;
doc.currentEditor().id().should.be.equal("0");
doc = await ws.openDocument({ fileName: "program.cs", textEditor: editorOne });
doc.isActiveInEditor().should.be.true;
doc.currentEditor().should.not.be.null;
doc.currentEditor().id().should.be.equal("1");
});
it("can open documents in different edtiors at same time", async () => {
let ws = new Workspace(new FakeMessageBus("0"), new FakeIdGenerator());
let project = await createProject(
{
packageName: "console",
files: [
{ name: "program.cs", content: "the program" },
{ name: "otherFile.cs", content: "other file content" }
]
});
ws.fromProject(project);
let editorZero = new FakeMonacoTextEditor("0");
let editorOne = new FakeMonacoTextEditor("1");
let programDocument = await ws.openDocument({ fileName: "program.cs", textEditor: editorZero });
let otherFileDocument = await ws.openDocument({ fileName: "otherFile.cs", textEditor: editorOne });
programDocument.isActiveInEditor().should.be.true;
programDocument.currentEditor().should.not.be.null;
programDocument.currentEditor().id().should.be.equal("0");
otherFileDocument.isActiveInEditor().should.be.true;
otherFileDocument.currentEditor().should.not.be.null;
otherFileDocument.currentEditor().id().should.be.equal("1");
});
}); | the_stack |
import * as Coordinator from '../../../../../front_end/ui/components/render_coordinator/render_coordinator.js';
import * as TreeOutline from '../../../../../front_end/ui/components/tree_outline/tree_outline.js';
import * as LitHtml from '../../../../../front_end/ui/lit-html/lit-html.js';
import {assertElement, assertShadowRoot, dispatchClickEvent, dispatchKeyDownEvent, dispatchMouseOutEvent, dispatchMouseOverEvent, getEventPromise, renderElementIntoDOM, stripLitHtmlCommentNodes} from '../../helpers/DOMHelpers.js';
const coordinator = Coordinator.RenderCoordinator.RenderCoordinator.instance();
const {assert} = chai;
async function renderTreeOutline<TreeNodeDataType>({
tree,
defaultRenderer,
}: {
tree: TreeOutline.TreeOutline.TreeOutlineData<TreeNodeDataType>['tree'],
// defaultRenderer is required usually but here we make it optinal and provide a default one as part of renderTreeOutline, to save duplication in every single test where we want to use a simple string renderer.
defaultRenderer?: TreeOutline.TreeOutline.TreeOutlineData<TreeNodeDataType>['defaultRenderer'],
}): Promise<{
component: TreeOutline.TreeOutline.TreeOutline<TreeNodeDataType>,
shadowRoot: ShadowRoot,
}> {
const component = new TreeOutline.TreeOutline.TreeOutline<TreeNodeDataType>();
const data: TreeOutline.TreeOutline.TreeOutlineData<TreeNodeDataType> = {
tree,
defaultRenderer: defaultRenderer ||
((node: TreeOutline.TreeOutlineUtils.TreeNode<TreeNodeDataType>) => LitHtml.html`${node.treeNodeData}`),
};
component.data = data;
renderElementIntoDOM(component);
assertShadowRoot(component.shadowRoot);
await coordinator.done();
return {
component,
shadowRoot: component.shadowRoot,
};
}
/**
* Wait for a certain number of children are rendered. We need this as the
* component uses LitHtml's until directive, which is async and not within the
* render coordinator's control.
*/
async function waitForRenderedTreeNodeCount(shadowRoot: ShadowRoot, expectedNodeCount: number): Promise<void> {
const actualNodeCount = shadowRoot.querySelectorAll('li[role="treeitem"]').length;
if (actualNodeCount === expectedNodeCount) {
return;
}
await new Promise<void>(resolve => {
requestAnimationFrame(async () => {
await waitForRenderedTreeNodeCount(shadowRoot, expectedNodeCount);
resolve();
});
});
}
function getFocusableTreeNode(shadowRoot: ShadowRoot): HTMLLIElement {
const focusableNode = shadowRoot.querySelector<HTMLLIElement>('li[role="treeitem"][tabindex="0"]');
if (!focusableNode) {
throw new Error('Could not find focused node in Tree shadow root');
}
return focusableNode;
}
/*
The structure represented by basicTreeData is:
- Offices
- Europe
- UK
- LON
- 6PS
- CSG
- BEL
- Germany
- MUC
- BER
- Products
- Chrome
- YouTube
- Drive
- Calendar
*/
// These node is pulled out as we test expandAndSelectTreeNode and getPathToTreeNode with them.
const nodeBelgraveHouse = {
treeNodeData: 'BEL',
id: 'BEL',
};
const nodeLondon = {
treeNodeData: 'LON',
id: 'LON',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> =>
Promise.resolve([{treeNodeData: '6PS', id: '6PS'}, {treeNodeData: 'CSG', id: 'CSG'}, nodeBelgraveHouse]),
};
const nodeUK = {
treeNodeData: 'UK',
id: 'UK',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([nodeLondon]),
};
const nodeEurope = {
treeNodeData: 'Europe',
id: 'Europe',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([
nodeUK,
{
treeNodeData: 'Germany',
id: 'Germany',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([
{treeNodeData: 'MUC', id: 'MUC'},
{treeNodeData: 'BER', id: 'BER'},
]),
},
]),
};
const nodeOffices = {
treeNodeData: 'Offices',
id: 'Offices',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([nodeEurope]),
};
const basicTreeData: TreeOutline.TreeOutlineUtils.TreeNode<string>[] = [
nodeOffices,
{
treeNodeData: 'Products',
id: '1',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([
{
treeNodeData: 'Chrome',
id: '2',
},
{
treeNodeData: 'YouTube',
id: '3',
},
{
treeNodeData: 'Drive',
id: '4',
},
{
treeNodeData: 'Calendar',
id: '5',
},
]),
},
];
/*
The structure represented by nodeAustralia is:
- Australia
- SA
- Adelaide
- Toorak Gardens
- Woodville South
- Gawler
- NSW
- Glebe
- Newtown
- Camperdown
*/
const nodeAustralia = {
treeNodeData: 'Australia',
id: 'australia',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([
{
treeNodeData: 'SA',
id: 'sa',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([
{
treeNodeData: 'Adelaide',
id: 'adelaide',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([
{treeNodeData: 'Toorak Gardens', id: 'toorak'},
{treeNodeData: 'Woodville South', id: 'woodville'},
{treeNodeData: 'Gawler', id: 'gawler'},
]),
},
]),
},
{
treeNodeData: 'NSW',
id: 'nsw',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([
{treeNodeData: 'Glebe', id: 'glebe'},
{treeNodeData: 'Newtown', id: 'newtown'},
{treeNodeData: 'Camperdown', id: 'camperdown'},
]),
},
]),
};
const NODE_COUNT_BASIC_DATA_FULLY_EXPANDED = 15;
const NODE_COUNT_BASIC_DATA_DEFAULT_EXPANDED = 12;
interface VisibleTreeNodeFromDOM {
renderedKey: string;
children?: VisibleTreeNodeFromDOM[];
}
/**
* Converts the nodes into a tree structure that we can assert against.
*/
function visibleNodesToTree(shadowRoot: ShadowRoot): VisibleTreeNodeFromDOM[] {
const tree: VisibleTreeNodeFromDOM[] = [];
function buildTreeNode(node: HTMLLIElement): VisibleTreeNodeFromDOM {
const item: VisibleTreeNodeFromDOM = {
renderedKey: nodeKeyInnerHTML(node),
};
if (node.getAttribute('aria-expanded') && node.getAttribute('aria-expanded') === 'true') {
item.children = [];
const childNodes = node.querySelectorAll<HTMLLIElement>(':scope > ul[role="group"]>li');
for (const child of childNodes) {
item.children.push(buildTreeNode(child));
}
}
return item;
}
const rootNodes = shadowRoot.querySelectorAll<HTMLLIElement>('ul[role="tree"]>li');
for (const root of rootNodes) {
tree.push(buildTreeNode(root));
}
return tree;
}
function treeNodeKeyText(node: HTMLLIElement) {
const keyNode = node.querySelector('[data-node-key]');
if (!keyNode) {
throw new Error('Found tree node without a key within it.');
}
return keyNode.getAttribute('data-node-key') || '';
}
function nodeKeyInnerHTML(node: HTMLLIElement) {
const keyNode = node.querySelector('[data-node-key]');
if (!keyNode) {
throw new Error('Found tree node without a key within it.');
}
return stripLitHtmlCommentNodes(keyNode.innerHTML);
}
function getVisibleTreeNodeByText(shadowRoot: ShadowRoot, text: string): HTMLLIElement {
const nodes = shadowRoot.querySelectorAll<HTMLLIElement>('li[role="treeitem"]');
const matchingNode = Array.from(nodes).find(node => {
return treeNodeKeyText(node) === text;
});
if (!matchingNode) {
throw new Error(`Could not find tree item with text ${text}.`);
}
return matchingNode;
}
describe('TreeOutline', () => {
it('renders with all non-root nodes hidden by default', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const visibleItems = shadowRoot.querySelectorAll<HTMLLIElement>('li[role="treeitem"]');
assert.lengthOf(visibleItems, 2);
const itemText1 = treeNodeKeyText(visibleItems[0]);
const itemText2 = treeNodeKeyText(visibleItems[1]);
assert.strictEqual(itemText1, 'Offices');
assert.strictEqual(itemText2, 'Products');
});
it('expands a node when the arrow icon is clicked', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
const arrowIcon = rootNode.querySelector<HTMLSpanElement>('.arrow-icon');
assertElement(arrowIcon, HTMLSpanElement);
dispatchClickEvent(arrowIcon);
await waitForRenderedTreeNodeCount(shadowRoot, 3);
const visibleTree = visibleNodesToTree(shadowRoot);
assert.deepEqual(visibleTree, [
{renderedKey: 'Offices', children: [{renderedKey: 'Europe'}]},
{renderedKey: 'Products'},
]);
});
it('does not expand nodes when clicking outside of the arrow by default', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(rootNode);
await waitForRenderedTreeNodeCount(shadowRoot, 2);
const visibleTree = visibleNodesToTree(shadowRoot);
assert.deepEqual(visibleTree, [
{renderedKey: 'Offices'},
{renderedKey: 'Products'},
]);
});
it('can be configured to expand nodes when any part of the node is clicked', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
component.setAttribute('clickabletitle', '');
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(rootNode);
await waitForRenderedTreeNodeCount(shadowRoot, 3);
const visibleTree = visibleNodesToTree(shadowRoot);
assert.deepEqual(visibleTree, [
{renderedKey: 'Offices', children: [{renderedKey: 'Europe'}]},
{renderedKey: 'Products'},
]);
});
describe('nowrap attribute', () => {
it('sets the white-space to initial by default', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
const key = rootNode.querySelector('[data-node-key]');
assertElement(key, HTMLElement);
const whiteSpaceValue = window.getComputedStyle(key).getPropertyValue('white-space');
assert.strictEqual(whiteSpaceValue, 'normal');
});
it('will set white-space: nowrap if the attribute is set', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
component.setAttribute('nowrap', '');
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
const key = rootNode.querySelector('[data-node-key]');
assertElement(key, HTMLElement);
const whiteSpaceValue = window.getComputedStyle(key).getPropertyValue('white-space');
assert.strictEqual(whiteSpaceValue, 'nowrap');
});
});
describe('toplevelbordercolor attribute', () => {
it('by default the nodes are not given a border', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
const borderTopValue = window.getComputedStyle(rootNode).getPropertyValue('border-top');
// Odd assertion: this is the default borderTop the browser "applies" if none is set.
assert.strictEqual(borderTopValue, '0px none rgb(0, 0, 0)');
});
it('gives the nodes a border if the attribute is set', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
component.setAttribute('toplevelbordercolor', 'rgb(255, 0, 0)');
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
const borderTopValue = window.getComputedStyle(rootNode).getPropertyValue('border-top');
assert.strictEqual(borderTopValue, '1px solid rgb(255, 0, 0)');
});
});
it('can take nodes with a custom key type', async () => {
interface CustomTreeKeyType {
property: string;
value: string;
}
const customRenderer = (node: TreeOutline.TreeOutlineUtils.TreeNode<CustomTreeKeyType>) => {
return LitHtml.html`<h2 class="item">${node.treeNodeData.property.toUpperCase()}:</h2>${node.treeNodeData.value}`;
};
const tinyTree: TreeOutline.TreeOutlineUtils.TreeNode<CustomTreeKeyType>[] = [{
treeNodeData: {property: 'name', value: 'jack'},
id: '0',
renderer: customRenderer,
children: () => Promise.resolve<TreeOutline.TreeOutlineUtils.TreeNode<CustomTreeKeyType>[]>([
{
renderer: customRenderer,
id: '1',
treeNodeData: {property: 'locationGroupName', value: 'EMEA'},
},
{
renderer: customRenderer,
id: '2',
treeNodeData: {property: 'locationGroupName', value: 'USA'},
},
{
renderer: customRenderer,
id: '3',
treeNodeData: {property: 'locationGroupName', value: 'APAC'},
},
]),
}];
const {component, shadowRoot} = await renderTreeOutline({
tree: tinyTree,
});
await component.expandRecursively();
await waitForRenderedTreeNodeCount(shadowRoot, 4);
const visibleTree = visibleNodesToTree(shadowRoot);
assert.deepEqual(visibleTree, [
{
renderedKey: '<h2 class="item">NAME:</h2>jack',
children: [
{
renderedKey: '<h2 class="item">LOCATIONGROUPNAME:</h2>EMEA',
},
{
renderedKey: '<h2 class="item">LOCATIONGROUPNAME:</h2>USA',
},
{
renderedKey: '<h2 class="item">LOCATIONGROUPNAME:</h2>APAC',
},
],
},
]);
});
it('can recursively expand the tree, going 3 levels deep by default', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively();
await waitForRenderedTreeNodeCount(shadowRoot, 12);
const visibleTree = visibleNodesToTree(shadowRoot);
assert.deepEqual(visibleTree, [
{
renderedKey: 'Offices',
children: [{
renderedKey: 'Europe',
children: [
{renderedKey: 'UK', children: [{renderedKey: 'LON'}]},
{renderedKey: 'Germany', children: [{renderedKey: 'MUC'}, {renderedKey: 'BER'}]},
],
}],
},
{
renderedKey: 'Products',
children: [
{
renderedKey: 'Chrome',
},
{
renderedKey: 'YouTube',
},
{
renderedKey: 'Drive',
},
{
renderedKey: 'Calendar',
},
],
},
]);
});
describe('expandToAndSelectTreeNode', () => {
it('expands the relevant part of the tree to reveal the given node', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandToAndSelectTreeNode(nodeBelgraveHouse);
await waitForRenderedTreeNodeCount(shadowRoot, 9);
const visibleTree = visibleNodesToTree(shadowRoot);
// The tree is expanded down to include "BEL" but the rest of the tree is still collapsed.
assert.deepEqual(visibleTree, [
{
renderedKey: 'Offices',
children: [{
renderedKey: 'Europe',
children: [
{
renderedKey: 'UK',
children: [
{renderedKey: 'LON', children: [{renderedKey: '6PS'}, {renderedKey: 'CSG'}, {renderedKey: 'BEL'}]},
],
},
{renderedKey: 'Germany'},
],
}],
},
{
renderedKey: 'Products',
},
]);
});
it('selects the given node once the tree has been expanded', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandToAndSelectTreeNode(nodeBelgraveHouse);
// Wait for the tree to be expanded
await waitForRenderedTreeNodeCount(shadowRoot, 9);
// Wait for the coordinator to have called focus() on the right node
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'BEL'),
);
});
});
it('can recursively collapse all children of a node', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_FULLY_EXPANDED);
const europeNode = getVisibleTreeNodeByText(shadowRoot, 'Europe');
await component.collapseChildrenOfNode(europeNode);
await waitForRenderedTreeNodeCount(shadowRoot, 7);
const visibleTree = visibleNodesToTree(shadowRoot);
assert.deepEqual(visibleTree, [
{
renderedKey: 'Offices',
children: [{
renderedKey: 'Europe',
}],
},
{
renderedKey: 'Products',
children: [
{
renderedKey: 'Chrome',
},
{
renderedKey: 'YouTube',
},
{
renderedKey: 'Drive',
},
{
renderedKey: 'Calendar',
},
],
},
]);
});
it('caches async child nodes and only fetches them once', async () => {
const fetchChildrenSpy = sinon.spy<() => Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]>>(() => {
return Promise.resolve([
{
treeNodeData: 'EMEA',
id: '1',
},
{
treeNodeData: 'USA',
id: '2',
},
{
treeNodeData: 'APAC',
id: '3',
},
]);
});
const tinyTree: TreeOutline.TreeOutlineUtils.TreeNode<string>[] = [
{
treeNodeData: 'Offices',
id: '0',
children: fetchChildrenSpy,
},
];
const {component, shadowRoot} = await renderTreeOutline({
tree: tinyTree,
});
// Expand it, then collapse it, then expand it again
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, 4);
assert.strictEqual(fetchChildrenSpy.callCount, 1);
const officesNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
await component.collapseChildrenOfNode(officesNode);
await waitForRenderedTreeNodeCount(shadowRoot, 1);
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, 4);
// Make sure that we only fetched the children once despite expanding the
// Tree twice.
assert.strictEqual(fetchChildrenSpy.callCount, 1);
const visibleTree = visibleNodesToTree(shadowRoot);
assert.deepEqual(visibleTree, [
{
renderedKey: 'Offices',
children: [
{
renderedKey: 'EMEA',
},
{renderedKey: 'USA'},
{renderedKey: 'APAC'},
],
},
]);
});
it('allows a node to have a custom renderer', async () => {
const tinyTree: TreeOutline.TreeOutlineUtils.TreeNode<string>[] = [{
treeNodeData: 'Offices',
id: 'Offices',
renderer: node => LitHtml.html`<h2 class="top-node">${node.treeNodeData.toUpperCase()}</h2>`,
children: () => Promise.resolve([
{
treeNodeData: 'EMEA',
id: 'EMEA',
},
{
treeNodeData: 'USA',
id: 'USA',
},
{
treeNodeData: 'APAC',
id: 'APAC',
},
]),
}];
const {component, shadowRoot} = await renderTreeOutline({
tree: tinyTree,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, 4);
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
const key = officeNode.querySelector('[data-node-key]');
assertElement(key, HTMLElement);
const renderedKey = stripLitHtmlCommentNodes(key.innerHTML);
assert.strictEqual(renderedKey, '<h2 class="top-node">OFFICES</h2>');
});
it('passes the custom renderer the expanded state', async () => {
const tinyTree: TreeOutline.TreeOutlineUtils.TreeNode<string>[] = [{
treeNodeData: 'Offices',
id: 'Offices',
renderer: (node, {isExpanded}) => {
return LitHtml.html`<h2 class="top-node">${node.treeNodeData.toUpperCase()}. Expanded: ${isExpanded}</h2>`;
},
children: () => Promise.resolve([
{
treeNodeData: 'EMEA',
id: 'EMEA',
},
{
treeNodeData: 'USA',
id: 'USA',
},
{
treeNodeData: 'APAC',
id: 'APAC',
},
]),
}];
const {component, shadowRoot} = await renderTreeOutline({
tree: tinyTree,
});
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
const key = officeNode.querySelector('[data-node-key]');
assertElement(key, HTMLElement);
let renderedKey = stripLitHtmlCommentNodes(key.innerHTML);
assert.strictEqual(renderedKey, '<h2 class="top-node">OFFICES. Expanded: false</h2>');
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, 4);
renderedKey = stripLitHtmlCommentNodes(key.innerHTML);
assert.strictEqual(renderedKey, '<h2 class="top-node">OFFICES. Expanded: true</h2>');
});
describe('navigating with keyboard', () => {
it('defaults to the first root node as active', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Offices'),
);
});
describe('pressing the ENTER key', () => {
it('expands the node if it is closed', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
await coordinator.done();
dispatchKeyDownEvent(officeNode, {key: 'Enter', bubbles: true});
await waitForRenderedTreeNodeCount(shadowRoot, 3);
assert.strictEqual(officeNode.getAttribute('aria-expanded'), 'true');
});
it('closes the node if it is open', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
component.expandRecursively();
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_DEFAULT_EXPANDED);
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
await coordinator.done();
dispatchKeyDownEvent(officeNode, {key: 'Enter', bubbles: true});
await waitForRenderedTreeNodeCount(shadowRoot, 6);
assert.strictEqual(officeNode.getAttribute('aria-expanded'), 'false');
});
});
describe('pressing the SPACE key', () => {
it('expands the node if it is closed', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
await coordinator.done();
dispatchKeyDownEvent(officeNode, {key: ' ', bubbles: true});
await waitForRenderedTreeNodeCount(shadowRoot, 3);
assert.strictEqual(officeNode.getAttribute('aria-expanded'), 'true');
});
it('closes the node if it is open', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively();
await waitForRenderedTreeNodeCount(shadowRoot, 12);
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
await coordinator.done();
dispatchKeyDownEvent(officeNode, {key: ' ', bubbles: true});
await waitForRenderedTreeNodeCount(shadowRoot, 6);
assert.strictEqual(officeNode.getAttribute('aria-expanded'), 'false');
});
});
describe('pressing the HOME key', () => {
it('takes the user to the top most root node', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_FULLY_EXPANDED);
const berlinNode = getVisibleTreeNodeByText(shadowRoot, 'BER');
dispatchClickEvent(berlinNode);
await coordinator.done();
dispatchKeyDownEvent(berlinNode, {key: 'Home', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Offices'),
);
});
});
describe('pressing the END key', () => {
it('takes the user to the last visible node if they are all expanded', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await coordinator.done();
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
dispatchKeyDownEvent(officeNode, {key: 'End', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
// Calendar is the very last node in the tree
getVisibleTreeNodeByText(shadowRoot, 'Calendar'),
);
});
it('does not expand any closed nodes and focuses the last visible node', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
// Expand the Offices part of the tree
const arrowIcon = officeNode.querySelector<HTMLSpanElement>('.arrow-icon');
assertElement(arrowIcon, HTMLSpanElement);
dispatchClickEvent(arrowIcon);
await waitForRenderedTreeNodeCount(shadowRoot, 3);
// Focus the "Europe" node.
const europeNode = getVisibleTreeNodeByText(shadowRoot, 'Europe');
dispatchClickEvent(europeNode);
dispatchKeyDownEvent(officeNode, {key: 'End', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
// Products is the last node in the tree, as its children are not expanded
getVisibleTreeNodeByText(shadowRoot, 'Products'),
);
});
});
describe('pressing the UP arrow', () => {
it('does nothing if on the root node', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
dispatchKeyDownEvent(officeNode, {key: 'ArrowUp', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
officeNode,
);
});
it('moves focus to the previous sibling', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively();
await waitForRenderedTreeNodeCount(shadowRoot, 12);
const berlinNode = getVisibleTreeNodeByText(shadowRoot, 'BER');
dispatchClickEvent(berlinNode);
dispatchKeyDownEvent(berlinNode, {key: 'ArrowUp', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'MUC'),
);
});
it('moves focus to the parent if there are no previous siblings', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively();
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_DEFAULT_EXPANDED);
const ukNode = getVisibleTreeNodeByText(shadowRoot, 'UK');
dispatchClickEvent(ukNode);
dispatchKeyDownEvent(ukNode, {key: 'ArrowUp', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Europe'),
);
});
it('moves focus to the parent\'s last child if there are no previous siblings and the parent is expanded',
async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively();
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_DEFAULT_EXPANDED);
const germanyNode = getVisibleTreeNodeByText(shadowRoot, 'Germany');
dispatchClickEvent(germanyNode);
dispatchKeyDownEvent(germanyNode, {key: 'ArrowUp', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'LON'),
);
});
it('moves focus to the parent\'s deeply nested last child if there are no previous siblings and the parent has children that are expanded',
async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_FULLY_EXPANDED);
const germanyNode = getVisibleTreeNodeByText(shadowRoot, 'Germany');
dispatchClickEvent(germanyNode);
dispatchKeyDownEvent(germanyNode, {key: 'ArrowUp', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'BEL'),
);
});
});
describe('pressing the RIGHT arrow', () => {
it('does nothing if it is on a node that cannot be expanded', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_FULLY_EXPANDED);
const chromeNode = getVisibleTreeNodeByText(shadowRoot, 'Chrome');
dispatchClickEvent(chromeNode);
dispatchKeyDownEvent(chromeNode, {key: 'ArrowRight', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
chromeNode,
);
});
it('expands the node if on an expandable node that is closed and does not move focus', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
dispatchKeyDownEvent(officeNode, {key: 'ArrowRight', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
officeNode,
);
assert.strictEqual(officeNode.getAttribute('aria-expanded'), 'true');
});
it('moves focus into the child if pressed on an expanded node', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
// Press once to expand, twice to navigate in to the first child
dispatchKeyDownEvent(officeNode, {key: 'ArrowRight', bubbles: true});
await coordinator.done();
dispatchKeyDownEvent(officeNode, {key: 'ArrowRight', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Europe'),
);
});
});
describe('pressing the LEFT arrow', () => {
it('closes the node if the focused node is expanded', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await coordinator.done();
const europeNode = getVisibleTreeNodeByText(shadowRoot, 'Europe');
dispatchClickEvent(europeNode);
dispatchKeyDownEvent(europeNode, {key: 'ArrowLeft', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Europe'),
);
const visibleTree = visibleNodesToTree(shadowRoot);
// The tree below "Europe" is hidden as the left arrow press closed that node.
assert.deepEqual(visibleTree, [
{
renderedKey: 'Offices',
children: [{
renderedKey: 'Europe',
}],
},
{
renderedKey: 'Products',
children: [
{
renderedKey: 'Chrome',
},
{
renderedKey: 'YouTube',
},
{
renderedKey: 'Drive',
},
{
renderedKey: 'Calendar',
},
],
},
]);
});
it('moves to the parent node if the current node is not expanded or unexpandable', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_FULLY_EXPANDED);
await coordinator.done();
const berlinNode = getVisibleTreeNodeByText(shadowRoot, 'BER');
dispatchClickEvent(berlinNode);
dispatchKeyDownEvent(berlinNode, {key: 'ArrowLeft', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Germany'),
);
});
it('does nothing when called on a root node', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const productsNode = getVisibleTreeNodeByText(shadowRoot, 'Products');
dispatchClickEvent(productsNode);
dispatchKeyDownEvent(productsNode, {key: 'ArrowLeft', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Products'),
);
});
});
describe('pressing the DOWN arrow', () => {
it('moves down to the next sibling if the node is not expanded', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
dispatchKeyDownEvent(officeNode, {key: 'ArrowDown', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Products'),
);
});
it('does not move if it is the last sibling and there are no parent siblings', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const productsNode = getVisibleTreeNodeByText(shadowRoot, 'Products');
dispatchClickEvent(productsNode);
dispatchKeyDownEvent(productsNode, {key: 'ArrowDown', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Products'),
);
});
it('moves down to the first child of the node if it is expanded', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively();
await coordinator.done();
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
dispatchKeyDownEvent(officeNode, {key: 'ArrowDown', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Europe'),
);
});
it('moves to its parent\'s sibling if it is the last child', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively();
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_DEFAULT_EXPANDED);
const lonNode = getVisibleTreeNodeByText(shadowRoot, 'LON');
dispatchClickEvent(lonNode);
dispatchKeyDownEvent(lonNode, {key: 'ArrowDown', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Germany'),
);
});
it('is able to navigate high up the tree to the correct next parent\'s sibling', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_FULLY_EXPANDED);
const berNode = getVisibleTreeNodeByText(shadowRoot, 'BER');
dispatchClickEvent(berNode);
dispatchKeyDownEvent(berNode, {key: 'ArrowDown', bubbles: true});
await coordinator.done();
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Products'),
);
});
});
});
// Note: all aria-* positional labels are 1 indexed, not 0 indexed.
describe('aria-* labels', () => {
it('adds correct aria-level labels', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_FULLY_EXPANDED);
await coordinator.done();
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
assert.strictEqual(rootNode.getAttribute('aria-level'), '1');
const europeNode = getVisibleTreeNodeByText(shadowRoot, 'Europe');
assert.strictEqual(europeNode.getAttribute('aria-level'), '2');
const germanyNode = getVisibleTreeNodeByText(shadowRoot, 'Germany');
assert.strictEqual(germanyNode.getAttribute('aria-level'), '3');
const berlinNode = getVisibleTreeNodeByText(shadowRoot, 'BER');
assert.strictEqual(berlinNode.getAttribute('aria-level'), '4');
});
it('adds the correct setsize label to the root node', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Products');
assert.strictEqual(rootNode.getAttribute('aria-setsize'), '2');
});
it('adds the correct setsize label to a deeply nested node', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_FULLY_EXPANDED);
const europeKey = getVisibleTreeNodeByText(shadowRoot, 'Europe');
assert.strictEqual(europeKey.getAttribute('aria-setsize'), '1');
const germanyKey = getVisibleTreeNodeByText(shadowRoot, 'Germany');
// 2 because there are two keys at this level in the tree: UK & Germany
assert.strictEqual(germanyKey.getAttribute('aria-setsize'), '2');
});
it('adds the posinset label to nodes correctly', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_FULLY_EXPANDED);
const europeKey = getVisibleTreeNodeByText(shadowRoot, 'Europe');
assert.strictEqual(europeKey.getAttribute('aria-posinset'), '1');
const csgOfficeKey = getVisibleTreeNodeByText(shadowRoot, 'CSG');
// CSG is 2nd in the LON office list: 6PS, CSG, BEL
assert.strictEqual(csgOfficeKey.getAttribute('aria-posinset'), '2');
});
it('sets aria-expanded to false on non-expanded nodes', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
assert.strictEqual(rootNode.getAttribute('aria-expanded'), 'false');
});
it('sets aria-expanded to true on expanded nodes', async () => {
const {shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
const rootNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
const arrowIcon = rootNode.querySelector<HTMLSpanElement>('.arrow-icon');
assertElement(arrowIcon, HTMLSpanElement);
dispatchClickEvent(arrowIcon);
await coordinator.done();
assert.strictEqual(rootNode.getAttribute('aria-expanded'), 'true');
});
it('does not set aria-expanded at all on leaf nodes', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await component.expandRecursively(Number.POSITIVE_INFINITY);
await waitForRenderedTreeNodeCount(shadowRoot, NODE_COUNT_BASIC_DATA_FULLY_EXPANDED);
const leafNodeCSGOffice = getVisibleTreeNodeByText(shadowRoot, 'CSG');
assert.strictEqual(leafNodeCSGOffice.getAttribute('aria-expanded'), null);
});
});
describe('emitting events', () => {
describe('itemselected event', () => {
it('emits an event when the user clicks on the node', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await coordinator.done();
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
const treeItemSelectedEvent =
getEventPromise<TreeOutline.TreeOutline.ItemSelectedEvent<string>>(component, 'itemselected');
dispatchClickEvent(officeNode);
const event = await treeItemSelectedEvent;
assert.deepEqual(event.data, {node: basicTreeData[0]});
});
it('emits an event when the user navigates to the node with their keyboard', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await coordinator.done();
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices');
dispatchClickEvent(officeNode);
await coordinator.done();
dispatchKeyDownEvent(officeNode, {key: 'ArrowDown', bubbles: true});
const treeItemSelectedEvent =
getEventPromise<TreeOutline.TreeOutline.ItemSelectedEvent<string>>(component, 'itemselected');
await coordinator.done();
const event = await treeItemSelectedEvent;
assert.deepEqual(event.data, {node: basicTreeData[1]});
});
});
describe('itemmouseover', () => {
it('emits an event when the user mouses over the element', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await coordinator.done();
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices').querySelector('.arrow-and-key-wrapper');
assertElement(officeNode, HTMLSpanElement);
const itemMouseOverEvent =
getEventPromise<TreeOutline.TreeOutline.ItemMouseOverEvent<string>>(component, 'itemmouseover');
dispatchMouseOverEvent(officeNode);
const event = await itemMouseOverEvent;
assert.deepEqual(event.data, {node: basicTreeData[0]});
});
});
describe('itemmouseout', () => {
it('emits an event when the user mouses out of the element', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: basicTreeData,
});
await coordinator.done();
const officeNode = getVisibleTreeNodeByText(shadowRoot, 'Offices').querySelector('.arrow-and-key-wrapper');
assertElement(officeNode, HTMLSpanElement);
dispatchMouseOverEvent(officeNode);
const itemMouseOutEvent =
getEventPromise<TreeOutline.TreeOutline.ItemMouseOutEvent<string>>(component, 'itemmouseout');
dispatchMouseOutEvent(officeNode);
const event = await itemMouseOutEvent;
assert.deepEqual(event.data, {node: basicTreeData[0]});
});
});
});
describe('matching on id parameter', () => {
it('expands the relevant part of the tree to reveal the given node', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: [nodeAustralia],
});
// Expand to the node with the given ID, the actual data doesn't matter in this case.
// This means you can search the tree, without having a reference to the specific tree data,
// just as long as you know the id for whatever thing you are looking for.
await component.expandToAndSelectTreeNode({treeNodeData: 'something else', id: 'gawler'});
await waitForRenderedTreeNodeCount(shadowRoot, 7);
const visibleTree = visibleNodesToTree(shadowRoot);
// The tree is expanded down to include "Gawler" but the rest of the tree is still collapsed.
assert.deepEqual(visibleTree, [{
renderedKey: 'Australia',
children: [
{
renderedKey: 'SA',
children: [
{
renderedKey: 'Adelaide',
children: [
{renderedKey: 'Toorak Gardens'},
{renderedKey: 'Woodville South'},
{renderedKey: 'Gawler'},
],
},
],
},
{renderedKey: 'NSW'},
],
}]);
});
it('remembers nodes expanded state across node updates', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: [nodeAustralia],
});
await component.expandToAndSelectTreeNode({treeNodeData: 'something else', id: 'gawler'});
// Update the node by replacing the root node.
const newNodeAustralia = {
treeNodeData: 'New Australia',
id: 'australia',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([
{
treeNodeData: 'Different SA',
id: 'sa',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([
{
treeNodeData: 'Phantom Adelaide',
id: 'adelaide',
children: (): Promise<TreeOutline.TreeOutlineUtils.TreeNode<string>[]> => Promise.resolve([
{treeNodeData: 'Totally not Gawler', id: 'gawler'},
]),
},
]),
},
]),
};
component.data = {
tree: [newNodeAustralia],
defaultRenderer: (node => LitHtml.html`${node.treeNodeData}`),
};
await waitForRenderedTreeNodeCount(shadowRoot, 4);
await coordinator.done();
const visibleTree = visibleNodesToTree(shadowRoot);
// The tree should still be expanded down to the node with key `gawler`.
assert.deepEqual(visibleTree, [{
renderedKey: 'New Australia',
children: [
{
renderedKey: 'Different SA',
children: [
{
renderedKey: 'Phantom Adelaide',
children: [
{renderedKey: 'Totally not Gawler'},
],
},
],
},
],
}]);
});
it('focuses the given node with an id once the tree has been expanded', async () => {
const {component, shadowRoot} = await renderTreeOutline({
tree: [nodeAustralia],
});
await component.expandToAndSelectTreeNode({treeNodeData: 'literally anything', id: 'gawler'});
await waitForRenderedTreeNodeCount(shadowRoot, 7);
await coordinator.done();
// The tree is expanded down to include "Gawler" but the rest of the tree is still collapsed.
assert.strictEqual(
getFocusableTreeNode(shadowRoot),
getVisibleTreeNodeByText(shadowRoot, 'Gawler'),
);
});
});
});
describe('TreeOutlineUtils', () => {
describe('getPathToTreeNode', () => {
it('can find the path to the given node', async () => {
const path = await TreeOutline.TreeOutlineUtils.getPathToTreeNode(basicTreeData, nodeBelgraveHouse);
assert.deepEqual(path, [nodeOffices, nodeEurope, nodeUK, nodeLondon, nodeBelgraveHouse]);
});
it('returns null if no path is found', async () => {
const path = await TreeOutline.TreeOutlineUtils.getPathToTreeNode(
basicTreeData, {treeNodeData: 'does-not-exist', id: '-1'});
assert.strictEqual(path, null);
});
});
}); | the_stack |
import { Point2D } from "../lib/types/sol"
import SCanvas from "../lib/sCanvas"
import { SimplePath } from "../lib/paths"
import { perlin2 } from "../lib/noise"
import { RadialGradient } from "../lib/gradient"
import { clamp, isoTransform } from "../lib"
const isometricExample = (p: SCanvas) => {
const { bottom, right } = p.meta
p.background(0, 0, 95)
// make origin a point centred horizontally, but near bottom
p.withTranslation([right / 2, bottom * 0.8], () => {
// 1/200 of width = height of 1 unit
const iso = isoTransform(0.005)
p.times(10, n => {
const sp = SimplePath.withPoints([])
p.times(100, m => {
// adjust all x,y,z for vertical size: as in isometric all get scaled linearly in vertical direction
sp.addPoint(
iso([
bottom * (10 - n) * 10,
bottom * 20 * Math.cos(p.t + (n * 4 + m) / 10),
bottom * m,
])
)
})
p.setStrokeColor(0, 0, 95)
p.lineWidth = 0.015
p.draw(sp)
p.setStrokeColor(215 - n * 3, 90, 60)
p.lineWidth = 0.005
p.draw(sp)
})
})
}
const isometricExample2 = (p: SCanvas) => {
const { bottom, right } = p.meta
p.lineWidth = 0.01 * bottom
p.background(30, 20, 85)
p.withTranslation([right / 2, bottom * 0.9], () => {
const iso = isoTransform(0.05 * bottom)
p.downFrom(10, n => {
p.downFrom(10, m => {
let sp = SimplePath.withPoints([])
const h = clamp({ from: -3, to: 6 }, p.poisson(4) - 3)
sp.addPoint(iso([n, h, m]))
sp.addPoint(iso([n + 1, h, m]))
sp.addPoint(iso([n + 1, h, m + 1]))
sp.addPoint(iso([n, h, m + 1]))
sp.close()
p.setFillColor(10 + h * 10, 100, 70)
p.fill(sp)
sp = SimplePath.withPoints([])
sp.addPoint(iso([n, h, m + 1]))
sp.addPoint(iso([n, h - 1, m + 1]))
sp.addPoint(iso([n, h - 1, m]))
sp.addPoint(iso([n, h, m]))
sp.close()
p.setFillColor(10 + h * 10, 75, 60)
p.fill(sp)
sp = SimplePath.withPoints([])
sp.addPoint(iso([n, h, m]))
sp.addPoint(iso([n + 1, h, m]))
sp.addPoint(iso([n + 1, h, m + 1]))
sp.addPoint(iso([n, h, m + 1]))
sp.addPoint(iso([n, h - 1, m + 1]))
sp.addPoint(iso([n, h - 1, m]))
sp.addPoint(iso([n, h, m]))
sp.close()
p.draw(sp)
})
})
})
}
const isometricExample3 = (p: SCanvas) => {
const { bottom, right } = p.meta
p.lineWidth = 0.01 * bottom
p.background(210, 70, 30)
p.setStrokeColor(30, 10, 30)
p.withTranslation([right / 2, bottom * 0.9], () => {
const iso = isoTransform(0.05 * bottom)
p.downFrom(10, n => {
p.downFrom(10, m => {
const sp = SimplePath.withPoints([])
const h = clamp(
{ from: -2, to: 5 },
p.poisson(4) - 3 + Math.cos(p.t + n + m)
)
sp.addPoint(iso([n, h, m]))
sp.addPoint(iso([n + 1, h, m]))
sp.addPoint(iso([n + 1, h, m + 1]))
sp.addPoint(iso([n, h, m + 1]))
sp.addPoint(iso([n, h - 1, m + 1]))
sp.addPoint(iso([n, h - 1, m]))
// sp.addPoint(iso([n + 1, h - 1, m + 1]))
sp.close()
p.setFillColor(h * 10 + 10 * Math.cos(h * 3), 95, 65, 0.9)
p.fill(sp)
p.draw(sp)
})
})
})
}
const isometricExample4 = (p: SCanvas) => {
const { bottom, right } = p.meta
p.lineWidth = 0.005 * bottom
p.background(340, 100, 40)
p.setStrokeColor(30, 5, 20)
p.withTranslation([right / 2, bottom * 0.9], () => {
const iso = isoTransform(0.05 * bottom)
p.downFrom(10, n => {
p.downFrom(10, m => {
const h = perlin2(n / 5, m / 10) * 5 + 4
const sp = SimplePath.withPoints([])
sp.addPoint(iso([n, 0, m]))
sp.addPoint(iso([n + 1, 0, m]))
sp.addPoint(iso([n + 0.5, h, m + 0.5]))
sp.close()
p.setFillColor(h * 10, 100, 75, 0.95)
p.fill(sp)
p.draw(sp)
const sp2 = SimplePath.withPoints([])
sp2.addPoint(iso([n, 0, m]))
sp2.addPoint(iso([n, 0, m + 1]))
sp2.addPoint(iso([n + 0.5, h, m + 0.5]))
sp2.close()
p.setFillColor(h * 10, 60, 75, 0.95)
p.fill(sp2)
p.draw(sp2)
})
})
})
}
const isometricExample5 = (p: SCanvas) => {
const { bottom, right } = p.meta
p.lineWidth = 0.005 * bottom
p.background(40, 40, 90)
p.setStrokeColor(30, 5, 20)
// make origin a point centred horizontally, but near bottom
p.withTranslation([right / 2, bottom * 0.95], () => {
const iso = isoTransform(0.05 * bottom)
const h = (x, y) => 2 + 5 * perlin2(x / 5 + p.t, y / 10 + p.t * 0.5)
p.downFrom(11, n => {
p.downFrom(11, m => {
p.doProportion(0.8, () => {
const sp = SimplePath.withPoints([])
sp.addPoint(iso([n, h(n, m), m]))
sp.addPoint(iso([n + 1, h(n + 1, m), m]))
sp.addPoint(iso([n + 1, h(n + 1, m + 1), m + 1]))
sp.addPoint(iso([n, h(n, m + 1), m + 1]))
sp.close()
p.proportionately([
[1, () => p.setFillColor(210, 100, 55 + 2.5 * h(n, m), 0.95)],
[1, () => p.setFillColor(0, 80, 50 + 2.5 * h(n, m), 0.95)],
])
p.fill(sp)
p.draw(sp)
})
})
})
})
}
const isometricExample6 = (p: SCanvas) => {
const { bottom, right } = p.meta
p.lineWidth = 0.005 * bottom
p.background(0, 0, 90)
p.setStrokeColor(30, 5, 20)
// make origin a point centred horizontally, but near bottom
p.withTranslation([right / 2, bottom * 0.95], () => {
const iso = isoTransform(0.05 * bottom)
p.downFrom(11, n => {
p.downFrom(11, m => {
p.times(3, k => {
p.doProportion(1 - (k + 1) / 6, () => {
const h = (x, y) =>
k * 2 + 2 * perlin2(x / 5 + p.t, y / 10 + p.t * 0.5)
const sp = SimplePath.withPoints([])
sp.addPoint(iso([n, h(n, m), m]))
sp.addPoint(iso([n + 1, h(n + 1, m), m]))
sp.addPoint(iso([n + 1, h(n + 1, m + 1), m + 1]))
sp.addPoint(iso([n, h(n, m + 1), m + 1]))
sp.close()
p.proportionately([
[
1,
() =>
p.setFillColor(210, 100, 55 + 2.5 * h(n, m), 0.95 - k / 8),
],
[
1,
() =>
p.setFillColor(340, 100, 45 + 2.5 * h(n, m), 0.95 - k / 8),
],
])
p.fill(sp)
p.draw(sp)
})
})
})
})
})
}
const isometricExample7 = (p: SCanvas) => {
const { bottom, right } = p.meta
p.lineWidth = 0.005 * bottom
p.background(0, 0, 90)
p.setStrokeColor(30, 5, 20)
// make origin a point centred horizontally, but near bottom
p.withTranslation([right / 2, bottom * 0.95], () => {
const iso = isoTransform(0.05 * bottom)
p.times(7, hr => {
const h = hr + Math.cos(p.t)
p.setFillColor(h * 10, 90, 50, 0.95)
const sp = SimplePath.withPoints([])
p.proportionately([
[
1,
() => {
sp.addPoint(iso([5, h, 0]))
sp.addPoint(iso([0, h, 0]))
sp.addPoint(iso([0, h, 1]))
sp.addPoint(iso([0, 5, 3]))
sp.addPoint(iso([1, 5, 3]))
sp.addPoint(iso([1, h, 1]))
sp.addPoint(iso([4, h, 1]))
},
],
[
1,
() => {
sp.addPoint(iso([8, h, 1]))
sp.addPoint(iso([8, h, 0]))
sp.addPoint(iso([8, 0, -2]))
sp.addPoint(iso([7, 0, -2]))
sp.addPoint(iso([7, h, 0]))
sp.addPoint(iso([4, h, 0]))
sp.addPoint(iso([4, h, 1]))
},
],
])
sp.addPoint(iso([4, h + 1, 3]))
p.proportionately([
[
1,
() => {
sp.addPoint(iso([4, h + 1, 7]))
sp.addPoint(iso([0, h, 7]))
sp.addPoint(iso([-2, 0, 7]))
sp.addPoint(iso([-2, 0, 8]))
sp.addPoint(iso([0, h, 8]))
sp.addPoint(iso([5, h + 1, 8]))
},
],
[
1,
() => {
sp.addPoint(iso([4, h + 1, 10]))
sp.addPoint(iso([5, h + 1, 10]))
sp.addPoint(iso([9, h + 2, 10]))
sp.addPoint(iso([11, 7, 10]))
sp.addPoint(iso([11, 7, 9]))
sp.addPoint(iso([9, h + 2, 9]))
sp.addPoint(iso([4, h + 2, 8]))
},
],
])
sp.addPoint(iso([5, h + 1, 3]))
sp.addPoint(iso([5, h, 1]))
sp.close()
p.fill(sp)
p.draw(sp)
})
})
}
const isometricExample8 = (p: SCanvas) => {
p.backgroundGradient(
new RadialGradient({
start: p.meta.center,
rStart: 0,
end: p.meta.center,
rEnd: 0.6,
colors: [[0, { h: 0, s: 0, l: 90 }], [1, { h: 215, s: 80, l: 30 }]],
})
)
const { bottom, right } = p.meta
p.lineWidth = 0.005 * bottom
p.setStrokeColor(30, 5, 20)
// make origin a point centred horizontally, but near bottom
p.withTranslation([right / 2, bottom * 0.95], () => {
const iso = isoTransform(0.05 * bottom)
const top = (x, y, z) => [
iso([x + 0, y, z + 0]),
iso([x + 1, y, z + 0]),
iso([x + 1, y, z + 1]),
iso([x + 0, y, z + 1]),
]
const left = (x, y, z) => [
iso([x, y, z + 0]),
iso([x, y - 0.5, z + 0]),
iso([x, y - 0.5, z + 1]),
iso([x, y, z + 1]),
]
p.times(7, y => {
p.times(7, () => {
const x = p.uniformRandomInt({ from: 0, to: 10 })
const z = p.uniformRandomInt({ from: 0, to: 10 })
p.setFillColor(200, 40, 50)
const sp = SimplePath.withPoints(top(x, y, z)).close()
p.fill(sp)
p.draw(sp)
p.setFillColor(180, 40, 50, 0.8)
const sp2 = SimplePath.withPoints(left(x, y, z)).close()
p.fill(sp2)
p.draw(sp2)
p.setFillColor(350, 40, 50, 0.8)
const sp3 = SimplePath.withPoints(left(x + 1, y + 0.5, z)).close()
p.fill(sp3)
p.draw(sp3)
})
})
})
}
const isometricExample9 = (p: SCanvas) => {
p.background(215, 80, 10)
const { bottom, right: r } = p.meta
p.lineWidth = 0.005 * bottom
p.setStrokeColor(0, 0, 90)
p.withTranslation([r / 2, bottom * 0.5], () => {
const iso = isoTransform(0.1 * bottom)
// Experimenting with helper functions... probably want to include in framework or as helpers somehow?
const top = (x, y, z, s) => [
iso([x, y, z]),
iso([x + s, y, z]),
iso([x + s, y, z + s]),
iso([x, y, z + s]),
]
const left = (x, y, z, s) => [
iso([x, y, z]),
iso([x, y - s, z + 0]),
iso([x, y - s, z + s]),
iso([x, y, z + s]),
]
const right = (x, y, z, s) => [
iso([x, y, z]),
iso([x + s, y, z]),
iso([x + s, y - s, z]),
iso([x, y - s, z]),
]
const shade = (fn, x, y, z, s, h, sat = 40, l = 50) => {
p.setFillColor(h, sat, l, 0.95)
const sp = SimplePath.withPoints(fn(x, y, z, s)).close()
p.fill(sp)
p.draw(sp)
}
const cube = (x, y, z, s) => {
shade(top, x, y, z, s, 200)
shade(left, x, y, z, s, 180)
shade(right, x, y, z, s, 350)
}
shade(top, -1.5, -2, -1.5, 5, 30, 20, 50)
cube(0, 0, 0, 2)
cube(1, -1, -1, 1)
cube(0.5, -1.5, -0.5, 0.5)
cube(-1, -1, 1, 1)
cube(-0.5, -1.5, 0.5, 0.5)
})
}
const isometricExample10 = (p: SCanvas) => {
p.background(175, 60, 10)
const { bottom, right: r } = p.meta
p.lineWidth = 0.005 * bottom
p.setStrokeColor(0, 0, 90)
const tracePoints = (points: Point2D[]) => {
const sp = SimplePath.withPoints(points).close()
p.draw(sp)
}
const sub3 = (
[a, b, c]: [number, number, number],
[d, e, f]: [number, number, number]
): [number, number, number] => [a - d, b - e, c - f]
p.withTranslation([r / 2, bottom * 0.5], () => {
const iso = isoTransform(0.2 * bottom)
const a: [number, number, number] = [
Math.cos(p.t) + Math.sin(p.t),
1,
-Math.sin(p.t) + Math.cos(p.t),
]
const b: [number, number, number] = [
Math.cos(p.t) - Math.sin(p.t),
1,
-Math.sin(p.t) - Math.cos(p.t),
]
const c: [number, number, number] = [
-Math.cos(p.t) - Math.sin(p.t),
1,
Math.sin(p.t) - Math.cos(p.t),
]
const d: [number, number, number] = [
-Math.cos(p.t) + Math.sin(p.t),
1,
Math.sin(p.t) + Math.cos(p.t),
]
const dH: [number, number, number] = [0, 2, 0]
tracePoints([
iso(sub3(a, dH)),
iso(sub3(b, dH)),
iso(sub3(c, dH)),
iso(sub3(d, dH)),
])
tracePoints([iso(a), iso(b), iso(sub3(b, dH)), iso(sub3(a, dH))])
tracePoints([iso(b), iso(c), iso(sub3(c, dH)), iso(sub3(b, dH))])
tracePoints([iso(c), iso(d), iso(sub3(d, dH)), iso(sub3(c, dH))])
tracePoints([iso(d), iso(a), iso(sub3(a, dH)), iso(sub3(d, dH))])
tracePoints([iso(a), iso(b), iso(c), iso(d)])
})
}
const lorenz = (p: SCanvas) => {
const { bottom, right: r, center } = p.meta
p.backgroundGradient(
new RadialGradient({
start: center,
end: center,
rStart: 0,
rEnd: 0.65,
colors: [[0, { h: 215, s: 80, l: 40 }], [1, { h: 215, s: 80, l: 10 }]],
})
)
p.lineWidth = 0.005 * bottom
const points: Point2D[] = []
p.withTranslation([r / 2, bottom * 0.2], () => {
const iso = isoTransform(0.01 * bottom)
let x = 0.82
let y = 0.12
let z = 0
let a = 10.0
let b = 30.0
let c = 8.0 / 3.0
let t = 0.01
const N = 3000
for (let i = 0; i < N; i++) {
points.push(iso([x, y - 35, z - 25]))
const x_ = x + t * a * (y - x)
const y_ = y + t * (x * (b - z) - y)
const z_ = z + t * (x * y - c * z)
x = x_
y = y_
z = z_
}
for (let j = 0; j < N / 10; j++) {
p.setStrokeColor(30 * Math.cos(j / 10), 100, 70)
p.draw(SimplePath.withPoints(points.slice(j * 10, (j + 1) * 10 + 1)))
}
})
}
const sketches: { name: string; sketch: (p: SCanvas) => void }[] = [
{ sketch: isometricExample, name: "Isometric" },
{ sketch: isometricExample2, name: "Isometric 2" },
{ sketch: isometricExample3, name: "Isometric 3" },
{ sketch: isometricExample4, name: "Isometric 4" },
{ sketch: isometricExample5, name: "Isometric 5" },
{ sketch: isometricExample6, name: "Isometric 6" },
{ sketch: isometricExample7, name: "Isometric Tapes" },
{ sketch: isometricExample8, name: "Isometric Fragments" },
{ sketch: isometricExample9, name: "Isometric Cube Examples" },
{ sketch: isometricExample10, name: "Isometric Rotation" },
{ sketch: lorenz, name: "Lorenz Attractor" },
]
export default sketches | the_stack |
import { SENSITIVE_STRING } from "@aws-sdk/smithy-client";
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types";
/**
* <p>The resource with the name requested already exists.</p>
*/
export interface AlreadyExistsException extends __SmithyException, $MetadataBearer {
name: "AlreadyExistsException";
$fault: "client";
Message?: string;
}
export namespace AlreadyExistsException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AlreadyExistsException): any => ({
...obj,
});
}
export interface CancelResourceRequestInput {
/**
* <p>The <code>RequestToken</code> of the <code>ProgressEvent</code> object returned by the
* resource operation request.</p>
*/
RequestToken: string | undefined;
}
export namespace CancelResourceRequestInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CancelResourceRequestInput): any => ({
...obj,
});
}
export enum HandlerErrorCode {
ACCESS_DENIED = "AccessDenied",
ALREADY_EXISTS = "AlreadyExists",
GENERAL_SERVICE_EXCEPTION = "GeneralServiceException",
INTERNAL_FAILURE = "InternalFailure",
INVALID_CREDENTIALS = "InvalidCredentials",
INVALID_REQUEST = "InvalidRequest",
NETWORK_FAILURE = "NetworkFailure",
NOT_FOUND = "NotFound",
NOT_STABILIZED = "NotStabilized",
NOT_UPDATABLE = "NotUpdatable",
RESOURCE_CONFLICT = "ResourceConflict",
SERVICE_INTERNAL_ERROR = "ServiceInternalError",
SERVICE_LIMIT_EXCEEDED = "ServiceLimitExceeded",
SERVICE_TIMEOUT = "ServiceTimeout",
THROTTLING = "Throttling",
}
export enum Operation {
CREATE = "CREATE",
DELETE = "DELETE",
UPDATE = "UPDATE",
}
export enum OperationStatus {
CANCEL_COMPLETE = "CANCEL_COMPLETE",
CANCEL_IN_PROGRESS = "CANCEL_IN_PROGRESS",
FAILED = "FAILED",
IN_PROGRESS = "IN_PROGRESS",
PENDING = "PENDING",
SUCCESS = "SUCCESS",
}
/**
* <p>Represents the current status of a resource operation request. For more information, see
* <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-manage-requests.html">Managing resource operation requests</a> in the
* <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
export interface ProgressEvent {
/**
* <p>The name of the resource type used in the operation.</p>
*/
TypeName?: string;
/**
* <p>The primary identifier for the resource.</p>
* <note>
* <p>In some cases, the resource identifier may be available before the resource operation
* has reached a status of <code>SUCCESS</code>.</p>
* </note>
*/
Identifier?: string;
/**
* <p>The unique token representing this resource operation request.</p>
* <p>Use the <code>RequestToken</code> with <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/APIReference/API_GetResourceRequestStatus.html">GetResourceRequestStatus</a> to return the current status of a resource operation
* request.</p>
*/
RequestToken?: string;
/**
* <p>The resource operation type.</p>
*/
Operation?: Operation | string;
/**
* <p>The current status of the resource operation request.</p>
* <ul>
* <li>
* <p>
* <code>PENDING</code>: The resource operation has not yet started.</p>
* </li>
* <li>
* <p>
* <code>IN_PROGRESS</code>: The resource operation is currently in progress.</p>
* </li>
* <li>
* <p>
* <code>SUCCESS</code>: The resource operation has successfully completed.</p>
* </li>
* <li>
* <p>
* <code>FAILED</code>: The resource operation has failed. Refer to the error code and
* status message for more information.</p>
* </li>
* <li>
* <p>
* <code>CANCEL_IN_PROGRESS</code>: The resource operation is in the process of being
* canceled.</p>
* </li>
* <li>
* <p>
* <code>CANCEL_COMPLETE</code>: The resource operation has been canceled.</p>
* </li>
* </ul>
*/
OperationStatus?: OperationStatus | string;
/**
* <p>When the resource operation request was initiated.</p>
*/
EventTime?: Date;
/**
* <p>A JSON string containing the resource model, consisting of each resource property and its
* current value.</p>
*/
ResourceModel?: string;
/**
* <p>Any message explaining the current status.</p>
*/
StatusMessage?: string;
/**
* <p>For requests with a status of <code>FAILED</code>, the associated error code.</p>
* <p>For error code definitions, see <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-test-contract-errors.html">Handler error codes</a> in the <i>CloudFormation Command
* Line Interface User Guide for Extension Development</i>.</p>
*/
ErrorCode?: HandlerErrorCode | string;
/**
* <p>When to next request the status of this resource operation request.</p>
*/
RetryAfter?: Date;
}
export namespace ProgressEvent {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ProgressEvent): any => ({
...obj,
...(obj.ResourceModel && { ResourceModel: SENSITIVE_STRING }),
});
}
export interface CancelResourceRequestOutput {
/**
* <p>Represents the current status of a resource operation request. For more information, see
* <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-manage-requests.html">Managing resource operation requests</a> in the
* <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
ProgressEvent?: ProgressEvent;
}
export namespace CancelResourceRequestOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CancelResourceRequestOutput): any => ({
...obj,
...(obj.ProgressEvent && { ProgressEvent: ProgressEvent.filterSensitiveLog(obj.ProgressEvent) }),
});
}
/**
* <p>The resource is currently being modified by another operation.</p>
*/
export interface ConcurrentModificationException extends __SmithyException, $MetadataBearer {
name: "ConcurrentModificationException";
$fault: "server";
Message?: string;
}
export namespace ConcurrentModificationException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ConcurrentModificationException): any => ({
...obj,
});
}
/**
* <p>A resource operation with the specified request token cannot be found.</p>
*/
export interface RequestTokenNotFoundException extends __SmithyException, $MetadataBearer {
name: "RequestTokenNotFoundException";
$fault: "client";
Message?: string;
}
export namespace RequestTokenNotFoundException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: RequestTokenNotFoundException): any => ({
...obj,
});
}
/**
* <p>The specified client token has already been used in another resource request.</p>
* <p>It is best practice for client tokens to be unique for each resource operation request.
* However, client token expire after 36 hours.</p>
*/
export interface ClientTokenConflictException extends __SmithyException, $MetadataBearer {
name: "ClientTokenConflictException";
$fault: "client";
Message?: string;
}
export namespace ClientTokenConflictException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ClientTokenConflictException): any => ({
...obj,
});
}
/**
* <p>Another resource operation is currently being performed on this resource.</p>
*/
export interface ConcurrentOperationException extends __SmithyException, $MetadataBearer {
name: "ConcurrentOperationException";
$fault: "client";
Message?: string;
}
export namespace ConcurrentOperationException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ConcurrentOperationException): any => ({
...obj,
});
}
export interface CreateResourceInput {
/**
* <p>The name of the resource type.</p>
*/
TypeName: string | undefined;
/**
* <p>For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version.</p>
*/
TypeVersionId?: string;
/**
* <p>The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the <code>
* <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html#schema-properties-handlers">handlers</a>
* </code> section of the <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html">resource type definition schema</a>.</p>
* <p>If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations.html#resource-operations-permissions">Specifying credentials</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
RoleArn?: string;
/**
* <p>A unique identifier to ensure the idempotency of the resource request. As a best practice, specify this token to ensure idempotency, so that Amazon Web Services Cloud Control API can accurately distinguish between request retries and new resource requests. You might retry a resource request to ensure that it was successfully received.</p>
* <p>A client token is valid for 36 hours once used. After that, a resource request with the same client token is treated as a new request.</p>
* <p>If you do not specify a client token, one is generated for inclusion in the request.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations.html#resource-operations-idempotency">Ensuring resource operation requests are unique</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
ClientToken?: string;
/**
* <p>Structured data format representing the desired state of the resource, consisting of that
* resource's properties and their desired values. </p>
* <note>
* <p>Cloud Control API currently supports JSON as a structured data format.</p>
* </note>
*
* <p>Specify the desired state as one of the following:</p>
* <ul>
* <li>
* <p>A JSON blob</p>
* </li>
* <li>
* <p>A local path containing the desired state in JSON data format</p>
* </li>
* </ul>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-create.html#resource-operations-create-desiredstate">Composing the desired state of the resource</a> in the <i>Amazon Web Services Cloud Control API User
* Guide</i>.</p>
* <p>For more information about the properties of a specific resource, refer to the related
* topic for the resource in the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html">Resource and property types reference</a> in the <i>Amazon Web Services
* CloudFormation Users Guide</i>.</p>
*/
DesiredState: string | undefined;
}
export namespace CreateResourceInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateResourceInput): any => ({
...obj,
...(obj.DesiredState && { DesiredState: SENSITIVE_STRING }),
});
}
export interface CreateResourceOutput {
/**
* <p>Represents the current status of the resource creation request.</p>
* <p>After you have initiated a resource creation request, you can monitor the progress of your
* request by calling <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/APIReference/API_GetResourceRequestStatus.html">GetResourceRequestStatus</a> using the <code>RequestToken</code> of the
* <code>ProgressEvent</code> returned by <code>CreateResource</code>.</p>
*/
ProgressEvent?: ProgressEvent;
}
export namespace CreateResourceOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateResourceOutput): any => ({
...obj,
...(obj.ProgressEvent && { ProgressEvent: ProgressEvent.filterSensitiveLog(obj.ProgressEvent) }),
});
}
/**
* <p>The resource handler has returned that the downstream service generated an error that does
* not map to any other handler error code.</p>
*/
export interface GeneralServiceException extends __SmithyException, $MetadataBearer {
name: "GeneralServiceException";
$fault: "client";
Message?: string;
}
export namespace GeneralServiceException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GeneralServiceException): any => ({
...obj,
});
}
/**
* <p>The resource handler has failed without a returning a more specific error code. This can
* include timeouts.</p>
*/
export interface HandlerFailureException extends __SmithyException, $MetadataBearer {
name: "HandlerFailureException";
$fault: "server";
Message?: string;
}
export namespace HandlerFailureException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: HandlerFailureException): any => ({
...obj,
});
}
/**
* <p>The resource handler has returned that an unexpected error occurred within the resource
* handler.</p>
*/
export interface HandlerInternalFailureException extends __SmithyException, $MetadataBearer {
name: "HandlerInternalFailureException";
$fault: "server";
Message?: string;
}
export namespace HandlerInternalFailureException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: HandlerInternalFailureException): any => ({
...obj,
});
}
/**
* <p>The resource handler has returned that the credentials provided by the user are
* invalid.</p>
*/
export interface InvalidCredentialsException extends __SmithyException, $MetadataBearer {
name: "InvalidCredentialsException";
$fault: "client";
Message?: string;
}
export namespace InvalidCredentialsException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InvalidCredentialsException): any => ({
...obj,
});
}
/**
* <p>The resource handler has returned that invalid input from the user has generated a generic
* exception.</p>
*/
export interface InvalidRequestException extends __SmithyException, $MetadataBearer {
name: "InvalidRequestException";
$fault: "client";
Message?: string;
}
export namespace InvalidRequestException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InvalidRequestException): any => ({
...obj,
});
}
/**
* <p>The resource handler has returned that the request could not be completed due to
* networking issues, such as a failure to receive a response from the server.</p>
*/
export interface NetworkFailureException extends __SmithyException, $MetadataBearer {
name: "NetworkFailureException";
$fault: "server";
Message?: string;
}
export namespace NetworkFailureException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: NetworkFailureException): any => ({
...obj,
});
}
/**
* <p>The resource handler has returned that the downstream resource failed to complete all of
* its ready-state checks.</p>
*/
export interface NotStabilizedException extends __SmithyException, $MetadataBearer {
name: "NotStabilizedException";
$fault: "client";
Message?: string;
}
export namespace NotStabilizedException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: NotStabilizedException): any => ({
...obj,
});
}
/**
* <p>One or more properties included in this resource operation are defined as create-only, and
* therefore cannot be updated.</p>
*/
export interface NotUpdatableException extends __SmithyException, $MetadataBearer {
name: "NotUpdatableException";
$fault: "client";
Message?: string;
}
export namespace NotUpdatableException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: NotUpdatableException): any => ({
...obj,
});
}
/**
* <p>Cloud Control API has not received a valid response from the resource handler, due to a
* configuration error. This includes issues such as the resource handler returning an invalid
* response, or timing out.</p>
*/
export interface PrivateTypeException extends __SmithyException, $MetadataBearer {
name: "PrivateTypeException";
$fault: "client";
Message?: string;
}
export namespace PrivateTypeException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: PrivateTypeException): any => ({
...obj,
});
}
/**
* <p>The resource is temporarily unavailable to be acted upon. For example, if the resource is
* currently undergoing an operation and cannot be acted upon until that operation is
* finished.</p>
*/
export interface ResourceConflictException extends __SmithyException, $MetadataBearer {
name: "ResourceConflictException";
$fault: "client";
Message?: string;
}
export namespace ResourceConflictException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceConflictException): any => ({
...obj,
});
}
/**
* <p>A resource with the specified identifier cannot be found.</p>
*/
export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer {
name: "ResourceNotFoundException";
$fault: "client";
Message?: string;
}
export namespace ResourceNotFoundException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({
...obj,
});
}
/**
* <p>The resource handler has returned that the downstream service returned an internal error,
* typically with a <code>5XX HTTP</code> status code.</p>
*/
export interface ServiceInternalErrorException extends __SmithyException, $MetadataBearer {
name: "ServiceInternalErrorException";
$fault: "server";
Message?: string;
}
export namespace ServiceInternalErrorException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ServiceInternalErrorException): any => ({
...obj,
});
}
/**
* <p>The resource handler has returned that a non-transient resource limit was reached on the
* service side.</p>
*/
export interface ServiceLimitExceededException extends __SmithyException, $MetadataBearer {
name: "ServiceLimitExceededException";
$fault: "client";
Message?: string;
}
export namespace ServiceLimitExceededException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ServiceLimitExceededException): any => ({
...obj,
});
}
/**
* <p>The request was denied due to request throttling.</p>
*/
export interface ThrottlingException extends __SmithyException, $MetadataBearer {
name: "ThrottlingException";
$fault: "client";
Message?: string;
}
export namespace ThrottlingException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ThrottlingException): any => ({
...obj,
});
}
/**
* <p>The specified extension does not exist in the CloudFormation registry.</p>
*/
export interface TypeNotFoundException extends __SmithyException, $MetadataBearer {
name: "TypeNotFoundException";
$fault: "client";
Message?: string;
}
export namespace TypeNotFoundException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TypeNotFoundException): any => ({
...obj,
});
}
/**
* <p>The specified resource does not support this resource operation.</p>
*/
export interface UnsupportedActionException extends __SmithyException, $MetadataBearer {
name: "UnsupportedActionException";
$fault: "client";
Message?: string;
}
export namespace UnsupportedActionException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UnsupportedActionException): any => ({
...obj,
});
}
export interface DeleteResourceInput {
/**
* <p>The name of the resource type.</p>
*/
TypeName: string | undefined;
/**
* <p>For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version.</p>
*/
TypeVersionId?: string;
/**
* <p>The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the <code>
* <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html#schema-properties-handlers">handlers</a>
* </code> section of the <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html">resource type definition schema</a>.</p>
* <p>If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations.html#resource-operations-permissions">Specifying credentials</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
RoleArn?: string;
/**
* <p>A unique identifier to ensure the idempotency of the resource request. As a best practice, specify this token to ensure idempotency, so that Amazon Web Services Cloud Control API can accurately distinguish between request retries and new resource requests. You might retry a resource request to ensure that it was successfully received.</p>
* <p>A client token is valid for 36 hours once used. After that, a resource request with the same client token is treated as a new request.</p>
* <p>If you do not specify a client token, one is generated for inclusion in the request.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations.html#resource-operations-idempotency">Ensuring resource operation requests are unique</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
ClientToken?: string;
/**
* <p>The identifier for the resource.</p>
* <p>You can specify the primary identifier, or any secondary identifier defined for the resource type in its resource schema. You can only specify one identifier. Primary identifiers can be specified as a string or JSON; secondary identifiers must be specified as JSON.</p>
* <p>For compound primary identifiers (that is, one that consists of multiple resource properties strung together), to specify the primary identifier as a string, list the property values <i>in the order they are specified</i> in the primary identifier definition, separated by <code>|</code>. </p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-identifier.html">Identifying resources</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
Identifier: string | undefined;
}
export namespace DeleteResourceInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteResourceInput): any => ({
...obj,
});
}
export interface DeleteResourceOutput {
/**
* <p>Represents the current status of the resource deletion request.</p>
* <p>After you have initiated a resource deletion request, you can monitor the progress of your
* request by calling <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/APIReference/API_GetResourceRequestStatus.html">GetResourceRequestStatus</a> using the <code>RequestToken</code> of the
* <code>ProgressEvent</code> returned by <code>DeleteResource</code>.</p>
*/
ProgressEvent?: ProgressEvent;
}
export namespace DeleteResourceOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteResourceOutput): any => ({
...obj,
...(obj.ProgressEvent && { ProgressEvent: ProgressEvent.filterSensitiveLog(obj.ProgressEvent) }),
});
}
export interface GetResourceInput {
/**
* <p>The name of the resource type.</p>
*/
TypeName: string | undefined;
/**
* <p>For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version.</p>
*/
TypeVersionId?: string;
/**
* <p>The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the <code>
* <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html#schema-properties-handlers">handlers</a>
* </code> section of the <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html">resource type definition schema</a>.</p>
* <p>If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations.html#resource-operations-permissions">Specifying credentials</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
RoleArn?: string;
/**
* <p>The identifier for the resource.</p>
* <p>You can specify the primary identifier, or any secondary identifier defined for the resource type in its resource schema. You can only specify one identifier. Primary identifiers can be specified as a string or JSON; secondary identifiers must be specified as JSON.</p>
* <p>For compound primary identifiers (that is, one that consists of multiple resource properties strung together), to specify the primary identifier as a string, list the property values <i>in the order they are specified</i> in the primary identifier definition, separated by <code>|</code>. </p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-identifier.html">Identifying resources</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
Identifier: string | undefined;
}
export namespace GetResourceInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetResourceInput): any => ({
...obj,
});
}
/**
* <p>Represents information about a provisioned resource.</p>
*/
export interface ResourceDescription {
/**
* <p>The primary identifier for the resource.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-identifier.html">Identifying
* resources</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
Identifier?: string;
/**
* <p>A list of the resource properties and their current values.</p>
*/
Properties?: string;
}
export namespace ResourceDescription {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceDescription): any => ({
...obj,
...(obj.Properties && { Properties: SENSITIVE_STRING }),
});
}
export interface GetResourceOutput {
/**
* <p>The name of the resource type.</p>
*/
TypeName?: string;
/**
* <p>Represents information about a provisioned resource.</p>
*/
ResourceDescription?: ResourceDescription;
}
export namespace GetResourceOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetResourceOutput): any => ({
...obj,
...(obj.ResourceDescription && {
ResourceDescription: ResourceDescription.filterSensitiveLog(obj.ResourceDescription),
}),
});
}
export interface GetResourceRequestStatusInput {
/**
* <p>A unique token used to track the progress of the resource operation request.</p>
* <p>Request tokens are included in the <code>ProgressEvent</code> type returned by a resource
* operation request.</p>
*/
RequestToken: string | undefined;
}
export namespace GetResourceRequestStatusInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetResourceRequestStatusInput): any => ({
...obj,
});
}
export interface GetResourceRequestStatusOutput {
/**
* <p>Represents the current status of the resource operation request.</p>
*/
ProgressEvent?: ProgressEvent;
}
export namespace GetResourceRequestStatusOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetResourceRequestStatusOutput): any => ({
...obj,
...(obj.ProgressEvent && { ProgressEvent: ProgressEvent.filterSensitiveLog(obj.ProgressEvent) }),
});
}
/**
* <p>The filter criteria to use in determining the requests returned.</p>
*/
export interface ResourceRequestStatusFilter {
/**
* <p>The operation types to include in the filter.</p>
*/
Operations?: (Operation | string)[];
/**
* <p>The operation statuses to include in the filter.</p>
* <ul>
* <li>
* <p>
* <code>PENDING</code>: The operation has been requested, but not yet initiated.</p>
* </li>
* <li>
* <p>
* <code>IN_PROGRESS</code>: The operation is currently in progress.</p>
* </li>
* <li>
* <p>
* <code>SUCCESS</code>: The operation has successfully completed.</p>
* </li>
* <li>
* <p>
* <code>FAILED</code>: The operation has failed.</p>
* </li>
* <li>
* <p>
* <code>CANCEL_IN_PROGRESS</code>: The operation is currently in the process of being
* canceled.</p>
* </li>
* <li>
* <p>
* <code>CANCEL_COMPLETE</code>: The operation has been canceled.</p>
* </li>
* </ul>
*/
OperationStatuses?: (OperationStatus | string)[];
}
export namespace ResourceRequestStatusFilter {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceRequestStatusFilter): any => ({
...obj,
});
}
export interface ListResourceRequestsInput {
/**
* <p>The maximum number of results to be returned with a single call. If the number of
* available results exceeds this maximum, the response includes a <code>NextToken</code> value
* that you can assign to the <code>NextToken</code> request parameter to get the next set of
* results.</p>
* <p>The default is <code>20</code>.</p>
*/
MaxResults?: number;
/**
* <p>If the previous paginated request didn't return all of the remaining results, the response object's <code>NextToken</code> parameter value is set to a token. To retrieve the next set of results, call this action again and assign that token to the request object's <code>NextToken</code> parameter. If there are no remaining results, the previous response object's <code>NextToken</code> parameter is set to <code>null</code>.</p>
*/
NextToken?: string;
/**
* <p>The filter criteria to apply to the requests returned.</p>
*/
ResourceRequestStatusFilter?: ResourceRequestStatusFilter;
}
export namespace ListResourceRequestsInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListResourceRequestsInput): any => ({
...obj,
});
}
export interface ListResourceRequestsOutput {
/**
* <p>The requests that match the specified filter criteria.</p>
*/
ResourceRequestStatusSummaries?: ProgressEvent[];
/**
* <p>If the request doesn't return all of the remaining results, <code>NextToken</code> is set to a token. To retrieve the next set of results, call <code>ListResources</code> again and assign that token to the request object's <code>NextToken</code> parameter. If the request returns all results, <code>NextToken</code> is set to null.</p>
*/
NextToken?: string;
}
export namespace ListResourceRequestsOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListResourceRequestsOutput): any => ({
...obj,
...(obj.ResourceRequestStatusSummaries && {
ResourceRequestStatusSummaries: obj.ResourceRequestStatusSummaries.map((item) =>
ProgressEvent.filterSensitiveLog(item)
),
}),
});
}
export interface ListResourcesInput {
/**
* <p>The name of the resource type.</p>
*/
TypeName: string | undefined;
/**
* <p>For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version.</p>
*/
TypeVersionId?: string;
/**
* <p>The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the <code>
* <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html#schema-properties-handlers">handlers</a>
* </code> section of the <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html">resource type definition schema</a>.</p>
* <p>If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations.html#resource-operations-permissions">Specifying credentials</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
RoleArn?: string;
/**
* <p>If the previous paginated request didn't return all of the remaining results, the response object's <code>NextToken</code> parameter value is set to a token. To retrieve the next set of results, call this action again and assign that token to the request object's <code>NextToken</code> parameter. If there are no remaining results, the previous response object's <code>NextToken</code> parameter is set to <code>null</code>.</p>
*/
NextToken?: string;
/**
* <p>The maximum number of results to be returned with a single call. If the number of
* available results exceeds this maximum, the response includes a <code>NextToken</code> value
* that you can assign to the <code>NextToken</code> request parameter to get the next set of
* results.</p>
* <p>The default is <code>20</code>.</p>
*/
MaxResults?: number;
/**
* <p>The resource model to use to select the resources to return.</p>
*/
ResourceModel?: string;
}
export namespace ListResourcesInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListResourcesInput): any => ({
...obj,
...(obj.ResourceModel && { ResourceModel: SENSITIVE_STRING }),
});
}
export interface ListResourcesOutput {
/**
* <p>The name of the resource type.</p>
*/
TypeName?: string;
/**
* <p>Information about the specified resources, including primary identifier and resource
* model.</p>
*/
ResourceDescriptions?: ResourceDescription[];
/**
* <p>If the request doesn't return all of the remaining results, <code>NextToken</code> is set to a token. To retrieve the next set of results, call <code>ListResources</code> again and assign that token to the request object's <code>NextToken</code> parameter. If the request returns all results, <code>NextToken</code> is set to null.</p>
*/
NextToken?: string;
}
export namespace ListResourcesOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListResourcesOutput): any => ({
...obj,
...(obj.ResourceDescriptions && {
ResourceDescriptions: obj.ResourceDescriptions.map((item) => ResourceDescription.filterSensitiveLog(item)),
}),
});
}
export interface UpdateResourceInput {
/**
* <p>The name of the resource type.</p>
*/
TypeName: string | undefined;
/**
* <p>For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version.</p>
*/
TypeVersionId?: string;
/**
* <p>The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the <code>
* <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html#schema-properties-handlers">handlers</a>
* </code> section of the <a href="https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html">resource type definition schema</a>.</p>
* <p>If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations.html#resource-operations-permissions">Specifying credentials</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
RoleArn?: string;
/**
* <p>A unique identifier to ensure the idempotency of the resource request. As a best practice, specify this token to ensure idempotency, so that Amazon Web Services Cloud Control API can accurately distinguish between request retries and new resource requests. You might retry a resource request to ensure that it was successfully received.</p>
* <p>A client token is valid for 36 hours once used. After that, a resource request with the same client token is treated as a new request.</p>
* <p>If you do not specify a client token, one is generated for inclusion in the request.</p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations.html#resource-operations-idempotency">Ensuring resource operation requests are unique</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
ClientToken?: string;
/**
* <p>The identifier for the resource.</p>
* <p>You can specify the primary identifier, or any secondary identifier defined for the resource type in its resource schema. You can only specify one identifier. Primary identifiers can be specified as a string or JSON; secondary identifiers must be specified as JSON.</p>
* <p>For compound primary identifiers (that is, one that consists of multiple resource properties strung together), to specify the primary identifier as a string, list the property values <i>in the order they are specified</i> in the primary identifier definition, separated by <code>|</code>. </p>
* <p>For more information, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-identifier.html">Identifying resources</a> in the <i>Amazon Web Services Cloud Control API User Guide</i>.</p>
*/
Identifier: string | undefined;
/**
* <p>A JavaScript Object Notation (JSON) document listing the patch operations that represent
* the updates to apply to the current resource properties. For details, see <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-update.html#resource-operations-update-patch">Composing the patch document</a> in the <i>Amazon Web Services Cloud Control API User
* Guide</i>.</p>
*/
PatchDocument: string | undefined;
}
export namespace UpdateResourceInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateResourceInput): any => ({
...obj,
...(obj.PatchDocument && { PatchDocument: SENSITIVE_STRING }),
});
}
export interface UpdateResourceOutput {
/**
* <p>Represents the current status of the resource update request.</p>
* <p>Use the <code>RequestToken</code> of the <code>ProgressEvent</code> with <a href="https://docs.aws.amazon.com/cloudcontrolapi/latest/APIReference/API_GetResourceRequestStatus.html">GetResourceRequestStatus</a> to return the current status of a resource operation
* request.</p>
*/
ProgressEvent?: ProgressEvent;
}
export namespace UpdateResourceOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateResourceOutput): any => ({
...obj,
...(obj.ProgressEvent && { ProgressEvent: ProgressEvent.filterSensitiveLog(obj.ProgressEvent) }),
});
} | the_stack |
import {
BasicGetValidParameters,
BasicPutValidParameters,
BasicGetInvalidParameters,
BasicGetEmptyParameters,
BasicGetNullParameters,
BasicGetNotProvidedParameters,
PrimitiveGetIntParameters,
PrimitivePutIntParameters,
PrimitiveGetLongParameters,
PrimitivePutLongParameters,
PrimitiveGetFloatParameters,
PrimitivePutFloatParameters,
PrimitiveGetDoubleParameters,
PrimitivePutDoubleParameters,
PrimitiveGetBoolParameters,
PrimitivePutBoolParameters,
PrimitiveGetStringParameters,
PrimitivePutStringParameters,
PrimitiveGetDateParameters,
PrimitivePutDateParameters,
PrimitiveGetDateTimeParameters,
PrimitivePutDateTimeParameters,
PrimitiveGetDateTimeRfc1123Parameters,
PrimitivePutDateTimeRfc1123Parameters,
PrimitiveGetDurationParameters,
PrimitivePutDurationParameters,
PrimitiveGetByteParameters,
PrimitivePutByteParameters,
ArrayGetValidParameters,
ArrayPutValidParameters,
ArrayGetEmptyParameters,
ArrayPutEmptyParameters,
ArrayGetNotProvidedParameters,
DictionaryGetValidParameters,
DictionaryPutValidParameters,
DictionaryGetEmptyParameters,
DictionaryPutEmptyParameters,
DictionaryGetNullParameters,
DictionaryGetNotProvidedParameters,
InheritanceGetValidParameters,
InheritancePutValidParameters,
PolymorphismGetValidParameters,
PolymorphismPutValidParameters,
PolymorphismGetDotSyntaxParameters,
PolymorphismGetComposedWithDiscriminatorParameters,
PolymorphismGetComposedWithoutDiscriminatorParameters,
PolymorphismGetComplicatedParameters,
PolymorphismPutComplicatedParameters,
PolymorphismPutMissingDiscriminatorParameters,
PolymorphismPutValidMissingRequiredParameters,
PolymorphicrecursiveGetValidParameters,
PolymorphicrecursivePutValidParameters,
ReadonlypropertyGetValidParameters,
ReadonlypropertyPutValidParameters,
FlattencomplexGetValidParameters
} from "./parameters";
import {
BasicGetValid200Response,
BasicGetValiddefaultResponse,
BasicPutValid200Response,
BasicPutValiddefaultResponse,
BasicGetInvalid200Response,
BasicGetInvaliddefaultResponse,
BasicGetEmpty200Response,
BasicGetEmptydefaultResponse,
BasicGetNull200Response,
BasicGetNulldefaultResponse,
BasicGetNotProvided200Response,
BasicGetNotProvideddefaultResponse,
PrimitiveGetInt200Response,
PrimitiveGetIntdefaultResponse,
PrimitivePutInt200Response,
PrimitivePutIntdefaultResponse,
PrimitiveGetLong200Response,
PrimitiveGetLongdefaultResponse,
PrimitivePutLong200Response,
PrimitivePutLongdefaultResponse,
PrimitiveGetFloat200Response,
PrimitiveGetFloatdefaultResponse,
PrimitivePutFloat200Response,
PrimitivePutFloatdefaultResponse,
PrimitiveGetDouble200Response,
PrimitiveGetDoubledefaultResponse,
PrimitivePutDouble200Response,
PrimitivePutDoubledefaultResponse,
PrimitiveGetBool200Response,
PrimitiveGetBooldefaultResponse,
PrimitivePutBool200Response,
PrimitivePutBooldefaultResponse,
PrimitiveGetString200Response,
PrimitiveGetStringdefaultResponse,
PrimitivePutString200Response,
PrimitivePutStringdefaultResponse,
PrimitiveGetDate200Response,
PrimitiveGetDatedefaultResponse,
PrimitivePutDate200Response,
PrimitivePutDatedefaultResponse,
PrimitiveGetDateTime200Response,
PrimitiveGetDateTimedefaultResponse,
PrimitivePutDateTime200Response,
PrimitivePutDateTimedefaultResponse,
PrimitiveGetDateTimeRfc1123200Response,
PrimitiveGetDateTimeRfc1123defaultResponse,
PrimitivePutDateTimeRfc1123200Response,
PrimitivePutDateTimeRfc1123defaultResponse,
PrimitiveGetDuration200Response,
PrimitiveGetDurationdefaultResponse,
PrimitivePutDuration200Response,
PrimitivePutDurationdefaultResponse,
PrimitiveGetByte200Response,
PrimitiveGetBytedefaultResponse,
PrimitivePutByte200Response,
PrimitivePutBytedefaultResponse,
ArrayGetValid200Response,
ArrayGetValiddefaultResponse,
ArrayPutValid200Response,
ArrayPutValiddefaultResponse,
ArrayGetEmpty200Response,
ArrayGetEmptydefaultResponse,
ArrayPutEmpty200Response,
ArrayPutEmptydefaultResponse,
ArrayGetNotProvided200Response,
ArrayGetNotProvideddefaultResponse,
DictionaryGetValid200Response,
DictionaryGetValiddefaultResponse,
DictionaryPutValid200Response,
DictionaryPutValiddefaultResponse,
DictionaryGetEmpty200Response,
DictionaryGetEmptydefaultResponse,
DictionaryPutEmpty200Response,
DictionaryPutEmptydefaultResponse,
DictionaryGetNull200Response,
DictionaryGetNulldefaultResponse,
DictionaryGetNotProvided200Response,
DictionaryGetNotProvideddefaultResponse,
InheritanceGetValid200Response,
InheritanceGetValiddefaultResponse,
InheritancePutValid200Response,
InheritancePutValiddefaultResponse,
PolymorphismGetValid200Response,
PolymorphismGetValiddefaultResponse,
PolymorphismPutValid200Response,
PolymorphismPutValiddefaultResponse,
PolymorphismGetDotSyntax200Response,
PolymorphismGetDotSyntaxdefaultResponse,
PolymorphismGetComposedWithDiscriminator200Response,
PolymorphismGetComposedWithDiscriminatordefaultResponse,
PolymorphismGetComposedWithoutDiscriminator200Response,
PolymorphismGetComposedWithoutDiscriminatordefaultResponse,
PolymorphismGetComplicated200Response,
PolymorphismGetComplicateddefaultResponse,
PolymorphismPutComplicated200Response,
PolymorphismPutComplicateddefaultResponse,
PolymorphismPutMissingDiscriminator200Response,
PolymorphismPutMissingDiscriminatordefaultResponse,
PolymorphismPutValidMissingRequired200Response,
PolymorphismPutValidMissingRequireddefaultResponse,
PolymorphicrecursiveGetValid200Response,
PolymorphicrecursiveGetValiddefaultResponse,
PolymorphicrecursivePutValid200Response,
PolymorphicrecursivePutValiddefaultResponse,
ReadonlypropertyGetValid200Response,
ReadonlypropertyGetValiddefaultResponse,
ReadonlypropertyPutValid200Response,
ReadonlypropertyPutValiddefaultResponse,
FlattencomplexGetValid200Response
} from "./responses";
import { getClient, ClientOptions, Client } from "@azure-rest/core-client";
import "@azure/core-auth";
export interface BasicGetValid {
/** Get complex type {id: 2, name: 'abc', color: 'YELLOW'} */
get(
options?: BasicGetValidParameters
): Promise<BasicGetValid200Response | BasicGetValiddefaultResponse>;
/** Please put {id: 2, name: 'abc', color: 'Magenta'} */
put(
options: BasicPutValidParameters
): Promise<BasicPutValid200Response | BasicPutValiddefaultResponse>;
}
export interface BasicGetInvalid {
/** Get a basic complex type that is invalid for the local strong type */
get(
options?: BasicGetInvalidParameters
): Promise<BasicGetInvalid200Response | BasicGetInvaliddefaultResponse>;
}
export interface BasicGetEmpty {
/** Get a basic complex type that is empty */
get(
options?: BasicGetEmptyParameters
): Promise<BasicGetEmpty200Response | BasicGetEmptydefaultResponse>;
}
export interface BasicGetNull {
/** Get a basic complex type whose properties are null */
get(
options?: BasicGetNullParameters
): Promise<BasicGetNull200Response | BasicGetNulldefaultResponse>;
}
export interface BasicGetNotProvided {
/** Get a basic complex type while the server doesn't provide a response payload */
get(
options?: BasicGetNotProvidedParameters
): Promise<
BasicGetNotProvided200Response | BasicGetNotProvideddefaultResponse
>;
}
export interface PrimitiveGetInt {
/** Get complex types with integer properties */
get(
options?: PrimitiveGetIntParameters
): Promise<PrimitiveGetInt200Response | PrimitiveGetIntdefaultResponse>;
/** Put complex types with integer properties */
put(
options: PrimitivePutIntParameters
): Promise<PrimitivePutInt200Response | PrimitivePutIntdefaultResponse>;
}
export interface PrimitiveGetLong {
/** Get complex types with long properties */
get(
options?: PrimitiveGetLongParameters
): Promise<PrimitiveGetLong200Response | PrimitiveGetLongdefaultResponse>;
/** Put complex types with long properties */
put(
options: PrimitivePutLongParameters
): Promise<PrimitivePutLong200Response | PrimitivePutLongdefaultResponse>;
}
export interface PrimitiveGetFloat {
/** Get complex types with float properties */
get(
options?: PrimitiveGetFloatParameters
): Promise<PrimitiveGetFloat200Response | PrimitiveGetFloatdefaultResponse>;
/** Put complex types with float properties */
put(
options: PrimitivePutFloatParameters
): Promise<PrimitivePutFloat200Response | PrimitivePutFloatdefaultResponse>;
}
export interface PrimitiveGetDouble {
/** Get complex types with double properties */
get(
options?: PrimitiveGetDoubleParameters
): Promise<PrimitiveGetDouble200Response | PrimitiveGetDoubledefaultResponse>;
/** Put complex types with double properties */
put(
options: PrimitivePutDoubleParameters
): Promise<PrimitivePutDouble200Response | PrimitivePutDoubledefaultResponse>;
}
export interface PrimitiveGetBool {
/** Get complex types with bool properties */
get(
options?: PrimitiveGetBoolParameters
): Promise<PrimitiveGetBool200Response | PrimitiveGetBooldefaultResponse>;
/** Put complex types with bool properties */
put(
options: PrimitivePutBoolParameters
): Promise<PrimitivePutBool200Response | PrimitivePutBooldefaultResponse>;
}
export interface PrimitiveGetString {
/** Get complex types with string properties */
get(
options?: PrimitiveGetStringParameters
): Promise<PrimitiveGetString200Response | PrimitiveGetStringdefaultResponse>;
/** Put complex types with string properties */
put(
options: PrimitivePutStringParameters
): Promise<PrimitivePutString200Response | PrimitivePutStringdefaultResponse>;
}
export interface PrimitiveGetDate {
/** Get complex types with date properties */
get(
options?: PrimitiveGetDateParameters
): Promise<PrimitiveGetDate200Response | PrimitiveGetDatedefaultResponse>;
/** Put complex types with date properties */
put(
options: PrimitivePutDateParameters
): Promise<PrimitivePutDate200Response | PrimitivePutDatedefaultResponse>;
}
export interface PrimitiveGetDateTime {
/** Get complex types with datetime properties */
get(
options?: PrimitiveGetDateTimeParameters
): Promise<
PrimitiveGetDateTime200Response | PrimitiveGetDateTimedefaultResponse
>;
/** Put complex types with datetime properties */
put(
options: PrimitivePutDateTimeParameters
): Promise<
PrimitivePutDateTime200Response | PrimitivePutDateTimedefaultResponse
>;
}
export interface PrimitiveGetDateTimeRfc1123 {
/** Get complex types with datetimeRfc1123 properties */
get(
options?: PrimitiveGetDateTimeRfc1123Parameters
): Promise<
| PrimitiveGetDateTimeRfc1123200Response
| PrimitiveGetDateTimeRfc1123defaultResponse
>;
/** Put complex types with datetimeRfc1123 properties */
put(
options: PrimitivePutDateTimeRfc1123Parameters
): Promise<
| PrimitivePutDateTimeRfc1123200Response
| PrimitivePutDateTimeRfc1123defaultResponse
>;
}
export interface PrimitiveGetDuration {
/** Get complex types with duration properties */
get(
options?: PrimitiveGetDurationParameters
): Promise<
PrimitiveGetDuration200Response | PrimitiveGetDurationdefaultResponse
>;
/** Put complex types with duration properties */
put(
options: PrimitivePutDurationParameters
): Promise<
PrimitivePutDuration200Response | PrimitivePutDurationdefaultResponse
>;
}
export interface PrimitiveGetByte {
/** Get complex types with byte properties */
get(
options?: PrimitiveGetByteParameters
): Promise<PrimitiveGetByte200Response | PrimitiveGetBytedefaultResponse>;
/** Put complex types with byte properties */
put(
options: PrimitivePutByteParameters
): Promise<PrimitivePutByte200Response | PrimitivePutBytedefaultResponse>;
}
export interface ArrayGetValid {
/** Get complex types with array property */
get(
options?: ArrayGetValidParameters
): Promise<ArrayGetValid200Response | ArrayGetValiddefaultResponse>;
/** Put complex types with array property */
put(
options: ArrayPutValidParameters
): Promise<ArrayPutValid200Response | ArrayPutValiddefaultResponse>;
}
export interface ArrayGetEmpty {
/** Get complex types with array property which is empty */
get(
options?: ArrayGetEmptyParameters
): Promise<ArrayGetEmpty200Response | ArrayGetEmptydefaultResponse>;
/** Put complex types with array property which is empty */
put(
options: ArrayPutEmptyParameters
): Promise<ArrayPutEmpty200Response | ArrayPutEmptydefaultResponse>;
}
export interface ArrayGetNotProvided {
/** Get complex types with array property while server doesn't provide a response payload */
get(
options?: ArrayGetNotProvidedParameters
): Promise<
ArrayGetNotProvided200Response | ArrayGetNotProvideddefaultResponse
>;
}
export interface DictionaryGetValid {
/** Get complex types with dictionary property */
get(
options?: DictionaryGetValidParameters
): Promise<DictionaryGetValid200Response | DictionaryGetValiddefaultResponse>;
/** Put complex types with dictionary property */
put(
options: DictionaryPutValidParameters
): Promise<DictionaryPutValid200Response | DictionaryPutValiddefaultResponse>;
}
export interface DictionaryGetEmpty {
/** Get complex types with dictionary property which is empty */
get(
options?: DictionaryGetEmptyParameters
): Promise<DictionaryGetEmpty200Response | DictionaryGetEmptydefaultResponse>;
/** Put complex types with dictionary property which is empty */
put(
options: DictionaryPutEmptyParameters
): Promise<DictionaryPutEmpty200Response | DictionaryPutEmptydefaultResponse>;
}
export interface DictionaryGetNull {
/** Get complex types with dictionary property which is null */
get(
options?: DictionaryGetNullParameters
): Promise<DictionaryGetNull200Response | DictionaryGetNulldefaultResponse>;
}
export interface DictionaryGetNotProvided {
/** Get complex types with dictionary property while server doesn't provide a response payload */
get(
options?: DictionaryGetNotProvidedParameters
): Promise<
| DictionaryGetNotProvided200Response
| DictionaryGetNotProvideddefaultResponse
>;
}
export interface InheritanceGetValid {
/** Get complex types that extend others */
get(
options?: InheritanceGetValidParameters
): Promise<
InheritanceGetValid200Response | InheritanceGetValiddefaultResponse
>;
/** Put complex types that extend others */
put(
options: InheritancePutValidParameters
): Promise<
InheritancePutValid200Response | InheritancePutValiddefaultResponse
>;
}
export interface PolymorphismGetValid {
/** Get complex types that are polymorphic */
get(
options?: PolymorphismGetValidParameters
): Promise<
PolymorphismGetValid200Response | PolymorphismGetValiddefaultResponse
>;
/** Put complex types that are polymorphic */
put(
options: PolymorphismPutValidParameters
): Promise<
PolymorphismPutValid200Response | PolymorphismPutValiddefaultResponse
>;
}
export interface PolymorphismGetDotSyntax {
/** Get complex types that are polymorphic, JSON key contains a dot */
get(
options?: PolymorphismGetDotSyntaxParameters
): Promise<
| PolymorphismGetDotSyntax200Response
| PolymorphismGetDotSyntaxdefaultResponse
>;
}
export interface PolymorphismGetComposedWithDiscriminator {
/** Get complex object composing a polymorphic scalar property and array property with polymorphic element type, with discriminator specified. Deserialization must NOT fail and use the discriminator type specified on the wire. */
get(
options?: PolymorphismGetComposedWithDiscriminatorParameters
): Promise<
| PolymorphismGetComposedWithDiscriminator200Response
| PolymorphismGetComposedWithDiscriminatordefaultResponse
>;
}
export interface PolymorphismGetComposedWithoutDiscriminator {
/** Get complex object composing a polymorphic scalar property and array property with polymorphic element type, without discriminator specified on wire. Deserialization must NOT fail and use the explicit type of the property. */
get(
options?: PolymorphismGetComposedWithoutDiscriminatorParameters
): Promise<
| PolymorphismGetComposedWithoutDiscriminator200Response
| PolymorphismGetComposedWithoutDiscriminatordefaultResponse
>;
}
export interface PolymorphismGetComplicated {
/** Get complex types that are polymorphic, but not at the root of the hierarchy; also have additional properties */
get(
options?: PolymorphismGetComplicatedParameters
): Promise<
| PolymorphismGetComplicated200Response
| PolymorphismGetComplicateddefaultResponse
>;
/** Put complex types that are polymorphic, but not at the root of the hierarchy; also have additional properties */
put(
options: PolymorphismPutComplicatedParameters
): Promise<
| PolymorphismPutComplicated200Response
| PolymorphismPutComplicateddefaultResponse
>;
}
export interface PolymorphismPutMissingDiscriminator {
/** Put complex types that are polymorphic, omitting the discriminator */
put(
options: PolymorphismPutMissingDiscriminatorParameters
): Promise<
| PolymorphismPutMissingDiscriminator200Response
| PolymorphismPutMissingDiscriminatordefaultResponse
>;
}
export interface PolymorphismPutValidMissingRequired {
/** Put complex types that are polymorphic, attempting to omit required 'birthday' field - the request should not be allowed from the client */
put(
options: PolymorphismPutValidMissingRequiredParameters
): Promise<
| PolymorphismPutValidMissingRequired200Response
| PolymorphismPutValidMissingRequireddefaultResponse
>;
}
export interface PolymorphicrecursiveGetValid {
/** Get complex types that are polymorphic and have recursive references */
get(
options?: PolymorphicrecursiveGetValidParameters
): Promise<
| PolymorphicrecursiveGetValid200Response
| PolymorphicrecursiveGetValiddefaultResponse
>;
/** Put complex types that are polymorphic and have recursive references */
put(
options: PolymorphicrecursivePutValidParameters
): Promise<
| PolymorphicrecursivePutValid200Response
| PolymorphicrecursivePutValiddefaultResponse
>;
}
export interface ReadonlypropertyGetValid {
/** Get complex types that have readonly properties */
get(
options?: ReadonlypropertyGetValidParameters
): Promise<
| ReadonlypropertyGetValid200Response
| ReadonlypropertyGetValiddefaultResponse
>;
/** Put complex types that have readonly properties */
put(
options: ReadonlypropertyPutValidParameters
): Promise<
| ReadonlypropertyPutValid200Response
| ReadonlypropertyPutValiddefaultResponse
>;
}
export interface FlattencomplexGetValid {
get(
options?: FlattencomplexGetValidParameters
): Promise<FlattencomplexGetValid200Response>;
}
export interface Routes {
/** Resource for '/complex/basic/valid' has methods for the following verbs: get, put */
(path: "/complex/basic/valid"): BasicGetValid;
/** Resource for '/complex/basic/invalid' has methods for the following verbs: get */
(path: "/complex/basic/invalid"): BasicGetInvalid;
/** Resource for '/complex/basic/empty' has methods for the following verbs: get */
(path: "/complex/basic/empty"): BasicGetEmpty;
/** Resource for '/complex/basic/null' has methods for the following verbs: get */
(path: "/complex/basic/null"): BasicGetNull;
/** Resource for '/complex/basic/notprovided' has methods for the following verbs: get */
(path: "/complex/basic/notprovided"): BasicGetNotProvided;
/** Resource for '/complex/primitive/integer' has methods for the following verbs: get, put */
(path: "/complex/primitive/integer"): PrimitiveGetInt;
/** Resource for '/complex/primitive/long' has methods for the following verbs: get, put */
(path: "/complex/primitive/long"): PrimitiveGetLong;
/** Resource for '/complex/primitive/float' has methods for the following verbs: get, put */
(path: "/complex/primitive/float"): PrimitiveGetFloat;
/** Resource for '/complex/primitive/double' has methods for the following verbs: get, put */
(path: "/complex/primitive/double"): PrimitiveGetDouble;
/** Resource for '/complex/primitive/bool' has methods for the following verbs: get, put */
(path: "/complex/primitive/bool"): PrimitiveGetBool;
/** Resource for '/complex/primitive/string' has methods for the following verbs: get, put */
(path: "/complex/primitive/string"): PrimitiveGetString;
/** Resource for '/complex/primitive/date' has methods for the following verbs: get, put */
(path: "/complex/primitive/date"): PrimitiveGetDate;
/** Resource for '/complex/primitive/datetime' has methods for the following verbs: get, put */
(path: "/complex/primitive/datetime"): PrimitiveGetDateTime;
/** Resource for '/complex/primitive/datetimerfc1123' has methods for the following verbs: get, put */
(path: "/complex/primitive/datetimerfc1123"): PrimitiveGetDateTimeRfc1123;
/** Resource for '/complex/primitive/duration' has methods for the following verbs: get, put */
(path: "/complex/primitive/duration"): PrimitiveGetDuration;
/** Resource for '/complex/primitive/byte' has methods for the following verbs: get, put */
(path: "/complex/primitive/byte"): PrimitiveGetByte;
/** Resource for '/complex/array/valid' has methods for the following verbs: get, put */
(path: "/complex/array/valid"): ArrayGetValid;
/** Resource for '/complex/array/empty' has methods for the following verbs: get, put */
(path: "/complex/array/empty"): ArrayGetEmpty;
/** Resource for '/complex/array/notprovided' has methods for the following verbs: get */
(path: "/complex/array/notprovided"): ArrayGetNotProvided;
/** Resource for '/complex/dictionary/typed/valid' has methods for the following verbs: get, put */
(path: "/complex/dictionary/typed/valid"): DictionaryGetValid;
/** Resource for '/complex/dictionary/typed/empty' has methods for the following verbs: get, put */
(path: "/complex/dictionary/typed/empty"): DictionaryGetEmpty;
/** Resource for '/complex/dictionary/typed/null' has methods for the following verbs: get */
(path: "/complex/dictionary/typed/null"): DictionaryGetNull;
/** Resource for '/complex/dictionary/typed/notprovided' has methods for the following verbs: get */
(path: "/complex/dictionary/typed/notprovided"): DictionaryGetNotProvided;
/** Resource for '/complex/inheritance/valid' has methods for the following verbs: get, put */
(path: "/complex/inheritance/valid"): InheritanceGetValid;
/** Resource for '/complex/polymorphism/valid' has methods for the following verbs: get, put */
(path: "/complex/polymorphism/valid"): PolymorphismGetValid;
/** Resource for '/complex/polymorphism/dotsyntax' has methods for the following verbs: get */
(path: "/complex/polymorphism/dotsyntax"): PolymorphismGetDotSyntax;
/** Resource for '/complex/polymorphism/composedWithDiscriminator' has methods for the following verbs: get */
(
path: "/complex/polymorphism/composedWithDiscriminator"
): PolymorphismGetComposedWithDiscriminator;
/** Resource for '/complex/polymorphism/composedWithoutDiscriminator' has methods for the following verbs: get */
(
path: "/complex/polymorphism/composedWithoutDiscriminator"
): PolymorphismGetComposedWithoutDiscriminator;
/** Resource for '/complex/polymorphism/complicated' has methods for the following verbs: get, put */
(path: "/complex/polymorphism/complicated"): PolymorphismGetComplicated;
/** Resource for '/complex/polymorphism/missingdiscriminator' has methods for the following verbs: put */
(
path: "/complex/polymorphism/missingdiscriminator"
): PolymorphismPutMissingDiscriminator;
/** Resource for '/complex/polymorphism/missingrequired/invalid' has methods for the following verbs: put */
(
path: "/complex/polymorphism/missingrequired/invalid"
): PolymorphismPutValidMissingRequired;
/** Resource for '/complex/polymorphicrecursive/valid' has methods for the following verbs: get, put */
(path: "/complex/polymorphicrecursive/valid"): PolymorphicrecursiveGetValid;
/** Resource for '/complex/readonlyproperty/valid' has methods for the following verbs: get, put */
(path: "/complex/readonlyproperty/valid"): ReadonlypropertyGetValid;
/** Resource for '/complex/flatten/valid' has methods for the following verbs: get */
(path: "/complex/flatten/valid"): FlattencomplexGetValid;
}
export type BodyComplexRestClientRestClient = Client & {
path: Routes;
};
export default function BodyComplexRestClient(
options: ClientOptions = {}
): BodyComplexRestClientRestClient {
const baseUrl = options.baseUrl ?? "http://localhost:3000";
options.apiVersion = options.apiVersion ?? "2016-02-29";
const client = getClient(baseUrl, options) as BodyComplexRestClientRestClient;
return client;
} | the_stack |
import * as assert from "assert";
import { Pool } from "pg";
import { cronItemMatches } from "./cronMatcher";
import { parseCrontab } from "./crontab";
import defer from "./deferred";
import getCronItems from "./getCronItems";
import {
Cron,
CronJob,
JobAndCronIdentifier,
KnownCrontab,
ParsedCronItem,
RunnerOptions,
TimestampDigest,
WorkerEvents,
} from "./interfaces";
import { processSharedOptions, Releasers } from "./lib";
interface CronRequirements {
pgPool: Pool;
events: WorkerEvents;
}
/**
* This function looks through all the cron items we have (e.g. from our
* crontab file) and compares them to the items we already know about. If the
* item is not previously know, we add it to the list `unknownIdentifiers` so
* that it can be recorded in the database (i.e. it will be "known" from now
* on). If the item was previously known, we add an entry to
* `backfillItemsAndDates` indicating the `item` and earliest time
* (`notBefore`) that a backfill should operate from. This is later compared
* to the configuration to see how much backfilling to do.
*/
function getBackfillAndUnknownItems(
parsedCronItems: ParsedCronItem[],
knownCrontabs: KnownCrontab[],
) {
const backfillItemsAndDates: Array<{
item: ParsedCronItem;
notBefore: Date;
}> = [];
const unknownIdentifiers: string[] = [];
for (const item of parsedCronItems) {
const known = knownCrontabs.find(
(record) => record.identifier === item.identifier,
);
if (known) {
// We only back-fill for tasks we already know about
const notBefore = known.last_execution || known.known_since;
backfillItemsAndDates.push({
item,
notBefore,
});
} else {
unknownIdentifiers.push(item.identifier);
}
}
return { backfillItemsAndDates, unknownIdentifiers };
}
/**
* Rounds the incoming date to the nearest minute (either rounding up or down).
* Tagged "unsafe" because it mutates the argument, this is desired for
* performance but may be unexpected.
*/
function unsafeRoundToMinute(ts: Date, roundUp = false): Date {
if (ts.getUTCSeconds() > 0 || ts.getUTCMilliseconds() > 0) {
ts.setUTCSeconds(0);
ts.setUTCMilliseconds(0);
if (roundUp) {
ts.setUTCMinutes(ts.getUTCMinutes() + 1);
}
}
return ts;
}
function makeJobForItem(
item: ParsedCronItem,
ts: string,
backfilled = false,
): CronJob {
return {
task: item.task,
payload: {
...item.payload,
_cron: {
ts,
backfilled,
},
},
queueName: item.options.queueName,
runAt: ts,
maxAttempts: item.options.maxAttempts,
priority: item.options.priority,
};
}
/**
* Schedules a list of cron jobs all due at the same timestamp. Jobs that were
* already scheduled (e.g. via a different Worker instance) will be skipped
* automatically.
*/
async function scheduleCronJobs(
pgPool: Pool,
escapedWorkerSchema: string,
jobsAndIdentifiers: JobAndCronIdentifier[],
ts: string,
useNodeTime: boolean,
) {
// Note that `identifier` is guaranteed to be unique for every record
// in `specs`.
await pgPool.query(
`
with specs as (
select
index,
(json->>'identifier')::text as identifier,
((json->'job')->>'task')::text as task,
((json->'job')->'payload')::json as payload,
((json->'job')->>'queueName')::text as queue_name,
((json->'job')->>'runAt')::timestamptz as run_at,
((json->'job')->>'maxAttempts')::int as max_attempts,
((json->'job')->>'priority')::int as priority
from json_array_elements($1::json) with ordinality AS entries (json, index)
),
locks as (
insert into ${escapedWorkerSchema}.known_crontabs (identifier, known_since, last_execution)
select
specs.identifier,
$2 as known_since,
$2 as last_execution
from specs
on conflict (identifier)
do update set last_execution = excluded.last_execution
where (known_crontabs.last_execution is null or known_crontabs.last_execution < excluded.last_execution)
returning known_crontabs.identifier
)
select
${escapedWorkerSchema}.add_job(
specs.task,
specs.payload,
specs.queue_name,
coalesce(specs.run_at, $3::timestamptz, now()),
specs.max_attempts,
null, -- job key
specs.priority
)
from specs
inner join locks on (locks.identifier = specs.identifier)
order by specs.index asc
`,
[
JSON.stringify(jobsAndIdentifiers),
ts,
useNodeTime ? new Date().toISOString() : null,
],
);
}
/**
* Marks any previously unknown crontab identifiers as now being known. Then
* performs backfilling on any crontab tasks that need it.
*/
async function registerAndBackfillItems(
{ pgPool, events, cron }: { pgPool: Pool; events: WorkerEvents; cron: Cron },
escapedWorkerSchema: string,
parsedCronItems: ParsedCronItem[],
startTime: Date,
useNodeTime: boolean,
) {
// First, scan the DB to get our starting point.
const { rows } = await pgPool.query<KnownCrontab>(
`SELECT * FROM ${escapedWorkerSchema}.known_crontabs`,
);
const {
backfillItemsAndDates,
unknownIdentifiers,
} = getBackfillAndUnknownItems(parsedCronItems, rows);
if (unknownIdentifiers.length) {
// They're known now.
await pgPool.query(
`
INSERT INTO ${escapedWorkerSchema}.known_crontabs (identifier, known_since)
SELECT identifier, $2
FROM unnest($1::text[]) AS unnest (identifier)
ON CONFLICT DO NOTHING
`,
[unknownIdentifiers, startTime.toISOString()],
);
}
// If any jobs are overdue, trigger them.
// NOTE: this is not the fastest algorithm, we can definitely optimise this later.
// First find out the largest backfill period:
const largestBackfill = parsedCronItems.reduce(
(largest, item) => Math.max(item.options.backfillPeriod, largest),
0,
);
// Then go back this period in time and fill forward from there.
if (largestBackfill > 0) {
// Unsafe because we mutate it during the loop (for performance); be sure
// to take a copy of it (or convert to string) when used in places where
// later mutation would cause issues.
const unsafeTs = new Date(+startTime - largestBackfill);
// Round up to the nearest minute.
unsafeRoundToMinute(unsafeTs, true);
// We're `await`-ing inside this loop: serialization is desired. If we were
// to parallelize this (e.g. with `Promise.all`) then race conditions could
// mean that backfilling of earlier tasks is skipped because
// known_crontabs.last_execution may be advanced for a later backfill
// before an earlier backfill occurs.
while (unsafeTs < startTime) {
const timeAgo = +startTime - +unsafeTs;
// Note: `ts` and `digest` are both safe.
const ts = unsafeTs.toISOString();
const digest = digestTimestamp(unsafeTs);
// The identifiers in this array are guaranteed to be unique, since cron
// items are guaranteed to have unique identifiers.
const itemsToBackfill: Array<JobAndCronIdentifier> = [];
// See if anything needs backfilling for this timestamp
for (const { item, notBefore } of backfillItemsAndDates) {
if (
item.options.backfillPeriod >= timeAgo &&
unsafeTs >= notBefore &&
cronItemMatches(item, digest)
) {
itemsToBackfill.push({
identifier: item.identifier,
job: makeJobForItem(item, ts, true),
});
}
}
if (itemsToBackfill.length) {
// We're currently backfilling once per timestamp (rather than
// gathering them all together and doing a single statement) due to
// the way the last_execution column of the known_crontabs table works.
// At this time it's not expected that backfilling will be sufficiently
// expensive to justify optimising this further.
events.emit("cron:backfill", {
cron,
itemsToBackfill,
timestamp: ts,
});
await scheduleCronJobs(
pgPool,
escapedWorkerSchema,
itemsToBackfill,
ts,
useNodeTime,
);
}
// Advance our counter (or risk infinite loop!).
unsafeTs.setUTCMinutes(unsafeTs.getUTCMinutes() + 1);
}
}
}
/** One minute in milliseconds */
const ONE_MINUTE = 60 * 1000;
/**
* Executes our scheduled jobs as required.
*
* This is not currently intended for usage directly; use `run` instead.
*
* @internal
*
* @param options - the common options
* @param parsedCronItems - MUTABLE list of _parsed_ cron items to monitor. Do not assume this is static.
* @param requirements - the helpers that this task needs
*/
export const runCron = (
options: RunnerOptions,
parsedCronItems: ParsedCronItem[],
requirements: CronRequirements,
): Cron => {
const { pgPool } = requirements;
const {
logger,
escapedWorkerSchema,
events,
useNodeTime,
} = processSharedOptions(options);
const promise = defer();
let released = false;
let timeout: NodeJS.Timer | null = null;
let stopCalled = false;
function stop(e?: Error) {
if (!stopCalled) {
stopCalled = true;
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
if (e) {
promise.reject(e);
} else {
promise.resolve();
}
} else {
logger.error(
"Graphile Worker internal bug in src/cron.ts: calling `stop()` more than once shouldn't be possible. Please report this.",
);
}
}
async function cronMain() {
if (released) {
return stop();
}
const start = new Date();
events.emit("cron:starting", { cron: this, start });
// We must backfill BEFORE scheduling any new jobs otherwise backfill won't
// work due to known_crontabs.last_execution having been updated.
await registerAndBackfillItems(
{ pgPool, events, cron: this },
escapedWorkerSchema,
parsedCronItems,
new Date(+start),
useNodeTime,
);
events.emit("cron:started", { cron: this, start });
if (released) {
return stop();
}
// The backfill may have taken a moment, we should continue from where the
// worker started and catch up as quickly as we can. This does **NOT**
// count as a backfill.
let nextTimestamp = unsafeRoundToMinute(new Date(+start), true);
const scheduleNextLoop = () => {
if (released) {
return stop();
}
// + 1 millisecond to try and ensure this happens in the next minute
// rather than at the end of the previous.
timeout = setTimeout(() => {
timeout = null;
loop();
}, Math.max(+nextTimestamp - Date.now() + 1, 1));
};
async function loop() {
try {
if (released) {
return stop();
}
// THIS MUST COME BEFORE nextTimestamp IS MUTATED
const digest = digestTimestamp(nextTimestamp);
const ts = nextTimestamp.toISOString();
const expectedTimestamp = +nextTimestamp;
// With seconds and milliseconds
const currentTimestamp = Date.now();
// Round to beginning of current minute; should match expectedTimestamp
const roundedCurrentTimestamp =
currentTimestamp - (currentTimestamp % ONE_MINUTE);
/*
* In the event of clock skew, or overloaded runloop causing delays,
* it's possible that expectedTimestamp and roundedCurrentTimestamp
* might not match up. If we've not hit expectedTimestamp yet, we
* should just reschedule. If we've gone past expectedTimestamp then we
* should do as much work as is necessary to catch up, ignoring
* backfill since this is never expected to be a large period.
*/
if (roundedCurrentTimestamp < expectedTimestamp) {
logger.debug(
`Graphile Worker Cron fired ${(
(expectedTimestamp - currentTimestamp) /
1000
).toFixed(3)}s too early (clock skew?); rescheduling`,
{
expectedTimestamp,
currentTimestamp,
},
);
events.emit("cron:prematureTimer", {
cron: this,
currentTimestamp,
expectedTimestamp,
});
// NOTE: we must NOT have mutated nextTimestamp before here in `loop()`.
scheduleNextLoop();
return;
} else if (roundedCurrentTimestamp > expectedTimestamp) {
logger.debug(
`Graphile Worker Cron fired too late; catching up (${Math.floor(
(currentTimestamp - expectedTimestamp) / ONE_MINUTE,
)}m${Math.floor(
((currentTimestamp - expectedTimestamp) % ONE_MINUTE) / 1000,
)}s behind)`,
);
events.emit("cron:overdueTimer", {
cron: this,
currentTimestamp,
expectedTimestamp,
});
}
// The identifiers in this array are guaranteed to be unique.
const jobsAndIdentifiers: Array<JobAndCronIdentifier> = [];
// Gather the relevant jobs
for (const item of parsedCronItems) {
if (cronItemMatches(item, digest)) {
jobsAndIdentifiers.push({
identifier: item.identifier,
job: makeJobForItem(item, ts),
});
}
}
// Finally actually run the jobs.
if (jobsAndIdentifiers.length) {
events.emit("cron:schedule", {
cron: this,
timestamp: expectedTimestamp,
jobsAndIdentifiers,
});
await scheduleCronJobs(
pgPool,
escapedWorkerSchema,
jobsAndIdentifiers,
ts,
useNodeTime,
);
events.emit("cron:scheduled", {
cron: this,
timestamp: expectedTimestamp,
jobsAndIdentifiers,
});
if (released) {
return stop();
}
}
// MUTATE nextTimestamp: advance by a minute ready for the next run.
nextTimestamp.setUTCMinutes(nextTimestamp.getUTCMinutes() + 1);
// This must come at the very end (otherwise we might accidentally skip
// timestamps on error).
scheduleNextLoop();
} catch (e) {
// If something goes wrong; abort. The calling code should re-schedule
// which will re-trigger the backfilling code.
return stop(e);
}
}
scheduleNextLoop();
}
cronMain().catch(stop);
return {
release() {
if (!released) {
released = true;
if (timeout) {
// Next loop is queued; lets cancel it early
stop();
}
}
return promise;
},
promise,
};
};
export async function getParsedCronItemsFromOptions(
options: RunnerOptions,
releasers: Releasers,
): Promise<Array<ParsedCronItem>> {
const { crontabFile, parsedCronItems, crontab } = options;
if (!crontabFile && !parsedCronItems && !crontab) {
return [];
}
if (crontab) {
assert(
!crontabFile,
"`crontab` and `crontabFile` must not be set at the same time.",
);
assert(
!parsedCronItems,
"`crontab` and `parsedCronItems` must not be set at the same time.",
);
return parseCrontab(crontab);
} else if (crontabFile) {
assert(
!parsedCronItems,
"`crontabFile` and `parsedCronItems` must not be set at the same time.",
);
const watchedCronItems = await getCronItems(options, crontabFile, false);
releasers.push(() => watchedCronItems.release());
return watchedCronItems.items;
} else {
assert(parsedCronItems != null, "Expected `parsedCronItems` to be set.");
// Basic check to ensure that users remembered to call
// `parseCronItems`/`parseCrontab`; not intended to be a full check, just a
// quick one to catch the obvious errors. Keep in mind that
// `parsedCronItems` is mutable so it may be changed later to contain more
// entries; we can't keep performing these checks everywhere for
// performance reasons.
assert(
Array.isArray(parsedCronItems),
"Expected `parsedCronItems` to be an array; you must use a helper e.g. `parseCrontab()` or `parseCronItems()` to produce this value.",
);
const firstItem = parsedCronItems[0];
if (firstItem) {
if (
!Array.isArray(firstItem.minutes) ||
!Array.isArray(firstItem.hours) ||
!Array.isArray(firstItem.dates) ||
!Array.isArray(firstItem.months) ||
!Array.isArray(firstItem.dows)
) {
throw new Error(
"Invalid `parsedCronItems`; you must use a helper e.g. `parseCrontab()` or `parseCronItems()` to produce this value.",
);
}
}
return parsedCronItems;
}
}
/**
* Digests a timestamp into its min/hour/date/month/dow components that are
* needed for cron matching.
*
* WARNING: the timestamp passed into this function might be mutated later, so
* **do not memoize** using the value itself. If memoization is necessary, it
* could be done using `+ts` as the key.
*/
function digestTimestamp(ts: Date): TimestampDigest {
const min = ts.getUTCMinutes();
const hour = ts.getUTCHours();
const date = ts.getUTCDate();
const month = ts.getUTCMonth() + 1;
const dow = ts.getUTCDay();
return { min, hour, date, month, dow };
} | the_stack |
import type { ComponentInterface } from '@stencil/core';
import { Component, Element, Host, Prop, State, h } from '@stencil/core';
import { chevronDown } from 'ionicons/icons';
import { config } from '../../global/config';
import { getIonMode } from '../../global/ionic-global';
import { addEventListener, getElementRoot, raf, removeEventListener, transitionEndAsync } from '../../utils/helpers';
const enum AccordionState {
Collapsed = 1 << 0,
Collapsing = 1 << 1,
Expanded = 1 << 2,
Expanding = 1 << 3,
}
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot header - Content is placed at the top and is used to
* expand or collapse the accordion item.
* @slot content - Content is placed below the header and is
* shown or hidden based on expanded state.
*
* @part header - The wrapper element for the header slot.
* @part content - The wrapper element for the content slot.
* @part expanded - The expanded element. Can be used in combination
* with the `header` and `content` parts (i.e. `::part(header expanded)`).
*/
@Component({
tag: 'ion-accordion',
styleUrls: {
ios: 'accordion.ios.scss',
md: 'accordion.md.scss',
},
shadow: {
delegatesFocus: true,
},
})
export class Accordion implements ComponentInterface {
private accordionGroupEl?: HTMLIonAccordionGroupElement | null;
private updateListener = () => this.updateState(false);
private contentEl: HTMLDivElement | undefined;
private contentElWrapper: HTMLDivElement | undefined;
private headerEl: HTMLDivElement | undefined;
private currentRaf: number | undefined;
@Element() el?: HTMLElement;
@State() state: AccordionState = AccordionState.Collapsed;
@State() isNext = false;
@State() isPrevious = false;
/**
* The value of the accordion. Defaults to an autogenerated
* value.
*/
@Prop() value = `ion-accordion-${accordionIds++}`;
/**
* If `true`, the accordion cannot be interacted with.
*/
@Prop() disabled = false;
/**
* If `true`, the accordion cannot be interacted with,
* but does not alter the opacity.
*/
@Prop() readonly = false;
/**
* The toggle icon to use. This icon will be
* rotated when the accordion is expanded
* or collapsed.
*/
@Prop() toggleIcon = chevronDown;
/**
* The slot inside of `ion-item` to
* place the toggle icon. Defaults to `'end'`.
*/
@Prop() toggleIconSlot: 'start' | 'end' = 'end';
connectedCallback() {
const accordionGroupEl = (this.accordionGroupEl = this.el?.closest('ion-accordion-group'));
if (accordionGroupEl) {
this.updateState(true);
addEventListener(accordionGroupEl, 'ionChange', this.updateListener);
}
}
disconnectedCallback() {
const accordionGroupEl = this.accordionGroupEl;
if (accordionGroupEl) {
removeEventListener(accordionGroupEl, 'ionChange', this.updateListener);
}
}
componentDidLoad() {
this.setItemDefaults();
this.slotToggleIcon();
/**
* We need to wait a tick because we
* just set ionItem.button = true and
* the button has not have been rendered yet.
*/
raf(() => {
/**
* Set aria label on button inside of ion-item
* once the inner content has been rendered.
*/
const expanded = this.state === AccordionState.Expanded || this.state === AccordionState.Expanding;
this.setAria(expanded);
});
}
private setItemDefaults = () => {
const ionItem = this.getSlottedHeaderIonItem();
if (!ionItem) {
return;
}
/**
* For a11y purposes, we make
* the ion-item a button so users
* can tab to it and use keyboard
* navigation to get around.
*/
ionItem.button = true;
ionItem.detail = false;
/**
* By default, the lines in an
* item should be full here, but
* only do that if a user has
* not explicitly overridden them
*/
if (ionItem.lines === undefined) {
ionItem.lines = 'full';
}
};
private getSlottedHeaderIonItem = () => {
const { headerEl } = this;
if (!headerEl) {
return;
}
/**
* Get the first ion-item
* slotted in the header slot
*/
const slot = headerEl.querySelector('slot');
if (!slot) {
return;
}
// This is not defined in unit tests
const ionItem =
slot.assignedElements &&
(slot.assignedElements().find((el) => el.tagName === 'ION-ITEM') as HTMLIonItemElement | undefined);
return ionItem;
};
private setAria = (expanded = false) => {
const ionItem = this.getSlottedHeaderIonItem();
if (!ionItem) {
return;
}
/**
* Get the native <button> element inside of
* ion-item because that is what will be focused
*/
const root = getElementRoot(ionItem);
const button = root.querySelector('button');
if (!button) {
return;
}
button.setAttribute('aria-expanded', `${expanded}`);
};
private slotToggleIcon = () => {
const ionItem = this.getSlottedHeaderIonItem();
if (!ionItem) {
return;
}
const { toggleIconSlot, toggleIcon } = this;
/**
* Check if there already is a toggle icon.
* If so, do not add another one.
*/
const existingToggleIcon = ionItem.querySelector('.ion-accordion-toggle-icon');
if (existingToggleIcon) {
return;
}
const iconEl = document.createElement('ion-icon');
iconEl.slot = toggleIconSlot;
iconEl.lazy = false;
iconEl.classList.add('ion-accordion-toggle-icon');
iconEl.icon = toggleIcon;
iconEl.setAttribute('aria-hidden', 'true');
ionItem.appendChild(iconEl);
};
private expandAccordion = (initialUpdate = false) => {
const { contentEl, contentElWrapper } = this;
if (initialUpdate || contentEl === undefined || contentElWrapper === undefined) {
this.state = AccordionState.Expanded;
return;
}
if (this.state === AccordionState.Expanded) {
return;
}
if (this.currentRaf !== undefined) {
cancelAnimationFrame(this.currentRaf);
}
if (this.shouldAnimate()) {
raf(() => {
this.state = AccordionState.Expanding;
this.currentRaf = raf(async () => {
const contentHeight = contentElWrapper.offsetHeight;
const waitForTransition = transitionEndAsync(contentEl, 2000);
contentEl.style.setProperty('max-height', `${contentHeight}px`);
await waitForTransition;
this.state = AccordionState.Expanded;
contentEl.style.removeProperty('max-height');
});
});
} else {
this.state = AccordionState.Expanded;
}
};
private collapseAccordion = (initialUpdate = false) => {
const { contentEl } = this;
if (initialUpdate || contentEl === undefined) {
this.state = AccordionState.Collapsed;
return;
}
if (this.state === AccordionState.Collapsed) {
return;
}
if (this.currentRaf !== undefined) {
cancelAnimationFrame(this.currentRaf);
}
if (this.shouldAnimate()) {
this.currentRaf = raf(async () => {
const contentHeight = contentEl.offsetHeight;
contentEl.style.setProperty('max-height', `${contentHeight}px`);
raf(async () => {
const waitForTransition = transitionEndAsync(contentEl, 2000);
this.state = AccordionState.Collapsing;
await waitForTransition;
this.state = AccordionState.Collapsed;
contentEl.style.removeProperty('max-height');
});
});
} else {
this.state = AccordionState.Collapsed;
}
};
/**
* Helper function to determine if
* something should animate.
* If prefers-reduced-motion is set
* then we should not animate, regardless
* of what is set in the config.
*/
private shouldAnimate = () => {
if (typeof (window as any) === 'undefined') {
return false;
}
const prefersReducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
if (prefersReducedMotion) {
return false;
}
const animated = config.get('animated', true);
if (!animated) {
return false;
}
if (this.accordionGroupEl && !this.accordionGroupEl.animated) {
return false;
}
return true;
};
private updateState = async (initialUpdate = false) => {
const accordionGroup = this.accordionGroupEl;
const accordionValue = this.value;
if (!accordionGroup) {
return;
}
const value = accordionGroup.value;
const shouldExpand = Array.isArray(value) ? value.includes(accordionValue) : value === accordionValue;
if (shouldExpand) {
this.expandAccordion(initialUpdate);
this.isNext = this.isPrevious = false;
} else {
this.collapseAccordion(initialUpdate);
/**
* When using popout or inset,
* the collapsed accordion items
* may need additional border radius
* applied. Check to see if the
* next or previous accordion is selected.
*/
const nextAccordion = this.getNextSibling();
const nextAccordionValue = nextAccordion?.value;
if (nextAccordionValue !== undefined) {
this.isPrevious = Array.isArray(value) ? value.includes(nextAccordionValue) : value === nextAccordionValue;
}
const previousAccordion = this.getPreviousSibling();
const previousAccordionValue = previousAccordion?.value;
if (previousAccordionValue !== undefined) {
this.isNext = Array.isArray(value) ? value.includes(previousAccordionValue) : value === previousAccordionValue;
}
}
};
private getNextSibling = () => {
if (!this.el) {
return;
}
const nextSibling = this.el.nextElementSibling;
if (nextSibling?.tagName !== 'ION-ACCORDION') {
return;
}
return nextSibling as HTMLIonAccordionElement;
};
private getPreviousSibling = () => {
if (!this.el) {
return;
}
const previousSibling = this.el.previousElementSibling;
if (previousSibling?.tagName !== 'ION-ACCORDION') {
return;
}
return previousSibling as HTMLIonAccordionElement;
};
private toggleExpanded() {
const { accordionGroupEl, value, state } = this;
if (accordionGroupEl) {
/**
* Because the accordion group may or may
* not allow multiple accordions open, we
* need to request the toggling of this
* accordion and the accordion group will
* make the decision on whether or not
* to allow it.
*/
const expand = state === AccordionState.Collapsed || state === AccordionState.Collapsing;
accordionGroupEl.requestAccordionToggle(value, expand);
}
}
render() {
const { disabled, readonly } = this;
const mode = getIonMode(this);
const expanded = this.state === AccordionState.Expanded || this.state === AccordionState.Expanding;
const headerPart = expanded ? 'header expanded' : 'header';
const contentPart = expanded ? 'content expanded' : 'content';
this.setAria(expanded);
return (
<Host
class={{
[mode]: true,
'accordion-expanding': this.state === AccordionState.Expanding,
'accordion-expanded': this.state === AccordionState.Expanded,
'accordion-collapsing': this.state === AccordionState.Collapsing,
'accordion-collapsed': this.state === AccordionState.Collapsed,
'accordion-next': this.isNext,
'accordion-previous': this.isPrevious,
'accordion-disabled': disabled,
'accordion-readonly': readonly,
'accordion-animated': config.getBoolean('animated', true),
}}
>
<div
onClick={() => this.toggleExpanded()}
id="header"
part={headerPart}
aria-controls="content"
ref={(headerEl) => (this.headerEl = headerEl)}
>
<slot name="header"></slot>
</div>
<div
id="content"
part={contentPart}
role="region"
aria-labelledby="header"
ref={(contentEl) => (this.contentEl = contentEl)}
>
<div id="content-wrapper" ref={(contentElWrapper) => (this.contentElWrapper = contentElWrapper)}>
<slot name="content"></slot>
</div>
</div>
</Host>
);
}
}
let accordionIds = 0; | the_stack |
import { ContractInterfaces } from '@augurproject/core';
import { EthersProvider } from '@augurproject/ethersjs-provider';
import {
Augur,
Connectors,
CreateCategoricalMarketParams,
createClient,
CreateScalarMarketParams,
CreateYesNoMarketParams,
DisputeWindow,
EmptyConnector,
HotLoadMarketInfo,
PlaceTradeDisplayParams,
SimulateTradeData,
WarpSyncData,
ZeroXPlaceTradeDisplayParams,
ZeroXSimulateTradeData,
} from '@augurproject/sdk';
import {
MarketInfo,
MarketList,
TemplateFilters,
} from '@augurproject/sdk-lite';
import { SDKConfiguration } from '@augurproject/utils';
import { BigNumber } from 'bignumber.js';
import { formatBytes32String } from 'ethers/utils';
import moment from 'moment';
import { Account } from '../constants';
import { makeSigner } from './blockchain';
const NULL_ADDRESS = '0x0000000000000000000000000000000000000000';
const MAX_APPROVAL = new BigNumber(2).pow(256).minus(1);
const MAX_REP_FAUCET = new BigNumber(499999).multipliedBy(10 ** 18);
export class ContractAPI {
static async userWrapper(
account: Account,
provider: EthersProvider,
config: SDKConfiguration,
connector: Connectors.BaseConnector = new EmptyConnector()
) {
const signer = await makeSigner(account, provider);
const augur = await createClient(config, connector, signer, provider, true);
return new ContractAPI(augur, provider, account);
}
static async wrapUsers(
accounts: Account[],
provider: EthersProvider,
config: SDKConfiguration,
connector: Connectors.BaseConnector = new EmptyConnector()
): Promise<ContractAPI[]> {
return Promise.all(
accounts.map(account =>
ContractAPI.userWrapper(account, provider, config, connector)
)
);
}
constructor(
readonly augur: Augur,
readonly provider: EthersProvider,
public account: Account
) {}
get dependencies() {
return this.augur.dependencies;
}
async sendEther(to: string, amount: BigNumber): Promise<void> {
return await this.augur.sendETH(to, amount);
}
async approve(wei = MAX_APPROVAL): Promise<void> {
const authority = this.augur.config.addresses.Augur;
await this.augur.contracts.cash.approve(authority, wei);
const fillOrder = this.augur.config.addresses.FillOrder;
await this.augur.contracts.cash.approve(fillOrder, wei);
await this.augur.contracts.shareToken.setApprovalForAll(fillOrder, true);
const createOrder = this.augur.config.addresses.CreateOrder;
await this.augur.contracts.cash.approve(createOrder, wei);
await this.augur.contracts.shareToken.setApprovalForAll(createOrder, true);
const zeroXTrade = this.augur.config.addresses.ZeroXTrade;
await this.augur.contracts.cash.approve(zeroXTrade, wei);
}
async getCashAllowance(): Promise<BigNumber> {
const owner = this.account.address;
const authority = this.augur.config.addresses.Augur;
return this.augur.contracts.cash.allowance_(owner, authority);
}
async approveIfNecessary(wei = MAX_APPROVAL): Promise<void> {
const current = await this.getCashAllowance();
if (current.lt(wei)) {
await this.approve(wei);
}
}
async createYesNoMarket(
params: CreateYesNoMarketParams,
faucet = true
): Promise<ContractInterfaces.Market> {
if (faucet) await this.marketFauceting();
return this.augur.createYesNoMarket(params);
}
async createCategoricalMarket(
params: CreateCategoricalMarketParams,
faucet = true
): Promise<ContractInterfaces.Market> {
if (faucet) await this.marketFauceting();
return this.augur.createCategoricalMarket(params);
}
async createScalarMarket(
params: CreateScalarMarketParams,
faucet = true
): Promise<ContractInterfaces.Market> {
if (faucet) await this.marketFauceting();
return this.augur.createScalarMarket(params);
}
async getRepBond(): Promise<BigNumber> {
return this.augur.contracts.universe.getOrCacheMarketRepBond_();
}
async marketFauceting() {
const marketCreationFee = await this.augur.contracts.universe.getOrCacheValidityBond_();
const repBond = await this.getRepBond();
console.log('Cash Faucet for market creation');
await this.faucetCashUpTo(marketCreationFee);
console.log('REP Faucet for market creation');
await this.faucetRepUpTo(repBond.plus(1e18));
}
async createReasonableYesNoMarket(
description = 'YesNo market description',
faucet = true,
feePercentage = 1
): Promise<ContractInterfaces.Market> {
const currentTimestamp = (await this.getTimestamp()).toNumber();
return this.createYesNoMarket(
{
endTime: new BigNumber(currentTimestamp + 30 * 24 * 60 * 60),
feePerCashInAttoCash: new BigNumber(feePercentage * 10).pow(16),
affiliateFeeDivisor: new BigNumber(25),
designatedReporter: this.account.address,
extraInfo: JSON.stringify({
categories: ['flash', 'Reasonable', 'YesNo'],
description,
}),
},
faucet
);
}
async createReasonableMarket(
outcomes: string[],
description = 'Categorical market description',
faucet = true
): Promise<ContractInterfaces.Market> {
const currentTimestamp = (await this.getTimestamp()).toNumber();
return this.createCategoricalMarket(
{
endTime: new BigNumber(currentTimestamp + 30 * 24 * 60 * 60),
feePerCashInAttoCash: new BigNumber(10).pow(16),
affiliateFeeDivisor: new BigNumber(25),
designatedReporter: this.account.address,
extraInfo: JSON.stringify({
categories: ['flash', 'Reasonable', 'Categorical'],
description,
}),
outcomes,
},
faucet
);
}
async createReasonableScalarMarket(
description = 'Scalar market description',
faucet = true
): Promise<ContractInterfaces.Market> {
const currentTimestamp = (await this.getTimestamp()).toNumber();
const minPrice = new BigNumber(50).multipliedBy(new BigNumber(10).pow(18));
const maxPrice = new BigNumber(250).multipliedBy(new BigNumber(10).pow(18));
return this.createScalarMarket(
{
endTime: new BigNumber(currentTimestamp + 30 * 24 * 60 * 60),
feePerCashInAttoCash: new BigNumber(10).pow(16),
affiliateFeeDivisor: new BigNumber(25),
designatedReporter: this.account.address,
extraInfo: JSON.stringify({
categories: ['flash', 'Reasonable', 'Scalar'],
description,
_scalarDenomination: 'scalar denom 1',
}),
numTicks: new BigNumber(20000),
prices: [minPrice, maxPrice],
},
faucet
);
}
async placeOrder(
market: string,
type: BigNumber,
numShares: BigNumber,
price: BigNumber,
outcome: BigNumber,
betterOrderID: string,
worseOrderID: string,
tradeGroupID: string
): Promise<string> {
if (type.isEqualTo(0)) {
// BID
const cost = numShares.multipliedBy(price);
await this.faucetCashUpTo(cost);
} else if (type.isEqualTo(1)) {
// ASK
const m = await this.getMarketContract(market);
const numTicks = await m.getNumTicks_();
const cost = numTicks
.plus(price.multipliedBy(-1))
.multipliedBy(numShares);
await this.faucetCashUpTo(cost);
} else {
throw Error(`Invalid order type ${type.toString()}`);
}
const events = await this.augur.contracts.createOrder.publicCreateOrder(
type,
numShares,
price,
market,
outcome,
betterOrderID,
worseOrderID,
tradeGroupID
);
let orderId = '';
for (const ev of events) {
if (ev.name === 'OrderEvent') {
interface HasOrderId {
orderId: string;
}
orderId = (ev.parameters as HasOrderId).orderId;
}
}
return orderId;
}
async simplePlaceOrder(
market: string,
type: BigNumber,
numShares: BigNumber,
price: BigNumber,
outcome: BigNumber
): Promise<string> {
return this.placeOrder(
market,
type,
numShares,
price,
outcome,
formatBytes32String(''),
formatBytes32String(''),
formatBytes32String('42')
);
}
async fillOrder(
orderId: string,
numShares: BigNumber,
tradeGroupId: string,
cost?: BigNumber
) {
if (cost) {
await this.faucetCashUpTo(cost);
}
await this.augur.contracts.fillOrder.publicFillOrder(
orderId,
numShares,
formatBytes32String(tradeGroupId),
formatBytes32String('')
);
}
async placeZeroXOrder(params: ZeroXPlaceTradeDisplayParams): Promise<void> {
await this.augur.zeroX.placeOrder(params);
}
async placeZeroXOrders(
params: ZeroXPlaceTradeDisplayParams[]
): Promise<void> {
console.log(
`${this.account.address} is creating orders: ${JSON.stringify(
params,
null,
2
)}`
);
await this.augur.zeroX.placeOrders(params);
}
async safePlaceOrders(params: ZeroXPlaceTradeDisplayParams[]): Promise<void> {
await this.augur.zeroX.safePlaceOrders(params);
}
async placeZeroXTrade(params: ZeroXPlaceTradeDisplayParams): Promise<void> {
const price =
params.direction === 0
? params.displayPrice
: params.numTicks.minus(params.displayPrice);
const cost = params.displayAmount
.multipliedBy(price)
.multipliedBy(10 ** 18);
await this.faucetCashUpTo(cost);
await this.augur.zeroX.placeTrade(params);
}
async placeBasicYesNoZeroXTrade(
direction: 0 | 1,
market: string,
outcome: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7,
displayAmount: BigNumber,
displayPrice: BigNumber,
displayShares: BigNumber,
expirationTime: BigNumber
): Promise<void> {
await this.placeZeroXTrade({
direction,
market,
numTicks: new BigNumber(1000),
numOutcomes: 3,
outcome,
tradeGroupId: formatBytes32String('42'),
fingerprint: formatBytes32String('11'),
doNotCreateOrders: false,
displayMinPrice: new BigNumber(0),
displayMaxPrice: new BigNumber(1),
displayAmount,
displayPrice,
displayShares,
expirationTime,
});
}
async takeBestOrder(
marketAddress: string,
type: BigNumber,
numShares: BigNumber,
price: BigNumber,
outcome: BigNumber,
tradeGroupID: string
): Promise<void> {
const cost = numShares.multipliedBy(price);
await this.faucetCashUpTo(cost);
const bestPriceAmount = await this.augur.contracts.trade.publicFillBestOrder_(
type,
marketAddress,
outcome,
numShares,
price,
tradeGroupID,
new BigNumber(3),
formatBytes32String('')
);
if (bestPriceAmount === new BigNumber(0)) {
throw new Error('Could not take best Order');
}
await this.augur.contracts.trade.publicFillBestOrder(
type,
marketAddress,
outcome,
numShares,
price,
tradeGroupID,
new BigNumber(3),
formatBytes32String('')
);
}
async cancelOrder(orderID: string): Promise<void> {
await this.augur.cancelOrder(orderID);
}
async cancelNativeOrder(orderID: string): Promise<void> {
await this.augur.contracts.cancelOrder.cancelOrder(orderID);
}
async placeNativeTrade(params: PlaceTradeDisplayParams): Promise<void> {
const price =
params.direction === 0
? params.displayPrice
: params.numTicks.minus(params.displayPrice);
const cost = params.displayAmount
.multipliedBy(price)
.multipliedBy(10 ** 18);
await this.faucetCashUpTo(cost);
await this.augur.trade.placeTrade(params);
}
async simulateNativeTrade(
params: PlaceTradeDisplayParams
): Promise<SimulateTradeData> {
return this.augur.trade.simulateTrade(params);
}
async simulateZeroXTrade(
params: ZeroXPlaceTradeDisplayParams
): Promise<ZeroXSimulateTradeData> {
return this.augur.zeroX.simulateTrade(params);
}
async placeBasicYesNoTrade(
direction: 0 | 1,
market: ContractInterfaces.Market,
outcome: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7,
displayAmount: BigNumber,
displayPrice: BigNumber,
displayShares: BigNumber
): Promise<void> {
await this.placeNativeTrade({
direction,
market: market.address,
numTicks: await market.getNumTicks_(),
numOutcomes: ((await market.getNumberOfOutcomes_()) as unknown) as
| 3
| 4
| 5
| 6
| 7
| 8,
outcome,
tradeGroupId: formatBytes32String('42'),
fingerprint: formatBytes32String('11'),
doNotCreateOrders: false,
displayMinPrice: new BigNumber(0),
displayMaxPrice: new BigNumber(1),
displayAmount,
displayPrice,
displayShares,
});
}
async simulateBasicYesNoTrade(
direction: 0 | 1,
market: ContractInterfaces.Market,
outcome: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7,
displayAmount: BigNumber,
displayPrice: BigNumber,
displayShares: BigNumber
): Promise<SimulateTradeData> {
return this.simulateNativeTrade({
direction,
market: market.address,
numTicks: await market.getNumTicks_(),
numOutcomes: ((await market.getNumberOfOutcomes_()) as unknown) as
| 3
| 4
| 5
| 6
| 7
| 8,
outcome,
tradeGroupId: formatBytes32String('42'),
fingerprint: formatBytes32String('11'),
doNotCreateOrders: false,
displayMinPrice: new BigNumber(0),
displayMaxPrice: new BigNumber(1),
displayAmount,
displayPrice,
displayShares,
});
}
async simulateBasicZeroXYesNoTrade(
direction: 0 | 1,
market: ContractInterfaces.Market,
outcome: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7,
displayAmount: BigNumber,
displayPrice: BigNumber,
displayShares: BigNumber,
doNotCreateOrders = false
): Promise<ZeroXSimulateTradeData> {
return this.simulateZeroXTrade({
direction,
takerAddress: this.account.address,
market: market.address,
numTicks: await market.getNumTicks_(),
numOutcomes: ((await market.getNumberOfOutcomes_()) as unknown) as
| 3
| 4
| 5
| 6
| 7
| 8,
outcome,
tradeGroupId: formatBytes32String('42'),
expirationTime: new BigNumber(Date.now() + 10000000),
fingerprint: formatBytes32String('11'),
doNotCreateOrders,
displayMinPrice: new BigNumber(0),
displayMaxPrice: new BigNumber(1),
displayAmount,
displayPrice,
displayShares,
});
}
async claimTradingProceeds(
market: ContractInterfaces.Market,
shareholder = this.account.address,
fingerprint = formatBytes32String('11')
): Promise<void> {
await this.augur.contracts.shareToken.claimTradingProceeds(
market.address,
shareholder,
fingerprint
);
}
async getOrderPrice(orderID: string): Promise<BigNumber> {
const price = await this.augur.contracts.orders.getPrice_(orderID);
if (price.toNumber() === 0) {
throw new Error('Unable to get order price');
}
return price;
}
getOrderAmount(orderID: string): Promise<BigNumber> {
return this.augur.contracts.orders.getAmount_(orderID);
}
async getBestOrderId(
type: BigNumber,
market: string,
outcome: BigNumber
): Promise<string> {
const orderID = await this.augur.contracts.orders.getBestOrderId_(
type,
market,
outcome
);
if (!orderID) {
throw new Error('Unable to get order price');
}
return orderID;
}
async getOrders(marketId: string, orderType: string, outcome: number) {
return this.augur.getZeroXOrders({
marketId,
orderType,
outcome,
});
}
async buyCompleteSets(
market: ContractInterfaces.Market,
amount: BigNumber
): Promise<void> {
const numTicks = await market.getNumTicks_();
const cashValue = amount.multipliedBy(numTicks);
await this.faucetCashUpTo(cashValue);
await this.augur.contracts.shareToken.publicBuyCompleteSets(
market.address,
amount
);
}
async sellCompleteSets(
market: ContractInterfaces.Market,
amount: BigNumber
): Promise<void> {
await this.augur.contracts.shareToken.publicSellCompleteSets(
market.address,
amount
);
}
async contribute(
market: ContractInterfaces.Market,
payoutNumerators: BigNumber[],
amount: BigNumber,
description = ''
): Promise<void> {
// Below is to ensure the signer is the account we're using in this instance
market = this.augur.contracts.marketFromAddress(market.address);
await market.contribute(payoutNumerators, amount, description);
}
async contributeToTentative(
market: ContractInterfaces.Market,
payoutNumerators: BigNumber[],
amount: BigNumber,
description = ''
): Promise<void> {
await market.contributeToTentative(payoutNumerators, amount, description);
}
async getRemainingToFill(
market: ContractInterfaces.Market,
payoutNumerators: BigNumber[]
): Promise<BigNumber> {
const payoutDistributionHash = await this.derivePayoutDistributionHash(
market,
payoutNumerators
);
const crowdsourcerAddress = await market.getCrowdsourcer_(
payoutDistributionHash
);
if (crowdsourcerAddress === NULL_ADDRESS) {
return new BigNumber(-1);
}
const crowdsourcer = this.augur.contracts.getReportingParticipant(
crowdsourcerAddress
);
return crowdsourcer.getRemainingToFill_();
}
async getCrowdsourcerDisputeBond(
market: ContractInterfaces.Market,
payoutNumerators: BigNumber[]
): Promise<BigNumber> {
const payoutDistributionHash = await this.derivePayoutDistributionHash(
market,
payoutNumerators
);
const crowdsourcerAddress = await market.getCrowdsourcer_(
payoutDistributionHash
);
if (crowdsourcerAddress === '0') {
const totalStake = await market.getParticipantStake_();
return totalStake.times(2);
}
const crowdsourcer = this.augur.contracts.getReportingParticipant(
crowdsourcerAddress
);
const remaining = await crowdsourcer.getRemainingToFill_();
return remaining;
}
async derivePayoutDistributionHash(
market: ContractInterfaces.Market,
payoutNumerators: BigNumber[]
): Promise<string> {
return market.derivePayoutDistributionHash_(payoutNumerators);
}
async isForking(): Promise<boolean> {
return this.augur.contracts.universe.isForking_();
}
async getDisputeThresholdForFork_(): Promise<BigNumber> {
return this.augur.contracts.universe.getDisputeThresholdForFork_();
}
async getDisputeThresholdForDisputePacing(): Promise<BigNumber> {
return this.augur.contracts.universe.getDisputeThresholdForDisputePacing_();
}
async getInitialReportMinValue(): Promise<BigNumber> {
return this.augur.contracts.universe.getInitialReportMinValue_();
}
migrateOutByPayout(
reputationToken: ContractInterfaces.ReputationToken,
payoutNumerators: BigNumber[],
attotokens: BigNumber
) {
return reputationToken.migrateOutByPayout(payoutNumerators, attotokens);
}
migrateOutByPayoutNumerators(
payoutNumerators: BigNumber[],
attotokens: BigNumber
) {
const reputationToken = this.augur.contracts.getReputationToken();
return reputationToken.migrateOutByPayout(payoutNumerators, attotokens);
}
async getNumSharesInMarket(
market: ContractInterfaces.Market,
outcome: BigNumber
): Promise<BigNumber> {
return this.augur.contracts.shareToken.balanceOfMarketOutcome_(
market.address,
outcome,
await this.augur.getAccount()
);
}
async getOrCreateCurrentDisputeWindow(initial = false): Promise<string> {
// Must make 2 calls because the first call is necessary but doesn't always return the dispute window.
await this.augur.contracts.universe.getOrCreateCurrentDisputeWindow(
initial
);
return this.augur.contracts.universe.getOrCreateCurrentDisputeWindow_(
initial
);
}
async getDisputeWindow(
market: ContractInterfaces.Market
): Promise<ContractInterfaces.DisputeWindow> {
const disputeWindowAddress = await market.getDisputeWindow_();
return this.augur.contracts.disputeWindowFromAddress(disputeWindowAddress);
}
async getDisputeWindowEndTime(
market: ContractInterfaces.Market
): Promise<BigNumber> {
const disputeWindowAddress = await market.getDisputeWindow_();
const disputeWindow = this.augur.contracts.disputeWindowFromAddress(
disputeWindowAddress
);
return disputeWindow.getEndTime_();
}
async getInitialReporter(
market: ContractInterfaces.Market
): Promise<ContractInterfaces.InitialReporter> {
const initialReporterAddress = await market.getInitialReporter_();
return this.augur.contracts.getInitialReporter(initialReporterAddress);
}
async getWinningReportingParticipant(
market: ContractInterfaces.Market
): Promise<ContractInterfaces.DisputeCrowdsourcer> {
const reportingParticipantAddress = await market.getWinningReportingParticipant_();
return this.augur.contracts.getReportingParticipant(
reportingParticipantAddress
);
}
async buyParticipationTokens(
disputeWindowAddress: string,
amount: BigNumber,
sender: string = this.account.address
): Promise<void> {
const disputeWindow = this.augur.contracts.disputeWindowFromAddress(
disputeWindowAddress
);
await disputeWindow.buy(amount, { sender });
}
async simpleBuyParticipationTokens(attoRep: BigNumber): Promise<void> {
const universe = this.augur.contracts.universe.address;
await this.augur.contracts.buyParticipationTokens.buyParticipationTokens(
universe,
attoRep
);
}
async redeemParticipationTokens(
disputeWindowAddress: string,
account: string = this.account.address
): Promise<void> {
const disputeWindow = this.augur.contracts.disputeWindowFromAddress(
disputeWindowAddress
);
await disputeWindow.redeem(account);
}
async getUniverse(
market: ContractInterfaces.Market
): Promise<ContractInterfaces.Universe> {
const universeAddress = await market.getUniverse_();
return this.augur.contracts.universeFromAddress(universeAddress);
}
async advanceTimestamp(secondsToAdvance: number | BigNumber): Promise<void> {
const currentTimestamp = await this.getTimestamp();
return this.setTimestamp(currentTimestamp.plus(secondsToAdvance));
}
async setTimestamp(timestamp: BigNumber): Promise<void> {
const time = this.augur.contracts.getTime();
if (this.augur.contracts.isTimeControlled(time)) {
await time.setTimestamp(timestamp);
try {
// sync our timestamp with our fake timestamp.
await this.provider.providerSend('evm_mine', [timestamp.toNumber()]);
} catch (e) {
// Not using ganache. Nothing really to do here.
}
} else {
throw Error(
'Cannot set timestamp because Time contract is not TimeControlled'
);
}
}
async getTimestamp(): Promise<BigNumber> {
return this.augur.contracts.augur.getTimestamp_();
}
async printTimestamp() {
const blocktime = await this.getTimestamp();
const epoch = Number(blocktime.toString()) * 1000;
console.log(`block: ${blocktime}`);
console.log(`local: ${moment(epoch).toString()}`);
console.log(
`utc: ${moment(epoch)
.utc()
.toString()}\n`
);
}
async doInitialReport(
market: ContractInterfaces.Market,
payoutNumerators: BigNumber[],
description = '',
extraStake = '0'
): Promise<void> {
// Below is to ensure the signer is the account we're using in this instance
market = this.augur.contracts.marketFromAddress(market.address);
await market.doInitialReport(
payoutNumerators,
description,
new BigNumber(extraStake)
);
}
async getMarketContract(address: string): Promise<ContractInterfaces.Market> {
return this.augur.getMarket(address);
}
async getMarketInfo(
marketIds: string | string[]
): Promise<MarketInfo[]> {
marketIds = Array.isArray(marketIds) ? marketIds : [marketIds];
return this.augur.getMarketsInfo({ marketIds });
}
async getMarkets(): Promise<MarketList> {
const universe = this.augur.contracts.universe.address;
return this.augur.getMarkets({ universe });
}
async getBettingMarkets(
params = {}
): Promise<MarketList> {
const universe = this.augur.contracts.universe.address;
return this.augur.getMarkets({ universe, templateFilter: TemplateFilters.sportsBook });
}
async getInitialReporterStake(
market: ContractInterfaces.Market,
payoutNumerators: BigNumber[]
): Promise<BigNumber> {
const payoutDistributionHash = await this.derivePayoutDistributionHash(
market,
payoutNumerators
);
const initialReporterAddress = await market.getCrowdsourcer_(
payoutDistributionHash
);
const initialReporter = this.augur.contracts.getInitialReporter(
initialReporterAddress
);
return initialReporter.getStake_();
}
async getParticipantStake(
market: ContractInterfaces.Market
): Promise<BigNumber> {
return market.getParticipantStake_();
}
async finalizeMarket(market: ContractInterfaces.Market): Promise<void> {
await market.finalize();
}
async faucetCash(attoCash: BigNumber, targetAddress?: string): Promise<void> {
const userAddress = await this.augur.getAccount();
const account = targetAddress || userAddress;
await this.augur.contracts.cash.faucet(attoCash);
if (account !== userAddress) {
await this.augur.contracts.cash.transfer(account, attoCash);
}
}
// Faucets cash if the target address (or current user) has less than `attoCash`.
// When fauceting, adds `extra` cash as a buffer.
async faucetCashUpTo(
attoCash: BigNumber,
extra = new BigNumber(0),
targetAddress: string = null
): Promise<void> {
targetAddress = targetAddress || (await this.augur.getAccount());
const balance = await this.getCashBalance(targetAddress);
const leftToFaucet = attoCash.minus(balance);
if (leftToFaucet.gt(0)) {
const totalToFaucet = leftToFaucet.plus(extra);
await this.faucetCash(totalToFaucet, targetAddress);
}
}
async faucetRep(attoRep: BigNumber, useLegacy = false): Promise<void> {
attoRep = BigNumber.min(attoRep, MAX_REP_FAUCET);
const reputationToken = this.augur.contracts.getReputationToken();
if (useLegacy) {
await this.augur.contracts.legacyReputationToken.faucet(attoRep);
} else {
if (typeof reputationToken['faucet'] === 'function') {
await reputationToken['faucet'](attoRep);
} else {
throw Error('Cannot faucet REP with non-test version of REP contract.');
}
}
}
// Faucets rep if the target address (or current user) has less than `attoRep`.
// When fauceting, adds `extra` rep as a buffer.
async faucetRepUpTo(
attoRep: BigNumber,
extra = new BigNumber(0),
useLegacy = false
): Promise<void> {
const address = await this.augur.getAccount();
const balance = await this.getRepBalance(address);
const leftToFaucet = attoRep.minus(balance);
if (leftToFaucet.gt(0)) {
const totalToFaucet = BigNumber.min(
MAX_REP_FAUCET,
leftToFaucet.plus(extra)
);
await this.faucetRep(totalToFaucet, useLegacy);
}
}
async transferCash(to: string, attoCash: BigNumber): Promise<void> {
await this.augur.contracts.cash.transfer(to, attoCash);
}
async addEthExchangeLiquidity(
attoCash: BigNumber,
attoEth: BigNumber
): Promise<void> {
await this.faucetCashUpTo(attoCash);
await this.augur.contracts.cash.transfer(
this.augur.contracts.ethExchange.address,
attoCash
);
await this.augur.contracts.weth.deposit({ attachedEth: attoEth });
await this.augur.contracts.weth.transfer(
this.augur.contracts.ethExchange.address,
attoEth
);
const owner = await this.augur.getAccount();
await this.augur.contracts.ethExchange.mint(owner);
}
async depositRelay(address: string, attoEth: BigNumber): Promise<void> {
await this.augur.contracts.relayHub.depositFor(address, {
attachedEth: attoEth,
});
}
async initWarpSync(universe: string): Promise<void> {
const warpSyncMarket = await this.augur.contracts.warpSync.markets_(
universe
);
if (warpSyncMarket === NULL_ADDRESS) {
await this.augur.contracts.warpSync.initializeUniverse(universe);
}
}
async reportAndFinalizeWarpSyncMarket(hash: string) {
const warpSyncMarket = await this.reportWarpSyncMarket(hash);
return this.finalizeWarpSyncMarket(warpSyncMarket);
}
async finalizeWarpSyncMarket(warpSyncMarket: ContractInterfaces.Market) {
const timestamp = (await this.getTimestamp()).plus(1000000);
await this.setTimestamp(timestamp);
await this.finalizeMarket(warpSyncMarket);
return warpSyncMarket;
}
async reportWarpSyncMarket(hash: string) {
const payoutNumerators = await this.getPayoutFromWarpSyncHash(hash);
const warpSyncMarket = await this.getWarpSyncMarket();
const timestamp = (await this.getTimestamp()).plus(1000000);
await this.setTimestamp(timestamp);
await this.doInitialReport(warpSyncMarket, payoutNumerators);
return warpSyncMarket;
}
getLegacyRepBalance(owner: string): Promise<BigNumber> {
return this.augur.contracts.legacyReputationToken.balanceOf_(owner);
}
getLegacyRepAllowance(owner: string, spender: string): Promise<BigNumber> {
return this.augur.contracts.legacyReputationToken.allowance_(
owner,
spender
);
}
async transferLegacyRep(to: string, amount: BigNumber): Promise<void> {
await this.augur.contracts.legacyReputationToken.transfer(to, amount);
}
async getChildUniverseReputationToken(parentPayoutDistributionHash: string) {
const childUniverseAddress = await this.augur.contracts.universe!.getChildUniverse_(
parentPayoutDistributionHash
);
const childUniverse = this.augur.contracts.universeFromAddress(
childUniverseAddress
);
const repContractAddress = await childUniverse.getReputationToken_();
return this.augur.contracts.reputationTokenFromAddress(
repContractAddress,
this.augur.config.networkId
);
}
// TODO: Determine why ETH balance doesn't change when buying complete sets or redeeming reporting participants
async getEthBalance(owner?: string): Promise<BigNumber> {
const balance = await this.provider.getBalance(
owner || this.account.address
);
return new BigNumber(balance.toString());
}
async getRepBalance(owner?: string): Promise<BigNumber> {
if (!owner) owner = await this.augur.getAccount();
return this.augur.contracts.getReputationToken().balanceOf_(owner);
}
async getCashBalance(owner?: string): Promise<BigNumber> {
if (!owner) owner = await this.augur.getAccount();
return this.augur.contracts.cash.balanceOf_(owner);
}
getRepAllowance(owner: string, spender: string): Promise<BigNumber> {
return this.augur.contracts.getReputationToken().allowance_(owner, spender);
}
getGasPrice(): Promise<BigNumber> {
return this.augur.getGasPrice();
}
async getHotLoadingMarketData(market: string): Promise<HotLoadMarketInfo> {
return this.augur.hotLoading.getMarketDataParams({ market });
}
async getHotLoadingDisputeWindowData(): Promise<DisputeWindow> {
return this.augur.hotLoading.getCurrentDisputeWindowData({
augur: this.augur.contracts.augur.address,
universe: this.augur.contracts.universe.address,
});
}
async mineBlock(): Promise<void> {
await this.provider.sendAsync({
id: 42,
method: 'evm_mine',
params: [],
jsonrpc: '2.0',
});
}
async startMining(): Promise<void> {
await this.provider.sendAsync({
id: 42,
method: 'miner_start',
params: [],
jsonrpc: '2.0',
});
}
async stopMining(): Promise<void> {
await this.provider.sendAsync({
id: 42,
method: 'miner_stop',
params: [],
jsonrpc: '2.0',
});
}
async fundSafe(safe: string, minimum = new BigNumber(1e21)) {
if ((await this.getCashBalance(safe)).lt(minimum)) {
await this.faucetCashUpTo(minimum, new BigNumber(0), safe);
}
return safe;
}
async initializeUniverseForWarpSync(): Promise<void> {
return this.augur.warpSync.initializeUniverse(
this.augur.contracts.universe.address
);
}
async getWarpSyncMarket(): Promise<ContractInterfaces.Market> {
return this.augur.warpSync.getWarpSyncMarket(
this.augur.contracts.universe.address
);
}
async getLastWarpSyncData(): Promise<WarpSyncData> {
return this.augur.warpSync.getLastWarpSyncData(
this.augur.contracts.universe.address
);
}
async getWarpSyncHashFromPayout(payout: BigNumber[]): Promise<string> {
return this.augur.warpSync.getWarpSyncHashFromPayout(payout[2]);
}
async getPayoutFromWarpSyncHash(hash: string): Promise<BigNumber[]> {
return this.augur.warpSync.getPayoutFromWarpSyncHash(hash);
}
async getWarpSyncHashFromMarket(
market: ContractInterfaces.Market
): Promise<string> {
return this.augur.warpSync.getWarpSyncHashFromMarket(market);
}
async addTokenExchangeLiquidity(
attoCash: BigNumber,
attoRep: BigNumber
): Promise<void> {
const contracts = this.augur.contracts;
const owner = await this.augur.getAccount();
const now = new Date();
const deadline = now.valueOf() * 1 + 3600000;
const APPROVAL_AMOUNT = new BigNumber(2 ** 255);
await this.faucetCashUpTo(attoCash);
await this.faucetRepUpTo(attoRep);
await contracts.cash.approve(contracts.uniswap.address, APPROVAL_AMOUNT);
await contracts.reputationToken.approve(
contracts.uniswap.address,
APPROVAL_AMOUNT
);
await contracts.uniswap.addLiquidity(
contracts.reputationToken.address,
contracts.cash.address,
attoRep,
attoCash,
new BigNumber(0),
new BigNumber(0),
owner,
new BigNumber(deadline)
);
}
} | the_stack |
import {
ConnectedWallet,
Connection,
ConnectType,
Installation,
NetworkInfo,
SignBytesResult,
SignResult,
TxResult,
WalletLCDClientConfig,
WalletStates,
WalletStatus,
} from '@terra-dev/wallet-types';
import {
TerraWebExtensionFeatures,
WebExtensionTxStatus,
} from '@terra-dev/web-extension-interface';
import {
AccAddress,
CreateTxOptions,
LCDClient,
PublicKey,
Tx,
} from '@terra-money/terra.js';
import deepEqual from 'fast-deep-equal';
import { BehaviorSubject, combineLatest, Observable, Subscription } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import {
CHROME_EXTENSION_INSTALL_URL,
DEFAULT_CHROME_EXTENSION_COMPATIBLE_BROWSER_CHECK,
} from './env';
import {
mapExtensionSignBytesError,
mapExtensionTxError,
} from './exception/mapExtensionTxError';
import { mapWalletConnectError } from './exception/mapWalletConnectError';
import {
ExtensionRouter,
ExtensionRouterStatus,
} from './modules/extension-router';
import {
ExtensionInfo,
getTerraExtensions,
} from './modules/extension-router/multiChannel';
import {
connect as reConnect,
connectIfSessionExists as reConnectIfSessionExists,
ReadonlyWalletController,
readonlyWalletModal,
ReadonlyWalletSession,
} from './modules/readonly-wallet';
import {
connect as wcConnect,
connectIfSessionExists as wcConnectIfSessionExists,
WalletConnectController,
WalletConnectControllerOptions,
WalletConnectSessionStatus,
} from './modules/walletconnect';
import { getExtensions } from './operators/getExtensions';
import { toConnectedWallet } from './operators/toConnectedWallet';
import { toLcdClient } from './operators/toLcdClient';
import { isDesktopChrome } from './utils/browser-check';
import { checkExtensionReady } from './utils/checkExtensionReady';
import { sortConnections } from './utils/sortConnections';
export interface WalletControllerOptions
extends WalletConnectControllerOptions {
/**
* ⚠️ Don't hardcoding this, use getChain Options()
*
* fallback network if controller is not connected
*/
defaultNetwork: NetworkInfo;
/**
* ⚠️ Don't hardcoding this, use getChain Options()
*
* for walletconnect
*
* The network rules passed by the Terra Station Mobile are 0 is testnet, 1 is mainnet.
*
* Always set testnet for 0 and mainnet for 1.
*
* @example
* ```
* const mainnet: NetworkInfo = {
* name: 'mainnet',
* chainID: 'columbus-5',
* lcd: 'https://lcd.terra.dev',
* }
*
* const testnet: NetworkInfo = {
* name: 'testnet',
* chainID: 'bombay-12',
* lcd: 'https://bombay-lcd.terra.dev',
* }
*
* const walletConnectChainIds: Record<number, NetworkInfo> = {
* 0: testnet,
* 1: mainnet,
* }
*
* <WalletProvider walletConnectChainIds={walletConnectChainIds}>
* ```
*/
walletConnectChainIds: Record<number, NetworkInfo>;
/**
* run at executing the `connect(ConnectType.READONLY)`
*/
createReadonlyWalletSession?: (
networks: NetworkInfo[],
) => Promise<ReadonlyWalletSession | null>;
/**
* run at executing the `connect(ConnectType.EXTENSION)`
* if user installed multiple wallets
*/
selectExtension?: (
extensionInfos: ExtensionInfo[],
) => Promise<ExtensionInfo | null>;
/**
* milliseconds to wait checking chrome extension is installed
*
* @default 1000 * 3 miliseconds
*/
waitingChromeExtensionInstallCheck?: number;
/**
* ⚠️ This API is an option for wallet developers. Please don't use dApp developers.
*
* @example
* ```
* <WalletProvider dangerously__chromeExtensionCompatibleBrowserCheck={(userAgent: string) => {
* return /MyWallet\//.test(userAgent);
* }}>
* ```
*/
dangerously__chromeExtensionCompatibleBrowserCheck?: (
userAgent: string,
) => boolean;
}
const CONNECTIONS = {
[ConnectType.READONLY]: {
type: ConnectType.READONLY,
name: 'View an address',
icon: 'https://assets.terra.money/icon/wallet-provider/readonly.svg',
} as Connection,
[ConnectType.WALLETCONNECT]: {
type: ConnectType.WALLETCONNECT,
name: 'Wallet Connect',
icon: 'https://assets.terra.money/icon/wallet-provider/walletconnect.svg',
} as Connection,
} as const;
const DEFAULT_WAITING_CHROME_EXTENSION_INSTALL_CHECK = 1000 * 3;
const WALLETCONNECT_SUPPORT_FEATURES = new Set<TerraWebExtensionFeatures>([
'post',
]);
const EMPTY_SUPPORT_FEATURES = new Set<TerraWebExtensionFeatures>();
export class WalletController {
private extension: ExtensionRouter | null = null;
private walletConnect: WalletConnectController | null = null;
private readonlyWallet: ReadonlyWalletController | null = null;
private _availableConnectTypes: BehaviorSubject<ConnectType[]>;
private _availableInstallTypes: BehaviorSubject<ConnectType[]>;
private _states: BehaviorSubject<WalletStates>;
private disableReadonlyWallet: (() => void) | null = null;
private disableExtension: (() => void) | null = null;
private disableWalletConnect: (() => void) | null = null;
private readonly _notConnected: WalletStates;
private readonly _initializing: WalletStates;
constructor(readonly options: WalletControllerOptions) {
this._notConnected = {
status: WalletStatus.WALLET_NOT_CONNECTED,
network: options.defaultNetwork,
};
this._initializing = {
status: WalletStatus.INITIALIZING,
network: options.defaultNetwork,
};
this._availableConnectTypes = new BehaviorSubject<ConnectType[]>([
ConnectType.READONLY,
ConnectType.WALLETCONNECT,
]);
this._availableInstallTypes = new BehaviorSubject<ConnectType[]>([]);
this._states = new BehaviorSubject<WalletStates>(this._initializing);
let numSessionCheck: number = 0;
// wait checking the availability of the chrome extension
// 0. check if extension wallet session is exists
checkExtensionReady(
options.waitingChromeExtensionInstallCheck ??
DEFAULT_WAITING_CHROME_EXTENSION_INSTALL_CHECK,
this.isChromeExtensionCompatibleBrowser(),
).then((ready: boolean) => {
if (ready) {
this._availableConnectTypes.next([
ConnectType.EXTENSION,
ConnectType.WALLETCONNECT,
ConnectType.READONLY,
]);
this.extension = new ExtensionRouter({
hostWindow: window,
selectExtension: options.selectExtension,
dangerously__chromeExtensionCompatibleBrowserCheck:
options.dangerously__chromeExtensionCompatibleBrowserCheck ??
DEFAULT_CHROME_EXTENSION_COMPATIBLE_BROWSER_CHECK,
defaultNetwork: options.defaultNetwork,
});
const subscription = this.extension
.states()
.pipe(
filter(({ type }) => type !== ExtensionRouterStatus.INITIALIZING),
)
.subscribe((extensionStates) => {
try {
subscription.unsubscribe();
} catch {}
if (
extensionStates.type === ExtensionRouterStatus.WALLET_CONNECTED &&
!this.disableWalletConnect &&
!this.disableReadonlyWallet
) {
this.enableExtension();
} else if (numSessionCheck === 0) {
numSessionCheck += 1;
} else {
this.updateStates(this._notConnected);
}
});
} else {
if (isDesktopChrome(this.isChromeExtensionCompatibleBrowser())) {
this._availableInstallTypes.next([ConnectType.EXTENSION]);
}
if (numSessionCheck === 0) {
numSessionCheck += 1;
} else {
this.updateStates(this._notConnected);
}
}
});
// 1. check if readonly wallet session is exists
const draftReadonlyWallet = reConnectIfSessionExists();
if (draftReadonlyWallet) {
this.enableReadonlyWallet(draftReadonlyWallet);
return;
}
// 2. check if walletconnect sesison is exists
const draftWalletConnect = wcConnectIfSessionExists(options);
if (
draftWalletConnect &&
draftWalletConnect.getLatestSession().status ===
WalletConnectSessionStatus.CONNECTED
) {
this.enableWalletConnect(draftWalletConnect);
} else if (numSessionCheck === 0) {
numSessionCheck += 1;
} else {
this.updateStates(this._notConnected);
}
}
/**
* Some mobile wallet emulates the behavior of chrome extension.
* It confirms that the current connection environment is such a wallet.
* (If you are running connect() by checking availableConnectType, you do not need to use this API.)
*
* @see Wallet#isChromeExtensionCompatibleBrowser
*/
isChromeExtensionCompatibleBrowser = (): boolean => {
return (
this.options.dangerously__chromeExtensionCompatibleBrowserCheck ??
DEFAULT_CHROME_EXTENSION_COMPATIBLE_BROWSER_CHECK
)(navigator.userAgent);
};
/**
* available connect types on the browser
*
* @see Wallet#availableConnectTypes
*/
availableConnectTypes = (): Observable<ConnectType[]> => {
return this._availableConnectTypes.asObservable();
};
/**
* available connections includes identifier, name, icon
*
* @see Wallet#availableConnections
*/
availableConnections = (): Observable<Connection[]> => {
return this._availableConnectTypes.pipe(
map((connectTypes) => {
const connections: Connection[] = [];
for (const connectType of connectTypes) {
if (connectType === ConnectType.EXTENSION) {
const terraExtensions = getTerraExtensions();
for (const terraExtension of terraExtensions) {
connections.push(
memoConnection(
ConnectType.EXTENSION,
terraExtension.name,
terraExtension.icon,
terraExtension.identifier,
),
);
}
} else {
connections.push(CONNECTIONS[connectType]);
}
}
return sortConnections(connections);
}),
);
};
/**
* available install types on the browser
*
* in this time, this only contains [ConnectType.EXTENSION]
*
* @see Wallet#availableInstallTypes
*/
availableInstallTypes = (): Observable<ConnectType[]> => {
return this._availableInstallTypes.asObservable();
};
/**
* available installations includes identifier, name, icon, url
*
* @see Wallet#availableInstallations
*/
availableInstallations = (): Observable<Installation[]> => {
return combineLatest([this.availableConnections(), getExtensions()]).pipe(
map(([connections, extensions]) => {
const installedIdentifiers = new Set<string>(
connections
.filter(({ type, identifier }) => {
return type === ConnectType.EXTENSION && !!identifier;
})
.map(({ identifier }) => {
return identifier!;
}),
);
return extensions
.filter(({ identifier }) => {
return !installedIdentifiers.has(identifier);
})
.map(({ name, identifier, icon, url }) => {
return {
type: ConnectType.EXTENSION,
identifier,
name,
icon,
url,
};
});
}),
);
};
/**
* @see Wallet#status
* @see Wallet#network
* @see Wallet#wallets
*/
states = (): Observable<WalletStates> => {
return this._states.asObservable();
};
/** get connectedWallet */
connectedWallet = (): Observable<ConnectedWallet | undefined> => {
return this._states.pipe(toConnectedWallet(this));
};
/** get lcdClient */
lcdClient = (
lcdClientConfig?: WalletLCDClientConfig,
): Observable<LCDClient> => {
return this._states.pipe(toLcdClient(lcdClientConfig));
};
/**
* reload the connected wallet states
*
* in this time, this only work on the ConnectType.EXTENSION
*
* @see Wallet#recheckStatus
*/
refetchStates = () => {
if (this.disableExtension) {
this.extension?.refetchStates();
}
};
/**
* @deprecated Please use availableInstallations
*
* install for the connect type
*
* @see Wallet#install
*/
install = (type: ConnectType) => {
if (type === ConnectType.EXTENSION) {
// TODO separate install links by browser types
window.open(CHROME_EXTENSION_INSTALL_URL, '_blank');
} else {
console.warn(
`[WalletController] ConnectType "${type}" does not support install() function`,
);
}
};
/**
* connect to wallet
*
* @see Wallet#connect
*/
connect = (type: ConnectType, identifier?: string) => {
switch (type) {
case ConnectType.READONLY:
const networks: NetworkInfo[] = Object.keys(
this.options.walletConnectChainIds,
).map((chainId) => this.options.walletConnectChainIds[+chainId]);
const createReadonlyWalletSession =
this.options.createReadonlyWalletSession?.(networks) ??
readonlyWalletModal({ networks });
createReadonlyWalletSession.then((readonlyWalletSession) => {
if (readonlyWalletSession) {
this.enableReadonlyWallet(reConnect(readonlyWalletSession));
}
});
break;
case ConnectType.WALLETCONNECT:
this.enableWalletConnect(wcConnect(this.options));
break;
case ConnectType.EXTENSION:
if (!this.extension) {
throw new Error(`extension instance is not created!`);
}
this.extension.connect(identifier);
this.enableExtension();
break;
default:
throw new Error(`Unknown ConnectType!`);
}
};
/**
* manual connect to read only session
*
* @see Wallet#connectReadonly
*/
connectReadonly = (terraAddress: string, network: NetworkInfo) => {
this.enableReadonlyWallet(
reConnect({
terraAddress,
network,
}),
);
};
/** @see Wallet#disconnect */
disconnect = () => {
this.disableReadonlyWallet?.();
this.disableReadonlyWallet = null;
this.disableExtension?.();
this.disableExtension = null;
this.disableWalletConnect?.();
this.disableWalletConnect = null;
this.updateStates(this._notConnected);
};
/**
* @see Wallet#post
* @param tx
* @param terraAddress only available new extension
*/
post = async (
tx: CreateTxOptions,
terraAddress?: string,
): Promise<TxResult> => {
// ---------------------------------------------
// extension
// ---------------------------------------------
if (this.disableExtension) {
return new Promise<TxResult>((resolve, reject) => {
if (!this.extension) {
reject(new Error(`extension instance not created!`));
return;
}
const subscription = this.extension.post(tx, terraAddress).subscribe({
next: (txResult) => {
if (txResult.status === WebExtensionTxStatus.SUCCEED) {
resolve({
...tx,
result: txResult.payload,
success: true,
});
subscription.unsubscribe();
}
},
error: (error) => {
reject(mapExtensionTxError(tx, error));
subscription.unsubscribe();
},
});
});
}
// ---------------------------------------------
// wallet connect
// ---------------------------------------------
else if (this.walletConnect) {
return this.walletConnect
.post(tx)
.then(
(result) =>
({
...tx,
result,
success: true,
} as TxResult),
)
.catch((error) => {
throw mapWalletConnectError(tx, error);
});
} else {
throw new Error(`There are no connections that can be posting tx!`);
}
};
/**
* @see Wallet#sign
* @param tx
* @param terraAddress only available new extension
*/
sign = async (
tx: CreateTxOptions,
terraAddress?: string,
): Promise<SignResult> => {
if (this.disableExtension) {
return new Promise<SignResult>((resolve, reject) => {
if (!this.extension) {
reject(new Error(`extension instance is not created!`));
return;
}
const subscription = this.extension.sign(tx, terraAddress).subscribe({
next: (txResult) => {
if (txResult.status === WebExtensionTxStatus.SUCCEED) {
resolve({
...tx,
result: Tx.fromData(txResult.payload),
success: true,
});
subscription.unsubscribe();
}
},
error: (error) => {
reject(mapExtensionTxError(tx, error));
subscription.unsubscribe();
},
});
});
}
throw new Error(`sign() method only available on extension`);
};
/**
* @see Wallet#signBytes
* @param bytes
* @param terraAddress only available new extension
*/
signBytes = async (
bytes: Buffer,
terraAddress?: string,
): Promise<SignBytesResult> => {
if (this.disableExtension) {
return new Promise<SignBytesResult>((resolve, reject) => {
if (!this.extension) {
reject(new Error(`extension instance is not created!`));
return;
}
const subscription = this.extension
.signBytes(bytes, terraAddress)
.subscribe({
next: (txResult) => {
if (txResult.status === WebExtensionTxStatus.SUCCEED) {
resolve({
result: {
recid: txResult.payload.recid,
signature: Uint8Array.from(
Buffer.from(txResult.payload.signature, 'base64'),
),
public_key: txResult.payload.public_key
? PublicKey.fromData(txResult.payload.public_key)
: undefined,
},
success: true,
});
subscription.unsubscribe();
}
},
error: (error) => {
reject(mapExtensionSignBytesError(bytes, error));
subscription.unsubscribe();
},
});
});
}
throw new Error(`signBytes() method only available on extension`);
// TODO implements signBytes() to other connect types
};
/**
* @see Wallet#hasCW20Tokens
* @param chainID
* @param tokenAddrs Token addresses
*/
hasCW20Tokens = async (
chainID: string,
...tokenAddrs: string[]
): Promise<{ [tokenAddr: string]: boolean }> => {
if (this.availableExtensionFeature('cw20-token')) {
return this.extension!.hasCW20Tokens(chainID, ...tokenAddrs);
}
throw new Error(`Does not support hasCW20Tokens() on this connection`);
};
/**
* @see Wallet#addCW20Tokens
* @param chainID
* @param tokenAddrs Token addresses
*/
addCW20Tokens = async (
chainID: string,
...tokenAddrs: string[]
): Promise<{ [tokenAddr: string]: boolean }> => {
if (this.availableExtensionFeature('cw20-token')) {
return this.extension!.addCW20Tokens(chainID, ...tokenAddrs);
}
throw new Error(`Does not support addCW20Tokens() on this connection`);
};
/**
* @see Wallet#hasNetwork
* @param network
*/
hasNetwork = (network: Omit<NetworkInfo, 'name'>): Promise<boolean> => {
if (this.availableExtensionFeature('network')) {
return this.extension!.hasNetwork(network);
}
throw new Error(`Does not support hasNetwork() on this connection`);
};
/**
* @see Wallet#hasNetwork
* @param network
*/
addNetwork = (network: NetworkInfo): Promise<boolean> => {
if (this.availableExtensionFeature('network')) {
return this.extension!.addNetwork(network);
}
throw new Error(`Does not support addNetwork() on this connection`);
};
// ================================================================
// internal
// connect type changing
// ================================================================
private availableExtensionFeature = (feature: TerraWebExtensionFeatures) => {
if (this.disableExtension && this.extension) {
const states = this.extension.getLastStates();
return (
states.type === ExtensionRouterStatus.WALLET_CONNECTED &&
states.supportFeatures.has(feature)
);
}
};
private updateStates = (next: WalletStates) => {
const prev = this._states.getValue();
if (
next.status === WalletStatus.WALLET_CONNECTED &&
next.wallets.length === 0
) {
next = {
status: WalletStatus.WALLET_NOT_CONNECTED,
network: next.network,
};
}
if (prev.status !== next.status || !deepEqual(prev, next)) {
this._states.next(next);
}
};
private enableReadonlyWallet = (readonlyWallet: ReadonlyWalletController) => {
this.disableWalletConnect?.();
this.disableExtension?.();
if (
this.readonlyWallet === readonlyWallet ||
(this.readonlyWallet?.terraAddress === readonlyWallet.terraAddress &&
this.readonlyWallet.network === readonlyWallet.network)
) {
return;
}
if (this.readonlyWallet) {
this.readonlyWallet.disconnect();
}
this.readonlyWallet = readonlyWallet;
this.updateStates({
status: WalletStatus.WALLET_CONNECTED,
network: readonlyWallet.network,
wallets: [
{
connectType: ConnectType.READONLY,
terraAddress: readonlyWallet.terraAddress,
design: 'readonly',
},
],
supportFeatures: EMPTY_SUPPORT_FEATURES,
connection: CONNECTIONS.READONLY,
});
this.disableReadonlyWallet = () => {
readonlyWallet.disconnect();
this.readonlyWallet = null;
this.disableReadonlyWallet = null;
};
};
private enableExtension = () => {
this.disableReadonlyWallet?.();
this.disableWalletConnect?.();
if (this.disableExtension || !this.extension) {
return;
}
const extensionSubscription = this.extension.states().subscribe({
next: (extensionStates) => {
if (
extensionStates.type === ExtensionRouterStatus.WALLET_CONNECTED &&
AccAddress.validate(extensionStates.wallet.terraAddress)
) {
this.updateStates({
status: WalletStatus.WALLET_CONNECTED,
network: extensionStates.network,
wallets: [
{
connectType: ConnectType.EXTENSION,
terraAddress: extensionStates.wallet.terraAddress,
design: extensionStates.wallet.design,
},
],
supportFeatures: extensionStates.supportFeatures,
connection: memoConnection(
ConnectType.EXTENSION,
extensionStates.extensionInfo.name,
extensionStates.extensionInfo.icon,
extensionStates.extensionInfo.identifier,
),
});
} else {
this.updateStates(this._notConnected);
}
},
});
this.disableExtension = () => {
this.extension?.disconnect();
extensionSubscription.unsubscribe();
this.disableExtension = null;
};
};
private enableWalletConnect = (walletConnect: WalletConnectController) => {
this.disableReadonlyWallet?.();
this.disableExtension?.();
if (this.walletConnect === walletConnect) {
return;
}
if (this.walletConnect) {
this.walletConnect.disconnect();
}
this.walletConnect = walletConnect;
const subscribeWalletConnect = (
wc: WalletConnectController,
): Subscription => {
return wc.session().subscribe({
next: (status) => {
switch (status.status) {
case WalletConnectSessionStatus.CONNECTED:
this.updateStates({
status: WalletStatus.WALLET_CONNECTED,
network:
this.options.walletConnectChainIds[status.chainId] ??
this.options.defaultNetwork,
wallets: [
{
connectType: ConnectType.WALLETCONNECT,
terraAddress: status.terraAddress,
design: 'walletconnect',
},
],
supportFeatures: WALLETCONNECT_SUPPORT_FEATURES,
connection: CONNECTIONS.WALLETCONNECT,
});
break;
default:
this.updateStates(this._notConnected);
break;
}
},
});
};
const walletConnectSessionSubscription =
subscribeWalletConnect(walletConnect);
this.disableWalletConnect = () => {
this.walletConnect?.disconnect();
this.walletConnect = null;
walletConnectSessionSubscription.unsubscribe();
this.disableWalletConnect = null;
};
};
}
const memoizedConnections = new Map<string, Connection>();
function memoConnection(
connectType: ConnectType,
name: string,
icon: string,
identifier: string | undefined = '',
): Connection {
const key = [connectType, name, icon, identifier].join(';');
if (memoizedConnections.has(key)) {
return memoizedConnections.get(key)!;
}
const connection: Connection = {
type: connectType,
name,
icon,
identifier,
};
memoizedConnections.set(key, connection);
return connection;
} | the_stack |
import AssociativeArray from "terriajs-cesium/Source/Core/AssociativeArray";
import Cartesian2 from "terriajs-cesium/Source/Core/Cartesian2";
import Cartesian3 from "terriajs-cesium/Source/Core/Cartesian3";
import CesiumMath from "terriajs-cesium/Source/Core/Math";
import Color from "terriajs-cesium/Source/Core/Color";
import DataSource from "terriajs-cesium/Source/DataSources/DataSource";
import Ellipsoid from "terriajs-cesium/Source/Core/Ellipsoid";
import Entity from "terriajs-cesium/Source/DataSources/Entity";
import EntityCollection from "terriajs-cesium/Source/DataSources/EntityCollection";
import EntityCluster from "terriajs-cesium/Source/DataSources/EntityCluster";
import isDefined from "../Core/isDefined";
import JulianDate from "terriajs-cesium/Source/Core/JulianDate";
import L, { LatLngBounds, PolylineOptions, LatLngBoundsLiteral } from "leaflet";
import LeafletScene from "./LeafletScene";
import PolygonHierarchy from "terriajs-cesium/Source/Core/PolygonHierarchy";
import PolylineGlowMaterialProperty from "terriajs-cesium/Source/DataSources/PolylineGlowMaterialProperty";
import PolylineDashMaterialProperty from "terriajs-cesium/Source/DataSources/PolylineDashMaterialProperty";
import Property from "terriajs-cesium/Source/DataSources/Property";
import Rectangle from "terriajs-cesium/Source/Core/Rectangle";
import { getLineStyleLeaflet } from "../Models/Catalog/Esri/esriLineStyle";
const destroyObject = require("terriajs-cesium/Source/Core/destroyObject")
.default;
const writeTextToCanvas = require("terriajs-cesium/Source/Core/writeTextToCanvas")
.default;
interface PointDetails {
layer?: L.CircleMarker;
lastPosition: Cartesian3;
lastPixelSize: number;
lastColor: Color;
lastOutlineColor: Color;
lastOutlineWidth: number;
}
interface PolygonDetails {
layer?: L.Polygon;
lastHierarchy?: PolygonHierarchy;
lastFill?: boolean;
lastFillColor: Color;
lastOutline?: boolean;
lastOutlineColor: Color;
}
interface RectangleDetails {
layer?: L.Rectangle;
lastFill?: boolean;
lastFillColor: Color;
lastOutline?: boolean;
lastOutlineColor: Color;
}
interface BillboardDetails {
layer?: L.Marker;
}
interface LabelDetails {
layer?: L.Marker;
}
interface PolylineDetails {
layer?: L.Polyline;
}
interface EntityDetails {
point?: PointDetails;
polygon?: PolygonDetails;
billboard?: BillboardDetails;
label?: LabelDetails;
polyline?: PolylineDetails;
rectangle?: RectangleDetails;
}
interface EntityHash {
[key: string]: EntityDetails;
}
const defaultColor = Color.WHITE;
const defaultOutlineColor = Color.BLACK;
const defaultOutlineWidth = 1.0;
const defaultPixelSize = 5.0;
const defaultWidth = 5.0;
//Single pixel black dot
const tmpImage =
"data:image/gif;base64,R0lGODlhAQABAPAAAAAAAP///yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==";
//NOT IMPLEMENTED
// Path primitive - no need identified
// Ellipse primitive - no need identified
// Ellipsoid primitive - 3d prim - no plans for this
// Model primitive - 3d prim - no plans for this
/**
* A variable to store what sort of bounds our leaflet map has been looking at
* 0 = a normal extent
* 1 = zoomed in close to the east/left of anti-meridian
* 2 = zoomed in close to the west/right of the anti-meridian
* When this value changes we'll need to recompute the location of our points
* to help them wrap around the anti-meridian
*/
let prevBoundsType = 0;
/**
* A {@link Visualizer} which maps {@link Entity#point} to Leaflet primitives.
**/
class LeafletGeomVisualizer {
private readonly _featureGroup: L.FeatureGroup;
private readonly _entitiesToVisualize: AssociativeArray;
private readonly _entityHash: EntityHash;
constructor(
readonly leafletScene: LeafletScene,
readonly entityCollection: EntityCollection
) {
entityCollection.collectionChanged.addEventListener(
this._onCollectionChanged,
this
);
this._featureGroup = L.featureGroup().addTo(leafletScene.map);
this._entitiesToVisualize = new AssociativeArray();
this._entityHash = {};
this._onCollectionChanged(
entityCollection,
entityCollection.values,
[],
[]
);
}
private _onCollectionChanged(
_entityCollection: EntityCollection,
added: Entity[],
removed: Entity[],
changed: Entity[]
) {
let entity;
const featureGroup = this._featureGroup;
const entities = this._entitiesToVisualize;
const entityHash = this._entityHash;
for (let i = added.length - 1; i > -1; i--) {
entity = added[i];
if (
((isDefined(entity.point) ||
isDefined(entity.billboard) ||
isDefined(entity.label)) &&
isDefined(entity.position)) ||
isDefined(entity.polyline) ||
isDefined(entity.polygon) ||
isDefined(entity.rectangle)
) {
entities.set(entity.id, entity);
entityHash[entity.id] = {};
}
}
for (let i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (
((isDefined(entity.point) ||
isDefined(entity.billboard) ||
isDefined(entity.label)) &&
isDefined(entity.position)) ||
isDefined(entity.polyline) ||
isDefined(entity.polygon) ||
isDefined(entity.rectangle)
) {
entities.set(entity.id, entity);
entityHash[entity.id] = entityHash[entity.id] || {};
} else {
cleanEntity(entity, featureGroup, entityHash);
entities.remove(entity.id);
}
}
for (let i = removed.length - 1; i > -1; i--) {
entity = removed[i];
cleanEntity(entity, featureGroup, entityHash);
entities.remove(entity.id);
}
}
/**
* Updates the primitives created by this visualizer to match their
* Entity counterpart at the given time.
*
*/
public update(time: JulianDate): boolean {
const entities = this._entitiesToVisualize.values;
const entityHash = this._entityHash;
const bounds = this.leafletScene.map.getBounds();
let applyLocalisedAntiMeridianFix = false;
let currentBoundsType = 0;
if (_isCloseToEasternAntiMeridian(bounds)) {
applyLocalisedAntiMeridianFix = true;
currentBoundsType = 1;
} else if (_isCloseToWesternAntiMeridian(bounds)) {
applyLocalisedAntiMeridianFix = true;
currentBoundsType = 2;
}
for (let i = 0, len = entities.length; i < len; i++) {
const entity = entities[i];
const entityDetails = entityHash[entity.id];
if (isDefined(entity._point)) {
this._updatePoint(
entity,
time,
entityHash,
entityDetails,
applyLocalisedAntiMeridianFix === true ? bounds : undefined,
prevBoundsType !== currentBoundsType
);
}
if (isDefined(entity.billboard)) {
this._updateBillboard(
entity,
time,
entityHash,
entityDetails,
applyLocalisedAntiMeridianFix === true ? bounds : undefined
);
}
if (isDefined(entity.label)) {
this._updateLabel(entity, time, entityHash, entityDetails);
}
if (isDefined(entity.polyline)) {
this._updatePolyline(entity, time, entityHash, entityDetails);
}
if (isDefined(entity.polygon)) {
this._updatePolygon(entity, time, entityHash, entityDetails);
}
if (isDefined(entity.rectangle)) {
this._updateRectangle(entity, time, entityHash, entityDetails);
}
}
prevBoundsType = currentBoundsType;
return true;
}
private _updatePoint(
entity: Entity,
time: JulianDate,
_entityHash: EntityHash,
entityDetails: EntityDetails,
bounds: LatLngBounds | undefined,
boundsJustChanged: boolean
) {
const featureGroup = this._featureGroup;
const pointGraphics = entity.point!;
const show =
entity.isAvailable(time) &&
getValueOrDefault(pointGraphics.show, time, true);
if (!show) {
cleanPoint(entity, featureGroup, entityDetails);
return;
}
let details = entityDetails.point;
if (!isDefined(details)) {
details = entityDetails.point = {
layer: undefined,
lastPosition: new Cartesian3(),
lastPixelSize: 1,
lastColor: new Color(),
lastOutlineColor: new Color(),
lastOutlineWidth: 1
};
}
const position = getValueOrUndefined(entity.position, time);
if (!isDefined(position)) {
cleanPoint(entity, featureGroup, entityDetails);
return;
}
const pixelSize = getValueOrDefault(
pointGraphics.pixelSize,
time,
defaultPixelSize
);
const color = getValueOrDefault(pointGraphics.color, time, defaultColor);
const outlineColor = getValueOrDefault(
pointGraphics.outlineColor,
time,
defaultOutlineColor
);
const outlineWidth = getValueOrDefault(
pointGraphics.outlineWidth,
time,
defaultOutlineWidth
);
let layer = details.layer;
if (!isDefined(layer)) {
const pointOptions = {
radius: pixelSize / 2.0,
fillColor: color.toCssColorString(),
fillOpacity: color.alpha,
color: outlineColor.toCssColorString(),
weight: outlineWidth,
opacity: outlineColor.alpha
};
layer = details.layer = L.circleMarker(
positionToLatLng(position, bounds),
pointOptions
);
layer.on("click", featureClicked.bind(undefined, this, entity));
layer.on("mousedown", featureMousedown.bind(undefined, this, entity));
featureGroup.addLayer(layer);
Cartesian3.clone(position, details.lastPosition);
details.lastPixelSize = pixelSize;
Color.clone(color, details.lastColor);
Color.clone(outlineColor, details.lastOutlineColor);
details.lastOutlineWidth = outlineWidth;
return layer;
}
if (
!Cartesian3.equals(position, details.lastPosition) ||
boundsJustChanged
) {
layer.setLatLng(positionToLatLng(position, bounds));
Cartesian3.clone(position, details.lastPosition);
}
if (pixelSize !== details.lastPixelSize) {
layer.setRadius(pixelSize / 2.0);
details.lastPixelSize = pixelSize;
}
const options = layer.options;
let applyStyle = false;
if (!Color.equals(color, details.lastColor)) {
options.fillColor = color.toCssColorString();
options.fillOpacity = color.alpha;
Color.clone(color, details.lastColor);
applyStyle = true;
}
if (!Color.equals(outlineColor, details.lastOutlineColor)) {
options.color = outlineColor.toCssColorString();
options.opacity = outlineColor.alpha;
Color.clone(outlineColor, details.lastOutlineColor);
applyStyle = true;
}
if (outlineWidth !== details.lastOutlineWidth) {
options.weight = outlineWidth;
details.lastOutlineWidth = outlineWidth;
applyStyle = true;
}
if (applyStyle) {
layer.setStyle(options);
}
}
private _updateBillboard(
entity: Entity,
time: JulianDate,
_entityHash: EntityHash,
entityDetails: EntityDetails,
bounds: LatLngBounds | undefined
) {
const markerGraphics = entity.billboard!;
const featureGroup = this._featureGroup;
let position;
let marker: L.Marker;
let details = entityDetails.billboard;
if (!isDefined(details)) {
details = entityDetails.billboard = {
layer: undefined
};
}
const geomLayer = details.layer;
let show =
entity.isAvailable(time) &&
getValueOrDefault(markerGraphics.show, time, true);
if (show) {
position = getValueOrUndefined(entity.position, time);
show = isDefined(position);
}
if (!show) {
cleanBillboard(entity, featureGroup, entityDetails);
return;
}
const cart = Ellipsoid.WGS84.cartesianToCartographic(position);
const latlng = positionToLatLng(position, bounds);
const image: any = getValue(markerGraphics.image, time);
const height: number | undefined = getValue(markerGraphics.height, time);
const width: number | undefined = getValue(markerGraphics.width, time);
const color = getValueOrDefault(markerGraphics.color, time, defaultColor);
const scale = getValueOrDefault(markerGraphics.scale, time, 1.0);
const verticalOrigin = getValueOrDefault(
markerGraphics.verticalOrigin,
time,
0
);
const horizontalOrigin = getValueOrDefault(
markerGraphics.horizontalOrigin,
time,
0
);
const pixelOffset = getValueOrDefault(
markerGraphics.pixelOffset,
time,
Cartesian2.ZERO
);
let imageUrl: string | undefined;
if (isDefined(image)) {
if (typeof image === "string") {
imageUrl = image;
} else if (isDefined(image.toDataURL)) {
imageUrl = image.toDataURL();
} else if (isDefined(image.url)) {
imageUrl = image.url;
} else {
imageUrl = image.src;
}
}
const iconOptions: any = {
color: color.toCssColorString(),
origUrl: imageUrl,
scale: scale,
horizontalOrigin: horizontalOrigin, //value: left, center, right
verticalOrigin: verticalOrigin //value: bottom, center, top
};
if (isDefined(height) || isDefined(width)) {
iconOptions.iconSize = [width, height];
}
let redrawIcon = false;
if (!isDefined(geomLayer)) {
const markerOptions = { icon: L.icon({ iconUrl: tmpImage }) };
marker = L.marker(latlng, markerOptions);
marker.on("click", featureClicked.bind(undefined, this, entity));
marker.on("mousedown", featureMousedown.bind(undefined, this, entity));
featureGroup.addLayer(marker);
details.layer = marker;
redrawIcon = true;
} else {
marker = geomLayer;
if (!marker.getLatLng().equals(latlng)) {
marker.setLatLng(latlng);
}
for (const prop in iconOptions) {
if (
isDefined(marker.options.icon) &&
iconOptions[prop] !== (<any>marker.options.icon.options)[prop]
) {
redrawIcon = true;
break;
}
}
}
if (redrawIcon) {
const drawBillboard = function(
image: HTMLImageElement,
dataurl: string | undefined
) {
iconOptions.iconUrl = dataurl || image;
if (!isDefined(iconOptions.iconSize)) {
iconOptions.iconSize = [image.width * scale, image.height * scale];
}
const w = iconOptions.iconSize[0],
h = iconOptions.iconSize[1];
const xOff = (w / 2) * (1 - horizontalOrigin) - pixelOffset.x;
const yOff = (h / 2) * (1 + verticalOrigin) - pixelOffset.y;
iconOptions.iconAnchor = [xOff, yOff];
if (!color.equals(defaultColor)) {
iconOptions.iconUrl = recolorBillboard(image, color);
}
marker.setIcon(L.icon(iconOptions));
};
const img = new Image();
img.onload = function() {
drawBillboard(img, imageUrl);
};
if (isDefined(imageUrl)) {
img.src = imageUrl;
}
}
}
private _updateLabel(
entity: Entity,
time: JulianDate,
_entityHash: EntityHash,
entityDetails: EntityDetails
) {
const labelGraphics = entity.label!;
const featureGroup = this._featureGroup;
let position;
let marker: L.Marker;
let details = entityDetails.label;
if (!isDefined(details)) {
details = entityDetails.label = {
layer: undefined
};
}
const geomLayer = details.layer;
let show =
entity.isAvailable(time) &&
getValueOrDefault(labelGraphics.show, time, true);
if (show) {
position = getValueOrUndefined(entity.position, time);
show = isDefined(position);
}
if (!show) {
cleanLabel(entity, featureGroup, entityDetails);
return;
}
const cart = Ellipsoid.WGS84.cartesianToCartographic(position);
const latlng = L.latLng(
CesiumMath.toDegrees(cart.latitude),
CesiumMath.toDegrees(cart.longitude)
);
const text = getValue(labelGraphics.text, time);
const font = getValue((labelGraphics.font as unknown) as Property, time);
const scale = getValueOrDefault(labelGraphics.scale, time, 1.0);
const fillColor = getValueOrDefault(
(labelGraphics.fillColor as unknown) as Property,
time,
defaultColor
);
const verticalOrigin = getValueOrDefault(
labelGraphics.verticalOrigin,
time,
0
);
const horizontalOrigin = getValueOrDefault(
labelGraphics.horizontalOrigin,
time,
0
);
const pixelOffset = getValueOrDefault(
labelGraphics.pixelOffset,
time,
Cartesian2.ZERO
);
const iconOptions: any = {
text: text,
font: font,
color: fillColor.toCssColorString(),
scale: scale,
horizontalOrigin: horizontalOrigin, //value: left, center, right
verticalOrigin: verticalOrigin //value: bottom, center, top
};
let redrawLabel = false;
if (!isDefined(geomLayer)) {
const markerOptions = { icon: L.icon({ iconUrl: tmpImage }) };
marker = L.marker(latlng, markerOptions);
marker.on("click", featureClicked.bind(undefined, this, entity));
marker.on("mousedown", featureMousedown.bind(undefined, this, entity));
featureGroup.addLayer(marker);
details.layer = marker;
redrawLabel = true;
} else {
marker = geomLayer;
if (!marker.getLatLng().equals(latlng)) {
marker.setLatLng(latlng);
}
for (const prop in iconOptions) {
if (
isDefined(marker.options.icon) &&
iconOptions[prop] !== (<any>marker.options.icon.options)[prop]
) {
redrawLabel = true;
break;
}
}
}
if (redrawLabel) {
const drawBillboard = function(image: HTMLImageElement, dataurl: string) {
iconOptions.iconUrl = dataurl || image;
if (!isDefined(iconOptions.iconSize)) {
iconOptions.iconSize = [image.width * scale, image.height * scale];
}
const w = iconOptions.iconSize[0],
h = iconOptions.iconSize[1];
const xOff = (w / 2) * (1 - horizontalOrigin) - pixelOffset.x;
const yOff = (h / 2) * (1 + verticalOrigin) - pixelOffset.y;
iconOptions.iconAnchor = [xOff, yOff];
marker.setIcon(L.icon(iconOptions));
};
const canvas = writeTextToCanvas(text, {
fillColor: fillColor,
font: font
});
const imageUrl = canvas.toDataURL();
const img = new Image();
img.onload = function() {
drawBillboard(img, imageUrl);
};
img.src = imageUrl;
}
}
private _updateRectangle(
entity: Entity,
time: JulianDate,
_entityHash: EntityHash,
entityDetails: EntityDetails
) {
const featureGroup = this._featureGroup;
const rectangleGraphics = entity.rectangle;
if (!isDefined(rectangleGraphics)) {
return;
}
const show =
entity.isAvailable(time) &&
getValueOrDefault(rectangleGraphics.show, time, true);
const rectangleCoordinates = rectangleGraphics.coordinates?.getValue(
time
) as Rectangle;
if (!show || !isDefined(rectangleCoordinates)) {
cleanRectangle(entity, featureGroup, entityDetails);
return;
}
const rectangleBounds: LatLngBoundsLiteral = [
[
CesiumMath.toDegrees(rectangleCoordinates.south),
CesiumMath.toDegrees(rectangleCoordinates.west)
],
[
CesiumMath.toDegrees(rectangleCoordinates.north),
CesiumMath.toDegrees(rectangleCoordinates.east)
]
];
let details = entityDetails.rectangle;
if (!isDefined(details)) {
details = entityDetails.rectangle = {
layer: undefined,
lastFill: undefined,
lastFillColor: new Color(),
lastOutline: undefined,
lastOutlineColor: new Color()
};
}
const fill = getValueOrDefault(
(rectangleGraphics.fill as unknown) as Property,
time,
true
);
const outline = getValueOrDefault(rectangleGraphics.outline, time, true);
let dashArray;
if (rectangleGraphics.outline instanceof PolylineDashMaterialProperty) {
dashArray = getDashArray(rectangleGraphics.outline, time);
}
const outlineWidth = getValueOrDefault(
(rectangleGraphics.outlineWidth as unknown) as Property,
time,
defaultOutlineWidth
);
const outlineColor = getValueOrDefault(
(rectangleGraphics.outlineColor as unknown) as Property,
time,
defaultOutlineColor
);
const material = getValueOrUndefined(
(rectangleGraphics.material as unknown) as Property,
time
);
let fillColor;
if (isDefined(material) && isDefined(material.color)) {
fillColor = material.color;
} else {
fillColor = defaultColor;
}
let layer = details.layer;
if (!isDefined(layer)) {
const polygonOptions: PolylineOptions = {
fill: fill,
fillColor: fillColor.toCssColorString(),
fillOpacity: fillColor.alpha,
weight: outline ? outlineWidth : 0.0,
color: outlineColor.toCssColorString(),
opacity: outlineColor.alpha
};
if (outline && dashArray) {
polygonOptions.dashArray = dashArray
.map(x => x * outlineWidth)
.join(",");
}
layer = details.layer = L.rectangle(rectangleBounds, polygonOptions);
layer.on("click", featureClicked.bind(undefined, this, entity));
layer.on("mousedown", featureMousedown.bind(undefined, this, entity));
featureGroup.addLayer(layer);
details.lastFill = fill;
details.lastOutline = outline;
Color.clone(fillColor, details.lastFillColor);
Color.clone(outlineColor, details.lastOutlineColor);
return;
}
const options = layer.options;
let applyStyle = false;
if (fill !== details.lastFill) {
options.fill = fill;
details.lastFill = fill;
applyStyle = true;
}
if (outline !== details.lastOutline) {
options.weight = outline ? outlineWidth : 0.0;
details.lastOutline = outline;
applyStyle = true;
}
if (!Color.equals(fillColor, details.lastFillColor)) {
options.fillColor = fillColor.toCssColorString();
options.fillOpacity = fillColor.alpha;
Color.clone(fillColor, details.lastFillColor);
applyStyle = true;
}
if (!Color.equals(outlineColor, details.lastOutlineColor)) {
options.color = outlineColor.toCssColorString();
options.opacity = outlineColor.alpha;
Color.clone(outlineColor, details.lastOutlineColor);
applyStyle = true;
}
if (!layer.getBounds().equals(rectangleBounds)) {
layer.setBounds(rectangleBounds);
}
if (applyStyle) {
layer.setStyle(options);
}
}
private _updatePolygon(
entity: Entity,
time: JulianDate,
_entityHash: EntityHash,
entityDetails: EntityDetails
) {
const featureGroup = this._featureGroup;
const polygonGraphics = entity.polygon!;
const show =
entity.isAvailable(time) &&
getValueOrDefault(polygonGraphics.show, time, true);
if (!show) {
cleanPolygon(entity, featureGroup, entityDetails);
return;
}
let details = entityDetails.polygon;
if (!isDefined(details)) {
details = entityDetails.polygon = {
layer: undefined,
lastHierarchy: undefined,
lastFill: undefined,
lastFillColor: new Color(),
lastOutline: undefined,
lastOutlineColor: new Color()
};
}
const hierarchy = getValueOrUndefined(polygonGraphics.hierarchy, time);
if (!isDefined(hierarchy)) {
cleanPolygon(entity, featureGroup, entityDetails);
return;
}
const fill = getValueOrDefault(
(polygonGraphics.fill as unknown) as Property,
time,
true
);
const outline = getValueOrDefault(polygonGraphics.outline, time, true);
let dashArray;
if (polygonGraphics.outline instanceof PolylineDashMaterialProperty) {
dashArray = getDashArray(polygonGraphics.outline, time);
}
const outlineWidth = getValueOrDefault(
(polygonGraphics.outlineWidth as unknown) as Property,
time,
defaultOutlineWidth
);
const outlineColor = getValueOrDefault(
(polygonGraphics.outlineColor as unknown) as Property,
time,
defaultOutlineColor
);
const material = getValueOrUndefined(
(polygonGraphics.material as unknown) as Property,
time
);
let fillColor;
if (isDefined(material) && isDefined(material.color)) {
fillColor = material.color;
} else {
fillColor = defaultColor;
}
let layer = details.layer;
if (!isDefined(layer)) {
const polygonOptions: PolylineOptions = {
fill: fill,
fillColor: fillColor.toCssColorString(),
fillOpacity: fillColor.alpha,
weight: outline ? outlineWidth : 0.0,
color: outlineColor.toCssColorString(),
opacity: outlineColor.alpha
};
if (outline && dashArray) {
polygonOptions.dashArray = dashArray
.map(x => x * outlineWidth)
.join(",");
}
layer = details.layer = L.polygon(
hierarchyToLatLngs(hierarchy),
polygonOptions
);
layer.on("click", featureClicked.bind(undefined, this, entity));
layer.on("mousedown", featureMousedown.bind(undefined, this, entity));
featureGroup.addLayer(layer);
details.lastHierarchy = hierarchy;
details.lastFill = fill;
details.lastOutline = outline;
Color.clone(fillColor, details.lastFillColor);
Color.clone(outlineColor, details.lastOutlineColor);
return;
}
if (hierarchy !== details.lastHierarchy) {
layer.setLatLngs(hierarchyToLatLngs(hierarchy));
details.lastHierarchy = hierarchy;
}
const options = layer.options;
let applyStyle = false;
if (fill !== details.lastFill) {
options.fill = fill;
details.lastFill = fill;
applyStyle = true;
}
if (outline !== details.lastOutline) {
options.weight = outline ? outlineWidth : 0.0;
details.lastOutline = outline;
applyStyle = true;
}
if (!Color.equals(fillColor, details.lastFillColor)) {
options.fillColor = fillColor.toCssColorString();
options.fillOpacity = fillColor.alpha;
Color.clone(fillColor, details.lastFillColor);
applyStyle = true;
}
if (!Color.equals(outlineColor, details.lastOutlineColor)) {
options.color = outlineColor.toCssColorString();
options.opacity = outlineColor.alpha;
Color.clone(outlineColor, details.lastOutlineColor);
applyStyle = true;
}
if (applyStyle) {
layer.setStyle(options);
}
}
private _updatePolyline(
entity: Entity,
time: JulianDate,
_entityHash: EntityHash,
entityDetails: EntityDetails
) {
const polylineGraphics = entity.polyline!;
const featureGroup = this._featureGroup;
let positions, polyline;
let details = entityDetails.polyline;
if (!isDefined(details)) {
details = entityDetails.polyline = {
layer: undefined
};
}
const geomLayer = details.layer;
let show =
entity.isAvailable(time) &&
getValueOrDefault(polylineGraphics.show, time, true);
if (show) {
positions = getValueOrUndefined(polylineGraphics.positions, time);
show = isDefined(positions);
}
if (!show) {
cleanPolyline(entity, featureGroup, entityDetails);
return;
}
const carts = Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
const latlngs = [];
for (let p = 0; p < carts.length; p++) {
latlngs.push(
L.latLng(
CesiumMath.toDegrees(carts[p].latitude),
CesiumMath.toDegrees(carts[p].longitude)
)
);
}
let color;
let dashArray: number[] | undefined;
let width: number;
if (polylineGraphics.material instanceof PolylineGlowMaterialProperty) {
color = defaultColor;
width = defaultWidth;
} else {
const material = polylineGraphics.material.getValue(time);
if (isDefined(material)) {
color = material.color;
}
color = color || defaultColor;
width = getValueOrDefault(
(polylineGraphics.width as unknown) as Property,
time,
defaultWidth
);
}
if (polylineGraphics.material instanceof PolylineDashMaterialProperty) {
dashArray = getDashArray(polylineGraphics.material, time);
}
const polylineOptions: PolylineOptions = {
color: color.toCssColorString(),
weight: width,
opacity: color.alpha
};
if (dashArray) {
polylineOptions.dashArray = dashArray.map(x => x * width).join(",");
}
if (!isDefined(geomLayer)) {
if (latlngs.length > 0) {
polyline = L.polyline(latlngs, polylineOptions);
polyline.on("click", featureClicked.bind(undefined, this, entity));
polyline.on(
"mousedown",
featureMousedown.bind(undefined, this, entity)
);
featureGroup.addLayer(polyline);
details.layer = polyline;
}
} else {
polyline = geomLayer;
const curLatLngs = polyline.getLatLngs();
let bPosChange = latlngs.length !== curLatLngs.length;
for (let i = 0; i < curLatLngs.length && !bPosChange; i++) {
const latlng = curLatLngs[i];
if (latlng instanceof L.LatLng && latlng.equals(latlngs[i])) {
bPosChange = true;
}
}
if (bPosChange) {
polyline.setLatLngs(latlngs);
}
for (let prop in polylineOptions) {
if ((<any>polylineOptions)[prop] !== (<any>polyline.options)[prop]) {
polyline.setStyle(polylineOptions);
break;
}
}
}
}
/**
* Returns true if this object was destroyed; otherwise, false.
*
*/
isDestroyed(): boolean {
return false;
}
/**
* Removes and destroys all primitives created by this instance.
*/
destroy() {
const entities = this._entitiesToVisualize.values;
const entityHash = this._entityHash;
for (let i = entities.length - 1; i > -1; i--) {
cleanEntity(entities[i], this._featureGroup, entityHash);
}
this.entityCollection.collectionChanged.removeEventListener(
this._onCollectionChanged,
this
);
this.leafletScene.map.removeLayer(this._featureGroup);
return destroyObject(this);
}
/**
* Computes the rectangular bounds which encloses the collection of
* entities to be visualized.
*/
getLatLngBounds(): LatLngBounds | undefined {
let result: LatLngBounds | undefined;
Object.keys(this._entityHash).forEach(entityId => {
const entityDetails: any = this._entityHash[entityId];
Object.keys(entityDetails).forEach(primitiveId => {
const primitive = entityDetails[primitiveId];
if (isDefined(primitive.layer)) {
if (isDefined(primitive.layer.getBounds)) {
const bounds = primitive.layer.getBounds();
if (isDefined(bounds)) {
result =
result === undefined
? L.latLngBounds(bounds.getSouthWest(), bounds.getNorthEast())
: result.extend(bounds);
}
}
if (isDefined(primitive.layer.getLatLng)) {
const latLng = primitive.layer.getLatLng();
if (isDefined(latLng)) {
result =
result === undefined
? L.latLngBounds([latLng])
: result.extend(latLng);
}
}
}
});
});
return result;
}
}
function getDashArray(
material: PolylineDashMaterialProperty,
time: JulianDate
): number[] {
let dashArray;
const dashPattern = material.dashPattern
? material.dashPattern.getValue(time)
: undefined;
return getLineStyleLeaflet(dashPattern);
}
function cleanEntity(
entity: Entity,
group: L.FeatureGroup,
entityHash: EntityHash
) {
const details = entityHash[entity.id];
cleanPoint(entity, group, details);
cleanPolygon(entity, group, details);
cleanBillboard(entity, group, details);
cleanLabel(entity, group, details);
cleanPolyline(entity, group, details);
delete entityHash[entity.id];
}
function cleanPoint(
_entity: Entity,
group: L.FeatureGroup,
details: EntityDetails
) {
if (isDefined(details.point) && isDefined(details.point.layer)) {
group.removeLayer(details.point.layer);
details.point = undefined;
}
}
function cleanPolygon(
_entity: Entity,
group: L.FeatureGroup,
details: EntityDetails
) {
if (isDefined(details.polygon) && isDefined(details.polygon.layer)) {
group.removeLayer(details.polygon.layer);
details.polygon = undefined;
}
}
function cleanBillboard(
_entity: Entity,
group: L.FeatureGroup,
details: EntityDetails
) {
if (isDefined(details.billboard) && isDefined(details.billboard.layer)) {
group.removeLayer(details.billboard.layer);
details.billboard = undefined;
}
}
function cleanLabel(
_entity: Entity,
group: L.FeatureGroup,
details: EntityDetails
) {
if (isDefined(details.label) && isDefined(details.label.layer)) {
group.removeLayer(details.label.layer);
details.label = undefined;
}
}
function cleanPolyline(
_entity: Entity,
group: L.FeatureGroup,
details: EntityDetails
) {
if (isDefined(details.polyline) && isDefined(details.polyline.layer)) {
group.removeLayer(details.polyline.layer);
details.polyline = undefined;
}
}
function cleanRectangle(
_entity: Entity,
group: L.FeatureGroup,
details: EntityDetails
) {
if (isDefined(details.rectangle) && isDefined(details.rectangle.layer)) {
group.removeLayer(details.rectangle.layer);
details.rectangle = undefined;
}
}
function _isCloseToEasternAntiMeridian(bounds: LatLngBounds) {
const w = bounds.getWest();
const e = bounds.getEast();
if (w > 140 && (e < -140 || e > 180)) {
return true;
}
return false;
}
function _isCloseToWesternAntiMeridian(bounds: LatLngBounds) {
const w = bounds.getWest();
const e = bounds.getEast();
if ((w > 180 || w < -140) && e < -140) {
return true;
}
return false;
}
function positionToLatLng(
position: Cartesian3,
bounds: LatLngBounds | undefined
) {
var cartographic = Ellipsoid.WGS84.cartesianToCartographic(position);
let lon = CesiumMath.toDegrees(cartographic.longitude);
if (bounds !== undefined) {
if (_isCloseToEasternAntiMeridian(bounds)) {
if (lon < -140) {
lon = lon + 360;
}
} else if (_isCloseToWesternAntiMeridian(bounds)) {
if (lon > 140) {
lon = lon - 360;
}
}
}
return L.latLng(CesiumMath.toDegrees(cartographic.latitude), lon);
}
function hierarchyToLatLngs(hierarchy: PolygonHierarchy) {
let holes: L.LatLng[][] = [];
const positions = Array.isArray(hierarchy) ? hierarchy : hierarchy.positions;
if (hierarchy.holes.length > 0) {
hierarchy.holes.forEach(hole => {
holes.push(convertEntityPositionsToLatLons(hole.positions));
});
return [convertEntityPositionsToLatLons(positions), ...holes];
} else {
return convertEntityPositionsToLatLons(positions);
}
}
//Recolor an image using 2d canvas
function recolorBillboard(
img: HTMLImageElement,
color: Color
): string | undefined {
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
const context = canvas.getContext("2d");
if (context === null) {
return;
}
context.drawImage(img, 0, 0);
const image = context.getImageData(0, 0, canvas.width, canvas.height);
const normClr = [color.red, color.green, color.blue, color.alpha];
const length = image.data.length; //pixel count * 4
for (let i = 0; i < length; i += 4) {
for (let j = 0; j < 4; j++) {
image.data[j + i] *= normClr[j];
}
}
context.putImageData(image, 0, 0);
return canvas.toDataURL();
}
function featureClicked(
visualizer: LeafletGeomVisualizer,
entity: Entity,
event: L.LeafletEvent
) {
visualizer.leafletScene.featureClicked.raiseEvent(entity, event);
}
function featureMousedown(
visualizer: LeafletGeomVisualizer,
entity: Entity,
event: L.LeafletEvent
) {
visualizer.leafletScene.featureMousedown.raiseEvent(entity, event);
}
function getValue<T>(
property: Property | undefined,
time: JulianDate
): T | undefined {
if (isDefined(property)) {
return property.getValue(time);
}
}
function getValueOrDefault<T>(
property: Property | undefined,
time: JulianDate,
defaultValue: T
): T {
if (isDefined(property)) {
const value = property.getValue(time);
if (isDefined(value)) {
return value;
}
}
return defaultValue;
}
function getValueOrUndefined(property: Property | undefined, time: JulianDate) {
if (isDefined(property)) {
return property.getValue(time);
}
}
function convertEntityPositionsToLatLons(positions: Cartesian3[]): L.LatLng[] {
var carts = Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
var latlngs: L.LatLng[] = [];
let lastLongitude;
for (var p = 0; p < carts.length; p++) {
let lon = CesiumMath.toDegrees(carts[p].longitude);
if (lastLongitude !== undefined) {
if (lastLongitude - lon > 180) {
lon = lon + 360;
} else if (lastLongitude - lon < -180) {
lon = lon - 360;
}
}
latlngs.push(L.latLng(CesiumMath.toDegrees(carts[p].latitude), lon));
lastLongitude = lon;
}
return latlngs;
}
export default class LeafletVisualizer {
visualizersCallback(
leafletScene: LeafletScene,
_entityCluster: EntityCluster,
dataSource: DataSource
) {
const entities = dataSource.entities;
return [new LeafletGeomVisualizer(leafletScene, entities)];
}
} | the_stack |
import * as _ from 'lodash';
import Autolinker, { HashtagServices, MentionServices } from '../src/autolinker';
import { UrlMatch } from "../src/match/url-match";
import { EmailMatch } from "../src/match/email-match";
import { HashtagMatch } from "../src/match/hashtag-match";
import { MentionMatch } from "../src/match/mention-match";
import { PhoneMatch } from "../src/match/phone-match";
import { Match } from '../src/match/match';
describe( "Autolinker", function() {
describe( "instantiating and using as a class", function() {
it( "should configure the instance with configuration options, and then be able to execute the link() method", function() {
let autolinker = new Autolinker( { newWindow: false, truncate: 25 } );
let result = autolinker.link( "Check out http://www.yahoo.com/some/long/path/to/a/file" );
expect( result ).toBe( 'Check out <a href="http://www.yahoo.com/some/long/path/to/a/file" title="http://www.yahoo.com/some/long/path/to/a/file">yahoo.com/some/long/pa…</a>' );
} );
} );
describe( "config checking", function() {
describe( "no configs", function() {
it( "should default to the default options if no `cfg` object is provided (namely, `newWindow: true`)", function() {
expect( Autolinker.link( "Welcome to google.com" ) ).toBe( 'Welcome to <a href="http://google.com" target="_blank" rel="noopener noreferrer">google.com</a>' );
} );
} );
describe( "`hashtag` cfg", function() {
it( "should throw if `hashtag` is a value other than `false` or one of the valid service names", function() {
expect( function() {
new Autolinker( { hashtag: true } as any ); // `true` is an invalid value - must be a service name
} ).toThrowError( "invalid `hashtag` cfg - see docs" );
expect( function() {
new Autolinker( { hashtag: 'non-existent-service' } as any );
} ).toThrowError( "invalid `hashtag` cfg - see docs" );
} );
it( "should not throw for the valid service name 'twitter'", function() {
expect( function() {
new Autolinker( { hashtag: 'twitter' } );
} ).not.toThrow();
} );
it( "should not throw for the valid service name 'facebook'", function() {
expect( function() {
new Autolinker( { hashtag: 'facebook' } );
} ).not.toThrow();
} );
it( "should not throw for the valid service name 'instagram'", function() {
expect( function() {
new Autolinker( { hashtag: 'instagram' } );
} ).not.toThrow();
} );
} );
describe( '`mention` cfg', function() {
it( "should throw if `mention` is a value other than `false` or one of the valid service names", function() {
expect( function() {
new Autolinker( { mention: true } as any ); // `true` is an invalid value - must be a service name
} ).toThrowError( "invalid `mention` cfg - see docs" );
expect( function() {
new Autolinker( { mention: 'non-existent-service' } as any );
} ).toThrowError( "invalid `mention` cfg - see docs" );
} );
it( "should not throw for the valid service name 'twitter'", function() {
expect( function() {
new Autolinker( { mention: 'twitter' } );
} ).not.toThrow();
} );
it( "should not throw for the valid service name 'instagram'", function() {
expect( function() {
new Autolinker( { mention: 'instagram' } );
} ).not.toThrow();
} );
} );
} );
describe( "link() method", function() {
let autolinker: Autolinker,
twitterAutolinker: Autolinker;
beforeEach( function() {
autolinker = new Autolinker( { newWindow: false } ); // so that target="_blank" is not added to resulting autolinked URLs
twitterAutolinker = new Autolinker( { mention: 'twitter', newWindow: false } );
} );
it( 'should return an empty string when provided `undefined` as its argument', function() {
expect( autolinker.link( undefined as any ) ).toBe( '' );
} );
it( 'should return an empty string when provided `null` as its argument', function() {
expect( autolinker.link( null as any ) ).toBe( '' );
} );
describe( "proper handling of HTML in the input string", function() {
it( "should automatically link URLs past the last HTML tag", function() {
let result = autolinker.link( '<p>Joe went to <a href="http://www.yahoo.com">yahoo</a></p> and http://google.com' );
expect( result ).toBe( '<p>Joe went to <a href="http://www.yahoo.com">yahoo</a></p> and <a href="http://google.com">google.com</a>' );
} );
it( "should NOT automatically link URLs within the attributes of existing HTML tags", function() {
let result = autolinker.link( '<p>Joe went to <a href="http://www.yahoo.com">yahoo</a></p>' );
expect( result ).toBe( '<p>Joe went to <a href="http://www.yahoo.com">yahoo</a></p>' );
} );
it( "should NOT automatically link URLs within the attributes of existing HTML tags when there are prefixed or suffixed spaces in the attribute values", function() {
let result = autolinker.link( '<p>Joe went to <a href=" http://www.yahoo.com">yahoo</a></p>' );
expect( result ).toBe( '<p>Joe went to <a href=" http://www.yahoo.com">yahoo</a></p>' );
let result2 = autolinker.link( '<p>Joe went to <a href="http://www.yahoo.com ">yahoo</a></p>' );
expect( result2 ).toBe( '<p>Joe went to <a href="http://www.yahoo.com ">yahoo</a></p>' );
} );
it( "when unquoted anchor href's exist, should NOT automatically link the text inside", function() {
let result = autolinker.link( '<p>Joe went to <a href=http://www.yahoo.com>yahoo</a></p>' );
expect( result ).toBe( '<p>Joe went to <a href=http://www.yahoo.com>yahoo</a></p>' );
let result2 = autolinker.link( '<p>Joe went to <a href=http://www.yahoo.com?query=1>yahoo</a></p>' );
expect( result2 ).toBe( '<p>Joe went to <a href=http://www.yahoo.com?query=1>yahoo</a></p>' );
} );
it( "should NOT automatically link URLs within self-closing tags", function() {
let result = autolinker.link( 'Just a flower image <img src="https://farm9.staticflickr.com/8378/8578790632_83c6471f3f_b.jpg" />' );
expect( result ).toBe( 'Just a flower image <img src="https://farm9.staticflickr.com/8378/8578790632_83c6471f3f_b.jpg" />' );
} );
it( "should NOT automatically link a URL found within the inner text of a pre-existing anchor tag", function() {
let result = autolinker.link( '<p>Joe went to <a href="http://www.yahoo.com">yahoo.com</a></p> yesterday.' );
expect( result ).toBe( '<p>Joe went to <a href="http://www.yahoo.com">yahoo.com</a></p> yesterday.' );
} );
it( "should NOT automatically link a URL found within the inner text of a pre-existing anchor tag that uses a capital letter for its tag name", function() {
let result = autolinker.link( '<p>Joe went to <A href="http://www.yahoo.com">yahoo.com</A></p> yesterday.' );
expect( result ).toBe( '<p>Joe went to <A href="http://www.yahoo.com">yahoo.com</A></p> yesterday.' );
} );
it( "should NOT automatically link a URL found within the inner text of a pre-existing anchor tag, but link others", function() {
let result = autolinker.link( '<p>Joe went to google.com, <a href="http://www.yahoo.com">yahoo.com</a>, and weather.com</p> yesterday.' );
expect( result ).toBe( '<p>Joe went to <a href="http://google.com">google.com</a>, <a href="http://www.yahoo.com">yahoo.com</a>, and <a href="http://weather.com">weather.com</a></p> yesterday.' );
} );
it( "should NOT automatically link an image tag with incorrect HTML attribute spacing", function() {
let result = autolinker.link( '<img src="https://ssl.gstatic.com/welcome_calendar.png" alt="Calendar" style="display:block;"width="129"height="129"/>' );
expect( result ).toBe( '<img src="https://ssl.gstatic.com/welcome_calendar.png" alt="Calendar" style="display:block;"width="129"height="129"/>' );
} );
it( "should NOT automatically link an image tag with a URL inside it, inside an anchor tag", function() {
let result = autolinker.link( '<a href="http://google.com"><img src="http://google.com/someImage.jpg" /></a>' );
expect( result ).toBe( '<a href="http://google.com"><img src="http://google.com/someImage.jpg" /></a>' );
} );
it( "should NOT automatically link an image tag with a URL inside it, inside an anchor tag, but match urls around the tags", function() {
let result = autolinker.link( 'google.com looks like <a href="http://google.com"><img src="http://google.com/someImage.jpg" /></a> (at google.com)' );
expect( result ).toBe( '<a href="http://google.com">google.com</a> looks like <a href="http://google.com"><img src="http://google.com/someImage.jpg" /></a> (at <a href="http://google.com">google.com</a>)' );
} );
it( "should NOT automatically link a URL found within the inner text of a style tag", function() {
var result = autolinker.link( 'Testing with <style> .class { background-image: url("http://www.example.com/image.png"); } </style> tags' );
expect( result ).toBe( 'Testing with <style> .class { background-image: url("http://www.example.com/image.png"); } </style> tags' );
} );
it( "should NOT automatically link a URL found within the inner text of a script tag", function() {
var result = autolinker.link( 'Testing with <script> alert("http://google.com"); </script> tags' );
expect( result ).toBe( 'Testing with <script> alert("http://google.com"); </script> tags' );
} );
it( "should NOT automatically link an image tag with a URL inside of it, when it has another attribute which has extraneous spaces surround its value (Issue #45)", function() {
let result = autolinker.link( "Testing <img src='http://terryshoemaker.files.wordpress.com/2013/03/placeholder1.jpg' style=' height: 22px; background-color: rgb(0, 188, 204); border-radius: 7px; padding: 2px; margin: 0px 2px;'>" );
expect( result ).toBe( "Testing <img src='http://terryshoemaker.files.wordpress.com/2013/03/placeholder1.jpg' style=' height: 22px; background-color: rgb(0, 188, 204); border-radius: 7px; padding: 2px; margin: 0px 2px;'>" );
} );
it( "should NOT automatically link a tag within an attribute of another tag (Issue #45)", function() {
let result = autolinker.link( '<form class="approval-form" name="thumbsUp" ng-submit="postApproval()"> <button type="submit"> <img class="thumbs-up" ng-click="comment.body=\'<img src=\'http://example.com/api-public/images/wg/w/Rating_and_Approval/icon-thumbs-up.png\' style=\'height: 22px; background-color: rgb(0, 188, 204); border-radius: 7px; padding: 2px; margin: 0px 2px;\'>\'+comment.body;" ng-src="http://example.com/api-public/images/wg/w/Rating_and_Approval/icon-thumbs-up.png"> </button> </form>' );
expect( result ).toBe( '<form class="approval-form" name="thumbsUp" ng-submit="postApproval()"> <button type="submit"> <img class="thumbs-up" ng-click="comment.body=\'<img src=\'http://example.com/api-public/images/wg/w/Rating_and_Approval/icon-thumbs-up.png\' style=\'height: 22px; background-color: rgb(0, 188, 204); border-radius: 7px; padding: 2px; margin: 0px 2px;\'>\'+comment.body;" ng-src="http://example.com/api-public/images/wg/w/Rating_and_Approval/icon-thumbs-up.png"> </button> </form>' );
} );
it( "should NOT remove `br` tags from the output (Issue #46)", function() {
let result = autolinker.link( "Testing<br /> with<br/> br<br> tags" );
expect( result ).toBe( "Testing<br /> with<br/> br<br> tags" );
} );
it( "should NOT automatically link anything in a !DOCTYPE tag (Issue #53)", function() {
let input = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
let result = autolinker.link( input );
expect( result ).toBe( input );
} );
it( "should NOT automatically link within comment tags", function() {
let result = autolinker.link( '<!-- google.com -->' );
expect( result ).toBe( '<!-- google.com -->' );
} );
it( "should NOT automatically link within multi-line comment tags", function() {
let result = autolinker.link( '<!--\n\tgoogle.com\n\t-->' );
expect( result ).toBe( '<!--\n\tgoogle.com\n\t-->' );
} );
it( "should automatically link between comment tags, but not the comment tags themselves", function() {
let result = autolinker.link( '<!-- google.com -->\nweather.com\n<!-- http://yahoo.com -->' );
expect( result ).toBe( '<!-- google.com -->\n<a href="http://weather.com">weather.com</a>\n<!-- http://yahoo.com -->' );
} );
it( "should NOT automatically link within comment tags, using part of the comment tag as the URL (Issue #88)", function() {
let result = autolinker.link( '<!--.post-author-->' );
expect( result ).toBe( '<!--.post-author-->' );
} );
it( "should automatically link tags after a !DOCTYPE tag", function() {
let input = [
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'<html>',
'<body>',
'Welcome to mysite.com',
'</body>',
'</html>'
].join( "" );
let result = autolinker.link( input );
expect( result ).toBe( [
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'<html>',
'<body>',
'Welcome to <a href="http://mysite.com">mysite.com</a>',
'</body>',
'</html>'
].join( "" ) );
} );
it( "should autolink the link, and not fail with 100% cpu in the Regex engine when presented with the input in issue #54", function() {
let inputStr = "Shai ist endlich in Deutschland! Und wir haben gute Nachrichten! <3 Alle, die den Shai-Rasierer kostenlos probieren, machen am Gewinnspiel eines Jahresvorrates Klingen mit. Den Rasierer bekommst Du kostenlos durch diesen Link: http://dorcoshai.de/pb1205ro, und dann machst Du am Gewinnspiel mit! Gefallt mir klicken, wenn Du gern einen Jahresvorrat Shai haben mochtest. (Y)",
result = autolinker.link( inputStr );
expect( result ).toBe( 'Shai ist endlich in Deutschland! Und wir haben gute Nachrichten! <3 Alle, die den Shai-Rasierer kostenlos probieren, machen am Gewinnspiel eines Jahresvorrates Klingen mit. Den Rasierer bekommst Du kostenlos durch diesen Link: <a href="http://dorcoshai.de/pb1205ro">dorcoshai.de/pb1205ro</a>, und dann machst Du am Gewinnspiel mit! Gefallt mir klicken, wenn Du gern einen Jahresvorrat Shai haben mochtest. (Y)' );
} );
it( "should not fail with an infinite loop for these given input strings (Issue #160)", function() {
let inputStrings = [
'asdf ouefof<33we oeweofjojfew oeijwffejifjew ojiwjoiwefj iowjefojwe iofjw:)<33',
'<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3',
'<33<33<33<33<33<33<33<33<33<33',
'<33<33<33<33<33<33<33<33<33<33<33'
];
inputStrings.forEach( function( str ) {
expect( autolinker.link( str ) ).toBe( str ); // no links in these, just making sure they don't fail with 100% cpu and an infinite loop
} );
} );
it( "should not fail with an infinite loop for an input string with " +
"completely invalid HTML (issue #160)",
function() {
let result = autolinker.link(
'<US_Con_SL_RTNS@dell.com\n' +
'He gave me a 1-800 customer care number that I\'ve called twice. The last time I called, about 3 weeks ago, the customer rep said he would request an expedited response. He gave me a reference number which is 925767619. Thankyou very much for looking into this.\n' +
'\n' +
'Ronald D Brigham\n' +
'brigham@mtnhome.com'
);
expect( result ).toBe( [
'<<a href="mailto:US_Con_SL_RTNS@dell.com">US_Con_SL_RTNS@dell.com</a>',
'He gave me a 1-800 customer care number that I\'ve called twice. The last time I called, about 3 weeks ago, the customer rep said he would request an expedited response. He gave me a reference number which is 925767619. Thankyou very much for looking into this.',
'',
'Ronald D Brigham',
'<a href="mailto:brigham@mtnhome.com">brigham@mtnhome.com</a>'
].join( '\n' ) );
} );
it( "should not fail with an infinite loop for an input string with " +
"marginally valid HTML (issue #157)",
function() {
let str = "Our first step should be to get a CBC with differential, accompanied by a blood smear. The blood smear will be read (by a Hematologist) as sparse platelets among RBCs and some WBCs, that will most likely be normal. The platelets that do show up on the blood smear may or may not be damaged. In the case of TTP, platelets should not be damaged, but rather just low in number. A CBC with platelet count <50K starts to raise eyebrows for a possible case requiring platelet transfusion. Now would be the time to get a Type & Screen, and most would also tend towards ordering PT, PTT, and INR, or the \"coagulative\" measurement laboratory tests. Confirmation of TTP would be made by a serum ADAMST13 activity level.";
let result = autolinker.link( str );
expect( result ).toBe( str );
} );
it( "should not fail with an infinite loop for an input string with " +
"an emoji (although really the <3 might be the original problem - " +
"issue #165)",
function() {
let str = '-Que estupendos nos vemos <3#lapeorfoto #despedida2016 #dehoyoenhoyo #rabbit';
let result = autolinker.link( str );
expect( result ).toBe( str );
} );
it( "should not fail with an infinite loop for an input string with " +
"a string that looks like HTML (Issue #172)",
function() {
let str = '<Office%20days:%20Tue.%20&%20Wed.%20(till%2015:30%20hr),%20Thu.%20(till%2017:30%20hr),%20Fri.%20(till%2012:30%20hr).%3c/a%3e%3cbr%3e%3c/td%3e%3ctd%20style=>',
result = autolinker.link( str );
expect( result ).toBe( str );
} );
it( "should not fail with a Maximum Call Stack Size Exceeded for an " +
"input with a large number of html entities (Issue #171)",
function() {
let testStr = (function() {
let t = [];
for (let i = 0; i < 50000; i++) {
t.push( ' /><br' );
}
return t.join( '' );
})();
let result = autolinker.link( testStr );
expect( result ).toBe( testStr );
} );
it( "should NOT modify the email address with other tags when inside another anchor", function() {
let input = [
'<div>First name: Subin</div>',
'<div>Surname: Sundar</div>',
'<div>',
'EmailMatch: ',
'<a href="mailto:subin.sundar@yo.in">',
'<font color="blue"><u>s</u></font>',
'<font color="blue"><u>ubin</u></font>',
'<font color="blue"><u>.sundar@yo.in</u></font>',
'</a>',
'</div>'
].join( "" );
let result = autolinker.link( input );
expect( result ).toBe( input );
} );
it( "should allow the full range of HTML attribute name characters as specified in the W3C HTML syntax document (http://www.w3.org/TR/html-markup/syntax.html)", function() {
// Note: We aren't actually expecting the HTML to be modified by this test
let inAndOutHtml = '<ns:p>Foo <a data-qux-="" href="http://www.example.com">Bar<\/a> Baz<\/ns:p>';
expect( autolinker.link( inAndOutHtml ) ).toBe( inAndOutHtml );
} );
it( "should properly autolink text within namespaced HTML elements, skipping over html elements with urls in attribute values", function() {
let html = '<ns:p>Go to google.com or <a data-qux-="test" href="http://www.example.com">Bar<\/a> Baz<\/ns:p>';
let result = autolinker.link( html );
expect( result ).toBe( '<ns:p>Go to <a href="http://google.com">google.com</a> or <a data-qux-="test" href="http://www.example.com">Bar<\/a> Baz<\/ns:p>' );
} );
it( "should properly skip over attribute names that could be interpreted as urls, while still autolinking urls in their inner text", function() {
let html = '<div google.com anotherAttr yahoo.com>My div that has an attribute of google.com</div>';
let result = autolinker.link( html );
expect( result ).toBe( '<div google.com anotherAttr yahoo.com>My div that has an attribute of <a href="http://google.com">google.com</a></div>' );
} );
it( "should properly skip over attribute names that could be interpreted as urls when they have a value, while still autolinking urls in their inner text", function() {
let html = '<div google.com="yes" anotherAttr=true yahoo.com="true">My div that has an attribute of google.com</div>';
let result = autolinker.link( html );
expect( result ).toBe( '<div google.com="yes" anotherAttr=true yahoo.com="true">My div that has an attribute of <a href="http://google.com">google.com</a></div>' );
} );
it( "should properly skip over attribute names that could be interpreted as urls when they have a value and any number of spaces between attrs, while still autolinking urls in their inner text", function() {
let html = '<div google.com="yes" \t\t anotherAttr=true yahoo.com="true" \t>My div that has an attribute of google.com</div>';
let result = autolinker.link( html );
expect( result ).toBe( '<div google.com="yes" \t\t anotherAttr=true yahoo.com="true" \t>My div that has an attribute of <a href="http://google.com">google.com</a></div>' );
} );
it( "should properly skip over attribute values that could be interpreted as urls/emails/twitter/mention accts, while still autolinking urls in their inner text", function() {
let html = '<div url="google.com" email="asdf@asdf.com" mention="@asdf">google.com asdf@asdf.com @asdf</div>';
let result = twitterAutolinker.link( html );
expect( result ).toBe( [
'<div url="google.com" email="asdf@asdf.com" mention="@asdf">',
'<a href="http://google.com">google.com</a> ',
'<a href="mailto:asdf@asdf.com">asdf@asdf.com</a> ',
'<a href="https://twitter.com/asdf">@asdf</a>',
'</div>'
].join( "" ) );
} );
it( "should properly skip over attribute names and values that could be interpreted as urls/emails/twitter accts, while still autolinking urls in their inner text", function() {
let html = '<div google.com="google.com" asdf@asdf.com="asdf@asdf.com" @asdf="@asdf">google.com asdf@asdf.com @asdf</div>';
let result = twitterAutolinker.link( html );
expect( result ).toBe( [
'<div google.com="google.com" asdf@asdf.com="asdf@asdf.com" @asdf="@asdf">',
'<a href="http://google.com">google.com</a> ',
'<a href="mailto:asdf@asdf.com">asdf@asdf.com</a> ',
'<a href="https://twitter.com/asdf">@asdf</a>',
'</div>'
].join( "" ) );
} );
it( "should properly handle HTML markup + text nodes that are nested within <a> tags", function() {
let html = '<a href="http://google.com"><b>google.com</b></a>';
let result = autolinker.link( html );
expect( result ).toBe( html );
} );
it( "should attempt to handle some invalid HTML markup relating to <a> tags, esp if there are extraneous closing </a> tags", function() {
let html = '</a><a href="http://google.com">google.com</a>';
let result = autolinker.link( html );
expect( result ).toBe( html );
} );
it( "should attempt to handle some more complex invalid HTML markup relating to <a> tags, esp if there are extraneous closing </a> tags", function() {
let html = [
'</a>', // invalid
'<a href="http://google.com">google.com</a>',
'<div>google.com</div>',
'</a>', // invalid
'<a href="http://yahoo.com">yahoo.com</a>',
'</a>', // invalid
'</a>', // invalid
'twitter.com'
].join( "" );
let result = autolinker.link( html );
expect( result ).toBe( [
'</a>', // invalid - left alone
'<a href="http://google.com">google.com</a>', // valid tag - left alone
'<div><a href="http://google.com">google.com</a></div>', // autolinked text in <div>
'</a>', // invalid - left alone
'<a href="http://yahoo.com">yahoo.com</a>', // valid tag - left alone
'</a>', // invalid - left alone
'</a>', // invalid - left alone
'<a href="http://twitter.com">twitter.com</a>' // autolinked text
].join( "" ) );
} );
it( "should handle after a url and not treat it as a query string", function() {
let html = "<p>Joe went to yahoo.com and google.com today</p>";
let result = autolinker.link( html );
expect( result ).toBe('<p>Joe went to <a href="http://yahoo.com">yahoo.com</a> and <a href="http://google.com">google.com</a> today</p>');
} );
it( "should handle HTML entities like within a non-autolinked part of a text node, properly appending it to the output", function() {
let html = "Joe went to yahoo.com and used HTML entities like > and < google.com";
let result = autolinker.link( html );
expect( result ).toBe( 'Joe went to <a href="http://yahoo.com">yahoo.com</a> and used HTML entities like > and < <a href="http://google.com">google.com</a>');
} );
it( "should handle & inside a url and not ignore it", function() {
let html = "<p>Joe went to example.com?arg=1&arg=2&arg=3</p>";
let result = autolinker.link( html );
expect( result ).toBe( '<p>Joe went to <a href="http://example.com?arg=1&arg=2&arg=3">example.com?arg=1&arg=2&arg=3</a></p>' );
} );
it( "should handle line breaks inside an HTML tag, not accidentally autolinking a URL within the tag", function() {
let html = '<a href="http://close.io/" style="font-family: Helvetica,\nArial">http://close.io</a>';
let result = autolinker.link( html );
expect( result ).toBe( '<a href="http://close.io/" style="font-family: Helvetica,\nArial">http://close.io</a>' );
} );
it( "should handle a URL inside an HTML-encoded anchor tag (Issue #76)", function() {
let html = "Joe learned about anchor tags on the <a href="http://www.w3schools.com/aaa">W3SCHOOLS</a> site ...";
let tobe = "Joe learned about anchor tags on the <a href="<a href=\"http://www.w3schools.com/aaa\">w3schools.com/aaa</a>">W3SCHOOLS</a> site ...";
let result = autolinker.link( html );
expect( result ).toBe( tobe );
} );
it( "should parse joined matchers", function() {
var html = "+1123123123http://google.com";
var tobe = "<a href=\"tel:+1123123123\">+1123123123</a><a href=\"http://google.com\">google.com</a>";
var result = autolinker.link( html );
expect( result ).toBe( tobe );
} );
} );
describe( "HTML entity character handling", () => {
it( "should handle an HTML entity at the beginning of the string", function() {
let result = autolinker.link( '&now go to google.com' );
expect( result ).toBe( '&now go to <a href="http://google.com">google.com</a>' );
} );
it( "should handle an HTML entity at the end of the string", function() {
let result = autolinker.link( 'now go to google.com &' );
expect( result ).toBe( 'now go to <a href="http://google.com">google.com</a> &' );
} );
it( "should handle an HTML entity at the beginning and end of the string", function() {
let result = autolinker.link( '&now go to google.com &' );
expect( result ).toBe( '&now go to <a href="http://google.com">google.com</a> &' );
} );
it( "should handle an HTML entity in the middle of the string", function() {
let result = autolinker.link( 'now &go to google.com' );
expect( result ).toBe( 'now &go to <a href="http://google.com">google.com</a>' );
} );
it( "should handle a string with only an HTML entity", function() {
let result = autolinker.link( '&' );
expect( result ).toBe( '&' );
} );
} );
describe( "`newWindow` option", function() {
it( "should not add target=\"_blank\" when the 'newWindow' option is set to false", function() {
let result = Autolinker.link( "Test http://url.com", { newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com">url.com</a>' );
} );
it( "should add target=\"_blank\" and rel=\"noopener noreferrer\" when the 'newWindow' option is set to true (see https://mathiasbynens.github.io/rel-noopener/ about the 'rel' attribute, which prevents a potential phishing attack)", function() {
let result = Autolinker.link( "Test http://url.com", { newWindow: true } );
expect( result ).toBe( 'Test <a href="http://url.com" target="_blank" rel="noopener noreferrer">url.com</a>' );
} );
} );
describe( "`stripPrefix` option", function() {
it( "should not remove the prefix for non-http protocols", function() {
let result = Autolinker.link( "Test file://execute-virus.com", { stripPrefix: true, newWindow: false } );
expect( result ).toBe( 'Test <a href="file://execute-virus.com">file://execute-virus.com</a>' );
} );
it( "should remove 'http://www.' when the 'stripPrefix' option is set to `true`", function() {
let result = Autolinker.link( "Test http://www.url.com", { stripPrefix: true, newWindow: false } );
expect( result ).toBe( 'Test <a href="http://www.url.com">url.com</a>' );
} );
it( "should not remove 'http://www.' when the 'stripPrefix' option is set to `false`", function() {
let result = Autolinker.link( "Test http://www.url.com", { stripPrefix: false, newWindow: false } );
expect( result ).toBe( 'Test <a href="http://www.url.com">http://www.url.com</a>' );
} );
it( 'should leave the original text as-is when the `stripPrefix` option is `false`', function() {
let result1 = Autolinker.link( 'My url.com', { stripPrefix: false, newWindow: false } );
expect( result1 ).toBe( 'My <a href="http://url.com">url.com</a>' );
let result2 = Autolinker.link( 'My www.url.com', { stripPrefix: false, newWindow: false } );
expect( result2 ).toBe( 'My <a href="http://www.url.com">www.url.com</a>' );
let result3 = Autolinker.link( 'My http://url.com', { stripPrefix: false, newWindow: false } );
expect( result3 ).toBe( 'My <a href="http://url.com">http://url.com</a>' );
let result4 = Autolinker.link( 'My http://www.url.com', { stripPrefix: false, newWindow: false } );
expect( result4 ).toBe( 'My <a href="http://www.url.com">http://www.url.com</a>' );
} );
it( "should remove the prefix by default", function() {
let result = Autolinker.link( "Test http://www.url.com", { newWindow: false } );
expect( result ).toBe( 'Test <a href="http://www.url.com">url.com</a>' );
} );
it( "when stripPrefix `scheme` is true, but `www` is false, it should " +
"only strip the scheme",
function() {
let result = Autolinker.link( "Test http://www.url.com", {
stripPrefix: { scheme: true, www: false },
newWindow: false
} );
expect( result ).toBe( 'Test <a href="http://www.url.com">www.url.com</a>' );
} );
it( "when stripPrefix `scheme` is false, but `www` is true, it should " +
"only strip the 'www'",
function() {
let result = Autolinker.link( "Test http://www.url.com", {
stripPrefix: { scheme: false, www: true },
newWindow: false
} );
expect( result ).toBe( 'Test <a href="http://www.url.com">http://url.com</a>' );
} );
it( "when stripPrefix `scheme` is false, but `www` is true for a " +
"scheme-only URL, it should not strip anything",
function() {
let result = Autolinker.link( "Test http://url.com", {
stripPrefix: { scheme: false, www: true },
newWindow: false
} );
expect( result ).toBe( 'Test <a href="http://url.com">http://url.com</a>' );
} );
it( "when stripPrefix `scheme` is false, but `www` is true for a " +
"'www'-only URL, it should strip the 'www'",
function() {
let result = Autolinker.link( "Test www.url.com", {
stripPrefix: { scheme: false, www: true },
newWindow: false
} );
expect( result ).toBe( 'Test <a href="http://www.url.com">url.com</a>' );
} );
it( "when stripPrefix `scheme` is true and `www` is true, it should " +
"strip the entire prefix (scheme and 'www')",
function() {
let result = Autolinker.link( "Test http://www.url.com", {
stripPrefix: { scheme: true, www: true },
newWindow: false
} );
expect( result ).toBe( 'Test <a href="http://www.url.com">url.com</a>' );
} );
it( "when stripPrefix `scheme` is false and `www` is false, it should " +
"not strip any prefix",
function() {
let result = Autolinker.link( "Test http://www.url.com", {
stripPrefix: { scheme: false, www: false },
newWindow: false
} );
expect( result ).toBe( 'Test <a href="http://www.url.com">http://www.url.com</a>' );
} );
} );
describe( "`stripTrailingSlash` option", function() {
it( "by default, should remove the trailing slash", function() {
let result = Autolinker.link( "http://google.com/", {
stripPrefix : false,
//stripTrailingSlash : true, -- not providing this cfg
newWindow : false
} );
expect( result ).toBe( '<a href="http://google.com/">http://google.com</a>' );
} );
it( "when provided as `true`, should remove the trailing slash", function() {
let result = Autolinker.link( "http://google.com/", {
stripPrefix : false,
stripTrailingSlash : true,
newWindow : false
} );
expect( result ).toBe( '<a href="http://google.com/">http://google.com</a>' );
} );
it( "when provided as `false`, should not remove (i.e. retain) the " +
"trailing slash",
function() {
let result = Autolinker.link( "http://google.com/", {
stripPrefix : false,
stripTrailingSlash : false,
newWindow : false
} );
expect( result ).toBe( '<a href="http://google.com/">http://google.com/</a>' );
} );
} );
describe( "`decodePercentEncoding` option", function() {
it( "by default, should decode percent-encoding", function() {
var result = Autolinker.link( "https://en.wikipedia.org/wiki/San_Jos%C3%A9", {
stripPrefix : false,
//decodePercentEncoding : true, -- not providing this cfg
newWindow : false
} );
expect( result ).toBe( '<a href="https://en.wikipedia.org/wiki/San_Jos%C3%A9">https://en.wikipedia.org/wiki/San_José</a>' );
} );
it( "when provided as `true`, should decode percent-encoding", function() {
var result = Autolinker.link( "https://en.wikipedia.org/wiki/San_Jos%C3%A9", {
stripPrefix : false,
decodePercentEncoding : true,
newWindow : false
} );
expect( result ).toBe( '<a href="https://en.wikipedia.org/wiki/San_Jos%C3%A9">https://en.wikipedia.org/wiki/San_José</a>' );
} );
it( "when provided as `false`, should not decode percent-encoding",
function() {
var result = Autolinker.link( "https://en.wikipedia.org/wiki/San_Jos%C3%A9", {
stripPrefix : false,
decodePercentEncoding : false,
newWindow : false
} );
expect( result ).toBe( '<a href="https://en.wikipedia.org/wiki/San_Jos%C3%A9">https://en.wikipedia.org/wiki/San_Jos%C3%A9</a>' );
} );
} );
describe( "`truncate` option", function() {
describe( 'number form', function() {
it( "should not perform any truncation if the `truncate` option is not passed in", function() {
let result = Autolinker.link( "Test http://url.com/with/path", { newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com/with/path">url.com/with/path</a>' );
} );
it( "should not perform any truncation if `truncate` is 0", function() {
let result = Autolinker.link( "Test http://url.com/with/path", { truncate: 0, newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com/with/path">url.com/with/path</a>' );
} );
it( "should truncate long a url/email/twitter to the given number of characters with the 'truncate' option specified", function() {
let result = Autolinker.link( "Test http://url.com/with/path", { truncate: 12, newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com/with/path" title="http://url.com/with/path">url.com/w…</a>' );
} );
it( "should leave a url/email/twitter alone if the length of the url is exactly equal to the length of the 'truncate' option", function() {
let result = Autolinker.link( "Test http://url.com/with/path", { truncate: 'url.com/with/path'.length, newWindow: false } ); // the exact length of the link
expect( result ).toBe( 'Test <a href="http://url.com/with/path">url.com/with/path</a>' );
} );
it( "should leave a url/email/twitter alone if it does not exceed the given number of characters provided in the 'truncate' option", function() {
let result = Autolinker.link( "Test http://url.com/with/path", { truncate: 25, newWindow: false } ); // just a random high number
expect( result ).toBe( 'Test <a href="http://url.com/with/path">url.com/with/path</a>' );
} );
} );
describe( 'object form (with `length` and `location` properties)', function() {
it( "should not perform any truncation if `truncate.length` is not passed in", function() {
let result = Autolinker.link( "Test http://url.com/with/path", { truncate: { location: 'end' }, newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com/with/path">url.com/with/path</a>' );
} );
it( "should not perform any truncation if `truncate.length` is 0", function() {
let result = Autolinker.link( "Test http://url.com/with/path", { truncate: { length: 0 }, newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com/with/path">url.com/with/path</a>' );
} );
it( 'should default the `location` to "end" if it is not provided', function() {
let result = Autolinker.link( "Test http://url.com/with/path", { truncate: { length: 12 }, newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com/with/path" title="http://url.com/with/path">url.com/w…</a>' );
} );
it( 'should truncate at the end when `location: "end"` is specified', function() {
let result = Autolinker.link( "Test http://url.com/with/path", { truncate: { length: 12, location: 'end' }, newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com/with/path" title="http://url.com/with/path">url.com/w…</a>' );
} );
it( 'should truncate in the middle when `location: "middle"` is specified', function() {
let result = Autolinker.link( "Test http://url.com/with/path", { truncate: { length: 12, location: 'middle' }, newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com/with/path" title="http://url.com/with/path">url.c…path</a>' );
} );
it( 'should truncate according to the "smart" truncation rules when `location: "smart"` is specified', function() {
let result = Autolinker.link( "Test http://url.com/with/path", { truncate: { length: 12, location: 'smart' }, newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com/with/path" title="http://url.com/with/path">url.com/…h</a>' );
} );
} );
} );
describe( "`className` option", function() {
it( "should not add className when the 'className' option is not a string with at least 1 character", function() {
let result = Autolinker.link( "Test http://url.com", { newWindow: false } );
expect( result ).toBe( 'Test <a href="http://url.com">url.com</a>' );
result = Autolinker.link( "Test http://url.com", { newWindow: false, className: null } as any );
expect( result ).toBe( 'Test <a href="http://url.com">url.com</a>' );
result = Autolinker.link( "Test http://url.com", { newWindow: false, className: "" } );
expect( result ).toBe( 'Test <a href="http://url.com">url.com</a>' );
} );
it( "should add className to links", function() {
let result = Autolinker.link( "Test http://url.com", { newWindow: false, className: 'myLink' } );
expect( result ).toBe( 'Test <a href="http://url.com" class="myLink myLink-url">url.com</a>' );
} );
it( "should add className to email links", function() {
let result = Autolinker.link( "Iggy's email is mr@iggypop.com", { newWindow: false, email: true, className: 'myLink' } );
expect( result ).toBe( 'Iggy\'s email is <a href="mailto:mr@iggypop.com" class="myLink myLink-email">mr@iggypop.com</a>' );
} );
it( "should add className to twitter links", function() {
let result = Autolinker.link( "hi from @iggypopschest", { newWindow: false, mention: 'twitter', className: 'myLink' } );
expect( result ).toBe( 'hi from <a href="https://twitter.com/iggypopschest" class="myLink myLink-mention myLink-twitter">@iggypopschest</a>' );
} );
it( "should add className to mention links", function() {
let result = Autolinker.link( "hi from @iggypopschest", { newWindow: false, mention: 'twitter', className: 'myLink' } );
expect( result ).toBe( 'hi from <a href="https://twitter.com/iggypopschest" class="myLink myLink-mention myLink-twitter">@iggypopschest</a>' );
result = Autolinker.link( "hi from @iggypopschest", { newWindow: false, mention: 'instagram', className: 'myLink' } );
expect( result ).toBe( 'hi from <a href="https://instagram.com/iggypopschest" class="myLink myLink-mention myLink-instagram">@iggypopschest</a>' );
} );
} );
describe( '`urls` option', function() {
let str = 'http://google.com www.google.com google.com'; // the 3 types: scheme URL, www URL, and TLD (top level domain) URL
it( 'should link all 3 types if the `urls` option is `true`', function() {
let result = Autolinker.link( str, { newWindow: false, stripPrefix: false, urls: true } );
expect( result ).toBe( [
'<a href="http://google.com">http://google.com</a>',
'<a href="http://www.google.com">www.google.com</a>',
'<a href="http://google.com">google.com</a>'
].join( ' ' ) );
} );
it( 'should not link any of the 3 types if the `urls` option is `false`', function() {
let result = Autolinker.link( str, { newWindow: false, stripPrefix: false, urls: false } );
expect( result ).toBe( [
'http://google.com',
'www.google.com',
'google.com'
].join( ' ' ) );
} );
it( 'should only link scheme URLs if `schemeMatches` is the only `urls` option that is `true`', function() {
let result = Autolinker.link( str, { newWindow: false, stripPrefix: false, urls: {
schemeMatches : true,
wwwMatches : false,
tldMatches : false
} } );
expect( result ).toBe( [
'<a href="http://google.com">http://google.com</a>',
'www.google.com',
'google.com'
].join( ' ' ) );
} );
it( 'should only link www URLs if `wwwMatches` is the only `urls` option that is `true`', function() {
let result = Autolinker.link( str, { newWindow: false, stripPrefix: false, urls: {
schemeMatches : false,
wwwMatches : true,
tldMatches : false
} } );
expect( result ).toBe( [
'http://google.com',
'<a href="http://www.google.com">www.google.com</a>',
'google.com'
].join( ' ' ) );
} );
it( 'should only link TLD URLs if `tldMatches` is the only `urls` option that is `true`', function() {
let result = Autolinker.link( str, { newWindow: false, stripPrefix: false, urls: {
schemeMatches : false,
wwwMatches : false,
tldMatches : true
} } );
expect( result ).toBe( [
'http://google.com',
'www.google.com',
'<a href="http://google.com">google.com</a>'
].join( ' ' ) );
} );
it( 'should link both scheme and www matches, but not TLD matches when `tldMatches` is the only option that is `false`', function() {
let result = Autolinker.link( str, { newWindow: false, stripPrefix: false, urls: {
schemeMatches : true,
wwwMatches : true,
tldMatches : false
} } );
expect( result ).toBe( [
'<a href="http://google.com">http://google.com</a>',
'<a href="http://www.google.com">www.google.com</a>',
'google.com'
].join( ' ' ) );
} );
} );
describe( "`urls` (as boolean), `email`, `phone`, `twitter`, and `mention` options", function() {
let inputStr = [
"Website: asdf.com",
"EmailMatch: asdf@asdf.com",
"Phone: (123) 456-7890",
"Mention: @asdf",
"HashtagMatch: #asdf"
].join( ", " );
it( "should link all 5 types if all 5 urls/email/phone/mention/hashtag options are enabled", function() {
let result = Autolinker.link( inputStr, {
hashtag: 'twitter',
mention: 'twitter',
newWindow: false
} );
expect( result ).toBe( [
'Website: <a href="http://asdf.com">asdf.com</a>',
'EmailMatch: <a href="mailto:asdf@asdf.com">asdf@asdf.com</a>',
'Phone: <a href="tel:1234567890">(123) 456-7890</a>',
'Mention: <a href="https://twitter.com/asdf">@asdf</a>',
'HashtagMatch: <a href="https://twitter.com/hashtag/asdf">#asdf</a>'
].join( ", " ) );
} );
it( "should link mentions based on value provided to mention option", function() {
let result = Autolinker.link( inputStr, { newWindow: false, hashtag: 'twitter', mention: 'twitter' } );
expect( result ).toBe( [
'Website: <a href="http://asdf.com">asdf.com</a>',
'EmailMatch: <a href="mailto:asdf@asdf.com">asdf@asdf.com</a>',
'Phone: <a href="tel:1234567890">(123) 456-7890</a>',
'Mention: <a href="https://twitter.com/asdf">@asdf</a>',
'HashtagMatch: <a href="https://twitter.com/hashtag/asdf">#asdf</a>'
].join( ", " ) );
result = Autolinker.link( inputStr, { newWindow: false, hashtag: 'twitter', mention: 'instagram' } );
expect( result ).toBe( [
'Website: <a href="http://asdf.com">asdf.com</a>',
'EmailMatch: <a href="mailto:asdf@asdf.com">asdf@asdf.com</a>',
'Phone: <a href="tel:1234567890">(123) 456-7890</a>',
'Mention: <a href="https://instagram.com/asdf">@asdf</a>',
'HashtagMatch: <a href="https://twitter.com/hashtag/asdf">#asdf</a>'
].join( ", " ) );
} );
it( "should not link urls when they are disabled", function() {
let result = Autolinker.link( inputStr, {
mention: 'twitter',
hashtag: 'twitter',
urls: false,
newWindow: false
} );
expect( result ).toBe( [
'Website: asdf.com',
'EmailMatch: <a href="mailto:asdf@asdf.com">asdf@asdf.com</a>',
'Phone: <a href="tel:1234567890">(123) 456-7890</a>',
'Mention: <a href="https://twitter.com/asdf">@asdf</a>',
'HashtagMatch: <a href="https://twitter.com/hashtag/asdf">#asdf</a>'
].join( ", " ) );
} );
it( "should not link email addresses when they are disabled", function() {
let result = Autolinker.link( inputStr, {
mention: 'twitter',
hashtag: 'twitter',
email: false,
newWindow: false
} );
expect( result ).toBe( [
'Website: <a href="http://asdf.com">asdf.com</a>',
'EmailMatch: asdf@asdf.com',
'Phone: <a href="tel:1234567890">(123) 456-7890</a>',
'Mention: <a href="https://twitter.com/asdf">@asdf</a>',
'HashtagMatch: <a href="https://twitter.com/hashtag/asdf">#asdf</a>'
].join( ", " ) );
} );
it( "should not link phone numbers when they are disabled", function() {
let result = Autolinker.link( inputStr, {
hashtag : 'twitter',
mention : 'twitter',
phone : false,
newWindow : false
} );
expect( result ).toBe( [
'Website: <a href="http://asdf.com">asdf.com</a>',
'EmailMatch: <a href="mailto:asdf@asdf.com">asdf@asdf.com</a>',
'Phone: (123) 456-7890',
'Mention: <a href="https://twitter.com/asdf">@asdf</a>',
'HashtagMatch: <a href="https://twitter.com/hashtag/asdf">#asdf</a>'
].join( ", " ) );
} );
it( "should not link mention handles when they are disabled", function() {
let result = Autolinker.link( inputStr, {
newWindow: false,
hashtag: 'twitter',
mention: false
} );
expect( result ).toBe( [
'Website: <a href="http://asdf.com">asdf.com</a>',
'EmailMatch: <a href="mailto:asdf@asdf.com">asdf@asdf.com</a>',
'Phone: <a href="tel:1234567890">(123) 456-7890</a>',
'Mention: @asdf',
'HashtagMatch: <a href="https://twitter.com/hashtag/asdf">#asdf</a>'
].join( ", " ) );
} );
it( "should not link Hashtags when they are disabled", function() {
let result = Autolinker.link( inputStr, {
mention : 'twitter',
hashtag : false,
newWindow : false
} );
expect( result ).toBe( [
'Website: <a href="http://asdf.com">asdf.com</a>',
'EmailMatch: <a href="mailto:asdf@asdf.com">asdf@asdf.com</a>',
'Phone: <a href="tel:1234567890">(123) 456-7890</a>',
'Mention: <a href="https://twitter.com/asdf">@asdf</a>',
'HashtagMatch: #asdf'
].join( ", " ) );
} );
} );
describe( "`replaceFn` option", function() {
let returnTrueFn = function() { return true; },
returnFalseFn = function() { return false; },
replaceFnSpy: jasmine.Spy;
beforeEach( function() {
replaceFnSpy = jasmine.createSpy( 'replaceFnSpy' );
} );
it( "by default, should be called with with the `Autolinker` instance " +
"as the context object (`this` reference)",
function() {
let replaceFnAutolinker = new Autolinker( {
replaceFn: replaceFnSpy
} );
replaceFnAutolinker.link( "asdf.com" ); // will call the `replaceFn`
expect( replaceFnSpy ).toHaveBeenCalled();
expect( replaceFnSpy.calls.first().object ).toBe( replaceFnAutolinker );
} );
it( "when provided a `context` option, should be called with with " +
"that object as the context object (`this` reference)",
function() {
let contextObj = { prop: 'value' };
let replaceFnAutolinker = new Autolinker( {
replaceFn : replaceFnSpy,
context : contextObj
} );
replaceFnAutolinker.link( "asdf.com" ); // will call the `replaceFn`
expect( replaceFnSpy ).toHaveBeenCalled();
expect( replaceFnSpy.calls.first().object ).toBe( contextObj );
} );
it( "should populate a UrlMatch object with the appropriate properties", function() {
let replaceFnCallCount = 0;
let result = Autolinker.link( "Website: asdf.com ", { // purposeful trailing space
replaceFn : function( match: Match ) {
replaceFnCallCount++;
expect( match.getMatchedText() ).toBe( 'asdf.com' );
expect( ( match as UrlMatch ).getUrl() ).toBe( 'http://asdf.com' );
}
} );
expect( replaceFnCallCount ).toBe( 1 ); // make sure the replaceFn was called
} );
it( "should populate an EmailMatch object with the appropriate properties", function() {
let replaceFnCallCount = 0;
let result = Autolinker.link( "EmailMatch: asdf@asdf.com ", { // purposeful trailing space
replaceFn : function( match: Match ) {
replaceFnCallCount++;
expect( match.getMatchedText() ).toBe( 'asdf@asdf.com' );
expect( ( match as EmailMatch ).getEmail() ).toBe( 'asdf@asdf.com' );
}
} );
expect( replaceFnCallCount ).toBe( 1 ); // make sure the replaceFn was called
} );
it( "should populate a HashtagMatch object with the appropriate properties", function() {
let replaceFnCallCount = 0;
let result = Autolinker.link( "HashtagMatch: #myHashtag ", { // purposeful trailing space
hashtag: 'twitter',
replaceFn : function( match: Match ) {
replaceFnCallCount++;
expect( match.getType() ).toBe( 'hashtag' );
expect( match.getMatchedText() ).toBe( '#myHashtag' );
expect( ( match as HashtagMatch ).getHashtag() ).toBe( 'myHashtag' );
}
} );
expect( replaceFnCallCount ).toBe( 1 ); // make sure the replaceFn was called
} );
it( "should populate a TwitterMatch object with the appropriate properties", function() {
let replaceFnCallCount = 0;
let result = Autolinker.link( "Twitter: @myTwitter ", { // purposeful trailing space
mention: 'twitter',
replaceFn : function( match: Match ) {
replaceFnCallCount++;
expect( match.getMatchedText() ).toBe( '@myTwitter' );
expect( ( match as MentionMatch ).getMention() ).toBe( 'myTwitter' );
}
} );
expect( replaceFnCallCount ).toBe( 1 ); // make sure the replaceFn was called
} );
it( "should populate a MentionMatch object with the appropriate properties", function() {
let replaceFnCallCount = 0;
let result = Autolinker.link( "Mention: @myTwitter ", { // purposeful trailing space
mention: 'twitter',
replaceFn : function( match: Match ) {
replaceFnCallCount++;
expect( match.getMatchedText() ).toBe( '@myTwitter' );
expect( ( match as MentionMatch ).getMention() ).toBe( 'myTwitter' );
}
} );
expect( replaceFnCallCount ).toBe( 1 ); // make sure the replaceFn was called
} );
it( "should replace the match as Autolinker would normally do when `true` is returned from the `replaceFn`", function() {
let result = Autolinker.link( "Website: asdf.com, EmailMatch: asdf@asdf.com, Twitter: @asdf", {
mention : 'twitter',
newWindow : false, // just to suppress the target="_blank" from the output for this test
replaceFn : returnTrueFn
} );
expect( result ).toBe( [
'Website: <a href="http://asdf.com">asdf.com</a>',
'EmailMatch: <a href="mailto:asdf@asdf.com">asdf@asdf.com</a>',
'Twitter: <a href="https://twitter.com/asdf">@asdf</a>'
].join( ", " ) );
} );
it( "should replace the match as Autolinker would normally do when there is no return value (i.e. `undefined` is returned) from the `replaceFn`", function() {
let result = Autolinker.link( "Website: asdf.com, EmailMatch: asdf@asdf.com, Twitter: @asdf", {
mention : 'twitter',
newWindow : false, // just to suppress the target="_blank" from the output for this test
replaceFn : function() {} // no return value (`undefined` is returned)
} );
expect( result ).toBe( [
'Website: <a href="http://asdf.com">asdf.com</a>',
'EmailMatch: <a href="mailto:asdf@asdf.com">asdf@asdf.com</a>',
'Twitter: <a href="https://twitter.com/asdf">@asdf</a>'
].join( ", " ) );
} );
it( "should leave the match as-is when `false` is returned from the `replaceFn`", function() {
let result = Autolinker.link( "Website: asdf.com, EmailMatch: asdf@asdf.com, Twitter: @asdf", {
mention : 'twitter',
replaceFn : returnFalseFn
} );
expect( result ).toBe( [
'Website: asdf.com',
'EmailMatch: asdf@asdf.com',
'Twitter: @asdf'
].join( ", " ) );
} );
it( "should use a string returned from the `replaceFn` as the HTML that is replaced in the input", function() {
let result = Autolinker.link( "Website: asdf.com, EmailMatch: asdf@asdf.com, Twitter: @asdf", {
mention : 'twitter',
replaceFn : function() { return "test"; }
} );
expect( result ).toBe( "Website: test, EmailMatch: test, Twitter: test" );
} );
it( "should allow an Autolinker.HtmlTag instance to be returned from the `replaceFn`, and use that as the HTML to be replaced from the input", function() {
let result = Autolinker.link( "Website: asdf.com", {
newWindow : false,
replaceFn : function( match ) {
let tag = match.buildTag();
tag.setInnerHtml( 'asdf!' ); // just to check that we're replacing with the returned `tag` instance
return tag;
}
} );
expect( result ).toBe( 'Website: <a href="http://asdf.com">asdf!</a>' );
} );
it( "should allow an Autolinker.HtmlTag instance to be modified before being returned from the `replaceFn`", function() {
let result = Autolinker.link( "Website: asdf.com", {
newWindow : false,
replaceFn : function( match ) {
let tag = match.buildTag();
tag.addClass( 'test' );
tag.addClass( 'test2' );
tag.setAttr( 'rel', 'nofollow' );
return tag;
}
} );
expect( result ).toBe( 'Website: <a href="http://asdf.com" class="test test2" rel="nofollow">asdf.com</a>' );
} );
it( "should not drop a trailing parenthesis of a URL match if the `replaceFn` returns false", function() {
let result = Autolinker.link( "Go to the website (asdf.com) and see", {
newWindow : false,
replaceFn : returnFalseFn
} );
expect( result ).toBe( 'Go to the website (asdf.com) and see' );
} );
describe( 'special cases which check the `prefixStr` and `suffixStr` vars in the code', function() {
it( "should leave the match as-is when the `replaceFn` returns `false` for a Twitter match", function() {
let result = Autolinker.link( "@asdf", { replaceFn: returnFalseFn } );
expect( result ).toBe( "@asdf" );
let result2 = Autolinker.link( "Twitter: @asdf", { mention: 'twitter', replaceFn: returnFalseFn } );
expect( result2 ).toBe( "Twitter: @asdf" );
} );
it( "should leave the match as-is when the `replaceFn` returns `false`, and the URL was wrapped in parenthesis", function() {
let result = Autolinker.link( "Go to (yahoo.com) my friend", { replaceFn: returnFalseFn } );
expect( result ).toBe( "Go to (yahoo.com) my friend" );
let result2 = Autolinker.link( "Go to en.wikipedia.org/wiki/IANA_(disambiguation) my friend", { replaceFn: returnFalseFn } );
expect( result2 ).toBe( "Go to en.wikipedia.org/wiki/IANA_(disambiguation) my friend" );
let result3 = Autolinker.link( "Go to (en.wikipedia.org/wiki/IANA_(disambiguation)) my friend", { replaceFn: returnFalseFn } );
expect( result3 ).toBe( "Go to (en.wikipedia.org/wiki/IANA_(disambiguation)) my friend" );
} );
it( "should leave the match as-is when the `replaceFn` returns `false`, and the URL was a protocol-relative match", function() {
let result = Autolinker.link( "Go to //yahoo.com my friend", { replaceFn: returnFalseFn } );
expect( result ).toBe( "Go to //yahoo.com my friend" );
} );
} );
} );
} );
describe( 'all match types tests', function() {
let testCases = {
schemeUrl : {
unlinked : 'http://google.com/path?param1=value1¶m2=value2#hash',
linked : '<a href="http://google.com/path?param1=value1¶m2=value2#hash">http://google.com/path?param1=value1¶m2=value2#hash</a>'
},
wwwUrl : {
unlinked : 'www.google.com/path?param1=value1¶m2=value2#hash',
linked : '<a href="http://www.google.com/path?param1=value1¶m2=value2#hash">www.google.com/path?param1=value1¶m2=value2#hash</a>'
},
tldUrl : {
unlinked : 'google.com/path?param1=value1¶m2=value2#hash',
linked : '<a href="http://google.com/path?param1=value1¶m2=value2#hash">google.com/path?param1=value1¶m2=value2#hash</a>'
},
email : {
unlinked : 'asdf@asdf.com',
linked : '<a href="mailto:asdf@asdf.com">asdf@asdf.com</a>'
},
mention : {
unlinked : '@asdf',
linked : '<a href="https://twitter.com/asdf">@asdf</a>'
},
phone : {
unlinked : '123-456-7890',
linked : '<a href="tel:1234567890">123-456-7890</a>'
},
hashtag : {
unlinked : '#Winning',
linked : '<a href="https://twitter.com/hashtag/Winning">#Winning</a>'
}
};
let numTestCaseKeys = Object.keys( testCases ).length;
let paragraphTpl = _.template( [
'Check link 1: <%= schemeUrl %>.',
'Check link 2: <%= wwwUrl %>.',
'Check link 3: <%= tldUrl %>.',
'My email is: <%= email %>.',
'My mention (twitter) username is <%= mention %>.',
'My phone number is <%= phone %>.',
'HashtagMatch <%= hashtag %>.'
].join( '\n' ) );
let sourceParagraph = paragraphTpl( {
schemeUrl : testCases.schemeUrl.unlinked,
wwwUrl : testCases.wwwUrl.unlinked,
tldUrl : testCases.tldUrl.unlinked,
email : testCases.email.unlinked,
mention : testCases.mention.unlinked,
phone : testCases.phone.unlinked,
hashtag : testCases.hashtag.unlinked
} );
it( 'should replace matches appropriately in a paragraph of text, using a variety of enabled matchers. Want to make sure that when one match type is disabled (such as emails), that other ones don\'t accidentally link part of them (such as from the url matcher)', function() {
interface MatcherTestConfig {
schemeMatches : boolean
wwwMatches : boolean
tldMatches : boolean
email : boolean;
mention : MentionServices | false;
phone : boolean;
hashtag : HashtagServices | false;
}
// We're going to run through every combination of matcher settings
// possible.
// 7 different settings and two possibilities for each (on or off)
// is 2^7 == 128 settings possibilities
for( let i = 0, len = Math.pow( 2, numTestCaseKeys ); i < len; i++ ) {
let cfg: MatcherTestConfig = {
schemeMatches : !!( i & parseInt( '00000001', 2 ) ),
wwwMatches : !!( i & parseInt( '00000010', 2 ) ),
tldMatches : !!( i & parseInt( '00000100', 2 ) ),
email : !!( i & parseInt( '00001000', 2 ) ),
mention : !!( i & parseInt( '00010000', 2 ) ) ? 'twitter' : false,
phone : !!( i & parseInt( '00100000', 2 ) ),
hashtag : !!( i & parseInt( '01000000', 2 ) ) ? 'twitter' : false
};
let autolinker = new Autolinker( {
urls : {
schemeMatches : cfg.schemeMatches,
wwwMatches : cfg.wwwMatches,
tldMatches : cfg.tldMatches
},
email : cfg.email,
mention : cfg.mention,
phone : cfg.phone,
hashtag : cfg.hashtag,
newWindow : false,
stripPrefix : false
} );
let result = autolinker.link( sourceParagraph ),
resultLines = result.split( '\n' ), // splitting line-by-line to make it easier to see where a failure is
expectedLines = generateExpectedLines( cfg );
expect( resultLines.length ).toBe( expectedLines.length ); // just in case
for( let j = 0, jlen = expectedLines.length; j < jlen; j++ ) {
if( resultLines[ j ] !== expectedLines[ j ] ) {
let errorMsg = generateErrMsg( resultLines[ j ], expectedLines[ j ], cfg );
throw new Error( errorMsg );
}
}
}
function generateExpectedLines( cfg: MatcherTestConfig ) {
let expectedLines = paragraphTpl( {
schemeUrl : cfg.schemeMatches ? testCases.schemeUrl.linked : testCases.schemeUrl.unlinked,
wwwUrl : cfg.wwwMatches ? testCases.wwwUrl.linked : testCases.wwwUrl.unlinked,
tldUrl : cfg.tldMatches ? testCases.tldUrl.linked : testCases.tldUrl.unlinked,
email : cfg.email ? testCases.email.linked : testCases.email.unlinked,
mention : cfg.mention ? testCases.mention.linked : testCases.mention.unlinked,
phone : cfg.phone ? testCases.phone.linked : testCases.phone.unlinked,
hashtag : cfg.hashtag ? testCases.hashtag.linked : testCases.hashtag.unlinked
} );
return expectedLines.split( '\n' ); // splitting line-by-line to make it easier to see where a failure is
}
function generateErrMsg( resultLine: string, expectedLine: string, cfg: MatcherTestConfig ) {
let errorMsg = [
'Expected: \'' + resultLine + '\' to be \'' + expectedLine + '\'\n'
];
errorMsg.push( '{' );
_.forOwn( cfg, ( value: any, key: string ) => {
errorMsg.push( '\t' + key + ': ' + value );
} );
errorMsg.push( '}' );
return errorMsg.join( '\n' );
}
} );
it( "should be able to parse a very long string", function() {
var testStr = (function() {
var t = [];
for (var i = 0; i < 50000; i++) {
t.push( ' foo' );
}
return t.join( '' );
})();
var result = Autolinker.link( testStr );
expect( result ).toBe( testStr );
} );
} );
describe( 'static parse()', function() {
it( 'should return an array of Match objects for the input', function() {
let text = [
'Website: asdf.com',
'EmailMatch: asdf@asdf.com',
'Phone: (123) 456-7890',
'Mention: @asdf1',
'HashtagMatch: #asdf2'
].join( ' ' );
let matches = Autolinker.parse( text, {
hashtag : 'twitter',
mention : 'twitter'
} );
expect( matches.length ).toBe( 5 );
expect( matches[ 0 ].getType() ).toBe( 'url' );
expect( ( matches[ 0 ] as UrlMatch ).getUrl() ).toBe( 'http://asdf.com' );
expect( matches[ 1 ].getType() ).toBe( 'email' );
expect( ( matches[ 1 ] as EmailMatch ).getEmail() ).toBe( 'asdf@asdf.com' );
expect( matches[ 2 ].getType() ).toBe( 'phone' );
expect( ( matches[ 2 ] as PhoneMatch ).getNumber() ).toBe( '1234567890' );
expect( matches[ 3 ].getType() ).toBe( 'mention' );
expect( ( matches[ 3 ] as MentionMatch ).getMention() ).toBe( 'asdf1' );
expect( matches[ 4 ].getType() ).toBe( 'hashtag' );
expect( ( matches[ 4 ] as HashtagMatch ).getHashtag() ).toBe( 'asdf2' );
} );
// TODO: This will no longer work in the TypeScript version of the codebase (2.0)
// Need to implement providing a custom PhoneMatcher
xdescribe( 'custom Phone.prototype.matcherRegex', function() {
// const matcherRegexOriginal = PhoneMatcher.prototype.matcherRegex;
// const testMatchOriginal = PhoneMatcher.prototype.testMatch;
beforeEach( function() {
const phoneInTextRegex = /(\+?852\-?)?[569]\d{3}\-?\d{4}/g;
// PhoneMatcher.prototype.matcherRegex = phoneInTextRegex;
// PhoneMatcher.prototype.testMatch = () => true;
} );
afterEach( function() {
// PhoneMatcher.prototype.matcherRegex = matcherRegexOriginal;
// PhoneMatcher.prototype.testMatch = testMatchOriginal;
} );
it( 'should match custom matcherRegex', function() {
let text = [
'91234567',
'9123-4567',
'61234567',
'51234567',
'+85291234567',
'+852-91234567',
'+852-9123-4567',
'852-91234567',
// invalid
'999',
'+852-912345678',
'123456789',
'+852-1234-56789',
].join( ' / ' );
let matches = Autolinker.parse( text, {
hashtag : 'twitter',
mention : 'twitter'
} );
expect( matches.length ).toBe( 8 );
expect( matches[ 0 ].getType() ).toBe( 'phone' );
expect( ( matches[ 0 ] as PhoneMatch ).getNumber() ).toBe( '91234567' );
expect( matches[ 2 ].getType() ).toBe( 'phone' );
expect( ( matches[ 2 ] as PhoneMatch ).getNumber() ).toBe( '61234567' );
} );
} );
} );
describe( 'parse()', function() {
it( 'should return an array of Match objects for the input', function() {
let autolinker = new Autolinker( {
hashtag : 'twitter',
mention : 'twitter'
} );
let text = [
'Website: asdf.com',
'EmailMatch: asdf@asdf.com',
'Phone: (123) 456-7890',
'Mention: @asdf1',
'HashtagMatch: #asdf2'
].join( ' ' );
let matches = autolinker.parse( text );
expect( matches.length ).toBe( 5 );
expect( matches[ 0 ].getType() ).toBe( 'url' );
expect( ( matches[ 0 ] as UrlMatch ).getUrl() ).toBe( 'http://asdf.com' );
expect( matches[ 1 ].getType() ).toBe( 'email' );
expect( ( matches[ 1 ] as EmailMatch ).getEmail() ).toBe( 'asdf@asdf.com' );
expect( matches[ 2 ].getType() ).toBe( 'phone' );
expect( ( matches[ 2 ] as PhoneMatch ).getNumber() ).toBe( '1234567890' );
expect( matches[ 3 ].getType() ).toBe( 'mention' );
expect( ( matches[ 3 ] as MentionMatch ).getMention() ).toBe( 'asdf1' );
expect( matches[ 4 ].getType() ).toBe( 'hashtag' );
expect( ( matches[ 4 ] as HashtagMatch ).getHashtag() ).toBe( 'asdf2' );
} );
} );
} ); | the_stack |
import { HttpProvider } from 'web3-core'
import { TxOptions } from '@ethereumjs/tx'
import { PrefixedHexString } from 'ethereumjs-util'
import { toBN, toHex } from 'web3-utils'
import { ContractInteractor } from '@opengsn/common/dist/ContractInteractor'
import { GsnTransactionDetails } from '@opengsn/common/dist/types/GsnTransactionDetails'
import { LoggerInterface } from '@opengsn/common/dist/LoggerInterface'
import { NetworkSimulatingProvider } from '@opengsn/common/dist/dev/NetworkSimulatingProvider'
import { ServerTestEnvironment } from './ServerTestEnvironment'
import { SignedTransactionDetails } from '@opengsn/relay/dist/TransactionManager'
import { GSNConfig } from '@opengsn/provider/dist/GSNConfigurator'
import { createClientLogger } from '@opengsn/provider/dist/ClientWinstonLogger'
import { evmMine, increaseTime, revert, snapshot } from './TestUtils'
import { signedTransactionToHash } from '@opengsn/common/dist/Utils'
import { GSNContractsDeployment } from '@opengsn/common/dist/GSNContractsDeployment'
import { defaultEnvironment, toNumber } from '@opengsn/common'
import sinon from 'sinon'
import chaiAsPromised from 'chai-as-promised'
const { expect, assert } = require('chai').use(chaiAsPromised)
contract('Network Simulation for Relay Server', function (accounts) {
const pendingTransactionTimeoutSeconds = 50
let logger: LoggerInterface
let env: ServerTestEnvironment
let provider: NetworkSimulatingProvider
before(async function () {
logger = createClientLogger({ logLevel: 'error' })
provider = new NetworkSimulatingProvider(web3.currentProvider as HttpProvider)
const maxPageSize = Number.MAX_SAFE_INTEGER
const contractFactory = async function (deployment: GSNContractsDeployment): Promise<ContractInteractor> {
const contractInteractor = new ContractInteractor({
environment: defaultEnvironment,
maxPageSize,
provider,
logger,
deployment
})
await contractInteractor.init()
return contractInteractor
}
env = new ServerTestEnvironment(web3.currentProvider as HttpProvider, accounts)
const clientConfig: Partial<GSNConfig> = { maxRelayNonceGap: 5 }
await env.init(clientConfig, {}, contractFactory)
await env.newServerInstance({ pendingTransactionTimeoutSeconds })
provider.setDelayTransactions(true)
})
describe('without automated mining', function () {
beforeEach(async function () {
await env.clearServerStorage()
})
it('should resolve once the transaction is broadcast', async function () {
assert.equal(provider.mempool.size, 0)
const { txHash } = await env.relayTransaction(false)
assert.equal(provider.mempool.size, 1)
const receipt = await env.web3.eth.getTransactionReceipt(txHash)
assert.isNull(receipt)
await provider.mineTransaction(txHash)
assert.equal(provider.mempool.size, 0)
await env.assertTransactionRelayed(txHash)
})
it('should broadcast multiple transactions at once', async function () {
assert.equal(provider.mempool.size, 0)
// cannot use the same sender as it will create same request with same forwarder nonce, etc
const overrideDetails = { from: accounts[1] }
// noinspection ES6MissingAwait - done on purpose
const promises = [env.relayTransaction(false), env.relayTransaction(false, overrideDetails)]
const txs = await Promise.all(promises)
assert.equal(provider.mempool.size, 2)
await provider.mineTransaction(txs[0].txHash)
await env.assertTransactionRelayed(txs[0].txHash)
await provider.mineTransaction(txs[1].txHash)
await env.assertTransactionRelayed(txs[1].txHash, overrideDetails)
})
})
describe('boosting stuck pending transactions', function () {
const gasPriceBelowMarket = toHex(20e9)
const gasPriceAboveMarket = toHex(30e9)
const expectedGasPriceAfterBoost = toBN(gasPriceBelowMarket).muln(12).divn(10).toString()
const stuckTransactionsCount = 5
const fairlyPricedTransactionIndex = 3
const originalTxHashes: string[] = []
const overrideParamsPerTx = new Map<PrefixedHexString, Partial<GsnTransactionDetails>>()
let rawTxOptions: TxOptions
before(async function () {
await env.relayServer.txStoreManager.clearAll()
await sendMultipleRelayedTransactions(stuckTransactionsCount)
})
describe('first time boosting stuck transactions', function () {
let id: string
before(async () => {
id = (await snapshot()).result
})
after(async () => {
await revert(id)
})
it('should not boost and resend transactions if not that many blocks passed since it was sent', async function () {
const latestBlock = await env.web3.eth.getBlock('latest')
const allBoostedTransactions = await env.relayServer._boostStuckPendingTransactions(latestBlock.number, toNumber(latestBlock.timestamp))
assert.equal(allBoostedTransactions.size, 0)
const storedTxs = await env.relayServer.txStoreManager.getAll()
assert.equal(storedTxs.length, stuckTransactionsCount)
for (let i = 0; i < stuckTransactionsCount; i++) {
assert.equal(storedTxs[i].txId, originalTxHashes[i])
}
})
it('should boost and resend underpriced transactions if the oldest one does not get mined after being sent for a long time', async function () {
// Increase time by mining necessary amount of blocks
await increaseTime(pendingTransactionTimeoutSeconds)
const latestBlock = await env.web3.eth.getBlock('latest')
const allBoostedTransactions = await env.relayServer._boostStuckPendingTransactions(latestBlock.number, toNumber(latestBlock.timestamp))
// NOTE: this is needed for the 'repeated boosting' test
for (const [originalTxHash, signedTransactionDetails] of allBoostedTransactions) {
overrideParamsPerTx.set(signedTransactionDetails.transactionHash, overrideParamsPerTx.get(originalTxHash)!)
}
// Tx #3 should not be changed
assert.equal(allBoostedTransactions.size, stuckTransactionsCount - 1)
await assertGasPrice(allBoostedTransactions, expectedGasPriceAfterBoost)
})
})
describe('repeated boosting', function () {
const expectedGasPriceAfterSecondBoost = toBN(expectedGasPriceAfterBoost).muln(12).divn(10).toString()
before('boosting transaction', assertBoostAndRebroadcast)
it('should not resend the transaction if not enough blocks passed since it was boosted', async function () {
await increaseTime(pendingTransactionTimeoutSeconds - 1)
const latestBlock = await env.web3.eth.getBlock('latest')
const allBoostedTransactions = await env.relayServer._boostStuckPendingTransactions(latestBlock.number, toNumber(latestBlock.timestamp))
assert.equal(allBoostedTransactions.size, 0)
})
it('should boost transactions that are not mined after being boosted another time', async function () {
await evmMine()
const latestBlock = await env.web3.eth.getBlock('latest')
const allBoostedTransactions = await env.relayServer._boostStuckPendingTransactions(latestBlock.number, toNumber(latestBlock.timestamp))
assert.equal(allBoostedTransactions.size, stuckTransactionsCount - 1)
await assertGasPrice(allBoostedTransactions, expectedGasPriceAfterSecondBoost)
})
})
describe('boosting & rebroadcasting all transactions', function () {
let id: string
before(async () => {
id = (await snapshot()).result
})
after(async () => {
await revert(id)
})
it('should boost underpriced transactions and only rebroadcast fairly priced transactions', assertBoostAndRebroadcast)
it('should throw when trying to boost a transaction with nonce higher than latest on-chain nonce', async function () {
const storedTxs = await env.relayServer.txStoreManager.getAll()
const latestNonce = await env.web3.eth.getTransactionCount(storedTxs[0].from)
assert.equal(storedTxs[0].nonce, latestNonce)
await env.relayServer.txStoreManager.removeTxsUntilNonce(storedTxs[0].from, latestNonce)
await increaseTime(pendingTransactionTimeoutSeconds)
const latestBlock = await web3.eth.getBlock('latest')
await expect(env.relayServer._boostStuckPendingTransactions(latestBlock.number, toNumber(latestBlock.timestamp))).to.be.eventually.rejectedWith(
`Boosting: missing nonce ${latestNonce}. Lowest stored tx nonce: ${storedTxs[1].nonce}`)
})
it('should not boost any transactions if config.pendingTransactionTimeoutBlocks did not pass yet', async function () {
await env.relayServer.txStoreManager.clearAll()
await env.relayServer.transactionManager._initNonces()
await sendMultipleRelayedTransactions(stuckTransactionsCount)
const storedTxs = await env.relayServer.txStoreManager.getAll()
const latestNonce = await env.web3.eth.getTransactionCount(storedTxs[0].from)
assert.equal(storedTxs[0].nonce, latestNonce)
const spy = sinon.spy(env.relayServer.logger, 'debug')
const message = `${storedTxs[0].from} : awaiting transaction with ID: ${storedTxs[0].txId} to be mined. creationBlockNumber: ${storedTxs[0].creationBlockNumber} nonce: ${storedTxs[0].nonce}`
let latestBlock = await web3.eth.getBlock('latest')
await env.relayServer._boostStuckPendingTransactions(latestBlock.number, toNumber(latestBlock.timestamp))
sinon.assert.calledWith(spy, message)
await increaseTime(pendingTransactionTimeoutSeconds - 1)
latestBlock = await web3.eth.getBlock('latest')
await env.relayServer._boostStuckPendingTransactions(latestBlock.number, toNumber(latestBlock.timestamp))
sinon.assert.calledWith(spy, message)
sinon.restore()
})
})
async function sendMultipleRelayedTransactions (_stuckTransactionsCount: number): Promise<void> {
for (let i = 0; i < _stuckTransactionsCount; i++) {
// Transaction #3 will have a sufficient gas price and shall not be boosted
// All transaction must come from different senders or else will be rejected on 'nonce mismatch'
const overrideTxParams: Partial<GsnTransactionDetails> = {
from: accounts[i],
maxPriorityFeePerGas: i === fairlyPricedTransactionIndex ? gasPriceAboveMarket : gasPriceBelowMarket,
maxFeePerGas: i === fairlyPricedTransactionIndex ? gasPriceAboveMarket : gasPriceBelowMarket
}
const { signedTx } = await env.relayTransaction(false, overrideTxParams)
rawTxOptions = env.relayServer.transactionManager.rawTxOptions
const transactionHash = signedTransactionToHash(signedTx, rawTxOptions)
originalTxHashes.push(transactionHash)
overrideParamsPerTx.set(transactionHash, overrideTxParams)
}
}
async function assertGasPrice (signedTransactions: Map<PrefixedHexString, SignedTransactionDetails>, expectedGasPriceAfterBoost: string): Promise<void> {
let i = 0
for (const [originalTxHash, signedTransactionDetails] of signedTransactions) {
if (i === fairlyPricedTransactionIndex) {
await provider.mineTransaction(originalTxHashes[fairlyPricedTransactionIndex])
}
await provider.mineTransaction(signedTransactionDetails.transactionHash)
const minedTx = await env.web3.eth.getTransaction(signedTransactionDetails.transactionHash)
const actualTxGasPrice = toBN(minedTx.gasPrice).toString()
assert.equal(actualTxGasPrice, expectedGasPriceAfterBoost)
const overrideDetails = overrideParamsPerTx.get(originalTxHash)
await env.assertTransactionRelayed(signedTransactionDetails.transactionHash, overrideDetails)
i++
}
}
async function assertBoostAndRebroadcast (): Promise<void> {
originalTxHashes.length = 0
await env.relayServer.txStoreManager.clearAll()
await env.relayServer.transactionManager._initNonces()
const spy = sinon.spy(env.relayServer.transactionManager, 'resendTransaction')
await sendMultipleRelayedTransactions(stuckTransactionsCount)
const storedTxsBefore = await env.relayServer.txStoreManager.getAll()
await increaseTime(pendingTransactionTimeoutSeconds)
const latestBlock = await env.web3.eth.getBlock('latest')
const allBoostedTransactions = await env.relayServer._boostStuckPendingTransactions(latestBlock.number, toNumber(latestBlock.timestamp))
// NOTE: this is needed for the 'repeated boosting' test
for (const [originalTxHash, signedTransactionDetails] of allBoostedTransactions) {
overrideParamsPerTx.set(signedTransactionDetails.transactionHash, overrideParamsPerTx.get(originalTxHash)!)
}
assert.equal(allBoostedTransactions.size, stuckTransactionsCount - 1)
const storedTxsAfter = await env.relayServer.txStoreManager.getAll()
assert.equal(storedTxsBefore.length, stuckTransactionsCount)
const spyCalls = spy.getCalls()
for (let i = 0; i < storedTxsBefore.length; i++) {
assert.equal(storedTxsBefore[i].attempts + 1, storedTxsAfter[i].attempts)
if (i === fairlyPricedTransactionIndex) {
sinon.assert.calledWith(spyCalls[i], storedTxsBefore[i], sinon.match.any, sinon.match.any, storedTxsBefore[i].maxFeePerGas, storedTxsBefore[i].maxPriorityFeePerGas, sinon.match.any)
} else {
sinon.assert.calledWith(spyCalls[i], storedTxsBefore[i], sinon.match.any, sinon.match.any, parseInt(expectedGasPriceAfterBoost), parseInt(expectedGasPriceAfterBoost), sinon.match.any)
}
}
sinon.restore()
}
})
}) | the_stack |
/// <reference path="../metricsPlugin.ts"/>
/// <reference path="../services/alertsManager.ts"/>
/// <reference path="../services/errorsManager.ts"/>
module HawkularMetrics {
export class AppServerTransactionsDetailsController {
public startTimeStamp: TimestampInMillis;
public endTimeStamp: TimestampInMillis;
public alertList: any[] = [];
public inflightTx: any = 0;
public abortedTx: any = 0;
public timedOutTx: any = 0;
public totalTx: any = 0;
public chartTxCommittedData: IChartDataPoint[];
public chartTxTimedOutData: IChartDataPoint[];
public chartTxAbortedData: IChartDataPoint[];
public chartTxData: IMultiDataPoint[] = [];
public chartTxInflightData: IContextChartDataPoint[];
// will contain in the format: 'metric name' : true | false
public skipChartData = {};
private feedId: FeedId;
private resourceId: ResourceId;
private TX_PFX = 'Transactions Metrics~Number of ';
public TOTAL_TX = { metricName: this.TX_PFX + 'Transactions', key: 'Transactions' };
public INFLIGHT_TX = { metricName: this.TX_PFX + 'In-Flight Transactions', key: 'In-Flight', color: '#d5d026' };
public COMMITTED_TX = { metricName: this.TX_PFX + 'Committed Transactions', key: 'Committed', color: '#1884c7' };
public ABORTED_TX = { metricName: this.TX_PFX + 'Aborted Transactions', key: 'Aborted', color: '#515252' };
public TIMEDOUT_TX = { metricName: this.TX_PFX + 'Timed Out Transactions', key: 'Timed Out', color: '#95489c' };
public HEURISTIC_TX = { metricName: this.TX_PFX + 'Heuristics', key: 'Heuristics', color: '#49a547' };
public APP_ROLLBACK = {
metricName: this.TX_PFX + 'Application Rollbacks', key: 'Application Rollbacks',
color: '#f57f20'
};
public RES_ROLLBACK = {
metricName: this.TX_PFX + 'Resource Rollbacks', key: 'Resource Rollbacks',
color: '#e12226'
};
constructor(private $scope: any,
private $rootScope: IHawkularRootScope,
private $interval: ng.IIntervalService,
private $routeParams: any,
private $log: ng.ILogService,
private HawkularNav: any,
private HawkularAlertRouterManager: IHawkularAlertRouterManager,
private MetricsService: IMetricsService,
private $q: ng.IQService) {
$scope.vm = this;
this.feedId = this.$routeParams.feedId;
this.resourceId = this.$routeParams.resourceId + '~/subsystem=transactions';
this.startTimeStamp = +moment().subtract(($routeParams.timeOffset || 3600000), 'milliseconds');
this.endTimeStamp = +moment();
this.chartTxCommittedData = [];
this.chartTxTimedOutData = [];
this.chartTxAbortedData = [];
this.chartTxInflightData = [];
if ($rootScope.currentPersona) {
this.refresh();
} else {
// currentPersona hasn't been injected to the rootScope yet, wait for it..
$rootScope.$watch('currentPersona', currentPersona => currentPersona && this.refresh());
}
// handle drag ranges on charts to change the time range
this.$scope.$on(EventNames.CHART_TIMERANGE_CHANGED, (event, data: Date[]) => {
this.changeTimeRange(data);
});
// handle drag ranges on charts to change the time range
this.$scope.$on('ContextChartTimeRangeChanged', (event, data: Date[]) => {
this.$log.debug('Received ContextChartTimeRangeChanged event' + data);
this.changeTimeRange(data);
});
this.HawkularAlertRouterManager.registerForAlerts(
this.$routeParams.feedId + '/' + this.$routeParams.resourceId,
'jvm',
_.bind(this.filterAlerts, this)
);
this.autoRefresh(20);
}
private autoRefreshPromise: ng.IPromise<number>;
private autoRefresh(intervalInSeconds: number): void {
this.autoRefreshPromise = this.$interval(() => {
this.refresh();
}, intervalInSeconds * 1000);
this.$scope.$on('$destroy', () => {
this.$interval.cancel(this.autoRefreshPromise);
});
}
public refresh(): void {
this.endTimeStamp = this.$routeParams.endTime || +moment();
this.startTimeStamp = this.endTimeStamp - (this.$routeParams.timeOffset || 3600000);
this.getTxData();
this.getAlerts();
this.$rootScope.lastUpdateTimestamp = new Date();
}
private changeTimeRange(data: Date[]): void {
this.startTimeStamp = data[0].getTime();
this.endTimeStamp = data[1].getTime();
this.HawkularNav.setTimestampStartEnd(this.startTimeStamp, this.endTimeStamp);
this.refresh();
}
public filterAlerts(alertData: IHawkularAlertQueryResult) {
let alertList = alertData.alertList;
_.remove(alertList, (item: IAlert) => {
switch (item.context.alertType) {
case 'TX': // FIXME: use correct types
item.alertType = item.context.alertType;
return false;
default:
return true;
}
});
this.alertList = alertList;
}
private getAlerts(): void {
this.HawkularAlertRouterManager.getAlertsForCurrentResource(
this.startTimeStamp,
this.endTimeStamp
);
}
private getTxData(): void {
this.getTxChartData();
this.getTxStatsData();
}
private getTxChartData(): void {
this.MetricsService.retrieveGaugeMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.INFLIGHT_TX.metricName),
this.startTimeStamp, this.endTimeStamp, 60).then((data) => {
if (data.length) {
this.chartTxInflightData = data;
}
});
let tmpChartTxData = [];
let txPromises = [];
if (!this.skipChartData[this.COMMITTED_TX.key]) {
let txCommittedPromise = this.MetricsService.retrieveCounterRateMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.COMMITTED_TX.metricName),
this.startTimeStamp, this.endTimeStamp, 60);
txPromises.push(txCommittedPromise);
txCommittedPromise.then((data) => {
tmpChartTxData.push({
key: this.COMMITTED_TX.key,
color: this.COMMITTED_TX.color,
values: MetricsService.formatBucketedChartOutput(data)
});
});
}
if (!this.skipChartData[this.ABORTED_TX.key]) {
let txAbortedPromise = this.MetricsService.retrieveCounterRateMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.ABORTED_TX.metricName),
this.startTimeStamp, this.endTimeStamp, 60);
txPromises.push(txAbortedPromise);
txAbortedPromise.then((data) => {
tmpChartTxData.push({
key: this.ABORTED_TX.key,
color: this.ABORTED_TX.color,
values: MetricsService.formatBucketedChartOutput(data)
});
});
}
if (!this.skipChartData[this.APP_ROLLBACK.key]) {
let appRollbackPromise = this.MetricsService.retrieveCounterRateMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.APP_ROLLBACK.metricName),
this.startTimeStamp, this.endTimeStamp, 60);
txPromises.push(appRollbackPromise);
appRollbackPromise.then((data) => {
tmpChartTxData.push({
key: this.APP_ROLLBACK.key,
color: this.APP_ROLLBACK.color,
values: MetricsService.formatBucketedChartOutput(data)
});
});
}
if (!this.skipChartData[this.RES_ROLLBACK.key]) {
let resRollbackPromise = this.MetricsService.retrieveCounterRateMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.RES_ROLLBACK.metricName),
this.startTimeStamp, this.endTimeStamp, 60);
txPromises.push(resRollbackPromise);
resRollbackPromise.then((data) => {
tmpChartTxData.push({
key: this.RES_ROLLBACK.key,
color: this.RES_ROLLBACK.color,
values: MetricsService.formatBucketedChartOutput(data)
});
});
}
if (!this.skipChartData[this.TIMEDOUT_TX.key]) {
let txTimedoutPromise = this.MetricsService.retrieveCounterRateMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.TIMEDOUT_TX.metricName),
this.startTimeStamp, this.endTimeStamp, 60);
txPromises.push(txTimedoutPromise);
txTimedoutPromise.then((data) => {
tmpChartTxData.push({
key: this.TIMEDOUT_TX.key,
color: this.TIMEDOUT_TX.color,
values: MetricsService.formatBucketedChartOutput(data)
});
});
}
if (!this.skipChartData[this.HEURISTIC_TX.key]) {
let txHeuristicPromise = this.MetricsService.retrieveCounterRateMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.HEURISTIC_TX.metricName),
this.startTimeStamp, this.endTimeStamp, 60);
txPromises.push(txHeuristicPromise);
txHeuristicPromise.then((data) => {
tmpChartTxData.push({
key: this.HEURISTIC_TX.key,
color: this.HEURISTIC_TX.color,
values: MetricsService.formatBucketedChartOutput(data)
});
});
}
this.$q.all(txPromises).finally(() => {
this.chartTxData = tmpChartTxData;
});
}
private getTxStatsData(): void {
this.MetricsService.retrieveGaugeMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.INFLIGHT_TX.metricName),
this.startTimeStamp, this.endTimeStamp, 1).then((resource) => {
if (resource.length) {
this.inflightTx = resource[0];
}
});
this.MetricsService.retrieveCounterMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.ABORTED_TX.metricName),
this.startTimeStamp, this.endTimeStamp, 1).then((resource) => {
if (resource.length) {
this.abortedTx = resource[0].max - resource[0].min;
}
});
this.MetricsService.retrieveCounterMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.TIMEDOUT_TX.metricName),
this.startTimeStamp, this.endTimeStamp, 1).then((resource) => {
if (resource.length) {
this.timedOutTx = resource[0].max - resource[0].min;
}
});
this.MetricsService.retrieveGaugeMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, this.TOTAL_TX.metricName),
this.startTimeStamp, this.endTimeStamp, 1).then((resource) => {
if (resource.length) {
this.totalTx = resource[0].max - resource[0].min;
}
});
}
public toggleChartData(name): void {
this.skipChartData[name] = !this.skipChartData[name];
this.getTxChartData();
}
}
_module.controller('AppServerTransactionsDetailsController', AppServerTransactionsDetailsController);
} | 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/bandwidthSchedulesMappers";
import * as Parameters from "../models/parameters";
import { DataBoxEdgeManagementClientContext } from "../dataBoxEdgeManagementClientContext";
/** Class representing a BandwidthSchedules. */
export class BandwidthSchedules {
private readonly client: DataBoxEdgeManagementClientContext;
/**
* Create a BandwidthSchedules.
* @param {DataBoxEdgeManagementClientContext} client Reference to the service client.
*/
constructor(client: DataBoxEdgeManagementClientContext) {
this.client = client;
}
/**
* Gets all the bandwidth schedules for a Data Box Edge/Data Box Gateway device.
* @param deviceName The device name.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<Models.BandwidthSchedulesListByDataBoxEdgeDeviceResponse>
*/
listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.BandwidthSchedulesListByDataBoxEdgeDeviceResponse>;
/**
* @param deviceName The device name.
* @param resourceGroupName The resource group name.
* @param callback The callback
*/
listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.BandwidthSchedulesList>): void;
/**
* @param deviceName The device name.
* @param resourceGroupName The resource group name.
* @param options The optional parameters
* @param callback The callback
*/
listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BandwidthSchedulesList>): void;
listByDataBoxEdgeDevice(deviceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BandwidthSchedulesList>, callback?: msRest.ServiceCallback<Models.BandwidthSchedulesList>): Promise<Models.BandwidthSchedulesListByDataBoxEdgeDeviceResponse> {
return this.client.sendOperationRequest(
{
deviceName,
resourceGroupName,
options
},
listByDataBoxEdgeDeviceOperationSpec,
callback) as Promise<Models.BandwidthSchedulesListByDataBoxEdgeDeviceResponse>;
}
/**
* Gets the properties of the specified bandwidth schedule.
* @param deviceName The device name.
* @param name The bandwidth schedule name.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<Models.BandwidthSchedulesGetResponse>
*/
get(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.BandwidthSchedulesGetResponse>;
/**
* @param deviceName The device name.
* @param name The bandwidth schedule name.
* @param resourceGroupName The resource group name.
* @param callback The callback
*/
get(deviceName: string, name: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.BandwidthSchedule>): void;
/**
* @param deviceName The device name.
* @param name The bandwidth schedule name.
* @param resourceGroupName The resource group name.
* @param options The optional parameters
* @param callback The callback
*/
get(deviceName: string, name: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BandwidthSchedule>): void;
get(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BandwidthSchedule>, callback?: msRest.ServiceCallback<Models.BandwidthSchedule>): Promise<Models.BandwidthSchedulesGetResponse> {
return this.client.sendOperationRequest(
{
deviceName,
name,
resourceGroupName,
options
},
getOperationSpec,
callback) as Promise<Models.BandwidthSchedulesGetResponse>;
}
/**
* Creates or updates a bandwidth schedule.
* @param deviceName The device name.
* @param name The bandwidth schedule name which needs to be added/updated.
* @param parameters The bandwidth schedule to be added or updated.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<Models.BandwidthSchedulesCreateOrUpdateResponse>
*/
createOrUpdate(deviceName: string, name: string, parameters: Models.BandwidthSchedule, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.BandwidthSchedulesCreateOrUpdateResponse> {
return this.beginCreateOrUpdate(deviceName,name,parameters,resourceGroupName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.BandwidthSchedulesCreateOrUpdateResponse>;
}
/**
* Deletes the specified bandwidth schedule.
* @param deviceName The device name.
* @param name The bandwidth schedule name.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(deviceName,name,resourceGroupName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Creates or updates a bandwidth schedule.
* @param deviceName The device name.
* @param name The bandwidth schedule name which needs to be added/updated.
* @param parameters The bandwidth schedule to be added or updated.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreateOrUpdate(deviceName: string, name: string, parameters: Models.BandwidthSchedule, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
deviceName,
name,
parameters,
resourceGroupName,
options
},
beginCreateOrUpdateOperationSpec,
options);
}
/**
* Deletes the specified bandwidth schedule.
* @param deviceName The device name.
* @param name The bandwidth schedule name.
* @param resourceGroupName The resource group name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(deviceName: string, name: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
deviceName,
name,
resourceGroupName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* Gets all the bandwidth schedules for a Data Box Edge/Data Box Gateway device.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.BandwidthSchedulesListByDataBoxEdgeDeviceNextResponse>
*/
listByDataBoxEdgeDeviceNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BandwidthSchedulesListByDataBoxEdgeDeviceNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByDataBoxEdgeDeviceNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BandwidthSchedulesList>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByDataBoxEdgeDeviceNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BandwidthSchedulesList>): void;
listByDataBoxEdgeDeviceNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BandwidthSchedulesList>, callback?: msRest.ServiceCallback<Models.BandwidthSchedulesList>): Promise<Models.BandwidthSchedulesListByDataBoxEdgeDeviceNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByDataBoxEdgeDeviceNextOperationSpec,
callback) as Promise<Models.BandwidthSchedulesListByDataBoxEdgeDeviceNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByDataBoxEdgeDeviceOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/bandwidthSchedules",
urlParameters: [
Parameters.deviceName,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BandwidthSchedulesList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/bandwidthSchedules/{name}",
urlParameters: [
Parameters.deviceName,
Parameters.name,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BandwidthSchedule
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/bandwidthSchedules/{name}",
urlParameters: [
Parameters.deviceName,
Parameters.name,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.BandwidthSchedule,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.BandwidthSchedule
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/bandwidthSchedules/{name}",
urlParameters: [
Parameters.deviceName,
Parameters.name,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByDataBoxEdgeDeviceNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BandwidthSchedulesList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import * as React from 'react';
import { IPropertyFieldDropDownSelectPropsInternal } from './PropertyFieldDropDownSelect';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown';
import { Async } from 'office-ui-fabric-react/lib/Utilities';
import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox';
import GuidHelper from './GuidHelper';
/**
* @interface
* PropertyFieldDropDownSelectHost properties interface
*
*/
export interface IPropertyFieldDropDownSelectHostProps extends IPropertyFieldDropDownSelectPropsInternal {
}
/**
* @interface
* PropertyFieldDropDownSelectHost state interface
*
*/
export interface IPropertyFieldDropDownSelectHostState {
isOpen: boolean;
isHoverDropdown?: boolean;
hoverFont?: string;
selectedFont?: string[];
safeSelectedFont?: string[];
errorMessage?: string;
}
/**
* @class
* Renders the controls for PropertyFieldDropDownSelect component
*/
export default class PropertyFieldDropDownSelectHost extends React.Component<IPropertyFieldDropDownSelectHostProps, IPropertyFieldDropDownSelectHostState> {
private async: Async;
private delayedValidate: (value: string[]) => void;
private _key: string;
/**
* @function
* Constructor
*/
constructor(props: IPropertyFieldDropDownSelectHostProps) {
super(props);
//Bind the current object to the external called onSelectDate method
this.onOpenDialog = this.onOpenDialog.bind(this);
this.toggleHover = this.toggleHover.bind(this);
this.toggleHoverLeave = this.toggleHoverLeave.bind(this);
this.onClickFont = this.onClickFont.bind(this);
this.mouseEnterDropDown = this.mouseEnterDropDown.bind(this);
this.mouseLeaveDropDown = this.mouseLeaveDropDown.bind(this);
this._key = GuidHelper.getGuid();
//Init the state
this.state = {
isOpen: false,
isHoverDropdown: false,
errorMessage: ''
};
this.async = new Async(this);
this.validate = this.validate.bind(this);
this.notifyAfterValidate = this.notifyAfterValidate.bind(this);
this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime);
//Inits the default value
if (props.initialValue != null && props.initialValue.length > 0 && this.props.options != null) {
for (var i = 0; i < this.props.options.length; i++) {
var font = this.props.options[i];
var found: boolean = false;
for (var j = 0; j < props.initialValue.length; j++) {
if (props.initialValue[j] == font.key) {
found = true;
break;
}
}
if (found == true)
font.isSelected = true;
}
}
}
/**
* @function
* Validates the new custom field value
*/
private validate(value: string[]): void {
if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) {
this.notifyAfterValidate(this.props.initialValue, value);
return;
}
var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || []);
if (result !== undefined) {
if (typeof result === 'string') {
if (result === undefined || result === '')
this.notifyAfterValidate(this.props.initialValue, value);
this.state.errorMessage = result;
this.setState(this.state);
}
else {
result.then((errorMessage: string) => {
if (errorMessage === undefined || errorMessage === '')
this.notifyAfterValidate(this.props.initialValue, value);
this.state.errorMessage = errorMessage;
this.setState(this.state);
});
}
}
else {
this.notifyAfterValidate(this.props.initialValue, value);
}
}
/**
* @function
* Notifies the parent Web Part of a property value change
*/
private notifyAfterValidate(oldValue: string[], newValue: string[]) {
if (this.props.onPropertyChange && newValue != null) {
this.props.properties[this.props.targetProperty] = newValue;
this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue);
if (!this.props.disableReactivePropertyChanges && this.props.render != null)
this.props.render();
}
}
/**
* @function
* Called when the component will unmount
*/
public componentWillUnmount() {
this.async.dispose();
}
/**
* @function
* Function to open the dialog
*/
private onOpenDialog(): void {
if (this.props.disabled === true)
return;
this.state.isOpen = !this.state.isOpen;
this.setState(this.state);
}
/**
* @function
* Mouse is hover a font
*/
private toggleHover(element?: any) {
var hoverFont: string = element.currentTarget.textContent;
this.state.hoverFont = hoverFont;
this.setState(this.state);
}
/**
* @function
* Mouse is leaving a font
*/
private toggleHoverLeave(element?: any) {
this.state.hoverFont = '';
this.setState(this.state);
}
/**
* @function
* Mouse is hover the fontpicker
*/
private mouseEnterDropDown(element?: any) {
this.state.isHoverDropdown = true;
this.setState(this.state);
}
/**
* @function
* Mouse is leaving the fontpicker
*/
private mouseLeaveDropDown(element?: any) {
this.state.isHoverDropdown = false;
this.setState(this.state);
}
private saveOptions(): void {
var res: string[] = [];
this.props.options.map((elm: IDropdownOption) => {
if (elm.isSelected)
res.push(elm.key.toString());
});
this.delayedValidate(res);
}
/**
* @function
* User clicked on a font
*/
private onClickFont(element: React.FormEvent<HTMLElement>, isChecked: boolean) {
var value: string = (element.currentTarget as any).value;
var option: IDropdownOption = this.getOption(value);
option.isSelected = isChecked;
this.setState(this.state);
this.saveOptions();
}
private getOption(key: string): IDropdownOption {
for (var i = 0; i < this.props.options.length; i++) {
var font = this.props.options[i];
if (font.key === key)
return font;
}
return null;
}
/**
* @function
* Renders the control
*/
public render(): JSX.Element {
//User wants to use the preview font picker, so just build it
var fontSelect = {
fontSize: '16px',
width: '100%',
position: 'relative',
display: 'inline-block',
zoom: 1
};
var dropdownColor = '1px solid #c8c8c8';
if (this.props.disabled === true)
dropdownColor = '1px solid #f4f4f4';
else if (this.state.isOpen === true)
dropdownColor = '1px solid #3091DE';
else if (this.state.isHoverDropdown === true)
dropdownColor = '1px solid #767676';
var fontSelectA = {
backgroundColor: this.props.disabled === true ? '#f4f4f4' : '#fff',
borderRadius : '0px',
backgroundClip : 'padding-box',
border: dropdownColor,
display: 'block',
overflow: 'hidden',
whiteSpace: 'nowrap',
position: 'relative',
height: '26px',
lineHeight: '26px',
padding: '0 0 0 8px',
color: this.props.disabled === true ? '#a6a6a6' : '#444',
textDecoration: 'none',
cursor: this.props.disabled === true ? 'default' : 'pointer'
};
var fontSelectASpan = {
marginRight: '26px',
display: 'block',
overflow: 'hidden',
whiteSpace: 'nowrap',
lineHeight: '1.8',
textOverflow: 'ellipsis',
cursor: this.props.disabled === true ? 'default' : 'pointer',
fontWeight: 400
};
var fontSelectADiv = {
borderRadius : '0 0px 0px 0',
backgroundClip : 'padding-box',
border: '0px',
position: 'absolute',
right: '0',
top: '0',
display: 'block',
height: '100%',
width: '22px'
};
var fontSelectADivB = {
display: 'block',
width: '100%',
height: '100%',
cursor: this.props.disabled === true ? 'default' : 'pointer',
marginTop: '2px'
};
var fsDrop = {
background: '#fff',
border: '1px solid #aaa',
borderTop: '0',
position: 'absolute',
top: '29px',
left: '0',
width: 'calc(100% - 2px)',
//boxShadow: '0 4px 5px rgba(0,0,0,.15)',
zIndex: 999,
display: this.state.isOpen ? 'block' : 'none'
};
var fsResults = {
margin: '0 4px 4px 0',
maxHeight: '190px',
width: 'calc(100% - 4px)',
padding: '0 0 0 4px',
position: 'relative',
overflowX: 'hidden',
overflowY: 'auto'
};
var carret: string = this.state.isOpen ? 'ms-Icon ms-Icon--ChevronUp' : 'ms-Icon ms-Icon--ChevronDown';
var foundSelected = false;
//Renders content
return (
<div style={{ marginBottom: '8px'}}>
<Label>{this.props.label}</Label>
<div style={fontSelect}>
<a style={fontSelectA} onClick={this.onOpenDialog}
onMouseEnter={this.mouseEnterDropDown} onMouseLeave={this.mouseLeaveDropDown} role="menuitem">
<span style={fontSelectASpan}>
{this.props.options.map((elm: IDropdownOption, index?: number) => {
if (elm.isSelected) {
if (foundSelected == false) {
foundSelected = true;
return (
<span key={this._key + '-spanselect-' + index}>{elm.text}</span>
);
}
else {
return (
<span key={this._key + '-spanselect-' + index}>, {elm.text}</span>
);
}
}
}
)}
{this.state.selectedFont}
</span>
<div style={fontSelectADiv}>
<i style={fontSelectADivB} className={carret}></i>
</div>
</a>
<div style={fsDrop}>
<ul style={fsResults}>
{this.props.options.map((font: IDropdownOption, index: number) => {
var backgroundColor: string = 'transparent';
if (this.state.hoverFont === font.text)
backgroundColor = '#eaeaea';
var innerStyle = {
lineHeight: '80%',
padding: '7px 7px 8px',
margin: '0',
listStyle: 'none',
fontSize: '16px',
backgroundColor: backgroundColor
};
return (
<li value={font.text}
key={this._key + '-dropdownselect-' + index}
onMouseEnter={this.toggleHover} role="menuitem" onMouseLeave={this.toggleHoverLeave} style={innerStyle}>
<Checkbox
defaultChecked={font.isSelected}
disabled={this.props.disabled}
label={font.text}
onChange={this.onClickFont}
inputProps={{value: font.key}}
/>
</li>
);
})
}
</ul>
</div>
</div>
{ this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ?
<div><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div>
<span>
<p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p>
</span>
</div>
: ''}
</div>
);
}
} | the_stack |
import {
ErrorCodes,
} from './errors';
import {
NodeTypes,
locStub,
RootNode,
Statement,
TextNode,
SimpleExpressionNode,
IfStatement,
BodyStatement,
ImportStatement,
UseStatement,
MixinStatement,
IdentifierNode,
VariableNode,
DeclarationStatement,
IncludeStatement,
OperatorNode,
RuleStatement,
ExtendStatement,
BinaryNode,
EachStatement,
ListNode,
createListNode,
createDeclarationStatement,
VarKeyNode,
puncType,
FunctionStatement,
createMixinStatement,
createFunctionStatement,
ReturnStatement,
createReturnStatement,
CallExpression,
createIdentifierNode,
createCallExpression,
createRuleStatement,
createIncludeStatement,
createIfStatement,
createEachStatement,
createVarKeyExpression,
createTextNode,
createSelectorNode,
createRootNode,
MediaStatement,
createMediaFeature,
MediaQuery,
MediaPrelude,
createMediaStatement,
createMediaPrelude,
createMediaQuery,
createBodyStatement,
createKeyframes,
Keyframes,
createKeyframesPrelude,
ContentPlaceholder,
createContentPlaceholder,
ForwardStatement,
} from './ast';
import {
debug,
PRECEDENCE,
fillWhitespace,
isKeyframesName,
range,
} from './util'
import { ParserOptions } from '@/type';
import { LexicalStream, Token } from './lexical';
/**
*
* @param {lex processed stream method} input
*/
export default function parse(input: LexicalStream, options: ParserOptions) {
const { filename, source } = options;
/**
* end with ';' , eg:
*
* $boder : 1px solid red;
*
* end with ',' | ')' , eg:
*
* @mixin test($param1:1,$param2:2){} // assign expression in @mixin or $include
*/
function defaultRightEndCondition() {
return isPuncToken(';')
}
function set_call_params_args_assign_right_end_condition() {
assignRightEndCondition = () => isPuncToken(',') || isPuncToken(')');
}
function reset_assign_right_end_condition() {
assignRightEndCondition = defaultRightEndCondition
}
function isPuncToken(ch?: puncType) {
let tok = input.peek();
return tok && tok.type == NodeTypes.PUNC && (!ch || tok.value == ch) && tok;
}
function isKwToken(kw: string): Token | boolean {
let tok = input.peek();
return tok && tok.type == NodeTypes.KEYWORD && (!kw || tok.value == kw) && tok;
}
function isKeyFramesToken() {
let tok = input.peek()
return tok && tok.type == NodeTypes.KEYWORD && isKeyframesName('keyframes');
}
function isOpToken(op?: string): OperatorNode | boolean {
let tok = input.peek();
if (tok && tok.type == NodeTypes.OPERATOR && (!op || tok.value == op)) {
return tok as OperatorNode
}
return false
}
function isAssignToken(): boolean {
let tok = input.peek()
return tok && tok.type === NodeTypes.DECLARATION;
}
function skipPunc(ch: any, silent: boolean = false) {
if (isPuncToken(ch)) input.next();
// mandatory skip
else {
!silent && input.emitError(ErrorCodes.EXPECTED_X, consumeNextTokenWithLoc().loc, ch)
}
}
function skipPuncSilent(ch: any) {
return skipPunc(ch, true)
}
// todos: replace typescript any
function delimited(start: puncType, stop: puncType, separator: puncType, parser: Function) {// FIFO
let statements: any[] = [], first = true;
skipPunc(start);
while (!input.eof()) {
if (debug()) break;
if (isPuncToken(stop)) break;
if (first) {
first = false;
} else {
if (separator === ';') {
skipPuncSilent(separator) // prevent nested block from emit error
} else {
skipPunc(separator);
}
}
if (isPuncToken(stop)) break;
statements.push(parser());
}
skipPunc(stop);
return statements;
}
let assignRightEndCondition = defaultRightEndCondition;
// type parseFunctionType = <T extends Node>(...args:any[]) => T
function injectLoc(parseFn) {
return function injectLocInner(...args) {
input.eliminateWhitespace()
let start = input.getCoordination(),
ast = parseFn.apply(null, args),
end = input.getCoordination();
/**
* patch DECLARATION , make left node start as start position
* patch BINARY node position, make binary left most node start as binary node start position
* */
if (ast.type === NodeTypes.BINARY || ast.type === NodeTypes.DECLARATION) {
let left = args[0]
if (left) {
while (left.type === NodeTypes.BINARY) {
left = left.left
}
start = left.loc.start;
}
}
let loc = {
start,
end,
filename
}
if (start.offset >= end.offset) {
input.emitError(ErrorCodes.INVALID_LOC_POSITION)
}
return {
...ast,
loc,
};
}
}
const consumeNextTokenWithLoc = injectLoc(() => input.next())
const parseError = injectLoc(function parseError() {
function parse_list(endCheck = () => !defaultRightEndCondition()) {
let list: SimpleExpressionNode[] = []
while (endCheck()) {
list.push(dispatchParser())
}
return {
type: NodeTypes.LIST,
value: list
}
}
return {
type: NodeTypes.ERROR,
value: parse_list()
}
})
/**
* divide dispatchParser
* by scan_right ( deal with right only expression which may contain call expression)
* and default (deal with left only expression which maybe a consecutive textNode as assign left type)
*
*/
function dispatchParserWithScanRight() {
return dispatchParser('scan_right')
}
function dispatchParser(scanType: 'scan_right' | '' = '') {
if (isKwToken('@extend')) {
input.next()
return parseExtend();
}
if (isKwToken('@mixin')) {
input.next()
return parseMixin();
}
if (isKwToken('@content')) {
let tok = consumeNextTokenWithLoc()
return parseContent(tok.loc);
}
if (isKwToken('@function')) {
input.next()
return parseFunction();
}
if (isKwToken('@return')) {
input.next()
return parseReturn();
}
if (isKwToken('@include')) {
input.next()
return parseInclude();
}
if (isKwToken('@use')) {
input.next()
return parseUse();
}
if (isKwToken('@forward')) {
input.next()
return parseFoward();
}
if (isKwToken('@import')) {
input.next()
return parseImport();
}
if (isKwToken('@if')) {
input.next()
return parseIf();
}
if (isKwToken('@each')) {
input.next()
return parseEach();
}
if (isKwToken('@plugin')) {
input.next()
return parsePlugin();
}
if (isKwToken('@error')) {
input.next()
return parseError();
}
let tok = input.peek();
if (tok.type === NodeTypes.VARIABLE || tok.type === NodeTypes.PLACEHOLDER) {
return consumeNextTokenWithLoc();
}
if (tok.type === NodeTypes.PUNC) {
if (tok.value === "#") {
return maybeVarKeyWrapper()
}
return consumeNextTokenWithLoc()
}
if (tok.type === NodeTypes.TEXT) {
if (scanType === 'scan_right') {
return maybeCall(consumeNextTokenWithLoc())
} else {
/**
* only parse expression left side, which won't contain callExpression
* eg:
* body .main{}
*/
return parseConsecutiveLeft()
}
}
/**
* cases like internal keyword
* @media only screen and (max-width: $maxwidth){}
* etc, should not throw error but parsed as special callExpression
*/
if (tok.type == NodeTypes.KEYWORD) {
if (isKwToken('@media')) {
input.next()
return parseMedia();
}
/**
* @-webkit-keyframes
* @-moz-keyframes
* @-o-keyframes
* @keyframes
*/
if (isKeyFramesToken()) {
let kf = input.next()
return parseKeyframes(kf.value)
}
return input.emitError(ErrorCodes.UNKNOWN_KEYWORD, consumeNextTokenWithLoc().loc, tok.value)
}
return input.emitError(ErrorCodes.UNKNONWN_TOKEN_TYPE, consumeNextTokenWithLoc().loc, tok.type)
}
function parsePlugin() {
function processFilenameExp(exp) {
exp.value = exp.value.match(/^['"](.+)['"]$/)[1]
return exp;
}
let delimitor = input.peek()
if (!delimitor.value.startsWith("'") && !delimitor.value.startsWith('"')) {
input.emitError(ErrorCodes.EXPECTED_X, locStub, `@plugin expected with ' or " but encountered ${delimitor}`)
}
return {
type: NodeTypes.PLUGIN,
value: processFilenameExp(consumeNextTokenWithLoc()),
loc: locStub
}
}
function parseKeyframes(keyframesName: string): Keyframes {
let children: Keyframes['prelude']['children'] = [];
while (!isPuncToken('{')) {
children.push(dispatchParser())
}
let bodyStatement: BodyStatement = parseBody()
return createKeyframes(keyframesName, createKeyframesPrelude(children), bodyStatement)
}
function parseMedia(): MediaStatement {
let mediaQueryListChildren: MediaPrelude['children'] = [],
mediaQueryChildren: MediaQuery['children'] = [];
set_call_params_args_assign_right_end_condition()
while (!isPuncToken('{')) {
if (isPuncToken(',')) {
// reset mediaQueryChildren
mediaQueryListChildren.push(createMediaQuery(mediaQueryChildren))
mediaQueryChildren = []
skipPunc(',')
} else if (isPuncToken('(')) {
skipPunc('(')
let left: DeclarationStatement['left'] = consumeNextTokenWithLoc(),
declaration = parseDeclaration(left)
mediaQueryChildren.push(createMediaFeature(declaration))
skipPunc(')')
} else {
mediaQueryChildren.push(consumeNextTokenWithLoc()) // eg: and,screen etc like TEXT
}
}
reset_assign_right_end_condition()
// flush array
if (mediaQueryChildren.length) {
mediaQueryListChildren.push(createMediaQuery(mediaQueryChildren))
mediaQueryChildren = []
}
let bodyStatement: BodyStatement = parseBody()
return createMediaStatement(createMediaPrelude(mediaQueryListChildren), bodyStatement)
}
function parseSimpleExpressionList(): SimpleExpressionNode[] {
let right: SimpleExpressionNode[] = [];
while (!assignRightEndCondition()) {
if (debug()) break;
/**
* catch error when missed ';', but encountered ':'
*/
if (isAssignToken() || isPuncToken('{')) {
let tok = consumeNextTokenWithLoc()
input.emitError(ErrorCodes.EXPECTED_X, tok.loc, ";")
}
let result: SimpleExpressionNode = maybeBinaryNode(dispatchParserWithScanRight(), 0);
right.push(result)
}
return right;
}
function parseDeclaration(left: DeclarationStatement['left']): DeclarationStatement {
input.next(); // skip ':' which is not punc type ,so could not use skipPunc
let right: ListNode = createListNode(parseSimpleExpressionList())
return createDeclarationStatement(left, right)
}
function maybeBinaryNode(left: TextNode | BinaryNode, left_prec): TextNode | BinaryNode {
if (isOpToken()) {
let tok: OperatorNode = isOpToken() as OperatorNode;
if (PRECEDENCE[tok.value] > left_prec) {
tok = consumeNextTokenWithLoc(); //skip op , add loc
let nextNode: TextNode = consumeNextTokenWithLoc();
if (nextNode.type !== NodeTypes.TEXT && nextNode.type !== NodeTypes.VARIABLE) {
input.emitError(ErrorCodes.EXPECT_TEXT_NODE_AFTER_OPERATOR_NODE, nextNode.loc)
}
return maybeBinaryNode({
type: NodeTypes.BINARY,
operator: tok,
left: left,
right: maybeBinaryNode(nextNode, PRECEDENCE[tok.value]),
loc: {
start: left.loc.start,
end: nextNode.loc.end,
filename
}
}, left_prec)
}
}
return left;
}
function parseRule(selector: RuleStatement['selector']): RuleStatement {
let children = delimited("{", "}", ";", parseStatement);
return createRuleStatement(selector, children)
}
function parseExtend(): ExtendStatement {
return {
type: NodeTypes.EXTEND,
param: consumeNextTokenWithLoc(),
loc: locStub
}
}
function parseBody(): BodyStatement {
let children: Statement[] = delimited("{", "}", ";", parseStatement);
return createBodyStatement(children)
}
function parseContent(loc: ContentPlaceholder['loc']): ContentPlaceholder {
return createContentPlaceholder(loc)
}
/**
* Todos: add @content kw and include body
*/
function parseMixin(): MixinStatement {
let id: IdentifierNode = createIdentifierNode(consumeNextTokenWithLoc()),
params: (VariableNode | DeclarationStatement)[] = [];
if (!isPuncToken('{')) {
/**
* Support default params, which contains assign ':' symbol; which will be processed in parseDeclaration
* @mixin replace-text($image,$x:default1, $y:default2) {
*/
set_call_params_args_assign_right_end_condition()
params = delimited('(', ')', ',', parseStatement);
}
reset_assign_right_end_condition()
return createMixinStatement(id, params, parseBody());
}
function parseFunction(): FunctionStatement {
let id: IdentifierNode = createIdentifierNode(consumeNextTokenWithLoc()),
params: (VariableNode | DeclarationStatement)[] = [];
if (!isPuncToken('{')) {
/**
* Support default params, which contains assign ':' symbol; which will be processed in parseDeclaration
* @functoin replace-text($image,$x:default1, $y:default2) {
*/
set_call_params_args_assign_right_end_condition()
params = delimited('(', ')', ',', parseStatement);
}
reset_assign_right_end_condition()
return createFunctionStatement(id, params, parseBody());
}
function parseReturn(): ReturnStatement {
return createReturnStatement(parseSimpleExpressionList())
}
/** to resolve rotate(30deg) or url("/images/mail.svg") kind of inner call expression
* also custom @function call
*/
function maybeCall(node: TextNode): TextNode | CallExpression {
if (isPuncToken('(')) {
set_call_params_args_assign_right_end_condition()
let callExpression = createCallExpression(createIdentifierNode(node), delimited('(', ')', ',', parseStatement))
reset_assign_right_end_condition()
return callExpression
}
return node;
}
function parseInclude(): IncludeStatement {
let id: IdentifierNode = createIdentifierNode(consumeNextTokenWithLoc()),
args: (VariableNode | DeclarationStatement)[] = [],
content: IncludeStatement['content'];// @include mixin1;
if (!isPuncToken(';')) {
set_call_params_args_assign_right_end_condition()
/**
* use maybeDeclaration to wrap to deal with possible default include args
* eg:
* @include avatar(100px, $circle: false);
*/
args = delimited('(', ')', ',', () => maybeDeclaration(dispatchParserWithScanRight)); // extend like expr or call expr
}
reset_assign_right_end_condition()
if (isPuncToken('{')) {
content = parseBody()
}
return createIncludeStatement(id, args, content);
}
function parseModuleParams(): ImportStatement['params'] {
function processFilenameExp(exp) {
exp.value = exp.value.match(/^['"](.+)['"]$/)[1]
return exp;
}
let delimitor = input.peek(),
params: TextNode[] = [];
if (!delimitor.value.startsWith("'") && !delimitor.value.startsWith('"')) {
input.emitError(ErrorCodes.EXPECTED_X, locStub, `@import expected with ' or " but encountered ${delimitor}`)
}
while (!isPuncToken(';')) { // @import 'foundation/code', 'foundation/lists';
params.push(processFilenameExp(consumeNextTokenWithLoc()));
if (isPuncToken(',')) {
skipPunc(',')
}
}
return params
}
function parseUse(): UseStatement {
return {
type: NodeTypes.USE,
params: parseModuleParams(),
loc: locStub
}
}
function parseFoward(): ForwardStatement {
return {
type: NodeTypes.FORWARD,
params: parseModuleParams(),
loc: locStub
}
}
function parseImport(): ImportStatement {
return {
type: NodeTypes.IMPORT,
params: parseModuleParams(),
loc: locStub
}
}
function parseIf(): IfStatement {
let alternate: IfStatement | BodyStatement | null = null,
testExpression: BinaryNode | TextNode,
bodyStatement: BodyStatement;
testExpression = maybeBinaryNode(dispatchParser(), 0);
bodyStatement = parseBody();
if (isKwToken('@else')) {
input.next();
let predictToken = input.peek();
/**
* check if it's a @else if statement
*/
if (predictToken.type === NodeTypes.TEXT && predictToken.value === 'if') {
input.next();
alternate = parseIf();
} else {
alternate = parseBody()
}
}
return createIfStatement(testExpression, bodyStatement, alternate)
}
function parseEach(): EachStatement {
let left = dispatchParser();
/**
* skip "in" expression
*/
input.next();
let right = dispatchParser();
skipPunc('{')
let bodyStatement = parseStatement()
skipPunc('}')
return createEachStatement(left, right, bodyStatement)
}
function parseConsecutiveLeft(): TextNode {
function read_while(predicate): TextNode[] {
let tokens: TextNode[] = [];
while (!input.eof() && predicate(input.peek()))
//to resolve test skew(20deg) rotate(20deg);
tokens.push(consumeNextTokenWithLoc());
return tokens;
}
let list: TextNode[] = read_while(tok => tok.type === NodeTypes.TEXT),
listNode: ListNode = createListNode(list);
// no nested ListNode for now, so we flatten and return TextNode
return {
type: NodeTypes.TEXT,
value: fillWhitespace(list).map(tok => tok.value).join(''),
loc: listNode.loc
}
}
/**
*
* #{var}
*/
function maybeVarKeyWrapper(): VarKeyNode | TextNode {
function parse_key_var_wrapper(varKeyStartLoc): VarKeyNode {
skipPunc('{')
let node = consumeNextTokenWithLoc();
if (node.type !== NodeTypes.VARIABLE) {
input.emitError(ErrorCodes.UNDEFINED_VARIABLE, node.loc, `${node} should be a variable which starts with '$'`)
}
skipPunc('}')
return createVarKeyExpression(node.value, {
start: varKeyStartLoc,
end: node.loc.end,
filename
})
}
let token = consumeNextTokenWithLoc(); // token maybe '#'
if (isPuncToken('{')) {
return parse_key_var_wrapper(token.loc.start)
}
/**
* color: #1212; or #selector{}
*/
let nextToken = consumeNextTokenWithLoc();
if (nextToken.type !== NodeTypes.TEXT) {
input.emitError(ErrorCodes.EXPECTED_X, nextToken.loc, `[maybeVarKeyWrapper]: expect str token but received ${nextToken.value}`)
}
return createTextNode(token.value + nextToken.value, {
start: token.start,
end: nextToken.end,
filename
})
}
function maybeDeclaration(exp) {
let expr = exp();
/**
* PseudoClassSelector may also enter which is not Declaration
* &:not([disabled]):hover{}
*
*/
if (isAssignToken()) {
/**
* solve scenario default value, prevent from ll(n) check eg:
* @mixin avatar($size, $circle: false) {}
* @include avatar(100px, $circle: false);
*
*/
if (expr.type === NodeTypes.VARIABLE) {
return parseDeclaration(expr)
}
/**
* solve complicated selector eg:
* &:not([disabled]):hover {}
*/
let lln = 1,
predictToken: Token;
while (true) {
predictToken = input.peek(lln);
if (predictToken.value === ';' || predictToken.value === '}') { // treat as NodeTypes.DECLARATION
return parseDeclaration(expr)
} else if (predictToken.value === '{') { // treat as NodeTypes.SELECTOR
return parseRule(
createSelectorNode(
createListNode(
range(lln - 1).map((): SimpleExpressionNode => {
let tok = consumeNextTokenWithLoc()
tok.type = NodeTypes.TEXT // transform to NodeTypes.TEXT
return tok;
})
)
)
)
} else {
lln++
}
}
}
/**
* handle selector may contain key_var, which should be resolved to list ast
* .icon-#{$size} {}
*/
if (isPuncToken('#')) {
return maybeDeclaration(() => {
return createListNode(
expr.type === NodeTypes.LIST ?
expr.value.concat(dispatchParser())
: [expr].concat(dispatchParser()))
})
}
if (isPuncToken('{')) {
return parseRule(createSelectorNode(expr)) //passin selector
}
return expr;
}
function parseStatement() {
return maybeDeclaration(function () {
return dispatchParser()
})
}
function isEnd() {
return input.eof()
}
function parsechildren(): Statement[] {
let children: Statement[] = [];
while (!isEnd()) {
children.push(parseStatement());
skipPuncSilent(";");
}
return children
}
function parseProgram(): RootNode {
return createRootNode(parsechildren(), { [filename]: source })
}
return parseProgram()
} | the_stack |
import postcss from 'postcss';
import postcssOldestSupported, { AcceptedPlugin } from 'postcss-8.2';
import path from 'path';
import fs, { promises as fsp } from 'fs';
import { strict as assert } from 'assert';
import type { PluginCreator, Plugin, Result } from 'postcss';
import { formatGitHubActionAnnotation } from './github-annotations';
import { dashesSeparator, formatCSSAssertError, formatWarningsAssertError } from './format-asserts';
import noopPlugin from './noop-plugin';
const emitGitHubAnnotations = process.env.GITHUB_ACTIONS && process.env.ENABLE_ANNOTATIONS_FOR_NODE === 'true' && process.env.ENABLE_ANNOTATIONS_FOR_OS === 'true';
type TestCaseOptions = {
// Debug message
message?: string,
// Plugin options. Only used if `plugins` is not specified.
options?: unknown,
// Plugins to use. When specified the original plugin is not used.
plugins?: Array<Plugin>,
// The expected number of warnings.
warnings?: number,
// Expected exception
// NOTE: plugins should not throw exceptions, this goes against best practices. Use `errors` instead.
exception?: RegExp,
// Override the file name of the "expect" file.
expect?: string,
// Override the file name of the "result" file.
result?: string,
// Do something before the test is run.
before?: () => void,
// Do something after the test is run.
after?: () => void|Promise<void>,
}
export default function runner(currentPlugin: PluginCreator<unknown>) {
let hasErrors = false;
// Plugin conforms to https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md
{
if (currentPlugin.postcss !== true) {
hasErrors = true;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
'postcss flag not set to "true" on exported plugin object',
'error',
{ file: './package.json', line: 1, col: 1 }, /* attributed to package.json because we don't know the source file of "currentPlugin" */
));
} else {
console.error(`\npostcss flag not set to "true"\n\n${dashesSeparator}`);
}
}
// https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#15-set-pluginpostcssplugin-with-plugin-name
// Set plugin.postcssPlugin with plugin name
const plugin = currentPlugin() as Plugin;
if (!plugin.postcssPlugin || typeof plugin.postcssPlugin !== 'string') {
hasErrors = true;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
'plugin name not set via "postcssPlugin"',
'error',
{ file: './package.json', line: 1, col: 1 }, /* attributed to package.json because we don't know the source file of "currentPlugin" */
));
} else {
console.error(`\nplugin name not set via "postcssPlugin"\n\n${dashesSeparator}`);
}
}
// https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#54-include-postcss-plugin-keyword-in-packagejson
// Include postcss-plugin keyword in package.json
const packageInfo = JSON.parse(fs.readFileSync('./package.json').toString());
if (!packageInfo.keywords || !packageInfo.keywords.includes('postcss-plugin')) {
hasErrors = true;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
'package.json does not include "postcss-plugin" keyword',
'error',
{ file: './package.json', line: 1, col: 1 }, /* attributed to package.json because we don't know the source file of "currentPlugin" */
));
} else {
console.error(`\npackage.json does not include "postcss-plugin" keyword\n\n${dashesSeparator}`);
}
}
// https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#11-clear-name-with-postcss--prefix
// Clear name with postcss- prefix
const isOlderPackageName = [
'css-has-pseudo',
'css-blank-pseudo',
'css-prefers-color-scheme',
'@csstools/css-has-pseudo-experimental',
].includes(packageInfo.name);
if (!packageInfo.name.startsWith('postcss-') && !packageInfo.name.startsWith('@csstools/postcss-') && !isOlderPackageName) {
hasErrors = true;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
'plugin name in package.json does not start with "postcss-"',
'error',
{ file: './package.json', line: 1, col: 1 },
));
} else {
console.error(`\nplugin name in package.json does not start with "postcss-"\n\n${dashesSeparator}`);
}
}
// https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#14-keep-postcss-to-peerdependencies
// Keep postcss to peerDependencies
if (Object.keys(Object(packageInfo.dependencies)).includes('postcss') && !('postcssTapeSelfTest' in currentPlugin)) {
hasErrors = true;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
'postcss should only be a peer and/or dev dependency',
'error',
{ file: './package.json', line: 1, col: 1 },
));
} else {
console.error(`\npostcss should only be a peer and/or dev dependency\n\n${dashesSeparator}`);
}
}
}
// Test cases
return async (options: Record<string, TestCaseOptions>) => {
const failureSummary = new Set();
for (const testCaseLabel in options) {
const testCaseOptions = options[testCaseLabel];
// Run "before" immediately.
if (testCaseOptions.before) {
await testCaseOptions.before();
}
const testSourceFilePathWithoutExtension = path.join('.', 'test', testCaseLabel.split(':')[0]);
const testFilePathWithoutExtension = path.join('.', 'test', testCaseLabel.replace(/:/g, '.'));
const testFilePath = `${testSourceFilePathWithoutExtension}.css`;
let expectFilePath = `${testFilePathWithoutExtension}.expect.css`;
let resultFilePath = `${testFilePathWithoutExtension}.result.css`;
if (testCaseOptions.expect) {
expectFilePath = path.join('.', 'test', testCaseOptions.expect);
}
if (testCaseOptions.result) {
resultFilePath = path.join('.', 'test', testCaseOptions.result);
}
const plugins = testCaseOptions.plugins ?? [currentPlugin(testCaseOptions.options)];
const input = await fsp.readFile(testFilePath, 'utf8');
// Check errors on expect file being missing
let expected: string|false = '';
try {
expected = await fsp.readFile(expectFilePath, 'utf8');
} catch (_) {
hasErrors = true;
expected = false;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
`${testCaseLabel}\n\nmissing or broken "expect" file: "${path.parse(expectFilePath).base}"`,
'error',
{ file: testFilePath, line: 1, col: 1 },
));
} else {
failureSummary.add(testCaseLabel);
console.error(`\n${testCaseLabel}\n\nmissing or broken "expect" file: "${path.parse(expectFilePath).base}"\n\n${dashesSeparator}`);
}
}
let result: Result;
let sawException = false;
try {
result = await postcss(plugins).process(input, {
from: testFilePath,
to: resultFilePath,
map: {
inline: false,
annotation: false,
},
});
} catch (err) {
sawException = true;
if (testCaseOptions.exception && testCaseOptions.exception.test(err.message)) {
// expected an exception and got one.
continue;
}
// rethrow
throw err;
}
if (!sawException && testCaseOptions.exception) {
hasErrors = true;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
`${testCaseLabel}\n\nexpected an exception but got none`,
'error',
{ file: testFilePath, line: 1, col: 1 },
));
} else {
failureSummary.add(testCaseLabel);
console.error(`\n${testCaseLabel}\n\nexpected an exception but got none\n\n${dashesSeparator}`);
}
}
// Try to write the result file, even if further checks fails.
// This helps writing new tests for plugins.
// Taking the result file as a starting point for the expect file.
const resultString = result.css.toString();
await fsp.writeFile(resultFilePath, resultString, 'utf8');
// Allow contributors to rewrite `.expect.css` files through postcss-tape.
if (process.env.REWRITE_EXPECTS) {
fsp.writeFile(expectFilePath, resultString, 'utf8');
}
// Can't do further checks if "expect" is missing.
if (expected === false) {
continue;
}
// Assert result with recent PostCSS.
//
// NOTE:
// The version we declare as a peer dependency in plugins.
{
try {
assert.strictEqual(resultString, expected);
} catch (err) {
hasErrors = true;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
formatCSSAssertError(testCaseLabel, testCaseOptions, err, true),
'error',
{ file: expectFilePath, line: 1, col: 1 },
));
} else {
failureSummary.add(testCaseLabel);
console.error(formatCSSAssertError(testCaseLabel, testCaseOptions, err));
}
}
}
// Assert result sourcemaps with recent PostCSS.
{
try {
if (result.map.toJSON().sources.includes('<no source>')) {
throw new Error('Sourcemap is broken');
}
} catch (err) {
hasErrors = true;
const helpText = '\nThis is most likely a newly created PostCSS AST Node without a value for "source".\nsee :\n- https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#24-set-nodesource-for-new-nodes\n- https://postcss.org/api/#node-source';
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
`${testCaseLabel}\n\nbroken source map: ${JSON.stringify(result.map.toJSON().sources)}\n${helpText}`,
'error',
{ file: testFilePath, line: 1, col: 1 },
));
} else {
failureSummary.add(testCaseLabel);
console.error(`\n${testCaseLabel}\n\nbroken source map: ${JSON.stringify(result.map.toJSON().sources)}\n${helpText}\n\n${dashesSeparator}`);
}
}
}
// Run "after" when initial postcss run has completely.
if (testCaseOptions.after) {
await testCaseOptions.after();
}
// Assert that the result can be passed back to PostCSS and still parses.
{
try {
const resultContents = await fsp.readFile(resultFilePath, 'utf8');
const secondPassResult = await postcss([noopPlugin()]).process(resultContents, {
from: resultFilePath,
to: resultFilePath,
map: {
inline: false,
annotation: false,
},
});
if (secondPassResult.warnings().length) {
throw new Error('Unexpected warnings on second pass');
}
} catch (_) {
hasErrors = true;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
`${testCaseLabel}\n\nresult was not parsable with PostCSS.`,
'error',
{ file: expectFilePath, line: 1, col: 1 },
));
} else {
failureSummary.add(testCaseLabel);
console.error(`\n${testCaseLabel}\n\nresult was not parsable with PostCSS.\n\n${dashesSeparator}`);
}
}
}
// Assert result with oldest supported PostCSS.
// Check against the actual result to avoid duplicate warnings.
//
// NOTE:
// The oldest version of PostCSS we support at this time.
// This does not need to be a different version than the latest version of PostCSS.
// There is no system behind setting this.
// It is here to allow testing a specific older version, if parts of the community can't update yet.
if (postcss([noopPlugin()]).version !== postcssOldestSupported([noopPlugin()]).version) { // https://postcss.org/api/#processor-version
const resultFromOldestPostCSS = await postcssOldestSupported(plugins as Array<AcceptedPlugin>).process(input, {
from: testFilePath,
to: resultFilePath,
map: {
inline: false,
annotation: false,
},
});
try {
assert.strictEqual(resultFromOldestPostCSS.css.toString(), resultString);
} catch (err) {
hasErrors = true;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
'testing older PostCSS:\n' + formatCSSAssertError(testCaseLabel, testCaseOptions, err, true),
'error',
{ file: expectFilePath, line: 1, col: 1 },
));
} else {
failureSummary.add(testCaseLabel);
console.error('testing older PostCSS:\n' + formatCSSAssertError(testCaseLabel, testCaseOptions, err));
}
}
}
// Assert that warnings have the expected amount.
{
try {
if (result.warnings().length || testCaseOptions.warnings) {
assert.strictEqual(result.warnings().length, testCaseOptions.warnings);
}
} catch (_) {
hasErrors = true;
if (emitGitHubAnnotations) {
console.log(formatGitHubActionAnnotation(
formatWarningsAssertError(testCaseLabel, testCaseOptions, result.warnings(), testCaseOptions.warnings, true),
'error',
{ file: expectFilePath, line: 1, col: 1 },
));
} else {
failureSummary.add(testCaseLabel);
console.error(formatWarningsAssertError(testCaseLabel, testCaseOptions, result.warnings(), testCaseOptions.warnings));
}
}
}
}
if (failureSummary.size) {
console.error('\nunexpected failures:');
for (const label of failureSummary.values()) {
console.error(' - ' + label);
}
}
if (hasErrors) {
process.exit(1);
}
console.warn('pass ' + (currentPlugin() as Plugin).postcssPlugin);
};
} | the_stack |
import { performanceLog } from "../common/decorators";
import { EOL } from "os";
import { parse } from "url";
import * as _ from "lodash";
import { CONNECTED_STATUS } from "../common/constants";
import {
TrackActionNames,
DebugCommandErrors,
CONNECTION_ERROR_EVENT_NAME,
DebugTools,
DEBUGGER_DETACHED_EVENT_NAME,
DEBUGGER_ATTACHED_EVENT_NAME,
} from "../constants";
import { EventEmitter } from "events";
import { IProjectDataService } from "../definitions/project";
import {
IDebugController,
IDeviceDebugService,
IDebugDataService,
IDebugData,
IDebugOptions,
IDebugResultInfo,
} from "../definitions/debug";
import { IDebugInformation } from "../declarations";
import {
IAnalyticsService,
IDictionary,
IErrors,
} from "../common/declarations";
import { IInjector } from "../common/definitions/yok";
import { injector } from "../common/yok";
export class DebugController extends EventEmitter implements IDebugController {
private _platformDebugServices: IDictionary<IDeviceDebugService> = {};
constructor(
private $analyticsService: IAnalyticsService,
private $debugDataService: IDebugDataService,
private $devicesService: Mobile.IDevicesService,
private $errors: IErrors,
private $injector: IInjector,
private $liveSyncProcessDataService: ILiveSyncProcessDataService,
private $logger: ILogger,
private $mobileHelper: Mobile.IMobileHelper,
private $projectDataService: IProjectDataService
) {
super();
}
@performanceLog()
public async startDebug(debugData: IDebugData): Promise<IDebugInformation> {
const { debugOptions: options } = debugData;
const device = this.$devicesService.getDeviceByIdentifier(
debugData.deviceIdentifier
);
if (!device) {
this.$errors.fail(
`Cannot find device with identifier ${debugData.deviceIdentifier}.`
);
}
if (device.deviceInfo.status !== CONNECTED_STATUS) {
this.$errors.fail(
`The device with identifier ${debugData.deviceIdentifier} is unreachable. Make sure it is Trusted and try again.`
);
}
await this.$analyticsService.trackEventActionInGoogleAnalytics({
action: TrackActionNames.Debug,
device,
additionalData:
this.$mobileHelper.isiOSPlatform(device.deviceInfo.platform) &&
options &&
options.inspector
? DebugTools.Inspector
: DebugTools.Chrome,
projectDir: debugData.projectDir,
});
if (
!(await device.applicationManager.isApplicationInstalled(
debugData.applicationIdentifier
))
) {
this.$errors.fail(
`The application ${debugData.applicationIdentifier} is not installed on device with identifier ${debugData.deviceIdentifier}.`
);
}
const debugService = this.getDeviceDebugService(device);
if (!debugService) {
this.$errors.fail(
`Unsupported device OS: ${device.deviceInfo.platform}. You can debug your applications only on iOS or Android.`
);
}
const debugOptions: IDebugOptions = _.cloneDeep(options);
const debugResultInfo = await debugService.debug(debugData, debugOptions);
return this.getDebugInformation(
debugResultInfo,
device.deviceInfo.identifier
);
}
public enableDebugging(
enableDebuggingData: IEnableDebuggingData
): Promise<IDebugInformation>[] {
const { deviceIdentifiers } = enableDebuggingData;
return _.map(deviceIdentifiers, (deviceIdentifier) =>
this.enableDebuggingCore(
enableDebuggingData.projectDir,
deviceIdentifier,
enableDebuggingData.debugOptions
)
);
}
public async disableDebugging(
disableDebuggingData: IDisableDebuggingData
): Promise<void> {
const { deviceIdentifiers, projectDir } = disableDebuggingData;
for (const deviceIdentifier of deviceIdentifiers) {
const liveSyncProcessInfo = this.$liveSyncProcessDataService.getPersistedData(
projectDir
);
if (liveSyncProcessInfo.currentSyncAction) {
await liveSyncProcessInfo.currentSyncAction;
}
const currentDeviceDescriptor = this.getDeviceDescriptor(
projectDir,
deviceIdentifier
);
if (currentDeviceDescriptor) {
currentDeviceDescriptor.debuggingEnabled = false;
} else {
this.$errors.fail(`Couldn't disable debugging for ${deviceIdentifier}`);
}
const currentDevice = this.$devicesService.getDeviceByIdentifier(
currentDeviceDescriptor.identifier
);
if (!currentDevice) {
this.$errors.fail(
`Couldn't disable debugging for ${deviceIdentifier}. Could not find device.`
);
}
await this.stopDebug(currentDevice.deviceInfo.identifier);
this.emit(DEBUGGER_DETACHED_EVENT_NAME, { deviceIdentifier });
}
}
public async attachDebugger(
attachDebuggerData: IAttachDebuggerData
): Promise<IDebugInformation> {
// Default values
if (attachDebuggerData.debugOptions) {
attachDebuggerData.debugOptions.chrome =
attachDebuggerData.debugOptions.chrome === undefined
? true
: attachDebuggerData.debugOptions.chrome;
attachDebuggerData.debugOptions.start =
attachDebuggerData.debugOptions.start === undefined
? true
: attachDebuggerData.debugOptions.start;
} else {
attachDebuggerData.debugOptions = {
chrome: true,
start: true,
};
}
const projectData = this.$projectDataService.getProjectData(
attachDebuggerData.projectDir
);
const debugData = this.$debugDataService.getDebugData(
attachDebuggerData.deviceIdentifier,
projectData,
attachDebuggerData.debugOptions
);
// const platformData = this.$platformsDataService.getPlatformData(settings.platform, projectData);
// Of the properties below only `buildForDevice` and `release` are currently used.
// Leaving the others with placeholder values so that they may not be forgotten in future implementations.
const debugInfo = await this.startDebug(debugData);
const result = this.printDebugInformation(
debugInfo,
attachDebuggerData.debugOptions.forceDebuggerAttachedEvent
);
return result;
}
@performanceLog()
public async enableDebuggingCoreWithoutWaitingCurrentAction(
projectDir: string,
deviceIdentifier: string,
debugOptions: IDebugOptions
): Promise<IDebugInformation> {
const deviceDescriptor = this.getDeviceDescriptor(
projectDir,
deviceIdentifier
);
if (!deviceDescriptor) {
this.$errors.fail(`Couldn't enable debugging for ${deviceIdentifier}`);
}
deviceDescriptor.debuggingEnabled = true;
deviceDescriptor.debugOptions = debugOptions;
const currentDeviceInstance = this.$devicesService.getDeviceByIdentifier(
deviceIdentifier
);
const attachDebuggerData: IAttachDebuggerData = {
deviceIdentifier,
isEmulator: currentDeviceInstance.isEmulator,
outputPath: deviceDescriptor.buildData.outputPath,
platform: currentDeviceInstance.deviceInfo.platform,
projectDir,
debugOptions,
};
let debugInformation: IDebugInformation;
try {
debugInformation = await this.attachDebugger(attachDebuggerData);
} catch (err) {
this.$logger.trace(
"Couldn't attach debugger, will modify options and try again.",
err
);
attachDebuggerData.debugOptions.start = false;
try {
debugInformation = await this.attachDebugger(attachDebuggerData);
} catch (innerErr) {
this.$logger.trace(
"Couldn't attach debugger with modified options.",
innerErr
);
throw err;
}
}
return debugInformation;
}
public printDebugInformation(
debugInformation: IDebugInformation,
fireDebuggerAttachedEvent: boolean = true
): IDebugInformation {
if (!!debugInformation.url) {
if (fireDebuggerAttachedEvent) {
this.emit(DEBUGGER_ATTACHED_EVENT_NAME, debugInformation);
}
this.$logger.info(
`To start debugging, open the following URL in Chrome:${EOL}${debugInformation.url}${EOL}`
.green
);
}
return debugInformation;
}
public async stopDebug(deviceIdentifier: string): Promise<void> {
const device = this.$devicesService.getDeviceByIdentifier(deviceIdentifier);
const debugService = this.getDeviceDebugService(device);
await debugService.debugStop();
}
private getDeviceDescriptor(
projectDir: string,
deviceIdentifier: string
): ILiveSyncDeviceDescriptor {
const deviceDescriptors = this.$liveSyncProcessDataService.getDeviceDescriptors(
projectDir
);
const currentDeviceDescriptor = _.find(
deviceDescriptors,
(d) => d.identifier === deviceIdentifier
);
return currentDeviceDescriptor;
}
private getDeviceDebugService(device: Mobile.IDevice): IDeviceDebugService {
if (!this._platformDebugServices[device.deviceInfo.identifier]) {
const devicePlatform = device.deviceInfo.platform;
if (this.$mobileHelper.isiOSPlatform(devicePlatform)) {
this._platformDebugServices[
device.deviceInfo.identifier
] = this.$injector.resolve("iOSDeviceDebugService", { device });
} else if (this.$mobileHelper.isAndroidPlatform(devicePlatform)) {
this._platformDebugServices[
device.deviceInfo.identifier
] = this.$injector.resolve("androidDeviceDebugService", { device });
} else {
this.$errors.fail(
DebugCommandErrors.UNSUPPORTED_DEVICE_OS_FOR_DEBUGGING
);
}
this.attachConnectionErrorHandlers(
this._platformDebugServices[device.deviceInfo.identifier]
);
}
return this._platformDebugServices[device.deviceInfo.identifier];
}
private attachConnectionErrorHandlers(
platformDebugService: IDeviceDebugService
) {
let connectionErrorHandler = (e: Error) =>
this.emit(CONNECTION_ERROR_EVENT_NAME, e);
connectionErrorHandler = connectionErrorHandler.bind(this);
platformDebugService.on(
CONNECTION_ERROR_EVENT_NAME,
connectionErrorHandler
);
}
private getDebugInformation(
debugResultInfo: IDebugResultInfo,
deviceIdentifier: string
): IDebugInformation {
const debugInfo: IDebugInformation = {
url: debugResultInfo.debugUrl,
port: 0,
deviceIdentifier,
};
if (debugResultInfo.debugUrl) {
const parseQueryString = true;
const wsQueryParam = <string>(
parse(debugResultInfo.debugUrl, parseQueryString).query.ws
);
const hostPortSplit = wsQueryParam && wsQueryParam.split(":");
debugInfo.port = hostPortSplit && +hostPortSplit[1];
}
return debugInfo;
}
private async enableDebuggingCore(
projectDir: string,
deviceIdentifier: string,
debugOptions: IDebugOptions
): Promise<IDebugInformation> {
const liveSyncProcessInfo = this.$liveSyncProcessDataService.getPersistedData(
projectDir
);
if (liveSyncProcessInfo && liveSyncProcessInfo.currentSyncAction) {
await liveSyncProcessInfo.currentSyncAction;
}
return this.enableDebuggingCoreWithoutWaitingCurrentAction(
projectDir,
deviceIdentifier,
debugOptions
);
}
}
injector.register("debugController", DebugController); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [frauddetector](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Frauddetector extends PolicyStatement {
public servicePrefix = 'frauddetector';
/**
* Statement provider for service [frauddetector](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to create a batch of variables
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_BatchCreateVariable.html
*/
public toBatchCreateVariable() {
return this.to('BatchCreateVariable');
}
/**
* Grants permission to get a batch of variables
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_BatchGetVariable.html
*/
public toBatchGetVariable() {
return this.to('BatchGetVariable');
}
/**
* Grants permission to cancel the specified batch import job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_CancelBatchImportJob.html
*/
public toCancelBatchImportJob() {
return this.to('CancelBatchImportJob');
}
/**
* Grants permission to cancel the specified batch prediction job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_CancelBatchPredictionJob.html
*/
public toCancelBatchPredictionJob() {
return this.to('CancelBatchPredictionJob');
}
/**
* Grants permission to create a batch import job
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_CreateBatchImportJob.html
*/
public toCreateBatchImportJob() {
return this.to('CreateBatchImportJob');
}
/**
* Grants permission to create a batch prediction job
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_CreateBatchPredictionJob.html
*/
public toCreateBatchPredictionJob() {
return this.to('CreateBatchPredictionJob');
}
/**
* Grants permission to create a detector version. The detector version starts in a DRAFT status
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_CreateDetectorVersion.html
*/
public toCreateDetectorVersion() {
return this.to('CreateDetectorVersion');
}
/**
* Grants permission to create a model using the specified model type
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_CreateModel.html
*/
public toCreateModel() {
return this.to('CreateModel');
}
/**
* Grants permission to create a version of the model using the specified model type and model id
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_CreateModelVersion.html
*/
public toCreateModelVersion() {
return this.to('CreateModelVersion');
}
/**
* Grants permission to create a rule for use with the specified detector
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_CreateRule.html
*/
public toCreateRule() {
return this.to('CreateRule');
}
/**
* Grants permission to create a variable
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_CreateVariable.html
*/
public toCreateVariable() {
return this.to('CreateVariable');
}
/**
* Grants permission to delete a batch import job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteBatchImportJob.html
*/
public toDeleteBatchImportJob() {
return this.to('DeleteBatchImportJob');
}
/**
* Grants permission to delete a batch prediction job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteBatchPredictionJob.html
*/
public toDeleteBatchPredictionJob() {
return this.to('DeleteBatchPredictionJob');
}
/**
* Grants permission to delete the detector. Before deleting a detector, you must first delete all detector versions and rule versions associated with the detector
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteDetector.html
*/
public toDeleteDetector() {
return this.to('DeleteDetector');
}
/**
* Grants permission to delete the detector version. You cannot delete detector versions that are in ACTIVE status
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteDetectorVersion.html
*/
public toDeleteDetectorVersion() {
return this.to('DeleteDetectorVersion');
}
/**
* Grants permission to delete an entity type. You cannot delete an entity type that is included in an event type
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteEntityType.html
*/
public toDeleteEntityType() {
return this.to('DeleteEntityType');
}
/**
* Grants permission to deletes the specified event
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteEvent.html
*/
public toDeleteEvent() {
return this.to('DeleteEvent');
}
/**
* Grants permission to delete an event type. You cannot delete an event type that is used in a detector or a model
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteEventType.html
*/
public toDeleteEventType() {
return this.to('DeleteEventType');
}
/**
* Grants permission to delete events for the specified event type
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteEventsByEventType.html
*/
public toDeleteEventsByEventType() {
return this.to('DeleteEventsByEventType');
}
/**
* Grants permission to remove a SageMaker model from Amazon Fraud Detector. You can remove an Amazon SageMaker model if it is not associated with a detector version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteExternalModel.html
*/
public toDeleteExternalModel() {
return this.to('DeleteExternalModel');
}
/**
* Grants permission to delete a label. You cannot delete labels that are included in an event type in Amazon Fraud Detector. You cannot delete a label assigned to an event ID. You must first delete the relevant event ID
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteLabel.html
*/
public toDeleteLabel() {
return this.to('DeleteLabel');
}
/**
* Grants permission to delete a model. You can delete models and model versions in Amazon Fraud Detector, provided that they are not associated with a detector version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteModel.html
*/
public toDeleteModel() {
return this.to('DeleteModel');
}
/**
* Grants permission to delete a model version. You can delete models and model versions in Amazon Fraud Detector, provided that they are not associated with a detector version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteModelVersion.html
*/
public toDeleteModelVersion() {
return this.to('DeleteModelVersion');
}
/**
* Grants permission to delete an outcome. You cannot delete an outcome that is used in a rule version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteOutcome.html
*/
public toDeleteOutcome() {
return this.to('DeleteOutcome');
}
/**
* Grants permission to delete the rule. You cannot delete a rule if it is used by an ACTIVE or INACTIVE detector version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteRule.html
*/
public toDeleteRule() {
return this.to('DeleteRule');
}
/**
* Grants permission to delete a variable. You cannot delete variables that are included in an event type in Amazon Fraud Detector
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DeleteVariable.html
*/
public toDeleteVariable() {
return this.to('DeleteVariable');
}
/**
* Grants permission to get all versions for a specified detector
*
* Access Level: Read
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DescribeDetector.html
*/
public toDescribeDetector() {
return this.to('DescribeDetector');
}
/**
* Grants permission to get all of the model versions for the specified model type or for the specified model type and model ID. You can also get details for a single, specified model version
*
* Access Level: Read
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_DescribeModelVersions.html
*/
public toDescribeModelVersions() {
return this.to('DescribeModelVersions');
}
/**
* Grants permission to get all batch import jobs or a specific job if you specify a job ID
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetBatchImportJobs.html
*/
public toGetBatchImportJobs() {
return this.to('GetBatchImportJobs');
}
/**
* Grants permission to get all batch prediction jobs or a specific job if you specify a job ID. This is a paginated API. If you provide a null maxResults, this action retrieves a maximum of 50 records per page. If you provide a maxResults, the value must be between 1 and 50. To get the next page results, provide the pagination token from the GetBatchPredictionJobsResponse as part of your request. A null pagination token fetches the records from the beginning
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetBatchPredictionJobs.html
*/
public toGetBatchPredictionJobs() {
return this.to('GetBatchPredictionJobs');
}
/**
* Grants permission to get a specific event type DeleteEventsByEventType API execution status
*
* Access Level: Read
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetDeleteEventsByEventTypeStatus.html
*/
public toGetDeleteEventsByEventTypeStatus() {
return this.to('GetDeleteEventsByEventTypeStatus');
}
/**
* Grants permission to get a particular detector version
*
* Access Level: Read
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetDetectorVersion.html
*/
public toGetDetectorVersion() {
return this.to('GetDetectorVersion');
}
/**
* Grants permission to get all detectors or a single detector if a detectorId is specified. This is a paginated API. If you provide a null maxResults, this action retrieves a maximum of 10 records per page. If you provide a maxResults, the value must be between 5 and 10. To get the next page results, provide the pagination token from the GetDetectorsResponse as part of your request. A null pagination token fetches the records from the beginning
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetDetectors.html
*/
public toGetDetectors() {
return this.to('GetDetectors');
}
/**
* Grants permission to get all entity types or a specific entity type if a name is specified. This is a paginated API. If you provide a null maxResults, this action retrieves a maximum of 10 records per page. If you provide a maxResults, the value must be between 5 and 10. To get the next page results, provide the pagination token from the GetEntityTypesResponse as part of your request. A null pagination token fetches the records from the beginning
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetEntityTypes.html
*/
public toGetEntityTypes() {
return this.to('GetEntityTypes');
}
/**
* Grants permission to get the details of the specified event
*
* Access Level: Read
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetEvent.html
*/
public toGetEvent() {
return this.to('GetEvent');
}
/**
* Grants permission to evaluate an event against a detector version. If a version ID is not provided, the detector’s (ACTIVE) version is used
*
* Access Level: Read
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetEventPrediction.html
*/
public toGetEventPrediction() {
return this.to('GetEventPrediction');
}
/**
* Grants permission to get all event types or a specific event type if name is provided. This is a paginated API. If you provide a null maxResults, this action retrieves a maximum of 10 records per page. If you provide a maxResults, the value must be between 5 and 10. To get the next page results, provide the pagination token from the GetEventTypesResponse as part of your request. A null pagination token fetches the records from the beginning
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetEventTypes.html
*/
public toGetEventTypes() {
return this.to('GetEventTypes');
}
/**
* Grants permission to get the details for one or more Amazon SageMaker models that have been imported into the service. This is a paginated API. If you provide a null maxResults, this actions retrieves a maximum of 10 records per page. If you provide a maxResults, the value must be between 5 and 10. To get the next page results, provide the pagination token from the GetExternalModelsResult as part of your request. A null pagination token fetches the records from the beginning
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetExternalModels.html
*/
public toGetExternalModels() {
return this.to('GetExternalModels');
}
/**
* Grants permission to get the encryption key if a Key Management Service (KMS) customer master key (CMK) has been specified to be used to encrypt content in Amazon Fraud Detector
*
* Access Level: Read
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetKMSEncryptionKey.html
*/
public toGetKMSEncryptionKey() {
return this.to('GetKMSEncryptionKey');
}
/**
* Grants permission to get all labels or a specific label if name is provided. This is a paginated API. If you provide a null maxResults, this action retrieves a maximum of 50 records per page. If you provide a maxResults, the value must be between 10 and 50. To get the next page results, provide the pagination token from the GetGetLabelsResponse as part of your request. A null pagination token fetches the records from the beginning
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetLabels.html
*/
public toGetLabels() {
return this.to('GetLabels');
}
/**
* Grants permission to get the details of the specified model version
*
* Access Level: Read
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetModelVersion.html
*/
public toGetModelVersion() {
return this.to('GetModelVersion');
}
/**
* Grants permission to get one or more models. Gets all models for the AWS account if no model type and no model id provided. Gets all models for the AWS account and model type, if the model type is specified but model id is not provided. Gets a specific model if (model type, model id) tuple is specified
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetModels.html
*/
public toGetModels() {
return this.to('GetModels');
}
/**
* Grants permission to get one or more outcomes. This is a paginated API. If you provide a null maxResults, this actions retrieves a maximum of 100 records per page. If you provide a maxResults, the value must be between 50 and 100. To get the next page results, provide the pagination token from the GetOutcomesResult as part of your request. A null pagination token fetches the records from the beginning
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetOutcomes.html
*/
public toGetOutcomes() {
return this.to('GetOutcomes');
}
/**
* Grants permission to get all rules for a detector (paginated) if ruleId and ruleVersion are not specified. Gets all rules for the detector and the ruleId if present (paginated). Gets a specific rule if both the ruleId and the ruleVersion are specified
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetRules.html
*/
public toGetRules() {
return this.to('GetRules');
}
/**
* Grants permission to get all of the variables or the specific variable. This is a paginated API. Providing null maxSizePerPage results in retrieving maximum of 100 records per page. If you provide maxSizePerPage the value must be between 50 and 100. To get the next page result, a provide a pagination token from GetVariablesResult as part of your request. Null pagination token fetches the records from the beginning
*
* Access Level: List
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_GetVariables.html
*/
public toGetVariables() {
return this.to('GetVariables');
}
/**
* Grants permission to list all tags associated with the resource. This is a paginated API. To get the next page results, provide the pagination token from the response as part of your request. A null pagination token fetches the records from the beginning
*
* Access Level: Read
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to create or update a detector
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_PutDetector.html
*/
public toPutDetector() {
return this.to('PutDetector');
}
/**
* Grants permission to create or update an entity type. An entity represents who is performing the event. As part of a fraud prediction, you pass the entity ID to indicate the specific entity who performed the event. An entity type classifies the entity. Example classifications include customer, merchant, or account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_PutEntityType.html
*/
public toPutEntityType() {
return this.to('PutEntityType');
}
/**
* Grants permission to create or update an event type. An event is a business activity that is evaluated for fraud risk. With Amazon Fraud Detector, you generate fraud predictions for events. An event type defines the structure for an event sent to Amazon Fraud Detector. This includes the variables sent as part of the event, the entity performing the event (such as a customer), and the labels that classify the event. Example event types include online payment transactions, account registrations, and authentications
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_PutEventType.html
*/
public toPutEventType() {
return this.to('PutEventType');
}
/**
* Grants permission to create or update an Amazon SageMaker model endpoint. You can also use this action to update the configuration of the model endpoint, including the IAM role and/or the mapped variables
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_PutExternalModel.html
*/
public toPutExternalModel() {
return this.to('PutExternalModel');
}
/**
* Grants permission to specify the Key Management Service (KMS) customer master key (CMK) to be used to encrypt content in Amazon Fraud Detector
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_PutKMSEncryptionKey.html
*/
public toPutKMSEncryptionKey() {
return this.to('PutKMSEncryptionKey');
}
/**
* Grants permission to create or update label. A label classifies an event as fraudulent or legitimate. Labels are associated with event types and used to train supervised machine learning models in Amazon Fraud Detector
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_PutLabel.html
*/
public toPutLabel() {
return this.to('PutLabel');
}
/**
* Grants permission to create or update an outcome
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_PutOutcome.html
*/
public toPutOutcome() {
return this.to('PutOutcome');
}
/**
* Grants permission to send event
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_SendEvent.html
*/
public toSendEvent() {
return this.to('SendEvent');
}
/**
* Grants permission to assign tags to a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove tags from a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update a detector version. The detector version attributes that you can update include models, external model endpoints, rules, rule execution mode, and description. You can only update a DRAFT detector version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UpdateDetectorVersion.html
*/
public toUpdateDetectorVersion() {
return this.to('UpdateDetectorVersion');
}
/**
* Grants permission to update the detector version's description. You can update the metadata for any detector version (DRAFT, ACTIVE, or INACTIVE)
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UpdateDetectorVersionMetadata.html
*/
public toUpdateDetectorVersionMetadata() {
return this.to('UpdateDetectorVersionMetadata');
}
/**
* Grants permission to update the detector version’s status. You can perform the following promotions or demotions using UpdateDetectorVersionStatus: DRAFT to ACTIVE, ACTIVE to INACTIVE, and INACTIVE to ACTIVE
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UpdateDetectorVersionStatus.html
*/
public toUpdateDetectorVersionStatus() {
return this.to('UpdateDetectorVersionStatus');
}
/**
* Grants permission to update an existing event record's label value
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UpdateEventLabel.html
*/
public toUpdateEventLabel() {
return this.to('UpdateEventLabel');
}
/**
* Grants permission to update a model. You can update the description attribute using this action
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UpdateModel.html
*/
public toUpdateModel() {
return this.to('UpdateModel');
}
/**
* Grants permission to update a model version. Updating a model version retrains an existing model version using updated training data and produces a new minor version of the model. You can update the training data set location and data access role attributes using this action. This action creates and trains a new minor version of the model, for example version 1.01, 1.02, 1.03
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UpdateModelVersion.html
*/
public toUpdateModelVersion() {
return this.to('UpdateModelVersion');
}
/**
* Grants permission to update the status of a model version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UpdateModelVersionStatus.html
*/
public toUpdateModelVersionStatus() {
return this.to('UpdateModelVersionStatus');
}
/**
* Grants permission to update a rule's metadata. The description attribute can be updated
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UpdateRuleMetadata.html
*/
public toUpdateRuleMetadata() {
return this.to('UpdateRuleMetadata');
}
/**
* Grants permission to update a rule version resulting in a new rule version. Updates a rule version resulting in a new rule version (version 1, 2, 3 ...)
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UpdateRuleVersion.html
*/
public toUpdateRuleVersion() {
return this.to('UpdateRuleVersion');
}
/**
* Grants permission to update a variable
*
* Access Level: Write
*
* https://docs.aws.amazon.com/frauddetector/latest/api/API_UpdateVariable.html
*/
public toUpdateVariable() {
return this.to('UpdateVariable');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"BatchCreateVariable",
"CancelBatchImportJob",
"CancelBatchPredictionJob",
"CreateBatchImportJob",
"CreateBatchPredictionJob",
"CreateDetectorVersion",
"CreateModel",
"CreateModelVersion",
"CreateRule",
"CreateVariable",
"DeleteBatchImportJob",
"DeleteBatchPredictionJob",
"DeleteDetector",
"DeleteDetectorVersion",
"DeleteEntityType",
"DeleteEvent",
"DeleteEventType",
"DeleteEventsByEventType",
"DeleteExternalModel",
"DeleteLabel",
"DeleteModel",
"DeleteModelVersion",
"DeleteOutcome",
"DeleteRule",
"DeleteVariable",
"PutDetector",
"PutEntityType",
"PutEventType",
"PutExternalModel",
"PutKMSEncryptionKey",
"PutLabel",
"PutOutcome",
"SendEvent",
"UpdateDetectorVersion",
"UpdateDetectorVersionMetadata",
"UpdateDetectorVersionStatus",
"UpdateEventLabel",
"UpdateModel",
"UpdateModelVersion",
"UpdateModelVersionStatus",
"UpdateRuleMetadata",
"UpdateRuleVersion",
"UpdateVariable"
],
"List": [
"BatchGetVariable",
"GetBatchImportJobs",
"GetBatchPredictionJobs",
"GetDetectors",
"GetEntityTypes",
"GetEventTypes",
"GetExternalModels",
"GetLabels",
"GetModels",
"GetOutcomes",
"GetRules",
"GetVariables"
],
"Read": [
"DescribeDetector",
"DescribeModelVersions",
"GetDeleteEventsByEventTypeStatus",
"GetDetectorVersion",
"GetEvent",
"GetEventPrediction",
"GetKMSEncryptionKey",
"GetModelVersion",
"ListTagsForResource"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type batch-prediction to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onBatchPrediction(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:batch-prediction/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type detector to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDetector(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:detector/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type detector-version to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDetectorVersion(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:detector-version/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type entity-type to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onEntityType(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:entity-type/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type external-model to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onExternalModel(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:external-model/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type event-type to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onEventType(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:event-type/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type label to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onLabel(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:label/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type model to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onModel(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:model/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type model-version to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onModelVersion(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:model-version/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type outcome to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onOutcome(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:outcome/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type rule to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onRule(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:rule/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type variable to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onVariable(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:variable/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type batch-import to the statement
*
* https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonfrauddetector.html#amazonfrauddetector-resources-for-iam-policies
*
* @param resourcePath - Identifier for the resourcePath.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onBatchImport(resourcePath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:frauddetector:${Region}:${Account}:batch-import/${ResourcePath}';
arn = arn.replace('${ResourcePath}', resourcePath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import execa from 'execa';
import fs from 'fs-extra';
import { ExitError, Path } from '@boost/common';
import { normalizeSeparators } from '@boost/common/test';
import { color } from '@boost/internal';
import { DriverContext } from '../../../src/contexts/DriverContext';
import { Driver } from '../../../src/Driver';
import { ExecuteCommandRoutine } from '../../../src/routines/driver/ExecuteCommandRoutine';
import {
getRoot,
mockDebugger,
mockDriver,
mockTool,
prependRoot,
stubDriverContext,
} from '../../../src/test';
import { Tool } from '../../../src/Tool';
describe('ExecuteCommandRoutine', () => {
let routine: ExecuteCommandRoutine;
let context: DriverContext;
let driver: Driver;
let tool: Tool;
beforeEach(() => {
tool = mockTool();
driver = mockDriver('babel', tool);
driver.configure({
args: ['--qux'],
env: { DEV: 'true' },
});
context = stubDriverContext(driver);
routine = new ExecuteCommandRoutine('babel', 'Run babel', {
argv: ['-a', '--foo', 'bar', 'baz'],
tool,
});
// @ts-expect-error Overwrite readonly
routine.debug = mockDebugger();
});
describe('constructor()', () => {
it('errors if `forceConfigOption` is not a boolean', () => {
expect(() => {
routine = new ExecuteCommandRoutine('test', 'test', {
// @ts-expect-error Invalid type
forceConfigOption: 'foo',
});
}).toThrowErrorMatchingSnapshot();
});
it('errors if `packageRoot` is not a string', () => {
expect(() => {
routine = new ExecuteCommandRoutine('test', 'test', {
// @ts-expect-error Invalid type
packageRoot: 123,
});
}).toThrowErrorMatchingSnapshot();
});
});
describe('captureOutput()', () => {
let logSpy: jest.SpyInstance;
let errorSpy: jest.SpyInstance;
let stream: execa.ExecaChildProcess;
class MockStream {
handler?: (chunk: Buffer) => void;
pipe() {
return this;
}
on(key: string, handler: (chunk: Buffer) => void) {
this.handler = handler;
return this;
}
emit() {
if (this.handler) {
this.handler(Buffer.from('buffered', 'utf8'));
}
}
}
beforeEach(() => {
tool.outStream = { write() {} };
tool.errStream = { write() {} };
stream = {
// @ts-expect-error Invalid type
stdout: new MockStream(),
// @ts-expect-error Invalid type
stderr: new MockStream(),
};
logSpy = jest.spyOn(tool.outStream, 'write');
errorSpy = jest.spyOn(tool.errStream, 'write');
});
afterEach(() => {
logSpy.mockRestore();
errorSpy.mockRestore();
});
describe('watch', () => {
it('enables if args option matches watch option', () => {
driver.metadata.watchOptions = ['--watch'];
context.args.unknown.watch = 'true';
expect(routine.captureOutput(context, stream)).toBe('watch');
});
it('enables if args option matches short watch option', () => {
driver.metadata.watchOptions = ['-w'];
context.args.unknown.w = 'true';
expect(routine.captureOutput(context, stream)).toBe('watch');
});
it('enables if positional args includes watch option', () => {
driver.metadata.watchOptions = ['watch'];
context.args.params = ['watch'];
expect(routine.captureOutput(context, stream)).toBe('watch');
});
it('disables if args option doesnt match watch option', () => {
driver.metadata.watchOptions = ['--watch'];
expect(routine.captureOutput(context, stream)).toBe('buffer');
});
it('disables if positional args doesnt include watch option', () => {
driver.metadata.watchOptions = ['--watch'];
context.args.params = ['--notWatch'];
expect(routine.captureOutput(context, stream)).toBe('buffer');
});
it('disables if args option is falsy', () => {
driver.metadata.watchOptions = ['--watch'];
expect(routine.captureOutput(context, stream)).toBe('buffer');
});
it('pipes a batch stream when enabled', () => {
const outSpy = jest.spyOn(stream.stdout!, 'pipe');
const errSpy = jest.spyOn(stream.stderr!, 'pipe');
driver.metadata.watchOptions = ['--watch'];
context.args.unknown.watch = 'true';
routine.captureOutput(context, stream);
expect(outSpy).toHaveBeenCalled();
expect(errSpy).toHaveBeenCalled();
});
it('registers a data handler when using watch', () => {
const outSpy = jest.spyOn(stream.stdout!, 'on');
const errSpy = jest.spyOn(stream.stderr!, 'on');
driver.metadata.watchOptions = ['--watch'];
context.args.unknown.watch = 'true';
routine.captureOutput(context, stream);
expect(outSpy).toHaveBeenCalledWith('data', expect.anything());
expect(errSpy).toHaveBeenCalledWith('data', expect.anything());
});
it('writes chunk to stdout stream', () => {
driver.metadata.watchOptions = ['--watch'];
context.args.unknown.watch = 'true';
routine.captureOutput(context, stream);
stream.stdout!.emit('data');
expect(logSpy).toHaveBeenCalledWith('buffered');
});
});
['stream', 'pipe'].forEach((strategy) => {
describe(`${strategy}`, () => {
beforeEach(() => {
driver.configure({
outputStrategy: strategy as 'stream',
});
});
it('enables if option is set', () => {
expect(routine.captureOutput(context, stream)).toBe(strategy);
});
it('doesnt pipe a batch stream', () => {
const outSpy = jest.spyOn(stream.stdout!, 'pipe');
const errSpy = jest.spyOn(stream.stderr!, 'pipe');
routine.captureOutput(context, stream);
expect(outSpy).not.toHaveBeenCalled();
expect(errSpy).not.toHaveBeenCalled();
});
it('registers a data handler', () => {
const outSpy = jest.spyOn(stream.stdout!, 'on');
const errSpy = jest.spyOn(stream.stderr!, 'on');
routine.captureOutput(context, stream);
expect(outSpy).toHaveBeenCalledWith('data', expect.anything());
expect(errSpy).toHaveBeenCalledWith('data', expect.anything());
});
it('writes chunk to stdout stream', () => {
routine.captureOutput(context, stream);
stream.stdout!.emit('data');
expect(logSpy).toHaveBeenCalledWith('buffered');
});
});
});
describe('buffer', () => {
beforeEach(() => {
driver.configure({
outputStrategy: 'buffer',
});
});
it('defaults to buffer if no option or not watching', () => {
expect(routine.captureOutput(context, stream)).toBe('buffer');
});
});
});
describe('execute()', () => {
beforeEach(() => {
driver.metadata.filterOptions = true;
});
it('executes pipeline in order', async () => {
routine.options.argv.push('--out-dir', './lib');
const argSpy = jest.spyOn(routine, 'gatherArgs');
const globSpy = jest.spyOn(routine, 'expandGlobPatterns');
const filterSpy = jest.spyOn(routine, 'filterUnknownOptions');
const optSpy = jest.spyOn(routine, 'includeConfigOption');
const runSpy = jest.spyOn(routine, 'runCommandWithArgs');
const response = await routine.execute(context);
expect(argSpy).toHaveBeenCalledWith(context, undefined, expect.anything());
expect(globSpy).toHaveBeenCalledWith(
context,
['--qux', '-a', '--foo', 'bar', 'baz', '--out-dir', './lib'],
expect.anything(),
);
expect(filterSpy).toHaveBeenCalledWith(
context,
['--qux', '-a', '--foo', 'bar', 'baz', '--out-dir', './lib'],
expect.anything(),
);
expect(optSpy).not.toHaveBeenCalled();
expect(runSpy).toHaveBeenCalledWith(
context,
['baz', '--out-dir', './lib'],
expect.anything(),
);
expect(response).toEqual({ stdout: '' });
});
it('includes config option if `useConfigOption` is true', async () => {
driver.metadata.useConfigOption = true;
context.configPaths.push({
driver: 'babel',
path: prependRoot(driver.metadata.configName),
});
const optSpy = jest.spyOn(routine, 'includeConfigOption');
const runSpy = jest.spyOn(routine, 'runCommandWithArgs');
await routine.execute(context);
expect(optSpy).toHaveBeenCalledWith(context, ['baz'], expect.anything());
expect(runSpy).toHaveBeenCalledWith(
context,
['baz', '--config', prependRoot(driver.metadata.configName).path()],
expect.anything(),
);
});
it('doesnt filter unknown if `filterOptions` is false', async () => {
driver.metadata.filterOptions = false;
const filterSpy = jest.spyOn(routine, 'filterUnknownOptions');
await routine.execute(context);
expect(filterSpy).not.toHaveBeenCalled();
});
it('calls `copyConfigToWorkspace` when driver is workspaces enabled', async () => {
driver.metadata.workspaceStrategy = 'copy';
routine.configure({
packageRoot: '/some/root',
});
const copySpy = jest.spyOn(routine, 'copyConfigToWorkspacePackage');
await routine.execute(context);
expect(copySpy).toHaveBeenCalledWith(context, ['baz'], expect.anything());
});
it('doesnt call `copyConfigToWorkspace` when driver is not workspaces enabled', async () => {
routine.configure({
packageRoot: '/some/root',
});
const copySpy = jest.spyOn(routine, 'copyConfigToWorkspacePackage');
await routine.execute(context);
expect(copySpy).not.toHaveBeenCalled();
});
it('doesnt call `copyConfigToWorkspace` when no workspace root', async () => {
driver.metadata.workspaceStrategy = 'copy';
const copySpy = jest.spyOn(routine, 'copyConfigToWorkspacePackage');
await routine.execute(context);
expect(copySpy).not.toHaveBeenCalled();
});
it('doesnt call `expandGlobPatterns` when expandGlobs is `false`', async () => {
driver.configure({ expandGlobs: false });
const expandGlobsSpy = jest.spyOn(routine, 'expandGlobPatterns');
await routine.execute(context);
expect(expandGlobsSpy).not.toHaveBeenCalled();
});
});
describe('copyConfigToWorkspacePackage()', () => {
it('copies each config into workspace root', async () => {
const copySpy = jest.spyOn(fs, 'copyFileSync').mockImplementation(() => true);
routine.configure({
packageRoot: '/some/root',
});
context.configPaths = [
{ driver: 'babel', path: new Path('.babelrc') },
{ driver: 'jest', path: new Path('jest.json') },
];
const args = await routine.copyConfigToWorkspacePackage(context, ['foo', '--bar']);
expect(args).toEqual(['foo', '--bar']);
expect(copySpy).toHaveBeenCalledWith('.babelrc', normalizeSeparators('/some/root/.babelrc'));
expect(copySpy).toHaveBeenCalledWith(
'jest.json',
normalizeSeparators('/some/root/jest.json'),
);
copySpy.mockRestore();
});
});
describe('expandGlobPatterns()', () => {
it('passes through if no globs', async () => {
const args = await routine.expandGlobPatterns(context, ['--foo', 'bar', '-z']);
expect(args).toEqual(['--foo', 'bar', '-z']);
});
it('converts globs to paths', async () => {
const args = await routine.expandGlobPatterns(context, ['--foo', '../tests/*', 'bar']);
// Make testing easier
args.sort();
expect(args).toEqual([
'--foo',
normalizeSeparators('../tests/__fixtures__'),
normalizeSeparators('../tests/configs'),
normalizeSeparators('../tests/setup.ts'),
'bar',
]);
});
it('handles missing paths', async () => {
const args = await routine.expandGlobPatterns(context, ['../some-fake-path/*.js']);
expect(args).toEqual([]);
});
});
describe('extractNativeOptions()', () => {
it('extracts all types of options', async () => {
const options = await routine.extractNativeOptions(context);
expect(options).toEqual(
expect.objectContaining({
'-f': true, // Short
'-M': true, // Uppercase short
'--filename': true, // Long
'--no-highlight-code': true, // With dashes
}),
);
});
it('supports multiple options within `helpOption`', async () => {
driver.metadata.helpOption = '--help --all';
const spy = jest.spyOn(routine, 'executeCommand');
await routine.extractNativeOptions(context);
expect(spy).toHaveBeenCalledWith('babel', ['--help', '--all'], {
env: { DEV: 'true' },
preferLocal: true,
});
});
it('supports uppercased options', async () => {
driver.getSupportedOptions = () => ['-u', '--all', '--changedFiles', '--watch-only'];
context.primaryDriver = driver;
const options = await routine.extractNativeOptions(context);
expect(options).toEqual(
expect.objectContaining({
'-u': true, // Short
'--all': true, // Long
'--changedFiles': true, // Camel case
'--watch-only': true, // Dashed
}),
);
});
});
describe('filterUnknownOptions()', () => {
it('returns supported options', async () => {
const args = await routine.filterUnknownOptions(context, [
'./src',
'-o',
'./lib',
'--out-dir',
'./dist',
'--minified',
]);
expect(args).toEqual(['./src', '-o', './lib', '--out-dir', './dist', '--minified']);
});
it('filters unsupported options', async () => {
const args = await routine.filterUnknownOptions(context, [
'./src',
'--foo',
'-o',
'./lib',
'--out-dir',
'./dist',
'-X',
'--minified',
'--bar',
]);
expect(args).toEqual(['./src', '-o', './lib', '--out-dir', './dist', '--minified']);
expect(routine.debug).toHaveBeenCalledWith(
'Filtered args: %s',
color.mute('--foo, -X, --bar'),
);
});
it('skips unsupported option setters', async () => {
const args = await routine.filterUnknownOptions(context, [
'--foo',
'123',
'--bar=456',
'-w',
'-c',
'789',
'-c=666',
]);
expect(args).toEqual(['-w']);
expect(routine.debug).toHaveBeenCalledWith(
'Filtered args: %s',
color.mute('--foo, 123, --bar=456, -c, 789, -c=666'),
);
});
});
describe('gatherArgs()', () => {
it('merges driver and command line args', async () => {
const args = await routine.gatherArgs(context);
expect(args).toEqual(['--qux', '-a', '--foo', 'bar', 'baz']);
});
it('rebuilds context args object', async () => {
expect(context.args).toEqual(
expect.objectContaining({
params: ['baz'],
options: {
a: true,
foo: 'bar',
},
}),
);
await routine.gatherArgs(context);
expect(context.args).toEqual(
expect.objectContaining({
params: ['baz'],
options: {
a: true,
foo: 'bar',
qux: true,
},
}),
);
});
});
describe('includeConfigOption()', () => {
it('does nothing if a config path doesnt match', async () => {
const args = await routine.includeConfigOption(context, ['--foo']);
expect(args).toEqual(['--foo']);
});
it('appends config path for a match', async () => {
context.configPaths.push({
driver: 'babel',
path: prependRoot(driver.metadata.configName),
});
const args = await routine.includeConfigOption(context, ['--foo']);
expect(args).toEqual(['--foo', '--config', prependRoot(driver.metadata.configName).path()]);
});
});
describe('runCommandWithArgs()', () => {
const task = expect.anything(); // new Task<DriverContext>('Task', () => {});
beforeEach(() => {
jest
.spyOn(routine, 'executeCommand')
.mockImplementation(() => Promise.resolve({ success: true } as any));
jest.spyOn(driver, 'processSuccess').mockImplementation();
jest.spyOn(driver, 'processFailure').mockImplementation();
});
it('executes command with correct args', async () => {
await routine.runCommandWithArgs(context, ['--wtf'], task);
expect(routine.executeCommand).toHaveBeenCalledWith('babel', ['--wtf'], {
cwd: getRoot().path(),
env: { DEV: 'true' },
preferLocal: true,
workUnit: task,
wrap: expect.any(Function),
});
});
it('handles success using driver', async () => {
const response = await routine.runCommandWithArgs(context, ['--wtf'], task);
expect(response).toEqual({ success: true });
expect(driver.processSuccess).toHaveBeenCalledWith({ success: true });
});
it('handles failure using driver', async () => {
(routine.executeCommand as jest.Mock).mockImplementation(() =>
Promise.reject(new Error('Oops')),
);
try {
await routine.runCommandWithArgs(context, ['--wtf'], task);
} catch (error) {
expect(driver.processFailure).toHaveBeenCalledWith(error);
}
});
it('persists exit code when a failure', async () => {
(routine.executeCommand as jest.Mock).mockImplementation(() => {
const error = new Error('Oops');
// @ts-expect-error Field doesnt exist on errors
error.exitCode = 3;
return Promise.reject(error);
});
try {
await routine.runCommandWithArgs(context, ['--wtf'], task);
} catch (error) {
expect(error).toBeInstanceOf(ExitError);
expect((error as ExitError).code).toBe(3);
}
});
it('handles out of memory failures', async () => {
(routine.executeCommand as jest.Mock).mockImplementation(() =>
// eslint-disable-next-line prefer-promise-reject-errors
Promise.reject({ exitCode: null, message: '', signal: 'SIGKILL' }),
);
try {
await routine.runCommandWithArgs(context, ['--wtf'], task);
} catch (error) {
expect(error).toEqual(new ExitError('Out of memory!', 1));
}
});
it('doesnt handle failure using driver if MaxBufferError occured', async () => {
const error = new Error('Oops');
error.name = 'MaxBufferError';
(routine.executeCommand as jest.Mock).mockImplementation(() => Promise.reject(error));
try {
await routine.runCommandWithArgs(context, ['--wtf'], task);
} catch {
expect(driver.processFailure).not.toHaveBeenCalled();
}
});
it('emits `onBeforeExecute` event', async () => {
const spy = jest.fn();
driver.onBeforeExecute.listen(spy);
await routine.runCommandWithArgs(context, ['--wtf'], task);
expect(spy).toHaveBeenCalledWith(context, ['--wtf']);
});
it('emits `onAfterExecute` event on success', async () => {
const spy = jest.fn();
driver.onAfterExecute.listen(spy);
await routine.runCommandWithArgs(context, ['--wtf'], task);
expect(spy).toHaveBeenCalledWith(context, { success: true });
});
it('emits `onFailedExecute` event on failure', async () => {
const spy = jest.fn();
driver.onFailedExecute.listen(spy);
(routine.executeCommand as jest.Mock).mockImplementation(() =>
Promise.reject(new Error('Oops')),
);
try {
await routine.runCommandWithArgs(context, ['--wtf'], task);
} catch (error) {
expect(spy).toHaveBeenCalledWith(context, error);
}
});
});
}); | the_stack |
import test, { Test } from "tape-promise/tape";
import { v4 as uuidv4 } from "uuid";
import HelloWorldContractJson from "../../../../solidity/hello-world-contract/HelloWorld.json";
import Web3 from "web3";
import Web3JsQuorum, { IPrivateTransactionReceipt } from "web3js-quorum";
import { BesuMpTestLedger } from "@hyperledger/cactus-test-tooling";
import { LogLevelDesc } from "@hyperledger/cactus-common";
import {
EthContractInvocationType,
PluginFactoryLedgerConnector,
Web3SigningCredentialType,
} from "../../../../../main/typescript";
import { PluginImportType } from "@hyperledger/cactus-core-api";
import { PluginRegistry } from "@hyperledger/cactus-core";
import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory";
const testCase = "Executes private transactions on Hyperledger Besu";
const logLevel: LogLevelDesc = "TRACE";
const doctorCactusHex =
"0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d446f63746f722043616374757300000000000000000000000000000000000000";
// WARNING: the keys here are demo purposes ONLY. Please use a tool like Orchestrate or EthSigner for production, rather than hard coding private keys
const keysStatic = {
tessera: {
member1: {
publicKey: "BULeR8JyUWhiuuCMU/HLA0Q5pzkYT+cHII3ZKBey3Bo=",
},
member2: {
publicKey: "QfeDAys9MPDs2XHExtc84jKGHxZg/aj52DTh0vtA3Xc=",
},
member3: {
publicKey: "1iTZde/ndBHvzhcl7V68x44Vx7pl8nwx9LqnM/AfJUg=",
},
},
besu: {
member1: {
url: "http://127.0.0.1:20000",
wsUrl: "ws://127.0.0.1:20001",
privateKey:
"8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63",
},
member2: {
url: "http://127.0.0.1:20002",
wsUrl: "ws://127.0.0.1:20003",
privateKey:
"c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3",
},
member3: {
url: "http://127.0.0.1:20004",
wsUrl: "ws://127.0.0.1:20005",
privateKey:
"ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f",
},
ethsignerProxy: {
url: "http://127.0.0.1:18545",
accountAddress: "9b790656b9ec0db1936ed84b3bea605873558198",
},
},
};
test(testCase, async (t: Test) => {
// At development time one can specify this environment variable if there is
// a multi-party network already running, which is doable with something like
// this on the terminal:
// docker run --rm --privileged --publish 2222:22 --publish 3000:3000 --publish 8545:8545 --publish 8546:8546 --publish 9001:9001 --publish 9081:9081 --publish 9082:9082 --publish 9083:9083 --publish 9090:9090 --publish 18545:18545 --publish 20000:20000 --publish 20001:20001 --publish 20002:20002 --publish 20003:20003 --publish 20004:20004 --publish 20005:20005 --publish 25000:25000 petermetz/cactus-besu-multi-party-all-in-one:0.1.2
//
// The upside of this approach is that a new container is not launched from
// scratch for every test execution which enables faster iteration.
const preWarmedLedger = process.env.CACTUS_TEST_PRE_WARMED_LEDGER === "true";
let keys: any;
if (preWarmedLedger) {
keys = keysStatic;
} else {
const ledger = new BesuMpTestLedger({ logLevel });
test.onFinish(() => ledger.stop());
await ledger.start();
keys = await ledger.getKeys();
}
const rpcApiHttpHostMember1 = keys.besu.member1.url;
const rpcApiHttpHostMember2 = keys.besu.member2.url;
const rpcApiHttpHostMember3 = keys.besu.member3.url;
const rpcApiWsHostMember1 = keys.besu.member1.wsUrl;
const rpcApiWsHostMember2 = keys.besu.member2.wsUrl;
const rpcApiWsHostMember3 = keys.besu.member3.wsUrl;
const web3Member1 = new Web3(rpcApiHttpHostMember1);
const web3Member2 = new Web3(rpcApiHttpHostMember2);
const web3Member3 = new Web3(rpcApiHttpHostMember3);
const pluginRegistry1 = new PluginRegistry();
const pluginRegistry2 = new PluginRegistry();
const pluginRegistry3 = new PluginRegistry();
const pluginFactoryLedgerConnector = new PluginFactoryLedgerConnector({
pluginImportType: PluginImportType.Local,
});
const connectorInstanceId1 = "besu1_" + uuidv4();
const connectorInstanceId2 = "besu2_" + uuidv4();
const connectorInstanceId3 = "besu3_" + uuidv4();
const keychainInstanceId1 = "keychain_instance1_" + uuidv4();
const keychainId1 = "keychain1_" + uuidv4();
const keychain1 = new PluginKeychainMemory({
instanceId: keychainInstanceId1,
keychainId: keychainId1,
logLevel,
});
t.ok(keychain1, "keychain1 truthy OK");
keychain1.set(
HelloWorldContractJson.contractName,
JSON.stringify(HelloWorldContractJson),
);
pluginRegistry1.add(keychain1);
const keychainInstanceId2 = "keychain_instance2_" + uuidv4();
const keychainId2 = "keychain2_" + uuidv4();
const keychain2 = new PluginKeychainMemory({
instanceId: keychainInstanceId2,
keychainId: keychainId2,
logLevel,
});
t.ok(keychain2, "keychain2 truthy OK");
keychain2.set(
HelloWorldContractJson.contractName,
JSON.stringify(HelloWorldContractJson),
);
pluginRegistry2.add(keychain2);
const keychainInstanceId3 = "keychain_instance3_" + uuidv4();
const keychainId3 = "keychain3_" + uuidv4();
const keychain3 = new PluginKeychainMemory({
instanceId: keychainInstanceId3,
keychainId: keychainId3,
logLevel,
});
t.ok(keychain3, "keychain3 truthy OK");
keychain3.set(
HelloWorldContractJson.contractName,
JSON.stringify(HelloWorldContractJson),
);
pluginRegistry3.add(keychain3);
const connector1 = await pluginFactoryLedgerConnector.create({
instanceId: connectorInstanceId1,
pluginRegistry: pluginRegistry1,
rpcApiHttpHost: rpcApiHttpHostMember1,
rpcApiWsHost: rpcApiWsHostMember1,
logLevel,
});
t.ok(connector1, "connector1 truthy OK");
test.onFinish(() => connector1.shutdown());
pluginRegistry1.add(connector1);
const connector2 = await pluginFactoryLedgerConnector.create({
instanceId: connectorInstanceId2,
pluginRegistry: pluginRegistry2,
rpcApiHttpHost: rpcApiHttpHostMember2,
rpcApiWsHost: rpcApiWsHostMember2,
logLevel,
});
t.ok(connector2, "connector2 truthy OK");
test.onFinish(() => connector2.shutdown());
pluginRegistry2.add(connector2);
const connector3 = await pluginFactoryLedgerConnector.create({
instanceId: connectorInstanceId3,
pluginRegistry: pluginRegistry3,
rpcApiHttpHost: rpcApiHttpHostMember3,
rpcApiWsHost: rpcApiWsHostMember3,
logLevel,
});
t.ok(connector3, "connector3 truthy OK");
test.onFinish(() => connector3.shutdown());
pluginRegistry3.add(connector3);
await connector1.onPluginInit();
await connector2.onPluginInit();
await connector3.onPluginInit();
const chainIdMember1 = await web3Member1.eth.getChainId();
t.comment(`chainIdMember1=${chainIdMember1}`);
const chainIdMember2 = await web3Member2.eth.getChainId();
t.comment(`chainIdMember2=${chainIdMember2}`);
const chainIdMember3 = await web3Member3.eth.getChainId();
t.comment(`chainIdMember3=${chainIdMember3}`);
const web3QuorumMember1 = Web3JsQuorum(web3Member1);
t.ok(web3QuorumMember1, "web3QuorumMember1 truthy OK");
const web3QuorumMember2 = Web3JsQuorum(web3Member2);
t.ok(web3QuorumMember2, "web3QuorumMember2 truthy OK");
const web3QuorumMember3 = Web3JsQuorum(web3Member3);
t.ok(web3QuorumMember3, "web3QuorumMember3 truthy OK");
const deployRes = await connector1.deployContract({
bytecode: HelloWorldContractJson.bytecode,
contractAbi: HelloWorldContractJson.abi,
contractName: HelloWorldContractJson.contractName,
constructorArgs: [],
privateTransactionConfig: {
privateFrom: keys.tessera.member1.publicKey,
privateFor: [
keys.tessera.member1.publicKey,
keys.tessera.member2.publicKey,
],
},
web3SigningCredential: {
secret: keys.besu.member1.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
keychainId: keychain1.getKeychainId(),
gas: 3000000,
});
t.ok(deployRes, "deployRes truthy OK");
t.ok(deployRes.transactionReceipt, "deployRes.transactionReceipt truthy OK");
t.ok(
deployRes.transactionReceipt.contractAddress,
"deployRes.transactionReceipt.contractAddress truthy OK",
);
t.ok(
deployRes.transactionReceipt.commitmentHash,
"deployRes.transactionReceipt.commitmentHash truthy OK",
);
// t.ok(deployRes.status, "deployRes.status truthy OK");
// t.equal(deployRes.status, 200, "deployRes.status === 200 OK");
// t.ok(deployRes.data, "deployRes.data truthy OK");
// t.ok(
// deployRes.data.transactionReceipt,
// "deployRes.data.transactionReceipt truthy OK",
// );
// t.ok(privacyMarkerTxHash, "privacyMarkerTxHash truthy OK");
const contractDeployReceipt = (await web3QuorumMember1.priv.waitForTransactionReceipt(
deployRes.transactionReceipt.commitmentHash,
)) as IPrivateTransactionReceipt;
t.ok(contractDeployReceipt, "contractDeployReceipt truthy OK");
const receipt = contractDeployReceipt as IPrivateTransactionReceipt;
const { contractAddress } = receipt;
t.comment(`Private contract address: ${contractAddress}`);
t.ok(contractAddress, "contractAddress truthy OK");
// Check that the third node does not see the transaction of the contract
// deployment that was sent to node 1 and 2 only, not 3.
const txReceiptNever = await web3QuorumMember3.priv.waitForTransactionReceipt(
deployRes.transactionReceipt.commitmentHash,
);
t.notok(txReceiptNever, "txReceiptNever falsy OK");
// Check that node 1 and 2 can indeed see the transaction for the contract
// deployment that was sent to them and them only (node 3 was left out)
// Note that changing this to use web3QuorumMember3 breaks it and I'm suspecting
// that this is what's plaguing the tests that are based on the connector
// which is instantiated with a single web3+web3 Quorum client.
// What I will try next is to have 3 connectors each with a web3 Quorum client
// that points to one of the 3 nodes and see if that makes it work.
const txReceiptAlways1 = await web3QuorumMember1.priv.waitForTransactionReceipt(
deployRes.transactionReceipt.commitmentHash,
);
t.ok(txReceiptAlways1, "txReceiptAlways1 truthy OK");
const txReceiptAlways2 = await web3QuorumMember2.priv.waitForTransactionReceipt(
deployRes.transactionReceipt.commitmentHash,
);
t.ok(txReceiptAlways2, "txReceiptAlways2 truthy OK");
const contract = new web3Member1.eth.Contract(
HelloWorldContractJson.abi as never,
);
{
t.comment("Checking if member1 can call setName()");
const data = contract.methods.setName("ProfessorCactus - #1").encodeABI();
const functionParams = {
to: contractDeployReceipt.contractAddress,
data,
privateFrom: keys.tessera.member1.publicKey,
privateFor: [keys.tessera.member2.publicKey],
privateKey: keys.besu.member1.privateKey,
};
const transactionHash = await web3QuorumMember1.priv.generateAndSendRawTransaction(
functionParams,
);
t.comment(`Transaction hash: ${transactionHash}`);
t.ok(transactionHash, "transactionHash truthy OK");
const result = await web3QuorumMember1.priv.waitForTransactionReceipt(
transactionHash,
);
t.comment(`Transaction receipt for set() call: ${JSON.stringify(result)}`);
t.ok(result, "set() result member 1 truthy OK");
}
{
t.comment("Checking if member1 can see new name via getName()");
const data = contract.methods.getName().encodeABI();
const fnParams = {
to: contractDeployReceipt.contractAddress,
data,
privateFrom: keys.tessera.member1.publicKey,
privateFor: [keys.tessera.member2.publicKey],
privateKey: keys.besu.member1.privateKey,
};
const privacyGroupId = web3QuorumMember1.utils.generatePrivacyGroup(
fnParams,
);
const callOutput = await web3QuorumMember1.priv.call(privacyGroupId, {
to: contractDeployReceipt.contractAddress,
data: contract.methods.getName().encodeABI(),
});
t.comment(`getName Call output: ${JSON.stringify(callOutput)}`);
t.ok(callOutput, "callOutput truthy OK");
const name = web3QuorumMember1.eth.abi.decodeParameter(
"string",
callOutput,
);
t.equal(name, "ProfessorCactus - #1", "getName() member 1 equals #1");
}
{
// Member 3 cannot see into the privacy group of 1 and 2 so the getName
// will not return the value that was set earlier in that privacy group.
t.comment("Checking if member3 can see new name via getName()");
const data = contract.methods.getName().encodeABI();
const fnParams = {
to: contractDeployReceipt.contractAddress,
data,
privateFrom: keys.tessera.member1.publicKey,
privateFor: [keys.tessera.member2.publicKey],
privateKey: keys.besu.member3.privateKey,
};
const privacyGroupId = web3QuorumMember3.utils.generatePrivacyGroup(
fnParams,
);
const callOutput = await web3QuorumMember3.priv.call(privacyGroupId, {
to: contractDeployReceipt.contractAddress,
data,
});
t.comment(`getName member3 output: ${JSON.stringify(callOutput)}`);
t.equal(callOutput, "0x", "member3 getName callOutput === 0x OK");
}
{
const data = contract.methods.setName("ProfessorCactus - #2").encodeABI();
t.comment("Checking if member2 can call setName()");
const functionParams = {
to: contractDeployReceipt.contractAddress,
data,
privateFrom: keys.tessera.member2.publicKey,
privateFor: [keys.tessera.member2.publicKey],
privateKey: keys.besu.member2.privateKey,
};
const transactionHash = await web3QuorumMember2.priv.generateAndSendRawTransaction(
functionParams,
);
t.comment(`Transaction hash: ${transactionHash}`);
t.ok(transactionHash, "transactionHash truthy OK");
const result = await web3QuorumMember2.priv.waitForTransactionReceipt(
transactionHash,
);
t.comment(`Transaction receipt for set() call: ${JSON.stringify(result)}`);
t.ok(result, "set() result member 2 truthy OK");
}
{
const data = contract.methods.setName("ProfessorCactus - #3").encodeABI();
t.comment("Checking if member3 can call setName()");
const functionParams = {
to: contractDeployReceipt.contractAddress,
data,
privateFrom: keys.tessera.member3.publicKey,
privateKey: keys.besu.member3.privateKey,
privateFor: [keys.tessera.member2.publicKey],
};
const transactionHash = await web3QuorumMember3.priv.generateAndSendRawTransaction(
functionParams,
);
t.comment(`setName tx hash for member 3: ${transactionHash}`);
t.ok(transactionHash, "setName tx hash for member 3 truthy OK");
const result = await web3QuorumMember3.priv.waitForTransactionReceipt(
transactionHash,
);
t.comment(`Transaction receipt for set() call: ${JSON.stringify(result)}`);
t.ok(result, "set() result for member 3 truthy OK");
}
{
t.comment("Checking that private contract cannot be called anonymously");
const contractInvocationNoPrivTxConfig = connector1.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress: contractDeployReceipt.contractAddress,
invocationType: EthContractInvocationType.Call,
gas: 3000000,
methodName: "getName",
params: [],
signingCredential: {
secret: "incorrect-secret",
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
await t.rejects(
contractInvocationNoPrivTxConfig,
/Returned values aren't valid, did it run Out of Gas\? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced\./,
"private contract call fails without Besu member credentials OK",
);
}
{
t.comment("Ensuring member1 can call setName() via connector");
const res = await connector1.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress: contractDeployReceipt.contractAddress,
invocationType: EthContractInvocationType.Send,
gas: 3000000,
methodName: "setName",
params: ["Doctor Cactus"],
privateTransactionConfig: {
privateFrom: keys.tessera.member1.publicKey,
privateFor: [keys.tessera.member2.publicKey],
},
signingCredential: {
secret: keys.besu.member1.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
t.equal(res.success, "0x1", "member1 setName callOutput === 0x1 OK");
}
{
t.comment(
"Ensuring member1 can call getName() and receive correct value after setName call",
);
const res = await connector1.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress: contractDeployReceipt.contractAddress,
invocationType: EthContractInvocationType.Call,
gas: 3000000,
methodName: "getName",
params: [],
privateTransactionConfig: {
privateFrom: keys.tessera.member1.publicKey,
privateFor: [keys.tessera.member2.publicKey],
},
signingCredential: {
secret: keys.besu.member1.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
t.equals(
res.callOutput,
doctorCactusHex,
"member1 getName callOutput === DoctorCactus",
);
}
{
t.comment(
"Ensuring member2 can call getName() and receive correct value after setName call",
);
const res = await connector2.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress: contractDeployReceipt.contractAddress,
invocationType: EthContractInvocationType.Call,
gas: 3000000,
methodName: "getName",
params: [],
privateTransactionConfig: {
privateFrom: keys.tessera.member1.publicKey,
privateFor: [keys.tessera.member2.publicKey],
},
signingCredential: {
secret: keys.besu.member1.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
t.equals(
res.callOutput,
doctorCactusHex,
"member2 getName callOutput === DoctorCactus",
);
}
{
t.comment("Checking if member3 can call getName() via connector");
const res = await connector3.invokeContract({
contractName: HelloWorldContractJson.contractName,
contractAbi: HelloWorldContractJson.abi,
contractAddress: contractDeployReceipt.contractAddress,
invocationType: EthContractInvocationType.Call,
gas: 3000000,
methodName: "getName",
params: [],
privateTransactionConfig: {
privateFrom: keys.tessera.member1.publicKey,
privateFor: [keys.tessera.member2.publicKey],
},
signingCredential: {
secret: keys.besu.member3.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
t.equal(res.callOutput, "0x", "member3 getName callOutput === 0x OK");
}
t.end();
}); | the_stack |
import { Ticker24 } from "./core/Ticker24";
import { Ease24 } from "./Ease24";
import { Tween24Event } from "./core/Tween24Event";
import { Updater } from "./core/updaters/Updater";
import { ObjectUpdater } from "./core/updaters/ObjectUpdater";
import { TransformUpdater } from "./core/updaters/TransformUpdater";
import { FunctionExecuter } from "./core/FunctionExecuter";
import { StyleUpdater } from "./core/updaters/StyleUpdater";
import { MultiUpdater } from "./core/updaters/MultiUpdater";
import { ArrayUtil } from "./utils/ArrayUtil";
import { ClassUtil } from "./utils/ClassUtil";
import { HTMLUtil } from "./utils/HTMLUtil";
import { StringUtil } from "./utils/StringUtil";
import { Sort24 } from "./index";
import { Text24 } from "./utils/Text24";
import { Event24 } from "./Event24";
export class Tween24 {
// Static
static readonly VERSION:string = "0.9.11";
private static readonly _TYPE_TWEEN :string = "tween";
private static readonly _TYPE_TWEEN_VELOCITY :string = "tween_velocity";
private static readonly _TYPE_TWEEN_TEXT :string = "tween_text";
private static readonly _TYPE_TWEEN_TEXT_VELOCITY:string = "tween_text_velocity";
private static readonly _TYPE_PROP :string = "prop";
private static readonly _TYPE_PROP_TEXT :string = "prop_text";
private static readonly _TYPE_WAIT :string = "wait";
private static readonly _TYPE_WAIT_EVENT :string = "wait_event";
private static readonly _TYPE_WAIT_EVENT_AND_FUNC:string = "wait_event_and_func";
private static readonly _TYPE_SERIAL :string = "serial";
private static readonly _TYPE_PARALLEL :string = "parallel";
private static readonly _TYPE_LAG :string = "lag";
private static readonly _TYPE_LOOP :string = "loop";
private static readonly _TYPE_FUNC :string = "func";
private static readonly _TYPE_IF_CASE :string = "if_case";
private static readonly _TYPE_IF_CASE_BY_FUNC :string = "if_case_by_func";
static ticker:Ticker24;
static ease :Ease24;
private static _playingTweens :Tween24[];
private static _manualPlayingTweens :Tween24[];
private static _playingTweensByTarget:Map<any, Tween24[]>;
private static _tweensById :Map<string, Tween24>;
private static _tweensByGroupId:Map<string, Tween24[]>;
private static _defaultEasing :Function = Ease24._Linear;
private static _debugMode :boolean = false;
private static _numCreateTween :number = 0;
// Tween param
private _singleTarget:any |null = null;
private _multiTarget :any[] |null = null;
private _easing :Function |null = null;
private _type :string = "";
private _time :number = NaN;
private _velocity :number = NaN;
private _delayTime:number = NaN;
private _startTime:number = NaN;
private _progress :number = 0;
private _debugMode :boolean = false;
private _numLayers :number = 0;
private _serialNumber :number = 0;
private _tweenId :string = "";
private _tweenGroupId :string = "";
private _targetString :string = "";
private _targetQuery :string|null = null;
private _useWillChange:boolean = false;
// Updater
private _objectUpdater :ObjectUpdater |null = null;
private _objectMultiUpdater :MultiUpdater |null = null;
private _transformUpdater :TransformUpdater|null = null;
private _transformMultiUpdater:MultiUpdater |null = null;
private _styleUpdater :StyleUpdater |null = null;
private _styleMultiUpdater :MultiUpdater |null = null;
private _allUpdaters :Updater[] |null = null;
// Refer
private _root :Tween24|null = null;
private _parent:Tween24|null = null;
private _next :Tween24|null = null;
// Status
private _isDOM :boolean = false;
private _isRoot :boolean = false;
private _isManual :boolean = false;
private _isTrigger:boolean = false;
private _inited :boolean = false;
private _played :boolean = false;
private _paused :boolean = false;
private _skiped :boolean = false;
private _eventWaiting :boolean = false;
private _firstUpdated :boolean = false;
private _isContainerTween :boolean = false;
private _createdBasicUpdater:boolean = false;
// Action & Callback
private _functionExecuters:{[key:string]:FunctionExecuter}|null = null;
// Container Tween
private _firstTween :Tween24 |null = null;
private _childTween :Tween24[]|null = null;
private _playingChildTween :Tween24[]|null = null;
private _originalChildTween:Tween24[]|null = null;
private _numChildren :number = 0;
private _numCompleteChildren:number = 0;
// Lag
private _lagTime :number = NaN;
private _totalLagTime:number = NaN;
private _lagSort :Function|null = null;
private _lagEasing :Function|null = null;
// Loop
private _numLoops :number = NaN;
private _currentLoops:number = NaN;
// If Case
private _ifFunc :Function|null = null;
private _trueTween :Tween24 |null = null;
private _falseTween:Tween24 |null = null;
// Dispatch event
private _dispatchEventTarget:any;
private _dispatchEventType :string|null = null;
// Trigger & Jump
private _triggered :boolean = false;
private _jumped :boolean = false;
private _jumpProg :number = NaN;
// Tween FPS
__fps:number = 0;
__beforeTime:number = 0;
constructor() {
Tween24.ease ||= new Ease24();
Tween24.ticker ||= new Ticker24();
Tween24._playingTweens ||= [];
Tween24._playingTweensByTarget ||= new Map<any, Tween24[]>();
}
// ------------------------------------------
//
// Tween control
//
// ------------------------------------------
/**
* トゥイーンを再生します。
* @memberof Tween24
*/
play = () => {
this._commonRootPlay();
}
/**
* トゥイーンを手動アップデート式で再生します。
* 関数 manualUpdate() を実行すると更新されます。
* @memberof Tween24
*/
manualPlay = () => {
Tween24._manualPlayingTweens ||= [];
this._isManual = true;
this._commonRootPlay();
}
private _commonRootPlay() {
if (!this._paused) {
if (!this._played) {
this._root = this;
this._isRoot = true;
this._inited = false;
this._firstUpdated = false;
this._play();
if (!this._isManual) Tween24.ticker.add(this);
else Tween24._manualPlayingTweens.push(this);
this._functionExecute(Tween24Event.PLAY);
}
}
else {
this._resume();
this._paused = false;
if (!this._isManual) Tween24.ticker.add(this);
else Tween24._manualPlayingTweens.push(this);
this._functionExecute(Tween24Event.RESUME);
}
}
private _play() {
if (this._isRoot) {
this._numLayers = 0;
}
else {
this._root = this._parent?._root || this._parent;
this._numLayers = this._parent ? this._parent._numLayers + 1 : 1;
}
this._played = true;
this._startTime = Ticker24.getTime() + this._delayTime * 1000;
// Velocity
if (this._type == Tween24._TYPE_TWEEN_VELOCITY || this._type == Tween24._TYPE_TWEEN_TEXT_VELOCITY) {
const deltas:number[] = [0];
if (this._allUpdaters?.length) {
for (const updater of this._allUpdaters) {
updater.init(false);
deltas.push(updater.getMaxAbsDelta());
}
}
this._time = Math.max(...deltas) / this._velocity;
}
Tween24._playingTweens.push(this);
// Skip
if (this._root?._skiped || this._parent?._skiped) this._skip();
this._debugLog("play");
}
private _resume() {
this._played = true;
const nowTime:number = Ticker24.getTime();
this._startTime = nowTime - this._time * 1000 * this._progress;
if (this._playingChildTween) {
for (const tween of this._playingChildTween) {
if (tween._playingChildTween) tween._resume();
else tween._startTime = nowTime - tween._time * 1000 * tween._progress;
}
}
Tween24._playingTweens.push(this);
}
/**
* トゥイーンを一時停止します。
* @memberof Tween24
*/
pause = () => {
if (this._isRoot) {
this._played = false;
this._paused = true;
if (this._isManual) ArrayUtil.removeItemFromArray(Tween24._manualPlayingTweens, this);
else Tween24.ticker.remove(this);
ArrayUtil.removeItemFromArray(Tween24._playingTweens, this);
this._functionExecute(Tween24Event.PAUSE);
}
}
/**
* トゥイーンを終点までスキップします。
* @memberof Tween24
*/
skip = () => {
this._skip();
}
private _skip() {
this._skiped = true;
if (this._playingChildTween) {
for (const tween of this._playingChildTween.concat()) {
tween._skip();
}
}
this.__update(0);
}
/**
* トゥイーンを停止します。
* @memberof Tween24
*/
stop = () => {
this._stop();
this._functionExecute(Tween24Event.STOP);
}
private _stop() {
this._tweenStop();
if (this._childTween) {
for (const tween of this._childTween) {
if (tween._childTween) tween._stop();
else tween._tweenStop();
}
}
}
// ------------------------------------------
//
// Tween work
//
// ------------------------------------------
private _initParam() {
// Pseudo element setting
if (this._isDOM && this._targetQuery && HTMLUtil.isPseudoQuery(this._targetQuery))
HTMLUtil.setTweenElementQuery(this._singleTarget || this._multiTarget, this._targetQuery);
// Updater init
if (this._allUpdaters?.length) {
for (const updater of this._allUpdaters) {
updater.init(this._root?._useWillChange || this._parent?._useWillChange || this._useWillChange);
}
}
// Overwrite
if (this._singleTarget)
this._overwrite(this._singleTarget);
else if (this._multiTarget) {
for (const target of this._multiTarget) {
this._overwrite(target);
}
}
}
private _overwrite(target:any) {
let tweens:Tween24[]|undefined = Tween24._playingTweensByTarget.get(target);
if (tweens) {
for (const tween of tweens) {
if (this !== tween) {
if (this._singleTarget) {
if (this._objectUpdater ) (tween._objectMultiUpdater ||tween._objectUpdater )?.overwrite(this._objectUpdater);
if (this._transformUpdater) (tween._transformMultiUpdater||tween._transformUpdater)?.overwrite(this._transformUpdater);
if (this._styleUpdater ) (tween._styleMultiUpdater ||tween._styleUpdater )?.overwrite(this._styleUpdater);
}
else if (this._multiTarget) {
if (tween._objectMultiUpdater ) this._objectMultiUpdater ?.overwriteMultiTo(tween._objectMultiUpdater);
else if (tween._objectUpdater ) this._objectMultiUpdater ?.overwriteTo (tween._objectUpdater);
if (tween._transformMultiUpdater) this._transformMultiUpdater?.overwriteMultiTo(tween._transformMultiUpdater);
else if (tween._transformUpdater ) this._transformMultiUpdater?.overwriteTo (tween._transformUpdater);
if (tween._styleMultiUpdater ) this._styleMultiUpdater ?.overwriteMultiTo(tween._styleMultiUpdater);
else if (tween._styleUpdater ) this._styleMultiUpdater ?.overwriteTo (tween._styleUpdater);
}
}
}
tweens.push(this);
}
else {
Tween24._playingTweensByTarget.set(target, [this]);
}
}
private _setIfCaseTween(flag:boolean) {
if (this._childTween) this._childTween.length = 0;
else this._childTween = [];
if (flag && this._trueTween)
this._childTween = [this._trueTween];
else if (this._falseTween)
this._childTween = [this._falseTween];
else
this._childTween = [];
this._numChildren = this._childTween.length;
}
manualUpdate = () => {
this.__update(Ticker24.getTime());
}
public __update(nowTime:number) {
this._updateProgress(this._time, this._startTime, nowTime);
// Delay
if (this._progress < 0) return;
// Init
if (!this._inited) {
this._inited = true;
this._initParam();
this._functionExecute(Tween24Event.INIT);
}
// Container Tween
if (this._isContainerTween) {
if (this._firstUpdated == false) {
this._firstUpdated = true;
// If case
if (this._type == Tween24._TYPE_IF_CASE_BY_FUNC) {
this._setIfCaseTween(this._ifFunc ? Boolean(this._ifFunc()) : false);
}
switch (this._type) {
case Tween24._TYPE_SERIAL:
if (this._firstTween) {
this._playingChildTween?.push(this._firstTween);
this._firstTween._play();
}
break;
case Tween24._TYPE_PARALLEL:
case Tween24._TYPE_LAG :
case Tween24._TYPE_LOOP :
case Tween24._TYPE_IF_CASE :
case Tween24._TYPE_IF_CASE_BY_FUNC :
if (this._childTween) {
for (const tween of this._childTween) {
this._playingChildTween?.push(tween);
tween._play();
}
}
break;
}
}
// Update
if (this._playingChildTween) {
for (const tween of this._playingChildTween) {
tween.__update(nowTime);
}
}
this._functionExecute(Tween24Event.UPDATE);
if (this._numChildren == this._numCompleteChildren) this._complete();
}
// Child Tween
else {
this._firstUpdated = true;
if (this._singleTarget || this._multiTarget) {
// Update propety
var prog = this._easing ? this._easing(this._progress, 0, 1, 1) : this._progress;
if (this._allUpdaters?.length) {
for (const updater of this._allUpdaters) {
updater.update(prog);
}
}
this._functionExecute(Tween24Event.UPDATE);
}
else {
this._functionExecute(Tween24Event.UPDATE);
}
// Jump
if (!Number.isNaN(this._jumpProg) && !this._jumped && this._progress >= this._jumpProg) {
this._jumped = true;
this._parent?._playNextTween(this);
}
// Complete
if (this._progress >= 1) {
// Wait event
if ((this._type == Tween24._TYPE_WAIT_EVENT || this._type == Tween24._TYPE_WAIT_EVENT_AND_FUNC) && this._dispatchEventTarget && this._dispatchEventType) {
if (this._eventWaiting == false) {
this._eventWaiting = true;
const waitHandler = () => {
this._eventWaiting = false;
if (this._dispatchEventType) Event24.remove(this._dispatchEventTarget, this._dispatchEventType);
// End
this._complete();
}
Event24.__addCallback(this._dispatchEventTarget, this._dispatchEventType, waitHandler);
if (this._type == Tween24._TYPE_WAIT_EVENT_AND_FUNC)
this._functionExecute(Tween24._TYPE_WAIT_EVENT_AND_FUNC);
}
}
else {
// Func
if (this._type == Tween24._TYPE_FUNC) {
this._functionExecute(Tween24._TYPE_FUNC);
}
// End
this._complete();
}
}
}
}
private _complete() {
this._debugLog("complete");
if (this._type == Tween24._TYPE_LOOP) {
this._currentLoops ++;
if (this._numLoops == 0 || this._numLoops > this._currentLoops) {
this._numCompleteChildren = 0;
this._play();
return;
}
}
if (this._parent) this._parent._completeChildTween(this);
this._functionExecute(Tween24Event.COMPLATE);
this._tweenStop();
}
private _tweenStop() {
if (this._isRoot) Tween24.ticker.remove(this);
if (this._playingChildTween) this._playingChildTween.length = 0;
this._numCompleteChildren = 0;
this._played = false;
this._inited = false;
this._jumped = false;
this._skiped = false;
this._triggered = false;
this._firstUpdated = false;
ArrayUtil.removeItemFromArray(Tween24._playingTweensByTarget.get(this._singleTarget), this);
ArrayUtil.removeItemFromArray(Tween24._playingTweens, this);
if (this._isManual) ArrayUtil.removeItemFromArray(Tween24._manualPlayingTweens, this);
}
private _completeChildTween(tween:Tween24) {
// this._debugLog("completeChildTween");
this._numCompleteChildren ++;
if (!this._triggered && tween._isTrigger) {
if (this._parent) {
this._triggered = true;
this._parent._playNextTween(this);
}
}
if (this._numChildren == this._numCompleteChildren) {
this._complete();
}
else if (this._playingChildTween) {
ArrayUtil.removeItemFromArray(this._playingChildTween, tween);
if (!tween._triggered && !tween._jumped) {
this._playNextTween(tween);
}
}
}
private _playNextTween(childTween:Tween24) {
var next:Tween24|null = childTween._next;
if (this._playingChildTween && next) {
this._playingChildTween.push(next);
next._play();
}
}
private _updateProgress(time:number, startTime:number, nowTime:number): number {
if (this._skiped) this._progress = 1;
else if (nowTime < startTime) this._progress = -1;
else if (time == 0) this._progress = 1;
else {
this._progress = (nowTime - startTime) / (time * 1000);
this._progress = (this._progress > 1) ? 1 : this._progress;
}
return this._progress;
}
// ------------------------------------------
//
// Tween Propety
//
// ------------------------------------------
/**
* 目標とするX座標を設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* また、パーセント値で指定された場合は、囲みボックスの寸法に対する相対値が設定されます。
* @param {number|string} value X座標
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
x (value:number|string): Tween24 { return ClassUtil.isNumber(value) ? this._setPropety("x", parseFloat(value as string)) : this._setPropetyStr("x", value as string); }
/**
* 目標とするY座標を設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* また、パーセント値で指定された場合は、囲みボックスの寸法に対する相対値が設定されます。
* @param {number|string} value Y座標
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
y (value:number|string): Tween24 { return ClassUtil.isNumber(value) ? this._setPropety("y", parseFloat(value as string)) : this._setPropetyStr("y", value as string); }
/**
* 目標とするXとY座標を設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* また、パーセント値で指定された場合は、囲みボックスの寸法に対する相対値が設定されます。
* @param {number|string} x X座標
* @param {number|string} y Y座標
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
xy (x:number|string, y:number|string): Tween24 { return this.x(x).y(y); }
/**
* 目標とする透明度を設定します。
* 対象が HTMLElement の場合は、CSS:opacity が適用されます。
* @param {number} value 透明度
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
alpha (value:number): Tween24 { return this._isDOM ? this._setStyle("opacity", value) : this._setPropety("alpha", value); }
/**
* 目標とする透明度を設定します。
* @param {number} value 透明度
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
opacity (value:number): Tween24 { return this._isDOM ? this._setStyle("opacity", value) : this._setPropety("opacity", value); }
/**
* 目標とする水平スケールを設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* @param {number} value 水平方向のスケール
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
scaleX (value:number): Tween24 { return this._setPropety("scaleX", value); }
/**
* 目標とする垂直スケールを設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* @param {number} value 垂直方向のスケール
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
scaleY (value:number): Tween24 { return this._setPropety("scaleY", value); }
/**
* 目標とするスケールを設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* @param {number} value 水平&垂直方向のスケール
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
scale (value:number): Tween24 { return this._setPropety("scaleX", value)._setPropety("scaleY", value); }
/**
* 目標とする水平・垂直スケールを設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* @param {number} scaleX 水平方向のスケール
* @param {number} scaleY 垂直方向のスケール
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
scaleXY (scaleX:number, scaleY:number): Tween24 { return this._setPropety("scaleX", scaleX)._setPropety("scaleY", scaleY); }
/**
* 目標とする水平傾斜を設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* @param {number} value 水平方向の傾斜
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
skewX (value:number): Tween24 { return this._setPropety("skewX", value); }
/**
* 目標とする垂直傾斜を設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* @param {number} value 垂直方向の傾斜
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
skewY (value:number): Tween24 { return this._setPropety("skewY", value); }
/**
* 目標とする水平&垂直傾斜を設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* @param {number} value 水平&垂直方向の傾斜
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
skew (value:number): Tween24 { return this._setPropety("skewX", value)._setPropety("skewY", value); }
/**
* 目標とする水平・垂直傾斜を設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* @param {number} skewX 水平方向の傾斜
* @param {number} skewY 垂直方向の傾斜
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
skewXY (skewX:number, skewY:number): Tween24 { return this._setPropety("skewX", skewX)._setPropety("skewY", skewY); }
/**
* 目標とする回転角度を設定します。
* 対象が HTMLElement の場合は、CSS:Transform が適用されます。
* @param {number} value 回転角度
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
rotation (value:number): Tween24 { return this._setPropety("rotation", value); }
/**
* 目標とする角度を設定します。
* @param {number} value 角度
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
angle (value:number): Tween24 { return this._isDOM ? this._setStyle("rotation", value) : this._setPropety("angle", value); }
/**
* CSS:top を設定します。
* @param {number|string} 上からの配置位置(距離)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
top (value:number|string): Tween24 { return this._setStyle("top", StringUtil.addUnit(value)); }
/**
* CSS:right を設定します。
* @param {number|string} 右からの配置位置(距離)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
right (value:number|string): Tween24 { return this._setStyle("right", StringUtil.addUnit(value)); }
/**
* CSS:bottom を設定します。
* @param {number|string} value 下からの配置位置(距離)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
bottom (value:number|string): Tween24 { return this._setStyle("bottom", StringUtil.addUnit(value)); }
/**
* CSS:left を設定します。
* @param {number|string} value 左からの配置位置(距離)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
left (value:number|string): Tween24 { return this._setStyle("left", StringUtil.addUnit(value)); }
/**
* 目標とする幅を設定します。
* 対象が HTMLElement の場合は、CSS:width が適用されます。
* @param {number|string} value 要素の幅
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
width (value:number|string): Tween24 { return this._isDOM ? this._setStyle("width", StringUtil.addUnit(value)) : this._setPropety("width", parseInt(value as string)); }
/**
* 目標とする高さを設定します。
* 対象が HTMLElement の場合は、CSS:height が適用されます。
* @param {number|string} value 要素の高さ
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
height (value:number|string): Tween24 { return this._isDOM ? this._setStyle("height", StringUtil.addUnit(value)) : this._setPropety("height", parseInt(value as string)); }
/**
* CSS:color を設定します。
* @param {string} colorCode 「#」「rgb()」フォーマットのカラー値
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
color (colorCode:string): Tween24 { return this._setStyle("color", colorCode); }
/**
* CSS:background-color(背景色)を設定します。
* @param {string} colorCode 「#」「rgb()」フォーマットのカラー値
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
backgroundColor (colorCode:string): Tween24 { return this._setStyle("background-color", colorCode); }
/**
* CSS:border-width(枠の太さ)を設定します。
* @param {number|string} value 枠の太さ
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
borderWidth (value:number|string): Tween24 { return this._setStyle("border-width", StringUtil.addUnit(value)); }
/**
* CSS:border-color(枠の色)を設定します。
* @param {number} colorCode 「#」「rgb()」フォーマットのカラー値
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
borderColor (colorCode:string): Tween24 { return this._setStyle("border-color", colorCode); }
/**
* CSS:border-radius(角丸)を設定します。
* @param {number|string} value 角丸の値
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
borderRadius (value:number|string): Tween24 { return this._setStyle("border-radius", StringUtil.addUnit(value)); }
/**
* CSS:letter-spacing(字間)を設定します。
* @param {number|string} value 字間
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
letterSpacing (value:number|string): Tween24 { return this._setStyle("letter-spacing", StringUtil.addUnit(value)); }
/**
* トゥイーンの遅延時間を設定します。
* @param {number} value 遅延時間(秒数)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
delay (value:number): Tween24 { this._delayTime += value; return this; }
/**
* 目標とするスタイルシートの値を設定します。
* 対象が HTMLElement の場合にのみ適用されます。
* @param {string} name プロパティ名
* @param {(number|string)} value 目標の値(数値指定の場合は、基本的にpx単位で計算されます)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
style (name:string, value: number|string): Tween24 { return this._setStyle(name, value); }
/**
* トゥイーン実行時に willChange を有効にするか設定します。
* 有効にすると強力な最適化をブラウザーが行い、アニメーションが滑らかになります。
* 対象が HTMLElement の場合にのみ適用されます。
* @param {boolean} [use=true]
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
willChange(use:boolean = true): Tween24 { this._useWillChange = use; return this; }
/**
* 子トゥイーンの完了トリガーに設定します。
* 設定したトゥイーンが完了したら、親トゥイーンが次のトゥイーンへ移行します。
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
trigger():Tween24 { this._isTrigger = true; return this; }
/**
* トゥイーンの途中で、次のトゥイーンへ移行します。
* @param {number} progress 移行させる進捗率
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
jump(progress:number):Tween24 { this._jumpProg = progress; return this; }
/**
* トゥイーン毎のFPS(1秒間の更新回数)を設定します。
* デフォルトでは0が設定され、ブラウザのリフレッシュレートに合わせて描画更新されます。
* (※ 子以下のトゥイーンには設定できません。)
* @param {number} fps FPSの値
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
fps (fps:number): Tween24 { this.__fps = fps; return this; }
/**
* トゥイーンのデバッグモードを設定します。
* デバッグモードをONにすると、トゥイーンの動作状況がコンソールに表示されます。
* @param {boolean} flag デバッグモードを使用するか
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
debug (flag:boolean = true): Tween24 { this._debugMode = flag; return this; }
private _setPropety(key:string, value:number):Tween24 {
this.createBasicUpdater();
if (this._singleTarget) {
if (this._objectUpdater ) this._objectUpdater .addProp(key, value);
else if (this._transformUpdater) this._transformUpdater.addProp(key, value);
}
else if (this._multiTarget) {
if (this._objectMultiUpdater ) this._objectMultiUpdater .addProp(key, value);
else if (this._transformMultiUpdater) this._transformMultiUpdater.addProp(key, value);
}
return this;
}
private _setPropetyStr(key:string, value:string):Tween24 {
this.createBasicUpdater();
if (this._singleTarget) {
if (this._transformUpdater) this._transformUpdater.addPropStr(key, value);
}
else if (this._multiTarget) {
if (this._transformMultiUpdater) this._transformMultiUpdater.addPropStr(key, value);
}
return this;
}
private _setStyle(name: string, value: number|string):Tween24 {
name = StringUtil.toKebab(name);
if (this._singleTarget) {
if (!this._styleUpdater) {
this._styleUpdater = new StyleUpdater(this._singleTarget, this._targetQuery);
this._allUpdaters?.push(this._styleUpdater);
}
this._styleUpdater.addPropStr(name, value as string);
}
else if (this._multiTarget) {
if (!this._styleMultiUpdater) {
this._styleMultiUpdater = new MultiUpdater(this._multiTarget, this._targetQuery).setupByType(StyleUpdater.className);
this._allUpdaters?.push(this._styleMultiUpdater);
}
this._styleMultiUpdater.addPropStr(name, value as string);
}
return this;
}
private createBasicUpdater() {
if (this._createdBasicUpdater) return;
this._createdBasicUpdater = true;
let updater:Updater|null = null;
if (this._isDOM) {
if (this._singleTarget) updater = this._transformUpdater ||= new TransformUpdater(this._singleTarget, this._targetQuery);
else if (this._multiTarget ) updater = this._transformMultiUpdater ||= new MultiUpdater (this._multiTarget , this._targetQuery).setupByType(TransformUpdater.className);
}
else {
if (this._singleTarget) updater = this._objectUpdater ||= new ObjectUpdater(this._singleTarget);
else if (this._multiTarget ) updater = this._objectMultiUpdater ||= new MultiUpdater (this._multiTarget, this._targetQuery).setupByType(ObjectUpdater.className);
}
if (updater) this._allUpdaters?.push(updater);
}
// ------------------------------------------
//
// Tween Callback
//
// ------------------------------------------
/**
* トゥイーン再生時に、実行する関数を設定します。
* @param {Function} func 実行する関数
* @param {...any[]} args 引数(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
onPlay (func:Function, ...args:any[]): Tween24 { return this._setFunctionExecute(Tween24Event.PLAY, func, func, args); }
/**
* トゥイーン開始時に、実行する関数を設定します。
* @param {Function} func 実行する関数
* @param {...any[]} args 引数(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
onInit (func:Function, ...args:any[]): Tween24 { return this._setFunctionExecute(Tween24Event.INIT, func, func, args); }
/**
* トゥイーン実行中に、実行する関数を設定します。
* @param {Function} func 実行する関数
* @param {...any[]} args 引数(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
onUpdate (func:Function, ...args:any[]): Tween24 { return this._setFunctionExecute(Tween24Event.UPDATE, func, func, args); }
/**
* トゥイーンが一時停止した時に、実行する関数を設定します。
* @param {Function} func 実行する関数
* @param {...any[]} args 引数(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
onPause (func:Function, ...args:any[]): Tween24 { return this._setFunctionExecute(Tween24Event.PAUSE, func, func, args); }
/**
* トゥイーンが一時停止中から、再開した時に実行する関数を設定します。
* @param {Function} func 実行する関数
* @param {...any[]} args 引数(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
onResume (func:Function, ...args:any[]): Tween24 { return this._setFunctionExecute(Tween24Event.RESUME, func, func, args); }
/**
* トゥイーンが停止された時に、実行する関数を設定します。
* @param {Function} func 実行する関数
* @param {...any[]} args 引数(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
onStop (func:Function, ...args:any[]): Tween24 { return this._setFunctionExecute(Tween24Event.STOP, func, func, args); }
/**
* トゥイーンが完了した時に、実行する関数を設定します。
* @param {Function} func 実行する関数
* @param {...any[]} args 引数(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
onComplete (func:Function, ...args:any[]): Tween24 { return this._setFunctionExecute(Tween24Event.COMPLATE, func, func, args); }
private _setFunctionExecute(key:string, scope:any, func:Function, args:any[]|null):Tween24 {
this._functionExecuters ||= {};
this._functionExecuters[key] = new FunctionExecuter(scope, func, args);
return this;
}
private _functionExecute(key:string) {
if (this._functionExecuters) {
this._functionExecuters[key]?.execute();
}
}
// ------------------------------------------
//
// Tween create
//
// ------------------------------------------
/**
* トゥイーンを設定します。
* @static
* @param {*} target 対象オブジェクト
* @param {number} time 時間(秒)
* @param {(Function|null)} [easing=null] イージング関数(デフォルト値:Ease24._Linear)
* @param {({[key:string]:number}|null)} [params=null] トゥイーンさせるパラメータ(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static tween(target: any, time: number, easing: Function|null = null, params: { [key: string]: number } | null = null): Tween24 {
return new Tween24()._createChildTween(Tween24._TYPE_TWEEN, target, time, easing, params);
}
/**
* 速度を指定するトゥイーンを設定します。
*
* このトゥイーンは、指定された速度とパラメータの変化量から時間を自動設定します。
* 複数パラメータを変化させる場合、変化量の一番大きい値を基準にします。
* x,y の座標系パラメータは、計算後の距離を変化量とします。
* @static
* @param {*} target 対象オブジェクト
* @param {number} velocity 1秒間の変化量(速度)
* @param {(Function|null)} [easing=null] イージング関数(デフォルト値:Ease24._Linear)
* @param {({ [key: string]: number } | null)} [params=null] トゥイーンさせるパラメータ(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static tweenVelocity(target: any, velocity: number, easing: Function|null = null, params: { [key: string]: number } | null = null): Tween24 {
return new Tween24()._createChildTween(Tween24._TYPE_TWEEN_VELOCITY, target, velocity, easing, params);
}
/**
* プロパティを設定します。
* @static
* @param {*} target 対象オブジェクト
* @param {({[key:string]:number}|null)} [params=null] 設定するパラメータ(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static prop(target: any, params: { [key: string]: number } | null = null): Tween24 {
return new Tween24()._createChildTween(Tween24._TYPE_PROP, target, 0, null, params);
}
/**
* クエリで指定した要素直下のテキストを1文字ずつに分解し、それぞれにプロパティを設定します。
* @static
* @param {string} targetQuery 対象要素を指定するクエリ
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static propText(targetQuery:string): Tween24 {
return Tween24._tweenText(Tween24._TYPE_PROP_TEXT, targetQuery, 0, null);
}
/**
* クエリで指定した要素直下のテキストを1文字ずつに分解し、それぞれにトゥイーンを設定します。
* @static
* @param {string} targetQuery 対象要素を指定するクエリ
* @param {number} time 時間(秒)
* @param {(Function|null)} [easing=null] イージング関数(デフォルト値:Ease24._Linear)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static tweenText(targetQuery:string, time:number, easing:Function|null = null): Tween24 {
return Tween24._tweenText(Tween24._TYPE_TWEEN_TEXT, targetQuery, time, easing);
}
/**
* 1文字ずつに分解したテキストを、元に戻します。
* @static
* @param {string} targetQuery 対象要素を指定するクエリ
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static resetText(targetQuery:string): Tween24 {
return Tween24.func(Text24.removeByTarget, targetQuery);
}
/**
* クエリで指定した要素直下のテキストを1文字ずつに分解し、それぞれに速度を指定するトゥイーンを設定します。
*
* このトゥイーンは、指定された速度とパラメータの変化量から時間を自動設定します。
* 複数パラメータを変化させる場合、変化量の一番大きい値を基準にします。
* x,y の座標系パラメータは、計算後の距離を変化量とします。
* @static
* @param {string} targetQuery 対象要素を指定するクエリ
* @param {number} velocity 1秒間の変化量(速度)
* @param {(Function|null)} [easing=null] イージング関数(デフォルト値:Ease24._Linear)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static tweenTextVelocity(targetQuery:string, velocity:number, easing:Function|null = null): Tween24 {
return Tween24._tweenText(Tween24._TYPE_TWEEN_VELOCITY, targetQuery, velocity, easing);
}
private static _tweenText(type:string, targetQuery:string, timeOrVelocity:number, easing:Function|null = null):Tween24 {
const targets:HTMLElement[] = HTMLUtil.querySelectorAll(targetQuery);
const textElements:any[] = [];
for (const target of targets) {
const text:Text24|undefined = Text24.getInstance(target);
if (text) {
textElements.push(...text.targets);
}
else {
const text:Text24 = new Text24(target, target.textContent?.trim() || "", false, false);
textElements.push(...text.targets);
}
}
const tween:Tween24 = new Tween24()._createChildTween(type, textElements, timeOrVelocity, easing, null);
tween._targetQuery = targetQuery + " span";
return tween;
}
/**
* トゥイーンを待機します。
* @static
* @param {number} time 待機時間(秒)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static wait(time: number): Tween24 {
return new Tween24()._createChildTween(Tween24._TYPE_WAIT, null, time, null, null);
}
/**
* 関数を実行します。
* @static
* @param {Function} func 実行する関数
* @param {...any[]} args 引数(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static func(func: Function, ...args: any[]): Tween24 {
return new Tween24()._createActionTween(Tween24._TYPE_FUNC)._setFunctionExecute(Tween24._TYPE_FUNC, func, func, args);
}
/**
* イベントを受け取るまで、待機します。
* @static
* @param {*} target イベントを受け取る対象
* @param {string} type 受け取るイベントタイプ
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static waitEvent(target:any, type:string): Tween24 {
return new Tween24()._createActionTween(Tween24._TYPE_WAIT_EVENT)._setWaitEvent(target, type);
}
/**
* 指定した関数を実行し、イベントを受け取るまで待機します。
* @static
* @param {*} target イベントを受け取る対象
* @param {string} type 受け取るイベントタイプ
* @param {Function} func 実行する関数
* @param {...any[]} args 引数(省略可)
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static waitEventAndFunc(target:any, type:string, func:Function, ...args:any[]): Tween24 {
return new Tween24()._createActionTween(Tween24._TYPE_WAIT_EVENT_AND_FUNC)._setWaitEvent(target, type)._setFunctionExecute(Tween24._TYPE_WAIT_EVENT_AND_FUNC, func, func, args);
}
private _setWaitEvent(target:any, type:string):Tween24 {
this._dispatchEventTarget = target;
this._dispatchEventType = type;
return this;
}
/**
* console.log() を実行します。
* @static
* @param {...any[]} message コンソールに出力する内容
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static log(...message:any[]): Tween24 {
return new Tween24()._createActionTween(Tween24._TYPE_FUNC)._setFunctionExecute(Tween24._TYPE_FUNC, window, window.console.log, message);
}
/**
* 順番に実行するトゥイーンを設定します。
* @static
* @param {...Tween24[]} childTween 実行するトゥイーンたち
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static serial(...childTween: Tween24[]): Tween24 {
return new Tween24()._createContainerTween(Tween24._TYPE_SERIAL, childTween);
}
/**
* 並列に実行するトゥイーンを設定します。
* @static
* @param {...Tween24[]} childTween 実行するトゥイーンたち
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static parallel(...childTween: Tween24[]): Tween24 {
return new Tween24()._createContainerTween(Tween24._TYPE_PARALLEL, childTween);
}
/**
* 子トゥイーンの対象が複数指定されていた場合、時差を設定します。
* @static
* @param {number} lagTime 対象毎の時差(秒数)
* @param {...Tween24[]} childTween 実行するトゥイーンたち
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static lag(lagTime:number, ...childTween: Tween24[]): Tween24 {
return Tween24.lagSort(lagTime, Sort24._Normal, ...childTween);
}
/**
* 子トゥイーンの対象が複数指定されていた場合、再生順をソートして時差を設定します。
* @static
* @param {number} lagTime 対象毎の時差(秒数)
* @param {Function} sort 再生順をソートする関数
* @param {...Tween24[]} childTween 実行するトゥイーンたち
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static lagSort(lagTime:number, sort:Function, ...childTween: Tween24[]): Tween24 {
const tweens:Tween24[] = [];
for (const tween of childTween) {
if (tween._multiTarget) {
const targets:any[] = sort == Sort24._Normal ? tween._multiTarget : sort(tween._multiTarget);
for (let i = 0; i < targets.length; i++) {
const t = targets[i];
tweens.push(tween.__clone(t, tween._targetQuery).delay(lagTime * i));
}
}
else {
tweens.push(tween);
}
}
const tween:Tween24 = new Tween24()._createContainerTween(Tween24._TYPE_LAG, tweens);
tween._lagTime = lagTime;
tween._lagSort = sort;
tween._originalChildTween = childTween;
return tween;
}
/**
* 子トゥイーンの対象が複数指定されていた場合、トータル時間を元に時差を設定します。
* @static
* @param {number} totalLagTime 時差のトータル時間(秒数)
* @param {...Tween24[]} childTween 実行するトゥイーンたち
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static lagTotal(totalLagTime:number, ...childTween: Tween24[]): Tween24 {
return Tween24.lagTotalSortEase(totalLagTime, Sort24._Normal, Ease24._Linear, ...childTween);
}
/**
* 子トゥイーンの対象が複数指定されていた場合、トータル時間を元にイージングをかけながら時差を設定します。
* @static
* @param {number} totalLagTime 時差のトータル時間(秒数)
* @param {Function} easing 時差の時間量のイージング
* @param {...Tween24[]} childTween 実行するトゥイーンたち
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static lagTotalEase(totalLagTime:number, easing:Function, ...childTween: Tween24[]): Tween24 {
return Tween24.lagTotalSortEase(totalLagTime, Sort24._Normal, easing, ...childTween);
}
/**
* 子トゥイーンの対象が複数指定されていた場合、再生順をソートして、トータル時間を元に時差を設定します。
* @static
* @param {number} totalLagTime 時差のトータル時間(秒数)
* @param {Function} sort 再生順をソートする関数
* @param {...Tween24[]} childTween 実行するトゥイーンたち
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static lagTotalSort(totalLagTime:number, sort:Function, ...childTween: Tween24[]): Tween24 {
return Tween24.lagTotalSortEase(totalLagTime, sort, Ease24._Linear, ...childTween);
}
/**
* 子トゥイーンの対象が複数指定されていた場合、再生順をソートして、トータル時間を元にイージングをかけながら時差を設定します。
* @static
* @param {number} totalLagTime 時差のトータル時間(秒数)
* @param {Function} sort 再生順をソートする関数
* @param {Function} easing 時差の時間量のイージング
* @param {...Tween24[]} childTween 実行するトゥイーンたち
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static lagTotalSortEase(totalLagTime:number, sort:Function, easing:Function, ...childTween: Tween24[]): Tween24 {
const tweens:Tween24[] = [];
for (const tween of childTween) {
if (tween._multiTarget) {
const targets:any[] = sort == Sort24._Normal ? tween._multiTarget : sort(tween._multiTarget);
const numTarget:number = targets.length;
for (let i = 0; i < numTarget; i++) {
const delay:number = easing((i + 1) / numTarget, 0, totalLagTime, 1);
tweens.push(tween.__clone(targets[i], tween._targetQuery).delay(delay));
}
}
else {
tweens.push(tween);
}
}
const tween:Tween24 = new Tween24()._createContainerTween(Tween24._TYPE_LAG, tweens);
tween._totalLagTime = totalLagTime;
tween._lagSort = sort;
tween._lagEasing = easing;
tween._originalChildTween = childTween;
return tween;
}
/**
* 繰り返し再生させるトゥイーンを設定します。
* ループ回数に「0」を指定すると、無制限に繰り返します。
* @static
* @param {number} numLoops ループさせる回数
* @param {Tween24} tween ループさせるトゥイーン
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static loop(numLoops:number, tween:Tween24):Tween24 {
const loopTween:Tween24 = new Tween24()._createContainerTween(Tween24._TYPE_LOOP, [tween]);
loopTween._numLoops = numLoops;
loopTween._currentLoops = 0;
return loopTween;
}
/**
* フラグに応じて再生するトゥイーンを設定します。
* フラグにboolean値を渡した場合はトゥイーン作成時に判定し、boolean値を返す関数を渡した場合はトゥイーン実行毎に判定します。
* @static
* @param {boolean|(()=>boolean)} flag boolean値か、boolean値を返す関数
* @param {Tween24} trueTween フラグが true の時に再生するトゥイーン
* @param {(Tween24|null)} [falseTween=null] フラグが false の時に再生するトゥイーン
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
static ifCase(flag:boolean|(()=>boolean), trueTween:Tween24, falseTween:Tween24|null = null):Tween24 {
let tween;
if (typeof(flag) == "function") {
tween = new Tween24()._createContainerTween(Tween24._TYPE_IF_CASE_BY_FUNC, falseTween ? [trueTween, falseTween] : [trueTween]);
tween._ifFunc = flag;
}
else {
tween = new Tween24()._createContainerTween(Tween24._TYPE_IF_CASE, flag ? [trueTween]: falseTween ? [falseTween]: []);
}
tween._trueTween = trueTween;
tween._falseTween = falseTween;
return tween;
}
/**
* トゥイーン実行時に boolean 値を返す関数を実行し、再生するトゥイーンを設定します。
* @static
* @param {()=>boolean} func boolean値を返す関数
* @param {Tween24} trueTween フラグが true の時に再生するトゥイーン
* @param {(Tween24|null)} [falseTween=null] フラグが false の時に再生するトゥイーン
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
// static ifCaseByFunc(func:()=>boolean, trueTween:Tween24, falseTween:Tween24|null = null):Tween24 {
// const childTween = falseTween ? [trueTween, falseTween] : [trueTween];
// const tween = new Tween24()._createContainerTween(Tween24._TYPE_IF_CASE_BY_FUNC, childTween);
// tween._ifFunc = func;
// tween._trueTween = trueTween;
// tween._falseTween = falseTween;
// return tween;
// }
private _createChildTween(type:string, target:any, timeOrVelocity:number, easing:Function|null, params:{[key:string]:number}|null): Tween24 {
this._type = type;
this._easing = easing || Tween24._defaultEasing;
this._delayTime = 0;
this._startTime = 0;
this._allUpdaters = [];
this._isContainerTween = false;
if (type == Tween24._TYPE_TWEEN_VELOCITY || type == Tween24._TYPE_TWEEN_TEXT_VELOCITY) {
this._time = 0;
this._velocity = timeOrVelocity;
}
else {
this._time = timeOrVelocity;
}
this._commonProcess();
if (Array.isArray(target)) {
if (ClassUtil.isString(target[0])) {
this._targetString = `[${target.toString()}]`;
this._warningLog("Does not support array type queries.");
}
else if (target[0] instanceof HTMLElement) {
this._isDOM = true;
this._targetString = `[HTMLElements]`;
this._multiTarget = target;
}
else {
this._multiTarget = target;
}
}
else if (ClassUtil.isString(target)) {
this._isDOM = true;
this._targetString = `${target}`;
this._targetQuery = target;
const t = HTMLUtil.querySelectorAll(target);
if (t.length <= 1) {
this._singleTarget = t[0];
}
else {
this._multiTarget = t;
}
}
else if (target instanceof HTMLElement) {
this._isDOM = true;
this._singleTarget = target;
}
else {
this._singleTarget = target;
}
if (params) {
for (const key in params) {
this._setPropety(key, params[key]);
}
}
return this;
}
private _createContainerTween(type:string, childTween:Tween24[]): Tween24 {
this._type = type;
this._time = 0;
this._delayTime = 0;
this._childTween = childTween;
this._firstTween = this._childTween[0];
this._playingChildTween = [];
this._numChildren = childTween.length;
this._numCompleteChildren = 0;
this._isContainerTween = true;
this._commonProcess();
var prev = this._firstTween;
var next;
if (type == Tween24._TYPE_SERIAL) {
for (var i = 0; i < this._numChildren; i++) {
next = this._childTween[i + 1];
prev._next = next;
prev._parent = this;
prev = next;
}
}
else {
for (const tween of this._childTween) {
tween._parent = this;
}
}
return this;
}
private _createActionTween(type:string) {
this._type = type;
this._time = 0;
this._delayTime = 0;
this._startTime = 0;
this._isContainerTween = false;
this._commonProcess();
return this;
}
private _commonProcess() {
this._serialNumber = ++ Tween24._numCreateTween;
}
// ------------------------------------------
//
// Tween control by ID and Group
//
// ------------------------------------------
/**
* トゥイーンのIDを設定します。
* @param {string} id トゥイーンのID
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
id (id:string): Tween24 { return this._setTweenId(id); }
/**
* 指定したIDのトゥイーンの play() を実行します。
* @static
* @param {string} id トゥイーンのID
* @memberof Tween24
*/
static playById = (id:string) => { Tween24._controlTweens(Tween24._getTweensById(id), Tween24Event.PLAY); }
/**
* 指定したIDのトゥイーンの manualPlay() を実行します。
* @static
* @param {string} id トゥイーンのID
* @memberof Tween24
*/
static manualPlayById = (id:string) => { Tween24._controlTweens(Tween24._getTweensById(id), Tween24Event.MANUAL_PLAY); }
/**
* 指定したIDのトゥイーンの pause() を実行します。
* @static
* @param {string} id トゥイーンのID
* @memberof Tween24
*/
static pauseById = (id:string) => { Tween24._controlTweens(Tween24._getTweensById(id), Tween24Event.PAUSE); }
/**
* 指定したIDのトゥイーンの skip() を実行します。
* @static
* @param {string} id トゥイーンのID
* @memberof Tween24
*/
static skipById = (id:string) => { Tween24._controlTweens(Tween24._getTweensById(id), Tween24Event.SKIP); }
/**
* 指定したIDのトゥイーンの stop() を実行します。
* @static
* @param {string} id トゥイーンのID
* @memberof Tween24
*/
static stopById = (id:string) => { Tween24._controlTweens(Tween24._getTweensById(id), Tween24Event.STOP); }
/**
* トゥイーンのグループIDを設定します。
* @param {string} groupId トゥイーンのグループID
* @return {Tween24} Tween24インスタンス
* @memberof Tween24
*/
groupId (groupId:string): Tween24 { return this._setTweenGroupId(groupId); }
/**
* 指定したグループIDのトゥイーンの play() を実行します。
* @static
* @param {string} groupId トゥイーンのID
* @memberof Tween24
*/
static playByGroupId = (groupId:string) => { Tween24._controlTweens(Tween24._getTweensByGroupId(groupId), Tween24Event.PLAY); }
/**
* 指定したグループIDのトゥイーンの manualPlay() を実行します。
* @static
* @param {string} groupId トゥイーンのID
* @memberof Tween24
*/
static manualPlayByGroupId = (groupId:string) => { Tween24._controlTweens(Tween24._getTweensByGroupId(groupId), Tween24Event.MANUAL_PLAY); }
/**
* 指定したグループIDのトゥイーンの pause() を実行します。
* @static
* @param {string} groupId トゥイーンのID
* @memberof Tween24
*/
static pauseByGroupId = (groupId:string) => { Tween24._controlTweens(Tween24._getTweensByGroupId(groupId), Tween24Event.PAUSE); }
/**
* 指定したグループIDのトゥイーンの skip() を実行します。
* @static
* @param {string} groupId トゥイーンのID
* @memberof Tween24
*/
static skipByGroupId = (groupId:string) => { Tween24._controlTweens(Tween24._getTweensByGroupId(groupId), Tween24Event.SKIP); }
/**
* 指定したグループIDのトゥイーンの stop() を実行します。
* @static
* @param {string} groupId トゥイーンのID
* @memberof Tween24
*/
static stopByGroupId = (groupId:string) => { Tween24._controlTweens(Tween24._getTweensByGroupId(groupId), Tween24Event.STOP); }
private _setTweenId(id:string): Tween24 {
this._tweenId = id;
Tween24._tweensById ||= new Map<string, Tween24>();
Tween24._tweensById.set(id, this);
return this;
}
private _setTweenGroupId(groupId:string): Tween24 {
this._tweenGroupId = groupId;
Tween24._tweensByGroupId ||= new Map<string, Tween24[]>();
const groupTweens = Tween24._tweensByGroupId.get(groupId) || [];
groupTweens.push(this);
Tween24._tweensByGroupId.set(groupId, groupTweens);
return this;
}
private static _getTweensById(id:string): Tween24[]|undefined { const tween = Tween24._tweensById?.get(id); return tween ? [tween] : undefined; }
private static _getTweensByGroupId(groupId:string): Tween24[]|undefined { return Tween24._tweensByGroupId?.get(groupId); }
private static _controlTweens(tweens:Tween24[]|undefined, event:string) {
if (tweens) {
switch (event) {
case Tween24Event.PLAY : tweens.forEach((tween) => { tween.play(); }); break;
case Tween24Event.MANUAL_PLAY : tweens.forEach((tween) => { tween.manualPlay(); }); break;
case Tween24Event.PAUSE : tweens.forEach((tween) => { tween.pause(); }); break;
case Tween24Event.SKIP : tweens.forEach((tween) => { tween.skip(); }); break;
case Tween24Event.STOP : tweens.forEach((tween) => { tween.stop(); }); break;
}
}
}
// ------------------------------------------
//
// Util
//
// ------------------------------------------
/**
* トゥイーン全体のFPS(1秒間の更新回数)を設定します。
* デフォルトでは0が設定され、ブラウザのリフレッシュレートに合わせて描画更新されます。
* @static
* @param {number} [fps=0] FPSの値
* @memberof Tween24
*/
static setFPS = (fps:number = 0) => {
Tween24.ticker.fps = fps;
}
/**
* デフォルトのイージングを設定します。
* @static
* @param {Function} [easing=Ease24._Linear] デフォルトのイージング
* @memberof Tween24
*/
static setDefaultEasing = (easing:Function = Ease24._Linear) => {
Tween24._defaultEasing = easing;
}
/**
* トゥイーン全体のデバッグモードを設定します。
* デバッグモードをONにすると、トゥイーンの動作状況がコンソールに表示されます。
* @static
* @param {boolean} flag デバッグモードを使用するか
* @memberof Tween24
*/
static debugMode = (flag:boolean) => {
Tween24._debugMode = flag;
}
static manualAllUpdate = () => {
const nowTime = Ticker24.getTime();
for (const tween of Tween24._manualPlayingTweens) {
tween.__update(nowTime);
}
}
__clone(base:any, baseQuery:string|null):Tween24 {
let copy:Tween24 = new Tween24();
let target:any;
if (this._targetQuery && baseQuery) {
for (const query of this._targetQuery.split(",")) {
if (query == baseQuery) {
target = base;
}
else {
const reg:RegExp = new RegExp("^" + baseQuery + " ")
if (reg.test(this._targetQuery)) {
target = HTMLUtil.querySelectorAllWithBase(base, this._targetQuery.replace(reg, ""));
}
else {
target = this._singleTarget || this._multiTarget;
}
}
}
}
else {
target = base;
}
switch (this._type) {
case Tween24._TYPE_TWEEN :
case Tween24._TYPE_TWEEN_VELOCITY :
case Tween24._TYPE_TWEEN_TEXT :
case Tween24._TYPE_TWEEN_TEXT_VELOCITY :
case Tween24._TYPE_PROP :
case Tween24._TYPE_PROP_TEXT :
copy._createChildTween(this._type, target, this._velocity || this._time, this._easing, null);
copy._targetQuery = this._targetQuery;
if (this._allUpdaters?.length) {
if (this._singleTarget && copy._multiTarget) {
for (const updater of this._allUpdaters) {
copy._allUpdaters?.push(new MultiUpdater(copy._multiTarget, this._targetQuery).setupByUpdater(updater));
}
}
else {
for (const updater of this._allUpdaters) {
copy._allUpdaters?.push(updater.clone(copy._singleTarget || copy._multiTarget, this._targetQuery));
}
}
}
break;
case Tween24._TYPE_WAIT :
copy._createChildTween(this._type, target, this._time, this._easing, null);
break;
case Tween24._TYPE_SERIAL :
case Tween24._TYPE_PARALLEL :
case Tween24._TYPE_LOOP :
const tweens:Tween24[] = [];
if (this._childTween) {
for (const tween of this._childTween) {
tweens.push(tween.__clone(base, baseQuery));
}
}
copy._createContainerTween(this._type, tweens);
copy._numLoops = this._numLoops;
break;
case Tween24._TYPE_LAG:
const lagTweens:Tween24[] = [];
if (this._originalChildTween) {
for (const tween of this._originalChildTween) {
lagTweens.push(tween.__clone(base, baseQuery));
}
}
if (!isNaN(this._lagTime)) {
copy = Tween24.lagSort(this._lagTime, this._lagSort || Sort24._Normal, ...lagTweens);
}
else {
copy = Tween24.lagTotalSortEase(this._totalLagTime, this._lagSort || Sort24._Normal, this._lagEasing || Ease24._Linear, ...lagTweens);
}
break;
case Tween24._TYPE_FUNC :
copy._type = this._type;
copy._time = copy._delayTime = copy._startTime = 0;
copy._isContainerTween = false;
break;
}
if (this._functionExecuters) {
copy._functionExecuters = {};
for (const key in this._functionExecuters) {
copy._functionExecuters[key] = this._functionExecuters[key].clone();
}
}
copy.willChange(this._useWillChange);
copy.delay(this._delayTime).fps(this.__fps).debug(this._debugMode);
return copy;
}
toString():string {
return `Tween24 ${this.getTweenTypeString()} ${this.getTweenParamString()}`
}
private _debugLog(message:any) {
if (Tween24._debugMode || this._debugMode || this._root?._debugMode || this._parent?._debugMode) {
const margin:string = " ".repeat(this._numLayers);
console.log(`${margin}${this.getTweenTypeString()} ${message} ${this.getTweenParamString()}`);
}
}
private _warningLog(message:string):void {
console.log(`Tween24 Warning: ${message}\n - ${this.toString()}`);
}
private getTweenTypeString():string {
let type:string = "";
type += this._parent ? `${this._parent._type}/` : "";
type += this._type;
return `[${type}]`;
}
private getTweenParamString():string {
let param:string = "";
param += this._targetString ? `target:${this._targetString}` : (`id:${this._tweenId || this._serialNumber}`);
switch (this._type) {
case Tween24._TYPE_TWEEN :
case Tween24._TYPE_WAIT :
case Tween24._TYPE_TWEEN_TEXT :
param += " time:" + this._time + " "; break;
case Tween24._TYPE_TWEEN_VELOCITY :
case Tween24._TYPE_TWEEN_TEXT_VELOCITY :
param += " velocity:" + this._velocity + " "; break;
}
if (this._delayTime) {
param += " delay:" + this._delayTime + " ";
}
if (this._allUpdaters) {
for (const updater of this._allUpdaters) {
param += updater.toString() + " ";
}
}
return `{${param.replace(/\s+/g," ").trim()}}`;
}
} | the_stack |
import 'rxjs/add/operator/switchMap';
import {Location} from '@angular/common';
import {DebugElement} from '@angular/core';
import {async, ComponentFixture, fakeAsync, flush, TestBed, tick} from '@angular/core/testing';
import {MatCardModule, MatDialog, MatIconModule, MatProgressSpinnerModule, MatTableModule} from '@angular/material';
import {By} from '@angular/platform-browser';
import {ActivatedRoute, convertToParamMap} from '@angular/router';
import {RouterTestingModule} from '@angular/router/testing';
import {MomentModule} from 'ngx-moment';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {StatusIconModule} from '../common/components/status-icon/status-icon.module';
import {ToolbarModule} from '../common/components/toolbar/toolbar.module';
import {DummyComponent} from '../common/test_helpers/dummy.component';
// tslint:disable-next-line:max-line-length
import {expectElementNotToExist, expectElementToExist, getAllElements, getElement, getElementText} from '../common/test_helpers/element_helper_functions';
import {mockBuildSummary_success} from '../common/test_helpers/mock_build_data';
import {getMockProject} from '../common/test_helpers/mock_project_data';
import {BuildSummary} from '../models/build_summary';
import {Project} from '../models/project';
import {SharedMaterialModule} from '../root/shared_material.module';
import {DataService} from '../services/data.service';
import {ProjectComponent} from './project.component';
import {SettingsDialogComponent} from './settings-dialog/settings-dialog.component';
import {SettingsDialogModule} from './settings-dialog/settings-dialog.modules';
describe('ProjectComponent', () => {
let location: Location;
let component: ProjectComponent;
let fixture: ComponentFixture<ProjectComponent>;
let fixtureEl: DebugElement;
let dataService: jasmine.SpyObj<Partial<DataService>>;
let projectSubject: Subject<Project>;
let rebuildSummarySubject: Subject<BuildSummary>;
let dialog: jasmine.SpyObj<Partial<MatDialog>>;
beforeEach(async(() => {
projectSubject = new Subject<Project>();
rebuildSummarySubject = new Subject<BuildSummary>();
dataService = {
getProject:
jasmine.createSpy().and.returnValue(projectSubject.asObservable()),
rebuild: jasmine.createSpy().and.returnValue(
rebuildSummarySubject.asObservable())
};
dialog = {open: jasmine.createSpy()};
TestBed
.configureTestingModule({
imports: [
StatusIconModule, MomentModule, ToolbarModule, MatCardModule,
MatTableModule, MatProgressSpinnerModule, SettingsDialogModule,
MatIconModule, RouterTestingModule.withRoutes([
{
path: 'project/:projectId/build/:buildId',
component: DummyComponent
},
{
path: '404',
component: DummyComponent
}
])
],
declarations: [ProjectComponent, DummyComponent],
providers: [
{provide: DataService, useValue: dataService}, {
provide: ActivatedRoute,
useValue:
{paramMap: Observable.of(convertToParamMap({id: '123'}))}
},
{provide: MatDialog, useValue: dialog}
],
})
.compileComponents();
fixture = TestBed.createComponent(ProjectComponent);
fixtureEl = fixture.debugElement;
component = fixture.componentInstance;
location = TestBed.get(Location);
}));
describe('Unit tests', () => {
it('should load project', () => {
expect(component.isLoading).toBe(true);
fixture.detectChanges(); // onInit()
expect(dataService.getProject).toHaveBeenCalledWith('123');
projectSubject.next(getMockProject()); // Resolve observable
expect(component.isLoading).toBe(false);
expect(component.project.id).toBe('12');
expect(component.project.name).toBe('the most coolest project');
expect(component.project.builds.length).toBe(2);
expect(component.project.builds[0].sha).toBe('asdfshzdggfdhdfh4');
});
it('should redirect if API returns an error', fakeAsync(() => {
fixture.detectChanges();
expect(dataService.getProject).toHaveBeenCalledWith('123');
projectSubject.error({});
tick();
expect(location.path()).toBe('/404');
}));
it('should update breadcrumbs after loading project', () => {
fixture.detectChanges(); // onInit()
expect(component.breadcrumbs[1].hint).toBe('Project');
expect(component.breadcrumbs[1].label).toBeUndefined();
projectSubject.next(getMockProject()); // Resolve observable
expect(component.breadcrumbs[1].label).toBe('the most coolest project');
});
it('#rebuild should send rebuild request', () => {
fixture.detectChanges(); // onInit()
projectSubject.next(getMockProject()); // Resolve observable
component.rebuild(new Event('click'), getMockProject().builds[0]);
expect(dataService.rebuild).toHaveBeenCalledWith('12', 2);
});
it('#rebuild should add new Build Summary to table data', fakeAsync(() => {
fixture.detectChanges(); // onInit()
projectSubject.next(getMockProject()); // Resolve observable
flush();
fixture.detectChanges();
flush();
component.rebuild(new Event('click'), getMockProject().builds[0]);
expect(component.project.builds.length).toBe(2);
rebuildSummarySubject.next(mockBuildSummary_success);
expect(component.project.builds.length).toBe(3);
}));
});
describe('Shallow Tests', () => {
describe('Project not loaded', () => {
beforeEach(() => {
fixture.detectChanges(); // onInit()
});
it('should not show project title', () => {
expectElementNotToExist(fixtureEl, '.fci-project-header');
});
it('table should not show loading spinner', () => {
expectElementToExist(
fixtureEl, '.fci-build-table .fci-loading-spinner');
});
it('details card should not show loading spinner', () => {
expectElementToExist(
fixtureEl, '.fci-project-details .fci-loading-spinner');
});
it('should open settings dialog when settings gear is clicked', () => {
fixture.debugElement.query(By.css('.fci-settings-button'))
.nativeElement.click();
expect(dialog.open).toHaveBeenCalledWith(SettingsDialogComponent, {
panelClass: 'fci-dialog',
width: '1028px',
data: {project: this.project},
});
});
});
describe('Project loaded', () => {
beforeEach(fakeAsync(() => {
fixture.detectChanges(); // onInit()
projectSubject.next(getMockProject()); // Resolve observable
flush();
fixture.detectChanges();
flush();
}));
it('should have toolbar with breadcrumbs', () => {
// toolbar exists
expect(getAllElements(fixtureEl, '.fci-crumb').length).toBe(2);
expect(component.breadcrumbs[0].label).toBe('Dashboard');
expect(component.breadcrumbs[0].url).toBe('/');
});
it('should have project title', () => {
expect(getElementText(fixtureEl, '.fci-project-header'))
.toBe('the most coolest project');
});
describe('table', () => {
let rowEls: DebugElement[];
beforeEach(() => {
rowEls = getAllElements(fixtureEl, '.mat-row');
expect(rowEls.length).toBe(2);
});
it('should not show loading spinner', () => {
expectElementNotToExist(
fixtureEl, '.fci-build-table .fci-loading-spinner');
});
it('should have status icon', () => {
expect(
getElementText(rowEls[0], '.mat-column-number .fci-status-icon'))
.toBe('check_circle');
expect(
getElementText(rowEls[1], '.mat-column-number .fci-status-icon'))
.toBe('cancel');
});
it('should have build number', () => {
expect(getElementText(rowEls[0], '.mat-column-number span'))
.toBe('2');
expect(getElementText(rowEls[1], '.mat-column-number span'))
.toBe('1');
});
it('should have duration', () => {
expect(getElementText(rowEls[0], '.mat-column-duration'))
.toBe('3 days');
});
it('should have branch', () => {
expect(getElementText(rowEls[0], '.mat-column-branch'))
.toBe('master');
});
it('should have sha link', () => {
expect(getElementText(rowEls[0], '.mat-column-sha a')).toBe('asdfsh');
});
it('should go to build when clicked', fakeAsync(() => {
rowEls[0].nativeElement.click();
tick();
expect(location.path()).toBe('/project/12/build/2');
}));
it('should not show rebuild button on successful builds', () => {
// First row is successful build
expectElementNotToExist(
rowEls[0], '.mat-column-sha .fci-button-visible');
});
it('should show rebuild button on failed builds', () => {
// Second row is failed build
expectElementToExist(
rowEls[1], '.mat-column-sha .fci-button-visible');
});
it('should rebuild when rebuild button is clicked', () => {
const buttonEl =
getElement(rowEls[1], '.mat-column-sha .fci-button-visible');
buttonEl.nativeElement.click();
expect(dataService.rebuild).toHaveBeenCalledWith('12', 1);
});
it('should add new row after rebuild is complete', () => {
const buttonEl =
getElement(rowEls[1], '.mat-column-sha .fci-button-visible');
buttonEl.nativeElement.click();
rebuildSummarySubject.next(mockBuildSummary_success);
fixture.detectChanges();
expect(getAllElements(fixtureEl, '.mat-row').length).toBe(3);
});
});
describe('details card', () => {
let cardEl: DebugElement;
let headerEls: DebugElement[];
let contentsEls: DebugElement[];
beforeEach(() => {
cardEl = getElement(fixtureEl, '.fci-project-details');
headerEls = getAllElements(cardEl, 'h5');
contentsEls = getAllElements(cardEl, 'div');
});
it('should not show loading spinner', () => {
expectElementNotToExist(cardEl, '.fci-loading-spinner');
});
it('should show Repo name', () => {
expect(getElementText(headerEls[0])).toBe('REPO');
expect(getElementText(contentsEls[0])).toBe('fastlane/TacoRocat');
});
it('should show lane', () => {
expect(getElementText(headerEls[1])).toBe('LANE');
expect(getElementText(contentsEls[1])).toBe('ios test');
});
it('should show last successful build number', () => {
expect(getElementText(headerEls[2])).toBe('LAST SUCCESSFUL BUILD');
expect(getElementText(contentsEls[2])).toBe('2');
});
it('should show last failed build number', () => {
expect(getElementText(headerEls[3])).toBe('LAST FAILED BUILD');
expect(getElementText(contentsEls[3])).toBe('1');
});
});
});
});
}); | the_stack |
import {html, css, LitElement} from 'lit';
import {property} from 'lit/decorators.js';
import {createChartWrapper, dataTable, DataTableLike} from './loader.js';
const DEFAULT_EVENTS = ['ready', 'select'];
/**
* Constructor names for supported chart types.
*
* `ChartWrapper` expects a constructor name and assumes `google.visualization`
* as the default namespace.
*/
const CHART_TYPES: Record<string, string|undefined> = {
'area': 'AreaChart',
'bar': 'BarChart',
'md-bar': 'google.charts.Bar',
'bubble': 'BubbleChart',
'calendar': 'Calendar',
'candlestick': 'CandlestickChart',
'column': 'ColumnChart',
'combo': 'ComboChart',
'gantt': 'Gantt',
'gauge': 'Gauge',
'geo': 'GeoChart',
'histogram': 'Histogram',
'line': 'LineChart',
'md-line': 'google.charts.Line',
'org': 'OrgChart',
'pie': 'PieChart',
'sankey': 'Sankey',
'scatter': 'ScatterChart',
'md-scatter': 'google.charts.Scatter',
'stepped-area': 'SteppedAreaChart',
'table': 'Table',
'timeline': 'Timeline',
'treemap': 'TreeMap',
'wordtree': 'WordTree',
};
/**
* `google-chart` encapsulates Google Charts as a web component, allowing you to
* easily visualize data. From simple line charts to complex hierarchical tree
* maps, the chart element provides a number of ready-to-use chart types.
*
* ```html
* <google-chart
* type='pie'
* options='{"title": "Distribution of days in 2001Q1"}'
* cols='[{"label":"Month", "type":"string"}, {"label":"Days",
* "type":"number"}]' rows='[["Jan", 31],["Feb", 28],["Mar", 31]]'>
* </google-chart>
* ```
*
* Note: if you're passing JSON as attributes, single quotes are necessary to be
* valid JSON. See
* https://www.polymer-project.org/1.0/docs/devguide/properties#configuring-object-and-array-properties.
*
* Height and width are specified as style attributes:
* ```css
* google-chart {
* height: 300px;
* width: 50em;
* }
* ```
*
* Data can be provided in one of three ways:
*
* - Via the `cols` and `rows` attributes:
* ```
* cols='[{"label":"Mth", "type":"string"},{"label":"Days", "type":"number"}]'
* rows='[["Jan", 31],["Feb", 28],["Mar", 31]]'
* ```
*
* - Via the `data` attribute, passing in the data directly:
* ```
* data='[["Month", "Days"], ["Jan", 31], ["Feb", 28], ["Mar", 31]]'
* ```
*
* - Via the `data` attribute, passing in the URL to a resource containing the
* data, in JSON format:
* ```
* data='http://example.com/chart-data.json'
* ```
*
* - Via the `data` attribute, passing in a Google DataTable object:
* ```
* data='{{dataTable}}'
* ```
*
* - Via the `view` attribute, passing in a Google DataView object:
* ```
* view='{{dataView}}'
* ```
*
* You can display the charts in locales other than "en" by setting the `lang`
* attribute on the `html` tag of your document:
* ```
* <html lang="ja">
* ```
*
* @demo demo/index.html
*/
export class GoogleChart extends LitElement {
/** @nocollapse */
static override styles = css`
:host {
display: -webkit-flex;
display: -ms-flex;
display: flex;
margin: 0;
padding: 0;
width: 400px;
height: 300px;
}
:host([hidden]) {
display: none;
}
:host([type="gauge"]) {
width: 300px;
height: 300px;
}
#chartdiv {
width: 100%;
}
/* Workaround for slow initial ready event for tables. */
.google-visualization-table-loadtest {
padding-left: 6px;
}
`;
/**
* Fired after a chart type is rendered and ready for interaction.
*
* @event google-chart-ready
* @param {{chart: !Object}} detail The raw chart object.
*/
/**
* Fired when the user makes a selection in the chart.
*
* @event google-chart-select
* @param {{chart: !Object}} detail The raw chart object.
*/
/**
* Type of the chart.
*
* Should be one of:
* - `area`
* - `(md-)bar`
* - `bubble`
* - `calendar`
* - `candlestick`
* - `column`
* - `combo`
* - `gantt`
* - `gauge`
* - `geo`
* - `histogram`
* - `(md-)line`
* - `org`
* - `pie`
* - `sankey`
* - `(md-)scatter`
* - `stepped-area`
* - `table`
* - `timeline`
* - `treemap`
* - `wordtree`
*
* See <a
* href="https://google-developers.appspot.com/chart/interactive/docs/gallery">Google
* Visualization API reference (Chart Gallery)</a> for details.
*/
@property({type: String, reflect: true})
type = 'column';
/**
* Enumerates the chart events that should be fired.
*
* Charts support a variety of events. By default, this element only
* fires on `ready` and `select`. If you would like to be notified of
* other chart events, use this property to list them.
* Events `ready` and `select` are always fired.
*
* Changes to this property are _not_ observed. Events are attached only
* at chart construction time.
*/
@property({type: Array})
events: string[] = [];
/**
* Sets the options for the chart.
*
* Example:
* ```
* {
* title: "Chart title goes here",
* hAxis: {title: "Categories"},
* vAxis: {title: "Values", minValue: 0, maxValue: 2},
* legend: "none"
* }
* ```
* See <a
* href="https://google-developers.appspot.com/chart/interactive/docs/gallery">Google
* Visualization API reference (Chart Gallery)</a> for the options available
* to each chart type.
*
* Setting this property always redraws the chart. If you would like to make
* changes to a sub-property, be sure to reassign the property:
* ```
* const options = googleChart.options;
* options.vAxis.logScale = true;
* googleChart.options = options;
* ```
* (Note: Missing parent properties are not automatically created.)
*/
@property({type: Object, hasChanged: () => true})
options: {}|undefined = undefined;
/**
* Sets the data columns for this object.
*
* When specifying data with `cols` you must also specify `rows`, and
* not specify `data`.
*
* Example:
* <pre>[{label: "Categories", type: "string"},
* {label: "Value", type: "number"}]</pre>
* See <a
* href="https://google-developers.appspot.com/chart/interactive/docs/reference#DataTable_addColumn">Google
* Visualization API reference (addColumn)</a> for column definition format.
*/
@property({type: Array})
cols: unknown[]|undefined = undefined;
/**
* Sets the data rows for this object.
*
* When specifying data with `rows` you must also specify `cols`, and
* not specify `data`.
*
* Example:
* <pre>[["Category 1", 1.0],
* ["Category 2", 1.1]]</pre>
* See <a
* href="https://google-developers.appspot.com/chart/interactive/docs/reference#addrow">Google
* Visualization API reference (addRow)</a> for row format.
*/
@property({type: Array})
rows: unknown[][]|undefined = undefined;
/**
* Sets the entire dataset for this object.
* Can be used to provide the data directly, or to provide a URL from
* which to request the data.
*
* The data format can be a two-dimensional array or the DataTable format
* expected by Google Charts.
* See <a
* href="https://google-developers.appspot.com/chart/interactive/docs/reference#DataTable">Google
* Visualization API reference (DataTable constructor)</a> for data table
* format details.
*
* When specifying data with `data` you must not specify `cols` or `rows`.
*
* Example:
* ```
* [["Categories", "Value"],
* ["Category 1", 1.0],
* ["Category 2", 1.1]]
* ```
*/
// Note: type: String, because it is parsed manually in the observer.
@property({type: String})
data: DataTableLike|string|undefined = undefined;
/**
* Sets the entire dataset for this object to a Google DataView.
*
* See <a
* href="https://google-developers.appspot.com/chart/interactive/docs/reference#dataview-class">Google
* Visualization API reference (DataView)</a> for details.
*
* When specifying data with `view` you must not specify `data`, `cols` or
* `rows`.
*/
@property({type: Object})
view: google.visualization.DataView|undefined = undefined;
/**
* Selected datapoint(s) in the chart.
*
* An array of objects, each with a numeric row and/or column property.
* `row` and `column` are the zero-based row or column number of an item
* in the data table to select.
*
* To select a whole column, set row to null;
* to select a whole row, set column to null.
*
* Example:
* ```
* [{row:0,column:1}, {row:1, column:null}]
* ```
*/
@property({type: Array})
selection: google.visualization.ChartSelection[]|undefined = undefined;
/**
* Whether the chart is currently rendered.
* @export
*/
drawn = false;
/**
* Internal data displayed on the chart.
*/
// tslint:disable-next-line:enforce-name-casing
@property({type: Object}) _data: google.visualization.DataTable|
google.visualization.DataView|undefined = undefined;
/**
* Internal chart object.
*/
private chartWrapper: google.visualization.ChartWrapper|null = null;
private redrawTimeoutId: number|undefined = undefined;
/** @override */
protected override render() {
return html`
<div id="styles"></div>
<div id="chartdiv"></div>
`;
}
/** @override */
protected override firstUpdated() {
createChartWrapper(this.shadowRoot!.getElementById('chartdiv')!)
.then(chartWrapper => {
this.chartWrapper = chartWrapper;
this.typeChanged();
google.visualization.events.addListener(chartWrapper, 'ready', () => {
this.drawn = true;
});
google.visualization.events.addListener(
chartWrapper, 'select', () => {
this.selection = chartWrapper.getChart()!.getSelection();
});
this.propagateEvents(DEFAULT_EVENTS, chartWrapper);
});
}
/** @override */
protected override updated(changedProperties: Map<string, unknown>) {
if (changedProperties.has('type')) this.typeChanged();
if (changedProperties.has('rows') || changedProperties.has('cols')) {
this.rowsOrColumnsChanged();
}
if (changedProperties.has('data')) this.dataChanged();
if (changedProperties.has('view')) this.viewChanged();
if (changedProperties.has('_data') ||
changedProperties.has('options')) this.redraw();
if (changedProperties.has('selection')) this.selectionChanged();
}
/** Reacts to chart type change. */
private typeChanged() {
if (this.chartWrapper == null) return;
this.chartWrapper.setChartType(CHART_TYPES[this.type] || this.type);
const lastChart = this.chartWrapper.getChart();
google.visualization.events.addOneTimeListener(
this.chartWrapper, 'ready', () => {
// Ready event fires after `chartWrapper` is initialized.
const chart = this.chartWrapper!.getChart();
if (chart !== lastChart) {
this.propagateEvents(
this.events.filter(
(eventName) => !DEFAULT_EVENTS.includes(eventName)),
chart);
}
const stylesDiv = this.shadowRoot!.getElementById('styles')!;
if (!stylesDiv.children.length) {
this.localizeGlobalStylesheets(stylesDiv);
}
if (this.selection) {
this.selectionChanged();
}
});
this.redraw();
}
/**
* Adds listeners to propagate events from the chart.
*/
private propagateEvents(events: string[], eventTarget: unknown) {
for (const eventName of events) {
google.visualization.events.addListener(
eventTarget, eventName, (event: unknown) => {
this.dispatchEvent(new CustomEvent(`google-chart-${eventName}`, {
bubbles: true,
composed: true,
detail: {
// Events fire after `chartWrapper` is initialized.
chart: this.chartWrapper!.getChart(),
data: event,
}
}));
});
}
}
/** Sets the selectiton on the chart. */
private selectionChanged() {
if (this.chartWrapper == null) return;
const chart = this.chartWrapper.getChart();
if (chart == null) return;
if (chart.setSelection) {
// Workaround for timeline chart which emits select event on setSelection.
// See issue #256.
if (this.type === 'timeline') {
const oldSelection = JSON.stringify(chart.getSelection());
const newSelection = JSON.stringify(this.selection);
if (newSelection === oldSelection) return;
}
chart.setSelection(this.selection);
}
}
/**
* Redraws the chart.
*
* Called automatically when data/type/selection attributes change.
* Call manually to handle view updates, page resizes, etc.
*/
redraw() {
if (this.chartWrapper == null || this._data == null) return;
// `ChartWrapper` can be initialized with `DataView` instead of `DataTable`.
this.chartWrapper.setDataTable(
this._data as google.visualization.DataTable);
this.chartWrapper.setOptions(this.options || {});
this.drawn = false;
if (this.redrawTimeoutId !== undefined) clearTimeout(this.redrawTimeoutId);
this.redrawTimeoutId = window.setTimeout(() => {
// Drawing happens after `chartWrapper` is initialized.
this.chartWrapper!.draw();
}, 5);
}
/**
* Returns the chart serialized as an image URI.
*
* Call this after the chart is drawn (`google-chart-ready` event).
*/
get imageURI(): string|null {
if (this.chartWrapper == null) return null;
const chart = this.chartWrapper.getChart();
return chart && (chart as google.visualization.ChartBaseRenderable).getImageURI();
}
/** Handles changes to the `view` attribute. */
private viewChanged() {
if (!this.view) return;
this._data = this.view;
}
/** Handles changes to the rows & columns attributes. */
private async rowsOrColumnsChanged() {
const {rows, cols} = this;
if (!rows || !cols) return;
try {
const dt = await dataTable({cols});
dt.addRows(rows);
this._data = dt;
} catch (reason) {
this.shadowRoot!.getElementById('chartdiv')!.textContent = String(reason);
}
}
/**
* Handles changes to the `data` attribute.
*/
private dataChanged() {
let data = this.data;
let dataPromise;
if (!data) {
return;
}
let isString = false;
// Polymer 2 will not call observer if type:Object is set and fails, so
// we must parse the string ourselves.
try {
// Try to deserialize the value of the `data` property which might be a
// serialized array.
data = JSON.parse(data as string) as DataTableLike;
} catch (e) {
isString = typeof data === 'string' || data instanceof String;
}
if (isString) {
// Load data asynchronously, from external URL.
dataPromise = fetch(data as string).then(response => response.json());
} else {
// Data is all ready to be processed.
dataPromise = Promise.resolve(data);
}
dataPromise.then(dataTable).then(data => {
this._data = data;
});
}
/**
* Queries global document head for Google Charts `link#load-css-*` and clones
* them into the local root's `div#styles` element for shadow dom support.
*/
private localizeGlobalStylesheets(stylesDiv: HTMLElement) {
// Get all Google Charts stylesheets.
const stylesheets = Array.from(document.head.querySelectorAll(
'link[rel="stylesheet"][type="text/css"][id^="load-css-"]'));
for (const stylesheet of stylesheets) {
// Clone necessary stylesheet attributes.
const clonedStylesheet = document.createElement('link');
clonedStylesheet.setAttribute('rel', 'stylesheet');
clonedStylesheet.setAttribute('type', 'text/css');
// `href` is always present.
clonedStylesheet.setAttribute('href', stylesheet.getAttribute('href')!);
stylesDiv.appendChild(clonedStylesheet);
}
}
}
customElements.define('google-chart', GoogleChart);
declare global {
interface HTMLElementTagNameMap {
'google-chart': GoogleChart;
}
} | the_stack |
import {assert} from 'chai';
import {suite, test} from "mocha-typescript";
import * as ion from '../src/Ion';
@suite('Text Reader')
class IonTextReaderTests {
private static escapeTerminatorTest(input, expected) {
let reader = ion.makeReader(input);
reader.next();
assert.equal(reader.stringValue(), expected);
}
private static ivmTest(reader, value, expected, depth, annotations) {
if (expected === "throw") {
assert.throws(() => {
reader.isIVM(value, depth, annotations)
});
} else {
let actual = reader.isIVM(value, depth, annotations);
assert.equal(actual, expected);
}
}
@test "Read string value"() {
let ionToRead = "\"string\"";
let ionReader = ion.makeReader(ionToRead);
ionReader.next();
assert.equal(ionReader.stringValue(), "string");
}
@test "Read emoji with modifier"() {
let s: string = 'a👩🏽b👩🏽👩🏽c';
let r: ion.Reader = ion.makeReader("'" + s + "'" + ' ' + '"' + s + '"' + ' ' + "'''" + s + "'''");
r.next();
assert.equal(r.stringValue(), s);
r.next();
assert.equal(r.stringValue(), s);
r.next();
assert.equal(r.stringValue(), s);
}
@test "Read boolean value"() {
let ionToRead = "true";
let ionReader = ion.makeReader(ionToRead);
ionReader.next();
assert.equal(ionReader.booleanValue(), true);
}
@test "Read clob value"() {
let ionToRead = '{{"\\xc2\\x80"}}';
let ionReader = ion.makeReader(ionToRead);
ionReader.next();
assert.deepEqual(ionReader.uInt8ArrayValue(), Uint8Array.from([194, 128]));
}
@test "Read boolean value in struct"() {
let ionToRead = "{ a: false }";
let ionReader = ion.makeReader(ionToRead);
ionReader.next();
ionReader.stepIn();
ionReader.next();
assert.equal(ionReader.booleanValue(), false);
}
@test "resolves symbol IDs"() {
let ionToRead = `$ion_symbol_table::{ symbols:[ "rock", "paper", "scissors" ]}{ $5: $6, $10: $11, $12: 'taco' }`;
let ionReader = ion.makeReader(ionToRead);
ionReader.next();
ionReader.stepIn();
ionReader.next();
assert.equal(ionReader.fieldName(), 'version');
assert.equal(ionReader.stringValue(), 'imports');
ionReader.next();
assert.equal(ionReader.fieldName(), "rock");
assert.equal(ionReader.stringValue(), "paper");
ionReader.next();
assert.equal(ionReader.fieldName(), "scissors");
assert.equal(ionReader.stringValue(), 'taco');
}
@test "Parse through struct"() {
let ionToRead = "{ key : \"string\" }";
let ionReader = ion.makeReader(ionToRead);
ionReader.next();
assert.equal(ion.IonTypes.STRUCT, ionReader.type());
ionReader.stepIn(); // Step into the base struct.
ionReader.next();
assert.equal(ionReader.fieldName(), "key");
assert.equal(ionReader.stringValue(), "string");
assert.isNull(ionReader.next());
}
@test "Parse through struct can skip over container"() {
let ionToRead = "{ a: { key1 : \"string1\" }, b: { key2 : \"string2\" } }";
let ionReader = ion.makeReader(ionToRead);
ionReader.next();
assert.equal(ion.IonTypes.STRUCT, ionReader.type());
ionReader.stepIn(); // Step into the base struct.
ionReader.next();
assert.equal(ionReader.fieldName(), "a");
ionReader.next();
assert.equal(ionReader.fieldName(), "b");
ionReader.stepIn(); // Step into the "b" struct.
ionReader.next();
assert.equal(ionReader.fieldName(), "key2");
assert.equal(ionReader.stringValue(), "string2");
assert.isNull(ionReader.next());
}
@test "Parse through struct can skip over nested containers"() {
let ionToRead = "{ outerkey1 : { innerkey1 : {a1: \"a1\", b1: \"b1\"} }, outerkey2 : { innerkey2 : {a2: \"a2\", b2: \"b2\"} } }";
let ionReader = ion.makeReader(ionToRead);
ionReader.next();
assert.equal(ion.IonTypes.STRUCT, ionReader.type());
ionReader.stepIn(); // Step into the base struct.
ionReader.next();
assert.equal(ionReader.fieldName(), "outerkey1");
ionReader.next();
assert.equal(ionReader.fieldName(), "outerkey2");
ionReader.stepIn(); // Step into the "b" struct.
ionReader.next();
assert.equal(ionReader.fieldName(), "innerkey2");
assert.isNull(ionReader.next());
}
@test "Parse through struct throws error on broken input"() {
let invalidIonToRead = "{broken";
let ionReader = ion.makeReader(invalidIonToRead);
ionReader.next();
assert.equal(ion.IonTypes.STRUCT, ionReader.type());
ionReader.stepIn(); // Step into the base struct.
assert.throws(() => ionReader.next());
}
@test "Reads an array"() {
let ionToRead = "{ key : ['v1', 'v2'] }";
let ionReader = ion.makeReader(ionToRead);
ionReader.next();
assert.equal(ion.IonTypes.STRUCT, ionReader.type());
ionReader.stepIn(); // Step into the base struct.
ionReader.next();
assert.equal(ionReader.fieldName(), "key");
ionReader.stepIn(); // Step into the array.
ionReader.next();
assert.equal(ionReader.stringValue(), "v1");
ionReader.next();
assert.equal(ionReader.stringValue(), "v2");
assert.isNull(ionReader.next());
}
@test "Reads a nested array"() {
let ionToRead = "{ key : [['v1', 'v2']] }";
let ionReader = ion.makeReader(ionToRead);
ionReader.next();
assert.equal(ion.IonTypes.STRUCT, ionReader.type());
ionReader.stepIn(); // Step into the base struct.
ionReader.next();
assert.equal(ionReader.fieldName(), "key");
ionReader.stepIn(); // Step into the outer array.
ionReader.next();
ionReader.stepIn(); // Step into the inner array.
ionReader.next();
assert.equal(ionReader.stringValue(), "v1");
ionReader.next();
assert.equal(ionReader.stringValue(), "v2");
assert.isNull(ionReader.next());
}
@test "Returns null on EOF"() {
let ionToRead = "";
let ionReader = ion.makeReader(ionToRead);
assert.isNull(ionReader.next());
assert.isNull(ionReader.next()); // EOF
}
@test "Parses escaped terminators correctly."() {
IonTextReaderTests.escapeTerminatorTest("'abc\\''", "abc'");
IonTextReaderTests.escapeTerminatorTest("'''abc\\''''", "abc'");
IonTextReaderTests.escapeTerminatorTest("'abc\\'' taco", "abc'");
IonTextReaderTests.escapeTerminatorTest("'''abc\\'''' taco", "abc'");
IonTextReaderTests.escapeTerminatorTest("'''abc\\'''' '''''' taco", "abc'");
IonTextReaderTests.escapeTerminatorTest('"abc\\""', 'abc"');
IonTextReaderTests.escapeTerminatorTest('"abc\\"" taco', 'abc"');
IonTextReaderTests.escapeTerminatorTest("'\\\n'", "");
IonTextReaderTests.escapeTerminatorTest("'''short1\\\n'''\n\n'''\\\nmulti-line string\nwith embedded\\nnew line\ncharacters\\\n'''", "short1multi-line string\nwith embedded\nnew line\ncharacters");
};
@test "text IVM"() {
let textReader = ion.makeReader("");
let isNotIVM = ["$ion_schema_1_0", "$ion_1", "$ion_1_a", "$ion_", "ion_1_"];
let unsupportedIVM = ["$ion_2_0", "$ion_1_999", "$ion_999_0", "$ion_1_1", "$ion_1_00"];
IonTextReaderTests.ivmTest(textReader, "$ion_1_0", true, 0, []);
IonTextReaderTests.ivmTest(textReader, "$ion_1_0", false, 1, []);
IonTextReaderTests.ivmTest(textReader, "$ion_1_0", false, 0, ["taco"]);
for (let i = 0; i < isNotIVM.length; i++) {
IonTextReaderTests.ivmTest(textReader, isNotIVM[i], false, 0, []);
}
for (let i = 0; i < unsupportedIVM.length; i++) {
IonTextReaderTests.ivmTest(textReader, unsupportedIVM[i], "throw", 0, []);
IonTextReaderTests.ivmTest(textReader, unsupportedIVM[i], false, 1, []);
IonTextReaderTests.ivmTest(textReader, unsupportedIVM[i], false, 0, ["taco"]);
}
}
@test "get position from reader" () {
const ionToRead = "ann1::{ key: valX } ann2::{ keyX: ['v1', 'v2'], keyY: ['v3', 'v4'] }";
const ionTextReader = ion.makeReader(ionToRead);
// In the comments below, the vertical bar '|' indicates the current position of the cursor at each step.
const pos1 = ionTextReader.position();
// |ann1::{ key: valX } ann2::{ keyX: ['v1', 'v2'], keyY: ['v3', 'v4'] }
assert.equal(pos1, 0);
ionTextReader.next();
// ann1::{| key: valX } ann2::{ keyX: ['v1', 'v2'], keyY: ['v3', 'v4'] }
const pos2 = ionTextReader.position();
assert.equal(pos2, 7);
ionTextReader.stepIn();
ionTextReader.next();
// ann1::{ key: valX |} ann2::{ keyX: ['v1', 'v2'], keyY: ['v3', 'v4'] }
const pos7 = ionTextReader.position();
assert.equal(pos7, 18);
ionTextReader.stepOut();
ionTextReader.next();
// ann1::{ key: valX } ann2::{| keyX: ['v1', 'v2'], keyY: ['v3', 'v4'] }
const pos3 = ionTextReader.position();
assert.equal(pos3, 27);
ionTextReader.stepIn();
ionTextReader.next();
// ann1::{ key: valX } ann2::{ keyX: [|'v1', 'v2'], keyY: ['v3', 'v4'] }
const pos4 = ionTextReader.position();
assert.equal(pos4, 35);
ionTextReader.stepIn();
ionTextReader.next();
// ann1::{ key: valX } ann2::{ keyX: ['v1'|, 'v2'], keyY: ['v3', 'v4'] }
const pos5 = ionTextReader.position();
assert.equal(pos5, 39);
ionTextReader.stepOut();
// ann1::{ key: valX } ann2::{ keyX: ['v1', 'v2']|, keyY: ['v3', 'v4'] }
const pos6 = ionTextReader.position();
assert.equal(pos6, 46);
ionTextReader.stepOut();
// ann1::{ key: valX } ann2::{ keyX: ['v1', 'v2'], keyY: ['v3', 'v4'] }|
const pos8 = ionTextReader.position();
assert.equal(pos8, 68);
}
@test "get position from multi-byte" () {
// 's': \u0073
// '好': \u597d
// 'の': \u306e
// 'ç': \u00e7
// '👩': \ud83d \udc69
// '👩🏽': \ud83d \udc69 \ud83c \udffd
const reader: ion.Reader = ion.makeReader("\"s\" \"好\" \"の\" \"ç\" \"👩\" \"👩🏽\"");
const pos = [3, 7, 11, 15, 20, 27];
let i = 0;
while (reader.next()) {
assert.equal(reader.position(), pos[i++]);
}
}
} | the_stack |
import * as test_util from '../test_util';
import * as util from '../util';
import {NDArrayMathGPU} from './math_gpu';
import {Array1D, Array2D, Array3D, Array4D, NDArray, Scalar} from './ndarray';
import * as webgl_util from './webgl/webgl_util';
describe('NDArrayMathGPU scope', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
});
it('scope returns NDArray', () => {
const a = Array1D.new([1, 2, 3]);
let b = Array1D.new([0, 0, 0]);
const numUsedTexturesBefore = math.getTextureManager().getNumUsedTextures();
math.scope(() => {
const result = math.scope(() => {
b = math.add(a, b) as Array1D;
b = math.add(a, b) as Array1D;
b = math.add(a, b) as Array1D;
return math.add(a, b);
});
// a, b, and result are new textures. All intermediates should be
// disposed.
expect(math.getTextureManager().getNumUsedTextures())
.toEqual(numUsedTexturesBefore + 3);
expect(result.getValues()).toEqual(new Float32Array([4, 8, 12]));
});
// a, b are new textures, result should be disposed.
expect(math.getTextureManager().getNumUsedTextures())
.toEqual(numUsedTexturesBefore + 2);
a.dispose();
b.dispose();
});
it('scope returns NDArray[]', () => {
const a = Array1D.new([1, 2, 3]);
const b = Array1D.new([0, -1, 1]);
const numUsedTexturesBefore = math.getTextureManager().getNumUsedTextures();
math.scope(() => {
const result = math.scope(() => {
math.add(a, b);
return [math.add(a, b), math.sub(a, b)];
});
// a, b, and 2 results are new textures. All intermediates should be
// disposed.
expect(math.getTextureManager().getNumUsedTextures())
.toEqual(numUsedTexturesBefore + 4);
expect(result[0].getValues()).toEqual(new Float32Array([1, 1, 4]));
expect(result[1].getValues()).toEqual(new Float32Array([1, 3, 2]));
});
// a, b are new textures, result should be disposed.
expect(math.getTextureManager().getNumUsedTextures())
.toEqual(numUsedTexturesBefore + 2);
a.dispose();
b.dispose();
});
it('basic scope usage without return', () => {
const a = Array1D.new([1, 2, 3]);
let b = Array1D.new([0, 0, 0]);
const numUsedTexturesBefore = math.getTextureManager().getNumUsedTextures();
math.scope(() => {
b = math.add(a, b) as Array1D;
b = math.add(a, b) as Array1D;
b = math.add(a, b) as Array1D;
math.add(a, b);
});
const numUsedTexturesAfter = math.getTextureManager().getNumUsedTextures();
// original a and b, all intermediates should be disposed.
expect(numUsedTexturesAfter).toEqual(numUsedTexturesBefore + 2);
});
it('nested scope usage', () => {
const a = Array1D.new([1, 2, 3]);
let b = Array1D.new([0, 0, 0]);
const numUsedTexturesBefore = math.getTextureManager().getNumUsedTextures();
math.scope(() => {
const result = math.scope(() => {
b = math.add(a, b) as Array1D;
b = math.scope(() => {
b = math.scope(() => {
return math.add(a, b) as Array1D;
});
// a, original b, and two intermediate textures should be the only
// textures.
expect(math.getTextureManager().getNumUsedTextures())
.toEqual(numUsedTexturesBefore + 4);
math.scope(() => {
math.add(a, b);
});
// All the intermediates should be cleaned up.
expect(math.getTextureManager().getNumUsedTextures())
.toEqual(numUsedTexturesBefore + 4);
return math.add(a, b) as Array1D;
});
expect(math.getTextureManager().getNumUsedTextures())
.toEqual(numUsedTexturesBefore + 4);
return math.add(a, b) as Array1D;
});
// a, b, and result are new textures. All intermediates should be
// disposed.
expect(math.getTextureManager().getNumUsedTextures())
.toEqual(numUsedTexturesBefore + 3);
expect(result.getValues()).toEqual(new Float32Array([4, 8, 12]));
});
// a, b, are new textures, result should be disposed.
expect(math.getTextureManager().getNumUsedTextures())
.toEqual(numUsedTexturesBefore + 2);
});
});
describe('NDArrayMathGPU clone', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('returns a ndarray with the same shape and value', () => {
const a = Array2D.new([3, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9]);
const aPrime = math.clone(a);
expect(aPrime.shape).toEqual(a.shape);
expect(aPrime.getValues()).toEqual(a.getValues());
a.dispose();
});
it('returns a ndarray with a different texture handle', () => {
const a = Array2D.new([3, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9]);
const aPrime = math.clone(a);
expect(a.inGPU()).toEqual(true);
expect(aPrime.inGPU()).toEqual(true);
expect(aPrime.getTexture()).not.toBe(a.getTexture());
a.dispose();
});
});
describe('NDArrayMathGPU slice2D', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('slicing a 1x1 from a 1x1 returns a 1x1', () => {
const a = Array2D.new([1, 1], [0]);
const b = math.slice2D(a, [0, 0], [1, 1]);
expect(b.shape).toEqual([1, 1]);
a.dispose();
});
it('returns a ndarray of slice size', () => {
const a = Array2D.zeros([100, 100]);
const b = math.slice2D(a, [0, 0], [12, 34]);
expect(b.shape).toEqual([12, 34]);
a.dispose();
});
it('returns the upper-left submatrix when begin is [0, 0]', () => {
const a = NDArray.randUniform<Array2D>([10, 10], -1, 1);
const b = math.slice2D(a, [0, 0], [2, 2]);
const aValues = a.getValues();
const expected =
new Float32Array([aValues[0], aValues[1], aValues[10], aValues[11]]);
test_util.expectArraysClose(b.getValues(), expected, 0);
a.dispose();
});
it('returns the rectangle specified', () => {
const a = Array2D.new([4, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
const b = math.slice2D(a, [1, 1], [3, 2]);
const expected = new Float32Array([5, 6, 8, 9, 11, 12]);
expect(b.getValues()).toEqual(expected);
a.dispose();
});
it('throws when requesting out of bounds slice', () => {
const a = Array2D.new([4, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
expect(() => math.slice2D(a, [1, 1], [10, 10])).toThrowError();
a.dispose();
});
});
describe('NDArrayMathGPU copy2D', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('throws an error if source and dest shapes have different areas', () => {
const source = Array2D.zeros([100, 100]);
const dest = Array2D.zeros([100, 100]);
const sourceSize: [number, number] = [20, 20];
const destSize: [number, number] = [5, 5];
expect(
() => math.copy2D(source, [0, 0], sourceSize, dest, [0, 0], destSize))
.toThrowError();
source.dispose();
dest.dispose();
});
it('copies a src shape into a dst shape', () => {
const source = Array2D.new([3, 4], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
const dest = Array2D.zeros([6, 2]);
math.copy2D(source, [1, 1], [2, 3], dest, [2, 0], [3, 2]);
expect(dest.getValues()).toEqual(new Float32Array([
0, 0, 0, 0, 6, 7, 8, 10, 11, 12, 0, 0
]));
source.dispose();
dest.dispose();
});
it('throws when requesting out of bounds source copy', () => {
const source = Array2D.new([3, 4], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
const dest = Array2D.zeros([6, 2]);
expect(() => math.copy2D(source, [1, 1], [10, 10], dest, [2, 0], [
3, 2
])).toThrowError();
source.dispose();
dest.dispose();
});
it('throws when requesting out of bounds dest copy', () => {
const source = Array2D.new([3, 4], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
const dest = Array2D.zeros([6, 2]);
expect(() => math.copy2D(source, [1, 1], [2, 3], dest, [2, 0], [
3, 10
])).toThrowError();
source.dispose();
dest.dispose();
});
});
describe('NDArrayMathGPU scaledNDArrayAdd', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('with 2D ndarrays', () => {
const a = Array2D.new([2, 3], [2, 4, 6, 8, 10, 12]);
const b = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const c1 = Scalar.new(3);
const c2 = Scalar.new(2);
const expected = new Float32Array([8, 16, 24, 32, 40, 48]);
const result = math.scaledArrayAdd<Array2D>(c1, a, c2, b);
expect(result.shape).toEqual([2, 3]);
expect(result.getValues()).toEqual(expected);
a.dispose();
b.dispose();
c1.dispose();
c2.dispose();
});
it('with 3D ndarrays', () => {
const a = Array3D.new([2, 2, 2], [2, 4, 6, 8, 10, 12, 3, 5]);
const b = Array3D.new([2, 2, 2], [1, 2, 3, 4, 5, 6, 7, 8]);
const c1 = Scalar.new(3);
const c2 = Scalar.new(2);
const expected = new Float32Array([8, 16, 24, 32, 40, 48, 23, 31]);
const result = math.scaledArrayAdd<Array3D>(c1, a, c2, b);
expect(result.shape).toEqual([2, 2, 2]);
expect(result.getValues()).toEqual(expected);
a.dispose();
b.dispose();
c1.dispose();
c2.dispose();
});
it('throws when passed non-scalars', () => {
const a = Array2D.new([2, 3], [2, 4, 6, 8, 10, 12]);
const b = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const c1 = Array1D.randNormal([10]);
const c2 = Scalar.new(2);
expect(() => math.scaledArrayAdd<Array2D>(c1 as Scalar, a, c2, b))
.toThrowError();
expect(() => math.scaledArrayAdd<Array2D>(c2, a, c1 as Scalar, b))
.toThrowError();
a.dispose();
b.dispose();
c1.dispose();
c2.dispose();
});
it('throws when NDArrays are different shape', () => {
const a = Array2D.new([2, 3], [2, 4, 6, 8, 10, 12]);
const b = Array2D.new([2, 4], [1, 2, 3, 4, 5, 6, 7, 8]);
const c1 = Scalar.new(3);
const c2 = Scalar.new(2);
expect(() => math.scaledArrayAdd<Array2D>(c1, a, c2, b)).toThrowError();
a.dispose();
b.dispose();
c1.dispose();
c2.dispose();
});
});
describe('NDArrayMathGPU concat3D', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('concat axis=0', () => {
const axis = 0;
const x1 = Array3D.new([1, 2, 3], [1, 11, 111, 2, 22, 222]);
const x2 = Array3D.new(
[2, 2, 3], [5, 55, 555, 6, 66, 666, 7, 77, 777, 8, 88, 888]);
const y = math.concat3D(x1, x2, axis);
expect(y.shape).toEqual([3, 2, 3]);
expect(y.getValues()).toEqual(new Float32Array([
1, 11, 111, 2, 22, 222, 5, 55, 555, 6, 66, 666, 7, 77, 777, 8, 88, 888
]));
});
it('concat axis=1', () => {
const axis = 1;
const x1 = Array3D.new([2, 1, 3], [1, 11, 111, 3, 33, 333]);
const x2 = Array3D.new(
[2, 2, 3], [5, 55, 555, 6, 66, 666, 7, 77, 777, 8, 88, 888]);
const result = math.concat3D(x1, x2, axis);
expect(result.shape).toEqual([2, 3, 3]);
expect(result.getValues()).toEqual(new Float32Array([
1, 11, 111, 5, 55, 555, 6, 66, 666, 3, 33, 333, 7, 77, 777, 8, 88, 888
]));
});
it('concat axis=2', () => {
const axis = 2;
const x1 = Array3D.new([2, 2, 2], [1, 11, 2, 22, 3, 33, 4, 44]);
const x2 = Array3D.new(
[2, 2, 3], [5, 55, 555, 6, 66, 666, 7, 77, 777, 8, 88, 888]);
const result = math.concat3D(x1, x2, axis);
expect(result.shape).toEqual([2, 2, 5]);
expect(result.getValues()).toEqual(new Float32Array([
1, 11, 5, 55, 555, 2, 22, 6, 66, 666,
3, 33, 7, 77, 777, 4, 44, 8, 88, 888
]));
});
it('concat throws when invalid non-axis shapes, axis=0', () => {
const axis = 0;
const x1 = Array3D.new([1, 1, 3], [1, 11, 111]);
const x2 = Array3D.new(
[2, 2, 3], [5, 55, 555, 6, 66, 666, 7, 77, 777, 8, 88, 888]);
expect(() => math.concat3D(x1, x2, axis)).toThrowError();
});
it('concat throws when invalid non-axis shapes, axis=1', () => {
const axis = 1;
const x1 = Array3D.new([1, 1, 3], [1, 11, 111]);
const x2 = Array3D.new(
[2, 2, 3], [5, 55, 555, 6, 66, 666, 7, 77, 777, 8, 88, 888]);
expect(() => math.concat3D(x1, x2, axis)).toThrowError();
});
it('concat throws when invalid non-axis shapes, axis=2', () => {
const axis = 2;
const x1 = Array3D.new([1, 2, 2], [1, 11, 2, 22]);
const x2 = Array3D.new(
[2, 2, 3], [5, 55, 555, 6, 66, 666, 7, 77, 777, 8, 88, 888]);
expect(() => math.concat3D(x1, x2, axis)).toThrowError();
});
});
describe('NDArrayMathGPU matMul', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('multiplies matrices', () => {
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const b = Array2D.new([3, 2], [0, 1, -3, 2, 2, 1]);
const c = math.matMul(a, b);
expect(c.shape).toEqual([2, 2]);
expect(c.getValues()).toEqual(new Float32Array([0, 8, -3, 20]));
a.dispose();
b.dispose();
c.dispose();
});
it('with implicit texture reshaping on GPU', () => {
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
// Make the texture shape different than the logical shape on purpose.
expect(a.getTextureShapeRC([6, 1])).toEqual([6, 1]);
const b = Array2D.new([3, 2], [1, 3, 0, 1, 2, 0]);
expect(b.getTextureShapeRC()).toEqual([3, 2]);
// Matmul should do implicit texture reshape on ndarray A in order to
// do the right logical multiplication.
const result = math.matMul(a, b);
expect(result.shape).toEqual([2, 2]);
expect(result.getTextureShapeRC()).toEqual([2, 2]);
expect(result.getValues()).toEqual(new Float32Array([7, 5, 16, 17]));
a.dispose();
b.dispose();
});
it('matmul throws when inner dimensions dont match', () => {
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const b = Array2D.new([4, 2], [0, 1, -3, 2, 2, 1, 2, 2]);
expect(() => math.matMul(a, b)).toThrowError();
a.dispose();
b.dispose();
});
it('matmul throws when passed non matrices', () => {
// tslint:disable-next-line:no-any
const a: any =
Array3D.new([2, 3, 2], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
const b = Array2D.new([4, 2], [0, 1, -3, 2, 2, 1, 2, 2]);
expect(() => math.matMul(a, b)).toThrowError();
expect(() => math.matMul(b, a)).toThrowError();
a.dispose();
b.dispose();
});
it('Vector times matrix', () => {
const v = Array1D.new([2, 3]);
const matrix = Array2D.new([2, 2], [1, 2, 3, 4]);
const result = math.vectorTimesMatrix(v, matrix);
const expected = new Float32Array([11, 16]);
expect(result.getValues()).toEqual(expected);
v.dispose();
matrix.dispose();
result.dispose();
});
it('Vector times matrix with implicit reshape', () => {
const v = Array1D.new([2, 3]);
// Make the texture shape be column on purpose.
expect(v.getTextureShapeRC([2, 1])).toEqual([2, 1]);
const matrix = Array2D.new([2, 2], [1, 2, 3, 4]);
const result = math.vectorTimesMatrix(v, matrix);
const expected = new Float32Array([11, 16]);
expect(result.getValues()).toEqual(expected);
v.dispose();
matrix.dispose();
});
it('Vector times matrix throws when not passed a vector', () => {
// tslint:disable-next-line:no-any
const v: any = Array2D.new([2, 2], [1, 2, 3, 4]);
const matrix = Array2D.new([2, 2], [1, 2, 3, 4]);
expect(() => math.vectorTimesMatrix(v, matrix)).toThrowError();
});
it('Vector times matrix throws when not passed a matrix', () => {
const v = Array1D.new([2, 3]);
// tslint:disable-next-line:no-any
const matrix: any = Array3D.new([2, 2, 2], [1, 2, 3, 4, 5, 6, 7, 8]);
expect(() => math.vectorTimesMatrix(v, matrix)).toThrowError();
});
it('Matrix times vector', () => {
const matrix = Array2D.new([2, 2], [1, 2, 3, 4]);
const v = Array1D.new([2, 3]);
const result = math.matrixTimesVector(matrix, v);
const expected = new Float32Array([8, 18]);
expect(result.getValues()).toEqual(expected);
matrix.dispose();
v.dispose();
});
it('Matrix times vector, larger than max texture size', () => {
const maxTexSize =
webgl_util.queryMaxTextureSize(math.getGPGPUContext().gl);
const matrix = Array2D.zeros([1, maxTexSize + 4]);
matrix.fill(1);
const v = Array1D.zeros([maxTexSize + 4]);
v.fill(1);
const result = math.matrixTimesVector(matrix, v);
const expected = new Float32Array([maxTexSize + 4]);
expect(result.getValues()).toEqual(expected);
matrix.dispose();
v.dispose();
});
it('Matrix * vector propagates NaNs', () => {
const matrix = Array2D.new([2, 2], [1, 2, 3, 4]);
const v = Array1D.new([2, NaN]);
const result = math.matrixTimesVector(matrix, v);
const expected = new Float32Array([NaN, NaN]);
expect(result.getValues()).toEqual(expected);
matrix.dispose();
v.dispose();
});
it('Matrix times vector with implicit reshape', () => {
const matrix = Array2D.new([2, 2], [1, 2, 3, 4]);
const v = Array1D.new([2, 3]);
// Make the texture shape be row on purpose.
expect(v.getTextureShapeRC([1, 2])).toEqual([1, 2]);
const result = math.matrixTimesVector(matrix, v);
const expected = new Float32Array([8, 18]);
expect(result.getValues()).toEqual(expected);
matrix.dispose();
v.dispose();
});
it('matrix times vector throws when not passed a vector', () => {
// tslint:disable-next-line:no-any
const v: any = Array2D.new([2, 2], [1, 2, 3, 4]);
const matrix = Array2D.new([2, 2], [1, 2, 3, 4]);
expect(() => math.matrixTimesVector(matrix, v)).toThrowError();
});
it('matrix times vector throws when not passed a matrix', () => {
const v = Array1D.new([2, 3]);
// tslint:disable-next-line:no-any
const matrix: any = Array3D.new([2, 2, 2], [1, 2, 3, 4, 5, 6, 7, 8]);
expect(() => math.matrixTimesVector(matrix, v)).toThrowError();
});
it('Dot product', () => {
const v1 = Array1D.new([2, 3]);
const v2 = Array1D.new([2, 1]);
const result = math.dotProduct(v1, v2);
expect(result.get()).toEqual(7);
v1.dispose();
v2.dispose();
result.dispose();
});
it('Dot product propagates NaNs', () => {
const v1 = Array1D.new([2, NaN]);
const v2 = Array1D.new([2, 1]);
const result = math.dotProduct(v1, v2);
expect(result.get()).toEqual(NaN);
v1.dispose();
v2.dispose();
});
it('Dot product with implicit reshaping', () => {
const v1 = Array1D.new([2, 3]);
// Make the texture shape be column on purpose.
expect(v1.getTextureShapeRC([2, 1])).toEqual([2, 1]);
const v2 = Array1D.new([2, 1]);
// Make the texture shape be row on purpose.
expect(v2.getTextureShapeRC([1, 2])).toEqual([1, 2]);
const result = math.dotProduct(v1, v2);
expect(result.get()).toEqual(7);
v1.dispose();
v2.dispose();
});
it('Dot product throws when vectors are different size', () => {
const v1 = Array1D.new([2, 3, 3]);
const v2 = Array1D.new([2, 1]);
expect(() => math.dotProduct(v1, v2)).toThrowError();
expect(() => math.dotProduct(v2, v1)).toThrowError();
v1.dispose();
v2.dispose();
});
it('Dot product throws when passed non vectors', () => {
// tslint:disable-next-line:no-any
const v1: any = Array2D.new([2, 2], [1, 2, 3, 3]);
const v2 = Array1D.new([2, 1]);
expect(() => math.dotProduct(v1, v2)).toThrowError();
expect(() => math.dotProduct(v2, v1)).toThrowError();
v1.dispose();
v2.dispose();
});
it('Outer product', () => {
const v1 = Array1D.new([2, 3]);
const v2 = Array1D.new([2, 1]);
const result = math.outerProduct(v1, v2);
const expected = new Float32Array([4, 2, 6, 3]);
expect(result.shape).toEqual([2, 2]);
expect(result.getValues()).toEqual(expected);
v1.dispose();
v2.dispose();
});
it('Outer product with implicit reshape', () => {
const v1 = Array1D.new([2, 3]);
// Make the texture shape be row on purpose.
expect(v1.getTextureShapeRC([1, 2])).toEqual([1, 2]);
const v2 = Array1D.new([2, 1]);
// Make the texture shape be column on purpose.
expect(v2.getTextureShapeRC([2, 1])).toEqual([2, 1]);
const result = math.outerProduct(v1, v2);
const expected = new Float32Array([4, 2, 6, 3]);
expect(result.shape).toEqual([2, 2]);
expect(result.getValues()).toEqual(expected);
v1.dispose();
v2.dispose();
});
});
describe('NDArrayMathGPU element-wise mul/div', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('multiplies same-shaped ndarrays', () => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array2D.new([2, 2], [5, 3, 4, -7]);
const expected = new Float32Array([5, 6, -12, 28]);
const result = math.elementWiseMul(a, b);
expect(result.shape).toEqual([2, 2]);
expect(result.inGPU()).toBe(true);
expect(result.getValues()).toEqual(expected);
expect(result.inGPU()).toBe(false);
a.dispose();
b.dispose();
});
it('propagates NaNs', () => {
const a = Array2D.new([2, 2], [1, 3, 4, 0]);
const b = Array2D.new([2, 2], [NaN, 3, NaN, 3]);
const result = math.elementWiseMul(a, b).getValues();
expect(result).toEqual(new Float32Array([NaN, 9, NaN, 0]));
a.dispose();
b.dispose();
});
it('mul throws when passed ndarrays of different shapes', () => {
const a = Array2D.new([2, 3], [1, 2, -3, -4, 5, 6]);
const b = Array2D.new([2, 2], [5, 3, 4, -7]);
expect(() => math.elementWiseMul(a, b)).toThrowError();
expect(() => math.elementWiseMul(b, a)).toThrowError();
a.dispose();
b.dispose();
});
it('divide', () => {
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const c = Array2D.new([2, 3], [1, 2, 3, 4, 2, 5]);
const r = math.divide(a, c);
expect(r.get(0, 0)).toBeCloseTo(1);
expect(r.get(0, 1)).toBeCloseTo(1);
expect(r.get(0, 2)).toBeCloseTo(1);
expect(r.get(1, 0)).toBeCloseTo(1);
expect(r.get(1, 1)).toBeCloseTo(2.5);
expect(r.get(1, 2)).toBeCloseTo(6 / 5);
a.dispose();
c.dispose();
});
it('divide propagates NaNs', () => {
const a = Array2D.new([2, 1], [1, 2]);
const c = Array2D.new([2, 1], [3, NaN]);
const r = math.divide(a, c).getValues();
expect(r[0]).toBeCloseTo(1 / 3);
expect(r[1]).toEqual(NaN);
a.dispose();
c.dispose();
});
it('div throws when passed ndarrays of different shapes', () => {
const a = Array2D.new([2, 3], [1, 2, -3, -4, 5, 6]);
const b = Array2D.new([2, 2], [5, 3, 4, -7]);
expect(() => math.divide(a, b)).toThrowError();
expect(() => math.divide(b, a)).toThrowError();
a.dispose();
b.dispose();
});
it('scalar divided by array', () => {
const c = Scalar.new(2);
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const r = math.scalarDividedByArray(c, a);
expect(r.get(0, 0)).toBeCloseTo(2 / 1);
expect(r.get(0, 1)).toBeCloseTo(2 / 2);
expect(r.get(0, 2)).toBeCloseTo(2 / 3);
expect(r.get(1, 0)).toBeCloseTo(2 / 4);
expect(r.get(1, 1)).toBeCloseTo(2 / 5);
expect(r.get(1, 2)).toBeCloseTo(2 / 6);
a.dispose();
c.dispose();
});
it('scalar divided by array propagates NaNs', () => {
const c = Scalar.new(NaN);
const a = Array2D.new([1, 3], [1, 2, 3]);
const r = math.scalarDividedByArray(c, a).getValues();
expect(r).toEqual(new Float32Array([NaN, NaN, NaN]));
a.dispose();
c.dispose();
});
it('scalar divided by array throws when passed non scalar', () => {
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3]);
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
expect(() => math.scalarDividedByArray(c, a)).toThrowError();
a.dispose();
c.dispose();
});
it('array divided by scalar', () => {
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const c = Scalar.new(2);
const r = math.arrayDividedByScalar(a, c);
expect(r.get(0, 0)).toBeCloseTo(1 / 2);
expect(r.get(0, 1)).toBeCloseTo(2 / 2);
expect(r.get(0, 2)).toBeCloseTo(3 / 2);
expect(r.get(1, 0)).toBeCloseTo(4 / 2);
expect(r.get(1, 1)).toBeCloseTo(5 / 2);
expect(r.get(1, 2)).toBeCloseTo(6 / 2);
a.dispose();
c.dispose();
});
it('array divided by scalar propagates NaNs', () => {
const a = Array2D.new([1, 3], [1, 2, NaN]);
const c = Scalar.new(2);
const r = math.arrayDividedByScalar(a, c).getValues();
expect(r[0]).toBeCloseTo(1 / 2);
expect(r[1]).toBeCloseTo(2 / 2);
expect(r[2]).toEqual(NaN);
a.dispose();
c.dispose();
});
it('array divided by scalar throws when passed non scalar', () => {
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3]);
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
expect(() => math.arrayDividedByScalar(a, c)).toThrowError();
a.dispose();
c.dispose();
});
});
describe('NDArrayMathGPU unary ops', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('relu', () => {
const a = Array1D.new([1, -2, 0, 3, -0.1]);
const result = math.relu(a);
expect(result.getValues()).toEqual(new Float32Array([1, 0, 0, 3, 0]));
a.dispose();
});
it('relu propagates NaNs', () => {
const a = Array1D.new([1, -2, 0, 3, -0.1, NaN]);
const result = math.relu(a);
expect(result.getValues()).toEqual(new Float32Array([1, 0, 0, 3, 0, NaN]));
a.dispose();
});
it('step with 1d ndarray', () => {
const a = Array1D.new([1, -2, 0, 3, -0.1]);
const result = math.step(a);
expect(result.getValues()).toEqual(new Float32Array([1, 0, 0, 1, 0]));
a.dispose();
});
it('step with 2d ndarray', () => {
const a = Array2D.new([2, 2], [1, -5, -3, 4]);
const result = math.step(a);
expect(result.shape).toEqual([2, 2]);
expect(result.getValues()).toEqual(new Float32Array([1, 0, 0, 1]));
a.dispose();
});
it('step propagates NaNs', () => {
const a = Array1D.new([1, -2, 0, 3, NaN]);
const result = math.step(a);
expect(result.getValues()).toEqual(new Float32Array([1, 0, 0, 1, NaN]));
a.dispose();
});
it('neg', () => {
const a = Array1D.new([1, -3, 2, 7, -4]);
const result = math.neg(a);
expect(result.getValues()).toEqual(new Float32Array([-1, 3, -2, -7, 4]));
a.dispose();
});
it('neg propagate NaNs', () => {
const a = Array1D.new([1, -3, 2, 7, NaN]);
const expected = [-1, 3, -2, -7, NaN];
expect(math.neg(a).getValues()).toEqual(new Float32Array(expected));
a.dispose();
});
it('tanh', () => {
const values = [1, -3, 2, 7, -4];
const a = Array1D.new(values);
const result = math.tanh(a);
const expected = new Float32Array(a.size);
for (let i = 0; i < a.size; i++) {
expected[i] = util.tanh(values[i]);
}
test_util.expectArraysClose(result.getValues(), expected, 1e-6);
a.dispose();
});
it('tanh propagates NaNs', () => {
const a = Array1D.new([4, NaN, 0]);
const res = math.tanh(a).getValues();
const expected = [util.tanh(4), NaN, util.tanh(0)];
test_util.expectArraysClose(res, new Float32Array(expected), 1e-5);
a.dispose();
});
it('sigmoid', () => {
const values = [1, -3, 2, 7, -4];
const a = Array1D.new(values);
const result = math.sigmoid(a);
const expected = new Float32Array(a.size);
for (let i = 0; i < a.size; i++) {
expected[i] = 1 / (1 + Math.exp(-values[i]));
}
test_util.expectArraysClose(result.getValues(), expected, 1e-6);
a.dispose();
});
it('sigmoid propagates NaNs', () => {
const a = Array1D.new([3, NaN]);
const res = math.sigmoid(a).getValues();
test_util.expectArraysClose(
res, new Float32Array([1 / (1 + Math.exp(-3)), NaN]), 1e-5);
a.dispose();
});
it('sin', () => {
const values = [1, -3, 2, 7, -4];
const a = Array1D.new(values);
const result = math.sin(a);
const expected = new Float32Array(a.size);
for (let i = 0; i < a.size; i++) {
expected[i] = Math.sin(values[i]);
}
test_util.expectArraysClose(result.getValues(), expected, 1e-3);
a.dispose();
});
it('sin propagates NaNs', () => {
const a = Array1D.new([4, NaN, 0]);
const res = math.sin(a).getValues();
const expected = [Math.sin(4), NaN, Math.sin(0)];
test_util.expectArraysClose(res, new Float32Array(expected), 1e-4);
a.dispose();
});
});
describe('NDArrayMathGPU min/max', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('max with one element dominating', () => {
const a = Array1D.new([3, -1, 0, 100, -7, 2]);
const r = math.max(a);
expect(r.get()).toBe(100);
a.dispose();
});
it('max with all elements being the same', () => {
const a = Array1D.new([3, 3, 3]);
const r = math.max(a);
expect(r.get()).toBe(3);
a.dispose();
});
it('max propagates NaNs', () => {
expect(math.max(Array1D.new([3, NaN, 2])).get()).toEqual(NaN);
});
it('min Array1D', () => {
const a = Array1D.new([3, -1, 0, 100, -7, 2]);
expect(math.min(a).get()).toBe(-7);
a.dispose();
});
it('min propagates NaNs', () => {
const a = Array1D.new([3, NaN, 2]);
expect(math.min(a).get()).toEqual(NaN);
a.dispose();
});
});
describe('NDArrayMathGPU scalar and element-wise', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('c + A', () => {
const c = Scalar.new(5);
const a = Array1D.new([1, 2, 3]);
const result = math.scalarPlusArray(c, a);
expect(result.getValues()).toEqual(new Float32Array([6, 7, 8]));
a.dispose();
c.dispose();
});
it('c + A propagates NaNs', () => {
const c = Scalar.new(NaN);
const a = Array1D.new([1, 2, 3]);
const res = math.scalarPlusArray(c, a).getValues();
expect(res).toEqual(new Float32Array([NaN, NaN, NaN]));
a.dispose();
c.dispose();
});
it('c + A throws when passed non scalar', () => {
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3]);
const a = Array1D.new([1, 2, 3]);
expect(() => math.scalarPlusArray(c, a)).toThrowError();
a.dispose();
c.dispose();
});
it('c - A', () => {
const c = Scalar.new(5);
const a = Array1D.new([7, 2, 3]);
const result = math.scalarMinusArray(c, a);
expect(result.getValues()).toEqual(new Float32Array([-2, 3, 2]));
a.dispose();
c.dispose();
});
it('c - A throws when passed non scalar', () => {
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3]);
const a = Array1D.new([1, 2, 3]);
expect(() => math.scalarMinusArray(c, a)).toThrowError();
a.dispose();
c.dispose();
});
it('A - c', () => {
const a = Array1D.new([1, 2, -3]);
const c = Scalar.new(5);
const result = math.arrayMinusScalar(a, c);
expect(result.getValues()).toEqual(new Float32Array([-4, -3, -8]));
a.dispose();
c.dispose();
result.dispose();
});
it('A - c propagates NaNs', () => {
const a = Array1D.new([1, NaN, 3]);
const c = Scalar.new(5);
const res = math.arrayMinusScalar(a, c).getValues();
expect(res).toEqual(new Float32Array([-4, NaN, -2]));
a.dispose();
c.dispose();
});
it('A - c throws when passed non scalar', () => {
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3]);
const a = Array1D.new([1, 2, 3]);
expect(() => math.arrayMinusScalar(a, c)).toThrowError();
a.dispose();
c.dispose();
});
it('A - B', () => {
const a = Array1D.new([2, 5, 1]);
const b = Array1D.new([4, 2, -1]);
const expected = new Float32Array([-2, 3, 2]);
const result = math.sub(a, b);
expect(result.getValues()).toEqual(expected);
a.dispose();
b.dispose();
});
it('A - B propagates NaNs', () => {
const a = Array1D.new([2, 5, 1]);
const b = Array1D.new([4, NaN, -1]);
const res = math.sub(a, b).getValues();
expect(res).toEqual(new Float32Array([-2, NaN, 2]));
a.dispose();
b.dispose();
});
it('A - B throws when passed ndarrays with different shape', () => {
const a = Array1D.new([2, 5, 1, 5]);
const b = Array1D.new([4, 2, -1]);
expect(() => math.sub(a, b)).toThrowError();
expect(() => math.sub(b, a)).toThrowError();
a.dispose();
b.dispose();
});
it('A + B', () => {
const a = Array1D.new([2, 5, 1]);
const b = Array1D.new([4, 2, -1]);
const expected = new Float32Array([6, 7, 0]);
const result = math.add(a, b);
expect(result.getValues()).toEqual(expected);
a.dispose();
b.dispose();
});
it('A + B propagates NaNs', () => {
const a = Array1D.new([2, 5, NaN]);
const b = Array1D.new([4, 2, -1]);
const res = math.add(a, b).getValues();
expect(res).toEqual(new Float32Array([6, 7, NaN]));
a.dispose();
b.dispose();
});
it('A + B throws when passed ndarrays with different shape', () => {
const a = Array1D.new([2, 5, 1, 5]);
const b = Array1D.new([4, 2, -1]);
expect(() => math.add(a, b)).toThrowError();
expect(() => math.add(b, a)).toThrowError();
a.dispose();
b.dispose();
});
});
describe('NDArrayMathGPU scalarTimesNDArray', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('scalar times ndarray', () => {
const a = Array2D.new([3, 2], [2, -5, 1, 1, 4, 0]);
const c = Scalar.new(2);
const expected = new Float32Array([4, -10, 2, 2, 8, 0]);
const result = math.scalarTimesArray(c, a);
expect(result.shape).toEqual([3, 2]);
expect(result.getValues()).toEqual(expected);
a.dispose();
c.dispose();
});
it('scalar times ndarray throws when passed non-scalar', () => {
const a = Array2D.new([3, 2], [2, -5, 1, 1, 4, 0]);
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3, 4]);
expect(() => math.scalarTimesArray(c, a)).toThrowError();
a.dispose();
c.dispose();
});
});
describe('NDArrayMathGPU log/exp', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('exp', () => {
const a = Array1D.new([1, 2, 0]);
const r = math.exp(a);
expect(r.get(0)).toBeCloseTo(Math.exp(1));
expect(r.get(1)).toBeCloseTo(Math.exp(2));
expect(r.get(2)).toBeCloseTo(1);
a.dispose();
});
it('exp propagates NaNs', () => {
const a = Array1D.new([1, NaN, 0]);
const r = math.exp(a).getValues();
expect(r).toEqual(new Float32Array([Math.exp(1), NaN, 1]));
a.dispose();
});
it('log', () => {
const a = Array1D.new([1, 2]);
const r = math.log(a);
expect(r.get(0)).toBeCloseTo(Math.log(1));
expect(r.get(1)).toBeCloseTo(Math.log(2));
a.dispose();
});
it('log propagates NaNs', () => {
const a = Array1D.new([1, NaN]);
const r = math.log(a).getValues();
expect(r).toEqual(new Float32Array([Math.log(1), NaN]));
a.dispose();
});
it('logSumExp', () => {
const a = Array1D.new([1, 2, -3]);
const result = math.logSumExp(a);
expect(result.get())
.toBeCloseTo(Math.log(Math.exp(1) + Math.exp(2) + Math.exp(-3)));
a.dispose();
result.dispose();
});
it('logSumExp propagates NaNs', () => {
const a = Array1D.new([1, 2, NaN]);
const result = math.logSumExp(a);
expect(result.get()).toEqual(NaN);
a.dispose();
});
});
describe('softmax', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('regular test', () => {
const y = math.softmax(Array1D.new([2, 1, 3]));
expect(y.get(0)).toBeCloseTo(0.24472847, 6);
expect(y.get(1)).toBeCloseTo(0.09003057, 6);
expect(y.get(2)).toBeCloseTo(0.66524095, 6);
expect(y.get(0) + y.get(1) + y.get(2)).toBeCloseTo(1, 6);
});
it('overflow', () => {
const y = math.softmax(Array1D.new([10000, 10000]));
expect(y.get(0)).toBeCloseTo(0.5, 3);
expect(y.get(1)).toBeCloseTo(0.5, 3);
});
it('underflow', () => {
const y = math.softmax(Array1D.new([-10000, -10000]));
expect(y.get(0)).toBeCloseTo(0.5, 3);
expect(y.get(1)).toBeCloseTo(0.5, 3);
});
it('Huge difference between probabilities', () => {
const y = math.softmax(Array1D.new([-10000, +10000]));
expect(y.get(0)).toBeCloseTo(0.0, 6);
expect(y.get(1)).toBeCloseTo(1, 6);
});
it('Propagates NaNs', () => {
const a = Array1D.new([2, 1, NaN]);
const y = math.softmax(a);
expect(y.getValues()).toEqual(new Float32Array([NaN, NaN, NaN]));
a.dispose();
});
});
describe('NDArrayMathGPU sum', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('sum', () => {
const a = Array2D.new([3, 2], [1, 2, 3, 0, 0, 1]);
const result = math.sum(a);
expect(result.get()).toBe(7);
a.dispose();
});
it('propagates NaNs', () => {
const a = Array2D.new([3, 2], [1, 2, 3, NaN, 0, 1]);
expect(math.sum(a).get()).toEqual(NaN);
a.dispose();
});
});
describe('NDArrayMathGPU argmax', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('Array1D', () => {
const a = Array1D.new([1, 0, 3, 2]);
const result = math.argMax(a);
expect(result.get()).toBe(2);
a.dispose();
});
it('propagates NaNs', () => {
const a = Array1D.new([5, 0, 3, NaN, 3]);
expect(math.argMax(a).get()).toEqual(NaN);
a.dispose();
});
});
describe('NDArrayMathGPU argmin', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('argmin', () => {
const a = Array1D.new([1, 0, 3, 2]);
const result = math.argMin(a);
expect(result.get()).toBe(1);
a.dispose();
});
it('Arg min propagates NaNs', () => {
const a = Array1D.new([5, 0, NaN, 7, 3]);
expect(math.argMin(a).get()).toEqual(NaN);
a.dispose();
});
});
describe('NDArrayMathGPU argmax equals', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('equals', () => {
const a = Array1D.new([5, 0, 3, 7, 3]);
const b = Array1D.new([-100.3, -20.0, -10.0, -5, -100]);
const result = math.argMaxEquals(a, b);
expect(result.get()).toBe(1);
});
it('not equals', () => {
const a = Array1D.new([5, 0, 3, 1, 3]);
const b = Array1D.new([-100.3, -20.0, -10.0, -5, 0]);
const result = math.argMaxEquals(a, b);
expect(result.get()).toBe(0);
});
it('propagates NaNs', () => {
const a = Array1D.new([0, 3, 1, 3]);
const b = Array1D.new([NaN, -20.0, -10.0, -5]);
const result = math.argMaxEquals(a, b);
expect(result.get()).toEqual(NaN);
});
it('throws when given arrays of different shape', () => {
const a = Array1D.new([5, 0, 3, 7, 3, 10]);
const b = Array1D.new([-100.3, -20.0, -10.0, -5, -100]);
expect(() => math.argMaxEquals(a, b)).toThrowError();
});
});
describe('NDArrayMathGPU conv2d', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('input=2x2x1,d2=1,f=1,s=1,p=0', () => {
const inputDepth = 1;
const inputShape: [number, number, number] = [2, 2, inputDepth];
const outputDepth = 1;
const fSize = 1;
const pad = 0;
const stride = 1;
const x = Array3D.new(inputShape, [1, 2, 3, 4]);
const w = Array4D.new([fSize, fSize, inputDepth, outputDepth], [2]);
const bias = Array1D.new([-1]);
const result = math.conv2d(x, w, bias, stride, pad);
const expected = new Float32Array([1, 3, 5, 7]);
expect(result.inGPU()).toBe(true);
expect(result.getValues()).toEqual(expected);
x.dispose();
w.dispose();
bias.dispose();
});
it('input=2x2x1,d2=1,f=2,s=1,p=0', () => {
const inputDepth = 1;
const inputShape: [number, number, number] = [2, 2, inputDepth];
const outputDepth = 1;
const fSize = 2;
const pad = 0;
const stride = 1;
const x = Array3D.new(inputShape, [1, 2, 3, 4]);
const w =
Array4D.new([fSize, fSize, inputDepth, outputDepth], [3, 1, 5, 0]);
const bias = Array1D.new([-1]);
const result = math.conv2d(x, w, bias, stride, pad);
const expected = new Float32Array([19]);
expect(result.inGPU()).toBe(true);
expect(result.getValues()).toEqual(expected);
x.dispose();
w.dispose();
bias.dispose();
});
it('throws when x is not rank 3', () => {
const inputDepth = 1;
const outputDepth = 1;
const fSize = 2;
const pad = 0;
const stride = 1;
// tslint:disable-next-line:no-any
const x: any = Array2D.new([2, 2], [1, 2, 3, 4]);
const w =
Array4D.new([fSize, fSize, inputDepth, outputDepth], [3, 1, 5, 0]);
const bias = Array1D.new([-1]);
expect(() => math.conv2d(x, w, bias, stride, pad)).toThrowError();
x.dispose();
w.dispose();
bias.dispose();
});
it('throws when weights is not rank 4', () => {
const inputDepth = 1;
const inputShape: [number, number, number] = [2, 2, inputDepth];
const pad = 0;
const stride = 1;
const x = Array3D.new(inputShape, [1, 2, 3, 4]);
// tslint:disable-next-line:no-any
const w: any = Array3D.new([2, 2, 1], [3, 1, 5, 0]);
const bias = Array1D.new([-1]);
expect(() => math.conv2d(x, w, bias, stride, pad)).toThrowError();
x.dispose();
w.dispose();
bias.dispose();
});
it('throws when biases is not rank 1', () => {
const inputDepth = 1;
const inputShape: [number, number, number] = [2, 2, inputDepth];
const outputDepth = 1;
const fSize = 2;
const pad = 0;
const stride = 1;
const x = Array3D.new(inputShape, [1, 2, 3, 4]);
const w =
Array4D.new([fSize, fSize, inputDepth, outputDepth], [3, 1, 5, 0]);
// tslint:disable-next-line:no-any
const bias: any = Array2D.new([2, 2], [2, 2, 2, 2]);
expect(() => math.conv2d(x, w, bias, stride, pad)).toThrowError();
x.dispose();
w.dispose();
bias.dispose();
});
it('throws when x depth does not match weight depth', () => {
const inputDepth = 1;
const wrongInputDepth = 5;
const inputShape: [number, number, number] = [2, 2, inputDepth];
const outputDepth = 1;
const fSize = 2;
const pad = 0;
const stride = 1;
const x = Array3D.new(inputShape, [1, 2, 3, 4]);
const w = NDArray.randNormal<Array4D>(
[fSize, fSize, wrongInputDepth, outputDepth]);
const bias = Array1D.new([-1]);
expect(() => math.conv2d(x, w, bias, stride, pad)).toThrowError();
x.dispose();
w.dispose();
bias.dispose();
});
});
describe('NDArrayMathGPU conv2dTranspose', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('input=2x2x1,d2=1,f=2,s=1,p=0', () => {
const origInputDepth = 1;
const origOutputDepth = 1;
const inputShape: [number, number, number] = [1, 1, origOutputDepth];
const fSize = 2;
const origPad = 0;
const origStride = 1;
const x = Array3D.new(inputShape, [2]);
const w = Array4D.new(
[fSize, fSize, origInputDepth, origOutputDepth], [3, 1, 5, 0]);
const b = Array1D.new([1]);
const result = math.conv2dTranspose(x, w, b, origStride, origPad);
const expected = new Float32Array([7, 3, 11, 1]);
expect(result.inGPU()).toBe(true);
expect(result.shape).toEqual([2, 2, 1]);
expect(result.getValues()).toEqual(expected);
x.dispose();
w.dispose();
b.dispose();
});
it('throws when x is not rank 3', () => {
const origInputDepth = 1;
const origOutputDepth = 1;
const fSize = 2;
const origPad = 0;
const origStride = 1;
// tslint:disable-next-line:no-any
const x: any = Array2D.new([2, 1], [2, 2]);
const w = Array4D.new(
[fSize, fSize, origInputDepth, origOutputDepth], [3, 1, 5, 0]);
const b = Array1D.new([1]);
expect(() => math.conv2dTranspose(x, w, b, origStride, origPad))
.toThrowError();
x.dispose();
w.dispose();
b.dispose();
});
it('throws when weights is not rank 4', () => {
const origInputDepth = 1;
const origOutputDepth = 1;
const inputShape: [number, number, number] = [1, 1, origOutputDepth];
const fSize = 2;
const origPad = 0;
const origStride = 1;
const x = Array3D.new(inputShape, [2]);
// tslint:disable-next-line:no-any
const w: any = Array3D.new([fSize, fSize, origInputDepth], [3, 1, 5, 0]);
const b = Array1D.new([1]);
expect(() => math.conv2dTranspose(x, w, b, origStride, origPad))
.toThrowError();
x.dispose();
w.dispose();
b.dispose();
});
it('throws when biases is not rank 1', () => {
const origInputDepth = 1;
const origOutputDepth = 1;
const inputShape: [number, number, number] = [1, 1, origOutputDepth];
const fSize = 2;
const origPad = 0;
const origStride = 1;
const x = Array3D.new(inputShape, [2]);
const w = Array4D.new(
[fSize, fSize, origInputDepth, origOutputDepth], [3, 1, 5, 0]);
// tslint:disable-next-line:no-any
const b: any = Array2D.new([2, 1], [1, 2]);
expect(() => math.conv2dTranspose(x, w, b, origStride, origPad))
.toThrowError();
x.dispose();
w.dispose();
b.dispose();
});
it('throws when x depth does not match weights original output depth', () => {
const origInputDepth = 1;
const origOutputDepth = 2;
const wrongOrigOutputDepth = 3;
const inputShape: [number, number, number] = [1, 1, origOutputDepth];
const fSize = 2;
const origPad = 0;
const origStride = 1;
const x = Array3D.new(inputShape, [2, 2]);
const w = NDArray.randNormal<Array4D>(
[fSize, fSize, origInputDepth, wrongOrigOutputDepth]);
const b = Array1D.new([1]);
expect(() => math.conv2dTranspose(x, w, b, origStride, origPad))
.toThrowError();
x.dispose();
w.dispose();
b.dispose();
});
});
describe('NDArrayMathGPU conv2dDerWeights', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('conv2dDerWeights input=3x3x1,d2=1,f=2,s=1,p=0', () => {
const inputDepth = 1;
const outputDepth = 1;
const inputShape: [number, number, number] = [3, 3, inputDepth];
const fSize = 2;
const stride = 1;
const pad = 0;
const weightsShape = [fSize, fSize, inputDepth, outputDepth];
const x = Array3D.new(inputShape, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dy = Array3D.new([2, 2, 1], [3, 1, 2, 0]);
const result = math.conv2dDerWeights(x, dy, fSize, stride, pad);
const expected = new Float32Array([13, 19, 31, 37]);
expect(result.inGPU()).toBe(true);
expect(result.shape).toEqual(weightsShape);
expect(result.getValues()).toEqual(expected);
x.dispose();
dy.dispose();
});
});
describe('NDArrayMathGPU conv2dDerWeights', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('conv2dDerBias dy=2x2x2', () => {
const outputDepth = 2;
const dyShape: [number, number, number] = [2, 2, outputDepth];
const dy = Array3D.new(dyShape, [1, 2, 3, 4, 5, 6, 7, 8]);
const result = math.conv2dDerBias(dy);
const expected = new Float32Array([16, 20]);
expect(result.inGPU()).toBe(true);
expect(result.shape).toEqual([outputDepth]);
expect(result.getValues()).toEqual(expected);
dy.dispose();
});
});
describe('NDArrayMathGPU maxPool', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('3x3x2 in, 2x2 filter, 1 stride', () => {
// Feed forward.
const a = Array3D.new(
[3, 3, 2],
[1, 99, 2, 88, 3, 77, 4, 66, 5, 55, 6, 44, 7, 33, 9, 22, 8, 11]);
const result = math.maxPool(a, 2, 1, 0);
expect(result.inGPU()).toBe(true);
expect(result.shape).toEqual([2, 2, 2]);
expect(result.getValues()).toEqual(new Float32Array([
5, 99, 6, 88, 9, 66, 9, 55
]));
a.dispose();
});
it('3x3x1 in, 2x2 filter, 1 stride, propagates NaNs', () => {
const a = Array3D.new([3, 3, 1], [1, 2, 3, 4, 5, 6, 7, NaN, 9]);
const result = math.maxPool(a, 2, 1, 0);
expect(result.shape).toEqual([2, 2, 1]);
expect(result.getValues()).toEqual(new Float32Array([5, 6, NaN, NaN]));
a.dispose();
});
it('4x4x1 in, 2x2 filter, 2 stride', () => {
// Feed forward.
const a = Array3D.new(
[4, 4, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
const result = math.maxPool(a, 2, 2, 0);
expect(result.inGPU()).toBe(true);
expect(result.shape).toEqual([2, 2, 1]);
expect(result.getValues()).toEqual(new Float32Array([5, 7, 13, 15]));
a.dispose();
});
it('throws when x is not rank 3', () => {
// tslint:disable-next-line:no-any
const a: any = Array2D.new([3, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9]);
expect(() => math.maxPool(a, 2, 1, 0)).toThrowError();
a.dispose();
});
});
describe('NDArrayMathGPU maxPoolBackprop', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('x=2x2x1, f=2, s=2, pad=1', () => {
const dy = Array3D.new([2, 2, 1], [1, 2, 3, 4]);
const maxPositions = Array3D.new([2, 2, 1], [3, 2, 1, 0]);
const expected = new Float32Array([1, 2, 3, 4]);
const dx = math.maxPoolBackprop(dy, maxPositions, 2, 2, 1);
expect(dx.inGPU()).toBe(true);
expect(dx.getValues()).toEqual(expected);
dy.dispose();
maxPositions.dispose();
dx.dispose();
});
// Max pool depth > 1.
it('x=3x3x2, f=2, s=1, no duplicate max value', () => {
const dy = Array3D.new([2, 2, 2], [1, 44, 2, 33, 3, 22, 4, 11]);
const x = Array3D.new(
[3, 3, 2],
[1, 99, 2, 55, 3, 66, 4, 66, 5, 88, 6, 44, 7, 99, 8, 55, 9, 100]);
const expected = new Float32Array(
[0, 44, 0, 0, 0, 0, 0, 0, 1, 33, 2, 0, 0, 22, 3, 0, 4, 11]);
const dx = math.maxPoolBackprop(dy, x, 2, 1, 0);
expect(dx.inGPU()).toBe(true);
expect(dx.getValues()).toEqual(expected);
dy.dispose();
x.dispose();
dx.dispose();
});
it('x=3x3x2, f=2, s=1 duplicate max value', () => {
const dy = Array3D.new([2, 2, 2], [1, 44, 2, 33, 3, 22, 4, 11]);
const x = Array3D.new(
[3, 3, 2], [0, 1, 0, 3, 0, 2, 0, 1, 5, 2, 0, 1, 0, 1, 0, 1, 0, 5]);
const expected = new Float32Array(
[0, 0, 0, 77, 0, 0, 0, 0, 10, 22, 0, 0, 0, 0, 0, 0, 0, 11]);
const dx = math.maxPoolBackprop(dy, x, 2, 1, 0);
expect(dx.inGPU()).toBe(true);
expect(dx.getValues()).toEqual(expected);
dy.dispose();
x.dispose();
dx.dispose();
});
});
describe('NDArrayMathGPU resizeBilinear', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.dispose();
});
it('simple alignCorners=false', () => {
const input = Array3D.new([2, 2, 1], [2, 2, 4, 4]);
const output = math.resizeBilinear3D(input, [3, 3], false);
test_util.expectArraysClose(
output.getValues(),
new Float32Array([2, 2, 2, 10 / 3, 10 / 3, 10 / 3, 4, 4, 4]), 1e-4);
input.dispose();
});
it('simple alignCorners=true', () => {
const input = Array3D.new([2, 2, 1], [2, 2, 4, 4]);
const output = math.resizeBilinear3D(input, [3, 3], true);
test_util.expectArraysClose(
output.getValues(), new Float32Array([2, 2, 2, 3, 3, 3, 4, 4, 4]),
1e-4);
input.dispose();
});
it('matches tensorflow w/ random numbers alignCorners=false', () => {
const input = Array3D.new([2, 3, 2], [
1.19074044, 0.91373104, 2.01611669, -0.52270832, 0.38725395, 1.30809779,
0.61835143, 3.49600659, 2.09230986, 0.56473997, 0.03823943, 1.19864896
]);
const output = math.resizeBilinear3D(input, [4, 5], false);
test_util.expectArraysClose(
output.getValues(), new Float32Array([
1.19074047, 0.91373104, 1.68596613, 0.05186744, 1.69034398,
-0.15654698, 0.7130264, 0.94193673, 0.38725394, 1.30809784,
0.9045459, 2.20486879, 1.59434628, 0.89455694, 1.68591988,
0.26748738, 0.58103991, 1.00690198, 0.21274668, 1.25337338,
0.6183514, 3.49600649, 1.50272655, 1.73724651, 1.68149579,
0.69152176, 0.44905344, 1.07186723, 0.03823943, 1.19864893,
0.6183514, 3.49600649, 1.50272655, 1.73724651, 1.68149579,
0.69152176, 0.44905344, 1.07186723, 0.03823943, 1.19864893
]),
1e-4);
input.dispose();
});
it('matches tensorflow w/ random numbers alignCorners=true', () => {
const input = Array3D.new([2, 3, 2], [
1.56324531, 2.13817752, 1.44398421, 1.07632684, 0.59306785, -0.36970865,
1.62451879, 1.8367334, 1.13944798, 2.01993218, 2.01919952, 2.67524054
]);
const output = math.resizeBilinear3D(input, [4, 5], true);
test_util.expectArraysClose(
output.getValues(), new Float32Array([
1.5632453, 2.13817763, 1.50361478, 1.60725224, 1.44398427,
1.07632685, 1.01852608, 0.35330909, 0.59306782, -0.36970866,
1.58366978, 2.03769612, 1.46307099, 1.71427906, 1.3424722,
1.39086199, 1.20545864, 1.01806819, 1.06844509, 0.6452744,
1.60409427, 1.93721485, 1.42252707, 1.82130599, 1.24096,
1.70539713, 1.3923912, 1.68282723, 1.54382229, 1.66025746,
1.62451875, 1.83673346, 1.38198328, 1.92833281, 1.13944793,
2.01993227, 1.57932377, 2.34758639, 2.01919961, 2.67524052
]),
1e-4);
input.dispose();
});
});
describe('NDArrayMathGPU batchNorm', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
math.startScope();
});
it('simple batchnorm, no offset or scale, 2x1x2', () => {
const x = Array3D.new([2, 1, 2], new Float32Array([2, 100, 4, 400]));
const mean = Array1D.new([1, 2]);
const variance = Array1D.new([2, 3]);
const varianceEpsilon = .001;
const result = math.batchNormalization3D(
x, mean, variance, varianceEpsilon, undefined, undefined);
test_util.expectArraysClose(
result.getValues(), new Float32Array([
(x.get(0, 0, 0) - mean.get(0)) * 1 /
Math.sqrt(variance.get(0) + varianceEpsilon),
(x.get(0, 0, 1) - mean.get(1)) * 1 /
Math.sqrt(variance.get(1) + varianceEpsilon),
(x.get(1, 0, 0) - mean.get(0)) * 1 /
Math.sqrt(variance.get(0) + varianceEpsilon),
(x.get(1, 0, 1) - mean.get(1)) * 1 /
Math.sqrt(variance.get(1) + varianceEpsilon)
]),
1e-4);
x.dispose();
mean.dispose();
variance.dispose();
});
it('simple batchnorm, no offset, 2x1x2', () => {
const x = Array3D.new([2, 1, 2], new Float32Array([2, 100, 4, 400]));
const mean = Array1D.new([1, 2]);
const variance = Array1D.new([2, 3]);
const scale = Array1D.new([4, 5]);
const varianceEpsilon = .001;
const result = math.batchNormalization3D(
x, mean, variance, varianceEpsilon, scale, undefined);
test_util.expectArraysClose(
result.getValues(), new Float32Array([
(x.get(0, 0, 0) - mean.get(0)) * scale.get(0) /
Math.sqrt(variance.get(0) + varianceEpsilon),
(x.get(0, 0, 1) - mean.get(1)) * scale.get(1) /
Math.sqrt(variance.get(1) + varianceEpsilon),
(x.get(1, 0, 0) - mean.get(0)) * scale.get(0) /
Math.sqrt(variance.get(0) + varianceEpsilon),
(x.get(1, 0, 1) - mean.get(1)) * scale.get(1) /
Math.sqrt(variance.get(1) + varianceEpsilon)
]),
1e-4);
x.dispose();
mean.dispose();
variance.dispose();
scale.dispose();
});
it('simple batchnorm, no scale, 2x1x2', () => {
const x = Array3D.new([2, 1, 2], new Float32Array([2, 100, 4, 400]));
const mean = Array1D.new([1, 2]);
const variance = Array1D.new([2, 3]);
const offset = Array1D.new([4, 5]);
const varianceEpsilon = .001;
const result = math.batchNormalization3D(
x, mean, variance, varianceEpsilon, undefined, offset);
test_util.expectArraysClose(
result.getValues(), new Float32Array([
offset.get(0) +
(x.get(0, 0, 0) - mean.get(0)) * 1 /
Math.sqrt(variance.get(0) + varianceEpsilon),
offset.get(1) +
(x.get(0, 0, 1) - mean.get(1)) * 1 /
Math.sqrt(variance.get(1) + varianceEpsilon),
offset.get(0) +
(x.get(1, 0, 0) - mean.get(0)) * 1 /
Math.sqrt(variance.get(0) + varianceEpsilon),
offset.get(1) +
(x.get(1, 0, 1) - mean.get(1)) * 1 /
Math.sqrt(variance.get(1) + varianceEpsilon)
]),
1e-4);
x.dispose();
mean.dispose();
variance.dispose();
offset.dispose();
});
it('simple batchnorm, 2x1x2', () => {
const x = Array3D.new([2, 1, 2], new Float32Array([2, 100, 4, 400]));
const mean = Array1D.new([1, 2]);
const variance = Array1D.new([2, 3]);
const offset = Array1D.new([3, 4]);
const scale = Array1D.new([4, 5]);
const varianceEpsilon = .001;
const result = math.batchNormalization3D(
x, mean, variance, varianceEpsilon, scale, offset);
test_util.expectArraysClose(
result.getValues(), new Float32Array([
offset.get(0) +
(x.get(0, 0, 0) - mean.get(0)) * scale.get(0) /
Math.sqrt(variance.get(0) + varianceEpsilon),
offset.get(1) +
(x.get(0, 0, 1) - mean.get(1)) * scale.get(1) /
Math.sqrt(variance.get(1) + varianceEpsilon),
offset.get(0) +
(x.get(1, 0, 0) - mean.get(0)) * scale.get(0) /
Math.sqrt(variance.get(0) + varianceEpsilon),
offset.get(1) +
(x.get(1, 0, 1) - mean.get(1)) * scale.get(1) /
Math.sqrt(variance.get(1) + varianceEpsilon)
]),
1e-4);
x.dispose();
mean.dispose();
variance.dispose();
scale.dispose();
offset.dispose();
});
it('batchnorm matches tensorflow, 2x3x3', () => {
const x =
Array3D.new([2, 3, 3], new Float32Array([
0.49955603, 0.04158615, -1.09440524, 2.03854165,
-0.61578344, 2.87533573, 1.18105987, 0.807462, 1.87888837,
2.26563962, -0.37040935, 1.35848753, -0.75347094,
0.15683117, 0.91925946, 0.34121279, 0.92717143, 1.89683965
]));
const mean = Array1D.new([0.39745062, -0.48062894, 0.4847822]);
const variance = Array1D.new([0.32375343, 0.67117643, 1.08334653]);
const offset = Array1D.new([0.69398749, -1.29056387, 0.9429723]);
const scale = Array1D.new([-0.5607271, 0.9878457, 0.25181573]);
const varianceEpsilon = .001;
const result = math.batchNormalization3D(
x, mean, variance, varianceEpsilon, scale, offset);
test_util.expectArraysClose(
result.getValues(), new Float32Array([
0.59352049, -0.66135202, 0.5610874, -0.92077015, -1.45341019,
1.52106473, -0.07704776, 0.26144429, 1.28010017, -1.14422404,
-1.15776136, 1.15425493, 1.82644104, -0.52249442, 1.04803919,
0.74932291, 0.40568101, 1.2844412
]),
1e-4);
x.dispose();
mean.dispose();
variance.dispose();
scale.dispose();
offset.dispose();
});
});
describe('NDArrayMathGPU debug mode', () => {
let math: NDArrayMathGPU;
beforeEach(() => {
math = new NDArrayMathGPU();
math.startScope();
});
afterEach(() => {
math.endScope(null!);
});
it('debug mode does not error when no nans', () => {
math.enableDebugMode();
const a = Array1D.new([2, -1, 0, 3]);
const res = math.relu(a);
expect(res.getValues()).toEqual(new Float32Array([2, 0, 0, 3]));
});
it('debug mode errors when there are nans', () => {
math.enableDebugMode();
const a = Array1D.new([2, NaN]);
const f = () => math.relu(a);
expect(f).toThrowError();
});
it('no errors where there are nans, and debug mode is disabled', () => {
const a = Array1D.new([2, NaN]);
const res = math.relu(a);
expect(res.getValues()).toEqual(new Float32Array([2, NaN]));
});
}); | the_stack |
import * as React from "react"
import update = require("react-addons-update")
import { NotFound } from "./notFound"
import { IBlock, IResponseError, ITxProp } from "./rest"
import { RestClient } from "./restClient"
import { TxLine } from "./txLine"
interface IBlockProps {
rest: RestClient
hash: string
notFound: boolean
}
interface IBlockViewState {
rest: RestClient
block?: IBlock
txs: ITxProp[]
hash: string
amount?: string
fees?: string
length?: number
volume?: string
notFound: boolean
hasMore: boolean
index: number
isUncle: boolean
reward: string
previousBlocks: string[]
}
export class BlockView extends React.Component<IBlockProps, IBlockViewState> {
public mounted: boolean = false
constructor(props: IBlockProps) {
super(props)
this.state = {
hasMore: true,
hash: props.hash,
index: 1,
isUncle: false,
notFound: false,
previousBlocks: [],
rest: props.rest,
reward: undefined,
txs: [],
}
}
public componentWillUnmount() {
this.mounted = false
}
public componentDidMount() {
this.mounted = true
this.state.rest.setLoading(true)
this.state.rest.getBlock(this.state.hash, 10)
.then((data: IBlock & IResponseError) => {
this.state.rest.setLoading(false)
if (!data.txs) { this.setState({ notFound: true }); return }
if (!this.mounted) { return }
this.setState({
amount: data.amount,
block: data,
fees: data.fee,
length: data.length,
previousBlocks: data.prevBlock !== undefined ? data.prevBlock.split(",") : [],
txs: data.txs,
volume: data.volume,
})
this.state.rest.isUncleBlock(this.state.hash)
.then((isUncle: boolean & IResponseError) => {
if (typeof (isUncle) === "boolean") {
this.setState({ isUncle })
} else {
this.setState({ notFound: true }); return
}
})
if (this.state.block.miner === undefined) { return }
this.state.rest.getMiningReward(this.state.hash)
.then((reward: string & IResponseError) => {
if (typeof (reward) === "string") {
this.setState({ reward })
} else {
this.setState({ reward: "-" })
}
})
.catch((e: Error) => {
this.setState({ reward: "-" })
alert(e)
})
})
.catch((e: Error) => {
alert(e)
})
}
public render() {
let uncleIndex = 0
let txIndex = 0
if (this.state.notFound) {
return <NotFound />
}
if (!this.state.notFound && this.state.block === undefined) {
return <div></div>
}
const date = new Date(this.state.block.timeStamp)
return (
<div>
{this.state.isUncle // When this block is uncle, it shows this is the uncle of which block
? <div className="contentTitle">Uncle</div>
: <div className="contentTitle">Block #{this.state.block.height}</div>
}
<table className="table_margined blockTable">
<thead>
<tr>
<th colSpan={2} className="tableBorder_Header tableHeader_floatLeft">Basic Info</th>
</tr>
</thead>
<tbody>
<tr>
<td className="tdSubTitle subTitle_width20">Height</td>
<td>{this.state.block.height}</td>
</tr>
<tr>
<td className="tdSubTitle subTitle_width20">Block Hash</td>
<td>{this.state.hash}</td>
</tr>
<tr>
<td className="tdSubTitle subTitle_width20">Previous Block Hash</td>
<td>
{this.state.previousBlocks.length > 0 ?
<a href={`/block/${this.state.previousBlocks[0]}`}>
{this.state.previousBlocks[0]}
</a>
: "None"}
</td>
</tr>
<tr>
<td className="tdSubTitle subTitle_width20">Uncles</td>
<td>{this.state.previousBlocks.length > 1
?
this.state.previousBlocks.slice(1)
.map((uncleHash: string) => {
return (
<div key={uncleIndex++}>
<a href={`/block/${uncleHash}`}>{uncleHash}</a><br />
</div>
)
})
: "None"}
</td>
</tr>
<tr>
<td className="tdSubTitle subTitle_width20">Merkle Root</td>
<td>{this.state.block.merkleRoot}</td>
</tr>
<tr>
<td className="tdSubTitle subTitle_width20">State Root</td>
<td>{this.state.block.stateRoot}</td>
</tr>
<tr style={{ display: `${this.state.block.resultHash !== undefined ? ("contents") : ("none")}` }}>
<td className="tdSubTitle subTitle_width20">Result Hash</td>
<td>{this.state.block.resultHash}</td>
</tr>
<tr>
<td className="tdSubTitle subTitle_width20">Difficulty</td>
<td>{this.state.block.difficulty}</td>
</tr>
<tr style={{ display: `${this.state.block.nonce !== undefined ? ("contents") : ("none")}` }}>
<td className="tdSubTitle subTitle_width20">Nonce</td>
<td>{this.state.block.nonce}</td>
</tr>
</tbody>
</table>
<table className="table_margined blockTable">
<thead>
<tr>
<th colSpan={2} className="tableBorder_Header tableHeader_floatLeft">Mining Info</th>
</tr>
</thead>
<tbody>
<tr style={{ display: `${this.state.block.miner !== undefined ? ("contents") : ("none")}` }}>
<td className="tdSubTitle subTitle_width20">Miner</td>
<td>
<a href={`/address/${this.state.block.miner}`}>{this.state.block.miner}</a>
</td>
</tr>
<tr>
<td className="tdSubTitle subTitle_width20">Mined Time</td>
<td>{date.toString()}</td>
</tr>
<tr style={{ display: `${this.state.reward !== undefined ? ("contents") : ("none")}` }}>
<td className="tdSubTitle subTitle_width20">Reward</td>
<td>{this.state.reward}</td>
</tr>
</tbody>
</table>
{this.state.isUncle || this.state.txs.length === 0 // Since uncle block has no tx, not need to show tx info
? null
: (<table className="table_margined blockTable">
<thead>
<tr>
<th colSpan={2} className="tableBorder_Header tableHeader_floatLeft">Tx Info</th>
</tr>
</thead>
<tbody>
<tr>
<td className="tdSubTitle subTitle_width20">Num of Txs</td>
<td>{this.state.length}</td>
</tr>
<tr>
<td className="tdSubTitle subTitle_width20">Tx Volume</td>
<td>{this.state.volume}</td>
</tr>
<tr>
<td className="tdSubTitle subTitle_width20">Tx Transfer</td>
<td>{this.state.amount}</td>
</tr>
<tr>
<td className="tdSubTitle subTitle_width20">Tx Fees</td>
<td>{this.state.fees}</td>
</tr>
</tbody>
</table>)
}
{this.state.txs.map((tx: ITxProp) => {
return (
<div key={txIndex++}>
<TxLine tx={tx} rest={this.state.rest} />
<button className="dmdl-button mdl-js-button mdl-button--raised mdl-button--colored txAmtBtn green">
{tx.estimated + " HYCON"}
</button>
</div>
)
})}
{this.state.hasMore && this.state.txs.length > 0
? <div><button className="btn btn-block btn-info" onClick={() => this.fetchNextTxs()}>Load more</button></div> : null}
</div>
)
}
private fetchNextTxs() {
this.state.rest.getNextTxsInBlock(this.state.hash, this.state.txs[0].hash, this.state.index).then((result: ITxProp[]) => {
if (!this.mounted) { return }
if (result.length === 0) { this.setState({ hasMore: false }) }
this.setState({
index: this.state.index + 1,
txs: update(this.state.txs, { $push: result }),
})
})
}
} | the_stack |
import { AutomatonWithGUI } from './AutomatonWithGUI';
import { BezierNode, Curve, FxSection, SerializedBezierNode, SerializedCurve, SerializedFxSection } from '@0b5vr/automaton';
import { EventEmittable } from './mixins/EventEmittable';
import { SerializableWithID } from './types/SerializableWithID';
import { StatusLevel, WithStatus } from './types/Status';
import { Throttle } from './utils/Throttle';
import { WithBypass } from './types/WithBypass';
import { WithID } from './types/WithID';
import { applyMixins } from './utils/applyMixins';
import { clamp } from './utils/clamp';
import { genID } from './utils/genID';
import { hasOverwrap } from './utils/hasOverwrap';
import { jsonCopy } from './utils/jsonCopy';
/**
* Handles of a new node will be created in this length.
*/
export const CURVE_DEFAULT_HANDLE_LENGTH = 0.1;
export const CURVE_FX_ROW_MAX = 5;
/**
* Represents "Status code" of a status of the {@link Curve}.
*/
export enum CurveStatusCode {
NOT_USED,
NAN_DETECTED,
}
/**
* It represents a channel of Automaton.
* It has even more pretty APIs than raw {@link Curve} yay
* @param automaton Parent automaton
* @param data Data of the channel
*/
export interface CurveWithGUI extends SerializableWithID<SerializedCurve> {}
export interface CurveWithGUI extends EventEmittable<CurveWithGUIEvents> {}
export interface CurveWithGUI extends WithStatus<CurveStatusCode> {}
export class CurveWithGUI extends Curve {
/**
* Default data of a curve.
*/
public static readonly DEFAULT_DATA: SerializedCurve = {
nodes: [
[ 0.0, 0.0, 0.0, 0.0, CURVE_DEFAULT_HANDLE_LENGTH, 0.0 ],
[ 1.0, 0.0, -CURVE_DEFAULT_HANDLE_LENGTH, 0.0, 0.0, 0.0 ],
],
fxs: []
};
/**
* The parent automaton.
*/
protected __automaton!: AutomatonWithGUI;
/**
* {@link __values} but without fxs.
*/
protected __valuesWithoutFxs!: Float32Array;
/**
* List of bezier nodes.
*/
protected __nodes!: Array<BezierNode & WithID>;
/**
* List of fx sections.
*/
protected __fxs!: Array<FxSection & WithBypass & WithID>;
/**
* I'm crying
*/
private __userCount: number = 0;
/**
* Limiting the emit of previewTime because it's too much
*/
private __throttlePreviewTime: Throttle;
/**
* List of bezier nodes.
*/
public get nodes(): Array<BezierNode & WithID> {
return jsonCopy( this.__nodes );
}
/**
* List of fx sections.
*/
public get fxs(): Array<FxSection & WithBypass & WithID> {
return jsonCopy( this.__fxs );
}
/**
* Whether the curve is being used in somewhere or not.
*/
public get isUsed(): boolean {
return this.getSpecificStatus( CurveStatusCode.NOT_USED ) == null;
}
public constructor( automaton: AutomatonWithGUI, data?: SerializedCurve & Partial<WithID> ) {
super( automaton, data || jsonCopy( CurveWithGUI.DEFAULT_DATA ) );
this.$id = data?.$id ?? genID();
this.__watchStatus( () => {
this.__setStatus( {
code: CurveStatusCode.NOT_USED,
level: StatusLevel.WARNING,
message: 'This curve has not been used yet'
} );
} );
this.__throttlePreviewTime = new Throttle( 16 );
}
/**
* Load a curve data.
* @param data Data of curve
*/
public deserialize( data: SerializedCurve ): void {
data.fxs?.forEach( ( fx ) => {
// fill missing params
const defParams = this.__automaton.getFxDefinitionParams( fx.def );
if ( defParams ) {
const newParams: { [ key: string ]: any } = {};
Object.entries( defParams ).forEach( ( [ key, value ] ) => {
newParams[ key ] = fx.params[ key ] ?? value.default;
} );
fx.params = newParams;
}
} );
super.deserialize( jsonCopy( data ) );
this.__nodes.forEach( ( node ) => {
node.$id = genID();
} );
this.__fxs.forEach( ( fxs ) => {
fxs.$id = genID();
} );
}
/**
* Precalculate value of samples.
*/
public precalc(): void {
const valuesLength = Math.ceil( this.__automaton.resolution * this.length ) + 1;
this.__values = new Float32Array( valuesLength );
this.__valuesWithoutFxs = new Float32Array( valuesLength );
this.__shouldNotInterpolate = new Uint8Array( valuesLength );
this.__generateCurve();
this.__valuesWithoutFxs.set( this.__values );
this.__applyFxs();
let hasNaN = false;
this.__values.forEach( ( v, i ) => {
if ( isNaN( v ) ) {
this.__values[ i ] = 0.0;
hasNaN = true;
}
} );
this.__watchStatus( () => {
if ( hasNaN ) {
this.__setStatus( {
code: CurveStatusCode.NAN_DETECTED,
level: StatusLevel.ERROR,
message: 'This curve has NaN value'
} );
} else {
this.__deleteStatus( CurveStatusCode.NAN_DETECTED );
}
} );
this.__emit( 'precalc' );
}
/**
* Update the preview time.
* Do not call this function if you're not a [[ChannelItemCurveWithGUI]].
* @param time Time
* @param value Value
*/
public emitPreviewTime( event: CurveWithGUIEvents[ 'previewTime' ] ): void {
this.__throttlePreviewTime.do( () => this.__emit( 'previewTime', event ) );
}
/**
* I'm crying
* Intended to be used in {@link ChannelWithGUI} via {@link ChannelItemWithGUI#curve}.
*/
public incrementUserCount(): void {
this.__userCount ++;
if ( this.__userCount === 1 ) {
this.__watchStatus( () => {
this.__deleteStatus( CurveStatusCode.NOT_USED );
} );
}
}
/**
* I'm crying
* Intended to be used in {@link ChannelWithGUI} via {@link ChannelItemWithGUI#curve}.
*/
public decrementUserCount(): void {
this.__userCount --;
if ( this.__userCount === 0 ) {
this.__watchStatus( () => {
this.__setStatus( {
code: CurveStatusCode.NOT_USED,
level: StatusLevel.WARNING,
message: 'This curve is not used'
} );
} );
}
}
/**
* Return how many node the curve currently have.
* @returns Nodes count
*/
public getNumNode(): number {
return this.__nodes.length;
}
/**
* Serialize its current state.
* @returns Serialized state
*/
public serialize(): SerializedCurve {
return {
nodes: this.__serializeNodes(),
fxs: this.__serializeFxs()
}; // 🔥
}
/**
* Get the nth node.
* @param index Index of the node
* @returns Data of the node
*/
public getNodeByIndex( index: number ): BezierNode & WithID {
const node = this.__nodes[ index ];
if ( !node ) {
throw new Error( `Given node index ${index} is invalid (Current count of nodes: ${this.__nodes.length})` );
}
return jsonCopy( node );
}
/**
* Dump data of a node.
* @param id Id of the node you want to dump
* @returns Data of the node
*/
public getNode( id: string ): BezierNode & WithID {
const index = this.__getNodeIndexById( id );
return jsonCopy( this.__nodes[ index ] );
}
/**
* Dump data of a previous node from a specified node.
* It might return `null` when the specified node is the first node.
* @param id Id of the node you want to refer
* @returns Data of the previous node
*/
public getPreviousNode( id: string ): ( BezierNode & WithID ) | null {
const index = this.__getNodeIndexById( id );
if ( index === 0 ) { return null; }
return jsonCopy( this.__nodes[ index - 1 ] );
}
/**
* Dump data of a next node from a specified node.
* It might return `null` when the specified node is the last node.
* @param id Id of the node you want to refer
* @returns Data of the next node
*/
public getNextNode( id: string ): ( BezierNode & WithID ) | null {
const index = this.__getNodeIndexById( id );
if ( index === this.__nodes.length - 1 ) { return null; }
return jsonCopy( this.__nodes[ index + 1 ] );
}
/**
* Create a node.
* @param time Time of new node
* @param value Value of new node
* @returns Data of the node
*/
public createNode( time: number, value: number ): BezierNode & WithID {
const id = genID();
const data = {
time,
value,
inTime: 0.0,
inValue: 0.0,
outTime: 0.0,
outValue: 0.0,
$id: id,
};
this.__nodes.push( data );
this.__sortNodes();
// if there are handles in previous or next node, make a handle
{
const prev = this.getPreviousNode( id );
const prevHasHandle = prev == null || prev.outTime !== 0.0 || prev.outValue !== 0.0;
const next = this.getNextNode( id );
const nextHasHandle = next == null || next.inTime !== 0.0 || next.inValue !== 0.0;
if ( prevHasHandle || nextHasHandle ) {
data.inTime = -CURVE_DEFAULT_HANDLE_LENGTH;
data.outTime = CURVE_DEFAULT_HANDLE_LENGTH;
}
}
this.precalc();
this.__emit( 'createNode', { id, node: jsonCopy( data ) } );
// if we added the last node, change the length
if ( this.isLastNode( id ) ) {
this.__emit( 'changeLength', { length: this.length } );
}
this.__automaton.shouldSave = true;
return jsonCopy( data );
}
/**
* Create a node from dumped data.
* @param node Dumped bezier node object
* @returns Data of the node
*/
public createNodeFromData( node: BezierNode & WithID ): BezierNode & WithID {
const data = jsonCopy( node );
this.__nodes.push( data );
this.__sortNodes();
this.precalc();
this.__emit( 'createNode', { id: node.$id, node: jsonCopy( data ) } );
// if we added the last node, change the length
if ( this.isLastNode( node.$id ) ) {
this.__emit( 'changeLength', { length: this.length } );
}
this.__automaton.shouldSave = true;
return jsonCopy( data );
}
/**
* Check whether the node is the first node or not.
* @param id Id of the node you want to check
*/
public isFirstNode( id: string ): boolean {
const index = this.__getNodeIndexById( id );
return index === 0;
}
/**
* Check whether the node is the last node or not.
* @param id Id of the node you want to check
*/
public isLastNode( id: string ): boolean {
const index = this.__getNodeIndexById( id );
return index === this.__nodes.length - 1;
}
/**
* Remove a node.
* @param id Id of the node you want to remove
*/
public removeNode( id: string ): void {
const index = this.__getNodeIndexById( id );
// we can't delete the first node
if ( index === 0 ) {
return;
}
const isLastNode = this.isLastNode( id );
this.__nodes.splice( index, 1 );
this.precalc();
this.__emit( 'removeNode', { id } );
// if we delete the last node, change the length
if ( isLastNode ) {
this.__emit( 'changeLength', { length: this.length } );
}
this.__automaton.shouldSave = true;
}
/**
* Move a node in the time axis.
* @param id Id of the node you want to move
* @param time Time
*/
public moveNodeTime( id: string, time: number ): void {
const index = this.__getNodeIndexById( id );
const node = this.__nodes[ index ];
let newTime = time;
if ( index === 0 ) {
newTime = 0;
} else {
newTime = Math.max( newTime, this.__nodes[ index - 1 ].time );
if ( index !== this.__nodes.length - 1 ) {
newTime = Math.min( newTime, this.__nodes[ index + 1 ].time );
}
}
node.time = newTime;
this.precalc();
this.__emit( 'updateNode', { id, node: jsonCopy( node ) } );
// if we moved the last node, change the length
if ( this.isLastNode( id ) ) {
this.__emit( 'changeLength', { length: this.length } );
}
this.__automaton.shouldSave = true;
}
/**
* Move a node in the value axis.
* @param id Id of the node you want to move
* @param value Value
*/
public moveNodeValue( id: string, value: number ): void {
const index = this.__getNodeIndexById( id );
const node = this.__nodes[ index ];
node.value = value;
this.precalc();
this.__emit( 'updateNode', { id, node: jsonCopy( node ) } );
this.__automaton.shouldSave = true;
}
/**
* Move a handle of a node in the time axis.
* @param id Id of the node you want to operate
* @param dir Which handle?
* @param time Time
*/
public moveHandleTime( id: string, dir: 'in' | 'out', time: number ): void {
const index = this.__getNodeIndexById( id );
if ( index === 0 && dir === 'in' ) { return; }
const node = this.__nodes[ index ];
const newTime = ( dir === 'in' ) ? Math.min( 0.0, time ) : Math.max( 0.0, time );
node[ dir === 'in' ? 'inTime' : 'outTime' ] = newTime;
this.precalc();
this.__emit( 'updateNode', { id, node: jsonCopy( node ) } );
this.__automaton.shouldSave = true;
}
/**
* Move a handle of a node in the value axis.
* @param id Id of the node you want to operate
* @param dir Which handle?
* @param value Value
*/
public moveHandleValue( id: string, dir: 'in' | 'out', value: number ): void {
const index = this.__getNodeIndexById( id );
if ( index === 0 && dir === 'in' ) { return; }
const node = this.__nodes[ index ];
node[ dir === 'in' ? 'inValue' : 'outValue' ] = value;
this.precalc();
this.__emit( 'updateNode', { id, node: jsonCopy( node ) } );
this.__automaton.shouldSave = true;
}
/**
* Reset a handle of a node.
* @param id Id of the node you want to operate
* @param dir Which handle?
*/
public resetHandle( id: string, dir: 'in' | 'out' ): void {
const index = this.__getNodeIndexById( id );
if ( index === 0 && dir === 'in' ) { return; }
const node = this.__nodes[ index ];
node[ dir === 'in' ? 'inTime' : 'outTime' ] = ( ( dir === 'in' ) ? -1.0 : 1.0 ) * CURVE_DEFAULT_HANDLE_LENGTH;
node[ dir === 'in' ? 'inValue' : 'outValue' ] = 0.0;
this.precalc();
this.__emit( 'updateNode', { id, node: jsonCopy( node ) } );
this.__automaton.shouldSave = true;
}
/**
* Get the nth fx section.
* @param index Index of the fx section
* @returns Data of the fx section
*/
public getFxByIndex( index: number ): FxSection & WithBypass & WithID {
const fx = this.__fxs[ index ];
if ( !fx ) {
throw new Error( `Given fx section index ${index} is invalid (Current count of fx sections: ${this.__fxs.length})` );
}
return jsonCopy( fx );
}
/**
* Dump data of a fx section.
* @param id Id of a fx section you want to dump
* @returns Data of the fx
*/
public getFx( id: string ): FxSection & WithBypass & WithID {
const index = this.__getFxIndexById( id );
return jsonCopy( this.__fxs[ index ] );
}
/**
* Create a fx.
* If it couldn't create an fx, it will return `null` instead.
* @param time Beginning time of new fx
* @param length Length of new fx
* @param def Definition id (kind) of new fx
* @returns Id of the new fx
*/
public createFx(
time: number,
length: number,
def: string
): ( FxSection & WithBypass & WithID ) | null {
const row = this.__getFreeRow( time, length );
if ( CURVE_FX_ROW_MAX <= row ) {
console.error( 'Too many fx stacks at here!' );
return null;
}
const id = genID();
const data: FxSection & WithBypass & WithID = {
$id: id,
time: time,
length: length,
row: row,
def: def,
params: this.__automaton.generateDefaultFxParams( def ),
bypass: false
};
this.__fxs.push( data );
this.__sortFxs();
this.precalc();
this.__emit( 'createFx', { id, fx: jsonCopy( data ) } );
this.__automaton.shouldSave = true;
return jsonCopy( data );
}
/**
* Create a fx from dumped data.
* If it couldn't create an fx, it will return empty string instead.
* @param fx Dumped fx data
* @returns Id of the new fx
*/
public createFxFromData(
fx: FxSection & WithBypass & WithID
): ( FxSection & WithBypass & WithID ) | null {
const row = this.__getFreeRow( fx.time, fx.length, fx.row );
if ( CURVE_FX_ROW_MAX <= row ) {
console.error( 'Too many fx stacks at here!' );
return null;
}
const data = jsonCopy( fx );
data.row = row;
this.__fxs.push( data );
this.__sortFxs();
this.precalc();
this.__emit( 'createFx', { id: data.$id, fx: jsonCopy( data ) } );
this.__automaton.shouldSave = true;
return jsonCopy( data );
}
/**
* Remove a fx.
* @param id Id of the fx you want to remove
*/
public removeFx( id: string ): void {
const index = this.__getFxIndexById( id );
this.__fxs.splice( index, 1 );
this.precalc();
this.__emit( 'removeFx', { id } );
this.__automaton.shouldSave = true;
}
/**
* Move a fx.
* @param id Id of the fx you want to move
* @param time Beginning time
*/
public moveFx( id: string, time: number ): void {
const index = this.__getFxIndexById( id );
const fx = this.__fxs[ index ];
const sameRow = this.__fxs.filter( ( fxOp ) => fxOp.row === fx.row );
const indexInRow = sameRow.indexOf( fx );
const prev = sameRow[ indexInRow - 1 ];
const left = prev ? ( prev.time + prev.length ) : 0.0;
const next = sameRow[ indexInRow + 1 ];
const right = next ? next.time : Infinity;
fx.time = clamp( time, left, right - fx.length );
this.precalc();
this.__emit( 'updateFx', { id, fx: jsonCopy( fx ) } );
this.__automaton.shouldSave = true;
}
/**
* Change row of a fx.
* @param id Id of the fx you want to move
* @param row Row
*/
public changeFxRow( id: string, row: number ): void {
const index = this.__getFxIndexById( id );
if ( row < 0 || CURVE_FX_ROW_MAX <= row ) {
throw new Error( `Row number ${row} is invalid` );
}
const fx = this.__fxs[ index ];
if ( fx.row === row ) { return; }
const sameRow = this.__fxs.filter( ( fxOp ) => fxOp.row === row );
const isValid = sameRow.every( ( fxOp ) =>
!hasOverwrap( fx.time, fx.length, fxOp.time, fxOp.length ) );
if ( !isValid ) { return; }
fx.row = row;
this.__sortFxs();
this.precalc();
this.__emit( 'updateFx', { id, fx: jsonCopy( fx ) } );
this.__automaton.shouldSave = true;
}
/**
* Bypass or unbypass a fx.
* @param id Id of the fx you want to change
* @param bypass If true, fx will be bypassed
*/
public bypassFx( id: string, bypass: boolean ): void {
const index = this.__getFxIndexById( id );
const fx = this.__fxs[ index ];
fx.bypass = bypass;
this.precalc();
this.__emit( 'updateFx', { id, fx: jsonCopy( fx ) } );
this.__automaton.shouldSave = true;
}
/**
* Change a param of a fx.
* @param id Id of the fx you want to change
* @param name Name of the param you want to change
* @param value Your desired value
*/
public changeFxParam( id: string, name: string, value: any ): void {
const index = this.__getFxIndexById( id );
const fx = this.__fxs[ index ];
const params = this.__automaton.getFxDefinitionParams( fx.def )!;
let newValue = value;
if ( params[ name ].min !== undefined ) {
newValue = Math.max( params[ name ].min!, newValue );
}
if ( params[ name ].max !== undefined ) {
newValue = Math.min( params[ name ].max!, newValue );
}
fx.params[ name ] = newValue;
this.precalc();
this.__emit( 'updateFx', { id, fx: jsonCopy( fx ) } );
this.__automaton.shouldSave = true;
}
/**
* Move a fx --force.
* Best for undo-redo operation. probably.
* @param id Id of the fx you want to move
* @param time Beginning time
* @param row Row
*/
public forceMoveFx( id: string, time: number, row: number ): void {
const index = this.__getFxIndexById( id );
const fx = this.__fxs[ index ];
fx.time = time;
fx.row = row;
this.__sortFxs();
this.precalc();
this.__emit( 'updateFx', { id, fx: jsonCopy( fx ) } );
this.__automaton.shouldSave = true;
}
/**
* Resize a fx.
* @param id Index of the fx you want to resize
* @param length Length
*/
public resizeFx( id: string, length: number ): void {
const index = this.__getFxIndexById( id );
const fx = this.__fxs[ index ];
const sameRow = this.__fxs.filter( ( fxOp ) => fxOp.row === fx.row );
const indexInRow = sameRow.indexOf( fx );
const next = sameRow[ indexInRow + 1 ];
const right = next ? next.time : Infinity;
fx.length = clamp( length, 0.0, right - fx.time );
this.precalc();
this.__emit( 'updateFx', { id, fx: jsonCopy( fx ) } );
this.__automaton.shouldSave = true;
}
/**
* Resize a fx by left side of the end.
* It's very GUI dev friendly method. yeah.
* @param id Index of the fx you want to resize
* @param length Length
*/
public resizeFxByLeft( id: string, length: number ): void {
const index = this.__getFxIndexById( id );
const fx = this.__fxs[ index ];
const end = fx.time + fx.length;
const sameRow = this.__fxs.filter( ( fxOp ) => fxOp.row === fx.row );
const indexInRow = sameRow.indexOf( fx );
const prev = sameRow[ indexInRow - 1 ];
const left = prev ? ( prev.time + prev.length ) : 0.0;
fx.length = Math.min( Math.max( length, 0.0 ), end - left );
fx.time = end - fx.length;
this.precalc();
this.__emit( 'updateFx', { id, fx: jsonCopy( fx ) } );
this.__automaton.shouldSave = true;
}
/**
* Same as {@link getValue}, but without fxs.
* This is an exclusive feature for WithGUI variant.
* @param time Time at the point you want to grab the value.
* @returns Result value
*/
public getValueWithoutFxs( time: number ): number {
if ( time < 0.0 ) {
// clamp left
return this.__valuesWithoutFxs[ 0 ];
} else if ( this.length <= time ) {
// clamp right
return this.__valuesWithoutFxs[ this.__valuesWithoutFxs.length - 1 ];
} else {
// fetch two values then do the linear interpolation
const index = time * this.__automaton.resolution;
const indexi = Math.floor( index );
const indexf = index % 1.0;
const v0 = this.__valuesWithoutFxs[ indexi ];
const v1 = this.__valuesWithoutFxs[ indexi + 1 ];
const v = v0 + ( v1 - v0 ) * indexf;
return v;
}
}
/**
* Serialize its nodes.
* @returns Serialized nodes
*/
private __serializeNodes(): SerializedBezierNode[] {
return this.__nodes.map( ( node ) => {
const { time, value, inTime, inValue, outTime, outValue } = node;
if ( outValue !== 0.0 ) {
return [ time, value, inTime, inValue, outTime, outValue ];
} else if ( outTime !== 0.0 ) {
return [ time, value, inTime, inValue, outTime ];
} else if ( inValue !== 0.0 ) {
return [ time, value, inTime, inValue ];
} else if ( inTime !== 0.0 ) {
return [ time, value, inTime ];
} else if ( value !== 0.0 ) {
return [ time, value ];
} else if ( time !== 0.0 ) {
return [ time ];
} else {
return [];
}
} );
}
/**
* Serialize its fxs.
* @returns Serialized fxs
*/
private __serializeFxs(): SerializedFxSection[] | undefined {
if ( this.__fxs.length === 0 ) { return undefined; }
return this.__fxs.map( ( fx ) => {
const data: SerializedFxSection = {
def: fx.def,
params: jsonCopy( fx.params )
};
if ( fx.time !== 0.0 ) {
data.time = fx.time;
}
if ( fx.length !== 0.0 ) {
data.length = fx.length;
}
if ( fx.row !== 0 ) {
data.row = fx.row;
}
if ( fx.bypass ) {
data.bypass = true;
}
return data;
} );
}
/**
* Watch for status changes.
* Execute given procedure immediately.
* If the procedure changes its status, emit an event.
* @param procedure A procedure that might change its status
*/
private __watchStatus( procedure: () => void ): void {
const prevStatus = this.status;
procedure();
if ( prevStatus !== this.status ) {
this.__emit( 'updateStatus' );
}
}
/**
* Sort nodes by time.
*/
private __sortNodes(): void {
this.__nodes = this.__nodes.sort( ( a, b ) => a.time - b.time );
}
/**
* Search for node that has given id then return index of it.
* If it couldn't find the node, it will throw an error instead.
* @param id Id of node you want to grab
* @returns The index of the node
*/
private __getNodeIndexById( id: string ): number {
const index = this.__nodes.findIndex( ( node ) => node.$id === id );
if ( index === -1 ) { throw new Error( `Searched for node id: ${id} but not found` ); }
return index;
}
/**
* Sort fxs by time.
*/
private __sortFxs(): void {
this.__fxs = this.__fxs.sort( ( a, b ) => a.time - b.time ).sort( ( a, b ) => a.row - b.row );
}
/**
* Search for fx section that has given id then return index of it.
* If it couldn't find the section, it will throw an error instead.
* @param id Id of section you want to grab
* @returns The index of the section
*/
private __getFxIndexById( id: string ): number {
const index = this.__fxs.findIndex( ( fx ) => fx.$id === id );
if ( index === -1 ) { throw new Error( `Searched for fx id: ${id} but not found` ); }
return index;
}
/**
* Search for vacance fx row for given time and length.
* @param time Beginning time of fx
* @param length Length of fx
* @param row If given, rows lower than this value will not be searched.
* @returns Minimal free fx row
*/
private __getFreeRow( _time: number, _length: number, _row: number = 0 ): number {
let row = _row || 0;
for ( let iFx = 0; iFx < this.__fxs.length; iFx ++ ) {
const fx = this.__fxs[ iFx ];
if ( fx.row < row ) { continue; }
if ( row < fx.row ) { break; }
if ( hasOverwrap( _time, _length, fx.time, fx.length ) ) {
row ++;
}
}
return row;
}
}
export interface CurveWithGUIEvents {
createNode: { id: string; node: BezierNode & WithID };
updateNode: { id: string; node: BezierNode & WithID };
removeNode: { id: string };
createFx: { id: string; fx: FxSection & WithBypass & WithID };
updateFx: { id: string; fx: FxSection & WithBypass & WithID };
removeFx: { id: string };
previewTime: {
time: number;
value: number;
itemTime: number;
itemSpeed: number;
itemOffset: number;
};
precalc: void;
updateStatus: void;
changeLength: { length: number };
}
applyMixins( CurveWithGUI, [ SerializableWithID, EventEmittable, WithStatus ] ); | the_stack |
import * as ES from './ecmascript';
import { GetIntrinsic, MakeIntrinsicClass } from './intrinsicclass';
import {
ISO_YEAR,
ISO_MONTH,
ISO_DAY,
ISO_HOUR,
ISO_MINUTE,
ISO_SECOND,
ISO_MILLISECOND,
ISO_MICROSECOND,
ISO_NANOSECOND,
CALENDAR,
EPOCHNANOSECONDS,
GetSlot
} from './slots';
import { Temporal } from '..';
import { DateTimeFormat } from './intl';
import type { PlainDateParams as Params, PlainDateReturn as Return } from './internaltypes';
const DISALLOWED_UNITS = ['hour', 'minute', 'second', 'millisecond', 'microsecond', 'nanosecond'] as const;
export class PlainDate implements Temporal.PlainDate {
constructor(
isoYearParam: Params['constructor'][0],
isoMonthParam: Params['constructor'][1],
isoDayParam: Params['constructor'][2],
calendarParam: Params['constructor'][3] = ES.GetISO8601Calendar()
) {
const isoYear = ES.ToIntegerThrowOnInfinity(isoYearParam);
const isoMonth = ES.ToIntegerThrowOnInfinity(isoMonthParam);
const isoDay = ES.ToIntegerThrowOnInfinity(isoDayParam);
const calendar = ES.ToTemporalCalendar(calendarParam);
// Note: if the arguments are not passed,
// ToIntegerThrowOnInfinity(undefined) will have returned 0, which will
// be rejected by RejectISODate in CreateTemporalDateSlots. This check
// exists only to improve the error message.
if (arguments.length < 3) {
throw new RangeError('missing argument: isoYear, isoMonth and isoDay are required');
}
ES.CreateTemporalDateSlots(this, isoYear, isoMonth, isoDay, calendar);
}
get calendar(): Return['calendar'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return GetSlot(this, CALENDAR);
}
get era(): Return['era'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarEra(GetSlot(this, CALENDAR), this);
}
get eraYear(): Return['eraYear'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarEraYear(GetSlot(this, CALENDAR), this);
}
get year(): Return['year'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarYear(GetSlot(this, CALENDAR), this);
}
get month(): Return['month'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarMonth(GetSlot(this, CALENDAR), this);
}
get monthCode(): Return['monthCode'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarMonthCode(GetSlot(this, CALENDAR), this);
}
get day(): Return['day'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarDay(GetSlot(this, CALENDAR), this);
}
get dayOfWeek(): Return['dayOfWeek'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarDayOfWeek(GetSlot(this, CALENDAR), this);
}
get dayOfYear(): Return['dayOfYear'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarDayOfYear(GetSlot(this, CALENDAR), this);
}
get weekOfYear(): Return['weekOfYear'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarWeekOfYear(GetSlot(this, CALENDAR), this);
}
get daysInWeek(): Return['daysInWeek'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarDaysInWeek(GetSlot(this, CALENDAR), this);
}
get daysInMonth(): Return['daysInMonth'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarDaysInMonth(GetSlot(this, CALENDAR), this);
}
get daysInYear(): Return['daysInYear'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarDaysInYear(GetSlot(this, CALENDAR), this);
}
get monthsInYear(): Return['monthsInYear'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarMonthsInYear(GetSlot(this, CALENDAR), this);
}
get inLeapYear(): Return['inLeapYear'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.CalendarInLeapYear(GetSlot(this, CALENDAR), this);
}
with(temporalDateLike: Params['with'][0], optionsParam: Params['with'][1] = undefined): Return['with'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
if (!ES.IsObject(temporalDateLike)) {
throw new TypeError('invalid argument');
}
ES.RejectObjectWithCalendarOrTimeZone(temporalDateLike);
const calendar = GetSlot(this, CALENDAR);
const fieldNames = ES.CalendarFields(calendar, ['day', 'month', 'monthCode', 'year'] as const);
const props = ES.ToPartialRecord(temporalDateLike, fieldNames);
if (!props) {
throw new TypeError('invalid date-like');
}
let fields = ES.ToTemporalDateFields(this, fieldNames);
fields = ES.CalendarMergeFields(calendar, fields, props);
fields = ES.ToTemporalDateFields(fields, fieldNames);
const options = ES.GetOptionsObject(optionsParam);
return ES.DateFromFields(calendar, fields, options);
}
withCalendar(calendarParam: Params['withCalendar'][0]): Return['withCalendar'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
const calendar = ES.ToTemporalCalendar(calendarParam);
return new PlainDate(GetSlot(this, ISO_YEAR), GetSlot(this, ISO_MONTH), GetSlot(this, ISO_DAY), calendar);
}
add(temporalDurationLike: Params['add'][0], optionsParam: Params['add'][1] = undefined): Return['add'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
const duration = ES.ToTemporalDuration(temporalDurationLike);
const options = ES.GetOptionsObject(optionsParam);
return ES.CalendarDateAdd(GetSlot(this, CALENDAR), this, duration, options);
}
subtract(
temporalDurationLike: Params['subtract'][0],
optionsParam: Params['subtract'][1] = undefined
): Return['subtract'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
const duration = ES.CreateNegatedTemporalDuration(ES.ToTemporalDuration(temporalDurationLike));
const options = ES.GetOptionsObject(optionsParam);
return ES.CalendarDateAdd(GetSlot(this, CALENDAR), this, duration, options);
}
until(otherParam: Params['until'][0], optionsParam: Params['until'][1] = undefined): Return['until'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
const other = ES.ToTemporalDate(otherParam);
const calendar = GetSlot(this, CALENDAR);
const otherCalendar = GetSlot(other, CALENDAR);
const calendarId = ES.ToString(calendar);
const otherCalendarId = ES.ToString(otherCalendar);
if (calendarId !== otherCalendarId) {
throw new RangeError(`cannot compute difference between dates of ${calendarId} and ${otherCalendarId} calendars`);
}
const options = ES.GetOptionsObject(optionsParam);
const smallestUnit = ES.ToSmallestTemporalUnit(options, 'day', DISALLOWED_UNITS);
const defaultLargestUnit = ES.LargerOfTwoTemporalUnits('day', smallestUnit);
const largestUnit = ES.ToLargestTemporalUnit(options, 'auto', DISALLOWED_UNITS, defaultLargestUnit);
ES.ValidateTemporalUnitRange(largestUnit, smallestUnit);
const roundingMode = ES.ToTemporalRoundingMode(options, 'trunc');
const roundingIncrement = ES.ToTemporalRoundingIncrement(options, undefined, false);
const untilOptions = { ...options, largestUnit };
const result = ES.CalendarDateUntil(calendar, this, other, untilOptions);
if (smallestUnit === 'day' && roundingIncrement === 1) return result;
let { years, months, weeks, days } = result;
({ years, months, weeks, days } = ES.RoundDuration(
years,
months,
weeks,
days,
0,
0,
0,
0,
0,
0,
roundingIncrement,
smallestUnit,
roundingMode,
this
));
const Duration = GetIntrinsic('%Temporal.Duration%');
return new Duration(years, months, weeks, days, 0, 0, 0, 0, 0, 0);
}
since(otherParam: Params['since'][0], optionsParam: Params['since'][1] = undefined): Return['since'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
const other = ES.ToTemporalDate(otherParam);
const calendar = GetSlot(this, CALENDAR);
const otherCalendar = GetSlot(other, CALENDAR);
const calendarId = ES.ToString(calendar);
const otherCalendarId = ES.ToString(otherCalendar);
if (calendarId !== otherCalendarId) {
throw new RangeError(`cannot compute difference between dates of ${calendarId} and ${otherCalendarId} calendars`);
}
const options = ES.GetOptionsObject(optionsParam);
const smallestUnit = ES.ToSmallestTemporalUnit(options, 'day', DISALLOWED_UNITS);
const defaultLargestUnit = ES.LargerOfTwoTemporalUnits('day', smallestUnit);
const largestUnit = ES.ToLargestTemporalUnit(options, 'auto', DISALLOWED_UNITS, defaultLargestUnit);
ES.ValidateTemporalUnitRange(largestUnit, smallestUnit);
const roundingMode = ES.ToTemporalRoundingMode(options, 'trunc');
const roundingIncrement = ES.ToTemporalRoundingIncrement(options, undefined, false);
const untilOptions = { ...options, largestUnit };
let { years, months, weeks, days } = ES.CalendarDateUntil(calendar, this, other, untilOptions);
const Duration = GetIntrinsic('%Temporal.Duration%');
if (smallestUnit === 'day' && roundingIncrement === 1) {
return new Duration(-years, -months, -weeks, -days, 0, 0, 0, 0, 0, 0);
}
({ years, months, weeks, days } = ES.RoundDuration(
years,
months,
weeks,
days,
0,
0,
0,
0,
0,
0,
roundingIncrement,
smallestUnit,
ES.NegateTemporalRoundingMode(roundingMode),
this
));
return new Duration(-years, -months, -weeks, -days, 0, 0, 0, 0, 0, 0);
}
equals(otherParam: Params['equals'][0]): Return['equals'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
const other = ES.ToTemporalDate(otherParam);
for (const slot of [ISO_YEAR, ISO_MONTH, ISO_DAY]) {
const val1 = GetSlot(this, slot);
const val2 = GetSlot(other, slot);
if (val1 !== val2) return false;
}
return ES.CalendarEquals(GetSlot(this, CALENDAR), GetSlot(other, CALENDAR));
}
toString(optionsParam: Params['toString'][0] = undefined): string {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
const options = ES.GetOptionsObject(optionsParam);
const showCalendar = ES.ToShowCalendarOption(options);
return ES.TemporalDateToString(this, showCalendar);
}
toJSON(): Return['toJSON'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return ES.TemporalDateToString(this);
}
toLocaleString(
locales: Params['toLocaleString'][0] = undefined,
options: Params['toLocaleString'][1] = undefined
): string {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return new DateTimeFormat(locales, options).format(this);
}
valueOf(): never {
throw new TypeError('use compare() or equals() to compare Temporal.PlainDate');
}
toPlainDateTime(temporalTimeParam: Params['toPlainDateTime'][0] = undefined): Return['toPlainDateTime'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
const year = GetSlot(this, ISO_YEAR);
const month = GetSlot(this, ISO_MONTH);
const day = GetSlot(this, ISO_DAY);
const calendar = GetSlot(this, CALENDAR);
if (temporalTimeParam === undefined) return ES.CreateTemporalDateTime(year, month, day, 0, 0, 0, 0, 0, 0, calendar);
const temporalTime = ES.ToTemporalTime(temporalTimeParam);
const hour = GetSlot(temporalTime, ISO_HOUR);
const minute = GetSlot(temporalTime, ISO_MINUTE);
const second = GetSlot(temporalTime, ISO_SECOND);
const millisecond = GetSlot(temporalTime, ISO_MILLISECOND);
const microsecond = GetSlot(temporalTime, ISO_MICROSECOND);
const nanosecond = GetSlot(temporalTime, ISO_NANOSECOND);
return ES.CreateTemporalDateTime(
year,
month,
day,
hour,
minute,
second,
millisecond,
microsecond,
nanosecond,
calendar
);
}
toZonedDateTime(item: Params['toZonedDateTime'][0]): Return['toZonedDateTime'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
let timeZone, temporalTime;
if (ES.IsObject(item)) {
const timeZoneLike = item.timeZone;
if (timeZoneLike === undefined) {
// The cast below is needed because it's possible here for
// `timeZoneLike` here to be `{ plainTime: Temporal.PlainTimeLike }`,
// not a TimeZoneProtocol.
// TODO: should we check for that shape to improve on the (bad) error
// message that the caller will get from ToTemporalTimeZone?
timeZone = ES.ToTemporalTimeZone(item as Temporal.TimeZoneProtocol);
} else {
timeZone = ES.ToTemporalTimeZone(timeZoneLike);
type TimeZoneAndPlainTimeProps = Exclude<typeof item, Temporal.TimeZoneProtocol>;
temporalTime = (item as TimeZoneAndPlainTimeProps).plainTime;
}
} else {
timeZone = ES.ToTemporalTimeZone(item);
}
const year = GetSlot(this, ISO_YEAR);
const month = GetSlot(this, ISO_MONTH);
const day = GetSlot(this, ISO_DAY);
const calendar = GetSlot(this, CALENDAR);
let hour = 0,
minute = 0,
second = 0,
millisecond = 0,
microsecond = 0,
nanosecond = 0;
if (temporalTime !== undefined) {
temporalTime = ES.ToTemporalTime(temporalTime);
hour = GetSlot(temporalTime, ISO_HOUR);
minute = GetSlot(temporalTime, ISO_MINUTE);
second = GetSlot(temporalTime, ISO_SECOND);
millisecond = GetSlot(temporalTime, ISO_MILLISECOND);
microsecond = GetSlot(temporalTime, ISO_MICROSECOND);
nanosecond = GetSlot(temporalTime, ISO_NANOSECOND);
}
const dt = ES.CreateTemporalDateTime(
year,
month,
day,
hour,
minute,
second,
millisecond,
microsecond,
nanosecond,
calendar
);
const instant = ES.BuiltinTimeZoneGetInstantFor(timeZone, dt, 'compatible');
return ES.CreateTemporalZonedDateTime(GetSlot(instant, EPOCHNANOSECONDS), timeZone, calendar);
}
toPlainYearMonth(): Return['toPlainYearMonth'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
const calendar = GetSlot(this, CALENDAR);
const fieldNames = ES.CalendarFields(calendar, ['monthCode', 'year'] as const);
const fields = ES.ToTemporalYearMonthFields(this, fieldNames);
return ES.YearMonthFromFields(calendar, fields);
}
toPlainMonthDay(): Return['toPlainMonthDay'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
const calendar = GetSlot(this, CALENDAR);
const fieldNames = ES.CalendarFields(calendar, ['day', 'monthCode'] as const);
const fields = ES.ToTemporalMonthDayFields(this, fieldNames);
return ES.MonthDayFromFields(calendar, fields);
}
getISOFields(): Return['getISOFields'] {
if (!ES.IsTemporalDate(this)) throw new TypeError('invalid receiver');
return {
calendar: GetSlot(this, CALENDAR),
isoDay: GetSlot(this, ISO_DAY),
isoMonth: GetSlot(this, ISO_MONTH),
isoYear: GetSlot(this, ISO_YEAR)
};
}
static from(item: Params['from'][0], optionsParam: Params['from'][1] = undefined): Return['from'] {
const options = ES.GetOptionsObject(optionsParam);
if (ES.IsTemporalDate(item)) {
ES.ToTemporalOverflow(options); // validate and ignore
return ES.CreateTemporalDate(
GetSlot(item, ISO_YEAR),
GetSlot(item, ISO_MONTH),
GetSlot(item, ISO_DAY),
GetSlot(item, CALENDAR)
);
}
return ES.ToTemporalDate(item, options);
}
static compare(oneParam: Params['compare'][0], twoParam: Params['compare'][1]): Return['compare'] {
const one = ES.ToTemporalDate(oneParam);
const two = ES.ToTemporalDate(twoParam);
return ES.CompareISODate(
GetSlot(one, ISO_YEAR),
GetSlot(one, ISO_MONTH),
GetSlot(one, ISO_DAY),
GetSlot(two, ISO_YEAR),
GetSlot(two, ISO_MONTH),
GetSlot(two, ISO_DAY)
);
}
[Symbol.toStringTag]!: 'Temporal.PlainDate';
}
MakeIntrinsicClass(PlainDate, 'Temporal.PlainDate'); | the_stack |
import { Component, OnDestroy, ViewChild, ElementRef, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DefaultApi } from '../../../../../../gen/api/DefaultApi';
import { Http } from '@angular/http';
import { BibTeXEntry } from '../../../../../../gen/model/BibTeXEntry';
import { Subscription } from 'rxjs/Subscription';
import { Rating } from '../../../../../../gen/model/Rating';
import UserRatingEnum = Rating.UserRatingEnum;
import { BracesValidator } from '../../../../../../theme/validators/braces.validator';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { getErrorMessage } from '../../../../../../shared/errorHandler';
@Component({
selector: 'reference-view',
templateUrl: './referenceview.html',
styleUrls: ['./referenceview.scss'],
})
export class ReferenceViewComponent implements OnInit, OnDestroy {
types = [
'article',
'book',
'booklet',
'conference',
'inbook',
'incollection',
'inproceedings',
'manual',
'mastersthesis',
'misc',
'phdthesis',
'proceedings',
'techreport',
'unpublished',
'standard',
];
article = [
// required fields
'title',
'author',
'journal',
'year',
];
articleOptional = [
// optional fields
'volume',
'pages',
'issn',
'number',
'month',
'note',
];
book = [
// required fields
'title',
'publisher',
'year',
'author',
'editor',
];
bookOptional = [
// optional fields
'volume',
'isbn',
'number',
'series',
'address',
'edition',
'month',
'note',
];
inbook = [
// required fields
'title',
'chapter',
'pages',
'publisher',
'year',
'author',
'editor',
];
inbookOptional = [
// optional fields
'volume',
'isbn',
'number',
'series',
'type',
'address',
'edition',
'month',
'note',
];
incollection = [
// required fields
'title',
'booktitle',
'publisher',
'year',
'author',
];
incollectionOptional = [
// optional fields
'editor',
'volume',
'isbn',
'number',
'series',
'type',
'chapter',
'pages',
'address',
'edition',
'month',
'note',
];
inproceedings = [
// required fields
'title',
'booktitle',
'year',
'author',
];
inproceedingsOptional = [
// optional fields
'editor',
'volume',
'number',
'series',
'pages',
'address',
'month',
'organization',
'publisher',
'note',
];
manual = [
// required fields
'title',
];
manualOptional = [
// optional fields
'author',
'address',
'edition',
'month',
'organization',
'year',
'isbn',
'note',
];
miscOptional = [
// optional fields
'author',
'title',
'howpublished',
'month',
'year',
'note',
];
phdthesis = [
// required fields
'author',
'title',
'school',
'year',
];
phdthesisOptional = [
// optional fields
'type',
'address',
'month',
'note',
];
standard = [
// required fields
'title',
'organization',
'institution',
];
standardOptional = [
// optional fields
'author',
'language',
'howpublished',
'type',
'number',
'revision',
'address',
'month',
'year',
'url',
'note',
];
techreport = [
// required fields
'author',
'title',
'year',
'institution',
];
techreportOptional = [
// optional fields
'type',
'number',
'address',
'month',
'note',
];
booklet = [
// required fields
'title',
];
bookletOptional = [
// optional fields
'author',
'howpublished',
'address',
'month',
'year',
'note',
];
conference = [
// required fields
'title',
'booktitle',
'year',
'author',
];
conferenceOptional = [
// optional fields
'editor',
'volume',
'number',
'series',
'pages',
'address',
'month',
'organization',
'publisher',
'note',
];
mastersthesis = [
// required fields
'author',
'title',
'school',
'year',
];
mastersthesisOptional = [
// optional fields
'type',
'address',
'month',
'note',
];
proceedings = [
// required fields
'title',
'year',
];
proceedingsOptional = [
// optional fields
'editor',
'volume',
'number',
'series',
'address',
'publisher',
'month',
'organization',
'isbn',
'note',
];
unpublished = [
// required fields
'author',
'title',
'note',
];
unpublishedOptional = [
// optional fields
'month',
'year',
];
id: string;
private sub: any;
addFile: Function;
saved: boolean = false;
errorUpload: boolean = false;
errorNoFile: boolean = false;
savedCounter: number = 0;
errorUploadCounter: number = 0;
errorNoFileCounter: number = 0;
userRatingEnum = UserRatingEnum;
ratingUser: UserRatingEnum;
ratingReference: number;
confirmedReference: boolean = false;
httpErrorMsg = null;
httpErrorMsgFile = null;
reference: BibTeXEntry = {
type: {
value: 'article',
},
key: {
value: '',
},
fields: {
title: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
author: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
journal: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
publisher: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
editor: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
chapter: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
pages: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
booktitle: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
school: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
organization: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
institution: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
month: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
year: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
crossrefString: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
keywords: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
Pdf: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
doi: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
url: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
comment: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
volume: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
issn: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
number: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
isbn: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
series: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
address: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
edition: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
type: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
howpublished: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
language: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
revision: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
note: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
abstract: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
review: {
string: '',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
},
},
// crossReference: null,
};
changedType: boolean = false;
setChangedType() {
this.changedType = true;
}
containsField(fieldName, tab) {
switch (this.reference.type.value) {
case 'article':
if (tab === 'required' && this.article.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.articleOptional.includes(fieldName)) {
return true;
}
break;
case 'book':
if (tab === 'required' && this.book.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.bookOptional.includes(fieldName)) {
return true;
}
break;
case 'inbook':
if (tab === 'required' && this.inbook.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.inbookOptional.includes(fieldName)) {
return true;
}
break;
case 'incollection':
if (tab === 'required' && this.incollection.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.incollectionOptional.includes(fieldName)) {
return true;
}
break;
case 'inproceedings':
if (tab === 'required' && this.inproceedings.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.inproceedingsOptional.includes(fieldName)) {
return true;
}
break;
case 'manual':
if (tab === 'required' && this.manual.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.manualOptional.includes(fieldName)) {
return true;
}
break;
case 'misc':
if (tab === 'optional' && this.miscOptional.includes(fieldName)) {
return true;
}
break;
case 'phdthesis':
if (tab === 'required' && this.phdthesis.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.phdthesisOptional.includes(fieldName)) {
return true;
}
break;
case 'standard':
if (tab === 'required' && this.standard.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.standardOptional.includes(fieldName)) {
return true;
}
break;
case 'techreport':
if (tab === 'required' && this.techreport.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.techreportOptional.includes(fieldName)) {
return true;
}
break;
case 'booklet':
if (tab === 'required' && this.booklet.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.bookletOptional.includes(fieldName)) {
return true;
}
break;
case 'conference':
if (tab === 'required' && this.conference.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.conferenceOptional.includes(fieldName)) {
return true;
}
break;
case 'mastersthesis':
if (tab === 'required' && this.mastersthesis.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.mastersthesisOptional.includes(fieldName)) {
return true;
}
break;
case 'proceedings':
if (tab === 'required' && this.proceedings.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.proceedingsOptional.includes(fieldName)) {
return true;
}
break;
case 'unpublished':
if (tab === 'required' && this.unpublished.includes(fieldName)) {
return true;
} else if (tab === 'optional' && this.unpublishedOptional.includes(fieldName)) {
return true;
}
break;
}
return false;
}
@Input() defaultValue: string = '';
@ViewChild('fileInput') fileInput: ElementRef;
@Input('loadReferences') loadReferences: boolean = false;
@Input('loadSuggestion') loadSuggestion: boolean = false;
loading: boolean = true;
suggestionId: number;
showFileSelector(): boolean {
this.fileInput.nativeElement.click();
return false;
}
setFileNameAtInput(): void {
const fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
this.defaultValue = fi.files[0].name;
} else {
this.defaultValue = '';
}
}
formTabRequired: FormGroup;
formTabOptional: FormGroup;
formTabGeneral: FormGroup;
formTabAbstract: FormGroup;
formTabReview: FormGroup;
errorMessageBraces: string = 'Braces do not match! Please adjust your text.';
errorMessageNumbers: string = 'No valid input! Only numbers are allowed.';
constructor(private router: Router, private route: ActivatedRoute, private api: DefaultApi, protected http: Http) {
this.formTabRequired = new FormGroup({
'bibtexid': new FormControl('', [Validators.pattern('[a-zA-Z-0-9]*')]),
'chapter': new FormControl('', [BracesValidator.validate]),
'pages': new FormControl('', [BracesValidator.validate]),
'title': new FormControl('', [BracesValidator.validate]),
'booktitle': new FormControl('', [BracesValidator.validate]),
'publisher': new FormControl('', [BracesValidator.validate]),
'journal': new FormControl('', [BracesValidator.validate]),
'school': new FormControl('', [BracesValidator.validate]),
'year': new FormControl('', [Validators.pattern('[1-9][0-9]*')]),
'author': new FormControl('', [BracesValidator.validate]),
'editor': new FormControl('', [BracesValidator.validate]),
'organization': new FormControl('', [BracesValidator.validate]),
'institution': new FormControl('', [BracesValidator.validate]),
'note': new FormControl('', [BracesValidator.validate]),
});
this.formTabOptional = new FormGroup({
'author': new FormControl('', [BracesValidator.validate]),
'title': new FormControl('', [BracesValidator.validate]),
'language': new FormControl('', [BracesValidator.validate]),
'editor': new FormControl('', [BracesValidator.validate]),
'volume': new FormControl('', [BracesValidator.validate]),
'number': new FormControl('', [BracesValidator.validate]),
'revision': new FormControl('', [BracesValidator.validate]),
'series': new FormControl('', [BracesValidator.validate]),
'type': new FormControl('', [BracesValidator.validate]),
'chapter': new FormControl('', [BracesValidator.validate]),
'pages': new FormControl('', [BracesValidator.validate]),
'organization': new FormControl('', [BracesValidator.validate]),
'address': new FormControl('', [BracesValidator.validate]),
'edition': new FormControl('', [BracesValidator.validate]),
'howpublished': new FormControl('', [BracesValidator.validate]),
'month': new FormControl('', [BracesValidator.validate]),
'year': new FormControl('', [Validators.pattern('[1-9][0-9]*')]),
'publisher': new FormControl('', [BracesValidator.validate]),
'issn': new FormControl('', [BracesValidator.validate]),
'isbn': new FormControl('', [BracesValidator.validate]),
'note': new FormControl('', [BracesValidator.validate]),
'url': new FormControl('', [BracesValidator.validate]),
});
this.formTabGeneral = new FormGroup({
'crossref': new FormControl('', [Validators.pattern('[a-zA-Z-0-9]*')]),
'keywords': new FormControl('', [BracesValidator.validate]),
'doi': new FormControl('', [BracesValidator.validate]),
'url': new FormControl('', [BracesValidator.validate]),
'comment': new FormControl('', [BracesValidator.validate]),
});
this.formTabAbstract = new FormGroup({
'abstract': new FormControl('', [BracesValidator.validate]),
});
this.formTabReview = new FormGroup({
'review': new FormControl('', [BracesValidator.validate]),
});
this.sub = this.route.params.subscribe(params => {
this.reference.key.value = params['id'];
this.suggestionId = Number(params['idSuggestion']);
});
this.addFile = function () {
const fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
const fileToUpload = fi.files[0];
this.api.savePdfFile(this.reference.key.value, fileToUpload).subscribe(
data => {
if (!this.loadReferences) {
// navigate user to new reference
this.router.navigate(['references', this.reference.key.value]);
} else {
this.reference.fields.Pdf = {
string: 'true',
type: 'org.jbibtex.StringValue',
style: 'BRACED',
};
// saved file, reset form and show success to user
var form = <HTMLFormElement> document.getElementById('fileUploadFrom');
form.reset();
this.defaultValue = '';
this.savedCounter++;
this.saved = true;
setTimeout(() => {
this.savedCounter--;
if (this.savedCounter === 0) {
this.saved = false;
}
}, 5000);
}
},
error => {
// get error message for user
this.httpErrorMsgFile = getErrorMessage(error);
this.errorUploadCounter++;
this.errorUpload = true;
setTimeout(() => {
this.errorUploadCounter--;
if (this.errorUploadCounter === 0) {
this.errorUpload = false;
}
}, 5000);
},
);
} else {
if (!this.loadReferences) {
// navigate user to new reference
this.router.navigate(['references', this.reference.key.value]);
} else {
// show alert if no file is selected
if (this.loadReferences) {
this.errorNoFileCounter++;
this.errorNoFile = true;
setTimeout(() => {
this.errorNoFileCounter--;
if (this.errorNoFileCounter === 0) {
this.errorNoFile = false;
}
}, 5000);
}
}
}
};
}
existsKeyAlreadyATBackend(key: string, crossref: boolean) {
this.api.getReference(key).subscribe(val => {
if (!crossref) {
this.keyExists = true;
} else {
this.crossrefExists = true;
}
},
(err) => {
if (err.status === 404) {
if (!crossref) {
this.keyExists = false;
} else {
this.crossrefExists = false;
}
} else {
this.errorHandler(err);
}
},
);
}
pdfView() {
this.router.navigate(['references', this.reference.key.value, 'pdf', 'comments']);
}
viewSuggestions() {
this.router.navigate(['references', this.reference.key.value, 'suggestions']);
}
keyExists: boolean = false;
crossrefExists: boolean = true;
validateBibTeXKey() {
if (this.formTabRequired.controls['bibtexid'].valid) {
// check if bibtexkey exists at backend
this.existsKeyAlreadyATBackend(this.reference.key.value, false);
}
}
existsCrossref(crossref: string) {
if (this.formTabGeneral.controls['crossref'].valid) {
this.existsKeyAlreadyATBackend(crossref, true);
} else {
// if entered key is not valid it cannot exist at backend
this.crossrefExists = false;
}
}
private subscription: Subscription;
saveSuggestion() {
// check if form content is valid
if (this.formTabRequired.valid && this.formTabOptional.valid && this.formTabGeneral.valid &&
this.formTabAbstract.valid && this.formTabReview.valid) {
if (!this.loadSuggestion) {
// save suggestion
this.api.saveSuggestion(this.reference.key.value, this.reference).subscribe(
data => {
// navigate user to suggestions
this.viewSuggestions();
},
(err) => {
this.errorHandler(err);
},
);
} else {
// update suggestion
this.api.updateSuggestion(this.reference.key.value, this.suggestionId, this.reference).subscribe(
data => {
// navigate user to suggestions
this.viewSuggestions();
},
(err) => {
this.errorHandler(err);
},
);
}
} else {
// jump to tab to show invalid input
this.jumpToInvalidContent();
}
}
save() {
// check if form content is valid
if (!this.keyExists && this.formTabRequired.valid && this.formTabOptional.valid && this.formTabGeneral.valid &&
this.formTabAbstract.valid && this.formTabReview.valid) {
// call api to save new reference
this.subscription = this.api.saveReference(this.reference.key.value, this.reference).subscribe(
data => {
// try to upload file if new reference is saved
this.addFile();
},
(err) => {
this.errorHandler(err);
},
);
} else {
// jump to tab to show invalid input
this.jumpToInvalidContent();
}
}
jumpToInvalidContent() {
// jump to tab to show invalid input
if (!this.formTabRequired.valid) {
let link = <HTMLAnchorElement> document.getElementsByClassName('nav-link')[0];
link.click();
} else if (!this.formTabOptional.valid) {
let link = <HTMLAnchorElement> document.getElementsByClassName('nav-link')[1];
link.click();
} else if (!this.formTabGeneral.valid) {
let link = <HTMLAnchorElement> document.getElementsByClassName('nav-link')[2];
link.click();
} else if (!this.formTabAbstract.valid) {
let link = <HTMLAnchorElement> document.getElementsByClassName('nav-link')[3];
link.click();
} else if (!this.formTabReview.valid) {
let link = <HTMLAnchorElement> document.getElementsByClassName('nav-link')[4];
link.click();
}
}
rateReference(rating: UserRatingEnum) {
// check if rating changed
if (this.ratingUser != rating) {
let rate: Rating = {
userRating: rating,
};
this.api.rateReference(this.reference.key.value, rate).subscribe(val => {
// change overall rating
this.ratingReference = val.overallRating;
// change rating of user
this.ratingUser = rating;
// set confirmed
this.confirmedReference = val.confirmed;
},
(err) => {
this.errorHandler(err);
},
);
}
}
private errorHandler(err: any) {
// show error to user
this.httpErrorMsg = getErrorMessage(err);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
ngOnInit() {
if (this.loadReferences) {
// get references from backend
this.api.getReference(this.reference.key.value).subscribe(val => {
// get ratings
if (val.fields.Confirmed != null) {
var s = JSON.stringify(val.fields.Confirmed);
if (s.indexOf('true') >= 0) {
this.confirmedReference = true;
} else {
this.confirmedReference = false;
}
}
if (val.fields.RatedByUser != null) {
var s = JSON.stringify(val.fields.RatedByUser);
if (s.indexOf('POSITIVE') >= 0) {
this.ratingUser = UserRatingEnum.POSITIVE;
} else if (s.indexOf('NEGATIVE') >= 0) {
this.ratingUser = UserRatingEnum.NEGATIVE;
}
}
if (val.fields.OverallRating != null) {
let s = JSON.stringify(val.fields.OverallRating);
if (s.indexOf('string') >= 0) {
let sub = s.substring(s.indexOf('string'), s.length - 1);
// get number from JSON
let array = sub.split('"');
if (array[2] != '') {
this.ratingReference = Number(array[2]);
}
}
}
// update reference fields
this.updateReferenceValues(val);
},
(err) => {
this.errorHandler(err);
},
);
} else if (this.loadSuggestion) {
this.api.getSuggestion(this.reference.key.value, this.suggestionId).subscribe(val => {
// update reference fields
this.updateReferenceValues(val);
},
(err) => {
this.errorHandler(err);
},
);
}
}
updateReferenceValues(val: any) {
// get reference
this.reference.type = val.type;
this.reference.key = val.key;
if (val.fields.title != null) {
this.reference.fields.title = val.fields.title;
}
if (val.fields.author != null) {
this.reference.fields.author = val.fields.author;
}
if (val.fields.journal != null) {
this.reference.fields.journal = val.fields.journal;
}
if (val.fields.year != null) {
this.reference.fields.year = val.fields.year;
}
if (val.fields.publisher != null) {
this.reference.fields.publisher = val.fields.publisher;
}
if (val.fields.editor != null) {
this.reference.fields.editor = val.fields.editor;
}
if (val.fields.chapter != null) {
this.reference.fields.chapter = val.fields.chapter;
}
if (val.fields.pages != null) {
this.reference.fields.pages = val.fields.pages;
}
if (val.fields.booktitle != null) {
this.reference.fields.booktitle = val.fields.booktitle;
}
if (val.fields.school != null) {
this.reference.fields.school = val.fields.school;
}
if (val.fields.organization != null) {
this.reference.fields.organization = val.fields.organization;
}
if (val.fields.institution != null) {
this.reference.fields.institution = val.fields.institution;
}
if (val.fields.note != null) {
this.reference.fields.note = val.fields.note;
}
if (val.fields.abstract != null) {
this.reference.fields.abstract = val.fields.abstract;
}
if (val.fields.review != null) {
this.reference.fields.review = val.fields.review;
}
if (val.fields.crossrefString != null) {
this.reference.fields.crossrefString = val.fields.crossrefString;
}
if (val.fields.keywords != null) {
this.reference.fields.keywords = val.fields.keywords;
}
if (val.fields.Pdf != null) {
this.reference.fields.Pdf = val.fields.Pdf;
}
if (val.fields.doi != null) {
this.reference.fields.doi = val.fields.doi;
}
if (val.fields.url != null) {
this.reference.fields.url = val.fields.url;
}
if (val.fields.comment != null) {
this.reference.fields.comment = val.fields.comment;
}
if (val.fields.volume != null) {
this.reference.fields.volume = val.fields.volume;
}
if (val.fields.number != null) {
this.reference.fields.number = val.fields.number;
}
if (val.fields.issn != null) {
this.reference.fields.issn = val.fields.issn;
}
if (val.fields.month != null) {
this.reference.fields.month = val.fields.month;
}
if (val.fields.isbn != null) {
this.reference.fields.isbn = val.fields.isbn;
}
if (val.fields.series != null) {
this.reference.fields.series = val.fields.series;
}
if (val.fields.address != null) {
this.reference.fields.address = val.fields.address;
}
if (val.fields.edition != null) {
this.reference.fields.edition = val.fields.edition;
}
if (val.fields.type != null) {
this.reference.fields.type = val.fields.type;
}
if (val.fields.howpublished != null) {
this.reference.fields.howpublished = val.fields.howpublished;
}
if (val.fields.language != null) {
this.reference.fields.language = val.fields.language;
}
if (val.fields.revision != null) {
this.reference.fields.revision = val.fields.revision;
}
// finished loading
this.loading = false;
}
} | the_stack |
import * as params from './params';
import {PBES2ESParams, PBEParameter, PBES2Params, PBKDF2Params, OneAsymmetricKey, EncryptedPrivateKeyInfo} from './asn1def';
import des from 'des.js';
import * as BufferMod from 'buffer';
import asn from 'asn1.js';
import jseu from 'js-encoding-utils';
import pbkdf from 'js-crypto-pbkdf';
import jscaes from 'js-crypto-aes';
import jscrandom from 'js-crypto-random';
import {AsnEncryptOptionsWithPassphrase, DER} from './typedef';
const Buffer = BufferMod.Buffer;
const BN = asn.bignum;
///////////////////////////////////////////////////////////////////
/**
* Generate EncryptedPrivateKeyInfo ASN.1 object.
* @param {DER} binKey - Binary key in DER format.
* @param {AsnEncryptOptionsWithPassphrase} [options={passphrase: ''}] - Encryption options for ASN.1 private key.
* @return {Promise<DER>} - Encrypted private key in DER.
*/
export const encryptEncryptedPrivateKeyInfo = async (
binKey: DER,
options: AsnEncryptOptionsWithPassphrase = {passphrase:''}
): Promise<DER> => {
// default params
if(typeof options.algorithm === 'undefined') options.algorithm = 'pbes2';
if(typeof options.iterationCount === 'undefined') options.iterationCount = 2048;
if (options.algorithm === 'pbes2') {
if(typeof options.cipher === 'undefined') options.cipher = 'aes256-cbc';
if(typeof options.prf === 'undefined') options.prf = 'hmacWithSHA256';
const kdfAlgorithm = 'pbkdf2'; // TODO: currently only pbkdf2 is available
const encryptedPBES2 = await encryptPBES2(binKey, options.passphrase, kdfAlgorithm, options.prf, options.iterationCount, options.cipher);
return encodePBES2(encryptedPBES2);
}
else {
const encryptedPBES1 = await encryptPBES1(binKey, options.passphrase, options.algorithm, options.iterationCount);
encryptedPBES1.encryptionAlgorithm.algorithm = <any>params.passwordBasedEncryptionSchemes[encryptedPBES1.encryptionAlgorithm.algorithm].oid; // work around
encryptedPBES1.encryptionAlgorithm.parameters = PBEParameter.encode(encryptedPBES1.encryptionAlgorithm.parameters, 'der');
return EncryptedPrivateKeyInfo.encode(encryptedPBES1, 'der');
}
};
/**
* Decrypt EncryptedPrivateKeyInfo
* @param {Object} epki - Parsed encrypted
* @param {String} passphrase - Passphrase to decyrpt the object.
* @return {Promise<Object>} - Decrypted object.
*/
export const decryptEncryptedPrivateKeyInfo = async (
epki: {encryptionAlgorithm: any, encryptedData: any},
passphrase: string
) => {
const decoded: {[index: string]: any} = {}; // work around
// encryptionAlgorithm.algorithm
decoded.encryptionAlgorithm = {
algorithm: params.getAlgorithmFromOidStrict(epki.encryptionAlgorithm.algorithm, params.passwordBasedEncryptionSchemes)
};
if (decoded.encryptionAlgorithm.algorithm === 'pbes2') {
decoded.encryptionAlgorithm.parameters = decodePBES2(epki.encryptionAlgorithm.parameters);
}
else {
decoded.encryptionAlgorithm.parameters = PBEParameter.decode(epki.encryptionAlgorithm.parameters, 'der');
}
decoded.encryptedData = epki.encryptedData;
// decrypt
if(decoded.encryptionAlgorithm.algorithm === 'pbes2') {
return await decryptPBES2(<any>decoded, passphrase); // work around
}
else return await decryptPBES1(decoded, passphrase);
};
//////////////////////////////
const encodePBES2 = (
decoded: {encryptionAlgorithm: any, encryptedData: any} // work around
) => {
const epki: {[index: string]: any} = { encryptionAlgorithm: {} }; // work around
// algorithm
epki.encryptionAlgorithm.algorithm = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].oid;
// kdf
const kdf = decoded.encryptionAlgorithm.parameters.keyDerivationFunc;
if(kdf.algorithm === 'pbkdf2') {
kdf.parameters.prf.algorithm = params.pbkdf2Prfs[kdf.parameters.prf.algorithm].oid;
kdf.parameters = PBKDF2Params.encode(kdf.parameters, 'der');
} else throw new Error('UnsupportedKDF');
kdf.algorithm = params.keyDerivationFunctions[kdf.algorithm].oid;
// encryptionScheme
const eS = decoded.encryptionAlgorithm.parameters.encryptionScheme;
if(Object.keys(PBES2ESParams).indexOf(eS.algorithm) >= 0){
eS.parameters = PBES2ESParams[eS.algorithm].encode(eS.parameters, 'der');
} else throw new Error('UnsupportedCipher');
eS.algorithm = params.encryptionSchemes[eS.algorithm].oid;
// params
epki.encryptionAlgorithm.parameters = PBES2Params.encode({ keyDerivationFunc: kdf, encryptionScheme: eS }, 'der');
// encoded data
epki.encryptedData = decoded.encryptedData;
return EncryptedPrivateKeyInfo.encode(epki, 'der');
};
const decodePBES2 = (rawParams: any) => { // work around
const pbes2Params = PBES2Params.decode(rawParams, 'der');
// keyDerivationFunc
const kdfAlgorithm = params.getAlgorithmFromOidStrict(pbes2Params.keyDerivationFunc.algorithm, params.keyDerivationFunctions);
let iterationCount;
let salt;
let prf;
if (kdfAlgorithm === 'pbkdf2') {
const pbkdf2Params = PBKDF2Params.decode(pbes2Params.keyDerivationFunc.parameters, 'der');
prf = {
algorithm: params.getAlgorithmFromOidStrict(pbkdf2Params.prf.algorithm, params.pbkdf2Prfs),
parameters: pbkdf2Params.prf.parameters
};
iterationCount = pbkdf2Params.iterationCount;
salt = {type: pbkdf2Params.salt.type, value: pbkdf2Params.salt.value};
} else throw new Error('UnsupportedKDF');
//encryptionScheme
const encryptionScheme = params.getAlgorithmFromOidStrict(pbes2Params.encryptionScheme.algorithm, params.encryptionSchemes);
let encryptionParams;
if(Object.keys(PBES2ESParams).indexOf(encryptionScheme) >= 0){
encryptionParams = PBES2ESParams[encryptionScheme].decode(pbes2Params.encryptionScheme.parameters, 'der');
} else throw new Error('UnsupportedCipher'); // TODO: Other Encryption Scheme
return {
keyDerivationFunc: {
algorithm: kdfAlgorithm,
parameters: { salt, iterationCount, prf }
},
encryptionScheme: {
algorithm: encryptionScheme,
parameters: encryptionParams
}
};
};
//////////////////////
// PBES2 RFC8018 Section 6.2.1
const encryptPBES2 = async (
binKey: any,
passphrase: string,
kdfAlgorithm: string,
prf: string,
iterationCount: number,
cipher: string
) => {
// kdf
const pBuffer = jseu.encoder.stringToArrayBuffer(passphrase);
const salt = await jscrandom.getRandomBytes(
params.keyDerivationFunctions[kdfAlgorithm].defaultSaltLen
); // TODO: currently only salt length of 8 is available
const keyLength = params.encryptionSchemes[cipher].keyLength; // get keyLength
let key;
if (kdfAlgorithm === 'pbkdf2') {
key = await pbkdf.pbkdf2(pBuffer, salt, iterationCount, keyLength, <any>params.pbkdf2Prfs[prf].hash); // work around
} else throw new Error('UnsupportedKDF');
// encrypt
let iv;
let encryptedData;
if (cipher === 'des-ede3-cbc') { // TODO other encryption schemes
iv = Buffer.from(await jscrandom.getRandomBytes(params.encryptionSchemes[cipher].ivLength));
const CBC = des.CBC.instantiate(des.EDE);
const ct = CBC.create({ type: 'encrypt', key: Buffer.from(key), iv });
encryptedData = Buffer.from(ct.update(binKey).concat(ct.final()));
}
else if (cipher === 'aes128-cbc' || cipher === 'aes192-cbc' || cipher === 'aes256-cbc'){
iv = await jscrandom.getRandomBytes(params.encryptionSchemes[cipher].ivLength);
encryptedData = Buffer.from( await jscaes.encrypt(
new Uint8Array(binKey), key, {name: 'AES-CBC', iv}
));
iv = Buffer.from(iv);
} else throw new Error('UnsupportedCipher');
// structure
return {
encryptedData,
encryptionAlgorithm: {
algorithm: 'pbes2',
parameters: {
keyDerivationFunc: {
algorithm: kdfAlgorithm,
parameters: {
salt: {type: 'specified', value: Buffer.from(salt)},
iterationCount: new BN(iterationCount),
prf: {algorithm: prf, parameters: Buffer.from([0x05, 0x00])}
}
},
encryptionScheme: { algorithm: cipher, parameters: iv }
}
}
};
};
//////////////////////////////
// PBES2 RFC8018 Section 6.2.2
const decryptPBES2 = async (
decoded: {encryptionAlgorithm: any, encryptedData: any},
passphrase: string
) => {
const kdf = decoded.encryptionAlgorithm.parameters.keyDerivationFunc;
const eS = decoded.encryptionAlgorithm.parameters.encryptionScheme;
// pbkdf2
const keyLength = params.encryptionSchemes[eS.algorithm].keyLength; // get keyLength
let key;
if(kdf.algorithm === 'pbkdf2') {
const pBuffer = jseu.encoder.stringToArrayBuffer(passphrase);
if (kdf.parameters.salt.type !== 'specified') throw new Error('UnsupportedSaltSource');
const salt = new Uint8Array(kdf.parameters.salt.value);
const iterationCount = kdf.parameters.iterationCount.toNumber();
const prf = kdf.parameters.prf.algorithm;
key = await pbkdf.pbkdf2(pBuffer, salt, iterationCount, keyLength, <any>params.pbkdf2Prfs[prf].hash);
}
else throw new Error('UnsupportedKDF');
// decryption
// TODO other encryption schemes
let out;
if(eS.algorithm === 'des-ede3-cbc'){
const iv = eS.parameters;
const CBC = des.CBC.instantiate(des.EDE);
const pt = CBC.create({ type: 'decrypt', key, iv });
out = Buffer.from(pt.update(decoded.encryptedData).concat(pt.final()));
}
else if (eS.algorithm === 'aes128-cbc' || eS.algorithm === 'aes192-cbc'|| eS.algorithm === 'aes256-cbc'){
const iv = new Uint8Array(eS.parameters);
out = Buffer.from( await jscaes.decrypt(
new Uint8Array(decoded.encryptedData), key, {name: 'AES-CBC', iv}
));
} else throw new Error('UnsupportedEncryptionAlgorithm');
return OneAsymmetricKey.decode(out, 'der');
};
//////////////////////////////
// PBES1 RFC8018 Section 6.1.1
const encryptPBES1 = async (
binKey: any,
passphrase: string,
algorithm: string,
iterationCount: number
) => {
// pbkdf1
const pBuffer = jseu.encoder.stringToArrayBuffer(passphrase);
const salt = await jscrandom.getRandomBytes(8); // defined as 8 octet
const hash = params.passwordBasedEncryptionSchemes[algorithm].hash;
const keyIv = await pbkdf.pbkdf1(pBuffer, salt, iterationCount, 16, <any>hash);
const key = keyIv.slice(0, 8);
const iv = keyIv.slice(8, 16);
// decryption
const encrypt = params.passwordBasedEncryptionSchemes[algorithm].encrypt;
let out;
// TODO: Other Encryption Scheme
if(encrypt === 'DES-CBC') {
const CBC = des.CBC.instantiate(des.DES);
const ct = CBC.create({type: 'encrypt', key, iv});
out = Buffer.from(ct.update(binKey).concat(ct.final()));
}
else throw new Error('UnsupportedEncryptionAlgorithm');
return {
encryptionAlgorithm: {
algorithm,
parameters: {
salt: Buffer.from(salt),
iterationCount: new BN(iterationCount)
}
},
encryptedData: out
};
};
//////////////////////////////
// PBES1 RFC8018 Section 6.1.2
const decryptPBES1 = async (
decoded: any,
passphrase: string
) => {
// pbkdf1
const pBuffer = jseu.encoder.stringToArrayBuffer(passphrase);
const salt = new Uint8Array(decoded.encryptionAlgorithm.parameters.salt);
const hash = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].hash;
const iterationCount = decoded.encryptionAlgorithm.parameters.iterationCount.toNumber();
const keyIv = await pbkdf.pbkdf1(pBuffer, salt, iterationCount, 16, <any>hash);
const key = keyIv.slice(0, 8);
const iv = keyIv.slice(8, 16);
// decryption
const encrypt = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].encrypt;
let out;
// TODO: Other Encryption Scheme
if(encrypt === 'DES-CBC') {
const CBC = des.CBC.instantiate(des.DES);
const ct = CBC.create({type: 'decrypt', key, iv});
out = Buffer.from(ct.update(decoded.encryptedData).concat(ct.final()));
}
else throw new Error('UnsupportedEncryptionAlgorithm');
return OneAsymmetricKey.decode(out, 'der');
}; | the_stack |
import querystring from 'querystring';
import AxiosError from 'axios-error';
import axios, { AxiosInstance } from 'axios';
import invariant from 'ts-invariant';
import warning from 'warning';
import {
OnRequestFunction,
camelcaseKeysDeep,
createRequestInterceptor,
snakecaseKeysDeep,
} from 'messaging-api-common';
import * as SlackTypes from './SlackTypes';
const DEFAULT_PAYLOAD_FIELDS_TO_STRINGIFY = ['attachments', 'blocks'];
function stringifyPayloadFields(
payload: Record<string, any> = {},
fields: Array<string> = DEFAULT_PAYLOAD_FIELDS_TO_STRINGIFY
): object {
fields.forEach((field) => {
if (payload[field] && typeof payload[field] !== 'string') {
// eslint-disable-next-line no-param-reassign
payload[field] = JSON.stringify(snakecaseKeysDeep(payload[field]));
}
});
return payload;
}
export default class SlackOAuthClient {
/**
* @deprecated Use `new SlackOAuthClient(...)` instead.
*/
static connect(config: SlackTypes.ClientConfig): SlackOAuthClient {
warning(
false,
'`SlackOAuthClient.connect(...)` is deprecated. Use `new SlackOAuthClient(...)` instead.'
);
return new SlackOAuthClient(config);
}
/**
* The underlying axios instance.
*/
readonly axios: AxiosInstance;
/**
* The access token used by the client.
*/
readonly accessToken: string;
/**
* chat.* APIs.
*/
readonly chat: {
/**
* Sends a message to a channel.
*
* @returns Typical success response
*
* ```js
* {
* "ok": true,
* "channel": "C1H9RESGL",
* "ts": "1503435956.000247",
* "message": {
* "text": "Here's a message for you",
* "username": "ecto1",
* "botId": "B19LU7CSY",
* "attachments": [
* {
* "text": "This is an attachment",
* "id": 1,
* "fallback": "This is an attachment's fallback"
* }
* ],
* "type": "message",
* "subtype": "bot_message",
* "ts": "1503435956.000247"
* }
* }
* }
* ```
*
* @see https://api.slack.com/methods/chat.postMessage
*
* @example
*
* ```js
* await client.chat.postMessage({
* channel: 'C1234567890',
* text: 'Hello world',
* });
* ```
*/
postMessage: (
options: SlackTypes.PostMessageOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Sends an ephemeral message to a user in a channel.
*
* @returns Typical success response
*
* ```js
* {
* "ok": true,
* "messageTs": "1502210682.580145"
* }
* ```
*
* @see https://api.slack.com/methods/chat.postEphemeral
*
* @example
*
* ```js
* await client.chat.postEphemeral({
* channel: 'C1234567890',
* text: 'Hello world',
* user: 'U0BPQUNTA',
* attachments: '[{"pretext": "pre-hello", "text": "text-world"}]',
* });
* ```
*/
postEphemeral: (
options: SlackTypes.PostEphemeralOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Updates a message.
*
* @returns Typical success response
*
* ```js
* {
* "ok": true,
* "channel": "C024BE91L",
* "ts": "1401383885.000061",
* "text": "Updated text you carefully authored",
* "message": {
* "text": "Updated text you carefully authored",
* "user": "U34567890"
* }
* }
* ```
*
* @see https://api.slack.com/methods/chat.update
*
* @example
*
* ```js
* await client.chat.update({
* channel: 'C1234567890',
* ts: '1405894322.002768',
* text: 'Hello world',
* });
* ```
*/
update: (
options: SlackTypes.UpdateMessageOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Deletes a message.
*
* @returns Typical success response
*
* ```js
* {
* "ok": true,
* "channel": "C024BE91L",
* "ts": "1401383885.000061"
* }
* ```
*
* @see https://api.slack.com/methods/chat.delete
*
* @example
*
* ```js
* await client.chat.delete({
* channel: 'C1234567890',
* ts: 'Timestamp of the message to be deleted.',
* });
* ```
*/
delete: (
options: SlackTypes.DeleteMessageOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Share a me message into a channel.
*
* @returns Typical success response
*
* ```js
* {
* "ok": true,
* "channel": "C024BE7LR",
* "ts": "1417671948.000006"
* }
* ```
*
* @see https://api.slack.com/methods/chat.meMessage
*
* @example
*
* ```js
* await client.chat.meMessage({
* channel: 'C1234567890',
* text: 'Hello world',
* });
* ```
*/
meMessage: (
options: SlackTypes.MeMessageOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Retrieve a permalink URL for a specific extant message.
*
* @returns Standard success response
*
* ```js
* {
* "ok": true,
* "channel": "C1H9RESGA",
* "permalink": "https://ghostbusters.slack.com/archives/C1H9RESGA/p135854651500008"
* }
* ```
*
* @see https://api.slack.com/methods/chat.getPermalink
*
* @example
*
* ```js
* await client.chat.getPermalink({
* channel: 'C1H9RESGA',
* messageTs: '1234567890.123456',
* });
* ```
*/
getPermalink: (
options: SlackTypes.GetPermalinkOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Schedules a message to be sent to a channel.
*
* @returns Typical success response
*
* ```js
* {
* "ok": true,
* "channel": "C1H9RESGL",
* "scheduledMessageId": "Q1298393284",
* "postAt": "1562180400",
* "message": {
* "text": "Here's a message for you in the future",
* "username": "ecto1",
* "botId": "B19LU7CSY",
* "attachments": [
* {
* "text": "This is an attachment",
* "id": 1,
* "fallback": "This is an attachment's fallback"
* }
* ],
* "type": "delayed_message",
* "subtype": "bot_message"
* }
* }
* ```
*
* @see https://api.slack.com/methods/chat.scheduleMessage
*
* @example
*
* ```js
* await client.chat.scheduleMessage({
* channel: 'C1234567890',
* postAt: '299876400',
* text: 'Hello world',
* });
* ```
*/
scheduleMessage: (
options: SlackTypes.ScheduleMessageOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Deletes a pending scheduled message from the queue.
*
* @returns Typical success response
*
* ```js
* {
* "ok": true
* }
* ```
*
* @see https://api.slack.com/methods/chat.deleteScheduledMessage
*
* @example
*
* ```js
* await client.chat.deleteScheduledMessage({
* channel: 'C123456789',
* scheduledMessageId: 'Q1234ABCD',
* });
* ```
*/
deleteScheduledMessage: (
options: SlackTypes.DeleteScheduledMessageOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Provide custom unfurl behavior for user-posted URLs.
*
* @returns Typical, minimal success response
*
* ```js
* {
* "ok": true
* }
* ```
*
* @see https://api.slack.com/methods/chat.unfurl
*
* @example
*
* ```js
* await client.chat.unfurl({
* channel: 'C123456789',
* ts: '1502210682.580145',
* unfurls: {
* 'https://example.com/': {
* text: 'Every day is the test.',
* },
* },
* });
* ```
*/
unfurl: (
options: SlackTypes.UnfurlOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
scheduledMessages: {
/**
* Returns a list of scheduled messages.
*
* @returns Typical success response
*
* ```js
* {
* "ok": true,
* "scheduledMessages": [
* {
* "id": 1298393284,
* "channelId": "C1H9RESGL",
* "postAt": 1551991428,
* "dateCreated": 1551891734,
* "text": "Here's a message for you in the future"
* }
* ],
* "responseMetadata": {
* "nextCursor": ""
* }
* }
* ```
*
* @see https://api.slack.com/methods/chat.scheduledMessages.list
*
* @example
*
* ```js
* await client.chat.scheduledMessages.list({
* channel: 'C123456789',
* });
* ```
*/
list: (
options: SlackTypes.GetScheduledMessagesOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
};
};
/**
* views.* APIs.
*/
readonly views: {
/**
* Open a view for a user.
*
* @returns Typical success response includes the opened view payload.
*
* @see https://api.slack.com/methods/views.open
*
* @example
*
* ```js
* await client.views.open({
* triggerId: '12345.98765.abcd2358fdea',
* view: {
* id: 'VMHU10V25',
* teamId: 'T8N4K1JN',
* type: 'modal',
* title: {
* type: 'plain_text',
* text: 'Quite a plain modal',
* },
* submit: {
* type: 'plain_text',
* text: 'Create',
* },
* blocks: [
* {
* type: 'input',
* blockId: 'a_block_id',
* label: {
* type: 'plain_text',
* text: 'A simple label',
* emoji: true,
* },
* optional: false,
* element: {
* type: 'plain_text_input',
* actionId: 'an_action_id',
* },
* },
* ],
* privateMetadata: 'Shh it is a secret',
* callbackId: 'identify_your_modals',
* externalId: '',
* state: {
* values: [],
* },
* hash: '156772938.1827394',
* clearOnClose: false,
* notifyOnClose: false,
* },
* });
* ```
*/
open: (
options: SlackTypes.OpenViewOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Publish a static view for a User.
*
* @returns Typical success response includes the published view payload.
*
* @see https://api.slack.com/methods/views.publish
*
* @example
*
* ```js
* await client.views.publish({
* userId: 'U0BPQUNTA',
* view: {
* id: 'VMHU10V25',
* teamId: 'T8N4K1JN',
* type: 'modal',
* title: {
* type: 'plain_text',
* text: 'Quite a plain modal',
* },
* submit: {
* type: 'plain_text',
* text: 'Create',
* },
* blocks: [
* {
* type: 'input',
* blockId: 'a_block_id',
* label: {
* type: 'plain_text',
* text: 'A simple label',
* emoji: true,
* },
* optional: false,
* element: {
* type: 'plain_text_input',
* actionId: 'an_action_id',
* },
* },
* ],
* privateMetadata: 'Shh it is a secret',
* callbackId: 'identify_your_modals',
* externalId: '',
* state: {
* values: [],
* },
* hash: '156772938.1827394',
* clearOnClose: false,
* notifyOnClose: false,
* },
* hash: '156772938.1827394,
* });
* ```
*/
publish: (
options: SlackTypes.PublishViewOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Push a view onto the stack of a root view.
*
* @returns Typical success response includes the pushed view payload.
*
* @see https://api.slack.com/methods/views.push
*
* @example
*
* ```js
* await client.views.push({
* triggerId: '12345.98765.abcd2358fdea',
* view: {
* id: 'VMHU10V25',
* teamId: 'T8N4K1JN',
* type: 'modal',
* title: {
* type: 'plain_text',
* text: 'Quite a plain modal',
* },
* submit: {
* type: 'plain_text',
* text: 'Create',
* },
* blocks: [
* {
* type: 'input',
* blockId: 'a_block_id',
* label: {
* type: 'plain_text',
* text: 'A simple label',
* emoji: true,
* },
* optional: false,
* element: {
* type: 'plain_text_input',
* actionId: 'an_action_id',
* },
* },
* ],
* privateMetadata: 'Shh it is a secret',
* callbackId: 'identify_your_modals',
* externalId: '',
* state: {
* values: [],
* },
* hash: '156772938.1827394',
* clearOnClose: false,
* notifyOnClose: false,
* },
* });
* ```
*/
push: (
options: SlackTypes.PushViewOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
/**
* Update an existing view.
*
* @returns Typical success response includes the updated view payload.
*
* @see https://api.slack.com/methods/views.update
*
* @example
*
* ```js
* await client.views.update({
* externalId: 'bmarley_view2',
* view: {
* id: 'VMHU10V25',
* teamId: 'T8N4K1JN',
* type: 'modal',
* title: {
* type: 'plain_text',
* text: 'Quite a plain modal',
* },
* submit: {
* type: 'plain_text',
* text: 'Create',
* },
* blocks: [
* {
* type: 'input',
* blockId: 'a_block_id',
* label: {
* type: 'plain_text',
* text: 'A simple label',
* emoji: true,
* },
* optional: false,
* element: {
* type: 'plain_text_input',
* actionId: 'an_action_id',
* },
* },
* ],
* privateMetadata: 'Shh it is a secret',
* callbackId: 'identify_your_modals',
* externalId: '',
* state: {
* values: [],
* },
* hash: '156772938.1827394',
* clearOnClose: false,
* notifyOnClose: false,
* },
* });
* ```
*/
update: (
options: SlackTypes.UpdateViewOptions
) => Promise<SlackTypes.OAuthAPIResponse>;
};
/**
* The callback to be called when receiving requests.
*/
private onRequest?: OnRequestFunction;
constructor(config: SlackTypes.ClientConfig) {
invariant(
typeof config !== 'string',
`SlackOAuthClient: do not allow constructing client with ${config} string. Use object instead.`
);
this.accessToken = config.accessToken;
this.onRequest = config.onRequest;
// Web API
// https://api.slack.com/web
this.axios = axios.create({
baseURL: `${config.origin || 'https://slack.com'}/api/`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
this.axios.interceptors.request.use(
createRequestInterceptor({ onRequest: this.onRequest })
);
this.chat = {
postMessage: this._postMessage.bind(this),
postEphemeral: this._postEphemeral.bind(this),
update: this._updateMessage.bind(this),
delete: this._deleteMessage.bind(this),
meMessage: this._meMessage.bind(this),
getPermalink: this._getPermalink.bind(this),
scheduleMessage: this._scheduleMessage.bind(this),
deleteScheduledMessage: this._deleteScheduledMessage.bind(this),
unfurl: this._unfurl.bind(this),
scheduledMessages: {
list: this._getScheduledMessages.bind(this),
},
};
this.views = {
open: this._openView.bind(this),
publish: this._publishView.bind(this),
push: this._pushView.bind(this),
update: this._updateView.bind(this),
};
}
async callMethod(
method: SlackTypes.AvailableMethod,
inputBody: Record<string, any> = {}
): Promise<SlackTypes.OAuthAPIResponse> {
try {
const body = {
...inputBody,
token: this.accessToken,
};
const response = await this.axios.post(
method,
querystring.stringify(snakecaseKeysDeep(body) as any)
);
const data = camelcaseKeysDeep(
response.data
) as any as SlackTypes.OAuthAPIResponse;
if (!data.ok) {
const { config, request } = response;
throw new AxiosError(`Slack API - ${data.error}`, {
config,
request,
response,
});
}
return data;
} catch (err: any) {
throw new AxiosError(err.message, err);
}
}
/**
* Gets information about a channel.
*
* @param channelId - Channel to get info on.
* @param options - Other optional parameters.
*
* @see https://api.slack.com/methods/channels.info
*
* @example
*
* ```js
* await client.getChannelInfo(channelId);
* // {
* // id: 'C8763',
* // name: 'fun',
* // ...
* // }
* ```
*/
getChannelInfo(
channelId: string,
options?: SlackTypes.GetInfoOptions
): Promise<SlackTypes.Channel> {
return this.callMethod('channels.info', {
channel: channelId,
...options,
}).then((data) => data.channel);
}
/**
* Retrieve information about a conversation.
*
* @param channelId - Channel to get info on.
* @param options - Other optional parameters.
*
* @see https://api.slack.com/methods/conversations.info
*
* @example
*
* ```js
* await client.getConversationInfo(channelId);
* // {
* // id: 'C8763',
* // name: 'fun',
* // ...
* // }
* ```
*/
getConversationInfo(
channelId: string,
options?: SlackTypes.GetInfoOptions
): Promise<SlackTypes.Channel> {
return this.callMethod('conversations.info', {
channel: channelId,
...options,
}).then((data) => data.channel);
}
/**
* Retrieve members of a conversation.
*
* @param channelId - Channel to get info on.
* @param options - Optional arguments.
*
* @see https://api.slack.com/methods/conversations.members
*
* @example
*
* ```js
* await client.getConversationMembers(channelId, { cursor: 'xxx' });
* await client.getConversationMembers(channelId);
* // {
* // members: ['U061F7AUR', 'U0C0NS9HN'],
* // next: 'cursor',
* // }
* ```
*/
getConversationMembers(
channelId: string,
options?: SlackTypes.ConversationMembersOptions
): Promise<{
members: string[];
next?: string;
}> {
return this.callMethod('conversations.members', {
channel: channelId,
...options,
}).then((data) => ({
members: data.members,
next: data.responseMetadata && data.responseMetadata.nextCursor,
}));
}
/**
* Recursively retrieve members of a conversation using cursor.
*
* @param channelId - Channel to get info on.
* @param options - Optional arguments.
*
* @see https://api.slack.com/methods/conversations.members
*
* @example
*
* ```js
* await client.getAllConversationMembers(channelId);
* // ['U061F7AUR', 'U0C0NS9HN', ...]
* ```
*/
async getAllConversationMembers(
channelId: string,
options?: Omit<SlackTypes.ConversationMembersOptions, 'cursor'>
): Promise<string[]> {
let allMembers: string[] = [];
let continuationCursor;
do {
const {
members,
next,
}: {
members: string[];
next?: string;
// eslint-disable-next-line no-await-in-loop
} = await this.getConversationMembers(channelId, {
cursor: continuationCursor,
...options,
});
allMembers = allMembers.concat(members);
continuationCursor = next;
} while (continuationCursor);
return allMembers;
}
/**
* Lists all channels in a Slack team.
*
* @param options - Optional arguments.
*
* @see https://api.slack.com/methods/conversations.list
*
* @example
*
* ```js
* await client.getConversationList({ cursor: 'xxx' });
* await client.getConversationList();
* // {
* // channels: [
* // {
* // id: 'C012AB3CD',
* // name: 'general',
* // ...
* // },
* // {
* // id: 'C012AB3C5',
* // name: 'random',
* // ...
* // },
* // ],
* // next: 'cursor',
* // }
* ```
*/
getConversationList(options?: SlackTypes.ConversationListOptions): Promise<{
channels: SlackTypes.Channel[];
next?: string;
}> {
return this.callMethod('conversations.list', options).then((data) => ({
channels: data.channels,
next: data.responseMetadata && data.responseMetadata.nextCursor,
}));
}
/**
* Recursively lists all channels in a Slack team using cursor.
*
* @param options - Optional arguments.
*
* @see https://api.slack.com/methods/conversations.list
*
* @example
*
* ```js
* await client.getAllConversationList();
* // [
* // {
* // id: 'C012AB3CD',
* // name: 'general',
* // ...
* // },
* // {
* // id: 'C012AB3C5',
* // name: 'random',
* // ...
* // },
* // ],
* ```
*/
async getAllConversationList(
options?: Omit<SlackTypes.ConversationListOptions, 'cursor'>
): Promise<SlackTypes.Channel[]> {
let allChannels: SlackTypes.Channel[] = [];
let continuationCursor: string | undefined;
do {
const nextOptions = continuationCursor
? { cursor: continuationCursor, ...options }
: options;
const {
channels,
next,
// eslint-disable-next-line no-await-in-loop
} = await this.getConversationList(nextOptions);
allChannels = allChannels.concat(channels);
continuationCursor = next;
} while (continuationCursor);
return allChannels;
}
postMessage(
channel: string,
inputMessage: SlackTypes.Message | string,
options: SlackTypes.PostMessageOptionalOptions = {}
): Promise<SlackTypes.OAuthAPIResponse> {
warning(
false,
'`postMessage` is deprecated. Use `chat.postMessage` instead.'
);
const message =
typeof inputMessage === 'string' ? { text: inputMessage } : inputMessage;
return this._postMessage({
channel,
...message,
...options,
});
}
/**
* Sends a message to the channel.
*
* @param options -
* @returns
*
* @see https://api.slack.com/methods/chat.postMessage
*
* @example
*
* ```js
* await client.chat.postMessage({
* channel: 'C8763',
* text: 'Hello!',
* });
* await client.chat.postMessage({
* channel: 'C8763',
* attachments: someAttachments,
* });
* ```
*/
private _postMessage(
options: SlackTypes.PostMessageOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod('chat.postMessage', stringifyPayloadFields(options));
}
/**
* Sends an ephemeral message to a user in a channel.
*
* @see https://api.slack.com/methods/chat.postEphemeral
*/
postEphemeral(
channel: string,
user: string,
inputMessage: SlackTypes.Message | string,
options: SlackTypes.PostEphemeralOptionalOptions = {}
): Promise<SlackTypes.OAuthAPIResponse> {
warning(
false,
'`postEphemeral` is deprecated. Use `chat.postEphemeral` instead.'
);
const message =
typeof inputMessage === 'string' ? { text: inputMessage } : inputMessage;
return this._postEphemeral({
channel,
user,
...message,
...options,
});
}
/**
* Sends an ephemeral message to a user in the channel.
*
* @see https://api.slack.com/methods/chat.postEphemeral
*
*/
private _postEphemeral(
options: SlackTypes.PostEphemeralOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod(
'chat.postEphemeral',
stringifyPayloadFields(options)
);
}
/**
* Updates a message.
*
* @see https://api.slack.com/methods/chat.update
*/
private _updateMessage(
options: SlackTypes.UpdateMessageOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod('chat.update', stringifyPayloadFields(options));
}
/**
* Deletes a message.
*
* @see https://api.slack.com/methods/chat.delete
*/
private _deleteMessage(
options: SlackTypes.DeleteMessageOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod('chat.delete', options);
}
/**
* Share a me message into a channel.
*
* @see https://api.slack.com/methods/chat.meMessage
*/
private _meMessage(
options: SlackTypes.MeMessageOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod('chat.meMessage', options);
}
/**
* Retrieve a permalink URL for a specific extant message
*
* @see https://api.slack.com/methods/chat.getPermalink
*/
private _getPermalink(
options: SlackTypes.GetPermalinkOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod('chat.getPermalink', options);
}
/**
* Schedules a message to be sent to a channel.
*
* @see https://api.slack.com/methods/chat.scheduleMessage
*/
private _scheduleMessage(
options: SlackTypes.ScheduleMessageOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod(
'chat.scheduleMessage',
stringifyPayloadFields(options)
);
}
/**
* Deletes a pending scheduled message from the queue.
*
* @see https://api.slack.com/methods/chat.deleteScheduledMessage
*/
private _deleteScheduledMessage(
options: SlackTypes.DeleteScheduledMessageOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod('chat.deleteScheduledMessage', options);
}
/**
* Returns a list of scheduled messages.
*
* @see https://api.slack.com/methods/chat.scheduledMessages.list
*/
private _getScheduledMessages(
options: SlackTypes.GetScheduledMessagesOptions = {}
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod('chat.scheduledMessages.list', options);
}
/**
* Provide custom unfurl behavior for user-posted URLs
*
* @see https://api.slack.com/methods/chat.unfurl
*/
private _unfurl(
options: SlackTypes.UnfurlOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod(
'chat.unfurl',
stringifyPayloadFields(options, ['view'])
);
}
/**
* Open a view for a user.
*
* @see https://api.slack.com/methods/views.open
*/
private _openView(
options: SlackTypes.OpenViewOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod(
'views.open',
stringifyPayloadFields(options, ['view'])
);
}
/**
* Publish a static view for a User.
*
* @see https://api.slack.com/methods/views.publish
*/
private _publishView(
options: SlackTypes.PublishViewOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod(
'views.publish',
stringifyPayloadFields(options, ['view'])
);
}
/**
* Update an existing view.
*
* @see https://api.slack.com/methods/views.update
*/
private _updateView(
options: SlackTypes.UpdateViewOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod(
'views.update',
stringifyPayloadFields(options, ['view'])
);
}
/**
* Push a view onto the stack of a root view.
*
* @see https://api.slack.com/methods/views.push
*/
private _pushView(
options: SlackTypes.PushViewOptions
): Promise<SlackTypes.OAuthAPIResponse> {
return this.callMethod(
'views.push',
stringifyPayloadFields(options, ['view'])
);
}
/**
* Gets information about a user.
*
* @param userId - User to get info on.
* @param options - Other optional parameters.
* @param options.includeLocale - Set this to true to receive the locale for this user. Defaults to false
*
* @see https://api.slack.com/methods/users.info
*
* @example
*
* ```js
* await client.getUserInfo(userId);
* // {
* // id: 'U123456',
* // name: 'bobby',
* // ...
* // }
* ```
*/
getUserInfo(
userId: string,
options?: SlackTypes.UserInfoOptions
): Promise<SlackTypes.User> {
return this.callMethod('users.info', { user: userId, ...options }).then(
(data) => data.user
);
}
/**
* Lists all users in a Slack team.
*
* @param options - Optional parameters.
* @param options.cursor - Paginate through collections of data by setting the `cursor` parameter to a `nextCursor` attribute returned by a previous request's `responseMetadata`.
*
* @see https://api.slack.com/methods/users.list
*
* @example
*
* ```js
* await client.getUserList({ cursor });
* // {
* // members: [
* // { ... },
* // { ... },
* // ],
* // next: 'abcdefg',
* // }
* ```
*/
getUserList(options?: SlackTypes.UserListOptions): Promise<{
members: SlackTypes.User[];
next?: string;
}> {
return this.callMethod('users.list', options).then((data) => ({
members: data.members,
next: data.responseMetadata && data.responseMetadata.nextCursor,
}));
}
/**
* Recursively lists all users in a Slack team using cursor.
*
* @see https://api.slack.com/methods/users.list
*
* @example
*
* ```js
* await client.getAllUserList();
* // [
* // { ... },
* // { ... },
* // ]
* ```
*/
async getAllUserList(
options?: Omit<SlackTypes.UserListOptions, 'cursor'>
): Promise<SlackTypes.User[]> {
let allUsers: SlackTypes.User[] = [];
let continuationCursor;
do {
const {
members: users,
next,
}: {
members: SlackTypes.User[];
next?: string;
// eslint-disable-next-line no-await-in-loop
} = await this.getUserList({
cursor: continuationCursor,
...options,
});
allUsers = allUsers.concat(users);
continuationCursor = next;
} while (continuationCursor);
return allUsers;
}
} | the_stack |
jest.mock('../../lib/api/deploy-stack');
import { CloudFormation } from 'aws-sdk';
import { CloudFormationDeployments } from '../../lib/api/cloudformation-deployments';
import { deployStack } from '../../lib/api/deploy-stack';
import { ToolkitInfo } from '../../lib/api/toolkit-info';
import { CloudFormationStack } from '../../lib/api/util/cloudformation';
import { testStack } from '../util';
import { mockBootstrapStack, MockSdkProvider } from '../util/mock-sdk';
import { FakeCloudformationStack } from './fake-cloudformation-stack';
let sdkProvider: MockSdkProvider;
let deployments: CloudFormationDeployments;
let mockToolkitInfoLookup: jest.Mock;
let currentCfnStackResources: { [key: string]: CloudFormation.StackResourceSummary[] };
let numberOfTimesListStackResourcesWasCalled: number;
beforeEach(() => {
jest.resetAllMocks();
sdkProvider = new MockSdkProvider();
deployments = new CloudFormationDeployments({ sdkProvider });
numberOfTimesListStackResourcesWasCalled = 0;
currentCfnStackResources = {};
sdkProvider.stubCloudFormation({
listStackResources: ({ StackName: stackName }) => {
numberOfTimesListStackResourcesWasCalled++;
const stackResources = currentCfnStackResources[stackName];
if (!stackResources) {
throw new Error(`Stack with id ${stackName} does not exist`);
}
return {
StackResourceSummaries: stackResources,
};
},
});
ToolkitInfo.lookup = mockToolkitInfoLookup = jest.fn().mockResolvedValue(ToolkitInfo.bootstrapStackNotFoundInfo(sdkProvider.sdk));
});
function mockSuccessfulBootstrapStackLookup(props?: Record<string, any>) {
const outputs = {
BucketName: 'BUCKET_NAME',
BucketDomainName: 'BUCKET_ENDPOINT',
BootstrapVersion: '1',
...props,
};
const fakeStack = mockBootstrapStack(sdkProvider.sdk, {
Outputs: Object.entries(outputs).map(([k, v]) => ({
OutputKey: k,
OutputValue: `${v}`,
})),
});
mockToolkitInfoLookup.mockResolvedValue(ToolkitInfo.fromStack(fakeStack, sdkProvider.sdk));
}
test('passes through hotswap=true to deployStack()', async () => {
// WHEN
await deployments.deployStack({
stack: testStack({
stackName: 'boop',
}),
hotswap: true,
});
// THEN
expect(deployStack).toHaveBeenCalledWith(expect.objectContaining({
hotswap: true,
}));
});
test('placeholders are substituted in CloudFormation execution role', async () => {
await deployments.deployStack({
stack: testStack({
stackName: 'boop',
properties: {
cloudFormationExecutionRoleArn: 'bloop:${AWS::Region}:${AWS::AccountId}',
},
}),
});
expect(deployStack).toHaveBeenCalledWith(expect.objectContaining({
roleArn: 'bloop:here:123456789012',
}));
});
test('role with placeholders is assumed if assumerole is given', async () => {
const mockForEnvironment = jest.fn().mockImplementation(() => { return { sdk: sdkProvider.sdk }; });
sdkProvider.forEnvironment = mockForEnvironment;
await deployments.deployStack({
stack: testStack({
stackName: 'boop',
properties: {
assumeRoleArn: 'bloop:${AWS::Region}:${AWS::AccountId}',
},
}),
});
expect(mockForEnvironment).toHaveBeenCalledWith(expect.anything(), expect.anything(), expect.objectContaining({
assumeRoleArn: 'bloop:here:123456789012',
}));
});
test('deployment fails if bootstrap stack is missing', async () => {
await expect(deployments.deployStack({
stack: testStack({
stackName: 'boop',
properties: {
assumeRoleArn: 'bloop:${AWS::Region}:${AWS::AccountId}',
requiresBootstrapStackVersion: 99,
},
}),
})).rejects.toThrow(/requires a bootstrap stack/);
});
test('deployment fails if bootstrap stack is too old', async () => {
mockSuccessfulBootstrapStackLookup({
BootstrapVersion: 5,
});
await expect(deployments.deployStack({
stack: testStack({
stackName: 'boop',
properties: {
assumeRoleArn: 'bloop:${AWS::Region}:${AWS::AccountId}',
requiresBootstrapStackVersion: 99,
},
}),
})).rejects.toThrow(/requires bootstrap stack version '99', found '5'/);
});
test('if toolkit stack cannot be found but SSM parameter name is present deployment succeeds', async () => {
// FIXME: Mocking a successful bootstrap stack lookup here should not be necessary.
// This should fail and return a placeholder failure object.
mockSuccessfulBootstrapStackLookup({
BootstrapVersion: 2,
});
let requestedParameterName: string;
sdkProvider.stubSSM({
getParameter(request) {
requestedParameterName = request.Name;
return {
Parameter: {
Value: '99',
},
};
},
});
await deployments.deployStack({
stack: testStack({
stackName: 'boop',
properties: {
assumeRoleArn: 'bloop:${AWS::Region}:${AWS::AccountId}',
requiresBootstrapStackVersion: 99,
bootstrapStackVersionSsmParameter: '/some/parameter',
},
}),
});
expect(requestedParameterName!).toEqual('/some/parameter');
});
test('readCurrentTemplateWithNestedStacks() can handle non-Resources in the template', async () => {
const cfnStack = new FakeCloudformationStack({
stackName: 'ParentOfStackWithOutputAndParameter',
stackId: 'StackId',
});
CloudFormationStack.lookup = (async (_, stackName: string) => {
switch (stackName) {
case 'ParentOfStackWithOutputAndParameter':
cfnStack.template = async () => ({
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-output-one-param-stack.nested.template.json',
},
},
},
});
break;
case 'NestedStack':
cfnStack.template = async () => ({
Resources: {
NestedResource: {
Type: 'AWS::Something',
Properties: {
Property: 'old-value',
},
},
},
Parameters: {
NestedParam: {
Type: 'String',
},
},
Outputs: {
NestedOutput: {
Value: {
Ref: 'NestedResource',
},
},
},
});
break;
default:
throw new Error('unknown stack name ' + stackName + ' found');
}
return cfnStack;
});
const rootStack = testStack({
stackName: 'ParentOfStackWithOutputAndParameter',
template: {
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-output-one-param-stack.nested.template.json',
},
},
},
},
});
pushStackResourceSummaries('ParentOfStackWithOutputAndParameter',
stackSummaryOf('NestedStack', 'AWS::CloudFormation::Stack',
'arn:aws:cloudformation:bermuda-triangle-1337:123456789012:stack/NestedStack/abcd',
),
);
// WHEN
const deployedTemplate = await deployments.readCurrentTemplateWithNestedStacks(rootStack);
// THEN
expect(deployedTemplate).toEqual({
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
NestedTemplate: {
Resources: {
NestedResource: {
Type: 'AWS::Something',
Properties: {
Property: 'old-value',
},
},
},
Outputs: {
NestedOutput: {
Value: {
Ref: 'NestedResource',
},
},
},
Parameters: {
NestedParam: {
Type: 'String',
},
},
},
},
Metadata: {
'aws:asset:path': 'one-output-one-param-stack.nested.template.json',
},
},
},
});
expect(rootStack.template).toEqual({
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
NestedTemplate: {
Resources: {
NestedResource: {
Type: 'AWS::Something',
Properties: {
Property: 'new-value',
},
},
},
Outputs: {
NestedOutput: {
Value: {
Ref: 'NestedResource',
},
},
},
Parameters: {
NestedParam: {
Type: 'Number',
},
},
},
},
Metadata: {
'aws:asset:path': 'one-output-one-param-stack.nested.template.json',
},
},
},
});
});
test('readCurrentTemplateWithNestedStacks() with a 3-level nested + sibling structure works', async () => {
const cfnStack = new FakeCloudformationStack({
stackName: 'MultiLevelRoot',
stackId: 'StackId',
});
CloudFormationStack.lookup = (async (_, stackName: string) => {
switch (stackName) {
case 'MultiLevelRoot':
cfnStack.template = async () => ({
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-two-stacks-stack.nested.template.json',
},
},
},
});
break;
case 'NestedStack':
cfnStack.template = async () => ({
Resources: {
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'old-value',
},
},
GrandChildStackA: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
GrandChildStackB: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
},
});
break;
case 'GrandChildStackA':
cfnStack.template = async () => ({
Resources: {
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'old-value',
},
},
},
});
break;
case 'GrandChildStackB':
cfnStack.template = async () => ({
Resources: {
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'old-value',
},
},
},
});
break;
default:
throw new Error('unknown stack name ' + stackName + ' found in cloudformation-deployments.test.ts');
}
return cfnStack;
});
const rootStack = testStack({
stackName: 'MultiLevelRoot',
template: {
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-two-stacks-stack.nested.template.json',
},
},
},
},
});
pushStackResourceSummaries('MultiLevelRoot',
stackSummaryOf('NestedStack', 'AWS::CloudFormation::Stack',
'arn:aws:cloudformation:bermuda-triangle-1337:123456789012:stack/NestedStack/abcd',
),
);
pushStackResourceSummaries('NestedStack',
stackSummaryOf('GrandChildStackA', 'AWS::CloudFormation::Stack',
'arn:aws:cloudformation:bermuda-triangle-1337:123456789012:stack/GrandChildStackA/abcd',
),
stackSummaryOf('GrandChildStackB', 'AWS::CloudFormation::Stack',
'arn:aws:cloudformation:bermuda-triangle-1337:123456789012:stack/GrandChildStackB/abcd',
),
);
pushStackResourceSummaries('GrandChildStackA',
stackSummaryOf('NestedStack', 'AWS::CloudFormation::Stack',
'arn:aws:cloudformation:bermuda-triangle-1337:123456789012:stack/GrandChildA/abcd',
),
);
pushStackResourceSummaries('GrandChildStackB',
stackSummaryOf('NestedStack', 'AWS::CloudFormation::Stack',
'arn:aws:cloudformation:bermuda-triangle-1337:123456789012:stack/GrandChildB/abcd',
),
);
// WHEN
const deployedTemplate = await deployments.readCurrentTemplateWithNestedStacks(rootStack);
// THEN
expect(deployedTemplate).toEqual({
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
NestedTemplate: {
Resources: {
GrandChildStackA: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
NestedTemplate: {
Resources: {
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'old-value',
},
},
},
},
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
GrandChildStackB: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
NestedTemplate: {
Resources: {
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'old-value',
},
},
},
},
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'old-value',
},
},
},
},
},
Metadata: {
'aws:asset:path': 'one-resource-two-stacks-stack.nested.template.json',
},
},
},
});
expect(rootStack.template).toEqual({
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
NestedTemplate: {
Resources: {
GrandChildStackA: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
NestedTemplate: {
Resources: {
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'new-value',
},
},
},
},
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
GrandChildStackB: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
NestedTemplate: {
Resources: {
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'new-value',
},
},
},
},
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'new-value',
},
},
},
},
},
Metadata: {
'aws:asset:path': 'one-resource-two-stacks-stack.nested.template.json',
},
},
},
});
});
test('readCurrentTemplateWithNestedStacks() on an undeployed parent stack with an (also undeployed) nested stack works', async () => {
// GIVEN
const cfnStack = new FakeCloudformationStack({
stackName: 'UndeployedParent',
stackId: 'StackId',
});
CloudFormationStack.lookup = (async (_cfn, _stackName: string) => {
cfnStack.template = async () => ({});
return cfnStack;
});
const rootStack = testStack({
stackName: 'UndeployedParent',
template: {
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-one-stack-stack.nested.template.json',
},
},
},
},
});
// WHEN
const deployedTemplate = await deployments.readCurrentTemplateWithNestedStacks(rootStack);
// THEN
expect(deployedTemplate).toEqual({
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
NestedTemplate: {
Resources: {
NestedStack: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
NestedTemplate: {},
},
},
},
},
},
},
},
});
});
test('readCurrentTemplateWithNestedStacks() caches calls to listStackResources()', async () => {
// GIVEN
const cfnStack = new FakeCloudformationStack({
stackName: 'CachingRoot',
stackId: 'StackId',
});
CloudFormationStack.lookup = (async (_cfn, _stackName: string) => {
cfnStack.template = async () => ({
Resources:
{
NestedStackA: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
NestedStackB: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
},
});
return cfnStack;
});
const rootStack = testStack({
stackName: 'CachingRoot',
template: {
Resources: {
NestedStackA: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
NestedStackB: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
},
},
});
pushStackResourceSummaries('CachingRoot',
stackSummaryOf('NestedStackA', 'AWS::CloudFormation::Stack',
'arn:aws:cloudformation:bermuda-triangle-1337:123456789012:stack/one-resource-stack/abcd',
),
stackSummaryOf('NestedStackB', 'AWS::CloudFormation::Stack',
'arn:aws:cloudformation:bermuda-triangle-1337:123456789012:stack/one-resource-stack/abcd',
),
);
// WHEN
await deployments.readCurrentTemplateWithNestedStacks(rootStack);
// THEN
expect(numberOfTimesListStackResourcesWasCalled).toEqual(1);
});
test('readCurrentTemplateWithNestedStacks() succesfully ignores stacks without metadata', async () => {
// GIVEN
const cfnStack = new FakeCloudformationStack({
stackName: 'MetadataRoot',
stackId: 'StackId',
});
CloudFormationStack.lookup = (async (_, stackName: string) => {
if (stackName === 'MetadataRoot') {
cfnStack.template = async () => ({
Resources: {
WithMetadata: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
},
});
} else {
cfnStack.template = async () => ({
Resources: {
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'old-value',
},
},
},
});
}
return cfnStack;
});
const rootStack = testStack({
stackName: 'MetadataRoot',
template: {
Resources: {
WithoutMetadata: {
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Type: 'AWS::CloudFormation::Stack',
},
WithEmptyMetadata: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {},
},
WithMetadata: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
},
},
});
pushStackResourceSummaries('MetadataRoot', stackSummaryOf('WithMetadata', 'AWS::CloudFormation::Stack',
'arn:aws:cloudformation:bermuda-triangle-1337:123456789012:stack/one-resource-stack/abcd',
));
// WHEN
const deployedTemplate = await deployments.readCurrentTemplateWithNestedStacks(rootStack);
// THEN
expect(deployedTemplate).toEqual({
Resources: {
WithMetadata: {
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
NestedTemplate: {
Resources: {
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'old-value',
},
},
},
},
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
},
});
expect(rootStack.template).toEqual({
Resources: {
WithoutMetadata: { // Unchanged
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
},
WithEmptyMetadata: { // Unchanged
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
},
Metadata: {},
},
WithMetadata: { // Changed
Type: 'AWS::CloudFormation::Stack',
Properties: {
TemplateURL: 'https://www.magic-url.com',
NestedTemplate: {
Resources: {
SomeResource: {
Type: 'AWS::Something',
Properties: {
Property: 'new-value',
},
},
},
},
},
Metadata: {
'aws:asset:path': 'one-resource-stack.nested.template.json',
},
},
},
});
});
function pushStackResourceSummaries(stackName: string, ...items: CloudFormation.StackResourceSummary[]) {
if (!currentCfnStackResources[stackName]) {
currentCfnStackResources[stackName] = [];
}
currentCfnStackResources[stackName].push(...items);
}
function stackSummaryOf(logicalId: string, resourceType: string, physicalResourceId: string): CloudFormation.StackResourceSummary {
return {
LogicalResourceId: logicalId,
PhysicalResourceId: physicalResourceId,
ResourceType: resourceType,
ResourceStatus: 'CREATE_COMPLETE',
LastUpdatedTimestamp: new Date(),
};
} | the_stack |
import AWS from "aws-sdk";
import { utils } from "@serverless/core";
const HOSTED_ZONE_ID = "Z2FDTNDATAQYW2"; // this is a constant that you can get from here https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html
/**
* Get Clients
* - Gets AWS SDK clients to use within this Component
*/
const getClients = (credentials, region = "us-east-1") => {
if (AWS && AWS.config) {
AWS.config.update({
maxRetries: parseInt(process.env.SLS_NEXT_MAX_RETRIES || "10"),
retryDelayOptions: { base: 200 }
});
}
const route53 = new AWS.Route53({
credentials,
region
});
const acm = new AWS.ACM({
credentials,
region: "us-east-1" // ACM must be in us-east-1
});
const cf = new AWS.CloudFront({
credentials,
region
});
return {
route53,
acm,
cf
};
};
/**
* Prepare Domains
* - Formats component domains & identifies cloud services they're using.
*/
const prepareSubdomains = (inputs) => {
const subdomains = [];
for (const subdomain in inputs.subdomains || {}) {
const domainObj: any = {};
domainObj.domain = `${subdomain}.${inputs.domain}`;
if (inputs.subdomains[subdomain].url.includes("cloudfront")) {
domainObj.distributionId = inputs.subdomains[subdomain].id;
domainObj.url = inputs.subdomains[subdomain].url;
domainObj.type = "awsCloudFront";
}
subdomains.push(domainObj);
}
return subdomains;
};
const getOutdatedDomains = (inputs, state) => {
if (inputs.domain !== state.domain) {
return state;
}
const outdatedDomains = {
domain: state.domain,
subdomains: []
};
for (const domain of state.subdomains) {
if (!inputs.subdomains[domain.domain]) {
outdatedDomains.subdomains.push(domain);
}
}
return outdatedDomains;
};
/**
* Get Domain Hosted Zone ID
* - Every Domain on Route53 always has a Hosted Zone w/ 2 Record Sets.
* - These Record Sets are: "Name Servers (NS)" & "Start of Authority (SOA)"
* - These don't need to be created and SHOULD NOT be modified.
*/
const getDomainHostedZoneId = async (route53, domain, privateZone) => {
const params = {
DNSName: domain
};
const hostedZonesRes = await route53.listHostedZonesByName(params).promise();
const hostedZone = hostedZonesRes.HostedZones.find(
// Name has a period at the end, so we're using includes rather than equals
(zone) =>
zone.Config.PrivateZone === privateZone && zone.Name.includes(domain)
);
if (!hostedZone) {
throw Error(
`Domain ${domain} was not found in your AWS account. Please purchase it from Route53 first then try again.`
);
}
return hostedZone.Id.replace("/hostedzone/", ""); // hosted zone id is always prefixed with this :(
};
/**
* Describe Certificate By Arn
* - Describe an AWS ACM Certificate by its ARN
*/
const describeCertificateByArn = async (acm, certificateArn) => {
const certificate = await acm
.describeCertificate({ CertificateArn: certificateArn })
.promise();
return certificate && certificate.Certificate
? certificate.Certificate
: null;
};
/**
* Get Certificate Arn By Domain
* - Gets an AWS ACM Certificate by a specified domain or return null
*/
const getCertificateArnByDomain = async (acm, domain) => {
const listRes = await acm.listCertificates().promise();
for (const certificate of listRes.CertificateSummaryList) {
if (certificate.DomainName === domain && certificate.CertificateArn) {
if (domain.startsWith("www.")) {
const nakedDomain = domain.replace("www.", "");
// check whether certificate support naked domain
const certDetail = await describeCertificateByArn(
acm,
certificate.CertificateArn
);
const nakedDomainCert = certDetail.DomainValidationOptions.find(
({ DomainName }) => DomainName === nakedDomain
);
if (!nakedDomainCert) {
continue;
}
}
return certificate.CertificateArn;
}
}
return null;
};
/**
* Create Certificate
* - Creates an AWS ACM Certificate for the specified domain
*/
const createCertificate = async (acm, domain) => {
const wildcardSubDomain = `*.${domain}`;
const params = {
DomainName: domain,
SubjectAlternativeNames: [domain, wildcardSubDomain],
ValidationMethod: "DNS"
};
const res = await acm.requestCertificate(params).promise();
return res.CertificateArn;
};
/**
* Validate Certificate
* - Validate an AWS ACM Certificate via the "DNS" method
*/
const validateCertificate = async (
acm,
route53,
certificate,
domain,
domainHostedZoneId
) => {
let readinessCheckCount = 16;
let statusCheckCount = 16;
let validationResourceRecord;
/**
* Check Readiness
* - Newly Created AWS ACM Certificates may not yet have the info needed to validate it
* - Specifically, the "ResourceRecord" object in the Domain Validation Options
* - Ensure this exists.
*/
const checkReadiness = async function () {
if (readinessCheckCount < 1) {
throw new Error(
"Your newly created AWS ACM Certificate is taking a while to initialize. Please try running this component again in a few minutes."
);
}
const cert = await describeCertificateByArn(
acm,
certificate.CertificateArn
);
// Find root domain validation option resource record
cert.DomainValidationOptions.forEach((option) => {
if (domain === option.DomainName) {
validationResourceRecord = option.ResourceRecord;
}
});
if (!validationResourceRecord) {
readinessCheckCount--;
await utils.sleep(5000);
return await checkReadiness();
}
};
await checkReadiness();
const checkRecordsParams = {
HostedZoneId: domainHostedZoneId,
MaxItems: "10",
StartRecordName: validationResourceRecord.Name
};
// Check if the validation resource record sets already exist.
// This might be the case if the user is trying to deploy multiple times while validation is occurring.
const existingRecords = await route53
.listResourceRecordSets(checkRecordsParams)
.promise();
if (!existingRecords.ResourceRecordSets.length) {
// Create CNAME record for DNS validation check
// NOTE: It can take 30 minutes or longer for DNS propagation so validation can complete, just continue on and don't wait for this...
const recordParams = {
HostedZoneId: domainHostedZoneId,
ChangeBatch: {
Changes: [
{
Action: "UPSERT",
ResourceRecordSet: {
Name: validationResourceRecord.Name,
Type: validationResourceRecord.Type,
TTL: 300,
ResourceRecords: [
{
Value: validationResourceRecord.Value
}
]
}
}
]
}
};
await route53.changeResourceRecordSets(recordParams).promise();
}
/**
* Check Validated Status
* - Newly Validated AWS ACM Certificates may not yet show up as valid
* - This gives them some time to update their status.
*/
const checkStatus = async function () {
if (statusCheckCount < 1) {
throw new Error(
"Your newly validated AWS ACM Certificate is taking a while to register as valid. Please try running this component again in a few minutes."
);
}
const cert = await describeCertificateByArn(
acm,
certificate.CertificateArn
);
if (cert.Status !== "ISSUED") {
statusCheckCount--;
await utils.sleep(10000);
return await checkStatus();
}
};
await checkStatus();
};
/**
* Configure DNS records for a distribution domain
*/
const configureDnsForCloudFrontDistribution = (
route53,
subdomain,
domainHostedZoneId,
distributionUrl,
domainType,
context
) => {
const dnsRecordParams = {
HostedZoneId: domainHostedZoneId,
ChangeBatch: {
Changes: []
}
};
// don't create www records for apex mode
if (!subdomain.domain.startsWith("www.") || domainType !== "apex") {
dnsRecordParams.ChangeBatch.Changes.push({
Action: "UPSERT",
ResourceRecordSet: {
Name: subdomain.domain,
Type: "A",
AliasTarget: {
HostedZoneId: HOSTED_ZONE_ID,
DNSName: distributionUrl,
EvaluateTargetHealth: false
}
}
});
}
// don't create apex records for www mode
if (subdomain.domain.startsWith("www.") && domainType !== "www") {
dnsRecordParams.ChangeBatch.Changes.push({
Action: "UPSERT",
ResourceRecordSet: {
Name: subdomain.domain.replace("www.", ""),
Type: "A",
AliasTarget: {
HostedZoneId: HOSTED_ZONE_ID,
DNSName: distributionUrl,
EvaluateTargetHealth: false
}
}
});
}
context.debug(
"Updating Route53 DNS records with parameters:\n" +
JSON.stringify(dnsRecordParams, null, 2)
);
return route53.changeResourceRecordSets(dnsRecordParams).promise();
};
/**
* Remove AWS CloudFront Website DNS Records
*/
const removeCloudFrontDomainDnsRecords = async (
route53,
domain,
domainHostedZoneId,
distributionUrl,
context
) => {
const params = {
HostedZoneId: domainHostedZoneId,
ChangeBatch: {
Changes: [
{
Action: "DELETE",
ResourceRecordSet: {
Name: domain,
Type: "A",
AliasTarget: {
HostedZoneId: HOSTED_ZONE_ID,
DNSName: distributionUrl,
EvaluateTargetHealth: false
}
}
}
]
}
};
// TODO: should the CNAME records be removed too?
try {
context.debug(
"Updating Route53 with parameters:\n" + JSON.stringify(params, null, 2)
);
await route53.changeResourceRecordSets(params).promise();
} catch (e) {
if (e.code !== "InvalidChangeBatch") {
throw e;
}
}
};
const addDomainToCloudfrontDistribution = async (
cf,
subdomain,
certificateArn,
domainMinimumProtocolVersion,
domainType,
defaultCloudfrontInputs,
context
) => {
// Update logic is a bit weird...
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudFront.html#updateDistribution-property
// 1. we gotta get the config first...
const params = await cf
.getDistributionConfig({ Id: subdomain.distributionId })
.promise();
// 2. then add this property
params.IfMatch = params.ETag;
// 3. then delete this property
delete params.ETag;
// 4. then set this property
params.Id = subdomain.distributionId;
// 5. then make our changes
params.DistributionConfig.Aliases = {
Items: [subdomain.domain]
};
if (subdomain.domain.startsWith("www.")) {
if (domainType === "apex") {
params.DistributionConfig.Aliases.Items = [
`${subdomain.domain.replace("www.", "")}`
];
} else if (domainType !== "www") {
params.DistributionConfig.Aliases.Items.push(
`${subdomain.domain.replace("www.", "")}`
);
}
}
// Update aliases quantity to reflect actual number of items
params.DistributionConfig.Aliases.Quantity =
params.DistributionConfig.Aliases.Items.length;
params.DistributionConfig.ViewerCertificate = {
ACMCertificateArn: certificateArn,
SSLSupportMethod: "sni-only",
MinimumProtocolVersion: domainMinimumProtocolVersion,
Certificate: certificateArn,
CertificateSource: "acm",
...defaultCloudfrontInputs.viewerCertificate
};
context.debug(
"Updating CloudFront distribution with parameters:\n" +
JSON.stringify(params, null, 2)
);
// 6. then finally update!
const res = await cf.updateDistribution(params).promise();
return {
id: res.Distribution.Id,
arn: res.Distribution.ARN,
url: res.Distribution.DomainName
};
};
const removeDomainFromCloudFrontDistribution = async (
cf,
subdomain,
domainMinimumProtocolVersion,
context
) => {
const params = await cf
.getDistributionConfig({ Id: subdomain.distributionId })
.promise();
params.IfMatch = params.ETag;
delete params.ETag;
params.Id = subdomain.distributionId;
params.DistributionConfig.Aliases = {
Quantity: 0,
Items: []
};
params.DistributionConfig.ViewerCertificate = {
SSLSupportMethod: "sni-only",
MinimumProtocolVersion: domainMinimumProtocolVersion
};
context.debug(
"Updating CloudFront distribution with parameters:\n" +
JSON.stringify(params, null, 2)
);
const res = await cf.updateDistribution(params).promise();
return {
id: res.Distribution.Id,
arn: res.Distribution.ARN,
url: res.Distribution.DomainName
};
};
const isMinimumProtocolVersionValid = (minimumProtocolVersion) => {
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-viewercertificate.html
const validMinimumProtocolVersions =
/(^SSLv3$|^TLSv1$|^TLSv1.1_2016$|^TLSv1.2_2018$|^TLSv1.2_2019$|^TLSv1.2_2021$|^TLSv1_2016$)/g;
return (
minimumProtocolVersion.match(validMinimumProtocolVersions)?.length === 1
);
};
export {
getClients,
prepareSubdomains,
getOutdatedDomains,
describeCertificateByArn,
getCertificateArnByDomain,
createCertificate,
validateCertificate,
getDomainHostedZoneId,
configureDnsForCloudFrontDistribution,
removeCloudFrontDomainDnsRecords,
addDomainToCloudfrontDistribution,
removeDomainFromCloudFrontDistribution,
isMinimumProtocolVersionValid
}; | the_stack |
import {BaseParamType} from '../../params/_Base';
import {CoreGraphNode} from '../../../core/graph/CoreGraphNode';
import {ParsedTree} from './ParsedTree';
import {LiteralConstructsController, LiteralConstructMethod} from '../LiteralConstructsController';
import {BaseMethod} from '../methods/_Base';
import {CoreAttribute} from '../../../core/geometry/Attribute';
// import {JsepsByString} from '../DependenciesController'
import jsep from 'jsep';
// import {Vector3} from 'three/src/math/Vector3'
type LiteralConstructDictionary = PolyDictionary<LiteralConstructMethod>;
type AnyDictionary = PolyDictionary<any>;
const NATIVE_MATH_METHODS = [
'abs',
'acos',
'acosh',
'asin',
'asinh',
'atan',
'atan2',
'atanh',
'ceil',
'cos',
'cosh',
'exp',
'expm1',
'floor',
'log',
'log1p',
'log2',
'log10',
'max',
'min',
'pow',
'round',
'sign',
'sin',
'sinh',
'sqrt',
'tan',
'tanh',
];
const NATIVE_ES6_MATH_METHODS = ['cbrt', 'hypot', 'log10', 'trunc'];
const NATIVE_MATH_METHODS_RENAMED: AnyDictionary = {
math_random: 'random',
};
const CORE_MATH_METHODS = ['fit', 'fit01', 'fract', 'deg2rad', 'rad2deg', 'rand', 'clamp'];
import {Easing} from '../../../core/math/Easing';
const EASING_METHODS = Object.keys(Easing);
const CORE_STRING_METHODS = ['precision'];
const NATIVE_MATH_CONSTANTS = ['E', 'LN2', 'LN10', 'LOG10E', 'LOG2E', 'PI', 'SQRT1_2', 'SQRT2'];
const DIRECT_EXPRESSION_FUNCTIONS: AnyDictionary = {};
NATIVE_MATH_METHODS.forEach((name) => {
DIRECT_EXPRESSION_FUNCTIONS[name] = `Math.${name}`;
});
NATIVE_ES6_MATH_METHODS.forEach((name) => {
DIRECT_EXPRESSION_FUNCTIONS[name] = `Math.${name}`;
});
Object.keys(NATIVE_MATH_METHODS_RENAMED).forEach((name) => {
const remaped = NATIVE_MATH_METHODS_RENAMED[name];
DIRECT_EXPRESSION_FUNCTIONS[name] = `Math.${remaped}`;
});
CORE_MATH_METHODS.forEach((name) => {
DIRECT_EXPRESSION_FUNCTIONS[name] = `Core.Math.${name}`;
});
EASING_METHODS.forEach((name) => {
DIRECT_EXPRESSION_FUNCTIONS[name] = `Core.Math.Easing.${name}`;
});
CORE_STRING_METHODS.forEach((name) => {
DIRECT_EXPRESSION_FUNCTIONS[name] = `Core.String.${name}`;
});
const LITERAL_CONSTRUCT: LiteralConstructDictionary = {
if: LiteralConstructsController.if,
};
const GLOBAL_CONSTANTS: PolyDictionary<string> = {};
NATIVE_MATH_CONSTANTS.forEach((name) => {
GLOBAL_CONSTANTS[name] = `Math.${name}`;
});
const QUOTE = "'";
const ARGUMENTS_SEPARATOR = ', ';
const ATTRIBUTE_PREFIX = '@';
import {VARIABLE_PREFIX} from './_Base';
const PROPERTY_OFFSETS: AnyDictionary = {
x: 0,
y: 1,
z: 2,
w: 3,
r: 0,
g: 1,
b: 2,
};
import {BaseTraverser} from './_Base';
import {MethodDependency} from '../MethodDependency';
import {AttributeRequirementsController} from '../AttributeRequirementsController';
import {CoreMath} from '../../../core/math/_Module';
import {CoreString} from '../../../core/String';
// import {AsyncFunction} from '../../../core/AsyncFunction';
import {Poly} from '../../Poly';
import {CoreType} from '../../../core/Type';
import {PolyDictionary} from '../../../types/GlobalTypes';
export class FunctionGenerator extends BaseTraverser {
private function: Function | undefined;
private _attribute_requirements_controller = new AttributeRequirementsController();
private function_main_string: string | undefined;
private methods: BaseMethod[] = [];
private method_index: number = -1;
public method_dependencies: MethodDependency[] = [];
public immutable_dependencies: CoreGraphNode[] = [];
// public jsep_dependencies: JsepDependency[] = []
// public jsep_nodes_by_missing_paths: JsepsByString = {}
// private string_generator: ExpressionStringGenerator = new ExpressionStringGenerator()
constructor(public param: BaseParamType) {
super(param);
}
public parse_tree(parsed_tree: ParsedTree) {
this.reset();
if (parsed_tree.error_message == null) {
try {
// this.function_pre_entities_loop_lines = [];
this._attribute_requirements_controller.reset();
// this.function_pre_body = ''
if (parsed_tree.node) {
const function_main_string = this.traverse_node(parsed_tree.node);
if (function_main_string && !this.is_errored()) {
this.function_main_string = function_main_string;
}
} else {
console.warn('no parsed_tree.node');
}
} catch (e) {
console.warn(`error in expression for param ${this.param.path()}`);
console.warn(e);
}
if (this.function_main_string) {
try {
// not sure why I needed AsyncFunction
this.function = new Function(
'Core',
'param',
'methods',
'_set_error_from_error',
`
try {
${this.function_body()}
} catch(e) {
_set_error_from_error(e)
return null;
}`
);
} catch (e) {
console.warn(e);
this.set_error('cannot generate function');
}
} else {
this.set_error('cannot generate function body');
}
} else {
this.set_error('cannot parse expression');
}
}
reset() {
super.reset();
this.function_main_string = undefined;
this.methods = [];
this.method_index = -1;
this.function = undefined;
this.method_dependencies = [];
this.immutable_dependencies = [];
}
function_body() {
if (this.param.options.isExpressionForEntities()) {
return `
const entities = param.expressionController.entities();
if(entities){
return new Promise( async (resolve, reject)=>{
let entity;
const entity_callback = param.expressionController.entity_callback();
${this._attribute_requirements_controller.assign_attributes_lines()}
if( ${this._attribute_requirements_controller.attribute_presence_check_line()} ){
${this._attribute_requirements_controller.assign_arrays_lines()}
for(let index=0; index < entities.length; index++){
entity = entities[index];
result = ${this.function_main_string};
entity_callback(entity, result);
}
resolve()
} else {
const error = new Error('attribute not found')
_set_error_from_error(error)
reject(error)
}
})
}
return []`;
} else {
return `
return new Promise( async (resolve, reject)=>{
try {
const value = ${this.function_main_string}
resolve(value)
} catch(e) {
_set_error_from_error(e)
reject()
}
})
`;
}
}
eval_allowed(): boolean {
return this.function != null;
}
eval_function() {
// this.param.entity_attrib_values = this.param.entity_attrib_values || {}
// this.param.entity_attrib_values.position =
// this.param.entity_attrib_values.position || new THREE.Vector3()
if (this.function) {
this.clear_error();
const Core = {
Math: CoreMath,
String: CoreString,
};
const result = this.function(Core, this.param, this.methods, this._set_error_from_error_bound);
return result;
}
}
//
//
// TRAVERSE METHODS
//
//
protected traverse_CallExpression(node: jsep.CallExpression): string | undefined {
const method_arguments = node.arguments.map((arg) => {
return this.traverse_node(arg);
});
const callee = node.callee as jsep.Identifier;
const method_name = callee.name;
if (method_name) {
// literal construct (if...)
const literal_contruct = LITERAL_CONSTRUCT[method_name];
if (literal_contruct) {
return literal_contruct(method_arguments);
}
// direct expressions (Math.floor, Math.sin...)
const arguments_joined = `${method_arguments.join(ARGUMENTS_SEPARATOR)}`;
const direct_function_name = DIRECT_EXPRESSION_FUNCTIONS[method_name];
if (direct_function_name) {
return `${direct_function_name}(${arguments_joined})`;
}
// indirect methods (pointsCount, asset...)
const expressionRegister = Poly.expressionsRegister;
const indirect_method = expressionRegister.getMethod(method_name);
if (indirect_method) {
const path_node = node.arguments[0];
// const path_argument = this.string_generator.traverse_node(path_node)
const function_string = `return ${method_arguments[0]}`;
let path_argument_function;
let path_argument = [];
try {
path_argument_function = new Function(function_string);
path_argument = path_argument_function();
} catch {
// path_argument_function = new AsyncFunction(function_string)
// it looks like if the input contains an await,
// it is because it has been generated by another indirect function.
// This means that the dependencies have been generated already
// so we may not need to do it now
}
this._create_method_and_dependencies(method_name, path_argument, path_node);
return `(await methods[${this.method_index}].processArguments([${arguments_joined}]))`;
} else {
const available_methods = expressionRegister.availableMethods().join(', ');
const message = `method not found (${method_name}), available methods are: ${available_methods}`;
Poly.warn(message);
}
}
this.set_error(`unknown method: ${method_name}`);
}
protected traverse_BinaryExpression(node: jsep.BinaryExpression): string {
// if(node.right.type == 'Identifier'){
// this.set_error(`cannot have identifier after ${node.operator}`)
// return ""
// }
return `(${this.traverse_node(node.left)} ${node.operator} ${this.traverse_node(node.right)})`;
}
protected traverse_LogicalExpression(node: jsep.LogicalExpression): string {
// || or &&
// if(node.right.type == 'Identifier'){
// this.set_error(`cannot have identifier after ${node.operator}`)
// return ""
// }
return `(${this.traverse_node(node.left)} ${node.operator} ${this.traverse_node(node.right)})`;
}
protected traverse_MemberExpression(node: jsep.MemberExpression): string {
return `${this.traverse_node(node.object)}.${this.traverse_node(node.property)}`;
}
protected traverse_UnaryExpression(node: jsep.UnaryExpression): string {
if (node.operator === ATTRIBUTE_PREFIX) {
let argument = node.argument;
let attribute_name;
let property;
switch (argument.type) {
case 'Identifier': {
const argument_identifier = (<unknown>argument) as jsep.Identifier;
attribute_name = argument_identifier.name;
break;
}
case 'MemberExpression': {
const argument_member_expression = (<unknown>argument) as jsep.MemberExpression;
const attrib_node = argument_member_expression.object as jsep.Identifier;
const property_node = argument_member_expression.property as jsep.Identifier;
attribute_name = attrib_node.name;
property = property_node.name;
break;
}
}
// this.function_pre_body += `
// param.entity_attrib_value(${QUOTE}${attrib_node.name}${QUOTE}, param.entity_attrib_values.position);
// `
if (attribute_name) {
attribute_name = CoreAttribute.remapName(attribute_name);
if (attribute_name == 'ptnum') {
return '((entity != null) ? entity.index() : 0)';
} else {
const var_attribute_size = this._attribute_requirements_controller.var_attribute_size(
attribute_name
);
const var_array = this._attribute_requirements_controller.var_array(attribute_name);
this._attribute_requirements_controller.add(attribute_name);
if (property) {
const property_offset = PROPERTY_OFFSETS[property];
return `${var_array}[entity.index()*${var_attribute_size}+${property_offset}]`;
} else {
return `${var_array}[entity.index()*${var_attribute_size}]`;
}
}
} else {
console.warn('attribute not found');
return '';
}
} else {
return `${node.operator}${this.traverse_node(node.argument)}`; // -5
}
}
protected traverse_Literal(node: jsep.Literal): string {
return `${node.raw}`; // 5 or 'string' (raw will include quotes)
}
protected traverse_Identifier(node: jsep.Identifier): string | undefined {
const identifier_first_char = node.name[0];
if (identifier_first_char == VARIABLE_PREFIX) {
const identifier_name_without_dollar_sign = node.name.substr(1);
// globals constants: Math.PI or Math.E
const direct_constant_name = GLOBAL_CONSTANTS[identifier_name_without_dollar_sign];
if (direct_constant_name) {
return direct_constant_name;
}
// scene or node globals: $F, $T, $OS, $CH, $OS
const method_name = `traverse_Identifier_${identifier_name_without_dollar_sign}`;
const method = (this as any)[method_name];
if (method) {
return (this as any)[method_name]();
} else {
this.set_error(`identifier unknown: ${node.name}`);
}
} else {
return node.name; // @ptnum will call this method and return "ptnum"
}
}
//
//
// Identifier methods (called from Identifier_body)
//
//
protected traverse_Identifier_F(): string {
this.immutable_dependencies.push(this.param.scene().timeController.graphNode);
return `param.scene().timeController.frame()`;
}
// protected traverse_Identifier_FPS(): string {
// this.immutable_dependencies.push(this.param.scene().timeController.graphNode);
// return `param.scene().timeController.fps`;
// }
protected traverse_Identifier_T(): string {
this.immutable_dependencies.push(this.param.scene().timeController.graphNode);
return `param.scene().timeController.time()`;
}
protected traverse_Identifier_OS(): string {
return `${QUOTE}${this.param.node.name()}${QUOTE}`;
}
protected traverse_Identifier_CH(): string {
return `${QUOTE}${this.param.name()}${QUOTE}`;
}
protected traverse_Identifier_CEX(): string {
return this._method_centroid('x');
}
protected traverse_Identifier_CEY(): string {
return this._method_centroid('y');
}
protected traverse_Identifier_CEZ(): string {
return this._method_centroid('z');
}
// TODO:
// '$OS': '_eval_identifier_as_node_name',
// '$BBX': '_eval_identifier_as_bounding_box_relative',
private _method_centroid(component: string): string {
const method_arguments = [0, `${QUOTE}${component}${QUOTE}`];
const arguments_joined = method_arguments.join(ARGUMENTS_SEPARATOR);
this._create_method_and_dependencies('centroid', 0);
return `(await methods[${this.method_index}].processArguments([${arguments_joined}]))`;
}
//
//
// Methods dependencies
//
//
private _create_method_and_dependencies(
method_name: string,
path_argument: number | string,
path_node?: jsep.Expression
) {
const expressionRegister = Poly.expressionsRegister;
const method_constructor = expressionRegister.getMethod(method_name);
if (!method_constructor) {
const available_methods = expressionRegister.availableMethods();
const message = `method not found (${method_name}), available methods are: ${available_methods.join(', ')}`;
this.set_error(message);
Poly.warn(message);
return;
}
const method = new method_constructor(this.param) as BaseMethod;
this.method_index += 1;
this.methods[this.method_index] = method;
if (method.require_dependency()) {
const method_dependency = method.findDependency(path_argument);
if (method_dependency) {
if (path_node) {
method_dependency.set_jsep_node(path_node);
}
this.method_dependencies.push(method_dependency);
} else {
if (path_node && CoreType.isString(path_argument)) {
this.param
.scene()
.missingExpressionReferencesController.register(this.param, path_node, path_argument);
}
}
}
// method_dependencies.resolved_graph_nodes.forEach((graph_node)=>{
// if(path_node){
// const jsep_dependency = new JsepDependency(graph_node, path_node)
// this.jsep_dependencies.push(jsep_dependency)
// } else {
// this.immutable_dependencies.push(graph_node)
// }
// })
// if(path_node){
// reference_search_result.missing_paths.forEach((path)=>{
// this.jsep_nodes_by_missing_paths[path] = this.jsep_nodes_by_missing_paths[path] || []
// this.jsep_nodes_by_missing_paths[path].push(path_node)
// })
// }
}
} | the_stack |
/// <reference path="../../typings/winjs/winjs.d.ts" />
module SplitViewTests {
"use strict";
var SplitViewPaneToggle = <typeof WinJS.UI.PrivateSplitViewPaneToggle>WinJS.UI.SplitViewPaneToggle;
var testRoot: HTMLElement;
var Utils = SplitViewTests.Utilities;
var createSplitView: (options?: any) => WinJS.UI.PrivateSplitView;
var createSplitViewPaneToggle: (element?: HTMLButtonElement, options?: any) => WinJS.UI.PrivateSplitViewPaneToggle;
function makeCreateSplitViewPaneToggle(testRoot) {
function createSplitViewPaneToggle(element?: HTMLButtonElement, options?: any): WinJS.UI.PrivateSplitViewPaneToggle {
var splitViewPaneToggle = new SplitViewPaneToggle(element, options);
testRoot.appendChild(splitViewPaneToggle.element);
return splitViewPaneToggle;
}
return createSplitViewPaneToggle;
}
function assertHasClass(element: HTMLElement, className: string, msg: string): void {
LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(element, className), msg);
}
// Taking the registration mechanism as a parameter allows us to use this code to test both
// DOM level 0 (e.g. oninvoked) and DOM level 2 (e.g. addEventListener) events.
function testEvents(registerForEvent: (splitViewPaneToggle: WinJS.UI.PrivateSplitViewPaneToggle, eventName: string, handler: Function) => void) {
var splitViewPaneToggle = createSplitViewPaneToggle();
var counter = 0;
registerForEvent(splitViewPaneToggle, "invoked", () => {
LiveUnit.Assert.areEqual(1, counter, "invoked fired out of order");
counter++;
});
LiveUnit.Assert.areEqual(0, counter, "before click: wrong number of events fired");
counter++;
splitViewPaneToggle._invoked();
LiveUnit.Assert.areEqual(2, counter, "after click: wrong number of events fired");
}
function testTogglingPaneState(args: {
firesInvokedEvent: boolean;
togglePaneState: (splitViewPaneToggle: WinJS.UI.PrivateSplitViewPaneToggle, splitView: WinJS.UI.PrivateSplitView) => void;
}) {
var invokedFired;
var onInvoked = () => {
invokedFired = true;
};
var verifyInvokedEvent = () => {
if (args.firesInvokedEvent) {
LiveUnit.Assert.isTrue(invokedFired, "SplitViewPaneToggle's invoked event should have fired");
} else {
LiveUnit.Assert.isFalse(invokedFired, "SplitViewPaneToggle's invoked event should not have fired");
}
};
var splitView = Utils.useSynchronousAnimations(createSplitView());
var splitViewPaneToggle = createSplitViewPaneToggle(null, {
splitView: splitView.element,
oninvoked: onInvoked
});
LiveUnit.Assert.isFalse(splitView.paneOpened, "Test expected SplitView to start out closed");
LiveUnit.Assert.areEqual("false", splitViewPaneToggle.element.getAttribute("aria-expanded"),
"Test expected SplitViewPaneToggle's aria-expanded attribute to start out 'false'");
invokedFired = false;
args.togglePaneState(splitViewPaneToggle, splitView);
verifyInvokedEvent();
LiveUnit.Assert.isTrue(splitView.paneOpened, "SplitView should have been opened by SplitViewPaneToggle");
LiveUnit.Assert.areEqual("true", splitViewPaneToggle.element.getAttribute("aria-expanded"),
"SplitViewPaneToggle's aria-expanded attribute should be 'true'");
invokedFired = false;
args.togglePaneState(splitViewPaneToggle, splitView);
verifyInvokedEvent();
LiveUnit.Assert.isFalse(splitView.paneOpened, "SplitView should have been closed by SplitViewPaneToggle");
LiveUnit.Assert.areEqual("false", splitViewPaneToggle.element.getAttribute("aria-expanded"),
"SplitViewPaneToggle's aria-expanded attribute should be 'false'");
}
export class SplitViewPaneToggleTests {
setUp() {
testRoot = document.createElement("div");
// Give it an id so that we can use it in styles to make sure our styles win over the defaults.
// We encourage apps to do the same.
testRoot.id = "test-root";
createSplitView = Utils.makeCreateSplitView(testRoot);
createSplitViewPaneToggle = makeCreateSplitViewPaneToggle(testRoot);
document.body.appendChild(testRoot);
}
tearDown() {
WinJS.Utilities.disposeSubTree(testRoot);
Helper.removeElement(testRoot);
}
testDomLevel0Events() {
testEvents((splitViewPaneToggle: WinJS.UI.PrivateSplitViewPaneToggle, eventName: string, handler: Function) => {
splitViewPaneToggle["on" + eventName] = handler;
});
}
testDomLevel2Events() {
testEvents((splitViewPaneToggle: WinJS.UI.PrivateSplitViewPaneToggle, eventName: string, handler: Function) => {
splitViewPaneToggle.addEventListener(eventName, handler);
});
}
// Verify that if we don't pass an element to the SplitViewPaneToggle's constructor, it creates
// one for us and initializes its DOM structure correctly.
testInitializationWithoutElement() {
var splitViewPaneToggle = createSplitViewPaneToggle();
LiveUnit.Assert.areEqual("BUTTON", splitViewPaneToggle.element.tagName, "SplitViewPaneToggle's element should be a button");
assertHasClass(splitViewPaneToggle.element, SplitViewPaneToggle._ClassNames.splitViewPaneToggle, "splitViewPaneToggle.element is missing class");
LiveUnit.Assert.isFalse(splitViewPaneToggle.element.hasAttribute("aria-controls"),
"SplitViewPaneToggle shouldn't have aria-controls attribute because it isn't paired with a SplitView");
LiveUnit.Assert.isFalse(splitViewPaneToggle.element.hasAttribute("aria-expanded"),
"SplitViewPaneToggle shouldn't have aria-expanded attribute because it isn't paired with a SplitView");
}
// Verify that if we pass an element containing markup to the SplitViewPaneToggle's constructor, it correctly
// initializes its DOM.
testInitializationWithElement() {
var element = document.createElement("button");
element.className = "myCustomClass";
var splitViewPaneToggle = createSplitViewPaneToggle(element);
LiveUnit.Assert.areEqual(element, splitViewPaneToggle.element, "SplitViewPaneToggle should have used the element that was passed to it");
LiveUnit.Assert.areEqual("BUTTON", element.tagName, "SplitViewPaneToggle's element should be a button");
assertHasClass(element, SplitViewPaneToggle._ClassNames.splitViewPaneToggle, "splitViewPaneToggle.element is missing class");
assertHasClass(element, "myCustomClass", "splitViewPaneToggle.element is missing class");
LiveUnit.Assert.isFalse(element.hasAttribute("aria-controls"),
"SplitViewPaneToggle shouldn't have aria-controls attribute because it isn't paired with a SplitView");
LiveUnit.Assert.isFalse(element.hasAttribute("aria-expanded"),
"SplitViewPaneToggle shouldn't have aria-expanded attribute because it isn't paired with a SplitView");
}
testInitializingProperties() {
var splitView = Utils.useSynchronousAnimations(createSplitView());
var splitViewPaneToggle = createSplitViewPaneToggle(null, {
splitView: splitView.element
});
LiveUnit.Assert.areEqual(splitView.element, splitViewPaneToggle.splitView, "splitView property has wrong value after initialization");
LiveUnit.Assert.areEqual(splitView.element.id, splitViewPaneToggle.element.getAttribute("aria-controls"),
"SplitViewPaneToggle has wrong value for aria-controls attribute");
LiveUnit.Assert.areEqual("false", splitViewPaneToggle.element.getAttribute("aria-expanded"),
"SplitViewPaneToggle's aria-expanded attribute should be 'false'");
}
testChangingProperties() {
var splitView = Utils.useSynchronousAnimations(createSplitView());
var splitViewPaneToggle = createSplitViewPaneToggle();
splitViewPaneToggle.splitView = splitView.element;
LiveUnit.Assert.areEqual(splitView.element, splitViewPaneToggle.splitView, "splitView property has wrong value after setting it");
LiveUnit.Assert.areEqual(splitView.element.id, splitViewPaneToggle.element.getAttribute("aria-controls"),
"SplitViewPaneToggle has wrong value for aria-controls attribute");
LiveUnit.Assert.areEqual("false", splitViewPaneToggle.element.getAttribute("aria-expanded"),
"SplitViewPaneToggle's aria-expanded attribute should be 'false'");
}
// Verify that the SplitViewPaneToggle correctly syncs with the SplitView when the
// SplitViewPaneToggle is created before the SplitView. This may happen during
// WinJS.UI.processAll because instantiation order depends on the order in which
// the controls appear in the DOM.
testInitializingSplitViewPaneToggleBeforeSplitView() {
[false, true].forEach((paneOpenedInitially) => {
var paneOpenedInitiallyStr = paneOpenedInitially ? "true" : "false";
var splitViewElement = document.createElement("div");
testRoot.appendChild(splitViewElement);
var splitViewPaneToggle = createSplitViewPaneToggle(null, {
splitView: splitViewElement
});
var splitView = Utils.useSynchronousAnimations(new SplitView(splitViewElement, {
paneOpened: paneOpenedInitially
}));
LiveUnit.Assert.areEqual(paneOpenedInitially, splitView.paneOpened, "SplitView paneOpened wasn't initialized correctly");
LiveUnit.Assert.areEqual(paneOpenedInitiallyStr, splitViewPaneToggle.element.getAttribute("aria-expanded"),
"SplitViewPaneToggle has wrong value for aria-expanded attribute");
LiveUnit.Assert.areEqual(splitView.element.id, splitViewPaneToggle.element.getAttribute("aria-controls"),
"SplitViewPaneToggle has wrong value for aria-controls attribute");
});
}
// Simulates invoking the button with mouse/touch/keyboard.
testTogglingPaneStateWithInvoke() {
testTogglingPaneState({
firesInvokedEvent: true,
togglePaneState: function (splitViewPaneToggle, splitView) {
splitViewPaneToggle._invoked();
}
});
}
testTogglingPaneStateWithAriaExpanded() {
testTogglingPaneState({
firesInvokedEvent: false,
togglePaneState: function (splitViewPaneToggle, splitView) {
var ariaExpanded = splitViewPaneToggle.element.getAttribute("aria-expanded") === "true";
splitViewPaneToggle.element.setAttribute("aria-expanded", ariaExpanded ? "false" : "true");
// Mutation observers notify asynchronously. Simulate synchronous notification
// so the test can be synchronous.
splitViewPaneToggle._onAriaExpandedPropertyChanged([{
type: "attributes",
target: splitViewPaneToggle.element,
attributeName: "aria-expanded"
}]);
}
});
}
testTogglingPaneStateWithSplitView() {
testTogglingPaneState({
firesInvokedEvent: false,
togglePaneState: function (splitViewPaneToggle, splitView) {
splitView.paneOpened = !splitView.paneOpened;
}
});
}
testDispose() {
function failEventHandler(eventName) {
return function () {
LiveUnit.Assert.fail(eventName + ": shouldn't have run due to control being disposed");
};
}
var splitView = Utils.useSynchronousAnimations(createSplitView());
var splitViewPaneToggle = createSplitViewPaneToggle(null, {
splitView: splitView.element,
oninvoked: failEventHandler("invoked")
});
LiveUnit.Assert.isFalse(splitView.paneOpened, "Test expected SplitView to start out closed");
splitViewPaneToggle.dispose();
LiveUnit.Assert.isTrue(splitViewPaneToggle._disposed, "SplitViewPaneToggle didn't mark itself as disposed");
splitViewPaneToggle._invoked();
LiveUnit.Assert.isFalse(splitView.paneOpened, "SplitView should still be closed");
splitViewPaneToggle.dispose();
}
}
}
LiveUnit.registerTestClass("SplitViewTests.SplitViewPaneToggleTests"); | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Allows creation of templates to de-identify content.
*
* To get more information about DeidentifyTemplate, see:
*
* * [API documentation](https://cloud.google.com/dlp/docs/reference/rest/v2/projects.deidentifyTemplates)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/dlp/docs/concepts-templates)
*
* ## Example Usage
* ### Dlp Deidentify Template Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const basic = new gcp.dataloss.PreventionDeidentifyTemplate("basic", {
* deidentifyConfig: {
* infoTypeTransformations: {
* transformations: [
* {
* infoTypes: [{
* name: "FIRST_NAME",
* }],
* primitiveTransformation: {
* replaceWithInfoTypeConfig: true,
* },
* },
* {
* infoTypes: [
* {
* name: "PHONE_NUMBER",
* },
* {
* name: "AGE",
* },
* ],
* primitiveTransformation: {
* replaceConfig: {
* newValue: {
* integerValue: 9,
* },
* },
* },
* },
* {
* infoTypes: [
* {
* name: "EMAIL_ADDRESS",
* },
* {
* name: "LAST_NAME",
* },
* ],
* primitiveTransformation: {
* characterMaskConfig: {
* charactersToIgnores: [{
* commonCharactersToIgnore: "PUNCTUATION",
* }],
* maskingCharacter: "X",
* numberToMask: 4,
* reverseOrder: true,
* },
* },
* },
* {
* infoTypes: [{
* name: "DATE_OF_BIRTH",
* }],
* primitiveTransformation: {
* replaceConfig: {
* newValue: {
* dateValue: {
* day: 1,
* month: 1,
* year: 2020,
* },
* },
* },
* },
* },
* {
* infoTypes: [{
* name: "CREDIT_CARD_NUMBER",
* }],
* primitiveTransformation: {
* cryptoDeterministicConfig: {
* context: {
* name: "sometweak",
* },
* cryptoKey: {
* transient: {
* name: "beep",
* },
* },
* surrogateInfoType: {
* name: "abc",
* },
* },
* },
* },
* ],
* },
* },
* description: "Description",
* displayName: "Displayname",
* parent: "projects/my-project-name",
* });
* ```
*
* ## Import
*
* DeidentifyTemplate can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:dataloss/preventionDeidentifyTemplate:PreventionDeidentifyTemplate default {{parent}}/deidentifyTemplates/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:dataloss/preventionDeidentifyTemplate:PreventionDeidentifyTemplate default {{parent}}/{{name}}
* ```
*/
export class PreventionDeidentifyTemplate extends pulumi.CustomResource {
/**
* Get an existing PreventionDeidentifyTemplate 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?: PreventionDeidentifyTemplateState, opts?: pulumi.CustomResourceOptions): PreventionDeidentifyTemplate {
return new PreventionDeidentifyTemplate(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:dataloss/preventionDeidentifyTemplate:PreventionDeidentifyTemplate';
/**
* Returns true if the given object is an instance of PreventionDeidentifyTemplate. 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 PreventionDeidentifyTemplate {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === PreventionDeidentifyTemplate.__pulumiType;
}
/**
* Configuration of the deidentify template
* Structure is documented below.
*/
public readonly deidentifyConfig!: pulumi.Output<outputs.dataloss.PreventionDeidentifyTemplateDeidentifyConfig>;
/**
* A description of the template.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* User set display name of the template.
*/
public readonly displayName!: pulumi.Output<string | undefined>;
/**
* Name of the information type. Either a name of your choosing when creating a CustomInfoType, or one of the names listed at [https://cloud.google.com/dlp/docs/infotypes-reference](https://cloud.google.com/dlp/docs/infotypes-reference) when specifying a built-in type. When sending Cloud DLP results to Data Catalog, infoType names should conform to the pattern `[A-Za-z0-9$-_]{1,64}`.
*/
public /*out*/ readonly name!: pulumi.Output<string>;
/**
* The parent of the template in any of the following formats:
* * `projects/{{project}}`
* * `projects/{{project}}/locations/{{location}}`
* * `organizations/{{organization_id}}`
* * `organizations/{{organization_id}}/locations/{{location}}`
*/
public readonly parent!: pulumi.Output<string>;
/**
* Create a PreventionDeidentifyTemplate 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: PreventionDeidentifyTemplateArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: PreventionDeidentifyTemplateArgs | PreventionDeidentifyTemplateState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as PreventionDeidentifyTemplateState | undefined;
inputs["deidentifyConfig"] = state ? state.deidentifyConfig : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["displayName"] = state ? state.displayName : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["parent"] = state ? state.parent : undefined;
} else {
const args = argsOrState as PreventionDeidentifyTemplateArgs | undefined;
if ((!args || args.deidentifyConfig === undefined) && !opts.urn) {
throw new Error("Missing required property 'deidentifyConfig'");
}
if ((!args || args.parent === undefined) && !opts.urn) {
throw new Error("Missing required property 'parent'");
}
inputs["deidentifyConfig"] = args ? args.deidentifyConfig : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["displayName"] = args ? args.displayName : undefined;
inputs["parent"] = args ? args.parent : undefined;
inputs["name"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(PreventionDeidentifyTemplate.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering PreventionDeidentifyTemplate resources.
*/
export interface PreventionDeidentifyTemplateState {
/**
* Configuration of the deidentify template
* Structure is documented below.
*/
deidentifyConfig?: pulumi.Input<inputs.dataloss.PreventionDeidentifyTemplateDeidentifyConfig>;
/**
* A description of the template.
*/
description?: pulumi.Input<string>;
/**
* User set display name of the template.
*/
displayName?: pulumi.Input<string>;
/**
* Name of the information type. Either a name of your choosing when creating a CustomInfoType, or one of the names listed at [https://cloud.google.com/dlp/docs/infotypes-reference](https://cloud.google.com/dlp/docs/infotypes-reference) when specifying a built-in type. When sending Cloud DLP results to Data Catalog, infoType names should conform to the pattern `[A-Za-z0-9$-_]{1,64}`.
*/
name?: pulumi.Input<string>;
/**
* The parent of the template in any of the following formats:
* * `projects/{{project}}`
* * `projects/{{project}}/locations/{{location}}`
* * `organizations/{{organization_id}}`
* * `organizations/{{organization_id}}/locations/{{location}}`
*/
parent?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a PreventionDeidentifyTemplate resource.
*/
export interface PreventionDeidentifyTemplateArgs {
/**
* Configuration of the deidentify template
* Structure is documented below.
*/
deidentifyConfig: pulumi.Input<inputs.dataloss.PreventionDeidentifyTemplateDeidentifyConfig>;
/**
* A description of the template.
*/
description?: pulumi.Input<string>;
/**
* User set display name of the template.
*/
displayName?: pulumi.Input<string>;
/**
* The parent of the template in any of the following formats:
* * `projects/{{project}}`
* * `projects/{{project}}/locations/{{location}}`
* * `organizations/{{organization_id}}`
* * `organizations/{{organization_id}}/locations/{{location}}`
*/
parent: pulumi.Input<string>;
} | the_stack |
import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component, ElementRef, Input, OnDestroy, OnInit, Renderer2, ViewChild } from '@angular/core';
import { JsonSchemaFormComponent } from '@cfstratos/ajsf-core';
import * as yaml from 'js-yaml';
import { BehaviorSubject, combineLatest, fromEvent, Observable, of, Subscription } from 'rxjs';
import { catchError, debounceTime, filter, map, startWith, tap } from 'rxjs/operators';
import { ConfirmationDialogConfig } from '../../../../../core/src/shared/components/confirmation-dialog.config';
import { ConfirmationDialogService } from '../../../../../core/src/shared/components/confirmation-dialog.service';
import { ThemeService } from '../../../../../store/src/theme.service';
import { diffObjects } from './diffvalues';
import { generateJsonSchemaFromObject } from './json-schema-generator';
import { mergeObjects } from './merge';
export interface ChartValuesConfig {
// URL of the JSON Schema for the chart values
schemaUrl: string;
// URL of the Chart Values
valuesUrl: string;
// Values for the current release (optional)
releaseValues?: string;
}
// Height of the toolbar that sits above the editor conmponent
const TOOLBAR_HEIGHT = 40;
// Editor modes - can be either using the form or the code editor
enum EditorMode {
CodeEditor = 'editor',
JSonSchemaForm = 'form',
}
@Component({
selector: 'app-chart-values-editor',
templateUrl: './chart-values-editor.component.html',
styleUrls: ['./chart-values-editor.component.scss']
})
export class ChartValuesEditorComponent implements OnInit, OnDestroy, AfterViewInit {
@Input() set config(config: ChartValuesConfig) {
if (!!config) {
this.schemaUrl = config.schemaUrl;
this.valuesUrl = config.valuesUrl;
this.releaseValues = config.releaseValues;
this.init();
}
}
schemaUrl: string;
valuesUrl: string;
releaseValues: string;
// Model for the editor - we set this once when the YAML support has been loaded
public model;
// Editor mode - either 'editor' for the Monaco Code Editor or 'form' for the JSON Schema Form editor
public mode: EditorMode = EditorMode.CodeEditor;
// Content shown in the code editor
public code = '';
// JSON Schema
public schema: any;
public hasSchema = false;
// Data shown in the form on load
public initialFormData = {};
// Data updated in the form as the user changes it
public formData = {};
// Is the YAML in the code editor invalid?
public yamlError = false;
// Monaco Code Editor settings
public minimap = true;
public lineNumbers = true;
// Chart Values - as both raw text (keeping comments) and parsed JSON
public chartValuesYaml: string;
public chartValues: any;
// Default Monaco options
public editorOptions = {
automaticLayout: false, // We will resize the editor to fit the available space
contextmenu: false, // Turn off the right-click context menu
tabSize: 2,
};
// Monaco editor
public editor: any;
// Observable - are we still loading resources?
public loading$: Observable<boolean>;
public initing = true;
// Observable for tracking if the Monaco editor has loaded
private monacoLoaded$ = new BehaviorSubject<boolean>(false);
private resizeSub: Subscription;
private themeSub: Subscription;
// Track whether the user changes the code in the text editor
private codeOnEnter: string;
// Reference to the editor, so we can adjust its size to fit
@ViewChild('monacoEditor', { read: ElementRef }) monacoEditor: ElementRef;
@ViewChild('schemaForm') schemaForm: JsonSchemaFormComponent;
// Confirmation dialog - copy values
overwriteValuesConfirmation = new ConfirmationDialogConfig(
'Overwrite Values?',
'Are you sure you want to replace your values with those from values.yaml?',
'Overwrite'
);
// Confirmation dialog - copy release values
overwriteReleaseValuesConfirmation = new ConfirmationDialogConfig(
'Overwrite Values?',
'Are you sure you want to replace your values with those from the release?',
'Overwrite'
);
// Confirmation dialog - diff values
overwriteDiffValuesConfirmation = new ConfirmationDialogConfig(
'Overwrite Values?',
'Are you sure you want to replace your values with the diff with values.yaml?',
'Overwrite'
);
// Confirmation dialog - clear values
clearValuesConfirmation = new ConfirmationDialogConfig(
'Clear Values?',
'Are you sure you want to clear the form values?',
'Overwrite'
);
constructor(
private elRef: ElementRef,
private renderer: Renderer2,
private httpClient: HttpClient,
private themeService: ThemeService,
private confirmDialog: ConfirmationDialogService,
) { }
ngOnInit(): void {
// Listen for window resize and resize the editor when this happens
this.resizeSub = fromEvent(window, 'resize').pipe(debounceTime(150)).subscribe(event => this.resize());
}
private init() {
// Observabled for loading schema and values for the Chart
const schema$ = this.httpClient.get(this.schemaUrl).pipe(catchError(e => of(null)));
const values$: Observable<string> = this.httpClient.get(this.valuesUrl, { responseType: 'text' }).pipe(
catchError(e => of(null))
);
// We need the schame, value sand the monaco editor to be all loaded before we're ready
this.loading$ = combineLatest(schema$, values$, this.monacoLoaded$).pipe(
filter(([schema, values, loaded]) => schema !== undefined && values !== undefined && loaded),
tap(([schema, values, loaded]) => {
this.schema = schema;
if (values !== null) {
this.chartValuesYaml = values;
this.chartValues = yaml.safeLoad(values, { json: true });
// Set the form to the chart values initially, so if the user does nothing, they get the defaults
this.initialFormData = this.chartValues;
}
// Default to form if there is a schema
if (schema !== null) {
this.hasSchema = true;
this.mode = EditorMode.JSonSchemaForm;
// Register schema with the Monaco editor
this.registerSchema(this.schema);
} else {
// No Schema, so register an auto-generated schema from the Chart's values
this.registerSchema(generateJsonSchemaFromObject('Generated Schema', this.chartValues));
// Inherit the previous values if available (upgrade)
if (this.releaseValues) {
this.code = yaml.safeDump(this.releaseValues);
}
}
this.updateModel();
}),
map(([schema, values, loaded]) => !loaded),
startWith(true)
);
this.initing = false;
}
ngAfterViewInit(): void {
this.resizeEditor();
}
ngOnDestroy(): void {
if (this.resizeSub) {
this.resizeSub.unsubscribe();
}
if (this.themeSub) {
this.themeSub.unsubscribe();
}
}
// Toggle editor minimap on/off
toggleMinimap() {
this.minimap = !this.minimap;
this.editor.updateOptions({ minimap: { enabled: this.minimap } });
}
// Toggle editor line numbers on/off
toggleLineNumbers() {
this.lineNumbers = !this.lineNumbers;
this.editor.updateOptions({ lineNumbers: this.lineNumbers ? 'on' : 'off' });
}
// Store the update form data when the form changes
// AJSF two-way binding seems to cause issues
formChanged(data: any) {
this.formData = data;
}
// The edit mode has changed (form or editor)
editModeChanged(mode) {
this.mode = mode.value;
if (this.mode === EditorMode.CodeEditor) {
// Form -> Editor
// Only copy if there is not an error - otherwise keep the invalid yaml from the editor that needs fixing
if (!this.yamlError) {
const codeYaml = yaml.safeLoad(this.code || '{}', { json: true });
const data = mergeObjects(codeYaml, this.formData);
this.code = this.getDiff(data);
this.codeOnEnter = this.code;
}
// Need to resize the editor, as it will be freshly shown
this.resizeEditor();
} else {
// Editor -> Form
// Try and parse the YAML - if we can't this is an error, so we can't edit this back in the form
try {
if (this.codeOnEnter === this.code) {
// Code did not change
return;
}
// Parse as json
const json = yaml.safeLoad(this.code || '{}', { json: true });
// Must be an object, otherwise it was not valid
if (typeof (json) !== 'object') {
throw new Error('Invalid YAML');
}
this.yamlError = false;
const data = mergeObjects(this.formData, json);
this.initialFormData = data;
this.formData = data;
} catch (e) {
// The yaml in the code editor is invalid, so we can't marshal it back to json for the from editor
this.yamlError = true;
}
}
}
// Called once the Monaco editor has loaded and then each time the model is update
// Store a reference to the editor and ensure the editor theme is synchronized with the Stratos theme
onMonacoInit(editor) {
this.editor = editor;
this.resize();
// Only load the YAML support once - when we set the model, onMonacoInit will et
if (this.model) {
return;
}
// Load the YAML Language support - require is available as it will have been loaded by the Monaco vs loader
const req = (window as any).require;
req(['vs/language/yaml/monaco.contribution'], () => {
// Set the model now that YAML support is loaded - this will update the editor correctly
this.updateModel();
this.monacoLoaded$.next(true);
});
// Watch for theme changes - set light/dark theme in the monaco editor as the Stratos theme changes
this.themeSub = this.themeService.getTheme().subscribe(theme => {
const monaco = (window as any).monaco;
const monacoTheme = (theme.styleName === 'dark-theme') ? 'vs-dark' : 'vs';
monaco.editor.setTheme(monacoTheme);
});
}
private updateModel() {
this.model = {
language: 'yaml',
uri: this.getSchemaUri()
};
}
// Delayed resize of editor to fit
resizeEditor() {
setTimeout(() => this.resize(), 1);
}
// Resize editor to fit
resize() {
// Return if resize before editor has been set
if (!this.editor) {
return;
}
// Get width and height of the host element
const w = this.elRef.nativeElement.offsetWidth;
let h = this.elRef.nativeElement.offsetHeight;
// Check if host element not visible (does not have a size)
if ((w === 0) && (h === 0)) {
return;
}
// Remove height of toolbar (since this is incluced in the height of the host element)
h = h - TOOLBAR_HEIGHT;
// Set the Monaco editor to the same size as the container
this.renderer.setStyle(this.monacoEditor.nativeElement, 'width', `${w}px`);
this.renderer.setStyle(this.monacoEditor.nativeElement, 'height', `${h}px`);
// Ask Monaco to layout again with its new size
this.editor.layout();
}
// Get an absolute URI for the Schema - it is not fetched, just used as a reference
// schemaUrl is a relative URL - e.g. /p1/v1/chartsvc....
getSchemaUri(): string {
return `https://stratos.app/schemas${this.schemaUrl}`;
}
// Register the schema with the Monaco editor
// Reference: https://github.com/pengx17/monaco-yaml/blob/master/examples/umd/index.html#L69
registerSchema(schema: any) {
const monaco = (window as any).monaco;
monaco.languages.yaml.yamlDefaults.setDiagnosticsOptions({
enableSchemaRequest: true,
hover: true,
completion: true,
validate: true,
format: true,
schemas: [
{
uri: this.getSchemaUri(),
fileMatch: [this.getSchemaUri()],
schema
}
]
});
}
public getValues(): object {
// Always diff the form with the Chart Values to get only the changes that the user has made
return (this.mode === EditorMode.JSonSchemaForm) ? diffObjects(this.formData, this.chartValues) : yaml.safeLoad(this.code);
}
public copyValues() {
const confirm = this.mode === EditorMode.JSonSchemaForm || this.mode === EditorMode.CodeEditor && this.code.length > 0;
if (confirm) {
this.confirmDialog.open(this.overwriteValuesConfirmation, () => {
this.doCopyValues();
});
} else {
this.doCopyValues();
}
}
// Copy the chart values into either the form or the code editor, depending on the current mode
private doCopyValues() {
if (this.mode === EditorMode.JSonSchemaForm) {
this.initialFormData = this.chartValues;
} else {
// Use the raw Yaml, so we keep comments and formatting
this.code = this.chartValuesYaml;
}
}
public copyReleaseValues() {
const confirm = this.mode === EditorMode.JSonSchemaForm || this.mode === EditorMode.CodeEditor && this.code.length > 0;
if (confirm) {
this.confirmDialog.open(this.overwriteReleaseValuesConfirmation, () => {
this.doCopyReleaseValues();
});
} else {
this.doCopyReleaseValues();
}
}
// Copy the release values into either the form or the code editor, depending on the current mode
private doCopyReleaseValues() {
if (this.mode === EditorMode.JSonSchemaForm) {
this.initialFormData = this.releaseValues;
} else {
this.code = yaml.safeDump(this.releaseValues);
}
}
// Reset the form values and the code
clearFormValues() {
this.confirmDialog.open(this.clearValuesConfirmation, () => {
this.initialFormData = {};
this.code = '';
this.codeOnEnter = '';
});
}
// Update the code editor to only show the YAML that contains the differences with the values.yaml
diff() {
this.confirmDialog.open(this.overwriteDiffValuesConfirmation, () => {
const userValues = yaml.safeLoad(this.code, { json: true });
this.code = this.getDiff(userValues);
});
}
getDiff(userValues: any): string {
let code = yaml.safeDump(diffObjects(userValues, this.chartValues));
if (code.trim() === '{}') {
code = '';
}
return code;
}
} | the_stack |
import { createLocalVue, shallowMount, Wrapper } from '@vue/test-utils';
import Vue from 'vue';
import Vuex from 'vuex';
import ListUniqueValues from '@/components/ListUniqueValues.vue';
import { VQBnamespace } from '@/store/';
import { setupMockStore } from './utils';
const localVue = createLocalVue();
localVue.use(Vuex);
describe('List Unique Value', () => {
let wrapper: Wrapper<Vue>;
/**
`shallowMountWrapper` is utility function for the `ListUniqueValues` component
It shallow mount the component with several options:
@param filterValue the value key of the prop `filter`
@param operator the operator key of the prop `filter`
@param loaded the `loaded` props of the component
@param isUniqueValuesLoading the store parameter indicating if column unique value is loading
By default the wrapper is mounted with 4 options: "France", "Framboise", "Spain" and "UK"
- The checked values are "France" and "Spain"
- All uniques are loaded
*/
const shallowMountWrapper = (
filterValue: string[] = ['France', 'Spain'],
operator: 'in' | 'nin' = 'in',
loaded = true,
isUniqueValuesLoading = false,
): Wrapper<Vue> => {
return shallowMount(ListUniqueValues, {
store: setupMockStore({
dataset: {
headers: [{ name: 'col1' }],
data: [],
},
isLoading: {
dataset: false,
uniqueValues: isUniqueValuesLoading,
},
}),
localVue,
propsData: {
filter: {
column: 'col1',
operator,
value: filterValue,
},
options: [
{ value: 'France', count: 10 },
{ value: 'Framboise', count: 9 },
{ value: 'UK', count: 4 },
{ value: 'Spain', count: 2 },
],
loaded,
},
});
};
beforeEach(() => {
wrapper = shallowMountWrapper();
});
it('should display the list of unique values and how much time they are present in the whole dataset', () => {
expect(wrapper.exists()).toBeTruthy();
const CheckboxWidgetArray = wrapper.findAll('CheckboxWidget-stub');
expect(CheckboxWidgetArray.length).toEqual(4);
expect(CheckboxWidgetArray.at(0).vm.$props.label).toEqual('France');
expect(CheckboxWidgetArray.at(0).vm.$props.info).toEqual('(10)');
expect(CheckboxWidgetArray.at(1).vm.$props.label).toEqual('Framboise');
expect(CheckboxWidgetArray.at(1).vm.$props.info).toEqual('(9)');
expect(CheckboxWidgetArray.at(2).vm.$props.label).toEqual('UK');
expect(CheckboxWidgetArray.at(2).vm.$props.info).toEqual('(4)');
expect(CheckboxWidgetArray.at(3).vm.$props.label).toEqual('Spain');
expect(CheckboxWidgetArray.at(3).vm.$props.info).toEqual('(2)');
});
it('should instantiate with correct value checked', () => {
const CheckboxWidgetArray = wrapper.findAll('CheckboxWidget-stub');
expect(CheckboxWidgetArray.at(0).vm.$props.value).toBeTruthy();
expect(CheckboxWidgetArray.at(1).vm.$props.value).toBeFalsy();
expect(CheckboxWidgetArray.at(2).vm.$props.value).toBeFalsy();
expect(CheckboxWidgetArray.at(3).vm.$props.value).toBeTruthy();
});
it('should display the list of unique values and how much time they are present in the whole dataset (with "nin" operator)', () => {
wrapper = shallowMountWrapper(['France', 'Spain'], 'nin');
expect(wrapper.exists()).toBeTruthy();
const CheckboxWidgetArray = wrapper.findAll('CheckboxWidget-stub');
expect(CheckboxWidgetArray.length).toEqual(4);
expect(CheckboxWidgetArray.at(0).vm.$props.label).toEqual('France');
expect(CheckboxWidgetArray.at(0).vm.$props.info).toEqual('(10)');
expect(CheckboxWidgetArray.at(1).vm.$props.label).toEqual('Framboise');
expect(CheckboxWidgetArray.at(1).vm.$props.info).toEqual('(9)');
expect(CheckboxWidgetArray.at(2).vm.$props.label).toEqual('UK');
expect(CheckboxWidgetArray.at(2).vm.$props.info).toEqual('(4)');
expect(CheckboxWidgetArray.at(3).vm.$props.label).toEqual('Spain');
expect(CheckboxWidgetArray.at(3).vm.$props.info).toEqual('(2)');
});
it('should instantiate with correct value checked (with "nin" operator)', () => {
wrapper = shallowMountWrapper(['Framboise', 'UK'], 'nin');
const CheckboxWidgetArray = wrapper.findAll('CheckboxWidget-stub');
expect(CheckboxWidgetArray.at(0).vm.$props.value).toBeTruthy();
expect(CheckboxWidgetArray.at(1).vm.$props.value).toBeFalsy();
expect(CheckboxWidgetArray.at(2).vm.$props.value).toBeFalsy();
expect(CheckboxWidgetArray.at(3).vm.$props.value).toBeTruthy();
});
it('should instantiate without the spinner', async () => {
expect(wrapper.find('.list-unique-values__loader-spinner').exists()).toBeFalsy();
});
it('should instantiate with the spinner', async () => {
wrapper = shallowMountWrapper(['France', 'Spain'], 'in', true, true);
expect(wrapper.find('.list-unique-values__loader-spinner').exists()).toBeTruthy();
});
describe('"load all values" message', () => {
it('should instantiate with the "load all values" message', () => {
expect(wrapper.find('.list-unique-values__load-all-values').exists()).toBeFalsy();
});
it('should dispatch when click on "load all values"', async () => {
wrapper = shallowMountWrapper(['France', 'Spain'], 'in', false);
const dispatchSpy = jest.spyOn(wrapper.vm.$store, 'dispatch');
await wrapper.find('.list-unique-values__load-all-values-button').trigger('click');
expect(dispatchSpy).toHaveBeenCalledTimes(1);
expect(dispatchSpy).toHaveBeenCalledWith(VQBnamespace('loadColumnUniqueValues'), {
column: 'col1',
});
});
it('should not instantiate with the "load all values" message', () => {
wrapper = shallowMountWrapper(['France', 'Spain'], 'in', false);
expect(wrapper.find('.list-unique-values__load-all-values').exists()).toBeTruthy();
});
});
describe('click on one checkbox', () => {
it('should emit new value', () => {
wrapper
.findAll('CheckboxWidget-stub')
.at(0)
.vm.$emit('input'); // unselecting "France" value
expect(wrapper.emitted().input[0][0]).toEqual({
column: 'col1',
operator: 'in',
value: ['Spain'],
});
});
it('should emit new value', () => {
wrapper
.findAll('CheckboxWidget-stub')
.at(1)
.vm.$emit('input'); // unselecting "Framboise" value
expect(wrapper.emitted().input[0][0]).toEqual({
column: 'col1',
operator: 'in',
value: ['France', 'Spain', 'Framboise'],
});
});
});
describe('click on "Clear all" button', () => {
it('should emit input on click clear all button', async () => {
await wrapper.find('.list-unique-values__clear-all').trigger('click');
expect(wrapper.emitted().input[0][0]).toEqual({
column: 'col1',
operator: 'in',
value: [],
});
});
});
describe('click on "Select all" button', () => {
it('should emit input on click select all button', async () => {
await wrapper.find('.list-unique-values__select-all').trigger('click');
expect(wrapper.emitted().input[0][0]).toEqual({
column: 'col1',
operator: 'nin',
value: [],
});
});
});
describe('search box', () => {
describe('with "in" operator', () => {
beforeEach(async () => {
const input = wrapper.find('.list-unique-values__search-box').element as HTMLInputElement;
input.value = 'Fr'; // "Fr" like the start of "France" and "Framboise"
await wrapper.find('.list-unique-values__search-box').trigger('input');
});
it('should filter the unique value when search on the searchbox', async () => {
const CheckboxWidgetArray = wrapper.findAll('CheckboxWidget-stub');
expect(CheckboxWidgetArray.length).toEqual(2);
expect(CheckboxWidgetArray.at(0).vm.$props.label).toEqual('France');
expect(CheckboxWidgetArray.at(0).vm.$props.info).toEqual('(10)');
expect(CheckboxWidgetArray.at(1).vm.$props.label).toEqual('Framboise');
expect(CheckboxWidgetArray.at(1).vm.$props.info).toEqual('(9)');
});
it('should emit new value when click "select all" button (with "in" operator)', async () => {
await wrapper.find('.list-unique-values__select-all').trigger('click');
// "France" and "Framboise" only should be updated:
expect(wrapper.emitted().input[0][0]).toEqual({
column: 'col1',
operator: 'in',
value: ['France', 'Spain', 'Framboise'],
});
});
it('should emit new value when click "clear all" button (with "in" operator)', async () => {
await wrapper.find('.list-unique-values__clear-all').trigger('click');
// "France" and "Framboise" only should be updated
expect(wrapper.emitted().input[0][0]).toEqual({
column: 'col1',
operator: 'in',
value: ['Spain'],
});
});
});
describe('with "nin" operator', () => {
beforeEach(async () => {
wrapper = shallowMountWrapper(['France', 'Spain'], 'nin');
const input = wrapper.find('.list-unique-values__search-box').element as HTMLInputElement;
input.value = 'Fr'; // "Fr" like the start of "France" and "Framboise"
await wrapper.find('.list-unique-values__search-box').trigger('input');
});
it('should filter the unique value when search on the searchbox', async () => {
const CheckboxWidgetArray = wrapper.findAll('CheckboxWidget-stub');
expect(CheckboxWidgetArray.length).toEqual(2);
expect(CheckboxWidgetArray.at(0).vm.$props.label).toEqual('France');
expect(CheckboxWidgetArray.at(0).vm.$props.info).toEqual('(10)');
expect(CheckboxWidgetArray.at(1).vm.$props.label).toEqual('Framboise');
expect(CheckboxWidgetArray.at(1).vm.$props.info).toEqual('(9)');
});
it('should emit new value when click "select all" button (with "nin" operator)', async () => {
await wrapper.find('.list-unique-values__select-all').trigger('click');
// "France" and "Framboise" only should be updated:
expect(wrapper.emitted().input[0][0]).toEqual({
column: 'col1',
operator: 'nin',
value: ['Spain'],
});
});
it('should emit new value when click "clear all" button (with "nin" operator)', async () => {
await wrapper.find('.list-unique-values__clear-all').trigger('click');
// "France" and "Framboise" only should be updated
expect(wrapper.emitted().input[0][0]).toEqual({
column: 'col1',
operator: 'nin',
value: ['France', 'Spain', 'Framboise'],
});
});
});
describe('with with object value', () => {
it('should filter the unique value when search on the searchbox', async () => {
wrapper = shallowMount(ListUniqueValues, {
store: setupMockStore({
dataset: {
headers: [{ name: 'col1' }],
data: [],
},
}),
localVue,
propsData: {
filter: {
column: 'col1',
operator: 'nin',
value: [],
},
options: [
{ value: { population: 10 }, count: 12 },
{ value: { population: 2 }, count: 9 },
{ value: { population: 3 }, count: 4 },
],
loaded: true,
},
});
let CheckboxWidgetArray = wrapper.findAll('CheckboxWidget-stub');
expect(CheckboxWidgetArray.length).toEqual(3);
expect(CheckboxWidgetArray.at(0).vm.$props.label).toEqual('{"population":10}');
expect(CheckboxWidgetArray.at(0).vm.$props.info).toEqual('(12)');
expect(CheckboxWidgetArray.at(1).vm.$props.label).toEqual('{"population":2}');
expect(CheckboxWidgetArray.at(1).vm.$props.info).toEqual('(9)');
expect(CheckboxWidgetArray.at(2).vm.$props.label).toEqual('{"population":3}');
expect(CheckboxWidgetArray.at(2).vm.$props.info).toEqual('(4)');
const input = wrapper.find('.list-unique-values__search-box').element as HTMLInputElement;
input.value = '2'; // "Fr" like the start of "France" and "Framboise"
await wrapper.find('.list-unique-values__search-box').trigger('input');
CheckboxWidgetArray = wrapper.findAll('CheckboxWidget-stub');
expect(CheckboxWidgetArray.length).toEqual(1);
expect(CheckboxWidgetArray.at(0).vm.$props.label).toEqual('{"population":2}');
expect(CheckboxWidgetArray.at(0).vm.$props.info).toEqual('(9)');
});
});
});
}); | the_stack |
import { PdfTreeGridCell } from './../export/pdf-base/pdf-grid-table';
import { PdfBorders } from './../export/pdf-base/pdf-borders';
import { ColumnModel } from './../models/column';
import { PointF, PdfColor, PdfFontFamily, PdfFontStyle, PdfStringFormat } from '@syncfusion/ej2-pdf-export';
import {
ContextMenuType, PdfPageSize, PageOrientation, ExportType, PdfTheme, TaskType
} from './enum';
import { ContextMenuOpenEventArgs as GridContextMenuOpenEventArgs } from '@syncfusion/ej2-grids';
import { ContextMenuClickEventArgs as GridContextMenuClickEventArgs } from '@syncfusion/ej2-grids';
import { RecordDoubleClickEventArgs as GridRecordDoubleClickEventArgs } from '@syncfusion/ej2-grids';
import { RowSelectingEventArgs as GridRowSelectingEventArgs } from '@syncfusion/ej2-grids';
import { CellSelectingEventArgs as GridCellSelectingEventArgs } from '@syncfusion/ej2-grids';
import { RowDeselectEventArgs as GridRowDeselectEventArgs } from '@syncfusion/ej2-grids';
import { RowSelectEventArgs as GridRowSelectEventArgs, RowDataBoundEventArgs as GridRowDataBoundEventArgs } from '@syncfusion/ej2-grids';
import { Column } from '../models/column';
import { TooltipEventArgs } from '@syncfusion/ej2-popups';
import { TimelineViewMode } from '../base/enum';
import { TimelineTierSettingsModel } from '../models/timeline-settings-model';
import { EventMarkerModel } from '../models/event-marker-model';
import { PdfPaddings } from '../export/pdf-base/index';
/**
* Specifies Gantt-chart interfaces
*
*/
export interface IGanttData {
/** Defines the child records of task. */
childRecords?: IGanttData[];
/** Defines the expanded state of task. */
expanded?: boolean;
/** Defines the properties which used in internal calculations. */
ganttProperties?: ITaskData;
/** Defines gantt data has child records or not. */
hasChildRecords?: boolean;
/** Defines the index of task. */
index?: number;
/** Defines the level of task. */
level?: number;
/** Defines the direct parent item of task. */
parentItem?: IParent;
/** Defines the parent unique id of task. */
parentUniqueID?: string;
/** Defines the data which specified in data source.
*
* @isGenericType true
*/
taskData?: Object;
/** Defines the unique id of task. */
uniqueID?: string;
/** Defines the indicators value of task. */
indicators?: IIndicator[];
/** Defines the delete . */
isDelete?: boolean;
}
export interface IParent {
/** Defines the unique id of task. */
uniqueID?: string;
/** Defines the expanded state of task. */
expanded?: boolean;
/** Defines the level of task. */
level?: number;
/** Defines the id of task. */
taskId?: string;
/** Defines the index of task. */
index?: number;
}
export interface ITaskData {
/** Defines the baselineleft of task. */
baselineLeft?: number;
/** Defines the baseline startdate of task. */
baselineStartDate?: Date;
/** Defines the baseline enddate of task. */
baselineEndDate?: Date;
/** Defines the baseline width of task. */
baselineWidth?: number;
/** Defines the end date of task. */
endDate?: Date;
/** Defines the css class of task. */
cssClass?: string;
/** Defines the duration of task. */
duration?: number;
/** Defines the duration unit of task. */
durationUnit?: string;
/** Defines the task is auto schedule-able or not. */
isAutoSchedule?: boolean;
/** Defines the task is milestone or not. */
isMilestone?: boolean;
/** Defines the left of task. */
left?: number;
/** Defines the progress of task. */
progress?: number;
/** Defines the progress width of task. */
progressWidth?: number;
/** Defines the resource info of task. */
resourceInfo?: Object[];
/** Defines the resource names of task. */
resourceNames?: string;
/** Defines the start date of task. */
startDate?: Date;
/** Defines the notes of task. */
notes?: string;
/** Defines the predecessors name of task. */
predecessorsName?: string | number | object[];
/** Defines the predecessor of task. */
predecessor?: IPredecessor[];
/** Defines the id of task. */
taskId?: string;
/** Defines the parent id of task. */
parentId?: string;
/** Defines the name of task. */
taskName?: string;
/** Defines the width of task. */
width?: number;
/** Defines the indicators of task. */
indicators?: IIndicator[];
/** Defines the unique id of task. */
uniqueID?: string;
/** Defines the total progress of task. */
totalProgress?: number;
/** Defines the total duration of task. */
totalDuration?: number;
/** Defines the work of the task. */
work?: number;
/** Defines the work unit of task. */
workUnit?: string;
/** Defines task type */
taskType?: TaskType;
/** Defines the auto scheduled task's start date. */
autoStartDate?: Date;
/** Defines the auto scheduled task's end date. */
autoEndDate?: Date;
/** Defines the auto scheduled task's duration */
autoDuration?: number;
/** Defines the auto scheduled task's left. */
autoLeft?: number;
/** Defines the auto scheduled task's width. */
autoWidth?: number;
/** It have taskId for ProjectView and uniqueID for resourceView */
rowUniqueID?: string;
/** Defines work timeline ranges. */
workTimelineRanges?: IWorkTimelineRanges[];
/** Defines overlap index. */
eOverlapIndex?: number;
/** Defines task segments. */
segments?: ITaskSegment[];
/**
* Defines shared task unique ids.
*/
sharedTaskUniqueIds?: string[];
}
export interface ITaskSegment {
/** Defines start date of the segment */
startDate?: Date;
/** Defines end date of the segment */
endDate?: Date;
/** Defines the duration of the segment. */
duration?: number;
/** Defines the width of a segment. */
width?: number;
/** Defines the progress width of a segment. */
progressWidth?: number;
/** Defines the left position of a segment. */
left?: number;
/** Defines the segment index */
segmentIndex?: number;
/** Defines the duration between 2 segments */
offsetDuration?: number;
/** Set for displaying progress in split taskbar */
showProgress?: boolean;
}
export interface IWorkTimelineRanges {
/** Defines start date of task */
startDate?: Date;
/** Defines end date of task */
endDate?: Date;
/** Defines left value of resource usage/resource histogram. */
left?: number;
/** Defines width of the resource usage/resource histogram. */
width?: number;
/** Defines height of the resource usage/resource histogram. */
height?: number;
/** Defines per day work. */
workPerDay?: number;
/** Defines whether resource is over allocate or not. */
isOverAllocated?: boolean;
/** Defines the task. */
task?: IGanttData;
/** Defines start date of task */
from?: Date;
/** Defines start date of task */
to?: Date;
}
export interface IGanttColumn {
field?: string;
headerText?: string;
editType?: string;
mappingName?: string;
allowEditing: boolean;
width: number;
format: string;
visible: boolean;
}
export interface IIndicator {
/** Defines the date of indicator. */
date?: Date | string;
/** Defines the icon class of indicator. */
iconClass?: string;
/** Defines the name of indicator. */
name?: string;
/** Defines the tooltip of indicator. */
tooltip?: string;
}
export interface IWorkingTimeRange {
from?: number;
to?: number;
isWorking?: boolean;
color?: string;
interval?: number;
}
export interface IQueryTaskbarInfoEventArgs {
/** Defines the data. */
data: IGanttData;
/** Defines the row element. */
rowElement: Element;
/** Defines the taskbar element. */
taskbarElement: Element;
/** Defines the taskbar background color. */
taskbarBgColor?: string;
/** Defines the taskbar border color. */
taskbarBorderColor?: string;
/** Defines the progressbar background color. */
progressBarBgColor?: string;
/** Defines the milestone color. */
//progressBarBorderColor?: string;
milestoneColor?: string;
/** Defines the right label color. */
rightLabelColor?: string;
/** Defines the left label color. */
leftLabelColor?: string;
/** Defines the task label color. */
taskLabelColor?: string;
/** Defines the baseline color. */
baselineColor?: string;
/** Defines the taskbar type. */
taskbarType: string;
}
export interface IGanttCellFormatter {
/** Method to format the cell value of date columns. */
getValue(column: Column, data: Object): Object;
}
export interface ITaskbarEditedEventArgs {
/** Defines the editingFields. */
editingFields?: ITaskData;
/** Defines the data. */
data?: IGanttData;
/** Defines the index of edited task. */
recordIndex?: number;
/** Defines the previous value of editing task. */
previousData?: ITaskData;
/** Defines the type of taskbar edit action. */
taskBarEditAction?: string;
/** Defines the duration roundoff. */
roundOffDuration?: boolean;
/** Defines the event is cancel-able or not. */
cancel?: boolean;
/** Defines the action. */
action?: string;
/** Defines the target element. */
target?: Element;
/** Defines the segment index. */
segmentIndex?: number;
}
export interface IKeyPressedEventArgs {
/** Defines the request type. */
requestType?: string;
/** Defines the key action. */
action?: string;
/** Defines the event. */
keyEvent?: Event;
}
export interface ITaskDeletedEventArgs {
deletedRecordCollection?: IGanttData[];
updatedRecordCollection?: IGanttData[];
cancel?: boolean;
action?: string;
}
export interface IDependencyEditData {
id?: string;
text?: string;
value?: string;
}
export interface IPredecessor {
/** Defines the from value of predecessor. */
from?: string;
/** Defines the to value of predecessor. */
to?: string;
/** Defines the type of predecessor. */
type?: string;
/** Defines the offset value of predecessor. */
offset?: number;
/** Defines the offset unit of predecessor. */
offsetUnit?: string;
/** Defines the predecessor is drawn-able or not. */
isDrawn?: boolean;
}
export interface IValidateArgs {
data?: IGanttData;
recordIndex?: number;
requestType?: string;
cancel?: boolean;
validateMode?: IValidateMode;
editEventArgs?: object;
}
export interface ITimeSpanEventArgs {
/** Defines the project start date. */
projectStartDate?: Date;
/** Defines the project end date. */
ProjectEndDate?: Date;
/** Defines the timeline roundoff state. */
isTimelineRoundOff?: boolean;
/** Defines the request type. */
requestType?: string;
/** Defines the event is cancel-able or not. */
cancel?: boolean;
/** Defines the action. */
action?: string;
}
export interface IValidateMode {
respectLink?: boolean;
removeLink?: boolean;
preserveLinkWithEditing?: boolean;
}
export interface IActionBeginEventArgs {
requestType?: string;
data?: IGanttData | IGanttData[];
modifiedRecords?: IGanttData[];
modifiedTaskData?: object[] | object;
cancel?: boolean;
taskBarEditAction?: string;
action?: string;
/** Defines the target element. */
target?: Element;
}
export interface IValidateLinkedTaskArgs {
editMode?: string;
data?: IGanttData;
requestType?: string;
validateMode?: IValidateMode;
cancel?: boolean;
}
export interface IConnectorLineObject {
parentLeft?: number;
childLeft?: number;
parentWidth?: number;
childWidth?: number;
parentIndex?: number;
childIndex?: number;
rowHeight?: number;
type?: string;
connectorLineId?: string;
milestoneParent?: boolean;
milestoneChild?: boolean;
parentIndexInCurrentView?: number;
childIndexInCurrentView?: number;
}
export interface ISplitterResizedEventArgs {
/** Defines the element. */
element?: HTMLElement;
/** Defines the event. */
event?: Event;
/** Defines the size of resized pane. */
paneSize?: number[];
/** Defines the pane. */
pane?: HTMLElement[];
/** Defines the index of resizing pane. */
index?: number[];
/** Defines the separator. */
separator?: HTMLElement;
/** Defines the event is cancel-able or not. */
cancel?: boolean;
}
export interface PredecessorTooltip {
/** Defines the from id of predecessor. */
fromId?: string;
/** Defines the to id of predecessor. */
toId?: string;
/** Defines the from name of predecessor. */
fromName?: string;
/** Defines the to name of predecessor. */
toName?: string;
/** Defines the link type of predecessor. */
linkType?: string;
/** Defines the link text of predecessor. */
linkText?: string;
/** Defines the offset value of predecessor. */
offset?: number;
/** Defines the offset unit of predecessor. */
offsetUnit?: string;
/** Defines the offset string value of predecessor. */
offsetString?: string;
}
export interface BeforeTooltipRenderEventArgs {
/** Defines the data. */
data?: BeforeTooltipRenderEventArgsData;
/** Defines the original event arguments of tooltip control. */
args?: TooltipEventArgs;
/** Defines the content. */
content?: string | Element;
/** Cancel the tooltip */
cancel?: boolean;
}
export interface QueryCellInfoEventArgs {
/** Defines the row data associated with this cell. */
data?: IGanttData;
/** Defines the cell element. */
cell?: Element;
/** Defines the column object associated with this cell. */
column?: Column;
/** Defines the no. of columns to be spanned */
colSpan?: number;
/** Defines the no. of rows to be spanned */
rowSpan?: number;
/** Defines the current action. */
requestType?: string;
/** Define the foreignKey row data associated with this column */
foreignKeyData?: Object;
}
/**
* Extending IGanttData and PredecessorTooltip interfaces for data used in BeforeTooltipRenderEventArgs interface.
*/
export interface BeforeTooltipRenderEventArgsData extends IGanttData, PredecessorTooltip {
}
export interface IDependencyEventArgs {
/** Specifies the predecessor task of dependency. */
fromItem?: IGanttData;
/** Specifies the successor task of dependency. */
toItem?: IGanttData;
/** Defines the new predecessor string. */
newPredecessorString?: string;
/** Defines the dependency link is valid or not */
isValidLink?: boolean;
/** Defines the request type. */
requestType?: string;
/** Defines predecessor object */
predecessor?: IPredecessor;
}
export interface ITaskAddedEventArgs {
/** Specifies the newly added task data with Gantt properties. */
data?: IGanttData[] | IGanttData;
/** Specifies the newly added task data without custom Gantt properties. */
newTaskData?: object[] | object;
/** Defines the modified records. */
modifiedRecords?: IGanttData[];
/** Defines the modified task data. */
modifiedTaskData?: object[] | object;
/** Defines the record index. */
recordIndex?: number | number[];
/** Defines the event is cancel-able or not. */
cancel?: boolean;
/** Defines the action. */
action?: string;
/** Defines the request type. */
requestType?: string;
}
export interface ICollapsingEventArgs {
/** Defines the TreeGrid row element */
gridRow: Node;
/** Defines the Gantt chart row element */
chartRow: Node;
/** Defines the name of the action. */
name?: string;
/** Defines the parent row data. */
data?: IGanttData;
/** Cancel the row expanding action */
cancel?: boolean;
}
export interface ContextMenuOpenEventArgs extends GridContextMenuOpenEventArgs {
/** Defines the TreeGrid row element */
gridRow?: Element;
/** Defines the chart row element */
chartRow?: Element;
/** Defines the selected row record */
rowData?: IGanttData;
/** Defines the context menu type */
type?: ContextMenuType;
/** Defines the hidden items collection */
hideItems?: string[];
/** Defines the sub menu hidden items collection */
hideChildItems?: string[];
/** Defines the disabled items collection */
disableItems?: string[];
/** Defines the target element. */
target?: Element;
top?: number;
left?: number;
}
export interface ContextMenuClickEventArgs extends GridContextMenuClickEventArgs {
/** Defines the selected row record */
rowData?: IGanttData;
/** Defines the context menu type */
type?: ContextMenuType;
}
export type ITimelineFormatter = (date?: Date, format?: string, tier?: string, mode?: string) => string;
export interface ZoomEventArgs {
/** Defines the request type. */
requestType?: string;
/** Defines the zoom action. */
action?: string;
/** Defines Zoom timeline settings. */
timeline?: ZoomTimelineSettings;
/** Defines the cancel option value. */
cancel?: boolean;
}
export interface ZoomTimelineSettings {
/** Defines the timeline view mode. */
timelineViewMode?: TimelineViewMode;
/** Defines top tier values. */
topTier?: TimelineTierSettingsModel;
/** Defines bottom tier values. */
bottomTier?: TimelineTierSettingsModel;
/** Defines timeline unit size. */
timelineUnitSize?: number;
weekStartDay?: number;
/** Defines weekend background color. */
weekendBackground?: string;
/** Defines showTooltip whether the tooltip will rendered or not. */
showTooltip?: boolean;
/** Defines perDay width. */
perDayWidth?: number;
/** Defines zooming level. */
level?: number;
/** Defines the updateTimescaleView. */
updateTimescaleView?: boolean;
}
/** @private */
export interface MousePoint {
pageX?: number;
pageY?: number;
}
/** @private */
export interface ITemplateData {
expanded?: boolean;
hasChildRecords?: boolean;
index?: number;
level?: number;
baselineLeft?: number;
baselineWidth?: number;
taskStartDate?: Date;
taskEndDate?: Date;
taskDuration?: number;
taskDurationUnit?: string;
taskPredecessorsName?: string;
taskResourceNames?: string;
isAutoSchedule?: boolean;
isMilestone?: boolean;
left?: number;
progressWidth?: number;
width?: number;
}
export interface RowSelectingEventArgs extends GridRowSelectingEventArgs {
/** Defines the data collections. */
data: IGanttData;
}
export interface RowSelectEventArgs extends GridRowSelectEventArgs {
/** Defines the data collections. */
data: IGanttData;
}
export interface RowDataBoundEventArgs extends GridRowDataBoundEventArgs {
/** Defines the data collections. */
data: IGanttData;
/** Defines the row element. */
row?: Element;
}
export interface RowDeselectEventArgs extends GridRowDeselectEventArgs {
/** Defines the selected/deselected row index. */
rowIndex?: number;
/** Defines the data collections. */
data?: IGanttData[];
/** Defines the selected/deselected row. */
row?: Element;
}
export interface ActionCompleteArgs extends ZoomEventArgs, IKeyPressedEventArgs {
element?: HTMLElement;
requestType?: string;
data?: IGanttData[];
modifiedRecords?: IGanttData[];
modifiedTaskData?: IGanttData[];
cancel?: boolean;
/** Specifies the newly added task data without custom Gantt properties.
*
* @isGenericType true
*/
newTaskData?: object;
/** Defines the record index. */
recordIndex?: number;
/** Defines the action. */
action?: string;
/** Defines the type of event. */
type?: string;
}
export interface ActionBeginArgs extends IDependencyEventArgs {
rowData?: IGanttData;
name?: string;
requestType?: string;
cancel?: boolean;
data?: IGanttData[];
modifiedRecords?: IGanttData[];
/**
* @isGenericType true
*/
modifiedTaskData?: object[];
/** Specifies the newly added task data without custom Gantt properties.
*
* @isGenericType true
*/
newTaskData?: object;
/** Defines the split date on context click action */
splitDate?: Date;
/** Defines the array of merge items indexes on context click action */
mergeSegmentIndexes?: {firstSegmentIndex: number, secondSegmentIndex: number}[];
/** Defines the record index. */
recordIndex?: number;
/** Defines the action. */
action?: string;
/** Defines the type of event. */
type?: string;
/** Defines the target element. */
target?: Element;
}
export interface CellEditArgs {
/** Defines the cancel option value. */
cancel?: boolean;
/** Defines the current row. */
row?: Element;
/** Defines the validation rules. */
validationRules?: Object;
/** Defines the name of the event. */
type?: string;
/** Defines foreign data object */
foreignKeyData?: Object;
/** Defines the row data object. */
rowData?: IGanttData;
/** Defines the column name. */
columnName?: string;
/** Defines the cell object. */
cell?: Element;
/** Defines the column object. */
columnObject?: Column;
/** Defines the cell value. */
value?: string;
/** Defines isForeignKey option value. */
isForeignKey?: boolean;
/** Defines the primaryKey. */
primaryKey?: string[];
}
export interface CellSelectingEventArgs extends GridCellSelectingEventArgs {
/** Defines the previously selected cell index */
previousRowCellIndex?: number;
}
export interface ScrollArgs {
/** Defines the action. */
action?: string;
/** Defines the action type. */
requestType?: string;
/** Defines the scroll direction. */
scrollDirection?: string;
/** Defines the scroll left value. */
scrollLeft?: number;
/** Defines the scroll top value. */
scrollTop?: number;
/** Defines the previous scroll top value. */
previousScrollTop?: number;
/** Defines the previous scroll left value. */
previousScrollLeft?: number;
}
export interface ITaskbarClickEventArgs {
/** Defines the taskbar element. */
taskbarElement?: Element;
/** Defines the data of record. */
data?: IGanttData;
/** Defines the row index of record. */
rowIndex?: number;
/** Defines the target element. */
target?: Element;
}
export interface RecordDoubleClickEventArgs extends GridRecordDoubleClickEventArgs {
/** Defines the row element. */
row?: Element;
/** Defines the data of record. */
rowData?: IGanttData;
/** Defines the row index of record. */
rowIndex?: number;
/** Defines the target element. */
target?: Element;
}
export interface RowDropEventArgs {
/** Defines the selected row's element. */
rows?: Element[];
/** Defines the target element from which drag starts. */
target?: Element;
/** Defines the type of the element to be dragged.
*
* @hidden
*/
draggableType?: string;
/** Defines the selected row data.
*
* @isGenericType true
*/
data?: Object[];
/** Defines the drag element from index. */
fromIndex?: number;
/** Defines the target element from index. */
dropIndex?: number;
/** Define the mouse event */
originalEvent?: object;
cancel?: boolean;
/** Defines drop position of the dragged record */
dropPosition?: string;
/** Defines the request type. */
requestType?: string;
/** Defines the modified records. */
modifiedRecords?: IGanttData[];
/** Defines the modified records. */
dropRecord?: IGanttData;
}
export interface IMouseMoveEventArgs {
/** Defines the row data. */
data?: IGanttData;
/** Defines the column. */
column?: Object;
/** Defines the timeline date. */
date?: Date;
/** Defines the original event. */
originalEvent?: Object;
/** Defines the predecessor. */
predecessor?: PredecessorTooltip;
/** Defines the indicator. */
indicator?: IIndicator;
/** Defines the event markers. */
eventMarkers?: EventMarkerModel;
}
export interface PdfExportProperties {
/** Defines the Pdf orientation. */
pageOrientation?: PageOrientation;
/** Defines the Pdf page size. */
pageSize?: PdfPageSize;
/** Enable the footer. */
enableFooter?: boolean;
/** Indicates whether to show the hidden columns in exported Pdf */
includeHiddenColumn?: boolean;
/** Defines the theme for exported Gantt */
theme?: PdfTheme;
/** Defines the style for exported Gantt */
ganttStyle?: IGanttStyle;
/** Defines the file name for the exported file */
fileName?: string;
/** Indicates to export current data or all data */
exportType?: ExportType;
/** Indicates whether to show the predecessors in exported Pdf */
showPredecessorLines?: boolean;
}
export interface PdfQueryCellInfoEventArgs {
/** Defines the column of the current cell. */
column?: ColumnModel;
/** Defines the style of the current cell. */
style?: PdfGanttCellStyle;
/** Defines the value of the current cell. */
value?: Date | string | number | boolean | Object;
/** Defines the data of the cell */
data?: Object;
/** Defines the current PDF cell */
cell?: PdfTreeGridCell;
}
export interface TimelineDetails {
startPoint?: number;
endPoint?: number;
startDate?: Date;
endDate?: Date;
dayStartDate?: Date;
totalWidth?: number;
startIndex?: number;
endIndex?: number;
pageStartPoint?: PointF;
}
export interface PageDetail {
startPoint?: PointF;
width?: number;
height?: number;
pageStartX?: number;
}
export interface TimelineFormat {
width?: number;
height?: number;
value?: string;
isWeekend?: boolean;
style?: PdfGanttCellStyle;
isFinished?: boolean;
completedWidth?: number;
startDate?: Date;
endDate?: Date;
}
export interface PdfGanttFontStyle {
/** Defines the font size */
fontSize?: number;
/** Defines the font style */
fontStyle?: PdfFontStyle;
/** Defines the font color */
fontColor?: PdfColor;
/** Defines the background color of the cell */
backgroundColor?: PdfColor;
/** Defines the border color of the cell */
borderColor?: PdfColor;
/** Defines the format of the cell value */
format?: PdfStringFormat;
}
export interface PdfGanttCellStyle extends PdfGanttFontStyle {
/** Defines the cell borders */
borders?: PdfBorders;
/** Defines the cell padding */
padding?: PdfPaddings;
}
export interface ITaskbarStyle {
/** Defines the parent taskbar background color */
parentTaskColor?: PdfColor;
/** Defines the parent progressbar background color */
parentProgressColor?: PdfColor;
/** Defines the parent taskbar border color */
parentTaskBorderColor?: PdfColor;
/** Defines the child taskbar background color */
taskColor?: PdfColor;
/** Defines the child progressbar background color */
progressColor?: PdfColor;
/** Defines the child taskbar border color */
taskBorderColor?: PdfColor;
/** Defines the milestone background color */
milestoneColor?: PdfColor;
/** Defines the progress text color */
progressFontColor?: PdfColor;
}
export interface IGanttStyle {
columnHeader?: PdfGanttCellStyle;
fontFamily?: PdfFontFamily;
cell?: PdfGanttCellStyle;
taskbar?: ITaskbarStyle;
label?: PdfGanttCellStyle;
timeline?: PdfGanttCellStyle;
chartGridLineColor?: PdfColor;
connectorLineColor?: PdfColor;
footer?: PdfGanttCellStyle;
}
export interface PdfQueryTimelineCellInfoEventArgs {
/** Defines the timeline cell */
timelineCell?: PdfGanttCellStyle;
/** Specify the value of the timeline cell */
value?: string;
}
export interface PdfQueryTaskbarInfoEventArgs {
/** Defines the Taskbar style */
taskbar?: ITaskbarStyle;
/** Specify the value of the task data */
data?: IGanttData;
}
export interface PdfColumnHeaderQueryCellInfoEventArgs {
/** Defines the PDF grid current cell. */
cell?: PdfTreeGridCell;
/** Defines the style of the current cell. */
style?: PdfGanttCellStyle;
/** Defines the current cell with column */
column?: ColumnModel;
/** Specify the value of the column header cell */
value?: string | Object ;
}
/** @private */
export interface TaskLabel {
value?: string;
left?: number;
isCompleted?: boolean;
isLeftCalculated?: boolean;
}
/**
* public Enum for `PdfHorizontalOverflowType`.
*
* @private
*/
export enum PdfHorizontalOverflowType {
/**
* Specifies the type of `NextPage`.
*
* @private
*/
NextPage,
/**
* Specifies the type of `LastPage`.
*
* @private
*/
LastPage
} | the_stack |
* ModifySiteAttribute请求参数结构体
*/
export interface ModifySiteAttributeRequest {
/**
* 站点ID
*/
SiteId: number
/**
* 站点名称
*/
Name?: string
/**
* 网站是否需要登录扫描:0-未知;-1-不需要;1-需要
*/
NeedLogin?: number
/**
* 登录后的cookie
*/
LoginCookie?: string
/**
* 用于测试cookie是否有效的URL
*/
LoginCheckUrl?: string
/**
* 用于测试cookie是否有效的关键字
*/
LoginCheckKw?: string
/**
* 禁止扫描器扫描的目录关键字
*/
ScanDisallow?: string
}
/**
* 监控任务详细数据
*/
export interface MonitorsDetail {
/**
* 监控任务基础信息。
*/
Basic?: Monitor
/**
* 监控任务包含的站点列表。
*/
Sites?: Array<MonitorMiniSite>
/**
* 监控任务包含的站点列表数量。
*/
SiteNumber?: number
/**
* 监控任务包含的受漏洞威胁的站点列表。
*/
ImpactSites?: Array<MonitorMiniSite>
/**
* 监控任务包含的受漏洞威胁的站点列表数量。
*/
ImpactSiteNumber?: number
/**
* 高风险漏洞数量。
*/
VulsHighNumber?: number
/**
* 中风险漏洞数量。
*/
VulsMiddleNumber?: number
/**
* 低风险漏洞数量。
*/
VulsLowNumber?: number
/**
* 提示数量。
*/
VulsNoticeNumber?: number
/**
* 监控任务包含的站点列表的平均扫描进度。
*/
Progress: number
/**
* 扫描页面总数。
*/
PageCount: number
/**
* 内容检测数量。
*/
ContentNumber: number
}
/**
* DescribeSites返回参数结构体
*/
export interface DescribeSitesResponse {
/**
* 站点数量。
*/
TotalCount?: number
/**
* 站点信息列表。
*/
Sites?: Array<Site>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeMonitors返回参数结构体
*/
export interface DescribeMonitorsResponse {
/**
* 监控任务列表。
*/
Monitors?: Array<MonitorsDetail>
/**
* 监控任务数量。
*/
TotalCount?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteSites请求参数结构体
*/
export interface DeleteSitesRequest {
/**
* 站点ID列表
*/
SiteIds: Array<number>
}
/**
* DescribeConfig请求参数结构体
*/
export type DescribeConfigRequest = null
/**
* DescribeVuls请求参数结构体
*/
export interface DescribeVulsRequest {
/**
* 站点ID
*/
SiteId?: number
/**
* 监控任务ID
*/
MonitorId?: number
/**
* 过滤条件
*/
Filters?: Array<Filter>
/**
* 偏移量,默认为0
*/
Offset?: number
/**
* 返回数量,默认为10,最大值为100
*/
Limit?: number
}
/**
* ModifyConfigAttribute返回参数结构体
*/
export interface ModifyConfigAttributeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateSites返回参数结构体
*/
export interface CreateSitesResponse {
/**
* 新增站点数。
*/
Number?: number
/**
* 站点数组
*/
Sites?: Array<MiniSite>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeVulsNumber请求参数结构体
*/
export type DescribeVulsNumberRequest = null
/**
* ModifyMonitorAttribute返回参数结构体
*/
export interface ModifyMonitorAttributeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifySiteAttribute返回参数结构体
*/
export interface ModifySiteAttributeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateVulsReport请求参数结构体
*/
export interface CreateVulsReportRequest {
/**
* 站点ID
*/
SiteId?: number
/**
* 监控任务ID
*/
MonitorId?: number
}
/**
* CreateSitesScans返回参数结构体
*/
export interface CreateSitesScansResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 站点验证数据
*/
export interface SitesVerification {
/**
* 根域名。
*/
Domain?: string
/**
* txt解析域名验证的name。
*/
TxtName?: string
/**
* txt解析域名验证的text。
*/
TxtText?: string
/**
* 验证有效期,在此之前有效。
*/
ValidTo?: string
/**
* 验证状态:0-未验证;1-已验证;2-验证失效,待重新验证。
*/
VerifyStatus?: number
/**
* CreatedAt。
*/
CreatedAt?: string
/**
* UpdatedAt。
*/
UpdatedAt?: string
/**
* ID。
*/
Id: number
/**
* 云用户appid
*/
Appid: number
/**
* 用于验证站点的url,即访问该url获取验证数据。
*/
VerifyUrl: string
/**
* 获取验证验证文件的url。
*/
VerifyFileUrl: string
}
/**
* DescribeSiteQuota返回参数结构体
*/
export interface DescribeSiteQuotaResponse {
/**
* 已购买的扫描次数。
*/
Total?: number
/**
* 已使用的扫描次数。
*/
Used?: number
/**
* 剩余可用的扫描次数。
*/
Available?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeVulsNumber返回参数结构体
*/
export interface DescribeVulsNumberResponse {
/**
* 受影响的网站总数。
*/
ImpactSiteNumber?: number
/**
* 已验证的网站总数。
*/
SiteNumber?: number
/**
* 高风险漏洞总数。
*/
VulsHighNumber?: number
/**
* 中风险漏洞总数。
*/
VulsMiddleNumber?: number
/**
* 低高风险漏洞总数。
*/
VulsLowNumber?: number
/**
* 风险提示总数。
*/
VulsNoticeNumber?: number
/**
* 扫描页面总数。
*/
PageCount?: number
/**
* 已验证的网站列表。
*/
Sites?: Array<MonitorMiniSite>
/**
* 受影响的网站列表。
*/
ImpactSites?: Array<MonitorMiniSite>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateVulsMisinformation请求参数结构体
*/
export interface CreateVulsMisinformationRequest {
/**
* 漏洞ID列表
*/
VulIds: Array<number>
}
/**
* DescribeVulsNumberTimeline请求参数结构体
*/
export type DescribeVulsNumberTimelineRequest = null
/**
* 监控任务中的站点信息。
*/
export interface MonitorMiniSite {
/**
* 站点ID。
*/
SiteId?: number
/**
* 站点Url。
*/
Url?: string
}
/**
* CreateSitesScans请求参数结构体
*/
export interface CreateSitesScansRequest {
/**
* 站点的ID列表
*/
SiteIds: Array<number>
/**
* 扫描模式,normal-正常扫描;deep-深度扫描
*/
ScannerType: string
/**
* 扫描速率限制,每秒发送X个HTTP请求
*/
RateLimit: number
}
/**
* CreateMonitors返回参数结构体
*/
export interface CreateMonitorsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeVuls返回参数结构体
*/
export interface DescribeVulsResponse {
/**
* 漏洞数量。
*/
TotalCount?: number
/**
* 漏洞信息列表。
*/
Vuls?: Array<Vul>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* VerifySites返回参数结构体
*/
export interface VerifySitesResponse {
/**
* 验证成功的根域名数量。
*/
SuccessNumber?: number
/**
* 验证失败的根域名数量。
*/
FailNumber?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateMonitors请求参数结构体
*/
export interface CreateMonitorsRequest {
/**
* 站点的url列表
*/
Urls: Array<string>
/**
* 任务名称
*/
Name: string
/**
* 扫描模式,normal-正常扫描;deep-深度扫描
*/
ScannerType: string
/**
* 扫描周期,单位小时,每X小时执行一次
*/
Crontab: number
/**
* 扫描速率限制,每秒发送X个HTTP请求
*/
RateLimit: number
/**
* 首次扫描开始时间
*/
FirstScanStartTime: string
}
/**
* DeleteMonitors返回参数结构体
*/
export interface DeleteMonitorsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 监控任务基础数据
*/
export interface Monitor {
/**
* 监控任务ID。
*/
Id?: number
/**
* 监控名称。
*/
Name?: string
/**
* 监测状态:1-监测中;2-暂停监测。
*/
MonitorStatus?: number
/**
* 监测模式,normal-正常扫描;deep-深度扫描。
*/
ScannerType?: string
/**
* 扫描周期,单位小时,每X小时执行一次。
*/
Crontab?: number
/**
* 指定扫描类型,3位数每位依次表示:扫描Web漏洞、扫描系统漏洞、扫描系统端口。
*/
IncludedVulsTypes?: string
/**
* 速率限制,每秒发送X个HTTP请求。
*/
RateLimit?: number
/**
* 首次扫描开始时间。
*/
FirstScanStartTime?: string
/**
* 扫描状态:0-待扫描(无任何扫描结果);1-扫描中(正在进行扫描);2-已扫描(有扫描结果且不正在扫描);3-扫描完成待同步结果。
*/
ScanStatus?: number
/**
* 上一次扫描完成时间。
*/
LastScanFinishTime?: string
/**
* 当前扫描开始时间,如扫描完成则为上一次扫描的开始时间。
*/
CurrentScanStartTime?: string
/**
* CreatedAt。
*/
CreatedAt?: string
/**
* UpdatedAt。
*/
UpdatedAt?: string
/**
* 云用户appid。
*/
Appid: number
/**
* 扫描状态:0-待检测;1-检测完成
*/
ContentScanStatus: number
}
/**
* 漏洞数据
*/
export interface Vul {
/**
* 漏洞ID。
*/
Id?: number
/**
* 站点ID。
*/
SiteId?: number
/**
* 扫描引擎的扫描任务ID。
*/
TaskId?: number
/**
* 漏洞级别:high、middle、low、notice。
*/
Level?: string
/**
* 漏洞名称。
*/
Name?: string
/**
* 出现漏洞的url。
*/
Url?: string
/**
* 网址/细节。
*/
Html?: string
/**
* 漏洞类型。
*/
Nickname?: string
/**
* 危害说明。
*/
Harm?: string
/**
* 漏洞描述。
*/
Describe?: string
/**
* 解决方案。
*/
Solution?: string
/**
* 漏洞参考。
*/
From?: string
/**
* 漏洞通过该参数攻击。
*/
Parameter?: string
/**
* CreatedAt。
*/
CreatedAt?: string
/**
* UpdatedAt。
*/
UpdatedAt?: string
/**
* 是否已经添加误报,0-否,1-是。
*/
IsReported: number
/**
* 云用户appid。
*/
Appid: number
/**
* 云用户标识。
*/
Uin: string
}
/**
* 用户漏洞数随时间变化统计数据
*/
export interface VulsTimeline {
/**
* ID。
*/
Id: number
/**
* 云用户appid。
*/
Appid: number
/**
* 日期。
*/
Date: string
/**
* 扫描页面总数量。
*/
PageCount: number
/**
* 已验证网站总数量。
*/
SiteNum: number
/**
* 受影响的网站总数量。
*/
ImpactSiteNum: number
/**
* 高危漏洞总数量。
*/
VulsHighNum: number
/**
* 中危漏洞总数量。
*/
VulsMiddleNum: number
/**
* 低危漏洞总数量。
*/
VulsLowNum: number
/**
* 风险提示总数量
*/
VulsNoticeNum: number
/**
* 记录添加时间。
*/
CreatedAt: string
/**
* 记录最近修改时间。
*/
UpdatedAt: string
}
/**
* CreateVulsMisinformation返回参数结构体
*/
export interface CreateVulsMisinformationResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* VerifySites请求参数结构体
*/
export interface VerifySitesRequest {
/**
* 站点的url列表
*/
Urls: Array<string>
}
/**
* 站点信息。
*/
export interface MiniSite {
/**
* 站点ID。
*/
SiteId: number
/**
* 站点Url。
*/
Url: string
}
/**
* ModifyMonitorAttribute请求参数结构体
*/
export interface ModifyMonitorAttributeRequest {
/**
* 监测任务ID
*/
MonitorId: number
/**
* 站点的url列表
*/
Urls: Array<string>
/**
* 任务名称
*/
Name: string
/**
* 扫描模式,normal-正常扫描;deep-深度扫描
*/
ScannerType: string
/**
* 扫描周期,单位小时,每X小时执行一次
*/
Crontab: number
/**
* 扫描速率限制,每秒发送X个HTTP请求
*/
RateLimit: number
/**
* 首次扫描开始时间
*/
FirstScanStartTime: string
/**
* 监测状态:1-监测中;2-暂停监测
*/
MonitorStatus: number
}
/**
* DescribeVulsNumberTimeline返回参数结构体
*/
export interface DescribeVulsNumberTimelineResponse {
/**
* 统计数据记录数量。
*/
TotalCount?: number
/**
* 用户漏洞数随时间变化统计数据。
*/
VulsTimeline?: Array<VulsTimeline>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateVulsReport返回参数结构体
*/
export interface CreateVulsReportResponse {
/**
* 报告下载地址
*/
ReportFileUrl?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateSites请求参数结构体
*/
export interface CreateSitesRequest {
/**
* 站点的url列表
*/
Urls: Array<string>
/**
* 访问网站的客户端标识
*/
UserAgent?: string
}
/**
* ModifyConfigAttribute请求参数结构体
*/
export interface ModifyConfigAttributeRequest {
/**
* 漏洞告警通知等级,4位分别代表:高危、中危、低危、提示
*/
NoticeLevel?: string
}
/**
* 描述键值对过滤器,用于条件过滤查询。例如过滤ID、名称、状态等
若存在多个Filter时,Filter间的关系为逻辑与(AND)关系。
若同一个Filter存在多个Values,同一Filter下Values间的关系为逻辑或(OR)关系。
*/
export interface Filter {
/**
* 过滤键的名称。
*/
Name: string
/**
* 一个或者多个过滤值。
*/
Values: Array<string>
}
/**
* DescribeMonitors请求参数结构体
*/
export interface DescribeMonitorsRequest {
/**
* 监控任务ID列表
*/
MonitorIds?: Array<number>
/**
* 过滤条件
*/
Filters?: Array<Filter>
/**
* 偏移量,默认为0
*/
Offset?: number
/**
* 返回数量,默认为10,最大值为100
*/
Limit?: number
}
/**
* DeleteSites返回参数结构体
*/
export interface DeleteSitesResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteMonitors请求参数结构体
*/
export interface DeleteMonitorsRequest {
/**
* 监控任务ID列表
*/
MonitorIds: Array<number>
}
/**
* DescribeSitesVerification返回参数结构体
*/
export interface DescribeSitesVerificationResponse {
/**
* 验证信息数量。
*/
TotalCount?: number
/**
* 验证信息列表。
*/
SitesVerification?: Array<SitesVerification>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 站点数据
*/
export interface Site {
/**
* 站点ID。
*/
Id?: number
/**
* 监控任务ID,为0时表示未加入监控任务。
*/
MonitorId?: number
/**
* 站点url。
*/
Url?: string
/**
* 站点名称。
*/
Name?: string
/**
* 验证状态:0-未验证;1-已验证;2-验证失效,待重新验证。
*/
VerifyStatus?: number
/**
* 监测状态:0-未监测;1-监测中;2-暂停监测。
*/
MonitorStatus?: number
/**
* 扫描状态:0-待扫描(无任何扫描结果);1-扫描中(正在进行扫描);2-已扫描(有扫描结果且不正在扫描);3-扫描完成待同步结果。
*/
ScanStatus?: number
/**
* 最近一次的AIScanner的扫描任务id,注意取消的情况。
*/
LastScanTaskId?: number
/**
* 最近一次扫描开始时间。
*/
LastScanStartTime?: string
/**
* 最近一次扫描完成时间。
*/
LastScanFinishTime?: string
/**
* 最近一次取消时间,取消即使用上一次扫描结果。
*/
LastScanCancelTime?: string
/**
* 最近一次扫描扫描的页面数。
*/
LastScanPageCount?: number
/**
* normal-正常扫描;deep-深度扫描。
*/
LastScanScannerType?: string
/**
* 最近一次扫描高风险漏洞数量。
*/
LastScanVulsHighNum?: number
/**
* 最近一次扫描中风险漏洞数量。
*/
LastScanVulsMiddleNum?: number
/**
* 最近一次扫描低风险漏洞数量。
*/
LastScanVulsLowNum?: number
/**
* 最近一次扫描提示信息数量。
*/
LastScanVulsNoticeNum?: number
/**
* 记录添加时间。
*/
CreatedAt?: string
/**
* 记录最近修改时间。
*/
UpdatedAt?: string
/**
* 速率限制,每秒发送X个HTTP请求。
*/
LastScanRateLimit?: number
/**
* 最近一次扫描漏洞总数量。
*/
LastScanVulsNum?: number
/**
* 最近一次扫描提示总数量
*/
LastScanNoticeNum?: number
/**
* 扫描进度,百分比整数
*/
Progress: number
/**
* 云用户appid。
*/
Appid: number
/**
* 云用户标识。
*/
Uin: string
/**
* 网站是否需要登录扫描:0-未知;-1-不需要;1-需要。
*/
NeedLogin: number
/**
* 登录后的cookie。
*/
LoginCookie: string
/**
* 登录后的cookie是否有效:0-无效;1-有效。
*/
LoginCookieValid: number
/**
* 用于测试cookie是否有效的URL。
*/
LoginCheckUrl: string
/**
* 用于测试cookie是否有效的关键字。
*/
LoginCheckKw: string
/**
* 禁止扫描器扫描的目录关键字。
*/
ScanDisallow: string
/**
* 访问网站的客户端标识。
*/
UserAgent: string
/**
* 内容检测状态:0-未检测;1-已检测;
*/
ContentStatus: number
/**
* 最近一次扫描内容检测数量
*/
LastScanContentNum: number
}
/**
* DescribeConfig返回参数结构体
*/
export interface DescribeConfigResponse {
/**
* 漏洞告警通知等级,4位分别代表:高危、中危、低危、提示。
*/
NoticeLevel?: string
/**
* 配置ID。
*/
Id?: number
/**
* 记录创建时间。
*/
CreatedAt?: string
/**
* 记录更新新建。
*/
UpdatedAt?: string
/**
* 云用户appid。
*/
Appid?: number
/**
* 内容检测通知等级-1:通知,0-不通知
*/
ContentLevel?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeSites请求参数结构体
*/
export interface DescribeSitesRequest {
/**
* 站点ID列表
*/
SiteIds?: Array<number>
/**
* 过滤条件
*/
Filters?: Array<Filter>
/**
* 偏移量,默认为0
*/
Offset?: number
/**
* 返回数量,默认为10,最大值为100
*/
Limit?: number
}
/**
* DescribeSiteQuota请求参数结构体
*/
export type DescribeSiteQuotaRequest = null
/**
* DescribeSitesVerification请求参数结构体
*/
export interface DescribeSitesVerificationRequest {
/**
* 站点的url列表
*/
Urls: Array<string>
} | the_stack |
// -----------------------------------------------------------------------------
// Model
// -----------------------------------------------------------------------------
export const CauseSym = Symbol.for("@effect/core/io/Cause")
export type CauseSym = typeof CauseSym
export const _E = Symbol.for("@effect/core/io/Cause/E")
export type _E = typeof _E
/**
* @tsplus type ets/Cause
*/
export interface Cause<E> extends Equals {
readonly [CauseSym]: CauseSym
readonly [_E]: () => E
}
/**
* @tsplus type ets/Cause/Ops
*/
export interface CauseOps {
$: CauseAspects
}
export const Cause: CauseOps = {
$: {}
}
/**
* @tsplus type ets/Cause/Aspects
*/
export interface CauseAspects {}
/**
* @tsplus unify ets/Cause
*/
export function unify<X extends Cause<any>>(
self: X
): Cause<[X] extends [Cause<infer CX>] ? CX : never> {
return self
}
export type RealCause<E> =
| Empty
| Fail<E>
| Die
| Interrupt
| Stackless<E>
| Then<E>
| Both<E>
/**
* @tsplus macro remove
*/
export function realCause<E>(cause: Cause<E>): asserts cause is RealCause<E> {
//
}
/**
* @tsplus fluent ets/Cause isEmptyType
*/
export function isEmptyType<E>(cause: Cause<E>): cause is Empty {
realCause(cause)
return cause._tag === "Empty"
}
/**
* @tsplus fluent ets/Cause isDieType
*/
export function isDieType<E>(cause: Cause<E>): cause is Die {
realCause(cause)
return cause._tag === "Die"
}
/**
* @tsplus fluent ets/Cause isFailType
*/
export function isFailType<E>(cause: Cause<E>): cause is Fail<E> {
realCause(cause)
return cause._tag === "Fail"
}
/**
* @tsplus fluent ets/Cause isInterruptType
*/
export function isInterruptType<E>(cause: Cause<E>): cause is Interrupt {
realCause(cause)
return cause._tag === "Interrupt"
}
/**
* @tsplus fluent ets/Cause isStacklessType
*/
export function isStacklessType<E>(cause: Cause<E>): cause is Stackless<E> {
realCause(cause)
return cause._tag === "Stackless"
}
/**
* @tsplus fluent ets/Cause isThenType
*/
export function isThenType<E>(cause: Cause<E>): cause is Then<E> {
realCause(cause)
return cause._tag === "Then"
}
/**
* @tsplus fluent ets/Cause isBothType
*/
export function isBothType<E>(cause: Cause<E>): cause is Both<E> {
realCause(cause)
return cause._tag === "Both"
}
export class Empty implements Cause<never>, Equals {
readonly _tag = "Empty"
readonly [CauseSym]: CauseSym = CauseSym
readonly [_E]!: () => never;
[Hash.sym](): number {
return _emptyHash
}
[Equals.sym](that: unknown): boolean {
return isCause(that) && this.__equalsSafe(that).run()
}
__equalsSafe(that: Cause<unknown>): Eval<boolean> {
realCause(that)
switch (that._tag) {
case "Empty": {
return Eval.succeed(true)
}
case "Both":
case "Then": {
return Eval.suspend(
this.__equalsSafe(that.left)
).zipWith(
Eval.suspend(this.__equalsSafe(that.right)),
(a, b) => a && b
)
}
case "Stackless": {
return Eval.suspend(this.__equalsSafe(that.cause))
}
default: {
return Eval.succeed(false)
}
}
}
}
export interface Fail<E> extends Cause<E> {}
export class Fail<E> implements Cause<E>, Equals {
readonly _tag = "Fail"
readonly [CauseSym]: CauseSym = CauseSym
readonly [_E]!: () => E
constructor(readonly value: E, readonly trace: Trace) {}
[Hash.sym](): number {
return Hash.combine(Hash.string(this._tag), Hash.unknown(this.value))
}
[Equals.sym](that: unknown): boolean {
return isCause(that) && this.__equalsSafe(that).run()
}
__equalsSafe(that: Cause<unknown>): Eval<boolean> {
realCause(that)
switch (that._tag) {
case "Fail": {
return Eval.succeed(Equals.equals(this.value, that.value))
}
case "Both":
case "Then": {
return Eval.suspend(sym(zero)(this, that))
}
case "Stackless": {
return Eval.suspend(this.__equalsSafe(that.cause))
}
default: {
return Eval.succeed(false)
}
}
}
}
export class Die implements Cause<never>, Equals {
readonly _tag = "Die"
readonly [CauseSym]: CauseSym = CauseSym
readonly [_E]!: () => never
constructor(readonly value: unknown, readonly trace: Trace) {}
[Hash.sym](): number {
return Hash.combine(Hash.string(this._tag), Hash.unknown(this.value))
}
[Equals.sym](that: unknown): boolean {
return isCause(that) && this.__equalsSafe(that).run()
}
__equalsSafe(that: Cause<unknown>): Eval<boolean> {
realCause(that)
switch (that._tag) {
case "Die": {
return Eval.succeed(Equals.equals(this.value, that.value))
}
case "Both":
case "Then": {
return Eval.suspend(sym(zero)(this, that))
}
case "Stackless": {
return Eval.suspend(this.__equalsSafe(that.cause))
}
default: {
return Eval.succeed(false)
}
}
}
}
export class Interrupt implements Cause<never>, Equals {
readonly _tag = "Interrupt"
readonly [CauseSym]: CauseSym = CauseSym
readonly [_E]!: () => never
constructor(readonly fiberId: FiberId, readonly trace: Trace) {}
[Hash.sym](): number {
return Hash.combine(Hash.string(this._tag), Hash.unknown(this.fiberId))
}
[Equals.sym](that: unknown): boolean {
return isCause(that) && this.__equalsSafe(that).run()
}
__equalsSafe(that: Cause<unknown>): Eval<boolean> {
realCause(that)
switch (that._tag) {
case "Interrupt": {
return Eval.succeed(Equals.equals(this.fiberId, that.fiberId))
}
case "Both":
case "Then": {
return Eval.suspend(sym(zero)(this, that))
}
case "Stackless": {
return Eval.suspend(this.__equalsSafe(that.cause))
}
default: {
return Eval.succeed(false)
}
}
}
}
export class Stackless<E> implements Cause<E>, Equals {
readonly _tag = "Stackless"
readonly [CauseSym]: CauseSym = CauseSym
readonly [_E]!: () => E
constructor(readonly cause: Cause<E>, readonly stackless: boolean) {}
[Hash.sym](): number {
return this.cause[Hash.sym]()
}
[Equals.sym](that: unknown): boolean {
return isCause(that) && this.__equalsSafe(that).run()
}
__equalsSafe(that: Cause<unknown>): Eval<boolean> {
realCause(this.cause)
realCause(that)
return that._tag === "Stackless"
? this.cause.__equalsSafe(that.cause)
: this.cause.__equalsSafe(that)
}
}
export class Then<E> implements Cause<E>, Equals {
readonly _tag = "Then"
readonly [CauseSym]: CauseSym = CauseSym
readonly [_E]!: () => E
constructor(readonly left: Cause<E>, readonly right: Cause<E>) {}
[Hash.sym](): number {
return hashCode(this)
}
[Equals.sym](that: unknown): boolean {
return isCause(that) && this.__equalsSafe(that).run()
}
__equalsSafe(that: Cause<unknown>): Eval<boolean> {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this
return Eval.gen(function*(_) {
realCause(that)
if (that._tag === "Stackless") {
return yield* _(self.__equalsSafe(that.cause))
}
return (
(yield* _(self.eq(that))) ||
(yield* _(sym(associativeThen)(self, that))) ||
(yield* _(sym(distributiveThen)(self, that))) ||
(yield* _(sym(zero)(self, that)))
)
})
}
private eq(that: Cause<unknown>): Eval<boolean> {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this
realCause(that)
if (that._tag === "Then") {
return Eval.gen(function*(_) {
realCause(self.left)
realCause(self.right)
return (
(yield* _(self.left.__equalsSafe(that.left))) &&
(yield* _(self.right.__equalsSafe(that.right)))
)
})
}
return Eval.succeed(false)
}
}
export class Both<E> implements Cause<E>, Equals {
readonly _tag = "Both"
readonly [CauseSym]: CauseSym = CauseSym
readonly [_E]!: () => E
constructor(readonly left: Cause<E>, readonly right: Cause<E>) {}
[Hash.sym](): number {
return hashCode(this)
}
[Equals.sym](that: unknown): boolean {
return isCause(that) && this.__equalsSafe(that).run()
}
__equalsSafe(that: Cause<unknown>): Eval<boolean> {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this
return Eval.gen(function*(_) {
realCause(that)
if (that._tag === "Stackless") {
return yield* _(self.__equalsSafe(that.cause))
}
return (
(yield* _(self.eq(that))) ||
(yield* _(sym(associativeBoth)(self, that))) ||
(yield* _(sym(distributiveBoth)(self, that))) ||
(yield* _(commutativeBoth(self, that))) ||
(yield* _(sym(zero)(self, that)))
)
})
}
private eq(that: Cause<unknown>): Eval<boolean> {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this
realCause(that)
if (that._tag === "Both") {
return Eval.gen(function*(_) {
realCause(self.left)
realCause(self.right)
return (
(yield* _(self.left.__equalsSafe(that.left))) &&
(yield* _(self.right.__equalsSafe(that.right)))
)
})
}
return Eval.succeed(false)
}
}
// -----------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------
/**
* @tsplus static ets/Cause/Ops empty
*/
export const empty: Cause<never> = new Empty()
/**
* @tsplus static ets/Cause/Ops die
*/
export function die(defect: unknown, trace: Trace = Trace.none): Cause<never> {
return new Die(defect, trace)
}
/**
* @tsplus static ets/Cause/Ops fail
*/
export function fail<E>(error: E, trace: Trace = Trace.none): Cause<E> {
return new Fail(error, trace)
}
/**
* @tsplus static ets/Cause/Ops interrupt
*/
export function interrupt(fiberId: FiberId, trace: Trace = Trace.none): Cause<never> {
return new Interrupt(fiberId, trace)
}
/**
* @tsplus static ets/Cause/Ops stack
*/
export function stack<E>(cause: Cause<E>): Cause<E> {
return new Stackless(cause, false)
}
/**
* @tsplus static ets/Cause/Ops stackless
*/
export function stackless<E>(cause: Cause<E>): Cause<E> {
return new Stackless(cause, true)
}
/**
* @tsplus operator ets/Cause +
* @tsplus static ets/Cause/Ops then
*/
export function combineSeq<E1, E2>(left: Cause<E1>, right: Cause<E2>): Cause<E1 | E2> {
return isEmpty(left) ? right : isEmpty(right) ? left : new Then<E1 | E2>(left, right)
}
/**
* @tsplus operator ets/Cause &
* @tsplus static ets/Cause/Ops both
*/
export function combinePar<E1, E2>(left: Cause<E1>, right: Cause<E2>): Cause<E1 | E2> {
// TODO(Mike/Max): discuss this, because ZIO does not flatten empty causes here
return isEmpty(left) ? right : isEmpty(right) ? left : new Both<E1 | E2>(left, right)
}
// -----------------------------------------------------------------------------
// Utilities
// -----------------------------------------------------------------------------
/**
* Determines if the provided value is a `Cause`.
*
* @tsplus fluent ets/Cause isCause
*/
export function isCause(self: unknown): self is Cause<unknown> {
return typeof self === "object" && self != null && CauseSym in self
}
/**
* Determines if the `Cause` is empty.
*
* @tsplus fluent ets/Cause isEmpty
*/
export function isEmpty<E>(cause: Cause<E>): boolean {
if (isEmptyType(cause) || (isStacklessType(cause) && isEmptyType(cause.cause))) {
return true
}
let causes: Stack<Cause<E>> | undefined = undefined
realCause(cause)
let current: RealCause<E> | undefined = cause
while (current) {
switch (current._tag) {
case "Die":
return false
case "Fail":
return false
case "Interrupt":
return false
case "Then": {
causes = new Stack(current.right, causes)
realCause(current.left)
current = current.left
break
}
case "Both": {
causes = new Stack(current.right, causes)
realCause(current.left)
current = current.left
break
}
case "Stackless": {
realCause(current.cause)
current = current.cause
break
}
default: {
current = undefined
}
}
if (!current && causes) {
realCause(causes.value)
current = causes.value
causes = causes.previous
}
}
return true
}
const _emptyHash = Hash.optimize(Hash.random())
function stepLoop<A>(
cause: Cause<A>,
stack: List<Cause<A>>,
parallel: HashSet<Cause<A>>,
sequential: List<Cause<A>>
): Tuple<[HashSet<Cause<A>>, List<Cause<A>>]> {
// eslint-disable-next-line no-constant-condition
while (1) {
realCause(cause)
switch (cause._tag) {
case "Empty": {
if (stack.length() === 0) {
return Tuple(parallel, sequential)
} else {
cause = stack.unsafeHead()!
const tail = stack.unsafeTail()
stack = tail == null ? List.nil() : tail
}
break
}
case "Then": {
const left = cause.left
const right = cause.right
realCause(left)
switch (left._tag) {
case "Empty": {
cause = cause.right
break
}
case "Then": {
cause = new Then(left.left, new Then(left.right, right))
break
}
case "Both": {
cause = new Both(new Then(left.left, right), new Then(left.right, right))
break
}
case "Stackless": {
cause = new Then(left.cause, right)
break
}
default: {
cause = left
sequential = sequential.prepend(right)
}
}
break
}
case "Both": {
stack = stack.prepend(cause.right)
cause = cause.left
break
}
case "Stackless": {
cause = cause.cause
break
}
default: {
if (stack.length() === 0) {
return Tuple(parallel.add(cause), sequential)
} else {
parallel = parallel.add(cause)
cause = stack.unsafeHead()!
const tail = stack.unsafeTail()
stack = tail == null ? List.nil() : tail
break
}
}
}
}
throw new Error("Bug")
}
/**
* Takes one step in evaluating a cause, returning a set of causes that fail
* in parallel and a list of causes that fail sequentially after those causes.
*/
function step<A>(self: Cause<A>): Tuple<[HashSet<Cause<A>>, List<Cause<A>>]> {
return stepLoop(self, List.empty(), HashSet(), List.empty())
}
function flattenCauseLoop<A>(
causes: List<Cause<A>>,
flattened: List<HashSet<Cause<A>>>
): List<HashSet<Cause<A>>> {
// eslint-disable-next-line no-constant-condition
while (1) {
const {
tuple: [parallel, sequential]
} = causes.reduce(
Tuple(HashSet<Cause<A>>(), List.empty<Cause<A>>()),
({ tuple: [parallel, sequential] }, cause) => {
const {
tuple: [set, seq]
} = step(cause)
return Tuple(parallel.union(set), sequential + seq)
}
)
const updated = parallel.size > 0 ? flattened.prepend(parallel) : flattened
if (sequential.length() === 0) {
return updated.reverse()
} else {
causes = sequential
flattened = updated
}
}
throw new Error("Bug")
}
/**
* Flattens a `Cause` to a sequence of sets of causes, where each set represents
* causes that fail in parallel and sequential sets represent causes that fail
* after each other.
*/
function flattenCause<E>(self: Cause<E>): List<HashSet<Cause<E>>> {
return flattenCauseLoop(List(self), List.empty())
}
function hashCode<E>(self: Cause<E>): number {
const flat = flattenCause(self)
const size = flat.length()
let head
if (size === 0) {
return _emptyHash
} else if (size === 1 && (head = flat.unsafeHead()!) && head.size === 1) {
return List.from(head).unsafeHead()![Hash.sym]()
} else {
return flat[Hash.sym]()
}
}
function sym<E>(
f: (a: Cause<E>, b: Cause<E>) => Eval<boolean>
): (a: Cause<E>, b: Cause<E>) => Eval<boolean> {
return (l, r) => f(l, r).zipWith(f(r, l), (a, b) => a || b)
}
function zero<E>(self: Cause<E>, that: Cause<E>): Eval<boolean> {
if (isThenType(self) && isEmptyType(self.right)) {
realCause(self.left)
return self.left.__equalsSafe(that)
}
if (isThenType(self) && isEmptyType(self.left)) {
realCause(self.right)
return self.right.__equalsSafe(that)
}
if (isBothType(self) && isEmptyType(self.right)) {
realCause(self.left)
return self.left.__equalsSafe(that)
}
if (isBothType(self) && isEmptyType(self.left)) {
realCause(self.right)
return self.right.__equalsSafe(that)
}
return Eval.succeedNow(false)
}
function associativeThen<E>(self: Cause<E>, that: Cause<E>): Eval<boolean> {
return Eval.gen(function*(_) {
if (
isThenType(self) &&
isThenType(self.left) &&
isThenType(that) &&
isThenType(that.right)
) {
const al = self.left.left
const bl = self.left.right
const cl = self.right
const ar = that.left
const br = that.right.left
const cr = that.right.right
realCause(al)
realCause(bl)
realCause(cl)
return (
(yield* _(al.__equalsSafe(ar))) &&
(yield* _(bl.__equalsSafe(br))) &&
(yield* _(cl.__equalsSafe(cr)))
)
}
return false
})
}
function distributiveThen<E>(self: Cause<E>, that: Cause<E>): Eval<boolean> {
return Eval.gen(function*(_) {
if (
isThenType(self) &&
isBothType(self.right) &&
isBothType(that) &&
isThenType(that.left) &&
isThenType(that.right)
) {
const al = self.left
const bl = self.right.left
const cl = self.right.right
const ar1 = that.left.left
const br = that.left.right
const ar2 = that.right.left
const cr = that.right.right
realCause(ar1)
realCause(al)
realCause(bl)
realCause(cl)
if (
(yield* _(ar1.__equalsSafe(ar2))) &&
(yield* _(al.__equalsSafe(ar1))) &&
(yield* _(bl.__equalsSafe(br))) &&
(yield* _(cl.__equalsSafe(cr)))
) {
return true
}
}
if (
isThenType(self) &&
isBothType(self.left) &&
isBothType(that) &&
isThenType(that.left) &&
isThenType(that.right)
) {
const al = self.left.left
const bl = self.left.right
const cl = self.right
const ar = that.left.left
const cr1 = that.left.right
const br = that.right.left
const cr2 = that.right.right
realCause(cr1)
realCause(al)
realCause(bl)
realCause(cl)
if (
(yield* _(cr1.__equalsSafe(cr2))) &&
(yield* _(al.__equalsSafe(ar))) &&
(yield* _(bl.__equalsSafe(br))) &&
(yield* _(cl.__equalsSafe(cr1)))
) {
return true
}
}
return false
})
}
function associativeBoth<E>(self: Cause<E>, that: Cause<E>): Eval<boolean> {
return Eval.gen(function*(_) {
if (
isBothType(self) &&
isBothType(self.left) &&
isBothType(that) &&
isBothType(that.right)
) {
const al = self.left.left
const bl = self.left.right
const cl = self.right
const ar = that.left
const br = that.right.left
const cr = that.right.right
realCause(al)
realCause(bl)
realCause(cl)
return (
(yield* _(al.__equalsSafe(ar))) &&
(yield* _(bl.__equalsSafe(br))) &&
(yield* _(cl.__equalsSafe(cr)))
)
}
return false
})
}
function distributiveBoth<E>(self: Cause<E>, that: Cause<E>): Eval<boolean> {
return Eval.gen(function*(_) {
if (
isBothType(self) &&
isThenType(self.left) &&
isThenType(self.right) &&
isThenType(that) &&
isBothType(that.right)
) {
const al1 = self.left.left
const bl = self.left.right
const al2 = self.right.left
const cl = self.right.right
const ar = that.left
const br = that.right.left
const cr = that.right.right
realCause(al1)
realCause(bl)
realCause(cl)
if (
(yield* _(al1.__equalsSafe(al2))) &&
(yield* _(al1.__equalsSafe(ar))) &&
(yield* _(bl.__equalsSafe(br))) &&
(yield* _(cl.__equalsSafe(cr)))
) {
return true
}
}
if (
isBothType(self) &&
isThenType(self.left) &&
isThenType(self.right) &&
isThenType(that) &&
isBothType(that.left)
) {
const al = self.left.left
const cl1 = self.left.right
const bl = self.right.left
const cl2 = self.right.right
const ar = that.left.left
const br = that.left.right
const cr = that.right
realCause(cl1)
realCause(al)
realCause(bl)
if (
(yield* _(cl1.__equalsSafe(cl2))) &&
(yield* _(al.__equalsSafe(ar))) &&
(yield* _(bl.__equalsSafe(br))) &&
(yield* _(cl1.__equalsSafe(cr)))
) {
return true
}
}
return false
})
}
function commutativeBoth<E>(self: Both<E>, that: Cause<E>): Eval<boolean> {
return Eval.gen(function*(_) {
if (isBothType(that)) {
realCause(self.left)
realCause(self.right)
return (
(yield* _(self.left.__equalsSafe(that.right))) &&
(yield* _(self.right.__equalsSafe(that.left)))
)
}
return false
})
} | the_stack |
import { Component, Input, OnInit, ViewChild, ViewContainerRef } from '@angular/core'
import { Http } from '@angular/http';
import { AwsService } from "app/aws/aws.service";
import { DateTimeUtil } from 'app/shared/class/index';
import { ModalComponent } from 'app/shared/component/index';
import { ToastsManager } from 'ng2-toastr';
import { ActionItem } from "app/view/game/module/shared/class/index";
import { LyMetricService } from 'app/shared/service/index';
import { FormBuilder, FormGroup, FormArray, Validators, FormControl } from '@angular/forms';
import { CloudGemDefectReporterApi, ValidationUtil } from './index';
enum EditMode {
List,
CreateField,
EditField,
DeleteField
}
@Component({
selector: 'client-configuration',
templateUrl: 'node_modules/@cloud-gems/cloudgemdefectreporter/client-configuration.component.html',
styleUrls: ['node_modules/@cloud-gems/cloudgemdefectreporter/client-configuration.component.css']
})
export class CloudGemDefectReporterClientConfigurationComponent {
@Input() context: any;
private EditMode = EditMode;
private editMode: EditMode;
private _apiHandler: CloudGemDefectReporterApi;
private isFormFieldNotPositiveNum = ValidationUtil.isFormFieldNotPositiveNum;
private customFields = [];
private curFields = [];
private isLoadingClientConfiguration: boolean;
private curEditingField: Object;
private currentField: Object;
private curFieldIndex: number;
private fieldTitleForm: FormGroup;
private predefinedFieldForm: FormGroup;
private textFieldForm: FormGroup;
private objectFieldForm: FormGroup;
private fieldTypes = [
{ 'typeinfo': { 'type': 'predefined', 'multipleSelect': true }, 'displayText': 'Multiple Choice (Checkboxes)' },
{ 'typeinfo': { 'type': 'predefined', 'multipleSelect': false }, 'displayText': 'Single Choice (Radio Buttons)' },
{ 'typeinfo': { 'type': 'text' }, 'displayText': 'Text' },
{ 'typeinfo': { 'type': 'object' }, 'displayText': 'Object' }
]
@ViewChild(ModalComponent) modalRef: ModalComponent;
constructor(private fb: FormBuilder, private http: Http, private aws: AwsService, private toastr: ToastsManager, private vcr: ViewContainerRef, private metric: LyMetricService) {
}
ngOnInit() {
this._apiHandler = new CloudGemDefectReporterApi(this.context.ServiceUrl, this.http, this.aws, this.metric, this.context.identifier);
this.getClientConfiguration();
this.editMode = EditMode.List;
}
/**
* Get the existing client configuration
**/
private getClientConfiguration(): void {
this.isLoadingClientConfiguration = true;
this._apiHandler.getClientConfiguration().subscribe(
response => {
let obj = JSON.parse(response.body.text());
this.customFields = obj.result.clientConfiguration;
for (let customField of this.customFields) {
this.deserializeCustomFieldDefaultValue(customField);
}
this.isLoadingClientConfiguration = false;
},
err => {
this.toastr.error("Failed to load the custom client configuration ", err);
this.isLoadingClientConfiguration = false;
}
);
}
/**
* Deserialize the default value of the custom field
* @param customField the customField to deserialize
**/
private deserializeCustomFieldDefaultValue(customField): void {
if (customField['type'] === "predefined" && customField["multipleSelect"]) {
customField["defaultValue"] = JSON.parse(customField["defaultValue"]);
}
else if (customField['type'] === "object") {
for (let property of customField['properties']) {
this.deserializeCustomFieldDefaultValue(property);
}
customField["defaultValue"] = JSON.parse(customField["defaultValue"]);
}
}
/**
* Create custom field forms
**/
private createFieldForms(): void {
this.createFieldTitleForm();
this.createPredefinedFieldForm();
this.createTextFieldForm();
}
/**
* Create the field title form
**/
private createFieldTitleForm(): void {
this.fieldTitleForm = this.fb.group({
'title': [this.curEditingField["title"], Validators.compose([Validators.required, this.duplicate])]
});
}
/**
* Check if the title already exists
**/
private duplicate = (control: FormControl) =>{
for (let field of this.curFields) {
if (this.curEditingField["title"] !== field['title'] && field['title'] === control.value) {
return { duplicate: true };
}
}
return null;
}
/**
* Create the check box or radio button options form
**/
private createPredefinedFieldForm(): void {
this.predefinedFieldForm = this.fb.group({
'options': this.fb.array([])
});
if (this.curEditingField["predefines"]) {
let options = <FormArray>this.predefinedFieldForm.controls["options"];
for (let option of this.curEditingField["predefines"]) {
let optionForm = this.fb.group({
'value': [option, Validators.compose([Validators.required])]
});
options.push(optionForm);
}
}
}
/**
* Create the text field form
**/
private createTextFieldForm(): void {
this.textFieldForm = this.fb.group({
'maxChars': [this.curEditingField["maxChars"], Validators.compose([Validators.required, ValidationUtil.positiveNumberValidator])]
});
}
/**
* Create a default custom field
**/
private createDefaultField(): Object {
let defaultField = {};
defaultField["type"] = "predefined";
defaultField["multipleSelect"] = true;
defaultField["predefines"] = [""];
return defaultField;
}
/**
* Update the type of the custom field
* @param type the new type of the custom field
**/
private onChangeFieldType(fieldType: any): void {
this.curEditingField["type"] = fieldType.typeinfo.type;
if (this.curEditingField["type"] == 'predefined') {
this.curEditingField["multipleSelect"] = fieldType.typeinfo.multipleSelect;
}
}
/**
* Check whether the required form field is empty
* @param form the form to check
* @param item the form field to check
* @returns {boolean} whether the required form field is empty
**/
private isFormFieldRequiredEmpty(form: any, item: string): boolean {
return (form.controls[item].hasError('required') && form.controls[item].touched)
}
/**
* Check whether the required form field is duplicate
* @param form the form to check
* @param item the form field to check
* @returns {boolean} whether the required form field is empty
**/
private isFormFieldTitleDuplicate(form: any, item: string): boolean {
return (form.controls[item].hasError('duplicate') && form.controls[item].touched)
}
/**
* Check whether the form field is valid
* @param form the form to check
* @param item the form field to check
* @returns {boolean} whether the required form field is valid
**/
private isFormFieldNotValid(form: any, item: string): boolean {
return !form.controls[item].valid && form.controls[item].touched
}
/**
* add a new option for the check box or radio button group
**/
private onAddOption(): void {
let options = <FormArray>this.predefinedFieldForm.controls["options"];
options.push(
this.fb.group({
'value': [null, Validators.compose([Validators.required])]
})
);
}
/**
* add a new option of the check box or radio button group
* @param optionIndex the index of the option
**/
private onDeleteOption(optionIndex: number): void {
let options = <FormArray>this.predefinedFieldForm.controls["options"];
options.removeAt(optionIndex);
}
/**
* Modify a custom field
**/
private onModifyField(): void {
if (!this.validateFieldForms()) {
return;
}
this.extractFieldForm();
if (this.curEditingField['type'] === 'object') {
this.curEditingField['properties'] = [];
}
else if (this.curEditingField['properties']) {
delete this.curEditingField['properties'];
}
delete this.curEditingField['defaultValue'];
this.curFields[this.curFieldIndex] = this.curEditingField;
this.modalRef.close();
}
/**
* Add a new custom field
**/
private onAddField(): void {
if (!this.validateFieldForms()) {
return;
}
this.extractFieldForm();
if (this.curEditingField['type'] === 'object') {
this.curEditingField['properties'] = [];
}
this.curFields.push(this.curEditingField);
this.modalRef.close();
}
/**
* Save the client configuration
**/
private updateClientConfiguration(): void{
let customFieldsCopy = JSON.parse(JSON.stringify(this.customFields));
for (let customField of customFieldsCopy) {
this.serializeCustomFieldDefaultValue(customField);
}
let body = { "clientConfiguration": customFieldsCopy };
this._apiHandler.updateClientConfiguration(body).subscribe(
response => {
this.toastr.success("The client configuration was saved successfully.")
},
err => {
this.toastr.error("Failed to update the client configuration. ", err);
}
);
}
/**
* Serialize the default value of the custom field
* @param customField the customField to serialize
**/
private serializeCustomFieldDefaultValue(customField): void {
if (customField['type'] === "predefined" && customField["multipleSelect"]) {
let selections = [];
for (let i = 0; i < customField["defaultValue"].length; i++) {
if (customField["defaultValue"][i]) {
selections.push(customField["predefines"][i])
}
}
customField["defaultValue"] = JSON.stringify(selections);
}
else if (customField['type'] === "object") {
for (let property of customField['properties']) {
this.serializeCustomFieldDefaultValue(property);
if (property['type'] === "predefined" && property["multipleSelect"]) {
customField["defaultValue"][property['title']] = JSON.parse(property["defaultValue"]);
}
else {
customField["defaultValue"][property['title']] = property["defaultValue"];
}
}
customField["defaultValue"] = JSON.stringify(customField["defaultValue"]);
}
}
/**
* validate the field forms
**/
private validateFieldForms(): boolean {
let success = true;
success = this.validateTitleFieldForm() && success;
switch (this.curEditingField["type"]) {
case "predefined":
success = this.validatePredefinedFieldForm() && success;
break;
case "text":
success = this.validateTextFieldForm() && success;
break;
}
return success;
}
/**
* validate the title field forms
**/
private validateTitleFieldForm(): boolean {
this.fieldTitleForm.controls["title"].markAsTouched();
return this.fieldTitleForm.controls["title"].valid;
}
/**
* validate the text field forms
**/
private validateTextFieldForm(): boolean {
this.textFieldForm.controls["maxChars"].markAsTouched();
return this.textFieldForm.controls["maxChars"].valid;
}
/**
* validate the check box or radio button field forms
**/
private validatePredefinedFieldForm(): boolean {
let success = true;
let options = <FormArray>this.predefinedFieldForm.controls["options"];
for (let option of options.controls) {
let optionForm = <FormGroup>option;
optionForm.controls["value"].markAsTouched();
success = success && optionForm.controls["value"].valid;
}
return success;
}
/**
* extract the custom field form
**/
private extractFieldForm(): void {
this.curEditingField["title"] = this.fieldTitleForm.value.title;
switch (this.curEditingField["type"]) {
case "predefined":
let predefines = [];
let options = <FormArray>this.predefinedFieldForm.controls["options"];
for (let optionForm of options.controls) {
predefines.push(optionForm.value.value);
}
this.curEditingField["predefines"] = predefines;
break;
case "text":
this.curEditingField["maxChars"] = +this.textFieldForm.value.maxChars;
break;
}
}
/**
* get the display name of each type
**/
private getFieldTypeDisplayText() {
switch (this.curEditingField["type"]) {
case "text":
return 'Text';
case "object":
return 'Object';
case "predefined":
if (this.curEditingField["multipleSelect"]) {
return "Multiple Choice (Checkboxes)";
} else {
return "Single Choice (Radio Buttons)";
}
default:
return "unknown";
}
}
/**
* Delete the current custom field
**/
private onDeleteField(): void {
this.curFields.splice(this.curFieldIndex, 1);
this.modalRef.close();
}
/**
* Define all the modals
**/
private onModifyFieldModal(fields: Object[], field: Object, fieldIndex: number): void {
this.curFields = fields;
this.curEditingField = JSON.parse(JSON.stringify(field))
this.createFieldForms();
this.editMode = EditMode.EditField;
this.curFieldIndex = fieldIndex;
}
private onDeleteFieldModal = (fields: Object[], field: Object, index: number) => {
this.curFields = fields;
this.curFieldIndex = index;
this.curEditingField = field;
this.editMode = EditMode.DeleteField;
}
private onDismissModal = () => {
this.editMode = EditMode.List;
}
private onAddNewFieldModal = (fields: Object[]) => {
this.curEditingField = this.createDefaultField();
this.curFields = fields;
this.createFieldForms();
this.editMode = EditMode.CreateField;
}
private getModalName = () => {
if (this.editMode == EditMode.EditField) {
return 'Edit Field';
}
else if (this.editMode == EditMode.CreateField) {
return 'Add New Field';
}
else if (this.editMode == EditMode.DeleteField) {
return 'Delete Field';
}
}
private getSubmitButtonText = () => {
if (this.editMode == EditMode.EditField) {
return 'Save Changes';
}
else if (this.editMode == EditMode.CreateField) {
return 'Add Field';
}
else if (this.editMode == EditMode.DeleteField) {
return 'Delete Field';
}
}
private onModalSubmit = () => {
if (this.editMode == EditMode.EditField) {
this.onModifyField();
}
else if (this.editMode == EditMode.CreateField) {
this.onAddField();
}
else if (this.editMode == EditMode.DeleteField) {
this.onDeleteField();
}
}
} | the_stack |
import CPU6502, {
CpuState,
FLAVOR_ROCKWELL_65C02,
flags
} from '../js/cpu6502';
import { TestMemory } from './util/memory';
import { bios, Program } from './util/bios';
import { toReadableState } from './util/cpu';
const DEFAULT_STATE: CpuState = {
cycles: 0,
s: flags.X,
sp: 0xff,
a: 0x00,
x: 0x00,
y: 0x00,
pc: 0x0400
};
let memory;
let cpu: CPU6502;
let program;
function initState(initialState: Partial<CpuState>) {
const state = {...DEFAULT_STATE, ...initialState};
cpu.setState(state);
}
function expectState(initialState: CpuState, expectedState: Partial<CpuState>) {
const state = {...initialState, ...expectedState};
expect(toReadableState(cpu.getState())).toEqual(toReadableState(state));
}
function initMemory(memAry: [page: number, off: number, data: number[]][]) {
for (let idx = 0; idx < memAry.length; idx++) {
const mem = memAry[idx];
let page = mem[0];
let off = mem[1];
const data = mem[2];
for (let jdx = 0; jdx < data.length; jdx++) {
cpu.write(page, off++, data[jdx]);
if (off > 0xff) {
page++;
off = 0;
}
}
}
}
function expectMemory(expectAry: [page: number, off: number, data: number[]][]) {
const memAry = [];
for (let idx = 0; idx < expectAry.length; idx++) {
const mem = expectAry[idx];
let page = mem[0];
let off = mem[1];
const expectData = mem[2];
const data = [];
for (let jdx = 0; jdx < expectData.length; jdx++) {
data.push(cpu.read(page, off++));
if (off > 0xff) {
page++;
off = 0;
}
}
memAry.push([mem[0], mem[1], data]);
}
expect(memAry).toEqual(expectAry);
}
function expectStack(expectAry: number[]) {
const state = cpu.getState();
expectMemory([[0x01, state.sp + 1, expectAry]]);
}
function testCode(code: number[], steps: number, setupState: Partial<CpuState>, expectedState: Partial<CpuState>) {
const initialState = {...DEFAULT_STATE, ...setupState};
const finalState = { pc: initialState.pc + code.length, ...expectedState };
program = new Program(0x04, code);
cpu.addPageHandler(program);
cpu.setState(initialState);
cpu.stepN(steps);
expectState(initialState, finalState);
}
describe('CPU6502', function() {
beforeEach(function() {
cpu = new CPU6502();
memory = new TestMemory(4);
cpu.addPageHandler(memory);
cpu.addPageHandler(bios);
});
describe('#step functions', function() {
const code = [0xEA, 0xEA, 0xEA, 0xEA, 0xEA, 0xEA, 0xEA, 0xEA];
const initialState = {...DEFAULT_STATE};
it('step', function() {
cpu.setState(initialState);
program = new Program(0x04, code);
cpu.addPageHandler(program);
cpu.step();
expect(cpu.getState()).toEqual(
{ ...DEFAULT_STATE, pc: 0x401, cycles: 2 }
);
expect(cpu.getCycles()).toEqual(2);
});
it('step with callback', function() {
const callback = jest.fn();
cpu.setState(initialState);
program = new Program(0x04, code);
cpu.addPageHandler(program);
cpu.step(callback);
expect(cpu.getState()).toEqual({
...DEFAULT_STATE, pc: 0x401, cycles: 2,
});
expect(cpu.getCycles()).toEqual(2);
expect(callback).toHaveBeenCalledTimes(1);
});
it('stepN', function() {
cpu.setState(initialState);
program = new Program(0x04, code);
cpu.addPageHandler(program);
cpu.stepN(4);
expect(cpu.getState()).toEqual({
...DEFAULT_STATE, pc: 0x404, cycles: 8,
});
expect(cpu.getCycles()).toEqual(8);
});
it('stepN with callback', function() {
const callback = jest.fn();
cpu.setState(initialState);
program = new Program(0x04, code);
cpu.addPageHandler(program);
cpu.stepN(4, callback);
expect(cpu.getState()).toEqual({
...DEFAULT_STATE, pc: 0x404, cycles: 8,
});
expect(cpu.getCycles()).toEqual(8);
expect(callback).toHaveBeenCalledTimes(4);
});
it('stepN with breakpoint', function() {
const callback = jest.fn().mockReturnValue(true);
cpu.setState(initialState);
program = new Program(0x04, code);
cpu.addPageHandler(program);
cpu.stepN(4, callback);
expect(cpu.getState()).toEqual({
...DEFAULT_STATE, pc: 0x401, cycles: 2,
});
expect(cpu.getCycles()).toEqual(2);
expect(callback).toHaveBeenCalledTimes(1);
});
it('stepCycles', function() {
cpu.setState(initialState);
program = new Program(0x04, code);
cpu.addPageHandler(program);
cpu.stepCycles(4);
expect(cpu.getState()).toEqual({
...DEFAULT_STATE, pc: 0x402, cycles: 4,
});
expect(cpu.getCycles()).toEqual(4);
});
it('stepCyclesDebug', function() {
cpu.setState(initialState);
program = new Program(0x04, code);
cpu.addPageHandler(program);
cpu.stepCyclesDebug(4);
expect(cpu.getState()).toEqual({
...DEFAULT_STATE, pc: 0x402, cycles: 4,
});
expect(cpu.getCycles()).toEqual(4);
});
it('stepCyclesDebug with callback', function() {
const callback = jest.fn();
cpu.setState(initialState);
program = new Program(0x04, code);
cpu.addPageHandler(program);
cpu.stepCyclesDebug(4, callback);
expect(cpu.getState()).toEqual({
...DEFAULT_STATE, pc: 0x402, cycles: 4,
});
expect(cpu.getCycles()).toEqual(4);
expect(callback).toHaveBeenCalledTimes(2);
});
it('stepCyclesDebug with breakpoint', function() {
const callback = jest.fn().mockReturnValue(true);
cpu.setState(initialState);
program = new Program(0x04, code);
cpu.addPageHandler(program);
cpu.stepCyclesDebug(4, callback);
expect(cpu.getState()).toEqual({
...DEFAULT_STATE, pc: 0x401, cycles: 2,
});
expect(cpu.getCycles()).toEqual(2);
expect(callback).toHaveBeenCalledTimes(1);
});
});
describe('#signals', function () {
it('should reset', function () {
cpu.reset();
expectState(DEFAULT_STATE, {
cycles: 2
});
});
it('should irq', function () {
cpu.irq();
expectState(DEFAULT_STATE, {
cycles: 5,
s: flags.X | flags.I,
sp: 0xfc,
pc: 0xff00
});
});
it('should not irq if I set', function () {
initState({
s: flags.X | flags.I
});
cpu.irq();
expectState(DEFAULT_STATE, {
s: flags.X | flags.I,
pc: 0x400
});
});
it('should nmi', function () {
cpu.nmi();
expectState(DEFAULT_STATE, {
cycles: 5,
s: flags.X | flags.I,
sp: 0xfc,
pc: 0xff00
});
});
});
describe('#misc', function () {
it('should NOP', function () {
testCode([0xEA], 1, {}, {
cycles: 2
});
});
it('should BRK', function () {
testCode([0x00, 0x00], 1, {}, {
cycles: 7,
s: flags.X | flags.I,
sp: 0xfc,
pc: 0xff00
});
});
it('should RTI', function () {
initMemory([[0x01, 0xFD, [0xA0, 0x34, 0x12]]]);
testCode([0x40], 1, {
sp: 0xFC
}, {
cycles: 6,
s: flags.X | flags.N,
sp: 0xFF,
pc: 0x1234
});
});
});
describe('#registers', function() {
it('should LDA immediate', function () {
testCode([0xA9, 0x44], 1, {}, {
cycles: 2,
a: 0x44
});
});
it('should TAX', function () {
testCode([0xAA], 1, {
a: 0x44
}, {
cycles: 2,
x: 0x44
});
});
it('should TAY', function () {
testCode([0xA8], 1, {
a: 0x44
}, {
cycles: 2,
y: 0x44
});
});
it('should LDX immediate', function () {
testCode([0xA2, 0x44], 1, {}, {
cycles: 2,
x: 0x44
});
});
it('should TXA', function () {
testCode([0x8A], 1, {
x: 0x44
}, {
cycles: 2,
a: 0x44
});
});
it('should DEX', function () {
testCode([0xCA], 1, {
x: 0x44
}, {
cycles: 2,
x: 0x43
});
});
it('should INX', function () {
testCode([0xE8], 1, {
x: 0x44
}, {
cycles: 2,
x: 0x45
});
});
it('should LDY immediate', function () {
testCode([0xA0, 0x44], 1, {}, {
cycles: 2,
y: 0x44
});
});
it('should TYA', function () {
testCode([0x98], 1, {
y: 0x44
}, {
cycles: 2,
a: 0x44
});
});
it('should DEY', function () {
testCode([0x88], 1, {
y: 0x44
}, {
cycles: 2,
y: 0x43
});
});
it('should INY', function () {
testCode([0xC8], 1, {
y: 0x44
}, {
cycles: 2,
y: 0x45
});
});
});
describe('#flags', function() {
it('should SEC', function () {
testCode([0x38], 1, {}, {
cycles: 2,
s: flags.X | flags.C
});
});
it('should CLC', function () {
testCode([0x18], 1, {
s: flags.X | flags.C
}, {
cycles: 2,
s: flags.X
});
});
it('should SEI', function () {
testCode([0x78], 1, {}, {
cycles: 2,
s: flags.X | flags.I
});
});
it('should CLI', function () {
testCode([0x58], 1, {
s: flags.X | flags.I
}, {
cycles: 2,
s: flags.X
});
});
it('should CLV', function () {
testCode([0xB8], 1, {
s: flags.X | flags.V
}, {
cycles: 2,
s: flags.X
});
});
it('should SED', function () {
testCode([0xF8], 1, {}, {
cycles: 2,
s: flags.X | flags.D
});
});
it('should CLD', function () {
testCode([0xD8], 1, {
s: flags.X | flags.D
}, {
cycles: 2,
s: flags.X
});
});
});
describe('#stack', function() {
it('should TXS', function() {
testCode([0x9A], 1, {
x: 0x44
}, {
cycles: 2,
sp: 0x44
});
});
it('should TSX', function() {
testCode([0xBA], 1, {
sp: 0x44
}, {
cycles: 2,
x: 0x44
});
});
it('should PHA', function() {
testCode([0x48], 1, {
a: 0x44
}, {
cycles: 3,
sp: 0xfe
});
expectStack([0x44]);
});
it('should PLA', function() {
initMemory([[0x01, 0xff, [0x44]]]);
testCode([0x68], 1, {
sp: 0xfe
}, {
cycles: 4,
a: 0x44,
sp: 0xff
});
});
it('should PHP', function() {
testCode([0x08], 1, {
s: flags.X | flags.N | flags.C
}, {
cycles: 3,
sp: 0xfe
});
expectStack([flags.X | flags.B | flags.N | flags.C]);
});
it('should PLP', function() {
initMemory([[0x01, 0xff, [flags.N | flags.C]]]);
testCode([0x28], 1, {
sp: 0xfe
}, {
cycles: 4,
s: flags.X | flags.N | flags.C,
sp: 0xff
});
});
});
describe('#jumps', function() {
it('should JMP abs', function () {
testCode([0x4C, 0x34, 0x12], 1, {}, {
cycles: 3,
pc: 0x1234
});
});
it('should JMP (abs)', function () {
initMemory([[0x03, 0x33, [0x34, 0x12]]]);
testCode([0x6C, 0x33, 0x03], 1, {}, {
cycles: 5,
pc: 0x1234
});
});
it('should JMP (abs) across page boundaries with bugs', function () {
initMemory([[0x02, 0xFF, [0x34, 0x12]],
[0x02, 0x00, [0xff]]]);
testCode([0x6C, 0xFF, 0x02], 1, {}, {
cycles: 5,
pc: 0xFF34
});
});
it('should JSR abs', function () {
testCode([0x20, 0x34, 0x12], 1, {}, {
cycles: 6,
sp: 0xFD,
pc: 0x1234
});
expectStack([0x02, 0x04]);
});
it('should RTS', function () {
initMemory([[0x01, 0xFE, [0x34, 0x12]]]);
testCode([0x60], 1, {
sp: 0xFD
}, {
cycles: 6,
sp: 0xFF,
pc: 0x1235
});
});
});
describe('#branches', function() {
// ********** bcs
it('should BCS forward', function () {
testCode([0xB0, 0x7F], 1, {
s: flags.X | flags.C
}, {
cycles: 3,
pc: 0x0481
});
});
it('should BCS backward', function () {
testCode([0xB0, 0xff], 1, {
s: flags.X | flags.C
}, {
cycles: 3,
pc: 0x0401
});
});
it('should BCS across pages with an extra cycle', function () {
testCode([0xB0, 0xfd], 1, {
s: flags.X | flags.C
}, {
cycles: 4,
pc: 0x03FF
});
});
it('should not BCS if carry clear', function () {
testCode([0xB0, 0xfd], 1, {}, {
cycles: 2,
pc: 0x0402
});
});
it('should BCC forward', function () {
testCode([0x90, 0x7F], 1, {}, {
cycles: 3,
pc: 0x0481
});
});
it('should BCC backward', function () {
testCode([0x90, 0xff], 1, {}, {
cycles: 3,
pc: 0x0401
});
});
it('should BCC across pages with an extra cycle', function () {
testCode([0x90, 0xfd], 1, {}, {
cycles: 4,
pc: 0x03FF
});
});
it('should not BCC if carry set', function () {
testCode([0x90, 0xfd], 1, {
s: flags.X | flags.C
}, {
cycles: 2,
pc: 0x0402
});
});
});
describe('#read memory', function() {
// ********** zp
it('should LDY zp', function () {
initMemory([[0x00, 0x33, [0x44]]]);
testCode([0xA4, 0x33], 1, {}, {
cycles: 3,
y: 0x44
});
});
it('should LDA zp', function () {
initMemory([[0x00, 0x33, [0x44]]]);
testCode([0xA5, 0x33], 1, {}, {
cycles: 3,
a: 0x44
});
});
it('should LDX zp', function () {
initMemory([[0x00, 0x33, [0x44]]]);
testCode([0xA6, 0x33], 1, {}, {
cycles: 3,
x: 0x44
});
});
// ********** zp,x
it('should LDY zp,x', function () {
initMemory([[0x00, 0x36, [0x44]]]);
testCode([0xB4, 0x33], 1, {
x: 3
}, {
cycles: 4,
y: 0x44
});
});
it('should LDA zp,x', function () {
initMemory([[0x00, 0x36, [0x44]]]);
testCode([0xB5, 0x33], 1, {
x: 3
}, {
cycles: 4,
a: 0x44
});
});
// ********** zp,y
it('should LDX zp,y', function () {
initMemory([[0x00, 0x36, [0x44]]]);
testCode([0xB6, 0x33], 1, {
y: 3
}, {
cycles: 4,
x: 0x44
});
});
// ********** (zp,x)
it('should LDA (zp,x)', function () {
initMemory([
[0x00, 0x36, [0x33, 0x03]],
[0x03, 0x33, [0x44]]]
);
testCode([0xA1, 0x33], 1, {
x: 3
}, {
cycles: 6,
a: 0x44
});
});
// ********** (zp),y
it('should LDA (zp),y', function () {
initMemory([
[0x00, 0x33, [0x33, 0x03]],
[0x03, 0x36, [0x44]]
]);
testCode([0xB1, 0x33], 1, {
y: 3
}, {
cycles: 5,
a: 0x44
});
});
// ********** (zp),y
it('should LDA (zp),y with an extra cycle on page cross', function () {
initMemory([
[0x00, 0x33, [0x33, 0x02]],
[0x03, 0x32, [0x44]]
]);
testCode([0xB1, 0x33], 1, {
y: 0xff
}, {
cycles: 6,
a: 0x44
});
});
// ********** abs
it('should LDY abs', function () {
initMemory([[0x03, 0x33, [0x44]]]);
testCode([0xAC, 0x33, 0x03], 1, {}, {
cycles: 4,
y: 0x44
});
});
it('should LDA abs', function () {
initMemory([[0x03, 0x33, [0x44]]]);
testCode([0xAD, 0x33, 0x03], 1, {}, {
cycles: 4,
a: 0x44
});
});
it('should LDX abs', function () {
initMemory([[0x03, 0x33, [0x44]]]);
testCode([0xAE, 0x33, 0x03], 1, {}, {
cycles: 4,
x: 0x44
});
});
// ********** abs, x
it('should LDY abs,x', function () {
initMemory([[0x03, 0x36, [0x44]]]);
testCode([0xBC, 0x33, 0x03], 1, {
x: 3
}, {
cycles: 4,
y: 0x44
});
});
it('should LDA abs,x', function () {
initMemory([[0x03, 0x36, [0x44]]]);
testCode([0xBD, 0x33, 0x03], 1, {
x: 3
}, {
cycles: 4,
a: 0x44
});
});
it('should LDY abs,x with extra cycle on page cross', function () {
initMemory([[0x03, 0x32, [0x44]]]);
testCode([0xBC, 0x33, 0x02], 1, {
x: 0xff
}, {
cycles: 5,
y: 0x44
});
});
it('should LDA abs,x with extra cycle on page cross', function () {
initMemory([[0x03, 0x32, [0x44]]]);
testCode([0xBD, 0x33, 0x02], 1, {
x: 0xff
}, {
cycles: 5,
a: 0x44
});
});
// ********** abs, y
it('should LDX abs,y', function () {
initMemory([[0x03, 0x36, [0x44]]]);
testCode([0xBE, 0x33, 0x03], 1, {
y: 3
}, {
cycles: 4,
x: 0x44
});
});
it('should LDX abs,y with extra cycle on page cross', function () {
initMemory([[0x03, 0x32, [0x44]]]);
testCode([0xBE, 0x33, 0x02], 1, {
y: 0xff
}, {
cycles: 5,
x: 0x44
});
});
});
describe('#write memory', function() {
// ********** zp
it('should STY zp', function () {
testCode([0x84, 0x33], 1, {
y: 0x44
}, {
cycles: 3
});
expectMemory([[0x00, 0x33, [0x44]]]);
});
it('should STA zp', function () {
testCode([0x85, 0x33], 1, {
a: 0x44
}, {
cycles: 3
});
expectMemory([[0x00, 0x33, [0x44]]]);
});
it('should STX zp', function () {
testCode([0x86, 0x33], 1, {
x: 0x44
}, {
cycles: 3
});
expectMemory([[0x00, 0x33, [0x44]]]);
});
// ********** zp,x
it('should STY zp,x', function () {
testCode([0x94, 0x33], 1, {
x: 3,
y: 0x44
}, {
cycles: 4
});
expectMemory([[0x00, 0x36, [0x44]]]);
});
it('should STA zp,x', function () {
testCode([0x95, 0x33], 1, {
a: 0x44,
x: 3
}, {
cycles: 4
});
expectMemory([[0x00, 0x36, [0x44]]]);
});
// ********** zp,y
it('should STX zp,y', function () {
testCode([0x96, 0x33], 1, {
x: 0x44,
y: 3
}, {
cycles: 4
});
expectMemory([[0x00, 0x36, [0x44]]]);
});
// ********** (zp,x)
it('should STA (zp,x)', function () {
initMemory([[0x00, 0x36, [0x33, 0x03]]]);
testCode([0x81, 0x33], 1, {
a: 0x44,
x: 3
}, {
cycles: 6
});
expectMemory([[0x03, 0x33, [0x44]]]);
});
// ********** (zp),y
it('should STA (zp),y', function () {
initMemory([[0x00, 0x33, [0x33, 0x03]]]);
testCode([0x91, 0x33], 1, {
a: 0x44,
y: 3
}, {
cycles: 6
});
expectMemory([[0x03, 0x36, [0x44]]]);
});
// ********** abs
it('should STY abs', function () {
testCode([0x8C, 0x33, 0x03], 1, {
y: 0x44
}, {
cycles: 4
});
expectMemory([[0x03, 0x33, [0x44]]]);
});
it('should STA abs', function () {
testCode([0x8D, 0x33, 0x03], 1, {
a: 0x44
}, {
cycles: 4
});
expectMemory([[0x03, 0x33, [0x44]]]);
});
it('should STX abs', function () {
testCode([0x8E, 0x33, 0x03], 1, {
x: 0x44
}, {
cycles: 4
});
expectMemory([[0x03, 0x33, [0x44]]]);
});
// ********** abs, x
it('should STA abs,x', function () {
testCode([0x9D, 0x33, 0x03], 1, {
a: 0x44,
x: 0x03
}, {
cycles: 5
});
expectMemory([[0x03, 0x36, [0x44]]]);
});
it('should STA abs,x with no extra cycle on page cross', function () {
testCode([0x9D, 0x33, 0x02], 1, {
a: 0x44,
x: 0xff
}, {
cycles: 5,
pc: 0x0403
});
expectMemory([[0x03, 0x32, [0x44]]]);
});
// ********** abs, y
it('should STA abs,y', function () {
testCode([0x99, 0x33, 0x03], 1, {
a: 0x44,
y: 0x03
}, {
cycles: 5
});
expectMemory([[0x03, 0x36, [0x44]]]);
});
it('should STA abs,y with no extra cycle on page cross', function () {
testCode([0x99, 0x33, 0x02], 1, {
a: 0x44,
y: 0xff
}, {
cycles: 5
});
expectMemory([[0x03, 0x32, [0x44]]]);
});
});
describe('#bit operations', function() {
// ********** ASL
it('should ASL A', function () {
testCode([0x0A], 1, {
a: 0x55
}, {
cycles: 2,
a: 0xAA,
s: flags.X | flags.N
});
});
it('should ASL A with carry out', function () {
testCode([0x0A], 1, {
a: 0xAA
}, {
cycles: 2,
a: 0x54,
s: flags.X | flags.C
});
});
it('should ASL abs', function () {
initMemory([[0x03, 0x33, [0x55]]]);
testCode([0x0E, 0x33, 0x03], 1, {
}, {
cycles: 6,
s: flags.X | flags.N
});
expectMemory([[0x03, 0x33, [0xAA]]]);
});
it('should ASL abs with carry out', function () {
initMemory([[0x03, 0x33, [0xAA]]]);
testCode([0x0E, 0x33, 0x03], 1, {
}, {
cycles: 6,
s: flags.X | flags.C
});
expectMemory([[0x03, 0x33, [0x54]]]);
});
// ********** ROL
it('should ROL A', function () {
testCode([0x2A], 1, {
a: 0x55
}, {
cycles: 2,
a: 0xAA,
s: flags.X | flags.N
});
});
it('should ROL A with carry out', function () {
testCode([0x2A], 1, {
a: 0xAA
}, {
cycles: 2,
a: 0x54,
s: flags.X | flags.C
});
});
it('should ROL A with carry in', function () {
testCode([0x2A], 1, {
s: flags.X | flags.C,
a: 0xAA
}, {
cycles: 2,
a: 0x55,
s: flags.X | flags.C
});
});
it('should ROL abs', function () {
initMemory([[0x03, 0x33, [0x55]]]);
testCode([0x2E, 0x33, 0x03], 1, {
}, {
cycles: 6,
s: flags.X | flags.N
});
expectMemory([[0x03, 0x33, [0xAA]]]);
});
it('should ROL abs with carry out', function () {
initMemory([[0x03, 0x33, [0xAA]]]);
testCode([0x2E, 0x33, 0x03], 1, {
}, {
cycles: 6,
s: flags.X | flags.C
});
expectMemory([[0x03, 0x33, [0x54]]]);
});
it('should ROL abs with carry in', function () {
initMemory([[0x03, 0x33, [0xAA]]]);
testCode([0x2E, 0x33, 0x03], 1, {
s: flags.X | flags.C
}, {
cycles: 6,
s: flags.X | flags.C
});
expectMemory([[0x03, 0x33, [0x55]]]);
});
// ********** LSR
it('should LSR A', function () {
testCode([0x4A], 1, {
a: 0xAA
}, {
cycles: 2,
a: 0x55
});
});
it('should LSR A with carry out', function () {
testCode([0x4A], 1, {
a: 0x55
}, {
cycles: 2,
a: 0x2A,
s: flags.X | flags.C
});
});
it('should LSR abs', function () {
initMemory([[0x03, 0x33, [0xAA]]]);
testCode([0x4E, 0x33, 0x03], 1, {
}, {
cycles: 6
});
expectMemory([[0x03, 0x33, [0x55]]]);
});
it('should LSR abs with carry out', function () {
initMemory([[0x03, 0x33, [0x55]]]);
testCode([0x4E, 0x33, 0x03], 1, {
}, {
cycles: 6,
s: flags.X | flags.C
});
expectMemory([[0x03, 0x33, [0x2A]]]);
});
// ********** ROR
it('should ROR A', function () {
testCode([0x6A], 1, {
a: 0xAA
}, {
cycles: 2,
a: 0x55
});
});
it('should ROR A with carry out', function () {
testCode([0x6A], 1, {
a: 0x55
}, {
cycles: 2,
s: flags.X | flags.C,
a: 0x2A
});
});
it('should ROR A with carry in', function () {
testCode([0x6A], 1, {
s: flags.X | flags.C,
a: 0x55
}, {
cycles: 2,
s: flags.X | flags.C | flags.N,
a: 0xAA
});
});
it('should ROR abs', function () {
initMemory([[0x03, 0x33, [0xAA]]]);
testCode([0x6E, 0x33, 0x03], 1, {
}, {
cycles: 6
});
expectMemory([[0x03, 0x33, [0x55]]]);
});
it('should ROR abs with carry out', function () {
initMemory([[0x03, 0x33, [0x55]]]);
testCode([0x6E, 0x33, 0x03], 1, {
}, {
cycles: 6,
s: flags.X | flags.C
});
expectMemory([[0x03, 0x33, [0x2A]]]);
});
it('should ROR abs with carry in', function () {
initMemory([[0x03, 0x33, [0x55]]]);
testCode([0x6E, 0x33, 0x03], 1, {
s: flags.X | flags.C
}, {
cycles: 6,
s: flags.X | flags.C | flags.N
});
expectMemory([[0x03, 0x33, [0xAA]]]);
});
it('should AND', function() {
initMemory([[0x03, 0x33, [0x55]]]);
testCode([0x2D, 0x33, 0x03], 1, {
a: 0xA5
}, {
cycles: 4,
a: 0x05
});
});
it('should ORA', function() {
initMemory([[0x03, 0x33, [0x55]]]);
testCode([0x0D, 0x33, 0x03], 1, {
a: 0xA0
}, {
cycles: 4,
s: flags.X | flags.N,
a: 0xF5
});
});
it('should EOR', function() {
initMemory([[0x03, 0x33, [0x55]]]);
testCode([0x4D, 0x33, 0x03], 1, {
a: 0xA5
}, {
cycles: 4,
s: flags.X | flags.N,
a: 0xF0
});
});
it('should BIT zp', function() {
initMemory([[0x00, 0x33, [0x55]]]);
testCode([0x24, 0x33], 1, {
a: 0x55
}, {
cycles: 3,
s: flags.X | flags.V
});
});
it('should BIT abs', function() {
initMemory([[0x03, 0x33, [0xAA]]]);
testCode([0x2C, 0x33, 0x03], 1, {
}, {
cycles: 4,
s: flags.X | flags.N | flags.Z
});
});
});
describe('#math', function() {
// ********** ADC
it('should ADC', function () {
testCode([0x69, 0x55], 1, {
a: 0x23
}, {
cycles: 2,
a: 0x78,
s: flags.X
});
});
it('should ADC with carry in', function () {
testCode([0x69, 0x55], 1, {
a: 0x23,
s: flags.X | flags.C
}, {
cycles: 2,
a: 0x79,
s: flags.X
});
});
it('should ADC with overflow out', function () {
testCode([0x69, 0x55], 1, {
a: 0x2B
}, {
cycles: 2,
a: 0x80,
s: flags.X | flags.N | flags.V
});
});
it('should ADC with carry out', function () {
testCode([0x69, 0x55], 1, {
a: 0xBB
}, {
cycles: 2,
a: 0x10,
s: flags.X | flags.C
});
});
// ********** ADC BCD
it('should ADC BCD', function () {
testCode([0x69, 0x16], 1, {
s: flags.X | flags.D,
a: 0x25
}, {
cycles: 2,
s: flags.X | flags.D,
a: 0x41
});
});
it('should ADC BCD with carry in', function () {
testCode([0x69, 0x55], 1, {
s: flags.X | flags.D | flags.C,
a: 0x23
}, {
cycles: 2,
s: flags.X | flags.D,
a: 0x79
});
});
it('should ADC BCD with carry out', function () {
testCode([0x69, 0x10], 1, {
s: flags.X | flags.D,
a: 0x91
}, {
cycles: 2,
a: 0x01,
s: flags.X | flags.N | flags.D | flags.C
});
});
// ********** SBC
it('should SBC', function () {
testCode([0xE9, 0x23], 1, {
s: flags.X | flags.C,
a: 0x55
}, {
cycles: 2,
a: 0x32,
s: flags.X | flags.C
});
});
it('should SBC with borrow in', function () {
testCode([0xE9, 0x23], 1, {
s: flags.X,
a: 0x55
}, {
cycles: 2,
a: 0x31,
s: flags.X | flags.C
});
});
it('should SBC with borrow out', function () {
testCode([0xE9, 0x55], 1, {
s: flags.X | flags.C,
a: 0x23
}, {
cycles: 2,
a: 0xCE,
s: flags.X | flags.N
});
});
it('should SBC with overflow out', function () {
testCode([0xE9, 0x7F], 1, {
s: flags.X | flags.C,
a: 0xAF
}, {
cycles: 2,
a: 0x30,
s: flags.X | flags.V | flags.C
});
});
// ********** SBC BCD
it('should SBC BCD', function () {
testCode([0xE9, 0x23], 1, {
s: flags.X | flags.D | flags.C,
a: 0x55
}, {
cycles: 2,
a: 0x32,
s: flags.X | flags.D | flags.C
});
});
it('should SBC BCD with borrow in', function () {
testCode([0xE9, 0x23], 1, {
s: flags.X | flags.D,
a: 0x55
}, {
cycles: 2,
a: 0x31,
s: flags.X | flags.D | flags.C
});
});
it('should SBC BCD with borrow out', function () {
testCode([0xE9, 0x55], 1, {
s: flags.X | flags.D | flags.C,
a: 0x23
}, {
cycles: 2,
a: 0x68,
s: flags.X | flags.N | flags.D
});
});
// ********** INC
it('should INC zp', function() {
initMemory([[0x00, 0x33, [0x44]]]);
testCode([0xE6, 0x33], 1, {
}, {
cycles: 5
});
expectMemory([[0x00, 0x33, [0x45]]]);
});
it('should INC zp,x', function() {
initMemory([[0x00, 0x043, [0x44]]]);
testCode([0xF6, 0x33], 1, {
x: 0x10
}, {
cycles: 6
});
expectMemory([[0x00, 0x43, [0x45]]]);
});
it('should INC abs', function() {
initMemory([[0x03, 0x33, [0x44]]]);
testCode([0xEE, 0x33, 0x03], 1, {
}, {
cycles: 6
});
expectMemory([[0x03, 0x33, [0x45]]]);
});
it('should INC abs,x', function() {
initMemory([[0x03, 0x043, [0x44]]]);
testCode([0xFE, 0x33, 0x03], 1, {
x: 0x10
}, {
cycles: 7
});
expectMemory([[0x03, 0x43, [0x45]]]);
});
// ********** DEC
it('should DEC zp', function() {
initMemory([[0x00, 0x33, [0x44]]]);
testCode([0xC6, 0x33], 1, {
}, {
cycles: 5
});
expectMemory([[0x00, 0x33, [0x43]]]);
});
it('should DEC zp,x', function() {
initMemory([[0x00, 0x043, [0x44]]]);
testCode([0xD6, 0x33], 1, {
x: 0x10
}, {
cycles: 6
});
expectMemory([[0x00, 0x43, [0x43]]]);
});
it('should DEC abs', function() {
initMemory([[0x03, 0x33, [0x44]]]);
testCode([0xCE, 0x33, 0x03], 1, {
}, {
cycles: 6
});
expectMemory([[0x03, 0x33, [0x43]]]);
});
it('should DEC abs,x', function() {
initMemory([[0x03, 0x043, [0x44]]]);
testCode([0xDE, 0x33, 0x03], 1, {
x: 0x10
}, {
cycles: 7
});
expectMemory([[0x03, 0x43, [0x43]]]);
});
});
describe('#comparison', function() {
// ********** CMP
it('should CMP less than', function() {
testCode([0xc9, 0x44], 1, {
a: 0x33
}, {
cycles: 2,
s: flags.X | flags.N
});
});
it('should CMP equal', function() {
testCode([0xc9, 0x44], 1, {
a: 0x44
}, {
cycles: 2,
s: flags.X | flags.Z | flags.C
});
});
it('should CMP greater than', function() {
testCode([0xc9, 0x44], 1, {
a: 0x55
}, {
cycles: 2,
s: flags.X | flags.C
});
});
// ********** CPX
it('should CPX less than', function() {
testCode([0xE0, 0x44], 1, {
x: 0x33
}, {
cycles: 2,
s: flags.X | flags.N
});
});
it('should CPX equal', function() {
testCode([0xE0, 0x44], 1, {
x: 0x44
}, {
cycles: 2,
s: flags.X | flags.Z | flags.C
});
});
it('should CPX greater than', function() {
testCode([0xE0, 0x44], 1, {
x: 0x55
}, {
cycles: 2,
s: flags.X | flags.C
});
});
// ********** CPY
it('should CPY less than', function() {
testCode([0xE0, 0x44], 1, {
y: 0x33
}, {
cycles: 2,
s: flags.X | flags.N
});
});
it('should CPY equal', function() {
testCode([0xc0, 0x44], 1, {
y: 0x44
}, {
cycles: 2,
s: flags.X | flags.Z | flags.C
});
});
it('should CPY greater than', function() {
testCode([0xc0, 0x44], 1, {
y: 0x55
}, {
cycles: 2,
s: flags.X | flags.C
});
});
});
});
describe('65c02', function() {
beforeEach(function() {
cpu = new CPU6502({ flavor: FLAVOR_ROCKWELL_65C02 });
memory = new TestMemory(4);
cpu.addPageHandler(memory);
cpu.addPageHandler(bios);
});
describe('#signals', function() {
it('should clear D on IRQ', function() {
initState({
s: flags.X | flags.D
});
cpu.irq();
expectState(DEFAULT_STATE, {
cycles: 5,
s: flags.X | flags.I,
sp: 0xfc,
pc: 0xff00
});
});
it('should clear D on NMI', function() {
initState({
s: flags.X | flags.D
});
cpu.nmi();
expectState(DEFAULT_STATE, {
cycles: 5,
s: flags.X | flags.I,
sp: 0xfc,
pc: 0xff00
});
});
it('should clear D on BRK', function () {
testCode([0x00, 0x00], 1, {
s: flags.X | flags.D
}, {
cycles: 7,
s: flags.X | flags.I,
sp: 0xfc,
pc: 0xff00
});
});
});
describe('#stack', function() {
it('should PHX', function() {
testCode([0xDA], 1, {
x: 0x44
}, {
cycles: 3,
sp: 0xfe
});
expectStack([0x44]);
});
it('should PLX', function() {
initMemory([[0x01, 0xff, [0x44]]]);
testCode([0xFA], 1, {
sp: 0xfe
}, {
cycles: 4,
x: 0x44,
sp: 0xff
});
});
it('should PHY', function() {
testCode([0x5A], 1, {
y: 0x44
}, {
cycles: 3,
sp: 0xfe
});
expectStack([0x44]);
});
it('should PLY', function() {
initMemory([[0x01, 0xff, [0x44]]]);
testCode([0x7A], 1, {
sp: 0xfe
}, {
cycles: 4,
y: 0x44,
sp: 0xff
});
});
});
describe('#jumps', function() {
it('should JMP (abs)', function () {
initMemory([[0x03, 0x33, [0x34, 0x12]]]);
testCode([0x6C, 0x33, 0x03], 1, {}, {
cycles: 6,
pc: 0x1234
});
});
it('should JMP (abs) across page boundries without bugs', function () {
initMemory([[0x02, 0xFF, [0x34, 0x12]],
[0x02, 0x00, [0xff]]]);
testCode([0x6C, 0xFF, 0x02], 1, {}, {
cycles: 6,
pc: 0x1234
});
});
it('should JMP (abs, x)', function () {
initMemory([[0x03, 0x43, [0x34, 0x12]]]);
testCode([0x7C, 0x33, 0x03], 1, {
x: 0x10
}, {
cycles: 6,
pc: 0x1234
});
});
});
describe('#other addressing mode fixes', function () {
it('should INC abs,x', function() {
initMemory([[0x03, 0x043, [0x44]]]);
testCode([0xFE, 0x33, 0x03], 1, {
x: 0x10
}, {
cycles: 7
});
expectMemory([[0x03, 0x43, [0x45]]]);
});
});
describe('#branches', function() {
it('should BRA forward', function () {
testCode([0x80, 0x7F], 1, {}, {
cycles: 3,
pc: 0x0481
});
});
it('should BRA backward', function () {
testCode([0x80, 0xFF], 1, {}, {
cycles: 3,
pc: 0x0401
});
});
});
describe('#read memory', function() {
// ********** (zp)
it('should LDA (zp)', function () {
initMemory([[0x00, 0x33, [0x33,0x03]],
[0x03, 0x33, [0x44]]]);
testCode([0xB2, 0x33], 1, {}, {
cycles: 5,
a: 0x44
});
});
});
describe('#write memory', function() {
// ********** (zp)
it('should STA (zp)', function () {
initMemory([[0x00, 0x33, [0x33, 0x03]]]);
testCode([0x92, 0x33], 1, {
a: 0x44
}, {
cycles: 5
});
expectMemory([[0x03, 0x33, [0x44]]]);
});
it('should STZ abs', function () {
initMemory([[0x03, 0x33, [0x44]]]);
testCode([0x9C, 0x33, 0x03], 1, {
a: 0x44
}, {
cycles: 4
});
expectMemory([[0x03, 0x33, [0x00]]]);
});
});
describe('#logical operators', function() {
it('should BIT imm and effect other flags', function() {
testCode([0x89, 0x33], 1, {
s: flags.X | flags.N,
a: 0x44
}, {
cycles: 2,
s: flags.X | flags.Z | flags.N
});
});
it('should BIT imm', function() {
testCode([0x89, 0x33], 1, {
a: 0x03
}, {
cycles: 2,
s: flags.X
});
});
// ******** TRB
it('should TRB zp', function() {
initMemory([[0x00, 0x33, [0x55]]]);
testCode([0x14, 0x33], 1, {
a: 0xA5
}, {
cycles: 5
});
expectMemory([[0x00, 0x33, [0x50]]]);
});
it('should TRB abs', function() {
initMemory([[0x03, 0x33, [0x55]]]);
testCode([0x1C, 0x33, 0x03], 1, {
a: 0xAA
}, {
cycles: 6,
s: flags.X | flags.Z
});
expectMemory([[0x00, 0x33, [0x00]]]);
});
// ******** TSB
it('should TSB zp', function() {
initMemory([[0x00, 0x33, [0x55]]]);
testCode([0x04, 0x33], 1, {
a: 0xA5
}, {
cycles: 5
});
expectMemory([[0x00, 0x33, [0xF5]]]);
});
it('should TSB abs', function() {
initMemory([[0x03, 0x33, [0x55]]]);
testCode([0x0C, 0x33, 0x03], 1, {
a: 0xAA
}, {
cycles: 6,
s: flags.X | flags.Z
});
expectMemory([[0x03, 0x33, [0xFF]]]);
});
});
describe('Branch bit set/reset', function () {
// ******** BBR
it('BBR0 should branch if bit 0 clear', function() {
initMemory([[0x00, 0x33, [0xFE]]]);
testCode([0x0F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBR0 should branch backward', function () {
initMemory([[0x00, 0x33, [0xFE]]]);
testCode([0x0F, 0x33, 0xFF], 1, {}, {
cycles: 6,
pc: 0x0402
});
});
it('BBR1 should branch if bit 1 clear', function() {
initMemory([[0x00, 0x33, [0xFD]]]);
testCode([0x1F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBR2 should branch if bit 2 clear', function() {
initMemory([[0x00, 0x33, [0xFB]]]);
testCode([0x2F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBR3 should branch if bit 3 clear', function() {
initMemory([[0x00, 0x33, [0xF7]]]);
testCode([0x3F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBR4 should branch if bit 4 clear', function() {
initMemory([[0x00, 0x33, [0xEF]]]);
testCode([0x4F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBR5 should branch if bit 5 clear', function() {
initMemory([[0x00, 0x33, [0xDF]]]);
testCode([0x5F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBR6 should branch if bit 6 clear', function() {
initMemory([[0x00, 0x33, [0xBF]]]);
testCode([0x6F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBR7 should branch if bit 7 clear', function() {
initMemory([[0x00, 0x33, [0x7F]]]);
testCode([0x7F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBR0 should not branch if bit 0 set', function() {
initMemory([[0x00, 0x33, [0x01]]]);
testCode([0x0F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBR1 should not branch if bit 1 set', function() {
initMemory([[0x00, 0x33, [0x02]]]);
testCode([0x1F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBR2 should not branch if bit 2 set', function() {
initMemory([[0x00, 0x33, [0x04]]]);
testCode([0x2F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBR3 should not branch if bit 3 set', function() {
initMemory([[0x00, 0x33, [0x08]]]);
testCode([0x3F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBR4 should not branch if bit 4 set', function() {
initMemory([[0x00, 0x33, [0x10]]]);
testCode([0x4F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBR5 should not branch if bit 5 set', function() {
initMemory([[0x00, 0x33, [0x20]]]);
testCode([0x5F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBR6 should not branch if bit 6 set', function() {
initMemory([[0x00, 0x33, [0x40]]]);
testCode([0x6F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBR7 should not branch if bit 7 set', function() {
initMemory([[0x00, 0x33, [0x80]]]);
testCode([0x7F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
// ******** BBS
it('BBS0 should branch if bit 0 set', function() {
initMemory([[0x00, 0x33, [0x01]]]);
testCode([0x8F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBS0 should branch backward', function () {
initMemory([[0x00, 0x33, [0x01]]]);
testCode([0x8F, 0x33, 0xFF], 1, {}, {
cycles: 6,
pc: 0x0402
});
});
it('BBS1 should branch if bit 1 set', function() {
initMemory([[0x00, 0x33, [0x02]]]);
testCode([0x9F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBS2 should branch if bit 2 set', function() {
initMemory([[0x00, 0x33, [0x04]]]);
testCode([0xAF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBS3 should branch if bit 3 set', function() {
initMemory([[0x00, 0x33, [0x08]]]);
testCode([0xBF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBS4 should branch if bit 4 set', function() {
initMemory([[0x00, 0x33, [0x10]]]);
testCode([0xCF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBS5 should branch if bit 5 set', function() {
initMemory([[0x00, 0x33, [0x20]]]);
testCode([0xDF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBS6 should branch if bit 6 set', function() {
initMemory([[0x00, 0x33, [0x40]]]);
testCode([0xEF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBS7 should branch if bit 7 set', function() {
initMemory([[0x00, 0x33, [0x80]]]);
testCode([0xFF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0482
});
});
it('BBS0 should not branch if bit 0 clear', function() {
initMemory([[0x00, 0x33, [0xFE]]]);
testCode([0x8F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBS1 should not branch if bit 1 clear', function() {
initMemory([[0x00, 0x33, [0xFD]]]);
testCode([0x9F, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBS2 should not branch if bit 2 clear', function() {
initMemory([[0x00, 0x33, [0xFB]]]);
testCode([0xAF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBS3 should not branch if bit 3 clear', function() {
initMemory([[0x00, 0x33, [0xF7]]]);
testCode([0xBF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBS4 should not branch if bit 4 clear', function() {
initMemory([[0x00, 0x33, [0xEF]]]);
testCode([0xCF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBS5 should not branch if bit 5 clear', function() {
initMemory([[0x00, 0x33, [0xDF]]]);
testCode([0xDF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBS6 should not branch if bit 6 clear', function() {
initMemory([[0x00, 0x33, [0xBF]]]);
testCode([0xEF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
it('BBS7 should not branch if bit 7 clear', function() {
initMemory([[0x00, 0x33, [0x7B]]]);
testCode([0xFF, 0x33, 0x7F], 1, {}, {
cycles: 6,
pc: 0x0403
});
});
});
describe('Bit set/reset', function () {
it('RMB0 should reset bit 0', function() {
initMemory([[0x00, 0x33, [0xFF]]]);
testCode([0x07, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0xFE]]]);
});
it('RMB1 should reset bit 1', function() {
initMemory([[0x00, 0x33, [0xFF]]]);
testCode([0x17, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0xFD]]]);
});
it('RMB2 should reset bit 2', function() {
initMemory([[0x00, 0x33, [0xFF]]]);
testCode([0x27, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0xFB]]]);
});
it('RMB3 should reset bit 3', function() {
initMemory([[0x00, 0x33, [0xFF]]]);
testCode([0x37, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0xF7]]]);
});
it('RMB4 should reset bit 4', function() {
initMemory([[0x00, 0x33, [0xFF]]]);
testCode([0x47, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0xEF]]]);
});
it('RMB5 should reset bit 5', function() {
initMemory([[0x00, 0x33, [0xFF]]]);
testCode([0x57, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0xDF]]]);
});
it('RMB6 should reset bit 6', function() {
initMemory([[0x00, 0x33, [0xFF]]]);
testCode([0x67, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0xBF]]]);
});
it('RMB7 should reset bit 7', function() {
initMemory([[0x00, 0x33, [0xFF]]]);
testCode([0x77, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0x7F]]]);
});
it('SMB0 should set bit 0', function() {
initMemory([[0x00, 0x33, [0x00]]]);
testCode([0x87, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0x01]]]);
});
it('SMB1 should set bit 1', function() {
initMemory([[0x00, 0x33, [0x00]]]);
testCode([0x97, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0x02]]]);
});
it('SMB2 should set bit 2', function() {
initMemory([[0x00, 0x33, [0x00]]]);
testCode([0xA7, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0x04]]]);
});
it('SMB3 should set bit 3', function() {
initMemory([[0x00, 0x33, [0x00]]]);
testCode([0xB7, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0x08]]]);
});
it('SMB4 should set bit 4', function() {
initMemory([[0x00, 0x33, [0x00]]]);
testCode([0xC7, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0x10]]]);
});
it('SMB5 should set bit 5', function() {
initMemory([[0x00, 0x33, [0x00]]]);
testCode([0xD7, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0x20]]]);
});
it('SMB6 should set bit 6', function() {
initMemory([[0x00, 0x33, [0x00]]]);
testCode([0xE7, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0x40]]]);
});
it('SMB7 should set bit 7', function() {
initMemory([[0x00, 0x33, [0x00]]]);
testCode([0xF7, 0x33], 1, {}, {
cycles: 5,
pc: 0x0402
});
expectMemory([[0x00, 0x33, [0x80]]]);
});
});
describe('#math', function() {
// INC A
it('should INC A', function() {
testCode([0x1A], 1, {
a: 0x44
},{
cycles: 2,
a: 0x45
});
});
// DEC A
it('should DEC A', function() {
testCode([0x3A], 1, {
a: 0x44
},{
cycles: 2,
a: 0x43
});
});
});
}); | the_stack |
import type { DataItem } from "../../core/render/Component";
import type { Entity, IEntitySettings } from "../../core/util/Entity";
import type { Color } from "../../core/util/Color";
import { Series, ISeriesSettings, ISeriesDataItem, ISeriesPrivate } from "./Series";
import { Container } from "../../core/render/Container";
import { Label } from "../../core/render/Label";
import { RoundedRectangle } from "../../core/render/RoundedRectangle";
import { Rectangle } from "../../core/render/Rectangle";
import { Template } from "../../core/util/Template";
import { ListTemplate } from "../../core/util/List";
import * as $utils from "../../core/util/Utils";
export interface ILegendDataItem extends ISeriesDataItem {
/**
* [[Container]] element holding all other legend item elements, labels,
* markers, etc.
*/
itemContainer: Container;
/**
* Marker element.
*/
marker: Container;
/**
* Marker rectangle element.
*/
markerRectangle: RoundedRectangle;
/**
* Label element.
*/
label: Label;
/**
* Value label element.
*/
valueLabel: Label;
/**
* Marker fill color.
*/
fill?: Color;
/**
* Marker stroke (outline) color.
*/
stroke?: Color;
/**
* Name of the legend item.
*/
name?: string;
}
export interface ILegendItemSettings extends IEntitySettings {
visible?: boolean;
}
/**
* @ignore
*/
export interface ILegendItem extends Entity {
_settings: ILegendItemSettings;
isHidden?: () => boolean;
show?: () => void;
hide?: () => void;
createLegendMarker?: () => {}
component?: Series;
// how to define that properties of dataItem should have legendDataItem?
}
//type ILegendDataItemSettings = { [K in keyof ILegendDataItem]?: string; };
export interface ILegendSettings extends ISeriesSettings {
/**
* If set to `true` the legend will not try to mimic appearance of the actual
* item but rather show default square marker.
*
* @default false
*/
useDefaultMarker?: boolean;
/**
* A key to look up in data for a name of the data item.
*
*/
nameField?: string;
/**
* A key to look up in data for a fill of the data item.
*
*/
fillField?: string;
/**
* A key to look up in data for a stroke of the data item.
*
*/
strokeField?: string;
/**
* Which legend item element will be clickable to toggle related chart item:
* * `"itemContainer"` - the whole legend item (default).
* * `"marker"` - legend item marker.
* * `"none"` - disables toggling of legend item.
*
* @default "itemContainer"
* @since 5.0.13
*/
clickTarget?: "itemContainer" | "marker" | "none"
}
export interface ILegendPrivate extends ISeriesPrivate {
}
/**
* A universal legend control.
*
* @important
* @see {@link https://www.amcharts.com/docs/v5/concepts/legend/} for more info
*/
export class Legend extends Series {
protected _afterNew() {
this._settings.themeTags = $utils.mergeTags(this._settings.themeTags, ["legend"]);
this.fields.push("name", "stroke", "fill");
super._afterNew();
}
public static className: string = "Legend";
public static classNames: Array<string> = Series.classNames.concat([Legend.className]);
declare public _settings: ILegendSettings;
declare public _privateSettings: ILegendPrivate;
declare public _dataItemSettings: ILegendDataItem;
/**
* List of all [[Container]] elements for legend items.
*
* @default new ListTemplate<Container>
*/
public readonly itemContainers: ListTemplate<Container> = new ListTemplate(
Template.new({}),
() => Container._new(this._root, {
themeTags: $utils.mergeTags(this.itemContainers.template.get("themeTags", []), ["legend", "item"]),
themeTagsSelf: $utils.mergeTags(this.itemContainers.template.get("themeTagsSelf", []), ["itemcontainer"]),
background: Rectangle.new(this._root, {
themeTags: $utils.mergeTags(this.itemContainers.template.get("themeTags", []), ["legend", "item", "background"]),
themeTagsSelf: $utils.mergeTags(this.itemContainers.template.get("themeTagsSelf", []), ["itemcontainer"])
})
}, [this.itemContainers.template])
);
/**
* @ignore
*/
public makeItemContainer(dataItem: DataItem<this["_dataItemSettings"]>): Container {
const itemContainer = this.children.push(this.itemContainers.make());
itemContainer._setDataItem(dataItem);
this.itemContainers.push(itemContainer);
itemContainer.states.create("disabled", {});
return itemContainer;
}
/**
* @ignore
*/
public makeMarker(): Container {
const marker = this.markers.make();
this.markers.push(marker);
marker.states.create("disabled", {});
return marker;
}
/**
* List of legend marker elements.
*
* @default new ListTemplate<Container>
*/
public readonly markers: ListTemplate<Container> = new ListTemplate(
Template.new({}),
() => Container._new(this._root, {
themeTags: $utils.mergeTags(this.markers.template.get("themeTags", []), ["legend", "marker"])
}, [this.markers.template])
);
/**
* @ignore
*/
public makeLabel(): Label {
const label = this.labels.make();
label.states.create("disabled", {});
return label;
}
/**
* List of legend label elements.
*
* @default new ListTemplate<Label>
*/
public readonly labels: ListTemplate<Label> = new ListTemplate(
Template.new({}),
() => Label._new(this._root, {
themeTags: $utils.mergeTags(this.labels.template.get("themeTags", []), ["legend", "label"])
}, [this.labels.template])
);
/**
* @ignore
*/
public makeValueLabel(): Label {
const valueLabel = this.valueLabels.make();
valueLabel.states.create("disabled", {});
return valueLabel;
}
/**
* List of legend value label elements.
*
* @default new ListTemplate<label>
*/
public readonly valueLabels: ListTemplate<Label> = new ListTemplate(
Template.new({}),
() => Label._new(this._root, {
themeTags: $utils.mergeTags(this.valueLabels.template.get("themeTags", []), ["legend", "label", "value"])
}, [this.valueLabels.template])
);
/**
* @ignore
*/
public makeMarkerRectangle(): RoundedRectangle {
const markerRectangle = this.markerRectangles.make();
markerRectangle.states.create("disabled", {});
return markerRectangle;
}
/**
* List of rectangle elements used for default legend markers.
*
* @default new ListTemplate<RoundedRectangle>
*/
public readonly markerRectangles: ListTemplate<RoundedRectangle> = new ListTemplate(
Template.new({}),
() => RoundedRectangle._new(this._root, {
themeTags: $utils.mergeTags(this.markerRectangles.template.get("themeTags", []), ["legend", "marker", "rectangle"])
}, [this.markerRectangles.template])
);
protected processDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
super.processDataItem(dataItem);
const itemContainer = this.makeItemContainer(dataItem);
const nameField = this.get("nameField");
const fillField = this.get("fillField");
const strokeField = this.get("strokeField");
if (itemContainer) {
const clickTarget = this.get("clickTarget", "itemContainer");
const item = dataItem.dataContext as ILegendItem;
if (item && item.set) {
item.set(<any>"legendDataItem", dataItem);
}
itemContainer._setDataItem(dataItem);
dataItem.set("itemContainer", itemContainer);
const marker = this.makeMarker();
if (marker) {
itemContainer.children.push(marker);
marker._setDataItem(dataItem);
dataItem.set("marker", marker);
const useDefaultMarker = this.get("useDefaultMarker");
const markerRectangle = marker.children.push(this.makeMarkerRectangle());
let fill = dataItem.get("fill");
let stroke = dataItem.get("stroke");
dataItem.set("markerRectangle", markerRectangle);
if (item && item.get) {
fill = item.get(fillField as any, fill);
stroke = item.get(strokeField as any, stroke);
}
if (!stroke) {
stroke = fill;
}
if (!useDefaultMarker) {
if (item && item.createLegendMarker) {
item.createLegendMarker();
}
}
markerRectangle.setAll({ fill, stroke });
// this solves if template field is set on slice
const component = item.component;
if (component && component.updateLegendMarker) {
component.updateLegendMarker(item as any);
}
}
const label = this.makeLabel();
if (label) {
itemContainer.children.push(label);
label._setDataItem(dataItem);
dataItem.set("label", label);
label.text.on("text", () => {
itemContainer.set("ariaLabel", label.text._getText() + "; " + this._t("Press ENTER to toggle"));
});
if (item && item.get) {
dataItem.set("name", item.get(nameField as any) as string);
}
let name = dataItem.get("name");
if (name) {
label.set("text", name);
}
}
const valueLabel = this.makeValueLabel();
if (valueLabel) {
itemContainer.children.push(valueLabel);
valueLabel._setDataItem(dataItem);
dataItem.set("valueLabel", valueLabel);
}
if (item && item.show) {
this._disposers.push(item.on("visible", (visible) => {
itemContainer.set("disabled", !visible)
}));
if (!item.get("visible")) {
itemContainer.set("disabled", true);
}
var clickContainer = itemContainer;
this._addHoverEvents(clickContainer, item, dataItem)
if (clickTarget != "none") {
if (clickTarget == "marker") {
clickContainer = marker;
}
this._addClickEvents(clickContainer, item, dataItem)
}
}
}
}
protected _addHoverEvents(container: Container, item: ILegendItem, _dataItem: DataItem<this["_dataItemSettings"]>) {
container.events.on("pointerover", () => {
const component = item.component;
if (component && component.hoverDataItem) {
component.hoverDataItem(item as any)
}
})
container.events.on("pointerout", () => {
const component = item.component;
if (component && component.hoverDataItem) {
component.unhoverDataItem(item as any)
}
})
}
protected _addClickEvents(container: Container, item: ILegendItem, dataItem: DataItem<this["_dataItemSettings"]>) {
container.set("cursorOverStyle", "pointer");
container.events.on("click", () => {
const labelText = dataItem.get("label").text._getText();
if (item.show && item.isHidden && (item.isHidden() || item.get("visible") === false)) {
item.show();
container.set("disabled", false);
this._root.readerAlert(this._t("%1 shown", this._root.locale, labelText));
}
else if (item.hide) {
item.hide();
container.set("disabled", true);
this._root.readerAlert(this._t("%1 hidden", this._root.locale, labelText));
}
})
}
/**
* @ignore
*/
public disposeDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
let itemContainer = dataItem.get("itemContainer");
if (itemContainer) {
this.itemContainers.removeValue(itemContainer);
itemContainer.dispose();
}
let marker = dataItem.get("marker");
if (marker) {
this.markers.removeValue(marker);
marker.dispose();
}
let markerRectangle = dataItem.get("markerRectangle");
if (markerRectangle) {
this.markerRectangles.removeValue(markerRectangle);
markerRectangle.dispose();
}
let label = dataItem.get("label");
if (label) {
this.labels.removeValue(label);
label.dispose();
}
let valueLabel = dataItem.get("valueLabel");
if (valueLabel) {
this.valueLabels.removeValue(valueLabel);
valueLabel.dispose();
}
}
} | the_stack |
import * as toml from '@toml-tools/lexer';
import { IToken } from 'chevrotain';
import { promises as fs } from 'fs';
import * as tomlStringify from '@iarna/toml/stringify';
interface TokenPrimitive {
index: number,
value: boolean | number | string
}
type TokenValue = Map<string, TokenValue> | TokenPrimitive | TokenValue[];
interface FillMap {
type: 'fill map',
map: Map<string, TokenValue>
};
interface FillArray {
type: 'fill array',
array: TokenValue[]
};
interface AssignMapValue {
type: 'assign map value',
map: Map<string, TokenValue>,
key: string
};
interface BeginAssignToMember {
type: 'begin assign to member',
isArray: boolean,
map: Map<string, TokenValue>,
key?: string
};
interface ExpectRSquare {
type: 'expect RSquare'
}
type State = FillMap | FillArray | AssignMapValue | BeginAssignToMember | ExpectRSquare;
/**
* A TOML file where primitive values (booleans, numbers, and strings) can be
* replaced without affecting the overall formatting.
*/
export class TomlFile {
/**
* A tree representation of the file content, where values map to token
* indices.
*/
private valueMap: Map<string, TokenValue>;
/**
* The file in token form.
*/
private tokens: IToken[];
/**
* The original file content.
*/
private source: string;
/**
* A sparse array of substituted values. Each value is indexed by their
* position in the token array.
*/
private substitutions: (boolean | number | string)[] = [];
private constructor(valueMap: Map<string, TokenValue>, tokens: IToken[], source: string) {
this.valueMap = valueMap;
this.tokens = tokens;
this.source = source;
}
/**
* Load a file as an editable TOML file.
*/
static async load(file: string): Promise<TomlFile> {
const source = (await fs.readFile(file)).toString('utf-8');
const [valueMap, tokens] = parseSource(source);
return new TomlFile(valueMap, tokens, source);
}
/**
* Checks if there is a replaceable primitive value at the provided location
* in the hierarchy.
*/
hasPrimitive(path: (string | number)[]): boolean {
let current: TokenValue = this.valueMap;
for (const key of path) {
if (current instanceof Map) {
if (typeof key !== 'string') {
return false;
}
if (!current.has(key)) {
return false;
}
current = current.get(key)!;
} else if (Array.isArray(current)) {
if (typeof key !== 'number') {
return false;
}
if (current[key] === undefined) {
return false;
}
current = current[key];
} else {
return false;
}
}
return !(current instanceof Map) && !Array.isArray(current);
}
/**
* Get the current value at a location in the hierarchy, if it's primitive.
* Throws an exception otherwise, or if it's not found.
*/
getPrimitive(path: (string | number)[]): boolean | string | number {
let current: TokenValue = this.valueMap;
let traversed = '';
for (const key of path) {
if (current instanceof Map) {
if (typeof key !== 'string') {
throw new Error(`expected a string index into ${traversed} but found ${key}`);
}
if (!current.has(key)) {
throw new Error(`${key} does not exist in ${traversed}`);
}
current = current.get(key)!;
traversed = traversed.length ? `${traversed}.${key}` : key;
} else if (Array.isArray(current)) {
if (typeof key !== 'number') {
throw new Error(`expected a number index into ${traversed} but found ${key}`);
}
if (current[key] === undefined) {
throw new Error(`[${key}] does not exist in ${traversed}`);
}
current = current[key];
traversed = `${traversed}[${key}]`;
} else {
throw new Error(`${traversed} is not an object or array`);
}
}
if (!(current instanceof Map) && !Array.isArray(current)) {
return current.value;
} else {
throw new Error(`expected ${traversed} to be a primitive value`)
}
}
/**
* Replace a value at a location in the hierarchy, if it's primitive. Throws
* an exception otherwise, or if it's not found.
*/
setPrimitive(path: (string | number)[], newValue: boolean | string | number) {
let current: TokenValue = this.valueMap;
let traversed = '';
for (const key of path) {
if (current instanceof Map) {
if (typeof key !== 'string') {
throw new Error(`expected a string index into ${traversed} but found ${key}`);
}
if (!current.has(key)) {
throw new Error(`${key} does not exist in ${traversed}`);
}
current = current.get(key)!;
traversed = traversed.length ? `${traversed}.${key}` : key;
} else if (Array.isArray(current)) {
if (typeof key !== 'number') {
throw new Error(`expected a number index into ${traversed} but found ${key}`);
}
if (current[key] === undefined) {
throw new Error(`[${key}] does not exist in ${traversed}`);
}
current = current[key];
traversed = `${traversed}[${key}]`;
} else {
throw new Error(`${traversed} is not an object or array`);
}
}
if (!(current instanceof Map) && !Array.isArray(current)) {
current.value = newValue;
this.substitutions[current.index] = newValue;
} else {
throw new Error(`expected ${traversed} to be a primitive value`)
}
}
/**
* Render the altered file content as a text string, that can be written to
* a file.
*/
render(): string {
let result = '';
let begin = 0;
let end = 0;
for (const [index, token] of this.tokens.entries()) {
if (this.substitutions[index] != undefined) {
result += this.source.substring(begin, token.startOffset);
result += tomlStringify.value(this.substitutions[index])
begin = token.endOffset! + 1;
end = begin;
} else {
end = token.endOffset! + 1;
}
}
if (begin != end) {
result += this.source.substring(begin, end);
}
return result;
}
}
/**
* Parses the file content into a token array and a hierarchy map. It doesn't do
* any detailed validation and mostly assumes the file valid.
*/
function parseSource(source: string): [Map<string, TokenValue>, IToken[]] {
const result = toml.tokenize(source);
const valueMap = new Map();
let stateStack: State[] = [{ type: 'fill map', map: valueMap }];
for (const [index, token] of result.tokens.entries()) {
if (!token.tokenType) {
throw Error(`missing token type for ${token.image}`);
}
const currentState = stateStack[stateStack.length - 1];
switch (token.tokenType.name) {
case 'UnquotedKey':
switch (currentState.type) {
case 'fill map':
stateStack.push({
type: 'assign map value',
map: currentState.map,
key: token.image
});
break;
case 'begin assign to member':
if (currentState.key) {
if (currentState.map.has(currentState.key)) {
const child = currentState.map.get(currentState.key);
if (child instanceof Map) {
currentState.map = child;
} else {
throw Error(`expected ${currentState.key} to be an object`);
}
} else {
const newMap = new Map();
currentState.map.set(currentState.key, newMap);
currentState.map = newMap;
}
}
currentState.key = token.image;
break;
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
case 'True':
switch (currentState.type) {
case 'assign map value':
currentState.map.set(currentState.key, { index, value: true });
stateStack.pop();
break;
case 'fill array':
currentState.array.push({ index, value: true });
break;
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
case 'False':
switch (currentState.type) {
case 'assign map value':
currentState.map.set(currentState.key, { index, value: false });
stateStack.pop();
break;
case 'fill array':
currentState.array.push({ index, value: false });
break;
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
case 'BasicString': {
const stringValue = token.image.substring(1, token.image.length - 1);
switch (currentState.type) {
case 'assign map value':
currentState.map.set(currentState.key, { index, value: stringValue });
stateStack.pop();
break;
case 'fill array':
currentState.array.push({ index, value: stringValue });
break;
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
}
case 'LSquare':
switch (currentState.type) {
case 'fill map':
stateStack = [
{ type: 'fill map', map: valueMap },
{ type: 'begin assign to member', isArray: false, map: valueMap }
];
break;
case 'begin assign to member':
currentState.isArray = true;
break;
case 'assign map value': {
const newArray: TokenValue[] = [];
currentState.map.set(currentState.key, newArray);
stateStack.pop();
stateStack.push({ type: 'fill array', array: newArray });
break;
}
case 'fill array': {
const newArray: TokenValue[] = [];
currentState.array.push(newArray);
stateStack.pop();
stateStack.push({ type: 'fill array', array: newArray });
break;
}
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
case 'RSquare':
switch (currentState.type) {
case 'begin assign to member':
const newMap = new Map();
if (!currentState.key) {
throw Error('expected a key when adding a member');
}
if (currentState.isArray) {
if (!currentState.map.has(currentState.key)) {
currentState.map.set(currentState.key, []);
}
const memberArray = currentState.map.get(currentState.key);
if (!Array.isArray(memberArray)) {
throw Error(`expected ${currentState.key} to be an array`);
}
memberArray.push(newMap);
} else {
currentState.map.set(currentState.key, newMap);
}
stateStack.pop();
stateStack.push({ type: 'fill map', map: newMap });
if (currentState.isArray) {
stateStack.push({ type: 'expect RSquare' });
}
break;
case 'fill array':
case 'expect RSquare':
stateStack.pop();
break;
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
case 'LCurly':
switch (currentState.type) {
case 'assign map value': {
const newMap = new Map();
currentState.map.set(currentState.key, newMap);
stateStack.pop();
stateStack.push({ type: 'fill map', map: newMap });
break;
}
case 'fill array': {
const newMap = new Map();
currentState.array.push(newMap);
stateStack.push({ type: 'fill map', map: newMap });
break;
}
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
case 'RCurly':
switch (currentState.type) {
case 'fill map':
stateStack.pop();
break;
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
case 'Dot':
switch (currentState.type) {
case 'begin assign to member':
break;
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
case 'Comma':
switch (currentState.type) {
case 'fill array':
case 'fill map':
break;
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
case 'KeyValSep':
switch (currentState.type) {
case 'assign map value':
break;
default:
unexpectedTokenError(token.tokenType.name, currentState.type, token);
break;
}
break;
case 'Newline':
case 'Comment':
break;
default:
throw Error(`unexpected token type ${token.tokenType.name}`);
}
}
return [valueMap, result.tokens];
}
/**
* Throw a formatted parse error.
*/
function unexpectedTokenError(tokenType: string, stateType: string, token: IToken) {
throw Error(`unexpected ${tokenType} during ${stateType}: ${token.image}`);
} | the_stack |
import { Inject, Injectable, Optional } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Response, ResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import '../rxjs-operators';
import { ProjectEntity } from '../model/projectEntity';
import { ProjectList } from '../model/projectList';
import { BASE_PATH } from '../variables';
import { Configuration } from '../configuration';
/* tslint:disable:no-unused-variable member-ordering */
@Injectable()
export class ProjectService {
protected basePath = 'https://localhost/v1';
public defaultHeaders: Headers = new Headers();
public configuration: Configuration = new Configuration();
constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
if (configuration) {
this.configuration = configuration;
this.basePath = basePath || configuration.basePath || this.basePath;
}
}
/**
* Create a Project
* Creates an empty Project
* @param name
* @param address
* @param longitude
* @param latitude
* @param meta
*/
public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, extraHttpRequestParams?: any): Observable<ProjectEntity> {
return this.createProjectWithHttpInfo(name, address, longitude, latitude, meta, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Delete a Project
* Returns a Project JSON object
* @param id Project id
*/
public deleteProjectById(id: number, extraHttpRequestParams?: any): Observable<{}> {
return this.deleteProjectByIdWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Get a Project
* Returns a Project JSON object
* @param id Project id
*/
public getProjectById(id: number, extraHttpRequestParams?: any): Observable<ProjectEntity> {
return this.getProjectByIdWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Get project list
* Returns a Project JSON object
* @param page
* @param perPage
* @param kind
* @param q
* @param filter
* @param latitude Valid with kind as location
* @param longitude Valid with kind as location
* @param scope Valid with kind as location, and between 1~9
*/
public getProjectList(page?: number, perPage?: number, kind?: string, q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, extraHttpRequestParams?: any): Observable<ProjectList> {
return this.getProjectListWithHttpInfo(page, perPage, kind, q, filter, latitude, longitude, scope, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Update project
*
* @param id Project id
* @param name User ID
* @param address Address
* @param longitude
* @param latitude
* @param meta
* @param thumbnail Project thumbnail
*/
public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: any, extraHttpRequestParams?: any): Observable<ProjectEntity> {
return this.updateProjectWithHttpInfo(id, name, address, longitude, latitude, meta, thumbnail, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Create a Project
* Creates an empty Project
* @param name
* @param address
* @param longitude
* @param latitude
* @param meta
*/
public createProjectWithHttpInfo(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/projects`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
let formParams = new URLSearchParams();
// to determine the Content-Type header
let consumes: string[] = [
'application/x-www-form-urlencoded'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
headers.set('Content-Type', 'application/x-www-form-urlencoded');
if (name !== undefined) {
formParams.set('name', <any>name);
}
if (address !== undefined) {
formParams.set('address', <any>address);
}
if (longitude !== undefined) {
formParams.set('longitude', <any>longitude);
}
if (latitude !== undefined) {
formParams.set('latitude', <any>latitude);
}
if (meta !== undefined) {
formParams.set('meta', <any>meta);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: formParams.toString(),
search: queryParameters,
responseType: ResponseContentType.Json
});
return this.http.request(path, requestOptions);
}
/**
* Delete a Project
* Returns a Project JSON object
* @param id Project id
*/
public deleteProjectByIdWithHttpInfo(id: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/projects/${id}`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling deleteProjectById.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters,
responseType: ResponseContentType.Json
});
return this.http.request(path, requestOptions);
}
/**
* Get a Project
* Returns a Project JSON object
* @param id Project id
*/
public getProjectByIdWithHttpInfo(id: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/projects/${id}`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getProjectById.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
responseType: ResponseContentType.Json
});
return this.http.request(path, requestOptions);
}
/**
* Get project list
* Returns a Project JSON object
* @param page
* @param perPage
* @param kind
* @param q
* @param filter
* @param latitude Valid with kind as location
* @param longitude Valid with kind as location
* @param scope Valid with kind as location, and between 1~9
*/
public getProjectListWithHttpInfo(page?: number, perPage?: number, kind?: string, q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/projects`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (page !== undefined) {
queryParameters.set('page', <any>page);
}
if (perPage !== undefined) {
queryParameters.set('per_page', <any>perPage);
}
if (kind !== undefined) {
queryParameters.set('kind', <any>kind);
}
if (q !== undefined) {
queryParameters.set('q', <any>q);
}
if (filter !== undefined) {
queryParameters.set('filter', <any>filter);
}
if (latitude !== undefined) {
queryParameters.set('latitude', <any>latitude);
}
if (longitude !== undefined) {
queryParameters.set('longitude', <any>longitude);
}
if (scope !== undefined) {
queryParameters.set('scope', <any>scope);
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
responseType: ResponseContentType.Json
});
return this.http.request(path, requestOptions);
}
/**
* Update project
*
* @param id Project id
* @param name User ID
* @param address Address
* @param longitude
* @param latitude
* @param meta
* @param thumbnail Project thumbnail
*/
public updateProjectWithHttpInfo(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: any, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/projects/${id}`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
let formParams = new URLSearchParams();
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling updateProject.');
}
// to determine the Content-Type header
let consumes: string[] = [
'multipart/form-data'
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
headers.set('Content-Type', 'application/x-www-form-urlencoded');
if (name !== undefined) {
formParams.set('name', <any>name);
}
if (address !== undefined) {
formParams.set('address', <any>address);
}
if (longitude !== undefined) {
formParams.set('longitude', <any>longitude);
}
if (latitude !== undefined) {
formParams.set('latitude', <any>latitude);
}
if (meta !== undefined) {
formParams.set('meta', <any>meta);
}
if (thumbnail !== undefined) {
formParams.set('thumbnail', <any>thumbnail);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: formParams.toString(),
search: queryParameters,
responseType: ResponseContentType.Json
});
return this.http.request(path, requestOptions);
}
} | the_stack |
import { AsAble } from "./ParserData";
import { ConvertingContext } from "./Converter";
import { otherwise } from "./HelpfulActions";
import { getActionFromID } from "./ActionData";
import { glyphs, colors } from "./Data/ShortcutMeta";
import { ArgParser, simpleParse } from "./ArgParser";
import {
extensionInputNameToContentItemClass,
ScPLNameContentItemClass
} from "./Data/TypeClasses";
import { nearestString } from "./nearestString";
export type PreprocessorAction = (
this: AsAble,
cc: ConvertingContext,
...args: AsAble[]
) => void | AsAble;
function glyphAction(this: AsAble, cc: ConvertingContext, iconName?: AsAble) {
if (!iconName) {
throw this.error(cc, "Please provide a glyph name.");
}
if (!iconName.canBeString(cc)) {
throw this.error(cc, "Glyph name must be able to be a string");
}
const glyph =
glyphs[
iconName
.asString(cc)
.toLowerCase()
.replace(/[^a-z]/g, "")
];
if (!glyph) {
throw this.error(
cc,
`Invalid glyph name. Must be one of: ${Object.keys(glyphs)}`
);
}
cc.shortcut.glyph = glyph;
}
const preprocessorActions: {
[key: string]: PreprocessorAction;
} = {
"@set": function(this, cc, ...args: AsAble[]) {
const pres = simpleParse(cc, ["name", "value"], args);
const namea = pres.name;
const value = pres.value;
if (!namea || !value) {
throw this.error(
cc,
"@set must have a name argument and a value argument."
);
}
// sets a variable with name name to value value
let name;
if (!namea.canBePreprocessorVariableName(cc)) {
if (!namea.canBeString(cc)) {
throw namea.error(
cc,
"Must be string or preprocessorvariable, forex: @:myvar or 'myvar'"
);
} else {
name = namea.asString(cc);
}
} else {
name = namea.asPreprocessorVariableName(cc);
}
cc.setParserVariable(name, value.getDeepestRealValue(cc));
},
"@foreach": function(this, cc, ...args: AsAble[]) {
const pres = simpleParse(cc, ["list", "method"], args);
const list = pres.list;
const method = pres.method;
if (!list || !method) {
throw this.error(
cc,
"@foreach must have a list argument and a method argument."
);
}
if (!list.canBeAbleArray(cc)) {
throw list.error(cc, "List must be a list.");
}
if (!method.canBeAction(cc)) {
throw method.error(
cc,
'Method must be action, for example `@{Text "\\(@:repeatitem)"}`'
);
}
list.asAbleArray(cc).forEach(item => {
const newCC = cc.in();
newCC.setParserVariable("repeatitem", item);
method.asAction(newCC);
});
},
"@if": function(this, cc, ...args: AsAble[]) {
const pres = simpleParse(cc, ["condition", "iftrue", "iffalse"], args);
const test = pres.condition;
const method = pres.iftrue;
const elseMethod = pres.iffalse;
if (!test || !method) {
throw this.error(
cc,
"@if must have 2-3 arguments. boolean, @{iftrue} @{iffalse}"
);
}
if (!test.canBeBoolean(cc)) {
throw test.error(cc, "Test must be a boolean.");
}
if (!method.canBeAction(cc)) {
throw method.error(
cc,
'Method must be action, for example `@{Text ""}`'
);
}
if (elseMethod && !elseMethod.canBeAction(cc)) {
throw method.error(
cc,
'Else method must be action, for example `@{Text ""}`'
);
}
if (test.asBoolean(cc)) {
const newCC = cc.in();
method.asAction(newCC);
} else if (elseMethod) {
const newCC = cc.in();
elseMethod.asAction(newCC);
}
},
"@error": function(this, cc, ...args: AsAble[]) {
const pres = simpleParse(cc, ["message"], args);
const message = pres.message;
if (!message) {
throw this.error(
cc,
"@error must have one argument, the error. Forex: @error 'error message'"
);
}
if (!message.canBeString(cc)) {
throw message.error(cc, "Message must be a string");
}
throw this.error(cc, message.asString(cc));
},
"@def": function(this, cc, ...args_: AsAble[]) {
const pres = simpleParse(cc, ["name", "arguments", "body"], args_);
const name = pres.name;
const args = pres.arguments;
const cb = pres.body;
if (!name || !args || !cb) {
throw this.error(
cc,
"@def must have 3 arguments: name, [args...], @{body}"
);
}
if (!name.canBeString(cc)) {
throw name.error(cc, "Name must be a @string");
}
if (!args.canBeArray(cc)) {
throw args.error(cc, "Args must be an array of [argname]");
}
if (!cb.canBeAction(cc)) {
throw args.error(cc, "Cb must be an (action) or @{ of actions }");
}
let nameStr = name.asString(cc).toLowerCase();
if (!nameStr.startsWith("@")) {
nameStr = `@${nameStr}`;
}
const argsArr = args.asArray(cc);
cc.setParserAction(nameStr, function(this, cc, ...args: AsAble[]) {
const newCC = cc.in();
ArgParser<undefined>(
argsArr.map(aa => ({ name: aa, data: undefined })),
(name: { name: string }, value: AsAble) => {
newCC.setParserVariable(name.name, value);
},
(value: AsAble) => {
throw value.error(
cc,
"InputArgs are not yet supported here."
);
},
() => true,
{ args, cc }
);
cb.asAction(newCC);
});
},
"@icon": glyphAction,
"@glyph": glyphAction,
"@color": function(this, cc, ...args: AsAble[]) {
const pres = simpleParse(cc, ["color"], args);
const colorName = pres.color;
if (!colorName) {
throw this.error(cc, "Please provide a color name.");
}
if (!colorName.canBeString(cc)) {
throw this.error(cc, "Color name must be able to be a string");
}
const color =
colors[
colorName
.asString(cc)
.toLowerCase()
.replace(/[^a-z]/g, "")
];
if (!color) {
throw this.error(
cc,
`Invalid color name. Must be one of: ${Object.keys(colors)}`
);
}
cc.shortcut.color = color;
},
"@showinsharesheet": function(this, cc, ...args: AsAble[]) {
const pres = simpleParse(cc, ["when"], args);
const when = pres.when;
if (!when) {
throw this.error(
cc,
"when is required containing a list of times to show in the sharesheet"
);
}
if (!when.canBeAbleArray(cc)) {
throw when.error(cc, "Must be array of when");
}
cc.shortcut.showinsharesheet = when.asAbleArray(cc).map(item => {
if (!item.canBeString(cc)) {
throw item.error(cc, "Must be string");
}
const itemStr = item.asString(cc);
const itemScPLClass = nearestString(itemStr, Object.keys(
extensionInputNameToContentItemClass
) as ScPLNameContentItemClass[]);
if (!itemScPLClass) {
throw item.error(
cc,
`Must be one of ${Object.keys(
extensionInputNameToContentItemClass
).join(", ")}`
);
}
const itemClass =
extensionInputNameToContentItemClass[itemScPLClass];
return itemClass;
});
},
"@showinwidget": function(this, cc, ...args: AsAble[]) {
const pres = simpleParse(cc, ["value"], args);
const setTo = pres.value;
if (!setTo) {
throw this.error(cc, "Please provide a true or false.");
}
if (!setTo.canBeBoolean(cc)) {
throw this.error(cc, "Value must be able to be a boolean");
}
cc.shortcut.showInWidget = setTo.asBoolean(cc);
},
"@importquestion": function(this, cc, ...args: AsAble[]) {
const pres = simpleParse(
cc,
["variable", "question", "defaultvalue"],
args
);
const variable = pres.variable;
const question = pres.question;
const defaultValue = pres.defaultvalue;
if (!variable) {
throw this.error(
cc,
"Variable is required (for example variable=q:myimportquestion)"
);
}
if (!question) {
throw this.error(
cc,
"Question is required (for example question='Pick a number')"
);
}
let varname: string;
if (variable.canBeNameType(cc)) {
const nameType = variable.asNameType(cc);
if (nameType.type !== "q") {
throw variable.error(
cc,
`Variable must be a q:variable (not a ${nameType.type}:variable)`
);
}
varname = nameType.name;
} else if (variable.canBeString(cc)) {
varname = variable.asString(cc);
} else {
throw variable.error(cc, "Must be q:questionname or questionname");
}
if (!question.canBeString(cc)) {
throw question.error(cc, "Must be string");
}
if (defaultValue && !defaultValue.canBeString(cc)) {
throw defaultValue.error(cc, "Must be string");
}
const result = cc.addImportQuestion(
varname,
question.asString(cc),
defaultValue ? defaultValue.asString(cc) : undefined
);
if (!result) {
throw variable.error(
cc,
`Import question named ${varname} already exists and has not been used.`
);
}
},
"@elseif": function(this, cc, ...args) {
const ifAction = cc.peekControlFlow();
if (!ifAction) {
throw this.error(cc, "The @elseif macro requires an if.");
}
// this should never happen shouldn't be testable
/* istanbul ignore if */
if (!ifAction[ifAction.length - 1]) {
throw this.error(
cc,
"The top item of the control flow stack has no items. This should never happen."
);
}
if (
ifAction[ifAction.length - 1].wfaction.id !==
"is.workflow.actions.conditional"
) {
throw this.error(cc, "ElseIf can only be used on an If action.");
// todo also error on the if action.
}
// create otherwise action
const otherwiseAction = otherwise(
{ start: this.start, end: this.end },
ifAction[ifAction.length - 1].uuid
);
cc.add(otherwiseAction);
// create if action
const newIfAction = getActionFromID("is.workflow.actions.conditional");
// this should never happen shouldn't be testable
/* istanbul ignore if */
if (!newIfAction) {
throw this.error(
cc,
"The conditional action does not exist. This should never happen."
);
}
newIfAction.build(cc, this, undefined, ...args);
const added = cc.endControlFlow();
// this should never happen shouldn't be testable
/* istanbul ignore if */
if (!added) {
throw this.error(
cc,
"Adding an if action did not add any control flow. This should never happen."
);
}
ifAction.push({
uuid: added[0].uuid,
number: 0,
wfaction: added[0].wfaction
});
}
};
export default preprocessorActions;
/*
current issue:
if value can be any AsAble, that can't become a class unless you changed all the values everywhere or something
canBeX checks if it has a property and the only way to fake that is have variables be proxies but that stops working
when you use .asString on them
possible "solution": if(instanceof PreprocessorVariable) {preprocessorvariable.getValue()}
*/ | the_stack |
import { UserConfigurationStore } from 'background/stores/global/user-configuration-store';
import { Logger } from 'common/logging/logger';
import { UserConfigMessageCreator } from 'common/message-creators/user-config-message-creator';
import { UserConfigurationStoreData } from 'common/types/store-data/user-configuration-store';
import { AdbWrapper, AdbWrapperFactory, DeviceInfo } from 'electron/platform/android/adb-wrapper';
import { DeviceConfig } from 'electron/platform/android/device-config';
import { AdbWrapperHolder } from 'electron/platform/android/setup/adb-wrapper-holder';
import { DeviceConfigurator } from 'electron/platform/android/setup/android-device-configurator';
import { DeviceConfiguratorFactory } from 'electron/platform/android/setup/android-device-configurator-factory';
import { LiveAndroidSetupDeps } from 'electron/platform/android/setup/live-android-setup-deps';
import { IMock, Mock, MockBehavior, Times } from 'typemoq';
describe('LiveAndroidSetupDeps', () => {
const expectedAdbLocation = 'Expected ADB location';
let deviceConfigFactoryMock: IMock<DeviceConfiguratorFactory>;
let deviceConfigMock: IMock<DeviceConfigurator>;
let configStoreMock: IMock<UserConfigurationStore>;
let configMessageCreatorMock: IMock<UserConfigMessageCreator>;
let loggerMock: IMock<Logger>;
let adbWrapperFactoryMock: IMock<AdbWrapperFactory>;
let adbWrapperHolderMock: IMock<AdbWrapperHolder>;
let adbWrapperStub: AdbWrapper;
let testSubject: LiveAndroidSetupDeps;
beforeEach(() => {
deviceConfigFactoryMock = Mock.ofType<DeviceConfiguratorFactory>(
undefined,
MockBehavior.Strict,
);
deviceConfigMock = Mock.ofType<DeviceConfigurator>(undefined, MockBehavior.Strict);
configStoreMock = Mock.ofType<UserConfigurationStore>(undefined, MockBehavior.Strict);
configMessageCreatorMock = Mock.ofType<UserConfigMessageCreator>(
undefined,
MockBehavior.Strict,
);
loggerMock = Mock.ofType<Logger>();
adbWrapperFactoryMock = Mock.ofType<AdbWrapperFactory>(undefined, MockBehavior.Strict);
adbWrapperHolderMock = Mock.ofType<AdbWrapperHolder>(undefined, MockBehavior.Strict);
adbWrapperStub = {} as AdbWrapper;
testSubject = new LiveAndroidSetupDeps(
deviceConfigFactoryMock.object,
configStoreMock.object,
configMessageCreatorMock.object,
loggerMock.object,
adbWrapperFactoryMock.object,
adbWrapperHolderMock.object,
);
});
function verifyAllMocks(): void {
deviceConfigFactoryMock.verifyAll();
deviceConfigMock.verifyAll();
configStoreMock.verifyAll();
configMessageCreatorMock.verifyAll();
}
async function initializeServiceConfig(): Promise<boolean> {
const stateData = { adbLocation: expectedAdbLocation } as UserConfigurationStoreData;
configStoreMock
.setup(m => m.getState())
.returns(() => stateData)
.verifiable(Times.once());
adbWrapperFactoryMock
.setup(m => m.createValidatedAdbWrapper(expectedAdbLocation))
.returns(() => Promise.resolve(adbWrapperStub));
adbWrapperHolderMock.setup(m => m.setAdb(adbWrapperStub)).verifiable();
deviceConfigFactoryMock
.setup(m => m.getDeviceConfigurator(adbWrapperStub))
.returns(() => deviceConfigMock.object)
.verifiable(Times.once());
return await testSubject.hasAdbPath();
}
it('hasAdbPath returns false on error', async () => {
configStoreMock
.setup(m => m.getState())
.throws(new Error('Threw during hasAdbPath'))
.verifiable(Times.once());
const success: boolean = await testSubject.hasAdbPath();
expect(success).toBe(false);
verifyAllMocks();
});
it('hasAdbPath chains and returns true on success', async () => {
const success: boolean = await initializeServiceConfig();
expect(success).toBe(true);
verifyAllMocks();
});
it('setAdbPath chains to UserConfigMessageCreator', () => {
configMessageCreatorMock
.setup(m => m.setAdbLocation(expectedAdbLocation))
.verifiable(Times.once());
testSubject.setAdbPath(expectedAdbLocation);
verifyAllMocks();
});
it('getDevices returns info from service configurator', async () => {
const expectedDevices: DeviceInfo[] = [
{
id: 'emulator1',
isEmulator: true,
friendlyName: 'an emulator',
},
{
id: 'phone123',
isEmulator: false,
friendlyName: 'a device',
},
];
deviceConfigMock
.setup(m => m.getConnectedDevices())
.returns(() => Promise.resolve(expectedDevices))
.verifiable(Times.once());
await initializeServiceConfig();
const actualDevices = await testSubject.getDevices();
expect(actualDevices).toBe(expectedDevices);
verifyAllMocks();
});
it('setSelectedDeviceId chains to service configurator', async () => {
const expectedDeviceId: string = 'abc-123';
deviceConfigMock.setup(m => m.setSelectedDevice(expectedDeviceId)).verifiable(Times.once());
await initializeServiceConfig();
testSubject.setSelectedDeviceId(expectedDeviceId);
verifyAllMocks();
});
it('hasExpectedServiceVersion returns false on error', async () => {
deviceConfigMock
.setup(m => m.hasRequiredServiceVersion())
.throws(new Error('Threw during hasExpectedServiceVersion'))
.verifiable(Times.once());
await initializeServiceConfig();
const success = await testSubject.hasExpectedServiceVersion();
expect(success).toBe(false);
verifyAllMocks();
});
it('hasExpectedServiceVersion returns false if service configurator returns false', async () => {
deviceConfigMock
.setup(m => m.hasRequiredServiceVersion())
.returns(() => Promise.resolve(false))
.verifiable(Times.once());
await initializeServiceConfig();
const success = await testSubject.hasExpectedServiceVersion();
expect(success).toBe(false);
verifyAllMocks();
});
it('hasExpectedServiceVersion returns true if service configurator returns true', async () => {
deviceConfigMock
.setup(m => m.hasRequiredServiceVersion())
.returns(() => Promise.resolve(true))
.verifiable(Times.once());
await initializeServiceConfig();
const success = await testSubject.hasExpectedServiceVersion();
expect(success).toBe(true);
verifyAllMocks();
});
it('installService returns false on error', async () => {
deviceConfigMock
.setup(m => m.installRequiredServiceVersion())
.throws(new Error('Threw during installService'))
.verifiable(Times.once());
await initializeServiceConfig();
const success = await testSubject.installService();
expect(success).toBe(false);
verifyAllMocks();
});
it('installService returns true on success', async () => {
deviceConfigMock
.setup(m => m.installRequiredServiceVersion())
.returns(() => Promise.resolve())
.verifiable(Times.once());
await initializeServiceConfig();
const success = await testSubject.installService();
expect(success).toBe(true);
verifyAllMocks();
});
it('hasExpectedPermissions returns false on error', async () => {
deviceConfigMock
.setup(m => m.hasRequiredPermissions())
.throws(new Error('Threw during hasExpectedPermissions'))
.verifiable(Times.once());
await initializeServiceConfig();
const success = await testSubject.hasExpectedPermissions();
expect(success).toBe(false);
verifyAllMocks();
});
it('hasExpectedPermissions returns false if service configurator returns false', async () => {
deviceConfigMock
.setup(m => m.hasRequiredPermissions())
.returns(() => Promise.resolve(false))
.verifiable(Times.once());
await initializeServiceConfig();
const success = await testSubject.hasExpectedPermissions();
expect(success).toBe(false);
verifyAllMocks();
});
it('hasExpectedPermissions returns true if service configurator returns true', async () => {
deviceConfigMock
.setup(m => m.hasRequiredPermissions())
.returns(() => Promise.resolve(true))
.verifiable(Times.once());
await initializeServiceConfig();
const success = await testSubject.hasExpectedPermissions();
expect(success).toBe(true);
verifyAllMocks();
});
it('grantOverlayPermission catches thrown errors', async () => {
// This test has the side effect of ensuring grantOverlayPermission is called
// So there is no need for a separate test.
deviceConfigMock
.setup(m => m.grantOverlayPermission())
.throws(new Error('Threw during grantOverlayPermission'))
.verifiable(Times.once());
await initializeServiceConfig();
await testSubject.grantOverlayPermission();
verifyAllMocks();
});
it('fetchDeviceConfig returns info from configurator', async () => {
const testConfig: DeviceConfig = {
deviceName: 'test-device',
appIdentifier: 'test-identifier',
};
deviceConfigMock
.setup(m => m.fetchDeviceConfig())
.returns(() => Promise.resolve(testConfig))
.verifiable(Times.once());
await initializeServiceConfig();
const config = await testSubject.fetchDeviceConfig();
expect(config).toEqual(testConfig);
verifyAllMocks();
});
it('fetchDeviceConfig catches thrown errors', async () => {
const expectedError = 'error thrown in configurator';
await initializeServiceConfig();
deviceConfigMock
.setup(m => m.fetchDeviceConfig())
.throws(new Error(expectedError))
.verifiable(Times.once());
await expect(testSubject.fetchDeviceConfig()).rejects.toThrow(expectedError);
verifyAllMocks();
});
}); | the_stack |
import * as bolt from '../bolt';
let parse = bolt.parse;
import * as generator from '../rules-generator';
import * as ast from '../ast';
import * as fileio from '../file-io';
import * as logger from '../logger';
import * as helper from './test-helper';
import {samples} from './sample-files';
import * as chai from 'chai';
chai.config.truncateThreshold = 1000;
let assert = chai.assert;
// TODO: Test duplicated function, and schema definitions.
// TODO: Test other parser errors - appropriate messages (exceptions).
suite("Rules Generator Tests", function() {
suite("Basic Samples", function() {
var tests = [
{ data: "path / {read() { true } write() { true }}",
expect: { rules: {".read": "true", ".write": "true"} }
},
{ data: "path / { write() { true }}",
expect: { rules: {".write": "true"} }
},
{ data: "path / { create() { true }}",
expect: { rules: {".write": "data.val() == null"} }
},
{ data: "path / { update() { true }}",
expect: { rules: {".write": "(data.val() != null && newData.val() != null)"} }
},
{ data: "path / { delete() { true }}",
expect: { rules: {".write": "(data.val() != null && newData.val() == null)"} }
},
{ data: "path / {read() { true }}",
expect: { rules: {".read": "true"} }
},
{ data: "path / { read() { false }}",
expect: { rules: {} }
},
{ data: "path / {index() { return ['a', 'b']; }}",
expect: { rules: {".indexOn": ["a", "b"]} }
},
{ data: "path / { validate() { return this > 0; }}",
expect: { rules: { ".validate": "newData.val() > 0" } }
},
];
helper.dataDrivenTest(tests, function(data, expect) {
var result = parse(data);
assert.ok(result);
var gen = new bolt.Generator(result);
var json = gen.generateRules();
assert.deepEqual(json, expect);
});
});
suite("Sample files", function() {
helper.dataDrivenTest(samples, function(filename) {
filename = 'samples/' + filename + '.' + bolt.FILE_EXTENSION;
return fileio.readFile(filename)
.then(function(response) {
var result = parse(response.content);
assert.ok(result, response.url);
var gen = new bolt.Generator(result);
var json = gen.generateRules();
assert.ok('rules' in json, response.url + " has rules");
return fileio.readJSONFile(response.url.replace('.' + bolt.FILE_EXTENSION, '.json'))
.then(function(response2) {
assert.deepEqual(json, response2);
});
})
.catch(function(error) {
assert.ok(false, error.message);
});
});
});
suite("Partial evaluation", function() {
var tests = [
{ f: "function f(a) { return true == a; }", x: "f(a == b)", expect: "true == (a == b)" },
{ f: "function f(a) { return a == true; }", x: "f(a == b)", expect: "a == b == true" },
{ f: "function f(a) { return a + 3; }", x: "f(1 + 2)", expect: "1 + 2 + 3" },
{ f: "function f(a) { return a + 3; }", x: "f(1 * 2)", expect: "1 * 2 + 3" },
{ f: "function f(a) { return a * 3; }", x: "f(1 + 2)", expect: "(1 + 2) * 3" },
{ f: "function f(a) { return a + 1; }", x: "f(a + a)", expect: "a + a + 1" },
{ f: "function f(a) { return g(a); } function g(a) { return a == true; }",
x: "f(123)", expect: "123 == true" },
{ f: "function f(a, b) { return g(a) == g(b); } function g(a) { return a == true; }",
x: "f(1, 2)", expect: "1 == true == (2 == true)" },
// Highler level function works as long as returns a constant function
{ f: "function f() { return g; } function g(a) { return a == true; }",
x: "f()(123)", expect: "123 == true" },
{ f: "function f(a) { return a + 1; }", x: "a[f(123)]", expect: "a[123 + 1]" },
{ f: "", x: "this", expect: "newData.val() == true" },
{ f: "", x: "!this", expect: "!(newData.val() == true)" },
{ f: "", x: "this.prop", expect: "newData.child('prop').val() == true" },
{ f: "", x: "!this.prop", expect: "!(newData.child('prop').val() == true)" },
{ f: "", x: "this.foo.parent()", expect: "newData.child('foo').parent().val() == true" },
{ f: "",
x: "this.foo || this.bar",
expect: "(newData.child('foo').val() == true || newData.child('bar').val() == true)"},
// TODO: Don't support snapshot functions beyond parent.
// TODO: Should warn user not to use Firebase builtins!
// { f: "", x: "this.isString()", expect: "newData.child('isString').val() == true" },
{ f: "function f(a) { return a == '123'; }", x: "f(this)", expect: "newData.val() == '123'" },
{ f: "function f(a) { return a == '123'; }",
x: "f(this.foo)", expect: "newData.child('foo').val() == '123'" },
];
helper.dataDrivenTest(tests, function(data, expect) {
var symbols = parse(data.f + " path /x { write() { return " + data.x + "; }}");
var gen = new bolt.Generator(symbols);
// Make sure local Schema initialized.
var json = <any> gen.generateRules();
assert.equal(json['rules']['x']['.write'], expect);
});
});
suite("String methods", function() {
var tests = [
{ data: "this.length",
expect: "newData.val().length" },
{ data: "this.length < 100",
expect: "newData.val().length < 100" },
{ data: "'abc'.length",
expect: "'abc'.length" },
{ data: "'abc'.includes('b')",
expect: "'abc'.contains('b')" },
{ data: "this.includes('b')",
expect: "newData.val().contains('b')" },
{ data: "'abc'.includes(this)",
expect: "'abc'.contains(newData.val())" },
{ data: "'abc'.startsWith(this)",
expect: "'abc'.beginsWith(newData.val())" },
{ data: "'abc'.endsWith(this)",
expect: "'abc'.endsWith(newData.val())" },
{ data: "'abc'.replace(this.a, this.b)",
expect: "'abc'.replace(newData.child('a').val(), newData.child('b').val())" },
{ data: "'ABC'.toLowerCase()",
expect: "'ABC'.toLowerCase()" },
{ data: "'abc'.toUpperCase()",
expect: "'abc'.toUpperCase()" },
{ data: "this.toUpperCase()",
expect: "newData.val().toUpperCase()" },
{ data: "'ababa'.test(/bab/)",
expect: "'ababa'.matches(/bab/)" },
];
helper.dataDrivenTest(tests, function(data, expect) {
var symbols = parse("path /x { write() { return " + data + "; }}");
var gen = new bolt.Generator(symbols);
// Make sure local Schema initialized.
var json = <any> gen.generateRules();
assert.equal(json['rules']['x']['.write'], expect);
});
});
suite("Builtin validation functions", function() {
var tests = [
[ 'String', 'this.isString()'],
[ 'Number', 'this.isNumber()'],
[ 'Boolean', 'this.isBoolean()'],
[ 'Object', 'this.hasChildren()'],
[ 'Null', 'false'],
];
helper.dataDrivenTest(tests, function(data, expect) {
var symbols = parse("path / {}");
var gen = new bolt.Generator(symbols);
gen.ensureValidator(ast.typeType(data));
var terms = <ast.Exp[]> gen.validators[data]['.validate'];
var result = bolt.decodeExpression(ast.andArray(terms));
assert.deepEqual(result, expect);
});
});
suite("Schema Validation", function() {
var tests = [
{ data: "type T {}",
expect: undefined },
{ data: "type T extends Object {}",
expect: {'.validate': "newData.hasChildren()"} },
{ data: "type T extends String {}",
expect: {'.validate': "newData.isString()"} },
{ data: "type T extends String { validate() { return this.length > 0; } }",
expect: {'.validate': "(newData.isString() && newData.val().length > 0)"} },
{ data: "type NonEmpty extends String { validate() { return this.length > 0; } } \
type T { prop: NonEmpty }",
expect: {'.validate': "newData.hasChildren(['prop'])",
prop: {
'.validate': '(newData.isString() && newData.val().length > 0)'
},
'$other': {'.validate': "false"}
} },
{ data: "type T {n: Number}",
expect: {'.validate': "newData.hasChildren(['n'])",
n: {'.validate': "newData.isNumber()"},
'$other': {'.validate': "false"}} },
{ data: "type T {s: String}",
expect: {'.validate': "newData.hasChildren(['s'])",
s: {'.validate': "newData.isString()"},
'$other': {'.validate': "false"}} },
{ data: "type T {b: Boolean}",
expect: {'.validate': "newData.hasChildren(['b'])",
b: {'.validate': "newData.isBoolean()"},
'$other': {'.validate': "false"}} },
{ data: "type T {x: Object}",
expect: {'.validate': "newData.hasChildren(['x'])",
x: {'.validate': "newData.hasChildren()"},
'$other': {'.validate': "false"}} },
{ data: "type T {x: Number|String}",
expect: {'.validate': "newData.hasChildren(['x'])",
x: {'.validate': "(newData.isNumber() || newData.isString())"},
'$other': {'.validate': "false"}} },
{ data: "type T { $key: Number }",
expect: {'.validate': "newData.hasChildren()",
'$key': {'.validate': "newData.isNumber()"}} },
{ data: "type T { 'a b': Number }",
expect: {'.validate': "newData.hasChildren(['a b'])",
'a b': {'.validate': "newData.isNumber()"},
'$other': {'.validate': 'false'}} },
{ data: "type T {a: Number, b: String}",
expect: {'.validate': "newData.hasChildren(['a', 'b'])",
a: {'.validate': "newData.isNumber()"},
b: {'.validate': "newData.isString()"},
'$other': {'.validate': "false"}} },
{ data: "type T {x: Number|Null}",
expect: {'.validate': "newData.hasChildren()",
x: {'.validate': "newData.isNumber()"},
'$other': {'.validate': "false"}} },
{ data: "type T {n: Number, validate() {return this.n < 7;}}",
expect: {'.validate': "(newData.hasChildren(['n']) && newData.child('n').val() < 7)",
n: {'.validate': "newData.isNumber()"},
'$other': {'.validate': "false"}} },
{ data: "type Bigger extends Number {validate() { return this > prior(this); }}" +
"type T { ts: Bigger }",
expect: {'.validate': "newData.hasChildren(['ts'])",
ts: {'.validate': "(newData.isNumber() && newData.val() > data.val())"},
'$other': {'.validate': "false"}} },
{ data: "type T {a: String, b: String, c: String}",
expect: {'.validate': "newData.hasChildren(['a', 'b', 'c'])",
a: {'.validate': "newData.isString()"},
b: {'.validate': "newData.isString()"},
c: {'.validate': "newData.isString()"},
'$other': {'.validate': "false"}} },
{ data: "type B { foo: Number } type T extends B { bar: String }",
expect: {'.validate': "newData.hasChildren(['foo', 'bar'])",
foo: {'.validate': "newData.isNumber()"},
bar: {'.validate': "newData.isString()"},
'$other': {'.validate': "false"}} },
{ data: "type T {n: Number, x: Map<String, Number>}",
expect: {'.validate': "newData.hasChildren(['n'])",
n: {'.validate': "newData.isNumber()"},
x: {'$key1': {'.validate': "newData.isNumber()"},
'.validate': "newData.hasChildren()" },
'$other': {'.validate': "false"}} },
{ data: "type T {x: Map<String, Number>}",
expect: {'.validate': "newData.hasChildren()",
x: {'$key1': {'.validate': "newData.isNumber()"},
'.validate': "newData.hasChildren()" },
'$other': {'.validate': "false"}} },
{ data: "type SmallString extends String { validate() { this.length < 32 } } " +
"type T {x: Map<SmallString, Number>}",
expect: {'.validate': "newData.hasChildren()",
x: {'$key1': {'.validate': "($key1.length < 32 && newData.isNumber())"},
'.validate': "newData.hasChildren()" },
'$other': {'.validate': "false"}} },
{ data: "type M extends Map<String, Number>; type T { x: M }",
expect: {'.validate': "newData.hasChildren()",
'$other': {'.validate': "false"},
'x': {'$key1': {'.validate': "newData.isNumber()"},
'.validate': "newData.hasChildren()" }} },
{ data: "type Pair<X, Y> { first: X, second: Y } type T extends Pair<String, Number>;",
expect: {'.validate': "newData.hasChildren(['first', 'second'])",
'first': {'.validate': "newData.isString()"},
'second': {'.validate': "newData.isNumber()"},
'$other': {'.validate': "false"}} },
{ data: "type X { a: Number, validate() { this.a == key() } } type T extends X[];",
expect: {'$key1': {'.validate': "(newData.hasChildren(['a']) && newData.child('a').val() == $key1)",
'a': {'.validate': "newData.isNumber()"},
'$other': {'.validate': "false"}},
'.validate': "newData.hasChildren()"
} },
{ data: "type X { a: Number, validate() { this.a == key() } } type T { x: X }",
expect: {'x': {'.validate': "(newData.hasChildren(['a']) && newData.child('a').val() == 'x')",
'a': {'.validate': "newData.isNumber()"},
'$other': {'.validate': "false"}},
'$other': {'.validate': "false"},
'.validate': "newData.hasChildren(['x'])"
} },
{ data: "type T extends String { validate() { root == 'new' && prior(root) == 'old' } }" +
"path /t/x is Any { read() { root == 'old' } }",
expect: {'.validate': "((newData.isString() && newData.parent().val() == 'new') && root.val() == 'old')",
'x': {'.read': "root.val() == 'old'"}
} },
];
helper.dataDrivenTest(tests, function(data, expect) {
var symbols = parse(data + " path /t is T;");
var gen = new bolt.Generator(symbols);
var rules = gen.generateRules();
if (expect === undefined) {
assert.deepEqual(rules, {"rules": {}});
} else {
assert.deepEqual(rules, {"rules": {t: expect}});
}
});
});
suite("extendValidator", function() {
var tests = [
{ data: {target: {}, src: {}},
expect: {} },
{ data: {target: {}, src: {'.x': [1]}},
expect: {'.x': [1]} },
{ data: {target: {'.x': [1]}, src: {'.x': [2]}},
expect: {'.x': [1, 2]} },
{ data: {target: {'.x': [1]}, src: {'.x': [2], c: {'.x': [3]}}},
expect: {'.x': [1, 2], c: {'.x': [3]}} },
{ data: {target: {'.x': [1], c: {'.x': [2]}}, src: {c: {'.x': [3]}}},
expect: {'.x': [1], c: {'.x': [2, 3]}} },
{ data: {target: {}, src: {a: {b: {c: {d: {'.x': [1], e: {'.x': [2]}}}}}}},
expect: {a: {b: {c: {d: {'.x': [1], e: {'.x': [2]}}}}}} },
];
helper.dataDrivenTest(tests, function(data, expect) {
generator.extendValidator(data.target, data.src);
assert.deepEqual(data.target, expect);
});
});
suite("mapValidator", function() {
var tests = [
{ data: {'.x': 'a'}, expect: {'.x': 'a+'} },
{ data: {'.x': 'b'}, expect: {} },
];
helper.dataDrivenTest(tests, function(data, expect) {
generator.mapValidator(data, function(value, prop) {
if (value === 'b') {
return undefined;
}
return value + '+';
});
assert.deepEqual(data, expect);
});
});
suite("Schema Generation Errors", function() {
var tests = [
{ data: "",
expect: /at least one path/ },
{ data: "type Simple extends String {a: String} path /x is Simple;",
expect: /properties.*extend/ },
{ data: "path /y { index() { return 1; }}",
expect: /index.*string/i },
{ data: "path /x { write() { return undefinedFunc(); }}",
expect: /undefined.*function/i },
{ data: "path /x is NoSuchType {}",
expect: /No type.*NoSuchType/ },
{ data: "path /x { unsupported() { true } }",
warn: /unsupported method/i },
{ data: "path /x { validate() { return this.test(123); } }",
expect: /convert value/i },
{ data: "path /x { validate() { return this.test('a/'); } }",
expect: /convert value/i },
{ data: "path /x { validate() { return this.test('/a/'); } }",
expect: /convert value/i },
{ data: "function f(a) { return f(a); } path / { validate() { return f(1); }}",
expect: /recursive/i },
{ data: "type X { $n: Number, $s: String } path / is X;",
expect: /wild property/ },
{ data: "type X { $$n: Number } path / is X;",
expect: /property names/i },
{ data: "type X { '\x01': Number } path / is X;",
expect: /property names/i },
{ data: "path / is Map;",
expect: /No type.*non-generic/ },
{ data: "type Pair<X, Y> {a: X, b: Y} path / is Pair;",
expect: /No type.*non-generic/ },
{ data: "path / is String<Number>;",
expect: /No type.*generic/ },
{ data: "path / is Map<Object, Number>;",
expect: /must derive from String/ },
{ data: "path / { write() { true } create() { true } }",
expect: /write-aliasing.*create/i },
{ data: "path / { write() { true } update() { true } }",
expect: /write-aliasing.*update/i },
{ data: "path / { write() { true } delete() { true } }",
expect: /write-aliasing.*delete/i },
];
helper.dataDrivenTest(tests, function(data, expect, t) {
logger.reset();
logger.silent();
let symbols = parse(data);
let gen = new bolt.Generator(symbols);
let lastError: string;
try {
gen.generateRules();
} catch (e) {
if (!expect) {
throw e;
}
lastError = logger.getLastMessage() || e.message;
assert.match(lastError, expect);
return;
}
if (expect) {
assert.fail(undefined, undefined, "No exception thrown.");
}
if (t.warn) {
assert.match(logger.getLastMessage(), t.warn);
}
});
});
}); | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_invoicelinetransaction_Information {
interface tab__116CED9D_22A3_4B70_BFBF_9021372780B7_Sections {
BillingSection: DevKit.Controls.Section;
GeneralSection: DevKit.Controls.Section;
ProjectSection: DevKit.Controls.Section;
QuantitySection: DevKit.Controls.Section;
}
interface tab_CorrectionTab_Sections {
tab_3_section_1: DevKit.Controls.Section;
}
interface tab_HiddenFieldsTab_Sections {
tab_2_section_1: DevKit.Controls.Section;
}
interface tab__116CED9D_22A3_4B70_BFBF_9021372780B7 extends DevKit.Controls.ITab {
Section: tab__116CED9D_22A3_4B70_BFBF_9021372780B7_Sections;
}
interface tab_CorrectionTab extends DevKit.Controls.ITab {
Section: tab_CorrectionTab_Sections;
}
interface tab_HiddenFieldsTab extends DevKit.Controls.ITab {
Section: tab_HiddenFieldsTab_Sections;
}
interface Tabs {
_116CED9D_22A3_4B70_BFBF_9021372780B7: tab__116CED9D_22A3_4B70_BFBF_9021372780B7;
CorrectionTab: tab_CorrectionTab;
HiddenFieldsTab: tab_HiddenFieldsTab;
}
interface Body {
Tab: Tabs;
/** Select the customer who this invoice will be sent to. */
msdyn_AccountCustomer: DevKit.Controls.Lookup;
/** Enter the amount on the transaction. */
msdyn_Amount: DevKit.Controls.Money;
/** Select the name of the amount calculation method. */
msdyn_AmountMethod: DevKit.Controls.OptionSet;
msdyn_BasisQuantity: DevKit.Controls.Decimal;
/** Select whether this transaction will be charged to the customer or not. Only chargeable transactions will add to the invoice total */
msdyn_BillingType: DevKit.Controls.OptionSet;
/** Shows the resource. */
msdyn_bookableresource: DevKit.Controls.Lookup;
/** Select the customer who this invoice will be sent to. */
msdyn_ContactCustomer: DevKit.Controls.Lookup;
/** Indicates if this transaction is correcting a previous transaction. */
msdyn_Correction: DevKit.Controls.Boolean;
/** Select whether the customer was a account or a contact */
msdyn_CustomerType: DevKit.Controls.OptionSet;
/** Type a description of the Invoice line transaction. */
msdyn_description: DevKit.Controls.String;
/** Enter the date on which this invoice line detail was sent to the customer */
msdyn_DocumentDate: DevKit.Controls.Date;
/** Date of invoiced transaction */
msdyn_EndDateTime: DevKit.Controls.DateTime;
/** The external description of the invoice line detail */
msdyn_externaldescription: DevKit.Controls.String;
/** Unique identifier for Invoice Line associated with Invoice Line Detail. */
msdyn_InvoiceLineId: DevKit.Controls.Lookup;
/** Unique identifier for Invoice Line associated with Invoice Line Detail. */
msdyn_InvoiceLineId_1: DevKit.Controls.Lookup;
/** The original transaction that is being corrected if this is a correction transaction. */
msdyn_OriginalInvoiceLineDetail: DevKit.Controls.Lookup;
/** Enter the price of the transaction. */
msdyn_Price: DevKit.Controls.Money;
/** Select the price list used for defaulting price on this transaction. */
msdyn_PriceList: DevKit.Controls.Lookup;
/** Select the name of the project on which this transaction was created. */
msdyn_Project: DevKit.Controls.Lookup;
/** Enter the quantity of the transaction. */
msdyn_Quantity: DevKit.Controls.Decimal;
/** Select the role that the user resource who logged this transaction worked as. */
msdyn_ResourceCategory: DevKit.Controls.Lookup;
/** Select the organizational unit at the time the entry was registered of the resource who performed the work. */
msdyn_ResourceOrganizationalUnitId: DevKit.Controls.Lookup;
/** Unique identifier for Order Line associated with Invoice Line Detail. */
msdyn_SalesContractLineId: DevKit.Controls.Lookup;
/** Enter the start date of the transaction. */
msdyn_StartDateTime: DevKit.Controls.DateTime;
/** Select the name of the project task for which this transaction was created. */
msdyn_Task: DevKit.Controls.Lookup;
/** Select the category of the transaction. */
msdyn_TransactionCategory: DevKit.Controls.Lookup;
/** Transaction classification of the invoice line */
msdyn_TransactionClassification: DevKit.Controls.OptionSet;
/** Transaction type of the invoice line */
msdyn_TransactionTypeCode: DevKit.Controls.OptionSet;
/** Select the unit of the transaction quantity. */
msdyn_Unit: DevKit.Controls.Lookup;
/** Select the unit group of the invoice line transaction. */
msdyn_UnitSchedule: DevKit.Controls.Lookup;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Shows the currency associated with the entity. */
TransactionCurrencyId: DevKit.Controls.Lookup;
}
interface quickForm_CorrectionQuickView_Body {
msdyn_Amount: DevKit.Controls.QuickView;
msdyn_BillingType: DevKit.Controls.QuickView;
msdyn_description: DevKit.Controls.QuickView;
msdyn_Price: DevKit.Controls.QuickView;
msdyn_Quantity: DevKit.Controls.QuickView;
}
interface quickForm_CorrectionQuickView extends DevKit.Controls.IQuickView {
Body: quickForm_CorrectionQuickView_Body;
}
interface QuickForm {
CorrectionQuickView: quickForm_CorrectionQuickView;
}
}
class Formmsdyn_invoicelinetransaction_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_invoicelinetransaction_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_invoicelinetransaction_Information */
Body: DevKit.Formmsdyn_invoicelinetransaction_Information.Body;
/** The QuickForm of form msdyn_invoicelinetransaction_Information */
QuickForm: DevKit.Formmsdyn_invoicelinetransaction_Information.QuickForm;
}
namespace Formmsdyn_invoicelinetransaction_Quick_Create {
interface tab_tab_1_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
tab_1_column_2_section_1: DevKit.Controls.Section;
tab_1_column_3_section_1: DevKit.Controls.Section;
}
interface tab_tab_1 extends DevKit.Controls.ITab {
Section: tab_tab_1_Sections;
}
interface Tabs {
tab_1: tab_tab_1;
}
interface Body {
Tab: Tabs;
msdyn_AccountVendor: DevKit.Controls.Lookup;
/** Select the name of the amount calculation method. */
msdyn_AmountMethod: DevKit.Controls.OptionSet;
msdyn_BasisAmount: DevKit.Controls.Money;
msdyn_BasisQuantity: DevKit.Controls.Decimal;
/** Shows the resource. */
msdyn_bookableresource: DevKit.Controls.Lookup;
msdyn_ContactVendor: DevKit.Controls.Lookup;
/** Enter the date on which this invoice line detail was sent to the customer */
msdyn_DocumentDate: DevKit.Controls.Date;
/** Date of invoiced transaction */
msdyn_EndDateTime: DevKit.Controls.DateTime;
/** Relevant when amount calculation method on the invoice line transaction is "Multiply basis amount by percent" */
msdyn_Percent: DevKit.Controls.Decimal;
/** Enter the price of the transaction. */
msdyn_Price: DevKit.Controls.Money;
/** Select the product on this invoice line transaction. */
msdyn_Product: DevKit.Controls.Lookup;
/** Select the name of the project on which this transaction was created. */
msdyn_Project: DevKit.Controls.Lookup;
/** Enter the quantity of the transaction. */
msdyn_Quantity: DevKit.Controls.Decimal;
/** Select the role that the user resource who logged this transaction worked as. */
msdyn_ResourceCategory: DevKit.Controls.Lookup;
/** Enter the start date of the transaction. */
msdyn_StartDateTime: DevKit.Controls.DateTime;
/** Select the name of the project task for which this transaction was created. */
msdyn_Task: DevKit.Controls.Lookup;
/** Select the category of the transaction. */
msdyn_TransactionCategory: DevKit.Controls.Lookup;
/** Transaction classification of the invoice line */
msdyn_TransactionClassification: DevKit.Controls.OptionSet;
/** Transaction type of the invoice line */
msdyn_TransactionTypeCode: DevKit.Controls.OptionSet;
msdyn_VendorType: DevKit.Controls.OptionSet;
}
}
class Formmsdyn_invoicelinetransaction_Quick_Create extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_invoicelinetransaction_Quick_Create
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_invoicelinetransaction_Quick_Create */
Body: DevKit.Formmsdyn_invoicelinetransaction_Quick_Create.Body;
}
class msdyn_invoicelinetransactionApi {
/**
* DynamicsCrm.DevKit msdyn_invoicelinetransactionApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Exchange rate for the currency associated with the entity with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Select the customer who this invoice will be sent to. */
msdyn_AccountCustomer: DevKit.WebApi.LookupValue;
msdyn_AccountingDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
msdyn_AccountVendor: DevKit.WebApi.LookupValue;
/** Enter the amount on the transaction. */
msdyn_Amount: DevKit.WebApi.MoneyValue;
/** Value of the Amount in base currency. */
msdyn_amount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Select the name of the amount calculation method. */
msdyn_AmountMethod: DevKit.WebApi.OptionSetValue;
msdyn_BasisAmount: DevKit.WebApi.MoneyValue;
/** Value of the Basis Amount in base currency. */
msdyn_basisamount_Base: DevKit.WebApi.MoneyValueReadonly;
msdyn_BasisPrice: DevKit.WebApi.MoneyValue;
/** Value of the Basis Price in base currency. */
msdyn_basisprice_Base: DevKit.WebApi.MoneyValueReadonly;
msdyn_BasisQuantity: DevKit.WebApi.DecimalValue;
/** Select whether this transaction will be charged to the customer or not. Only chargeable transactions will add to the invoice total */
msdyn_BillingType: DevKit.WebApi.OptionSetValue;
/** Shows the resource. */
msdyn_bookableresource: DevKit.WebApi.LookupValue;
/** Select the customer who this invoice will be sent to. */
msdyn_ContactCustomer: DevKit.WebApi.LookupValue;
msdyn_ContactVendor: DevKit.WebApi.LookupValue;
/** Select the organizational unit in charge of the related contract. */
msdyn_contractorganizationalunitid: DevKit.WebApi.LookupValue;
/** Indicates if this transaction is correcting a previous transaction. */
msdyn_Correction: DevKit.WebApi.BooleanValue;
/** Select whether the customer was a account or a contact */
msdyn_CustomerType: DevKit.WebApi.OptionSetValue;
/** Type a description of the Invoice line transaction. */
msdyn_description: DevKit.WebApi.StringValue;
/** Enter the date on which this invoice line detail was sent to the customer */
msdyn_DocumentDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Date of invoiced transaction */
msdyn_EndDateTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
msdyn_ExchangeRateDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** The external description of the invoice line detail */
msdyn_externaldescription: DevKit.WebApi.StringValue;
/** The invoice to which this invoice line detail belongs. */
msdyn_Invoice: DevKit.WebApi.LookupValue;
/** Amount to be invoiced. This is the line amount less the previously invoiced amount when this is a correction. */
msdyn_InvoiceAmount: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Invoice Amount in base currency. */
msdyn_invoiceamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** (Deprecated) Shows the invoice line that this invoice line transaction is associated to. */
msdyn_InvoiceLine: DevKit.WebApi.StringValue;
/** Unique identifier for Invoice Line associated with Invoice Line Detail. */
msdyn_InvoiceLineId: DevKit.WebApi.LookupValue;
/** Shows the entity instances. */
msdyn_invoicelinetransactionId: DevKit.WebApi.GuidValue;
/** The original transaction that is being corrected if this is a correction transaction. */
msdyn_OriginalInvoiceLineDetail: DevKit.WebApi.LookupValue;
/** Relevant when amount calculation method on the invoice line transaction is "Multiply basis amount by percent" */
msdyn_Percent: DevKit.WebApi.DecimalValue;
/** Amount that was previously invoiced if this is a correction. */
msdyn_PreviousAmount: DevKit.WebApi.MoneyValue;
/** Value of the Previous Amount in base currency. */
msdyn_previousamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter the price of the transaction. */
msdyn_Price: DevKit.WebApi.MoneyValue;
/** Value of the Price in base currency. */
msdyn_price_Base: DevKit.WebApi.MoneyValueReadonly;
/** Select the price list used for defaulting price on this transaction. */
msdyn_PriceList: DevKit.WebApi.LookupValue;
/** Select the product on this invoice line transaction. */
msdyn_Product: DevKit.WebApi.LookupValue;
/** Select the name of the project on which this transaction was created. */
msdyn_Project: DevKit.WebApi.LookupValue;
/** Enter the quantity of the transaction. */
msdyn_Quantity: DevKit.WebApi.DecimalValue;
/** Select the role that the user resource who logged this transaction worked as. */
msdyn_ResourceCategory: DevKit.WebApi.LookupValue;
/** Select the organizational unit at the time the entry was registered of the resource who performed the work. */
msdyn_ResourceOrganizationalUnitId: DevKit.WebApi.LookupValue;
/** Select the name of the project contract that this invoice belongs to. */
msdyn_SalesContract: DevKit.WebApi.LookupValue;
/** (Deprecated) Shows the ID of the project contract line for this invoice line */
msdyn_SalesContractLine: DevKit.WebApi.StringValue;
/** Unique identifier for Order Line associated with Invoice Line Detail. */
msdyn_SalesContractLineId: DevKit.WebApi.LookupValue;
/** Enter the start date of the transaction. */
msdyn_StartDateTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Select the name of the project task for which this transaction was created. */
msdyn_Task: DevKit.WebApi.LookupValue;
/** Select the category of the transaction. */
msdyn_TransactionCategory: DevKit.WebApi.LookupValue;
/** Transaction classification of the invoice line */
msdyn_TransactionClassification: DevKit.WebApi.OptionSetValue;
/** Transaction type of the invoice line */
msdyn_TransactionTypeCode: DevKit.WebApi.OptionSetValue;
/** Select the unit of the transaction quantity. */
msdyn_Unit: DevKit.WebApi.LookupValue;
/** Select the unit group of the invoice line transaction. */
msdyn_UnitSchedule: DevKit.WebApi.LookupValue;
msdyn_VendorType: DevKit.WebApi.OptionSetValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Invoice Line Detail */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Invoice Line Detail */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the currency associated with the entity. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_invoicelinetransaction {
enum msdyn_AmountMethod {
/** 192350001 */
Fixed_Price,
/** 192350003 */
Multiply_Basis_Amount_By_Percent,
/** 192350002 */
Multiply_Basis_Quantity_By_Price,
/** 192350000 */
Multiply_Quantity_By_Price,
/** 690970000 */
Tax_Calculation
}
enum msdyn_BillingType {
/** 192350001 */
Chargeable,
/** 192350002 */
Complimentary,
/** 192350000 */
Non_Chargeable,
/** 192350003 */
Not_Available
}
enum msdyn_CustomerType {
/** 192350001 */
Account,
/** 192350002 */
Contact
}
enum msdyn_TransactionClassification {
/** 690970001 */
Additional,
/** 690970000 */
Commission,
/** 192350001 */
Expense,
/** 192350004 */
Fee,
/** 192350002 */
Material,
/** 192350003 */
Milestone,
/** 690970002 */
Tax,
/** 192350000 */
Time
}
enum msdyn_TransactionTypeCode {
/** 192350006 */
Billed_Sales,
/** 192350000 */
Cost,
/** 192350008 */
Inter_Organizational_Sales,
/** 192350004 */
Project_Contract,
/** 192350007 */
Resourcing_Unit_Cost,
/** 192350005 */
Unbilled_Sales
}
enum msdyn_VendorType {
/** 192350001 */
Account,
/** 192350002 */
Contact
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information','Quick Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
require('reflect-metadata/reflect');
import {MetaUtils} from '../core/metadata/utils';
import {Decorators} from '../core/constants';
import {DecoratorType} from '../core/enums/decorator-type';
import * as Utils from "../mongoose/utils";
import * as modeEntity from '../core/dynamic/model-entity';
import {Strict} from '../mongoose/enums/';
import Mongoose = require("mongoose");
import {course} from './models/course';
import {student} from './models/student';
import * as Enumerable from 'linq';
var Q = require('q');
var database: { [key: string]: Array<any> } = <any>{};
var _mongooseModel: { [key: string]: any } = <any>{};
var _databaseCalls: { [key: string]: any } = <any>{};
class ModelNames {
public static course: string = course.prototype.constructor.name;
public static student: string = student.prototype.constructor.name;
}
class courseRepository{
find(param: any): Q.Promise<any> {
return MongoDbMock.find(param, database[ModelNames.course]);
}
findOne(param: any): Q.Promise<any> {
return MongoDbMock.findOne(param, database[ModelNames.course]);
}
create(object: any): Q.Promise<any> {
return MongoDbMock.create(object, _mongooseModel[ModelNames.course], database[ModelNames.course]);
}
findOneAndRemove(query: any): Q.Promise<any> {
return MongoDbMock.findOneAndRemove(query, database[ModelNames.course]);
}
findOneAndUpdate(query: any, object: any, param: any): Q.Promise<any> {
return MongoDbMock.findOneAndUpdate(query, object, param, database[ModelNames.course]);
}
update(query: any, object: any, param: any): Q.Promise<any> {
return MongoDbMock.update(query, object, param, database[ModelNames.course]);
}
}
class studentRepository{
find(param: any): Q.Promise<any> {
return MongoDbMock.find(param, database[ModelNames.student]);
}
findOne(param: any): Q.Promise<any> {
return MongoDbMock.findOne(param, database[ModelNames.student]);
}
create(object: any): Q.Promise<any> {
return MongoDbMock.create(object, _mongooseModel[ModelNames.student], database[ModelNames.student]);
}
findOneAndRemove(query: any): Q.Promise<any> {
return MongoDbMock.findOneAndRemove(query, database[ModelNames.student]);
}
findOneAndUpdate(query: any, object: any, param: any): Q.Promise<any> {
return MongoDbMock.findOneAndUpdate(query, object, param, database[ModelNames.student]);
}
update(query: any, object: any, param: any): Q.Promise<any> {
return MongoDbMock.update(query, object, param, database[ModelNames.student]);
}
}
export class MongoDbMock {
static setEmptytoObject(obj: any) {
if (obj == undefined || obj != {}) {
obj['toObject'] = function () {
return {};
}
}
}
public static find(param: any, collection: Array<any>): Q.Promise<any> {
var res = [];
if (JSON.stringify(param) === JSON.stringify({})) {
res = collection;
}
else {
var prop;
for (var p in param) {
prop = p;
break;
}
if (prop == '_id') {
if (param[prop]['$in']) {
var arr: Array<any> = param[prop]['$in'];
res = Enumerable.from(collection).where(x => arr.find(id => x['_id'] == id.toString())).toArray();
}
else {
res = Enumerable.from(collection).where(x => x['_doc'][prop] == param[prop].toString()).firstOrDefault();
}
}
else {
var arr: Array<any> = param[prop]['$in'];
if (arr) {
Enumerable.from(collection).forEach(x => {
if (x['_doc'][prop]) {
var f = x['_doc'][prop].find(x => arr.find(id => x.toString() == id));
if (f) {
res.push(x);
}
}
});
}
else {
res = Enumerable.from(collection).where(x => x['_doc'][prop] == param[prop].toString()).firstOrDefault();
}
}
}
//console.log('find (', param, ') => ', res);
return Q.when(res);
}
public static findOne(param: any, collection: Array<any>): Q.Promise<any> {
var res = {};
for (var item in param) {
var id = param[item].toString();
res = Enumerable.from(collection).where(x => x['_doc'][item] == param[item].toString()).firstOrDefault();
break;
}
//console.log('findOne (', param, ') => ', res);
return Q.when(res);
}
public static create(object: any, model: any, collection: Array<any>): Q.Promise<any> {
var res;
if (object instanceof Array) {
res = [];
Enumerable.from(object).forEach(x => {
var obj = new model(x);
collection.push(obj);
res.push(obj);
});
}
else {
var obj = new model(object);
collection.push(obj);
res = obj;
}
//console.log('create(', object, ')=> ', obj);
return Q.when(res);
}
public static findOneAndRemove(query: any, collection: Array<any>): Q.Promise<any> {
var res = {};
for (var item in query) {
res = Enumerable.from(collection).where(x => x['_doc'][item] == query[item].toString()).firstOrDefault();
if (res) {
collection.splice(collection.indexOf(res), 1);
}
break;
}
//console.log('findOneAndRemove (', query, ') => ', res);
return Q.when(res);
}
public static findOneAndUpdate(query: any, object: any, param: any, collection: Array<any>): Q.Promise<any> {
var res = {};
for (var item in query) {
res = Enumerable.from(collection).where(x => x['_doc'][item] == query[item].toString()).firstOrDefault();
if (res) {
var setObject, unsetObject, pushObject;
if (object['$set']) {
setObject = object['$set'];
}
if (object['$unset']) {
unsetObject = object['$unset'];
}
if (object['$push']) {
pushObject = object['$push'];
}
for (var prop in setObject) {
res['_doc'][prop] = setObject[prop];
}
for (var prop in unsetObject) {
delete res['_doc'][prop];
}
for (var prop in pushObject) {
var vals = pushObject[prop]['$each'];
if (!res['_doc'][prop]) {
res['_doc'][prop] = [];
}
Enumerable.from(vals).forEach(x => res['_doc'][prop].push(x));
}
}
break;
}
//console.log('findOneAndUpdate (', query, object, param, ') => ', res);
return Q.when(res);
}
public static update(query: any, object: any, param: any, collection: Array<any>): Q.Promise<any> {
var res = [];
if (JSON.stringify(query) === JSON.stringify(MongoDbMock.updateCondition) ||
(JSON.stringify(query) === JSON.stringify({}) &&
JSON.stringify(object) === JSON.stringify(MongoDbMock.updateCondition))) {
var id = MongoDbMock.updateResult['_id'].toString();
res = collection.find(x => x['_id'] == id);
for (var ind in MongoDbMock.updateResult) {
res['_doc'][ind] = MongoDbMock.updateResult[ind];
}
res = [res];
//console.log('condition matched', res, id);
}
//console.log('update (', query, object, param), ') =>', res);
return Q.when(res);
}
private static updateCondition;
private static updateResult;
public static setOnUpdate(model: any, cond: any, object: any) {
//console.log('setOnUpdate - ', cond, object);
MongoDbMock.updateCondition = cond;
MongoDbMock.updateResult = object;
}
}
export function AddAllFakeFunctions() {
database[ModelNames.course] = [];
_mongooseModel[ModelNames.course] = Mongoose.model(ModelNames.course, new Mongoose.Schema(course.prototype.schema()));
_databaseCalls[ModelNames.course] = new courseRepository();
database[ModelNames.student] = [];
_mongooseModel[ModelNames.student] = Mongoose.model(ModelNames.student, new Mongoose.Schema(student.prototype.schema()));
_databaseCalls[ModelNames.student] = new studentRepository();
console.log('added all faked function');
}
export function createMongooseModel(name: Function, object: any): Mongoose.Model<any> {
object['_id'] = new Mongoose.Types.ObjectId();
var model = new _mongooseModel[name.prototype.constructor.name](object);
database[name.prototype.constructor.name].push(model);
return model;
}
export function getMongooseModel(name: Function): Mongoose.Model<any> {
return _mongooseModel[name.prototype.constructor.name];
}
export function getFakeFunctionForMongoose(func, model): any {
var fn: Function = func as Function;
var res = _databaseCalls[model.modelName][func.name];
if (!res) {
//console.log('return fake function - ', model.modelName, fn.length, fn.arguments, fn);
if (fn.length == 4) {
return _databaseCalls[model.modelName]['findOneAndUpdate'];
}
else if (fn.length == 3) {
return _databaseCalls[model.modelName]['findOneAndRemove'];
}
}
return res;
}
export function clearDatabase() {
database[ModelNames.course] = [];
database[ModelNames.student] = [];
}
export class mockedFunctions {
castToMongooseType(value, schemaType) {
//console.log('castToMongooseType - ', value, schemaType);
if (value['_id']) {
return value['_id'];
}
else {
return value;
}
}
getEntity(object: any) {
//console.log('getEntity - ', object);
switch (object) {
case ModelNames.course:
return course;
case ModelNames.student:
return student;
}
}
getModel(object: any) {
//console.log('getModel - ', object);
return _mongooseModel[object];
}
getDbSpecifcModel(object: any, schema: any) {
return _mongooseModel[object];
}
//getMetaData(entity: any, decprator: any) {
//}
//getMetaDataForPropKey(entity: any, prop: any) {
//}
//getAllRelationsForTargetInternal(entity: any) {
//}
//getAllRelationsForTarget(entity: any) {
//}
//isRelationDecorator(decorator: any) {
//}
//getPrimaryKeyMetadata(entity: any) {
//}
} | the_stack |
import _fixture96Plate from '@opentrons/shared-data/labware/fixtures/2/fixture_96_plate.json'
import _fixture12Trough from '@opentrons/shared-data/labware/fixtures/2/fixture_12_trough.json'
import _fixture384Plate from '@opentrons/shared-data/labware/fixtures/2/fixture_384_plate.json'
import merge from 'lodash/merge'
import omit from 'lodash/omit'
import produce from 'immer'
import { createEmptyLiquidState, createTipLiquidState } from '../utils'
import { makeContext, DEFAULT_PIPETTE, SOURCE_LABWARE } from '../fixtures'
import {
dispenseUpdateLiquidState,
DispenseUpdateLiquidStateArgs,
} from '../getNextRobotStateAndWarnings/dispenseUpdateLiquidState'
import type { LabwareDefinition2 } from '@opentrons/shared-data'
import type { InvariantContext, RobotState } from '../types'
const fixture96Plate = _fixture96Plate as LabwareDefinition2
const fixture12Trough = _fixture12Trough as LabwareDefinition2
const fixture384Plate = _fixture384Plate as LabwareDefinition2
let dispenseSingleCh150ToA1Args: GetUpdatedLiquidStateParams
let invariantContext: InvariantContext
beforeEach(() => {
invariantContext = makeContext()
dispenseSingleCh150ToA1Args = {
invariantContext,
pipette: DEFAULT_PIPETTE,
volume: 150,
useFullVolume: false,
labware: SOURCE_LABWARE,
well: 'A1',
}
})
type GetUpdatedLiquidStateParams = Omit<
DispenseUpdateLiquidStateArgs,
'prevLiquidState'
>
function getUpdatedLiquidState(
params: GetUpdatedLiquidStateParams,
initialLiquidState: RobotState['liquidState']
): RobotState['liquidState'] {
return produce(initialLiquidState, draft => {
dispenseUpdateLiquidState({
...params,
prevLiquidState: draft,
})
})
}
describe('...single-channel pipette', () => {
it('fully dispense single ingredient into empty well, with explicit volume', () => {
const initialLiquidState = merge(
{},
createEmptyLiquidState(invariantContext),
{
pipettes: {
p300SingleId: {
'0': {
ingred1: { volume: 150 },
},
},
},
}
)
const result = getUpdatedLiquidState(
dispenseSingleCh150ToA1Args,
initialLiquidState
)
expect(result).toMatchObject({
pipettes: {
p300SingleId: {
'0': {
ingred1: { volume: 0 },
},
},
},
labware: {
sourcePlateId: {
A1: { ingred1: { volume: 150 } },
A2: {},
B1: {},
},
},
})
})
it('fully dispense single ingredient into empty well, with useFullVolume', () => {
const initialLiquidState = merge(
{},
createEmptyLiquidState(invariantContext),
{
pipettes: {
p300SingleId: {
'0': {
ingred1: { volume: 150 },
},
},
},
}
)
const result = getUpdatedLiquidState(
{
...omit(dispenseSingleCh150ToA1Args, 'volume'),
useFullVolume: true,
},
initialLiquidState
)
expect(result).toMatchObject({
pipettes: {
p300SingleId: {
'0': {
ingred1: { volume: 0 },
},
},
},
labware: {
sourcePlateId: {
A1: { ingred1: { volume: 150 } },
A2: {},
B1: {},
},
},
})
})
it('dispense ingred 1 into well containing ingreds 1 & 2', () => {
const initialLiquidState = merge(
{},
createEmptyLiquidState(invariantContext),
{
pipettes: {
p300SingleId: {
'0': {
ingred1: { volume: 150 },
},
},
},
labware: {
sourcePlateId: {
A1: {
ingred1: { volume: 30 },
ingred2: { volume: 50 },
},
},
},
}
)
const result = getUpdatedLiquidState(
dispenseSingleCh150ToA1Args,
initialLiquidState
)
expect(result).toMatchObject({
pipettes: {
p300SingleId: {
'0': {
ingred1: { volume: 0 },
},
},
},
labware: {
sourcePlateId: {
A1: {
ingred1: { volume: 150 + 30 },
ingred2: { volume: 50 },
},
A2: {},
B1: {},
},
},
})
})
it('dispense ingred 1 & 2 into well containing 2 & 3', () => {
const initialLiquidState = merge(
{},
createEmptyLiquidState(invariantContext),
{
pipettes: {
p300SingleId: {
'0': {
ingred1: { volume: 50 },
ingred2: { volume: 100 },
},
},
},
labware: {
sourcePlateId: {
A1: {
ingred2: { volume: 25 },
ingred3: { volume: 20 },
},
},
},
}
)
const result = getUpdatedLiquidState(
dispenseSingleCh150ToA1Args,
initialLiquidState
)
expect(result).toMatchObject({
pipettes: {
p300SingleId: {
'0': {
ingred1: { volume: 0 },
ingred2: { volume: 0 },
},
},
},
labware: {
sourcePlateId: {
A1: {
ingred1: { volume: 50 },
ingred2: { volume: 100 + 25 },
ingred3: { volume: 20 },
},
A2: {},
B1: {},
},
},
})
})
it('partially dispense ingred 1 & 2 into well containing 2 & 3', () => {
const initialLiquidState = merge(
{},
createEmptyLiquidState(invariantContext),
{
pipettes: {
p300SingleId: {
'0': {
ingred1: { volume: 50 },
ingred2: { volume: 200 },
},
},
},
labware: {
sourcePlateId: {
A1: {
ingred2: { volume: 25 },
ingred3: { volume: 20 },
},
},
},
}
)
const result = getUpdatedLiquidState(
dispenseSingleCh150ToA1Args,
initialLiquidState
)
expect(result).toMatchObject({
pipettes: {
p300SingleId: {
'0': {
ingred1: { volume: 20 },
ingred2: { volume: 80 },
},
},
},
labware: {
sourcePlateId: {
A1: {
ingred1: { volume: 0 + (50 - 20) },
ingred2: { volume: 25 + (200 - 80) },
ingred3: { volume: 0 + 20 },
},
A2: {},
B1: {},
},
},
})
})
describe('handle air in pipette tips', () => {
it.todo('TODO(IL 2018-03-16): deal with air (especially regarding air gap)')
})
})
describe('...8-channel pipette', () => {
describe('dispense into empty column with different ingreds in each tip:', () => {
const tests = [
{
labwareType: 'fixture_96_plate',
def: fixture96Plate,
expectedLabwareMatch: {
sourcePlateId: {
A1: {
ingred2: { volume: 25 + 150 },
ingred3: { volume: 20 },
},
B1: {},
C1: { ingred1: { volume: 150 } },
D1: { ingred1: { volume: 150 } },
E1: { ingred1: { volume: 150 } },
F1: { ingred1: { volume: 150 } },
G1: { ingred1: { volume: 150 } },
H1: { ingred1: { volume: 150 } },
},
},
},
{
labwareType: 'fixture_12_trough',
def: fixture12Trough,
expectedLabwareMatch: {
sourcePlateId: {
A1: {
ingred1: { volume: 6 * 150 },
ingred2: { volume: 25 + 150 },
ingred3: { volume: 20 },
},
A2: {},
},
},
},
{
labwareType: 'fixture_384_plate',
def: fixture384Plate,
expectedLabwareMatch: {
sourcePlateId: {
A1: {
ingred2: { volume: 25 + 150 },
ingred3: { volume: 20 },
},
C1: {},
E1: { ingred1: { volume: 150 } },
G1: { ingred1: { volume: 150 } },
I1: { ingred1: { volume: 150 } },
K1: { ingred1: { volume: 150 } },
M1: { ingred1: { volume: 150 } },
O1: { ingred1: { volume: 150 } },
// odd rows out
B1: {},
D1: {},
F1: {},
H1: {},
J1: {},
L1: {},
N1: {},
P1: {},
},
},
},
]
tests.forEach(({ labwareType, def, expectedLabwareMatch }) =>
// make sourcePlateId a different labware def each time
it(labwareType, () => {
const customInvariantContext = makeContext()
customInvariantContext.labwareEntities.sourcePlateId = {
id: SOURCE_LABWARE,
labwareDefURI: labwareType,
def,
}
const blankLiquidState = createEmptyLiquidState(customInvariantContext)
const initialLiquidState = merge({}, blankLiquidState, {
pipettes: {
p300MultiId: {
// all tips have 150uL of ingred1, except tips 0 and 1
...createTipLiquidState(8, { ingred1: { volume: 150 } }),
'0': {
ingred2: { volume: 200 },
},
'1': {},
},
},
labware: {
sourcePlateId: {
A1: {
ingred2: { volume: 25 },
ingred3: { volume: 20 },
},
},
},
})
const result = getUpdatedLiquidState(
{
invariantContext: customInvariantContext,
labware: SOURCE_LABWARE,
pipette: 'p300MultiId',
useFullVolume: false,
volume: 150,
well: 'A1',
},
initialLiquidState
)
expect(result).toMatchObject({
pipettes: {
p300MultiId: {
...createTipLiquidState(8, { ingred1: { volume: 0 } }),
'0': {
ingred2: { volume: 50 },
},
'1': {},
},
},
labware: expectedLabwareMatch,
})
})
)
})
}) | the_stack |
import {
Box2,
BufferGeometry,
FileLoader,
Float32BufferAttribute,
Loader,
Matrix3,
Path,
Shape,
ShapePath,
ShapeUtils,
Vector2,
Vector3
} from 'three';
/* eslint-disable */
class SVGLoader extends Loader {
defaultDPI = 90; // MA:
defaultUnit = 'px'; // MA:
defs = []; // MA:
constructor( manager? ) {
super( manager );
// Default dots per inch
this.defaultDPI = 90;
// Accepted units: 'mm', 'cm', 'in', 'pt', 'pc', 'px'
this.defaultUnit = 'px';
}
load( url, onLoad, onProgress, onError ) {
const scope = this;
const loader = new FileLoader( scope.manager );
loader.setPath( scope.path );
loader.setRequestHeader( scope.requestHeader );
loader.setWithCredentials( scope.withCredentials );
loader.load( url, function ( text ) {
try {
onLoad( scope.parse( text ) );
} catch ( e ) {
if ( onError ) {
onError( e );
} else {
console.error( e );
}
scope.manager.itemError( url );
}
}, onProgress, onError );
}
parse( text ) {
const scope = this;
function parseNode( node, style ) {
if ( node.nodeType !== 1 ) return;
const transform = getNodeTransform( node );
let traverseChildNodes = true;
let path = null;
switch ( node.nodeName ) {
case 'svg':
break;
case 'style':
parseCSSStylesheet( node );
break;
case 'g':
style = parseStyle( node, style );
break;
case 'path':
style = parseStyle( node, style );
if ( node.hasAttribute( 'd' ) ) path = parsePathNode( node );
break;
case 'rect':
style = parseStyle( node, style );
path = parseRectNode( node );
break;
case 'polygon':
style = parseStyle( node, style );
path = parsePolygonNode( node );
break;
case 'polyline':
style = parseStyle( node, style );
path = parsePolylineNode( node );
break;
case 'circle':
style = parseStyle( node, style );
path = parseCircleNode( node );
break;
case 'ellipse':
style = parseStyle( node, style );
path = parseEllipseNode( node );
break;
case 'line':
style = parseStyle( node, style );
path = parseLineNode( node );
break;
case 'defs':
traverseChildNodes = false;
parseDefs(node);
break;
case 'use':
style = parseStyle( node, style );
const usedNodeId = node.href.baseVal.substring( 1 );
const usedNode = node.viewportElement.getElementById( usedNodeId );
if ( usedNode ) {
parseNode( usedNode, style );
} else {
console.warn( 'SVGLoader: \'use node\' references non-existent node id: ' + usedNodeId );
}
break;
default:
// console.log( node );
}
if ( path ) {
if ( style.fill !== undefined && style.fill !== 'none' ) {
path.color.setStyle( style.fill );
}
transformPath( path, currentTransform );
paths.push( path );
path.userData = { node: node, style: style };
}
if ( traverseChildNodes ) {
const nodes = node.childNodes;
for ( let i = 0; i < nodes.length; i ++ ) {
parseNode( nodes[ i ], style );
}
}
if ( transform ) {
transformStack.pop();
if ( transformStack.length > 0 ) {
currentTransform.copy( transformStack[ transformStack.length - 1 ] );
} else {
currentTransform.identity();
}
}
}
function parsePathNode( node ) {
const path = new ShapePath();
const point = new Vector2();
const control = new Vector2();
const firstPoint = new Vector2();
let isFirstPoint = true;
let doSetFirstPoint = false;
const d = node.getAttribute( 'd' );
// console.log( d );
const commands = d.match( /[a-df-z][^a-df-z]*/ig );
for ( let i = 0, l = commands.length; i < l; i ++ ) {
const command = commands[ i ];
const type = command.charAt( 0 );
const data = command.substr( 1 ).trim();
if ( isFirstPoint === true ) {
doSetFirstPoint = true;
isFirstPoint = false;
}
let numbers;
switch ( type ) {
case 'M':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
point.x = numbers[ j + 0 ];
point.y = numbers[ j + 1 ];
control.x = point.x;
control.y = point.y;
if ( j === 0 ) {
path.moveTo( point.x, point.y );
} else {
path.lineTo( point.x, point.y );
}
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'H':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
point.x = numbers[ j ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'V':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
point.y = numbers[ j ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'L':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
point.x = numbers[ j + 0 ];
point.y = numbers[ j + 1 ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'C':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 6 ) {
path.bezierCurveTo(
numbers[ j + 0 ],
numbers[ j + 1 ],
numbers[ j + 2 ],
numbers[ j + 3 ],
numbers[ j + 4 ],
numbers[ j + 5 ]
);
control.x = numbers[ j + 2 ];
control.y = numbers[ j + 3 ];
point.x = numbers[ j + 4 ];
point.y = numbers[ j + 5 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'S':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
path.bezierCurveTo(
getReflection( point.x, control.x ),
getReflection( point.y, control.y ),
numbers[ j + 0 ],
numbers[ j + 1 ],
numbers[ j + 2 ],
numbers[ j + 3 ]
);
control.x = numbers[ j + 0 ];
control.y = numbers[ j + 1 ];
point.x = numbers[ j + 2 ];
point.y = numbers[ j + 3 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'Q':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
path.quadraticCurveTo(
numbers[ j + 0 ],
numbers[ j + 1 ],
numbers[ j + 2 ],
numbers[ j + 3 ]
);
control.x = numbers[ j + 0 ];
control.y = numbers[ j + 1 ];
point.x = numbers[ j + 2 ];
point.y = numbers[ j + 3 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'T':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
const rx = getReflection( point.x, control.x );
const ry = getReflection( point.y, control.y );
path.quadraticCurveTo(
rx,
ry,
numbers[ j + 0 ],
numbers[ j + 1 ]
);
control.x = rx;
control.y = ry;
point.x = numbers[ j + 0 ];
point.y = numbers[ j + 1 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'A':
numbers = parseFloats( data, [ 3, 4 ], 7 );
for ( let j = 0, jl = numbers.length; j < jl; j += 7 ) {
// skip command if start point == end point
if ( numbers[ j + 5 ] == point.x && numbers[ j + 6 ] == point.y ) continue;
const start = point.clone();
point.x = numbers[ j + 5 ];
point.y = numbers[ j + 6 ];
control.x = point.x;
control.y = point.y;
parseArcCommand(
path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point
);
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'm':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
point.x += numbers[ j + 0 ];
point.y += numbers[ j + 1 ];
control.x = point.x;
control.y = point.y;
if ( j === 0 ) {
path.moveTo( point.x, point.y );
} else {
path.lineTo( point.x, point.y );
}
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'h':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
point.x += numbers[ j ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'v':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
point.y += numbers[ j ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'l':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
point.x += numbers[ j + 0 ];
point.y += numbers[ j + 1 ];
control.x = point.x;
control.y = point.y;
path.lineTo( point.x, point.y );
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'c':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 6 ) {
path.bezierCurveTo(
point.x + numbers[ j + 0 ],
point.y + numbers[ j + 1 ],
point.x + numbers[ j + 2 ],
point.y + numbers[ j + 3 ],
point.x + numbers[ j + 4 ],
point.y + numbers[ j + 5 ]
);
control.x = point.x + numbers[ j + 2 ];
control.y = point.y + numbers[ j + 3 ];
point.x += numbers[ j + 4 ];
point.y += numbers[ j + 5 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 's':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
path.bezierCurveTo(
getReflection( point.x, control.x ),
getReflection( point.y, control.y ),
point.x + numbers[ j + 0 ],
point.y + numbers[ j + 1 ],
point.x + numbers[ j + 2 ],
point.y + numbers[ j + 3 ]
);
control.x = point.x + numbers[ j + 0 ];
control.y = point.y + numbers[ j + 1 ];
point.x += numbers[ j + 2 ];
point.y += numbers[ j + 3 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'q':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
path.quadraticCurveTo(
point.x + numbers[ j + 0 ],
point.y + numbers[ j + 1 ],
point.x + numbers[ j + 2 ],
point.y + numbers[ j + 3 ]
);
control.x = point.x + numbers[ j + 0 ];
control.y = point.y + numbers[ j + 1 ];
point.x += numbers[ j + 2 ];
point.y += numbers[ j + 3 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 't':
numbers = parseFloats( data );
for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
const rx = getReflection( point.x, control.x );
const ry = getReflection( point.y, control.y );
path.quadraticCurveTo(
rx,
ry,
point.x + numbers[ j + 0 ],
point.y + numbers[ j + 1 ]
);
control.x = rx;
control.y = ry;
point.x = point.x + numbers[ j + 0 ];
point.y = point.y + numbers[ j + 1 ];
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'a':
numbers = parseFloats( data, [ 3, 4 ], 7 );
for ( let j = 0, jl = numbers.length; j < jl; j += 7 ) {
// skip command if no displacement
if ( numbers[ j + 5 ] == 0 && numbers[ j + 6 ] == 0 ) continue;
const start = point.clone();
point.x += numbers[ j + 5 ];
point.y += numbers[ j + 6 ];
control.x = point.x;
control.y = point.y;
parseArcCommand(
path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point
);
if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
}
break;
case 'Z':
case 'z':
path.currentPath.autoClose = true;
if ( path.currentPath.curves.length > 0 ) {
// Reset point to beginning of Path
point.copy( firstPoint );
path.currentPath.currentPoint.copy( point );
isFirstPoint = true;
}
break;
default:
console.warn( command );
}
// console.log( type, parseFloats( data ), parseFloats( data ).length )
doSetFirstPoint = false;
}
return path;
}
function parseCSSStylesheet( node ) {
if ( ! node.sheet || ! node.sheet.cssRules || ! node.sheet.cssRules.length ) return;
for ( let i = 0; i < node.sheet.cssRules.length; i ++ ) {
const stylesheet = node.sheet.cssRules[ i ];
if ( stylesheet.type !== 1 ) continue;
const selectorList = stylesheet.selectorText
.split( /,/gm )
.filter( Boolean )
.map( i => i.trim() );
for ( let j = 0; j < selectorList.length; j ++ ) {
stylesheets[ selectorList[ j ] ] = Object.assign(
stylesheets[ selectorList[ j ] ] || {},
stylesheet.style
);
}
}
}
/**
* https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
* https://mortoray.com/2017/02/16/rendering-an-svg-elliptical-arc-as-bezier-curves/ Appendix: Endpoint to center arc conversion
* From
* rx ry x-axis-rotation large-arc-flag sweep-flag x y
* To
* aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation
*/
function parseArcCommand( path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end ) {
if ( rx == 0 || ry == 0 ) {
// draw a line if either of the radii == 0
path.lineTo( end.x, end.y );
return;
}
x_axis_rotation = x_axis_rotation * Math.PI / 180;
// Ensure radii are positive
rx = Math.abs( rx );
ry = Math.abs( ry );
// Compute (x1', y1')
const dx2 = ( start.x - end.x ) / 2.0;
const dy2 = ( start.y - end.y ) / 2.0;
const x1p = Math.cos( x_axis_rotation ) * dx2 + Math.sin( x_axis_rotation ) * dy2;
const y1p = - Math.sin( x_axis_rotation ) * dx2 + Math.cos( x_axis_rotation ) * dy2;
// Compute (cx', cy')
let rxs = rx * rx;
let rys = ry * ry;
const x1ps = x1p * x1p;
const y1ps = y1p * y1p;
// Ensure radii are large enough
const cr = x1ps / rxs + y1ps / rys;
if ( cr > 1 ) {
// scale up rx,ry equally so cr == 1
const s = Math.sqrt( cr );
rx = s * rx;
ry = s * ry;
rxs = rx * rx;
rys = ry * ry;
}
const dq = ( rxs * y1ps + rys * x1ps );
const pq = ( rxs * rys - dq ) / dq;
let q = Math.sqrt( Math.max( 0, pq ) );
if ( large_arc_flag === sweep_flag ) q = - q;
const cxp = q * rx * y1p / ry;
const cyp = - q * ry * x1p / rx;
// Step 3: Compute (cx, cy) from (cx', cy')
const cx = Math.cos( x_axis_rotation ) * cxp - Math.sin( x_axis_rotation ) * cyp + ( start.x + end.x ) / 2;
const cy = Math.sin( x_axis_rotation ) * cxp + Math.cos( x_axis_rotation ) * cyp + ( start.y + end.y ) / 2;
// Step 4: Compute θ1 and Δθ
const theta = svgAngle( 1, 0, ( x1p - cxp ) / rx, ( y1p - cyp ) / ry );
const delta = svgAngle( ( x1p - cxp ) / rx, ( y1p - cyp ) / ry, ( - x1p - cxp ) / rx, ( - y1p - cyp ) / ry ) % ( Math.PI * 2 );
path.currentPath.absellipse( cx, cy, rx, ry, theta, theta + delta, sweep_flag === 0, x_axis_rotation );
}
function svgAngle( ux, uy, vx, vy ) {
const dot = ux * vx + uy * vy;
const len = Math.sqrt( ux * ux + uy * uy ) * Math.sqrt( vx * vx + vy * vy );
let ang = Math.acos( Math.max( - 1, Math.min( 1, dot / len ) ) ); // floating point precision, slightly over values appear
if ( ( ux * vy - uy * vx ) < 0 ) ang = - ang;
return ang;
}
/*
* According to https://www.w3.org/TR/SVG/shapes.html#RectElementRXAttribute
* rounded corner should be rendered to elliptical arc, but bezier curve does the job well enough
*/
function parseRectNode( node ) {
const x = parseFloatWithUnits( node.getAttribute( 'x' ) || 0 );
const y = parseFloatWithUnits( node.getAttribute( 'y' ) || 0 );
const rx = parseFloatWithUnits( node.getAttribute( 'rx' ) || 0 );
const ry = parseFloatWithUnits( node.getAttribute( 'ry' ) || 0 );
const w = parseFloatWithUnits( node.getAttribute( 'width' ) );
const h = parseFloatWithUnits( node.getAttribute( 'height' ) );
const path = new ShapePath();
path.moveTo( x + 2 * rx, y );
path.lineTo( x + w - 2 * rx, y );
if ( rx !== 0 || ry !== 0 ) path.bezierCurveTo( x + w, y, x + w, y, x + w, y + 2 * ry );
path.lineTo( x + w, y + h - 2 * ry );
if ( rx !== 0 || ry !== 0 ) path.bezierCurveTo( x + w, y + h, x + w, y + h, x + w - 2 * rx, y + h );
path.lineTo( x + 2 * rx, y + h );
if ( rx !== 0 || ry !== 0 ) {
path.bezierCurveTo( x, y + h, x, y + h, x, y + h - 2 * ry );
}
path.lineTo( x, y + 2 * ry );
if ( rx !== 0 || ry !== 0 ) {
path.bezierCurveTo( x, y, x, y, x + 2 * rx, y );
}
return path;
}
function parsePolygonNode( node ) {
function iterator( match, a, b ) {
const x = parseFloatWithUnits( a );
const y = parseFloatWithUnits( b );
if ( index === 0 ) {
path.moveTo( x, y );
} else {
path.lineTo( x, y );
}
index ++;
}
const regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g;
const path = new ShapePath();
let index = 0;
node.getAttribute( 'points' ).replace( regex, iterator );
path.currentPath.autoClose = true;
return path;
}
function parsePolylineNode( node ) {
function iterator( match, a, b ) {
const x = parseFloatWithUnits( a );
const y = parseFloatWithUnits( b );
if ( index === 0 ) {
path.moveTo( x, y );
} else {
path.lineTo( x, y );
}
index ++;
}
const regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g;
const path = new ShapePath();
let index = 0;
node.getAttribute( 'points' ).replace( regex, iterator );
path.currentPath.autoClose = false;
return path;
}
function parseCircleNode( node ) {
const x = parseFloatWithUnits( node.getAttribute( 'cx' ) || 0 );
const y = parseFloatWithUnits( node.getAttribute( 'cy' ) || 0 );
const r = parseFloatWithUnits( node.getAttribute( 'r' ) || 0 );
const subpath = new Path();
subpath.absarc( x, y, r, 0, Math.PI * 2, true);
const path = new ShapePath();
path.subPaths.push( subpath );
return path;
}
function parseEllipseNode( node ) {
const x = parseFloatWithUnits( node.getAttribute( 'cx' ) || 0 );
const y = parseFloatWithUnits( node.getAttribute( 'cy' ) || 0 );
const rx = parseFloatWithUnits( node.getAttribute( 'rx' ) || 0 );
const ry = parseFloatWithUnits( node.getAttribute( 'ry' ) || 0 );
const subpath = new Path();
subpath.absellipse( x, y, rx, ry, 0, Math.PI * 2, true, 0);
const path = new ShapePath();
path.subPaths.push( subpath );
return path;
}
function parseLineNode( node ) {
const x1 = parseFloatWithUnits( node.getAttribute( 'x1' ) || 0 );
const y1 = parseFloatWithUnits( node.getAttribute( 'y1' ) || 0 );
const x2 = parseFloatWithUnits( node.getAttribute( 'x2' ) || 0 );
const y2 = parseFloatWithUnits( node.getAttribute( 'y2' ) || 0 );
const path = new ShapePath();
path.moveTo( x1, y1 );
path.lineTo( x2, y2 );
path.currentPath.autoClose = false;
return path;
}
//
function parseDefs( node ) {
if (!scope.defs) {
scope.defs = [];
}
const nodes = node.childNodes;
for (const node of nodes) {
const stops = node.childNodes;
for ( const stop of stops ) {
if (stop.hasAttribute && stop.hasAttribute('stop-color')) {
scope.defs[node.id] = stop.getAttribute( 'stop-color' );
break;
}
}
}
}
function parseStyle( node, style ) {
style = Object.assign( {}, style ); // clone style
let stylesheetStyles = {};
if ( node.hasAttribute( 'class' ) ) {
const classSelectors = node.getAttribute( 'class' )
.split( /\s/ )
.filter( Boolean )
.map( i => i.trim() );
for ( let i = 0; i < classSelectors.length; i ++ ) {
stylesheetStyles = Object.assign( stylesheetStyles, stylesheets[ '.' + classSelectors[ i ] ] );
}
}
if ( node.hasAttribute( 'id' ) ) {
stylesheetStyles = Object.assign( stylesheetStyles, stylesheets[ '#' + node.getAttribute( 'id' ) ] );
}
function addStyle( svgName, jsName, adjustFunction? ) {
if ( adjustFunction === undefined ) adjustFunction = function copy( v ) {
if ( v.startsWith( 'url' ) ) {
let ref = v.match(/url\(#(.*)\)/);
if (ref && ref[1]) {
return scope.defs[ref[1]];
} else {
return v;
}
} else {
return v;
}
};
if ( node.hasAttribute( svgName ) ) style[ jsName ] = adjustFunction( node.getAttribute( svgName ) );
if ( stylesheetStyles[ svgName ] ) style[ jsName ] = adjustFunction( stylesheetStyles[ svgName ] );
if ( node.style && node.style[ svgName ] !== '' ) style[ jsName ] = adjustFunction( node.style[ svgName ] );
}
function clamp( v ) {
return Math.max( 0, Math.min( 1, parseFloatWithUnits( v ) ) );
}
function positive( v ) {
return Math.max( 0, parseFloatWithUnits( v ) );
}
addStyle( 'fill', 'fill' );
addStyle( 'fill-opacity', 'fillOpacity', clamp );
addStyle( 'opacity', 'opacity', clamp );
addStyle( 'stroke', 'stroke' );
addStyle( 'stroke-opacity', 'strokeOpacity', clamp );
addStyle( 'stroke-width', 'strokeWidth', positive );
addStyle( 'stroke-linejoin', 'strokeLineJoin' );
addStyle( 'stroke-linecap', 'strokeLineCap' );
addStyle( 'stroke-miterlimit', 'strokeMiterLimit', positive );
addStyle( 'visibility', 'visibility' );
return style;
}
// http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes
function getReflection( a, b ) {
return a - ( b - a );
}
// from https://github.com/ppvg/svg-numbers (MIT License)
function parseFloats( input, flags?, stride? ) {
if ( typeof input !== 'string' ) {
throw new TypeError( 'Invalid input: ' + typeof input );
}
// Character groups
const RE = {
SEPARATOR: /[ \t\r\n\,.\-+]/,
WHITESPACE: /[ \t\r\n]/,
DIGIT: /[\d]/,
SIGN: /[-+]/,
POINT: /\./,
COMMA: /,/,
EXP: /e/i,
FLAGS: /[01]/
};
// States
const SEP = 0;
const INT = 1;
const FLOAT = 2;
const EXP = 3;
let state = SEP;
let seenComma = true;
let number = '', exponent = '';
const result = [];
function throwSyntaxError( current, i, partial ) {
const error = new SyntaxError( 'Unexpected character "' + current + '" at index ' + i + '.' );
//MA: error.partial = partial;
throw error;
}
function newNumber() {
if ( number !== '' ) {
if ( exponent === '' ) result.push( Number( number ) );
else result.push( Number( number ) * Math.pow( 10, Number( exponent ) ) );
}
number = '';
exponent = '';
}
let current;
const length = input.length;
for ( let i = 0; i < length; i ++ ) {
current = input[ i ];
// check for flags
if ( Array.isArray( flags ) && flags.includes( result.length % stride ) && RE.FLAGS.test( current ) ) {
state = INT;
number = current;
newNumber();
continue;
}
// parse until next number
if ( state === SEP ) {
// eat whitespace
if ( RE.WHITESPACE.test( current ) ) {
continue;
}
// start new number
if ( RE.DIGIT.test( current ) || RE.SIGN.test( current ) ) {
state = INT;
number = current;
continue;
}
if ( RE.POINT.test( current ) ) {
state = FLOAT;
number = current;
continue;
}
// throw on double commas (e.g. "1, , 2")
if ( RE.COMMA.test( current ) ) {
if ( seenComma ) {
throwSyntaxError( current, i, result );
}
seenComma = true;
}
}
// parse integer part
if ( state === INT ) {
if ( RE.DIGIT.test( current ) ) {
number += current;
continue;
}
if ( RE.POINT.test( current ) ) {
number += current;
state = FLOAT;
continue;
}
if ( RE.EXP.test( current ) ) {
state = EXP;
continue;
}
// throw on double signs ("-+1"), but not on sign as separator ("-1-2")
if ( RE.SIGN.test( current )
&& number.length === 1
&& RE.SIGN.test( number[ 0 ] ) ) {
throwSyntaxError( current, i, result );
}
}
// parse decimal part
if ( state === FLOAT ) {
if ( RE.DIGIT.test( current ) ) {
number += current;
continue;
}
if ( RE.EXP.test( current ) ) {
state = EXP;
continue;
}
// throw on double decimal points (e.g. "1..2")
if ( RE.POINT.test( current ) && number[ number.length - 1 ] === '.' ) {
throwSyntaxError( current, i, result );
}
}
// parse exponent part
if ( state === EXP ) {
if ( RE.DIGIT.test( current ) ) {
exponent += current;
continue;
}
if ( RE.SIGN.test( current ) ) {
if ( exponent === '' ) {
exponent += current;
continue;
}
if ( exponent.length === 1 && RE.SIGN.test( exponent ) ) {
throwSyntaxError( current, i, result );
}
}
}
// end of number
if ( RE.WHITESPACE.test( current ) ) {
newNumber();
state = SEP;
seenComma = false;
} else if ( RE.COMMA.test( current ) ) {
newNumber();
state = SEP;
seenComma = true;
} else if ( RE.SIGN.test( current ) ) {
newNumber();
state = INT;
number = current;
} else if ( RE.POINT.test( current ) ) {
newNumber();
state = FLOAT;
number = current;
} else {
throwSyntaxError( current, i, result );
}
}
// add the last number found (if any)
newNumber();
return result;
}
// Units
const units = [ 'mm', 'cm', 'in', 'pt', 'pc', 'px' ];
// Conversion: [ fromUnit ][ toUnit ] (-1 means dpi dependent)
const unitConversion = {
'mm': {
'mm': 1,
'cm': 0.1,
'in': 1 / 25.4,
'pt': 72 / 25.4,
'pc': 6 / 25.4,
'px': - 1
},
'cm': {
'mm': 10,
'cm': 1,
'in': 1 / 2.54,
'pt': 72 / 2.54,
'pc': 6 / 2.54,
'px': - 1
},
'in': {
'mm': 25.4,
'cm': 2.54,
'in': 1,
'pt': 72,
'pc': 6,
'px': - 1
},
'pt': {
'mm': 25.4 / 72,
'cm': 2.54 / 72,
'in': 1 / 72,
'pt': 1,
'pc': 6 / 72,
'px': - 1
},
'pc': {
'mm': 25.4 / 6,
'cm': 2.54 / 6,
'in': 1 / 6,
'pt': 72 / 6,
'pc': 1,
'px': - 1
},
'px': {
'px': 1
}
};
function parseFloatWithUnits( string ) {
let theUnit = 'px';
if ( typeof string === 'string' || string instanceof String ) {
for ( let i = 0, n = units.length; i < n; i ++ ) {
const u = units[ i ];
if ( string.endsWith( u ) ) {
theUnit = u;
string = string.substring( 0, string.length - u.length );
break;
}
}
}
let scale = undefined;
if ( theUnit === 'px' && scope.defaultUnit !== 'px' ) {
// Conversion scale from pixels to inches, then to default units
scale = unitConversion[ 'in' ][ scope.defaultUnit ] / scope.defaultDPI;
} else {
scale = unitConversion[ theUnit ][ scope.defaultUnit ];
if ( scale < 0 ) {
// Conversion scale to pixels
scale = unitConversion[ theUnit ][ 'in' ] * scope.defaultDPI;
}
}
return scale * parseFloat( string );
}
// Transforms
function getNodeTransform( node ) {
if ( ! ( node.hasAttribute( 'transform' ) || ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) ) ) {
return null;
}
const transform = parseNodeTransform( node );
if ( transformStack.length > 0 ) {
transform.premultiply( transformStack[ transformStack.length - 1 ] );
}
currentTransform.copy( transform );
transformStack.push( transform );
return transform;
}
function parseNodeTransform( node ) {
const transform = new Matrix3();
const currentTransform = tempTransform0;
if ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) {
const tx = parseFloatWithUnits( node.getAttribute( 'x' ) );
const ty = parseFloatWithUnits( node.getAttribute( 'y' ) );
transform.translate( tx, ty );
}
if ( node.hasAttribute( 'transform' ) ) {
const transformsTexts = node.getAttribute( 'transform' ).split( ')' );
for ( let tIndex = transformsTexts.length - 1; tIndex >= 0; tIndex -- ) {
const transformText = transformsTexts[ tIndex ].trim();
if ( transformText === '' ) continue;
const openParPos = transformText.indexOf( '(' );
const closeParPos = transformText.length;
if ( openParPos > 0 && openParPos < closeParPos ) {
const transformType = transformText.substr( 0, openParPos );
const array = parseFloats( transformText.substr( openParPos + 1, closeParPos - openParPos - 1 ) );
currentTransform.identity();
switch ( transformType ) {
case 'translate':
if ( array.length >= 1 ) {
const tx = array[ 0 ];
let ty = tx;
if ( array.length >= 2 ) {
ty = array[ 1 ];
}
currentTransform.translate( tx, ty );
}
break;
case 'rotate':
if ( array.length >= 1 ) {
let angle = 0;
let cx = 0;
let cy = 0;
// Angle
angle = - array[ 0 ] * Math.PI / 180;
if ( array.length >= 3 ) {
// Center x, y
cx = array[ 1 ];
cy = array[ 2 ];
}
// Rotate around center (cx, cy)
tempTransform1.identity().translate( - cx, - cy );
tempTransform2.identity().rotate( angle );
tempTransform3.multiplyMatrices( tempTransform2, tempTransform1 );
tempTransform1.identity().translate( cx, cy );
currentTransform.multiplyMatrices( tempTransform1, tempTransform3 );
}
break;
case 'scale':
if ( array.length >= 1 ) {
const scaleX = array[ 0 ];
let scaleY = scaleX;
if ( array.length >= 2 ) {
scaleY = array[ 1 ];
}
currentTransform.scale( scaleX, scaleY );
}
break;
case 'skewX':
if ( array.length === 1 ) {
currentTransform.set(
1, Math.tan( array[ 0 ] * Math.PI / 180 ), 0,
0, 1, 0,
0, 0, 1
);
}
break;
case 'skewY':
if ( array.length === 1 ) {
currentTransform.set(
1, 0, 0,
Math.tan( array[ 0 ] * Math.PI / 180 ), 1, 0,
0, 0, 1
);
}
break;
case 'matrix':
if ( array.length === 6 ) {
currentTransform.set(
array[ 0 ], array[ 2 ], array[ 4 ],
array[ 1 ], array[ 3 ], array[ 5 ],
0, 0, 1
);
}
break;
}
}
transform.premultiply( currentTransform );
}
}
return transform;
}
function transformPath( path, m ) {
function transfVec2( v2 ) {
tempV3.set( v2.x, v2.y, 1 ).applyMatrix3( m );
v2.set( tempV3.x, tempV3.y );
}
const isRotated = isTransformRotated( m );
const subPaths = path.subPaths;
for ( let i = 0, n = subPaths.length; i < n; i ++ ) {
const subPath = subPaths[ i ];
const curves = subPath.curves;
for ( let j = 0; j < curves.length; j ++ ) {
const curve = curves[ j ];
if ( curve.isLineCurve ) {
transfVec2( curve.v1 );
transfVec2( curve.v2 );
} else if ( curve.isCubicBezierCurve ) {
transfVec2( curve.v0 );
transfVec2( curve.v1 );
transfVec2( curve.v2 );
transfVec2( curve.v3 );
} else if ( curve.isQuadraticBezierCurve ) {
transfVec2( curve.v0 );
transfVec2( curve.v1 );
transfVec2( curve.v2 );
} else if ( curve.isEllipseCurve ) {
if ( isRotated ) {
console.warn( 'SVGLoader: Elliptic arc or ellipse rotation or skewing is not implemented.' );
}
tempV2.set( curve.aX, curve.aY );
transfVec2( tempV2 );
curve.aX = tempV2.x;
curve.aY = tempV2.y;
curve.xRadius *= getTransformScaleX( m );
curve.yRadius *= getTransformScaleY( m );
}
}
}
}
function isTransformRotated( m ) {
return m.elements[ 1 ] !== 0 || m.elements[ 3 ] !== 0;
}
function getTransformScaleX( m ) {
const te = m.elements;
return Math.sqrt( te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] );
}
function getTransformScaleY( m ) {
const te = m.elements;
return Math.sqrt( te[ 3 ] * te[ 3 ] + te[ 4 ] * te[ 4 ] );
}
//
const paths = [];
const stylesheets = {};
const transformStack = [];
const tempTransform0 = new Matrix3();
const tempTransform1 = new Matrix3();
const tempTransform2 = new Matrix3();
const tempTransform3 = new Matrix3();
const tempV2 = new Vector2();
const tempV3 = new Vector3();
const currentTransform = new Matrix3();
const xml = new DOMParser().parseFromString( text, 'image/svg+xml' ); // application/xml
parseNode( xml.documentElement, {
fill: '#000',
fillOpacity: 1,
strokeOpacity: 1,
strokeWidth: 1,
strokeLineJoin: 'miter',
strokeLineCap: 'butt',
strokeMiterLimit: 4
} );
const data = { paths: paths, xml: xml.documentElement };
// console.log( paths );
return data;
}
static createShapes( shapePath ) {
// Param shapePath: a shapepath as returned by the parse function of this class
// Returns Shape object
const BIGNUMBER = 999999999;
const IntersectionLocationType = {
ORIGIN: 0,
DESTINATION: 1,
BETWEEN: 2,
LEFT: 3,
RIGHT: 4,
BEHIND: 5,
BEYOND: 6
};
const classifyResult = {
loc: IntersectionLocationType.ORIGIN,
t: 0
};
function findEdgeIntersection( a0, a1, b0, b1 ) {
const x1 = a0.x;
const x2 = a1.x;
const x3 = b0.x;
const x4 = b1.x;
const y1 = a0.y;
const y2 = a1.y;
const y3 = b0.y;
const y4 = b1.y;
const nom1 = ( x4 - x3 ) * ( y1 - y3 ) - ( y4 - y3 ) * ( x1 - x3 );
const nom2 = ( x2 - x1 ) * ( y1 - y3 ) - ( y2 - y1 ) * ( x1 - x3 );
const denom = ( y4 - y3 ) * ( x2 - x1 ) - ( x4 - x3 ) * ( y2 - y1 );
const t1 = nom1 / denom;
const t2 = nom2 / denom;
if ( ( ( denom === 0 ) && ( nom1 !== 0 ) ) || ( t1 <= 0 ) || ( t1 >= 1 ) || ( t2 < 0 ) || ( t2 > 1 ) ) {
//1. lines are parallel or edges don't intersect
return null;
} else if ( ( nom1 === 0 ) && ( denom === 0 ) ) {
//2. lines are colinear
//check if endpoints of edge2 (b0-b1) lies on edge1 (a0-a1)
for ( let i = 0; i < 2; i ++ ) {
classifyPoint( i === 0 ? b0 : b1, a0, a1 );
//find position of this endpoints relatively to edge1
if ( classifyResult.loc == IntersectionLocationType.ORIGIN ) {
const point = ( i === 0 ? b0 : b1 );
return { x: point.x, y: point.y, t: classifyResult.t };
} else if ( classifyResult.loc == IntersectionLocationType.BETWEEN ) {
const x = + ( ( x1 + classifyResult.t * ( x2 - x1 ) ).toPrecision( 10 ) );
const y = + ( ( y1 + classifyResult.t * ( y2 - y1 ) ).toPrecision( 10 ) );
return { x: x, y: y, t: classifyResult.t, };
}
}
return null;
} else {
//3. edges intersect
for ( let i = 0; i < 2; i ++ ) {
classifyPoint( i === 0 ? b0 : b1, a0, a1 );
if ( classifyResult.loc == IntersectionLocationType.ORIGIN ) {
const point = ( i === 0 ? b0 : b1 );
return { x: point.x, y: point.y, t: classifyResult.t };
}
}
const x = + ( ( x1 + t1 * ( x2 - x1 ) ).toPrecision( 10 ) );
const y = + ( ( y1 + t1 * ( y2 - y1 ) ).toPrecision( 10 ) );
return { x: x, y: y, t: t1 };
}
}
function classifyPoint( p, edgeStart, edgeEnd ) {
const ax = edgeEnd.x - edgeStart.x;
const ay = edgeEnd.y - edgeStart.y;
const bx = p.x - edgeStart.x;
const by = p.y - edgeStart.y;
const sa = ax * by - bx * ay;
if ( ( p.x === edgeStart.x ) && ( p.y === edgeStart.y ) ) {
classifyResult.loc = IntersectionLocationType.ORIGIN;
classifyResult.t = 0;
return;
}
if ( ( p.x === edgeEnd.x ) && ( p.y === edgeEnd.y ) ) {
classifyResult.loc = IntersectionLocationType.DESTINATION;
classifyResult.t = 1;
return;
}
if ( sa < - Number.EPSILON ) {
classifyResult.loc = IntersectionLocationType.LEFT;
return;
}
if ( sa > Number.EPSILON ) {
classifyResult.loc = IntersectionLocationType.RIGHT;
return;
}
if ( ( ( ax * bx ) < 0 ) || ( ( ay * by ) < 0 ) ) {
classifyResult.loc = IntersectionLocationType.BEHIND;
return;
}
if ( ( Math.sqrt( ax * ax + ay * ay ) ) < ( Math.sqrt( bx * bx + by * by ) ) ) {
classifyResult.loc = IntersectionLocationType.BEYOND;
return;
}
let t;
if ( ax !== 0 ) {
t = bx / ax;
} else {
t = by / ay;
}
classifyResult.loc = IntersectionLocationType.BETWEEN;
classifyResult.t = t;
}
function getIntersections( path1, path2 ) {
const intersectionsRaw = [];
const intersections = [];
for ( let index = 1; index < path1.length; index ++ ) {
const path1EdgeStart = path1[ index - 1 ];
const path1EdgeEnd = path1[ index ];
for ( let index2 = 1; index2 < path2.length; index2 ++ ) {
const path2EdgeStart = path2[ index2 - 1 ];
const path2EdgeEnd = path2[ index2 ];
const intersection = findEdgeIntersection( path1EdgeStart, path1EdgeEnd, path2EdgeStart, path2EdgeEnd );
if ( intersection !== null && intersectionsRaw.find( i => i.t <= intersection.t + Number.EPSILON && i.t >= intersection.t - Number.EPSILON ) === undefined ) {
intersectionsRaw.push( intersection );
intersections.push( new Vector2( intersection.x, intersection.y ) );
}
}
}
return intersections;
}
function getScanlineIntersections( scanline, boundingBox, paths ) {
const center = new Vector2();
boundingBox.getCenter( center );
const allIntersections = [];
paths.forEach( path => {
// check if the center of the bounding box is in the bounding box of the paths.
// this is a pruning method to limit the search of intersections in paths that can't envelop of the current path.
// if a path envelops another path. The center of that oter path, has to be inside the bounding box of the enveloping path.
if ( path.boundingBox.containsPoint( center ) ) {
const intersections = getIntersections( scanline, path.points );
intersections.forEach( p => {
allIntersections.push( { identifier: path.identifier, isCW: path.isCW, point: p } );
} );
}
} );
allIntersections.sort( ( i1, i2 ) => {
return i1.point.x - i2.point.x;
} );
return allIntersections;
}
function isHoleTo( simplePath, allPaths, scanlineMinX, scanlineMaxX, _fillRule ) {
if ( _fillRule === null || _fillRule === undefined || _fillRule === '' ) {
_fillRule = 'nonzero';
}
const centerBoundingBox = new Vector2();
simplePath.boundingBox.getCenter( centerBoundingBox );
const scanline = [ new Vector2( scanlineMinX, centerBoundingBox.y ), new Vector2( scanlineMaxX, centerBoundingBox.y ) ];
const scanlineIntersections = getScanlineIntersections( scanline, simplePath.boundingBox, allPaths );
scanlineIntersections.sort( ( i1, i2 ) => {
return i1.point.x - i2.point.x;
} );
const baseIntersections = [];
const otherIntersections = [];
scanlineIntersections.forEach( i => {
if ( i.identifier === simplePath.identifier ) {
baseIntersections.push( i );
} else {
otherIntersections.push( i );
}
} );
const firstXOfPath = baseIntersections[ 0 ].point.x;
// build up the path hierarchy
const stack = [];
let i = 0;
while ( i < otherIntersections.length && otherIntersections[ i ].point.x < firstXOfPath ) {
if ( stack.length > 0 && stack[ stack.length - 1 ] === otherIntersections[ i ].identifier ) {
stack.pop();
} else {
stack.push( otherIntersections[ i ].identifier );
}
i ++;
}
stack.push( simplePath.identifier );
if ( _fillRule === 'evenodd' ) {
const isHole = stack.length % 2 === 0 ? true : false;
const isHoleFor = stack[ stack.length - 2 ];
return { identifier: simplePath.identifier, isHole: isHole, for: isHoleFor };
} else if ( _fillRule === 'nonzero' ) {
// check if path is a hole by counting the amount of paths with alternating rotations it has to cross.
let isHole = true;
let isHoleFor = null;
let lastCWValue = null;
for ( let i = 0; i < stack.length; i ++ ) {
const identifier = stack[ i ];
if ( isHole ) {
lastCWValue = allPaths[ identifier ].isCW;
isHole = false;
isHoleFor = identifier;
} else if ( lastCWValue !== allPaths[ identifier ].isCW ) {
lastCWValue = allPaths[ identifier ].isCW;
isHole = true;
}
}
return { identifier: simplePath.identifier, isHole: isHole, for: isHoleFor };
} else {
console.warn( 'fill-rule: "' + _fillRule + '" is currently not implemented.' );
}
}
// check for self intersecting paths
// TODO
// check intersecting paths
// TODO
// prepare paths for hole detection
let identifier = 0;
let scanlineMinX = BIGNUMBER;
let scanlineMaxX = - BIGNUMBER;
let simplePaths = shapePath.subPaths.map( p => {
const points = p.getPoints();
let maxY = - BIGNUMBER;
let minY = BIGNUMBER;
let maxX = - BIGNUMBER;
let minX = BIGNUMBER;
//points.forEach(p => p.y *= -1);
for ( let i = 0; i < points.length; i ++ ) {
const p = points[ i ];
if ( p.y > maxY ) {
maxY = p.y;
}
if ( p.y < minY ) {
minY = p.y;
}
if ( p.x > maxX ) {
maxX = p.x;
}
if ( p.x < minX ) {
minX = p.x;
}
}
//
if ( scanlineMaxX <= maxX ) {
scanlineMaxX = maxX + 1;
}
if ( scanlineMinX >= minX ) {
scanlineMinX = minX - 1;
}
return { points: points, isCW: ShapeUtils.isClockWise( points ), identifier: identifier ++, boundingBox: new Box2( new Vector2( minX, minY ), new Vector2( maxX, maxY ) ) };
} );
simplePaths = simplePaths.filter( sp => sp.points.length > 0 );
// check if path is solid or a hole
const isAHole = simplePaths.map( p => isHoleTo( p, simplePaths, scanlineMinX, scanlineMaxX, shapePath.userData.style.fillRule ) );
const shapesToReturn = [];
simplePaths.forEach( p => {
const amIAHole = isAHole[ p.identifier ];
if ( ! amIAHole.isHole ) {
const shape = new Shape( p.points );
const holes = isAHole.filter( h => h.isHole && h.for === p.identifier );
holes.forEach( h => {
const path = simplePaths[ h.identifier ];
shape.holes.push( new Path( path.points ) );
} );
shapesToReturn.push( shape );
}
} );
return shapesToReturn;
}
static getStrokeStyle( width, color, lineJoin, lineCap, miterLimit ) {
// Param width: Stroke width
// Param color: As returned by THREE.Color.getStyle()
// Param lineJoin: One of "round", "bevel", "miter" or "miter-limit"
// Param lineCap: One of "round", "square" or "butt"
// Param miterLimit: Maximum join length, in multiples of the "width" parameter (join is truncated if it exceeds that distance)
// Returns style object
width = width !== undefined ? width : 1;
color = color !== undefined ? color : '#000';
lineJoin = lineJoin !== undefined ? lineJoin : 'miter';
lineCap = lineCap !== undefined ? lineCap : 'butt';
miterLimit = miterLimit !== undefined ? miterLimit : 4;
return {
strokeColor: color,
strokeWidth: width,
strokeLineJoin: lineJoin,
strokeLineCap: lineCap,
strokeMiterLimit: miterLimit
};
}
static pointsToStroke( points, style, arcDivisions, minDistance ) {
// Generates a stroke with some witdh around the given path.
// The path can be open or closed (last point equals to first point)
// Param points: Array of Vector2D (the path). Minimum 2 points.
// Param style: Object with SVG properties as returned by SVGLoader.getStrokeStyle(), or SVGLoader.parse() in the path.userData.style object
// Params arcDivisions: Arc divisions for round joins and endcaps. (Optional)
// Param minDistance: Points closer to this distance will be merged. (Optional)
// Returns BufferGeometry with stroke triangles (In plane z = 0). UV coordinates are generated ('u' along path. 'v' across it, from left to right)
const vertices = [];
const normals = [];
const uvs = [];
if ( SVGLoader.pointsToStrokeWithBuffers( points, style, arcDivisions, minDistance, vertices, normals, uvs ) === 0 ) {
return null;
}
const geometry = new BufferGeometry();
geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
geometry.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
return geometry;
}
static pointsToStrokeWithBuffers( points, style, arcDivisions, minDistance, vertices, normals, uvs, vertexOffset? ) {
// This function can be called to update existing arrays or buffers.
// Accepts same parameters as pointsToStroke, plus the buffers and optional offset.
// Param vertexOffset: Offset vertices to start writing in the buffers (3 elements/vertex for vertices and normals, and 2 elements/vertex for uvs)
// Returns number of written vertices / normals / uvs pairs
// if 'vertices' parameter is undefined no triangles will be generated, but the returned vertices count will still be valid (useful to preallocate the buffers)
// 'normals' and 'uvs' buffers are optional
const tempV2_1 = new Vector2();
const tempV2_2 = new Vector2();
const tempV2_3 = new Vector2();
const tempV2_4 = new Vector2();
const tempV2_5 = new Vector2();
const tempV2_6 = new Vector2();
const tempV2_7 = new Vector2();
const lastPointL = new Vector2();
const lastPointR = new Vector2();
const point0L = new Vector2();
const point0R = new Vector2();
const currentPointL = new Vector2();
const currentPointR = new Vector2();
const nextPointL = new Vector2();
const nextPointR = new Vector2();
const innerPoint = new Vector2();
const outerPoint = new Vector2();
arcDivisions = arcDivisions !== undefined ? arcDivisions : 12;
minDistance = minDistance !== undefined ? minDistance : 0.001;
vertexOffset = vertexOffset !== undefined ? vertexOffset : 0;
// First ensure there are no duplicated points
points = removeDuplicatedPoints( points );
const numPoints = points.length;
if ( numPoints < 2 ) return 0;
const isClosed = points[ 0 ].equals( points[ numPoints - 1 ] );
let currentPoint;
let previousPoint = points[ 0 ];
let nextPoint;
const strokeWidth2 = style.strokeWidth / 2;
const deltaU = 1 / ( numPoints - 1 );
let u0 = 0, u1;
let innerSideModified;
let joinIsOnLeftSide;
let isMiter;
let initialJoinIsOnLeftSide = false;
let numVertices = 0;
let currentCoordinate = vertexOffset * 3;
let currentCoordinateUV = vertexOffset * 2;
// Get initial left and right stroke points
getNormal( points[ 0 ], points[ 1 ], tempV2_1 ).multiplyScalar( strokeWidth2 );
lastPointL.copy( points[ 0 ] ).sub( tempV2_1 );
lastPointR.copy( points[ 0 ] ).add( tempV2_1 );
point0L.copy( lastPointL );
point0R.copy( lastPointR );
for ( let iPoint = 1; iPoint < numPoints; iPoint ++ ) {
currentPoint = points[ iPoint ];
// Get next point
if ( iPoint === numPoints - 1 ) {
if ( isClosed ) {
// Skip duplicated initial point
nextPoint = points[ 1 ];
} else nextPoint = undefined;
} else {
nextPoint = points[ iPoint + 1 ];
}
// Normal of previous segment in tempV2_1
const normal1 = tempV2_1;
getNormal( previousPoint, currentPoint, normal1 );
tempV2_3.copy( normal1 ).multiplyScalar( strokeWidth2 );
currentPointL.copy( currentPoint ).sub( tempV2_3 );
currentPointR.copy( currentPoint ).add( tempV2_3 );
u1 = u0 + deltaU;
innerSideModified = false;
if ( nextPoint !== undefined ) {
// Normal of next segment in tempV2_2
getNormal( currentPoint, nextPoint, tempV2_2 );
tempV2_3.copy( tempV2_2 ).multiplyScalar( strokeWidth2 );
nextPointL.copy( currentPoint ).sub( tempV2_3 );
nextPointR.copy( currentPoint ).add( tempV2_3 );
joinIsOnLeftSide = true;
tempV2_3.subVectors( nextPoint, previousPoint );
if ( normal1.dot( tempV2_3 ) < 0 ) {
joinIsOnLeftSide = false;
}
if ( iPoint === 1 ) initialJoinIsOnLeftSide = joinIsOnLeftSide;
tempV2_3.subVectors( nextPoint, currentPoint );
tempV2_3.normalize();
const dot = Math.abs( normal1.dot( tempV2_3 ) );
// If path is straight, don't create join
if ( dot !== 0 ) {
// Compute inner and outer segment intersections
const miterSide = strokeWidth2 / dot;
tempV2_3.multiplyScalar( - miterSide );
tempV2_4.subVectors( currentPoint, previousPoint );
tempV2_5.copy( tempV2_4 ).setLength( miterSide ).add( tempV2_3 );
innerPoint.copy( tempV2_5 ).negate();
const miterLength2 = tempV2_5.length();
const segmentLengthPrev = tempV2_4.length();
tempV2_4.divideScalar( segmentLengthPrev );
tempV2_6.subVectors( nextPoint, currentPoint );
const segmentLengthNext = tempV2_6.length();
tempV2_6.divideScalar( segmentLengthNext );
// Check that previous and next segments doesn't overlap with the innerPoint of intersection
if ( tempV2_4.dot( innerPoint ) < segmentLengthPrev && tempV2_6.dot( innerPoint ) < segmentLengthNext ) {
innerSideModified = true;
}
outerPoint.copy( tempV2_5 ).add( currentPoint );
innerPoint.add( currentPoint );
isMiter = false;
if ( innerSideModified ) {
if ( joinIsOnLeftSide ) {
nextPointR.copy( innerPoint );
currentPointR.copy( innerPoint );
} else {
nextPointL.copy( innerPoint );
currentPointL.copy( innerPoint );
}
} else {
// The segment triangles are generated here if there was overlapping
makeSegmentTriangles();
}
switch ( style.strokeLineJoin ) {
case 'bevel':
makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 );
break;
case 'round':
// Segment triangles
createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified );
// Join triangles
if ( joinIsOnLeftSide ) {
makeCircularSector( currentPoint, currentPointL, nextPointL, u1, 0 );
} else {
makeCircularSector( currentPoint, nextPointR, currentPointR, u1, 1 );
}
break;
case 'miter':
case 'miter-clip':
default:
const miterFraction = ( strokeWidth2 * style.strokeMiterLimit ) / miterLength2;
if ( miterFraction < 1 ) {
// The join miter length exceeds the miter limit
if ( style.strokeLineJoin !== 'miter-clip' ) {
makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 );
break;
} else {
// Segment triangles
createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified );
// Miter-clip join triangles
if ( joinIsOnLeftSide ) {
tempV2_6.subVectors( outerPoint, currentPointL ).multiplyScalar( miterFraction ).add( currentPointL );
tempV2_7.subVectors( outerPoint, nextPointL ).multiplyScalar( miterFraction ).add( nextPointL );
addVertex( currentPointL, u1, 0 );
addVertex( tempV2_6, u1, 0 );
addVertex( currentPoint, u1, 0.5 );
addVertex( currentPoint, u1, 0.5 );
addVertex( tempV2_6, u1, 0 );
addVertex( tempV2_7, u1, 0 );
addVertex( currentPoint, u1, 0.5 );
addVertex( tempV2_7, u1, 0 );
addVertex( nextPointL, u1, 0 );
} else {
tempV2_6.subVectors( outerPoint, currentPointR ).multiplyScalar( miterFraction ).add( currentPointR );
tempV2_7.subVectors( outerPoint, nextPointR ).multiplyScalar( miterFraction ).add( nextPointR );
addVertex( currentPointR, u1, 1 );
addVertex( tempV2_6, u1, 1 );
addVertex( currentPoint, u1, 0.5 );
addVertex( currentPoint, u1, 0.5 );
addVertex( tempV2_6, u1, 1 );
addVertex( tempV2_7, u1, 1 );
addVertex( currentPoint, u1, 0.5 );
addVertex( tempV2_7, u1, 1 );
addVertex( nextPointR, u1, 1 );
}
}
} else {
// Miter join segment triangles
if ( innerSideModified ) {
// Optimized segment + join triangles
if ( joinIsOnLeftSide ) {
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( outerPoint, u1, 0 );
addVertex( lastPointR, u0, 1 );
addVertex( outerPoint, u1, 0 );
addVertex( innerPoint, u1, 1 );
} else {
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( outerPoint, u1, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( innerPoint, u1, 0 );
addVertex( outerPoint, u1, 1 );
}
if ( joinIsOnLeftSide ) {
nextPointL.copy( outerPoint );
} else {
nextPointR.copy( outerPoint );
}
} else {
// Add extra miter join triangles
if ( joinIsOnLeftSide ) {
addVertex( currentPointL, u1, 0 );
addVertex( outerPoint, u1, 0 );
addVertex( currentPoint, u1, 0.5 );
addVertex( currentPoint, u1, 0.5 );
addVertex( outerPoint, u1, 0 );
addVertex( nextPointL, u1, 0 );
} else {
addVertex( currentPointR, u1, 1 );
addVertex( outerPoint, u1, 1 );
addVertex( currentPoint, u1, 0.5 );
addVertex( currentPoint, u1, 0.5 );
addVertex( outerPoint, u1, 1 );
addVertex( nextPointR, u1, 1 );
}
}
isMiter = true;
}
break;
}
} else {
// The segment triangles are generated here when two consecutive points are collinear
makeSegmentTriangles();
}
} else {
// The segment triangles are generated here if it is the ending segment
makeSegmentTriangles();
}
if ( ! isClosed && iPoint === numPoints - 1 ) {
// Start line endcap
addCapGeometry( points[ 0 ], point0L, point0R, joinIsOnLeftSide, true, u0 );
}
// Increment loop variables
u0 = u1;
previousPoint = currentPoint;
lastPointL.copy( nextPointL );
lastPointR.copy( nextPointR );
}
if ( ! isClosed ) {
// Ending line endcap
addCapGeometry( currentPoint, currentPointL, currentPointR, joinIsOnLeftSide, false, u1 );
} else if ( innerSideModified && vertices ) {
// Modify path first segment vertices to adjust to the segments inner and outer intersections
let lastOuter = outerPoint;
let lastInner = innerPoint;
if ( initialJoinIsOnLeftSide !== joinIsOnLeftSide ) {
lastOuter = innerPoint;
lastInner = outerPoint;
}
if ( joinIsOnLeftSide ) {
if ( isMiter || initialJoinIsOnLeftSide ) {
lastInner.toArray( vertices, 0 * 3 );
lastInner.toArray( vertices, 3 * 3 );
if ( isMiter ) {
lastOuter.toArray( vertices, 1 * 3 );
}
}
} else {
if ( isMiter || ! initialJoinIsOnLeftSide ) {
lastInner.toArray( vertices, 1 * 3 );
lastInner.toArray( vertices, 3 * 3 );
if ( isMiter ) {
lastOuter.toArray( vertices, 0 * 3 );
}
}
}
}
return numVertices;
// -- End of algorithm
// -- Functions
function getNormal( p1, p2, result ) {
result.subVectors( p2, p1 );
return result.set( - result.y, result.x ).normalize();
}
function addVertex( position, u, v ) {
if ( vertices ) {
vertices[ currentCoordinate ] = position.x;
vertices[ currentCoordinate + 1 ] = position.y;
vertices[ currentCoordinate + 2 ] = 0;
if ( normals ) {
normals[ currentCoordinate ] = 0;
normals[ currentCoordinate + 1 ] = 0;
normals[ currentCoordinate + 2 ] = 1;
}
currentCoordinate += 3;
if ( uvs ) {
uvs[ currentCoordinateUV ] = u;
uvs[ currentCoordinateUV + 1 ] = v;
currentCoordinateUV += 2;
}
}
numVertices += 3;
}
function makeCircularSector( center, p1, p2, u, v ) {
// param p1, p2: Points in the circle arc.
// p1 and p2 are in clockwise direction.
tempV2_1.copy( p1 ).sub( center ).normalize();
tempV2_2.copy( p2 ).sub( center ).normalize();
let angle = Math.PI;
const dot = tempV2_1.dot( tempV2_2 );
if ( Math.abs( dot ) < 1 ) angle = Math.abs( Math.acos( dot ) );
angle /= arcDivisions;
tempV2_3.copy( p1 );
for ( let i = 0, il = arcDivisions - 1; i < il; i ++ ) {
tempV2_4.copy( tempV2_3 ).rotateAround( center, angle );
addVertex( tempV2_3, u, v );
addVertex( tempV2_4, u, v );
addVertex( center, u, 0.5 );
tempV2_3.copy( tempV2_4 );
}
addVertex( tempV2_4, u, v );
addVertex( p2, u, v );
addVertex( center, u, 0.5 );
}
function makeSegmentTriangles() {
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( currentPointL, u1, 0 );
addVertex( lastPointR, u0, 1 );
addVertex( currentPointL, u1, 1 );
addVertex( currentPointR, u1, 0 );
}
function makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u ) {
if ( innerSideModified ) {
// Optimized segment + bevel triangles
if ( joinIsOnLeftSide ) {
// Path segments triangles
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( currentPointL, u1, 0 );
addVertex( lastPointR, u0, 1 );
addVertex( currentPointL, u1, 0 );
addVertex( innerPoint, u1, 1 );
// Bevel join triangle
addVertex( currentPointL, u, 0 );
addVertex( nextPointL, u, 0 );
addVertex( innerPoint, u, 0.5 );
} else {
// Path segments triangles
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( currentPointR, u1, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( innerPoint, u1, 0 );
addVertex( currentPointR, u1, 1 );
// Bevel join triangle
addVertex( currentPointR, u, 1 );
addVertex( nextPointR, u, 0 );
addVertex( innerPoint, u, 0.5 );
}
} else {
// Bevel join triangle. The segment triangles are done in the main loop
if ( joinIsOnLeftSide ) {
addVertex( currentPointL, u, 0 );
addVertex( nextPointL, u, 0 );
addVertex( currentPoint, u, 0.5 );
} else {
addVertex( currentPointR, u, 1 );
addVertex( nextPointR, u, 0 );
addVertex( currentPoint, u, 0.5 );
}
}
}
function createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ) {
if ( innerSideModified ) {
if ( joinIsOnLeftSide ) {
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( currentPointL, u1, 0 );
addVertex( lastPointR, u0, 1 );
addVertex( currentPointL, u1, 0 );
addVertex( innerPoint, u1, 1 );
addVertex( currentPointL, u0, 0 );
addVertex( currentPoint, u1, 0.5 );
addVertex( innerPoint, u1, 1 );
addVertex( currentPoint, u1, 0.5 );
addVertex( nextPointL, u0, 0 );
addVertex( innerPoint, u1, 1 );
} else {
addVertex( lastPointR, u0, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( currentPointR, u1, 1 );
addVertex( lastPointL, u0, 0 );
addVertex( innerPoint, u1, 0 );
addVertex( currentPointR, u1, 1 );
addVertex( currentPointR, u0, 1 );
addVertex( innerPoint, u1, 0 );
addVertex( currentPoint, u1, 0.5 );
addVertex( currentPoint, u1, 0.5 );
addVertex( innerPoint, u1, 0 );
addVertex( nextPointR, u0, 1 );
}
}
}
function addCapGeometry( center, p1, p2, joinIsOnLeftSide, start, u ) {
// param center: End point of the path
// param p1, p2: Left and right cap points
switch ( style.strokeLineCap ) {
case 'round':
if ( start ) {
makeCircularSector( center, p2, p1, u, 0.5 );
} else {
makeCircularSector( center, p1, p2, u, 0.5 );
}
break;
case 'square':
if ( start ) {
tempV2_1.subVectors( p1, center );
tempV2_2.set( tempV2_1.y, - tempV2_1.x );
tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center );
tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center );
// Modify already existing vertices
if ( joinIsOnLeftSide ) {
tempV2_3.toArray( vertices, 1 * 3 );
tempV2_4.toArray( vertices, 0 * 3 );
tempV2_4.toArray( vertices, 3 * 3 );
} else {
tempV2_3.toArray( vertices, 1 * 3 );
tempV2_3.toArray( vertices, 3 * 3 );
tempV2_4.toArray( vertices, 0 * 3 );
}
} else {
tempV2_1.subVectors( p2, center );
tempV2_2.set( tempV2_1.y, - tempV2_1.x );
tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center );
tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center );
const vl = vertices.length;
// Modify already existing vertices
if ( joinIsOnLeftSide ) {
tempV2_3.toArray( vertices, vl - 1 * 3 );
tempV2_4.toArray( vertices, vl - 2 * 3 );
tempV2_4.toArray( vertices, vl - 4 * 3 );
} else {
tempV2_3.toArray( vertices, vl - 2 * 3 );
tempV2_4.toArray( vertices, vl - 1 * 3 );
tempV2_4.toArray( vertices, vl - 4 * 3 );
}
}
break;
case 'butt':
default:
// Nothing to do here
break;
}
}
function removeDuplicatedPoints( points ) {
// Creates a new array if necessary with duplicated points removed.
// This does not remove duplicated initial and ending points of a closed path.
let dupPoints = false;
for ( let i = 1, n = points.length - 1; i < n; i ++ ) {
if ( points[ i ].distanceTo( points[ i + 1 ] ) < minDistance ) {
dupPoints = true;
break;
}
}
if ( ! dupPoints ) return points;
const newPoints = [];
newPoints.push( points[ 0 ] );
for ( let i = 1, n = points.length - 1; i < n; i ++ ) {
if ( points[ i ].distanceTo( points[ i + 1 ] ) >= minDistance ) {
newPoints.push( points[ i ] );
}
}
newPoints.push( points[ points.length - 1 ] );
return newPoints;
}
}
}
export { SVGLoader }; | the_stack |
import { gunzip } from "fflate";
import { Jiffies } from "./Jiffies";
import { SchemeType } from "./SchemeType";
type WriteCallback = (str: string) => void;
type DebugCallback = (
ptr: number,
resolver: (resultStep: boolean) => void
) => void;
class RuntimeExit extends Error {}
interface ImportPromiseResolver {
resolver: (ptr: number) => void;
promise: number;
}
export class SchemeRuntime {
private readonly module_: WebAssembly.Module;
private instance_: WebAssembly.Instance | undefined;
private exports_: WebAssembly.Exports | undefined;
private readonly unicodeData_: Record<number, ArrayBuffer> = {};
private readonly lines_: string[] = [];
private readonly writePriorityCallbacks_: WriteCallback[] = [];
private readonly writeCallbacks_: WriteCallback[] = [];
private readonly debugCallbacks_: DebugCallback[] = [];
private initialized_: boolean = false;
private env_: number = 0;
private partial_: boolean = false;
private waiting_: boolean = false;
private readonly promises_: Map<number, ImportPromiseResolver> = new Map();
private readonly jiffies_: Jiffies = Jiffies.init();
private readonly environment_: Map<string, string> = new Map();
constructor(module: WebAssembly.Module) {
this.module_ = module;
}
addEventListener(event: "write", callback: WriteCallback): void;
addEventListener(event: "write-priority", callback: WriteCallback): void;
addEventListener(event: "debug", callback: DebugCallback): void;
addEventListener(event: unknown, callback: unknown) {
if (event === "write") {
this.writeCallbacks_.push(callback as WriteCallback);
} else if (event === "write-priority") {
this.writePriorityCallbacks_.push(callback as WriteCallback);
} else if (event === "debug") {
this.debugCallbacks_.push(callback as DebugCallback);
}
}
removeEventListener(event: "write", callback: WriteCallback): void;
removeEventListener(event: "write-priority", callback: WriteCallback): void;
removeEventListener(event: "debug", callback: DebugCallback): void;
removeEventListener(event: unknown, callback: unknown) {
if (event === "write") {
const index = this.writeCallbacks_.findIndex((el) => el === callback);
if (index >= 0) {
this.writeCallbacks_.splice(index, 1);
}
} else if (event === "write-priority") {
const index = this.writePriorityCallbacks_.findIndex(
(el) => el === callback
);
if (index >= 0) {
this.writePriorityCallbacks_.splice(index, 1);
}
} else if (event === "debug") {
const index = this.debugCallbacks_.findIndex((el) => el === callback);
if (index >= 0) {
this.debugCallbacks_.splice(index, 1);
}
}
}
get instance(): WebAssembly.Instance {
if (!this.instance_) {
throw new Error("Invalid operation");
}
return this.instance_;
}
get exports(): WebAssembly.Exports {
if (!this.exports_) {
throw new Error("Invalid operation");
}
return this.exports_;
}
get replEnv(): number {
return this.env_;
}
get stopped(): boolean {
return this.instance_ === undefined;
}
get partial(): boolean {
return this.partial_;
}
get waiting(): boolean {
return this.waiting_;
}
get memory(): WebAssembly.Memory {
return this.exports.memory as WebAssembly.Memory;
}
runtimeInit() {
(this.exports.runtimeInit as () => void)();
}
mallocInit() {
(this.exports.mallocInit as () => void)();
}
runtimeCleanup() {
(this.exports.runtimeCleanup as () => void)();
}
get gHeap(): number {
return (this.exports.gHeap as WebAssembly.Global).value as number;
}
get gReader(): number {
return (this.exports.gReader as WebAssembly.Global).value as number;
}
get gNil(): number {
return (this.exports.gNil as WebAssembly.Global).value as number;
}
get gGcIsCollecting(): boolean {
return !!((this.exports.gGcIsCollecting as WebAssembly.Global)
.value as number);
}
get gGcCollectionCount(): number {
return (this.exports.gGcCollectionCount as WebAssembly.Global)
.value as number;
}
get gGcCollectedCount(): number {
return (this.exports.gGcCollectedCount as WebAssembly.Global)
.value as number;
}
get gGcTotalCollectedCount(): number {
return (this.exports.gGcTotalCollectedCount as WebAssembly.Global)
.value as number;
}
get gGcNotCollectedCount(): number {
return (this.exports.gGcNotCollectedCount as WebAssembly.Global)
.value as number;
}
get gGcTotalNotCollectedCount(): number {
return (this.exports.gGcTotalNotCollectedCount as WebAssembly.Global)
.value as number;
}
get gDebug(): boolean {
return ((this.exports.gDebug as WebAssembly.Global).value as number) != 0;
}
set gDebug(value: boolean) {
(this.exports.gDebug as WebAssembly.Global).value = value ? 1 : 0;
}
strFromCodePoints(ptr: number, len: number): number {
return (
this.exports.strFromCodePoints as (ptr: number, len: number) => number
)(ptr, len);
}
heapAllocString(str: string): number {
return (this.exports.heapAllocString as (ptr: number) => number)(
this.createString(str)
);
}
heapAllocCons(car: number, cdr: number): number {
return (this.exports.heapAllocCons as (car: number, cdr: number) => number)(
car,
cdr
);
}
heapAllocError(symbol: string, message: string): number {
return (
this.exports.heapAllocError as (symbol: number, message: number) => number
)(this.createString(symbol), this.createString(message));
}
readerRollback(reader: number) {
(this.exports.readerRollback as (reader: number) => void)(reader);
}
read(): number {
return (this.exports.read as () => number)();
}
environmentInit(heap: number, outer: number): number {
return (
this.exports.environmentInit as (heap: number, outer: number) => number
)(heap, outer);
}
registerBuiltins(heap: number, env: number) {
(this.exports.registerBuiltins as (heap: number, env: number) => void)(
heap,
env
);
}
print(ptr: number) {
(this.exports.print as (ptr: number) => void)(ptr);
}
eval(env: number, ptr: number): number {
return (this.exports.eval as (env: number, ptr: number) => number)(
env,
ptr
);
}
gcRun(env: number) {
(this.exports.gcRun as (env: number) => void)(env);
}
malloc(size: number): number {
return (this.exports.malloc as (size: number) => number)(size);
}
free(ptr: number) {
(this.exports.free as (ptr: number) => void)(ptr);
}
heapItem(ptr: number, size: number = 3): Uint32Array {
return new Uint32Array(this.memory.buffer.slice(ptr, ptr + size * 4));
}
pokeMemory(ptr: number, data: ArrayBuffer) {
const byteArray = new Uint8Array(data);
const view = new Uint8Array(this.memory.buffer);
view.set(byteArray, ptr);
}
isError(ptr: number) {
return (this.heapItem(ptr)[0] & SchemeType.Mask) == SchemeType.Error;
}
isEofError(ptr: number) {
const heapWords = this.heapItem(ptr);
if ((heapWords[0] & SchemeType.Mask) != SchemeType.Error) {
return false;
}
const symbol = this.heapItem(heapWords[1]);
return this.getString(symbol[1]) == "eof";
}
isDebugBreak(ptr: number) {
const heapWords = this.heapItem(ptr);
if ((heapWords[0] & SchemeType.Mask) != SchemeType.Cont) {
return false;
}
// continuation is conveniently the same size as a heap item
const continuation = this.heapItem(heapWords[1]);
// check the continuation function
// %debug-fn is defined as -2 in builtins.wat
return continuation[0] == 0xffff_fffe; //-2;
}
async addDebugPromise(ptr: number): Promise<number> {
const heapCons = this.heapItem(ptr);
if (!this.debugCallbacks_.length) {
return heapCons[2];
}
const p = new Promise<boolean>((resolve) => {
try {
if (this.debugCallbacks_.length == 0) {
resolve(false);
} else {
this.debugCallbacks_[0](ptr, resolve);
}
} catch (err) {
console.error(err);
resolve(false);
}
});
const evalFramePtr = heapCons[2];
const evalFrame = this.heapItem(evalFramePtr);
const argsFramePtr = evalFrame[2];
const argsFrame = this.heapItem(argsFramePtr);
const heapCont = this.heapItem(heapCons[1]);
if (heapCont[1] == 0 && heapCont[2] == 0) {
if (await p) {
// move the initial cons, two items down the continuation stack
heapCons[2] = argsFrame[2];
this.pokeMemory(ptr, heapCons.buffer);
argsFrame[2] = ptr;
this.pokeMemory(argsFramePtr, argsFrame.buffer);
//use the expression environtment
heapCont[1] = this.heapItem(evalFrame[1])[1];
// put a g-nil into the continuation frame object in the argument
// position (this allows the result to be prepended)
heapCont[2] = this.gNil;
this.pokeMemory(heapCons[1], heapCont.buffer);
}
return evalFramePtr;
} else {
await p;
heapCont[0] = -3; // skip value
this.pokeMemory(heapCons[1], heapCont.buffer);
return ptr;
}
}
isImportPromise(ptr: number) {
const heapWords = this.heapItem(ptr);
if ((heapWords[0] & SchemeType.Mask) != SchemeType.Cont) {
return false;
}
// continuation is conveniently the same size as a heap item
const continuation = this.heapItem(heapWords[1]);
// check the continuation function
// %cont-import-promise is defined as 204 in builtins.wat
return continuation[0] == 204;
}
addImportPromise(ptr: number): Promise<number> {
const heapWords = this.heapItem(ptr);
const continuation = this.heapItem(heapWords[1]);
const index = continuation[2];
return new Promise<number>((resolve) =>
this.promises_.set(index, { resolver: resolve, promise: ptr })
);
}
resolveImportPromise(promise: number, text: string): boolean {
return this.settleImportPromise(promise, this.heapAllocString(text));
}
rejectImportPromise(
promise: number,
symbol: string,
message: string
): boolean {
const value = this.heapAllocError(symbol, message);
return this.settleImportPromise(promise, value);
}
settleImportPromise(promiseIdx: number, value: number): boolean {
const promiseObj = this.promises_.get(promiseIdx);
if (!promiseObj) {
return false;
}
const { resolver, promise: ptr } = promiseObj;
const heapWords = this.heapItem(ptr);
if ((heapWords[0] & SchemeType.Mask) != SchemeType.Cont) {
throw new Error("Unexpected object in import promise list");
}
const continuation = this.heapItem(heapWords[1]);
if (continuation[0] != 204) {
throw new Error("Unexpected function in continuation");
}
if (continuation[2] !== promiseIdx) {
throw new Error("Unexpected promise in continuation");
}
// this is the promise.
continuation[0] = 0;
continuation[2] = value;
this.pokeMemory(heapWords[1], continuation.buffer);
this.promises_.delete(promiseIdx);
this.waiting_ = this.promises_.size > 0;
resolver(ptr);
return true;
}
isNil(ptr: number) {
return (this.heapItem(ptr)[0] & SchemeType.Mask) == SchemeType.Nil;
}
createString(str: string): number {
const codePoints = new Uint32Array(
Array.from(str).map((el) => el.codePointAt(0) || 0xfffd)
);
const byteArray = new Uint8Array(codePoints.buffer);
const ptr = this.malloc(codePoints.length * 4);
const view = new Uint8Array(this.memory.buffer);
view.set(byteArray, ptr);
const strPtr = this.strFromCodePoints(ptr, codePoints.length);
this.free(ptr);
return strPtr;
}
getString(ptr: number) {
const len = new Uint32Array(this.memory.buffer.slice(ptr, ptr + 4))[0];
const utf8 = new Uint8Array(len);
utf8.set(new Uint8Array(this.memory.buffer.slice(ptr + 4, ptr + len + 4)));
const str = new TextDecoder().decode(utf8);
return str;
}
reader(): number {
if (this.lines_.length == 0) {
return 0;
}
const line = this.lines_.shift() || "";
return this.createString(line);
}
writer(ptr: number) {
const str = this.getString(ptr);
this.onWrite(str);
}
onWrite(str: string) {
if (this.writePriorityCallbacks_.length) {
this.writePriorityCallbacks_.forEach((el) => el(str));
} else {
this.writeCallbacks_.forEach((el) => el(str));
}
}
close(fd: number) {
console.warn(`(port-close ${fd})`);
}
open(name: number, mode: number) {
console.warn(`(port-open ${this.getString(name)} #x${mode.toString(16)})`);
return -1;
}
exit(exitCode: number) {
throw new RuntimeExit(`Scheme exited with code: ${exitCode}`);
}
getEnvironmentVariable(name: number): number {
const value = this.environment_.get(this.getString(name));
if (typeof value === "string") {
return this.heapAllocString(value);
}
return 0;
}
getEnvironmentVariables(): number {
let tail = this.gNil;
for (const entry of this.environment_.entries()) {
const pair = this.heapAllocCons(
this.heapAllocString(entry[0]),
this.heapAllocString(entry[1])
);
tail = this.heapAllocCons(pair, tail);
}
return tail;
}
setEnvironmentVariable(name: number, value: number) {
this.environment_.set(this.getString(name), this.getString(value));
}
commandLine() {
return this.heapAllocCons(
this.heapAllocString("/usr/local/bin/scheme.wasm"),
this.gNil
);
}
unicodeLoadData(block: number, ptr: number) {
const src = new Uint8Array(this.unicodeData_[block]);
const dst = new Uint8Array(this.memory.buffer);
dst.set(src, ptr);
}
waitFor(timeoutMs: number): Promise<void> {
return new Promise<void>((resolve) => {
window.setTimeout(() => resolve(), timeoutMs);
});
}
async doFileRead(promiseIdx: number, filenamePtr: number): Promise<void> {
try {
const filename = this.getString(filenamePtr);
const response = await fetch(`./scheme/${filename}`);
if (!response.ok) {
throw new Error(response.statusText);
}
const text = await response.text();
while (!this.resolveImportPromise(promiseIdx, text)) {
await this.waitFor(100);
}
} catch (err) {
this.rejectImportPromise(
promiseIdx,
"file-read",
err instanceof Error ? err.message : "unknown"
);
console.error(err);
}
}
doRead(filenamePtr: number): number {
const word = new Uint32Array(1);
self.crypto.getRandomValues(word);
const promiseIdx = word[0];
this.doFileRead(promiseIdx, filenamePtr).catch(console.error);
return promiseIdx;
}
fileRead(filenamePtr: number) {
return this.doRead(filenamePtr);
}
async processLine(str: string): Promise<void> {
if (this.stopped) {
return;
}
if (this.waiting_) {
return;
}
try {
if (!this.initialized_) {
this.environment_.clear();
this.environment_.set("HOME", "/home/schemer");
this.environment_.set("LOGNAME", "schemer");
this.environment_.set("PATH", "/usr/local/bin:/usr/bin");
this.environment_.set("PWD", "/home/schemer");
this.environment_.set("USER", "schemer");
this.env_ = this.environmentInit(this.gHeap, 0);
this.registerBuiltins(this.gHeap, this.env_);
this.initialized_ = true;
this.lines_.push('(include "prelude.scm")\n');
}
this.lines_.push(str);
while (this.lines_.length) {
let expr = this.read();
let first = true;
if (this.isEofError(expr)) {
this.partial_ = true;
break;
} else if (expr != 0) {
while (true) {
const result = this.eval(this.env_, expr);
if (this.isDebugBreak(result)) {
expr = await this.addDebugPromise(result);
continue;
} else if (this.isImportPromise(result)) {
expr = await this.addImportPromise(result);
continue;
} else if (result != 0 && !this.isNil(result)) {
if (first) {
first = false;
} else {
this.onWrite("\n");
}
this.print(result);
}
break;
}
this.partial_ = false;
}
}
} catch (err) {
console.error(err);
this.instance_ = undefined;
this.exports_ = undefined;
this.initialized_ = false;
if (err instanceof RuntimeExit) {
this.onWrite(`\x1B[0;32m${err.message}\n`);
} else {
if (err instanceof Error && typeof err.stack == "string") {
err.stack
.split("\n")
.forEach((el) => this.onWrite(`\x1B[0;31m${el}\n`));
this.onWrite("\n");
} else {
this.onWrite(`\x1B[0;31m${err}\n`);
}
}
this.onWrite(
"\n\x1B[0;94mPress <Enter> to restart scheme runtime.\x1B[0m\n"
);
}
}
gunzipResponse(response: Response): Promise<string> {
return response.arrayBuffer().then(
(buffer) =>
new Promise((resolve, reject) =>
gunzip(new Uint8Array(buffer), (err, data) => {
if (err) {
reject(err);
} else {
resolve(new TextDecoder().decode(data));
}
})
)
);
}
async loadUnicodeBlocks() {
const response = await fetch("./unicode/blocks.json.gz");
const raw = await this.gunzipResponse(response);
const data = JSON.parse(raw);
if (typeof data !== "object") {
throw new Error("Invalid unicode block data");
}
for (const key of Object.keys(data)) {
const blockIndex = Number(key);
if (isNaN(blockIndex)) {
continue;
}
const blockData = Uint8Array.from(atob(data[key]), (c) =>
c.charCodeAt(0)
);
this.unicodeData_[blockIndex] = blockData;
}
}
async start() {
const imports: WebAssembly.Imports = {
io: {
read: () => this.reader(),
write: (ptr: number) => this.writer(ptr),
},
port: {
close: (fd: number) => this.close(fd),
open: (name: number, mode: number) => this.open(name, mode),
},
process: {
exit: (exitCode: number) => this.exit(exitCode),
getEnvironmentVariable: (name: number) =>
this.getEnvironmentVariable(name),
getEnvironmentVariables: () => this.getEnvironmentVariables(),
setEnvironmentVariable: (name: number, value: number) =>
this.setEnvironmentVariable(name, value),
commandLine: () => this.commandLine(),
},
unicode: {
loadData: (block: number, ptr: number) =>
this.unicodeLoadData(block, ptr),
},
file: {
read: (filenamePtr: number) => this.fileRead(filenamePtr),
},
time: {
currentSecond: () => Date.now() / 1000,
currentJiffy: () => this.jiffies_.current,
jiffiesPerSecond: () => this.jiffies_.jiffiesPerSecond,
},
};
this.instance_ = await WebAssembly.instantiate(this.module_, imports);
this.exports_ = this.instance.exports;
this.initialized_ = false;
}
static async load() {
const module = await WebAssembly.compileStreaming(
fetch("./wasm/scheme.wasm")
);
const runtime = new SchemeRuntime(module);
await runtime.loadUnicodeBlocks();
await runtime.start();
return runtime;
}
} | the_stack |
export enum LogLevel {
trace = 0,
info,
warn,
error
}
const INSPECTOR_LEVELS: string[] = []
INSPECTOR_LEVELS[LogLevel.trace] = 'debug'
INSPECTOR_LEVELS[LogLevel.info] = 'log'
INSPECTOR_LEVELS[LogLevel.warn] = 'warning'
INSPECTOR_LEVELS[LogLevel.error] = 'error'
// Strip the inner function in getNativeLogFunction(), if in dev also
// strip method printing to originalConsole.
// const INSPECTOR_FRAMES_TO_SKIP = globalThis.__DEV__ ? 2 : 1
// const INSPECTOR_FRAMES_TO_SKIP = 2
const groupStack = []
interface Context {
formatValueCalls: number,
seen: unknown[],
}
function groupFormat(prefix: string, msg: string) {
// Insert group formatting before the console message
return groupStack.join('') + prefix + ' ' + (msg || '')
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar: unknown): ar is unknown[] {
return Array.isArray(ar)
}
function isBoolean(arg: unknown): arg is boolean {
return typeof arg === 'boolean'
}
function isNull(arg: unknown): arg is null {
return arg === null
}
// function isNullOrUndefined(arg: unknown): arg is null | undefined {
// return arg == null
// }
function isNumber(arg: unknown): arg is number {
return typeof arg === 'number'
}
function isString(arg: unknown): arg is string {
return typeof arg === 'string'
}
// function isSymbol(arg: unknown): arg is symbol {
// return typeof arg === 'symbol'
// }
function isUndefined(arg: unknown): arg is undefined {
return arg === void 0
}
function isRegExp(re: unknown): re is RegExp {
return isObject(re) && objectToString(re) === '[object RegExp]'
}
function isObject(arg: unknown): arg is Record<string, unknown> {
return typeof arg === 'object' && arg !== null
}
function isDate(d: unknown): d is Date {
return isObject(d) && objectToString(d) === '[object Date]'
}
function isError(e: unknown): e is Error {
return (
isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error)
)
}
// eslint-disable-next-line @typescript-eslint/ban-types
function isFunction(arg: unknown): arg is Function {
return typeof arg === 'function'
}
function objectToString(o: unknown) {
return Object.prototype.toString.call(o)
}
function hasOwnProperty(obj: unknown, prop: string) {
return Object.prototype.hasOwnProperty.call(obj, prop)
}
// function formatPrimitive(ctx: Context, value: unknown) {
function formatPrimitive(value: unknown) {
// if (isUndefined(value)) return ctx.stylize('undefined', 'undefined')
if (isUndefined(value)) return 'undefined'
if (isString(value)) {
const simple =
"'" +
JSON.stringify(value)
.replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') +
"'"
// return ctx.stylize(simple, 'string')
return simple
}
// if (isNumber(value)) return ctx.stylize('' + value, 'number')
if (isNumber(value)) return '' + value
// if (isBoolean(value)) return ctx.stylize('' + value, 'boolean')
if (isBoolean(value)) return '' + value
// For some reason typeof null is "object", so special case here.
// if (isNull(value)) return ctx.stylize('null', 'null')
if (isNull(value)) return 'null'
return
}
function arrayToHash(array: string[]) {
const hash: Record<string, boolean> = {}
array.forEach(function (val) {
hash[val] = true
})
return hash
}
function formatError(value: unknown) {
return '[' + Error.prototype.toString.call(value) + ']'
}
function formatProperty(ctx: Context, value: Record<string, unknown> | unknown[], recurseTimes: number | null, visibleKeys: Record<string, boolean>, key: string, array: boolean) {
let name: string | undefined
let str = ''
const desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }
if (desc.get) {
if (desc.set) {
// str = ctx.stylize('[Getter/Setter]', 'special')
str = '[Getter/Setter]'
} else {
// str = ctx.stylize('[Getter]', 'special')
str = '[Getter]'
}
} else {
if (desc.set) {
// str = ctx.stylize('[Setter]', 'special')
str = '[Setter]'
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']'
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null)
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1)
}
if ((str).indexOf('\n') > -1) {
if (array) {
str = str
.split('\n')
.map(function (line) {
return ' ' + line
})
.join('\n')
.substr(2)
} else {
str =
'\n' +
str
.split('\n')
.map(function (line) {
return ' ' + line
})
.join('\n')
}
}
} else {
// str = ctx.stylize('[Circular]', 'special')
str = '[Circular]'
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str
}
name = JSON.stringify('' + key)
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2)
// name = ctx.stylize(name, 'name')
} else {
name = name
.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'")
// name = ctx.stylize(name, 'string')
}
}
return name + ': ' + str
}
function formatArray(ctx: Context, value: unknown[], recurseTimes: number | null, visibleKeys: Record<string, boolean>, keys: string[]) {
const output: string[] = []
for (let i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(
formatProperty(
ctx,
value,
recurseTimes,
visibleKeys,
String(i),
true,
),
)
} else {
output.push('')
}
}
keys.forEach(function (key) {
if (!key.match(/^\d+$/)) {
output.push(
formatProperty(ctx, value, recurseTimes, visibleKeys, key, true),
)
}
})
return output
}
function formatValue(ctx: Context, value: Record<string, unknown> | unknown[], recurseTimes: number | null) {
ctx.formatValueCalls++
if (ctx.formatValueCalls > 200) {
return `[TOO BIG formatValueCalls ${ctx.formatValueCalls
} exceeded limit of 200]`
}
// Primitive types cannot have properties
const primitive = formatPrimitive(value)
if (primitive) {
return primitive
}
// Look up the keys of the object.
const keys = Object.keys(value)
const visibleKeys = arrayToHash(keys)
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (
isError(value) &&
(keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)
) {
return formatError(value)
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
const name = value.name ? ': ' + value.name : ''
// return ctx.stylize('[Function' + name + ']', 'special')
return '[Function' + name + ']'
}
if (isRegExp(value)) {
// return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp')
return RegExp.prototype.toString.call(value)
}
if (isDate(value)) {
// return ctx.stylize(Date.prototype.toString.call(value), 'date')
return Date.prototype.toString.call(value)
}
if (isError(value)) {
return formatError(value)
}
}
let base = '',
array = false,
braces = ['{', '}']
// Make Array say that they are Array
if (isArray(value)) {
array = true
braces = ['[', ']']
}
// Make functions say that they are functions
if (isFunction(value)) {
const n = value.name ? ': ' + value.name : ''
base = ' [Function' + n + ']'
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value)
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value)
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value)
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1]
}
if (recurseTimes != null && recurseTimes < 0) {
if (isRegExp(value)) {
// return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp')
return RegExp.prototype.toString.call(value)
} else {
// return ctx.stylize('[Object]', 'special')
return '[Object]'
}
}
ctx.seen.push(value)
let output: string[] | undefined
if (array && isArray(value)) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys)
} else {
output = keys.map(function (key) {
return formatProperty(
ctx,
value,
recurseTimes,
visibleKeys,
key,
array,
)
})
}
ctx.seen.pop()
return reduceToSingleString(output, base, braces)
}
function reduceToSingleString(output: string[], base: string, braces: string[]) {
// let numLinesEst = 0
const length = output.reduce(function (prev, cur) {
// numLinesEst++
// if (cur.indexOf('\n') >= 0) numLinesEst++
// 清空颜色
// eslint-disable-next-line no-control-regex
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1
}, 0)
if (length > 60) {
return (
braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1]
)
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]
}
function inspect(obj: Record<string, unknown>, opts: { depth: number }) {
const ctx = {
seen: [],
formatValueCalls: 0,
// stylize: stylizeNoColor,
}
return formatValue(ctx, obj, opts.depth)
}
export function consoleAssertPolyfill(expression: unknown, label: string): void {
if (!expression) {
globalThis.nativeLoggingHook('Assertion failed: ' + label, LogLevel.error)
}
}
export function getNativeLogFunction(level: LogLevel): (...args: unknown[]) => void {
return (...args: unknown[]) => {
let str: string | undefined
if (args.length === 1 && typeof args[0] === 'string') {
str = args[0]
} else {
str = Array.prototype.map
.call(args, function (arg) {
return inspect(arg, { depth: 10 })
})
.join(', ')
}
// TRICKY
// If more than one argument is provided, the code above collapses them all
// into a single formatted string. This transform wraps string arguments in
// single quotes (e.g. "foo" -> "'foo'") which then breaks the "Warning:"
// check below. So it's important that we look at the first argument, rather
// than the formatted argument string.
const firstArg = args[0]
let logLevel = level
if (
typeof firstArg === 'string' &&
firstArg.slice(0, 9) === 'Warning: ' &&
logLevel >= LogLevel.error
) {
// Hummer warnings use console.error so that a stack trace is shown,
// but we don't (currently) want these to show a redbox
// (Note: Logic duplicated in ExceptionsManager.js.)
logLevel = LogLevel.warn
}
// if (globalThis.__inspectorLog) {
// globalThis.__inspectorLog(
// INSPECTOR_LEVELS[logLevel],
// str,
// [].slice.call(args),
// INSPECTOR_FRAMES_TO_SKIP,
// )
// }
if (groupStack.length) {
str = groupFormat('', str)
}
globalThis.nativeLoggingHook(str, logLevel)
}
} | the_stack |
import { Dispatch, SetStateAction, useState } from "react";
/**
* @internal
* @remarks \@since 2.8.5
*/
type Initializer<V extends string> = readonly V[] | (() => readonly V[]);
/**
* The change handler for indeterminate checkboxes.
*
* @param values - The current list of checked values.
* @typeParam V - The values allowed for the list of checkboxes.
* @internal
* @remarks \@since 2.8.5
*/
type OnChange<V extends string> = (values: readonly V[]) => void;
/**
* @remarks \@since 2.8.5
* @typeParam V - The values allowed for the list of checkboxes.
*/
export interface IndeterminateCheckedHookOptions<V extends string> {
/**
* Enabling this option will update the returned props to rename `onChange` to
* `onCheckedChange` to work with the {@link MenuItemCheckbox} component.
*
* @defaultValue `false`
*/
menu?: boolean;
/**
* This is the `useState` initializer that can be used if some checkboxes should
* be checked by default.
*/
onChange?: OnChange<V>;
/**
* The change handler for indeterminate checkboxes.
*
* @param values - The current list of checked values.
*/
defaultCheckedValues?: Initializer<V>;
}
/** @remarks \@since 2.8.5 */
export interface BaseProvidedIndeterminateCheckboxProps {
/**
* Note: This will only be provided when the {@link indeterminate} prop is
* `true`.
*/
"aria-checked"?: "mixed";
/**
* Boolean if the root checkbox is currently checked.
*/
checked: boolean;
/**
* This will be set to `true` when at least one checkbox has been checked but
* not every checkbox to enable the {@link CheckboxProps.indeterminate} state.
*/
indeterminate: boolean;
}
/**
* @remarks \@since 2.8.5
* @internal
*/
export interface ProvidedIndeterminateCheckboxProps
extends BaseProvidedIndeterminateCheckboxProps {
onChange(): void;
}
/**
* @remarks \@since 2.8.5
* @internal
*/
export interface ProvidedIndeterminateMenuItemCheckboxProps
extends BaseProvidedIndeterminateCheckboxProps {
onCheckedChange(): void;
}
/**
* @remarks \@since 2.8.5
* @internal
*/
interface ProvidedCombinedIndeterminateProps
extends BaseProvidedIndeterminateCheckboxProps {
onChange?(): void;
onCheckedChange?(): void;
}
/**
* @remarks \@since 2.8.5
* @typeParam V - The values allowed for the list of checkboxes.
*/
export interface BaseProvidedIndeterminateControlledCheckboxProps<
V extends string
> {
/**
* One of the values provided to the {@link useIndeterminateChecked} hook.
*/
value: V;
/**
* Boolean if the current checkbox is checked.
*/
checked: boolean;
}
/**
* @remarks \@since 2.8.5
* @typeParam V - The values allowed for the list of checkboxes.
* @internal
*/
export interface ProvidedIndeterminateControlledCheckboxProps<V extends string>
extends BaseProvidedIndeterminateControlledCheckboxProps<V> {
onChange(): void;
}
/**
* @remarks \@since 2.8.5
* @typeParam V - The values allowed for the list of checkboxes.
* @internal
*/
export interface ProvidedIndeterminateControlledMenuItemCheckboxProps<
V extends string
> extends BaseProvidedIndeterminateControlledCheckboxProps<V> {
onCheckedChange(): void;
}
/**
* @remarks \@since 2.8.5
* @typeParam V - The values allowed for the list of checkboxes.
* @internal
*/
interface ProvidedCombinedIndeterminateControlledProps<V extends string>
extends BaseProvidedIndeterminateControlledCheckboxProps<V> {
onChange?(): void;
onCheckedChange?(): void;
}
/**
* @remarks \@since 2.8.5
* @typeParam V - The values allowed for the list of checkboxes.
*/
export interface BaseIndeterminateCheckedHookReturnValue<V extends string> {
/**
* A list of all the values that are currently checked.
*/
checkedValues: readonly V[];
/**
* A function to manually override the {@link checkedValues} if the default
* hook's implementation does not work for your use-case.
*/
setCheckedValues: Dispatch<SetStateAction<readonly V[]>>;
}
/**
* @remarks \@since 2.8.5
* @typeParam V - The values allowed for the list of checkboxes.
* @internal
*/
interface OnChangeReturnValue<V extends string>
extends BaseIndeterminateCheckedHookReturnValue<V> {
rootProps: ProvidedIndeterminateCheckboxProps;
getProps(value: V): ProvidedIndeterminateControlledCheckboxProps<V>;
}
/**
* @remarks \@since 2.8.5
* @typeParam V - The values allowed for the list of checkboxes.
* @internal
*/
interface OnCheckedChangeReturnValue<V extends string>
extends BaseIndeterminateCheckedHookReturnValue<V> {
rootProps: ProvidedIndeterminateMenuItemCheckboxProps;
getProps(value: V): ProvidedIndeterminateControlledMenuItemCheckboxProps<V>;
}
/**
* @remarks \@since 2.8.5
* @typeParam V - The values allowed for the list of checkboxes.
* @internal
*/
export interface CombinedIndeterminateCheckedHookReturnValue<V extends string>
extends BaseIndeterminateCheckedHookReturnValue<V> {
rootProps: ProvidedCombinedIndeterminateProps;
getProps(value: V): ProvidedCombinedIndeterminateControlledProps<V>;
}
export function useIndeterminateChecked<V extends string>(
values: readonly V[],
options?: IndeterminateCheckedHookOptions<V> & { menu?: false }
): OnChangeReturnValue<V>;
export function useIndeterminateChecked<V extends string>(
values: readonly V[],
options: IndeterminateCheckedHookOptions<V> & { menu: true }
): OnCheckedChangeReturnValue<V>;
/**
* This hook allows you to toggle the state of multiple checkboxes in a single
* place along with an indeterminate checkbox that can check/uncheck all
* checkboxes at once.
*
* @example
* Simple value list with labels lookup:
* ```tsx
* const values = ["a", "b", "c", "d"] as const;
* const LABELS = {
* a: "Label 1",
* b: "Label 2",
* c: "Label 3",
* d: "Label 4",
* } as const;
* const { getProps, rootProps } = useIndeterminateChecked(values);
*
* return (
* <>
* <Checkbox id="root-checkbox" {...rootProps} label="Root Checkbox" />
* {values.map((value, i) => (
* <Checkbox
* id={`child-checkbox-${i + 1}`}
* label={LABELS[value]}
* {...getProps(value)}
* />
* ))}
* </>
* );
* ```
*
* @example
* Fetch Data From Server and check first result
* ```tsx
* interface ServerFetchedData {
* id: Guid;
* name: string;
* }
*
*
* const [data, setData] = useState<readonly ServerFetchedData[]>([]);
* const { getProps, rootProps, setCheckedValues } = useIndeterminateChecked(
* data.map(({ id }) => id),
* );
*
* useEffect(() => {
* let cancelled = false;
* (async function load() {
* const response = await fetch("/my-api");
* const json = await response.json();
* if (!cancelled) {
* // pretend validation and sanity checks
* setData(json);
* setCheckedValues(json[0].id);
* }
* })();
* return () => {
* cancelled = true;
* };
* }, []);
*
* return (
* <>
* <Checkbox id="root-checkbox" {...rootProps} label="Root Checkbox" />
* {data.map(({ id, name }, i) => (
* <Checkbox
* id={`child-checkbox-${i + 1}`}
* label={name}
* {...getProps(id)}
* />
* ))}
* </>
* );
* ```
*
* @example
* With MenuItemCheckbox
* ```tsx
* const values = ["a", "b", "c", "d"] as const;
* const LABELS = {
* a: "Label 1",
* b: "Label 2",
* c: "Label 3",
* d: "Label 4",
* } as const;
* const { getProps, rootProps } = useIndeterminateChecked(values, {
* menu: true,
* });
*
* return (
* <DropdownMenu
* id="dropdown-menu-id"
* items={[
* <MenuItemCheckbox
* id="dropdown-menu-id-toggle-all"
* {...rootProps}
* >
* Toggle All
* </MenuItemCheckbox>,
* ...values.map((value, i) => (
* <MenuItemCheckbox
* id={`dropdown-menu-id-${i + 1}`}
* {...getProps(value)}
* >
* {LABELS[value]}
* </MenuItemCheckbox>
* ))
* ]}
* >
* Button
* </DropdownMenu>
* );
* ```
*
* @typeParam V - The allowed values for the checkboxes
* @param values - The allowed values for the checkboxes which is used to
* control the checked states.
* @param defaultOrOptions - The {@link IndeterminateCheckedHookOptions} or a
* `useState` initializer callback/default value for backwards compatibility
* @param optionalOnChange - This is really just for backwards compatibility and
* should not be used. Use {@link IndeterminateCheckedHookOptions.onChange}
* instead.
* @returns an object containing the `rootProps` to pass to the indeterminate
* checkbox, a `getProps` function to provide the controlled behavior for the
* additional `values` in the checkbox list, a list of `checkedValues`, and a
* `setCheckedValues` function to manually override the state if needed.
*/
export function useIndeterminateChecked<V extends string>(
values: readonly V[],
{
menu = false,
onChange: propOnChange,
defaultCheckedValues = [],
}: IndeterminateCheckedHookOptions<V> = {}
): CombinedIndeterminateCheckedHookReturnValue<V> {
const [checkedValues, setCheckedValues] =
useState<readonly V[]>(defaultCheckedValues);
const checked = checkedValues.length > 0;
const indeterminate = checked && checkedValues.length < values.length;
const updateCheckedValues = (values: readonly V[]): void => {
propOnChange?.(values);
setCheckedValues(values);
};
const rootProps: ProvidedCombinedIndeterminateProps = {
"aria-checked": indeterminate ? "mixed" : undefined,
checked,
indeterminate,
[menu ? "onCheckedChange" : "onChange"]: () => {
updateCheckedValues(
checkedValues.length === 0 || indeterminate ? values : []
);
},
};
const getProps = (
value: V
): ProvidedCombinedIndeterminateControlledProps<V> => {
return {
value,
checked: checkedValues.includes(value),
[menu ? "onCheckedChange" : "onChange"]: () => {
const i = checkedValues.indexOf(value);
const nextChecked = checkedValues.slice();
if (i === -1) {
nextChecked.push(value);
} else {
nextChecked.splice(i, 1);
}
updateCheckedValues(nextChecked);
},
};
};
return {
rootProps,
getProps,
checkedValues,
setCheckedValues,
};
} | the_stack |
import { Vector } from 'matter-js';
import { IBallRouter } from './router';
import { Board } from './board';
import { Part } from 'parts/part';
import { PartType } from 'parts/factory';
import { Ball } from 'parts/ball';
import { PART_SIZE, BALL_RADIUS, SPACING } from './constants';
import { Slope, Side } from 'parts/fence';
import { GearBase } from 'parts/gearbit';
type RouteMethod = (part:Part, ball:Ball) => boolean;
// compute the ball radius and diameter in grid units
const RAD = BALL_RADIUS / SPACING;
const DIAM = 2 * RAD;
// square the diameter for fast distance tests
const DIAM_2 = DIAM * DIAM;
// the thickness of fences in grid units
const FENCE = 0.125;
// the speed at which a ball should move through schematic parts
const STEP:number = 1 / PART_SIZE;
// the offset the schematic router should move toward when routing a ball,
// which must be over 0.5 to allow the next part to capture the ball
const EXIT:number = 0.51 + RAD;
export class SchematicBallRouter implements IBallRouter {
constructor(public readonly board:Board) {
this.balls = this.board.balls;
}
public balls:Set<Ball>;
public onBoardSizeChanged() { }
public update(speed:number, correction:number):void {
const iterations:number = Math.ceil(speed * 8);
for (let i:number = 0; i < iterations; i++) {
for (const ball of this.balls) {
ball.vx = ball.vy = 0;
ball.minX = ball.maxX = ball.maxY = NaN;
if (this.routeBall(ball)) {
this.board.layoutPart(ball, ball.column, ball.row);
}
else {
this.board.removeBall(ball);
}
}
this.stackBalls();
this.moveBalls();
this.confineBalls();
GearBase.update();
}
}
protected moveBalls():void {
for (const ball of this.balls) {
const m = Math.sqrt((ball.vx * ball.vx) + (ball.vy * ball.vy));
if (m == 0.0) continue;
const d = Math.min(m, STEP);
ball.column += (ball.vx * d) / m;
ball.row += (ball.vy * d) / m;
}
}
protected confineBalls():void {
for (const ball of this.balls) {
if ((! isNaN(ball.maxX)) && (ball.column > ball.maxX)) {
ball.column = ball.maxX;
}
if ((! isNaN(ball.minX)) && (ball.column < ball.minX)) {
ball.column = ball.minX;
}
if ((! isNaN(ball.maxY)) && (ball.row > ball.maxY)) {
ball.row = ball.maxY;
}
}
}
protected routeBall(ball:Ball):boolean {
let part:Part;
let method:RouteMethod;
// confine the ball on the sides
this.checkSides(ball);
// get the part containing the ball's center
part = this.board.getPart(Math.round(ball.column), Math.round(ball.row));
if ((part) && (method = this.routeMethodForPart(part)) &&
(method.call(this, part, ball))) return(true);
// get the leading corner of the ball's location if
// we know it's moving horizontally
if (ball.lastColumn !== ball.column) {
const sign = ball.lastColumn < ball.column ? 1 : -1;
const c = ball.column + (RAD * sign);
const r = ball.row + RAD;
// get the part on the grid square containing the leading corner
part = this.board.getPart(Math.round(c), Math.round(r));
if ((part) && (method = this.routeMethodForPart(part)) &&
(method.call(this, part, ball))) return(true);
}
// if we get here, the ball was not moved, so let it fall
this.routeFreefall(ball);
if (ball.row > this.board.rowCount + 0.5) return(false);
return(true);
}
protected checkSides(ball:Ball):void {
const c = Math.round(ball.column);
const r = Math.round(ball.row);
const left = this.board.getPart(c - 1, r);
const center = this.board.getPart(c, r);
const right = this.board.getPart(c + 1, r);
if (((left) && (left.type == PartType.SIDE) && (left.isFlipped)) ||
((center) && (center.type == PartType.SIDE) && (! center.isFlipped))) {
ball.minX = c - 0.5 + RAD + (FENCE / 2);
}
if (((right) && (right.type == PartType.SIDE) && (! right.isFlipped)) ||
((center) && (center.type == PartType.SIDE) && (center.isFlipped))) {
ball.maxX = c + 0.5 - RAD - (FENCE / 2);
}
}
protected routeMethodForPart(part:Part):RouteMethod {
if (! part) return(null);
switch(part.type) {
case PartType.RAMP: return(this.routeRamp);
case PartType.CROSSOVER: return(this.routeCrossover);
case PartType.INTERCEPTOR: return(this.routeInterceptor);
case PartType.BIT: // fall-through
case PartType.GEARBIT: return(this.routeBit);
case PartType.SIDE: return(this.routeSide);
case PartType.SLOPE: return(this.routeSlope);
case PartType.DROP: return(this.routeDrop);
case PartType.TURNSTILE: return(this.routeTurnstile);
default: return(null);
}
}
protected routeRamp(part:Part, ball:Ball):boolean {
// if the ball is in the top half of the part, proceed toward the center
if (ball.row < part.row) this.approachTarget(ball, part.column, part.row);
// otherwise proceed toward the exit point
else {
this.approachTarget(ball,
part.column + (part.isFlipped ? -EXIT : EXIT), part.row + EXIT);
}
return(true);
}
protected routeCrossover(part:Part, ball:Ball):boolean {
// if the ball is in the top half of the part, proceed toward the center
if (ball.row < part.row) this.approachTarget(ball, part.column, part.row);
// in the bottom half, route based on prior direction
else if (ball.lastDistinctColumn < ball.column) { // traveling right
this.approachTarget(ball, part.column + EXIT, part.row + EXIT);
}
else { // traveling left
this.approachTarget(ball, part.column - EXIT, part.row + EXIT);
}
return(true);
}
protected routeInterceptor(part:Part, ball:Ball):boolean {
ball.minX = part.column - 0.5 + RAD;
ball.maxX = part.column + 0.5 - RAD;
ball.maxY = part.row + 0.5 - RAD;
return(this.routeFreefall(ball));
}
protected routeBit(part:Part, ball:Ball):boolean {
// if the ball is in the top half of the part, proceed toward the center,
// rotating the bit as we go
if (ball.row < part.row) {
this._initialBitValue.set(part, part.bitValue);
this.approachTarget(ball, part.column, part.row);
}
else if (! this._initialBitValue.get(part)) {
this.approachTarget(ball, part.column + EXIT, part.row + EXIT);
}
else {
this.approachTarget(ball, part.column - EXIT, part.row + EXIT);
}
// rotate the part as the ball travels through it
let r = (part.row + 0.5) - ball.row;
if (! this._initialBitValue.get(part)) r = 1.0 - r;
part.rotation = r;
return(true);
}
private _initialBitValue:WeakMap<Part,boolean> = new WeakMap();
protected routeSide(part:Part, ball:Ball):boolean {
// if the ball is contacting the side, push it inward
if (part.isFlipped) { // right side
ball.maxX = part.column + 0.5 - RAD;
}
else { // left side
ball.minX = part.column - 0.5 + RAD;
}
return(this.routeFreefall(ball));
}
protected routeSlope(part:Part, ball:Ball):boolean {
if (! (part instanceof Slope)) return(false);
// get the ball's row and column as a percentage of the part area
const r = ball.row - (part.row - 0.5);
let c = ball.column - (part.column - 0.5);
if (part.isFlipped) c = 1 - c;
// get the level the ball center should be at at that column
const m = part.modulus;
const s = part.sequence;
const level = ((c + s - FENCE) / m) - RAD;
// if the ball is above the slope, allow it to drop
if (r + STEP <= level) return(this.routeFreefall(ball));
// if the ball is well below the slope, allow it to drop
if (r > level + DIAM) return(this.routeFreefall(ball));
// the ball is near the fence, so put it on top of the fence
ball.maxY = (part.row - 0.5) + level;
// get the target column to aim for
const sign = part.isFlipped ? -1 : 1;
let target = sign * EXIT;
// roll toward the exit
this.approachTarget(ball, part.column + target,
part.row - 0.5 + ((0.5 + (target * sign) + s - FENCE) / m) - RAD);
return(true);
}
protected routeDrop(part:Part, ball:Ball):boolean {
if (ball.released) {
const sign = part.isFlipped ? -1 : 1;
this.approachTarget(ball, part.column + (sign * EXIT),
part.row + 0.5 - RAD);
}
else {
const offset = RAD + (FENCE / 2);
ball.minX = part.column - 0.5 + offset;
ball.maxX = part.column + 0.5 - offset;
ball.maxY = part.row + 0.5 - offset;
this.routeFreefall(ball);
}
return(true);
}
protected routeTurnstile(part:Part, ball:Ball):boolean {
// convert to direction and position neutral coordinates for simplicity
const sign = part.isFlipped ? -1 : 1;
let r = ball.row - part.row;
let tc = NaN;
let tr = NaN;
// lots of magic numbers here because the shape is complicated
const pocketR = -0.35;
const pocketC = 0.13;
if (r < pocketR) {
// if another ball is already rotating the turnstile,
// stop this one until that one goes through
if (part.rotation > 0.1) return(true);
tc = pocketC;
tr = pocketR;
}
else if ((part.rotation < 1.0) && (r < pocketC)) {
part.rotation += 0.01;
const v = Vector.rotate({ x: pocketC, y: pocketR },
part.angleForRotation(part.rotation) * sign);
tc = v.x;
tr = v.y;
}
else {
part.rotation = 0.0;
tr = 0.28;
tc = EXIT;
}
// if there is a target, convert back into real coordinates and route
if ((! isNaN(tc)) && (! isNaN(tr))) {
this.approachTarget(ball, part.column + (tc * sign), part.row + tr);
}
return(true);
}
protected routeFreefall(ball:Ball):boolean {
ball.vy += STEP;
return(true);
}
// move the ball toward the given location
protected approachTarget(ball:Ball, c:number, r:number):void {
let v = Vector.normalise({ x: c - ball.column, y: r - ball.row });
ball.vx += v.x * STEP;
ball.vy += v.y * STEP;
}
// BALL STACKING ************************************************************
protected stackBalls():void {
// group balls into columns containing balls that are on either side
const columns:Ball[][] = [ ];
const add = (ball:Ball, c:number) => {
if ((c < 0) || (c >= this.board.rowCount)) return;
if (columns[c] === undefined) columns[c] = [ ];
columns[c].push(ball);
};
for (const ball of this.balls) {
const center = Math.round(ball.column);
add(ball, center);
add(ball, center - 1);
add(ball, center + 1);
}
// sort the balls in each column from bottom to top
for (const c in columns) {
const column = columns[c];
if (! column) continue;
column.sort((a, b) => a.row > b.row ? -1 : a.row < b.row ? 1 : 0);
this.stackColumn(parseInt(c), column);
}
}
protected stackColumn(column:number, balls:Ball[]):void {
let ball:Ball;
let r:number, c:number, i:number, j:number, dc:number, dr:number;
const collisions:Set<Ball> = new Set();
for (i = 0; i < balls.length; i++) {
ball = balls[i];
// don't move balls from other columns, they'll be taken care of there
if (Math.round(ball.column) !== column) continue;
// iterate over balls below this one to find collisions
collisions.clear();
r = ball.row;
c = ball.column;
for (j = i - 1; j >= 0; j--) {
dc = balls[j].column - c;
dr = balls[j].row - r;
// if we find a ball more than a diameter below this one,
// the rest must be lower
if (dr > DIAM) break;
if ((dr * dr) + (dc * dc) < DIAM_2) {
collisions.add(balls[j]);
}
}
// if there are no collisions, there's nothing to do
if (collisions.size == 0) continue;
// if the ball is in contact, remove any horizontal motion
// applied by the router so far
ball.vx = 0;
// move away from each other ball
for (const b of collisions) {
let dx = ball.column - b.column;
let dy = ball.row - b.row;
const m = Math.sqrt((dx * dx) + (dy * dy));
// if two ball are directly on top of eachother, push one of them up
if (! (m > 0)) {
ball.vy -= (DIAM - STEP);
}
else {
const d = (DIAM - STEP) - m;
// add some jitter so balls don't stack up vertically
if (dx === 0.0) dx = (Math.random() - 0.5) * STEP * 0.01;
if (d > 0) {
ball.vx += (dx * d) / m;
ball.vy += (dy * d) / m;
}
}
}
}
}
} | the_stack |
import * as path from 'path';
import * as os from 'os';
import cli from 'cli-ux';
// Node
import * as fsExtra from 'fs-extra';
// Local
import { Logger, SfdxError, Messages, fs, SfdxProject } from '@salesforce/core';
import MdapiDeployApi = require('../mdapi/mdapiDeployApi');
import consts = require('../core/constants');
import MetadataRegistry = require('./metadataRegistry');
import * as syncCommandHelper from './syncCommandHelper';
import { WorkspaceFileState } from './workspaceFileState';
import { MetadataTypeFactory } from './metadataTypeFactory';
import { SourceDeployApiBase } from './sourceDeployApiBase';
import { WorkspaceElementObj } from './workspaceElement';
import { getSourceElementsFromSourcePath, createOutputDir, cleanupOutputDir } from './sourceUtil';
import { AggregateSourceElement } from './aggregateSourceElement';
import { AggregateSourceElements } from './aggregateSourceElements';
import * as PathUtils from './sourcePathUtil';
import { SourceWorkspaceAdapter } from './sourceWorkspaceAdapter';
import { SourceElementsResolver } from './sourceElementsResolver';
export interface DeployResult {
outboundFiles: WorkspaceElementObj[];
deploys?: any[];
userCanceled?: boolean;
}
export class SourceDeployApi extends SourceDeployApiBase {
private swa: SourceWorkspaceAdapter;
private isDelete: boolean;
private tmpBackupDeletions;
private DELETE_NOT_SUPPORTED_IN_CONTENT = ['StaticResource'];
static packagesDeployed: number;
// @todo we shouldn't cross the command api separation by re-using cli options as dependencies for the api.
async doDeploy(options): Promise<DeployResult> {
let aggregateSourceElements = new AggregateSourceElements();
this.isDelete = options.delete;
this.logger = await Logger.child('SourceDeployApi');
this.isAsync = options.wait === consts.MIN_SRC_DEPLOY_WAIT_MINUTES;
// Only put SWA in stateless mode when sourcepath param is used.
const mode = options.sourcepath && SourceWorkspaceAdapter.modes.STATELESS;
this.logger.debug(`mode: ${mode}`);
const sfdxProject = SfdxProject.getInstance();
const swaOptions: SourceWorkspaceAdapter.Options = {
org: this.orgApi,
metadataRegistryImpl: MetadataRegistry,
defaultPackagePath: sfdxProject.getDefaultPackage().name,
fromConvert: true,
sourceMode: mode,
};
this.swa = await SourceWorkspaceAdapter.create(swaOptions);
const packageNames = sfdxProject.getUniquePackageNames();
const tmpOutputDir = await createOutputDir('sourceDeploy');
try {
const sourceElementsResolver = new SourceElementsResolver(this.orgApi, this.swa);
if (options.sourcepath) {
this.logger.info(`Deploying metadata in sourcepath '${options.sourcepath}' to org: '${this.orgApi.name}'`);
aggregateSourceElements = await getSourceElementsFromSourcePath(options.sourcepath, this.swa);
// sourcepaths can be outside of a packageDirectory, in which case the packageName will be undefined.
// Add `undefined` as a valid package to deploy for this case.
packageNames.push(undefined);
} else if (options.manifest) {
this.logger.info(`Deploying metadata in manifest '${options.manifest}' to org: '${this.orgApi.name}'`);
aggregateSourceElements = await sourceElementsResolver.getSourceElementsFromManifest(options.manifest);
} else if (options.metadata) {
aggregateSourceElements = await sourceElementsResolver.getSourceElementsFromMetadata(
options,
aggregateSourceElements,
tmpOutputDir
);
} else if (options.validateddeployrequestid) {
// this is a quick deploy
return new MdapiDeployApi(this.orgApi).deploy(options);
} else {
// This should never happen but just a little OC - 'else if' without an 'else'
throw SfdxError.create('salesforce-alm', 'source', 'missingScopeOption');
}
SourceDeployApi.packagesDeployed = aggregateSourceElements.size;
let _handleDeleteResult = false;
if (this.isDelete) {
if (options.sourcepath) {
_handleDeleteResult = await this._handleDelete(options.noprompt, aggregateSourceElements, options.sourcepath);
} else {
// if it is the metadata option, options.sourcepath was empty. Create a path to the "source" from the MD name
_handleDeleteResult = await this._handleDelete(
options.noprompt,
aggregateSourceElements,
path.join(this.swa.defaultSrcDir, 'aura', options.metadata.split(':').pop())
);
}
if (!_handleDeleteResult) {
return { outboundFiles: [], userCanceled: true };
}
}
if (isNaN(options.wait)) {
options.wait = this.force.config.getConfigContent().defaultSrcWaitMinutes;
}
const results: DeployResult = { outboundFiles: [], deploys: [] };
if (aggregateSourceElements.size > 0) {
// Deploy AggregateSourceElements in the order specified within the project config.
for (const pkgName of packageNames) {
const aseMap = aggregateSourceElements.get(pkgName);
if (aseMap && aseMap.size) {
this.logger.info('deploying package:', pkgName);
let tmpPkgOutputDir: string;
// Clone the options object passed to this.doDeploy so options don't
// leak from 1 package deploy to the next.
const deployOptions = Object.assign({}, options);
try {
// Create a temp directory
tmpPkgOutputDir = await createOutputDir('sourceDeploy_pkg');
deployOptions.deploydir = tmpPkgOutputDir;
// change the manifest path to point to the package.xml from the
// package tmp deploy dir
deployOptions.manifest = path.join(tmpPkgOutputDir, 'package.xml');
deployOptions.ignorewarnings = deployOptions.ignorewarnings || this.isDelete;
const _ases = new AggregateSourceElements().set(pkgName, aseMap);
if (!deployOptions.checkonly) {
await this._doLocalDelete(_ases);
}
let result = await this.convertAndDeploy(deployOptions, this.swa, _ases, this.isDelete);
// If we are only checking the metadata deploy, return what `mdapi:deploy` returns.
// Otherwise process results and return similar to `source:push`
if (!deployOptions.checkonly && !this.isAsync) {
result = await this._processResults(result, _ases, deployOptions.deploydir);
}
// NOTE: This object assign is unfortunate and wrong, but we have to do it to maintain
// JSON output backwards compatibility between pre-mpd and mpd deploys.
const outboundFiles = results.outboundFiles;
Object.assign(results, result);
if (result.outboundFiles && result.outboundFiles.length) {
results.outboundFiles = [...outboundFiles, ...result.outboundFiles];
}
results.deploys.push(result);
} finally {
// Remove the sourcePathInfos.json file and delete any temp dirs
this.orgApi.getSourcePathInfos().delete();
await cleanupOutputDir(tmpPkgOutputDir);
await cleanupOutputDir(this.tmpBackupDeletions);
}
}
}
}
return results;
} finally {
await cleanupOutputDir(tmpOutputDir);
}
}
private async _doLocalDelete(ases: AggregateSourceElements) {
this.tmpBackupDeletions = await createOutputDir('sourceDelete');
const cleanedCache = new Map<string, boolean>();
ases.getAllSourceElements().forEach((ase: AggregateSourceElement) => {
ase
.getPendingDeletedWorkspaceElements()
.forEach((we) =>
fsExtra.copySync(we.getSourcePath(), path.join(this.tmpBackupDeletions, path.basename(we.getSourcePath())))
);
ase.commitDeletes([]);
const dirname = path.dirname(ase.getMetadataFilePath());
if (!cleanedCache.get(dirname)) {
const contentPaths = ase.getContentPaths(ase.getMetadataFilePath());
contentPaths.forEach((content) => {
if (content.includes('__tests__') && content.includes('lwc')) {
fs.unlinkSync(content);
}
});
// This should only be called once per type. For example if there are 1000 static resources then
// cleanEmptyDirs should be called once not 1000 times.
PathUtils.cleanEmptyDirs(dirname);
cleanedCache.set(dirname, true);
}
});
}
private async _handleDelete(noprompt: boolean, ases: AggregateSourceElements, sourcepath: string) {
let pendingDelPathsForPrompt = [];
const typedefObj = MetadataTypeFactory.getMetadataTypeFromSourcePath(sourcepath, this.swa.metadataRegistry);
const metadataType = typedefObj ? typedefObj.getMetadataName() : null;
/** delete of static resources file is not supported by cli */
if (this.DELETE_NOT_SUPPORTED_IN_CONTENT.includes(metadataType)) {
const data = fsExtra.statSync(sourcepath);
if (data.isFile()) {
throw SfdxError.create('salesforce-alm', 'source', 'StaticResourceDeleteError');
}
}
ases.getAllSourceElements().forEach((ase) => {
ase.getWorkspaceElements().some((we) => {
const type = we.getMetadataName();
const sourceMemberMetadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName(
type,
this.swa.metadataRegistry
);
const shouldDeleteWorkspaceAggregate = sourceMemberMetadataType.shouldDeleteWorkspaceAggregate(type);
if (shouldDeleteWorkspaceAggregate) {
ase.markForDelete();
return true;
} else {
// the type is decomposed and we only want to delete components of an aggregate element
const sourcepaths = sourcepath.split(',');
if (sourcepaths.some((sp) => we.getSourcePath().includes(sp.trim()))) {
we.setState(WorkspaceFileState.DELETED);
ase.addPendingDeletedWorkspaceElement(we);
}
}
});
pendingDelPathsForPrompt = pendingDelPathsForPrompt.concat(
ase.getPendingDeletedWorkspaceElements().map((el) => `${os.EOL}${el.getSourcePath()}`)
);
});
if (noprompt || pendingDelPathsForPrompt.length === 0) {
return true;
}
return this._handlePrompt(pendingDelPathsForPrompt);
}
private async _handlePrompt(pathsToPrompt: string[]): Promise<boolean> {
// @todo this prompt should no be in the API. Need to remove.
const messages = Messages.loadMessages('salesforce-alm', 'source_delete');
// the pathsToPrompt looks like [ '\n/path/to/metadata', '\n/path/to/metadata/two']
// move the \n from the front to in between each entry for proper output
const paths = pathsToPrompt.map((p) => p.substr(2)).join('\n');
const promptMessage = messages.getMessage('sourceDeletePrompt', [paths]);
const answer: string = await cli.prompt(promptMessage);
return answer.toUpperCase() === 'YES' || answer.toUpperCase() === 'Y';
}
private async _processResults(result, aggregateSourceElements: AggregateSourceElements, deployDir: string) {
if (result.success && result.details.componentFailures) {
this.removeFailedAggregates(result.details.componentFailures, aggregateSourceElements);
}
// We need to check both success and status because a status of 'SucceededPartial' returns success === true even though rollbackOnError is set.
if (result.success && result.status === 'Succeeded') {
const isNonDestructiveChangeDelete =
this.isDelete && !fsExtra.existsSync(`${deployDir}${path.sep}destructiveChangesPost.xml`);
result.outboundFiles = this.getOutboundFiles(aggregateSourceElements, isNonDestructiveChangeDelete);
return result;
} else {
// throw the error that is created by _setupDeployFail
throw await this._setupDeployFail(result, aggregateSourceElements);
}
}
private async _setupDeployFail(result, aggSourceElements: AggregateSourceElements) {
const deployFailed: any = new Error();
if (result.timedOut) {
deployFailed.name = 'PollingTimeout';
} else {
deployFailed.name = 'DeployFailed';
deployFailed.failures = syncCommandHelper.getDeployFailures(result, aggSourceElements, this.swa.metadataRegistry);
}
if (result.success && result.status === 'SucceededPartial') {
deployFailed.outboundFiles = this.getOutboundFiles(aggSourceElements);
}
if (this.isDelete) {
await this._revertDeletions(aggSourceElements);
const messages = Messages.loadMessages('salesforce-alm', 'source_delete');
deployFailed.message = messages.getMessage('sourceDeleteFailure');
}
return deployFailed;
}
// Revert all deletions since something went wrong and they were not deleted server side.
// This copies all the files from the temporary location back to their original location.
private async _revertDeletions(ases: AggregateSourceElements) {
for (const ase of ases.getAllSourceElements()) {
const parentDir = path.dirname(ase.getMetadataFilePath());
try {
await fs.access(parentDir, fs.constants.R_OK);
} catch (e) {
// If the parent directory does not exist, re-create it
await fs.mkdirp(parentDir, fs.DEFAULT_USER_DIR_MODE);
}
// Re-create each workspace element
for (const we of ase.getWorkspaceElements()) {
const backupPath = path.join(this.tmpBackupDeletions, path.basename(we.getSourcePath()));
fsExtra.copySync(backupPath, we.getSourcePath());
}
}
}
} | the_stack |
import llvm from 'llvm-node';
import ts from 'typescript';
import { Stdlib } from '../stdlib';
import * as symtab from '../symtab';
import CodeGenArray from './array-literal-expression';
import CodeGenBinary from './binary-expression';
import CodeGenBoolean from './boolean-literal-expression';
import CodeGenCall from './call-expression';
import CodeGenClassDeclaration from './class-declaration';
import CodeGenCondition from './condition-expression';
import CodeGenDo from './do-statement';
import CodeGenElemAccess from './element-access-expression';
import CodeGenEnum from './enum-declaration';
import CodeGenExport from './export-declaration';
import CodeGenForOf from './for-of-statement';
import CodeGenFor from './for-statement';
import CodeGenFuncDecl from './function-declaration';
import CodeGenGlobalObjectInt8Array from './global-object-int8array';
import CodeGenIf from './if-statement';
import CodeGenModule from './module-declaration';
import CodeGenNew from './new-expression';
import CodeGenNumeric from './numeric-expression';
import CodeGenObject from './object-literal-expression';
import CodeGenPrefixUnary from './prefix-unary-expression';
import CodeGenPropertyAccessExpression from './property-access-expression';
import CodeGenReturn from './return-statement';
import CodeGenString from './string-literal-expression';
import CodeGenVarDecl from './variable-declaration';
import CodeGenWhile from './while-statement';
export default class LLVMCodeGen {
public readonly program: ts.Program;
public readonly checker: ts.TypeChecker;
public readonly builder: llvm.IRBuilder;
public readonly context: llvm.LLVMContext;
public readonly module: llvm.Module;
public readonly symtab: symtab.Symtab;
public readonly stdlib: Stdlib;
public readonly cgArray: CodeGenArray;
public readonly cgBinary: CodeGenBinary;
public readonly cgBoolean: CodeGenBoolean;
public readonly cgCall: CodeGenCall;
public readonly cgClassDeclaration: CodeGenClassDeclaration;
public readonly cgCondition: CodeGenCondition;
public readonly cgDo: CodeGenDo;
public readonly cgElemAccess: CodeGenElemAccess;
public readonly cgEnum: CodeGenEnum;
public readonly cgExport: CodeGenExport;
public readonly cgForOf: CodeGenForOf;
public readonly cgFor: CodeGenFor;
public readonly cgFuncDecl: CodeGenFuncDecl;
public readonly cgInt8Array: CodeGenGlobalObjectInt8Array;
public readonly cgIf: CodeGenIf;
public readonly cgModule: CodeGenModule;
public readonly cgNumeric: CodeGenNumeric;
public readonly cgObject: CodeGenObject;
public readonly cgNew: CodeGenNew;
public readonly cgPrefixUnary: CodeGenPrefixUnary;
public readonly cgPropertyAccessExpression: CodeGenPropertyAccessExpression;
public readonly cgReturn: CodeGenReturn;
public readonly cgString: CodeGenString;
public readonly cgVarDecl: CodeGenVarDecl;
public readonly cgWhile: CodeGenWhile;
public currentBreakBlock: llvm.BasicBlock | undefined;
public currentContinueBlock: llvm.BasicBlock | undefined;
public currentFunction: llvm.Function | undefined;
public currentType: ts.TypeNode | undefined;
constructor(main: string) {
this.program = ts.createProgram([main], {});
this.checker = this.program.getTypeChecker();
this.context = new llvm.LLVMContext();
this.module = new llvm.Module('main', this.context);
this.builder = new llvm.IRBuilder(this.context);
this.symtab = new symtab.Symtab();
this.stdlib = new Stdlib(this);
this.cgArray = new CodeGenArray(this);
this.cgBinary = new CodeGenBinary(this);
this.cgBoolean = new CodeGenBoolean(this);
this.cgCall = new CodeGenCall(this);
this.cgClassDeclaration = new CodeGenClassDeclaration(this);
this.cgCondition = new CodeGenCondition(this);
this.cgDo = new CodeGenDo(this);
this.cgElemAccess = new CodeGenElemAccess(this);
this.cgEnum = new CodeGenEnum(this);
this.cgExport = new CodeGenExport(this);
this.cgForOf = new CodeGenForOf(this);
this.cgFor = new CodeGenFor(this);
this.cgFuncDecl = new CodeGenFuncDecl(this);
this.cgInt8Array = new CodeGenGlobalObjectInt8Array(this);
this.cgIf = new CodeGenIf(this);
this.cgModule = new CodeGenModule(this);
this.cgNumeric = new CodeGenNumeric(this);
this.cgObject = new CodeGenObject(this);
this.cgNew = new CodeGenNew(this);
this.cgPrefixUnary = new CodeGenPrefixUnary(this);
this.cgPropertyAccessExpression = new CodeGenPropertyAccessExpression(this);
this.cgReturn = new CodeGenReturn(this);
this.cgString = new CodeGenString(this);
this.cgVarDecl = new CodeGenVarDecl(this);
this.cgWhile = new CodeGenWhile(this);
this.currentBreakBlock = undefined;
this.currentContinueBlock = undefined;
this.currentFunction = undefined;
this.currentType = undefined;
}
public withFunction(func: llvm.Function, body: () => any): any {
const a = this.currentFunction;
this.currentFunction = func;
const r = body();
this.currentFunction = a;
return r;
}
public withType(type: ts.TypeNode | undefined, body: () => any): any {
const a = this.currentType;
this.currentType = type;
const r = body();
this.currentType = a;
return r;
}
public withContinueBreakBlock(c: llvm.BasicBlock, b: llvm.BasicBlock, body: () => any): any {
const rc = this.currentContinueBlock;
this.currentContinueBlock = c;
const rb = this.currentBreakBlock;
this.currentBreakBlock = b;
const r = body();
this.currentContinueBlock = rc;
this.currentBreakBlock = rb;
return r;
}
public genText(): string {
return this.module.print();
}
public genGlobalVariable(initializer: llvm.Constant): llvm.Value {
return new llvm.GlobalVariable(
this.module,
initializer.type,
false,
llvm.LinkageTypes.ExternalLinkage,
initializer
);
}
public genSourceFile(file: string): void {
this.program.getSourceFile(file)!.forEachChild(node => {
switch (node.kind) {
case ts.SyntaxKind.EndOfFileToken:
return;
case ts.SyntaxKind.VariableStatement:
this.genVariableStatement(node as ts.VariableStatement);
break;
case ts.SyntaxKind.FunctionDeclaration:
this.genFunctionDeclaration(node as ts.FunctionDeclaration);
break;
case ts.SyntaxKind.ClassDeclaration:
this.genClassDeclaration(node as ts.ClassDeclaration);
break;
case ts.SyntaxKind.EnumDeclaration:
this.genEnumDeclaration(node as ts.EnumDeclaration);
break;
case ts.SyntaxKind.ExpressionStatement:
this.genExpressionStatement(node as ts.ExpressionStatement);
break;
case ts.SyntaxKind.ModuleDeclaration:
this.genModuleDeclaration(node as ts.ModuleDeclaration);
break;
case ts.SyntaxKind.ExportDeclaration:
this.genExportDeclaration(node as ts.ExportDeclaration);
break;
default:
throw new Error('Unsupported grammar');
}
});
this.cgFuncDecl.genImplemention();
}
public genNumeric(node: ts.NumericLiteral): llvm.ConstantInt {
return this.cgNumeric.genNumeric(node);
}
public genStringLiteral(node: ts.StringLiteral): llvm.Value {
return this.cgString.genStringLiteral(node);
}
public genBoolean(node: ts.BooleanLiteral): llvm.ConstantInt {
return this.cgBoolean.genBoolean(node);
}
public genIdentifier(node: ts.Identifier): llvm.Value {
const symbol = this.symtab.get(node.getText())! as symtab.Leaf;
let r = symbol.data;
for (let i = 0; i < symbol.ptrs; i++) {
r = this.builder.createLoad(r);
}
return r;
}
public genType(type: ts.TypeNode): llvm.Type {
switch (type.kind) {
case ts.SyntaxKind.VoidKeyword:
return llvm.Type.getVoidTy(this.context);
case ts.SyntaxKind.AnyKeyword:
return llvm.Type.getInt64Ty(this.context);
case ts.SyntaxKind.BooleanKeyword:
return llvm.Type.getInt1Ty(this.context);
case ts.SyntaxKind.NumberKeyword:
return llvm.Type.getInt64Ty(this.context);
case ts.SyntaxKind.StringKeyword:
return llvm.Type.getInt8PtrTy(this.context);
case ts.SyntaxKind.TypeReference:
const real = type as ts.TypeReferenceNode;
if (real.typeName.kind === ts.SyntaxKind.Identifier) {
const typeName = (real.typeName as ts.Identifier).getText();
if (typeName === 'Int8Array') {
return llvm.Type.getInt8PtrTy(this.context);
}
const structType = this.module.getTypeByName(typeName);
if (structType) {
return structType.getPointerTo();
}
const dest = this.symtab.get(typeName);
if (symtab.isMeso(dest)) {
for (const v of dest.data.values()) {
return (v as symtab.Leaf).data.type;
}
}
throw new Error('Unsupported type'); // TODO: impl struct
}
throw new Error(`Unsupported type ${type.getText()}`);
case ts.SyntaxKind.TypeLiteral:
return this.cgObject.genObjectLiteralType(type as ts.TypeLiteralNode);
case ts.SyntaxKind.ArrayType:
const elementType = this.genType((type as ts.ArrayTypeNode).elementType);
return elementType.getPointerTo();
default:
throw new Error(`Unsupported type ${type.kind}`);
}
}
public genBlock(node: ts.Block): void {
node.statements.forEach(b => {
this.genStatement(b);
});
}
public genExpression(expr: ts.Expression): llvm.Value {
switch (expr.kind) {
case ts.SyntaxKind.NumericLiteral:
return this.genNumeric(expr as ts.NumericLiteral);
case ts.SyntaxKind.StringLiteral:
return this.genStringLiteral(expr as ts.StringLiteral);
case ts.SyntaxKind.Identifier:
return this.genIdentifier(expr as ts.Identifier);
case ts.SyntaxKind.FalseKeyword:
return this.genBoolean(expr as ts.BooleanLiteral);
case ts.SyntaxKind.TrueKeyword:
return this.genBoolean(expr as ts.BooleanLiteral);
case ts.SyntaxKind.ArrayLiteralExpression:
return this.genArrayLiteral(expr as ts.ArrayLiteralExpression);
case ts.SyntaxKind.ElementAccessExpression:
return this.genElementAccess(expr as ts.ElementAccessExpression);
case ts.SyntaxKind.CallExpression:
return this.genCallExpression(expr as ts.CallExpression);
case ts.SyntaxKind.ParenthesizedExpression:
return this.genParenthesizedExpression(expr as ts.ParenthesizedExpression);
case ts.SyntaxKind.PrefixUnaryExpression:
return this.genPrefixUnaryExpression(expr as ts.PrefixUnaryExpression);
case ts.SyntaxKind.BinaryExpression:
return this.genBinaryExpression(expr as ts.BinaryExpression);
case ts.SyntaxKind.PropertyAccessExpression:
return this.genPropertyAccessExpression(expr as ts.PropertyAccessExpression);
case ts.SyntaxKind.ObjectLiteralExpression:
return this.genObjectLiteralExpression(expr as ts.ObjectLiteralExpression);
case ts.SyntaxKind.NewExpression:
return this.genNewExpression(expr as ts.NewExpression);
case ts.SyntaxKind.ConditionalExpression:
return this.genConditionalExpression(expr as ts.ConditionalExpression);
default:
throw new Error('Unsupported expression');
}
}
public genArrayLiteral(node: ts.ArrayLiteralExpression): llvm.Value {
return this.cgArray.genArrayLiteral(node);
}
public genElementAccess(node: ts.ElementAccessExpression): llvm.Value {
return this.cgElemAccess.genElementAccessExpression(node);
}
public genCallExpression(node: ts.CallExpression): llvm.Value {
return this.cgCall.genCallExpression(node);
}
public genParenthesizedExpression(node: ts.ParenthesizedExpression): llvm.Value {
return this.genExpression(node.expression);
}
public genPrefixUnaryExpression(node: ts.PrefixUnaryExpression): llvm.Value {
return this.cgPrefixUnary.genPrefixUnaryExpression(node);
}
public genBinaryExpression(node: ts.BinaryExpression): llvm.Value {
return this.cgBinary.genBinaryExpression(node);
}
public genStatement(node: ts.Statement): llvm.Value | void {
switch (node.kind) {
case ts.SyntaxKind.Block: // 219
return this.genBlock(node as ts.Block);
case ts.SyntaxKind.VariableStatement: // 220
return this.genVariableStatement(node as ts.VariableStatement);
case ts.SyntaxKind.EmptyStatement: // 221
return;
case ts.SyntaxKind.ExpressionStatement: // 222
return this.genExpressionStatement(node as ts.ExpressionStatement);
case ts.SyntaxKind.IfStatement: // 223
return this.genIfStatement(node as ts.IfStatement);
case ts.SyntaxKind.DoStatement: // 224
return this.genDoStatement(node as ts.DoStatement);
case ts.SyntaxKind.WhileStatement: // 225
return this.genWhileStatement(node as ts.WhileStatement);
case ts.SyntaxKind.ForStatement: // 226
return this.genForStatement(node as ts.ForStatement);
case ts.SyntaxKind.ForOfStatement: // 228
return this.genForOfStatement(node as ts.ForOfStatement);
case ts.SyntaxKind.ContinueStatement: // 229
return this.genContinueStatement();
case ts.SyntaxKind.BreakStatement: // 230
return this.genBreakStatement();
case ts.SyntaxKind.ReturnStatement: // 231
return this.genReturnStatement(node as ts.ReturnStatement);
case ts.SyntaxKind.FunctionDeclaration: // 240
return this.genFunctionDeclaration(node as ts.FunctionDeclaration);
case ts.SyntaxKind.ClassDeclaration: // 241
this.genClassDeclaration(node as ts.ClassDeclaration);
return;
case ts.SyntaxKind.EnumDeclaration: // 244
return this.genEnumDeclaration(node as ts.EnumDeclaration);
default:
throw new Error('Unsupported statement');
}
}
public genVariableDeclaration(node: ts.VariableDeclaration): void {
this.cgVarDecl.genVariableDeclaration(node);
}
public genVariableStatement(node: ts.VariableStatement): void {
node.declarationList.declarations.forEach(item => {
this.genVariableDeclaration(item);
});
}
public genExpressionStatement(node: ts.ExpressionStatement): llvm.Value {
return this.genExpression(node.expression);
}
public genContinueStatement(): void {
this.builder.createBr(this.currentContinueBlock!);
}
public genBreakStatement(): void {
this.builder.createBr(this.currentBreakBlock!);
}
public genReturnStatement(node: ts.ReturnStatement): llvm.Value {
return this.cgReturn.genReturnStatement(node);
}
public genIfStatement(node: ts.IfStatement): void {
return this.cgIf.genIfStatement(node);
}
public genDoStatement(node: ts.DoStatement): void {
return this.cgDo.genDoStatement(node);
}
public genWhileStatement(node: ts.WhileStatement): void {
return this.cgWhile.genWhileStatement(node);
}
public genForStatement(node: ts.ForStatement): void {
return this.cgFor.genForStatement(node);
}
public genForOfStatement(node: ts.ForOfStatement): void {
return this.cgForOf.genForOfStatement(node);
}
// 240 ts.SyntaxKind.FunctionDeclaration
public genFunctionDeclaration(node: ts.FunctionDeclaration): void {
return this.cgFuncDecl.genFunctionDeclaration(node);
}
public genClassDeclaration(node: ts.ClassDeclaration): llvm.StructType {
return this.cgClassDeclaration.genClassDeclaration(node);
}
public genEnumDeclaration(node: ts.EnumDeclaration): void {
return this.cgEnum.genEnumDeclaration(node);
}
// 245 SyntakKind.ModuleDeclaration
public genModuleDeclaration(node: ts.ModuleDeclaration): void {
return this.cgModule.genModuleDeclaration(node);
}
public genExportDeclaration(node: ts.ExportDeclaration): void {
return this.cgExport.genExportDeclaration(node);
}
public genPropertyAccessExpression(node: ts.PropertyAccessExpression): llvm.Value {
return this.cgPropertyAccessExpression.genPropertyAccessExpression(node);
}
public genPropertyAccessExpressionPtr(node: ts.PropertyAccessExpression): llvm.Value {
return this.cgClassDeclaration.genPropertyAccessExpressionPtr(node);
}
public genObjectLiteralExpression(node: ts.ObjectLiteralExpression): llvm.Value {
return this.cgObject.genObjectLiteralExpression(node);
}
public genNewExpression(node: ts.NewExpression): llvm.Value {
return this.cgNew.genNewExpression(node);
}
public genConditionalExpression(node: ts.ConditionalExpression): llvm.Value {
return this.cgCondition.genConditionalExpression(node);
}
} | the_stack |
import { h } from "@siteimprove/alfa-dom/h";
import { test } from "@siteimprove/alfa-test";
import { Device } from "@siteimprove/alfa-device";
import { Namespace } from "@siteimprove/alfa-dom";
import { Name } from "../src";
const device = Device.standard();
test(`.from() determines the name of a text node`, (t) => {
const text = h.text("Hello world");
t.deepEqual(Name.from(text, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "data",
text: "/text()[1]",
},
],
},
});
});
test(`.from() determines the name of a <button> element with child text content`, (t) => {
const button = <button>Hello world</button>;
t.deepEqual(Name.from(button, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/button[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/button[1]/text()[1]",
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <div> element with a role of button and
with child text content`, (t) => {
const button = <div role="button">Hello world</div>;
t.deepEqual(Name.from(button, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/div[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/div[1]/text()[1]",
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <button> element with partially hidden
children`, (t) => {
const button = (
<button>
Hello world
<span style={{ display: "none" }}>!</span>
</button>
);
t.deepEqual(Name.from(button, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/button[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/button[1]/text()[1]",
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <button> element with a <span> child
element with child text content`, (t) => {
const button = (
<button>
<span>Hello world</span>
</button>
);
t.deepEqual(Name.from(button, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/button[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/button[1]/span[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/button[1]/span[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <button> element with an aria-label
attribute`, (t) => {
const button = <button aria-label="Hello world" />;
t.deepEqual(Name.from(button, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/button[1]/@aria-label",
},
],
},
});
});
test(`.from() determines the name of a <button> element with an empty aria-label
attribute and child text content`, (t) => {
const button = <button aria-label="">Hello world</button>;
t.deepEqual(Name.from(button, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/button[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/button[1]/text()[1]",
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <button> element with an aria-labelledby
attribute that points to a <p> element with child text content`, (t) => {
const button = <button aria-labelledby="foo" />;
<div>
{button}
<p id="foo">Hello world</p>
</div>;
t.deepEqual(Name.from(button, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "reference",
attribute: "/div[1]/button[1]/@aria-labelledby",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/div[1]/p[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/div[1]/p[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <button> element with an aria-labelledby
attribute that points to two <p> elements with child text content`, (t) => {
const button = <button aria-labelledby="foo bar" />;
<div>
{button}
<p id="foo">Hello</p>
<p id="bar">world</p>
</div>;
t.deepEqual(Name.from(button, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "reference",
attribute: "/div[1]/button[1]/@aria-labelledby",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/div[1]/p[1]",
name: {
value: "Hello",
sources: [
{
type: "data",
text: "/div[1]/p[1]/text()[1]",
},
],
},
},
{
type: "descendant",
element: "/div[1]/p[2]",
name: {
value: "world",
sources: [
{
type: "data",
text: "/div[1]/p[2]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <button> element with a title attribute
and no other non-whitespace child text content`, (t) => {
const button = (
<button title="Hello world">
<span> </span>
</button>
);
t.deepEqual(Name.from(button, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/button[1]/@title",
},
],
},
});
});
test(`.from() determines the name of an <img> element with an alt attribute`, (t) => {
const img = <img alt="Hello world" />;
t.deepEqual(Name.from(img, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/img[1]/@alt",
},
],
},
});
});
test(`.from() determines the name of an <a> element with a <img> child element
with an alt attribute`, (t) => {
const a = (
<a href="#">
<img alt="Hello world" />
</a>
);
t.deepEqual(Name.from(a, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]",
name: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/a[1]/img[1]/@alt",
},
],
},
},
],
},
});
});
test(`.from() rejects whitespace only content and defaults to next step`, (t) => {
const a = (
<a href="#" title="Hello world">
<span> </span>
</a>
);
t.deepEqual(Name.from(a, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/a[1]/@title",
},
],
},
});
});
test(`.from() determines the name of an <a> element with a <figure> child element
with a <img> child element with an alt attribute`, (t) => {
const a = (
<a href="#">
<figure>
<img alt="Hello world" />
</figure>
</a>
);
t.deepEqual(Name.from(a, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]/figure[1]",
name: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/a[1]/figure[1]/img[1]/@alt",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of an <a> element with text in its subtree`, (t) => {
const a = (
<a href="#" title="Content">
Hello world
</a>
);
t.deepEqual(Name.from(a, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/a[1]/text()[1]",
},
],
},
},
],
},
});
});
test(`.from() determines the name of an <a> element with text in its subtree,
when the source is nested`, (t) => {
const a = (
<a href="#" title="Content">
<span>Hello world</span>
</a>
);
t.deepEqual(Name.from(a, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]/span[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/a[1]/span[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of an <a> element with text in its subtree,
when the source is nested and doesn't itself allow naming`, (t) => {
const a = (
<a href="#" title="Content">
<p>Hello world</p>
</a>
);
t.deepEqual(Name.from(a, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]/p[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/a[1]/p[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of an <a> element with text in its subtree,
when the source is nested and presentational`, (t) => {
const a = (
<a href="#" title="Content">
<span role="none">Hello world</span>
</a>
);
t.deepEqual(Name.from(a, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]/span[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/a[1]/span[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of an <a> element with text in its subtree,
when there are multiple nested sources`, (t) => {
const a = (
<a href="#" title="Content">
<span>Hello</span> <span>world</span>
</a>
);
t.deepEqual(Name.from(a, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]",
name: {
value: "Hello",
sources: [
{
type: "descendant",
element: "/a[1]/span[1]",
name: {
value: "Hello",
sources: [
{
type: "data",
text: "/a[1]/span[1]/text()[1]",
},
],
},
},
],
},
},
{
type: "descendant",
element: "/a[1]",
name: {
value: " ",
sources: [
{
type: "data",
text: "/a[1]/text()[1]",
},
],
},
},
{
type: "descendant",
element: "/a[1]",
name: {
value: "world",
sources: [
{
type: "descendant",
element: "/a[1]/span[2]",
name: {
value: "world",
sources: [
{
type: "data",
text: "/a[1]/span[2]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() joins descendant names without a space`, (t) => {
const a = (
<a href="#">
<span>Hello</span>
<span>world</span>
</a>
);
t.deepEqual(Name.from(a, device).toJSON(), {
type: "some",
value: {
value: "Helloworld",
sources: [
{
type: "descendant",
element: "/a[1]",
name: {
value: "Hello",
sources: [
{
type: "descendant",
element: "/a[1]/span[1]",
name: {
value: "Hello",
sources: [
{
type: "data",
text: "/a[1]/span[1]/text()[1]",
},
],
},
},
],
},
},
{
type: "descendant",
element: "/a[1]",
name: {
value: "world",
sources: [
{
type: "descendant",
element: "/a[1]/span[2]",
name: {
value: "world",
sources: [
{
type: "data",
text: "/a[1]/span[2]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of an <area> element with an alt attribute`, (t) => {
const area = <area alt="Hello world" />;
t.deepEqual(Name.from(area, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/area[1]/@alt",
},
],
},
});
});
test(`.from() determines the name of a <fieldset> element with a <legend> child
element with child text content`, (t) => {
const fieldset = (
<fieldset>
<legend>Hello world</legend>
This is a fieldset
</fieldset>
);
t.deepEqual(Name.from(fieldset, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/fieldset[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/fieldset[1]/legend[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/fieldset[1]/legend[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <figure> element with a <figcaption>
child element with child text content`, (t) => {
const figure = (
<figure>
<img alt="This is an image" />
<figcaption>Hello world</figcaption>
</figure>
);
t.deepEqual(Name.from(figure, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/figure[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/figure[1]/figcaption[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/figure[1]/figcaption[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <table> element with a <caption> child
element with child text content`, (t) => {
const table = (
<table>
<caption>Hello world</caption>
<tr>
<td>This is a table cell</td>
</tr>
</table>
);
t.deepEqual(Name.from(table, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/table[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/table[1]/caption[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/table[1]/caption[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of an <input> element with a <label> parent
element with child text content`, (t) => {
const input = <input />;
<form>
<label>
Hello world
{input}
</label>
</form>;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "ancestor",
element: "/form[1]/label[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/form[1]/label[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/form[1]/label[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of an <input> element with a <label> element
whose for attribute points to the <input> element`, (t) => {
const input = <input id="foo" />;
<form>
<label for="foo">Hello world</label>
{input}
</form>;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "reference",
attribute: "/form[1]/label[1]/@for",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/form[1]/label[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/form[1]/label[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of an <input> element with both a <label>
parent element with child text content and a <label> element whose for
attribute points to the <input> element`, (t) => {
const input = <input id="foo" />;
<form>
<label>
Hello world
{input}
</label>
<label for="foo">!</label>
</form>;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Hello world !",
sources: [
{
type: "ancestor",
element: "/form[1]/label[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/form[1]/label[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/form[1]/label[1]/text()[1]",
},
],
},
},
],
},
},
{
type: "reference",
attribute: "/form[1]/label[2]/@for",
name: {
value: "!",
sources: [
{
type: "descendant",
element: "/form[1]/label[2]",
name: {
value: "!",
sources: [
{
type: "data",
text: "/form[1]/label[2]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <select> element with a <label> parent
element with child text content`, (t) => {
const select = <select />;
<form>
<label>
Hello world
{select}
</label>
</form>;
t.deepEqual(Name.from(select, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "ancestor",
element: "/form[1]/label[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/form[1]/label[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/form[1]/label[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of an <input> element with a placeholder
attribute`, (t) => {
const input = <input placeholder="Hello world" />;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/input[1]/@placeholder",
},
],
},
});
});
test(`.from() determines the name of an <input> element with a placeholder
and a title attribute, with the title attribute taking precedence`, (t) => {
const input = <input title="Hello title" placeholder="Hello placeholder" />;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Hello title",
sources: [
{
type: "label",
attribute: "/input[1]/@title",
},
],
},
});
});
test(`.from() determines the name of an <input type="button"> element with a
value attribute`, (t) => {
const input = <input type="button" value="Hello world" />;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/input[1]/@value",
},
],
},
});
});
test(`.from() determines the name of an <input type="submit"> element`, (t) => {
const input = <input type="submit" />;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Submit",
sources: [],
},
});
});
test(`.from() determines the name of an <input type="submit"> element with a
value attribute`, (t) => {
const input = <input type="submit" value="Hello world" />;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/input[1]/@value",
},
],
},
});
});
test(`.from() determines the name of an <input type="reset"> element`, (t) => {
const input = <input type="reset" />;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Reset",
sources: [],
},
});
});
test(`.from() determines the name of an <input type="reset"> element with a
value attribute`, (t) => {
const input = <input type="reset" value="Hello world" />;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/input[1]/@value",
},
],
},
});
});
test(`.from() determines the name of an <input type="image"> element`, (t) => {
const input = <input type="image" />;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Submit",
sources: [],
},
});
});
test(`.from() determines the name of an <input type="image"> element with an
alt attribute`, (t) => {
const input = <input type="image" alt="Hello world" />;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/input[1]/@alt",
},
],
},
});
});
test(`.from() determines the name of a <button> element with a role of
presentation`, (t) => {
// Due to presentational role conflict resolution, the role of `presentation`
// is ignored to ensure that the button, which is focusable, remains operable.
const button = <button role="presentation">Hello world</button>;
t.deepEqual(Name.from(button, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/button[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/button[1]/text()[1]",
},
],
},
},
],
},
});
});
test(`.from() determines the name of a <img> element with a an empty alt
attribute and an aria-label attribute`, (t) => {
// Due to presentational role conflict resolution, the role of `presentation`
// is ignored to ensure that the `aria-label` attribute, which is a global
// `aria-*` attribute, is exposed.
const img = <img alt="" aria-label="Hello world" />;
t.deepEqual(Name.from(img, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "label",
attribute: "/img[1]/@aria-label",
},
],
},
});
});
test(`.from() determines the name of an SVG <svg> element with a <title> child
element with child text content`, (t) => {
const svg = (
<svg xmlns={Namespace.SVG}>
<title xmlns={Namespace.SVG}>Hello world</title>
</svg>
);
t.deepEqual(Name.from(svg, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/svg[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/svg[1]/title[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/svg[1]/title[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() determines the name of an SVG <a> element with child text content`, (t) => {
const a = (
<a xmlns={Namespace.SVG} href="#">
Hello world
</a>
);
t.deepEqual(Name.from(a, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/a[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/a[1]/text()[1]",
},
],
},
},
],
},
});
});
test(`.from() correctly handles aria-labelledby references to hidden elements
with child elements with child text content`, (t) => {
const label = <label aria-labelledby="foo" />;
<div>
{label}
<div id="foo" hidden>
<span>Hello world</span>
</div>
</div>;
t.deepEqual(Name.from(label, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "reference",
attribute: "/div[1]/label[1]/@aria-labelledby",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/div[1]/div[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/div[1]/div[1]/span[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/div[1]/div[1]/span[1]/text()[1]",
},
],
},
},
],
},
},
],
},
},
],
},
});
});
test(`.from() correctly handles circular aria-labelledby references`, (t) => {
const foo = (
<div id="foo" aria-labelledby="bar">
Foo
</div>
);
const bar = (
<div id="bar" aria-labelledby="foo">
Bar
</div>
);
<div>
{foo}
{bar}
</div>;
t.deepEqual(Name.from(foo, device).toJSON(), {
type: "some",
value: {
value: "Bar",
sources: [
{
type: "reference",
attribute: "/div[1]/div[1]/@aria-labelledby",
name: {
value: "Bar",
sources: [
{
type: "descendant",
element: "/div[1]/div[2]",
name: {
value: "Bar",
sources: [
{
type: "data",
text: "/div[1]/div[2]/text()[1]",
},
],
},
},
],
},
},
],
},
});
t.deepEqual(Name.from(bar, device).toJSON(), {
type: "some",
value: {
value: "Foo",
sources: [
{
type: "reference",
attribute: "/div[1]/div[2]/@aria-labelledby",
name: {
value: "Foo",
sources: [
{
type: "descendant",
element: "/div[1]/div[1]",
name: {
value: "Foo",
sources: [
{
type: "data",
text: "/div[1]/div[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() correctly handles chained aria-labelledby references`, (t) => {
const foo = (
<div id="foo" aria-labelledby="bar">
Foo
</div>
);
const bar = (
<div id="bar" aria-labelledby="baz">
Bar
</div>
);
<div>
{foo}
{bar}
<div id="baz">Baz</div>
</div>;
// From the perspective of `foo`, `bar` has a name of "Bar" as the second
// `aria-labelledby` reference isn't followed.
t.deepEqual(Name.from(foo, device).toJSON(), {
type: "some",
value: {
value: "Bar",
sources: [
{
type: "reference",
attribute: "/div[1]/div[1]/@aria-labelledby",
name: {
value: "Bar",
sources: [
{
type: "descendant",
element: "/div[1]/div[2]",
name: {
value: "Bar",
sources: [
{
type: "data",
text: "/div[1]/div[2]/text()[1]",
},
],
},
},
],
},
},
],
},
});
// From the perspective of `bar`, it has a name of "Baz" as `bar` doesn't care
// about `foo` and therefore only sees a single `aria-labelledby` reference.
t.deepEqual(Name.from(bar, device).toJSON(), {
type: "some",
value: {
value: "Baz",
sources: [
{
type: "reference",
attribute: "/div[1]/div[2]/@aria-labelledby",
name: {
value: "Baz",
sources: [
{
type: "descendant",
element: "/div[1]/div[3]",
name: {
value: "Baz",
sources: [
{
type: "data",
text: "/div[1]/div[3]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() correctly handles self-referencing aria-labelledby references`, (t) => {
const foo = (
<div id="foo" aria-labelledby="foo bar">
Hello
</div>
);
<div>
{foo}
<div id="bar">world</div>
</div>;
t.deepEqual(Name.from(foo, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "reference",
attribute: "/div[1]/div[1]/@aria-labelledby",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/div[1]/div[1]",
name: {
value: "Hello",
sources: [
{
type: "data",
text: "/div[1]/div[1]/text()[1]",
},
],
},
},
{
type: "descendant",
element: "/div[1]/div[2]",
name: {
value: "world",
sources: [
{
type: "data",
text: "/div[1]/div[2]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(".from() ignores nodes that are not exposed when computing name from content", (t) => {
const heading = (
<h1>
<span>Hello</span>
<span aria-hidden="true">world</span>
</h1>
);
t.deepEqual(Name.from(heading, device).toJSON(), {
type: "some",
value: {
value: "Hello",
sources: [
{
type: "descendant",
element: "/h1[1]",
name: {
value: "Hello",
sources: [
{
type: "descendant",
element: "/h1[1]/span[1]",
name: {
value: "Hello",
sources: [
{
type: "data",
text: "/h1[1]/span[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() behaves correctly when encountering a descendant that doesn't
itself have a name, but should have one when required by an ancestor`, (t) => {
const table = <table>Hello world</table>;
const heading = <h1>{table}</h1>;
// On its own, the <table> element has no name as it's not named by its
// contents.
t.deepEqual(Name.from(table, device).toJSON(), {
type: "none",
});
// When part of an <h1> element, which is named by its content, the <table>
// element also takes its name from its content to ensure that the name
// propagates to the <h1> element.
t.deepEqual(Name.from(heading, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/h1[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/h1[1]/table[1]",
name: {
value: "Hello world",
sources: [
{
type: "data",
text: "/h1[1]/table[1]/text()[1]",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() does not use implicit <label> elements for naming <input> elements
if the <label> element has a non-matching for attribute`, (t) => {
const input = <input />;
<form>
<label for="bar">
{input}
Hello world
</label>
</form>;
t.deepEqual(Name.from(input, device).toJSON(), {
type: "none",
});
});
test(`.from() correctly assigns names to <input> elements with implicit <label>
elements even if IDs are duplicated`, (t) => {
const foo = <input id="foo" />;
const bar = <input id="foo" />;
<form>
<label>
Hello world
{foo}
</label>
<label>
Lorem ipsum
{bar}
</label>
</form>;
t.deepEqual(Name.from(foo, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "ancestor",
element: "/form[1]/label[1]",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/form[1]/label[1]",
name: {
value: "Hello world",
sources: [
{
text: "/form[1]/label[1]/text()[1]",
type: "data",
},
],
},
},
],
},
},
],
},
});
t.deepEqual(Name.from(bar, device).toJSON(), {
type: "some",
value: {
value: "Lorem ipsum",
sources: [
{
type: "ancestor",
element: "/form[1]/label[2]",
name: {
value: "Lorem ipsum",
sources: [
{
type: "descendant",
element: "/form[1]/label[2]",
name: {
value: "Lorem ipsum",
sources: [
{
text: "/form[1]/label[2]/text()[1]",
type: "data",
},
],
},
},
],
},
},
],
},
});
});
test(`.from() only associates <label> elements with for attributes with the
first matching element`, (t) => {
const foo = <input id="foo" />;
const bar = <input id="foo" />;
<form>
<label for="foo">Hello world</label>
{foo}
{bar}
</form>;
t.deepEqual(Name.from(foo, device).toJSON(), {
type: "some",
value: {
value: "Hello world",
sources: [
{
type: "reference",
attribute: "/form[1]/label[1]/@for",
name: {
value: "Hello world",
sources: [
{
type: "descendant",
element: "/form[1]/label[1]",
name: {
value: "Hello world",
sources: [
{
text: "/form[1]/label[1]/text()[1]",
type: "data",
},
],
},
},
],
},
},
],
},
});
t.deepEqual(Name.from(bar, device).toJSON(), {
type: "none",
});
}); | the_stack |
import { isBoolean } from "../typeChecks";
/**
* A setter functor for HTML attributes.
**/
export class Attr {
readonly tags: readonly string[];
/**
* Creates a new setter functor for HTML Attributes
* @param key - the attribute name.
* @param value - the value to set for the attribute.
* @param tags - the HTML tags that support this attribute.
*/
constructor(
public readonly key: string,
public readonly value: any,
private readonly bySetAttribute: boolean,
...tags: string[]) {
this.tags = tags.map(t => t.toLocaleUpperCase());
Object.freeze(this);
}
/**
* Set the attribute value on an HTMLElement
* @param elem - the element on which to set the attribute.
*/
applyToElement(elem: HTMLElement) {
const isDataSet = this.key.startsWith("data-");
const isValid = this.tags.length === 0
|| this.tags.indexOf(elem.tagName) > -1
|| isDataSet;
if (!isValid) {
console.warn(`Element ${elem.tagName} does not support Attribute ${this.key}`);
}
else if (isDataSet) {
const subkey = this.key.substring(5);
elem.dataset[subkey] = this.value;
}
else if (this.key === "style") {
Object.assign(elem.style, this.value);
}
else if (this.bySetAttribute) {
elem.setAttribute(this.key, this.value);
}
else if (this.key in elem) {
(elem as any)[this.key] = this.value;
}
else if (this.value === false) {
elem.removeAttribute(this.key);
}
else if (this.value === true) {
elem.setAttribute(this.key, "");
}
else {
elem.setAttribute(this.key, this.value);
}
}
}
/**
* a list of types the server accepts, typically a file type.
* @param value - the value to set on the attribute.
**/
export function accept(value: string) { return new Attr("accept", value, false, "form", "input"); }
/**
* The accessKey attribute
**/
export function accessKey(value: string) { return new Attr("accessKey", value, false, "input", "button"); }
/**
* specifying the horizontal alignment of the element.
**/
export function align(value: string) { return new Attr("align", value, false, "applet", "caption", "col", "colgroup", "hr", "iframe", "img", "table", "tbody", "td", "tfoot", "th", "thead", "tr"); }
/**
* Specifies a feature-policy for the iframe.
**/
export function allow(value: string) { return new Attr("allow", value, false, "iframe"); }
/**
* Alternative text in case an image can't be displayed.
**/
export function alt(value: string) { return new Attr("alt", value, false, "applet", "area", "img", "input"); }
/**
* Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application.
**/
export function ariaActiveDescendant(value: string) { return new Attr("ariaActiveDescendant", value, false); }
/**
* Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute.
**/
export function ariaAtomic(value: boolean) { return new Attr("ariaAtomic", value, false); }
/**
* Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be presented if they are made.
**/
export function ariaAutoComplete(value: string) { return new Attr("ariaAutoComplete", value, false); }
/**
* Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user.
**/
export function ariaBusy(value: boolean) { return new Attr("ariaBusy", value, false); }
/**
* Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. See related aria-pressed and aria-selected.
**/
export function ariaChecked(value: boolean) { return new Attr("ariaChecked", value, false); }
/**
* Defines the total number of columns in a table, grid, or treegrid. See related aria-colindex.
**/
export function ariaColCount(value: number) { return new Attr("ariaColCount", value, false); }
/**
* Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. See related aria-colcount and aria-colspan.
**/
export function ariaColIndex(value: number) { return new Attr("ariaColIndex", value, false); }
/**
* Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. See related aria-colindex and aria-rowspan.
**/
export function ariaColSpan(value: number) { return new Attr("ariaColSpan", value, false); }
/**
* Identifies the element (or elements) whose contents or presence are controlled by the current element. See related aria-owns.
**/
export function ariaControls(value: string) { return new Attr("ariaControls", value, false); }
/**
* Indicates the element that represents the current item within a container or set of related elements.
**/
export function ariaCurrent(value: string) { return new Attr("ariaCurrent", value, false); }
/**
* Identifies the element (or elements) that describes the object. See related aria-labelledby.
**/
export function ariaDescribedBy(value: string) { return new Attr("ariaDescribedBy", value, false); }
/**
* Identifies the element that provides a detailed, extended description for the object. See related aria-describedby.
**/
export function ariaDetails(value: string) { return new Attr("ariaDetails", value, false); }
/**
* Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. See related aria-hidden and aria-readonly.
**/
export function ariaDisabled(value: boolean) { return new Attr("ariaDisabled", value, false); }
/**
* Identifies the element that provides an error message for the object. See related aria-invalid and aria-describedby.
**/
export function ariaErrorMessage(value: string) { return new Attr("ariaErrorMessage", value, false); }
/**
* Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed.
**/
export function ariaExpanded(value: boolean) { return new Attr("ariaExpanded", value, false); }
/**
* Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, allows assistive technology to override the general default of reading in document source order.
**/
export function ariaFlowTo(value: string) { return new Attr("ariaFlowTo", value, false); }
/**
* Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element.
**/
export function ariaHasPopup(value: string) { return new Attr("ariaHasPopup", value, false); }
/**
* Indicates whether the element is exposed to an accessibility API. See related aria-disabled.
**/
export function ariaHidden(value: boolean) { return new Attr("ariaHidden", value, false); }
/**
* Indicates the entered value does not conform to the format expected by the application. See related aria-errormessage.
**/
export function ariaInvalid(value: string) { return new Attr("ariaInvalid", value, false); }
/**
* Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element.
**/
export function ariaKeyShortcuts(value: string) { return new Attr("ariaKeyShortcuts", value, false); }
/**
* Defines a string value that labels the current element. See related aria-labelledby.
**/
export function ariaLabel(value: string) { return new Attr("ariaLabel", value, false); }
/**
* Identifies the element (or elements) that labels the current element. See related aria-describedby.
**/
export function ariaLabelledBy(value: string) { return new Attr("ariaLabelledBy", value, false); }
/**
* Defines the hierarchical level of an element within a structure.
**/
export function ariaLevel(value: number) { return new Attr("ariaLevel", value, false); }
/**
* Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.
**/
export function ariaLive(value: string) { return new Attr("ariaLive", value, false); }
/**
* Indicates whether an element is modal when displayed
**/
export function ariaModal(value: boolean) { return new Attr("ariaModal", value, false); }
/**
* Indicates whether a text box accepts multiple lines of input or only a single line.
**/
export function ariaMultiline(value: boolean) { return new Attr("ariaMultiline", value, false); }
/**
* Indicates that the user may select more than one item from the current selectable descendants.
**/
export function ariaMultiSelectable(value: boolean) { return new Attr("ariaMultiSelectable", value, false); }
/**
* Indicates that the user may select more than one item from the current selectable descendants.
**/
export function ariaOrientation(value: string) { return new Attr("ariaOrientation", value, false); }
/**
* Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship between DOM elements where the DOM hierarchy cannot be used to represent the relationship. See related aria-controls.
**/
export function ariaOwns(value: string) { return new Attr("ariaOwns", value, false); }
/**
* Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. A hint could be a sample value or a brief description of the expected format.
**/
export function ariaPlaceholder(value: string) { return new Attr("ariaPlaceholder", value, false); }
/**
* Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. See related aria-setsize.
**/
export function ariaPosInSet(value: number) { return new Attr("ariaPosInSet", value, false); }
/**
* Indicates the current "pressed" state of toggle buttons. See related aria-checked and aria-selected.
**/
export function ariaPressed(value: boolean) { return new Attr("ariaPressed", value, false); }
/**
* Indicates that the element is not editable, but is otherwise operable. See related aria-disabled.
**/
export function ariaReadOnly(value: boolean) { return new Attr("ariaReadOnly", value, false); }
/**
* Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. See related aria-atomic.
**/
export function ariaRelevant(value: string) { return new Attr("ariaRelevant", value, false); }
/**
* Indicates that user input is required on the element before a form may be submitted.
**/
export function ariaRequired(value: boolean) { return new Attr("ariaRequired", value, false); }
/**
* Defines a human-readable, author-localized description for the role of an element.
**/
export function ariaRoleDescription(value: string) { return new Attr("ariaRoleDescription", value, false); }
/**
* Defines the total number of rows in a table, grid, or treegrid. See related aria-rowindex.
**/
export function ariaRowCount(value: number) { return new Attr("ariaRowCount", value, false); }
/**
* Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. See related aria-rowcount and aria-rowspan.
**/
export function ariaRowIndex(value: number) { return new Attr("ariaRowIndex", value, false); }
/**
Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. See related aria-rowindex and aria-colspan.
**/
export function ariaRowSpan(value: number) { return new Attr("ariaRowSpan", value, false); }
/**
* Indicates the current "selected" state of various widgets. See related aria-checked and aria-pressed.
**/
export function ariaSelected(value: boolean) { return new Attr("ariaSelected", value, false); }
/**
* Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. See related aria-posinset.
**/
export function ariaSetSize(value: number) { return new Attr("ariaSetsize", value, false); }
/**
* Indicates if items in a table or grid are sorted in ascending or descending order.
**/
export function ariaSort(value: string) { return new Attr("ariaSort", value, false); }
/**
* Defines the maximum allowed value for a range widget.
**/
export function ariaValueMax(value: number) { return new Attr("ariaValueMax", value, false); }
/**
* Defines the minimum allowed value for a range widget.
**/
export function ariaValueMin(value: number) { return new Attr("ariaValueMin", value, false); }
/**
* Defines the current value for a range widget. See related aria-valuetext.
**/
export function ariaValueNow(value: number) { return new Attr("ariaValueNow", value, false); }
/**
* Defines the human readable text alternative of aria-valuenow for a range widget.
**/
export function ariaValueText(value: string) { return new Attr("ariaValueText", value, false); }
/**
* Executes the script asynchronously.
**/
export function async(value: string) { return new Attr("async", value, false, "script"); }
/**
* Sets whether input is automatically capitalized when entered by user
**/
export function autoCapitalize(value: boolean) { return new Attr("autocapitalize", value, false); }
/**
* Indicates whether controls in this form can by default have their values automatically completed by the browser.
**/
export function autoComplete(value: boolean) { return new Attr("autocomplete", value ? "on" : "off", false, "form", "input", "select", "textarea"); }
/**
* The element should be automatically focused after the page loaded.
**/
export function autoFocus(value: boolean) { return new Attr("autofocus", value, false, "button", "input", "keygen", "select", "textarea"); }
/**
* The audio or video should play as soon as possible.
**/
export function autoPlay(value: boolean) { return new Attr("autoplay", value, false, "audio", "video"); }
/**
* Contains the time range of already buffered media.
**/
export function buffered(value: boolean) { return new Attr("buffered", value, false, "audio", "video"); }
/**
* From the HTML Media Capture
**/
export function capture(value: boolean) { return new Attr("capture", value, false, "input"); }
/**
* Declares the character encoding of the page or script.
**/
export function charSet(value: string) { return new Attr("charset", value, false, "meta", "script"); }
/**
* Indicates whether the element should be checked on page load.
**/
export function checked(value: boolean) { return new Attr("checked", value, false, "command", "input"); }
/**
* Contains a URI which points to the source of the quote or change.
**/
export function cite(value: string) { return new Attr("cite", value, false, "blockquote", "del", "ins", "q"); }
/**
* Often used with CSS to style elements with common properties.
**/
export function className(value: string) { return new Attr("className", value, false); }
/**
* Specifies the URL of the applet's class file to be loaded and executed.
**/
export function code(value: string) { return new Attr("code", value, false, "applet"); }
/**
* This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored.
**/
export function codeBase(value: string) { return new Attr("codebase", value, false, "applet"); }
/**
* Defines the number of columns in a textarea.
**/
export function cols(value: number) { return new Attr("cols", value, false, "textarea"); }
/**
* The colspan attribute defines the number of columns a cell should span.
**/
export function colSpan(value: number) { return new Attr("colspan", value, false, "td", "th"); }
/**
* A value associated with http-equiv or name depending on the context.
**/
export function content(value: string) { return new Attr("content", value, false, "meta"); }
/**
* Indicates whether the element's content is editable.
**/
export function contentEditable(value: string) { return new Attr("contenteditable", value, false); }
/**
* Defines the ID of a <menu> element which will serve as the element's context menu.
**/
export function contextMenu(value: string) { return new Attr("contextmenu", value, false); }
/**
* Indicates whether the browser should show playback controls to the user.
**/
export function controls(value: boolean) { return new Attr("controls", value, false, "audio", "video"); }
/**
* A set of values specifying the coordinates of the hot-spot region.
**/
export function coords(value: string) { return new Attr("coords", value, false, "area"); }
/**
* How the element handles cross-origin requests
**/
export function crossOrigin(value: string) { return new Attr("crossorigin", value, false, "audio", "img", "link", "script", "video"); }
/**
* Specifies the Content Security Policy that an embedded document must agree to enforce upon itself.
**/
export function csp(value: string) { return new Attr("csp", value, false, "iframe"); }
/**
* Specifies the URL of the resource.
**/
export function data(value: string) { return new Attr("data", value, false, "object"); }
/**
* Lets you attach custom attributes to an HTML element.
*/
export function customData(name: string, value: any) { return new Attr("data-" + name, value, false); }
/**
* Indicates the date and time associated with the element.
**/
export function dateTime(value: Date) { return new Attr("datetime", value, false, "del", "ins", "time"); }
/**
* Indicates the preferred method to decode the image.
**/
export function decoding(value: string) { return new Attr("decoding", value, false, "img"); }
/**
* Indicates that the track should be enabled unless the user's preferences indicate something different.
**/
export function htmlDefault(value: boolean|string) { return new Attr("default", value, false, "track"); }
/**
* Indicates that the script should be executed after the page has been parsed.
**/
export function defer(value: boolean) { return new Attr("defer", value, false, "script"); }
/**
* Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
**/
export function dir(value: string) { return new Attr("dir", value, false); }
/**
* Indicates whether the user can interact with the element.
**/
export function disabled(value: boolean) { return new Attr("disabled", value, false, "button", "command", "fieldset", "input", "keygen", "optgroup", "option", "select", "textarea"); }
/**
* ???
**/
export function dirName(value: string) { return new Attr("dirname", value, false, "input", "textarea"); }
/**
* Indicates that the hyperlink is to be used for downloading a resource.
**/
export function download(value: boolean) { return new Attr("download", value, false, "a", "area"); }
/**
* Defines whether the element can be dragged.
**/
export function draggable(value: boolean) { return new Attr("draggable", value, false); }
/**
* Indicates that the element accepts the dropping of content onto it.
**/
export function dropZone(value: string) { return new Attr("dropzone", value, false); }
/**
* Defines the content type of the form data when the method is POST.
**/
export function encType(value: string) { return new Attr("enctype", value, false, "form"); }
/**
* The enterkeyhint specifies what action label (or icon) to present for the enter key on virtual keyboards. The attribute can be used with form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable attribute).
**/
export function enterKeyHint(value: string) { return new Attr("enterkeyhint", value, false, "textarea"); }
/**
* Describes elements which belongs to this one.
**/
export function htmlFor(value: string) { return new Attr("htmlFor", value, false, "label", "output"); }
/**
* Indicates the form that is the owner of the element.
**/
export function form(value: string) { return new Attr("form", value, false, "button", "fieldset", "input", "keygen", "label", "meter", "object", "output", "progress", "select", "textarea"); }
/**
* Indicates the action of the element, overriding the action defined in the <form>.
**/
export function formAction(value: string) { return new Attr("formaction", value, false, "input", "button"); }
/**
* If the button/input is a submit button (type="submit"), this attribute sets the encoding type to use during form submission. If this attribute is specified, it overrides the enctype attribute of the button's form owner.
**/
export function formEncType(value: string) { return new Attr("formenctype", value, false, "button", "input"); }
/**
* If the button/input is a submit button (type="submit"), this attribute sets the submission method to use during form submission (GET, POST, etc.). If this attribute is specified, it overrides the method attribute of the button's form owner.
**/
export function formMethod(value: string) { return new Attr("formmethod", value, false, "button", "input"); }
/**
* If the button/input is a submit button (type="submit"), this boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the novalidate attribute of the button's form owner.
**/
export function formNoValidate(value: boolean) { return new Attr("formnovalidate", value, false, "button", "input"); }
/**
* If the button/input is a submit button (type="submit"), this attribute specifies the browsing context (for example, tab, window, or inline frame) in which to display the response that is received after submitting the form. If this attribute is specified, it overrides the target attribute of the button's form owner.
**/
export function formTarget(value: string) { return new Attr("formtarget", value, false, "button", "input"); }
/**
* IDs of the <th> elements which applies to this element.
**/
export function headers(value: string) { return new Attr("headers", value, false, "td", "th"); }
/**
* Specifies the height of elements listed here. For all other elements, use the CSS height property.
**/
export function htmlHeight(value: number | string) { return new Attr("height", value, false, "canvas", "embed", "iframe", "img", "input", "object", "video"); }
/**
* Prevents rendering of given element, while keeping child elements, e.g. script elements, active.
**/
export function hidden(value: boolean) { return new Attr("hidden", value, false); }
/**
* Indicates the lower bound of the upper range.
**/
export function high(value: number) { return new Attr("high", value, false, "meter"); }
/**
* The URL of a linked resource.
**/
export function href(value: string) { return new Attr("href", value, false, "a", "area", "base", "link"); }
/**
* Specifies the language of the linked resource.
**/
export function hrefLang(value: string) { return new Attr("hreflang", value, false, "a", "area", "link"); }
/**
* Defines a pragma directive.
**/
export function httpEquiv(value: string) { return new Attr("httpEquiv", value, false, "meta"); }
/**
* Specifies a picture which represents the command.
**/
export function icon(value: string) { return new Attr("icon", value, false, "command"); }
/**
* Often used with CSS to style a specific element. The value of this attribute must be unique.
**/
export function id(value: string) { return new Attr("id", value, false); }
/**
* Indicates the relative fetch priority for the resource.
**/
export function importance(value: string) { return new Attr("importance", value, false, "iframe", "img", "link", "script"); }
/**
* Provides a hint as to the type of data that might be entered by the user while editing the element or its contents. The attribute can be used with form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable attribute).
**/
export function inputMode(value: string) { return new Attr("inputmode", value, false, "textarea"); }
/**
* Specifies a Subresource Integrity value that allows browsers to verify what they fetch.
**/
export function integrity(value: string) { return new Attr("integrity", value, false, "link", "script"); }
/**
* This attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute.
**/
export function intrinsicSize(value: string) { return new Attr("intrinsicsize", value, false, "img"); }
/**
* Indicates that the image is part of a server-side image map.
**/
export function isMap(value: boolean) { return new Attr("ismap", value, false, "img"); }
/**
* Specifies the type of key generated.
**/
export function keyType(value: string) { return new Attr("keytype", value, false, "keygen"); }
/**
* The itemprop attribute
**/
export function itemProp(value: string) { return new Attr("itemprop", value, false); }
/**
* Specifies the kind of text track.
**/
export function kind(value: string) { return new Attr("kind", value, false, "track"); }
/**
* Specifies a user-readable title of the element.
**/
export function label(value: string) { return new Attr("label", value, false, "optgroup", "option", "track"); }
/**
* Defines the language used in the element.
**/
export function lang(value: string) { return new Attr("lang", value, false); }
/**
* Defines the script language used in the element.
**/
export function language(value: string) { return new Attr("language", value, false, "script"); }
/**
* Identifies a list of pre-defined options to suggest to the user.
**/
export function list(value: string) { return new Attr("list", value, true, "input"); }
/**
* Indicates whether the media should start playing from the start when it's finished.
**/
export function loop(value: boolean) { return new Attr("loop", value, false, "audio", "bgsound", "marquee", "video"); }
/**
* Indicates the upper bound of the lower range.
**/
export function low(value: number) { return new Attr("low", value, false, "meter"); }
/**
* Indicates the maximum value allowed.
**/
export function max(value: number) { return new Attr("max", value, false, "input", "meter", "progress"); }
/**
* Defines the maximum number of characters allowed in the element.
**/
export function maxLength(value: number) { return new Attr("maxlength", value, false, "input", "textarea"); }
/**
* Defines the minimum number of characters allowed in the element.
**/
export function minLength(value: number) { return new Attr("minlength", value, false, "input", "textarea"); }
/**
* Specifies a hint of the media for which the linked resource was designed.
**/
export function media(value: string) { return new Attr("media", value, false, "a", "area", "link", "source", "style"); }
/**
* Defines which HTTP method to use when submitting the form. Can be GET (default) or POST.
**/
export function method(value: string) { return new Attr("method", value, false, "form"); }
/**
* Indicates the minimum value allowed.
**/
export function min(value: number) { return new Attr("min", value, false, "input", "meter"); }
/**
* Indicates whether multiple values can be entered in an input of the type email or file.
**/
export function multiple(value: boolean) { return new Attr("multiple", value, false, "input", "select"); }
/**
* Indicates whether the audio will be initially silenced on page load.
**/
export function muted(value: boolean) { return new Attr("muted", value, false, "audio", "video"); }
/**
* Name of the element. For example used by the server to identify the fields in form submits.
**/
export function name(value: string) { return new Attr("name", value, false, "button", "form", "fieldset", "iframe", "input", "keygen", "object", "output", "select", "textarea", "map", "meta", "param"); }
/**
* This attribute indicates that the form shouldn't be validated when submitted.
**/
export function noValidate(value: boolean) { return new Attr("novalidate", value, false, "form"); }
/**
* Indicates whether the details will be shown on page load.
**/
export function open(value: string) { return new Attr("open", value, false, "details"); }
/**
* Indicates the optimal numeric value.
**/
export function optimum(value: number) { return new Attr("optimum", value, false, "meter"); }
/**
* Defines a regular expression which the element's value will be validated against.
**/
export function pattern(value: string) { return new Attr("pattern", value, false, "input"); }
/**
* The ping attribute specifies a space-separated list of URLs to be notified if a user follows the hyperlink.
**/
export function ping(value: string) { return new Attr("ping", value, false, "a", "area"); }
/**
* Provides a hint to the user of what can be entered in the field.
**/
export function placeHolder(value: string) { return new Attr("placeholder", value, false, "input", "textarea"); }
/**
* Indicates that the media element should play automatically on iOS.
**/
export function playsInline(value: boolean) { return new Attr("playsInline", value, false, "audio", "video"); }
/**
* A URL indicating a poster frame to show until the user plays or seeks.
**/
export function poster(value: string) { return new Attr("poster", value, false, "video"); }
/**
* Indicates whether the whole resource, parts of it or nothing should be preloaded.
**/
export function preload(value: boolean|string) { return new Attr("preload", value, false, "audio", "video"); }
/**
* Indicates whether the element can be edited.
**/
export function readOnly(value: boolean) { return new Attr("readonly", value, false, "input", "textarea"); }
/**
* The radiogroup attribute
**/
export function radioGroup(value: string) { return new Attr("radiogroup", value, false, "command"); }
/**
* Specifies which referrer is sent when fetching the resource.
**/
export function referrerPolicy(value: string) { return new Attr("referrerpolicy", value, false, "a", "area", "iframe", "img", "link", "script"); }
/**
* Specifies the relationship of the target object to the link object.
**/
export function rel(value: string) { return new Attr("rel", value, false, "a", "area", "link"); }
/**
* Indicates whether this element is required to fill out or not.
**/
export function required(value: boolean) { return new Attr("required", value, false, "input", "select", "textarea"); }
/**
* Indicates whether the list should be displayed in a descending order instead of a ascending.
**/
export function reversed(value: boolean) { return new Attr("reversed", value, false, "ol"); }
/**
* Defines the number of rows in a text area.
**/
export function role(value: string) { return new Attr("role", value, false); }
/**
* The rows attribute
**/
export function rows(value: number) { return new Attr("rows", value, false, "textarea"); }
/**
* Defines the number of rows a table cell should span over.
**/
export function rowSpan(value: number) { return new Attr("rowspan", value, false, "td", "th"); }
/**
* Stops a document loaded in an iframe from using certain features (such as submitting forms or opening new windows).
**/
export function sandbox(value: string) { return new Attr("sandbox", value, false, "iframe"); }
/**
* Defines the cells that the header test (defined in the th element) relates to.
**/
export function scope(value: string) { return new Attr("scope", value, false, "th"); }
/**
* The scoped attribute
**/
export function scoped(value: boolean) { return new Attr("scoped", value, false, "style"); }
/**
* Defines a value which will be selected on page load.
**/
export function selected(value: boolean) { return new Attr("selected", value, false, "option"); }
/**
* The shape attribute
**/
export function shape(value: string) { return new Attr("shape", value, false, "a", "area"); }
/**
* Defines the width of the element (in pixels). If the element's type attribute is text or password then it's the number of characters.
**/
export function size(value: number) { return new Attr("size", value, false, "input", "select"); }
/**
* Assigns a slot in a shadow DOM shadow tree to an element.
**/
export function slot(value: string) { return new Attr("slot", value, false); }
/**
* The sizes attribute
**/
export function sizes(value: string) { return new Attr("sizes", value, false, "link", "img", "source"); }
/**
* The span attribute
**/
export function span(value: string) { return new Attr("span", value, false, "col", "colgroup"); }
/**
* Indicates whether spell checking is allowed for the element.
**/
export function spellCheck(value: boolean) { return new Attr("spellcheck", value, false); }
/**
* The URL of the embeddable content.
**/
export function src(value: string) { return new Attr("src", value, false, "audio", "embed", "iframe", "img", "input", "script", "source", "track", "video"); }
/**
* The srcdoc attribute
**/
export function srcDoc(value: string) { return new Attr("srcdoc", value, false, "iframe"); }
/**
* The srclang attribute
**/
export function srcLang(value: string) { return new Attr("srclang", value, false, "track"); }
/**
* A MediaStream object to use as a source for an HTML video or audio element
**/
export function srcObject(value: MediaProvider) { return new Attr("srcObject", value, false, "audio", "video"); }
/**
* One or more responsive image candidates.
**/
export function srcSet(value: string) { return new Attr("srcset", value, false, "img", "source"); }
/**
* Defines the first number if other than 1.
**/
export function start(value: number) { return new Attr("start", value, false, "ol"); }
/**
* Defines CSS styles which will override styles previously set.
*
* NOTE: DO NOT USE THIS. You should use `styles()` instead.
**/
export function __deprecated__style__deprecated__(value: any) {
for (let k in value) {
if (!value[k] && !isBoolean(value[k])) {
delete value[k];
}
}
return new Attr("style", value, false);
}
/**
* The step attribute
**/
export function step(value: number) { return new Attr("step", value, false, "input"); }
/**
* The summary attribute
**/
export function summary(value: string) { return new Attr("summary", value, false, "table"); }
/**
* Overrides the browser's default tab order and follows the one specified instead.
**/
export function tabIndex(value: number) { return new Attr("tabindex", value, false); }
/**
* Text to be displayed in a tooltip when hovering over the element.
**/
export function title(value: string) { return new Attr("title", value, false); }
/**
* The target attribute
**/
export function target(value: string) { return new Attr("target", value, false, "a", "area", "base", "form"); }
/**
* Specify whether an element’s attribute values and the values of its Text node children are to be translated when the page is localized, or whether to leave them unchanged.
**/
export function translate(value: boolean) { return new Attr("translate", value, false); }
/**
* Defines the type of the element.
**/
export function type(value: string) { return new Attr("type", value, false, "button", "input", "command", "embed", "link", "object", "script", "source", "style", "menu"); }
/**
* Defines a default value which will be displayed in the element on page load.
**/
export function value(value: string | number) { return new Attr("value", value, false, "button", "data", "input", "li", "meter", "option", "progress", "param"); }
/**
* Defines a default value which will be displayed in the element on page load.
**/
export function valueAsNumber(value: number) { return new Attr("valueAsNumber", value, false, "input"); }
/**
* Defines a default value which will be displayed in the element on page load.
**/
export function valueAsDate(value: Date) { return new Attr("valueAsDate", value, false, "input"); }
/**
* setting the volume at which a media element plays.
**/
export function volume(value: number) { return new Attr("volume", value, false, "audio", "video"); }
/**
* The usemap attribute
**/
export function useMap(value: boolean) { return new Attr("usemap", value, false, "img", "input", "object"); }
/**
* For the elements listed here, this establishes the element's width.
**/
export function htmlWidth(value: number | string) { return new Attr("width", value, false, "canvas", "embed", "iframe", "img", "input", "object", "video"); }
/**
* Indicates whether the text should be wrapped.
**/
export function wrap(value: boolean) { return new Attr("wrap", value, false, "textarea"); } | the_stack |
import type * as Protocol from '../../generated/protocol.js';
import type * as ProtocolProxyApi from '../../generated/protocol-proxy-api.js';
import type {DOMNode} from './DOMModel.js';
import {DOMModel} from './DOMModel.js';
import {DeferredDOMNode} from './DOMModel.js';
import type {Target} from './Target.js';
import {Capability} from './Target.js';
import {SDKModel} from './SDKModel.js';
// TODO(crbug.com/1167717): Make this a const enum again
// eslint-disable-next-line rulesdir/const_enum
export enum CoreAxPropertyName {
Name = 'name',
Description = 'description',
Value = 'value',
Role = 'role',
}
export interface CoreOrProtocolAxProperty {
name: CoreAxPropertyName|Protocol.Accessibility.AXPropertyName;
value: Protocol.Accessibility.AXValue;
}
export class AccessibilityNode {
readonly #accessibilityModelInternal: AccessibilityModel;
readonly #agent: ProtocolProxyApi.AccessibilityApi;
readonly #idInternal: Protocol.Accessibility.AXNodeId;
readonly #backendDOMNodeIdInternal: Protocol.DOM.BackendNodeId|null;
readonly #deferredDOMNodeInternal: DeferredDOMNode|null;
readonly #ignoredInternal: boolean;
readonly #ignoredReasonsInternal: Protocol.Accessibility.AXProperty[]|undefined;
readonly #roleInternal: Protocol.Accessibility.AXValue|null;
readonly #nameInternal: Protocol.Accessibility.AXValue|null;
readonly #descriptionInternal: Protocol.Accessibility.AXValue|null;
readonly #valueInternal: Protocol.Accessibility.AXValue|null;
readonly #propertiesInternal: Protocol.Accessibility.AXProperty[]|null;
#childIds: string[]|null;
#parentNodeInternal: AccessibilityNode|null;
constructor(accessibilityModel: AccessibilityModel, payload: Protocol.Accessibility.AXNode) {
this.#accessibilityModelInternal = accessibilityModel;
this.#agent = accessibilityModel.getAgent();
this.#idInternal = payload.nodeId;
accessibilityModel.setAXNodeForAXId(this.#idInternal, this);
if (payload.backendDOMNodeId) {
accessibilityModel.setAXNodeForBackendDOMNodeId(payload.backendDOMNodeId, this);
this.#backendDOMNodeIdInternal = payload.backendDOMNodeId;
this.#deferredDOMNodeInternal = new DeferredDOMNode(accessibilityModel.target(), payload.backendDOMNodeId);
} else {
this.#backendDOMNodeIdInternal = null;
this.#deferredDOMNodeInternal = null;
}
this.#ignoredInternal = payload.ignored;
if (this.#ignoredInternal && 'ignoredReasons' in payload) {
this.#ignoredReasonsInternal = payload.ignoredReasons;
}
this.#roleInternal = payload.role || null;
this.#nameInternal = payload.name || null;
this.#descriptionInternal = payload.description || null;
this.#valueInternal = payload.value || null;
this.#propertiesInternal = payload.properties || null;
this.#childIds = payload.childIds || null;
this.#parentNodeInternal = null;
}
id(): Protocol.Accessibility.AXNodeId {
return this.#idInternal;
}
accessibilityModel(): AccessibilityModel {
return this.#accessibilityModelInternal;
}
ignored(): boolean {
return this.#ignoredInternal;
}
ignoredReasons(): Protocol.Accessibility.AXProperty[]|null {
return this.#ignoredReasonsInternal || null;
}
role(): Protocol.Accessibility.AXValue|null {
return this.#roleInternal || null;
}
coreProperties(): CoreOrProtocolAxProperty[] {
const properties: CoreOrProtocolAxProperty[] = [];
if (this.#nameInternal) {
properties.push({name: CoreAxPropertyName.Name, value: this.#nameInternal});
}
if (this.#descriptionInternal) {
properties.push({name: CoreAxPropertyName.Description, value: this.#descriptionInternal});
}
if (this.#valueInternal) {
properties.push({name: CoreAxPropertyName.Value, value: this.#valueInternal});
}
return properties;
}
name(): Protocol.Accessibility.AXValue|null {
return this.#nameInternal || null;
}
description(): Protocol.Accessibility.AXValue|null {
return this.#descriptionInternal || null;
}
value(): Protocol.Accessibility.AXValue|null {
return this.#valueInternal || null;
}
properties(): Protocol.Accessibility.AXProperty[]|null {
return this.#propertiesInternal || null;
}
parentNode(): AccessibilityNode|null {
return this.#parentNodeInternal;
}
setParentNode(parentNode: AccessibilityNode|null): void {
this.#parentNodeInternal = parentNode;
}
isDOMNode(): boolean {
return Boolean(this.#backendDOMNodeIdInternal);
}
backendDOMNodeId(): Protocol.DOM.BackendNodeId|null {
return this.#backendDOMNodeIdInternal;
}
deferredDOMNode(): DeferredDOMNode|null {
return this.#deferredDOMNodeInternal;
}
highlightDOMNode(): void {
const deferredNode = this.deferredDOMNode();
if (!deferredNode) {
return;
}
// Highlight node in page.
deferredNode.highlight();
}
children(): AccessibilityNode[] {
if (!this.#childIds) {
return [];
}
const children = [];
for (const childId of this.#childIds) {
const child = this.#accessibilityModelInternal.axNodeForId(childId);
if (child) {
children.push(child);
}
}
return children;
}
numChildren(): number {
if (!this.#childIds) {
return 0;
}
return this.#childIds.length;
}
hasOnlyUnloadedChildren(): boolean {
if (!this.#childIds || !this.#childIds.length) {
return false;
}
return this.#childIds.every(id => this.#accessibilityModelInternal.axNodeForId(id) === null);
}
// Only the root node gets a frameId, so nodes have to walk up the tree to find their frameId.
getFrameId(): Protocol.Page.FrameId|null {
const domNode = this.accessibilityModel().domNodeforAXNode(this);
if (!domNode) {
return null;
}
return domNode.frameId();
}
}
export class AccessibilityModel extends SDKModel<void> {
agent: ProtocolProxyApi.AccessibilityApi;
#axIdToAXNode: Map<string, AccessibilityNode>;
readonly #backendDOMNodeIdToAXNode: Map<Protocol.DOM.BackendNodeId, AccessibilityNode>;
readonly #backendDOMNodeIdToDOMNode: Map<Protocol.DOM.BackendNodeId, DOMNode|null>;
constructor(target: Target) {
super(target);
this.agent = target.accessibilityAgent();
this.resumeModel();
this.#axIdToAXNode = new Map();
this.#backendDOMNodeIdToAXNode = new Map();
this.#backendDOMNodeIdToDOMNode = new Map();
}
clear(): void {
this.#axIdToAXNode.clear();
}
async resumeModel(): Promise<void> {
await this.agent.invoke_enable();
}
async suspendModel(): Promise<void> {
await this.agent.invoke_disable();
}
async requestPartialAXTree(node: DOMNode): Promise<void> {
const {nodes} = await this.agent.invoke_getPartialAXTree({nodeId: node.id, fetchRelatives: true});
if (!nodes) {
return;
}
for (const payload of nodes) {
new AccessibilityNode(this, payload);
}
for (const axNode of this.#axIdToAXNode.values()) {
for (const axChild of axNode.children()) {
axChild.setParentNode(axNode);
}
}
}
private async pushNodesToFrontend(backendIds: Set<Protocol.DOM.BackendNodeId>): Promise<void> {
const domModel = this.target().model(DOMModel);
if (!domModel) {
return;
}
const newNodesToTrack = await domModel.pushNodesByBackendIdsToFrontend(backendIds);
newNodesToTrack?.forEach((value, key) => this.#backendDOMNodeIdToDOMNode.set(key, value));
}
private createNodesFromPayload(payloadNodes: Protocol.Accessibility.AXNode[]): AccessibilityNode[] {
const backendIds: Set<Protocol.DOM.BackendNodeId> = new Set();
const accessibilityNodes = payloadNodes.map(node => {
const sdkNode = new AccessibilityNode(this, node);
const backendId = sdkNode.backendDOMNodeId();
if (backendId) {
backendIds.add(backendId);
}
return sdkNode;
});
this.pushNodesToFrontend(backendIds);
for (const sdkNode of accessibilityNodes) {
for (const sdkChild of sdkNode.children()) {
sdkChild.setParentNode(sdkNode);
}
}
return accessibilityNodes;
}
async requestRootNode(depth: number = 2, frameId?: Protocol.Page.FrameId): Promise<AccessibilityNode|undefined> {
const {nodes} = await this.agent.invoke_getFullAXTree({depth, frameId});
if (!nodes) {
return;
}
const axNodes = this.createNodesFromPayload(nodes);
const root = axNodes[0];
return root;
}
async requestAXChildren(nodeId: Protocol.Accessibility.AXNodeId, frameId?: Protocol.Page.FrameId):
Promise<AccessibilityNode[]> {
const {nodes} = await this.agent.invoke_getChildAXNodes({id: nodeId, frameId});
if (!nodes) {
return [];
}
const axNodes = this.createNodesFromPayload(nodes);
return axNodes;
}
async requestAndLoadSubTreeToNode(node: DOMNode): Promise<AccessibilityNode|null> {
// Node may have already been loaded, so don't bother requesting it again.
const loadedAXNode = this.axNodeForDOMNode(node);
if (loadedAXNode) {
return loadedAXNode;
}
const {nodes} = await this.agent.invoke_getPartialAXTree({nodeId: node.id, fetchRelatives: true});
if (!nodes) {
return null;
}
const ancestors = this.createNodesFromPayload(nodes);
// Request top level children nodes.
for (const node of ancestors) {
await this.requestAXChildren(node.id());
}
return this.axNodeForDOMNode(node);
}
async updateSubtreeAndAncestors(backendNodeId: Protocol.DOM.BackendNodeId): Promise<void> {
const {nodes} = await this.agent.invoke_getPartialAXTree({backendNodeId, fetchRelatives: true});
if (!nodes) {
return;
}
this.createNodesFromPayload(nodes);
}
axNodeForId(axId: string): AccessibilityNode|null {
return this.#axIdToAXNode.get(axId) || null;
}
setAXNodeForAXId(axId: string, axNode: AccessibilityNode): void {
this.#axIdToAXNode.set(axId, axNode);
}
axNodeForDOMNode(domNode: DOMNode|null): AccessibilityNode|null {
if (!domNode) {
return null;
}
return this.#backendDOMNodeIdToAXNode.get(domNode.backendNodeId()) ?? null;
}
domNodeforAXNode(axNode: AccessibilityNode): DOMNode|null {
const backendDOMNodeId = axNode.backendDOMNodeId();
if (!backendDOMNodeId) {
return null;
}
return this.#backendDOMNodeIdToDOMNode.get(backendDOMNodeId) ?? null;
}
setAXNodeForBackendDOMNodeId(backendDOMNodeId: Protocol.DOM.BackendNodeId, axNode: AccessibilityNode): void {
this.#backendDOMNodeIdToAXNode.set(backendDOMNodeId, axNode);
}
getAgent(): ProtocolProxyApi.AccessibilityApi {
return this.agent;
}
}
SDKModel.register(AccessibilityModel, {capabilities: Capability.DOM, autostart: false}); | the_stack |
export interface paths {
"/version/update": {
put: operations["updateVersion"];
parameters: {};
};
"/version": {
get: operations["checkVersion"];
parameters: {};
};
"/tuners": {
get: operations["getTuners"];
parameters: {};
};
"/status": {
get: operations["getStatus"];
parameters: {};
};
"/services": {
get: operations["getServices"];
parameters: {};
};
"/restart": {
put: operations["restart"];
parameters: {};
};
"/programs": {
get: operations["getPrograms"];
parameters: {};
};
"/log/stream": {
get: operations["getLogStream"];
parameters: {};
};
"/log": {
get: operations["getLog"];
parameters: {};
};
"/iptv/xmltv": {
get: {
parameters: {};
responses: {
/** OK */
200: unknown;
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
parameters: {};
};
"/iptv/playlist": {
get: {
parameters: {};
responses: {
/** OK */
200: unknown;
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
parameters: {};
};
"/iptv/lineup.json": {
get: {
parameters: {};
responses: {
/** OK */
200: unknown;
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
parameters: {};
};
"/iptv/lineup_status.json": {
get: {
parameters: {};
responses: {
/** OK */
200: unknown;
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
parameters: {};
};
"/iptv/discover.json": {
get: {
parameters: {};
responses: {
/** OK */
200: unknown;
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
parameters: {};
};
"/events/stream": {
get: operations["getEventsStream"];
parameters: {};
};
"/events": {
get: operations["getEvents"];
parameters: {};
};
"/config/tuners": {
get: operations["getTunersConfig"];
put: operations["updateTunersConfig"];
parameters: {};
};
"/config/server": {
get: operations["getServerConfig"];
put: operations["updateServerConfig"];
parameters: {};
};
"/config/channels/scan": {
/**
* Entry rewriting specifications:
* - The scan is performed on a range of channels of the specified type and the entries for those channels, if any, are saved in the configuration file.
* - If the channel to be scanned is described in the configuration file and is enabled, the scan will not be performed for that channel and the entries described will remain intact. If you do not want to keep the entries, use the `refresh` option.
* - All entries outside the channel range of the specified type will be deleted.
* - All entries of a type other than the specified type will remain.
*
* About BS Subchannel Style:
* - Only when scanning BS, you can specify the channel number in the subchannel style (e.g. BS01_0). To specify the channel number, use minSubCh and maxSubCh in addition to minCh and maxCh.
* - The subchannel number parameters (minSubCh, maxSubCh) are used only if the type is BS and are ignored otherwise.
* - Subchannel style scans scan in the following range:
* From `BS${minCh}_${minSubCh}` to `BS${maxCh}_${maxSubCh}`
* - In the subchannel style, minCh and maxCh are zero padded to two digits. minSubCh and maxSubCh are not padded.
* - BS "non" subchannel style scans and GR scans are basically the same. Note that if you scan the wrong channel range, the GR channel will be registered as BS and the BS channel will be registered as GR. This problem does not occur because CS scan uses a character string with `CS` added as a channel number prefix.
*/
put: operations["channelScan"];
parameters: {};
};
"/config/channels": {
get: operations["getChannelsConfig"];
put: operations["updateChannelsConfig"];
parameters: {};
};
"/channels": {
get: operations["getChannels"];
parameters: {};
};
"/tuners/{index}/process": {
get: operations["getTunerProcess"];
delete: operations["killTunerProcess"];
parameters: {
path: {
index: number;
};
};
};
"/tuners/{index}": {
get: operations["getTuner"];
parameters: {
path: {
index: number;
};
};
};
"/services/{id}/stream": {
get: operations["getServiceStream"];
parameters: {
path: {
id: number;
};
header: {
"X-Mirakurun-Priority"?: number;
};
query: {
decode?: number;
};
};
};
"/services/{id}/logo": {
get: operations["getLogoImage"];
parameters: {
path: {
id: number;
};
};
};
"/services/{id}": {
get: operations["getService"];
parameters: {
path: {
id: number;
};
};
};
"/programs/{id}/stream": {
get: operations["getProgramStream"];
parameters: {
path: {
id: number;
};
header: {
"X-Mirakurun-Priority"?: number;
};
query: {
decode?: number;
};
};
};
"/programs/{id}": {
get: operations["getProgram"];
parameters: {
path: {
id: number;
};
};
};
"/channels/{type}/{channel}/stream": {
get: operations["getChannelStream"];
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
channel: string;
};
header: {
"X-Mirakurun-Priority"?: number;
};
query: {
decode?: number;
};
};
};
"/channels/{type}/{channel}/services/{id}/stream": {
get: operations["getServiceStreamByChannel"];
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
channel: string;
id: number;
};
header: {
"X-Mirakurun-Priority"?: number;
};
query: {
decode?: number;
};
};
};
"/channels/{type}/{channel}/services/{id}": {
get: operations["getServiceByChannel"];
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
channel: string;
id: number;
};
};
};
"/channels/{type}/{channel}/services": {
get: operations["getServicesByChannel"];
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
channel: string;
};
};
};
"/channels/{type}/{channel}": {
get: operations["getChannel"];
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
channel: string;
};
};
};
"/channels/{type}": {
get: operations["getChannelsByType"];
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
};
};
};
}
export interface definitions {
Error: {
code?: number;
reason?: string;
errors?: definitions["ErrorOfOpenAPI"][];
};
ErrorOfOpenAPI: {
errorCode?: string;
message?: string;
location?: string;
};
ProgramId: number;
EventId: number;
ServiceId: number;
NetworkId: number;
ServiceItemId: number;
UnixtimeMS: number;
Channel: {
type: definitions["ChannelType"];
channel: string;
name?: string;
satellite?: string;
space?: number;
freq?: number;
/** @enum {string} */
polarity?: "H" | "V";
tsmfRelTs?: number;
services?: definitions["Service"][];
};
/** @enum {string} */
ChannelType: "GR" | "BS" | "CS" | "SKY";
Service: {
id: definitions["ServiceItemId"];
serviceId: definitions["ServiceId"];
networkId: definitions["NetworkId"];
name: string;
type: number;
logoId?: number;
hasLogoData?: boolean;
remoteControlKeyId?: number;
epgReady?: boolean;
epgUpdatedAt?: definitions["UnixtimeMS"];
channel?: definitions["Channel"];
};
Program: {
id: definitions["ProgramId"];
eventId: definitions["EventId"];
serviceId: definitions["ServiceId"];
networkId: definitions["NetworkId"];
startAt: definitions["UnixtimeMS"];
duration: number;
isFree: boolean;
name?: string;
description?: string;
genres?: definitions["ProgramGenre"][];
video?: {
type?: definitions["ProgramVideoType"];
resolution?: definitions["ProgramVideoResolution"];
streamContent?: number;
componentType?: number;
};
audios?: {
componentType?: number;
componentTag?: number;
isMain?: boolean;
samplingRate?: definitions["ProgramAudioSamplingRate"];
langs?: (
| "jpn"
| "eng"
| "deu"
| "fra"
| "ita"
| "rus"
| "zho"
| "kor"
| "spa"
| "etc"
)[];
}[];
extended?: { [key: string]: unknown };
relatedItems?: definitions["RelatedItem"][];
series?: {
id?: number;
repeat?: number;
pattern?: definitions["ProgramPattern"];
expiresAt?: definitions["UnixtimeMS"];
episode?: definitions["ProgramEpisodeNumber"];
lastEpisode?: definitions["ProgramEpisodeNumber"];
name?: string;
};
};
ProgramGenre: {
lv1?: number;
lv2?: number;
un1?: number;
un2?: number;
};
/** @enum {string} */
ProgramVideoType: "mpeg2" | "h.264" | "h.265";
/** @enum {string} */
ProgramVideoResolution:
| "240p"
| "480i"
| "480p"
| "720p"
| "1080i"
| "1080p"
| "2160p"
| "4320p";
/** @enum {integer} */
ProgramAudioSamplingRate: 16000 | 22050 | 24000 | 32000 | 44100 | 48000;
ProgramPattern: number;
ProgramEpisodeNumber: number;
RelatedItem: {
/** @enum {string} */
type?: "shared" | "relay" | "movement";
networkId?: number;
serviceId?: number;
eventId?: number;
};
TunerDevice: {
index: number;
name: string;
types: definitions["ChannelType"][];
command: string;
pid: number;
users: definitions["TunerUser"][];
isAvailable: boolean;
isRemote?: boolean;
isFree: boolean;
isUsing: boolean;
isFault: boolean;
};
TunerUser: {
id: string;
priority: number;
agent?: string;
url?: string;
disableDecoder?: boolean;
streamSetting?: {
channel: definitions["ConfigChannelsItem"];
networkId?: number;
serviceId?: number;
eventId?: number;
noProvide?: boolean;
parseNIT?: boolean;
parseSDT?: boolean;
parseEIT?: boolean;
};
streamInfo?: {
[key: string]: {
packet: number;
drop: number;
};
};
};
TunerProcess: {
pid: number;
};
Event: {
resource: definitions["EventResource"];
type: definitions["EventType"];
data: { [key: string]: unknown };
time: definitions["UnixtimeMS"];
};
/** @enum {string} */
EventResource: "program" | "service" | "tuner";
/** @enum {string} */
EventType: "create" | "update" | "remove";
ConfigServer: {
path?: string;
port?: number;
hostname?: string;
disableIPv6?: boolean;
logLevel?: number;
maxLogHistory?: number;
maxBufferBytesBeforeReady?: number;
eventEndTimeout?: number;
programGCInterval?: number;
epgGatheringInterval?: number;
epgRetrievalTime?: number;
logoDataInterval?: number;
disableEITParsing?: boolean;
disableWebUI?: boolean;
allowIPv4CidrRanges?: string[];
allowIPv6CidrRanges?: string[];
};
ConfigTuners: definitions["ConfigTunersItem"][];
ConfigTunersItem: {
name: string;
types: definitions["ChannelType"][];
command?: string;
dvbDevicePath?: string;
remoteMirakurunHost?: string;
remoteMirakurunPort?: number;
remoteMirakurunDecoder?: boolean;
decoder?: string;
isDisabled?: boolean;
};
ConfigChannels: definitions["ConfigChannelsItem"][];
ConfigChannelsItem: {
name: string;
type: definitions["ChannelType"];
channel: string;
serviceId?: definitions["ServiceId"];
satellite?: string;
space?: number;
freq?: number;
/** @enum {string} */
polarity?: "H" | "V";
isDisabled?: boolean;
};
Version: {
current?: string;
latest?: string;
};
Status: {
time?: number;
version?: string;
process?: {
arch?: string;
platform?: string;
versions?: { [key: string]: unknown };
env?: { [key: string]: unknown };
pid?: number;
memoryUsage?: {
rss?: number;
heapTotal?: number;
heapUsed?: number;
};
};
epg?: {
gatheringNetworks?: definitions["NetworkId"][];
storedEvents?: number;
};
rpcCount?: number;
streamCount?: {
tunerDevice?: number;
tsFilter?: number;
decoder?: number;
};
errorCount?: {
uncaughtException?: number;
unhandledRejection?: number;
bufferOverflow?: number;
tunerDeviceRespawn?: number;
decoderRespawn?: number;
};
timerAccuracy?: {
last?: number;
m1?: {
avg?: number;
min?: number;
max?: number;
};
m5?: {
avg?: number;
min?: number;
max?: number;
};
m15?: {
avg?: number;
min?: number;
max?: number;
};
};
};
}
export interface operations {
updateVersion: {
parameters: {
query: {
force?: boolean;
};
};
responses: {
/** Accepted */
202: unknown;
/** Update Nothing */
409: {
schema: definitions["Error"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
checkVersion: {
parameters: {};
responses: {
/** OK */
200: {
schema: definitions["Version"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getTuners: {
parameters: {};
responses: {
/** OK */
200: {
schema: definitions["TunerDevice"][];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getStatus: {
parameters: {};
responses: {
/** OK */
200: {
schema: definitions["Status"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getServices: {
parameters: {
query: {
serviceId?: number;
networkId?: number;
name?: string;
type?: number;
"channel.type"?: "GR" | "BS" | "CS" | "SKY";
"channel.channel"?: string;
};
};
responses: {
/** OK */
200: {
schema: definitions["Service"][];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
restart: {
parameters: {};
responses: {
/** Accepted */
202: unknown;
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getPrograms: {
parameters: {
query: {
networkId?: number;
serviceId?: number;
eventId?: number;
};
};
responses: {
/** OK */
200: {
schema: definitions["Program"][];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getLogStream: {
parameters: {};
responses: {
/** OK */
200: unknown;
/** Unexpected Error */
default: unknown;
};
};
getLog: {
parameters: {};
responses: {
/** OK */
200: unknown;
/** Unexpected Error */
default: unknown;
};
};
getEventsStream: {
parameters: {
query: {
resource?: "program" | "service" | "tuner";
type?: "create" | "update" | "remove";
};
};
responses: {
/** OK */
200: {
schema: definitions["Event"][];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getEvents: {
parameters: {};
responses: {
/** OK */
200: {
schema: definitions["Event"][];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getTunersConfig: {
parameters: {};
responses: {
/** OK */
200: {
schema: definitions["ConfigTuners"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
updateTunersConfig: {
parameters: {
body: {
body?: definitions["ConfigTuners"];
};
};
responses: {
/** OK */
200: {
schema: definitions["ConfigTuners"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getServerConfig: {
parameters: {};
responses: {
/** OK */
200: {
schema: definitions["ConfigServer"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
updateServerConfig: {
parameters: {
body: {
body?: definitions["ConfigServer"];
};
};
responses: {
/** OK */
200: {
schema: definitions["ConfigServer"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
/**
* Entry rewriting specifications:
* - The scan is performed on a range of channels of the specified type and the entries for those channels, if any, are saved in the configuration file.
* - If the channel to be scanned is described in the configuration file and is enabled, the scan will not be performed for that channel and the entries described will remain intact. If you do not want to keep the entries, use the `refresh` option.
* - All entries outside the channel range of the specified type will be deleted.
* - All entries of a type other than the specified type will remain.
*
* About BS Subchannel Style:
* - Only when scanning BS, you can specify the channel number in the subchannel style (e.g. BS01_0). To specify the channel number, use minSubCh and maxSubCh in addition to minCh and maxCh.
* - The subchannel number parameters (minSubCh, maxSubCh) are used only if the type is BS and are ignored otherwise.
* - Subchannel style scans scan in the following range:
* From `BS${minCh}_${minSubCh}` to `BS${maxCh}_${maxSubCh}`
* - In the subchannel style, minCh and maxCh are zero padded to two digits. minSubCh and maxSubCh are not padded.
* - BS "non" subchannel style scans and GR scans are basically the same. Note that if you scan the wrong channel range, the GR channel will be registered as BS and the BS channel will be registered as GR. This problem does not occur because CS scan uses a character string with `CS` added as a channel number prefix.
*/
channelScan: {
parameters: {
query: {
/** dry run. If `true`, the scanned result will not be saved. */
dryRun?: boolean;
/** Specifies the channel type to scan. */
type?: "GR" | "BS" | "CS";
/** Specifies the minimum number of channel numbers to scan. */
minCh?: number;
/** Specifies the maximum number of channel numbers to scan. */
maxCh?: number;
/** Specifies the minimum number of subchannel numbers to scan. This parameter is only used if the type is `BS` and the bs_subch_style is `true`. */
minSubCh?: number;
/** Specifies the maximum number of subchannel numbers to scan. This parameter is only used if the type is `BS` and the bs_subch_style is `true`. */
maxSubCh?: number;
/** Specify true to specify the channel in the subchannel style. Only used for BS scans. (e.g. BS01_0) */
useSubCh?: boolean;
/**
* To specify the service explictly, use the `Service` mode.
*
* _Default value (GR)_: Channel
* _Default value (BS/CS)_: Service
*/
scanMode?: "Channel" | "Service";
/**
* If `true`, set disable on add channel.
*
* _Default value (GR)_: false
* _Default value (BS/CS)_: true
*/
setDisabledOnAdd?: boolean;
/**
* If `true`, update the existing settings without inheriting them.
* However, non-scanned types of channels will always be inherited.
*/
refresh?: boolean;
};
};
responses: {
/** OK */
200: unknown;
/** Already Scanning */
409: {
schema: definitions["Error"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getChannelsConfig: {
parameters: {};
responses: {
/** OK */
200: {
schema: definitions["ConfigChannels"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
updateChannelsConfig: {
parameters: {
body: {
body?: definitions["ConfigChannels"];
};
};
responses: {
/** OK */
200: {
schema: definitions["ConfigChannels"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getChannels: {
parameters: {
query: {
type?: "GR" | "BS" | "CS" | "SKY";
channel?: string;
name?: string;
};
};
responses: {
/** OK */
200: {
schema: definitions["Channel"][];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getTunerProcess: {
parameters: {
path: {
index: number;
};
};
responses: {
/** OK */
200: {
schema: definitions["TunerProcess"];
};
/** Not Found */
404: {
schema: definitions["Error"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
killTunerProcess: {
parameters: {
path: {
index: number;
};
};
responses: {
/** OK */
200: {
schema: {
pid?: unknown;
};
};
/** Not Found */
404: {
schema: definitions["Error"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getTuner: {
parameters: {
path: {
index: number;
};
};
responses: {
/** OK */
200: {
schema: definitions["TunerDevice"];
};
/** Not Found */
404: {
schema: definitions["Error"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getServiceStream: {
parameters: {
path: {
id: number;
};
header: {
"X-Mirakurun-Priority"?: number;
};
query: {
decode?: number;
};
};
responses: {
/** OK */
200: unknown;
/** Not Found */
404: unknown;
/** Tuner Resource Unavailable */
503: unknown;
/** Unexpected Error */
default: unknown;
};
};
getLogoImage: {
parameters: {
path: {
id: number;
};
};
responses: {
/** OK */
200: unknown;
/** Not Found */
404: unknown;
/** Logo Data Unavailable */
503: unknown;
/** Unexpected Error */
default: unknown;
};
};
getService: {
parameters: {
path: {
id: number;
};
};
responses: {
/** OK */
200: {
schema: definitions["Service"];
};
/** Not Found */
404: {
schema: definitions["Error"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getProgramStream: {
parameters: {
path: {
id: number;
};
header: {
"X-Mirakurun-Priority"?: number;
};
query: {
decode?: number;
};
};
responses: {
/** OK */
200: unknown;
/** Not Found */
404: unknown;
/** Tuner Resource Unavailable */
503: unknown;
/** Unexpected Error */
default: unknown;
};
};
getProgram: {
parameters: {
path: {
id: number;
};
};
responses: {
/** OK */
200: {
schema: definitions["Program"];
};
/** Not Found */
404: {
schema: definitions["Error"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getChannelStream: {
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
channel: string;
};
header: {
"X-Mirakurun-Priority"?: number;
};
query: {
decode?: number;
};
};
responses: {
/** OK */
200: unknown;
/** Not Found */
404: unknown;
/** Tuner Resource Unavailable */
503: unknown;
/** Unexpected Error */
default: unknown;
};
};
getServiceStreamByChannel: {
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
channel: string;
id: number;
};
header: {
"X-Mirakurun-Priority"?: number;
};
query: {
decode?: number;
};
};
responses: {
/** OK */
200: unknown;
/** Not Found */
404: unknown;
/** Tuner Resource Unavailable */
503: unknown;
/** Unexpected Error */
default: unknown;
};
};
getServiceByChannel: {
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
channel: string;
id: number;
};
};
responses: {
/** OK */
200: {
schema: definitions["Service"][];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getServicesByChannel: {
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
channel: string;
};
};
responses: {
/** OK */
200: {
schema: definitions["Service"][];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getChannel: {
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
channel: string;
};
};
responses: {
/** OK */
200: {
schema: definitions["Channel"];
};
/** Not Found */
404: {
schema: definitions["Error"];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
getChannelsByType: {
parameters: {
path: {
type: "GR" | "BS" | "CS" | "SKY";
};
query: {
channel?: string;
name?: string;
};
};
responses: {
/** OK */
200: {
schema: definitions["Channel"][];
};
/** Unexpected Error */
default: {
schema: definitions["Error"];
};
};
};
}
export interface external {} | the_stack |
import {
calculateDiff,
mergeDiffs,
statementsToDiff,
} from '@/core/diff/helper';
import { getPrimitiveType } from '@/core/generator/code/helper';
import { getData } from '@/core/helper';
import { Logger } from '@/core/logger';
import {
Author,
changeSetAttributes,
Constraints,
createXMLString,
Dialect,
FormatChangeSet,
FormatColumnOptions,
FormatIndexOptions,
formatNames,
FormatRelationOptions,
FormatTableDiff,
FormatTableOptions,
generateSeqName,
KeyColumn,
mapppingTranslationsDatabase,
supportedDialects,
translate,
XMLNode,
} from '@/core/parser/helper';
import { orderByNameASC } from '@/engine/store/helper/table.helper';
import { IERDEditorContext } from '@/internal-types/ERDEditorContext';
import { Relationship } from '@@types/engine/store/relationship.state';
import { Snapshot } from '@@types/engine/store/snapshot';
import {
Column,
Index,
Table,
TableState,
} from '@@types/engine/store/table.state';
import { Diff } from '../diff';
const xmlns = 'http://www.liquibase.org/xml/ns/dbchangelog';
const xmlnsxsi = 'http://www.w3.org/2001/XMLSchema-instance';
const xsiSchemaLocation =
'http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd';
/**
* Creates Liquibase XML file with export (*only supports source dialect `PostgreSQL` and creates changeSet in `oracle`, `mssql` and `postgresql`)
*/
export function createLiquibase(
context: IERDEditorContext,
id: string,
name: string
): string {
const currentDatabase = context.store.canvasState.database;
var changeSets: XMLNode[];
switch (currentDatabase) {
case 'PostgreSQL':
const author: Author = {
id: id.replace(/\.xml$/g, ''),
name: name,
};
changeSets = createXMLPostgreOracleMSS(context, author);
break;
default:
alert(
`Export from ${currentDatabase} dialect not supported, please use PostgreSQL`
);
return '';
}
return [
`<?xml version="1.0" encoding="UTF-8"?>`,
`<databaseChangeLog xmlns="${xmlns}" xmlns:xsi="${xmlnsxsi}" xsi:schemaLocation="${xsiSchemaLocation}">`,
createXMLString(changeSets),
`</databaseChangeLog>`,
].join('\n');
}
export const createXMLPostgreOracleMSS = (
context: IERDEditorContext,
author: Author
): XMLNode[] => {
const { snapshots, store } = context;
const { tableState, relationshipState } = store;
// check if no previous snapshots (if size==1 --> first snapshot is the current state)
if (snapshots.length <= 1) {
return [
createSequences(tableState, author),
...supportedDialects.map(dbName =>
createChangeSet({
dialect: dbName,
tableState,
relationshipState,
author,
})
),
];
}
Logger.log('Tables were changed, generating diff...');
Logger.log({ snapshots });
/**
* Latest change
*/
function mostRecentDiff(): Diff[] {
var oldSnap = snapshots[snapshots.length - 1];
var newSnap = snapshots[snapshots.length - 1];
for (let i = snapshots.length - 1; i > 0; i--) {
if (
snapshots[i].metadata?.type === 'user' ||
snapshots[i].metadata?.type === 'before-export'
) {
newSnap = snapshots[i];
oldSnap = snapshots[i - 1];
break;
}
}
Logger.log('mostRecentDiff()', calculateDiff(oldSnap, newSnap));
return calculateDiff(oldSnap, newSnap);
}
/**
* Original file that was imported
*/
function originalFileImport(): Diff[][] {
const snapsWithStatements: Snapshot[] = [];
for (let i = snapshots.length - 1; i >= 0; i--) {
if (
snapshots[i].metadata?.type === 'before-import' &&
snapshots[i].metadata?.filename.replace(/\.xml$/g, '').toLowerCase() ===
author.id.toLowerCase()
) {
for (let j = i; j >= 0; j--) {
if (
snapshots[j].metadata?.filename
.replace(/\.xml$/g, '')
.toLowerCase() !== author.id.toLowerCase()
) {
break;
}
snapsWithStatements.push(snapshots[j]);
}
break;
}
}
const historicalDiffs: Diff[][] = [];
for (let i = 0; i < snapsWithStatements.length; i++) {
historicalDiffs.push(statementsToDiff(snapsWithStatements[i], context));
}
Logger.log('originalFileImport()', { historicalDiffs });
return historicalDiffs;
}
/**
* Files that were changed and snapshot changes are only stored in memory
*/
function updatedFileImport(): Diff[][] {
const diffs: Diff[][] = [];
for (let i = snapshots.length - 1; i >= 0; i--) {
if (
snapshots[i].metadata?.type === 'before-export' &&
snapshots[i + 1]?.metadata?.type === 'after-export' &&
snapshots[i].metadata?.filename.replace(/\.xml$/g, '').toLowerCase() ===
author.id.toLowerCase()
) {
diffs.push(calculateDiff(snapshots[i - 1], snapshots[i]));
}
}
Logger.log('updatedFileImport()', { diffs });
return diffs;
}
return createTableDiff({
author,
diffs: mergeDiffs(
mostRecentDiff(),
...updatedFileImport(),
...originalFileImport()
),
});
};
function generateChangeSetSequence(author: Author): XMLNode {
return new XMLNode(
'changeSet',
changeSetAttributes({ author, suffix: 'common-sequences' }),
[generatePreConditions()]
);
}
function generatePreConditions(): XMLNode {
return new XMLNode(
'preConditions',
[{ name: 'onFail', value: 'MARK_RAN' }],
[
new XMLNode(
'or',
[],
supportedDialects.map(
dbName => new XMLNode('dbms', [{ name: 'type', value: dbName }])
)
),
]
);
}
export function createSequence(tableName: string, columnName: string): XMLNode {
return new XMLNode('createSequence', [
{ name: 'sequenceName', value: generateSeqName(tableName, columnName) },
{ name: 'startValue', value: '1' },
]);
}
export function dropSequence(tableName: string, columnName: string): XMLNode {
return new XMLNode('dropSequence', [
{ name: 'sequenceName', value: generateSeqName(tableName, columnName) },
]);
}
export function createSequences(
tableState: TableState,
author: Author
): XMLNode {
var changeSet: XMLNode = generateChangeSetSequence(author);
tableState.tables.forEach(table => {
table.columns.forEach(column => {
if (column.option.autoIncrement) {
changeSet.addChildren(createSequence(table.name, column.name));
}
});
});
return changeSet;
}
export const createTableDiff = ({
author,
diffs,
}: FormatTableDiff): XMLNode[] => {
Logger.log('Exporting diffs', diffs);
var changeSets: XMLNode[] = [];
var changeSetSequences: XMLNode = generateChangeSetSequence(author);
var changeSetModifyPG: XMLNode = new XMLNode(
'changeSet',
changeSetAttributes({ author, dialect: 'postgresql', suffix: 'postgresql' })
);
var changeSetModifyOracle: XMLNode = new XMLNode(
'changeSet',
changeSetAttributes({ author, dialect: 'oracle', suffix: 'oracle' })
);
var changeSetModifyMssql: XMLNode = new XMLNode(
'changeSet',
changeSetAttributes({ author, dialect: 'mssql', suffix: 'mssql' })
);
var changeSetCommon: XMLNode = new XMLNode(
'changeSet',
changeSetAttributes({ author, suffix: 'common' })
);
let columnsToAdd: Map<Table, Column[]> = new Map();
diffs.forEach(diff => {
// add table
if (diff.type === 'table' && diff.changes === 'add') {
const newTable = diff.newTable;
changeSetSequences.addChildren(
...newTable.columns
.filter(col => col.option.autoIncrement)
.map(col => createSequence(newTable.name, col.name))
);
changeSetModifyPG.addChildren(
createTable({ table: newTable, dialect: 'postgresql' })
);
changeSetModifyOracle.addChildren(
createTable({ table: newTable, dialect: 'oracle' })
);
changeSetModifyMssql.addChildren(
createTable({ table: newTable, dialect: 'mssql' })
);
}
// drop table
else if (diff.type === 'table' && diff.changes === 'remove') {
changeSetCommon.addChildren(dropTable(diff.oldTable));
}
// rename table
else if (diff.type === 'table' && diff.changes === 'modify') {
if (diff.oldTable.name !== diff.newTable.name) {
changeSetCommon.addChildren(renameTable(diff.oldTable, diff.newTable));
}
}
// add column
else if (diff.type === 'column' && diff.changes === 'add') {
const table = diff.table;
columnsToAdd.set(table, [
...(columnsToAdd.get(table) || []),
diff.newColumn,
]);
}
// drop column
else if (diff.type === 'column' && diff.changes === 'remove') {
changeSetCommon.addChildren(dropColumn(diff.table, diff.oldColumn));
}
// add index
else if (diff.type === 'index' && diff.changes === 'add') {
changeSetCommon.addChildren(
createIndex({ table: diff.table, index: diff.newIndex })
);
}
// drop index
else if (diff.type === 'index' && diff.changes === 'remove') {
changeSetCommon.addChildren(dropIndex(diff.table, diff.oldIndex));
}
// add FK
else if (diff.type === 'relationship' && diff.changes === 'add') {
changeSetCommon.addChildren(
addForeignKeyConstraint({
startTable: diff.startTable,
endTable: diff.endTable,
relationship: diff.newRelationship,
})
);
}
// drop FK
else if (diff.type === 'relationship' && diff.changes === 'remove') {
changeSetCommon.addChildren(
dropForeignKeyConstraint(diff.table, diff.oldRelationship)
);
}
// modify column
else if (diff.type === 'column' && diff.changes === 'modify') {
const { oldColumn, newColumn, table } = diff;
// name was changed
if (oldColumn.name !== newColumn.name) {
changeSetCommon.addChildren(renameColumn(table, newColumn, oldColumn));
}
// auto increment changed
if (oldColumn.option.autoIncrement !== newColumn.option.autoIncrement) {
if (newColumn.option.autoIncrement === true) {
changeSetSequences.addChildren(
createSequence(table.name, newColumn.name)
);
} else {
changeSetSequences.addChildren(
dropSequence(table.name, newColumn.name)
);
}
}
// primary key changed
if (oldColumn.option.primaryKey !== newColumn.option.primaryKey) {
if (newColumn.option.primaryKey === true) {
changeSetCommon.addChildren(addPrimaryKey(table, [newColumn]));
} else {
changeSetCommon.addChildren(dropPrimaryKey(table));
}
}
// unique changed
if (oldColumn.option.unique !== newColumn.option.unique) {
if (newColumn.option.unique === true) {
changeSetCommon.addChildren(addUniqueConstraint(table, [newColumn]));
} else {
changeSetCommon.addChildren(dropUniqueConstraint(table));
}
}
// datatype was changed
if (oldColumn.dataType !== newColumn.dataType) {
changeSetModifyPG.addChildren(
modifyDataType(table, newColumn, 'postgresql')
);
changeSetModifyOracle.addChildren(
modifyDataType(table, newColumn, 'oracle')
);
changeSetModifyMssql.addChildren(
modifyDataType(table, newColumn, 'mssql')
);
}
}
});
columnsToAdd.forEach((colums, table) => {
changeSetModifyPG.addChildren(addColumn(table, colums, 'postgresql'));
changeSetModifyOracle.addChildren(addColumn(table, colums, 'oracle'));
changeSetModifyMssql.addChildren(addColumn(table, colums, 'mssql'));
});
// sequences - (minus) first child is always preconditions
if (changeSetSequences.children.length > 1) {
changeSets.push(changeSetSequences);
}
// if modification
if (changeSetModifyPG.children.length) {
changeSets.push(changeSetModifyPG);
changeSets.push(changeSetModifyOracle);
changeSets.push(changeSetModifyMssql);
}
// if common
if (changeSetCommon.children.length) {
changeSets.push(changeSetCommon);
}
return changeSets;
};
export const createChangeSet = ({
dialect,
tableState,
relationshipState,
author,
}: FormatChangeSet): XMLNode => {
var changeSet: XMLNode = new XMLNode('changeSet');
const tables = orderByNameASC(tableState.tables);
const relationships = relationshipState.relationships;
const indexes = tableState.indexes;
changeSet.addAttribute(
...changeSetAttributes({ author, dialect, suffix: dialect })
);
tables.forEach(table => {
changeSet.addChildren(
createTable({
table,
dialect,
})
);
});
relationships.forEach(relationship => {
const startTable = getData(tables, relationship.start.tableId);
const endTable = getData(tables, relationship.end.tableId);
if (startTable && endTable)
changeSet.addChildren(
addForeignKeyConstraint({
startTable,
endTable,
relationship,
})
);
});
indexes.forEach(index => {
const table = getData(tables, index.tableId);
if (table)
changeSet.addChildren(
createIndex({
table,
index,
})
);
});
return changeSet;
};
export const createTable = ({
table,
dialect,
}: FormatTableOptions): XMLNode => {
var createTable: XMLNode = new XMLNode('createTable');
createTable.addAttribute({ name: 'tableName', value: table.name });
if (table.comment)
createTable.addAttribute({ name: 'remarks', value: table.comment });
table.columns.forEach((column, i) => {
createTable.addChildren(
formatColumn({
table,
column,
dialect,
})
);
});
return createTable;
};
/**
* Formatting of one column
*/
export const formatColumn = ({
table,
column,
dialect,
}: FormatColumnOptions): XMLNode => {
var columnXML: XMLNode = new XMLNode('column', [
{ name: 'name', value: column.name },
{
name: 'type',
value: translate('postgresql', dialect, column.dataType),
},
]);
if (column.dataType)
columnXML.addAttribute({
name: 'type',
value: translate('postgresql', dialect, column.dataType),
});
if (column.option.autoIncrement) {
const primitive = getPrimitiveType(
column.dataType,
mapppingTranslationsDatabase[dialect]
);
if (
dialect === 'postgresql' &&
(primitive === 'int' || primitive === 'long')
) {
columnXML.addAttribute({
name: 'defaultValueComputed',
value: `nextval('${generateSeqName(
table.name,
column.name
)}'::regclass)`,
});
} else {
columnXML.addAttribute({
name: 'autoIncrement',
value: column.option.autoIncrement.toString(),
});
}
}
if (column.default)
columnXML.addAttribute({ name: 'defaultValue', value: column.default });
if (column.comment)
columnXML.addAttribute({ name: 'remarks', value: column.comment });
// if constraints
if (
column.option.notNull ||
column.option.primaryKey ||
column.option.unique
) {
columnXML.addChildren(
formatConstraints({
primaryKey: column.option.primaryKey,
nullable: !column.option.notNull,
unique: column.option.unique,
})
);
}
return columnXML;
};
/**
* Formatting constraints inside one column
*/
export const formatConstraints = (constraints: Constraints): XMLNode => {
var constraintsXML: XMLNode = new XMLNode('constraints');
if (constraints.primaryKey)
constraintsXML.addAttribute({
name: 'primaryKey',
value: constraints.primaryKey.toString(),
});
if (constraints.nullable === false)
constraintsXML.addAttribute({
name: 'nullable',
value: constraints.nullable.toString(),
});
if (constraints.unique)
constraintsXML.addAttribute({
name: 'unique',
value: constraints.unique.toString(),
});
return constraintsXML;
};
export const addForeignKeyConstraint = ({
startTable,
endTable,
relationship,
}: FormatRelationOptions): XMLNode => {
if (startTable && endTable) {
const columns: KeyColumn = {
start: [],
end: [],
};
relationship.end.columnIds.forEach(columnId => {
const column = getData(endTable.columns, columnId);
if (column) {
columns.end.push(column);
}
});
relationship.start.columnIds.forEach(columnId => {
const column = getData(startTable.columns, columnId);
if (column) {
columns.start.push(column);
}
});
return new XMLNode('addForeignKeyConstraint', [
{ name: 'baseColumnNames', value: formatNames(columns.end) },
{ name: 'baseTableName', value: endTable.name },
{
name: 'constraintName',
value: `FK_${startTable.name}_TO_${endTable.name}`.toLowerCase(),
},
{ name: 'deferrable', value: 'false' },
{ name: 'initiallyDeferred', value: 'false' },
{ name: 'referencedColumnNames', value: formatNames(columns.start) },
{ name: 'referencedTableName', value: startTable.name },
]);
}
return new XMLNode('');
};
/**
* Creating index
*/
export const createIndex = ({ table, index }: FormatIndexOptions): XMLNode => {
// gets real columns, using id
const colsWithIndex = index.columns
.map(indexColumn => {
const column = getData(table.columns, indexColumn.id);
if (column) {
return {
name: `${column.name}`,
descending: indexColumn.orderType === 'DESC',
};
}
return null;
})
.filter(columnName => columnName !== null) as {
name: string;
descending: boolean;
}[];
if (colsWithIndex.length !== 0) {
var createIndex: XMLNode = new XMLNode('createIndex');
let indexName = index.name;
if (index.name.trim() === '') {
indexName = `${table.name}`;
}
createIndex.addAttribute(
{ name: 'indexName', value: indexName },
{ name: 'tableName', value: table.name }
);
if (index.unique)
createIndex.addAttribute({
name: 'unique',
value: index.unique.toString(),
});
colsWithIndex.forEach(column => {
var columnXML = new XMLNode('column', [
{ name: 'name', value: column.name },
]);
if (column.descending)
columnXML.addAttribute({
name: 'descending',
value: column.descending.toString(),
});
createIndex.addChildren(columnXML);
});
return createIndex;
}
return new XMLNode('');
};
export const dropTable = (table: Table): XMLNode => {
return new XMLNode('dropTable', [{ name: 'tableName', value: table.name }]);
};
export const addColumn = (
table: Table,
columns: Column[],
dialect: Dialect
): XMLNode => {
var addColumn: XMLNode = new XMLNode('addColumn', [
{ name: 'tableName', value: table.name },
]);
columns.forEach(column => {
addColumn.addChildren(formatColumn({ table, column, dialect }));
});
return addColumn;
};
export const dropColumn = (table: Table, column: Column): XMLNode => {
return new XMLNode('dropColumn', [
{ name: 'tableName', value: table.name },
{ name: 'columnName', value: column.name },
]);
};
export const modifyDataType = (
table: Table,
newColumn: Column,
dialectTo: Dialect
): XMLNode => {
return new XMLNode('modifyDataType', [
{ name: 'tableName', value: table.name },
{ name: 'columnName', value: newColumn.name },
{
name: 'newDataType',
value: translate('postgresql', dialectTo, newColumn.dataType),
},
]);
};
export const renameColumn = (
table: Table,
newColumn: Column,
oldColumn: Column
): XMLNode => {
return new XMLNode('renameColumn', [
{ name: 'tableName', value: table.name },
{ name: 'newColumnName', value: newColumn.name },
{ name: 'oldColumnName', value: oldColumn.name },
]);
};
export const renameTable = (newTable: Table, oldTable: Table): XMLNode => {
return new XMLNode('renameTable', [
{ name: 'newTableName', value: newTable.name },
{ name: 'oldTableName', value: oldTable.name },
]);
};
export const dropIndex = (table: Table, index: Index): XMLNode => {
return new XMLNode('dropIndex', [
{ name: 'indexName', value: index.name },
{ name: 'tableName', value: table.name },
]);
};
function dropForeignKeyConstraint(
table: Table,
relationship: Relationship
): XMLNode {
return new XMLNode('dropForeignKeyConstraint', [
{ name: 'baseTableName', value: table.name },
{ name: 'constraintName', value: relationship.constraintName || '???' },
]);
}
function addPrimaryKey(table: Table, columns: Column[]): XMLNode {
return new XMLNode('addPrimaryKey', [
{ name: 'tableName', value: table.name },
{ name: 'columnNames', value: formatNames(columns) },
]);
}
function dropPrimaryKey(table: Table): XMLNode {
return new XMLNode('dropPrimaryKey', [
{ name: 'tableName', value: table.name },
]);
}
function addUniqueConstraint(table: Table, columns: Column[]): XMLNode {
return new XMLNode('addUniqueConstraint', [
{ name: 'tableName', value: table.name },
{ name: 'columnNames', value: formatNames(columns) },
]);
}
function dropUniqueConstraint(table: Table): XMLNode {
return new XMLNode('dropUniqueConstraint', [
{ name: 'tableName', value: table.name },
{ name: 'constraintName', value: '???' },
]);
} | the_stack |
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
import { ClientRequestCache } from "./client-request-cache";
import { defer } from "../utils/promiseutil";
import { UserMembership } from "./membership-cache";
import { unstable } from "../errors";
import BridgeErrorReason = unstable.BridgeErrorReason;
import { APPSERVICE_LOGIN_TYPE, ClientEncryptionSession } from "./encryption";
import Logging from "./logging";
import { ReadStream } from "fs";
import BotSdk, { MatrixClient, MatrixProfileInfo, PresenceState } from "matrix-bot-sdk";
const log = Logging.get("Intent");
export type IntentBackingStore = {
getMembership: (roomId: string, userId: string) => UserMembership,
getMemberProfile: (roomId: string, userid: string) => MatrixProfileInfo,
getPowerLevelContent: (roomId: string) => PowerLevelContent | undefined,
setMembership: (roomId: string, userId: string, membership: UserMembership, profile: MatrixProfileInfo) => void,
setPowerLevelContent: (roomId: string, content: PowerLevelContent) => void,
};
type OnEventSentHook = (roomId: string, type: string, content: Record<string, unknown>, eventId: string) => void;
export interface IntentOpts {
backingStore?: IntentBackingStore,
caching?: {
ttl?: number,
size?: number,
}
dontCheckPowerLevel?: boolean;
dontJoin?: boolean;
enablePresence?: boolean;
registered?: boolean;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getJsSdkClient?: () => any,
encryption?: {
sessionPromise: Promise<ClientEncryptionSession|null>;
sessionCreatedCallback: (session: ClientEncryptionSession) => Promise<void>;
ensureClientSyncingCallback: () => Promise<void>;
};
onEventSent?: OnEventSentHook,
}
export interface RoomCreationOpts {
createAsClient?: boolean;
options?: Record<string, unknown>;
}
export interface FileUploadOpts {
name?: string;
type?: string;
}
/**
* Returns the first parameter that is a number or 0.
*/
const returnFirstNumber = (...args: unknown[]) => {
for (const arg of args) {
if (typeof arg === "number") {
return arg;
}
}
return 0;
}
const DEFAULT_CACHE_TTL = 90000;
const DEFAULT_CACHE_SIZE = 1024;
export type PowerLevelContent = {
// eslint-disable-next-line camelcase
state_default?: unknown;
// eslint-disable-next-line camelcase
events_default?: unknown;
// eslint-disable-next-line camelcase
users_default?: unknown;
users?: {
[userId: string]: unknown;
},
events?: {
[eventType: string]: unknown;
}
};
type UserProfileKeys = "avatar_url"|"displayname"|null;
export class Intent {
private static getClientWarningFired = false;
private _requestCaches: {
profile: ClientRequestCache<MatrixProfileInfo, [string, UserProfileKeys]>,
roomstate: ClientRequestCache<unknown, []>,
event: ClientRequestCache<unknown, [string, string]>
}
private opts: {
backingStore: IntentBackingStore,
caching: {
ttl: number,
size: number,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getJsSdkClient?: () => any,
dontCheckPowerLevel?: boolean;
dontJoin?: boolean;
enablePresence: boolean;
registered?: boolean;
onEventSent?: OnEventSentHook,
}
// These two are only used if no opts.backingStore is provided to the constructor.
private readonly _membershipStates: Record<string, [UserMembership, MatrixProfileInfo]> = {};
private readonly _powerLevels: Record<string, PowerLevelContent> = {};
private readonly encryptedRooms = new Map<string, string|false>();
private readonly encryption?: {
sessionPromise: Promise<ClientEncryptionSession|null>;
sessionCreatedCallback: (session: ClientEncryptionSession) => Promise<void>;
ensureClientSyncingCallback: () => Promise<void>;
};
private readyPromise?: Promise<unknown>;
// The legacyClient is created on demand when bridges need to use
// it, but is not created by default anymore.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private legacyClient?: any;
/**
* Create an entity which can fulfil the intent of a given user.
* @constructor
* @param botSdkIntent The bot sdk intent which this intent wraps
* fulfilled e.g. the entity joining the room when you call intent.join(roomId).
* @param botClient The client instance for the AS bot itself.
* This will be used to perform more priveleged actions such as creating new
* rooms, sending invites, etc.
* @param opts Options for this Intent instance.
* @param opts.registered True to inform this instance that the client
* is already registered. No registration requests will be made from this Intent.
* Default: false.
* @param opts.dontCheckPowerLevel True to not check for the right power
* level before sending events. Default: false.
*
* @param opts.backingStore An object with 4 functions, outlined below.
* If this Object is supplied, ALL 4 functions must be supplied. If this Object
* is not supplied, the Intent will maintain its own backing store for membership
* and power levels, which may scale badly for lots of users.
*
* @param opts.backingStore.getMembership A function which is called with a
* room ID and user ID which should return the membership status of this user as
* a string e.g "join". `null` should be returned if the membership is unknown.
*
* @param opts.backingStore.getPowerLevelContent A function which is called
* with a room ID which should return the power level content for this room, as an Object.
* `null` should be returned if there is no known content.
*
* @param opts.backingStore.setMembership A function with the signature:
* function(roomId, userId, membership) which will set the membership of the given user in
* the given room. This has no return value.
*
* @param opts.backingStore.setPowerLevelContent A function with the signature:
* function(roomId, content) which will set the power level content in the given room.
* This has no return value.
*
* @param opts.dontJoin True to not attempt to join a room before
* sending messages into it. The surrounding code will have to ensure the correct
* membership state itself in this case. Default: false.
*
* @param opts.enablePresence True to send presence, false to no-op.
*
* @param opts.caching.ttl How long requests can stay in the cache, in milliseconds.
* @param opts.caching.size How many entries should be kept in the cache, before the oldest is dropped.
* @param opts.getJsSdkClient Create a Matrix JS SDK client on demand for legacy code.
*/
constructor(
public readonly botSdkIntent: BotSdk.Intent,
private readonly botClient: BotSdk.MatrixClient,
opts: IntentOpts = {}) {
if (opts.backingStore) {
if (!opts.backingStore.setPowerLevelContent ||
!opts.backingStore.getPowerLevelContent ||
!opts.backingStore.setMembership ||
!opts.backingStore.getMembership) {
throw new Error("Intent backingStore missing required functions");
}
}
this.encryption = opts.encryption;
this.opts = {
...opts,
backingStore: opts.backingStore ? { ...opts.backingStore } : {
getMembership: (roomId: string, userId: string) => {
if (userId !== this.userId) {
return null;
}
return this._membershipStates[roomId] && this._membershipStates[roomId][0];
},
getMemberProfile: (roomId: string, userId: string) => {
if (userId !== this.userId) {
return {};
}
return this._membershipStates[roomId] && this._membershipStates[roomId][1];
},
getPowerLevelContent: (roomId: string) => {
return this._powerLevels[roomId];
},
setMembership: (
roomId: string, userId: string, membership: UserMembership, profile: MatrixProfileInfo) => {
if (userId !== this.userId) {
return;
}
this._membershipStates[roomId] = [membership, profile];
},
setPowerLevelContent: (roomId: string, content: PowerLevelContent) => {
this._powerLevels[roomId] = content;
},
},
caching: {
size: opts.caching?.ttl || DEFAULT_CACHE_SIZE,
ttl: opts.caching?.ttl || DEFAULT_CACHE_TTL,
},
enablePresence: opts.enablePresence !== false,
};
this._requestCaches = {
profile: new ClientRequestCache(
this.opts.caching.ttl,
this.opts.caching.size,
(_: string, userId: string, info: UserProfileKeys) => {
return this.getProfileInfo(userId, info, false);
}
),
roomstate: new ClientRequestCache(
this.opts.caching.ttl,
this.opts.caching.size,
(roomId: string) => {
return this.roomState(roomId, false);
}
),
event: new ClientRequestCache(
this.opts.caching.ttl,
this.opts.caching.size,
(_: string, roomId: string, eventId: string) => {
return this.getEvent(roomId, eventId, false);
}
),
};
}
public get matrixClient(): MatrixClient {
return this.botSdkIntent.underlyingClient;
}
/**
* Legacy property to access the matrix-js-sdk.
* @deprecated Support for the matrix-js-sdk client will be going away in
* a future release. Where possible, the intent object functions should be
* used. The `botSdkIntent` also provides access to the new client.
* @see getClient
*/
public get client() {
return this.getClient();
}
/**
* Return a matrix-js-sdk client, which is created on demand.
* @deprecated Support for the matrix-js-sdk client will be going away in
* a future release. Where possible, the intent object functions should be
* used. The `botSdkIntent` also provides access to the new client.
* @return The client
*/
public getClient() {
if (this.legacyClient) {
return this.legacyClient;
}
if (!this.opts.getJsSdkClient) {
throw Error('Legacy client not available');
}
if (!Intent.getClientWarningFired) {
console.warn("Support for the matrix-js-sdk will be going away in a future release." +
"Please replace usage of Intent.getClient() and Intent.client with either " +
"Intent functions, or Intent.matrixClient");
Intent.getClientWarningFired = true;
}
this.legacyClient = this.opts.getJsSdkClient();
return this.legacyClient;
}
public get userId(): string {
return this.botSdkIntent.userId;
}
/**
* Resolve a roomId or alias into a roomId. If a roomId is given, it is immediately returned.
* @param roomAliasOrId A roomId or alias to resolve.
* @throws If the provided string was incorrectly formatted or alias does not exist.
*/
public async resolveRoom(roomAliasOrId: string): Promise<string> {
return this.botSdkIntent.underlyingClient.resolveRoom(roomAliasOrId);
}
/**
* Send a plaintext message to a room.
*
* This will automatically make the client join the room so they can send the
* message if they are not already joined. It will also make sure that the client
* has sufficient power level to do this.
* @param roomId The room to send to.
* @param text The text string to send.
* @returns The Matrix event ID.
*/
public sendText(roomId: string, text: string): Promise<{event_id: string}> {
return this.sendMessage(roomId, {
body: text,
msgtype: "m.text"
});
}
/**
* Set the name of a room.
*
* This will automatically make the client join the room so they can set the
* name if they are not already joined. It will also make sure that the client
* has sufficient power level to do this.
* @param roomId The room to send to.
* @param name The room name.
* @returns The Matrix event ID.
*/
public async setRoomName(roomId: string, name: string): Promise<{event_id: string}> {
return this.sendStateEvent(roomId, "m.room.name", "", {
name: name
});
}
/**
* Set the topic of a room.
*
* This will automatically make the client join the room so they can set the
* topic if they are not already joined. It will also make sure that the client
* has sufficient power level to do this.
* @param roomId The room to send to.
* @param topic The room topic.
*/
public async setRoomTopic(roomId: string, topic: string): Promise<{event_id: string}> {
return this.sendStateEvent(roomId, "m.room.topic", "", {
topic: topic
});
}
/**
* Set the avatar of a room.
*
* This will automatically make the client join the room so they can set the
* topic if they are not already joined. It will also make sure that the client
* has sufficient power level to do this.
* @param roomId The room to send to.
* @param avatar The url of the avatar.
* @param info Extra information about the image. See m.room.avatar for details.
*/
public setRoomAvatar(roomId: string, avatar: string, info?: string): Promise<{event_id: string}> {
return this.sendStateEvent(roomId, "m.room.avatar", "", {
info,
url: avatar,
});
}
/**
* Send a typing event to a room.
*
* This will automatically make the client join the room so they can send the
* typing event if they are not already joined.
* @param roomId The room to send to.
* @param isTyping True if typing
*/
public async sendTyping(roomId: string, isTyping: boolean) {
await this._ensureJoined(roomId);
return this.botSdkIntent.underlyingClient.setTyping(roomId, isTyping);
}
/**
* Send a read receipt to a room.
*
* This will automatically make the client join the room so they can send the
* receipt event if they are not already joined.
* @param roomId The room to send to.
* @param eventId The event ID to set the receipt mark to.
*/
public async sendReadReceipt(roomId: string, eventId: string) {
await this._ensureJoined(roomId);
return this.botSdkIntent.underlyingClient.sendReadReceipt(roomId, eventId);
}
/**
* Set the power level of the given target.
* @param roomId The room to set the power level in.
* @param target The target user ID
* @param level The desired level. Undefined will remove the users custom power level.
*/
public async setPowerLevel(roomId: string, target: string, level: number|undefined) {
await this._ensureJoined(roomId);
const powerLevel: PowerLevelContent = await this.getStateEvent(roomId, "m.room.power_levels", "", true);
if (powerLevel && level && (powerLevel?.users || {})[target] !== level) {
powerLevel.users = powerLevel.users || {};
powerLevel.users[target] = level;
await this.sendStateEvent(roomId, "m.room.power_levels", "", powerLevel);
}
else if (powerLevel?.users && !level) {
delete powerLevel.users[target];
await this.sendStateEvent(roomId, "m.room.power_levels", "", powerLevel);
}
else if (!powerLevel && level) {
await this.botSdkIntent.underlyingClient.setUserPowerLevel(target, roomId, level);
}
// Otherwise this is a no-op
log.debug(`Setting PL of ${target} in ${roomId} to ${level} was a no-op`)
}
/**
* Send an `m.room.message` event to a room.
*
* This will automatically make the client join the room so they can send the
* message if they are not already joined. It will also make sure that the client
* has sufficient power level to do this.
* @param roomId The room to send to.
* @param content The event content
*/
public sendMessage(roomId: string, content: Record<string, unknown>) {
return this.sendEvent(roomId, "m.room.message", content);
}
/**
* Send a message event to a room.
*
* This will automatically make the client join the room so they can send the
* message if they are not already joined. It will also make sure that the client
* has sufficient power level to do this.
* @param roomId The room to send to.
* @param type The event type
* @param content The event content
*/
public async sendEvent(roomId: string, type: string, content: Record<string, unknown>)
// eslint-disable-next-line camelcase
: Promise<{event_id: string}> {
if (this.encryption) {
let encrypted = false;
try {
encrypted = !!(await this.isRoomEncrypted(roomId));
}
catch (ex) {
// This is unexpected. Fail safe.
log.debug(`Could not determine if room is encrypted. Assuming yes:`, ex);
encrypted = true;
}
if (encrypted) {
// We *need* to sync before we can send a message to an encrypted room.
await this.ensureRegistered();
await this.encryption.ensureClientSyncingCallback();
}
}
await this._ensureJoined(roomId);
await this._ensureHasPowerLevelFor(roomId, type, false);
return this._joinGuard(roomId, async() => {
const result = {
// eslint-disable-next-line camelcase
event_id: await this.botSdkIntent.underlyingClient.sendEvent(roomId, type, content),
};
this.opts.onEventSent?.(roomId, type, content, result.event_id);
return result;
});
}
/**
* Send a state event to a room.
*
* This will automatically make the client join the room so they can send the
* state if they are not already joined. It will also make sure that the client
* has sufficient power level to do this.
* @param roomId The room to send to.
* @param type The event type
* @param skey The state key
* @param content The event content
*/
public async sendStateEvent(roomId: string, type: string, skey: string, content: Record<string, unknown>
// eslint-disable-next-line camelcase
): Promise<{event_id: string}> {
return this._joinGuard(roomId, async() => {
try {
return {
// eslint-disable-next-line camelcase
event_id: await this.botSdkIntent.underlyingClient.sendStateEvent(roomId, type, skey, content),
}
}
catch (ex) {
if (ex.body.errcode !== "M_FORBIDDEN") {
throw ex;
}
}
await this._ensureHasPowerLevelFor(roomId, type, true);
return {
// eslint-disable-next-line camelcase
event_id: await this.botSdkIntent.underlyingClient.sendStateEvent(roomId, type, skey, content)
}
});
}
/**
* Get the current room state for a room.
*
* This will automatically make the client join the room so they can get the
* state if they are not already joined.
* @param roomId The room to get the state from.
* @param useCache Should the request attempt to lookup
* state from the cache.
*/
public async roomState(roomId: string, useCache=false) {
await this._ensureJoined(roomId);
if (useCache) {
return this._requestCaches.roomstate.get(roomId);
}
return this.botSdkIntent.underlyingClient.getRoomState(roomId);
}
/**
* Create a room with a set of options.
* @param opts Options.
* @param opts.createAsClient True to create this room as a client and
* not the bot: the bot will not join. False to create this room as the bot and
* auto-join the client. Default: false.
* @param opts.options Options to pass to the client SDK /createRoom API.
*/
// eslint-disable-next-line camelcase
public async createRoom(opts: RoomCreationOpts): Promise<{room_id: string}> {
const cli = opts.createAsClient ? this.botSdkIntent.underlyingClient : this.botClient;
const options = opts.options || {};
if (!opts.createAsClient) {
// invite the client if they aren't already
options.invite = options.invite || [];
if (Array.isArray(options.invite) && !options.invite.includes(this.userId)) {
options.invite.push(this.userId);
}
}
// make sure that the thing doing the room creation isn't inviting itself
// else Synapse hard fails the operation with M_FORBIDDEN
if (Array.isArray(options.invite) && options.invite.includes(this.userId)) {
options.invite.splice(options.invite.indexOf(this.userId), 1);
}
await this.ensureRegistered();
const roomId = await cli.createRoom(options);
// create a fake power level event to give the room creator ops if we
// don't yet have a power level event.
if (this.opts.backingStore.getPowerLevelContent(roomId)) {
return {room_id: roomId};
}
const users: Record<string, number> = {};
users[this.userId] = 100;
this.opts.backingStore.setPowerLevelContent(roomId, {
users_default: 0,
events_default: 0,
state_default: 50,
users: users,
events: {}
});
return {room_id: roomId};
}
/**
* Invite a user to a room.
*
* This will automatically make the client join the room so they can send the
* invite if they are not already joined.
* @param roomId The room to invite the user to.
* @param target The user ID to invite.
* @return Resolved when invited, else rejected with an error.
*/
public async invite(roomId: string, target: string) {
await this._ensureJoined(roomId);
return this.botSdkIntent.underlyingClient.inviteUser(target, roomId);
}
/**
* Kick a user from a room.
*
* This will automatically make the client join the room so they can send the
* kick if they are not already joined.
* @param roomId The room to kick the user from.
* @param target The target of the kick operation.
* @param reason Optional. The reason for the kick.
* @return Resolved when kickked, else rejected with an error.
*/
public async kick(roomId: string, target: string, reason?: string) {
if (target !== this.userId) {
// Only ensure joined if we are not also the kicker
await this._ensureJoined(roomId);
}
return this.botSdkIntent.underlyingClient.kickUser(target, roomId, reason);
}
/**
* Ban a user from a room.
*
* This will automatically make the client join the room so they can send the
* ban if they are not already joined.
* @param roomId The room to ban the user from.
* @param target The target of the ban operation.
* @param reason Optional. The reason for the ban.
* @return Resolved when banned, else rejected with an error.
*/
public async ban(roomId: string, target: string, reason?: string) {
await this._ensureJoined(roomId);
return this.botSdkIntent.underlyingClient.banUser(target, roomId, reason);
}
/**
* Unban a user from a room.
*
* This will automatically make the client join the room so they can send the
* unban if they are not already joined.
* @param roomId The room to unban the user from.
* @param target The target of the unban operation.
* @return Resolved when unbanned, else rejected with an error.
*/
public async unban(roomId: string, target: string) {
await this._ensureJoined(roomId);
return this.botSdkIntent.underlyingClient.unbanUser(target, roomId);
}
/**
* Join a room
*
* This will automatically send an invite from the bot if it is an invite-only
* room, which may make the bot attempt to join the room if it isn't already.
* @param roomIdOrAlias The room ID or room alias to join.
* @param viaServers The server names to try and join through in
* addition to those that are automatically chosen.
*/
public async join(roomIdOrAlias: string, viaServers?: string[]): Promise<string> {
return this._ensureJoined(roomIdOrAlias, false, viaServers);
}
/**
* Leave a room
*
* This will no-op if the user isn't in the room.
* @param roomId The room to leave.
* @param reason An optional string to explain why the user left the room.
*/
public async leave(roomId: string, reason?: string) {
if (reason) {
await this.botSdkIntent.ensureRegistered();
return this.botSdkIntent.underlyingClient.kickUser(this.userId, roomId, reason);
}
return this.botSdkIntent.leaveRoom(roomId);
}
/**
* Get a user's profile information
*
* @param userId The ID of the user whose profile to return
* @param info The profile field name to retrieve (e.g. 'displayname'
* or 'avatar_url'), or null to fetch the entire profile information.
* @param useCache Should the request attempt to lookup
* state from the cache.
* @return A Promise that resolves with the requested user's profile
* information
*/
public async getProfileInfo(
userId: string, info: UserProfileKeys = null, useCache = true): Promise<MatrixProfileInfo> {
await this.ensureRegistered();
if (useCache) {
return this._requestCaches.profile.get(`${userId}`, userId, null);
}
const profile: MatrixProfileInfo = await this.botSdkIntent.underlyingClient.getUserProfile(userId);
if (info === 'avatar_url') {
return { avatar_url: profile.avatar_url };
}
if (info === 'displayname') {
return { displayname: profile.displayname };
}
return profile;
}
/**
* Set the user's display name
*
* @param name The new display name
*/
public async setDisplayName(name: string) {
await this.ensureRegistered();
return this.botSdkIntent.underlyingClient.setDisplayName(name);
}
/**
* Set the user's avatar URL
*
* @param url The new avatar URL
*/
public async setAvatarUrl(url: string) {
await this.ensureRegistered();
return this.botSdkIntent.underlyingClient.setAvatarUrl(url);
}
/**
* Ensure that the user has the given profile information set. If it does not,
* set it.
* @param displayname The displayname to set. Leave undefined to ignore.
* @param avatarUrl The avatar to set. Leave undefined to ignore.
*/
public async ensureProfile(displayname?: string, avatarUrl?: string) {
if (!displayname && !avatarUrl) {
throw Error('At least one of displayname,avatarUrl must be defined');
}
const profile = await this.getProfileInfo(this.userId, null, false);
if (displayname && profile.displayname !== displayname) {
await this.setDisplayName(displayname);
}
if (avatarUrl && profile.avatar_url !== avatarUrl) {
await this.setAvatarUrl(avatarUrl);
}
}
public async setRoomUserProfile(roomId: string, profile: MatrixProfileInfo) {
const currProfile = this.opts.backingStore.getMemberProfile(roomId, this.userId);
// Compare the user's current profile (from cache) with the profile
// that is requested. Only send the state event if something that was
// requested to change is different from the current value.
if (("displayname" in profile && currProfile.displayname != profile.displayname) ||
("avatar_url" in profile && currProfile.avatar_url != profile.avatar_url)) {
const content = {
membership: "join",
...currProfile,
...profile,
};
await this.sendStateEvent(roomId, 'm.room.member', this.userId, content);
}
}
/**
* Create a new alias mapping.
* @param alias The room alias to create
* @param roomId The room ID the alias should point at.
*/
public async createAlias(alias: string, roomId: string) {
await this.ensureRegistered();
return this.botSdkIntent.underlyingClient.createRoomAlias(alias, roomId);
}
/**
* Set the presence of this user.
* @param presence One of "online", "offline" or "unavailable".
* @param status_msg The status message to attach.
* @return Resolves if the presence was set or no-oped, rejects otherwise.
*/
public async setPresence(presence: PresenceState, statusMsg?: string) {
if (!this.opts.enablePresence) {
return undefined;
}
await this.ensureRegistered();
return this.botSdkIntent.underlyingClient.setPresenceStatus(presence, statusMsg);
}
/**
* Signals that an error occured while handling an event by the bridge.
*
* **Warning**: This function is unstable and is likely to change pending the outcome
* of https://github.com/matrix-org/matrix-doc/pull/2162.
* @param roomID ID of the room in which the error occured.
* @param eventID ID of the event for which the error occured.
* @param networkName Name of the bridged network.
* @param reason The reason why the bridge error occured.
* @param reason_body A human readable string d
* @param affectedUsers Array of regex matching all affected users.
*/
public async unstableSignalBridgeError(
roomID: string,
eventID: string,
networkName: string|undefined,
reason: BridgeErrorReason,
affectedUsers: string[],
) {
return this.sendEvent(
roomID,
"de.nasnotfound.bridge_error",
{
network_name: networkName,
reason: reason,
affected_users: affectedUsers,
"m.relates_to": {
rel_type: "m.reference",
event_id: eventID,
},
}
);
}
/**
* Get an event in a room.
* This will automatically make the client join the room so they can get the
* event if they are not already joined.
* @param roomId The room to fetch the event from.
* @param eventId The eventId of the event to fetch.
* @param useCache Should the request attempt to lookup from the cache.
* @return Resolves with the content of the event, or rejects if not found.
*/
public async getEvent(roomId: string, eventId: string, useCache=true) {
await this.ensureRegistered();
if (useCache) {
return this._requestCaches.event.get(`${roomId}:${eventId}`, roomId, eventId);
}
return this.botSdkIntent.underlyingClient.getEvent(roomId, eventId);
}
/**
* Get a state event in a room.
* This will automatically make the client join the room so they can get the
* state if they are not already joined.
* @param roomId The room to get the state from.
* @param eventType The event type to fetch.
* @param stateKey The state key of the event to fetch.
* @param returnNull Return null on not found, rather than throwing
*/
public async getStateEvent(roomId: string, eventType: string, stateKey = "", returnNull = false) {
await this._ensureJoined(roomId);
try {
return await this.botSdkIntent.underlyingClient.getRoomStateEvent(roomId, eventType, stateKey);
}
catch (ex) {
if (ex.body.errcode !== "M_NOT_FOUND" || !returnNull) {
throw ex;
}
}
return null;
}
/**
* Check if a room is encrypted. If it is, return the algorithm.
* @param roomId The room ID to be checked
* @returns The encryption algorithm or false
*/
public async isRoomEncrypted(roomId: string): Promise<string|false> {
const existing = this.encryptedRooms.get(roomId);
if (existing !== undefined) {
return existing;
}
try {
const ev = await this.getStateEvent(roomId, "m.room.encryption");
const algo = ev.algorithm as unknown;
if (typeof algo === 'string' && algo) {
this.encryptedRooms.set(roomId, algo);
return algo;
}
// Return false if missing, not a string or empty.
return false;
}
catch (ex) {
if (ex.statusCode == 404) {
this.encryptedRooms.set(roomId, false);
return false;
}
throw ex;
}
}
/**
* Upload a file to the homeserver.
* @param content The file contents
* @param opts Additional options for the upload.
* @returns A MXC URL pointing to the uploaded data.
*/
public async uploadContent(content: Buffer|string|ReadStream, opts: FileUploadOpts = {}): Promise<string> {
await this.ensureRegistered();
let buffer: Buffer;
if (typeof content === "string") {
buffer = Buffer.from(content, "utf8");
}
else if (content instanceof ReadStream) {
buffer = Buffer.from(content);
}
else {
buffer = content;
}
return this.botSdkIntent.underlyingClient.uploadContent(
buffer,
opts.type,
opts.name,
);
}
/**
* Set the visibility of a room in the homeserver's room directory.
* @param roomId The room
* @param visibility Should the room be visible
*/
public async setRoomDirectoryVisibility(roomId: string, visibility: "public"|"private") {
await this.ensureRegistered();
return this.botSdkIntent.underlyingClient.setDirectoryVisibility(roomId, visibility);
}
/**
* Set the visibility of a room in the appservice's room directory.
* This only works if you have defined the `protocol` in the registration file.
* @param roomId The room
* @param networkId The network (not protocol) that owns this room. E.g. "freenode" (for an IRC bridge)
* @param visibility Should the room be visible
*/
public async setRoomDirectoryVisibilityAppService(roomId: string, networkId: string,
visibility: "public"|"private") {
await this.ensureRegistered();
// XXX: No function for this yet.
return this.client.setRoomDirectoryVisibilityAppService(roomId, visibility, networkId);
}
/**
* Inform this Intent class of an incoming event. Various optimisations will be
* done if this is provided. For example, a /join request won't be sent out if
* it knows you've already been joined to the room. This function does nothing
* if a backing store was provided to the Intent.
* @param event The incoming event JSON
*/
public onEvent(event: {
type: string,
// eslint-disable-next-line camelcase
content: {membership: UserMembership, displayname?: string, avatar_url?: string, algorithm?: string},
// eslint-disable-next-line camelcase
state_key: unknown,
// eslint-disable-next-line camelcase
room_id: string
}) {
if (event.state_key === undefined) {
// We MUST operate on state events exclusively
return;
}
// Invalidate the state cache if anything changes in the state.
this._requestCaches.roomstate.invalidate(event.room_id);
if (!this._membershipStates || !this._powerLevels) {
return;
}
if (event.type === "m.room.member" &&
event.state_key === this.userId &&
event.content.membership) {
const profile: MatrixProfileInfo = {};
if (event.content.displayname) {
profile.displayname = event.content.displayname;
}
if (event.content.avatar_url) {
profile.avatar_url = event.content.avatar_url;
}
this._membershipStates[event.room_id] = [event.content.membership, profile];
}
else if (event.type === "m.room.power_levels") {
this.opts.backingStore.setPowerLevelContent(event.room_id, event.content as unknown as PowerLevelContent);
}
else if (event.type === "m.room.encryption" && typeof event.content.algorithm === "string") {
this.encryptedRooms.set(event.room_id, event.content.algorithm);
}
}
// Guard a function which returns a promise which may reject if the user is not
// in the room. If the promise rejects, join the room and retry the function.
private async _joinGuard<T>(roomId: string, promiseFn: () => Promise<T>): Promise<T> {
try {
// await so we can handle the error
return await promiseFn();
}
catch (err) {
if (err.body?.errcode !== "M_FORBIDDEN") {
// not a guardable error
throw err;
}
await this._ensureJoined(roomId, true);
return promiseFn();
}
}
private async _ensureJoined(
roomIdOrAlias: string, ignoreCache = false, viaServers?: string[], passthroughError = false
): Promise<string> {
const opts: { viaServers?: string[] } = { };
if (viaServers) {
opts.viaServers = viaServers;
}
// Resolve the alias
const roomId = await this.resolveRoom(roomIdOrAlias);
if (!ignoreCache && this.opts.backingStore.getMembership(roomId, this.userId) === "join") {
return roomId;
}
/* Logic:
if client /join:
SUCCESS
else if bot /invite client:
if client /join:
SUCCESS
else:
FAIL (client couldn't join)
else if bot /join:
if bot /invite client and client /join:
SUCCESS
else:
FAIL (bot couldn't invite)
else:
FAIL (bot can't get into the room)
*/
const deferredPromise = defer<string>();
const mark = (room: string, state: UserMembership) => {
this.opts.backingStore.setMembership(room, this.userId, state, {});
if (state === "join") {
deferredPromise.resolve(room);
}
}
const dontJoin = this.opts.dontJoin;
try {
await this.ensureRegistered();
if (dontJoin) {
deferredPromise.resolve(roomId);
return deferredPromise.promise;
}
try {
await this.botSdkIntent.underlyingClient.joinRoom(roomId, opts.viaServers);
mark(roomId, "join");
}
catch (ex) {
if (ex.body.errcode !== "M_FORBIDDEN") {
throw ex;
}
try {
// Try bot inviting client
await this.botClient.inviteUser(this.userId, roomIdOrAlias);
await this.botClient.joinRoom(roomId, opts.viaServers);
mark(roomId, "join");
}
catch (_ex) {
// Try bot joining
await this.botClient.joinRoom(roomId, opts.viaServers);
await this.botClient.inviteUser(this.userId, roomId);
await this.botSdkIntent.underlyingClient.joinRoom(roomId, opts.viaServers);
mark(roomId, "join");
}
}
}
catch (ex) {
deferredPromise.reject(passthroughError ? ex : Error("Failed to join room"));
}
return deferredPromise.promise;
}
/**
* Ensures that the client has the required power level to post the event type.
* @param roomId Required as power levels exist inside a room.
* @param eventTypes The event type to check the permissions for.
* @param isState Are we checking for state permissions or regular event permissions.
* @return If found, the power level event
*/
private async _ensureHasPowerLevelFor(roomId: string, eventType: string, isState: boolean) {
if (this.opts.dontCheckPowerLevel && eventType !== "m.room.power_levels") {
return undefined;
}
const userId = this.userId;
const plContent = this.opts.backingStore.getPowerLevelContent(roomId)
|| await this.botSdkIntent.underlyingClient.getRoomStateEvent(roomId, "m.room.power_levels", "");
const eventContent: PowerLevelContent = plContent && typeof plContent === "object" ? plContent : {};
this.opts.backingStore.setPowerLevelContent(roomId, eventContent);
// Borrowed from https://github.com/turt2live/matrix-bot-sdk/blob/master/src/MatrixClient.ts#L1147
// We're using our own version for caching.
let requiredPower: number = isState ? 50 : 0;
if (isState && typeof eventContent.state_default === "number") {
requiredPower = eventContent.state_default
}
if (!isState && typeof eventContent.users_default === "number") {
requiredPower = eventContent.users_default;
}
if (typeof eventContent.events?.[eventType] === "number") {
requiredPower = eventContent.events[eventType] as number;
}
let userPower = 0;
if (typeof eventContent.users?.[userId] === "number") {
userPower = eventContent.users[userId] as number;
}
if (requiredPower > userPower) {
const botUserId = await this.botClient.getUserId();
let botPower = 0;
if (typeof eventContent.users?.[botUserId] === "number") {
botPower = eventContent.users[botUserId] as number;
}
let requiredPowerPowerLevels = 50;
if (typeof eventContent.state_default === "number") {
requiredPowerPowerLevels = eventContent.state_default
}
if (typeof eventContent.events?.[eventType] === "number") {
requiredPower = eventContent.events[eventType] as number;
}
if (requiredPowerPowerLevels > botPower) {
// even the bot has no power here.. give up.
throw new Error(
`Cannot ensure client has power level for event ${eventType} ` +
`: client has ${userPower} and we require ` +
`${requiredPower} and the bot doesn't have permission to ` +
`edit the client's power level.`
);
}
// TODO: This might be inefficent.
// update the client's power level first
await this.botClient.setUserPowerLevel(
userId, roomId, requiredPower
);
// tweak the level for the client to reflect the new reality
eventContent.users = {
...eventContent.users,
[userId]: requiredPower,
};
}
return eventContent;
}
private async loginForEncryptedClient() {
const userId: string = this.userId;
const res = await this.botSdkIntent.underlyingClient.doRequest(
"POST",
"/_matrix/client/r0/login",
undefined,
{
type: APPSERVICE_LOGIN_TYPE,
identifier: {
type: "m.id.user",
user: userId,
}
},
);
return {
accessToken: res.access_token as string,
deviceId: res.device_id as string,
};
}
public async ensureRegistered(forceRegister = false) {
const userId: string = this.userId;
log.debug(`Checking if user ${this.userId} is registered`);
// We want to skip if and only if all of these conditions are met.
// Calling /register twice isn't disasterous, but not calling it *at all* IS.
if (!forceRegister && this.opts.registered && !this.encryption) {
log.debug("ensureRegistered: Registered, and not encrypted");
return "registered=true";
}
let registerRes;
if (forceRegister || !this.opts.registered) {
try {
registerRes = await this.botSdkIntent.ensureRegistered();
this.opts.registered = true;
}
catch (err) {
if (err.body?.errcode === "M_EXCLUSIVE" && this.botClient === this.botSdkIntent.underlyingClient) {
// Registering the bot will leave it
this.opts.registered = true;
}
else if (err.body?.errcode === "M_USER_IN_USE") {
this.opts.registered = true;
}
else {
throw err;
}
}
}
if (!this.encryption) {
log.debug("ensureRegistered: Registered, and not encrypted");
// We don't care about encryption, or the encryption is ready.
return registerRes;
}
if (this.readyPromise) {
log.debug("ensureRegistered: ready promise ongoing");
try {
// Should fall through and find the session.
await this.readyPromise;
}
catch (ex) {
log.debug("ensureRegistered: failed to ready", ex);
// Failed to ready up - fall through and try again.
}
}
// Encryption enabled, check if we have a session.
let session = await this.encryption.sessionPromise;
if (session) {
log.debug("ensureRegistered: Existing enc session, reusing");
// We have existing credentials, set them on the client and run away.
// We need to overwrite the access token here.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(this.botSdkIntent.underlyingClient as any).accessToken = session.accessToken;
this.botSdkIntent.underlyingClient.storageProvider.setSyncToken(session.syncToken);
}
else {
this.readyPromise = (async () => {
log.debug("ensureRegistered: Attempting encrypted login");
// Login as the user
const result = await this.loginForEncryptedClient();
session = {
userId,
...result,
syncToken: null,
};
if (this.encryption) {
this.encryption.sessionPromise = Promise.resolve(session);
}
await this.encryption?.sessionCreatedCallback(session);
})();
await this.readyPromise;
}
return undefined;
}
} | the_stack |
import { empty } from '@formkit/utils'
import {
parseRules,
defaultHints,
createValidationPlugin,
FormKitValidationRule,
} from '../src/validation'
import { createNode } from '@formkit/core'
import { jest } from '@jest/globals'
const defaultValidation = {
...defaultHints,
timer: 0,
queued: true,
state: null,
deps: new Map(),
}
const nextTick = () => new Promise<void>((r) => setTimeout(r, 0))
describe('validation rule parsing', () => {
it('can parse a single string rule', () => {
const required = () => true
expect(parseRules('required', { required })).toEqual([
{
...defaultValidation,
args: [],
rule: required,
name: 'required',
},
])
})
it('can parse a multiple string rules', () => {
const required = () => true
const flavor = () => true
expect(parseRules('required|flavor', { required, flavor })).toEqual([
{
...defaultValidation,
rule: required,
name: 'required',
args: [],
},
{
...defaultValidation,
rule: flavor,
name: 'flavor',
args: [],
},
])
})
it('can parse string arguments', () => {
const flavor = () => true
const before = () => true
const flavorResult = {
...defaultValidation,
rule: flavor,
name: 'flavor',
args: ['apple', 'banana'],
}
expect(parseRules('flavor:apple,banana', { flavor })).toEqual([
flavorResult,
])
expect(
parseRules('before:10/15/2020|flavor:apple,banana', { flavor, before })
).toEqual([
{
...defaultValidation,
rule: before,
name: 'before',
args: ['10/15/2020'],
},
flavorResult,
])
})
it('can use the “force” validator hint', () => {
const flavor = () => true
expect(parseRules('*flavor:apple|flavor', { flavor })).toEqual([
{
...defaultValidation,
rule: flavor,
name: 'flavor',
args: ['apple'],
force: true,
},
{
...defaultValidation,
rule: flavor,
name: 'flavor',
args: [],
},
])
})
it('can use the “empty” validator hint', () => {
const pizza = () => true
expect(parseRules('+pizza:cheese|pizza', { pizza })).toEqual([
{
...defaultValidation,
rule: pizza,
name: 'pizza',
args: ['cheese'],
force: false,
skipEmpty: false,
},
{
...defaultValidation,
rule: pizza,
name: 'pizza',
args: [],
skipEmpty: true,
},
])
})
it('leaves out validations that do not have matching rules', () => {
const all9s = () => true
expect(parseRules('required|all9s', { all9s })).toEqual([
{
...defaultValidation,
rule: all9s,
name: 'all9s',
args: [],
},
])
})
it('preserves hints provided by the validation rule', () => {
const required = () => true
required.skipEmpty = false
expect(parseRules('required', { required })).toEqual([
{
...defaultValidation,
rule: required,
args: [],
name: 'required',
skipEmpty: false,
},
])
})
it('it uses inline hints to override function hints', () => {
const required = () => true
required.force = false
expect(parseRules('*required', { required })).toEqual([
{
...defaultValidation,
rule: required,
name: 'required',
args: [],
force: true,
},
])
})
it('can parse multiple hints, in either direction', () => {
const required = () => true
required.force = false
const result = [
{
...defaultValidation,
rule: required,
name: 'required',
args: [],
force: true,
blocking: false,
},
]
expect(parseRules('*?required', { required })).toEqual(result)
expect(parseRules('?*required', { required })).toEqual(result)
})
it('can parse debounce hints in the middle', () => {
const required = () => true
required.force = false
expect(parseRules('*(200)?required', { required })).toEqual([
{
...defaultValidation,
rule: required,
name: 'required',
args: [],
debounce: 200,
blocking: false,
force: true,
},
])
})
it('can parse debounce hints at the start', () => {
const required = () => true
required.force = false
expect(parseRules('(5)*?required', { required })).toEqual([
{
...defaultValidation,
rule: required,
name: 'required',
args: [],
debounce: 5,
blocking: false,
force: true,
},
])
})
it('can parse debounce hints at the end', () => {
const required = () => true
required.force = false
expect(parseRules('*?(999)required', { required })).toEqual([
{
...defaultValidation,
rule: required,
name: 'required',
args: [],
debounce: 999,
blocking: false,
force: true,
},
])
})
it('can parse solo debounce hints', () => {
const required = () => true
const free = () => true
required.force = false
expect(parseRules('free|(2000)required', { required, free })).toEqual([
{
...defaultValidation,
args: [],
rule: free,
name: 'free',
},
{
...defaultValidation,
args: [],
rule: required,
name: 'required',
debounce: 2000,
},
])
})
it('can parse rules in array format', () => {
const required = () => true
const party = () => true
expect(
parseRules([['required'], ['*party', 'arg1', 'arg2']], {
required,
party,
})
).toEqual([
{
...defaultValidation,
rule: required,
name: 'required',
args: [],
},
{
...defaultValidation,
rule: party,
name: 'party',
args: ['arg1', 'arg2'],
force: true,
},
])
})
it('preserves types when using array syntax', () => {
const matches = () => true
const parsed = parseRules([['matches', /^S.*$/]], { matches })
expect(parsed[0].args[0]).toBeInstanceOf(RegExp)
})
it('parses hints in array syntax', () => {
const matches = () => true
const parsed = parseRules([['*matches', /^S.*$/]], { matches })
expect(parsed[0].force).toBeTruthy()
})
})
describe('validation rule sequencing', () => {
const required: FormKitValidationRule = ({ value }) => !empty(value)
required.skipEmpty = false
const validationPlugin = createValidationPlugin({
required,
length: ({ value }, length) => ('' + value).length >= parseInt(length),
contains: ({ value }, substr) => ('' + value).includes(substr),
exists: ({ value }) => {
return new Promise((resolve) =>
setTimeout(() => {
resolve(['bar', 'foobar'].includes(String(value)))
}, 100)
)
},
confirm: (node, address) => {
return node.value === node.at(address)!.value
},
})
it('runs non-async non-debounced rules synchronously with bailing', async () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'required|length:5|contains:bar',
},
value: '',
})
expect(node.store).toHaveProperty('rule_required')
// Should not exist because of empty
expect(node.store).not.toHaveProperty('rule_length')
node.input('foo', false)
await nextTick()
// Should no longer fail on required, but on length
expect(node.store).not.toHaveProperty('rule_required')
expect(node.store).toHaveProperty('rule_length')
expect(node.store).not.toHaveProperty('rule_contains')
node.input('foo foo', false)
await nextTick()
expect(node.store).not.toHaveProperty('rule_required')
expect(node.store).not.toHaveProperty('rule_length')
expect(node.store).toHaveProperty('rule_contains')
node.input('foobar', false)
await nextTick()
expect(node.store).not.toHaveProperty('rule_required')
expect(node.store).not.toHaveProperty('rule_length')
expect(node.store).not.toHaveProperty('rule_contains')
})
it('runs rules serially after debounce', async () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'required|(200)length:5|*contains:bar',
},
value: '',
})
await nextTick()
expect(node.store).toHaveProperty('rule_required')
expect(node.store).not.toHaveProperty('rule_length')
node.input('foo', false)
await nextTick()
expect(node.store).not.toHaveProperty('rule_required')
expect(node.store).not.toHaveProperty('rule_length')
await new Promise((r) => setTimeout(r, 205))
expect(node.store).toHaveProperty('rule_length')
expect(node.store).toHaveProperty('rule_contains')
})
it('awaits async rule resolution before continuing and removes messages immediately', async () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'required|length:5|exists|*contains:bar',
},
value: 'abcdef',
})
expect(node.store).not.toHaveProperty('rule_exists')
expect(node.store).not.toHaveProperty('rule_contains')
await new Promise((r) => setTimeout(r, 105))
expect(node.store).toHaveProperty('rule_exists')
expect(node.store).toHaveProperty('rule_contains')
node.input('foobars', false)
// These messages should be removed because they have been tagged with
// 'removeImmediately' since they come on or after an async rule
await nextTick()
expect(node.store).not.toHaveProperty('rule_exists')
expect(node.store).not.toHaveProperty('rule_contains')
})
it('cancels out mid-stream validations, never adding them', async () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'required|exists',
},
value: 'abcdef',
})
await nextTick()
node.input('foo', false)
await nextTick()
expect(node.store).not.toHaveProperty('rule_exists')
node.input('foobar', false)
await new Promise((r) => setTimeout(r, 110))
expect(node.store).not.toHaveProperty('rule_exists')
})
it('sets a validating message during validation runs', async () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'required|length:5|exists|*contains:bar',
},
value: 'abcdef',
})
// Initialize a validating counter
node.ledger.count(
'validating',
(m) => m.key === 'validating' && m.type === 'state'
)
expect(node.store).toHaveProperty('validating')
await node.ledger.settled('validating')
expect(node.store).not.toHaveProperty('validating')
node.input('foobar', false)
await nextTick()
expect(node.store).toHaveProperty('validating')
})
it('can run arbitrary validation rules', async () => {
const node = createNode({
plugins: [validationPlugin],
props: {
label: 'ABC Field',
validation: 'abc',
validationRules: {
abc: ({ value }) => value === 'abc',
},
validationMessages: {
abc: ({ name }) => `${name} should be 'abc'`,
},
},
value: 'abcdef',
})
expect(node.store.rule_abc.value).toBe("ABC Field should be 'abc'")
})
it('can replace a validation message with a string', () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'required',
validationMessages: {
required: 'Fill this out!',
},
},
value: '',
})
expect(node.store.rule_required.value).toBe('Fill this out!')
})
it('can re-run a rule after it has failed, passed, and then failed again', async () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'required',
},
value: 'abcdef',
})
expect(node.store).not.toHaveProperty('rule_required')
node.input('', false)
await nextTick()
expect(node.store).toHaveProperty('rule_required')
node.input('abc', false)
await nextTick()
expect(node.store).not.toHaveProperty('rule_required')
node.input('', false)
await nextTick()
expect(node.store).toHaveProperty('rule_required')
})
it('tracks dependencies on other inputs', async () => {
const confirm: FormKitValidationRule = jest.fn((node, address) => {
return node.value === node.at(address)!.value
})
const length: FormKitValidationRule = jest.fn(
({ value }, length) => ('' + value).length >= parseInt(length)
)
const required: FormKitValidationRule = jest.fn(({ value }) => !!value)
required.skipEmpty = false
const validation = createValidationPlugin({
confirm,
length,
required,
})
const parent = createNode({
type: 'group',
plugins: [validation],
})
const bar = createNode({ name: 'bar', value: 'def', parent })
const foo = createNode({
name: 'foo',
value: 'abc',
props: { validation: 'required|confirm:bar|length:20' },
parent,
})
expect(foo.store).not.toHaveProperty('rule_required')
expect(foo.store).toHaveProperty('rule_confirm')
expect(foo.store).not.toHaveProperty('rule_length')
expect(required).toHaveBeenCalledTimes(1)
expect(confirm).toHaveBeenCalledTimes(1)
expect(length).toHaveBeenCalledTimes(0) // Should not have been called because confirm failed.
bar.input('abc', false)
await nextTick()
expect(foo.store).not.toHaveProperty('rule_required')
expect(foo.store).not.toHaveProperty('rule_confirm')
expect(foo.store).toHaveProperty('rule_length')
expect(required).toHaveBeenCalledTimes(2) // Should be called again, because we dont do equality comparisons (after >= beta.7)
expect(confirm).toHaveBeenCalledTimes(2)
expect(length).toHaveBeenCalledTimes(1) // have been should be triggered because it's state was null ie "unknown"
foo.input('', false)
await nextTick()
expect(foo.store).toHaveProperty('rule_required')
expect(foo.store).not.toHaveProperty('rule_confirm')
expect(foo.store).not.toHaveProperty('rule_length')
})
it('removes validation messages that come after failing rules', async () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'required|exists',
},
value: 'abcdef',
})
node.input('foo', false)
// TODO: this test failed intermittently after implementing class override system
await new Promise((r) => setTimeout(r, 200))
expect(node.store).toHaveProperty('rule_exists') // value is not foobar
node.input('', false)
await nextTick()
expect(node.store).not.toHaveProperty('rule_exists')
})
it('shows forced validation messages even after a failing rule', async () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'length:7|*contains:hij',
},
value: 'abcdef',
})
expect(node.store).toHaveProperty('rule_length')
expect(node.store).toHaveProperty('rule_contains')
node.input('abcdefhij', false)
await nextTick()
expect(node.store).not.toHaveProperty('rule_length')
expect(node.store).not.toHaveProperty('rule_contains')
})
it('removes old validations when validation prop changes', () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'length:7',
},
value: 'abcdef',
})
expect(node.store).toHaveProperty('rule_length')
node.props.validation = 'contains:bar'
expect(node.store).not.toHaveProperty('rule_length')
expect(node.store).toHaveProperty('rule_contains')
})
it('fails multiple times with long running validation rules', async () => {
const node = createNode({
plugins: [validationPlugin],
props: {
validation: 'required|length:5|longrun',
validationRules: {
longrun(node) {
return new Promise<boolean>((r) => {
setTimeout(() => {
if (node.value !== 'barbar') return r(false)
r(true)
}, 100)
})
},
},
},
value: 'foo',
})
expect(node.store).toHaveProperty('rule_length')
node.input('foobar', false)
await nextTick()
expect(node.store).toHaveProperty('validating')
await new Promise((r) => setTimeout(r, 120))
expect(node.store).not.toHaveProperty('validating')
expect(node.store).toHaveProperty('rule_longrun')
node.input('foobars', false)
await nextTick()
expect(node.store).toHaveProperty('validating')
await new Promise((r) => setTimeout(r, 120))
expect(node.store).not.toHaveProperty('validating')
expect(node.store).toHaveProperty('rule_longrun')
node.input('foobarss', false)
await nextTick()
node.input('foo', false)
await new Promise((r) => setTimeout(r, 200))
expect(node.store).toHaveProperty('rule_length')
expect(node.store).not.toHaveProperty('rule_longrun')
})
it('runs skipEmpty rules without preceding rules once the field has a value', async () => {
const node = createNode({
value: '',
plugins: [validationPlugin],
props: {
validation: 'contains:foo',
validationVisibility: 'live',
},
})
expect(node.store).not.toHaveProperty('rule_contains')
node.input('baba', false)
await new Promise((r) => setTimeout(r, 25))
expect(node.store).toHaveProperty('rule_contains')
})
}) | the_stack |
import { Processor } from 'windicss/lib';
import { colorObject } from 'windicss/types/interfaces';
import { generateCompletions } from '../src/utils/completions';
const processor = new Processor();
const completions = generateCompletions(processor, processor.theme('colors') as colorObject, true, '');
const attrs = completions.attr;
function include(keys: string[], values: string[]) {
values.map(i => expect(keys).toContain(i));
}
function match(key: string, statics: string[], colors?: string[]) {
include(attrs.static[key], statics);
colors && include(attrs.color[key].map(i => i.label), colors);
}
it('generate font completions', () => {
match('font', [
'sans', 'serif', 'mono',
'italic', 'not-italic',
'thin', 'extralight', 'light',
'antialiased', 'subpixel-antialiased',
'normal-nums', 'ordinal', 'slashed-zero',
'tracking-tighter', 'tracking-tight',
'leading-none', 'leading-tight',
]);
});
it('generate text completions', () => {
match('text', [
'xs',
'left',
'baseline', 'top', 'middle',
'opacity-40', 'opacity-60',
'underline', 'line-through',
'underline-opacity-50', 'underline-auto', 'underline-2', 'underline-offset-auto',
'tab', 'tab-0', 'tab-2', 'tab-4',
'indent', 'indent-xs', 'indent-sm', 'indent-md',
'uppercase', 'lowercase', 'capitalize',
'stroke', 'stroke-none', 'stroke-sm',
'shadow', 'shadow-sm', 'shadow-md',
'truncate', 'overflow-ellipsis',
'space-normal', 'space-nowrap', 'space-pre',
'break-normal', 'break-words',
'write-normal', 'write-orient-mixed',
'hyphens-none', 'hyphens-manual',
'placeholder-opacity-50',
], [
'blue-500', 'red-500',
'underline-green-500', 'underline-gray-500',
'stroke-transparent', 'stroke-blue-500',
'placeholder-blue-500', 'placeholder-gray-700',
]);
});
it('genreate underline utilities', () => {
match('underline', [
'~', 'line-through', 'none',
'solid', 'double', 'dotted', 'dashed',
'opacity-50',
'auto', '0', '2', '4', '8',
'offset-auto', 'offset-1', 'offset-2',
], [
'green-500', 'current',
]);
});
it('generate list utilities', () => {
match('list', [
'none', 'disc', 'decimal',
'inside', 'outside',
]);
});
it('generate bg utilities', () => {
match('bg', [
'fixed', 'local', 'scroll',
'bottom', 'center', 'left',
'opacity-50', 'opacity-60',
'repeat', 'no-repeat', 'repeat-x',
'auto', 'cover', 'contain',
'clip-border', 'clip-padding', 'clip-content',
'origin-border', 'origin-padding', 'origin-content',
'blend-normal', 'blend-overlay', 'blend-darken',
'none',
], [
'green-500', 'current',
]);
});
it('generate gradient utilities', () => {
match('gradient', [
'none', 'to-t', 'to-r', 'to-br',
], [
'from-green-500', 'from-current',
'via-red-500',
'to-pink-500',
]);
});
it('generate border utilities', () => {
match('border', [
'~', '0', '2', '4', 't-0', 't-0', 'l-2', 'r-2',
'rounded-none', 'rounded-sm', 'rounded-b-sm',
'solid', 'dashed', 'dotted', 'double', 'none',
'collapse', 'separate',
'opacity-50', 'opacity-60',
], [
'gray-500', 'yellow-500',
]);
});
it('generate divide utilities', () => {
match('divide', [
'y', 'x', 'y-reverse', 'x-reverse', 'y-2',
'solid', 'dashed', 'dotted', 'double', 'none',
'opacity-50', 'opacity-60',
], [
'gray-500', 'yellow-500',
]);
});
it('generate ring utilities', () => {
match('ring', [
'~', 'inset', '0', '1', '2',
'opacity-50', 'opacity-60',
'offset-4', 'offset-8',
], [
'gray-500', 'yellow-500',
'offset-gray-200', 'offset-gray-400',
]);
});
it('generate icon utilities', () => {
match('icon', [
'stroke-0', 'stroke-1', 'stroke-2',
'stroke-dash-1', 'stroke-dash-2',
'stroke-offset-0', 'stroke-offset-2',
'stroke-cap-auto', 'stroke-cap-square',
'stroke-join-auto',
], [
'fill-gray-500', 'fill-yellow-500',
'stroke-current', 'stroke-gray-400',
]);
});
it('generate container', () => {
match('container', [ '~' ]);
});
it('generate padding utilities', () => {
match('p', [
'0', 'px', '1', '2', '4',
'y-0', 'y-px', 'y-1', 'y-2', 'y-4',
'x-0', 'x-px', 'x-1', 'x-2', 'x-4',
't-0', 't-px', 't-1', 't-2', 't-4',
'b-0', 'b-px', 'b-1', 'b-2', 'b-4',
'r-0', 'r-px', 'r-1', 'r-2', 'r-4',
]);
});
it('generate margin utilities', () => {
match('m', [
'0', 'px', '1', '2', '4',
'y-0', 'y-px', 'y-1', 'y-2', 'y-4',
'x-0', 'x-px', 'x-1', 'x-2', 'x-4',
't-0', 't-px', 't-1', 't-2', 't-4',
'b-0', 'b-px', 'b-1', 'b-2', 'b-4',
'r-0', 'r-px', 'r-1', 'r-2', 'r-4',
'-t-px', '-t-2',
]);
});
it('generate space utilities', () => {
match('space', [
'x-4', '-x-4',
'x-reverse',
'y-2', '-y-2',
'y-reverse',
]);
});
it('generate width utilities', () => {
match('w', [
'0', 'auto', 'px', 'full', 'sm', 'md', 'screen-sm', 'min-content', 'max-content',
'min-0', 'min-px', 'min-full', 'min-sm', 'min-md', 'min-screen-sm',
'max-0', 'max-px', 'max-full', 'max-sm', 'max-md', 'max-screen-sm',
]);
});
it('generate height utilities', () => {
match('h', [
'0', 'auto', 'px', 'full', 'sm', 'md', 'screen-sm', 'min-content', 'max-content',
'min-0', 'min-px', 'min-full', 'min-sm', 'min-md', 'min-screen-sm',
'max-0', 'max-px', 'max-full', 'max-sm', 'max-md', 'max-screen-sm',
]);
});
it('generate flex utilities', () => {
match('flex', [
'~', 'inline',
'row', 'row-reverse', 'col', 'col-reverse',
'wrap', 'wrap-reverse', 'nowrap',
'1', 'auto', 'initial', 'none',
'grow', 'grow-0',
'shrink', 'shrink-0',
]);
});
it('generate grid utilities', () => {
match('grid', [
'~', 'inline',
'cols-1', 'cols-3', 'cols-none',
'col-auto', 'col-span-2',
'row-auto', 'row-span-2',
'rows-1', 'rows-3', 'rows-none',
'flow-row', 'flow-col', 'flow-row-dense', 'flow-col-dense',
'auto-cols-auto', 'auto-cols-min',
'auto-rows-auto', 'auto-rows-min',
'gap-2', 'gap-x-4', 'gap-y-2',
]);
});
it('generate table utilities', () => {
match('table', [
'~', 'inline', 'caption', 'cell', 'column', 'column-group', 'footer-group', 'header-group', 'row-group', 'row',
'auto', 'fixed',
'caption-top', 'caption-bottom',
'empty-cells-visible', 'empty-cells-hidden',
]);
});
it('generate order utilities', () => {
match('order', [
'1', '2', 'first', 'last',
]);
});
it('generate align utilities', () => {
match('align', [
// 'center', 'start', 'end', 'around', 'evenly',
'content-center', 'content-start', 'content-end', 'content-around',
'items-start', 'items-end', 'items-center',
'self-auto', 'self-start', 'self-end',
]);
});
it('generate justify utilities', () => {
match('justify', [
'center', 'start', 'end', 'around', 'evenly',
// 'content-center', 'content-start', 'content-end', 'content-around',
'items-start', 'items-end', 'items-center',
'self-auto', 'self-start', 'self-end',
]);
});
it('generate place utilities', () => {
match('place', [
// 'center', 'start', 'end', 'around', 'evenly',
'content-center', 'content-start', 'content-end', 'content-around',
'items-start', 'items-end', 'items-center',
'self-auto', 'self-start', 'self-end',
]);
});
it('generate display utilities', () => {
match('display', [
'inline', 'flow-root', 'contents', 'list-item', 'block', 'inline-block',
'visible', 'invisible',
'backface-visible', 'backface-hidden',
]);
});
it('generate pos utilities', () => {
match('pos', [
'static', 'fixed', 'absolute', 'relative', 'sticky',
'inset-1', '-inset-1', '-inset-x-1', '-inset-y-2',
'top-0', 'left-0', 'bottom-0', 'right-0',
'float-right', 'float-left', 'float-none',
'clear-left', 'clear-right', 'clear-both', 'clear-none',
'isolate', 'isolation-auto',
]);
});
it('generate box utilities', () => {
match('box', [
'decoration-slice', 'decoration-clone',
'border', 'content',
]);
});
it('generate caret utilities', () => {
match('caret', [
'opacity-0', 'opacity-50',
], [
'gray-500', 'green-500',
]);
});
it('generate isolation utilities', () => {
match('isolation', [
'isolate', 'auto',
]);
});
it('generate object utilities', () => {
match('object', [
'contain', 'cover', 'fill', 'none', 'scale-down',
'bottom', 'center', 'left', 'left-bottom',
]);
});
it('generate overflow utilities', () => {
match('overflow', [
'auto', 'hidden', 'visible', 'scroll',
'x-auto', 'x-hidden', 'x-visible',
'y-auto', 'y-hidden', 'y-visible',
]);
});
it('generate overscroll utilities', () => {
match('overscroll', [
'auto', 'contain', 'none',
'x-auto', 'x-contain', 'x-none',
'y-auto', 'y-contain', 'y-none',
]);
});
it('generate zIndex utilities', () => {
match('z', [
'auto', '0', '10', '20', '50',
]);
});
it('generate shadow utilities', () => {
match('shadow', [
'sm', '~', 'md', 'lg', 'xl', '2xl', 'inner', 'none',
], [
'gray-200', 'green-500',
]);
});
it('generate opacity utilities', () => {
match('opacity', [
'0', '5', '10', '20',
]);
});
it('generate blend utilities', () => {
match('blend', [
'normal', 'multiply', 'screen', 'overlay', 'darken',
]);
});
it('generate filter utilities', () => {
match('filter', [
'~', 'none',
'blur-0', 'blur-sm', 'blur', 'blur-md',
'brightness-0', 'brightness-50', 'brightness-75',
'contrast-0', 'contrast-50', 'contrast-75',
'drop-shadow-sm', 'drop-shadow', 'drop-shadow-md',
'grayscale-0', 'grayscale',
'-hue-rotate-180', '-hue-rotate-90', 'hue-rotate-90', 'hue-rotate-180',
'invert-0', 'invert',
'saturate-0', 'saturate-50', 'saturate-100',
'sepia-0', 'sepia',
]);
});
it('generate backdrop utilities', () => {
match('backdrop', [
'~', 'none',
'blur-0', 'blur-sm', 'blur', 'blur-md',
'brightness-0', 'brightness-50', 'brightness-75',
'contrast-0', 'contrast-50', 'contrast-75',
'grayscale-0', 'grayscale',
'-hue-rotate-180', '-hue-rotate-90', 'hue-rotate-90', 'hue-rotate-180',
'invert-0', 'invert',
'opacity-0', 'opacity-50',
'saturate-0', 'saturate-50', 'saturate-100',
'sepia-0', 'sepia',
]);
});
it('generate transition utilities', () => {
match('transition', [
'~', 'none', 'all', 'colors', 'opacity', 'shadow', 'transform',
'duration-75', 'duration-100', 'duration-150',
'ease-linear', 'ease-in', 'ease-out', 'ease-in-out',
'delay-75', 'delay-100', 'delay-150',
]);
});
it('generate animation utilities', () => {
match('animate', [
'none', 'spin', 'ping', 'pulse', 'bounce',
]);
});
it('generate transform utilities', () => {
match('transform', [
'~', 'gpu', 'none',
'preserve-flat', 'preserve-3d',
'perspect-lg', 'perspect-none',
'perspect-origin-center', 'perspect-origin-top',
'origin-center', 'origin-top',
'scale-0', 'scale-50', 'scale-75',
'scale-x-50', 'scale-y-50', 'scale-z-75',
'rotate-45', '-rotate-45',
'rotate-x-45', 'rotate-y-45', 'rotate-z-90',
'translate-x-2', '-translate-x-4', 'translate-y-40', 'translate-z-12',
'skew-x-2', '-skew-x-6', 'skew-y-2', '-skew-y-2',
]);
});
it('generate appearance', () => {
match('appearance', [
'none',
]);
});
it('generate cursor', () => {
match('cursor', [
'auto', 'default', 'pointer', 'wait', 'text', 'move', 'help', 'not-allowed',
]);
});
it('generate pointer events', () => {
match('pointer', [
'none', 'auto',
]);
});
it('generate resize utilities', () => {
match('resize', [
'~', 'x', 'y', 'none',
]);
});
it('generate select utilities', () => {
match('select', [
'none', 'text', 'all', 'auto',
]);
});
it('generate sr utilities', () => {
match('sr', [
'only', 'not-only',
]);
}); | the_stack |
import { injectable } from "inversify";
import { Point } from "../../utils/geometry";
import { Routable, isRoutable, canEditRouting, SRoutingHandle } from './model';
import { Action } from "../../base/actions/action";
import { Command, CommandExecutionContext, CommandResult } from "../../base/commands/command";
import { SModelElement, SModelRoot, SParentElement, SModelIndex } from '../../base/model/smodel';
import { Animation } from '../../base/animations/animation';
export function createRoutingHandle(kind: 'junction' | 'line', parentId: string, index: number): SRoutingHandle {
const handle = new SRoutingHandle();
handle.type = kind === 'junction' ? 'routing-point' : 'volatile-routing-point';
handle.kind = kind;
handle.pointIndex = index;
return handle;
}
export function createRoutingHandles(editTarget: SParentElement & Routable): void {
const rpCount = editTarget.routingPoints.length;
const targetId = editTarget.id;
editTarget.add(createRoutingHandle('line', targetId, -1));
for (let i = 0; i < rpCount; i++) {
editTarget.add(createRoutingHandle('junction', targetId, i));
editTarget.add(createRoutingHandle('line', targetId, i));
}
}
export class SwitchEditModeAction implements Action {
kind = SwitchEditModeCommand.KIND;
constructor(public readonly elementsToActivate: string[] = [],
public readonly elementsToDeactivate: string[] = []) {
}
}
@injectable()
export class SwitchEditModeCommand extends Command {
static KIND: string = "switchEditMode";
protected elementsToActivate: SModelElement[] = [];
protected elementsToDeactivate: SModelElement[] = [];
protected handlesToRemove: { handle: SRoutingHandle, parent: SParentElement & Routable, point?: Point }[] = [];
constructor(public action: SwitchEditModeAction) {
super();
}
execute(context: CommandExecutionContext): SModelRoot {
const index = context.root.index;
this.action.elementsToActivate.forEach(id => {
const element = index.getById(id);
if (element !== undefined )
this.elementsToActivate.push(element);
});
this.action.elementsToDeactivate.forEach(id => {
const element = index.getById(id);
if (element !== undefined)
this.elementsToDeactivate.push(element);
if (element instanceof SRoutingHandle && isRoutable(element.parent)) {
const parent = element.parent;
if (this.shouldRemoveHandle(element, parent)) {
this.handlesToRemove.push({ handle: element, parent });
this.elementsToDeactivate.push(parent);
this.elementsToActivate.push(parent);
}
}
});
return this.doExecute(context);
}
protected doExecute(context: CommandExecutionContext): SModelRoot {
this.handlesToRemove.forEach(entry => {
entry.point = entry.parent.routingPoints.splice(entry.handle.pointIndex, 1)[0];
});
this.elementsToDeactivate.forEach(element => {
if (isRoutable(element) && element instanceof SParentElement)
element.removeAll(child => child instanceof SRoutingHandle);
else if (element instanceof SRoutingHandle)
element.editMode = false;
});
this.elementsToActivate.forEach(element => {
if (canEditRouting(element) && element instanceof SParentElement)
createRoutingHandles(element);
else if (element instanceof SRoutingHandle)
element.editMode = true;
});
return context.root;
}
protected shouldRemoveHandle(handle: SRoutingHandle, parent: Routable): boolean {
if (handle.kind === 'junction') {
const route = parent.route();
return route.find(rp => rp.pointIndex === handle.pointIndex) === undefined;
}
return false;
}
undo(context: CommandExecutionContext): CommandResult {
this.handlesToRemove.forEach(entry => {
if (entry.point !== undefined)
entry.parent.routingPoints.splice(entry.handle.pointIndex, 0, entry.point);
});
this.elementsToActivate.forEach(element => {
if (isRoutable(element) && element instanceof SParentElement)
element.removeAll(child => child instanceof SRoutingHandle);
else if (element instanceof SRoutingHandle)
element.editMode = false;
});
this.elementsToDeactivate.forEach(element => {
if (canEditRouting(element) && element instanceof SParentElement)
createRoutingHandles(element);
else if (element instanceof SRoutingHandle)
element.editMode = true;
});
return context.root;
}
redo(context: CommandExecutionContext): CommandResult {
return this.doExecute(context);
}
}
export interface HandleMove {
elementId: string
fromPosition?: Point
toPosition: Point
}
export interface ResolvedHandleMove {
elementId: string
element: SRoutingHandle
parent: SParentElement
fromPosition?: Point
toPosition: Point
}
export class MoveRoutingHandleAction implements Action {
kind: string = MoveRoutingHandleCommand.KIND;
constructor(public readonly moves: HandleMove[],
public readonly animate: boolean = true) {
}
}
@injectable()
export class MoveRoutingHandleCommand extends Command {
static KIND: string = 'moveHandle';
resolvedMoves: Map<string, ResolvedHandleMove> = new Map;
originalRoutingPoints: Map<string, Point[]> = new Map;
constructor(protected action: MoveRoutingHandleAction) {
super();
}
execute(context: CommandExecutionContext) {
const model = context.root;
this.action.moves.forEach(
move => {
const resolvedMove = this.resolve(move, model.index);
if (resolvedMove !== undefined) {
this.resolvedMoves.set(resolvedMove.elementId, resolvedMove);
const parent = resolvedMove.parent;
if (isRoutable(parent))
this.originalRoutingPoints.set(parent.id, parent.routingPoints.slice());
}
}
);
if (this.action.animate) {
return new MoveHandlesAnimation(model, this.resolvedMoves, this.originalRoutingPoints, context).start();
} else {
return this.doMove(context);
}
}
protected resolve(move: HandleMove, index: SModelIndex<SModelElement>): ResolvedHandleMove | undefined {
const element = index.getById(move.elementId);
if (element instanceof SRoutingHandle) {
return {
elementId: move.elementId,
element: element,
parent: element.parent,
fromPosition: move.fromPosition,
toPosition: move.toPosition
};
}
return undefined;
}
protected doMove(context: CommandExecutionContext): SModelRoot {
this.resolvedMoves.forEach(res => {
const handle = res.element;
const parent = res.parent;
if (isRoutable(parent)) {
const points = parent.routingPoints;
let index = handle.pointIndex;
if (handle.kind === 'line') {
// Upgrade to a proper routing point
handle.kind = 'junction';
handle.type = 'routing-point';
points.splice(index + 1, 0, res.fromPosition || points[Math.max(index, 0)]);
parent.children.forEach(child => {
if (child instanceof SRoutingHandle && (child === handle || child.pointIndex > index))
child.pointIndex++;
});
parent.add(createRoutingHandle('line', parent.id, index));
parent.add(createRoutingHandle('line', parent.id, index + 1));
index++;
}
if (index >= 0 && index < points.length) {
points[index] = res.toPosition;
}
}
});
return context.root;
}
undo(context: CommandExecutionContext): CommandResult {
if (this.action.animate) {
return new MoveHandlesAnimation(context.root, this.resolvedMoves, this.originalRoutingPoints, context, true).start();
} else {
this.resolvedMoves.forEach(res => {
const parent = res.parent;
const points = this.originalRoutingPoints.get(parent.id);
if (points !== undefined && isRoutable(parent)) {
parent.routingPoints = points;
parent.removeAll(e => e instanceof SRoutingHandle);
createRoutingHandles(parent);
}
});
return context.root;
}
}
redo(context: CommandExecutionContext): CommandResult {
if (this.action.animate) {
return new MoveHandlesAnimation(context.root, this.resolvedMoves, this.originalRoutingPoints, context, false).start();
} else {
return this.doMove(context);
}
}
}
export class MoveHandlesAnimation extends Animation {
constructor(protected model: SModelRoot,
public handleMoves: Map<string, ResolvedHandleMove>,
public originalRoutingPoints: Map<string, Point[]>,
context: CommandExecutionContext,
protected reverse: boolean = false) {
super(context);
}
tween(t: number) {
this.handleMoves.forEach(handleMove => {
const parent = handleMove.parent;
if (isRoutable(parent) && handleMove.fromPosition !== undefined) {
if (this.reverse && t === 1) {
const revPoints = this.originalRoutingPoints.get(parent.id);
if (revPoints !== undefined) {
parent.routingPoints = revPoints;
parent.removeAll(e => e instanceof SRoutingHandle);
createRoutingHandles(parent);
return;
}
}
const points = parent.routingPoints;
const index = handleMove.element.pointIndex;
if (index >= 0 && index < points.length) {
if (this.reverse) {
points[index] = {
x: (1 - t) * handleMove.toPosition.x + t * handleMove.fromPosition.x,
y: (1 - t) * handleMove.toPosition.y + t * handleMove.fromPosition.y
};
} else {
points[index] = {
x: (1 - t) * handleMove.fromPosition.x + t * handleMove.toPosition.x,
y: (1 - t) * handleMove.fromPosition.y + t * handleMove.toPosition.y
};
}
}
}
});
return this.model;
}
} | the_stack |
import {PubSub} from '@google-cloud/pubsub';
import {assert} from 'chai';
import {describe, it, before, after} from 'mocha';
import {execSync, commandFor} from './common';
import * as uuid from 'uuid';
describe('subscriptions', () => {
const projectId = process.env.GCLOUD_PROJECT;
const pubsub = new PubSub({projectId});
const runId = uuid.v4();
const topicNameOne = `topic1-${runId}`;
const topicNameTwo = `topic2-${runId}`;
const topicNameThree = `topic3-${runId}`;
const subscriptionNameOne = `sub1-${runId}`;
const subscriptionNameTwo = `sub2-${runId}`;
const subscriptionNameFour = `sub4-${runId}`;
const subscriptionNameFive = `sub5-${runId}`;
const subscriptionNameSix = `sub6-${runId}`;
const subscriptionNameSeven = `sub7-${runId}`;
const subscriptionNameEight = `sub8-${runId}`;
const subscriptionNameDetach = `testdetachsubsxyz-${runId}`;
const fullTopicNameOne = `projects/${projectId}/topics/${topicNameOne}`;
const fullSubscriptionNameOne = `projects/${projectId}/subscriptions/${subscriptionNameOne}`;
const fullSubscriptionNameTwo = `projects/${projectId}/subscriptions/${subscriptionNameTwo}`;
const fullSubscriptionNameFour = `projects/${projectId}/subscriptions/${subscriptionNameFour}`;
before(async () => {
return Promise.all([
pubsub.createTopic(topicNameOne),
pubsub.createTopic(topicNameTwo),
pubsub.createTopic(topicNameThree),
]);
});
after(async () => {
const [subscriptions] = await pubsub.getSubscriptions();
const runSubs = subscriptions.filter(x => x.name.endsWith(runId));
for (const sub of runSubs) {
await sub.delete();
}
const [topics] = await pubsub.getTopics();
const runTops = topics.filter(x => x.name.endsWith(runId));
for (const t of runTops) {
await t.delete();
}
});
it('should create a subscription', async () => {
const output = execSync(
`${commandFor(
'createSubscription'
)} ${topicNameOne} ${subscriptionNameOne}`
);
assert.include(output, `Subscription ${subscriptionNameOne} created.`);
const [subscriptions] = await pubsub.topic(topicNameOne).getSubscriptions();
assert.strictEqual(subscriptions[0].name, fullSubscriptionNameOne);
});
it('should create a push subscription', async () => {
const output = execSync(
`${commandFor(
'createPushSubscription'
)} ${topicNameOne} ${subscriptionNameTwo}`
);
assert.include(output, `Subscription ${subscriptionNameTwo} created.`);
const [subscriptions] = await pubsub.topic(topicNameOne).getSubscriptions();
assert(subscriptions.some(s => s.name === fullSubscriptionNameTwo));
});
it('should modify the config of an existing push subscription', async () => {
const output = execSync(
`${commandFor('modifyPushConfig')} ${topicNameTwo} ${subscriptionNameTwo}`
);
assert.include(
output,
`Modified push config for subscription ${subscriptionNameTwo}.`
);
});
it('should get metadata for a subscription', async () => {
const output = execSync(
`${commandFor('getSubscription')} ${subscriptionNameOne}`
);
const expected =
`Subscription: ${fullSubscriptionNameOne}` +
`\nTopic: ${fullTopicNameOne}` +
'\nPush config: ' +
'\nAck deadline: 10s';
assert.include(output, expected);
});
it('should list all subscriptions', async () => {
const output = execSync(`${commandFor('listSubscriptions')}`);
assert.match(output, /Subscriptions:/);
assert.match(output, new RegExp(fullSubscriptionNameOne));
assert.match(output, new RegExp(fullSubscriptionNameTwo));
});
it('should list subscriptions for a topic', async () => {
const output = execSync(
`${commandFor('listTopicSubscriptions')} ${topicNameOne}`
);
assert.match(output, new RegExp(`Subscriptions for ${topicNameOne}:`));
assert.match(output, new RegExp(fullSubscriptionNameOne));
assert.match(output, new RegExp(fullSubscriptionNameTwo));
});
it('should listen for messages', async () => {
const messageIds = await pubsub
.topic(topicNameOne)
.publish(Buffer.from('Hello, world!'));
const output = execSync(
`${commandFor('listenForMessages')} ${subscriptionNameOne} 10`
);
assert.match(output, new RegExp(`Received message ${messageIds}:`));
});
it('should listen for messages with custom attributes', async () => {
const messageIds = await pubsub
.topic(topicNameOne)
.publish(Buffer.from('Hello, world!'), {attr: 'value'});
const output = execSync(
`${commandFor('listenWithCustomAttributes')} ${subscriptionNameOne} 10`
);
assert.match(
output,
new RegExp(`Received message: id ${messageIds}.*attr.*value`)
);
});
it('should listen for messages synchronously', async () => {
await pubsub.topic(topicNameOne).publish(Buffer.from('Hello, world!'));
const output = execSync(
`${commandFor('synchronousPull')} ${projectId} ${subscriptionNameOne}`
);
assert.match(output, /Hello/);
assert.match(output, /Done./);
});
it('should listen for messages synchronously with lease management', async () => {
await pubsub.topic(topicNameOne).publish(Buffer.from('Hello, world!'));
const output = execSync(
`${commandFor(
'synchronousPullWithLeaseManagement'
)} ${projectId} ${subscriptionNameOne}`
);
assert.match(output, /Done./);
});
it('should listen to messages with flow control', async () => {
const topicTwo = pubsub.topic(topicNameTwo);
await topicTwo.subscription(subscriptionNameFour).get({autoCreate: true});
await topicTwo.publish(Buffer.from('Hello, world!'));
const output = execSync(
`${commandFor(
'subscribeWithFlowControlSettings'
)} ${subscriptionNameFour} 5`
);
assert.include(
output,
'ready to receive messages at a controlled volume of 5 messages.'
);
const [subscriptions] = await pubsub.topic(topicNameTwo).getSubscriptions();
assert(subscriptions.some(s => s.name === fullSubscriptionNameFour));
});
it('should listen for error messages', () => {
assert.throws(
() => execSync('node listenForErrors nonexistent-subscription'),
/Resource not found/
);
});
it('should set the IAM policy for a subscription', async () => {
execSync(`${commandFor('setSubscriptionPolicy')} ${subscriptionNameOne}`);
const results = await pubsub
.subscription(subscriptionNameOne)
.iam.getPolicy();
const policy = results[0];
assert.deepStrictEqual(policy.bindings, [
{
role: 'roles/pubsub.editor',
members: ['group:cloud-logs@google.com'],
condition: null,
},
{
role: 'roles/pubsub.viewer',
members: ['allUsers'],
condition: null,
},
]);
});
it('should get the IAM policy for a subscription', async () => {
const results = await pubsub
.subscription(subscriptionNameOne)
.iam.getPolicy();
const output = execSync(
`${commandFor('getSubscriptionPolicy')} ${subscriptionNameOne}`
);
assert.include(
output,
`Policy for subscription: ${JSON.stringify(results[0].bindings)}.`
);
});
it('should test permissions for a subscription', async () => {
const output = execSync(
`${commandFor('testSubscriptionPermissions')} ${subscriptionNameOne}`
);
assert.match(output, /Tested permissions for subscription/);
});
it('should delete a subscription', async () => {
const output = execSync(
`${commandFor('deleteSubscription')} ${subscriptionNameOne}`
);
assert.include(output, `Subscription ${subscriptionNameOne} deleted.`);
const [subscriptions] = await pubsub.getSubscriptions();
assert.ok(subscriptions);
assert(subscriptions.every(s => s.name !== fullSubscriptionNameOne));
});
it('should detach a subscription', async () => {
await pubsub.createSubscription(topicNameOne, subscriptionNameDetach);
const output = execSync(
`${commandFor('detachSubscription')} ${subscriptionNameDetach}`
);
assert.include(output, "'before' detached status: false");
assert.include(output, "'after' detached status: true");
const [subscriptionDetached] = await pubsub
.subscription(subscriptionNameDetach)
.detached();
assert(subscriptionDetached === true);
});
it('should create a subscription with dead letter policy.', async () => {
const output = execSync(
`${commandFor(
'createSubscriptionWithDeadLetterPolicy'
)} ${topicNameTwo} ${subscriptionNameFive} ${topicNameThree}`
);
assert.include(
output,
`Created subscription ${subscriptionNameFive} with dead letter topic ${topicNameThree}.`
);
const [subscription] = await pubsub
.topic(topicNameTwo)
.subscription(subscriptionNameFive)
.get();
assert.strictEqual(
subscription.metadata?.deadLetterPolicy?.maxDeliveryAttempts,
10
);
});
it('should listen for messages synchronously with delivery attempts.', async () => {
await pubsub.topic(topicNameOne).createSubscription(subscriptionNameSix, {
deadLetterPolicy: {
deadLetterTopic: pubsub.topic(topicNameThree).name,
maxDeliveryAttempts: 10,
},
});
await pubsub.topic(topicNameOne).publish(Buffer.from('Hello, world!'));
const output = execSync(
`${commandFor(
'synchronousPullWithDeliveryAttempts'
)} ${projectId} ${subscriptionNameSix}`
);
assert.match(output, /Hello/);
assert.match(output, /Delivery Attempt: 1/);
});
it('should update a subscription with dead letter policy.', async () => {
const [presub] = await pubsub
.topic(topicNameOne)
.subscription(subscriptionNameSeven)
.get({autoCreate: true});
await presub.setMetadata({
deadLetterPolicy: {
deadLetterTopic: pubsub.topic(topicNameThree).name,
maxDeliveryAttempts: 10,
},
});
execSync(
`${commandFor(
'updateDeadLetterPolicy'
)} ${topicNameOne} ${subscriptionNameSeven}`
);
const [subscription] = await pubsub
.topic(topicNameOne)
.subscription(subscriptionNameSeven)
.get();
assert.equal(
subscription.metadata?.deadLetterPolicy?.maxDeliveryAttempts,
15
);
});
it('should remove dead letter policy.', async () => {
const [presub] = await pubsub
.topic(topicNameOne)
.subscription(subscriptionNameSeven)
.get({autoCreate: true});
await presub.setMetadata({
deadLetterPolicy: {
deadLetterTopic: pubsub.topic(topicNameThree).name,
maxDeliveryAttempts: 10,
},
});
execSync(
`${commandFor(
'removeDeadLetterPolicy'
)} ${topicNameOne} ${subscriptionNameSeven}`
);
const [subscription] = await pubsub
.topic(topicNameOne)
.subscription(subscriptionNameSeven)
.get();
assert.isNull(subscription.metadata?.deadLetterPolicy);
});
it('should create a subscription with ordering enabled.', async () => {
const output = execSync(
`${commandFor(
'createSubscriptionWithOrdering'
)} ${topicNameTwo} ${subscriptionNameEight} ${topicNameThree}`
);
assert.include(
output,
`Created subscription ${subscriptionNameEight} with ordering enabled.`
);
const [subscription] = await pubsub
.topic(topicNameTwo)
.subscription(subscriptionNameEight)
.get();
assert.strictEqual(subscription.metadata?.enableMessageOrdering, true);
});
}); | the_stack |
import { fileBundle } from "../../bundled-files";
import { getImportPath } from "../../chef/helpers";
import { ClassDeclaration } from "../../chef/javascript/components/constructs/class";
import { ArgumentList, FunctionDeclaration } from "../../chef/javascript/components/constructs/function";
import { Module } from "../../chef/javascript/components/module";
import { GenerateDocString } from "../../chef/javascript/components/statements/comments";
import { ExportStatement, ImportStatement } from "../../chef/javascript/components/statements/import-export";
import { ReturnStatement } from "../../chef/javascript/components/statements/statement";
import { VariableDeclaration } from "../../chef/javascript/components/statements/variable";
import { TypeSignature } from "../../chef/javascript/components/types/type-signature";
import { Expression, Operation, VariableReference } from "../../chef/javascript/components/value/expression";
import { TemplateLiteral } from "../../chef/javascript/components/value/template-literal";
import { Value, Type, ValueTypes } from "../../chef/javascript/components/value/value";
import { Component } from "../../component";
import { IFinalPrismSettings } from "../../settings";
import { IServerRenderSettings, ServerRenderChunk, ServerRenderedChunks, serverRenderPrismNode } from "../../templating/builders/server-render";
import { IShellData } from "../template";
import { dirname, relative, join, resolve } from "path";
function renderServerChunk(serverChunk: ServerRenderChunk): ValueTypes | string {
if (typeof serverChunk === "string") {
return serverChunk;
} else if ("value" in serverChunk) {
if (serverChunk.escape) {
return new Expression({
lhs: new VariableReference("escape"),
operation: Operation.Call,
rhs: serverChunk.value
});
} else {
return serverChunk.value;
}
} else if ("condition" in serverChunk) {
return new Expression({
lhs: serverChunk.condition as ValueTypes,
operation: Operation.Ternary,
rhs: new ArgumentList([
templateLiteralFromServerRenderChunks(serverChunk.truthyRenderExpression),
templateLiteralFromServerRenderChunks(serverChunk.falsyRenderExpression)
])
});
} else if ("subject" in serverChunk) {
return new Expression({
lhs: new VariableReference("join", new Expression({
lhs: new VariableReference("map", serverChunk.subject),
operation: Operation.Call,
rhs: new FunctionDeclaration(
null,
[serverChunk.variable],
[new ReturnStatement(
templateLiteralFromServerRenderChunks(serverChunk.childRenderExpression)
)],
{ bound: false }
)
})),
operation: Operation.Call,
rhs: new Value(Type.string)
});
} else if ("component" in serverChunk) {
const args: Map<string, ValueTypes> = new Map(
Array.from(serverChunk.args).map(([name, [value, _]]) => {
if (typeof value === "object" && "argument" in value) return [name, value.argument];
else if (Array.isArray(value)) return [name, templateLiteralFromServerRenderChunks(value)]
else return [name, renderServerChunk(value) as ValueTypes];
})
);
const func = serverChunk.component.serverRenderFunction!;
return new Expression({
lhs: new VariableReference(func.actualName!),
operation: Operation.Call,
rhs: func.buildArgumentListFromArgumentsMap(args)
});
} else {
throw Error();
}
}
/**
* Creates a `TemplateLiteral`
* @param serverChunks Array of chunks
*/
function templateLiteralFromServerRenderChunks(serverChunks: ServerRenderedChunks): TemplateLiteral {
return new TemplateLiteral(serverChunks.map(serverChunk => renderServerChunk(serverChunk)));
}
export function makeTsComponentServerModule(
comp: Component,
settings: IFinalPrismSettings,
ssrSettings: IServerRenderSettings
): void {
comp.serverModule = new Module(join(settings.absoluteServerOutputPath, comp.relativeFilename));
for (const statement of comp.clientModule.statements) {
if (statement instanceof ClassDeclaration) {
// Don't copy the front side component definition
if (statement !== comp.componentClass) comp.serverModule!.statements.push(statement);
} else if (statement instanceof ExportStatement) {
if (statement.exported !== comp.componentClass) comp.serverModule!.statements.push(statement);
} else if (statement instanceof ImportStatement) {
// If component
if (statement.from.endsWith(".prism.js") || statement.from.endsWith(".prism.ts")) {
const newImports: Array<string> = [];
let importedComponent: Component | null = null;
for (const [key] of statement.variable?.entries ?? []) {
if (comp.importedComponents.has(key as string)) {
importedComponent = comp.importedComponents.get(key as string)!;
newImports.push(importedComponent.serverRenderFunction!.actualName!)
} else {
newImports.push(key as string);
}
}
const newPath = getImportPath(
comp.serverModule!.filename!,
importedComponent!.serverModule!.filename!
);
const newImport = new ImportStatement(newImports, newPath, statement.as, statement.typeOnly);
comp.serverModule!.statements.push(newImport);
} else if (!(statement as any).prismPrelude && !statement.from.endsWith(".css")) {
const newPath = getImportPath(
comp.serverModule!.filename!,
resolve(dirname(comp.filename), statement.from)
);
const newImport = new ImportStatement(statement.variable, newPath, statement.as, statement.typeOnly);
comp.serverModule!.statements.push(newImport);
}
} else if (statement !== comp.customElementDefineStatement) {
comp.serverModule!.statements.push(statement);
}
}
comp.serverRenderFunction = new FunctionDeclaration(
`render${comp.className}Component`,
comp.serverRenderParameters,
[]
);
if (comp.defaultData && comp.noSSRData) {
comp.serverRenderFunction.statements.push(new VariableDeclaration("data", {
value: comp.defaultData,
typeSignature: comp.dataTypeSignature
}));
}
// Final argument is to add a entry onto the component that is sent attributes
const serverRenderChunks = serverRenderPrismNode(comp.componentHTMLTag, comp.templateData.nodeData, ssrSettings, comp.globals);
const renderTemplateLiteral = templateLiteralFromServerRenderChunks(serverRenderChunks);
// TODO would comp work just using the existing slot functionality?
// TODO could do in the page render function
if (comp.usesLayout) {
// Generate comp components markup and then pass it to the layout render function to be injected
const innerContent = new VariableDeclaration("content", {
isConstant: true,
value: renderTemplateLiteral
});
comp.serverRenderFunction.statements.push(innerContent);
// TODO layout data is different to component data. Should be interpreted in same way as client global
const renderArgs = new Map([
["attributes", new Value(Type.string)],
["data", new VariableReference("data")],
["contentSlot", innerContent.toReference()]
] as Array<[string, ValueTypes]>);
for (const clientGlobal of comp.clientGlobals) {
renderArgs.set((clientGlobal[0].tail as VariableReference).name, clientGlobal[0]);
}
let argumentList: ArgumentList;
try {
argumentList = comp.usesLayout.serverRenderFunction!.buildArgumentListFromArgumentsMap(renderArgs)
} catch (error) {
throw Error(`Layout "${comp.usesLayout.filename}" has a client global not present in "${comp.filename}"`);
}
const callLayoutSSRFunction = new Expression({
lhs: new VariableReference(comp.usesLayout.serverRenderFunction!.actualName!),
operation: Operation.Call,
rhs: argumentList
});
comp.serverRenderFunction.statements.push(new ReturnStatement(callLayoutSSRFunction));
} else {
comp.serverRenderFunction.statements.push(new ReturnStatement(renderTemplateLiteral));
}
comp.serverModule!.addExport(comp.serverRenderFunction);
if (comp.renderFromEndpoint) {
// TODO recomputing chunks slow :(
// Same chunks without component tag
const chunks = comp.componentHTMLTag.children
.flatMap((child) => serverRenderPrismNode(
child,
comp.templateData.nodeData,
ssrSettings,
comp.globals,
false,
true
)
);
comp.serverModule.statements.push(new FunctionDeclaration(
`render${comp.className}Content`,
comp.serverRenderParameters.filter((name) => name.name !== "attributes"),
[
new ReturnStatement(templateLiteralFromServerRenderChunks(chunks))
]
));
}
// If has page decorator, add another function that renders the page into full document with head
if (comp.isPage) {
const pageRenderArgs: Array<ValueTypes> = comp.needsData ? [new VariableReference("data")] : [];
pageRenderArgs.push(...comp.clientGlobals.map(cG => cG[0]));
const pageRenderCall: ValueTypes = new Expression({
lhs: new VariableReference(comp.serverRenderFunction.actualName!),
operation: Operation.Call,
rhs: new ArgumentList(pageRenderArgs)
});
const metaDataArg: ValueTypes = (comp.title || comp.metadata) ?
templateLiteralFromServerRenderChunks(comp.metaDataChunks) :
new Value(Type.string);
// Creates "return renderHTML(renderComponent(***))"
const renderAsPage = new ReturnStatement(
new Expression({
lhs: new VariableReference("renderHTML"),
operation: Operation.Call,
rhs: new ArgumentList([pageRenderCall, metaDataArg])
})
);
const renderPageFunction = new FunctionDeclaration(
`render${comp.className}Page`,
comp.serverRenderParameters,
[renderAsPage]
);
let description = "Server render function for ";
if (comp.filename) {
// Create a link back to the component
description += `[${comp.className}](file:///${comp.filename?.replace(/\\/g, "/")})`
} else {
description += comp.className;
}
// Generate a docstring for the function
const functionDocumentationString = GenerateDocString({
text: description,
remarks: "Built using [Prism](https://github.com/kaleidawave/prism)",
});
comp.serverModule!.statements.push(functionDocumentationString);
comp.pageServerRenderFunction = renderPageFunction;
comp.serverModule!.addExport(renderPageFunction);
}
// Add imports from the server module
const imports: Array<VariableDeclaration> = [];
// Renders the component around the HTML document
if (comp.isPage) imports.push(new VariableDeclaration("renderHTML"));
// Escapes HTML values
if (comp.needsData) imports.push(new VariableDeclaration("escape"));
if (imports.length > 0) {
comp.serverModule!.addImport(
imports,
"./" +
relative(
dirname(comp.serverModule!.filename ?? ""),
join(settings.absoluteServerOutputPath, "prism")
).replace(/\\/g, "/")
);
}
}
export function buildPrismServerModule(template: IShellData, settings: IFinalPrismSettings): Module {
// Include the escape function
const baseServerModule = Module.fromString(fileBundle.get("server.ts")!, join(settings.absoluteServerOutputPath, "prism"));
// Create a template literal to build the index page. As the template has been parsed it will include slots for rendering slots
const pageRenderTemplateLiteral = serverRenderPrismNode(template.document, template.nodeData, { minify: settings.minify, addDisableToElementWithEvents: false });
// Create function with content and meta slot parameters
const pageRenderFunction = new FunctionDeclaration(
"renderHTML",
[
new VariableDeclaration("contentSlot", { typeSignature: new TypeSignature({ name: "string" }) }),
new VariableDeclaration("metaSlot", { typeSignature: new TypeSignature({ name: "string" }) })
],
[new ReturnStatement(templateLiteralFromServerRenderChunks(pageRenderTemplateLiteral))],
);
baseServerModule.addExport(pageRenderFunction);
return baseServerModule;
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreError } from '@classes/errors/error';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreCourseCommonModWSOptions } from '@features/course/services/course';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreRatingInfo } from '@features/rating/services/rating';
import { CoreTagItem } from '@features/tag/services/tag';
import { CoreApp } from '@services/app';
import { CoreFileEntry } from '@services/file-helper';
import { CoreFilepool } from '@services/filepool';
import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites';
import { CoreUtils } from '@services/utils/utils';
import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws';
import { makeSingleton } from '@singletons';
import { AddonModDataFieldsDelegate } from './data-fields-delegate';
import { AddonModDataOffline } from './data-offline';
import { AddonModDataAutoSyncData, AddonModDataSyncProvider } from './data-sync';
const ROOT_CACHE_KEY = 'mmaModData:';
declare module '@singletons/events' {
/**
* Augment CoreEventsData interface with events specific to this service.
*
* @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
*/
export interface CoreEventsData {
[AddonModDataSyncProvider.AUTO_SYNCED]: AddonModDataAutoSyncData;
[AddonModDataProvider.ENTRY_CHANGED]: AddonModDataEntryChangedEventData;
}
}
export enum AddonModDataAction {
ADD = 'add',
EDIT = 'edit',
DELETE = 'delete',
APPROVE = 'approve',
DISAPPROVE = 'disapprove',
USER = 'user',
USERPICTURE = 'userpicture',
MORE = 'more',
MOREURL = 'moreurl',
COMMENTS = 'comments',
TIMEADDED = 'timeadded',
TIMEMODIFIED = 'timemodified',
TAGS = 'tags',
APPROVALSTATUS = 'approvalstatus',
DELCHECK = 'delcheck', // Unused.
EXPORT = 'export', // Unused.
}
export enum AddonModDataTemplateType {
LIST_HEADER = 'listtemplateheader',
LIST = 'listtemplate',
LIST_FOOTER = 'listtemplatefooter',
ADD = 'addtemplate',
SEARCH = 'asearchtemplate',
SINGLE = 'singletemplate',
}
export enum AddonModDataTemplateMode {
LIST = 'list',
EDIT = 'edit',
SHOW = 'show',
SEARCH = 'search',
}
/**
* Service that provides some features for databases.
*/
@Injectable({ providedIn: 'root' })
export class AddonModDataProvider {
static readonly COMPONENT = 'mmaModData';
static readonly PER_PAGE = 25;
static readonly ENTRY_CHANGED = 'addon_mod_data_entry_changed';
/**
* Adds a new entry to a database.
*
* @param dataId Data instance ID.
* @param entryId EntryId or provisional entry ID when offline.
* @param courseId Course ID.
* @param contents The fields data to be created.
* @param groupId Group id, 0 means that the function will determine the user group.
* @param fields The fields that define the contents.
* @param siteId Site ID. If not defined, current site.
* @param forceOffline Force editing entry in offline.
* @return Promise resolved when the action is done.
*/
async addEntry(
dataId: number,
entryId: number,
courseId: number,
contents: AddonModDataEntryWSField[],
groupId: number = 0,
fields: AddonModDataField[],
siteId?: string,
forceOffline: boolean = false,
): Promise<AddonModDataAddEntryResult> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a data to be synchronized later.
const storeOffline = async (): Promise<AddonModDataAddEntryResult> => {
const entry = await AddonModDataOffline.saveEntry(
dataId,
entryId,
AddonModDataAction.ADD,
courseId,
groupId,
contents,
undefined,
siteId,
);
return {
// Return provissional entry Id.
newentryid: entry.entryid,
sent: false,
};
};
// Checks to store offline.
if (!CoreApp.isOnline() || forceOffline) {
const notifications = this.checkFields(fields, contents);
if (notifications.length > 0) {
return { fieldnotifications: notifications };
}
}
// Remove unnecessary not synced actions.
await this.deleteEntryOfflineAction(dataId, entryId, AddonModDataAction.ADD, siteId);
// App is offline, store the action.
if (!CoreApp.isOnline() || forceOffline) {
return storeOffline();
}
try {
const result: AddonModDataAddEntryResult = await this.addEntryOnline(dataId, contents, groupId, siteId);
result.sent = true;
return result;
} catch (error) {
if (CoreUtils.isWebServiceError(error)) {
// The WebService has thrown an error, this means that responses cannot be submitted.
throw error;
}
// Couldn't connect to server, store in offline.
return storeOffline();
}
}
/**
* Adds a new entry to a database. It does not cache calls. It will fail if offline or cannot connect.
*
* @param dataId Database ID.
* @param data The fields data to be created.
* @param groupId Group id, 0 means that the function will determine the user group.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the action is done.
*/
async addEntryOnline(
dataId: number,
data: AddonModDataEntryWSField[],
groupId?: number,
siteId?: string,
): Promise<AddonModDataAddEntryWSResponse> {
const site = await CoreSites.getSite(siteId);
const params: AddonModDataAddEntryWSParams = {
databaseid: dataId,
data,
};
if (typeof groupId !== 'undefined') {
params.groupid = groupId;
}
return site.write<AddonModDataAddEntryWSResponse>('mod_data_add_entry', params);
}
/**
* Approves or unapproves an entry.
*
* @param dataId Database ID.
* @param entryId Entry ID.
* @param approve Whether to approve (true) or unapprove the entry.
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the action is done.
*/
async approveEntry(
dataId: number,
entryId: number,
approve: boolean,
courseId: number,
siteId?: string,
): Promise<AddonModDataApproveEntryResult | undefined> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a data to be synchronized later.
const storeOffline = async (): Promise<AddonModDataApproveEntryResult> => {
const action = approve ? AddonModDataAction.APPROVE : AddonModDataAction.DISAPPROVE;
await AddonModDataOffline.saveEntry(dataId, entryId, action, courseId, undefined, undefined, undefined, siteId);
return {
sent: false,
};
};
// Get if the opposite action is not synced.
const oppositeAction = approve ? AddonModDataAction.DISAPPROVE : AddonModDataAction.APPROVE;
const found = await this.deleteEntryOfflineAction(dataId, entryId, oppositeAction, siteId);
if (found) {
// Offline action has been found and deleted. Stop here.
return;
}
if (!CoreApp.isOnline()) {
// App is offline, store the action.
return storeOffline();
}
try {
await this.approveEntryOnline(entryId, approve, siteId);
return {
sent: true,
};
} catch (error) {
if (CoreUtils.isWebServiceError(error)) {
// The WebService has thrown an error, this means that responses cannot be submitted.
throw error;
}
// Couldn't connect to server, store in offline.
return storeOffline();
}
}
/**
* Approves or unapproves an entry. It does not cache calls. It will fail if offline or cannot connect.
*
* @param entryId Entry ID.
* @param approve Whether to approve (true) or unapprove the entry.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the action is done.
*/
async approveEntryOnline(entryId: number, approve: boolean, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params: AddonModDataApproveEntryWSParams = {
entryid: entryId,
approve,
};
await site.write('mod_data_approve_entry', params);
}
/**
* Convenience function to check fields requeriments here named "notifications".
*
* @param fields The fields that define the contents.
* @param contents The contents data of the fields.
* @return Array of notifications if any or false.
*/
protected checkFields(fields: AddonModDataField[], contents: AddonModDataSubfieldData[]): AddonModDataFieldNotification[] {
const notifications: AddonModDataFieldNotification[] = [];
const contentsIndexed = CoreUtils.arrayToObjectMultiple(contents, 'fieldid');
// App is offline, check required fields.
fields.forEach((field) => {
const notification = AddonModDataFieldsDelegate.getFieldsNotifications(field, contentsIndexed[field.id]);
if (notification) {
notifications.push({
fieldname: field.name,
notification,
});
}
});
return notifications;
}
/**
* Deletes an entry.
*
* @param dataId Database ID.
* @param entryId Entry ID.
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the action is done.
*/
async deleteEntry(dataId: number, entryId: number, courseId: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a data to be synchronized later.
const storeOffline = async (): Promise<void> => {
await AddonModDataOffline.saveEntry(
dataId,
entryId,
AddonModDataAction.DELETE,
courseId,
undefined,
undefined,
undefined,
siteId,
);
};
// Check if the opposite action is not synced and just delete it.
const addedOffline = await this.deleteEntryOfflineAction(dataId, entryId, AddonModDataAction.ADD, siteId);
if (addedOffline) {
// Offline add action found and deleted. Stop here.
return;
}
if (!CoreApp.isOnline()) {
// App is offline, store the action.
return storeOffline();
}
try {
await this.deleteEntryOnline(entryId, siteId);
} catch (error) {
if (CoreUtils.isWebServiceError(error)) {
// The WebService has thrown an error, this means that responses cannot be submitted.
throw error;
}
// Couldn't connect to server, store in offline.
return storeOffline();
}
}
/**
* Deletes an entry. It does not cache calls. It will fail if offline or cannot connect.
*
* @param entryId Entry ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the action is done.
*/
async deleteEntryOnline(entryId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params: AddonModDataDeleteEntryWSParams = {
entryid: entryId,
};
await site.write('mod_data_delete_entry', params);
}
/**
* Delete entry offline action.
*
* @param dataId Database ID.
* @param entryId Entry ID.
* @param action Action name to delete.
* @param siteId Site ID.
* @return Resolved with true if the action has been found and deleted.
*/
protected async deleteEntryOfflineAction(
dataId: number,
entryId: number,
action: AddonModDataAction,
siteId: string,
): Promise<boolean> {
try {
// Get other not not synced actions.
await AddonModDataOffline.getEntry(dataId, entryId, action, siteId);
await AddonModDataOffline.deleteEntry(dataId, entryId, action, siteId);
return true;
} catch {
// Not found.
return false;
}
}
/**
* Updates an existing entry.
*
* @param dataId Database ID.
* @param entryId Entry ID.
* @param courseId Course ID.
* @param contents The contents data to be updated.
* @param fields The fields that define the contents.
* @param siteId Site ID. If not defined, current site.
* @param forceOffline Force editing entry in offline.
* @return Promise resolved when the action is done.
*/
async editEntry(
dataId: number,
entryId: number,
courseId: number,
contents: AddonModDataEntryWSField[],
fields: AddonModDataField[],
siteId?: string,
forceOffline: boolean = false,
): Promise<AddonModDataEditEntryResult> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a data to be synchronized later.
const storeOffline = async (): Promise<AddonModDataEditEntryResult> => {
await AddonModDataOffline.saveEntry(
dataId,
entryId,
AddonModDataAction.EDIT,
courseId,
undefined,
contents,
undefined,
siteId,
);
return {
updated: true,
sent: false,
};
};
if (!CoreApp.isOnline() || forceOffline) {
const notifications = this.checkFields(fields, contents);
if (notifications.length > 0) {
return { fieldnotifications: notifications };
}
}
// Remove unnecessary not synced actions.
await this.deleteEntryOfflineAction(dataId, entryId, AddonModDataAction.EDIT, siteId);
if (!CoreApp.isOnline() || forceOffline) {
// App is offline, store the action.
return storeOffline();
}
try {
const result: AddonModDataEditEntryResult = await this.editEntryOnline(entryId, contents, siteId);
result.sent = true;
return result;
} catch (error) {
if (CoreUtils.isWebServiceError(error)) {
// The WebService has thrown an error, this means that responses cannot be submitted.
throw error;
}
// Couldn't connect to server, store in offline.
return storeOffline();
}
}
/**
* Updates an existing entry. It does not cache calls. It will fail if offline or cannot connect.
*
* @param entryId Entry ID.
* @param data The fields data to be updated.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the action is done.
*/
async editEntryOnline(
entryId: number,
data: AddonModDataEntryWSField[],
siteId?: string,
): Promise<AddonModDataUpdateEntryWSResponse> {
const site = await CoreSites.getSite(siteId);
const params: AddonModDataUpdateEntryWSParams = {
entryid: entryId,
data,
};
return site.write<AddonModDataUpdateEntryWSResponse>('mod_data_update_entry', params);
}
/**
* Performs the whole fetch of the entries in the database.
*
* @param dataId Data ID.
* @param options Other options.
* @return Promise resolved when done.
*/
fetchAllEntries(dataId: number, options: AddonModDataGetEntriesOptions = {}): Promise<AddonModDataEntry[]> {
options.siteId = options.siteId || CoreSites.getCurrentSiteId();
options = Object.assign({
page: 0,
perPage: AddonModDataProvider.PER_PAGE,
}, options);
return this.fetchEntriesRecursive(dataId, [], options);
}
/**
* Recursive call on fetch all entries.
*
* @param dataId Data ID.
* @param entries Entries already fetch (just to concatenate them).
* @param options Other options.
* @return Promise resolved when done.
*/
protected async fetchEntriesRecursive(
dataId: number,
entries: AddonModDataEntry[],
options: AddonModDataGetEntriesOptions,
): Promise<AddonModDataEntry[]> {
const result = await this.getEntries(dataId, options);
entries = entries.concat(result.entries);
const canLoadMore = options.perPage! > 0 && ((options.page! + 1) * options.perPage!) < result.totalcount;
if (canLoadMore) {
options.page!++;
return this.fetchEntriesRecursive(dataId, entries, options);
}
return entries;
}
/**
* Get cache key for data data WS calls.
*
* @param courseId Course ID.
* @return Cache key.
*/
protected getDatabaseDataCacheKey(courseId: number): string {
return ROOT_CACHE_KEY + 'data:' + courseId;
}
/**
* Get prefix cache key for all database activity data WS calls.
*
* @param dataId Data ID.
* @return Cache key.
*/
protected getDatabaseDataPrefixCacheKey(dataId: number): string {
return ROOT_CACHE_KEY + dataId;
}
/**
* Get a database data. If more than one is found, only the first will be returned.
*
* @param courseId Course ID.
* @param key Name of the property to check.
* @param value Value to search.
* @param options Other options.
* @return Promise resolved when the data is retrieved.
*/
protected async getDatabaseByKey(
courseId: number,
key: string,
value: number,
options: CoreSitesCommonWSOptions = {},
): Promise<AddonModDataData> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModDataGetDatabasesByCoursesWSParams = {
courseids: [courseId],
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getDatabaseDataCacheKey(courseId),
updateFrequency: CoreSite.FREQUENCY_RARELY,
component: AddonModDataProvider.COMPONENT,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response =
await site.read<AddonModDataGetDatabasesByCoursesWSResponse>('mod_data_get_databases_by_courses', params, preSets);
const currentData = response.databases.find((data) => data[key] == value);
if (currentData) {
return currentData;
}
throw new CoreError('Activity not found');
}
/**
* Get a data by course module ID.
*
* @param courseId Course ID.
* @param cmId Course module ID.
* @param options Other options.
* @return Promise resolved when the data is retrieved.
*/
getDatabase(courseId: number, cmId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModDataData> {
return this.getDatabaseByKey(courseId, 'coursemodule', cmId, options);
}
/**
* Get a data by ID.
*
* @param courseId Course ID.
* @param id Data ID.
* @param options Other options.
* @return Promise resolved when the data is retrieved.
*/
getDatabaseById(courseId: number, id: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModDataData> {
return this.getDatabaseByKey(courseId, 'id', id, options);
}
/**
* Get prefix cache key for all database access information data WS calls.
*
* @param dataId Data ID.
* @return Cache key.
*/
protected getDatabaseAccessInformationDataPrefixCacheKey(dataId: number): string {
return this.getDatabaseDataPrefixCacheKey(dataId) + ':access:';
}
/**
* Get cache key for database access information data WS calls.
*
* @param dataId Data ID.
* @param groupId Group ID.
* @return Cache key.
*/
protected getDatabaseAccessInformationDataCacheKey(dataId: number, groupId: number = 0): string {
return this.getDatabaseAccessInformationDataPrefixCacheKey(dataId) + groupId;
}
/**
* Get access information for a given database.
*
* @param dataId Data ID.
* @param options Other options.
* @return Promise resolved when the database is retrieved.
*/
async getDatabaseAccessInformation(
dataId: number,
options: AddonModDataAccessInfoOptions = {},
): Promise<AddonModDataGetDataAccessInformationWSResponse> {
const site = await CoreSites.getSite(options.siteId);
options.groupId = options.groupId || 0;
const params: AddonModDataGetDataAccessInformationWSParams = {
databaseid: dataId,
groupid: options.groupId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getDatabaseAccessInformationDataCacheKey(dataId, options.groupId),
component: AddonModDataProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
return site.read<AddonModDataGetDataAccessInformationWSResponse>('mod_data_get_data_access_information', params, preSets);
}
/**
* Get entries for a specific database and group.
*
* @param dataId Data ID.
* @param options Other options.
* @return Promise resolved when the database is retrieved.
*/
async getEntries(dataId: number, options: AddonModDataGetEntriesOptions = {}): Promise<AddonModDataEntries> {
options = Object.assign({
groupId: 0,
sort: 0,
order: 'DESC',
page: 0,
perPage: AddonModDataProvider.PER_PAGE,
}, options);
const site = await CoreSites.getSite(options.siteId);
// Always use sort and order params to improve cache usage (entries are identified by params).
const params: AddonModDataGetEntriesWSParams = {
databaseid: dataId,
returncontents: true,
page: options.page,
perpage: options.perPage,
groupid: options.groupId,
sort: options.sort,
order: options.order,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getEntriesCacheKey(dataId, options.groupId),
updateFrequency: CoreSite.FREQUENCY_SOMETIMES,
component: AddonModDataProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModDataGetEntriesWSResponse>('mod_data_get_entries', params, preSets);
const entriesFormatted = response.entries.map((entry) => this.formatEntryContents(entry));
return Object.assign(response, {
entries: entriesFormatted,
});
}
/**
* Get cache key for database entries data WS calls.
*
* @param dataId Data ID.
* @param groupId Group ID.
* @return Cache key.
*/
protected getEntriesCacheKey(dataId: number, groupId: number = 0): string {
return this.getEntriesPrefixCacheKey(dataId) + groupId;
}
/**
* Get prefix cache key for database all entries data WS calls.
*
* @param dataId Data ID.
* @return Cache key.
*/
protected getEntriesPrefixCacheKey(dataId: number): string {
return this.getDatabaseDataPrefixCacheKey(dataId) + ':entries:';
}
/**
* Get an entry of the database activity.
*
* @param dataId Data ID for caching purposes.
* @param entryId Entry ID.
* @param options Other options.
* @return Promise resolved when the entry is retrieved.
*/
async getEntry(
dataId: number,
entryId: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModDataGetEntryFormatted> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModDataGetEntryWSParams = {
entryid: entryId,
returncontents: true,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getEntryCacheKey(dataId, entryId),
updateFrequency: CoreSite.FREQUENCY_SOMETIMES,
component: AddonModDataProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModDataGetEntryWSResponse>('mod_data_get_entry', params, preSets);
return Object.assign(response, {
entry: this.formatEntryContents(response.entry),
});
}
/**
* Formats the contents of an entry.
*
* @param entry Original WS entry.
* @returns Entry with contents formatted.
*/
protected formatEntryContents(entry: AddonModDataEntryWS): AddonModDataEntry {
return Object.assign(entry, {
contents: CoreUtils.arrayToObject(entry.contents, 'fieldid'),
});
}
/**
* Get cache key for database entry data WS calls.
*
* @param dataId Data ID for caching purposes.
* @param entryId Entry ID.
* @return Cache key.
*/
protected getEntryCacheKey(dataId: number, entryId: number): string {
return this.getDatabaseDataPrefixCacheKey(dataId) + ':entry:' + entryId;
}
/**
* Get the list of configured fields for the given database.
*
* @param dataId Data ID.
* @param options Other options.
* @return Promise resolved when the fields are retrieved.
*/
async getFields(dataId: number, options: CoreCourseCommonModWSOptions = {}): Promise<AddonModDataField[]> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModDataGetFieldsWSParams = {
databaseid: dataId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getFieldsCacheKey(dataId),
updateFrequency: CoreSite.FREQUENCY_RARELY,
component: AddonModDataProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModDataGetFieldsWSResponse>('mod_data_get_fields', params, preSets);
if (response.fields) {
return response.fields;
}
throw new CoreError('No fields were returned.');
}
/**
* Get cache key for database fields data WS calls.
*
* @param dataId Data ID.
* @return Cache key.
*/
protected getFieldsCacheKey(dataId: number): string {
return this.getDatabaseDataPrefixCacheKey(dataId) + ':fields';
}
/**
* Invalidate the prefetched content.
* To invalidate files, use AddonModDataProvider#invalidateFiles.
*
* @param moduleId The module ID.
* @param courseId Course ID of the module.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const promises: Promise<void>[] = [];
promises.push(this.getDatabase(courseId, moduleId).then(async (database) => {
const ps: Promise<void>[] = [];
// Do not invalidate module data before getting module info, we need it!
ps.push(this.invalidateDatabaseData(courseId, siteId));
ps.push(this.invalidateDatabaseWSData(database.id, siteId));
ps.push(this.invalidateFieldsData(database.id, siteId));
await Promise.all(ps);
return;
}));
promises.push(this.invalidateFiles(moduleId, siteId));
await CoreUtils.allPromises(promises);
}
/**
* Invalidates database access information data.
*
* @param dataId Data ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateDatabaseAccessInformationData(dataId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getDatabaseAccessInformationDataPrefixCacheKey(dataId));
}
/**
* Invalidates database entries data.
*
* @param dataId Data ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateEntriesData(dataId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getEntriesPrefixCacheKey(dataId));
}
/**
* Invalidates database fields data.
*
* @param dataId Data ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateFieldsData(dataId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getFieldsCacheKey(dataId));
}
/**
* Invalidate the prefetched files.
*
* @param moduleId The module ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the files are invalidated.
*/
async invalidateFiles(moduleId: number, siteId?: string): Promise<void> {
await CoreFilepool.invalidateFilesByComponent(siteId, AddonModDataProvider.COMPONENT, moduleId);
}
/**
* Invalidates database data.
*
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateDatabaseData(courseId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getDatabaseDataCacheKey(courseId));
}
/**
* Invalidates database data except files and module info.
*
* @param databaseId Data ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateDatabaseWSData(databaseId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getDatabaseDataPrefixCacheKey(databaseId));
}
/**
* Invalidates database entry data.
*
* @param dataId Data ID for caching purposes.
* @param entryId Entry ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateEntryData(dataId: number, entryId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getEntryCacheKey(dataId, entryId));
}
/**
* Return whether or not the plugin is enabled in a certain site. Plugin is enabled if the database WS are available.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with true if plugin is enabled, rejected or resolved with false otherwise.
* @since 3.3
*/
async isPluginEnabled(siteId?: string): Promise<boolean> {
const site = await CoreSites.getSite(siteId);
return site.wsAvailable('mod_data_get_data_access_information');
}
/**
* Report the database as being viewed.
*
* @param id Module ID.
* @param name Name of the data.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS call is successful.
*/
async logView(id: number, name?: string, siteId?: string): Promise<void> {
const params: AddonModDataViewDatabaseWSParams = {
databaseid: id,
};
await CoreCourseLogHelper.logSingle(
'mod_data_view_database',
params,
AddonModDataProvider.COMPONENT,
id,
name,
'data',
{},
siteId,
);
}
/**
* Performs search over a database.
*
* @param dataId The data instance id.
* @param options Other options.
* @return Promise resolved when the action is done.
*/
async searchEntries(dataId: number, options: AddonModDataSearchEntriesOptions = {}): Promise<AddonModDataEntries> {
const site = await CoreSites.getSite(options.siteId);
options.groupId = options.groupId || 0;
options.sort = options.sort || 0;
options.order || options.order || 'DESC';
options.page = options.page || 0;
options.perPage = options.perPage || AddonModDataProvider.PER_PAGE;
options.readingStrategy = options.readingStrategy || CoreSitesReadingStrategy.PREFER_NETWORK;
const params: AddonModDataSearchEntriesWSParams = {
databaseid: dataId,
groupid: options.groupId,
returncontents: true,
page: options.page,
perpage: options.perPage,
};
const preSets: CoreSiteWSPreSets = {
component: AddonModDataProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
if (typeof options.sort != 'undefined') {
params.sort = options.sort;
}
if (typeof options.order !== 'undefined') {
params.order = options.order;
}
if (typeof options.search !== 'undefined') {
params.search = options.search;
}
if (typeof options.advSearch !== 'undefined') {
params.advsearch = options.advSearch;
}
const response = await site.read<AddonModDataSearchEntriesWSResponse>('mod_data_search_entries', params, preSets);
const entriesFormatted = response.entries.map((entry) => this.formatEntryContents(entry));
return Object.assign(response, {
entries: entriesFormatted,
});
}
}
export const AddonModData = makeSingleton(AddonModDataProvider);
/**
* Params of mod_data_view_database WS.
*/
type AddonModDataViewDatabaseWSParams = {
databaseid: number; // Data instance id.
};
/**
* Params of mod_data_search_entries WS.
*/
type AddonModDataSearchEntriesWSParams = {
databaseid: number; // Data instance id.
groupid?: number; // Group id, 0 means that the function will determine the user group.
returncontents?: boolean; // Whether to return contents or not.
search?: string; // Search string (empty when using advanced).
advsearch?: AddonModDataSearchEntriesAdvancedField[];
sort?: number; // Sort the records by this field id, reserved ids are:
// 0: timeadded
// -1: firstname
// -2: lastname
// -3: approved
// -4: timemodified.
// Empty for using the default database setting.
order?: string; // The direction of the sorting: 'ASC' or 'DESC'. Empty for using the default database setting.
page?: number; // The page of records to return.
perpage?: number; // The number of records to return per page.
};
/**
* Data returned by mod_data_search_entries WS.
*/
export type AddonModDataSearchEntriesWSResponse = {
entries: AddonModDataEntryWS[];
totalcount: number; // Total count of records returned by the search.
maxcount?: number; // Total count of records that the user could see in the database (if all the search criterias were removed).
listviewcontents?: string; // The list view contents as is rendered in the site.
warnings?: CoreWSExternalWarning[];
};
/**
* Options to pass to get access info.
*/
export type AddonModDataAccessInfoOptions = CoreCourseCommonModWSOptions & {
groupId?: number; // Group Id.
};
/**
* Options to pass to get entries.
*/
export type AddonModDataGetEntriesOptions = CoreCourseCommonModWSOptions & {
groupId?: number; // Group Id.
sort?: number; // Sort the records by this field id, defaults to 0. Reserved ids are:
// 0: timeadded
// -1: firstname
// -2: lastname
// -3: approved
// -4: timemodified
order?: string; // The direction of the sorting: 'ASC' or 'DESC'. Defaults to 'DESC'.
page?: number; // Page of records to return. Defaults to 0.
perPage?: number; // Records per page to return. Defaults to AddonModDataProvider.PER_PAGE.
};
/**
* Options to pass to search entries.
*/
export type AddonModDataSearchEntriesOptions = AddonModDataGetEntriesOptions & {
search?: string; // Search text. It will be used if advSearch is not defined.
advSearch?: AddonModDataSearchEntriesAdvancedField[];
};
/**
* Database entry (online or offline).
*/
export type AddonModDataEntry = Omit<AddonModDataEntryWS, 'contents'> & {
contents: AddonModDataEntryFields; // The record contents.
tags?: CoreTagItem[]; // Tags.
// Calculated data.
deleted?: boolean; // Entry is deleted offline.
hasOffline?: boolean; // Entry has offline actions.
};
/**
* Database entry data from WS.
*/
export type AddonModDataEntryWS = {
id: number; // Record id.
userid: number; // The id of the user who created the record.
groupid: number; // The group id this record belongs to (0 for no groups).
dataid: number; // The database id this record belongs to.
timecreated: number; // Time the record was created.
timemodified: number; // Last time the record was modified.
approved: boolean; // Whether the entry has been approved (if the database is configured in that way).
canmanageentry: boolean; // Whether the current user can manage this entry.
fullname?: string; // The user who created the entry fullname.
contents?: AddonModDataEntryField[];
tags?: CoreTagItem[]; // Tags.
};
/**
* Entry field content.
*/
export type AddonModDataEntryField = {
id: number; // Content id.
fieldid: number; // The field type of the content.
recordid: number; // The record this content belongs to.
content: string; // Contents.
content1: string; // Contents.
content2: string; // Contents.
content3: string; // Contents.
content4: string; // Contents.
files: CoreFileEntry[];
};
/**
* Entry contents indexed by field id.
*/
export type AddonModDataEntryFields = {
[fieldid: number]: AddonModDataEntryField;
};
/**
* List of entries returned by web service and helper functions.
*/
export type AddonModDataEntries = {
entries: AddonModDataEntry[]; // Online entries.
totalcount: number; // Total count of online entries or found entries.
maxcount?: number; // Total count of online entries. Only returned when searching.
offlineEntries?: AddonModDataEntry[]; // Offline entries.
hasOfflineActions?: boolean; // Whether the database has offline data.
hasOfflineRatings?: boolean; // Whether the database has offline ratings.
};
/**
* Subfield form data.
*/
export type AddonModDataSubfieldData = {
fieldid: number;
subfield?: string;
value?: unknown; // Value encoded in JSON.
files?: CoreFileEntry[];
};
/**
* Params of mod_data_get_data_access_information WS.
*/
type AddonModDataGetDataAccessInformationWSParams = {
databaseid: number; // Database instance id.
groupid?: number; // Group id, 0 means that the function will determine the user group.
};
/**
* Data returned by mod_data_get_data_access_information WS.
*/
export type AddonModDataGetDataAccessInformationWSResponse = {
groupid: number; // User current group id (calculated).
canaddentry: boolean; // Whether the user can add entries or not.
canmanageentries: boolean; // Whether the user can manage entries or not.
canapprove: boolean; // Whether the user can approve entries or not.
timeavailable: boolean; // Whether the database is available or not by time restrictions.
inreadonlyperiod: boolean; // Whether the database is in read mode only.
numentries: number; // The number of entries the current user added.
entrieslefttoadd: number; // The number of entries left to complete the activity.
entrieslefttoview: number; // The number of entries left to view other users entries.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_data_get_databases_by_courses WS.
*/
type AddonModDataGetDatabasesByCoursesWSParams = {
courseids?: number[]; // Array of course ids.
};
/**
* Data returned by mod_data_get_databases_by_courses WS.
*/
type AddonModDataGetDatabasesByCoursesWSResponse = {
databases: AddonModDataData[];
warnings?: CoreWSExternalWarning[];
};
/**
* Database data returned by mod_assign_get_assignments.
*/
export type AddonModDataData = {
id: number; // Database id.
course: number; // Course id.
name: string; // Database name.
intro: string; // The Database intro.
introformat?: number; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
comments: boolean; // Comments enabled.
timeavailablefrom: number; // Timeavailablefrom field.
timeavailableto: number; // Timeavailableto field.
timeviewfrom: number; // Timeviewfrom field.
timeviewto: number; // Timeviewto field.
requiredentries: number; // Requiredentries field.
requiredentriestoview: number; // Requiredentriestoview field.
maxentries: number; // Maxentries field.
rssarticles: number; // Rssarticles field.
singletemplate: string; // Singletemplate field.
listtemplate: string; // Listtemplate field.
listtemplateheader: string; // Listtemplateheader field.
listtemplatefooter: string; // Listtemplatefooter field.
addtemplate: string; // Addtemplate field.
rsstemplate: string; // Rsstemplate field.
rsstitletemplate: string; // Rsstitletemplate field.
csstemplate: string; // Csstemplate field.
jstemplate: string; // Jstemplate field.
asearchtemplate: string; // Asearchtemplate field.
approval: boolean; // Approval field.
manageapproved: boolean; // Manageapproved field.
scale?: number; // Scale field.
assessed?: number; // Assessed field.
assesstimestart?: number; // Assesstimestart field.
assesstimefinish?: number; // Assesstimefinish field.
defaultsort: number; // Defaultsort field.
defaultsortdir: number; // Defaultsortdir field.
editany?: boolean; // Editany field (not used any more).
notification?: number; // Notification field (not used any more).
timemodified?: number; // Time modified.
coursemodule: number; // Coursemodule.
introfiles?: CoreWSExternalFile[];
};
/**
* Params of mod_data_add_entry WS.
*/
type AddonModDataAddEntryWSParams = {
databaseid: number; // Data instance id.
groupid?: number; // Group id, 0 means that the function will determine the user group.
data: AddonModDataEntryWSField[]; // The fields data to be created.
};
/**
* Data returned by mod_data_add_entry WS.
*/
export type AddonModDataAddEntryWSResponse = {
newentryid: number; // True new created entry id. 0 if the entry was not created.
generalnotifications: string[];
fieldnotifications: AddonModDataFieldNotification[];
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_data_approve_entry WS.
*/
type AddonModDataApproveEntryWSParams = {
entryid: number; // Record entry id.
approve?: boolean; // Whether to approve (true) or unapprove the entry.
};
/**
* Params of mod_data_delete_entry WS.
*/
type AddonModDataDeleteEntryWSParams = {
entryid: number; // Record entry id.
};
/**
* Params of mod_data_update_entry WS.
*/
type AddonModDataUpdateEntryWSParams = {
entryid: number; // The entry record id.
data: AddonModDataEntryWSField[]; // The fields data to be updated.
};
/**
* Data returned by mod_data_update_entry WS.
*/
export type AddonModDataUpdateEntryWSResponse = {
updated: boolean; // True if the entry was successfully updated, false other wise.
generalnotifications: string[];
fieldnotifications: AddonModDataFieldNotification[];
warnings?: CoreWSExternalWarning[];
};
// The fields data to be created or updated.
export type AddonModDataEntryWSField = {
fieldid: number; // The field id. AddonModDataSubfieldData
subfield?: string; // The subfield name (if required).
value: string; // The contents for the field always JSON encoded.
};
/**
* Params of mod_data_get_entries WS.
*/
type AddonModDataGetEntriesWSParams = {
databaseid: number; // Data instance id.
groupid?: number; // Group id, 0 means that the function will determine the user group.
returncontents?: boolean; // Whether to return contents or not. This will return each entry raw contents and the complete list
// view(using the template).
sort?: number; // Sort the records by this field id, reserved ids are:
// 0: timeadded
// -1: firstname
// -2: lastname
// -3: approved
// -4: timemodified.
// Empty for using the default database setting.
order?: string; // The direction of the sorting: 'ASC' or 'DESC'. Empty for using the default database setting.
page?: number; // The page of records to return.
perpage?: number; // The number of records to return per page.
};
/**
* Data returned by mod_data_get_entries WS.
*/
export type AddonModDataGetEntriesWSResponse = {
entries: AddonModDataEntryWS[];
totalcount: number; // Total count of records.
totalfilesize: number; // Total size (bytes) of the files included in the records.
listviewcontents?: string; // The list view contents as is rendered in the site.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_data_get_entry WS.
*/
type AddonModDataGetEntryWSParams = {
entryid: number; // Record entry id.
returncontents?: boolean; // Whether to return contents or not.
};
/**
* Data returned by mod_data_get_entry WS.
*/
type AddonModDataGetEntryWSResponse = {
entry: AddonModDataEntryWS;
entryviewcontents?: string; // The entry as is rendered in the site.
ratinginfo?: CoreRatingInfo; // Rating information.
warnings?: CoreWSExternalWarning[];
};
/**
* Data returned by mod_data_get_entry WS.
*/
export type AddonModDataGetEntryFormatted = {
entry: AddonModDataEntry;
entryviewcontents?: string; // The entry as is rendered in the site.
ratinginfo?: CoreRatingInfo; // Rating information.
warnings?: CoreWSExternalWarning[];
};
export type AddonModDataFieldNotification = {
fieldname: string; // The field name.
notification: string; // The notification for the field.
};
/**
* Params of mod_data_get_fields WS.
*/
type AddonModDataGetFieldsWSParams = {
databaseid: number; // Database instance id.
};
/**
* Data returned by mod_data_get_fields WS.
*/
type AddonModDataGetFieldsWSResponse = {
fields: AddonModDataField[];
warnings?: CoreWSExternalWarning[];
};
/**
* Field data returned by mod_data_get_fields WS.
*/
export type AddonModDataField = {
id: number; // Field id.
dataid: number; // The field type of the content.
type: string; // The field type.
name: string; // The field name.
description: string; // The field description.
required: boolean; // Whether is a field required or not.
param1: string; // Field parameters.
param2: string; // Field parameters.
param3: string; // Field parameters.
param4: string; // Field parameters.
param5: string; // Field parameters.
param6: string; // Field parameters.
param7: string; // Field parameters.
param8: string; // Field parameters.
param9: string; // Field parameters.
param10: string; // Field parameters.
};
export type AddonModDataEntryChangedEventData = {
dataId: number;
entryId?: number;
deleted?: boolean;
};
/**
* Advanced search field.
*/
export type AddonModDataSearchEntriesAdvancedField = {
name: string; // Field key for search. Use fn or ln for first or last name.
value: string; // JSON encoded value for search.
};
/**
* Advanced search field.
*/
export type AddonModDataSearchEntriesAdvancedFieldFormatted = {
name: string; // Field key for search. Use fn or ln for first or last name.
value: unknown; // JSON encoded value for search.
};
export type AddonModDataAddEntryResult = Partial<AddonModDataAddEntryWSResponse> & {
sent?: boolean; // True if sent, false if stored offline.
};
export type AddonModDataApproveEntryResult = {
sent?: boolean; // True if sent, false if stored offline.
};
export type AddonModDataEditEntryResult = Partial<AddonModDataUpdateEntryWSResponse> & {
sent?: boolean; // True if sent, false if stored offline.
}; | the_stack |
import { print as printWindow, createElement, isNullOrUndefined, Browser } from '@syncfusion/ej2-base';
import { Chart } from '../../chart/chart';
import { SvgRenderer } from '@syncfusion/ej2-svg-base';
import { AccumulationChart } from '../../accumulation-chart/accumulation';
import { getElement, removeElement } from '../utils/helper';
import { ExportType } from '../utils/enum';
import { IPrintEventArgs, IAfterExportEventArgs } from '../../chart/model/chart-interface';
import { beforePrint, afterExport } from '../model/constants';
import {
PdfPageOrientation, PdfDocument, PdfBitmap, SizeF, PdfMargins, PdfStandardFont, PdfPageTemplateElement,
PdfSolidBrush, PdfColor
} from '@syncfusion/ej2-pdf-export';
import { RangeNavigator } from '../..';
import { StockChart } from '../../stock-chart/stock-chart';
import { BulletChart } from '../../bullet-chart/bullet-chart';
import { IPDFArgs } from '../../common/model/interface';
/**
* Export Functionalities
*/
/** @private */
interface IControlValue {
width: number;
height: number;
svg: Element;
}
export class ExportUtils {
private control: Chart | AccumulationChart | RangeNavigator | StockChart | BulletChart;
private printWindow: Window;
/**
* Constructor for chart and accumulation annotation
*
* @param control
*/
constructor(control: Chart | AccumulationChart | RangeNavigator | StockChart | BulletChart) {
this.control = control;
}
/**
* To print the accumulation and chart elements
*
* @param elements
*/
public print(elements?: string[] | string | Element): void {
this.printWindow = window.open('', 'print', 'height=' + window.outerHeight + ',width=' + window.outerWidth + ',tabbar=no');
this.printWindow.moveTo(0, 0);
this.printWindow.resizeTo(screen.availWidth, screen.availHeight);
const argsData: IPrintEventArgs = {
cancel: false, htmlContent: this.getHTMLContent(elements), name: beforePrint
};
this.control.trigger(beforePrint, argsData);
if (!argsData.cancel) {
printWindow(argsData.htmlContent, this.printWindow);
}
}
/**
* To get the html string of the chart and accumulation
*
* @param elements
* @private
*/
public getHTMLContent(elements?: string[] | string | Element): Element {
const div: Element = createElement('div');
if (elements) {
if (elements instanceof Array) {
for (let j: number = 0; j < elements.length; j++) {
const value: string = elements[j];
div.appendChild(getElement(value).cloneNode(true) as Element);
}
} else if (elements instanceof Element) {
div.appendChild(elements.cloneNode(true) as Element);
} else {
div.appendChild(getElement(elements).cloneNode(true) as Element);
}
} else {
div.appendChild(this.control.element.cloneNode(true) as Element);
}
return div;
}
/**
* To export the file as image/svg format
*
* @param type
* @param fileName
*/
public export(
type: ExportType, fileName: string,
orientation?: PdfPageOrientation,
controls?: (Chart | AccumulationChart | RangeNavigator | StockChart | BulletChart)[],
width?: number, height?: number, isVertical?: boolean,
header?: IPDFArgs, footer?: IPDFArgs
): void {
const controlValue: IControlValue = this.getControlsValue(controls, isVertical);
width = width ? width : controlValue.width;
height = height ? height : controlValue.height;
let element: HTMLCanvasElement = this.control.svgObject as HTMLCanvasElement;
const isCanvas: boolean = (this.control as Chart).enableCanvas;
let image: string;
if (!isCanvas) {
element = <HTMLCanvasElement>createElement('canvas', {
id: 'ej2-canvas',
attrs: {
'width': width.toString(),
'height': height.toString()
}
});
}
const isDownload: boolean = !(Browser.userAgent.toString().indexOf('HeadlessChrome') > -1);
orientation = isNullOrUndefined(orientation) ? PdfPageOrientation.Landscape : orientation;
const svgData: string = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' +
controlValue.svg.outerHTML +
'</svg>';
const url: string = window.URL.createObjectURL(
new Blob(
type === 'SVG' ? [svgData] :
[(new XMLSerializer()).serializeToString(controlValue.svg)],
{ type: 'image/svg+xml' }
)
);
if (type === 'SVG') {
if (Browser.info.name === 'msie') {
const svg: Blob = new Blob([(new XMLSerializer()).serializeToString(controlValue.svg)], { type: 'application/octet-stream' });
window.navigator.msSaveOrOpenBlob(svg, fileName + '.' + type.toLocaleLowerCase());
} else {
this.triggerDownload(fileName, type, url, isDownload);
}
} else if (Browser.info.name === 'msie') {
let canvas: HTMLCanvasElement = element;
if (!isCanvas) {
canvas = this.createCanvas();
}
image = canvas.toDataURL();
if (type === 'PDF') {
this.exportPdf(canvas, orientation, width, height, isDownload, fileName, header, footer);
} else {
this.doexport(type, image, fileName);
}
} else {
const image: HTMLImageElement = new Image();
const ctx: CanvasRenderingContext2D = element.getContext('2d');
image.onload = (() => {
ctx.drawImage(image, 0, 0);
window.URL.revokeObjectURL(url);
if (type === 'PDF') {
this.exportPdf(element, orientation, width, height, isDownload, fileName, header, footer);
} else {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(element.toBlob(null), fileName + '.' + (type as string).toLocaleLowerCase());
} else {
this.triggerDownload(
fileName, type,
element.toDataURL('image/' + type.toLowerCase()),
isDownload
);
}
}
});
image.src = url;
}
if (!isCanvas) {
removeElement(document.getElementById(this.control.element.id + '_canvas'));
}
}
/**
* To get data url for charts.
*
* @param chart
*/
public getDataUrl(chart: Chart | AccumulationChart): { element: HTMLCanvasElement, dataUrl?: string, blobUrl?: string } {
const controlValue: IControlValue = this.getControlsValue([chart]);
let element: HTMLCanvasElement = this.control.svgObject as HTMLCanvasElement;
const isCanvas: boolean = (this.control as Chart).enableCanvas;
if (!isCanvas) {
element = <HTMLCanvasElement>createElement('canvas', {
id: 'ej2-canvas',
attrs: {
'width': controlValue.width.toString(),
'height': controlValue.height.toString()
}
});
}
const url: string = window.URL.createObjectURL(
new Blob(
[(new XMLSerializer()).serializeToString(controlValue.svg)],
{ type: 'image/svg+xml' }
)
);
if (Browser.info.name === 'msie') {
let canvas: HTMLCanvasElement = element;
if (!isCanvas) {
canvas = this.createCanvas();
}
const argsData: IAfterExportEventArgs = {
name: afterExport, cancel: false, dataUrl: element.toDataURL('image/png')
};
chart.trigger(afterExport, argsData);
return { element: canvas, dataUrl: canvas.toDataURL() };
} else {
const image: HTMLImageElement = new Image();
const ctx: CanvasRenderingContext2D = element.getContext('2d');
image.onload = (() => {
ctx.drawImage(image, 0, 0);
window.URL.revokeObjectURL(url);
const argsData: IAfterExportEventArgs = {
name: afterExport, cancel: false, dataUrl: element.toDataURL('image/png')
};
chart.trigger(afterExport, argsData);
return argsData.dataUrl;
});
image.src = url;
return { element: element, blobUrl: url };
}
}
/**
* To trigger the download element
*
* @param fileName
* @param type
* @param url
*/
public triggerDownload(fileName: string, type: ExportType, url: string, isDownload: boolean): void {
createElement('a', {
attrs: {
'download': fileName + '.' + (type as string).toLocaleLowerCase(),
'href': url
}
}).dispatchEvent(new MouseEvent(isDownload ? 'click' : 'move', {
view: window,
bubbles: false,
cancelable: true
}));
}
/**
* To get the maximum size value
*
* @param controls
* @param name
*/
// eslint-disable-next-line max-len
private getControlsValue(controls: (Chart | RangeNavigator | AccumulationChart | StockChart | BulletChart)[], isVertical?: boolean): IControlValue {
let width: number = 0;
let height: number = 0;
const isCanvas: boolean = (this.control as Chart).enableCanvas;
const svgObject: Element = new SvgRenderer('').createSvg({
id: 'Svg_Export_Element',
width: 200, height: 200
});
controls.map((control: Chart | RangeNavigator | AccumulationChart | BulletChart | StockChart) => {
const svg: Node = control.svgObject.cloneNode(true);
const groupEle: Element = control.renderer.createGroup({
style: (isNullOrUndefined(isVertical) || isVertical) ? 'transform: translateY(' + height + 'px)' :
'transform: translateX(' + width + 'px)'
});
const backgroundColor: string = (svg.childNodes[0] as HTMLElement) ? (svg.childNodes[0] as HTMLElement).getAttribute('fill') : 'transparent';
if ((control.theme === 'Tailwind' || control.theme === 'TailwindDark' || control.theme === "Fluent")
&& (backgroundColor === 'rgba(255,255,255, 0.0)' || backgroundColor === 'transparent')) {
(svg.childNodes[0] as HTMLElement).setAttribute('fill', 'rgba(255,255,255, 1)');
}
if (!isCanvas) {
groupEle.appendChild(svg);
}
let top: number = 0;
let left: number = 0;
if ((control as StockChart).stockLegendModule && (control as StockChart).legendSettings.visible) {
if ((control as StockChart).legendSettings.position === "Bottom" || (control as StockChart).legendSettings.position === "Top"
|| (control as StockChart).legendSettings.position === "Auto") {
top += (control as StockChart).stockLegendModule.legendBounds.height;
} else if ((control as StockChart).legendSettings.position === "Left" || (control as StockChart).legendSettings.position === "Right") {
left += (control as StockChart).stockLegendModule.legendBounds.width;
}
}
width = (isNullOrUndefined(isVertical) || isVertical) ? Math.max(control.availableSize.width + left, width) :
width + control.availableSize.width + left;
height = (isNullOrUndefined(isVertical) || isVertical) ? height + control.availableSize.height + top :
Math.max(control.availableSize.height + top, height);
if (!isCanvas) {
svgObject.appendChild(groupEle);
}
});
if (!isCanvas) {
svgObject.setAttribute('width', width + '');
svgObject.setAttribute('height', height + '');
}
return {
'width': width,
'height': height,
'svg': svgObject
};
}
private createCanvas(): HTMLCanvasElement {
const chart: Chart = (this.control as Chart);
this.canvasRender(true, chart);
const canvas: HTMLCanvasElement = <HTMLCanvasElement>chart.svgObject;
this.canvasRender(false, chart);
return canvas;
}
/**
* To convert svg chart into canvas chart to fix export issue in IE
* We cant export svg to other formats in IE
*
* @param enableCanvas
* @param chart
* @param enableCanvas
* @param chart
*/
private canvasRender(enableCanvas: boolean, chart: Chart): void {
chart.enableCanvas = enableCanvas;
chart['preRender']();
chart['render']();
}
// eslint-disable-next-line max-len
private exportPdf(element: HTMLCanvasElement, orientation: PdfPageOrientation, width: number, height: number, isDownload: boolean, fileName: string, header?: IPDFArgs, footer?: IPDFArgs): void {
const document: PdfDocument = new PdfDocument();
const margin: PdfMargins = document.pageSettings.margins;
const pdfDefaultWidth: number = document.pageSettings.width;
const pdfDefaultHeight: number = document.pageSettings.height;
let imageString: string = element.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
document.pageSettings.orientation = orientation;
const exactWidth: number = (pdfDefaultWidth < width) ? (width + margin.left + margin.right) : pdfDefaultWidth;
const exactHeight: number = (pdfDefaultHeight < height) ? (height + margin.top + margin.bottom) : pdfDefaultHeight;
if (header !== undefined) {
const font: PdfStandardFont = new PdfStandardFont(1, header.fontSize || 15);
const pdfHeader: PdfPageTemplateElement = new PdfPageTemplateElement(exactWidth, 40);
pdfHeader.graphics.drawString(header.content + '', font, null, new PdfSolidBrush(new PdfColor(0, 0, 0)), header.x, header.y, null);
document.template.top = pdfHeader;
}
if (footer !== undefined) {
const font: PdfStandardFont = new PdfStandardFont(1, footer.fontSize || 15);
const pdfFooter: PdfPageTemplateElement = new PdfPageTemplateElement(exactWidth, 40);
pdfFooter.graphics.drawString(footer.content + '', font, null, new PdfSolidBrush(new PdfColor(0, 0, 0)), footer.x, footer.y, null);
document.template.bottom = pdfFooter;
}
document.pageSettings.size = new SizeF(exactWidth, exactHeight);
imageString = imageString.slice(imageString.indexOf(',') + 1);
document.pages.add().graphics.drawImage(
new PdfBitmap(imageString), 0, 0, width, height
);
if (isDownload) {
document.save(fileName + '.pdf');
document.destroy();
}
}
private doexport(
type: ExportType, image: string, fileName: string): void {
let images: HTMLElement | string[] = [];
const fileType: string = type || 'JPG';
images = [image];
this.exportImage(images, fileName, fileType, image);
}
private exportImage(images: string[] | HTMLElement, fileName: string, fileType: string, image: string): void {
const buffers: ArrayBuffer[] = [];
const length: number = (!(images instanceof HTMLElement)) ? images.length : 0;
for (let g: number = 0; g < length; g++) {
image = images[g];
image = image.replace(/^data:[a-z]*;,/, '');
const image1: string[] = image.split(',');
const byteString: string = atob(image1[1]);
const buffer: ArrayBuffer = new ArrayBuffer(byteString.length);
const intArray: Uint8Array = new Uint8Array(buffer);
for (let i: number = 0; i < byteString.length; i++) {
intArray[i] = byteString.charCodeAt(i);
}
buffers.push(buffer);
}
for (let j: number = 0; j < buffers.length; j++) {
const b: Blob = new Blob([buffers[j]], { type: 'application/octet-stream' });
if (Browser.info.name === 'msie') {
window.navigator.msSaveOrOpenBlob(b, fileName + '.' + fileType.toLocaleLowerCase());
}
}
}
} | the_stack |
import { abstract } from "../common";
import { nativeClass, NativeClass } from "../nativeclass";
import { float32_t, int32_t } from "../nativetype";
import type { Abilities } from "./abilities";
import { Actor, ActorUniqueID, DimensionId } from "./actor";
import { AttributeId, AttributeInstance } from "./attribute";
import type { BlockPos, Vec3 } from "./blockpos";
import { Certificate } from "./connreq";
import { ArmorSlot, ContainerId, Item, ItemStack, PlayerInventory, PlayerUIContainer } from "./inventory";
import type { NetworkIdentifier } from "./networkidentifier";
import type { Packet } from "./packet";
import { BossEventPacket, ScorePacketInfo, SetDisplayObjectivePacket, SetScorePacket, SetTitlePacket, TextPacket, TransferPacket } from "./packets";
import { DisplaySlot } from "./scoreboard";
import { serverInstance } from "./server";
import type { SerializedSkin } from "./skin";
export class Player extends Actor {
abilities: Abilities;
playerUIContainer: PlayerUIContainer;
/** @deprecated Use `this.getSpawnDimension()` instead */
get respawnDimension(): DimensionId {
return this.getSpawnDimension();
}
/** @deprecated Use `this.getSpawnPosition()` instead */
get respawnPosition(): BlockPos {
return this.getSpawnPosition();
}
deviceId: string;
protected _setName(name: string): void {
abstract();
}
/**
* Adds an item to the player's inventory
* @remarks Player inventory will not be updated. Use ServerPlayer.sendInventory() to update it.
*
* @param itemStack - Item to add
* @returns {boolean} Whether the item has been added successfully (Full inventory can be a cause of failure)
*/
addItem(itemStack: ItemStack): boolean {
abstract();
}
/**
* Teleports the player to another dimension
*
* @param dimensionId - The dimension ID
* @param respawn - Indicates whether the dimension change is based on a respawn (player died in dimension)
*
* @see DimensionId
*/
changeDimension(dimensionId: DimensionId, respawn: boolean): void {
abstract();
}
/**
* Changes the player's name
*
* @param name - New name
*/
setName(name: string): void {
abstract();
}
/**
* Teleports the player to a specified position
* @remarks This function is used when entities teleport players (e.g: ender pearls). Use Actor.teleport() if you want to teleport the player.
*
* @param position - Position to teleport the player to
* @param shouldStopRiding - Defines whether the player should stop riding an entity when teleported
* @param cause - Cause of teleportation
* @param sourceEntityType - Entity type that caused the teleportation
* @param sourceActorId - ActorUniqueID of the source entity
*
* @privateRemarks causes of teleportation are currently unknown.
*/
teleportTo(position: Vec3, shouldStopRiding: boolean, cause: number, sourceEntityType: number, sourceActorId: ActorUniqueID): void {
abstract();
}
/**
* Returns the player's gamemode
*/
getGameType(): GameType {
abstract();
}
/**
* Returns the player's inventory proxy
*/
getInventory(): PlayerInventory {
abstract();
}
/**
* Returns the item currently held by the player
*/
getMainhandSlot(): ItemStack {
abstract();
}
/**
* Returns the item currently in the player's offhand slot
*/
getOffhandSlot(): ItemStack {
abstract();
}
/**
* Returns the player's permission level
* @see PlayerPermission
*/
getPermissionLevel(): PlayerPermission {
abstract();
}
/**
* Returns the player's skin
*/
getSkin(): SerializedSkin {
abstract();
}
/**
* Triggers an item cooldown (e.g: Ender pearl)
* @remarks This function seems to crash the server. use ItemStack.startCoolDown() instead.
*
* @param item - Item to start the cooldown on
*/
startCooldown(item: Item): void {
abstract();
}
/**
* Changes the player's gamemode
*
* @param gameType - Gamemode to switch to
*/
setGameType(gameType: GameType): void {
abstract();
}
/**
* Changes the player's size
* @remarks This function does not update the player's skin size.
*
* @param width - New width
* @param height - New height
*/
setSize(width: number, height: number): void {
abstract();
}
/**
* Sets the player's sleeping status
*/
setSleeping(value: boolean): void {
abstract();
}
/**
* Returns the player's sleeping status
*/
isSleeping(): boolean {
abstract();
}
/**
* Returns whether the player is currently jumping
*/
isJumping(): boolean {
abstract();
}
/**
* Syncs the player's abilities with the client
*/
syncAbilties(): void {
abstract();
}
/**
* Sets the player's respawn position
*
* @param pos - Respawn position
* @param dimension - Dimension
*/
setRespawnPosition(pos: BlockPos, dimension: DimensionId):void {
abstract();
}
/**
* Returns the Dimension ID of the player's respawn point
* @remarks Currently, it's always the Overworld
*/
getSpawnDimension(): DimensionId {
abstract();
}
/**
* Returns the position of the player's respawn point
*/
getSpawnPosition(): BlockPos {
abstract();
}
/**
* Returns the player's certificate
*/
getCertificate(): Certificate {
abstract();
}
}
export class ServerPlayer extends Player {
/** @deprecated Use `this.getNetworkIdentifier()` instead */
networkIdentifier: NetworkIdentifier;
protected _sendInventory(shouldSelectSlot: boolean): void {
abstract();
}
/**
* Applies knockback to the player
*/
knockback(source: Actor, damage: int32_t, xd: float32_t, zd: float32_t, power: float32_t, height: float32_t, heightCap: float32_t): void {
abstract();
}
/**
* Returns the player's NetworkIdentifier
*/
getNetworkIdentifier():NetworkIdentifier {
abstract();
}
/**
* Returns the player's next ContainerId
* @remarks Values range from 1 to 99
*/
nextContainerCounter(): ContainerId {
abstract();
}
/**
* Opens the player's inventory
*/
openInventory(): void {
abstract();
}
/**
* Sends a packet to the player
*
* @param packet - Packet to send
*/
sendNetworkPacket(packet: Packet): void {
abstract();
}
/**
* Updates the player's inventory
* @remarks The shouldSelectSlot parameter seems to be pointless
*
* @param shouldSelectSlot - Defines whether the player should select the currently selected slot (?)
*/
sendInventory(shouldSelectSlot: boolean = false): void {
serverInstance.nextTick().then(() => this._sendInventory(shouldSelectSlot));
}
/**
* Updates a player's attribute
*
* @param id - Attribute ID to update
* @param value - New value of the attribute
*/
setAttribute(id: AttributeId, value: number): AttributeInstance | null {
abstract();
}
/**
* Sets the player's armor
*
* @param slot - Armor slot
* @param itemStack - Armor item to set
*/
setArmor(slot: ArmorSlot, itemStack:ItemStack): void {
abstract();
}
/**
* Sends a chat-like message to the player
* @remarks The message will have this format : <author> message
*
* @param message - Message to send
* @param author - Message author (will be put inside the <>)
*/
sendChat(message: string, author: string): void {
const pk = TextPacket.create();
pk.type = TextPacket.Types.Chat;
pk.name = author;
pk.message = message;
this.sendNetworkPacket(pk);
}
/**
* Sends a whisper-like message to the player
* @remarks The message will have this format : <author> message (same as ServerPlayer.sendChat())
*
* @param message - Message to send
* @param author - Message author (will be put inside the <>)
*/
sendWhisper(message: string, author: string): void {
const pk = TextPacket.create();
pk.type = TextPacket.Types.Chat;
pk.name = author;
pk.message = message;
this.sendNetworkPacket(pk);
}
/**
* Sends a raw message to the player
*
* @param message - Message to send
*/
sendMessage(message: string): void {
const pk = TextPacket.create();
pk.type = TextPacket.Types.Raw;
pk.message = message;
this.sendNetworkPacket(pk);
}
/**
* Sends a jukebox-like popup to the player
* @remarks Does not have a background like other popups.
*
* @param message - Popup text
* @param params - Translation keys to use
*/
sendJukeboxPopup(message: string, params: string[] = []): void {
const pk = TextPacket.create();
pk.type = TextPacket.Types.JukeboxPopup;
pk.message = message;
for (const param of params) {
pk.params.push(param);
}
pk.needsTranslation = true;
this.sendNetworkPacket(pk);
}
/**
* Sends a popup to the player
*
* @param message - Popup text
* @param params - Translation keys to use
*/
sendPopup(message: string, params: string[] = []): void {
const pk = TextPacket.create();
pk.type = TextPacket.Types.Popup;
pk.message = message;
for (const param of params) {
pk.params.push(param);
}
pk.needsTranslation = true;
this.sendNetworkPacket(pk);
}
/**
* Sends a tip-like popup to the player
* @remarks Smaller than a Popup, positioned lower than an Actionbar
*
* @param message - Tip text
* @param params - Translation keys to use
*/
sendTip(message: string, params: string[] = []): void {
const pk = TextPacket.create();
pk.type = TextPacket.Types.Tip;
pk.message = message;
for (const param of params) {
pk.params.push(param);
}
pk.needsTranslation = true;
this.sendNetworkPacket(pk);
}
/**
* Sends a translated message to the player
*
* @param message - Message to send
* @param params - Translation keys
*/
sendTranslatedMessage(message: string, params: string[] = []): void {
const pk = TextPacket.create();
pk.type = TextPacket.Types.Translate;
pk.message = message;
pk.params.push(...params);
pk.needsTranslation = true;
this.sendNetworkPacket(pk);
}
/**
* Displays a bossbar to the player
* @remarks Bossbar percentage doesn't seem to function.
*
* @param title - Text above the bossbar
* @param percent - Bossbar filling percentage
*/
setBossBar(title: string, percent: number): void {
this.removeBossBar();
const pk = BossEventPacket.create();
pk.entityUniqueId = this.getUniqueIdBin();
pk.playerUniqueId = this.getUniqueIdBin();
pk.type = BossEventPacket.Types.Show;
pk.title = title;
pk.healthPercent = percent;
this.sendNetworkPacket(pk);
pk.dispose();
}
/**
* Resets title duration
*/
resetTitleDuration(): void {
const pk = SetTitlePacket.create();
pk.type = SetTitlePacket.Types.Reset;
this.sendNetworkPacket(pk);
pk.dispose();
}
/**
* Sets the title animation duration (in ticks)
* @remarks Will not affect actionbar and other popups.
*
* @param fadeInTime - fade-in duration (in ticks)
* @param stayTime - stay time duration (in ticks)
* @param fadeOutTime - fade-out duration (in ticks)
*/
setTitleDuration(fadeInTime: number, stayTime: number, fadeOutTime: number): void {
const pk = SetTitlePacket.create();
pk.type = SetTitlePacket.Types.AnimationTimes;
pk.fadeInTime = fadeInTime;
pk.stayTime = stayTime;
pk.fadeOutTime = fadeOutTime;
this.sendNetworkPacket(pk);
pk.dispose();
}
/**
* Sends a title to the player
*
* @param title - Title text
* @param subtitle - Subtitle text
*/
sendTitle(title: string, subtitle?: string): void {
const pk = SetTitlePacket.create();
pk.type = SetTitlePacket.Types.Title;
pk.text = title;
this.sendNetworkPacket(pk);
pk.dispose();
if (subtitle) this.sendSubtitle(subtitle);
}
/**
* Sends a subtitle to the player
* @remarks Will not display if there is no title being displayed
*
* @param subtitle - subtitle text
*/
sendSubtitle(subtitle: string): void {
const pk = SetTitlePacket.create();
pk.type = SetTitlePacket.Types.Subtitle;
pk.text = subtitle;
this.sendNetworkPacket(pk);
pk.dispose();
}
/**
* Clears player's title and subtitle
* @remarks Will not affect actionbar and other popups
*/
clearTitle(): void {
const pk = SetTitlePacket.create();
pk.type = SetTitlePacket.Types.Clear;
this.sendNetworkPacket(pk);
pk.dispose();
}
/**
* Sends an actionbar-like popup to the player
* @remarks Smaller than a Popup, positioned higher than a Tip
*
* @param actionbar - Actionbar text
*/
sendActionbar(actionbar: string): void {
const pk = SetTitlePacket.create();
pk.type = SetTitlePacket.Types.Actionbar;
pk.text = actionbar;
this.sendNetworkPacket(pk);
pk.dispose();
}
/**
* Removes the bossbar
*/
removeBossBar(): void {
const pk = BossEventPacket.create();
pk.entityUniqueId = this.getUniqueIdBin();
pk.playerUniqueId = this.getUniqueIdBin();
pk.type = BossEventPacket.Types.Hide;
this.sendNetworkPacket(pk);
pk.dispose();
}
/**
* Displays a scoreboard with custom text & scores
*
* @param title - Scoreboard title
* @param lines - Scoreboard lines
* @param name - Scoreboard name
*
* @example setFakeScoreboard("test", ["my score is 0", ["my score is 3", 3], "my score is 2 as my index is 2"])
*/
setFakeScoreboard(title: string, lines: Array<string | [string, number]>, name: string = `tmp-${new Date().getTime()}`): string {
this.removeFakeScoreboard();
{
const pk = SetDisplayObjectivePacket.create();
pk.displaySlot = DisplaySlot.Sidebar;
pk.objectiveName = name;
pk.displayName = title;
pk.criteriaName = "dummy";
this.sendNetworkPacket(pk);
pk.dispose();
}
{
const pk = SetScorePacket.create();
pk.type = SetScorePacket.Type.CHANGE;
const entries: Array<ScorePacketInfo> = [];
for (const [i, line] of lines.entries()) {
const entry = ScorePacketInfo.construct();
entry.objectiveName = name;
entry.scoreboardId.idAsNumber = i + 1;
entry.type = ScorePacketInfo.Type.FAKE_PLAYER;
if (typeof line === "string") {
entry.score = i + 1;
entry.customName = line;
} else {
entry.score = line[1];
entry.customName = line[0];
}
pk.entries.push(entry);
entries.push(entry);
}
this.sendNetworkPacket(pk);
pk.dispose();
for (const entry of entries) {
entry.destruct();
}
}
return name;
}
/**
* Removes scoreboard
*/
removeFakeScoreboard(): void {
const pk = SetDisplayObjectivePacket.create();
pk.displaySlot = DisplaySlot.Sidebar;
pk.objectiveName = "";
pk.displayName = "";
pk.criteriaName = "dummy";
this.sendNetworkPacket(pk);
pk.dispose();
}
/**
* Transfers the player to another server
*
* @param address - Server address
* @param port - Server port
*/
transferServer(address: string, port: number = 19132): void {
const pk = TransferPacket.create();
pk.address = address;
pk.port = port;
this.sendNetworkPacket(pk);
pk.dispose();
}
}
@nativeClass(0x282)
export class PlayerListEntry extends NativeClass {
static constructWith(player: Player): PlayerListEntry {
abstract();
}
/** @deprecated */
static create(player: Player): PlayerListEntry {
return PlayerListEntry.constructWith(player);
}
}
/**
* Lists possible player gamemodes
*/
export enum GameType {
Survival,
Creative,
Adventure,
SurvivalSpectator,
CreativeSpectator,
Default
}
/**
* Lists possible player permission levels
*/
export enum PlayerPermission {
VISITOR,
MEMBER,
OPERATOR,
CUSTOM
} | the_stack |
import { RowNode } from "./rowNode";
import { GridApi } from "../gridApi";
import { ColumnApi } from "../columns/columnApi";
import { Column } from "./column";
import { IViewportDatasource } from "../interfaces/iViewportDatasource";
import { ICellRenderer, ICellRendererComp, ICellRendererFunc } from "../rendering/cellRenderers/iCellRenderer";
import { ColDef, ColGroupDef, IAggFunc, SuppressKeyboardEventParams } from "./colDef";
import { IDatasource } from "../interfaces/iDatasource";
import { CellPosition } from "./cellPosition";
import { IServerSideDatasource } from "../interfaces/iServerSideDatasource";
import { CsvExportParams, ProcessCellForExportParams, ProcessHeaderForExportParams } from "../interfaces/exportParams";
import {
AsyncTransactionsFlushed,
BodyScrollEvent,
BodyScrollEndEvent,
CellClickedEvent,
CellContextMenuEvent,
CellDoubleClickedEvent,
CellEditingStartedEvent,
CellEditingStoppedEvent,
CellFocusedEvent,
CellKeyDownEvent,
CellKeyPressEvent,
CellMouseDownEvent,
CellMouseOutEvent,
CellMouseOverEvent,
CellValueChangedEvent,
ChartCreated,
ChartDestroyed,
ChartOptionsChanged,
ChartRangeSelectionChanged,
ColumnAggFuncChangeRequestEvent,
ColumnEverythingChangedEvent,
ColumnGroupOpenedEvent,
ColumnMovedEvent,
ColumnPinnedEvent,
ColumnPivotChangedEvent,
ColumnPivotChangeRequestEvent,
ColumnPivotModeChangedEvent,
ColumnResizedEvent,
ColumnRowGroupChangedEvent,
ColumnRowGroupChangeRequestEvent,
ColumnValueChangedEvent,
ColumnValueChangeRequestEvent,
ColumnVisibleEvent,
ComponentStateChangedEvent,
DisplayedColumnsChangedEvent,
DragStartedEvent,
DragStoppedEvent,
ExpandCollapseAllEvent,
FilterOpenedEvent,
FilterChangedEvent,
FilterModifiedEvent,
FirstDataRenderedEvent,
GridColumnsChangedEvent,
GridReadyEvent,
ModelUpdatedEvent,
NewColumnsLoadedEvent,
PaginationChangedEvent,
PasteEndEvent,
PasteStartEvent,
PinnedRowDataChangedEvent,
RangeSelectionChangedEvent,
RowClickedEvent,
RowDataChangedEvent,
RowDataUpdatedEvent,
RowDoubleClickedEvent,
RowDragEvent,
RowEditingStartedEvent,
RowEditingStoppedEvent,
RowGroupOpenedEvent,
RowSelectedEvent,
RowValueChangedEvent,
SelectionChangedEvent,
SortChangedEvent,
ToolPanelVisibleChangedEvent,
ViewportChangedEvent,
VirtualColumnsChangedEvent,
VirtualRowRemovedEvent,
GridSizeChangedEvent,
FullWidthCellKeyPressEvent,
FullWidthCellKeyDownEvent
} from "../events";
import { IComponent } from "../interfaces/iComponent";
import { ILoadingOverlayComp } from "../rendering/overlays/loadingOverlayComponent";
import { INoRowsOverlayComp } from "../rendering/overlays/noRowsOverlayComponent";
import { StatusPanelDef } from "../interfaces/iStatusPanel";
import { SideBarDef } from "./sideBar";
import { ChartMenuOptions } from "../interfaces/iChartOptions";
import { AgChartTheme, AgChartThemeOverrides } from "../interfaces/iAgChartOptions";
import { ServerSideTransaction } from "../interfaces/serverSideTransaction";
import { HeaderPosition } from "../headerRendering/common/headerPosition";
import { ExcelExportParams, ExcelStyle } from "../interfaces/iExcelCreator";
import { ILoadingCellRendererParams } from "../rendering/cellRenderers/loadingCellRenderer";
export interface GridOptions {
// ******************************************************************************************************
// If you change the properties on this interface, you must also update PropertyKeys to be consistent. *
// ******************************************************************************************************
// *** Accessories *** //
/** Specifies the status bar components to use in the status bar. */
statusBar?: { statusPanels: StatusPanelDef[]; };
/** Specifies the side bar components. */
sideBar?: SideBarDef | string | boolean | null;
/** Set to `true` to not show the context menu. Use if you don't want to use the default 'right click' context menu. */
suppressContextMenu?: boolean;
/**
* When using `suppressContextMenu`, you can use the `onCellContextMenu` function to provide your own code to handle cell `contextmenu` events.
* This flag is useful to prevent the browser from showing its default context menu.
*/
preventDefaultOnContextMenu?: boolean;
/** Allows context menu to show, even when `Ctrl` key is held down. */
allowContextMenuWithControlKey?: boolean;
/** Set to `true` to always show the column menu button, rather than only showing when the mouse is over the column header. */
suppressMenuHide?: boolean;
/** Set to `true` to use the browser's default tooltip instead of using the grid's Tooltip Component */
enableBrowserTooltips?: boolean;
/**
* The delay in milliseconds that it takes for tooltips to show up once an element is hovered over.
* **Note:** This property does not work if `enableBrowserTooltips` is `true`.
*/
tooltipShowDelay?: number;
/** Set to `true` to have tooltips follow the cursor once they are displayed. */
tooltipMouseTrack?: boolean;
/** DOM element to use as the popup parent for grid popups (context menu, column menu etc). */
popupParent?: HTMLElement;
// *** Clipboard *** //
/** Set to `true` to also include headers when copying to clipboard using `Ctrl + C` clipboard. */
copyHeadersToClipboard?: boolean;
/** Specify the deliminator to use when copying to clipboard. */
clipboardDeliminator?: string;
/** Set to `true` to only have the range selection, and not row selection, copied to clipboard. */
suppressCopyRowsToClipboard?: boolean;
/** Set to `true` to work around a bug with Excel (Windows) that adds an extra empty line at the end of ranges copied to the clipboard. */
suppressLastEmptyLineOnPaste?: boolean;
/** Set to `true` to turn off paste operations within the grid. */
suppressClipboardPaste?: boolean;
/** Set to `true` to stop the grid trying to use the Clipboard API, if it is blocked, and immediately fallback to the workaround. */
suppressClipboardApi?: boolean;
// *** Columns *** //
/** Array of Column / Column Group definitions. */
columnDefs?: (ColDef | ColGroupDef)[] | null;
/** A default column definition. Items defined in the actual column definitions get precedence. */
defaultColDef?: ColDef;
/** A default column group definition. All column group definitions will use these properties. Items defined in the actual column group definition get precedence. */
defaultColGroupDef?: Partial<ColGroupDef>;
/** An object map of custom column types which contain groups of properties that column definitions can inherit by referencing in their `type` property. */
columnTypes?: { [key: string]: ColDef; };
/** Keeps the order of Columns maintained after new Column Definitions are updated. */
maintainColumnOrder?: boolean;
/** If `true`, then dots in field names (e.g. `address.firstline`) are not treated as deep references. Allows you to use dots in your field name if you prefer. */
suppressFieldDotNotation?: boolean;
/** @deprecated */
deltaColumnMode?: boolean;
/** @deprecated */
applyColumnDefOrder?: boolean; // is now the default, to turn off, set maintainColumnOrder
/** @deprecated */
immutableColumns?: boolean;
/** @deprecated */
suppressSetColumnStateEvents?: boolean;
/** @deprecated */
suppressColumnStateEvents?: boolean;
/** @deprecated Set via `defaultColDef.width` */
colWidth?: number;
/** @deprecated Set via `defaultColDef.minWidth` */
minColWidth?: number;
/** @deprecated Set via `defaultColDef.maxWidth` */
maxColWidth?: number;
// *** Column Headers *** //
/** The height in pixels for the row containing the column label header. Default: `25` */
headerHeight?: number;
/** The height in pixels for the rows containing header column groups. If not specified, it uses `headerHeight`. */
groupHeaderHeight?: number;
/** The height in pixels for the row containing the floating filters. Default: `20` */
floatingFiltersHeight?: number;
/** The height in pixels for the row containing the columns when in pivot mode. If not specified, it uses `headerHeight`. */
pivotHeaderHeight?: number;
/** The height in pixels for the row containing header column groups when in pivot mode. If not specified, it uses `groupHeaderHeight`. */
pivotGroupHeaderHeight?: number;
// *** Column Moving *** //
/** Allow reordering and pinning columns by dragging columns from the Columns Tool Panel to the grid. */
allowDragFromColumnsToolPanel?: boolean;
/** Set to `true` to suppress column moving, i.e. to make the columns fixed position. */
suppressMovableColumns?: boolean;
/** If `true`, the `ag-column-moving` class is not added to the grid while columns are moving. In the default themes, this results in no animation when moving columns. */
suppressColumnMoveAnimation?: boolean;
/** If `true`, when you drag a column out of the grid (e.g. to the group zone) the column is not hidden. */
suppressDragLeaveHidesColumns?: boolean;
// *** Column Sizing *** //
/** Set to `'shift'` to have shift-resize as the default resize operation (same as user holding down `Shift` while resizing). */
colResizeDefault?: string;
/** Suppresses auto-sizing columns for columns. In other words, double clicking a column's header's edge will not auto-size. */
suppressAutoSize?: boolean;
/**
* Number of pixels to add to a column width after the [auto-sizing](/column-sizing/#auto-size-columns) calculation.
* Set this if you want to add extra room to accommodate (for example) sort icons, or some other dynamic nature of the header.
*/
autoSizePadding?: number;
/** Set this to `true` to skip the `headerName` when `autoSize` is called by default. */
skipHeaderOnAutoSize?: boolean;
// *** Components *** //
/** A map of component names to plain JavaScript components. */
components?: { [p: string]: any; };
/** A map of component names to framework (Angular, React, Vue etc.) components. */
frameworkComponents?: { [p: string]: { new(): any; }; } | any;
// *** Editing *** //
/** Set to `'fullRow'` to enable Full Row Editing. Otherwise leave blank to edit one cell at a time. */
editType?: string;
/** Set to `true` to enable Single Click Editing for cells, to start editing with a single click. */
singleClickEdit?: boolean;
/** Set to `true` so that neither single nor double click starts editing. */
suppressClickEdit?: boolean;
/**
* Set this to `true` to stop cell editing when grid loses focus.
* The default is that the grid stays editing until focus goes onto another cell. For inline (non-popup) editors only.
*/
stopEditingWhenCellsLoseFocus?: boolean;
/**
* Set to `true` along with `enterMovesDownAfterEdit` to have Excel-style behaviour for the `Enter` key.
* i.e. pressing the `Enter` key will move down to the cell beneath.
*/
enterMovesDown?: boolean;
/**
* Set to `true` along with `enterMovesDown` to have Excel-style behaviour for the 'Enter' key.
* i.e. pressing the Enter key will move down to the cell beneath.
*/
enterMovesDownAfterEdit?: boolean;
/** Set to `true` to enable Undo / Redo while editing. */
undoRedoCellEditing?: boolean;
/** Set the size of the undo / redo stack. */
undoRedoCellEditingLimit?: number;
/** @deprecated Use stopEditingWhenCellsLoseFocus instead */
stopEditingWhenGridLosesFocus?: boolean;
// *** Export *** //
/** A default configuration object used to export to CSV. */
defaultCsvExportParams?: CsvExportParams;
/** Prevents the user from exporting the grid to CSV. */
suppressCsvExport?: boolean;
/** A default configuration object used to export to Excel. */
defaultExcelExportParams?: ExcelExportParams;
/** Prevents the user from exporting the grid to Excel. */
suppressExcelExport?: boolean;
/** A list (array) of Excel styles to be used when exporting to Excel with styles. */
excelStyles?: ExcelStyle[];
/** @deprecated Use defaultCsvExportParams or defaultExcelExportParams */
defaultExportParams?: CsvExportParams | ExcelExportParams;
// *** Filter *** //
/** Rows are filtered using this text as a quick filter. */
quickFilterText?: string;
/** Set to `true` to turn on the quick filter cache, used to improve performance when using the quick filter. */
cacheQuickFilter?: boolean;
/** Set to `true` to override the default tree data filtering behaviour to instead exclude child nodes from filter results. */
excludeChildrenWhenTreeDataFiltering?: boolean;
/** @deprecated Use floatingFilter on the colDef instead */
floatingFilter?: boolean;
/** @deprecated */
enableOldSetFilterModel?: boolean;
// *** Integrated Charts *** //
/** Set to `true` to Enable Charts. */
enableCharts?: boolean;
/** The list of chart themes to be used. */
chartThemes?: string[];
/** A map containing custom chart themes. */
customChartThemes?: { [name: string]: AgChartTheme };
/** Chart theme overrides applied to all themes. */
chartThemeOverrides?: AgChartThemeOverrides;
// *** Loading Cell Renderers *** //
/** `cellRenderer` to use when data is loading via a DataSource. */
loadingCellRenderer?: { new(): ICellRenderer; } | string;
/** Framework `cellRenderer` to use when data is loading via a DataSource. */
loadingCellRendererFramework?: any;
/** Params to be passed to loading cell renderer component. */
loadingCellRendererParams?: any;
/** Callback to select which loading cell renderer to be used when data is loading via a DataSource. */
loadingCellRendererSelector?: LoadingCellRendererSelectorFunc;
// *** Localisation *** //
// just set once
/** A map of key->value pairs for localising text within the grid. */
localeText?: { [key: string]: string };
// *** Master Detail *** //
/** Set to `true` to enable Master Detail. */
masterDetail?: boolean;
/** Set to `true` to keep detail rows for when they are displayed again. */
keepDetailRows?: boolean;
/** Sets the number of details rows to keep. */
keepDetailRowsCount?: number;
/** Provide a custom `detailCellRenderer` to use when a master row is expanded. */
detailCellRenderer?: { new(): ICellRendererComp; } | ICellRendererFunc | string;
/** Framework `detailCellRenderer` to use when a master row is expanded. */
detailCellRendererFramework?: any;
/** Specifies the params to be used by the Detail Cell Renderer. Can also be a function that provides the params to enable dynamic definitions of the params. */
detailCellRendererParams?: any;
/** Set fixed height in pixels for each detail row. */
detailRowHeight?: number;
/** Set to `true` to have the detail grid dynamically change it's height to fit it's rows. */
detailRowAutoHeight?: boolean;
// *** Miscellaneous *** //
// changeable, but no immediate impact
/** Provides a context object that is provided to different callbacks the grid uses. Used for passing additional information to the callbacks by your application. */
context?: any;
/** A list of grids to treat as Aligned Grids. If grids are aligned then the columns and horizontal scrolling will be kept in sync. */
alignedGrids?: GridOptions[];
/** Change this value to set the tabIndex order of the Grid within your application. Default: `0` */
tabIndex?: number;
/**
* The number of rows rendered outside the viewable area the grid renders.
* Having a buffer means the grid will have rows ready to show as the user slowly scrolls vertically.
* Default: `10`
*/
rowBuffer?: number;
/** Set to `true` to turn on the value cache. */
valueCache?: boolean;
/** Set to `true` to configure the value cache to not expire after data updates. */
valueCacheNeverExpires?: boolean;
/** Set to `true` to allow cell expressions. */
enableCellExpressions?: boolean;
/**
* If `true`, row nodes do not have their parents set.
* The grid doesn't use the parent reference, but it is included to help the client code navigate the node tree if it wants by providing bi-direction navigation up and down the tree.
* If this is a problem (e.g. if you need to convert the tree to JSON, which does not allow cyclic dependencies) then set this to `true`.
*/
suppressParentsInRowNodes?: boolean;
/** Disables touch support (but does not remove the browser's efforts to simulate mouse events on touch). */
suppressTouch?: boolean;
/** Set to `true` to not set focus back on the grid after a refresh. This can avoid issues where you want to keep the focus on another part of the browser. */
suppressFocusAfterRefresh?: boolean;
/** Disables the asynchronous nature of the events introduced in v10, and makes them synchronous. This property only exists for the purpose of supporting legacy code which has a dependency on synchronous events from earlier versions (v9 or earlier) of AG Grid. **It is strongly recommended that you do not change this property unless you have legacy issues.** */
suppressAsyncEvents?: boolean;
/** The grid will check for `ResizeObserver` and use it if it exists in the browser, otherwise it will use the grid's alternative implementation. Some users reported issues with Chrome's `ResizeObserver`. Use this property to always use the grid's alternative implementation should such problems exist. */
suppressBrowserResizeObserver?: boolean;
/** Disables showing a warning message in the console if using a `gridOptions` or `colDef` property that doesn't exist. */
suppressPropertyNamesCheck?: boolean;
/** Disables change detection. */
suppressChangeDetection?: boolean;
/** Set this to `true` to enable debug information from the grid and related components. Will result in additional logging being output, but very useful when investigating problems. */
debug?: boolean;
// *** Overlays *** //
/** Provide a template for 'loading' overlay. */
overlayLoadingTemplate?: string;
/** Provide a custom loading overlay component. */
loadingOverlayComponent?: { new(): ILoadingOverlayComp; } | string;
/** Same as `loadingOverlayComponent` but for a framework component. */
loadingOverlayComponentFramework?: any;
/** Customise the parameters provided to the loading overlay component. */
loadingOverlayComponentParams?: any;
/** Disables the 'loading' overlay. */
suppressLoadingOverlay?: boolean;
/** Provide a template for 'no rows' overlay. */
overlayNoRowsTemplate?: string;
/** Provide a custom no rows overlay component */
noRowsOverlayComponent?: { new(): INoRowsOverlayComp; } | string;
/** Same as `noRowsOverlayComponent` but for a framework component. */
noRowsOverlayComponentFramework?: any;
/** Customise the parameters provided to the no rows overlay component. */
noRowsOverlayComponentParams?: any;
/** Disables the 'no rows' overlay. */
suppressNoRowsOverlay?: boolean;
// *** Pagination *** //
/** Set whether pagination is enabled. */
pagination?: boolean;
/** How many rows to load per page. If `paginationAutoPageSize` is specified, this property is ignored. Default: `100` */
paginationPageSize?: number;
/** Set to `true` so that the number of rows to load per page is automatically adjusted by the grid so each page shows enough rows to just fill the area designated for the grid. If `false`, `paginationPageSize` is used. */
paginationAutoPageSize?: boolean;
/** Set to `true` to have pages split children of groups when using Row Grouping or detail rows with Master Detail. */
paginateChildRows?: boolean;
/**
* If `true`, the default grid controls for navigation are hidden.
* This is useful if `pagination=true` and you want to provide your own pagination controls.
* Otherwise, when `pagination=true` the grid automatically shows the necessary controls at the bottom so that the user can navigate through the different pages.
*/
suppressPaginationPanel?: boolean;
// *** Pivot and Aggregation *** //
/** Set to `true` to enable pivot mode. */
pivotMode?: boolean;
/** When to show the 'pivot panel' (where you drag rows to pivot) at the top. Note that the pivot panel will never show if `pivotMode` is off. */
pivotPanelShow?: string;
/** When set and the grid is in pivot mode, automatically calculated totals will appear within the Pivot Column Groups, in the position specified. */
pivotColumnGroupTotals?: string;
/** When set and the grid is in pivot mode, automatically calculated totals will appear for each value column in the position specified. */
pivotRowTotals?: string;
/** If `true`, the grid will not swap in the grouping column when pivoting. Useful if pivoting using Server Side Row Model or Viewport Row Model and you want full control of all columns including the group column. */
pivotSuppressAutoColumn?: boolean;
/** When enabled, pivot column groups will appear 'fixed', without the ability to expand and collapse the column groups. */
suppressExpandablePivotGroups?: boolean;
/** If `true`, then row group, pivot and value aggregation will be read-only from the GUI. The grid will display what values are used for each, but will not allow the user to change the selection. */
functionsReadOnly?: boolean;
/** A map of 'function name' to 'function' for custom aggregation functions. */
aggFuncs?: { [key: string]: IAggFunc; };
/** When `true`, column headers won't include the `aggFunc` name, e.g. `'sum(Bank Balance)`' will just be `'Bank Balance'`. */
suppressAggFuncInHeader?: boolean;
/** When `true`, the aggregations won't be computed for the root node of the grid. */
suppressAggAtRootLevel?: boolean;
/** When using change detection, only the updated column will be re-aggregated. */
aggregateOnlyChangedColumns?: boolean;
/** Set to `true` so that aggregations are not impacted by filtering. */
suppressAggFilteredOnly?: boolean;
// *** Rendering *** //
/** Set to `true` to enable Row Animation. */
animateRows?: boolean;
/** Set to `true` to have cells flash after data changes. */
enableCellChangeFlash?: boolean;
/**
* To be used in combination with `enableCellChangeFlash`, this configuration will set the delay in milliseconds of how long a cell should remain in its \"flashed\" state.
* Default: `500`
*/
cellFlashDelay?: number;
/**
* To be used in combination with `enableCellChangeFlash`, this configuration will set the delay in milliseconds of how long the \"flashed\" state animation takes to fade away after the timer set by `cellFlashDelay` has completed.
* Default: `1000`
*/
cellFadeDelay?: number;
/** Set to `true` to have cells flash after data changes even when the change is due to filtering. */
allowShowChangeAfterFilter?: boolean;
/**
* Switch between layout options: `normal`, `autoHeight`, `print`.
* Default: `normal`
*/
domLayout?: string;
/** When `true`, the order of rows and columns in the DOM are consistent with what is on screen. */
ensureDomOrder?: boolean;
/** Set to `true` to operate the grid in RTL (Right to Left) mode. */
enableRtl?: boolean;
/** Set to `true` so that the grid doesn't virtualise the columns. For example, if you have 100 columns, but only 10 visible due to scrolling, all 100 will always be rendered. */
suppressColumnVirtualisation?: boolean;
/** By default the grid has a limit of rendering a maximum of 500 rows at once (remember the grid only renders rows you can see, so unless your display shows more than 500 rows without vertically scrolling this will never be an issue).
* <br />**This is only relevant if you are manually setting `rowBuffer` to a high value (rendering more rows than can be seen) or if your grid height is able to display more than 500 rows at once.** */
suppressMaxRenderedRowRestriction?: boolean;
// *** Row Drag and Drop *** //
/** Set to `true` to enable Managed Row Dragging. */
rowDragManaged?: boolean;
/** Set to `true` to suppress row dragging. */
suppressRowDrag?: boolean;
/** Set to `true` to suppress moving rows while dragging the `rowDrag` waffle. This option highlights the position where the row will be placed and it will only move the row on mouse up. */
suppressMoveWhenRowDragging?: boolean;
/** Set to `true` to enable clicking and dragging anywhere on the row without the need for a drag handle. */
rowDragEntireRow?: boolean;
/** Set to `true` to enable dragging multiple rows at the same time. */
rowDragMultiRow?: boolean;
// *** Row Full Width *** //
/** Sets the Cell Renderer to use for full width rows. */
fullWidthCellRenderer?: { new(): ICellRendererComp; } | ICellRendererFunc | string;
/** Same as `fullWidthCellRenderer` but for a framework component. */
fullWidthCellRendererFramework?: any;
/** Customise the parameters provided to the `fullWidthCellRenderer` component. */
fullWidthCellRendererParams?: any;
/** Set to `true` to have the detail grid embedded in the master grid's container and so link their horizontal scrolling. */
embedFullWidthRows?: boolean;
/** @deprecated */
deprecatedEmbedFullWidthRows?: boolean;
// *** Row Grouping *** //
/**
* Specifies how the results of row grouping should be displayed.
*
* The options are:
*
* `'singleColumn'`: single group column automatically added by the grid.
* `'multipleColumns'`: a group column per row group is added automatically.
* `'groupRows'`: group rows are automatically added instead of group columns.
* `'custom'`: informs the grid that group columns will be provided.
*/
groupDisplayType?: RowGroupingDisplayType;
/** If grouping, set to the number of levels to expand by default, e.g. `0` for none, `1` for first level only, etc. Set to `-1` to expand everything. */
groupDefaultExpanded?: number;
/** Allows specifying the group 'auto column' if you are not happy with the default. If grouping, this column definition is included as the first column in the grid. If not grouping, this column is not included. */
autoGroupColumnDef?: ColDef;
/** When `true`, preserves the current group order when sorting on non-group columns. */
groupMaintainOrder?: boolean;
/** When `true`, if you select a group, the children of the group will also be selected. */
groupSelectsChildren?: boolean;
/**
* If grouping, this controls whether to show a group footer when the group is expanded.
* If `true`, then by default, the footer will contain aggregate data (if any) when shown and the header will be blank.
* When closed, the header will contain the aggregate data regardless of this setting (as the footer is hidden anyway).
* This is handy for 'total' rows, that are displayed below the data when the group is open, and alongside the group when it is closed.
*/
groupIncludeFooter?: boolean;
/** Set to `true` to show a 'grand total' group footer across all groups. */
groupIncludeTotalFooter?: boolean;
/** If `true`, and showing footer, aggregate data will always be displayed at both the header and footer levels. This stops the possibly undesirable behaviour of the header details 'jumping' to the footer on expand. */
groupSuppressBlankHeader?: boolean;
/** If using `groupSelectsChildren`, then only the children that pass the current filter will get selected. */
groupSelectsFiltered?: boolean;
/** Shows the open group in the group column for non-group rows. */
showOpenedGroup?: boolean;
/** Set to `true` to collapse groups that only have one child. */
groupRemoveSingleChildren?: boolean;
/** Set to `true` to collapse lowest level groups that only have one child. */
groupRemoveLowestSingleChildren?: boolean;
/** Set to `true` to hide parents that are open. When used with multiple columns for showing groups, it can give a more pleasing user experience. */
groupHideOpenParents?: boolean;
/** When to show the 'row group panel' (where you drag rows to group) at the top. */
rowGroupPanelShow?: string;
/** Sets the Cell Renderer to use when `groupDisplayType = 'groupRows'`. */
groupRowRenderer?: { new(): ICellRendererComp; } | ICellRendererFunc | string;
/** Same as `groupRowRenderer` but for a framework component. */
groupRowRendererFramework?: any;
/** Customise the parameters provided to the `groupRowRenderer` component. */
groupRowRendererParams?: any;
/** By default, when a column is un-grouped, i.e. using the Row Group Panel, it is made visible in the grid. This property stops the column becoming visible again when un-grouping. */
suppressMakeColumnVisibleAfterUnGroup?: boolean;
/** Set to `true` to enable the Grid to work with Tree Data. You must also implement the `getDataPath(data)` callback. */
treeData?: boolean;
/** @deprecated - this is now groupRowRendererParams.innerRenderer */
groupRowInnerRenderer?: { new(): ICellRendererComp; } | ICellRendererFunc | string;
/** @deprecated - this is now groupRowRendererParams.innerRendererFramework */
groupRowInnerRendererFramework?: any;
/** @deprecated - Use groupDisplayType = 'multipleColumns' instead */
groupMultiAutoColumn?: boolean;
/** @deprecated - Use groupDisplayType = 'groupRows' instead */
groupUseEntireRow?: boolean;
/** @deprecated - Use groupDisplayType = 'custom' instead */
groupSuppressAutoColumn?: boolean;
/** @deprecated - no longer needed, transaction updates keep group state */
rememberGroupStateWhenNewData?: boolean;
// *** Row Pinning *** //
/** Data to be displayed as pinned top rows in the grid. */
pinnedTopRowData?: any[];
/** Data to be displayed as pinned bottom rows in the grid. */
pinnedBottomRowData?: any[];
// *** Row Model *** //
/** Sets the row model type. */
rowModelType?: string;
// *** Row Model: Client-side *** //
// changeable with impact
/** Set the data to be displayed as rows in the grid. */
rowData?: any[] | null;
/** Enables Immutable Data mode, for compatibility with immutable stores. */
immutableData?: boolean;
/** How many milliseconds to wait before executing a batch of async transactions. */
asyncTransactionWaitMillis?: number;
/** Prevents Transactions changing sort, filter, group or pivot state when transaction only contains updates. */
suppressModelUpdateAfterUpdateTransaction?: boolean;
/** @deprecated */
deltaRowDataMode?: boolean;
/** @deprecated use asyncTransactionWaitMillis instead */
batchUpdateWaitMillis?: number;
// *** Row Model: Infinite / Server-side *** //
/** Provide the datasource for infinite scrolling. */
datasource?: IDatasource;
/**
* How many extra blank rows to display to the user at the end of the dataset, which sets the vertical scroll and then allows the grid to request viewing more rows of data.
* Default: `1`
*/
cacheOverflowSize?: number;
/**
* How many extra blank rows to display to the user at the end of the dataset, which sets the vertical scroll and then allows the grid to request viewing more rows of data.
* Default: `1`
*/
infiniteInitialRowCount?: number;
/** Whether to use Full Store or Partial Store for storing rows. */
serverSideStoreType?: ServerSideStoreType;
/**
* How many rows for each block in the store, i.e. how many rows returned from the server at a time.
* Default: `100`
*/
cacheBlockSize?: number;
/** How many blocks to keep in the store. Default is no limit, so every requested block is kept. Use this if you have memory concerns, and blocks that were least recently viewed will be purged when the limit is hit. The grid will additionally make sure it has all the blocks needed to display what is currently visible, in case this property is set to a low value. */
maxBlocksInCache?: number;
/**
* How many requests to hit the server with concurrently. If the max is reached, requests are queued.
*/
maxConcurrentDatasourceRequests?: number;
/** How many milliseconds to wait before loading a block. Useful when scrolling over many rows, spanning many Partial Store blocks, as it prevents blocks loading until scrolling has settled. */
blockLoadDebounceMillis?: number;
/** When enabled, closing group rows will remove children of that row. Next time the row is opened, child rows will be read from the datasource again. This property only applies when there is Row Grouping */
purgeClosedRowNodes?: boolean;
/** Provide the `serverSideDatasource` for server side row model. */
serverSideDatasource?: IServerSideDatasource;
/** When enabled, always refreshes top level groups regardless of which column was sorted. This property only applies when there is Row Grouping. */
serverSideSortingAlwaysResets?: boolean;
/** When enabled, always refreshes stores after filter has changed. Used by Full Store only, to allow Server-Side Filtering. */
serverSideFilteringAlwaysResets?: boolean;
/** @deprecated */
suppressEnterpriseResetOnNewColumns?: boolean;
// *** Row Model: Viewport *** //
/** To use the viewport row model you need to provide the grid with a `viewportDatasource`. */
viewportDatasource?: IViewportDatasource;
/** When using viewport row model, sets the page size for the viewport. */
viewportRowModelPageSize?: number;
/** When using viewport row model, sets the buffer size for the viewport. */
viewportRowModelBufferSize?: number;
// *** Scrolling *** //
/** Set to `true` to always show the horizontal scrollbar. */
alwaysShowHorizontalScroll?: boolean;
/** Set to `true` to always show the vertical scrollbar. */
alwaysShowVerticalScroll?: boolean;
/** Set to `true` to debounce the vertical scrollbar. Can provide smoother scrolling on older browsers, e.g. Internet Explorer. */
debounceVerticalScrollbar?: boolean;
/** Set to `true` to never show the horizontal scroll. This is useful if the grid is aligned with another grid and will scroll when the other grid scrolls. (Should not be used in combination with `alwaysShowHorizontalScroll`.) */
suppressHorizontalScroll?: boolean;
/** When `true`, the grid will not scroll to the top when new row data is provided. Use this if you don't want the default behaviour of scrolling to the top every time you load new data. */
suppressScrollOnNewData?: boolean;
/** When `true`, the grid will not allow mousewheel / touchpad scroll when popup elements are present. */
suppressScrollWhenPopupsAreOpen?: boolean;
/** When `true`, the grid will not use animation frames when drawing rows while scrolling. Use this if the grid is working fast enough that you don't need animation frames and you don't want the grid to flicker. */
suppressAnimationFrame?: boolean;
/** If `true`, middle clicks will result in `click` events for cells and rows. Otherwise the browser will use middle click to scroll the grid.<br />**Note:** Not all browsers fire `click` events with the middle button. Most will fire only `mousedown` and `mouseup` events, which can be used to focus a cell, but will not work to call the `onCellClicked` function. */
suppressMiddleClickScrolls?: boolean;
/** If `true`, mouse wheel events will be passed to the browser. Useful if your grid has no vertical scrolls and you want the mouse to scroll the browser page. */
suppressPreventDefaultOnMouseWheel?: boolean;
/** Tell the grid how wide in pixels the scrollbar is, which is used in grid width calculations. Set only if using non-standard browser-provided scrollbars, so the grid can use the non-standard size in its calculations. */
scrollbarWidth?: number;
// *** Selection *** //
/** Type of Row Selection: `single`, `multiple`. */
rowSelection?: string;
/** Set to `true` to allow multiple rows to be selected using single click. */
rowMultiSelectWithClick?: boolean;
/** If `true`, rows will not be deselected if you hold down `Ctrl` and click the row or press `Space`. */
suppressRowDeselection?: boolean;
/** If `true`, row selection won't happen when rows are clicked. Use when you only want checkbox selection. */
suppressRowClickSelection?: boolean;
/** If `true`, cells won't be selectable. This means cells will not get keyboard focus when you click on them. */
suppressCellSelection?: boolean;
/** If `true`, only a single range can be selected. */
suppressMultiRangeSelection?: boolean;
/**
* Set to `true` to be able to select the text within cells.
*
* **Note:** When this is set to `true`, the clipboard service is disabled.
*/
enableCellTextSelection?: boolean;
/** Set to `true` to enable Range Selection. */
enableRangeSelection?: boolean;
/** Set to `true` to enable the Range Handle. */
enableRangeHandle?: boolean;
/** Set to `true` to enable the Fill Handle. */
enableFillHandle?: boolean;
/** Set to `'x'` to force the fill handle direction to horizontal, or set to `'y'` to force the fill handle direction to vertical. */
fillHandleDirection?: string;
/** Set this to `true` to prevent cell values from being cleared when the Range Selection is reduced by the Fill Handle. */
suppressClearOnFillReduction?: boolean;
/** @deprecated - rowDeselection is now true by default and should be suppressed by using suppressRowDeselection */
rowDeselection?: boolean;
// *** Sorting *** //
/** Array defining the order in which sorting occurs (if sorting is enabled). Values can be `'asc'`, `'desc'` or `null`. For example: `sortingOrder: ['asc', 'desc']`. */
sortingOrder?: (string | null)[];
/** Set to `true` to specify that the sort should take accented characters into account. If this feature is turned on the sort will be slower. */
accentedSort?: boolean;
/** Set to `true` to show the 'no sort' icon. */
unSortIcon?: boolean;
/** Set to `true` to suppress multi-sort when the user shift-clicks a column header. */
suppressMultiSort?: boolean;
/** Set to `'ctrl'` to have multi sorting work using the `Ctrl` (or `Command ⌘` for Mac) key. */
multiSortKey?: string;
/** Set to `true` to suppress sorting of un-sorted data to match original row data. */
suppressMaintainUnsortedOrder?: boolean;
// *** Styling *** //
/** Icons to use inside the grid instead of the grid's default icons. */
icons?: { [key: string]: Function | string; };
/** Default row height in pixels. */
rowHeight?: number;
/** The style properties to apply to all rows. Set to an object of key (style names) and values (style values) */
rowStyle?: RowStyle;
/** CSS class(es) for all rows. Provide either a string (class name) or array of strings (array of class names). */
rowClass?: string | string[];
/** Rules which can be applied to include certain CSS classes. */
rowClassRules?: RowClassRules;
/** Set to `true` to not highlight rows by adding the `ag-row-hover` CSS class. */
suppressRowHoverHighlight?: boolean;
/** Uses CSS `top` instead of CSS `transform` for positioning rows. Useful if the transform function is causing issues such as used in row spanning. */
suppressRowTransform?: boolean;
/** Set to `true` to highlight columns by adding the `ag-column-hover` CSS class. */
columnHoverHighlight?: boolean;
deltaSort?: boolean;
treeDataDisplayType?: TreeDataDisplayType;
angularCompileRows?: boolean;
angularCompileFilters?: boolean;
functionsPassive?: boolean;
enableGroupEdit?: boolean;
// *****************************************************************************************************
// If you change the callbacks on this interface, you must also update PropertyKeys to be consistent. *
// *****************************************************************************************************
// *** Accessories *** //
/** For customising the context menu. */
getContextMenuItems?: GetContextMenuItems;
/** For customising the main 'column header' menu. */
getMainMenuItems?: GetMainMenuItems;
/** Allows user to process popups after they are created. Applications can use this if they want to, for example, reposition the popup. */
postProcessPopup?: (params: PostProcessPopupParams) => void;
// *** Clipboard *** //
/** Allows you to process cells for the clipboard. Handy if for example you have `Date` objects that need to have a particular format if importing into Excel. */
processCellForClipboard?(params: ProcessCellForExportParams): any;
/** Allows you to process header values for the clipboard. */
processHeaderForClipboard?(params: ProcessHeaderForExportParams): any;
/** Allows you to process cells from the clipboard. Handy if for example you have number fields, and want to block non-numbers from getting into the grid. */
processCellFromClipboard?(params: ProcessCellForExportParams): any;
/** Allows you to get the data that would otherwise go to the clipboard. To be used when you want to control the 'copy to clipboard' operation yourself. */
sendToClipboard?: (params: SendToClipboardParams) => void;
/** Allows complete control of the paste operation, including cancelling the operation (so nothing happens) or replacing the data with other data. */
processDataFromClipboard?: (params: ProcessDataFromClipboardParams) => string[][] | null;
// *** Filtering *** //
/** Grid calls this method to know if an external filter is present. */
isExternalFilterPresent?(): boolean;
/** Should return `true` if external filter passes, otherwise `false`. */
doesExternalFilterPass?(node: RowNode): boolean;
// *** Integrated Charts *** //
/** Callback to be used to customise the chart toolbar items. */
getChartToolbarItems?: GetChartToolbarItems;
/** Callback to enable displaying the chart in an alternative chart container. */
createChartContainer?: (params: ChartRef) => void;
// *** Keyboard Navigation *** //
/** Allows overriding the default behaviour for when user hits navigation (arrow) key when a header is focused. */
navigateToNextHeader?: (params: NavigateToNextHeaderParams) => HeaderPosition;
/** Allows overriding the default behaviour for when user hits `Tab` key when a header is focused. */
tabToNextHeader?: (params: TabToNextHeaderParams) => HeaderPosition;
/** Allows overriding the default behaviour for when user hits navigation (arrow) key when a cell is focused. */
navigateToNextCell?: (params: NavigateToNextCellParams) => CellPosition;
/** Allows overriding the default behaviour for when user hits `Tab` key when a cell is focused. */
tabToNextCell?: (params: TabToNextCellParams) => CellPosition;
/** Suppress the grid taking action for the relevant keyboard event when a cell is focused. */
suppressKeyboardEvent?: (params: SuppressKeyboardEventParams) => boolean;
// *** Localisation *** //
/** A callback for localising text within the grid. */
localeTextFunc?: (key: string, defaultValue: string) => string;
// *** Miscellaneous *** //
/** Allows overriding what `document` is used. Currently used by Drag and Drop (may extend to other places in the future). Use this when you want the grid to use a different `document` than the one available on the global scope. This can happen if docking out components (something which Electron supports) */
getDocument?: () => Document;
// *** Pagination *** //
/** Allows user to format the numbers in the pagination panel, i.e. 'row count' and 'page number' labels. This is for pagination panel only, to format numbers inside the grid's cells (i.e. your data), then use `valueFormatter` in the column definitions. */
paginationNumberFormatter?: (params: PaginationNumberFormatterParams) => string;
// *** Row Grouping and Pivoting *** //
/** Callback for grouping. */
groupRowAggNodes?(nodes: RowNode[]): any;
/** (Client-side Row Model only) Allows groups to be open by default. */
isGroupOpenByDefault?: (params: IsGroupOpenByDefaultParams) => boolean;
/** Allows default sorting of groups. */
defaultGroupOrderComparator?: (nodeA: RowNode, nodeB: RowNode) => number;
/** Callback to be used with pivoting, to allow changing the second column definition. */
processSecondaryColDef?(colDef: ColDef): void;
/** Callback to be used with pivoting, to allow changing the second column group definition. */
processSecondaryColGroupDef?(colGroupDef: ColGroupDef): void;
/** Callback to be used when working with Tree Data when `treeData = true`. */
getDataPath?: GetDataPath;
/** @deprecated - Use defaultGroupOrderComparator instead */
defaultGroupSortComparator?: (nodeA: RowNode, nodeB: RowNode) => number;
// *** Row Model: Server Side *** //
/** Allows setting the child count for a group row. */
getChildCount?(dataItem: any): number;
/** Allows providing different params for different levels of grouping. */
getServerSideStoreParams?: (params: GetServerSideStoreParamsParams) => ServerSideStoreParams;
/** Allows groups to be open by default. */
isServerSideGroupOpenByDefault?: (params: IsServerSideGroupOpenByDefaultParams) => boolean;
/** Allows cancelling transactions. */
isApplyServerSideTransaction?: IsApplyServerSideTransaction;
/** SSRM Tree Data: Allows specifying which rows are expandable. */
isServerSideGroup?: IsServerSideGroup;
/** SSRM Tree Data: Allows specifying group keys. */
getServerSideGroupKey?: GetServerSideGroupKey;
// *** Rows *** //
/**
* Return a business key for the node. If implemented, each row in the DOM will have an attribute `row-id='abc'` where `abc` is what you return as the business key.
* This is useful for automated testing, as it provides a way for your tool to identify rows based on unique business keys.
*/
getBusinessKeyForNode?(node: RowNode): string;
/** Allows you to set the ID for a particular row node based on the data. Useful for selection and server side sorting and filtering for paging and virtual pagination. */
getRowNodeId?: GetRowNodeIdFunc;
/** Allows you to process rows after they are created, so you can do final adding of custom attributes etc. */
processRowPostCreate?(params: ProcessRowParams): void;
/** Callback to be used to determine which rows are selectable. By default rows are selectable, so return `false` to make a row un-selectable. */
isRowSelectable?: IsRowSelectable;
/** Callback to be used with Master Detail to determine if a row should be a master row. If `false` is returned no detail row will exist for this row. */
isRowMaster?: IsRowMaster;
/** Callback to fill values instead of simply copying values or increasing number values using linear progression. */
fillOperation?: (params: FillOperationParams) => any;
// *** Sorting *** //
/** Callback to perform additional sorting after the grid has sorted the rows. */
postSort?(nodes: RowNode[]): void;
// *** Styling *** //
/** Callback version of property `rowStyle` to set style for each row individually. Function should return an object of CSS values. */
getRowStyle?: (params: RowClassParams) => RowStyle;
/** Callback version of property `rowClass` to set class(es) for each row individually. Function should return either a string (class name), array of strings (array of class names) or undefined for no class. */
getRowClass?: (params: RowClassParams) => string | string[] | undefined;
/** Callback version of property `rowHeight` to set height for each row individually. Function should return a positive number of pixels, or return `null`/`undefined` to use the default row height. */
getRowHeight?: (params: RowHeightParams) => number | undefined | null;
/** Tells the grid if this row should be rendered as full width. */
isFullWidthCell?(rowNode: RowNode): boolean;
// **********************************************************************************************************
// * If you change the events on this interface, you do *not* need to update PropertyKeys to be consistent, *
// * as event callbacks are automatically generated. *
// **********************************************************************************************************
// *** Accessories *** //
/** The tool panel was hidden or shown. Use `api.isToolPanelShowing()` to get status. */
onToolPanelVisibleChanged?(event: ToolPanelVisibleChangedEvent): void;
// *** Clipboard *** //
/** Paste operation has started. */
onPasteStart?(event: PasteStartEvent): void;
/** Paste operation has ended. */
onPasteEnd?(event: PasteEndEvent): void;
// *** Columns *** //
/** A column, or group of columns, was hidden / shown. */
onColumnVisible?(event: ColumnVisibleEvent): void;
/** A column, or group of columns, was pinned / unpinned. */
onColumnPinned?(event: ColumnPinnedEvent): void;
/** A column was resized. */
onColumnResized?(event: ColumnResizedEvent): void;
/** A column was moved. To find out when the column move is finished you can use the `dragStopped` event below. */
onColumnMoved?(event: ColumnMovedEvent): void;
/** A value column was added or removed. */
onColumnValueChanged?(event: ColumnValueChangedEvent): void;
/** The pivot mode flag was changed. */
onColumnPivotModeChanged?(event: ColumnPivotModeChangedEvent): void;
/** A pivot column was added, removed or order changed. */
onColumnPivotChanged?(event: ColumnPivotChangedEvent): void;
/** A column group was opened / closed. */
onColumnGroupOpened?(event: ColumnGroupOpenedEvent): void;
/** User set new columns. */
onNewColumnsLoaded?(event: NewColumnsLoadedEvent): void;
/** The list of grid columns changed. */
onGridColumnsChanged?(event: GridColumnsChangedEvent): void;
/** The list of displayed columns changed. This can result from columns open / close, column move, pivot, group, etc. */
onDisplayedColumnsChanged?(event: DisplayedColumnsChangedEvent): void;
/** The list of rendered columns changed (only columns in the visible scrolled viewport are rendered by default). */
onVirtualColumnsChanged?(event: VirtualColumnsChangedEvent): void;
/** Shotgun - gets called when either a) new columns are set or b) `columnApi.setState()` is used, so everything has changed. */
onColumnEverythingChanged?(event: ColumnEverythingChangedEvent): void;
// *** Components *** //
/**
* Only used by Angular, React and VueJS AG Grid components (not used if doing plain JavaScript or Angular 1.x).
* If the grid receives changes due to bound properties, this event fires after the grid has finished processing the change.
*/
onComponentStateChanged?(event: ComponentStateChangedEvent): void;
// *** Editing *** //
/** Value has changed after editing. */
onCellValueChanged?(event: CellValueChangedEvent): void;
/** A cell's value within a row has changed. This event corresponds to Full Row Editing only. */
onRowValueChanged?(event: RowValueChangedEvent): void;
/** Editing a cell has started. */
onCellEditingStarted?(event: CellEditingStartedEvent): void;
/** Editing a cell has stopped. */
onCellEditingStopped?(event: CellEditingStoppedEvent): void;
/** Editing a row has started (when row editing is enabled). When row editing, this event will be fired once and `cellEditingStarted` will be fired for each individual cell. This event corresponds to Full Row Editing only. */
onRowEditingStarted?(event: RowEditingStartedEvent): void;
/** Editing a row has stopped (when row editing is enabled). When row editing, this event will be fired once and `cellEditingStopped` will be fired for each individual cell. This event corresponds to Full Row Editing only. */
onRowEditingStopped?(event: RowEditingStoppedEvent): void;
// *** Filtering *** //
/** Filter has been opened. */
onFilterOpened?(event: FilterOpenedEvent): void;
/** Filter has been modified and applied. */
onFilterChanged?(event: FilterChangedEvent): void;
/** Filter was modified but not applied. Used when filters have 'Apply' buttons. */
onFilterModified?(event: FilterModifiedEvent): void;
// *** Integrated Charts *** //
/** A chart has been created. */
onChartCreated?(event: ChartCreated): void;
/** The data range for the chart has been changed. */
onChartRangeSelectionChanged?(event: ChartRangeSelectionChanged): void;
/** Formatting changes have been made by users through the Format Panel. */
onChartOptionsChanged?(event: ChartOptionsChanged): void;
/** A chart has been destroyed. */
onChartDestroyed?(event: ChartDestroyed): void;
// *** Keyboard Navigation *** //
/** DOM event `keyDown` happened on a cell. */
onCellKeyDown?(event: CellKeyDownEvent | FullWidthCellKeyDownEvent): void;
/** DOM event `keyPress` happened on a cell. */
onCellKeyPress?(event: CellKeyPressEvent | FullWidthCellKeyPressEvent): void;
// *** Miscellaneous *** //
/** The grid has initialised. Use this event if, for example, you need to use the grid's API to fix the columns to size. */
onGridReady?(event: GridReadyEvent): void;
/** Fired the first time data is rendered into the grid. */
onFirstDataRendered?(event: FirstDataRenderedEvent): void;
/** The size of the grid `div` has changed. In other words, the grid was resized. */
onGridSizeChanged?(event: GridSizeChangedEvent): void;
/** Displayed rows have changed. Triggered after sort, filter or tree expand / collapse events. */
onModelUpdated?(event: ModelUpdatedEvent): void;
/** A row was removed from the DOM, for any reason. Use to clean up resources (if any) used by the row. */
onVirtualRowRemoved?(event: VirtualRowRemovedEvent): void;
/** Which rows are rendered in the DOM has changed. */
onViewportChanged?(event: ViewportChangedEvent): void;
/** The body was scrolled horizontally or vertically. */
onBodyScroll?(event: BodyScrollEvent): void;
/** Main body of the grid has stopped scrolling, either horizontally or vertically. */
onBodyScrollEnd?(event: BodyScrollEndEvent): void;
/** When dragging starts. This could be any action that uses the grid's Drag and Drop service, e.g. Column Moving, Column Resizing, Range Selection, Fill Handle, etc. */
onDragStarted?(event: DragStartedEvent): void;
/** When dragging stops. This could be any action that uses the grid's Drag and Drop service, e.g. Column Moving, Column Resizing, Range Selection, Fill Handle, etc. */
onDragStopped?(event: DragStoppedEvent): void;
// *** Pagination *** //
/**
* Triggered every time the paging state changes. Some of the most common scenarios for this event to be triggered are:
*
* - The page size changes.
* - The current shown page is changed.
* - New data is loaded onto the grid.
*/
onPaginationChanged?(event: PaginationChangedEvent): void;
// *** Row Drag and Drop *** //
/** A drag has started, or dragging was already started and the mouse has re-entered the grid having previously left the grid. */
onRowDragEnter?(event: RowDragEvent): void;
/** The mouse has moved while dragging. */
onRowDragMove?(event: RowDragEvent): void;
/** The mouse has left the grid while dragging. */
onRowDragLeave?(event: RowDragEvent): void;
/** The drag has finished over the grid. */
onRowDragEnd?(event: RowDragEvent): void;
// *** Row Grouping *** //
/** A row group column was added or removed. */
onColumnRowGroupChanged?(event: ColumnRowGroupChangedEvent): void;
/** A row group was opened or closed. */
onRowGroupOpened?(event: RowGroupOpenedEvent): void;
/** Fired when calling either of the API methods `expandAll()` or `collapseAll()`. */
onExpandOrCollapseAll?(event: ExpandCollapseAllEvent): void;
// *** Row Pinning *** //
/** The client has set new pinned row data into the grid. */
onPinnedRowDataChanged?(event: PinnedRowDataChangedEvent): void;
// *** Row Model: Client Side *** //
/** The client has set new data into the grid using `api.setRowData()` or by changing the `rowData` bound property. */
onRowDataChanged?(event: RowDataChangedEvent): void;
/** The client has updated data for the grid using `api.applyTransaction(transaction)` or by changing the `rowData` bound property with `immutableData=true`. */
onRowDataUpdated?(event: RowDataUpdatedEvent): void;
/** Async transactions have been applied. Contains a list of all transaction results. */
onAsyncTransactionsFlushed?(event: AsyncTransactionsFlushed): void;
// *** Selection *** //
/** Cell is clicked. */
onCellClicked?(event: CellClickedEvent): void;
/** Cell is double clicked. */
onCellDoubleClicked?(event: CellDoubleClickedEvent): void;
/** Cell is focused. */
onCellFocused?(event: CellFocusedEvent): void;
/** Mouse entered cell. */
onCellMouseOver?(event: CellMouseOverEvent): void;
/** Mouse left cell. */
onCellMouseOut?(event: CellMouseOutEvent): void;
/** Mouse down on cell. */
onCellMouseDown?(event: CellMouseDownEvent): void;
/** Row is clicked. */
onRowClicked?(event: RowClickedEvent): void;
/** Row is double clicked. */
onRowDoubleClicked?(event: RowDoubleClickedEvent): void;
/** Row is selected or deselected. The event contains the node in question, so call the node's `isSelected()` method to see if it was just selected or deselected. */
onRowSelected?(event: RowSelectedEvent): void;
/** Row selection is changed. Use the grid API `getSelectedNodes()` to get the new list of selected nodes. */
onSelectionChanged?(event: SelectionChangedEvent): void;
/** Cell is right clicked. */
onCellContextMenu?(event: CellContextMenuEvent): void;
/** A change to range selection has occurred. */
onRangeSelectionChanged?(event: RangeSelectionChangedEvent): void;
// *** Sorting *** //
/** Sort has changed. The grid also listens for this and updates the model. */
onSortChanged?(event: SortChangedEvent): void;
onColumnRowGroupChangeRequest?(event: ColumnRowGroupChangeRequestEvent): void;
onColumnPivotChangeRequest?(event: ColumnPivotChangeRequestEvent): void;
onColumnValueChangeRequest?(event: ColumnValueChangeRequestEvent): void;
onColumnAggFuncChangeRequest?(event: ColumnAggFuncChangeRequestEvent): void;
// apis, set by the grid on init, set to null on destroy
api?: GridApi | null;
columnApi?: ColumnApi | null;
}
export type RowGroupingDisplayType = 'singleColumn' | 'multipleColumns' | 'groupRows' | 'custom';
export type TreeDataDisplayType = 'auto' | 'custom';
export interface FillOperationParams {
/** The mouse event for the fill operation. */
event: MouseEvent;
/** The values that have been processed by the fill operation. */
values: any[];
/** The RowNode of the current cell being changed. */
rowNode: RowNode;
/** The Column of the current cell being changed. */
column: Column;
/** The values that were present before processing started. */
initialValues: any[];
/** The index of the current processed value. */
currentIndex: number;
/** The value of the cell being currently processed by the Fill Operation. */
currentCellValue: any;
/** The direction of the Fill Operation. */
direction: 'up' | 'down' | 'left' | 'right';
api: GridApi;
columnApi: ColumnApi;
/** The context as provided on `gridOptions.context` */
context: any;
}
export interface GetDataPath {
(data: any): string[];
}
export interface IsServerSideGroup {
(dataItem: any): boolean;
}
export interface IsApplyServerSideTransaction {
(params: IsApplyServerSideTransactionParams): boolean;
}
export interface IsApplyServerSideTransactionParams {
/** The transaction getting applied. */
transaction: ServerSideTransaction;
/** The parent RowNode, if transaction is applied to a group. */
parentNode: RowNode;
//** Store info, if any, as passed via the success() callback when loading data. */
storeInfo: any;
}
export interface GetServerSideGroupKey {
(dataItem: any): string;
}
export interface IsRowMaster {
(dataItem: any): boolean;
}
export interface IsRowSelectable {
(node: RowNode): boolean;
}
export interface RowClassRules {
[cssClassName: string]: (((params: RowClassParams) => boolean) | string);
}
export interface RowStyle { [cssProperty: string]: string | number; }
export interface RowClassParams {
/** The data associated with this row from rowData */
data: any;
/** The RowNode associated with this row */
node: RowNode;
/** The index of the row */
rowIndex: number;
/** If using AngularJs, is the row's child scope, otherwise null */
$scope: any;
api: GridApi;
columnApi: ColumnApi;
/** The context as provided on `gridOptions.context` */
context: any;
}
export interface RowHeightParams {
data: any;
node: RowNode;
api: GridApi;
/** The context as provided on `gridOptions.context` */
context: any;
}
export interface SendToClipboardParams {
data: string;
}
export interface GetContextMenuItemsParams {
/** Names of the items that would be provided by default. */
defaultItems: string[] | undefined;
/** The column, if a cell was clicked, otherwise null. */
column: Column | null;
/** The row node, if a cell was clicked, otherwise null. */
node: RowNode | null;
/** The value, if a cell was clicked, otherwise null. */
value: any;
api: GridApi;
columnApi: ColumnApi;
/** The context as provided on `gridOptions.context` */
context: any;
}
export interface GetContextMenuItems {
(params: GetContextMenuItemsParams): (string | MenuItemDef)[];
}
export interface GetChartToolbarItemsParams {
defaultItems?: ChartMenuOptions[];
api: GridApi;
columnApi: ColumnApi;
}
export interface GetChartToolbarItems {
(params: GetChartToolbarItemsParams): ChartMenuOptions[];
}
export interface MenuItemDef {
/** Name of the menu item */
name: string;
/** It the item should be enabled / disabled */
disabled?: boolean;
/** Shortcut (just display text, saying the shortcut here does nothing) */
shortcut?: string;
/** Function that gets executed when item is chosen */
action?: () => void;
/** Set to true to provide a check beside the option */
checked?: boolean;
/** The icon to display, either a DOM element or HTML string */
icon?: HTMLElement | string;
/** If this item is a sub menu, contains a list of menu item definitions */
subMenu?: (MenuItemDef | string)[] | IComponent<any>;
/** CSS classes to apply to the menu item */
cssClasses?: string[];
/** Tooltip for the menu item */
tooltip?: string;
}
export interface GetMainMenuItemsParams {
/** The column that was clicked */
column: Column;
/** List of the items that would be displayed by default */
defaultItems: string[];
api: GridApi;
columnApi: ColumnApi;
/** The context as provided on `gridOptions.context` */
context: any;
}
export interface GetMainMenuItems {
(params: GetMainMenuItemsParams): (string | MenuItemDef)[];
}
export interface GetRowNodeIdFunc {
(data: any): string;
}
export interface ProcessRowParams {
eRow: HTMLElement;
ePinnedLeftRow: HTMLElement;
ePinnedRightRow: HTMLElement;
rowIndex: number;
node: RowNode;
api: GridApi;
columnApi: ColumnApi;
addRenderedRowListener: (eventType: string, listener: Function) => void;
/** The context as provided on `gridOptions.context` */
context: any;
}
export interface NavigateToNextHeaderParams {
/** The key for the arrow key pressed,
* left = 'ArrowLeft', up = 'ArrowUp', right = 'ArrowRight', down = 'ArrowDown' */
key: string;
/** The header that currently has focus */
previousHeaderPosition: HeaderPosition | null;
/** The header the grid would normally pick as the next header for this navigation */
nextHeaderPosition: HeaderPosition | null;
/** The number of header rows present in the grid */
headerRowCount: number;
event: KeyboardEvent;
api: GridApi;
columnApi: ColumnApi;
}
export interface TabToNextHeaderParams {
/** True if the Shift key is also down */
backwards: boolean;
/** The header that currently has focus */
previousHeaderPosition: HeaderPosition | null;
/** The header the grid would normally pick as the next header for this navigation */
nextHeaderPosition: HeaderPosition | null;
/** The number of header rows present in the grid */
headerRowCount: number;
api: GridApi;
columnApi: ColumnApi;
}
export interface NavigateToNextCellParams {
/** The keycode for the arrow key pressed:
* left = 37, up = 38, right = 39, down = 40 */
key: number;
/** The cell that currently has focus */
previousCellPosition: CellPosition;
/** The cell the grid would normally pick as the next cell for navigation */
nextCellPosition: CellPosition | null;
event: KeyboardEvent | null;
api: GridApi;
columnApi: ColumnApi;
}
export interface TabToNextCellParams {
/** True if the Shift key is also down */
backwards: boolean;
/** True if the current cell is editing
* (you may want to skip cells that are not editable, as the grid will enter the next cell in editing mode also if tabbing) */
editing: boolean;
/** The cell that currently has focus */
previousCellPosition: CellPosition;
/** The cell the grid would normally pick as the next cell for navigation. */
nextCellPosition: CellPosition | null;
api: GridApi;
columnApi: ColumnApi;
}
export interface PostProcessPopupParams {
/** If popup is for a column, this gives the Column */
column?: Column | null;
/** If popup is for a row, this gives the RowNode */
rowNode?: RowNode | null;
/** The popup we are showing */
ePopup: HTMLElement;
/** The different types are:
* 'contextMenu', 'columnMenu', 'aggFuncSelect', 'popupCellEditor' */
type: string;
/** If the popup is as a result of a button click (eg menu button),
* this is the component that the user clicked */
eventSource?: HTMLElement | null;
/** If the popup is as a result of a click or touch,
* this is the event - eg user showing context menu */
mouseEvent?: MouseEvent | Touch | null;
}
export interface PaginationNumberFormatterParams {
value: number;
}
export interface ProcessDataFromClipboardParams {
/** 2D array of all cells from the clipboard */
data: string[][];
}
export interface ChartRef {
/** The id of the created chart. */
chartId: string;
/** The chart instance that is produced by AG Charts which can be used to interact with the chart directly. */
chart: any;
/** The chart DOM element, which the application is responsible for placing into the DOM. */
chartElement: HTMLElement;
/** The application is responsible for calling this when the chart is no longer needed. */
destroyChart: () => void;
}
export type ServerSideStoreType = 'full' | 'partial';
export interface ServerSideStoreParams {
/**
* What store type to use.
* If missing, then defaults to grid option `serverSideStoreType`.
* */
storeType?: ServerSideStoreType;
/**
* For Partial Store only.
* How many blocks to keep in cache.
* If missing, defaults to grid options `maxBlocksInCache`.
*/
maxBlocksInCache?: number;
/**
* For Partial Store only.
* Cache block size.
* If missing, defaults to grid options `cacheBlockSize`.
*/
cacheBlockSize?: number;
}
export interface GetServerSideStoreParamsParams {
/** The level of the store. Top level is 0. */
level: number;
/** The Row Node for the group that got expanded, or undefined if top level (ie no parent) */
parentRowNode?: RowNode;
/** Active Row Group Columns, if any. */
rowGroupColumns: Column[];
/** Active Pivot Columns, if any. */
pivotColumns: Column[];
/** true if pivot mode is active. */
pivotMode: boolean;
}
export interface IsServerSideGroupOpenByDefaultParams {
data: any;
rowNode: RowNode;
}
export interface IsGroupOpenByDefaultParams {
/** The row node being considered. */
rowNode: RowNode;
/** The Column for which this row is grouping. */
rowGroupColumn: Column;
/** Same as `rowNode.level` - what level the group is at, e.g. 0 for top level, 1 for second etc */
level: number;
/** Same as `rowNode.field` - the field we are grouping on, e.g. 'country' */
field: string;
/** Same as `rowNode.key`, the value of this group, e.g. 'Ireland' */
key: string;
}
export interface LoadingCellRendererSelectorFunc {
(params: ILoadingCellRendererParams): LoadingCellRendererSelectorResult | undefined;
}
export interface LoadingCellRendererSelectorResult {
/** Equivalent of setting `loadingCellRenderer` */
component?: { new(): ICellRenderer; } | string;
/** Equivalent of setting `loadingCellRendererFramework` */
frameworkComponent?: any;
/** Equivalent of setting `loadingCellRendererParams` */
params?: any;
} | the_stack |
'use strict';
import * as _ from 'lodash';
import * as chai from 'chai';
import * as sinon from 'sinon';
import {
FirebaseRemoteConfigError,
RemoteConfigApiClient
} from '../../../src/remote-config/remote-config-api-client-internal';
import { HttpClient } from '../../../src/utils/api-request';
import * as utils from '../utils';
import * as mocks from '../../resources/mocks';
import { FirebaseAppError } from '../../../src/utils/error';
import { FirebaseApp } from '../../../src/app/firebase-app';
import { deepCopy } from '../../../src/utils/deep-copy';
import { getSdkVersion } from '../../../src/utils/index';
import {
RemoteConfigTemplate, Version, ListVersionsResult,
} from '../../../src/remote-config/index';
const expect = chai.expect;
describe('RemoteConfigApiClient', () => {
const ERROR_RESPONSE = {
error: {
code: 404,
message: 'Requested entity not found',
status: 'NOT_FOUND',
},
};
const VALIDATION_ERROR_MESSAGES = [
'[VALIDATION_ERROR]: [foo] are not valid condition names. All keys in all conditional value' +
' maps must be valid condition names.',
'[VERSION_MISMATCH]: Expected version 6, found 8 for project: 123456789012'
];
const EXPECTED_HEADERS = {
'Authorization': 'Bearer mock-token',
'X-Firebase-Client': `fire-admin-node/${getSdkVersion()}`,
'Accept-Encoding': 'gzip',
};
const VERSION_INFO: Version = {
versionNumber: '86',
updateOrigin: 'ADMIN_SDK_NODE',
updateType: 'INCREMENTAL_UPDATE',
updateUser: {
email: 'firebase-adminsdk@gserviceaccount.com'
},
description: 'production version',
updateTime: '2020-06-15T16:45:03.000Z',
}
const TEST_RESPONSE = {
conditions: [{ name: 'ios', expression: 'exp' }],
parameters: { param: { defaultValue: { value: 'true' }, valueType: 'BOOLEAN' } },
parameterGroups: { group: { parameters: { paramabc: { defaultValue: { value: 'true' } } }, } },
version: VERSION_INFO,
};
const TEST_VERSIONS_RESULT: ListVersionsResult = {
versions: [
{
versionNumber: '78',
updateTime: '2020-05-07T18:46:09.495Z',
updateUser: {
email: 'user@gmail.com',
imageUrl: 'https://photo.jpg'
},
description: 'Rollback to version 76',
updateOrigin: 'REST_API',
updateType: 'ROLLBACK',
rollbackSource: '76'
},
{
versionNumber: '77',
updateTime: '2020-05-07T18:44:41.555Z',
updateUser: {
email: 'user@gmail.com',
imageUrl: 'https://photo.jpg'
},
updateOrigin: 'REST_API',
updateType: 'INCREMENTAL_UPDATE',
},
],
nextPageToken: '76'
}
const noProjectId = 'Failed to determine project ID. Initialize the SDK with service '
+ 'account credentials, or set project ID as an app option. Alternatively, set the '
+ 'GOOGLE_CLOUD_PROJECT environment variable.';
const mockOptions = {
credential: new mocks.MockCredential(),
projectId: 'test-project',
};
const clientWithoutProjectId = new RemoteConfigApiClient(
mocks.mockCredentialApp());
const REMOTE_CONFIG_TEMPLATE: RemoteConfigTemplate = {
conditions: [
{
name: 'ios',
expression: 'device.os == \'ios\'',
tagColor: 'PINK',
},
],
parameters: {
// eslint-disable-next-line @typescript-eslint/camelcase
holiday_promo_enabled: {
defaultValue: { value: 'true' },
conditionalValues: { ios: { useInAppDefault: true } },
description: 'this is a promo',
valueType: 'BOOLEAN'
},
},
parameterGroups: {
// eslint-disable-next-line @typescript-eslint/camelcase
new_menu: {
description: 'Description of the group.',
parameters: {
// eslint-disable-next-line @typescript-eslint/camelcase
pumpkin_spice_season: {
defaultValue: { value: 'A Gryffindor must love a pumpkin spice latte.' },
conditionalValues: {
'android_en': { value: 'A Droid must love a pumpkin spice latte.' },
},
description: 'Description of the parameter.',
},
},
},
},
etag: 'etag-123456789012-6',
version: {
description: 'production version'
}
};
// Stubs used to simulate underlying api calls.
let stubs: sinon.SinonStub[] = [];
let app: FirebaseApp;
let apiClient: RemoteConfigApiClient;
beforeEach(() => {
app = mocks.appWithOptions(mockOptions);
apiClient = new RemoteConfigApiClient(app);
});
afterEach(() => {
_.forEach(stubs, (stub) => stub.restore());
stubs = [];
return app.delete();
});
describe('Constructor', () => {
it('should reject when the app is null', () => {
expect(() => new RemoteConfigApiClient(null as unknown as FirebaseApp))
.to.throw('First argument passed to admin.remoteConfig() must be a valid Firebase app instance.');
});
});
describe('getTemplate', () => {
it('should reject when project id is not available', () => {
return clientWithoutProjectId.getTemplate()
.should.eventually.be.rejectedWith(noProjectId);
});
// tests for api response validations
runEtagHeaderTests(() => apiClient.getTemplate());
runErrorResponseTests(() => apiClient.getTemplate());
it('should resolve with the latest template on success', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_RESPONSE, 200, { etag: 'etag-123456789012-1' }));
stubs.push(stub);
return apiClient.getTemplate()
.then((resp) => {
expect(resp.conditions).to.deep.equal(TEST_RESPONSE.conditions);
expect(resp.parameters).to.deep.equal(TEST_RESPONSE.parameters);
expect(resp.parameterGroups).to.deep.equal(TEST_RESPONSE.parameterGroups);
expect(resp.etag).to.equal('etag-123456789012-1');
expect(resp.version).to.deep.equal(TEST_RESPONSE.version);
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'GET',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig',
headers: EXPECTED_HEADERS,
});
});
});
});
describe('getTemplateAtVersion', () => {
it('should reject when project id is not available', () => {
return clientWithoutProjectId.getTemplateAtVersion(65)
.should.eventually.be.rejectedWith(noProjectId);
});
// test for version number validations
runTemplateVersionNumberTests((v: string | number) => { apiClient.getTemplateAtVersion(v); });
// tests for api response validations
runEtagHeaderTests(() => apiClient.getTemplateAtVersion(65));
runErrorResponseTests(() => apiClient.getTemplateAtVersion(65));
it('should convert version number to string', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_RESPONSE, 200, { etag: 'etag-123456789012-60' }));
stubs.push(stub);
return apiClient.getTemplateAtVersion(60)
.then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'GET',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig',
headers: EXPECTED_HEADERS,
data: { versionNumber: '60' },
});
});
});
it('should resolve with the requested template version on success', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_RESPONSE, 200, { etag: 'etag-123456789012-60' }));
stubs.push(stub);
return apiClient.getTemplateAtVersion('60')
.then((resp) => {
expect(resp.conditions).to.deep.equal(TEST_RESPONSE.conditions);
expect(resp.parameters).to.deep.equal(TEST_RESPONSE.parameters);
expect(resp.parameterGroups).to.deep.equal(TEST_RESPONSE.parameterGroups);
expect(resp.etag).to.equal('etag-123456789012-60');
expect(resp.version).to.deep.equal(TEST_RESPONSE.version);
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'GET',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig',
headers: EXPECTED_HEADERS,
data: { versionNumber: '60' },
});
});
});
});
describe('validateTemplate', () => {
it('should reject when project id is not available', () => {
return clientWithoutProjectId.validateTemplate(REMOTE_CONFIG_TEMPLATE)
.should.eventually.be.rejectedWith(noProjectId);
});
// tests for input template validations
testInvalidInputTemplates((t: RemoteConfigTemplate) => apiClient.validateTemplate(t));
// tests for api response validations
runEtagHeaderTests(() => apiClient.validateTemplate(REMOTE_CONFIG_TEMPLATE));
runErrorResponseTests(() => apiClient.validateTemplate(REMOTE_CONFIG_TEMPLATE));
it('should exclude output only parameters from version metadata', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_RESPONSE, 200, { etag: 'etag-123456789012-0' }));
stubs.push(stub);
const templateCopy = deepCopy(REMOTE_CONFIG_TEMPLATE);
templateCopy.version = VERSION_INFO;
return apiClient.validateTemplate(templateCopy)
.then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'PUT',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig?validate_only=true',
headers: { ...EXPECTED_HEADERS, 'If-Match': REMOTE_CONFIG_TEMPLATE.etag },
data: {
conditions: REMOTE_CONFIG_TEMPLATE.conditions,
parameters: REMOTE_CONFIG_TEMPLATE.parameters,
parameterGroups: REMOTE_CONFIG_TEMPLATE.parameterGroups,
version: { description: VERSION_INFO.description },
}
});
});
});
it('should resolve with the requested template on success', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_RESPONSE, 200, { etag: 'etag-123456789012-0' }));
stubs.push(stub);
return apiClient.validateTemplate(REMOTE_CONFIG_TEMPLATE)
.then((resp) => {
expect(resp.conditions).to.deep.equal(TEST_RESPONSE.conditions);
expect(resp.parameters).to.deep.equal(TEST_RESPONSE.parameters);
expect(resp.parameterGroups).to.deep.equal(TEST_RESPONSE.parameterGroups);
// validate template returns an etag with the suffix -0 when successful.
// verify that the etag matches the original template etag.
expect(resp.etag).to.equal('etag-123456789012-6');
expect(resp.version).to.deep.equal(TEST_RESPONSE.version);
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'PUT',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig?validate_only=true',
headers: { ...EXPECTED_HEADERS, 'If-Match': REMOTE_CONFIG_TEMPLATE.etag },
data: {
conditions: REMOTE_CONFIG_TEMPLATE.conditions,
parameters: REMOTE_CONFIG_TEMPLATE.parameters,
parameterGroups: REMOTE_CONFIG_TEMPLATE.parameterGroups,
version: REMOTE_CONFIG_TEMPLATE.version,
}
});
});
});
[null, undefined, ''].forEach((etag) => {
it('should reject when the etag in template is null, undefined, or an empty string', () => {
expect(() => apiClient.validateTemplate({
conditions: [], parameters: {}, parameterGroups: {}, etag: etag as any
})).to.throw('ETag must be a non-empty string.');
});
});
VALIDATION_ERROR_MESSAGES.forEach((message) => {
it('should reject with failed-precondition when a validation error occurres', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.rejects(utils.errorFrom({
error: {
code: 400,
message: message,
status: 'FAILED_PRECONDITION'
}
}, 400));
stubs.push(stub);
const expected = new FirebaseRemoteConfigError('failed-precondition', message);
return apiClient.validateTemplate(REMOTE_CONFIG_TEMPLATE)
.should.eventually.be.rejected.and.deep.include(expected);
});
});
});
describe('publishTemplate', () => {
it('should reject when project id is not available', () => {
return clientWithoutProjectId.publishTemplate(REMOTE_CONFIG_TEMPLATE)
.should.eventually.be.rejectedWith(noProjectId);
});
// tests for input template validations
testInvalidInputTemplates((t: RemoteConfigTemplate) => apiClient.publishTemplate(t));
// tests for api response validations
runEtagHeaderTests(() => apiClient.publishTemplate(REMOTE_CONFIG_TEMPLATE));
runErrorResponseTests(() => apiClient.publishTemplate(REMOTE_CONFIG_TEMPLATE));
it('should exclude output only parameters from version metadata', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_RESPONSE, 200, { etag: 'etag-123456789012-6' }));
stubs.push(stub);
const templateCopy = deepCopy(REMOTE_CONFIG_TEMPLATE);
templateCopy.version = VERSION_INFO;
return apiClient.publishTemplate(templateCopy)
.then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'PUT',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig',
headers: { ...EXPECTED_HEADERS, 'If-Match': REMOTE_CONFIG_TEMPLATE.etag },
data: {
conditions: REMOTE_CONFIG_TEMPLATE.conditions,
parameters: REMOTE_CONFIG_TEMPLATE.parameters,
parameterGroups: REMOTE_CONFIG_TEMPLATE.parameterGroups,
version: { description: VERSION_INFO.description },
}
});
});
});
const testOptions = [
{ options: undefined, etag: 'etag-123456789012-6' },
{ options: { force: true }, etag: '*' }
];
testOptions.forEach((option) => {
it('should resolve with the published template on success', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_RESPONSE, 200, { etag: 'etag-123456789012-6' }));
stubs.push(stub);
return apiClient.publishTemplate(REMOTE_CONFIG_TEMPLATE, option.options)
.then((resp) => {
expect(resp.conditions).to.deep.equal(TEST_RESPONSE.conditions);
expect(resp.parameters).to.deep.equal(TEST_RESPONSE.parameters);
expect(resp.parameterGroups).to.deep.equal(TEST_RESPONSE.parameterGroups);
expect(resp.etag).to.equal('etag-123456789012-6');
expect(resp.version).to.deep.equal(TEST_RESPONSE.version);
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'PUT',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig',
headers: { ...EXPECTED_HEADERS, 'If-Match': option.etag },
data: {
conditions: REMOTE_CONFIG_TEMPLATE.conditions,
parameters: REMOTE_CONFIG_TEMPLATE.parameters,
parameterGroups: REMOTE_CONFIG_TEMPLATE.parameterGroups,
version: REMOTE_CONFIG_TEMPLATE.version,
}
});
});
});
});
[null, undefined, ''].forEach((etag) => {
it('should reject when the etag in template is null, undefined, or an empty string', () => {
expect(() => apiClient.publishTemplate({
conditions: [], parameters: {}, parameterGroups: {}, etag: etag as any
})).to.throw('ETag must be a non-empty string.');
});
});
VALIDATION_ERROR_MESSAGES.forEach((message) => {
it('should reject with failed-precondition when a validation error occurs', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.rejects(utils.errorFrom({
error: {
code: 400,
message: message,
status: 'FAILED_PRECONDITION'
}
}, 400));
stubs.push(stub);
const expected = new FirebaseRemoteConfigError('failed-precondition', message);
return apiClient.publishTemplate(REMOTE_CONFIG_TEMPLATE)
.should.eventually.be.rejected.and.deep.include(expected);
});
});
});
describe('rollback', () => {
it('should reject when project id is not available', () => {
return clientWithoutProjectId.rollback('60')
.should.eventually.be.rejectedWith(noProjectId);
});
// test for version number validations
runTemplateVersionNumberTests((v: string | number) => { apiClient.rollback(v); });
// tests for api response validations
runEtagHeaderTests(() => apiClient.rollback(60));
runErrorResponseTests(() => apiClient.rollback(60));
it('should convert version number to string', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_RESPONSE, 200, { etag: 'etag-123456789012-55' }));
stubs.push(stub);
return apiClient.rollback(55)
.then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'POST',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig:rollback',
headers: EXPECTED_HEADERS,
data: {
versionNumber: '55',
}
});
});
});
it('should resolve with the rollbacked template on success', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_RESPONSE, 200, { etag: 'etag-123456789012-60' }));
stubs.push(stub);
return apiClient.rollback('60')
.then((resp) => {
expect(resp.conditions).to.deep.equal(TEST_RESPONSE.conditions);
expect(resp.parameters).to.deep.equal(TEST_RESPONSE.parameters);
expect(resp.parameterGroups).to.deep.equal(TEST_RESPONSE.parameterGroups);
expect(resp.etag).to.equal('etag-123456789012-60');
expect(resp.version).to.deep.equal(TEST_RESPONSE.version);
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'POST',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig:rollback',
headers: EXPECTED_HEADERS,
data: {
versionNumber: '60',
}
});
});
});
});
describe('listVersions', () => {
it('should reject when project id is not available', () => {
return clientWithoutProjectId.listVersions()
.should.eventually.be.rejectedWith(noProjectId);
});
// tests for api response validations
runErrorResponseTests(() => apiClient.listVersions());
[null, 'abc', '', [], true, 102, 1.2].forEach((invalidOption) => {
it(`should throw if options is ${invalidOption}`, () => {
expect(() => apiClient.listVersions(invalidOption as any))
.to.throw('ListVersionsOptions must be a non-null object');
});
});
[null, 'abc', '', [], {}, true, NaN, 0, -100, 301, 450].forEach((invalidPageSize) => {
it(`should throw if pageSize is ${invalidPageSize}`, () => {
expect(() => apiClient.listVersions({ pageSize: invalidPageSize } as any))
.to.throw(/^pageSize must be a (number.|number between 1 and 300 \(inclusive\).)$/);
});
});
[null, '', 102, 1.2, [], {}, true, NaN].forEach((invalidPageToken) => {
it(`should throw if pageToken is ${invalidPageToken}`, () => {
expect(() => apiClient.listVersions({ pageToken: invalidPageToken } as any))
.to.throw('pageToken must be a string value');
});
});
['', null, NaN, true, [], {}].forEach(
(invalidVersion) => {
it(`should throw if the endVersionNumber is: ${invalidVersion}`, () => {
expect(() => apiClient.listVersions({ endVersionNumber: invalidVersion } as any))
.to.throw(/^endVersionNumber must be a non-empty string in int64 format or a number$/);
});
});
['abc', 'a123b', 'a123', '123a', 1.2, '70.2'].forEach(
(invalidVersion) => {
it(`should throw if the endVersionNumber is: ${invalidVersion}`, () => {
expect(() => apiClient.listVersions({ endVersionNumber: invalidVersion } as any))
.to.throw(/^endVersionNumber must be an integer or a string in int64 format$/);
});
});
[null, '', 'abc', '2020-05-07T18:44:41.555Z', 102, 1.2, [], {}, true, NaN].forEach(
(invalidStartTime) => {
it(`should throw if startTime is ${invalidStartTime}`, () => {
expect(() => apiClient.listVersions({ startTime: invalidStartTime } as any))
.to.throw('startTime must be a valid Date object or a UTC date string.');
});
});
[null, '', 'abc', '2020-05-07T18:44:41.555Z', 102, 1.2, [], {}, true, NaN].forEach(
(invalidEndTime) => {
it(`should throw if endTime is ${invalidEndTime}`, () => {
expect(() => apiClient.listVersions({ endTime: invalidEndTime } as any))
.to.throw('endTime must be a valid Date object or a UTC date string.');
});
});
it('should convert input timestamps to ISO strings', () => {
const startTime = new Date(2020, 4, 2);
const endTime = 'Thu, 07 May 2020 18:44:41 GMT';
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_VERSIONS_RESULT, 200));
stubs.push(stub);
return apiClient.listVersions({
startTime,
endTime,
})
.then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'GET',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig:listVersions',
headers: EXPECTED_HEADERS,
data: {
// timestamps should be converted to ISO strings
startTime: startTime.toISOString(),
endTime: new Date(endTime).toISOString(),
}
});
});
});
it('should convert endVersionNumber to string', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_VERSIONS_RESULT, 200));
stubs.push(stub);
return apiClient.listVersions({
endVersionNumber: 70
})
.then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'GET',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig:listVersions',
headers: EXPECTED_HEADERS,
data: {
// endVersionNumber should be converted to string
endVersionNumber: '70'
}
});
});
});
it('should remove undefined fields from options', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_VERSIONS_RESULT, 200));
stubs.push(stub);
return apiClient.listVersions({
pageSize: undefined,
pageToken: undefined,
endVersionNumber: 70,
})
.then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'GET',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig:listVersions',
headers: EXPECTED_HEADERS,
data: {
endVersionNumber: '70'
}
});
});
});
it('should resolve with a list of template versions on success', () => {
const startTime = new Date(2020, 4, 2);
const endTime = 'Thu, 07 May 2020 18:44:41 GMT';
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_VERSIONS_RESULT, 200));
stubs.push(stub);
return apiClient.listVersions({
pageSize: 2,
pageToken: '70',
endVersionNumber: '78',
startTime: startTime,
endTime: endTime,
})
.then((resp) => {
expect(resp.versions).to.deep.equal(TEST_VERSIONS_RESULT.versions);
expect(resp.nextPageToken).to.equal(TEST_VERSIONS_RESULT.nextPageToken);
expect(stub).to.have.been.calledOnce.and.calledWith({
method: 'GET',
url: 'https://firebaseremoteconfig.googleapis.com/v1/projects/test-project/remoteConfig:listVersions',
headers: EXPECTED_HEADERS,
data: {
pageSize: 2,
pageToken: '70',
endVersionNumber: '78',
startTime: startTime.toISOString(),
endTime: new Date(endTime).toISOString(),
}
});
});
});
});
function runTemplateVersionNumberTests(rcOperation: Function): void {
['', null, NaN, true, [], {}].forEach((invalidVersion) => {
it(`should reject if the versionNumber is: ${invalidVersion}`, () => {
expect(() => rcOperation(invalidVersion as any))
.to.throw(/^versionNumber must be a non-empty string in int64 format or a number$/);
});
});
['abc', 'a123b', 'a123', '123a', 1.2, '70.2'].forEach((invalidVersion) => {
it(`should reject if the versionNumber is: ${invalidVersion}`, () => {
expect(() => rcOperation(invalidVersion as any))
.to.throw(/^versionNumber must be an integer or a string in int64 format$/);
});
});
}
function runEtagHeaderTests(rcOperation: () => Promise<RemoteConfigTemplate>): void {
it('should reject when the etag is not present in the response', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.resolves(utils.responseFrom(TEST_RESPONSE));
stubs.push(stub);
const expected = new FirebaseRemoteConfigError('invalid-argument',
'ETag header is not present in the server response.');
return rcOperation()
.should.eventually.be.rejected.and.deep.include(expected);
});
}
function runErrorResponseTests(rcOperation: () => Promise<RemoteConfigTemplate | ListVersionsResult>): void {
it('should reject when a full platform error response is received', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.rejects(utils.errorFrom(ERROR_RESPONSE, 404));
stubs.push(stub);
const expected = new FirebaseRemoteConfigError('not-found', 'Requested entity not found');
return rcOperation()
.should.eventually.be.rejected.and.deep.include(expected);
});
it('should reject with unknown-error when error code is not present', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.rejects(utils.errorFrom({}, 404));
stubs.push(stub);
const expected = new FirebaseRemoteConfigError('unknown-error', 'Unknown server error: {}');
return rcOperation()
.should.eventually.be.rejected.and.deep.include(expected);
});
it('should reject with unknown-error for non-json response', () => {
const stub = sinon
.stub(HttpClient.prototype, 'send')
.rejects(utils.errorFrom('not json', 404));
stubs.push(stub);
const expected = new FirebaseRemoteConfigError(
'unknown-error', 'Unexpected response with status: 404 and body: not json');
return rcOperation()
.should.eventually.be.rejected.and.deep.include(expected);
});
it('should reject when rejected with a FirebaseAppError', () => {
const expected = new FirebaseAppError('network-error', 'socket hang up');
const stub = sinon
.stub(HttpClient.prototype, 'send')
.rejects(expected);
stubs.push(stub);
return rcOperation()
.should.eventually.be.rejected.and.deep.include(expected);
});
}
function testInvalidInputTemplates(rcOperation: Function): void {
const INVALID_PARAMETERS: any[] = [null, '', 'abc', 1, true, []];
const INVALID_PARAMETER_GROUPS: any[] = [null, '', 'abc', 1, true, []];
const INVALID_CONDITIONS: any[] = [null, '', 'abc', 1, true, {}];
const INVALID_ETAG_TEMPLATES: any[] = [
{ parameters: {}, parameterGroups: {}, conditions: [], etag: '' },
Object()
];
const INVALID_TEMPLATES: any[] = [null, 'abc', 123];
const inputTemplate = deepCopy(REMOTE_CONFIG_TEMPLATE);
INVALID_PARAMETERS.forEach((invalidParameter) => {
it(`should throw if the parameters is ${JSON.stringify(invalidParameter)}`, () => {
(inputTemplate as any).parameters = invalidParameter;
inputTemplate.conditions = [];
expect(() => rcOperation(inputTemplate))
.to.throw('Remote Config parameters must be a non-null object');
});
});
INVALID_PARAMETER_GROUPS.forEach((invalidParameterGroup) => {
it(`should throw if the parameter groups is ${JSON.stringify(invalidParameterGroup)}`, () => {
(inputTemplate as any).parameterGroups = invalidParameterGroup;
inputTemplate.conditions = [];
inputTemplate.parameters = {};
expect(() => rcOperation(inputTemplate))
.to.throw('Remote Config parameter groups must be a non-null object');
});
});
INVALID_CONDITIONS.forEach((invalidConditions) => {
it(`should throw if the conditions is ${JSON.stringify(invalidConditions)}`, () => {
(inputTemplate as any).conditions = invalidConditions;
inputTemplate.parameters = {};
inputTemplate.parameterGroups = {};
expect(() => rcOperation(inputTemplate))
.to.throw('Remote Config conditions must be an array');
});
});
INVALID_ETAG_TEMPLATES.forEach((invalidEtagTemplate) => {
it(`should throw if the template is ${JSON.stringify(invalidEtagTemplate)}`, () => {
expect(() => rcOperation(invalidEtagTemplate))
.to.throw('ETag must be a non-empty string.');
});
});
INVALID_TEMPLATES.forEach((invalidTemplate) => {
it(`should throw if the template is ${JSON.stringify(invalidTemplate)}`, () => {
expect(() => rcOperation(invalidTemplate))
.to.throw(`Invalid Remote Config template: ${JSON.stringify(invalidTemplate)}`);
});
});
}
}); | the_stack |
import { Option, Some } from "./Option";
import { Vector } from "./Vector";
import { WithEquality, getHashCode,
areEqual, Ordering, ToOrderable } from "./Comparison";
import { contractTrueEquality } from "./Contract";
import { inspect } from "./Value";
import { HashMap } from "./HashMap";
import { HashSet } from "./HashSet";
import { Seq, IterableArray } from "./Seq";
import { Lazy } from "./Lazy";
import { LinkedList } from "./LinkedList";
import * as SeqHelpers from "./SeqHelpers";
/**
* A Stream is either [[EmptyStream]] or [[ConsStream]]
* "static methods" available through [[StreamStatic]]
* @param T the item type
*/
export type Stream<T> = EmptyStream<T> | ConsStream<T>;
/**
* Holds the "static methods" for [[Stream]]
*/
export class StreamStatic {
/**
* The empty stream
*/
empty<T>(): Stream<T> {
return <EmptyStream<T>>emptyStream;
}
/**
* Create a Stream with the elements you give.
*/
of<T>(elt:T, ...elts:T[]): ConsStream<T>;
of<T>(...elts:T[]): Stream<T>;
of<T>(...elts:T[]): Stream<T> {
return Stream.ofIterable(elts);
}
/**
* Build a stream from any iterable, which means also
* an array for instance.
* @param T the item type
*/
ofIterable<T>(elts: Iterable<T>): Stream<T> {
// need to eagerly copy the iterable. the reason
// is, if we would build the stream based on the iterator
// in the iterable, Stream.tail() would do it.next().
// but it.next() modifies the iterator (mutability),
// and you would end up with getting two different tails
// for the same stream if you call .tail() twice in a row
if (Array.isArray(elts)) {
return Stream.ofArray(elts);
}
return Stream.ofArray(Array.from(elts));
}
/**
* Curried type guard for Stream.
* Sometimes needed also due to https://github.com/Microsoft/TypeScript/issues/20218
*
* Vector.of(Stream.of(1), Stream.empty<number>())
* .filter(Stream.isEmpty)
* => Vector.of(Stream.empty<number>())
*/
isEmpty<T>(s: Stream<T>): s is EmptyStream<T> {
return s.isEmpty();
}
/**
* Curried type guard for Stream.
* Sometimes needed also due to https://github.com/Microsoft/TypeScript/issues/20218
*
* Vector.of(Stream.of(1), Stream.empty<number>())
* .filter(Stream.isNotEmpty)
* .map(s => s.head().get()+1)
* => Vector.of(2)
*/
isNotEmpty<T>(s: Stream<T>): s is ConsStream<T> {
return !s.isEmpty();
}
/**
* @hidden
*/
private ofArray<T>(elts: Array<T>): Stream<T> {
if (elts.length === 0) {
return <EmptyStream<T>>emptyStream;
}
const head = elts[0];
return new ConsStream(head, Lazy.of(() => Stream.ofArray(elts.slice(1))));
}
/**
* Build an infinite stream from a seed and a transformation function.
*
* Stream.iterate(1, x => x*2).take(4);
* => Stream.of(1,2,4,8)
*/
iterate<T>(seed:T, fn: (v:T)=>T): ConsStream<T> {
return new ConsStream(seed, Lazy.of(()=>Stream.iterate(fn(seed), fn)));
}
/**
* Build an infinite stream by calling repeatedly a function.
*
* Stream.continually(() => 1).take(4);
* => Stream.of(1,1,1,1)
*
* Stream.continually(Math.random).take(2);
* => Stream.of(0.49884723907769635, 0.3226548779864311)
*/
continually<T>(fn: ()=>T): ConsStream<T> {
return new ConsStream(fn(), Lazy.of(() => Stream.continually(fn)));
}
/**
* Dual to the foldRight function. Build a collection from a seed.
* Takes a starting element and a function.
* It applies the function on the starting element; if the
* function returns None, it stops building the list, if it
* returns Some of a pair, it adds the first element to the result
* and takes the second element as a seed to keep going.
*
* Stream.unfoldRight(
* 10, x=>Option.of(x)
* .filter(x => x!==0)
* .map<[number,number]>(x => [x,x-1]));
* => Stream.of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
*/
unfoldRight<T,U>(seed: T, fn: (x:T)=>Option<[U,T]>): Stream<U> {
let nextVal = fn(seed);
if (nextVal.isNone()) {
return <EmptyStream<U>>emptyStream;
}
return new ConsStream(
nextVal.get()[0],
Lazy.of(()=>Stream.unfoldRight(nextVal.getOrThrow()[1], fn)));
}
/**
* Combine any number of iterables you give in as
* parameters to produce a new collection which combines all,
* in tuples. For instance:
*
* Stream.zip(Stream.of(1,2,3), ["a","b","c"], LinkedList.of(8,9,10))
* => Stream.of([1,"a",8], [2,"b",9], [3,"c",10])
*
* The result collection will have the length of the shorter
* of the input iterables. Extra elements will be discarded.
*
* Also see the non-static version [[ConsStream.zip]], which only combines two
* collections.
* @param A A is the type of the tuple that'll be generated
* (`[number,string,number]` for the code sample)
*/
zip<A extends any[]>(...iterables: IterableArray<A>): Stream<A> {
const iterators: Iterator<A>[] = iterables.map(i => i[Symbol.iterator]());
let items = iterators.map(i => i.next());
if (items.some(item => item.done)) {
return <EmptyStream<A>>emptyStream;
}
return new ConsStream(items.map(item => item.value) as A,
Lazy.of(() => Stream.zip<A>(...
<any>iterators.map(i=>({ [Symbol.iterator]: ()=>i})))));
}
}
/**
* The Stream constant allows to call the Stream "static" methods
*/
export const Stream = new StreamStatic();
/**
* EmptyStream is the empty stream; every non-empty
* stream also has a pointer to an empty stream
* after its last element.
* "static methods" available through [[StreamStatic]]
* @param T the item type
*/
export class EmptyStream<T> implements Seq<T> {
/**
* @hidden
*/
readonly className: "EmptyStream" = <any>undefined; // https://stackoverflow.com/a/47841595/516188
/**
* Implementation of the Iterator interface.
*/
[Symbol.iterator](): Iterator<T> {
return {
next(): IteratorResult<T> {
return {
done: true,
value: <any>undefined
};
}
}
}
/**
* View this Some a as Stream. Useful to help typescript type
* inference sometimes.
*/
asStream(): Stream<T> {
return this;
}
/**
* @hidden
*/
hasTrueEquality(): boolean {
return SeqHelpers.seqHasTrueEquality<T>(this);
}
/**
* Get the length of the collection.
*/
length(): number {
return 0;
}
/**
* If the collection contains a single element,
* return Some of its value, otherwise return None.
*/
single(): Option<T> {
return Option.none<T>();
}
/**
* true if the collection is empty, false otherwise.
*/
isEmpty(): this is EmptyStream<T> {
return true;
}
/**
* Get the first value of the collection, if any.
* returns Option.Some if the collection is not empty,
* Option.None if it's empty.
*/
head(): Option<T> {
return Option.none<T>();
}
/**
* Get all the elements in the collection but the first one.
* If the collection is empty, return None.
*/
tail(): Option<Stream<T>> {
return Option.none<Stream<T>>();
}
/**
* Get the last value of the collection, if any.
* returns Option.Some if the collection is not empty,
* Option.None if it's empty.
*/
last(): Option<T> {
return Option.none<T>();
}
/**
* Retrieve the element at index idx.
* Returns an option because the collection may
* contain less elements than the index.
*
* Careful this is going to have poor performance
* on Stream, which is not a good data structure
* for random access!
*/
get(idx: number): Option<T> {
return Option.none<T>();
}
/**
* Search for an item matching the predicate you pass,
* return Option.Some of that element if found,
* Option.None otherwise.
*/
find(predicate:(v:T)=>boolean): Option<T> {
return Option.none<T>();
}
/**
* Returns true if the item is in the collection,
* false otherwise.
*/
contains(v:T&WithEquality): boolean {
return false;
}
/**
* Return a new stream keeping only the first n elements
* from this stream.
*/
take(n: number): Stream<T> {
return this;
}
/**
* Returns a new collection, discarding the elements
* after the first element which fails the predicate.
*/
takeWhile(predicate: (x:T)=>boolean): Stream<T> {
return this;
}
/**
* Returns a new collection, discarding the elements
* after the first element which fails the predicate,
* but starting from the end of the collection.
*
* Stream.of(1,2,3,4).takeRightWhile(x => x > 2)
* => Stream.of(3,4)
*/
takeRightWhile(predicate:(x:T)=>boolean): Stream<T> {
return this;
}
/**
* Returns a new collection with the first
* n elements discarded.
* If the collection has less than n elements,
* returns the empty collection.
*/
drop(n:number): Stream<T> {
return this;
}
/**
* Returns a new collection, discarding the first elements
* until one element fails the predicate. All elements
* after that point are retained.
*/
dropWhile(predicate:(x:T)=>boolean): Stream<T> {
return this;
}
/**
* Returns a new collection with the last
* n elements discarded.
* If the collection has less than n elements,
* returns the empty collection.
*/
dropRight(n:number): Stream<T> {
return this;
}
/**
* Returns a new collection, discarding the last elements
* until one element fails the predicate. All elements
* before that point are retained.
*/
dropRightWhile(predicate:(x:T)=>boolean): Stream<T> {
return this;
}
/**
* Reduces the collection to a single value using the
* associative binary function you give. Since the function
* is associative, order of application doesn't matter.
*
* Example:
*
* Stream.of(1,2,3).fold(0, (a,b) => a + b);
* => 6
*/
fold(zero:T, fn:(v1:T,v2:T)=>T): T {
return zero;
}
/**
* Reduces the collection to a single value.
* Left-associative.
*
* Example:
*
* Vector.of("a", "b", "c").foldLeft("!", (xs,x) => x+xs);
* => "cba!"
*
* @param zero The initial value
* @param fn A function taking the previous value and
* the current collection item, and returning
* an updated value.
*/
foldLeft<U>(zero: U, fn:(soFar:U,cur:T)=>U): U {
return zero;
}
/**
* Reduces the collection to a single value.
* Right-associative.
*
* Example:
*
* Vector.of("a", "b", "c").foldRight("!", (x,xs) => xs+x);
* => "!cba"
*
* @param zero The initial value
* @param fn A function taking the current collection item and
* the previous value , and returning
* an updated value.
*/
foldRight<U>(zero: U, fn:(cur:T, soFar:U)=>U): U {
return zero;
}
/**
* Combine this collection with the collection you give in
* parameter to produce a new collection which combines both,
* in pairs. For instance:
*
* Stream.of(1,2,3).zip(["a","b","c"])
* => Stream.of([1,"a"], [2,"b"], [3,"c"])
*
* The result collection will have the length of the shorter
* of both collections. Extra elements will be discarded.
*
* Also see [[StreamStatic.zip]] (static version which can more than two
* iterables)
*/
zip<U>(other: Iterable<U>): Stream<[T,U]> {
return <EmptyStream<[T,U]>>emptyStream;
}
/**
* Combine this collection with the index of the elements
* in it. Handy if you need the index when you map on
* the collection for instance:
*
* Stream.of("a","b").zipWithIndex().map(([v,idx]) => v+idx);
* => Stream.of("a0", "b1")
*/
zipWithIndex(): Stream<[T,number]> {
return <Stream<[T,number]>>SeqHelpers.zipWithIndex<T>(this);
}
/**
* Reverse the collection. For instance:
*
* Stream.of(1,2,3).reverse();
* => Stream.of(3,2,1)
*/
reverse(): Stream<T> {
return this;
}
/**
* Takes a predicate; returns a pair of collections.
* The first one is the longest prefix of this collection
* which satisfies the predicate, and the second collection
* is the remainder of the collection.
*
* Stream.of(1,2,3,4,5,6).span(x => x <3)
* => [Stream.of(1,2), Stream.of(3,4,5,6)]
*/
span(predicate:(x:T)=>boolean): [Stream<T>,Stream<T>] {
return [this, this];
}
/**
* Split the collection at a specific index.
*
* Stream.of(1,2,3,4,5).splitAt(3)
* => [Stream.of(1,2,3), Stream.of(4,5)]
*/
splitAt(index:number): [Stream<T>,Stream<T>] {
return [this, this];
}
/**
* Returns a pair of two collections; the first one
* will only contain the items from this collection for
* which the predicate you give returns true, the second
* will only contain the items from this collection where
* the predicate returns false.
*
* Stream.of(1,2,3,4).partition(x => x%2===0)
* => [Stream.of(2,4),Stream.of(1,3)]
*/
partition<U extends T>(predicate:(v:T)=>v is U): [Stream<U>,Stream<Exclude<T,U>>];
partition(predicate:(x:T)=>boolean): [Stream<T>,Stream<T>];
partition<U extends T>(predicate:(v:T)=>boolean): [Stream<U>,Stream<any>] {
return [Stream.empty<U>(), Stream.empty<T>()];
}
/**
* Group elements in the collection using a classifier function.
* Elements are then organized in a map. The key is the value of
* the classifier, and in value we get the list of elements
* matching that value.
*
* also see [[ConsStream.arrangeBy]]
*/
groupBy<C>(classifier: (v:T)=>C & WithEquality): HashMap<C,Stream<T>> {
return HashMap.empty<C,Stream<T>>();
}
/**
* Matches each element with a unique key that you extract from it.
* If the same key is present twice, the function will return None.
*
* also see [[ConsStream.groupBy]]
*/
arrangeBy<K>(getKey: (v:T)=>K&WithEquality): Option<HashMap<K,T>> {
return SeqHelpers.arrangeBy<T,K>(this, getKey);
}
/**
* Randomly reorder the elements of the collection.
*/
shuffle(): Stream<T> {
return Stream.ofIterable(SeqHelpers.shuffle(this.toArray()));
}
/**
* Append an element at the end of this Stream.
*/
append(v:T): Stream<T> {
return Stream.of(v);
}
/*
* Append multiple elements at the end of this Stream.
*/
appendAll(elts:Iterable<T>): Stream<T> {
return Stream.ofIterable(elts);
}
/**
* Remove multiple elements from a stream
*
* Stream.of(1,2,3,4,3,2,1).removeAll([2,4])
* => Stream.of(1,3,3,1)
*/
removeAll(elts:Iterable<T&WithEquality>): Stream<T> {
return this;
}
/**
* Removes the first element matching the predicate
* (use [[ConsStream.filter]] to remove all elements matching a predicate)
*/
removeFirst(predicate: (x:T)=>boolean): Stream<T> {
return this;
}
/*
* Append another Stream at the end of this Stream.
*
* There is no function taking a javascript iterator,
* because iterators are stateful and Streams lazy.
* If we would create two Streams working on the same iterator,
* the streams would interact with one another.
* It also breaks the cycle() function.
*/
appendStream(elts:Stream<T>): Stream<T> {
return elts;
}
/**
* Prepend an element at the beginning of the collection.
*/
prepend(elt: T): Stream<T> {
return Stream.of(elt);
}
/**
* Prepend multiple elements at the beginning of the collection.
*/
prependAll(elt: Iterable<T>): Stream<T> {
return Stream.ofIterable(elt);
}
/**
* Repeat infinitely this Stream.
* For instance:
*
* Stream.of(1,2,3).cycle().take(8)
* => Stream.of(1,2,3,1,2,3,1,2)
*/
cycle(): Stream<T> {
return <EmptyStream<T>>emptyStream;
}
/**
* Return a new collection where each element was transformed
* by the mapper function you give.
*/
map<U>(mapper:(v:T)=>U): Stream<U> {
return <EmptyStream<U>>emptyStream;
}
/**
* Apply the mapper function on every element of this collection.
* The mapper function returns an Option; if the Option is a Some,
* the value it contains is added to the result Collection, if it's
* a None, the value is discarded.
*
* Stream.of(1,2,6).mapOption(x => x%2===0 ?
* Option.of(x+1) : Option.none<number>())
* => Stream.of(3, 7)
*/
mapOption<U>(mapper:(v:T)=>Option<U>): Stream<U> {
return <EmptyStream<U>>emptyStream;
}
/**
* Calls the function you give for each item in the collection,
* your function returns a collection, all the collections are
* concatenated.
* This is the monadic bind.
*/
flatMap<U>(mapper:(v:T)=>Stream<U>): Stream<U> {
return <EmptyStream<U>>emptyStream;
}
/**
* Returns true if the predicate returns true for all the
* elements in the collection.
*/
allMatch<U extends T>(predicate:(v:T)=>v is U): this is Stream<U>;
allMatch(predicate:(v:T)=>boolean): boolean;
allMatch(predicate:(v:T)=>boolean): boolean {
return true;
}
/**
* Returns true if there the predicate returns true for any
* element in the collection.
*/
anyMatch(predicate:(v:T)=>boolean): boolean {
return false;
}
/**
* Call a predicate for each element in the collection,
* build a new collection holding only the elements
* for which the predicate returned true.
*/
filter<U extends T>(predicate:(v:T)=>v is U): Stream<U>;
filter(predicate:(v:T)=>boolean): Stream<T>;
filter(predicate:(v:T)=>boolean): Stream<T> {
return this;
}
/**
* Returns a new collection with elements
* sorted according to the comparator you give.
*
* const activityOrder = ["Writer", "Actor", "Director"];
* Stream.of({name:"George", activity: "Director"}, {name:"Robert", activity: "Actor"})
* .sortBy((p1,p2) => activityOrder.indexOf(p1.activity) - activityOrder.indexOf(p2.activity));
* => Stream.of({"name":"Robert","activity":"Actor"}, {"name":"George","activity":"Director"})
*
* also see [[ConsStream.sortOn]]
*/
sortBy(compare: (v1:T,v2:T)=>Ordering): Stream<T> {
return this;
}
/**
* Give a function associating a number or a string with
* elements from the collection, and the elements
* are sorted according to that value.
*
* Stream.of({a:3,b:"b"},{a:1,b:"test"},{a:2,b:"a"}).sortOn(elt=>elt.a)
* => Stream.of({a:1,b:"test"},{a:2,b:"a"},{a:3,b:"b"})
*
* You can also sort by multiple criteria, and request 'descending'
* sorting:
*
* Stream.of({a:1,b:"b"},{a:1,b:"test"},{a:2,b:"a"}).sortOn(elt=>elt.a,{desc:elt=>elt.b})
* => Stream.of({a:1,b:"test"},{a:1,b:"b"},{a:2,b:"a"})
*
* also see [[ConsStream.sortBy]]
*/
sortOn(...getKeys: Array<ToOrderable<T>|{desc:ToOrderable<T>}>): Stream<T> {
return this;
}
/**
* Remove duplicate items; elements are mapped to keys, those
* get compared.
*
* Stream.of(1,1,2,3,2,3,1).distinctBy(x => x);
* => Stream.of(1,2,3)
*/
distinctBy<U>(keyExtractor: (x:T)=>U&WithEquality): Stream<T> {
return this;
}
/**
* Call a function for element in the collection.
*/
forEach(fn: (v:T)=>void): Stream<T> {
return this;
}
/**
* Reduces the collection to a single value by repeatedly
* calling the combine function.
* No starting value. The order in which the elements are
* passed to the combining function is undetermined.
*/
reduce(combine: (v1:T,v2:T)=>T): Option<T> {
return SeqHelpers.reduce(this, combine);
}
/**
* Compare values in the collection and return the smallest element.
* Returns Option.none if the collection is empty.
*
* also see [[ConsStream.minOn]]
*/
minBy(compare: (v1:T,v2:T)=>Ordering): Option<T> {
return Option.none<T>();
}
/**
* Call the function you give for each value in the collection
* and return the element for which the result was the smallest.
* Returns Option.none if the collection is empty.
*
* Stream.of({name:"Joe", age:12}, {name:"Paula", age:6}).minOn(x=>x.age)
* => Option.of({name:"Paula", age:6})
*
* also see [[ConsStream.minBy]]
*/
minOn(getOrderable: ToOrderable<T>): Option<T> {
return Option.none<T>();
}
/**
* Compare values in the collection and return the largest element.
* Returns Option.none if the collection is empty.
*
* also see [[ConsStream.maxOn]]
*/
maxBy(compare: (v1:T,v2:T)=>Ordering): Option<T> {
return Option.none<T>();
}
/**
* Call the function you give for each value in the collection
* and return the element for which the result was the largest.
* Returns Option.none if the collection is empty.
*
* Stream.of({name:"Joe", age:12}, {name:"Paula", age:6}).maxOn(x=>x.age)
* => Option.of({name:"Joe", age:12})
*
* also see [[ConsStream.maxBy]]
*/
maxOn(getOrderable: ToOrderable<T>): Option<T> {
return Option.none<T>();
}
/**
* Call the function you give for each element in the collection
* and sum all the numbers, return that sum.
* Will return 0 if the collection is empty.
*
* Stream.of(1,2,3).sumOn(x=>x)
* => 6
*/
sumOn(getNumber: (v:T)=>number): number {
return 0;
}
/**
* Slides a window of a specific size over the sequence.
* Returns a lazy stream so memory use is not prohibitive.
*
* Stream.of(1,2,3,4,5,6,7,8).sliding(3)
* => Stream.of(Stream.of(1,2,3), Stream.of(4,5,6), Stream.of(7,8))
*/
sliding(count:number): Stream<Stream<T>> {
return <Stream<Stream<T>>>SeqHelpers.sliding(this, count);
}
/**
* Apply the function you give to all elements of the sequence
* in turn, keeping the intermediate results and returning them
* along with the final result in a list.
*
* Stream.of(1,2,3).scanLeft(0, (soFar,cur)=>soFar+cur)
* => Stream.of(0,1,3,6)
*/
scanLeft<U>(init:U, fn:(soFar:U,cur:T)=>U): Stream<U> {
return new ConsStream(init, Lazy.of(()=><EmptyStream<U>>emptyStream));
}
/**
* Apply the function you give to all elements of the sequence
* in turn, keeping the intermediate results and returning them
* along with the final result in a list.
* The first element of the result is the final cumulative result.
*
* Stream.of(1,2,3).scanRight(0, (cur,soFar)=>soFar+cur)
* => Stream.of(6,5,3,0)
*/
scanRight<U>(init:U, fn:(cur:T,soFar:U)=>U): Stream<U> {
return new ConsStream(init, Lazy.of(()=><EmptyStream<U>>emptyStream));
}
/**
* Joins elements of the collection by a separator.
* Example:
*
* Vector.of(1,2,3).mkString(", ")
* => "1, 2, 3"
*/
mkString(separator: string): string {
return "";
}
/**
* Convert to array.
* Don't do it on an infinite stream!
*/
toArray(): T[] {
return [];
}
/**
* Convert to vector.
* Don't do it on an infinite stream!
*/
toVector(): Vector<T> {
return Vector.empty<T>();
}
/**
* Convert this collection to a map. You give a function which
* for each element in the collection returns a pair. The
* key of the pair will be used as a key in the map, the value,
* as a value in the map. If several values get the same key,
* entries will be lost.
*
* Stream.of(1,2,3).toMap(x=>[x.toString(), x])
* => HashMap.of(["1",1], ["2",2], ["3",3])
*/
toMap<K,V>(converter:(x:T)=>[K & WithEquality,V]): HashMap<K,V> {
return HashMap.empty<K,V>();
}
/**
* Convert this collection to a set. Since the elements of the
* Seq may not support equality, you must pass a function returning
* a value supporting equality.
*
* Stream.of(1,2,3,3,4).toSet(x=>x)
* => HashSet.of(1,2,3,4)
*/
toSet<K>(converter:(x:T)=>K&WithEquality): HashSet<K> {
return HashSet.empty<K>();
}
/**
* Convert this collection to a list.
*/
toLinkedList(): LinkedList<T> {
return LinkedList.ofIterable(this);
}
/**
* Transform this value to another value type.
* Enables fluent-style programming by chaining calls.
*/
transform<U>(converter:(x:Stream<T>)=>U): U {
return converter(this);
}
/**
* Two objects are equal if they represent the same value,
* regardless of whether they are the same object physically
* in memory.
*/
equals(other: Stream<T&WithEquality>): boolean {
if (!other) {
return false;
}
return other.isEmpty();
}
/**
* Get a number for that object. Two different values
* may get the same number, but one value must always get
* the same number. The formula can impact performance.
*/
hashCode(): number {
return 1;
}
[inspect](): string {
return this.toString();
}
/**
* Get a human-friendly string representation of that value.
*
* Also see [[ConsStream.mkString]]
*/
toString(): string {
return "[]";
}
}
/**
* ConsStream holds a value and a lazy pointer to a next element,
* which could be [[ConsStream]] or [[EmptyStream]].
* A ConsStream is basically a non-empty stream. It will
* contain at least one element.
* "static methods" available through [[StreamStatic]]
* @param T the item type
*/
export class ConsStream<T> implements Seq<T> {
/**
* @hidden
*/
readonly className: "ConsStream" = <any>undefined; // https://stackoverflow.com/a/47841595/516188
/**
* @hidden
*/
public constructor(protected value: T, protected _tail: Lazy<Stream<T>>) {}
/**
* Implementation of the Iterator interface.
*/
[Symbol.iterator](): Iterator<T> {
let item: Stream<T> = this;
return {
next(): IteratorResult<T> {
if (item.isEmpty()) {
return { done: true, value: <any>undefined };
}
const value = item.head().get();
item = item.tail().get();
return {done: false, value};
}
};
}
/**
* View this Some a as Stream. Useful to help typescript type
* inference sometimes.
*/
asStream(): Stream<T> {
return this;
}
/**
* @hidden
*/
hasTrueEquality(): boolean {
return SeqHelpers.seqHasTrueEquality<T>(this);
}
/**
* Get the length of the collection.
*/
length(): number {
return this.foldLeft(0, (n, ignored) => n + 1);
}
/**
* If the collection contains a single element,
* return Some of its value, otherwise return None.
*/
single(): Option<T> {
return this._tail.get().isEmpty() ?
Option.of(this.value) :
Option.none<T>();
}
/**
* true if the collection is empty, false otherwise.
*/
isEmpty(): this is EmptyStream<T> {
return false;
}
/**
* Get the first value of the collection, if any.
* returns Option.Some if the collection is not empty,
* Option.None if it's empty.
*/
head(): Some<T> {
return Option.some(this.value);
}
/**
* Get all the elements in the collection but the first one.
* If the collection is empty, return None.
*/
tail(): Some<Stream<T>> {
return Option.some(this._tail.get());
}
/**
* Get the last value of the collection, if any.
* returns Option.Some if the collection is not empty,
* Option.None if it's empty.
*/
last(): Some<T> {
let curItem: Stream<T> = this;
while (true) {
const item = (<ConsStream<T>>curItem).value;
curItem = (<ConsStream<T>>curItem)._tail.get();
if (curItem.isEmpty()) {
return Option.some(item);
}
}
}
/**
* Retrieve the element at index idx.
* Returns an option because the collection may
* contain less elements than the index.
*
* Careful this is going to have poor performance
* on Stream, which is not a good data structure
* for random access!
*/
get(idx: number): Option<T> {
let curItem: Stream<T> = this;
let i=0;
while (!curItem.isEmpty()) {
if (i === idx) {
const item = curItem.value;
return Option.of(item);
}
curItem = curItem._tail.get();
++i;
}
return Option.none<T>();
}
/**
* Search for an item matching the predicate you pass,
* return Option.Some of that element if found,
* Option.None otherwise.
*/
find(predicate:(v:T)=>boolean): Option<T> {
let curItem: Stream<T> = this;
while (!curItem.isEmpty()) {
const item = curItem.value;
if (predicate(item)) {
return Option.of(item);
}
curItem = curItem._tail.get();
}
return Option.none<T>();
}
/**
* Returns true if the item is in the collection,
* false otherwise.
*/
contains(v:T&WithEquality): boolean {
return this.find(x => areEqual(x,v)).isSome();
}
/**
* Return a new stream keeping only the first n elements
* from this stream.
*/
take(n: number): Stream<T> {
if (n < 1) {
return <EmptyStream<T>>emptyStream;
}
return new ConsStream(this.value,
Lazy.of(() => this._tail.get().take(n-1)));
}
/**
* Returns a new collection, discarding the elements
* after the first element which fails the predicate.
*/
takeWhile(predicate: (x:T)=>boolean): Stream<T> {
if (!predicate(this.value)) {
return <EmptyStream<T>>emptyStream;
}
return new ConsStream(this.value,
Lazy.of(() => this._tail.get().takeWhile(predicate)));
}
/**
* Returns a new collection, discarding the elements
* after the first element which fails the predicate,
* but starting from the end of the collection.
*
* Stream.of(1,2,3,4).takeRightWhile(x => x > 2)
* => Stream.of(3,4)
*/
takeRightWhile(predicate:(x:T)=>boolean): Stream<T> {
return this.reverse().takeWhile(predicate).reverse();
}
/**
* Returns a new collection with the first
* n elements discarded.
* If the collection has less than n elements,
* returns the empty collection.
*/
drop(n:number): Stream<T> {
let i = n;
let curItem: Stream<T> = this;
while (i-- > 0 && !curItem.isEmpty()) {
curItem = curItem._tail.get();
}
return curItem;
}
/**
* Returns a new collection, discarding the first elements
* until one element fails the predicate. All elements
* after that point are retained.
*/
dropWhile(predicate:(x:T)=>boolean): Stream<T> {
let curItem: Stream<T> = this;
while (!curItem.isEmpty() && predicate(curItem.value)) {
curItem = curItem._tail.get();
}
return curItem;
}
/**
* Returns a new collection with the last
* n elements discarded.
* If the collection has less than n elements,
* returns the empty collection.
*/
dropRight(n:number): Stream<T> {
// going twice through the list...
const length = this.length();
return this.take(length-n);
}
/**
* Returns a new collection, discarding the last elements
* until one element fails the predicate. All elements
* before that point are retained.
*/
dropRightWhile(predicate:(x:T)=>boolean): Stream<T> {
return this.reverse().dropWhile(predicate).reverse();
}
/**
* Reduces the collection to a single value using the
* associative binary function you give. Since the function
* is associative, order of application doesn't matter.
*
* Example:
*
* Stream.of(1,2,3).fold(0, (a,b) => a + b);
* => 6
*/
fold(zero:T, fn:(v1:T,v2:T)=>T): T {
return this.foldLeft(zero, fn);
}
/**
* Reduces the collection to a single value.
* Left-associative.
*
* Example:
*
* Vector.of("a", "b", "c").foldLeft("!", (xs,x) => x+xs);
* => "cba!"
*
* @param zero The initial value
* @param fn A function taking the previous value and
* the current collection item, and returning
* an updated value.
*/
foldLeft<U>(zero: U, fn:(soFar:U,cur:T)=>U): U {
let r = zero;
let curItem: Stream<T> = this;
while (!curItem.isEmpty()) {
r = fn(r, curItem.value);
curItem = curItem._tail.get();
}
return r;
}
/**
* Reduces the collection to a single value.
* Right-associative.
*
* Example:
*
* Vector.of("a", "b", "c").foldRight("!", (x,xs) => xs+x);
* => "!cba"
*
* @param zero The initial value
* @param fn A function taking the current collection item and
* the previous value , and returning
* an updated value.
*/
foldRight<U>(zero: U, fn:(cur:T, soFar:U)=>U): U {
return this.reverse().foldLeft(zero, (xs,x)=>fn(x,xs));
}
/**
* Combine this collection with the collection you give in
* parameter to produce a new collection which combines both,
* in pairs. For instance:
*
* Stream.of(1,2,3).zip(["a","b","c"])
* => Stream.of([1,"a"], [2,"b"], [3,"c"])
*
* The result collection will have the length of the shorter
* of both collections. Extra elements will be discarded.
*
* Also see [[StreamStatic.zip]] (static version which can more than two
* iterables)
*/
zip<U>(other: Iterable<U>): Stream<[T,U]> {
const otherIterator = other[Symbol.iterator]();
let otherCurItem = otherIterator.next();
if (this.isEmpty() || otherCurItem.done) {
return <EmptyStream<[T,U]>>emptyStream;
}
return new ConsStream([this.value, otherCurItem.value] as [T,U],
Lazy.of(() => this._tail.get().zip(
{ [Symbol.iterator]: ()=>otherIterator})));
}
/**
* Combine this collection with the index of the elements
* in it. Handy if you need the index when you map on
* the collection for instance:
*
* Stream.of("a","b").zipWithIndex().map(([v,idx]) => v+idx);
* => Stream.of("a0", "b1")
*/
zipWithIndex(): Stream<[T,number]> {
return <Stream<[T,number]>>SeqHelpers.zipWithIndex<T>(this);
}
/**
* Reverse the collection. For instance:
*
* Stream.of(1,2,3).reverse();
* => Stream.of(3,2,1)
*/
reverse(): Stream<T> {
return this.foldLeft(<Stream<T>><EmptyStream<T>>emptyStream, (xs,x) => xs.prepend(x));
}
/**
* Takes a predicate; returns a pair of collections.
* The first one is the longest prefix of this collection
* which satisfies the predicate, and the second collection
* is the remainder of the collection.
*
* Stream.of(1,2,3,4,5,6).span(x => x <3)
* => [Stream.of(1,2), Stream.of(3,4,5,6)]
*/
span(predicate:(x:T)=>boolean): [Stream<T>,Stream<T>] {
return [this.takeWhile(predicate), this.dropWhile(predicate)];
}
/**
* Split the collection at a specific index.
*
* Stream.of(1,2,3,4,5).splitAt(3)
* => [Stream.of(1,2,3), Stream.of(4,5)]
*/
splitAt(index:number): [Stream<T>,Stream<T>] {
return [this.take(index), this.drop(index)];
}
/**
* Returns a pair of two collections; the first one
* will only contain the items from this collection for
* which the predicate you give returns true, the second
* will only contain the items from this collection where
* the predicate returns false.
*
* Stream.of(1,2,3,4).partition(x => x%2===0)
* => [Stream.of(2,4),Stream.of(1,3)]
*/
partition<U extends T>(predicate:(v:T)=>v is U): [Stream<U>,Stream<Exclude<T,U>>];
partition(predicate:(x:T)=>boolean): [Stream<T>,Stream<T>];
partition(predicate:(v:T)=>boolean): [Stream<T>,Stream<T>] {
// goes twice over the list, but since we want a lazy behavior...
return [this.filter(predicate), this.filter(x => !predicate(x))];
}
/**
* Group elements in the collection using a classifier function.
* Elements are then organized in a map. The key is the value of
* the classifier, and in value we get the list of elements
* matching that value.
*
* also see [[ConsStream.arrangeBy]]
*/
groupBy<C>(classifier: (v:T)=>C & WithEquality): HashMap<C,Stream<T>> {
return this.foldLeft(
HashMap.empty<C,Stream<T>>(),
(acc: HashMap<C,Stream<T>>, v:T) =>
acc.putWithMerge(
classifier(v), Stream.of(v),
(v1:Stream<T>,v2:Stream<T>)=>v1.appendStream(v2)));
}
/**
* Matches each element with a unique key that you extract from it.
* If the same key is present twice, the function will return None.
*
* also see [[ConsStream.groupBy]]
*/
arrangeBy<K>(getKey: (v:T)=>K&WithEquality): Option<HashMap<K,T>> {
return SeqHelpers.arrangeBy<T,K>(this, getKey);
}
/**
* Randomly reorder the elements of the collection.
*/
shuffle(): Stream<T> {
return Stream.ofIterable(SeqHelpers.shuffle(this.toArray()));
}
/**
* Append an element at the end of this Stream.
*/
append(v:T): Stream<T> {
const tail = this._tail.get();
return new ConsStream(
this.value,
Lazy.of(()=>tail.append(v)));
}
/*
* Append multiple elements at the end of this Stream.
*/
appendAll(elts:Iterable<T>): Stream<T> {
return this.appendStream(Stream.ofIterable(elts));
}
/**
* Remove multiple elements from a stream
*
* Stream.of(1,2,3,4,3,2,1).removeAll([2,4])
* => Stream.of(1,3,3,1)
*/
removeAll(elts:Iterable<T&WithEquality>): Stream<T> {
return <Stream<T>><any>SeqHelpers.removeAll(this, elts);
}
/**
* Removes the first element matching the predicate
* (use [[ConsStream.filter]] to remove all elements matching a predicate)
*/
removeFirst(predicate: (x:T)=>boolean): Stream<T> {
const tail = this._tail.get();
return predicate(this.value) ?
tail :
new ConsStream(this.value,
Lazy.of(()=>tail.removeFirst(predicate)));
}
/*
* Append another Stream at the end of this Stream.
*
* There is no function taking a javascript iterator,
* because iterators are stateful and Streams lazy.
* If we would create two Streams working on the same iterator,
* the streams would interact with one another.
* It also breaks the cycle() function.
*/
appendStream(elts:Stream<T>): Stream<T> {
const tail = this._tail.get();
return new ConsStream(
this.value,
Lazy.of(() => tail.appendStream(elts)));
}
/**
* Prepend an element at the beginning of the collection.
*/
prepend(elt: T): Stream<T> {
return new ConsStream(
elt,
Lazy.of(()=>this));
}
/**
* Prepend multiple elements at the beginning of the collection.
*/
prependAll(elts: Iterable<T>): Stream<T> {
return Stream.ofIterable(elts).appendAll(this);
}
/**
* Repeat infinitely this Stream.
* For instance:
*
* Stream.of(1,2,3).cycle().take(8)
* => Stream.of(1,2,3,1,2,3,1,2)
*/
cycle(): Stream<T> {
return this._cycle(this);
}
private _cycle(toRepeat: Stream<T>): Stream<T> {
const tail = this._tail.get();
return new ConsStream(
this.value,
Lazy.of(() => tail.isEmpty() ? toRepeat.cycle() : tail._cycle(toRepeat)));
}
/**
* Return a new collection where each element was transformed
* by the mapper function you give.
*/
map<U>(mapper:(v:T)=>U): Stream<U> {
return new ConsStream(mapper(this.value),
Lazy.of(() => this._tail.get().map(mapper)));
}
/**
* Apply the mapper function on every element of this collection.
* The mapper function returns an Option; if the Option is a Some,
* the value it contains is added to the result Collection, if it's
* a None, the value is discarded.
*
* Stream.of(1,2,6).mapOption(x => x%2===0 ?
* Option.of(x+1) : Option.none<number>())
* => Stream.of(3, 7)
*/
mapOption<U>(mapper:(v:T)=>Option<U>): Stream<U> {
const mapped = mapper(this.value);
return mapped.isSome() ?
new ConsStream(mapped.get(),
Lazy.of(() => this._tail.get().mapOption(mapper))) :
this._tail.get().mapOption(mapper);
}
/**
* Calls the function you give for each item in the collection,
* your function returns a collection, all the collections are
* concatenated.
* This is the monadic bind.
*/
flatMap<U>(mapper:(v:T)=>Stream<U>): Stream<U> {
return mapper(this.value).appendStream(
this._tail.get().flatMap(mapper));
}
/**
* Returns true if the predicate returns true for all the
* elements in the collection.
*/
allMatch<U extends T>(predicate:(v:T)=>v is U): this is Stream<U>;
allMatch(predicate:(v:T)=>boolean): boolean;
allMatch(predicate:(v:T)=>boolean): boolean {
return this.find(x => !predicate(x)).isNone();
}
/**
* Returns true if there the predicate returns true for any
* element in the collection.
*/
anyMatch(predicate:(v:T)=>boolean): boolean {
return this.find(predicate).isSome();
}
/**
* Call a predicate for each element in the collection,
* build a new collection holding only the elements
* for which the predicate returned true.
*/
filter<U extends T>(predicate:(v:T)=>v is U): Stream<U>;
filter(predicate:(v:T)=>boolean): Stream<T>;
filter(predicate:(v:T)=>boolean): Stream<T> {
return predicate(this.value) ?
new ConsStream(this.value,
Lazy.of(() => this._tail.get().filter(predicate))) :
this._tail.get().filter(predicate);
}
/**
* Returns a new collection with elements
* sorted according to the comparator you give.
*
* const activityOrder = ["Writer", "Actor", "Director"];
* Stream.of({name:"George", activity: "Director"}, {name:"Robert", activity: "Actor"})
* .sortBy((p1,p2) => activityOrder.indexOf(p1.activity) - activityOrder.indexOf(p2.activity));
* => Stream.of({"name":"Robert","activity":"Actor"}, {"name":"George","activity":"Director"})
*
* also see [[ConsStream.sortOn]]
*/
sortBy(compare: (v1:T,v2:T)=>Ordering): Stream<T> {
return Stream.ofIterable<T>(this.toArray().sort(compare));
}
/**
* Give a function associating a number or a string with
* elements from the collection, and the elements
* are sorted according to that value.
*
* Stream.of({a:3,b:"b"},{a:1,b:"test"},{a:2,b:"a"}).sortOn(elt=>elt.a)
* => Stream.of({a:1,b:"test"},{a:2,b:"a"},{a:3,b:"b"})
*
* You can also sort by multiple criteria, and request 'descending'
* sorting:
*
* Stream.of({a:1,b:"b"},{a:1,b:"test"},{a:2,b:"a"}).sortOn(elt=>elt.a,{desc:elt=>elt.b})
* => Stream.of({a:1,b:"test"},{a:1,b:"b"},{a:2,b:"a"})
*
* also see [[ConsStream.sortBy]]
*/
sortOn(...getKeys: Array<ToOrderable<T>|{desc:ToOrderable<T>}>): Stream<T> {
return <Stream<T>>SeqHelpers.sortOn<T>(this, getKeys);
}
/**
* Remove duplicate items; elements are mapped to keys, those
* get compared.
*
* Stream.of(1,1,2,3,2,3,1).distinctBy(x => x);
* => Stream.of(1,2,3)
*/
distinctBy<U>(keyExtractor: (x:T)=>U&WithEquality): Stream<T> {
return <Stream<T>>SeqHelpers.distinctBy(this, keyExtractor);
}
/**
* Call a function for element in the collection.
*/
forEach(fn: (v:T)=>void): Stream<T> {
let curItem: Stream<T> = this;
while (!curItem.isEmpty()) {
fn(curItem.value);
curItem = curItem._tail.get();
}
return this;
}
/**
* Reduces the collection to a single value by repeatedly
* calling the combine function.
* No starting value. The order in which the elements are
* passed to the combining function is undetermined.
*/
reduce(combine: (v1:T,v2:T)=>T): Option<T> {
return SeqHelpers.reduce(this, combine);
}
/**
* Compare values in the collection and return the smallest element.
* Returns Option.none if the collection is empty.
*
* also see [[ConsStream.minOn]]
*/
minBy(compare: (v1:T,v2:T)=>Ordering): Option<T> {
return SeqHelpers.minBy(this, compare);
}
/**
* Call the function you give for each value in the collection
* and return the element for which the result was the smallest.
* Returns Option.none if the collection is empty.
*
* Stream.of({name:"Joe", age:12}, {name:"Paula", age:6}).minOn(x=>x.age)
* => Option.of({name:"Paula", age:6})
*
* also see [[ConsStream.minBy]]
*/
minOn(getOrderable: ToOrderable<T>): Option<T> {
return SeqHelpers.minOn(this, getOrderable);
}
/**
* Compare values in the collection and return the largest element.
* Returns Option.none if the collection is empty.
*
* also see [[ConsStream.maxOn]]
*/
maxBy(compare: (v1:T,v2:T)=>Ordering): Option<T> {
return SeqHelpers.maxBy(this, compare);
}
/**
* Call the function you give for each value in the collection
* and return the element for which the result was the largest.
* Returns Option.none if the collection is empty.
*
* Stream.of({name:"Joe", age:12}, {name:"Paula", age:6}).maxOn(x=>x.age)
* => Option.of({name:"Joe", age:12})
*
* also see [[ConsStream.maxBy]]
*/
maxOn(getOrderable: ToOrderable<T>): Option<T> {
return SeqHelpers.maxOn(this, getOrderable);
}
/**
* Call the function you give for each element in the collection
* and sum all the numbers, return that sum.
* Will return 0 if the collection is empty.
*
* Stream.of(1,2,3).sumOn(x=>x)
* => 6
*/
sumOn(getNumber: (v:T)=>number): number {
return SeqHelpers.sumOn(this, getNumber);
}
/**
* Slides a window of a specific size over the sequence.
* Returns a lazy stream so memory use is not prohibitive.
*
* Stream.of(1,2,3,4,5,6,7,8).sliding(3)
* => Stream.of(Stream.of(1,2,3), Stream.of(4,5,6), Stream.of(7,8))
*/
sliding(count:number): Stream<Stream<T>> {
return <Stream<Stream<T>>>SeqHelpers.sliding(this, count);
}
/**
* Apply the function you give to all elements of the sequence
* in turn, keeping the intermediate results and returning them
* along with the final result in a list.
*
* Stream.of(1,2,3).scanLeft(0, (soFar,cur)=>soFar+cur)
* => Stream.of(0,1,3,6)
*/
scanLeft<U>(init:U, fn:(soFar:U,cur:T)=>U): Stream<U> {
return new ConsStream(
init,
Lazy.of(()=>this._tail.get().scanLeft(fn(init, this.value), fn)));
}
/**
* Apply the function you give to all elements of the sequence
* in turn, keeping the intermediate results and returning them
* along with the final result in a list.
* The first element of the result is the final cumulative result.
*
* Stream.of(1,2,3).scanRight(0, (cur,soFar)=>soFar+cur)
* => Stream.of(6,5,3,0)
*/
scanRight<U>(init:U, fn:(cur:T,soFar:U)=>U): Stream<U> {
// can't be lazy
const fn2 = (x:U,y:T)=>fn(y,x);
return this.reverse().scanLeft(init, fn2).reverse();
}
/**
* Joins elements of the collection by a separator.
* Example:
*
* Vector.of(1,2,3).mkString(", ")
* => "1, 2, 3"
*/
mkString(separator: string): string {
let r = "";
let curItem: Stream<T> = this;
let isNotFirst = false;
while (!curItem.isEmpty()) {
if (isNotFirst) {
r += separator;
}
r += SeqHelpers.toStringHelper(curItem.value, {quoteStrings:false});
curItem = curItem._tail.get();
isNotFirst = true;
}
return r;
}
/**
* Convert to array.
* Don't do it on an infinite stream!
*/
toArray(): T[] {
let r:T[] = [];
let curItem: Stream<T> = this;
while (!curItem.isEmpty()) {
r.push(curItem.value);
curItem = curItem._tail.get();
}
return r;
}
/**
* Convert to vector.
* Don't do it on an infinite stream!
*/
toVector(): Vector<T> {
return Vector.ofIterable<T>(this.toArray());
}
/**
* Convert this collection to a map. You give a function which
* for each element in the collection returns a pair. The
* key of the pair will be used as a key in the map, the value,
* as a value in the map. If several values get the same key,
* entries will be lost.
*
* Stream.of(1,2,3).toMap(x=>[x.toString(), x])
* => HashMap.of(["1",1], ["2",2], ["3",3])
*/
toMap<K,V>(converter:(x:T)=>[K & WithEquality,V]): HashMap<K,V> {
return this.foldLeft(HashMap.empty<K,V>(), (acc,cur) => {
const converted = converter(cur);
return acc.put(converted[0], converted[1]);
});
}
/**
* Convert this collection to a set. Since the elements of the
* Seq may not support equality, you must pass a function returning
* a value supporting equality.
*
* Stream.of(1,2,3,3,4).toSet(x=>x)
* => HashSet.of(1,2,3,4)
*/
toSet<K>(converter:(x:T)=>K&WithEquality): HashSet<K> {
return this.foldLeft(HashSet.empty<K>(), (acc,cur) => {
return acc.add(converter(cur));
});
}
/**
* Convert this collection to a list.
*/
toLinkedList(): LinkedList<T> {
return LinkedList.ofIterable(this);
}
/**
* Transform this value to another value type.
* Enables fluent-style programming by chaining calls.
*/
transform<U>(converter:(x:Stream<T>)=>U): U {
return converter(this);
}
/**
* Two objects are equal if they represent the same value,
* regardless of whether they are the same object physically
* in memory.
*/
equals(other: Stream<T&WithEquality>): boolean {
if (<any>other === this) {
return true;
}
if (!other || !other.tail) {
return false;
}
contractTrueEquality("Stream.equals", this, other);
let myVal: Stream<T> = this;
let hisVal = other;
while (true) {
if (myVal.isEmpty() !== hisVal.isEmpty()) {
return false;
}
if (myVal.isEmpty()) {
// they are both empty, end of the stream
return true;
}
const myHead = myVal.value;
const hisHead = (<ConsStream<T>>hisVal).value;
if ((myHead === undefined) !== (hisHead === undefined)) {
return false;
}
if (myHead === undefined || hisHead === undefined) {
// they are both undefined, the || is for TS's flow analysis
// so he realizes none of them is undefined after this.
continue;
}
if (!areEqual(myHead, hisHead)) {
return false;
}
myVal = myVal._tail.get();
hisVal = (<ConsStream<T&WithEquality>>hisVal)._tail.get();
}
}
/**
* Get a number for that object. Two different values
* may get the same number, but one value must always get
* the same number. The formula can impact performance.
*/
hashCode(): number {
let hash = 1;
let curItem: Stream<T> = this;
while (!curItem.isEmpty()) {
hash = 31 * hash + getHashCode(curItem.value);
curItem = curItem._tail.get();
}
return hash;
}
[inspect](): string {
return this.toString();
}
/**
* Get a human-friendly string representation of that value.
*
* Also see [[ConsStream.mkString]]
*/
toString(): string {
let curItem: Stream<T> = this;
let result = "Stream(";
while (!curItem.isEmpty()) {
result += SeqHelpers.toStringHelper(curItem.value);
const tail: Lazy<Stream<T>> = curItem._tail;
if (!tail.isEvaluated()) {
result += ", ?";
break;
}
curItem = tail.get();
if (!curItem.isEmpty()) {
result += ", ";
}
}
return result + ")";
}
}
const emptyStream = new EmptyStream<any>(); | the_stack |
import { ArmSiteDescriptor } from 'app/shared/resourceDescriptors';
import { FunctionAppService } from 'app/shared/services/function-app.service';
import { FunctionAppContextComponent } from 'app/shared/components/function-app-context-component';
import { LogCategories, SiteTabIds } from './../shared/models/constants';
import { LogService } from './../shared/services/log.service';
import { ArmService } from 'app/shared/services/arm.service';
import { BusyStateScopeManager } from './../busy-state/busy-state-scope-manager';
import { BroadcastService } from './../shared/services/broadcast.service';
import { DropDownElement } from './../shared/models/drop-down-element';
import { PortalResources } from './../shared/models/portal-resources';
import { TableItem, TblComponent } from './../controls/tbl/tbl.component';
import { ViewChild } from '@angular/core';
import { Subscription as RxSubscription } from 'rxjs/Subscription';
import { TranslateService } from '@ngx-translate/core';
import { CacheService } from './../shared/services/cache.service';
import { PortalService } from './../shared/services/portal.service';
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { FunctionService } from 'app/shared/services/function.service';
interface LogicAppInfo {
name: string;
id: string;
resourceGroup: string;
location: string;
}
export interface LogicAppTableItem extends TableItem {
title: string;
id: string;
resourceGroup: string;
location: string;
}
@Component({
selector: 'app-logic-apps',
templateUrl: './logic-apps.component.html',
styleUrls: ['./logic-apps.component.scss'],
})
export class LogicAppsComponent extends FunctionAppContextComponent {
private _resourceId: string;
public logicApps: LogicAppInfo[] = [];
public tableItems: TableItem[] = [];
public subId: string;
public logicAppsIcon = 'image/logicapp.svg';
public initialized = false;
public allLocations = this._translateService.instant(PortalResources.allLocations);
public numberLocations = this._translateService.instant(PortalResources.locationCount);
public locationOptions: DropDownElement<string>[] = [];
public locationsDisplayText = this.allLocations;
public selectedLocations: string[] = [];
public allResourceGroups = this._translateService.instant(PortalResources.allResourceGroups);
public numberResourceGroups = this._translateService.instant(PortalResources.resourceGroupCount);
public resourceGroupOptions: DropDownElement<string>[] = [];
public resourceGroupsDisplayText = this.allResourceGroups;
public selectedResourceGroups: string[] = [];
private _busyManager: BusyStateScopeManager;
@ViewChild('table')
logicAppTable: TblComponent;
public groupOptions: DropDownElement<string>[] = [
{ displayLabel: this._translateService.instant(PortalResources.grouping_none), value: 'none' },
{ displayLabel: this._translateService.instant(PortalResources.grouping_resourceGroup), value: 'resourceGroup' },
{ displayLabel: this._translateService.instant(PortalResources.grouping_location), value: 'location' },
];
public groupDisplayText = '';
public currGroup = 'none';
constructor(
private _armService: ArmService,
private _portalService: PortalService,
private _cacheService: CacheService,
private _translateService: TranslateService,
private _logService: LogService,
_functionAppService: FunctionAppService,
broadcastService: BroadcastService,
functionService: FunctionService
) {
super('logic-apps', _functionAppService, broadcastService, functionService);
this._busyManager = new BusyStateScopeManager(broadcastService, SiteTabIds.logicApps);
}
setup(): RxSubscription {
return this.viewInfoEvents
.switchMap(viewInfo => {
this._busyManager.setBusy();
this.initialized = false;
this._resourceId = viewInfo.resourceId;
this.subId = new ArmSiteDescriptor(this._resourceId).getWebsiteId().SubscriptionId;
// Have to remove leading '/' for filter to function and ending '/' for unique function apps
const logicAppResId = this._resourceId.substr(1) + '/';
return Observable.zip(
this._cacheService.getArm(
`/subscriptions/${this.subId}/providers/Microsoft.Logic/workflows?api-version=${
this._armService.logicAppsApiVersion
}&$filter=contains(referencedResourceId, '${logicAppResId}')`,
true,
this._armService.logicAppsApiVersion,
true
),
this._cacheService.getArm(
`/subscriptions/${this.subId}/providers/Microsoft.Logic/workflows`,
true,
this._armService.logicAppsApiVersion,
true
),
(a, s) => ({ app: a.json(), sub: s.json() })
);
})
.do(null, e => {
this._logService.error(LogCategories.generalSettings, '/logic-apps', e);
})
.retry()
.subscribe(r => {
const selectedJson = r.app.value.length > 0 ? r.app : r.sub;
this.logicApps = selectedJson.value
.map(
app =>
<LogicAppInfo>{
name: app.name,
id: app.id,
resourceGroup: app.id.split('/')[4],
location: this._translateService.instant(app.location),
type: 'row',
}
)
.sort((a: LogicAppInfo, b: LogicAppInfo) => {
return a.name.localeCompare(b.name);
});
this.tableItems = this.logicApps.map(
app =>
<LogicAppTableItem>{
title: app.name,
id: app.id,
resourceGroup: app.resourceGroup,
location: app.location,
type: 'row',
}
);
this.locationOptions = this.uniqueTypes(this.logicApps, 'location').map(location => ({
displayLabel: location,
value: location,
}));
this.resourceGroupOptions = this.uniqueTypes(this.logicApps, 'resourceGroup').map(resourceGroup => ({
displayLabel: resourceGroup,
value: resourceGroup,
}));
this._busyManager.clearBusy();
this.initialized = true;
});
}
clickRow(item: LogicAppTableItem) {
this._portalService.openBladeDeprecated(
{
detailBlade: 'LogicAppsDesignerBlade',
detailBladeInputs: {
id: item.id,
},
extension: 'Microsoft_Azure_EMA',
},
'LogicAppsComponent'
);
}
uniqueTypes(apps: LogicAppInfo[], type: string) {
const typeDict = {};
apps.forEach(app => (typeDict[app[type]] = app[type]));
const typeArray = [];
for (const typeItem in typeDict) {
if (typeDict.hasOwnProperty(typeItem)) {
typeArray.push(typeItem);
}
}
return typeArray.sort();
}
// Todo: [agruning] Encapsulate locations/resources drop-down logic - https://github.com/Azure/azure-functions-ux/issues/1897
onLocationsSelect(locations: string[]) {
this.selectedLocations = locations;
const newItems = this.tableItems.filter(item => item.type === 'group');
const filteredItems = this.logicApps
.filter(app => this.selectedLocations.find(l => l === app.location))
.filter(app => this.selectedResourceGroups.find(r => r === app.resourceGroup))
.map(
app =>
<LogicAppTableItem>{
title: app.name,
id: app.id,
type: 'row',
resourceGroup: app.resourceGroup,
location: app.location,
}
);
this.tableItems = newItems.concat(filteredItems);
// timeout is needed to re-render to page for the grouping update with new locations
setTimeout(() => {
this.logicAppTable.groupItems(this.currGroup);
}, 0);
if (this.selectedLocations.length === this.locationOptions.length) {
this._updateLocDisplayText(this.allLocations);
} else if (this.selectedLocations.length > 1) {
this._updateLocDisplayText(this.numberLocations.format(locations.length));
} else {
this._updateLocDisplayText(`${this.selectedLocations[0]}`);
}
}
private _updateLocDisplayText(displayText: string) {
// timeout is needed to re-render the page for display update
setTimeout(() => {
this.locationsDisplayText = displayText;
}, 0);
}
onResourceGroupsSelect(resourceGroups: string[]) {
this.selectedResourceGroups = resourceGroups;
const newItems = this.tableItems.filter(item => item.type === 'group');
const filteredItems = this.logicApps
.filter(app => this.selectedResourceGroups.find(r => r === app.resourceGroup))
.filter(app => this.selectedLocations.find(l => l === app.location))
.map(
app =>
<LogicAppTableItem>{
title: app.name,
id: app.id,
type: 'row',
resourceGroup: app.resourceGroup,
location: app.location,
}
);
this.tableItems = newItems.concat(filteredItems);
// timeout is needed to re-render to page for the grouping update with new resourceGroups
setTimeout(() => {
this.logicAppTable.groupItems(this.currGroup);
}, 0);
if (this.selectedResourceGroups.length === this.resourceGroupOptions.length) {
this._updateResGroupDisplayText(this.allResourceGroups);
} else if (this.selectedResourceGroups.length > 1) {
this._updateResGroupDisplayText(this.numberResourceGroups.format(resourceGroups.length));
} else {
this._updateResGroupDisplayText(`${this.selectedResourceGroups[0]}`);
}
}
private _updateResGroupDisplayText(displayText: string) {
// timeout is needed to re-render the page for display update
setTimeout(() => {
this.resourceGroupsDisplayText = displayText;
}, 0);
}
onGroupSelect(group: string) {
this.currGroup = group;
// timeout is needed to re-render the page for grouping update
setTimeout(() => {
this.logicAppTable.groupItems(group);
}, 0);
}
} | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Operations
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface Operations {
/**
* Lists all of the available insights REST API operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>;
/**
* Lists all of the available insights REST API operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>;
list(callback: ServiceCallback<models.OperationListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void;
/**
* Lists all of the available insights REST API operations.
*
* @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<OperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>;
/**
* Lists all of the available insights REST API operations.
*
* @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 {OperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void;
}
/**
* @class
* Annotations
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface Annotations {
/**
* Gets the list of annotations for a component for given time range
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} start The start time to query from for annotations, cannot
* be older than 90 days from current date.
*
* @param {string} end The end time to query for annotations.
*
* @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<AnnotationsListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(resourceGroupName: string, resourceName: string, start: string, end: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AnnotationsListResult>>;
/**
* Gets the list of annotations for a component for given time range
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} start The start time to query from for annotations, cannot
* be older than 90 days from current date.
*
* @param {string} end The end time to query for annotations.
*
* @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 {AnnotationsListResult} - 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.
*
* {AnnotationsListResult} [result] - The deserialized result object if an error did not occur.
* See {@link AnnotationsListResult} 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(resourceGroupName: string, resourceName: string, start: string, end: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AnnotationsListResult>;
list(resourceGroupName: string, resourceName: string, start: string, end: string, callback: ServiceCallback<models.AnnotationsListResult>): void;
list(resourceGroupName: string, resourceName: string, start: string, end: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AnnotationsListResult>): void;
/**
* Create an Annotation of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} annotationProperties Properties that need to be specified to
* create an annotation of a Application Insights component.
*
* @param {string} [annotationProperties.annotationName] Name of annotation
*
* @param {string} [annotationProperties.category] Category of annotation, free
* form
*
* @param {date} [annotationProperties.eventTime] Time when event occurred
*
* @param {string} [annotationProperties.id] Unique Id for annotation
*
* @param {string} [annotationProperties.properties] Serialized JSON object for
* detailed properties
*
* @param {string} [annotationProperties.relatedAnnotation] Related parent
* annotation if any
*
* @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<Array>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(resourceGroupName: string, resourceName: string, annotationProperties: models.Annotation, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Annotation[]>>;
/**
* Create an Annotation of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} annotationProperties Properties that need to be specified to
* create an annotation of a Application Insights component.
*
* @param {string} [annotationProperties.annotationName] Name of annotation
*
* @param {string} [annotationProperties.category] Category of annotation, free
* form
*
* @param {date} [annotationProperties.eventTime] Time when event occurred
*
* @param {string} [annotationProperties.id] Unique Id for annotation
*
* @param {string} [annotationProperties.properties] Serialized JSON object for
* detailed properties
*
* @param {string} [annotationProperties.relatedAnnotation] Related parent
* annotation if any
*
* @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 {Array} - 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.
*
* {Array} [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.
*/
create(resourceGroupName: string, resourceName: string, annotationProperties: models.Annotation, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Annotation[]>;
create(resourceGroupName: string, resourceName: string, annotationProperties: models.Annotation, callback: ServiceCallback<models.Annotation[]>): void;
create(resourceGroupName: string, resourceName: string, annotationProperties: models.Annotation, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Annotation[]>): void;
/**
* Delete an Annotation of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} annotationId The unique annotation ID. This is unique within
* a Application Insights component.
*
* @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<Object>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, resourceName: string, annotationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<any>>;
/**
* Delete an Annotation of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} annotationId The unique annotation ID. This is unique within
* a Application Insights component.
*
* @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 {Object} - 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.
*
* {Object} [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, resourceName: string, annotationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<any>;
deleteMethod(resourceGroupName: string, resourceName: string, annotationId: string, callback: ServiceCallback<any>): void;
deleteMethod(resourceGroupName: string, resourceName: string, annotationId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<any>): void;
/**
* Get the annotation for given id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} annotationId The unique annotation ID. This is unique within
* a Application Insights component.
*
* @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<Array>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, annotationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Annotation[]>>;
/**
* Get the annotation for given id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} annotationId The unique annotation ID. This is unique within
* a Application Insights component.
*
* @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 {Array} - 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.
*
* {Array} [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.
*/
get(resourceGroupName: string, resourceName: string, annotationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Annotation[]>;
get(resourceGroupName: string, resourceName: string, annotationId: string, callback: ServiceCallback<models.Annotation[]>): void;
get(resourceGroupName: string, resourceName: string, annotationId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Annotation[]>): void;
}
/**
* @class
* APIKeys
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface APIKeys {
/**
* Gets a list of API keys of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<ApplicationInsightsComponentAPIKeyListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentAPIKeyListResult>>;
/**
* Gets a list of API keys of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {ApplicationInsightsComponentAPIKeyListResult} - 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.
*
* {ApplicationInsightsComponentAPIKeyListResult} [result] - The deserialized result object if an error did not occur.
* See {@link
* ApplicationInsightsComponentAPIKeyListResult} 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(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentAPIKeyListResult>;
list(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.ApplicationInsightsComponentAPIKeyListResult>): void;
list(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentAPIKeyListResult>): void;
/**
* Create an API Key of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} aPIKeyProperties Properties that need to be specified to
* create an API key of a Application Insights component.
*
* @param {string} [aPIKeyProperties.name] The name of the API Key.
*
* @param {array} [aPIKeyProperties.linkedReadProperties] The read access
* rights of this API Key.
*
* @param {array} [aPIKeyProperties.linkedWriteProperties] The write access
* rights of this API 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<ApplicationInsightsComponentAPIKey>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(resourceGroupName: string, resourceName: string, aPIKeyProperties: models.APIKeyRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentAPIKey>>;
/**
* Create an API Key of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} aPIKeyProperties Properties that need to be specified to
* create an API key of a Application Insights component.
*
* @param {string} [aPIKeyProperties.name] The name of the API Key.
*
* @param {array} [aPIKeyProperties.linkedReadProperties] The read access
* rights of this API Key.
*
* @param {array} [aPIKeyProperties.linkedWriteProperties] The write access
* rights of this API 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 {ApplicationInsightsComponentAPIKey} - 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.
*
* {ApplicationInsightsComponentAPIKey} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentAPIKey} 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(resourceGroupName: string, resourceName: string, aPIKeyProperties: models.APIKeyRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentAPIKey>;
create(resourceGroupName: string, resourceName: string, aPIKeyProperties: models.APIKeyRequest, callback: ServiceCallback<models.ApplicationInsightsComponentAPIKey>): void;
create(resourceGroupName: string, resourceName: string, aPIKeyProperties: models.APIKeyRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentAPIKey>): void;
/**
* Delete an API Key of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} keyId The API Key ID. This is unique within a Application
* Insights component.
*
* @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<ApplicationInsightsComponentAPIKey>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, resourceName: string, keyId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentAPIKey>>;
/**
* Delete an API Key of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} keyId The API Key ID. This is unique within a Application
* Insights component.
*
* @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 {ApplicationInsightsComponentAPIKey} - 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.
*
* {ApplicationInsightsComponentAPIKey} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentAPIKey} 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.
*/
deleteMethod(resourceGroupName: string, resourceName: string, keyId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentAPIKey>;
deleteMethod(resourceGroupName: string, resourceName: string, keyId: string, callback: ServiceCallback<models.ApplicationInsightsComponentAPIKey>): void;
deleteMethod(resourceGroupName: string, resourceName: string, keyId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentAPIKey>): void;
/**
* Get the API Key for this key id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} keyId The API Key ID. This is unique within a Application
* Insights component.
*
* @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<ApplicationInsightsComponentAPIKey>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, keyId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentAPIKey>>;
/**
* Get the API Key for this key id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} keyId The API Key ID. This is unique within a Application
* Insights component.
*
* @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 {ApplicationInsightsComponentAPIKey} - 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.
*
* {ApplicationInsightsComponentAPIKey} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentAPIKey} 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, resourceName: string, keyId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentAPIKey>;
get(resourceGroupName: string, resourceName: string, keyId: string, callback: ServiceCallback<models.ApplicationInsightsComponentAPIKey>): void;
get(resourceGroupName: string, resourceName: string, keyId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentAPIKey>): void;
}
/**
* @class
* ExportConfigurations
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface ExportConfigurations {
/**
* Gets a list of Continuous Export configuration of an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<Array>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentExportConfiguration[]>>;
/**
* Gets a list of Continuous Export configuration of an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {Array} - 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.
*
* {Array} [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.
*/
list(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentExportConfiguration[]>;
list(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.ApplicationInsightsComponentExportConfiguration[]>): void;
list(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentExportConfiguration[]>): void;
/**
* Create a Continuous Export configuration of an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} exportProperties Properties that need to be specified to
* create a Continuous Export configuration of a Application Insights
* component.
*
* @param {string} [exportProperties.recordTypes] The document types to be
* exported, as comma separated values. Allowed values include 'Requests',
* 'Event', 'Exceptions', 'Metrics', 'PageViews', 'PageViewPerformance', 'Rdd',
* 'PerformanceCounters', 'Availability', 'Messages'.
*
* @param {string} [exportProperties.destinationType] The Continuous Export
* destination type. This has to be 'Blob'.
*
* @param {string} [exportProperties.destinationAddress] The SAS URL for the
* destination storage container. It must grant write permission.
*
* @param {string} [exportProperties.isEnabled] Set to 'true' to create a
* Continuous Export configuration as enabled, otherwise set it to 'false'.
*
* @param {string} [exportProperties.notificationQueueEnabled] Deprecated
*
* @param {string} [exportProperties.notificationQueueUri] Deprecated
*
* @param {string} [exportProperties.destinationStorageSubscriptionId] The
* subscription ID of the destination storage container.
*
* @param {string} [exportProperties.destinationStorageLocationId] The location
* ID of the destination storage container.
*
* @param {string} [exportProperties.destinationAccountId] The name of
* destination storage account.
*
* @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<Array>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(resourceGroupName: string, resourceName: string, exportProperties: models.ApplicationInsightsComponentExportRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentExportConfiguration[]>>;
/**
* Create a Continuous Export configuration of an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} exportProperties Properties that need to be specified to
* create a Continuous Export configuration of a Application Insights
* component.
*
* @param {string} [exportProperties.recordTypes] The document types to be
* exported, as comma separated values. Allowed values include 'Requests',
* 'Event', 'Exceptions', 'Metrics', 'PageViews', 'PageViewPerformance', 'Rdd',
* 'PerformanceCounters', 'Availability', 'Messages'.
*
* @param {string} [exportProperties.destinationType] The Continuous Export
* destination type. This has to be 'Blob'.
*
* @param {string} [exportProperties.destinationAddress] The SAS URL for the
* destination storage container. It must grant write permission.
*
* @param {string} [exportProperties.isEnabled] Set to 'true' to create a
* Continuous Export configuration as enabled, otherwise set it to 'false'.
*
* @param {string} [exportProperties.notificationQueueEnabled] Deprecated
*
* @param {string} [exportProperties.notificationQueueUri] Deprecated
*
* @param {string} [exportProperties.destinationStorageSubscriptionId] The
* subscription ID of the destination storage container.
*
* @param {string} [exportProperties.destinationStorageLocationId] The location
* ID of the destination storage container.
*
* @param {string} [exportProperties.destinationAccountId] The name of
* destination storage account.
*
* @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 {Array} - 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.
*
* {Array} [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.
*/
create(resourceGroupName: string, resourceName: string, exportProperties: models.ApplicationInsightsComponentExportRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentExportConfiguration[]>;
create(resourceGroupName: string, resourceName: string, exportProperties: models.ApplicationInsightsComponentExportRequest, callback: ServiceCallback<models.ApplicationInsightsComponentExportConfiguration[]>): void;
create(resourceGroupName: string, resourceName: string, exportProperties: models.ApplicationInsightsComponentExportRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentExportConfiguration[]>): void;
/**
* Delete a Continuous Export configuration of an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} exportId The Continuous Export configuration ID. This is
* unique within a Application Insights component.
*
* @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<ApplicationInsightsComponentExportConfiguration>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, resourceName: string, exportId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentExportConfiguration>>;
/**
* Delete a Continuous Export configuration of an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} exportId The Continuous Export configuration ID. This is
* unique within a Application Insights component.
*
* @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 {ApplicationInsightsComponentExportConfiguration} - 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.
*
* {ApplicationInsightsComponentExportConfiguration} [result] - The deserialized result object if an error did not occur.
* See {@link
* ApplicationInsightsComponentExportConfiguration} 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.
*/
deleteMethod(resourceGroupName: string, resourceName: string, exportId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentExportConfiguration>;
deleteMethod(resourceGroupName: string, resourceName: string, exportId: string, callback: ServiceCallback<models.ApplicationInsightsComponentExportConfiguration>): void;
deleteMethod(resourceGroupName: string, resourceName: string, exportId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentExportConfiguration>): void;
/**
* Get the Continuous Export configuration for this export id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} exportId The Continuous Export configuration ID. This is
* unique within a Application Insights component.
*
* @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<ApplicationInsightsComponentExportConfiguration>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, exportId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentExportConfiguration>>;
/**
* Get the Continuous Export configuration for this export id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} exportId The Continuous Export configuration ID. This is
* unique within a Application Insights component.
*
* @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 {ApplicationInsightsComponentExportConfiguration} - 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.
*
* {ApplicationInsightsComponentExportConfiguration} [result] - The deserialized result object if an error did not occur.
* See {@link
* ApplicationInsightsComponentExportConfiguration} 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, resourceName: string, exportId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentExportConfiguration>;
get(resourceGroupName: string, resourceName: string, exportId: string, callback: ServiceCallback<models.ApplicationInsightsComponentExportConfiguration>): void;
get(resourceGroupName: string, resourceName: string, exportId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentExportConfiguration>): void;
/**
* Update the Continuous Export configuration for this export id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} exportId The Continuous Export configuration ID. This is
* unique within a Application Insights component.
*
* @param {object} exportProperties Properties that need to be specified to
* update the Continuous Export configuration.
*
* @param {string} [exportProperties.recordTypes] The document types to be
* exported, as comma separated values. Allowed values include 'Requests',
* 'Event', 'Exceptions', 'Metrics', 'PageViews', 'PageViewPerformance', 'Rdd',
* 'PerformanceCounters', 'Availability', 'Messages'.
*
* @param {string} [exportProperties.destinationType] The Continuous Export
* destination type. This has to be 'Blob'.
*
* @param {string} [exportProperties.destinationAddress] The SAS URL for the
* destination storage container. It must grant write permission.
*
* @param {string} [exportProperties.isEnabled] Set to 'true' to create a
* Continuous Export configuration as enabled, otherwise set it to 'false'.
*
* @param {string} [exportProperties.notificationQueueEnabled] Deprecated
*
* @param {string} [exportProperties.notificationQueueUri] Deprecated
*
* @param {string} [exportProperties.destinationStorageSubscriptionId] The
* subscription ID of the destination storage container.
*
* @param {string} [exportProperties.destinationStorageLocationId] The location
* ID of the destination storage container.
*
* @param {string} [exportProperties.destinationAccountId] The name of
* destination storage account.
*
* @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<ApplicationInsightsComponentExportConfiguration>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, exportId: string, exportProperties: models.ApplicationInsightsComponentExportRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentExportConfiguration>>;
/**
* Update the Continuous Export configuration for this export id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} exportId The Continuous Export configuration ID. This is
* unique within a Application Insights component.
*
* @param {object} exportProperties Properties that need to be specified to
* update the Continuous Export configuration.
*
* @param {string} [exportProperties.recordTypes] The document types to be
* exported, as comma separated values. Allowed values include 'Requests',
* 'Event', 'Exceptions', 'Metrics', 'PageViews', 'PageViewPerformance', 'Rdd',
* 'PerformanceCounters', 'Availability', 'Messages'.
*
* @param {string} [exportProperties.destinationType] The Continuous Export
* destination type. This has to be 'Blob'.
*
* @param {string} [exportProperties.destinationAddress] The SAS URL for the
* destination storage container. It must grant write permission.
*
* @param {string} [exportProperties.isEnabled] Set to 'true' to create a
* Continuous Export configuration as enabled, otherwise set it to 'false'.
*
* @param {string} [exportProperties.notificationQueueEnabled] Deprecated
*
* @param {string} [exportProperties.notificationQueueUri] Deprecated
*
* @param {string} [exportProperties.destinationStorageSubscriptionId] The
* subscription ID of the destination storage container.
*
* @param {string} [exportProperties.destinationStorageLocationId] The location
* ID of the destination storage container.
*
* @param {string} [exportProperties.destinationAccountId] The name of
* destination storage account.
*
* @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 {ApplicationInsightsComponentExportConfiguration} - 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.
*
* {ApplicationInsightsComponentExportConfiguration} [result] - The deserialized result object if an error did not occur.
* See {@link
* ApplicationInsightsComponentExportConfiguration} for
* more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, resourceName: string, exportId: string, exportProperties: models.ApplicationInsightsComponentExportRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentExportConfiguration>;
update(resourceGroupName: string, resourceName: string, exportId: string, exportProperties: models.ApplicationInsightsComponentExportRequest, callback: ServiceCallback<models.ApplicationInsightsComponentExportConfiguration>): void;
update(resourceGroupName: string, resourceName: string, exportId: string, exportProperties: models.ApplicationInsightsComponentExportRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentExportConfiguration>): void;
}
/**
* @class
* ComponentCurrentBillingFeatures
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface ComponentCurrentBillingFeatures {
/**
* Returns current billing features for an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<ApplicationInsightsComponentBillingFeatures>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentBillingFeatures>>;
/**
* Returns current billing features for an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {ApplicationInsightsComponentBillingFeatures} - 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.
*
* {ApplicationInsightsComponentBillingFeatures} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentBillingFeatures}
* 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, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentBillingFeatures>;
get(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.ApplicationInsightsComponentBillingFeatures>): void;
get(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentBillingFeatures>): void;
/**
* Update current billing features for an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} billingFeaturesProperties Properties that need to be
* specified to update billing features for an Application Insights component.
*
* @param {object} [billingFeaturesProperties.dataVolumeCap] An Application
* Insights component daily data volumne cap
*
* @param {number} [billingFeaturesProperties.dataVolumeCap.cap] Daily data
* volume cap in GB.
*
* @param {number} [billingFeaturesProperties.dataVolumeCap.warningThreshold]
* Reserved, not used for now.
*
* @param {boolean}
* [billingFeaturesProperties.dataVolumeCap.stopSendNotificationWhenHitThreshold]
* Reserved, not used for now.
*
* @param {boolean}
* [billingFeaturesProperties.dataVolumeCap.stopSendNotificationWhenHitCap] Do
* not send a notification email when the daily data volume cap is met.
*
* @param {array} [billingFeaturesProperties.currentBillingFeatures] Current
* enabled pricing plan. When the component is in the Enterprise plan, this
* will list both 'Basic' and 'Application Insights Enterprise'.
*
* @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<ApplicationInsightsComponentBillingFeatures>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, billingFeaturesProperties: models.ApplicationInsightsComponentBillingFeatures, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentBillingFeatures>>;
/**
* Update current billing features for an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} billingFeaturesProperties Properties that need to be
* specified to update billing features for an Application Insights component.
*
* @param {object} [billingFeaturesProperties.dataVolumeCap] An Application
* Insights component daily data volumne cap
*
* @param {number} [billingFeaturesProperties.dataVolumeCap.cap] Daily data
* volume cap in GB.
*
* @param {number} [billingFeaturesProperties.dataVolumeCap.warningThreshold]
* Reserved, not used for now.
*
* @param {boolean}
* [billingFeaturesProperties.dataVolumeCap.stopSendNotificationWhenHitThreshold]
* Reserved, not used for now.
*
* @param {boolean}
* [billingFeaturesProperties.dataVolumeCap.stopSendNotificationWhenHitCap] Do
* not send a notification email when the daily data volume cap is met.
*
* @param {array} [billingFeaturesProperties.currentBillingFeatures] Current
* enabled pricing plan. When the component is in the Enterprise plan, this
* will list both 'Basic' and 'Application Insights Enterprise'.
*
* @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 {ApplicationInsightsComponentBillingFeatures} - 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.
*
* {ApplicationInsightsComponentBillingFeatures} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentBillingFeatures}
* for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, resourceName: string, billingFeaturesProperties: models.ApplicationInsightsComponentBillingFeatures, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentBillingFeatures>;
update(resourceGroupName: string, resourceName: string, billingFeaturesProperties: models.ApplicationInsightsComponentBillingFeatures, callback: ServiceCallback<models.ApplicationInsightsComponentBillingFeatures>): void;
update(resourceGroupName: string, resourceName: string, billingFeaturesProperties: models.ApplicationInsightsComponentBillingFeatures, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentBillingFeatures>): void;
}
/**
* @class
* ComponentQuotaStatus
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface ComponentQuotaStatus {
/**
* Returns daily data volume cap (quota) status for an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<ApplicationInsightsComponentQuotaStatus>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentQuotaStatus>>;
/**
* Returns daily data volume cap (quota) status for an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {ApplicationInsightsComponentQuotaStatus} - 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.
*
* {ApplicationInsightsComponentQuotaStatus} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentQuotaStatus} 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, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentQuotaStatus>;
get(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.ApplicationInsightsComponentQuotaStatus>): void;
get(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentQuotaStatus>): void;
}
/**
* @class
* ComponentFeatureCapabilities
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface ComponentFeatureCapabilities {
/**
* Returns feature capabilites of the application insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<ApplicationInsightsComponentFeatureCapabilities>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentFeatureCapabilities>>;
/**
* Returns feature capabilites of the application insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {ApplicationInsightsComponentFeatureCapabilities} - 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.
*
* {ApplicationInsightsComponentFeatureCapabilities} [result] - The deserialized result object if an error did not occur.
* See {@link
* ApplicationInsightsComponentFeatureCapabilities} 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, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentFeatureCapabilities>;
get(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.ApplicationInsightsComponentFeatureCapabilities>): void;
get(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentFeatureCapabilities>): void;
}
/**
* @class
* ComponentAvailableFeatures
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface ComponentAvailableFeatures {
/**
* Returns all available features of the application insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<ApplicationInsightsComponentAvailableFeatures>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentAvailableFeatures>>;
/**
* Returns all available features of the application insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {ApplicationInsightsComponentAvailableFeatures} - 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.
*
* {ApplicationInsightsComponentAvailableFeatures} [result] - The deserialized result object if an error did not occur.
* See {@link
* ApplicationInsightsComponentAvailableFeatures} 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, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentAvailableFeatures>;
get(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.ApplicationInsightsComponentAvailableFeatures>): void;
get(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentAvailableFeatures>): void;
}
/**
* @class
* ProactiveDetectionConfigurations
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface ProactiveDetectionConfigurations {
/**
* Gets a list of ProactiveDetection configurations of an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<Array>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentProactiveDetectionConfiguration[]>>;
/**
* Gets a list of ProactiveDetection configurations of an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {Array} - 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.
*
* {Array} [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.
*/
list(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentProactiveDetectionConfiguration[]>;
list(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.ApplicationInsightsComponentProactiveDetectionConfiguration[]>): void;
list(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentProactiveDetectionConfiguration[]>): void;
/**
* Get the ProactiveDetection configuration for this configuration id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} configurationId The ProactiveDetection configuration ID.
* This is unique within a Application Insights component.
*
* @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<ApplicationInsightsComponentProactiveDetectionConfiguration>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, configurationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentProactiveDetectionConfiguration>>;
/**
* Get the ProactiveDetection configuration for this configuration id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} configurationId The ProactiveDetection configuration ID.
* This is unique within a Application Insights component.
*
* @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 {ApplicationInsightsComponentProactiveDetectionConfiguration} - 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.
*
* {ApplicationInsightsComponentProactiveDetectionConfiguration} [result] - The deserialized result object if an error did not occur.
* See {@link
* ApplicationInsightsComponentProactiveDetectionConfiguration}
* 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, resourceName: string, configurationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentProactiveDetectionConfiguration>;
get(resourceGroupName: string, resourceName: string, configurationId: string, callback: ServiceCallback<models.ApplicationInsightsComponentProactiveDetectionConfiguration>): void;
get(resourceGroupName: string, resourceName: string, configurationId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentProactiveDetectionConfiguration>): void;
/**
* Update the ProactiveDetection configuration for this configuration id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} configurationId The ProactiveDetection configuration ID.
* This is unique within a Application Insights component.
*
* @param {object} proactiveDetectionProperties Properties that need to be
* specified to update the ProactiveDetection configuration.
*
* @param {string} [proactiveDetectionProperties.name] The rule name
*
* @param {boolean} [proactiveDetectionProperties.enabled] A flag that
* indicates whether this rule is enabled by the user
*
* @param {boolean}
* [proactiveDetectionProperties.sendEmailsToSubscriptionOwners] A flag that
* indicated whether notifications on this rule should be sent to subscription
* owners
*
* @param {array} [proactiveDetectionProperties.customEmails] Custom email
* addresses for this rule notifications
*
* @param {string} [proactiveDetectionProperties.lastUpdatedTime] The last time
* this rule was updated
*
* @param {object} [proactiveDetectionProperties.ruleDefinitions] Static
* definitions of the ProactiveDetection configuration rule (same values for
* all components).
*
* @param {string} [proactiveDetectionProperties.ruleDefinitions.name] The rule
* name
*
* @param {string} [proactiveDetectionProperties.ruleDefinitions.displayName]
* The rule name as it is displayed in UI
*
* @param {string} [proactiveDetectionProperties.ruleDefinitions.description]
* The rule description
*
* @param {string} [proactiveDetectionProperties.ruleDefinitions.helpUrl] URL
* which displays aditional info about the proactive detection rule
*
* @param {boolean} [proactiveDetectionProperties.ruleDefinitions.isHidden] A
* flag indicating whether the rule is hidden (from the UI)
*
* @param {boolean}
* [proactiveDetectionProperties.ruleDefinitions.isEnabledByDefault] A flag
* indicating whether the rule is enabled by default
*
* @param {boolean} [proactiveDetectionProperties.ruleDefinitions.isInPreview]
* A flag indicating whether the rule is in preview
*
* @param {boolean}
* [proactiveDetectionProperties.ruleDefinitions.supportsEmailNotifications] A
* flag indicating whether email notifications are supported for detections for
* this rule
*
* @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<ApplicationInsightsComponentProactiveDetectionConfiguration>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, configurationId: string, proactiveDetectionProperties: models.ApplicationInsightsComponentProactiveDetectionConfiguration, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentProactiveDetectionConfiguration>>;
/**
* Update the ProactiveDetection configuration for this configuration id.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} configurationId The ProactiveDetection configuration ID.
* This is unique within a Application Insights component.
*
* @param {object} proactiveDetectionProperties Properties that need to be
* specified to update the ProactiveDetection configuration.
*
* @param {string} [proactiveDetectionProperties.name] The rule name
*
* @param {boolean} [proactiveDetectionProperties.enabled] A flag that
* indicates whether this rule is enabled by the user
*
* @param {boolean}
* [proactiveDetectionProperties.sendEmailsToSubscriptionOwners] A flag that
* indicated whether notifications on this rule should be sent to subscription
* owners
*
* @param {array} [proactiveDetectionProperties.customEmails] Custom email
* addresses for this rule notifications
*
* @param {string} [proactiveDetectionProperties.lastUpdatedTime] The last time
* this rule was updated
*
* @param {object} [proactiveDetectionProperties.ruleDefinitions] Static
* definitions of the ProactiveDetection configuration rule (same values for
* all components).
*
* @param {string} [proactiveDetectionProperties.ruleDefinitions.name] The rule
* name
*
* @param {string} [proactiveDetectionProperties.ruleDefinitions.displayName]
* The rule name as it is displayed in UI
*
* @param {string} [proactiveDetectionProperties.ruleDefinitions.description]
* The rule description
*
* @param {string} [proactiveDetectionProperties.ruleDefinitions.helpUrl] URL
* which displays aditional info about the proactive detection rule
*
* @param {boolean} [proactiveDetectionProperties.ruleDefinitions.isHidden] A
* flag indicating whether the rule is hidden (from the UI)
*
* @param {boolean}
* [proactiveDetectionProperties.ruleDefinitions.isEnabledByDefault] A flag
* indicating whether the rule is enabled by default
*
* @param {boolean} [proactiveDetectionProperties.ruleDefinitions.isInPreview]
* A flag indicating whether the rule is in preview
*
* @param {boolean}
* [proactiveDetectionProperties.ruleDefinitions.supportsEmailNotifications] A
* flag indicating whether email notifications are supported for detections for
* this rule
*
* @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 {ApplicationInsightsComponentProactiveDetectionConfiguration} - 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.
*
* {ApplicationInsightsComponentProactiveDetectionConfiguration} [result] - The deserialized result object if an error did not occur.
* See {@link
* ApplicationInsightsComponentProactiveDetectionConfiguration}
* for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, resourceName: string, configurationId: string, proactiveDetectionProperties: models.ApplicationInsightsComponentProactiveDetectionConfiguration, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentProactiveDetectionConfiguration>;
update(resourceGroupName: string, resourceName: string, configurationId: string, proactiveDetectionProperties: models.ApplicationInsightsComponentProactiveDetectionConfiguration, callback: ServiceCallback<models.ApplicationInsightsComponentProactiveDetectionConfiguration>): void;
update(resourceGroupName: string, resourceName: string, configurationId: string, proactiveDetectionProperties: models.ApplicationInsightsComponentProactiveDetectionConfiguration, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentProactiveDetectionConfiguration>): void;
}
/**
* @class
* Components
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface Components {
/**
* Gets a list of all Application Insights components within 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<ApplicationInsightsComponentListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentListResult>>;
/**
* Gets a list of all Application Insights components within 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 {ApplicationInsightsComponentListResult} - 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.
*
* {ApplicationInsightsComponentListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentListResult} 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.ApplicationInsightsComponentListResult>;
list(callback: ServiceCallback<models.ApplicationInsightsComponentListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentListResult>): void;
/**
* Gets a list of Application Insights components within a resource group.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @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<ApplicationInsightsComponentListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentListResult>>;
/**
* Gets a list of Application Insights components within a resource group.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @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 {ApplicationInsightsComponentListResult} - 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.
*
* {ApplicationInsightsComponentListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentListResult} 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.ApplicationInsightsComponentListResult>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.ApplicationInsightsComponentListResult>): void;
listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentListResult>): void;
/**
* Deletes an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {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, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, resourceName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Returns an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<ApplicationInsightsComponent>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponent>>;
/**
* Returns an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {ApplicationInsightsComponent} - 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.
*
* {ApplicationInsightsComponent} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponent} 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, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponent>;
get(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.ApplicationInsightsComponent>): void;
get(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponent>): void;
/**
* Creates (or updates) an Application Insights component. Note: You cannot
* specify a different value for InstrumentationKey nor AppId in the Put
* operation.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} insightProperties Properties that need to be specified to
* create an Application Insights component.
*
* @param {string} insightProperties.kind The kind of application that this
* component refers to, used to customize UI. This value is a freeform string,
* values should typically be one of the following: web, ios, other, store,
* java, phone.
*
* @param {string} insightProperties.applicationType Type of application being
* monitored. Possible values include: 'web', 'other'
*
* @param {string} [insightProperties.flowType] Used by the Application
* Insights system to determine what kind of flow this component was created
* by. This is to be set to 'Bluefield' when creating/updating a component via
* the REST API. Possible values include: 'Bluefield'
*
* @param {string} [insightProperties.requestSource] Describes what tool
* created this Application Insights component. Customers using this API should
* set this to the default 'rest'. Possible values include: 'rest'
*
* @param {string} [insightProperties.hockeyAppId] The unique application ID
* created when a new application is added to HockeyApp, used for
* communications with HockeyApp.
*
* @param {number} [insightProperties.samplingPercentage] Percentage of the
* data produced by the application being monitored that is being sampled for
* Application Insights telemetry.
*
* @param {string} insightProperties.location Resource location
*
* @param {object} [insightProperties.tags] Resource tags
*
* @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<ApplicationInsightsComponent>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, insightProperties: models.ApplicationInsightsComponent, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponent>>;
/**
* Creates (or updates) an Application Insights component. Note: You cannot
* specify a different value for InstrumentationKey nor AppId in the Put
* operation.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} insightProperties Properties that need to be specified to
* create an Application Insights component.
*
* @param {string} insightProperties.kind The kind of application that this
* component refers to, used to customize UI. This value is a freeform string,
* values should typically be one of the following: web, ios, other, store,
* java, phone.
*
* @param {string} insightProperties.applicationType Type of application being
* monitored. Possible values include: 'web', 'other'
*
* @param {string} [insightProperties.flowType] Used by the Application
* Insights system to determine what kind of flow this component was created
* by. This is to be set to 'Bluefield' when creating/updating a component via
* the REST API. Possible values include: 'Bluefield'
*
* @param {string} [insightProperties.requestSource] Describes what tool
* created this Application Insights component. Customers using this API should
* set this to the default 'rest'. Possible values include: 'rest'
*
* @param {string} [insightProperties.hockeyAppId] The unique application ID
* created when a new application is added to HockeyApp, used for
* communications with HockeyApp.
*
* @param {number} [insightProperties.samplingPercentage] Percentage of the
* data produced by the application being monitored that is being sampled for
* Application Insights telemetry.
*
* @param {string} insightProperties.location Resource location
*
* @param {object} [insightProperties.tags] Resource tags
*
* @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 {ApplicationInsightsComponent} - 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.
*
* {ApplicationInsightsComponent} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponent} 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, resourceName: string, insightProperties: models.ApplicationInsightsComponent, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponent>;
createOrUpdate(resourceGroupName: string, resourceName: string, insightProperties: models.ApplicationInsightsComponent, callback: ServiceCallback<models.ApplicationInsightsComponent>): void;
createOrUpdate(resourceGroupName: string, resourceName: string, insightProperties: models.ApplicationInsightsComponent, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponent>): void;
/**
* Updates an existing component's tags. To update other fields use the
* CreateOrUpdate method.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} componentTags Updated tag information to set into the
* component instance.
*
* @param {object} [componentTags.tags] Resource tags
*
* @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<ApplicationInsightsComponent>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateTagsWithHttpOperationResponse(resourceGroupName: string, resourceName: string, componentTags: models.TagsResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponent>>;
/**
* Updates an existing component's tags. To update other fields use the
* CreateOrUpdate method.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} componentTags Updated tag information to set into the
* component instance.
*
* @param {object} [componentTags.tags] Resource tags
*
* @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 {ApplicationInsightsComponent} - 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.
*
* {ApplicationInsightsComponent} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponent} 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.
*/
updateTags(resourceGroupName: string, resourceName: string, componentTags: models.TagsResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponent>;
updateTags(resourceGroupName: string, resourceName: string, componentTags: models.TagsResource, callback: ServiceCallback<models.ApplicationInsightsComponent>): void;
updateTags(resourceGroupName: string, resourceName: string, componentTags: models.TagsResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponent>): void;
/**
* Purges data in an Application Insights component by a set of user-defined
* filters.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} body Describes the body of a request to purge data in a
* single table of an Application Insights component
*
* @param {string} body.table Table from which to purge data.
*
* @param {array} body.filters The set of columns and filters (queries) to run
* over them to purge the resulting data.
*
* @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<ComponentPurgeResponse>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
purgeWithHttpOperationResponse(resourceGroupName: string, resourceName: string, body: models.ComponentPurgeBody, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ComponentPurgeResponse>>;
/**
* Purges data in an Application Insights component by a set of user-defined
* filters.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} body Describes the body of a request to purge data in a
* single table of an Application Insights component
*
* @param {string} body.table Table from which to purge data.
*
* @param {array} body.filters The set of columns and filters (queries) to run
* over them to purge the resulting data.
*
* @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 {ComponentPurgeResponse} - 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.
*
* {ComponentPurgeResponse} [result] - The deserialized result object if an error did not occur.
* See {@link ComponentPurgeResponse} 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.
*/
purge(resourceGroupName: string, resourceName: string, body: models.ComponentPurgeBody, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ComponentPurgeResponse>;
purge(resourceGroupName: string, resourceName: string, body: models.ComponentPurgeBody, callback: ServiceCallback<models.ComponentPurgeResponse>): void;
purge(resourceGroupName: string, resourceName: string, body: models.ComponentPurgeBody, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ComponentPurgeResponse>): void;
/**
* Get status for an ongoing purge operation.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} purgeId In a purge status request, this is the Id of the
* operation the status of which is returned.
*
* @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<ComponentPurgeStatusResponse>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getPurgeStatusWithHttpOperationResponse(resourceGroupName: string, resourceName: string, purgeId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ComponentPurgeStatusResponse>>;
/**
* Get status for an ongoing purge operation.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} purgeId In a purge status request, this is the Id of the
* operation the status of which is returned.
*
* @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 {ComponentPurgeStatusResponse} - 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.
*
* {ComponentPurgeStatusResponse} [result] - The deserialized result object if an error did not occur.
* See {@link ComponentPurgeStatusResponse} 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.
*/
getPurgeStatus(resourceGroupName: string, resourceName: string, purgeId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ComponentPurgeStatusResponse>;
getPurgeStatus(resourceGroupName: string, resourceName: string, purgeId: string, callback: ServiceCallback<models.ComponentPurgeStatusResponse>): void;
getPurgeStatus(resourceGroupName: string, resourceName: string, purgeId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ComponentPurgeStatusResponse>): void;
/**
* Gets a list of all Application Insights components within 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<ApplicationInsightsComponentListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentListResult>>;
/**
* Gets a list of all Application Insights components within 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 {ApplicationInsightsComponentListResult} - 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.
*
* {ApplicationInsightsComponentListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentListResult} 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.ApplicationInsightsComponentListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.ApplicationInsightsComponentListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentListResult>): void;
/**
* Gets a list of Application Insights components within a 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<ApplicationInsightsComponentListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentListResult>>;
/**
* Gets a list of Application Insights components within a 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 {ApplicationInsightsComponentListResult} - 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.
*
* {ApplicationInsightsComponentListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentListResult} 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.ApplicationInsightsComponentListResult>;
listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.ApplicationInsightsComponentListResult>): void;
listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentListResult>): void;
}
/**
* @class
* WorkItemConfigurations
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface WorkItemConfigurations {
/**
* Gets the list work item configurations that exist for the application
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<WorkItemConfigurationsListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkItemConfigurationsListResult>>;
/**
* Gets the list work item configurations that exist for the application
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {WorkItemConfigurationsListResult} - 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.
*
* {WorkItemConfigurationsListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WorkItemConfigurationsListResult} 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(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkItemConfigurationsListResult>;
list(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.WorkItemConfigurationsListResult>): void;
list(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkItemConfigurationsListResult>): void;
/**
* Create a work item configuration for an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} workItemConfigurationProperties Properties that need to be
* specified to create a work item configuration of a Application Insights
* component.
*
* @param {string} [workItemConfigurationProperties.connectorId] Unique
* connector id
*
* @param {string} [workItemConfigurationProperties.connectorDataConfiguration]
* Serialized JSON object for detaile d properties
*
* @param {boolean} [workItemConfigurationProperties.validateOnly] Boolean
* indicating validate only
*
* @param {string} [workItemConfigurationProperties.workItemProperties] Custom
* work item properties
*
* @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<WorkItemConfiguration>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(resourceGroupName: string, resourceName: string, workItemConfigurationProperties: models.WorkItemCreateConfiguration, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkItemConfiguration>>;
/**
* Create a work item configuration for an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} workItemConfigurationProperties Properties that need to be
* specified to create a work item configuration of a Application Insights
* component.
*
* @param {string} [workItemConfigurationProperties.connectorId] Unique
* connector id
*
* @param {string} [workItemConfigurationProperties.connectorDataConfiguration]
* Serialized JSON object for detaile d properties
*
* @param {boolean} [workItemConfigurationProperties.validateOnly] Boolean
* indicating validate only
*
* @param {string} [workItemConfigurationProperties.workItemProperties] Custom
* work item properties
*
* @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 {WorkItemConfiguration} - 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.
*
* {WorkItemConfiguration} [result] - The deserialized result object if an error did not occur.
* See {@link WorkItemConfiguration} 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(resourceGroupName: string, resourceName: string, workItemConfigurationProperties: models.WorkItemCreateConfiguration, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkItemConfiguration>;
create(resourceGroupName: string, resourceName: string, workItemConfigurationProperties: models.WorkItemCreateConfiguration, callback: ServiceCallback<models.WorkItemConfiguration>): void;
create(resourceGroupName: string, resourceName: string, workItemConfigurationProperties: models.WorkItemCreateConfiguration, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkItemConfiguration>): void;
/**
* Gets default work item configurations that exist for the application
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<WorkItemConfiguration>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getDefaultWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkItemConfiguration>>;
/**
* Gets default work item configurations that exist for the application
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {WorkItemConfiguration} - 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.
*
* {WorkItemConfiguration} [result] - The deserialized result object if an error did not occur.
* See {@link WorkItemConfiguration} 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.
*/
getDefault(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkItemConfiguration>;
getDefault(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.WorkItemConfiguration>): void;
getDefault(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkItemConfiguration>): void;
/**
* Delete an workitem configuration of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} workItemConfigId The unique work item configuration Id. This
* can be either friendly name of connector as defined in connector
* 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<Object>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, resourceName: string, workItemConfigId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<any>>;
/**
* Delete an workitem configuration of an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} workItemConfigId The unique work item configuration Id. This
* can be either friendly name of connector as defined in connector
* 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 {Object} - 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.
*
* {Object} [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, resourceName: string, workItemConfigId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<any>;
deleteMethod(resourceGroupName: string, resourceName: string, workItemConfigId: string, callback: ServiceCallback<any>): void;
deleteMethod(resourceGroupName: string, resourceName: string, workItemConfigId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<any>): void;
}
/**
* @class
* Favorites
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface Favorites {
/**
* Gets a list of favorites defined within an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.favoriteType] The type of favorite. Value can be
* either shared or user. Possible values include: 'shared', 'user'
*
* @param {string} [options.sourceType] Source type of favorite to return. When
* left out, the source type defaults to 'other' (not present in this enum).
* Possible values include: 'retention', 'notebook', 'sessions', 'events',
* 'userflows', 'funnel', 'impact', 'segmentation'
*
* @param {boolean} [options.canFetchContent] Flag indicating whether or not to
* return the full content for each applicable favorite. If false, only return
* summary content for favorites.
*
* @param {array} [options.tags] Tags that must be present on each favorite
* returned.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Array>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { favoriteType? : string, sourceType? : string, canFetchContent? : boolean, tags? : string[], customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentFavorite[]>>;
/**
* Gets a list of favorites defined within an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.favoriteType] The type of favorite. Value can be
* either shared or user. Possible values include: 'shared', 'user'
*
* @param {string} [options.sourceType] Source type of favorite to return. When
* left out, the source type defaults to 'other' (not present in this enum).
* Possible values include: 'retention', 'notebook', 'sessions', 'events',
* 'userflows', 'funnel', 'impact', 'segmentation'
*
* @param {boolean} [options.canFetchContent] Flag indicating whether or not to
* return the full content for each applicable favorite. If false, only return
* summary content for favorites.
*
* @param {array} [options.tags] Tags that must be present on each favorite
* returned.
*
* @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 {Array} - 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.
*
* {Array} [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.
*/
list(resourceGroupName: string, resourceName: string, options?: { favoriteType? : string, sourceType? : string, canFetchContent? : boolean, tags? : string[], customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentFavorite[]>;
list(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.ApplicationInsightsComponentFavorite[]>): void;
list(resourceGroupName: string, resourceName: string, options: { favoriteType? : string, sourceType? : string, canFetchContent? : boolean, tags? : string[], customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentFavorite[]>): void;
/**
* Get a single favorite by its FavoriteId, defined within an Application
* Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} favoriteId The Id of a specific favorite defined in the
* Application Insights component
*
* @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<ApplicationInsightsComponentFavorite>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, favoriteId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentFavorite>>;
/**
* Get a single favorite by its FavoriteId, defined within an Application
* Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} favoriteId The Id of a specific favorite defined in the
* Application Insights component
*
* @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 {ApplicationInsightsComponentFavorite} - 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.
*
* {ApplicationInsightsComponentFavorite} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentFavorite} 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, resourceName: string, favoriteId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentFavorite>;
get(resourceGroupName: string, resourceName: string, favoriteId: string, callback: ServiceCallback<models.ApplicationInsightsComponentFavorite>): void;
get(resourceGroupName: string, resourceName: string, favoriteId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentFavorite>): void;
/**
* Adds a new favorites to an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} favoriteId The Id of a specific favorite defined in the
* Application Insights component
*
* @param {object} favoriteProperties Properties that need to be specified to
* create a new favorite and add it to an Application Insights component.
*
* @param {string} [favoriteProperties.name] The user-defined name of the
* favorite.
*
* @param {string} [favoriteProperties.config] Configuration of this particular
* favorite, which are driven by the Azure portal UX. Configuration data is a
* string containing valid JSON
*
* @param {string} [favoriteProperties.version] This instance's version of the
* data model. This can change as new features are added that can be marked
* favorite. Current examples include MetricsExplorer (ME) and Search.
*
* @param {string} [favoriteProperties.favoriteType] Enum indicating if this
* favorite definition is owned by a specific user or is shared between all
* users with access to the Application Insights component. Possible values
* include: 'shared', 'user'
*
* @param {string} [favoriteProperties.sourceType] The source of the favorite
* definition.
*
* @param {array} [favoriteProperties.tags] A list of 0 or more tags that are
* associated with this favorite definition
*
* @param {string} [favoriteProperties.category] Favorite category, as defined
* by the user at creation time.
*
* @param {boolean} [favoriteProperties.isGeneratedFromTemplate] Flag denoting
* wether or not this favorite was generated from a template.
*
* @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<ApplicationInsightsComponentFavorite>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
addWithHttpOperationResponse(resourceGroupName: string, resourceName: string, favoriteId: string, favoriteProperties: models.ApplicationInsightsComponentFavorite, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentFavorite>>;
/**
* Adds a new favorites to an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} favoriteId The Id of a specific favorite defined in the
* Application Insights component
*
* @param {object} favoriteProperties Properties that need to be specified to
* create a new favorite and add it to an Application Insights component.
*
* @param {string} [favoriteProperties.name] The user-defined name of the
* favorite.
*
* @param {string} [favoriteProperties.config] Configuration of this particular
* favorite, which are driven by the Azure portal UX. Configuration data is a
* string containing valid JSON
*
* @param {string} [favoriteProperties.version] This instance's version of the
* data model. This can change as new features are added that can be marked
* favorite. Current examples include MetricsExplorer (ME) and Search.
*
* @param {string} [favoriteProperties.favoriteType] Enum indicating if this
* favorite definition is owned by a specific user or is shared between all
* users with access to the Application Insights component. Possible values
* include: 'shared', 'user'
*
* @param {string} [favoriteProperties.sourceType] The source of the favorite
* definition.
*
* @param {array} [favoriteProperties.tags] A list of 0 or more tags that are
* associated with this favorite definition
*
* @param {string} [favoriteProperties.category] Favorite category, as defined
* by the user at creation time.
*
* @param {boolean} [favoriteProperties.isGeneratedFromTemplate] Flag denoting
* wether or not this favorite was generated from a template.
*
* @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 {ApplicationInsightsComponentFavorite} - 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.
*
* {ApplicationInsightsComponentFavorite} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentFavorite} 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.
*/
add(resourceGroupName: string, resourceName: string, favoriteId: string, favoriteProperties: models.ApplicationInsightsComponentFavorite, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentFavorite>;
add(resourceGroupName: string, resourceName: string, favoriteId: string, favoriteProperties: models.ApplicationInsightsComponentFavorite, callback: ServiceCallback<models.ApplicationInsightsComponentFavorite>): void;
add(resourceGroupName: string, resourceName: string, favoriteId: string, favoriteProperties: models.ApplicationInsightsComponentFavorite, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentFavorite>): void;
/**
* Updates a favorite that has already been added to an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} favoriteId The Id of a specific favorite defined in the
* Application Insights component
*
* @param {object} favoriteProperties Properties that need to be specified to
* update the existing favorite.
*
* @param {string} [favoriteProperties.name] The user-defined name of the
* favorite.
*
* @param {string} [favoriteProperties.config] Configuration of this particular
* favorite, which are driven by the Azure portal UX. Configuration data is a
* string containing valid JSON
*
* @param {string} [favoriteProperties.version] This instance's version of the
* data model. This can change as new features are added that can be marked
* favorite. Current examples include MetricsExplorer (ME) and Search.
*
* @param {string} [favoriteProperties.favoriteType] Enum indicating if this
* favorite definition is owned by a specific user or is shared between all
* users with access to the Application Insights component. Possible values
* include: 'shared', 'user'
*
* @param {string} [favoriteProperties.sourceType] The source of the favorite
* definition.
*
* @param {array} [favoriteProperties.tags] A list of 0 or more tags that are
* associated with this favorite definition
*
* @param {string} [favoriteProperties.category] Favorite category, as defined
* by the user at creation time.
*
* @param {boolean} [favoriteProperties.isGeneratedFromTemplate] Flag denoting
* wether or not this favorite was generated from a template.
*
* @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<ApplicationInsightsComponentFavorite>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, favoriteId: string, favoriteProperties: models.ApplicationInsightsComponentFavorite, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentFavorite>>;
/**
* Updates a favorite that has already been added to an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} favoriteId The Id of a specific favorite defined in the
* Application Insights component
*
* @param {object} favoriteProperties Properties that need to be specified to
* update the existing favorite.
*
* @param {string} [favoriteProperties.name] The user-defined name of the
* favorite.
*
* @param {string} [favoriteProperties.config] Configuration of this particular
* favorite, which are driven by the Azure portal UX. Configuration data is a
* string containing valid JSON
*
* @param {string} [favoriteProperties.version] This instance's version of the
* data model. This can change as new features are added that can be marked
* favorite. Current examples include MetricsExplorer (ME) and Search.
*
* @param {string} [favoriteProperties.favoriteType] Enum indicating if this
* favorite definition is owned by a specific user or is shared between all
* users with access to the Application Insights component. Possible values
* include: 'shared', 'user'
*
* @param {string} [favoriteProperties.sourceType] The source of the favorite
* definition.
*
* @param {array} [favoriteProperties.tags] A list of 0 or more tags that are
* associated with this favorite definition
*
* @param {string} [favoriteProperties.category] Favorite category, as defined
* by the user at creation time.
*
* @param {boolean} [favoriteProperties.isGeneratedFromTemplate] Flag denoting
* wether or not this favorite was generated from a template.
*
* @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 {ApplicationInsightsComponentFavorite} - 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.
*
* {ApplicationInsightsComponentFavorite} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentFavorite} for
* more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, resourceName: string, favoriteId: string, favoriteProperties: models.ApplicationInsightsComponentFavorite, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentFavorite>;
update(resourceGroupName: string, resourceName: string, favoriteId: string, favoriteProperties: models.ApplicationInsightsComponentFavorite, callback: ServiceCallback<models.ApplicationInsightsComponentFavorite>): void;
update(resourceGroupName: string, resourceName: string, favoriteId: string, favoriteProperties: models.ApplicationInsightsComponentFavorite, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentFavorite>): void;
/**
* Remove a favorite that is associated to an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} favoriteId The Id of a specific favorite defined in the
* Application Insights component
*
* @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, resourceName: string, favoriteId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Remove a favorite that is associated to an Application Insights component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} favoriteId The Id of a specific favorite defined in the
* Application Insights component
*
* @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, resourceName: string, favoriteId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, resourceName: string, favoriteId: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, resourceName: string, favoriteId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
}
/**
* @class
* WebTestLocations
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface WebTestLocations {
/**
* Gets a list of web test locations available to this Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<ApplicationInsightsWebTestLocationsListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsWebTestLocationsListResult>>;
/**
* Gets a list of web test locations available to this Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {ApplicationInsightsWebTestLocationsListResult} - 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.
*
* {ApplicationInsightsWebTestLocationsListResult} [result] - The deserialized result object if an error did not occur.
* See {@link
* ApplicationInsightsWebTestLocationsListResult} 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(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsWebTestLocationsListResult>;
list(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.ApplicationInsightsWebTestLocationsListResult>): void;
list(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsWebTestLocationsListResult>): void;
}
/**
* @class
* WebTests
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface WebTests {
/**
* Get all Application Insights web tests defined within a specified resource
* group.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @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<WebTestListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WebTestListResult>>;
/**
* Get all Application Insights web tests defined within a specified resource
* group.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @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 {WebTestListResult} - 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.
*
* {WebTestListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WebTestListResult} 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.WebTestListResult>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.WebTestListResult>): void;
listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WebTestListResult>): void;
/**
* Get a specific Application Insights web test definition.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} webTestName The name of the Application Insights webtest
* 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<WebTest>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, webTestName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WebTest>>;
/**
* Get a specific Application Insights web test definition.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} webTestName The name of the Application Insights webtest
* 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 {WebTest} - 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.
*
* {WebTest} [result] - The deserialized result object if an error did not occur.
* See {@link WebTest} 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, webTestName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WebTest>;
get(resourceGroupName: string, webTestName: string, callback: ServiceCallback<models.WebTest>): void;
get(resourceGroupName: string, webTestName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WebTest>): void;
/**
* Creates or updates an Application Insights web test definition.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} webTestName The name of the Application Insights webtest
* resource.
*
* @param {object} webTestDefinition Properties that need to be specified to
* create or update an Application Insights web test definition.
*
* @param {string} [webTestDefinition.kind] The kind of web test that this web
* test watches. Choices are ping and multistep. Possible values include:
* 'ping', 'multistep'
*
* @param {string} webTestDefinition.syntheticMonitorId Unique ID of this
* WebTest. This is typically the same value as the Name field.
*
* @param {string} webTestDefinition.webTestName User defined name if this
* WebTest.
*
* @param {string} [webTestDefinition.description] Purpose/user defined
* descriptive test for this WebTest.
*
* @param {boolean} [webTestDefinition.enabled] Is the test actively being
* monitored.
*
* @param {number} [webTestDefinition.frequency] Interval in seconds between
* test runs for this WebTest. Default value is 300.
*
* @param {number} [webTestDefinition.timeout] Seconds until this WebTest will
* timeout and fail. Default value is 30.
*
* @param {string} webTestDefinition.webTestKind The kind of web test this is,
* valid choices are ping and multistep. Possible values include: 'ping',
* 'multistep'
*
* @param {boolean} [webTestDefinition.retryEnabled] Allow for retries should
* this WebTest fail.
*
* @param {array} webTestDefinition.locations A list of where to physically run
* the tests from to give global coverage for accessibility of your
* application.
*
* @param {object} [webTestDefinition.configuration] An XML configuration
* specification for a WebTest.
*
* @param {string} [webTestDefinition.configuration.webTest] The XML
* specification of a WebTest to run against an application.
*
* @param {string} webTestDefinition.location Resource location
*
* @param {object} [webTestDefinition.tags] Resource tags
*
* @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<WebTest>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, webTestName: string, webTestDefinition: models.WebTest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WebTest>>;
/**
* Creates or updates an Application Insights web test definition.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} webTestName The name of the Application Insights webtest
* resource.
*
* @param {object} webTestDefinition Properties that need to be specified to
* create or update an Application Insights web test definition.
*
* @param {string} [webTestDefinition.kind] The kind of web test that this web
* test watches. Choices are ping and multistep. Possible values include:
* 'ping', 'multistep'
*
* @param {string} webTestDefinition.syntheticMonitorId Unique ID of this
* WebTest. This is typically the same value as the Name field.
*
* @param {string} webTestDefinition.webTestName User defined name if this
* WebTest.
*
* @param {string} [webTestDefinition.description] Purpose/user defined
* descriptive test for this WebTest.
*
* @param {boolean} [webTestDefinition.enabled] Is the test actively being
* monitored.
*
* @param {number} [webTestDefinition.frequency] Interval in seconds between
* test runs for this WebTest. Default value is 300.
*
* @param {number} [webTestDefinition.timeout] Seconds until this WebTest will
* timeout and fail. Default value is 30.
*
* @param {string} webTestDefinition.webTestKind The kind of web test this is,
* valid choices are ping and multistep. Possible values include: 'ping',
* 'multistep'
*
* @param {boolean} [webTestDefinition.retryEnabled] Allow for retries should
* this WebTest fail.
*
* @param {array} webTestDefinition.locations A list of where to physically run
* the tests from to give global coverage for accessibility of your
* application.
*
* @param {object} [webTestDefinition.configuration] An XML configuration
* specification for a WebTest.
*
* @param {string} [webTestDefinition.configuration.webTest] The XML
* specification of a WebTest to run against an application.
*
* @param {string} webTestDefinition.location Resource location
*
* @param {object} [webTestDefinition.tags] Resource tags
*
* @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 {WebTest} - 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.
*
* {WebTest} [result] - The deserialized result object if an error did not occur.
* See {@link WebTest} 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, webTestName: string, webTestDefinition: models.WebTest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WebTest>;
createOrUpdate(resourceGroupName: string, webTestName: string, webTestDefinition: models.WebTest, callback: ServiceCallback<models.WebTest>): void;
createOrUpdate(resourceGroupName: string, webTestName: string, webTestDefinition: models.WebTest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WebTest>): void;
/**
* Creates or updates an Application Insights web test definition.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} webTestName The name of the Application Insights webtest
* resource.
*
* @param {object} webTestTags Updated tag information to set into the web test
* instance.
*
* @param {object} [webTestTags.tags] Resource tags
*
* @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<WebTest>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateTagsWithHttpOperationResponse(resourceGroupName: string, webTestName: string, webTestTags: models.TagsResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WebTest>>;
/**
* Creates or updates an Application Insights web test definition.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} webTestName The name of the Application Insights webtest
* resource.
*
* @param {object} webTestTags Updated tag information to set into the web test
* instance.
*
* @param {object} [webTestTags.tags] Resource tags
*
* @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 {WebTest} - 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.
*
* {WebTest} [result] - The deserialized result object if an error did not occur.
* See {@link WebTest} 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.
*/
updateTags(resourceGroupName: string, webTestName: string, webTestTags: models.TagsResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WebTest>;
updateTags(resourceGroupName: string, webTestName: string, webTestTags: models.TagsResource, callback: ServiceCallback<models.WebTest>): void;
updateTags(resourceGroupName: string, webTestName: string, webTestTags: models.TagsResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WebTest>): void;
/**
* Deletes an Application Insights web test.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} webTestName The name of the Application Insights webtest
* 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<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, webTestName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes an Application Insights web test.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} webTestName The name of the Application Insights webtest
* 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 {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, webTestName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, webTestName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, webTestName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Get all Application Insights web test alerts definitioned within 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<WebTestListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WebTestListResult>>;
/**
* Get all Application Insights web test alerts definitioned within 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 {WebTestListResult} - 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.
*
* {WebTestListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WebTestListResult} 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.WebTestListResult>;
list(callback: ServiceCallback<models.WebTestListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WebTestListResult>): void;
/**
* Get all Application Insights web tests defined for the specified component.
*
* @param {string} componentName The name of the Application Insights component
* resource.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @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<WebTestListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByComponentWithHttpOperationResponse(componentName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WebTestListResult>>;
/**
* Get all Application Insights web tests defined for the specified component.
*
* @param {string} componentName The name of the Application Insights component
* resource.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @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 {WebTestListResult} - 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.
*
* {WebTestListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WebTestListResult} 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.
*/
listByComponent(componentName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WebTestListResult>;
listByComponent(componentName: string, resourceGroupName: string, callback: ServiceCallback<models.WebTestListResult>): void;
listByComponent(componentName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WebTestListResult>): void;
/**
* Get all Application Insights web tests defined within a specified resource
* group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WebTestListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WebTestListResult>>;
/**
* Get all Application Insights web tests defined within a specified resource
* group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WebTestListResult} - 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.
*
* {WebTestListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WebTestListResult} 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.WebTestListResult>;
listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.WebTestListResult>): void;
listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WebTestListResult>): void;
/**
* Get all Application Insights web test alerts definitioned within 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<WebTestListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WebTestListResult>>;
/**
* Get all Application Insights web test alerts definitioned within 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 {WebTestListResult} - 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.
*
* {WebTestListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WebTestListResult} 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.WebTestListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.WebTestListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WebTestListResult>): void;
/**
* Get all Application Insights web tests defined for the specified component.
*
* @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<WebTestListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByComponentNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WebTestListResult>>;
/**
* Get all Application Insights web tests defined for the specified component.
*
* @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 {WebTestListResult} - 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.
*
* {WebTestListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WebTestListResult} 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.
*/
listByComponentNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WebTestListResult>;
listByComponentNext(nextPageLink: string, callback: ServiceCallback<models.WebTestListResult>): void;
listByComponentNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WebTestListResult>): void;
}
/**
* @class
* AnalyticsItems
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface AnalyticsItems {
/**
* Gets a list of Analytics Items defined within an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} scopePath Enum indicating if this item definition is owned
* by a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'analyticsItems',
* 'myanalyticsItems'
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.scope] Enum indicating if this item definition is
* owned by a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'shared', 'user'
*
* @param {string} [options.type] Enum indicating the type of the Analytics
* item. Possible values include: 'none', 'query', 'function', 'folder',
* 'recent'
*
* @param {boolean} [options.includeContent] Flag indicating whether or not to
* return the content of each applicable item. If false, only return the item
* information.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Array>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(resourceGroupName: string, resourceName: string, scopePath: string, options?: { scope? : string, type? : string, includeContent? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentAnalyticsItem[]>>;
/**
* Gets a list of Analytics Items defined within an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} scopePath Enum indicating if this item definition is owned
* by a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'analyticsItems',
* 'myanalyticsItems'
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.scope] Enum indicating if this item definition is
* owned by a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'shared', 'user'
*
* @param {string} [options.type] Enum indicating the type of the Analytics
* item. Possible values include: 'none', 'query', 'function', 'folder',
* 'recent'
*
* @param {boolean} [options.includeContent] Flag indicating whether or not to
* return the content of each applicable item. If false, only return the item
* information.
*
* @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 {Array} - 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.
*
* {Array} [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.
*/
list(resourceGroupName: string, resourceName: string, scopePath: string, options?: { scope? : string, type? : string, includeContent? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentAnalyticsItem[]>;
list(resourceGroupName: string, resourceName: string, scopePath: string, callback: ServiceCallback<models.ApplicationInsightsComponentAnalyticsItem[]>): void;
list(resourceGroupName: string, resourceName: string, scopePath: string, options: { scope? : string, type? : string, includeContent? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentAnalyticsItem[]>): void;
/**
* Gets a specific Analytics Items defined within an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} scopePath Enum indicating if this item definition is owned
* by a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'analyticsItems',
* 'myanalyticsItems'
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.id] The Id of a specific item defined in the
* Application Insights component
*
* @param {string} [options.name] The name of a specific item defined in the
* Application Insights component
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ApplicationInsightsComponentAnalyticsItem>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, scopePath: string, options?: { id? : string, name? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentAnalyticsItem>>;
/**
* Gets a specific Analytics Items defined within an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} scopePath Enum indicating if this item definition is owned
* by a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'analyticsItems',
* 'myanalyticsItems'
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.id] The Id of a specific item defined in the
* Application Insights component
*
* @param {string} [options.name] The name of a specific item defined in the
* Application Insights component
*
* @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 {ApplicationInsightsComponentAnalyticsItem} - 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.
*
* {ApplicationInsightsComponentAnalyticsItem} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentAnalyticsItem}
* 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, resourceName: string, scopePath: string, options?: { id? : string, name? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentAnalyticsItem>;
get(resourceGroupName: string, resourceName: string, scopePath: string, callback: ServiceCallback<models.ApplicationInsightsComponentAnalyticsItem>): void;
get(resourceGroupName: string, resourceName: string, scopePath: string, options: { id? : string, name? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentAnalyticsItem>): void;
/**
* Adds or Updates a specific Analytics Item within an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} scopePath Enum indicating if this item definition is owned
* by a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'analyticsItems',
* 'myanalyticsItems'
*
* @param {object} itemProperties Properties that need to be specified to
* create a new item and add it to an Application Insights component.
*
* @param {string} [itemProperties.id] Internally assigned unique id of the
* item definition.
*
* @param {string} [itemProperties.name] The user-defined name of the item.
*
* @param {string} [itemProperties.content] The content of this item
*
* @param {string} [itemProperties.scope] Enum indicating if this item
* definition is owned by a specific user or is shared between all users with
* access to the Application Insights component. Possible values include:
* 'shared', 'user'
*
* @param {string} [itemProperties.type] Enum indicating the type of the
* Analytics item. Possible values include: 'query', 'function', 'folder',
* 'recent'
*
* @param {object} [itemProperties.properties]
*
* @param {string} [itemProperties.properties.functionAlias] A function alias,
* used when the type of the item is Function
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.overrideItem] Flag indicating whether or not to
* force save an item. This allows overriding an item if it already exists.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ApplicationInsightsComponentAnalyticsItem>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
putWithHttpOperationResponse(resourceGroupName: string, resourceName: string, scopePath: string, itemProperties: models.ApplicationInsightsComponentAnalyticsItem, options?: { overrideItem? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationInsightsComponentAnalyticsItem>>;
/**
* Adds or Updates a specific Analytics Item within an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} scopePath Enum indicating if this item definition is owned
* by a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'analyticsItems',
* 'myanalyticsItems'
*
* @param {object} itemProperties Properties that need to be specified to
* create a new item and add it to an Application Insights component.
*
* @param {string} [itemProperties.id] Internally assigned unique id of the
* item definition.
*
* @param {string} [itemProperties.name] The user-defined name of the item.
*
* @param {string} [itemProperties.content] The content of this item
*
* @param {string} [itemProperties.scope] Enum indicating if this item
* definition is owned by a specific user or is shared between all users with
* access to the Application Insights component. Possible values include:
* 'shared', 'user'
*
* @param {string} [itemProperties.type] Enum indicating the type of the
* Analytics item. Possible values include: 'query', 'function', 'folder',
* 'recent'
*
* @param {object} [itemProperties.properties]
*
* @param {string} [itemProperties.properties.functionAlias] A function alias,
* used when the type of the item is Function
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.overrideItem] Flag indicating whether or not to
* force save an item. This allows overriding an item if it already exists.
*
* @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 {ApplicationInsightsComponentAnalyticsItem} - 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.
*
* {ApplicationInsightsComponentAnalyticsItem} [result] - The deserialized result object if an error did not occur.
* See {@link ApplicationInsightsComponentAnalyticsItem}
* 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.
*/
put(resourceGroupName: string, resourceName: string, scopePath: string, itemProperties: models.ApplicationInsightsComponentAnalyticsItem, options?: { overrideItem? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationInsightsComponentAnalyticsItem>;
put(resourceGroupName: string, resourceName: string, scopePath: string, itemProperties: models.ApplicationInsightsComponentAnalyticsItem, callback: ServiceCallback<models.ApplicationInsightsComponentAnalyticsItem>): void;
put(resourceGroupName: string, resourceName: string, scopePath: string, itemProperties: models.ApplicationInsightsComponentAnalyticsItem, options: { overrideItem? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationInsightsComponentAnalyticsItem>): void;
/**
* Deletes a specific Analytics Items defined within an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} scopePath Enum indicating if this item definition is owned
* by a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'analyticsItems',
* 'myanalyticsItems'
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.id] The Id of a specific item defined in the
* Application Insights component
*
* @param {string} [options.name] The name of a specific item defined in the
* Application Insights component
*
* @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, resourceName: string, scopePath: string, options?: { id? : string, name? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes a specific Analytics Items defined within an Application Insights
* component.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {string} scopePath Enum indicating if this item definition is owned
* by a specific user or is shared between all users with access to the
* Application Insights component. Possible values include: 'analyticsItems',
* 'myanalyticsItems'
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.id] The Id of a specific item defined in the
* Application Insights component
*
* @param {string} [options.name] The name of a specific item defined in the
* Application Insights component
*
* @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, resourceName: string, scopePath: string, options?: { id? : string, name? : string, customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, resourceName: string, scopePath: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, resourceName: string, scopePath: string, options: { id? : string, name? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
}
/**
* @class
* Workbooks
* __NOTE__: An instance of this class is automatically created for an
* instance of the ApplicationInsightsManagementClient.
*/
export interface Workbooks {
/**
* Get all Workbooks defined within a specified resource group and category.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} category Category of workbook to return. Possible values
* include: 'workbook', 'TSG', 'performance', 'retention'
*
* @param {object} [options] Optional Parameters.
*
* @param {array} [options.tags] Tags presents on each workbook returned.
*
* @param {boolean} [options.canFetchContent] Flag indicating whether or not to
* return the full content for each applicable workbook. If false, only return
* summary content for workbooks.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkbooksListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, category: string, options?: { tags? : string[], canFetchContent? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkbooksListResult>>;
/**
* Get all Workbooks defined within a specified resource group and category.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} category Category of workbook to return. Possible values
* include: 'workbook', 'TSG', 'performance', 'retention'
*
* @param {object} [options] Optional Parameters.
*
* @param {array} [options.tags] Tags presents on each workbook returned.
*
* @param {boolean} [options.canFetchContent] Flag indicating whether or not to
* return the full content for each applicable workbook. If false, only return
* summary content for workbooks.
*
* @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 {WorkbooksListResult} - 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.
*
* {WorkbooksListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WorkbooksListResult} 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, category: string, options?: { tags? : string[], canFetchContent? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkbooksListResult>;
listByResourceGroup(resourceGroupName: string, category: string, callback: ServiceCallback<models.WorkbooksListResult>): void;
listByResourceGroup(resourceGroupName: string, category: string, options: { tags? : string[], canFetchContent? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkbooksListResult>): void;
/**
* Get a single workbook by its resourceName.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<Workbook>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workbook>>;
/**
* Get a single workbook by its resourceName.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {Workbook} - 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.
*
* {Workbook} [result] - The deserialized result object if an error did not occur.
* See {@link Workbook} 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, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workbook>;
get(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.Workbook>): void;
get(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workbook>): void;
/**
* Delete a workbook.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Delete a workbook.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* 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 {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, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, resourceName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Create a new workbook.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} workbookProperties Properties that need to be specified to
* create a new workbook.
*
* @param {string} [workbookProperties.kind] The kind of workbook. Choices are
* user and shared. Possible values include: 'user', 'shared'
*
* @param {string} workbookProperties.workbookName The user-defined name of the
* workbook.
*
* @param {string} workbookProperties.serializedData Configuration of this
* particular workbook. Configuration data is a string containing valid JSON
*
* @param {string} [workbookProperties.version] This instance's version of the
* data model. This can change as new features are added that can be marked
* workbook.
*
* @param {string} workbookProperties.workbookId Internally assigned unique id
* of the workbook definition.
*
* @param {string} workbookProperties.sharedTypeKind Enum indicating if this
* workbook definition is owned by a specific user or is shared between all
* users with access to the Application Insights component. Possible values
* include: 'user', 'shared'
*
* @param {string} workbookProperties.category Workbook category, as defined by
* the user at creation time.
*
* @param {array} [workbookProperties.workbookTags] A list of 0 or more tags
* that are associated with this workbook definition
*
* @param {string} workbookProperties.userId Unique user id of the specific
* user that owns this workbook.
*
* @param {string} [workbookProperties.sourceResourceId] Optional resourceId
* for a source resource.
*
* @param {string} [workbookProperties.location] Resource location
*
* @param {object} [workbookProperties.tags] Resource tags
*
* @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<Workbook>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, workbookProperties: models.Workbook, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workbook>>;
/**
* Create a new workbook.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} workbookProperties Properties that need to be specified to
* create a new workbook.
*
* @param {string} [workbookProperties.kind] The kind of workbook. Choices are
* user and shared. Possible values include: 'user', 'shared'
*
* @param {string} workbookProperties.workbookName The user-defined name of the
* workbook.
*
* @param {string} workbookProperties.serializedData Configuration of this
* particular workbook. Configuration data is a string containing valid JSON
*
* @param {string} [workbookProperties.version] This instance's version of the
* data model. This can change as new features are added that can be marked
* workbook.
*
* @param {string} workbookProperties.workbookId Internally assigned unique id
* of the workbook definition.
*
* @param {string} workbookProperties.sharedTypeKind Enum indicating if this
* workbook definition is owned by a specific user or is shared between all
* users with access to the Application Insights component. Possible values
* include: 'user', 'shared'
*
* @param {string} workbookProperties.category Workbook category, as defined by
* the user at creation time.
*
* @param {array} [workbookProperties.workbookTags] A list of 0 or more tags
* that are associated with this workbook definition
*
* @param {string} workbookProperties.userId Unique user id of the specific
* user that owns this workbook.
*
* @param {string} [workbookProperties.sourceResourceId] Optional resourceId
* for a source resource.
*
* @param {string} [workbookProperties.location] Resource location
*
* @param {object} [workbookProperties.tags] Resource tags
*
* @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 {Workbook} - 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.
*
* {Workbook} [result] - The deserialized result object if an error did not occur.
* See {@link Workbook} 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, resourceName: string, workbookProperties: models.Workbook, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workbook>;
createOrUpdate(resourceGroupName: string, resourceName: string, workbookProperties: models.Workbook, callback: ServiceCallback<models.Workbook>): void;
createOrUpdate(resourceGroupName: string, resourceName: string, workbookProperties: models.Workbook, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workbook>): void;
/**
* Updates a workbook that has already been added.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} workbookProperties Properties that need to be specified to
* create a new workbook.
*
* @param {string} [workbookProperties.kind] The kind of workbook. Choices are
* user and shared. Possible values include: 'user', 'shared'
*
* @param {string} workbookProperties.workbookName The user-defined name of the
* workbook.
*
* @param {string} workbookProperties.serializedData Configuration of this
* particular workbook. Configuration data is a string containing valid JSON
*
* @param {string} [workbookProperties.version] This instance's version of the
* data model. This can change as new features are added that can be marked
* workbook.
*
* @param {string} workbookProperties.workbookId Internally assigned unique id
* of the workbook definition.
*
* @param {string} workbookProperties.sharedTypeKind Enum indicating if this
* workbook definition is owned by a specific user or is shared between all
* users with access to the Application Insights component. Possible values
* include: 'user', 'shared'
*
* @param {string} workbookProperties.category Workbook category, as defined by
* the user at creation time.
*
* @param {array} [workbookProperties.workbookTags] A list of 0 or more tags
* that are associated with this workbook definition
*
* @param {string} workbookProperties.userId Unique user id of the specific
* user that owns this workbook.
*
* @param {string} [workbookProperties.sourceResourceId] Optional resourceId
* for a source resource.
*
* @param {string} [workbookProperties.location] Resource location
*
* @param {object} [workbookProperties.tags] Resource tags
*
* @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<Workbook>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, workbookProperties: models.Workbook, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workbook>>;
/**
* Updates a workbook that has already been added.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceName The name of the Application Insights component
* resource.
*
* @param {object} workbookProperties Properties that need to be specified to
* create a new workbook.
*
* @param {string} [workbookProperties.kind] The kind of workbook. Choices are
* user and shared. Possible values include: 'user', 'shared'
*
* @param {string} workbookProperties.workbookName The user-defined name of the
* workbook.
*
* @param {string} workbookProperties.serializedData Configuration of this
* particular workbook. Configuration data is a string containing valid JSON
*
* @param {string} [workbookProperties.version] This instance's version of the
* data model. This can change as new features are added that can be marked
* workbook.
*
* @param {string} workbookProperties.workbookId Internally assigned unique id
* of the workbook definition.
*
* @param {string} workbookProperties.sharedTypeKind Enum indicating if this
* workbook definition is owned by a specific user or is shared between all
* users with access to the Application Insights component. Possible values
* include: 'user', 'shared'
*
* @param {string} workbookProperties.category Workbook category, as defined by
* the user at creation time.
*
* @param {array} [workbookProperties.workbookTags] A list of 0 or more tags
* that are associated with this workbook definition
*
* @param {string} workbookProperties.userId Unique user id of the specific
* user that owns this workbook.
*
* @param {string} [workbookProperties.sourceResourceId] Optional resourceId
* for a source resource.
*
* @param {string} [workbookProperties.location] Resource location
*
* @param {object} [workbookProperties.tags] Resource tags
*
* @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 {Workbook} - 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.
*
* {Workbook} [result] - The deserialized result object if an error did not occur.
* See {@link Workbook} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, resourceName: string, workbookProperties: models.Workbook, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workbook>;
update(resourceGroupName: string, resourceName: string, workbookProperties: models.Workbook, callback: ServiceCallback<models.Workbook>): void;
update(resourceGroupName: string, resourceName: string, workbookProperties: models.Workbook, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workbook>): void;
} | the_stack |
import assert from 'assert';
import extend from '../util/extend';
import ParsingError from './parsing_error';
import ParsingContext from './parsing_context';
import EvaluationContext from './evaluation_context';
import CompoundExpression from './compound_expression';
import Step from './definitions/step';
import Interpolate from './definitions/interpolate';
import Coalesce from './definitions/coalesce';
import Let from './definitions/let';
import definitions from './definitions';
import * as isConstant from './is_constant';
import RuntimeError from './runtime_error';
import {success, error} from '../util/result';
import {supportsPropertyExpression, supportsZoomExpression, supportsInterpolation} from '../util/properties';
import type {Type, EvaluationKind} from './types';
import type {Value} from './values';
import type {Expression} from './expression';
import type {StylePropertySpecification} from '../style-spec';
import type {Result} from '../util/result';
import type {InterpolationType} from './definitions/interpolate';
import type {PropertyValueSpecification} from '../types.g';
import type {FormattedSection} from './types/formatted';
import type Point from '@mapbox/point-geometry';
import type {CanonicalTileID} from '../../source/tile_id';
export type Feature = {
readonly type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon';
readonly id?: any;
readonly properties: {[_: string]: any};
readonly patterns?: {
[_: string]: {
'min': string;
'mid': string;
'max': string;
};
};
readonly geometry?: Array<Array<Point>>;
};
export type FeatureState = {[_: string]: any};
export type GlobalProperties = Readonly<{
zoom: number;
heatmapDensity?: number;
lineProgress?: number;
isSupportedScript?: (_: string) => boolean;
accumulated?: Value;
}>;
export class StyleExpression {
expression: Expression;
_evaluator: EvaluationContext;
_defaultValue: Value;
_warningHistory: {[key: string]: boolean};
_enumValues: {[_: string]: any};
constructor(expression: Expression, propertySpec?: StylePropertySpecification | null) {
this.expression = expression;
this._warningHistory = {};
this._evaluator = new EvaluationContext();
this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;
this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null;
}
evaluateWithoutErrorHandling(
globals: GlobalProperties,
feature?: Feature,
featureState?: FeatureState,
canonical?: CanonicalTileID,
availableImages?: Array<string>,
formattedSection?: FormattedSection
): any {
this._evaluator.globals = globals;
this._evaluator.feature = feature;
this._evaluator.featureState = featureState;
this._evaluator.canonical = canonical;
this._evaluator.availableImages = availableImages || null;
this._evaluator.formattedSection = formattedSection;
return this.expression.evaluate(this._evaluator);
}
evaluate(
globals: GlobalProperties,
feature?: Feature,
featureState?: FeatureState,
canonical?: CanonicalTileID,
availableImages?: Array<string>,
formattedSection?: FormattedSection
): any {
this._evaluator.globals = globals;
this._evaluator.feature = feature || null;
this._evaluator.featureState = featureState || null;
this._evaluator.canonical = canonical;
this._evaluator.availableImages = availableImages || null;
this._evaluator.formattedSection = formattedSection || null;
try {
const val = this.expression.evaluate(this._evaluator);
// eslint-disable-next-line no-self-compare
if (val === null || val === undefined || (typeof val === 'number' && val !== val)) {
return this._defaultValue;
}
if (this._enumValues && !(val in this._enumValues)) {
throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ')}, but found ${JSON.stringify(val)} instead.`);
}
return val;
} catch (e) {
if (!this._warningHistory[e.message]) {
this._warningHistory[e.message] = true;
if (typeof console !== 'undefined') {
console.warn(e.message);
}
}
return this._defaultValue;
}
}
}
export function isExpression(expression: unknown) {
return Array.isArray(expression) && expression.length > 0 &&
typeof expression[0] === 'string' && expression[0] in definitions;
}
/**
* Parse and typecheck the given style spec JSON expression. If
* options.defaultValue is provided, then the resulting StyleExpression's
* `evaluate()` method will handle errors by logging a warning (once per
* message) and returning the default value. Otherwise, it will throw
* evaluation errors.
*
* @private
*/
export function createExpression(expression: unknown, propertySpec?: StylePropertySpecification | null): Result<StyleExpression, Array<ParsingError>> {
const parser = new ParsingContext(definitions, [], propertySpec ? getExpectedType(propertySpec) : undefined);
// For string-valued properties, coerce to string at the top level rather than asserting.
const parsed = parser.parse(expression, undefined, undefined, undefined,
propertySpec && propertySpec.type === 'string' ? {typeAnnotation: 'coerce'} : undefined);
if (!parsed) {
assert(parser.errors.length > 0);
return error(parser.errors);
}
return success(new StyleExpression(parsed, propertySpec));
}
export class ZoomConstantExpression<Kind extends EvaluationKind> {
kind: Kind;
isStateDependent: boolean;
_styleExpression: StyleExpression;
constructor(kind: Kind, expression: StyleExpression) {
this.kind = kind;
this._styleExpression = expression;
this.isStateDependent = kind !== ('constant' as EvaluationKind) && !isConstant.isStateConstant(expression.expression);
}
evaluateWithoutErrorHandling(
globals: GlobalProperties,
feature?: Feature,
featureState?: FeatureState,
canonical?: CanonicalTileID,
availableImages?: Array<string>,
formattedSection?: FormattedSection
): any {
return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);
}
evaluate(
globals: GlobalProperties,
feature?: Feature,
featureState?: FeatureState,
canonical?: CanonicalTileID,
availableImages?: Array<string>,
formattedSection?: FormattedSection
): any {
return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);
}
}
export class ZoomDependentExpression<Kind extends EvaluationKind> {
kind: Kind;
zoomStops: Array<number>;
isStateDependent: boolean;
_styleExpression: StyleExpression;
interpolationType: InterpolationType;
constructor(kind: Kind, expression: StyleExpression, zoomStops: Array<number>, interpolationType?: InterpolationType) {
this.kind = kind;
this.zoomStops = zoomStops;
this._styleExpression = expression;
this.isStateDependent = kind !== ('camera' as EvaluationKind) && !isConstant.isStateConstant(expression.expression);
this.interpolationType = interpolationType;
}
evaluateWithoutErrorHandling(
globals: GlobalProperties,
feature?: Feature,
featureState?: FeatureState,
canonical?: CanonicalTileID,
availableImages?: Array<string>,
formattedSection?: FormattedSection
): any {
return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);
}
evaluate(
globals: GlobalProperties,
feature?: Feature,
featureState?: FeatureState,
canonical?: CanonicalTileID,
availableImages?: Array<string>,
formattedSection?: FormattedSection
): any {
return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);
}
interpolationFactor(input: number, lower: number, upper: number): number {
if (this.interpolationType) {
return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper);
} else {
return 0;
}
}
}
export type ConstantExpression = {
kind: 'constant';
readonly evaluate: (
globals: GlobalProperties,
feature?: Feature,
featureState?: FeatureState,
canonical?: CanonicalTileID,
availableImages?: Array<string>
) => any;
};
export type SourceExpression = {
kind: 'source';
isStateDependent: boolean;
readonly evaluate: (
globals: GlobalProperties,
feature?: Feature,
featureState?: FeatureState,
canonical?: CanonicalTileID,
availableImages?: Array<string>,
formattedSection?: FormattedSection
) => any;
};
export type CameraExpression = {
kind: 'camera';
readonly evaluate: (
globals: GlobalProperties,
feature?: Feature,
featureState?: FeatureState,
canonical?: CanonicalTileID,
availableImages?: Array<string>
) => any;
readonly interpolationFactor: (input: number, lower: number, upper: number) => number;
zoomStops: Array<number>;
interpolationType: InterpolationType;
};
export type CompositeExpression = {
kind: 'composite';
isStateDependent: boolean;
readonly evaluate: (
globals: GlobalProperties,
feature?: Feature,
featureState?: FeatureState,
canonical?: CanonicalTileID,
availableImages?: Array<string>,
formattedSection?: FormattedSection
) => any;
readonly interpolationFactor: (input: number, lower: number, upper: number) => number;
zoomStops: Array<number>;
interpolationType: InterpolationType;
};
export type StylePropertyExpression = ConstantExpression | SourceExpression | CameraExpression | CompositeExpression;
export function createPropertyExpression(expressionInput: unknown, propertySpec: StylePropertySpecification): Result<StylePropertyExpression, Array<ParsingError>> {
const expression = createExpression(expressionInput, propertySpec);
if (expression.result === 'error') {
return expression;
}
const parsed = expression.value.expression;
const isFeatureConstant = isConstant.isFeatureConstant(parsed);
if (!isFeatureConstant && !supportsPropertyExpression(propertySpec)) {
return error([new ParsingError('', 'data expressions not supported')]);
}
const isZoomConstant = isConstant.isGlobalPropertyConstant(parsed, ['zoom']);
if (!isZoomConstant && !supportsZoomExpression(propertySpec)) {
return error([new ParsingError('', 'zoom expressions not supported')]);
}
const zoomCurve = findZoomCurve(parsed);
if (!zoomCurve && !isZoomConstant) {
return error([new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);
} else if (zoomCurve instanceof ParsingError) {
return error([zoomCurve]);
} else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) {
return error([new ParsingError('', '"interpolate" expressions cannot be used with this property')]);
}
if (!zoomCurve) {
return success(isFeatureConstant ?
(new ZoomConstantExpression('constant', expression.value) as ConstantExpression) :
(new ZoomConstantExpression('source', expression.value) as SourceExpression));
}
const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined;
return success(isFeatureConstant ?
(new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType) as CameraExpression) :
(new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType) as CompositeExpression));
}
import {isFunction, createFunction} from '../function';
import {Color} from './values';
// serialization wrapper for old-style stop functions normalized to the
// expression interface
export class StylePropertyFunction<T> {
_parameters: PropertyValueSpecification<T>;
_specification: StylePropertySpecification;
kind: EvaluationKind;
evaluate: (globals: GlobalProperties, feature?: Feature) => any;
interpolationFactor: ((input: number, lower: number, upper: number) => number);
zoomStops: Array<number>;
constructor(parameters: PropertyValueSpecification<T>, specification: StylePropertySpecification) {
this._parameters = parameters;
this._specification = specification;
extend(this, createFunction(this._parameters, this._specification));
}
static deserialize<T>(serialized: {
_parameters: PropertyValueSpecification<T>;
_specification: StylePropertySpecification;
}) {
return new StylePropertyFunction(serialized._parameters, serialized._specification) as StylePropertyFunction<T>;
}
static serialize<T>(input: StylePropertyFunction<T>) {
return {
_parameters: input._parameters,
_specification: input._specification
};
}
}
export function normalizePropertyExpression<T>(
value: PropertyValueSpecification<T>,
specification: StylePropertySpecification
): StylePropertyExpression {
if (isFunction(value)) {
return new StylePropertyFunction(value, specification) as any;
} else if (isExpression(value)) {
const expression = createPropertyExpression(value, specification);
if (expression.result === 'error') {
// this should have been caught in validation
throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', '));
}
return expression.value;
} else {
let constant: any = value;
if (typeof value === 'string' && specification.type === 'color') {
constant = Color.parse(value);
}
return {
kind: 'constant',
evaluate: () => constant
};
}
}
// Zoom-dependent expressions may only use ["zoom"] as the input to a top-level "step" or "interpolate"
// expression (collectively referred to as a "curve"). The curve may be wrapped in one or more "let" or
// "coalesce" expressions.
function findZoomCurve(expression: Expression): Step | Interpolate | ParsingError | null {
let result = null;
if (expression instanceof Let) {
result = findZoomCurve(expression.result);
} else if (expression instanceof Coalesce) {
for (const arg of expression.args) {
result = findZoomCurve(arg);
if (result) {
break;
}
}
} else if ((expression instanceof Step || expression instanceof Interpolate) &&
expression.input instanceof CompoundExpression &&
expression.input.name === 'zoom') {
result = expression;
}
if (result instanceof ParsingError) {
return result;
}
expression.eachChild((child) => {
const childResult = findZoomCurve(child);
if (childResult instanceof ParsingError) {
result = childResult;
} else if (!result && childResult) {
result = new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.');
} else if (result && childResult && result !== childResult) {
result = new ParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.');
}
});
return result;
}
import {ColorType, StringType, NumberType, BooleanType, ValueType, FormattedType, ResolvedImageType, array} from './types';
function getExpectedType(spec: StylePropertySpecification): Type {
const types = {
color: ColorType,
string: StringType,
number: NumberType,
enum: StringType,
boolean: BooleanType,
formatted: FormattedType,
resolvedImage: ResolvedImageType
};
if (spec.type === 'array') {
return array(types[spec.value] || ValueType, spec.length);
}
return types[spec.type];
}
function getDefaultValue(spec: StylePropertySpecification): Value {
if (spec.type === 'color' && isFunction(spec.default)) {
// Special case for heatmap-color: it uses the 'default:' to define a
// default color ramp, but createExpression expects a simple value to fall
// back to in case of runtime errors
return new Color(0, 0, 0, 0);
} else if (spec.type === 'color') {
return Color.parse(spec.default) || null;
} else if (spec.default === undefined) {
return null;
} else {
return spec.default;
}
} | the_stack |
import { stripIndent } from 'common-tags';
import { promises as fs } from 'fs';
import { Server } from 'net';
import { SinonSpy, SinonStub, spy, stub } from 'sinon';
import { expect } from 'chai';
import prepare = require('./lib/prepare');
import * as config from '../src/config';
import * as deviceState from '../src/device-state';
import Log from '../src/lib/supervisor-console';
import balenaAPI = require('./lib/mocked-balena-api');
import { schema } from '../src/config/schema';
import ConfigJsonConfigBackend from '../src/config/configJson';
import * as TargetState from '../src/device-state/target-state';
import * as ApiHelper from '../src/lib/api-helper';
import supervisorVersion = require('../src/lib/supervisor-version');
import * as eventTracker from '../src/event-tracker';
import { TypedError } from 'typed-error';
import { DeviceNotFoundError } from '../src/lib/errors';
let ApiBinder: typeof import('../src/api-binder');
class ExpectedError extends TypedError {}
const initModels = async (obj: Dictionary<any>, filename: string) => {
await prepare();
// @ts-expect-error setting read-only property
config.configJsonBackend = new ConfigJsonConfigBackend(schema, filename);
await config.generateRequiredFields();
// @ts-expect-error using private properties
config.configJsonBackend.cache = await config.configJsonBackend.read();
await config.generateRequiredFields();
obj.logger = {
clearOutOfDateDBLogs: () => {
/* noop */
},
} as any;
ApiBinder = await import('../src/api-binder');
await ApiBinder.initialized;
obj.apiBinder = ApiBinder;
await deviceState.initialized;
obj.deviceState = deviceState;
};
const mockProvisioningOpts = {
apiEndpoint: 'http://0.0.0.0:3000',
uuid: 'abcd',
deviceApiKey: 'averyvalidkey',
provisioningApiKey: 'anotherveryvalidkey',
apiTimeout: 30000,
};
describe('ApiBinder', () => {
const defaultConfigBackend = config.configJsonBackend;
let server: Server;
before(async () => {
delete require.cache[require.resolve('../src/api-binder')];
spy(balenaAPI.balenaBackend!, 'registerHandler');
server = balenaAPI.listen(3000);
});
after(() => {
// @ts-expect-error setting read-only property
balenaAPI.balenaBackend!.registerHandler.restore();
try {
server.close();
} catch (error) {
/* noop */
}
});
// We do not support older OS versions anymore, so we only test this case
describe('on an OS with deviceApiKey support', () => {
const components: Dictionary<any> = {};
let eventTrackSpy: SinonSpy;
before(async () => {
eventTrackSpy = spy(eventTracker, 'track');
await initModels(components, '/config-apibinder.json');
});
afterEach(() => {
eventTrackSpy.resetHistory();
});
after(async () => {
eventTrackSpy.restore();
// @ts-expect-error setting read-only property
config.configJsonBackend = defaultConfigBackend;
await config.generateRequiredFields();
});
it('provisions a device', async () => {
const opts = await config.get('provisioningOptions');
await ApiHelper.provision(components.apiBinder.balenaApi, opts);
expect(balenaAPI.balenaBackend!.registerHandler).to.be.calledOnce;
expect(eventTrackSpy).to.be.called;
expect(eventTrackSpy).to.be.calledWith('Device bootstrap success');
// @ts-expect-error function does not exist on type
balenaAPI.balenaBackend!.registerHandler.resetHistory();
});
it('exchanges keys if resource conflict when provisioning', async () => {
// Get current config to extend
const currentConfig = await config.get('provisioningOptions');
// Stub config values so we have correct conditions
const configStub = stub(config, 'get').resolves({
...currentConfig,
registered_at: null,
provisioningApiKey: '123', // Previous test case deleted the provisioningApiKey so add one
uuid: 'not-unique', // This UUID is used in mocked-balena-api as an existing registered UUID
});
// If api-binder reaches this function then tests pass
// We throw an error so we don't have to keep stubbing
const functionToReach = stub(
ApiHelper,
'exchangeKeyAndGetDeviceOrRegenerate',
).throws(new ExpectedError());
spy(Log, 'debug');
try {
const opts = await config.get('provisioningOptions');
await ApiHelper.provision(components.apiBinder.balenaApi, opts);
} catch (e) {
// Check that the error thrown is from this test
expect(e).to.be.instanceOf(ExpectedError);
}
expect(functionToReach.called).to.be.true;
expect((Log.debug as SinonSpy).lastCall.lastArg).to.equal(
'UUID already registered, trying a key exchange',
);
// Restore stubs
configStub.restore();
functionToReach.restore();
(Log.debug as SinonStub).restore();
});
it('deletes the provisioning key', async () => {
expect(await config.get('apiKey')).to.be.undefined;
});
it('sends the correct parameters when provisioning', async () => {
const conf = JSON.parse(
await fs.readFile('./test/data/config-apibinder.json', 'utf8'),
);
expect(balenaAPI.balenaBackend!.devices).to.deep.equal({
'1': {
id: 1,
application: conf.applicationId,
uuid: conf.uuid,
device_type: conf.deviceType,
api_key: conf.deviceApiKey,
mac_address: '00:11:22:33:44:55 66:77:88:99:AA:BB',
os_variant: 'dev',
os_version: 'balenaOS 2.0.6+rev1',
supervisor_version: supervisorVersion,
},
});
});
});
describe('fetchDevice', () => {
const components: Dictionary<any> = {};
before(() => {
return initModels(components, '/config-apibinder.json');
});
after(async () => {
// @ts-expect-error setting read-only property
config.configJsonBackend = defaultConfigBackend;
await config.generateRequiredFields();
});
it('gets a device by its uuid from the balena API', async () => {
// Manually add a device to the mocked API
balenaAPI.balenaBackend!.devices[3] = {
id: 3,
user: 'foo',
application: 1337,
uuid: 'abcd',
device_type: 'intel-nuc',
api_key: 'verysecure',
};
const device = await ApiHelper.fetchDevice(
components.apiBinder.balenaApi,
'abcd',
'someApiKey',
30000,
);
expect(device).to.deep.equal(balenaAPI.balenaBackend!.devices[3]);
});
});
describe('exchangeKeyAndGetDevice', () => {
const components: Dictionary<any> = {};
before(() => {
return initModels(components, '/config-apibinder.json');
});
after(async () => {
// @ts-expect-error setting read-only property
config.configJsonBackend = defaultConfigBackend;
await config.generateRequiredFields();
});
it('returns the device if it can fetch it with the deviceApiKey', async () => {
spy(balenaAPI.balenaBackend!, 'deviceKeyHandler');
const fetchDeviceStub = stub(ApiHelper, 'fetchDevice');
fetchDeviceStub.onCall(0).resolves({ id: 1 });
const device = await ApiHelper.exchangeKeyAndGetDevice(
components.apiBinder.balenaApi,
mockProvisioningOpts,
);
expect(balenaAPI.balenaBackend!.deviceKeyHandler).to.not.be.called;
expect(device).to.deep.equal({ id: 1 });
expect(fetchDeviceStub).to.be.calledOnce;
// @ts-expect-error function does not exist on type
balenaAPI.balenaBackend.deviceKeyHandler.restore();
fetchDeviceStub.restore();
});
it('throws if it cannot get the device with any of the keys', () => {
spy(balenaAPI.balenaBackend!, 'deviceKeyHandler');
const fetchDeviceStub = stub(ApiHelper, 'fetchDevice').throws(
new DeviceNotFoundError(),
);
const promise = ApiHelper.exchangeKeyAndGetDevice(
components.apiBinder.balenaApi,
mockProvisioningOpts,
);
promise.catch(() => {
/* noop */
});
return expect(promise).to.be.rejected.then(() => {
expect(balenaAPI.balenaBackend!.deviceKeyHandler).to.not.be.called;
expect(fetchDeviceStub).to.be.calledTwice;
fetchDeviceStub.restore();
// @ts-expect-error function does not exist on type
balenaAPI.balenaBackend.deviceKeyHandler.restore();
});
});
it('exchanges the key and returns the device if the provisioning key is valid', async () => {
spy(balenaAPI.balenaBackend!, 'deviceKeyHandler');
const fetchDeviceStub = stub(ApiHelper, 'fetchDevice');
fetchDeviceStub.onCall(0).throws(new DeviceNotFoundError());
fetchDeviceStub.onCall(1).returns(Promise.resolve({ id: 1 }));
const device = await ApiHelper.exchangeKeyAndGetDevice(
components.apiBinder.balenaApi,
mockProvisioningOpts as any,
);
expect(balenaAPI.balenaBackend!.deviceKeyHandler).to.be.calledOnce;
expect(device).to.deep.equal({ id: 1 });
expect(fetchDeviceStub).to.be.calledTwice;
fetchDeviceStub.restore();
// @ts-expect-error function does not exist on type
balenaAPI.balenaBackend.deviceKeyHandler.restore();
});
});
describe('unmanaged mode', () => {
const components: Dictionary<any> = {};
before(() => {
return initModels(components, '/config-apibinder-offline.json');
});
after(async () => {
// @ts-expect-error setting read-only property
config.configJsonBackend = defaultConfigBackend;
await config.generateRequiredFields();
});
it('does not generate a key if the device is in unmanaged mode', async () => {
const mode = await config.get('unmanaged');
// Ensure offline mode is set
expect(mode).to.equal(true);
// Check that there is no deviceApiKey
const conf = await config.getMany(['deviceApiKey', 'uuid']);
expect(conf['deviceApiKey']).to.be.empty;
expect(conf['uuid']).to.not.be.undefined;
});
describe('Minimal config unmanaged mode', () => {
const components2: Dictionary<any> = {};
before(() => {
return initModels(components2, '/config-apibinder-offline2.json');
});
it('does not generate a key with the minimal config', async () => {
const mode = await config.get('unmanaged');
expect(mode).to.equal(true);
const conf = await config.getMany(['deviceApiKey', 'uuid']);
expect(conf['deviceApiKey']).to.be.empty;
return expect(conf['uuid']).to.not.be.undefined;
});
});
});
describe('healthchecks', () => {
const components: Dictionary<any> = {};
let configStub: SinonStub;
let infoLobSpy: SinonSpy;
let previousLastFetch: ReturnType<typeof process.hrtime>;
before(async () => {
await initModels(components, '/config-apibinder.json');
previousLastFetch = TargetState.lastFetch;
});
after(async () => {
// @ts-expect-error setting read-only property
config.configJsonBackend = defaultConfigBackend;
await config.generateRequiredFields();
});
beforeEach(() => {
// This configStub will be modified in each test case so we can
// create the exact conditions we want to for testing healthchecks
configStub = stub(config, 'getMany');
infoLobSpy = spy(Log, 'info');
});
afterEach(() => {
configStub.restore();
infoLobSpy.restore();
(TargetState as any).lastFetch = previousLastFetch;
});
it('passes with correct conditions', async () => {
// Set unmanaged to false so we check all values
// The other values are stubbed to make it pass
configStub.resolves({
unmanaged: false,
appUpdatePollInterval: 1000,
connectivityCheckEnabled: false,
});
// Set lastFetch to now so it is within appUpdatePollInterval
(TargetState as any).lastFetch = process.hrtime();
expect(await components.apiBinder.healthcheck()).to.equal(true);
});
it('passes if unmanaged is true and exit early', async () => {
// Setup failing conditions
configStub.resolves({
unmanaged: false,
appUpdatePollInterval: null,
connectivityCheckEnabled: false,
});
// Verify this causes healthcheck to fail
expect(await components.apiBinder.healthcheck()).to.equal(false);
// Do it again but set unmanaged to true
configStub.resolves({
unmanaged: true,
appUpdatePollInterval: null,
connectivityCheckEnabled: false,
});
expect(await components.apiBinder.healthcheck()).to.equal(true);
});
it('fails if appUpdatePollInterval not set in config and exit early', async () => {
configStub.resolves({
unmanaged: false,
appUpdatePollInterval: null,
connectivityCheckEnabled: false,
});
expect(await components.apiBinder.healthcheck()).to.equal(false);
expect(Log.info).to.be.calledOnce;
expect((Log.info as SinonSpy).lastCall?.lastArg).to.equal(
'Healthcheck failure - Config value `appUpdatePollInterval` cannot be null',
);
});
it("fails when hasn't checked target state within poll interval", async () => {
configStub.resolves({
unmanaged: false,
appUpdatePollInterval: 1,
connectivityCheckEnabled: false,
});
expect(await components.apiBinder.healthcheck()).to.equal(false);
expect(Log.info).to.be.calledOnce;
expect((Log.info as SinonSpy).lastCall?.lastArg).to.equal(
'Healthcheck failure - Device has not fetched target state within appUpdatePollInterval limit',
);
});
it('fails when stateReportHealthy is false', async () => {
const currentState = await import('../src/device-state/current-state');
configStub.resolves({
unmanaged: false,
appUpdatePollInterval: 1000,
connectivityCheckEnabled: true,
});
// Set lastFetch to now so it is within appUpdatePollInterval
(TargetState as any).lastFetch = process.hrtime();
// Copy previous values to restore later
const previousStateReportErrors = currentState.stateReportErrors;
const previousDeviceStateConnected =
// @ts-ignore
components.deviceState.connected;
// Set additional conditions not in configStub to cause a fail
try {
currentState.stateReportErrors = 4;
components.deviceState.connected = true;
expect(await components.apiBinder.healthcheck()).to.equal(false);
expect(Log.info).to.be.calledOnce;
expect((Log.info as SinonSpy).lastCall?.lastArg).to.equal(
stripIndent`
Healthcheck failure - At least ONE of the following conditions must be true:
- No connectivityCheckEnabled ? false
- device state is disconnected ? false
- stateReportErrors less then 3 ? false`,
);
} finally {
// Restore previous values
currentState.stateReportErrors = previousStateReportErrors;
components.deviceState.connected = previousDeviceStateConnected;
}
});
});
}); | the_stack |
import { bin } from "./bin";
import { VoidPointer } from "./core";
import { NativeArray, nativeClass, NativeClass, nativeField } from "./nativeclass";
import { bin64_t, int32_t, uint16_t, uint32_t, uint8_t } from "./nativetype";
const UBYTE = uint8_t;
type UBYTE = uint8_t;
const USHORT = uint16_t;
type USHORT = uint16_t;
const ULONG = uint32_t;
type ULONG = uint32_t;
export const MAX_PATH = 260;
export const PAGE_NOACCESS = 0x01;
export const PAGE_READONLY = 0x02;
export const PAGE_READWRITE = 0x04;
export const PAGE_WRITECOPY = 0x08;
export const PAGE_EXECUTE = 0x10;
export const PAGE_EXECUTE_READ = 0x20;
export const PAGE_EXECUTE_READWRITE = 0x40;
export const PAGE_EXECUTE_WRITECOPY = 0x80;
export const PAGE_GUARD = 0x100;
export const PAGE_NOCACHE = 0x200;
export const PAGE_WRITECOMBINE = 0x400;
export const PAGE_GRAPHICS_NOACCESS = 0x0800;
export const PAGE_GRAPHICS_READONLY = 0x1000;
export const PAGE_GRAPHICS_READWRITE = 0x2000;
export const PAGE_GRAPHICS_EXECUTE = 0x4000;
export const PAGE_GRAPHICS_EXECUTE_READ = 0x8000;
export const PAGE_GRAPHICS_EXECUTE_READWRITE = 0x10000;
export const PAGE_GRAPHICS_COHERENT = 0x20000;
export const PAGE_ENCLAVE_THREAD_CONTROL = 0x80000000;
export const PAGE_REVERT_TO_FILE_MAP = 0x80000000;
export const PAGE_TARGETS_NO_UPDATE = 0x40000000;
export const PAGE_TARGETS_INVALID = 0x40000000;
export const PAGE_ENCLAVE_UNVALIDATED = 0x20000000;
export const PAGE_ENCLAVE_DECOMMIT = 0x10000000;
export const MEM_COMMIT = 0x00001000;
export const MEM_RESERVE = 0x00002000;
export const MEM_REPLACE_PLACEHOLDER = 0x00004000;
export const MEM_RESERVE_PLACEHOLDER = 0x00040000;
export const MEM_RESET = 0x00080000;
export const MEM_TOP_DOWN = 0x00100000;
export const MEM_WRITE_WATCH = 0x00200000;
export const MEM_PHYSICAL = 0x00400000;
export const MEM_ROTATE = 0x00800000;
export const MEM_DIFFERENT_IMAGE_BASE_OK = 0x00800000;
export const MEM_RESET_UNDO = 0x01000000;
export const MEM_LARGE_PAGES = 0x20000000;
export const MEM_4MB_PAGES = 0x80000000;
export const MEM_64K_PAGES = (MEM_LARGE_PAGES | MEM_PHYSICAL);
export const MEM_UNMAP_WITH_TRANSIENT_BOOST = 0x00000001;
export const MEM_COALESCE_PLACEHOLDERS = 0x00000001;
export const MEM_PRESERVE_PLACEHOLDER = 0x00000002;
export const MEM_DECOMMIT = 0x00004000;
export const MEM_RELEASE = 0x00008000;
export const MEM_FREE = 0x00010000;
export const CHAR = uint8_t;
export type CHAR = uint8_t;
export const BYTE = uint8_t;
export type BYTE = uint8_t;
export const WORD = uint16_t;
export type WORD = uint16_t;
export const DWORD = uint32_t;
export type DWORD = uint32_t;
export const LONG = int32_t;
export type LONG = int32_t;
export const ULONGLONG = bin64_t;
export type ULONGLONG = bin64_t;
export const ULONG_PTR = bin64_t;
export type ULONG_PTR = bin64_t;
export const IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
export const IMAGE_DOS_SIGNATURE = 0x5A4D; // MZ
export const IMAGE_DIRECTORY_ENTRY_EXPORT = 0; // Export Directory
export const IMAGE_DIRECTORY_ENTRY_IMPORT = 1; // Import Directory
export const IMAGE_DIRECTORY_ENTRY_RESOURCE = 2; // Resource Directory
export const IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3; // Exception Directory
export const IMAGE_DIRECTORY_ENTRY_SECURITY = 4; // Security Directory
export const IMAGE_DIRECTORY_ENTRY_BASERELOC = 5; // Base Relocation Table
export const IMAGE_DIRECTORY_ENTRY_DEBUG = 6; // Debug Directory
// IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 // (X86 usage)
export const IMAGE_DIRECTORY_ENTRY_ARCHITECTURE = 7; // Architecture Specific Data
export const IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8; // RVA of GP
export const IMAGE_DIRECTORY_ENTRY_TLS = 9; // TLS Directory
export const IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10; // Load Configuration Directory
export const IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = 11; // Bound Import Directory in headers
export const IMAGE_DIRECTORY_ENTRY_IAT = 12; // Import Address Table
export const IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT = 13; // Delay Load Import Descriptors
export const IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14; // COM Runtime descriptor
export const IMAGE_ORDINAL_FLAG64 = bin.make64(0, 0x80000000);
export const IMAGE_ORDINAL_FLAG32 = 0x80000000;
export const b64_LOW_WORD = bin.make(0xffff, 4);
export function IMAGE_ORDINAL64(Ordinal:string):string { return (bin.bitand(Ordinal, b64_LOW_WORD)); }
export function IMAGE_SNAP_BY_ORDINAL64(Ordinal:string):boolean { return (bin.bitand(Ordinal, IMAGE_ORDINAL_FLAG64) !== bin64_t.zero); }
@nativeClass()
export class IMAGE_DATA_DIRECTORY extends NativeClass {
@nativeField(DWORD)
VirtualAddress:DWORD;
@nativeField(DWORD)
Size:DWORD;
}
@nativeClass()
export class IMAGE_DOS_HEADER extends NativeClass {
@nativeField(WORD)
e_magic: WORD; // Magic number
@nativeField(WORD)
e_cblp: WORD; // Bytes on last page of file
@nativeField(WORD)
e_cp: WORD; // Pages in file
@nativeField(WORD)
e_crlc: WORD; // Relocations
@nativeField(WORD)
e_cparhdr: WORD; // Size of header in paragraphs
@nativeField(WORD)
e_minalloc: WORD; // Minimum extra paragraphs needed
@nativeField(WORD)
e_maxalloc: WORD; // Maximum extra paragraphs needed
@nativeField(WORD)
e_ss: WORD; // Initial (relative) SS value
@nativeField(WORD)
e_sp: WORD; // Initial SP value
@nativeField(WORD)
e_csum: WORD; // Checksum
@nativeField(WORD)
e_ip: WORD; // Initial IP value
@nativeField(WORD)
e_cs: WORD; // Initial (relative) CS value
@nativeField(WORD)
e_lfarlc: WORD; // File address of relocation table
@nativeField(WORD)
e_ovno: WORD; // Overlay number
@nativeField(NativeArray.make(WORD, 4))
e_res: NativeArray<WORD>; // Reserved words
@nativeField(WORD)
e_oemid: WORD; // OEM identifier (for e_oeminfo)
@nativeField(WORD)
e_oeminfo: WORD; // OEM information; e_oemid specific
@nativeField(NativeArray.make(WORD, 10))
e_res2: NativeArray<WORD>; // Reserved words
@nativeField(WORD)
e_lfanew: LONG; // File address of new exe header
}
@nativeClass()
export class IMAGE_FILE_HEADER extends NativeClass {
@nativeField(WORD)
Machine: WORD;
@nativeField(WORD)
NumberOfSections: WORD;
@nativeField(DWORD)
TimeDateStamp: DWORD;
@nativeField(DWORD)
PointerToSymbolTable: DWORD;
@nativeField(DWORD)
NumberOfSymbols: DWORD;
@nativeField(WORD)
SizeOfOptionalHeader: WORD;
@nativeField(WORD)
Characteristics: WORD;
}
@nativeClass()
export class IMAGE_OPTIONAL_HEADER64 extends NativeClass {
@nativeField(WORD)
Magic: WORD;
@nativeField(BYTE)
MajorLinkerVersion: BYTE;
@nativeField(BYTE)
MinorLinkerVersion: BYTE;
@nativeField(DWORD)
SizeOfCode: DWORD;
@nativeField(DWORD)
SizeOfInitializedData: DWORD;
@nativeField(DWORD)
SizeOfUninitializedData: DWORD;
@nativeField(DWORD)
AddressOfEntryPoint: DWORD;
@nativeField(DWORD)
BaseOfCode: DWORD;
@nativeField(ULONGLONG)
ImageBase: ULONGLONG;
@nativeField(DWORD)
SectionAlignment: DWORD;
@nativeField(DWORD)
FileAlignment: DWORD;
@nativeField(WORD)
MajorOperatingSystemVersion: WORD;
@nativeField(WORD)
MinorOperatingSystemVersion: WORD;
@nativeField(WORD)
MajorImageVersion: WORD;
@nativeField(WORD)
MinorImageVersion: WORD;
@nativeField(WORD)
MajorSubsystemVersion: WORD;
@nativeField(WORD)
MinorSubsystemVersion: WORD;
@nativeField(DWORD)
Win32VersionValue: DWORD;
@nativeField(DWORD)
SizeOfImage: DWORD;
@nativeField(DWORD)
SizeOfHeaders: DWORD;
@nativeField(DWORD)
CheckSum: DWORD;
@nativeField(WORD)
Subsystem: WORD;
@nativeField(WORD)
DllCharacteristics: WORD;
@nativeField(ULONGLONG)
SizeOfStackReserve: ULONGLONG;
@nativeField(ULONGLONG)
SizeOfStackCommit: ULONGLONG;
@nativeField(ULONGLONG)
SizeOfHeapReserve: ULONGLONG;
@nativeField(ULONGLONG)
SizeOfHeapCommit: ULONGLONG;
@nativeField(DWORD)
LoaderFlags: DWORD;
@nativeField(DWORD)
NumberOfRvaAndSizes: DWORD;
@nativeField(NativeArray.make<IMAGE_DATA_DIRECTORY>(IMAGE_DATA_DIRECTORY, IMAGE_NUMBEROF_DIRECTORY_ENTRIES))
DataDirectory: NativeArray<IMAGE_DATA_DIRECTORY>;
}
@nativeClass()
export class IMAGE_NT_HEADERS64 extends NativeClass {
@nativeField(DWORD)
Signature: DWORD;
@nativeField(IMAGE_FILE_HEADER)
FileHeader: IMAGE_FILE_HEADER;
@nativeField(IMAGE_OPTIONAL_HEADER64)
OptionalHeader: IMAGE_OPTIONAL_HEADER64;
}
@nativeClass()
export class IMAGE_DEBUG_DIRECTORY extends NativeClass {
@nativeField(DWORD)
Characteristics: DWORD;
@nativeField(DWORD)
TimeDateStamp: DWORD;
@nativeField(WORD)
MajorVersion: WORD;
@nativeField(WORD)
MinorVersion: WORD;
@nativeField(DWORD)
Type: DWORD;
@nativeField(DWORD)
SizeOfData: DWORD;
@nativeField(DWORD)
AddressOfRawData: DWORD;
@nativeField(DWORD)
PointerToRawData: DWORD;
}
@nativeClass()
export class IMAGE_IMPORT_DESCRIPTOR extends NativeClass {
@nativeField(WORD)
Characteristics:DWORD; // 0 for terminating null import descriptor
@nativeField(WORD)
OriginalFirstThunk:DWORD; // RVA to original unbound IAT (PIMAGE_THUNK_DATA)
@nativeField(DWORD)
TimeDateStamp: DWORD; // 0 if not bound,
// -1 if bound, and real date\time stamp
// in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT (new BIND)
// O.W. date/time stamp of DLL bound to (Old BIND)
@nativeField(DWORD)
ForwarderChain: DWORD; // -1 if no forwarders
@nativeField(DWORD)
Name: DWORD;
@nativeField(DWORD)
FirstThunk: DWORD; // RVA to IAT (if bound this IAT has actual addresses)
}
class IMAGE_THUNK_DATA64_union extends NativeClass {
ForwarderString:ULONGLONG; // PBYTE
Function:ULONGLONG; // PDWORD
Ordinal:ULONGLONG;
AddressOfData:ULONGLONG; // PIMAGE_IMPORT_BY_NAME
}
IMAGE_THUNK_DATA64_union.defineAsUnion({
ForwarderString:ULONGLONG, // PBYTE
Function:ULONGLONG, // PDWORD
Ordinal:ULONGLONG,
AddressOfData:ULONGLONG, // PIMAGE_IMPORT_BY_NAME
});
@nativeClass()
export class IMAGE_THUNK_DATA64 extends NativeClass {
@nativeField(IMAGE_THUNK_DATA64_union)
u1:IMAGE_THUNK_DATA64_union;
}
class IMAGE_SECTION_HEADER_Misc extends NativeClass {
PhysicalAddress:DWORD;
VirtualSize:DWORD;
}
IMAGE_SECTION_HEADER_Misc.defineAsUnion({
PhysicalAddress:DWORD,
VirtualSize:DWORD,
});
const IMAGE_SIZEOF_SHORT_NAME = 8;
@nativeClass()
export class IMAGE_SECTION_HEADER extends NativeClass {
@nativeField(NativeArray.make(BYTE, IMAGE_SIZEOF_SHORT_NAME))
Name: NativeArray<BYTE>;
@nativeField(IMAGE_SECTION_HEADER_Misc)
Misc:IMAGE_SECTION_HEADER_Misc;
@nativeField(DWORD)
VirtualAddress:DWORD;
@nativeField(DWORD)
SizeOfRawData:DWORD;
@nativeField(DWORD)
PointerToRawData:DWORD;
@nativeField(DWORD)
PointerToRelocations:DWORD;
@nativeField(DWORD)
PointerToLinenumbers:DWORD;
@nativeField(WORD)
NumberOfRelocations:WORD;
@nativeField(WORD)
NumberOfLinenumbers:WORD;
@nativeField(DWORD)
Characteristics:DWORD;
}
const EXCEPTION_MAXIMUM_PARAMETERS = 15; // maximum number of exception parameters
@nativeClass()
export class EXCEPTION_RECORD extends NativeClass {
@nativeField(DWORD)
ExceptionCode:DWORD;
@nativeField(DWORD)
ExceptionFlags:DWORD;
@nativeField(VoidPointer)
ExceptionRecord:VoidPointer;
@nativeField(VoidPointer)
ExceptionAddress:VoidPointer;
@nativeField(DWORD)
NumberParameters:DWORD;
@nativeField(DWORD)
dummy:DWORD;
@nativeField(NativeArray.make(ULONG_PTR, EXCEPTION_MAXIMUM_PARAMETERS))
ExceptionInformation:NativeArray<ULONG_PTR>;
}
// typedef struct DECLSPEC_ALIGN(16) DECLSPEC_NOINITALL _CONTEXT {
// //
// // Register parameter home addresses.
// //
// // N.B. These fields are for convience - they could be used to extend the
// // context record in the future.
// //
// DWORD64 P1Home;
// DWORD64 P2Home;
// DWORD64 P3Home;
// DWORD64 P4Home;
// DWORD64 P5Home;
// DWORD64 P6Home;
// //
// // Control flags.
// //
// DWORD ContextFlags;
// DWORD MxCsr;
// //
// // Segment Registers and processor flags.
// //
// WORD SegCs;
// WORD SegDs;
// WORD SegEs;
// WORD SegFs;
// WORD SegGs;
// WORD SegSs;
// DWORD EFlags;
// //
// // Debug registers
// //
// DWORD64 Dr0;
// DWORD64 Dr1;
// DWORD64 Dr2;
// DWORD64 Dr3;
// DWORD64 Dr6;
// DWORD64 Dr7;
// //
// // Integer registers.
// //
// DWORD64 Rax;
// DWORD64 Rcx;
// DWORD64 Rdx;
// DWORD64 Rbx;
// DWORD64 Rsp;
// DWORD64 Rbp;
// DWORD64 Rsi;
// DWORD64 Rdi;
// DWORD64 R8;
// DWORD64 R9;
// DWORD64 R10;
// DWORD64 R11;
// DWORD64 R12;
// DWORD64 R13;
// DWORD64 R14;
// DWORD64 R15;
// //
// // Program counter.
// //
// DWORD64 Rip;
// //
// // Floating point state.
// //
// union {
// XMM_SAVE_AREA32 FltSave;
// struct {
// M128A Header[2];
// M128A Legacy[8];
// M128A Xmm0;
// M128A Xmm1;
// M128A Xmm2;
// M128A Xmm3;
// M128A Xmm4;
// M128A Xmm5;
// M128A Xmm6;
// M128A Xmm7;
// M128A Xmm8;
// M128A Xmm9;
// M128A Xmm10;
// M128A Xmm11;
// M128A Xmm12;
// M128A Xmm13;
// M128A Xmm14;
// M128A Xmm15;
// } DUMMYSTRUCTNAME;
// } DUMMYUNIONNAME;
// //
// // Vector registers.
// //
// M128A VectorRegister[26];
// DWORD64 VectorControl;
// //
// // Special debug control registers.
// //
// DWORD64 DebugControl;
// DWORD64 LastBranchToRip;
// DWORD64 LastBranchFromRip;
// DWORD64 LastExceptionToRip;
// DWORD64 LastExceptionFromRip;
// } CONTEXT, *PCONTEXT;
@nativeClass()
export class EXCEPTION_POINTERS extends NativeClass {
@nativeField(EXCEPTION_RECORD.ref())
ExceptionRecord:EXCEPTION_RECORD;
@nativeField(VoidPointer)
ContextRecord:VoidPointer; // CONTEXT
}
@nativeClass()
export class FILETIME extends NativeClass {
@nativeField(DWORD)
dwLowDateTime: DWORD;
@nativeField(DWORD)
dwHighDateTime: DWORD;
}
export function IMAGE_FIRST_SECTION(ntheader:IMAGE_NT_HEADERS64):IMAGE_SECTION_HEADER {
return ntheader.addAs(IMAGE_SECTION_HEADER, IMAGE_NT_HEADERS64.offsetOf('OptionalHeader') + ntheader.FileHeader.SizeOfOptionalHeader);
}
export const EXCEPTION_BREAKPOINT = 0x80000003|0;
export const EXCEPTION_ACCESS_VIOLATION = 0xC0000005|0;
export const STATUS_INVALID_PARAMETER = 0xC000000D|0;
export const EXCEPTION_NONCONTINUABLE_EXCEPTION = 0xC0000025|0;
export const FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
export const FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
export const FORMAT_MESSAGE_FROM_STRING = 0x00000400;
export const FORMAT_MESSAGE_FROM_HMODULE = 0x00000800;
export const FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
export const FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
export const FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF;
export function MAKELANGID(p:number, s:number):number {
return (s << 10) | p;
}
export function PRIMARYLANGID(lgid:number):number {
return lgid & 0x3ff;
}
export function SUBLANGID(lgid:number):number {
return (lgid & 0xffff) >>> 10;
}
export const LANG_NEUTRAL = 0x00;
export const LANG_INVARIANT = 0x7f;
export const LANG_AFRIKAANS = 0x36;
export const LANG_ALBANIAN = 0x1c;
export const LANG_ALSATIAN = 0x84;
export const LANG_AMHARIC = 0x5e;
export const LANG_ARABIC = 0x01;
export const LANG_ARMENIAN = 0x2b;
export const LANG_ASSAMESE = 0x4d;
export const LANG_AZERI = 0x2c; // for Azerbaijani, LANG_AZERBAIJANI is preferred
export const LANG_AZERBAIJANI = 0x2c;
export const LANG_BANGLA = 0x45;
export const LANG_BASHKIR = 0x6d;
export const LANG_BASQUE = 0x2d;
export const LANG_BELARUSIAN = 0x23;
export const LANG_BENGALI = 0x45; // Some prefer to use LANG_BANGLA
export const LANG_BRETON = 0x7e;
export const LANG_BOSNIAN = 0x1a; // Use with SUBLANG_BOSNIAN_* Sublanguage IDs
export const LANG_BOSNIAN_NEUTRAL = 0x781a; // Use with the ConvertDefaultLocale function
export const LANG_BULGARIAN = 0x02;
export const LANG_CATALAN = 0x03;
export const LANG_CENTRAL_KURDISH = 0x92;
export const LANG_CHEROKEE = 0x5c;
export const LANG_CHINESE = 0x04; // Use with SUBLANG_CHINESE_* Sublanguage IDs
export const LANG_CHINESE_SIMPLIFIED = 0x04; // Use with the ConvertDefaultLocale function
export const LANG_CHINESE_TRADITIONAL = 0x7c04; // Use with the ConvertDefaultLocale function
export const LANG_CORSICAN = 0x83;
export const LANG_CROATIAN = 0x1a;
export const LANG_CZECH = 0x05;
export const LANG_DANISH = 0x06;
export const LANG_DARI = 0x8c;
export const LANG_DIVEHI = 0x65;
export const LANG_DUTCH = 0x13;
export const LANG_ENGLISH = 0x09;
export const LANG_ESTONIAN = 0x25;
export const LANG_FAEROESE = 0x38;
export const LANG_FARSI = 0x29; // Deprecated: use LANG_PERSIAN instead
export const LANG_FILIPINO = 0x64;
export const LANG_FINNISH = 0x0b;
export const LANG_FRENCH = 0x0c;
export const LANG_FRISIAN = 0x62;
export const LANG_FULAH = 0x67;
export const LANG_GALICIAN = 0x56;
export const LANG_GEORGIAN = 0x37;
export const LANG_GERMAN = 0x07;
export const LANG_GREEK = 0x08;
export const LANG_GREENLANDIC = 0x6f;
export const LANG_GUJARATI = 0x47;
export const LANG_HAUSA = 0x68;
export const LANG_HAWAIIAN = 0x75;
export const LANG_HEBREW = 0x0d;
export const LANG_HINDI = 0x39;
export const LANG_HUNGARIAN = 0x0e;
export const LANG_ICELANDIC = 0x0f;
export const LANG_IGBO = 0x70;
export const LANG_INDONESIAN = 0x21;
export const LANG_INUKTITUT = 0x5d;
export const LANG_IRISH = 0x3c; // Use with the SUBLANG_IRISH_IRELAND Sublanguage ID
export const LANG_ITALIAN = 0x10;
export const LANG_JAPANESE = 0x11;
export const LANG_KANNADA = 0x4b;
export const LANG_KASHMIRI = 0x60;
export const LANG_KAZAK = 0x3f;
export const LANG_KHMER = 0x53;
export const LANG_KICHE = 0x86;
export const LANG_KINYARWANDA = 0x87;
export const LANG_KONKANI = 0x57;
export const LANG_KOREAN = 0x12;
export const LANG_KYRGYZ = 0x40;
export const LANG_LAO = 0x54;
export const LANG_LATVIAN = 0x26;
export const LANG_LITHUANIAN = 0x27;
export const LANG_LOWER_SORBIAN = 0x2e;
export const LANG_LUXEMBOURGISH = 0x6e;
export const LANG_MACEDONIAN = 0x2f; // the Former Yugoslav Republic of Macedonia
export const LANG_MALAY = 0x3e;
export const LANG_MALAYALAM = 0x4c;
export const LANG_MALTESE = 0x3a;
export const LANG_MANIPURI = 0x58;
export const LANG_MAORI = 0x81;
export const LANG_MAPUDUNGUN = 0x7a;
export const LANG_MARATHI = 0x4e;
export const LANG_MOHAWK = 0x7c;
export const LANG_MONGOLIAN = 0x50;
export const LANG_NEPALI = 0x61;
export const LANG_NORWEGIAN = 0x14;
export const LANG_OCCITAN = 0x82;
export const LANG_ODIA = 0x48;
export const LANG_ORIYA = 0x48; // Deprecated: use LANG_ODIA, instead.
export const LANG_PASHTO = 0x63;
export const LANG_PERSIAN = 0x29;
export const LANG_POLISH = 0x15;
export const LANG_PORTUGUESE = 0x16;
export const LANG_PULAR = 0x67; // Deprecated: use LANG_FULAH instead
export const LANG_PUNJABI = 0x46;
export const LANG_QUECHUA = 0x6b;
export const LANG_ROMANIAN = 0x18;
export const LANG_ROMANSH = 0x17;
export const LANG_RUSSIAN = 0x19;
export const LANG_SAKHA = 0x85;
export const LANG_SAMI = 0x3b;
export const LANG_SANSKRIT = 0x4f;
export const LANG_SCOTTISH_GAELIC = 0x91;
export const LANG_SERBIAN = 0x1a; // Use with the SUBLANG_SERBIAN_* Sublanguage IDs
export const LANG_SERBIAN_NEUTRAL = 0x7c1a; // Use with the ConvertDefaultLocale function
export const LANG_SINDHI = 0x59;
export const LANG_SINHALESE = 0x5b;
export const LANG_SLOVAK = 0x1b;
export const LANG_SLOVENIAN = 0x24;
export const LANG_SOTHO = 0x6c;
export const LANG_SPANISH = 0x0a;
export const LANG_SWAHILI = 0x41;
export const LANG_SWEDISH = 0x1d;
export const LANG_SYRIAC = 0x5a;
export const LANG_TAJIK = 0x28;
export const LANG_TAMAZIGHT = 0x5f;
export const LANG_TAMIL = 0x49;
export const LANG_TATAR = 0x44;
export const LANG_TELUGU = 0x4a;
export const LANG_THAI = 0x1e;
export const LANG_TIBETAN = 0x51;
export const LANG_TIGRIGNA = 0x73;
export const LANG_TIGRINYA = 0x73; // Preferred spelling in locale
export const LANG_TSWANA = 0x32;
export const LANG_TURKISH = 0x1f;
export const LANG_TURKMEN = 0x42;
export const LANG_UIGHUR = 0x80;
export const LANG_UKRAINIAN = 0x22;
export const LANG_UPPER_SORBIAN = 0x2e;
export const LANG_URDU = 0x20;
export const LANG_UZBEK = 0x43;
export const LANG_VALENCIAN = 0x03;
export const LANG_VIETNAMESE = 0x2a;
export const LANG_WELSH = 0x52;
export const LANG_WOLOF = 0x88;
export const LANG_XHOSA = 0x34;
export const LANG_YAKUT = 0x85; // Deprecated: use LANG_SAKHA,instead
export const LANG_YI = 0x78;
export const LANG_YORUBA = 0x6a;
export const LANG_ZULU = 0x35;
export const SUBLANG_NEUTRAL = 0x00; // language neutral
export const SUBLANG_DEFAULT = 0x01; // user default
export const SUBLANG_SYS_DEFAULT = 0x02; // system default
export const SUBLANG_CUSTOM_DEFAULT = 0x03; // default custom language/locale
export const SUBLANG_CUSTOM_UNSPECIFIED = 0x04; // custom language/locale
export const SUBLANG_UI_CUSTOM_DEFAULT = 0x05; // Default custom MUI language/locale
export const SUBLANG_AFRIKAANS_SOUTH_AFRICA = 0x01; // Afrikaans (South Africa) 0x0436 af-ZA
export const SUBLANG_ALBANIAN_ALBANIA = 0x01; // Albanian (Albania) 0x041c sq-AL
export const SUBLANG_ALSATIAN_FRANCE = 0x01; // Alsatian (France) 0x0484
export const SUBLANG_AMHARIC_ETHIOPIA = 0x01; // Amharic (Ethiopia) 0x045e
export const SUBLANG_ARABIC_SAUDI_ARABIA = 0x01; // Arabic (Saudi Arabia)
export const SUBLANG_ARABIC_IRAQ = 0x02; // Arabic (Iraq)
export const SUBLANG_ARABIC_EGYPT = 0x03; // Arabic (Egypt)
export const SUBLANG_ARABIC_LIBYA = 0x04; // Arabic (Libya)
export const SUBLANG_ARABIC_ALGERIA = 0x05; // Arabic (Algeria)
export const SUBLANG_ARABIC_MOROCCO = 0x06; // Arabic (Morocco)
export const SUBLANG_ARABIC_TUNISIA = 0x07; // Arabic (Tunisia)
export const SUBLANG_ARABIC_OMAN = 0x08; // Arabic (Oman)
export const SUBLANG_ARABIC_YEMEN = 0x09; // Arabic (Yemen)
export const SUBLANG_ARABIC_SYRIA = 0x0a; // Arabic (Syria)
export const SUBLANG_ARABIC_JORDAN = 0x0b; // Arabic (Jordan)
export const SUBLANG_ARABIC_LEBANON = 0x0c; // Arabic (Lebanon)
export const SUBLANG_ARABIC_KUWAIT = 0x0d; // Arabic (Kuwait)
export const SUBLANG_ARABIC_UAE = 0x0e; // Arabic (U.A.E)
export const SUBLANG_ARABIC_BAHRAIN = 0x0f; // Arabic (Bahrain)
export const SUBLANG_ARABIC_QATAR = 0x10; // Arabic (Qatar)
export const SUBLANG_ARMENIAN_ARMENIA = 0x01; // Armenian (Armenia) 0x042b hy-AM
export const SUBLANG_ASSAMESE_INDIA = 0x01; // Assamese (India) 0x044d
export const SUBLANG_AZERI_LATIN = 0x01; // Azeri (Latin) - for Azerbaijani, SUBLANG_AZERBAIJANI_AZERBAIJAN_LATIN preferred
export const SUBLANG_AZERI_CYRILLIC = 0x02; // Azeri (Cyrillic) - for Azerbaijani, SUBLANG_AZERBAIJANI_AZERBAIJAN_CYRILLIC preferred
export const SUBLANG_AZERBAIJANI_AZERBAIJAN_LATIN = 0x01; // Azerbaijani (Azerbaijan, Latin)
export const SUBLANG_AZERBAIJANI_AZERBAIJAN_CYRILLIC = 0x02; // Azerbaijani (Azerbaijan, Cyrillic)
export const SUBLANG_BANGLA_INDIA = 0x01; // Bangla (India)
export const SUBLANG_BANGLA_BANGLADESH = 0x02; // Bangla (Bangladesh)
export const SUBLANG_BASHKIR_RUSSIA = 0x01; // Bashkir (Russia) 0x046d ba-RU
export const SUBLANG_BASQUE_BASQUE = 0x01; // Basque (Basque) 0x042d eu-ES
export const SUBLANG_BELARUSIAN_BELARUS = 0x01; // Belarusian (Belarus) 0x0423 be-BY
export const SUBLANG_BENGALI_INDIA = 0x01; // Bengali (India) - Note some prefer SUBLANG_BANGLA_INDIA
export const SUBLANG_BENGALI_BANGLADESH = 0x02; // Bengali (Bangladesh) - Note some prefer SUBLANG_BANGLA_BANGLADESH
export const SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_LATIN = 0x05; // Bosnian (Bosnia and Herzegovina - Latin) 0x141a bs-BA-Latn
export const SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC = 0x08; // Bosnian (Bosnia and Herzegovina - Cyrillic) 0x201a bs-BA-Cyrl
export const SUBLANG_BRETON_FRANCE = 0x01; // Breton (France) 0x047e
export const SUBLANG_BULGARIAN_BULGARIA = 0x01; // Bulgarian (Bulgaria) 0x0402
export const SUBLANG_CATALAN_CATALAN = 0x01; // Catalan (Catalan) 0x0403
export const SUBLANG_CENTRAL_KURDISH_IRAQ = 0x01; // Central Kurdish (Iraq) 0x0492 ku-Arab-IQ
export const SUBLANG_CHEROKEE_CHEROKEE = 0x01; // Cherokee (Cherokee) 0x045c chr-Cher-US
export const SUBLANG_CHINESE_TRADITIONAL = 0x01; // Chinese (Taiwan) 0x0404 zh-TW
export const SUBLANG_CHINESE_SIMPLIFIED = 0x02; // Chinese (PR China) 0x0804 zh-CN
export const SUBLANG_CHINESE_HONGKONG = 0x03; // Chinese (Hong Kong S.A.R., P.R.C.) 0x0c04 zh-HK
export const SUBLANG_CHINESE_SINGAPORE = 0x04; // Chinese (Singapore) 0x1004 zh-SG
export const SUBLANG_CHINESE_MACAU = 0x05; // Chinese (Macau S.A.R.) 0x1404 zh-MO
export const SUBLANG_CORSICAN_FRANCE = 0x01; // Corsican (France) 0x0483
export const SUBLANG_CZECH_CZECH_REPUBLIC = 0x01; // Czech (Czech Republic) 0x0405
export const SUBLANG_CROATIAN_CROATIA = 0x01; // Croatian (Croatia)
export const SUBLANG_CROATIAN_BOSNIA_HERZEGOVINA_LATIN = 0x04; // Croatian (Bosnia and Herzegovina - Latin) 0x101a hr-BA
export const SUBLANG_DANISH_DENMARK = 0x01; // Danish (Denmark) 0x0406
export const SUBLANG_DARI_AFGHANISTAN = 0x01; // Dari (Afghanistan)
export const SUBLANG_DIVEHI_MALDIVES = 0x01; // Divehi (Maldives) 0x0465 div-MV
export const SUBLANG_DUTCH = 0x01; // Dutch
export const SUBLANG_DUTCH_BELGIAN = 0x02; // Dutch (Belgian)
export const SUBLANG_ENGLISH_US = 0x01; // English (USA)
export const SUBLANG_ENGLISH_UK = 0x02; // English (UK)
export const SUBLANG_ENGLISH_AUS = 0x03; // English (Australian)
export const SUBLANG_ENGLISH_CAN = 0x04; // English (Canadian)
export const SUBLANG_ENGLISH_NZ = 0x05; // English (New Zealand)
export const SUBLANG_ENGLISH_EIRE = 0x06; // English (Irish)
export const SUBLANG_ENGLISH_SOUTH_AFRICA = 0x07; // English (South Africa)
export const SUBLANG_ENGLISH_JAMAICA = 0x08; // English (Jamaica)
export const SUBLANG_ENGLISH_CARIBBEAN = 0x09; // English (Caribbean)
export const SUBLANG_ENGLISH_BELIZE = 0x0a; // English (Belize)
export const SUBLANG_ENGLISH_TRINIDAD = 0x0b; // English (Trinidad)
export const SUBLANG_ENGLISH_ZIMBABWE = 0x0c; // English (Zimbabwe)
export const SUBLANG_ENGLISH_PHILIPPINES = 0x0d; // English (Philippines)
export const SUBLANG_ENGLISH_INDIA = 0x10; // English (India)
export const SUBLANG_ENGLISH_MALAYSIA = 0x11; // English (Malaysia)
export const SUBLANG_ENGLISH_SINGAPORE = 0x12; // English (Singapore)
export const SUBLANG_ESTONIAN_ESTONIA = 0x01; // Estonian (Estonia) 0x0425 et-EE
export const SUBLANG_FAEROESE_FAROE_ISLANDS = 0x01; // Faroese (Faroe Islands) 0x0438 fo-FO
export const SUBLANG_FILIPINO_PHILIPPINES = 0x01; // Filipino (Philippines) 0x0464 fil-PH
export const SUBLANG_FINNISH_FINLAND = 0x01; // Finnish (Finland) 0x040b
export const SUBLANG_FRENCH = 0x01; // French
export const SUBLANG_FRENCH_BELGIAN = 0x02; // French (Belgian)
export const SUBLANG_FRENCH_CANADIAN = 0x03; // French (Canadian)
export const SUBLANG_FRENCH_SWISS = 0x04; // French (Swiss)
export const SUBLANG_FRENCH_LUXEMBOURG = 0x05; // French (Luxembourg)
export const SUBLANG_FRENCH_MONACO = 0x06; // French (Monaco)
export const SUBLANG_FRISIAN_NETHERLANDS = 0x01; // Frisian (Netherlands) 0x0462 fy-NL
export const SUBLANG_FULAH_SENEGAL = 0x02; // Fulah (Senegal) 0x0867 ff-Latn-SN
export const SUBLANG_GALICIAN_GALICIAN = 0x01; // Galician (Galician) 0x0456 gl-ES
export const SUBLANG_GEORGIAN_GEORGIA = 0x01; // Georgian (Georgia) 0x0437 ka-GE
export const SUBLANG_GERMAN = 0x01; // German
export const SUBLANG_GERMAN_SWISS = 0x02; // German (Swiss)
export const SUBLANG_GERMAN_AUSTRIAN = 0x03; // German (Austrian)
export const SUBLANG_GERMAN_LUXEMBOURG = 0x04; // German (Luxembourg)
export const SUBLANG_GERMAN_LIECHTENSTEIN = 0x05; // German (Liechtenstein)
export const SUBLANG_GREEK_GREECE = 0x01; // Greek (Greece)
export const SUBLANG_GREENLANDIC_GREENLAND = 0x01; // Greenlandic (Greenland) 0x046f kl-GL
export const SUBLANG_GUJARATI_INDIA = 0x01; // Gujarati (India (Gujarati Script)) 0x0447 gu-IN
export const SUBLANG_HAUSA_NIGERIA_LATIN = 0x01; // Hausa (Latin, Nigeria) 0x0468 ha-NG-Latn
export const SUBLANG_HAWAIIAN_US = 0x01; // Hawiian (US) 0x0475 haw-US
export const SUBLANG_HEBREW_ISRAEL = 0x01; // Hebrew (Israel) 0x040d
export const SUBLANG_HINDI_INDIA = 0x01; // Hindi (India) 0x0439 hi-IN
export const SUBLANG_HUNGARIAN_HUNGARY = 0x01; // Hungarian (Hungary) 0x040e
export const SUBLANG_ICELANDIC_ICELAND = 0x01; // Icelandic (Iceland) 0x040f
export const SUBLANG_IGBO_NIGERIA = 0x01; // Igbo (Nigeria) 0x0470 ig-NG
export const SUBLANG_INDONESIAN_INDONESIA = 0x01; // Indonesian (Indonesia) 0x0421 id-ID
export const SUBLANG_INUKTITUT_CANADA = 0x01; // Inuktitut (Syllabics) (Canada) 0x045d iu-CA-Cans
export const SUBLANG_INUKTITUT_CANADA_LATIN = 0x02; // Inuktitut (Canada - Latin)
export const SUBLANG_IRISH_IRELAND = 0x02; // Irish (Ireland)
export const SUBLANG_ITALIAN = 0x01; // Italian
export const SUBLANG_ITALIAN_SWISS = 0x02; // Italian (Swiss)
export const SUBLANG_JAPANESE_JAPAN = 0x01; // Japanese (Japan) 0x0411
export const SUBLANG_KANNADA_INDIA = 0x01; // Kannada (India (Kannada Script)) 0x044b kn-IN
export const SUBLANG_KASHMIRI_SASIA = 0x02; // Kashmiri (South Asia)
export const SUBLANG_KASHMIRI_INDIA = 0x02; // For app compatibility only
export const SUBLANG_KAZAK_KAZAKHSTAN = 0x01; // Kazakh (Kazakhstan) 0x043f kk-KZ
export const SUBLANG_KHMER_CAMBODIA = 0x01; // Khmer (Cambodia) 0x0453 kh-KH
export const SUBLANG_KICHE_GUATEMALA = 0x01; // K'iche (Guatemala)
export const SUBLANG_KINYARWANDA_RWANDA = 0x01; // Kinyarwanda (Rwanda) 0x0487 rw-RW
export const SUBLANG_KONKANI_INDIA = 0x01; // Konkani (India) 0x0457 kok-IN
export const SUBLANG_KOREAN = 0x01; // Korean (Extended Wansung)
export const SUBLANG_KYRGYZ_KYRGYZSTAN = 0x01; // Kyrgyz (Kyrgyzstan) 0x0440 ky-KG
export const SUBLANG_LAO_LAO = 0x01; // Lao (Lao PDR) 0x0454 lo-LA
export const SUBLANG_LATVIAN_LATVIA = 0x01; // Latvian (Latvia) 0x0426 lv-LV
export const SUBLANG_LITHUANIAN = 0x01; // Lithuanian
export const SUBLANG_LOWER_SORBIAN_GERMANY = 0x02; // Lower Sorbian (Germany) 0x082e wee-DE
export const SUBLANG_LUXEMBOURGISH_LUXEMBOURG = 0x01; // Luxembourgish (Luxembourg) 0x046e lb-LU
export const SUBLANG_MACEDONIAN_MACEDONIA = 0x01; // Macedonian (Macedonia (FYROM)) 0x042f mk-MK
export const SUBLANG_MALAY_MALAYSIA = 0x01; // Malay (Malaysia)
export const SUBLANG_MALAY_BRUNEI_DARUSSALAM = 0x02; // Malay (Brunei Darussalam)
export const SUBLANG_MALAYALAM_INDIA = 0x01; // Malayalam (India (Malayalam Script) ) 0x044c ml-IN
export const SUBLANG_MALTESE_MALTA = 0x01; // Maltese (Malta) 0x043a mt-MT
export const SUBLANG_MAORI_NEW_ZEALAND = 0x01; // Maori (New Zealand) 0x0481 mi-NZ
export const SUBLANG_MAPUDUNGUN_CHILE = 0x01; // Mapudungun (Chile) 0x047a arn-CL
export const SUBLANG_MARATHI_INDIA = 0x01; // Marathi (India) 0x044e mr-IN
export const SUBLANG_MOHAWK_MOHAWK = 0x01; // Mohawk (Mohawk) 0x047c moh-CA
export const SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA = 0x01; // Mongolian (Cyrillic, Mongolia)
export const SUBLANG_MONGOLIAN_PRC = 0x02; // Mongolian (PRC)
export const SUBLANG_NEPALI_INDIA = 0x02; // Nepali (India)
export const SUBLANG_NEPALI_NEPAL = 0x01; // Nepali (Nepal) 0x0461 ne-NP
export const SUBLANG_NORWEGIAN_BOKMAL = 0x01; // Norwegian (Bokmal)
export const SUBLANG_NORWEGIAN_NYNORSK = 0x02; // Norwegian (Nynorsk)
export const SUBLANG_OCCITAN_FRANCE = 0x01; // Occitan (France) 0x0482 oc-FR
export const SUBLANG_ODIA_INDIA = 0x01; // Odia (India (Odia Script)) 0x0448 or-IN
export const SUBLANG_ORIYA_INDIA = 0x01; // Deprecated: use SUBLANG_ODIA_INDIA instead
export const SUBLANG_PASHTO_AFGHANISTAN = 0x01; // Pashto (Afghanistan)
export const SUBLANG_PERSIAN_IRAN = 0x01; // Persian (Iran) 0x0429 fa-IR
export const SUBLANG_POLISH_POLAND = 0x01; // Polish (Poland) 0x0415
export const SUBLANG_PORTUGUESE = 0x02; // Portuguese
export const SUBLANG_PORTUGUESE_BRAZILIAN = 0x01; // Portuguese (Brazil)
export const SUBLANG_PULAR_SENEGAL = 0x02; // Deprecated: Use SUBLANG_FULAH_SENEGAL instead
export const SUBLANG_PUNJABI_INDIA = 0x01; // Punjabi (India (Gurmukhi Script)) 0x0446 pa-IN
export const SUBLANG_PUNJABI_PAKISTAN = 0x02; // Punjabi (Pakistan (Arabic Script)) 0x0846 pa-Arab-PK
export const SUBLANG_QUECHUA_BOLIVIA = 0x01; // Quechua (Bolivia)
export const SUBLANG_QUECHUA_ECUADOR = 0x02; // Quechua (Ecuador)
export const SUBLANG_QUECHUA_PERU = 0x03; // Quechua (Peru)
export const SUBLANG_ROMANIAN_ROMANIA = 0x01; // Romanian (Romania) 0x0418
export const SUBLANG_ROMANSH_SWITZERLAND = 0x01; // Romansh (Switzerland) 0x0417 rm-CH
export const SUBLANG_RUSSIAN_RUSSIA = 0x01; // Russian (Russia) 0x0419
export const SUBLANG_SAKHA_RUSSIA = 0x01; // Sakha (Russia) 0x0485 sah-RU
export const SUBLANG_SAMI_NORTHERN_NORWAY = 0x01; // Northern Sami (Norway)
export const SUBLANG_SAMI_NORTHERN_SWEDEN = 0x02; // Northern Sami (Sweden)
export const SUBLANG_SAMI_NORTHERN_FINLAND = 0x03; // Northern Sami (Finland)
export const SUBLANG_SAMI_LULE_NORWAY = 0x04; // Lule Sami (Norway)
export const SUBLANG_SAMI_LULE_SWEDEN = 0x05; // Lule Sami (Sweden)
export const SUBLANG_SAMI_SOUTHERN_NORWAY = 0x06; // Southern Sami (Norway)
export const SUBLANG_SAMI_SOUTHERN_SWEDEN = 0x07; // Southern Sami (Sweden)
export const SUBLANG_SAMI_SKOLT_FINLAND = 0x08; // Skolt Sami (Finland)
export const SUBLANG_SAMI_INARI_FINLAND = 0x09; // Inari Sami (Finland)
export const SUBLANG_SANSKRIT_INDIA = 0x01; // Sanskrit (India) 0x044f sa-IN
export const SUBLANG_SCOTTISH_GAELIC = 0x01; // Scottish Gaelic (United Kingdom) 0x0491 gd-GB
export const SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN = 0x06; // Serbian (Bosnia and Herzegovina - Latin)
export const SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC = 0x07; // Serbian (Bosnia and Herzegovina - Cyrillic)
export const SUBLANG_SERBIAN_MONTENEGRO_LATIN = 0x0b; // Serbian (Montenegro - Latn)
export const SUBLANG_SERBIAN_MONTENEGRO_CYRILLIC = 0x0c; // Serbian (Montenegro - Cyrillic)
export const SUBLANG_SERBIAN_SERBIA_LATIN = 0x09; // Serbian (Serbia - Latin)
export const SUBLANG_SERBIAN_SERBIA_CYRILLIC = 0x0a; // Serbian (Serbia - Cyrillic)
export const SUBLANG_SERBIAN_CROATIA = 0x01; // Croatian (Croatia) 0x041a hr-HR
export const SUBLANG_SERBIAN_LATIN = 0x02; // Serbian (Latin)
export const SUBLANG_SERBIAN_CYRILLIC = 0x03; // Serbian (Cyrillic)
export const SUBLANG_SINDHI_INDIA = 0x01; // Sindhi (India) reserved 0x0459
export const SUBLANG_SINDHI_PAKISTAN = 0x02; // Sindhi (Pakistan) 0x0859 sd-Arab-PK
export const SUBLANG_SINDHI_AFGHANISTAN = 0x02; // For app compatibility only
export const SUBLANG_SINHALESE_SRI_LANKA = 0x01; // Sinhalese (Sri Lanka)
export const SUBLANG_SOTHO_NORTHERN_SOUTH_AFRICA = 0x01; // Northern Sotho (South Africa)
export const SUBLANG_SLOVAK_SLOVAKIA = 0x01; // Slovak (Slovakia) 0x041b sk-SK
export const SUBLANG_SLOVENIAN_SLOVENIA = 0x01; // Slovenian (Slovenia) 0x0424 sl-SI
export const SUBLANG_SPANISH = 0x01; // Spanish (Castilian)
export const SUBLANG_SPANISH_MEXICAN = 0x02; // Spanish (Mexico)
export const SUBLANG_SPANISH_MODERN = 0x03; // Spanish (Modern)
export const SUBLANG_SPANISH_GUATEMALA = 0x04; // Spanish (Guatemala)
export const SUBLANG_SPANISH_COSTA_RICA = 0x05; // Spanish (Costa Rica)
export const SUBLANG_SPANISH_PANAMA = 0x06; // Spanish (Panama)
export const SUBLANG_SPANISH_DOMINICAN_REPUBLIC = 0x07; // Spanish (Dominican Republic)
export const SUBLANG_SPANISH_VENEZUELA = 0x08; // Spanish (Venezuela)
export const SUBLANG_SPANISH_COLOMBIA = 0x09; // Spanish (Colombia)
export const SUBLANG_SPANISH_PERU = 0x0a; // Spanish (Peru)
export const SUBLANG_SPANISH_ARGENTINA = 0x0b; // Spanish (Argentina)
export const SUBLANG_SPANISH_ECUADOR = 0x0c; // Spanish (Ecuador)
export const SUBLANG_SPANISH_CHILE = 0x0d; // Spanish (Chile)
export const SUBLANG_SPANISH_URUGUAY = 0x0e; // Spanish (Uruguay)
export const SUBLANG_SPANISH_PARAGUAY = 0x0f; // Spanish (Paraguay)
export const SUBLANG_SPANISH_BOLIVIA = 0x10; // Spanish (Bolivia)
export const SUBLANG_SPANISH_EL_SALVADOR = 0x11; // Spanish (El Salvador)
export const SUBLANG_SPANISH_HONDURAS = 0x12; // Spanish (Honduras)
export const SUBLANG_SPANISH_NICARAGUA = 0x13; // Spanish (Nicaragua)
export const SUBLANG_SPANISH_PUERTO_RICO = 0x14; // Spanish (Puerto Rico)
export const SUBLANG_SPANISH_US = 0x15; // Spanish (United States)
export const SUBLANG_SWAHILI_KENYA = 0x01; // Swahili (Kenya) 0x0441 sw-KE
export const SUBLANG_SWEDISH = 0x01; // Swedish
export const SUBLANG_SWEDISH_FINLAND = 0x02; // Swedish (Finland)
export const SUBLANG_SYRIAC_SYRIA = 0x01; // Syriac (Syria) 0x045a syr-SY
export const SUBLANG_TAJIK_TAJIKISTAN = 0x01; // Tajik (Tajikistan) 0x0428 tg-TJ-Cyrl
export const SUBLANG_TAMAZIGHT_ALGERIA_LATIN = 0x02; // Tamazight (Latin, Algeria) 0x085f tzm-Latn-DZ
export const SUBLANG_TAMAZIGHT_MOROCCO_TIFINAGH = 0x04; // Tamazight (Tifinagh) 0x105f tzm-Tfng-MA
export const SUBLANG_TAMIL_INDIA = 0x01; // Tamil (India)
export const SUBLANG_TAMIL_SRI_LANKA = 0x02; // Tamil (Sri Lanka) 0x0849 ta-LK
export const SUBLANG_TATAR_RUSSIA = 0x01; // Tatar (Russia) 0x0444 tt-RU
export const SUBLANG_TELUGU_INDIA = 0x01; // Telugu (India (Telugu Script)) 0x044a te-IN
export const SUBLANG_THAI_THAILAND = 0x01; // Thai (Thailand) 0x041e th-TH
export const SUBLANG_TIBETAN_PRC = 0x01; // Tibetan (PRC)
export const SUBLANG_TIGRIGNA_ERITREA = 0x02; // Tigrigna (Eritrea)
export const SUBLANG_TIGRINYA_ERITREA = 0x02; // Tigrinya (Eritrea) 0x0873 ti-ER (preferred spelling)
export const SUBLANG_TIGRINYA_ETHIOPIA = 0x01; // Tigrinya (Ethiopia) 0x0473 ti-ET
export const SUBLANG_TSWANA_BOTSWANA = 0x02; // Setswana / Tswana (Botswana) 0x0832 tn-BW
export const SUBLANG_TSWANA_SOUTH_AFRICA = 0x01; // Setswana / Tswana (South Africa) 0x0432 tn-ZA
export const SUBLANG_TURKISH_TURKEY = 0x01; // Turkish (Turkey) 0x041f tr-TR
export const SUBLANG_TURKMEN_TURKMENISTAN = 0x01; // Turkmen (Turkmenistan) 0x0442 tk-TM
export const SUBLANG_UIGHUR_PRC = 0x01; // Uighur (PRC) 0x0480 ug-CN
export const SUBLANG_UKRAINIAN_UKRAINE = 0x01; // Ukrainian (Ukraine) 0x0422 uk-UA
export const SUBLANG_UPPER_SORBIAN_GERMANY = 0x01; // Upper Sorbian (Germany) 0x042e wen-DE
export const SUBLANG_URDU_PAKISTAN = 0x01; // Urdu (Pakistan)
export const SUBLANG_URDU_INDIA = 0x02; // Urdu (India)
export const SUBLANG_UZBEK_LATIN = 0x01; // Uzbek (Latin)
export const SUBLANG_UZBEK_CYRILLIC = 0x02; // Uzbek (Cyrillic)
export const SUBLANG_VALENCIAN_VALENCIA = 0x02; // Valencian (Valencia) 0x0803 ca-ES-Valencia
export const SUBLANG_VIETNAMESE_VIETNAM = 0x01; // Vietnamese (Vietnam) 0x042a vi-VN
export const SUBLANG_WELSH_UNITED_KINGDOM = 0x01; // Welsh (United Kingdom) 0x0452 cy-GB
export const SUBLANG_WOLOF_SENEGAL = 0x01; // Wolof (Senegal)
export const SUBLANG_XHOSA_SOUTH_AFRICA = 0x01; // isiXhosa / Xhosa (South Africa) 0x0434 xh-ZA
export const SUBLANG_YAKUT_RUSSIA = 0x01; // Deprecated: use SUBLANG_SAKHA_RUSSIA instead
export const SUBLANG_YI_PRC = 0x01; // Yi (PRC)) 0x0478
export const SUBLANG_YORUBA_NIGERIA = 0x01; // Yoruba (Nigeria) 046a yo-NG
export const SUBLANG_ZULU_SOUTH_AFRICA = 0x01; // isiZulu / Zulu (South Africa) 0x0435 zu-ZA
export const ERROR_MOD_NOT_FOUND = 126; | the_stack |
'use strict';
import { expect } from 'chai';
import * as sinon from 'sinon';
import { instance, mock, when } from 'ts-mockito';
import { Terminal } from 'vscode';
import { ApplicationEnvironment } from '../../../../client/common/application/applicationEnvironment';
import { WorkspaceService } from '../../../../client/common/application/workspace';
import { PlatformService } from '../../../../client/common/platform/platformService';
import { IPlatformService } from '../../../../client/common/platform/types';
import { CurrentProcess } from '../../../../client/common/process/currentProcess';
import { SettingsShellDetector } from '../../../../client/common/terminal/shellDetectors/settingsShellDetector';
import { TerminalNameShellDetector } from '../../../../client/common/terminal/shellDetectors/terminalNameShellDetector';
import { UserEnvironmentShellDetector } from '../../../../client/common/terminal/shellDetectors/userEnvironmentShellDetector';
import { VSCEnvironmentShellDetector } from '../../../../client/common/terminal/shellDetectors/vscEnvironmentShellDetector';
import { ShellIdentificationTelemetry, TerminalShellType } from '../../../../client/common/terminal/types';
import { getNamesAndValues } from '../../../../client/common/utils/enum';
import { OSType } from '../../../../client/common/utils/platform';
suite('Shell Detectors', () => {
let platformService: IPlatformService;
let currentProcess: CurrentProcess;
let workspaceService: WorkspaceService;
let appEnv: ApplicationEnvironment;
// Dummy data for testing.
const shellPathsAndIdentification = new Map<string, TerminalShellType>();
shellPathsAndIdentification.set('c:\\windows\\system32\\cmd.exe', TerminalShellType.commandPrompt);
shellPathsAndIdentification.set('c:\\windows\\system32\\bash.exe', TerminalShellType.bash);
shellPathsAndIdentification.set('c:\\windows\\system32\\wsl.exe', TerminalShellType.wsl);
shellPathsAndIdentification.set('c:\\windows\\system32\\gitbash.exe', TerminalShellType.gitbash);
shellPathsAndIdentification.set('/usr/bin/bash', TerminalShellType.bash);
shellPathsAndIdentification.set('/usr/bin/zsh', TerminalShellType.zsh);
shellPathsAndIdentification.set('/usr/bin/ksh', TerminalShellType.ksh);
shellPathsAndIdentification.set('c:\\windows\\system32\\powershell.exe', TerminalShellType.powershell);
shellPathsAndIdentification.set('c:\\windows\\system32\\pwsh.exe', TerminalShellType.powershellCore);
shellPathsAndIdentification.set('/usr/microsoft/xxx/powershell/powershell', TerminalShellType.powershell);
shellPathsAndIdentification.set('/usr/microsoft/xxx/powershell/pwsh', TerminalShellType.powershellCore);
shellPathsAndIdentification.set('/usr/bin/fish', TerminalShellType.fish);
shellPathsAndIdentification.set('c:\\windows\\system32\\shell.exe', TerminalShellType.other);
shellPathsAndIdentification.set('/usr/bin/shell', TerminalShellType.other);
shellPathsAndIdentification.set('/usr/bin/csh', TerminalShellType.cshell);
shellPathsAndIdentification.set('/usr/bin/tcsh', TerminalShellType.tcshell);
shellPathsAndIdentification.set('/usr/bin/xonsh', TerminalShellType.xonsh);
shellPathsAndIdentification.set('/usr/bin/xonshx', TerminalShellType.other);
const telemetryProperties: ShellIdentificationTelemetry = {
failed: true,
shellIdentificationSource: 'default',
terminalProvided: false,
hasCustomShell: undefined,
hasShellInEnv: undefined,
};
setup(() => {
platformService = mock(PlatformService);
workspaceService = mock(WorkspaceService);
currentProcess = mock(CurrentProcess);
appEnv = mock(ApplicationEnvironment);
});
test('Test Priority of detectors', async () => {
expect(new TerminalNameShellDetector().priority).to.equal(4);
expect(new VSCEnvironmentShellDetector(instance(appEnv)).priority).to.equal(3);
expect(new SettingsShellDetector(instance(workspaceService), instance(platformService)).priority).to.equal(2);
expect(new UserEnvironmentShellDetector(instance(currentProcess), instance(platformService)).priority).to.equal(
1,
);
});
test('Test identification of Terminal Shells (base class method)', async () => {
const shellDetector = new TerminalNameShellDetector();
shellPathsAndIdentification.forEach((shellType, shellPath) => {
expect(shellDetector.identifyShellFromShellPath(shellPath)).to.equal(
shellType,
`Incorrect Shell Type for path '${shellPath}'`,
);
});
});
test('Identify shell based on name of terminal', async () => {
const shellDetector = new TerminalNameShellDetector();
shellPathsAndIdentification.forEach((shellType, shellPath) => {
expect(shellDetector.identify(telemetryProperties, { name: shellPath } as any)).to.equal(
shellType,
`Incorrect Shell Type for name '${shellPath}'`,
);
});
expect(shellDetector.identify(telemetryProperties, undefined)).to.equal(
undefined,
'Should be undefined when there is no temrinal',
);
});
test('Identify shell based on custom VSC shell path', async () => {
const shellDetector = new VSCEnvironmentShellDetector(instance(appEnv));
shellPathsAndIdentification.forEach((shellType, shellPath) => {
when(appEnv.shell).thenReturn('defaultshellPath');
expect(
shellDetector.identify(telemetryProperties, ({
creationOptions: { shellPath },
} as unknown) as Terminal),
).to.equal(shellType, `Incorrect Shell Type from identifyShellByTerminalName, for path '${shellPath}'`);
});
});
test('Identify shell based on VSC API', async () => {
const shellDetector = new VSCEnvironmentShellDetector(instance(appEnv));
shellPathsAndIdentification.forEach((shellType, shellPath) => {
when(appEnv.shell).thenReturn(shellPath);
expect(shellDetector.identify(telemetryProperties, { name: shellPath } as any)).to.equal(
shellType,
`Incorrect Shell Type from identifyShellByTerminalName, for path '${shellPath}'`,
);
});
when(appEnv.shell).thenReturn(undefined as any);
expect(shellDetector.identify(telemetryProperties, undefined)).to.equal(
undefined,
'Should be undefined when vscode.env.shell is undefined',
);
});
test('Identify shell based on VSC Settings', async () => {
const shellDetector = new SettingsShellDetector(instance(workspaceService), instance(platformService));
shellPathsAndIdentification.forEach((shellType, shellPath) => {
// Assume the same paths are stored in user settings, we should still be able to identify the shell.
shellDetector.getTerminalShellPath = () => shellPath;
expect(shellDetector.identify(telemetryProperties, {} as any)).to.equal(
shellType,
`Incorrect Shell Type for path '${shellPath}'`,
);
});
});
getNamesAndValues<OSType>(OSType).forEach((os) => {
test(`Get shell path from settings (OS ${os.name})`, async () => {
const shellPathInSettings = 'some value';
const shellDetector = new SettingsShellDetector(instance(workspaceService), instance(platformService));
const getStub = sinon.stub();
const config = { get: getStub } as any;
getStub.returns(shellPathInSettings);
when(workspaceService.getConfiguration('terminal.integrated.shell')).thenReturn(config);
when(platformService.osType).thenReturn(os.value);
const shellPath = shellDetector.getTerminalShellPath();
expect(shellPath).to.equal(os.value === OSType.Unknown ? '' : shellPathInSettings);
expect(getStub.callCount).to.equal(os.value === OSType.Unknown ? 0 : 1);
if (os.value !== OSType.Unknown) {
expect(getStub.args[0][0]).to.equal(os.name.toLowerCase());
}
});
});
test('Identify shell based on user environment variables', async () => {
const shellDetector = new UserEnvironmentShellDetector(instance(currentProcess), instance(platformService));
shellPathsAndIdentification.forEach((shellType, shellPath) => {
// Assume the same paths are defined in user environment variables, we should still be able to identify the shell.
shellDetector.getDefaultPlatformShell = () => shellPath;
expect(shellDetector.identify(telemetryProperties, {} as any)).to.equal(
shellType,
`Incorrect Shell Type for path '${shellPath}'`,
);
});
});
test('Default shell on Windows < 10 is cmd.exe', () => {
const shellDetector = new UserEnvironmentShellDetector(instance(currentProcess), instance(platformService));
when(platformService.osType).thenReturn(OSType.Windows);
when(platformService.osRelease).thenReturn('7');
when(currentProcess.env).thenReturn({});
const shellPath = shellDetector.getDefaultPlatformShell();
expect(shellPath).to.equal('cmd.exe');
});
test('Default shell on Windows >= 10 32bit is powershell.exe', () => {
const shellDetector = new UserEnvironmentShellDetector(instance(currentProcess), instance(platformService));
when(platformService.osType).thenReturn(OSType.Windows);
when(platformService.osRelease).thenReturn('10');
when(currentProcess.env).thenReturn({ windir: 'WindowsDir', PROCESSOR_ARCHITEW6432: '', comspec: 'hello.exe' });
const shellPath = shellDetector.getDefaultPlatformShell();
expect(shellPath).to.equal('WindowsDir\\Sysnative\\WindowsPowerShell\\v1.0\\powershell.exe');
});
test('Default shell on Windows >= 10 64bit is powershell.exe', () => {
const shellDetector = new UserEnvironmentShellDetector(instance(currentProcess), instance(platformService));
when(platformService.osType).thenReturn(OSType.Windows);
when(platformService.osRelease).thenReturn('10');
when(currentProcess.env).thenReturn({ windir: 'WindowsDir', comspec: 'hello.exe' });
const shellPath = shellDetector.getDefaultPlatformShell();
expect(shellPath).to.equal('WindowsDir\\System32\\WindowsPowerShell\\v1.0\\powershell.exe');
});
test('Default shell on Windows < 10 is what ever is defined in env.comspec', () => {
const shellDetector = new UserEnvironmentShellDetector(instance(currentProcess), instance(platformService));
when(platformService.osType).thenReturn(OSType.Windows);
when(platformService.osRelease).thenReturn('7');
when(currentProcess.env).thenReturn({ comspec: 'hello.exe' });
const shellPath = shellDetector.getDefaultPlatformShell();
expect(shellPath).to.equal('hello.exe');
});
[OSType.OSX, OSType.Linux].forEach((osType) => {
test(`Default shell on ${osType} is /bin/bash`, () => {
const shellDetector = new UserEnvironmentShellDetector(instance(currentProcess), instance(platformService));
when(platformService.osType).thenReturn(OSType.OSX);
when(currentProcess.env).thenReturn({});
const shellPath = shellDetector.getDefaultPlatformShell();
expect(shellPath).to.equal('/bin/bash');
});
test(`Default shell on ${osType} is what ever is in env.SHELL`, () => {
const shellDetector = new UserEnvironmentShellDetector(instance(currentProcess), instance(platformService));
when(platformService.osType).thenReturn(OSType.OSX);
when(currentProcess.env).thenReturn({ SHELL: 'hello terminal.app' });
const shellPath = shellDetector.getDefaultPlatformShell();
expect(shellPath).to.equal('hello terminal.app');
});
test(`Default shell on ${osType} is what ever is /bin/bash if env.SHELL == /bin/false`, () => {
const shellDetector = new UserEnvironmentShellDetector(instance(currentProcess), instance(platformService));
when(platformService.osType).thenReturn(OSType.OSX);
when(currentProcess.env).thenReturn({ SHELL: '/bin/false' });
const shellPath = shellDetector.getDefaultPlatformShell();
expect(shellPath).to.equal('/bin/bash');
});
});
}); | the_stack |
import { browser } from "webextension-polyfill-ts";
import { MediaElement } from '../../shared/types';
import debug from '../../shared/debug';
import ConfigProvider from '../../shared/configProvider';
import DynamicThresholdCalculator from "./DynamicThresholdCalculator";
import AudioSync from "./AudioSync";
import Statistics from "./Statistics";
/**
* Silence Skipper: This class is doing the job of actually inspecting media elements and
* slowing them up or down
*/
export default class SilenceSkipper {
// Constructor variables
element : MediaElement;
config : ConfigProvider;
// State variables
isAttached = false;
isSpedUp = false;
samplesUnderThreshold = 0;
isInspectionRunning = false;
samplesSinceLastVolumeMessage = 0;
_targetPlaybackRate = 0;
_rateChangeListenerAdded = false;
_blockRateChangeEvents = false;
_handlingRateChangeError = false;
_samplePosition = 0; // This will count up to 50, then and reset to 0
// Audio variables
audioContext : AudioContext | undefined;
analyser : AnalyserNode | undefined;
gain : GainNode | undefined;
source: MediaElementAudioSourceNode | undefined;
audioFrequencies : Float32Array | undefined;
// Dependencies
dynamicThresholdCalculator : DynamicThresholdCalculator;
audioSync : AudioSync;
statistics : Statistics;
/**
* Add silence skipper to element
*
* @param mediaElement Element to attach to
* @param config Config Provider to use
*/
constructor(mediaElement : MediaElement, config : ConfigProvider) {
this.element = mediaElement;
this.config = config;
// Enable Skip Silence if we should
const isEnabled = this.config.get('enabled');
if (isEnabled) {
if (!this.isInspectionRunning) {
// Start running the inspection
this._inspectSample();
}
}
this.dynamicThresholdCalculator = new DynamicThresholdCalculator(config);
this.audioSync = new AudioSync(this);
this.statistics = new Statistics(this);
// Attach our config listener
this.config.onUpdate(() => this._onConfigUpdate());
}
/**
* Attach the element to the current class.
* This is only needed when we are actually skipping silent parts as we are using excess resources
* otherwise - this is why this step is not done in the constructor
*/
_attachToElement() {
// We don't need to attach multiple times
if (this.isAttached) return false;
this.audioContext = new AudioContext();
// Create our audio components
this.analyser = this.audioContext.createAnalyser();
this.source = this.audioContext.createMediaElementSource(this.element);
this.gain = this.audioContext.createGain();
// Connect our components
// Source -> Analyser -> Gain -> Destination
this.source
.connect(this.analyser)
.connect(this.gain)
.connect(this.audioContext.destination);
this.audioFrequencies = new Float32Array(this.analyser.fftSize);
this.isAttached = true;
}
/**
* Fixes issues changing the playback rate by temporarily blocking `ratechange` event listeners.
*/
_handlePlaybackRateChangeError() {
this._handlingRateChangeError = true;
// If the playback rate was set to zero by the website, it's probably because the video is not
// loaded and can no longer be played, and so shouldn't be tampered with.
if (this.element.playbackRate !== 0) {
// Prevent ratechange event listeners from running while we forcibly change playback rate
this._blockRateChangeEvents = true;
if (!this._rateChangeListenerAdded) {
// Passing in `true` for the third parameter causes the event to be captured on the way down.
this.element.addEventListener('ratechange', (event: Event) => {
if (this._blockRateChangeEvents) {
// Ensure the event never reaches its listeners
event.stopImmediatePropagation();
} else {
// If the playback rate changes from 0 back to the default rate (usually 1) and that's
// not what we want it to be, update it.
if (
this.element.playbackRate !== 0
&& this.element.playbackRate === this.element.defaultPlaybackRate
&& this.element.playbackRate !== this._targetPlaybackRate
) {
this._setPlaybackRate(this._targetPlaybackRate);
}
}
}, true);
this._rateChangeListenerAdded = true;
}
setTimeout(() => {
// Now try setting the rate again
this.element.playbackRate = this._targetPlaybackRate;
// Wait for any ratechange events to fire and get blocked
setTimeout(() => {
// Once we have successfully changed the playback rate, allow rate change events again.
// We don't just remove the event entirely as we might only want to override the event
// some of the time.
this._blockRateChangeEvents = false;
this._handlingRateChangeError = false;
}, 1);
}, 1);
} else {
this._handlingRateChangeError = false;
}
}
/**
* Attempts to change the video playback rate
*/
_setPlaybackRate(rate: number) {
this._targetPlaybackRate = rate;
if (rate === 1) {
// Setting the speed to exactly 1 will cause audio clicking
// Setting the speed to slightly greater than 1 will prevent this from happening
// Related: https://github.com/vantezzen/skip-silence/issues/52
this._targetPlaybackRate = 1.01;
}
this.element.playbackRate = this._targetPlaybackRate;
if (!this._handlingRateChangeError) {
// Make sure that the playback rate actually changed
setTimeout(() => {
const failedToChangeRate = this.element.playbackRate !== this._targetPlaybackRate;
if (failedToChangeRate) {
// If it didn't, try to forcibly change it
this._handlePlaybackRateChangeError();
}
}, 1);
}
}
/**
* Listener for config changes to update the settings
*/
_onConfigUpdate() {
const isEnabled = this.config.get('enabled');
if (isEnabled) {
if (!this.isInspectionRunning) {
// Start running the inspection
this._inspectSample();
}
// Update our speed to the new config speed
const playbackSpeed = this.config.get('playback_speed');
const silenceSpeed = this.config.get('silence_speed');
if (this.isSpedUp) {
this._setPlaybackRate(silenceSpeed);
} else {
this._setPlaybackRate(playbackSpeed);
}
// Update gain level
const muteSilence = this.config.get("mute_silence");
if(muteSilence && this.isSpedUp) {
if (this.gain) {
// Make sure our silence is muted
this.gain.gain.value = 0;
}
} else if (this.gain) {
// Make sure we are not muted
this.gain.gain.value = 1;
}
}
}
/**
* Calculate the current volume of the media
*/
_calculateVolume() {
if (!this.analyser || !this.audioFrequencies) {
debug("SilenceSkipper: Can't calculate volume as we are not attached");
return 100;
}
this.analyser.getFloatTimeDomainData(this.audioFrequencies);
// Compute volume via peak instantaneous power over the interval
let peakInstantaneousPower = 0;
for (let i = 0; i < this.audioFrequencies.length; i++) {
const power = this.audioFrequencies[i];
peakInstantaneousPower = Math.max(power, peakInstantaneousPower);
}
const volume = (500 * peakInstantaneousPower);
return volume;
}
/**
* Send a command to the popup
*
* @param command Command to send
* @param data Additional data to send (optional)
*/
_sendCommand(command : String, data : Object = {}) {
browser.runtime.sendMessage({ command, ...data });
}
/**
* Slow the video down to playback speed
*/
_slowDown() {
const playbackSpeed = this.config.get('playback_speed');
this.isSpedUp = false;
this.samplesUnderThreshold = 0;
this._sendCommand('slowDown');
this.statistics.onSkipEnd();
this._setPlaybackRate(playbackSpeed);
if(this.config.get("mute_silence")) {
// Slowly remove our mute
// If we do this immediately, we may cause a "clicking" noise
// Source: http://alemangui.github.io/ramp-to-value
if (this.gain && this.audioContext) {
this.gain.gain.setTargetAtTime(1, this.audioContext.currentTime, 0.04);
}
}
}
/**
* Speed the video up to silence speed
*/
_speedUp() {
const silenceSpeed = this.config.get('silence_speed');
this._sendCommand('speedUp');
this.statistics.onSkipStart();
this.isSpedUp = true;
if (this.config.get("mute_silence")) {
// Get the audio muted before we speed up the video
// This will help remove the "clicking" sound when speeding up with remaining audio
if (this.gain && this.audioContext) {
this.gain.gain.setTargetAtTime(0, this.audioContext.currentTime, 0.015);
}
setTimeout(() => {
this._setPlaybackRate(silenceSpeed);
}, 20);
} else {
this._setPlaybackRate(silenceSpeed);
}
}
/**
* Inspect the current sample of the media and speed up or down accordingly
*/
_inspectSample() {
this.isInspectionRunning = true;
// Make sure we are attached
if (!this.isAttached) this._attachToElement();
this._samplePosition = (this._samplePosition + 1) % 50;
const volume = this._calculateVolume();
const useDynamicThreshold = this.config.get('dynamic_silence_threshold');
if (useDynamicThreshold && volume > 0) {
this.dynamicThresholdCalculator.previousSamples.push(volume);
if (this._samplePosition === 0) {
// Let the dynamic threshold calculator re-calculate the threshold
// This is only done every 50 samples to reduce load
this.dynamicThresholdCalculator.calculate();
}
}
const threshold = useDynamicThreshold ? this.dynamicThresholdCalculator.threshold : this.config.get('silence_threshold');
const sampleThreshold = this.config.get('samples_threshold');
if (volume < threshold && !this.element.paused && !this.isSpedUp) {
// We are below our threshold and should possibly slow down
this.samplesUnderThreshold += 1;
if (this.samplesUnderThreshold >= sampleThreshold) {
// We are over our sample threshold and should speed up!
this._speedUp();
}
} else if (volume > threshold && this.isSpedUp) {
// Slow back down as we are now in a loud part again
this._slowDown();
}
// Send our volume information to the popup
this.samplesSinceLastVolumeMessage++;
if (this.samplesSinceLastVolumeMessage >= 2) {
this._sendCommand('volume', {
data: volume
});
this.samplesSinceLastVolumeMessage = 0;
}
// Check if we should continue inspecting
if (this.config.get('enabled')) {
// Continue inspecting the next sample
setTimeout(() => this._inspectSample(), 25);
} else {
// Stop inspecting
this.isInspectionRunning = false;
// Make sure the video is back to normal speed
if (this.isSpedUp) {
this.isSpedUp = false;
this.samplesUnderThreshold = 0;
}
this._sendCommand('slowDown');
this._setPlaybackRate(1);
this._sendCommand('volume', {
data: 0
});
}
}
} | the_stack |
import { ClassType, getEnumLabels, getEnumValues, getValidEnumValue, isObject, isValidEnumValue } from '@deepkit/core';
import { arrayBufferToBase64, base64ToArrayBuffer, base64ToTypedArray, typedArrayToBase64 } from './core';
import { getClassToXFunction, getPartialClassToXFunction, getPartialXToClassFunction, getXToClassFunction, JitConverterOptions } from './jit';
import { jsonTypeGuards } from './json-typeguards';
import { ClassSchema, getClassSchema, getClassTypeFromInstance, PropertySchema } from './model';
import { Serializer } from './serializer';
import { CompilerState, getDataConverterJS } from './serializer-compiler';
import { getSortedUnionTypes } from './union';
import { ExtractClassType, JSONEntity, PlainOrFullEntityFromClassTypeOrSchema } from './utils';
import { validate, ValidationFailed } from './validation';
import { createReference, createReferenceClass, isReference, isReferenceHydrated } from './reference';
export class JSONSerializer extends Serializer {
constructor() {
super('json');
}
}
export const jsonSerializer = new JSONSerializer();
export function compilerToString(property: PropertySchema, state: CompilerState) {
state.addSetter(`typeof ${state.accessor} === 'string' ? ${state.accessor} : ''+${state.accessor};`);
}
/**
* Converts a class instance into a plain object, which can be used with JSON.stringify() to convert it into a JSON string.
*/
export function classToPlain<T extends ClassType | ClassSchema>(classTypeOrSchema: T, target: ExtractClassType<T>, options?: JitConverterOptions): JSONEntity<ExtractClassType<T>> {
return getClassToXFunction(getClassSchema(classTypeOrSchema), jsonSerializer)(target, options);
}
/**
* Take a regular object literal and returns an instance of classType.
* Missing data is either replaced by the default value of that property or undefined.
*
* This method does not validate the given data. Use either [[validatedPlainToClass]] to validate beforehand
* or use [[validate]] on your newly created instance.
*
* ```typescript
* const entity = plainToClass(MyEntity, {field1: 'value'});
* entity instanceof MyEntity; //true
* ```
*/
export function plainToClass<T extends ClassType | ClassSchema>(
classTypeOrSchema: T,
data: PlainOrFullEntityFromClassTypeOrSchema<ExtractClassType<T>>,
options?: JitConverterOptions
): ExtractClassType<T> {
return getXToClassFunction(getClassSchema(classTypeOrSchema), jsonSerializer)(data, options) as ExtractClassType<T>;
}
/**
* Same as [plainToClass] but with validation before creating the class instance.
*
* ```typescript
* try {
* const entity = await validatedPlainToClass(MyEntity, {field1: 'value'});
* entity instanceof MyEntity; //true
* } catch (error) {
* if (error instanceof ValidationFailed) {
* //handle that case.
* }
* }
* ```
*/
export function validatedPlainToClass<T extends ClassType | ClassSchema>(
classType: T,
data: PlainOrFullEntityFromClassTypeOrSchema<ExtractClassType<T>>,
options?: JitConverterOptions
): ExtractClassType<T> {
const item = plainToClass(classType, data, options);
const errors = validate(classType, item);
if (errors.length) {
throw new ValidationFailed(errors);
}
return item;
}
export function isBinaryJSON(v: any): boolean {
return v && v['$type'] === 'binary' && typeof v.data === 'string';
}
export function isBigIntJSON(v: any): boolean {
return v && v['$type'] === 'bigint' && typeof v.data === 'string';
}
/**
* Clones a class instance deeply.
*/
export function cloneClass<T>(target: T, options?: JitConverterOptions): T {
const s = jsonSerializer.for(getClassTypeFromInstance(target));
return s.deserialize(s.serialize(target, options), options, options?.parents);
}
jsonSerializer.toClass.register('string', compilerToString);
jsonSerializer.fromClass.register('string', compilerToString);
export function compilerToNumber(property: PropertySchema, state: CompilerState) {
state.addSetter(`typeof ${state.accessor} === 'number' ? ${state.accessor} : +${state.accessor};`);
}
jsonSerializer.toClass.register('number', compilerToNumber);
jsonSerializer.fromClass.register('number', compilerToNumber);
jsonSerializer.toClass.register('literal', (property: PropertySchema, state: CompilerState) => {
const literalValue = state.setVariable('_literal_value_' + property.name, property.literalValue);
state.addSetter(literalValue);
});
jsonSerializer.toClass.register('uuid', (property: PropertySchema, state: CompilerState) => {
state.addCodeForSetter(`if ('string' === typeof ${state.accessor}) ${state.setter} = ${state.accessor};`);
});
jsonSerializer.fromClass.register('uuid', (property: PropertySchema, state: CompilerState) => {
state.addCodeForSetter(`if ('string' === typeof ${state.accessor}) ${state.setter} = ${state.accessor};`);
});
jsonSerializer.toClass.prepend('undefined', (property, state: CompilerState) => {
if (property.type === 'literal' && !property.isOptional) {
const literalValue = state.setVariable('_literal_value_' + property.name, property.literalValue);
state.addSetter(literalValue);
}
return;
});
jsonSerializer.fromClass.prepend('undefined', (property, state: CompilerState) => {
if (property.type === 'literal' && !property.isOptional) {
const literalValue = state.setVariable('_literal_value_' + property.name, property.literalValue);
state.addSetter(literalValue);
}
return;
});
jsonSerializer.toClass.prepend('null', (property: PropertySchema, state: CompilerState) => {
if (property.type === 'literal' && !property.isNullable) {
const literalValue = state.setVariable('_literal_value_' + property.name, property.literalValue);
state.addSetter(literalValue);
}
});
jsonSerializer.fromClass.prepend('null', (property: PropertySchema, state: CompilerState) => {
if (property.type === 'literal' && !property.isNullable) {
const literalValue = state.setVariable('_literal_value_' + property.name, property.literalValue);
state.addSetter(literalValue);
}
});
jsonSerializer.toClass.register('date', (property: PropertySchema, state: CompilerState) => {
state.addSetter(`new Date(${state.accessor});`);
});
jsonSerializer.toClass.register('boolean', (property: PropertySchema, state: CompilerState) => {
state.addCodeForSetter(`
if ('boolean' === typeof ${state.accessor}) {
${state.setter} = ${state.accessor};
} else {
if ('true' === ${state.accessor} || '1' === ${state.accessor} || 1 === ${state.accessor}) ${state.setter} = true;
if ('false' === ${state.accessor} || '0' === ${state.accessor} || 0 === ${state.accessor}) ${state.setter} = false;
}
`);
});
jsonSerializer.toClass.register('enum', (property: PropertySchema, state: CompilerState) => {
//this a candidate where we can extract ENUM information during build time and check very fast during
//runtime, so we don't need a call to getResolvedClassTypeForValidType(), isValidEnumValue(), etc in runtime anymore.
const allowLabelsAsValue = property.allowLabelsAsValue;
const typeValue = state.setVariable('typeValue', property.resolveClassType);
state.setContext({
isValidEnumValue,
getEnumValues,
getEnumLabels,
getValidEnumValue
});
state.addCodeForSetter(`
var typeValue = ${typeValue};
if (undefined !== ${state.accessor} && !isValidEnumValue(typeValue, ${state.accessor}, ${allowLabelsAsValue})) {
const valids = getEnumValues(typeValue);
if (${allowLabelsAsValue}) {
//IE11 compatible way
getEnumLabels(typeValue).forEach(function(label){valids.push(label);});
}
throw new Error('Invalid ENUM given in property ${property.name}: ' + ${state.accessor} + ', valid: ' + valids.join(','));
}
${state.setter} = getValidEnumValue(typeValue, ${state.accessor}, ${allowLabelsAsValue});
`);
});
jsonSerializer.toClass.registerForBinary((property: PropertySchema, state: CompilerState) => {
state.setContext({ base64ToTypedArray });
state.setContext({ isBinaryJSON });
//property.type maps to global type constructor names
state.addSetter(`${state.accessor} instanceof ${property.type} ? ${state.accessor} : (isBinaryJSON(${state.accessor}) ? base64ToTypedArray(${state.accessor}.data, ${property.type}) : new ${property.type}())`);
});
jsonSerializer.toClass.register('arrayBuffer', (property: PropertySchema, state: CompilerState) => {
state.setContext({ base64ToArrayBuffer });
state.setContext({ isBinaryJSON });
state.addSetter(`${state.accessor} instanceof ArrayBuffer ? ${state.accessor} : (isBinaryJSON(${state.accessor}) ? base64ToArrayBuffer(${state.accessor}.data): new ArrayBuffer())`);
});
//we need to add '$type' to make union with auto-detection work
jsonSerializer.fromClass.registerForBinary((property: PropertySchema, state: CompilerState) => {
state.setContext({ typedArrayToBase64 });
state.addSetter(`{'$type': 'binary', data: typedArrayToBase64(${state.accessor})}`);
});
jsonSerializer.fromClass.register('arrayBuffer', (property: PropertySchema, state: CompilerState) => {
state.setContext({ arrayBufferToBase64 });
state.addSetter(`{'$type': 'binary', data: arrayBufferToBase64(${state.accessor})}`);
});
jsonSerializer.toClass.register('bigint', (property: PropertySchema, state: CompilerState) => {
state.setContext({ isBigIntJSON });
const convert = `'string' === typeof ${state.accessor} || 'number' === typeof ${state.accessor} ? BigInt(${state.accessor}) : 0n`;
state.addSetter(`typeof ${state.accessor} === 'bigint' ? ${state.accessor} : (isBigIntJSON(${state.accessor}) ? BigInt('0x' + ${state.accessor}.data): (${convert}))`);
});
jsonSerializer.fromClass.register('bigint', (property: PropertySchema, state: CompilerState) => {
state.addSetter(`{'$type': 'bigint', data: ${state.accessor}.toString(16)}`);
});
const convertToPlainUsingToJson = (property: PropertySchema, state: CompilerState) => {
state.addSetter(`${state.accessor}.toJSON();`);
};
jsonSerializer.fromClass.register('date', convertToPlainUsingToJson);
export function convertArray(property: PropertySchema, state: CompilerState) {
const a = state.compilerContext.reserveName('a');
const l = state.compilerContext.reserveName('l');
let setDefault = property.isOptional ? '' : `${state.setter} = [];`;
//we just use `a.length` to check whether its array-like, because Array.isArray() is way too slow.
state.addCodeForSetter(`
if (${state.accessor}.length === undefined || 'string' === typeof ${state.accessor} || 'function' !== typeof ${state.accessor}.slice) {
${setDefault}
} else {
let ${l} = ${state.accessor}.length;
let ${a} = ${state.accessor}.slice();
while (${l}--) {
//make sure all elements have the correct type
if (${state.accessor}[${l}] !== undefined && ${state.accessor}[${l}] !== null) {
let itemValue;
${getDataConverterJS(`itemValue`, `${a}[${l}]`, property.getSubType(), state.serializerCompilers, state.compilerContext, state.jitStack)}
if (${!property.getSubType().isOptional} && itemValue === undefined) {
${a}.splice(${l}, 1);
} else {
${a}[${l}] = itemValue;
}
}
}
${state.setter} = ${a};
}
`);
}
jsonSerializer.fromClass.register('array', convertArray);
jsonSerializer.toClass.register('array', convertArray);
function convertMap(property: PropertySchema, state: CompilerState) {
const a = state.compilerContext.reserveName('a');
const i = state.compilerContext.reserveName('i');
let setDefault = property.isOptional ? '' : `${state.setter} = {};`;
state.addCodeForSetter(`
let ${a} = {};
//we make sure its a object and not an array
if (${state.accessor} && 'object' === typeof ${state.accessor} && 'function' !== typeof ${state.accessor}.slice) {
for (let ${i} in ${state.accessor}) {
if (!${state.accessor}.hasOwnProperty(${i})) continue;
if (${!property.getSubType().isOptional} && ${state.accessor}[${i}] === undefined) {
continue;
}
${getDataConverterJS(`${a}[${i}]`, `${state.accessor}[${i}]`, property.getSubType(), state.serializerCompilers, state.compilerContext, state.jitStack)}
}
${state.setter} = ${a};
} else {
${setDefault}
}
`);
}
jsonSerializer.fromClass.register('map', convertMap);
jsonSerializer.toClass.register('map', convertMap);
jsonSerializer.fromClass.register('promise', (property: PropertySchema, state: CompilerState) => {
state.addCodeForSetter(getDataConverterJS(state.setter, state.accessor, property.templateArgs[0] || new PropertySchema(property.name).setType('any'), state.serializerCompilers, state.compilerContext, state.jitStack));
});
jsonSerializer.toClass.register('promise', (property: PropertySchema, state: CompilerState) => {
state.addCodeForSetter(getDataConverterJS(state.setter, state.accessor, property.templateArgs[0] || new PropertySchema(property.name).setType('any'), state.serializerCompilers, state.compilerContext, state.jitStack));
});
jsonSerializer.fromClass.register('class', (property: PropertySchema, state: CompilerState) => {
const foreignClassSchema = getClassSchema(property.resolveClassType!);
const classToX = state.setVariable('classToX', state.jitStack.getOrCreate(foreignClassSchema, () => getClassToXFunction(foreignClassSchema, state.serializerCompilers.serializer, state.jitStack)));
state.setContext({ isObject, isReference, isReferenceHydrated });
let serializeObject = `
${state.setter} = ${classToX}.fn(${state.accessor}, _options, _stack, _depth);
`;
if (property.isReference && foreignClassSchema.hasPrimaryFields()) {
serializeObject = `
if (isReference(${state.accessor}) && !isReferenceHydrated(${state.accessor})) {
${getDataConverterJS(state.setter, `${state.accessor}.${foreignClassSchema.getPrimaryField().name}`, foreignClassSchema.getPrimaryField(), state.serializerCompilers, state.compilerContext, state.jitStack)}
} else {
${state.setter} = ${classToX}.fn(${state.accessor}, _options, _stack, _depth);
}
`;
}
state.addCodeForSetter(`
if (isObject(${state.accessor})) {
${serializeObject}
} else if (${property.isReference}) {
${state.setter} = ${state.accessor};
}
`);
});
jsonSerializer.toClass.register('class', (property: PropertySchema, state) => {
if (!property.resolveClassType) {
throw new Error(`Property ${property.name} has no classType defined`);
}
const foreignClassSchema = getClassSchema(property.resolveClassType);
const xToClass = state.setVariable('xToClass', state.jitStack.getOrCreate(foreignClassSchema, () => getXToClassFunction(foreignClassSchema, state.serializerCompilers.serializer, state.jitStack)));
if (foreignClassSchema.decorator) {
//the actual type checking happens within getXToClassFunction()'s constructor param
//so we dont check here for object.
state.addSetter(`${xToClass}.fn(${state.accessor}, _options, getParents(), _state)`);
return;
}
state.setContext({ isObject, isReference, createReference });
let primaryKeyHandling = '';
if (property.isReference) {
const referenceClassTypeVar = state.setVariable('referenceClassType', createReferenceClass(foreignClassSchema));
//when its a primary key only, we need to convert it to the a real object.
//if we
primaryKeyHandling = `
if (isObject(${state.accessor})) {
${getDataConverterJS(state.setter, state.accessor, property.getResolvedClassSchema().getPrimaryField(), state.serializerCompilers, state.compilerContext, state.jitStack)}
} else {
${state.setter} = createReference(${referenceClassTypeVar}, {${foreignClassSchema.getPrimaryField().name}: ${state.accessor}});
}
`;
}
state.addCodeForSetter(`
//object and not an array
if ('object' === typeof ${state.accessor} && 'function' !== typeof ${state.accessor}.slice) {
if (isReference(${state.accessor})) {
${state.setter} = ${state.accessor};
} else {
${state.setter} = ${xToClass}.fn(${state.accessor}, _options, getParents(), _state);
}
} else if (${!property.isReference} && 'string' === typeof ${state.accessor} && '{' === ${state.accessor}[0]) {
try {
${state.setter} = ${xToClass}.fn(JSON.parse(${state.accessor}), _options, getParents(), _state);
} catch (e) {}
} else if (${property.isReference}) {
${primaryKeyHandling}
}
`);
});
jsonSerializer.toClass.register('union', (property: PropertySchema, state) => {
let discriminator: string[] = [`if (false) { }`];
const discriminants: string[] = [];
for (const unionType of getSortedUnionTypes(property, jsonTypeGuards)) {
discriminants.push(unionType.property.type);
}
let elseBranch = `throw new Error('No valid discriminant was found, so could not determine class type. Guard tried: [${discriminants.join(',')}].');`;
if (property.isOptional) {
elseBranch = '';
} else if (property.isNullable) {
elseBranch = `${state.setter} = null;`;
} else if (property.hasManualDefaultValue()) {
const defaultVar = state.setVariable('default', property.defaultValue);
elseBranch = `${state.setter} = ${defaultVar}();`;
}
for (const unionType of getSortedUnionTypes(property, jsonTypeGuards)) {
const guardVar = state.setVariable('guard_' + unionType.property.type, unionType.guard);
discriminator.push(`
//guard:${unionType.property.type}
else if (${guardVar}(${state.accessor})) {
${getDataConverterJS(state.setter, state.accessor, unionType.property, state.serializerCompilers, state.compilerContext, state.jitStack)}
}
`);
}
state.addCodeForSetter(`
${discriminator.join('\n')}
else {
${elseBranch}
}
`);
});
jsonSerializer.fromClass.register('union', (property: PropertySchema, state) => {
let discriminator: string[] = [`if (false) { }`];
const discriminants: string[] = [];
for (const unionType of getSortedUnionTypes(property, jsonTypeGuards)) {
discriminants.push(unionType.property.type);
}
let elseBranch = `throw new Error('No valid discriminant was found, so could not determine class type. Guard tried: [${discriminants.join(',')}].');`;
if (property.isOptional) {
elseBranch = '';
} else if (property.isNullable) {
elseBranch = `${state.setter} = null;`;
} else if (property.hasManualDefaultValue()) {
const defaultVar = state.setVariable('default', property.defaultValue);
elseBranch = `${state.setter} = ${defaultVar}();`;
}
for (const unionType of getSortedUnionTypes(property, jsonTypeGuards)) {
const guardVar = state.setVariable('guard_' + unionType.property.type, unionType.guard);
discriminator.push(`
//guard:${unionType.property.type}
else if (${guardVar}(${state.accessor})) {
${getDataConverterJS(state.setter, state.accessor, unionType.property, state.serializerCompilers, state.compilerContext, state.jitStack)}
}
`);
}
state.addCodeForSetter(`
${discriminator.join('\n')}
else {
${elseBranch}
}
`);
});
jsonSerializer.toClass.register('partial', (property, state) => {
const classSchema = getClassSchema(property.getSubType().resolveClassType!);
const partialXToClass = state.setVariable('partialXToClass', state.jitStack.getOrCreate(classSchema, () => getPartialXToClassFunction(classSchema, state.serializerCompilers.serializer)));
state.addSetter(`${partialXToClass}.fn(${state.accessor}, _options, getParents(), _state);`);
});
jsonSerializer.fromClass.register('partial', (property, state) => {
const classSchema = getClassSchema(property.getSubType().resolveClassType!);
const partialClassToX = state.setVariable('partialClassToX', state.jitStack.getOrCreate(classSchema, () => getPartialClassToXFunction(classSchema, state.serializerCompilers.serializer)));
state.addSetter(`${partialClassToX}.fn(${state.accessor}, _options, _stack, _depth)`);
}); | the_stack |
import {AriaColorWheelProps} from '@react-types/color';
import {ColorWheelState} from '@react-stately/color';
import {focusWithoutScrolling, mergeProps, useGlobalListeners, useLabels} from '@react-aria/utils';
import React, {ChangeEvent, HTMLAttributes, InputHTMLAttributes, RefObject, useCallback, useRef} from 'react';
import {useKeyboard, useMove} from '@react-aria/interactions';
import {useLocale} from '@react-aria/i18n';
interface ColorWheelAriaProps extends AriaColorWheelProps {
/** The outer radius of the color wheel. */
outerRadius: number,
/** The inner radius of the color wheel. */
innerRadius: number
}
interface ColorWheelAria {
/** Props for the track element. */
trackProps: HTMLAttributes<HTMLElement>,
/** Props for the thumb element. */
thumbProps: HTMLAttributes<HTMLElement>,
/** Props for the visually hidden range input element. */
inputProps: InputHTMLAttributes<HTMLInputElement>
}
/**
* Provides the behavior and accessibility implementation for a color wheel component.
* Color wheels allow users to adjust the hue of an HSL or HSB color value on a circular track.
*/
export function useColorWheel(props: ColorWheelAriaProps, state: ColorWheelState, inputRef: RefObject<HTMLElement>): ColorWheelAria {
let {
isDisabled,
innerRadius,
outerRadius,
'aria-label': ariaLabel
} = props;
let {addGlobalListener, removeGlobalListener} = useGlobalListeners();
let thumbRadius = (innerRadius + outerRadius) / 2;
let focusInput = useCallback(() => {
if (inputRef.current) {
focusWithoutScrolling(inputRef.current);
}
}, [inputRef]);
let stateRef = useRef<ColorWheelState>(null);
stateRef.current = state;
let currentPosition = useRef<{x: number, y: number}>(null);
let {keyboardProps} = useKeyboard({
onKeyDown(e) {
// these are the cases that useMove doesn't handle
if (!/^(PageUp|PageDown)$/.test(e.key)) {
e.continuePropagation();
return;
}
// same handling as useMove, don't need to stop propagation, useKeyboard will do that for us
e.preventDefault();
// remember to set this and unset it so that onChangeEnd is fired
stateRef.current.setDragging(true);
switch (e.key) {
case 'PageUp':
e.preventDefault();
state.increment(stateRef.current.pageStep);
break;
case 'PageDown':
e.preventDefault();
state.decrement(stateRef.current.pageStep);
break;
}
stateRef.current.setDragging(false);
}
});
let moveHandler = {
onMoveStart() {
currentPosition.current = null;
state.setDragging(true);
},
onMove({deltaX, deltaY, pointerType, shiftKey}) {
if (currentPosition.current == null) {
currentPosition.current = stateRef.current.getThumbPosition(thumbRadius);
}
currentPosition.current.x += deltaX;
currentPosition.current.y += deltaY;
if (pointerType === 'keyboard') {
if (deltaX > 0 || deltaY < 0) {
state.increment(shiftKey ? stateRef.current.pageStep : stateRef.current.step);
} else if (deltaX < 0 || deltaY > 0) {
state.decrement(shiftKey ? stateRef.current.pageStep : stateRef.current.step);
}
} else {
stateRef.current.setHueFromPoint(currentPosition.current.x, currentPosition.current.y, thumbRadius);
}
},
onMoveEnd() {
isOnTrack.current = undefined;
state.setDragging(false);
focusInput();
}
};
let {moveProps: movePropsThumb} = useMove(moveHandler);
let currentPointer = useRef<number | null | undefined>(undefined);
let isOnTrack = useRef<boolean>(false);
let {moveProps: movePropsContainer} = useMove({
onMoveStart() {
if (isOnTrack.current) {
moveHandler.onMoveStart();
}
},
onMove(e) {
if (isOnTrack.current) {
moveHandler.onMove(e);
}
},
onMoveEnd() {
if (isOnTrack.current) {
moveHandler.onMoveEnd();
}
}
});
let onThumbDown = (id: number | null) => {
if (!state.isDragging) {
currentPointer.current = id;
focusInput();
state.setDragging(true);
if (typeof PointerEvent !== 'undefined') {
addGlobalListener(window, 'pointerup', onThumbUp, false);
} else {
addGlobalListener(window, 'mouseup', onThumbUp, false);
addGlobalListener(window, 'touchend', onThumbUp, false);
}
}
};
let onThumbUp = (e) => {
let id = e.pointerId ?? e.changedTouches?.[0].identifier;
if (id === currentPointer.current) {
focusInput();
state.setDragging(false);
currentPointer.current = undefined;
isOnTrack.current = false;
if (typeof PointerEvent !== 'undefined') {
removeGlobalListener(window, 'pointerup', onThumbUp, false);
} else {
removeGlobalListener(window, 'mouseup', onThumbUp, false);
removeGlobalListener(window, 'touchend', onThumbUp, false);
}
}
};
let onTrackDown = (track: Element, id: number | null, pageX: number, pageY: number) => {
let rect = track.getBoundingClientRect();
let x = pageX - rect.x - rect.width / 2;
let y = pageY - rect.y - rect.height / 2;
let radius = Math.sqrt(x * x + y * y);
if (innerRadius < radius && radius < outerRadius && !state.isDragging && currentPointer.current === undefined) {
isOnTrack.current = true;
currentPointer.current = id;
stateRef.current.setHueFromPoint(x, y, radius);
focusInput();
state.setDragging(true);
if (typeof PointerEvent !== 'undefined') {
addGlobalListener(window, 'pointerup', onTrackUp, false);
} else {
addGlobalListener(window, 'mouseup', onTrackUp, false);
addGlobalListener(window, 'touchend', onTrackUp, false);
}
}
};
let onTrackUp = (e) => {
let id = e.pointerId ?? e.changedTouches?.[0].identifier;
if (isOnTrack.current && id === currentPointer.current) {
isOnTrack.current = false;
currentPointer.current = undefined;
state.setDragging(false);
focusInput();
if (typeof PointerEvent !== 'undefined') {
removeGlobalListener(window, 'pointerup', onTrackUp, false);
} else {
removeGlobalListener(window, 'mouseup', onTrackUp, false);
removeGlobalListener(window, 'touchend', onTrackUp, false);
}
}
};
let trackInteractions = isDisabled ? {} : mergeProps({
...(typeof PointerEvent !== 'undefined' ? {
onPointerDown: (e: React.PointerEvent) => {
if (e.pointerType === 'mouse' && (e.button !== 0 || e.altKey || e.ctrlKey || e.metaKey)) {
return;
}
onTrackDown(e.currentTarget, e.pointerId, e.clientX, e.clientY);
}} : {
onMouseDown: (e: React.MouseEvent) => {
if (e.button !== 0 || e.altKey || e.ctrlKey || e.metaKey) {
return;
}
onTrackDown(e.currentTarget, undefined, e.clientX, e.clientY);
},
onTouchStart: (e: React.TouchEvent) => {
onTrackDown(e.currentTarget, e.changedTouches[0].identifier, e.changedTouches[0].clientX, e.changedTouches[0].clientY);
}
})
}, movePropsContainer);
let thumbInteractions = isDisabled ? {} : mergeProps({
onMouseDown: (e: React.MouseEvent) => {
if (e.button !== 0 || e.altKey || e.ctrlKey || e.metaKey) {
return;
}
onThumbDown(undefined);
},
onPointerDown: (e: React.PointerEvent) => {
if (e.pointerType === 'mouse' && (e.button !== 0 || e.altKey || e.ctrlKey || e.metaKey)) {
return;
}
onThumbDown(e.pointerId);
},
onTouchStart: (e: React.TouchEvent) => {
onThumbDown(e.changedTouches[0].identifier);
}
}, keyboardProps, movePropsThumb);
let {x, y} = state.getThumbPosition(thumbRadius);
// Provide a default aria-label if none is given
let {locale} = useLocale();
if (ariaLabel == null && props['aria-labelledby'] == null) {
ariaLabel = state.value.getChannelName('hue', locale);
}
let inputLabellingProps = useLabels({
...props,
'aria-label': ariaLabel
});
let {minValue, maxValue, step} = state.value.getChannelRange('hue');
return {
trackProps: {
...trackInteractions,
style: {
position: 'relative',
touchAction: 'none',
width: outerRadius * 2,
height: outerRadius * 2,
background: `
conic-gradient(
from 90deg,
hsl(0, 100%, 50%),
hsl(30, 100%, 50%),
hsl(60, 100%, 50%),
hsl(90, 100%, 50%),
hsl(120, 100%, 50%),
hsl(150, 100%, 50%),
hsl(180, 100%, 50%),
hsl(210, 100%, 50%),
hsl(240, 100%, 50%),
hsl(270, 100%, 50%),
hsl(300, 100%, 50%),
hsl(330, 100%, 50%),
hsl(360, 100%, 50%)
)
`,
clipPath: `path(evenodd, "${circlePath(outerRadius, outerRadius, outerRadius)} ${circlePath(outerRadius, outerRadius, innerRadius)}")`
}
},
thumbProps: {
...thumbInteractions,
style: {
position: 'absolute',
left: '50%',
top: '50%',
transform: `translate(calc(${x}px - 50%), calc(${y}px - 50%))`,
touchAction: 'none'
}
},
inputProps: mergeProps(
inputLabellingProps,
{
type: 'range',
min: String(minValue),
max: String(maxValue),
step: String(step),
'aria-valuetext': state.value.formatChannelValue('hue', locale),
disabled: isDisabled,
value: `${state.value.getChannelValue('hue')}`,
onChange: (e: ChangeEvent<HTMLInputElement>) => {
state.setHue(parseFloat(e.target.value));
}
}
)
};
}
// Creates an SVG path string for a circle.
function circlePath(cx: number, cy: number, r: number) {
return `M ${cx}, ${cy} m ${-r}, 0 a ${r}, ${r}, 0, 1, 0, ${r * 2}, 0 a ${r}, ${r}, 0, 1, 0 ${-r * 2}, 0`;
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.