text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as pulumi from "@pulumi/pulumi";
import * as express from "express";
import * as cloudfunctions from ".";
import * as storage from "../storage";
import * as filepath from "path";
import * as utils from "../utils";
/**
* Google Cloud Functions uses this parameter to provide details of your Function's execution. For
* more information, see https://cloud.google.com/functions/docs/writing/background#function_parameters
*/
export interface Context {
/** A unique ID for the event. For example: "70172329041928". */
eventId: string;
/** The date/time this event was created. For example: "2018-04-09T07:56:12.975Z". */
timestamp: string;
/** The type of the event. For example: "google.pubsub.topic.publish". */
eventType: string;
/** The resource that emitted the event. See derived contexts for more specific information
* about the shape of this property. */
resource: any;
}
/**
* Callback is the signature for an Google Cloud Function entrypoint.
*
* [data] is the data passed in by specific services calling the Function (like storage, or pubsub).
* The shape of it will be specific to individual services.
*
* [context] Cloud Functions uses this parameter to provide details of your Function's execution.
* For more information, see
* https://cloud.google.com/functions/docs/writing/background#function_parameters
*
* [callback] A callback to signal completion of the function's execution. Follows the "errback"
* convention, which interprets the first argument as an error.
*
* You must signal when background functions have completed. Otherwise, your function can continue
* to run and be forcibly terminated by the system. You can signal function completion by:
*
* 1. Invoking the callback argument,
* 2. Returning a Promise,
* 3. Wrapping your function using the async keyword (which causes your function to implicitly
* return a Promise), or
* 4. Returning a value.
*
* If invoking the callback argument or synchronously returning a value, ensure that all
* asynchronous processes have completed first. If returning a Promise, Cloud Functions ensures that
* the Promise is settled before terminating.
*/
export type Callback<D, C extends Context, R> = (data: D, context: C, callback: (error?: any, result?: R) => void) => Promise<R> | void;
/**
* CallbackFactory is the signature for a function that will be called once to produce the
* entrypoint function that GCP Cloud Function will invoke. It can be used to initialize expensive
* state once that can then be used across all invocations of the Function (as long as the Function
* is using the same warm node instance).
*/
export type CallbackFactory<D, C extends Context, R> = () => Callback<D, C, R>;
/**
* Describes the policy in case of function's execution failure. If empty, then defaults to ignoring
* failures (i.e. not retrying them).
*/
export interface FailurePolicy {
/**
* Whether the function should be retried on failure.
*
* If true, a function execution will be retried on any failure. A failed execution will be
* retried up to 7 days with an exponential backoff (capped at 10 seconds). Retried execution is
* charged as any other execution.
*/
retry: pulumi.Input<boolean>
}
/**
* A CallbackFunction is a special type of gcp.cloudfunctions.Function that can be created out of an
* actual JavaScript function instance. The function instance will be analyzed and packaged up
* (including dependencies) into a form that can be used by Cloud Functions. See
* https://github.com/pulumi/docs/blob/master/reference/serializing-functions.md for additional
* details on this process.
*
* Note: CallbackFunctions create Google Cloud Functions that uses the [nodejs8] runtime.
* Importantly, calls follow the `(data, context) => ...` form, not the `(event, callback) => ...`
* form that is used with the [nodejs6] runtime. This also adds support for asynchronous functions
* as well. See
* https://cloud.google.com/functions/docs/writing/background#functions_background_parameters-node8
* for more details.
*/
export class CallbackFunction extends pulumi.ComponentResource {
/**
* Bucket and BucketObject storing all the files that comprise the Function. The contents of
* these files will be generated automatically from the JavaScript callback function passed in
* as well as the package.json file for your pulumi app.
*/
public readonly bucket: storage.Bucket;
public readonly bucketObject: storage.BucketObject;
/** Underlying raw resource for the Function that is created. */
public readonly function: cloudfunctions.Function;
constructor(name: string, args: CallbackFunctionArgs, opts: pulumi.ComponentResourceOptions = {}) {
super("gcp:cloudfunctions:CallbackFunction", name, undefined, opts);
const parentOpts = { parent: this };
const handlerName = "handler";
const serializedFileNameNoExtension = "index";
const func = args.callback || args.callbackFactory;
if (!func) {
throw new Error("One of [callback] or [callbackFactory] must be provided.");
}
const closure = pulumi.runtime.serializeFunction(func, {
serialize: _ => true,
exportName: handlerName,
isFactoryFunction: !!args.callbackFactory,
});
const codePaths = computeCodePaths(closure, serializedFileNameNoExtension, args.codePathOptions);
// https://cloud.google.com/storage/docs/naming
//
// Bucket names must contain only lowercase letters, numbers, dashes (-), underscores (_),
// and dots.
const bucketName = name.toLowerCase().replace(/[^-_a-z0-9]/gi, "-");
this.bucket = args.bucket || new storage.Bucket(bucketName, {
project: args.project,
location: args.location || "US", // The default of "US" here is what it previously defaulted to
}, parentOpts);
this.bucketObject = new storage.BucketObject(`${name}`, {
bucket: this.bucket.name,
source: new pulumi.asset.AssetArchive(codePaths),
}, parentOpts);
const argsCopy = {
...args
};
// remove the values we've added on top of everything.
delete argsCopy.callback;
delete argsCopy.callbackFactory;
delete argsCopy.codePathOptions;
// Function names : can only contain letters, numbers, underscores and hyphens
const functionName = name.replace(/[^-_a-z0-9]/gi, "-");
this.function = new cloudfunctions.Function(functionName, {
...argsCopy,
runtime: utils.ifUndefined(args.runtime, "nodejs8"),
entryPoint: handlerName,
sourceArchiveBucket: this.bucket.name,
sourceArchiveObject: this.bucketObject.name,
}, parentOpts);
const invoker = new cloudfunctions.FunctionIamMember(`${functionName}-invoker`, {
project: this.function.project,
region: this.function.region,
cloudFunction: this.function.name,
role: utils.ifUndefined(args.iamRole, "roles/cloudfunctions.invoker"),
member: utils.ifUndefined(args.iamMember, "allUsers")
}, {
...parentOpts,
/**
* This alias exists to be backwards compatible for previous versions that did
* not set a parent on this resource.
* https://github.com/pulumi/pulumi-gcp/issues/543
*/
aliases: [{ parent: undefined }],
});
this.registerOutputs();
}
}
/**
* An http-triggered Cloud-Function that, when invoked, will execute the code supplied by a
* user-provided JavaScript-Function. To handle HTTP, Cloud Functions uses Express 4.16.3.
*
* You invoke HTTP functions from standard HTTP requests. These HTTP requests wait for the response
* and support handling of common HTTP request methods like GET, PUT, POST, DELETE and OPTIONS. When
* you use Cloud Functions, a TLS certificate is automatically provisioned for you, so all HTTP
* functions can be invoked via a secure connection.
*
* See more information at: https://cloud.google.com/functions/docs/writing/http
*/
export class HttpCallbackFunction extends CallbackFunction {
/**
* URL which triggers function execution.
*/
public readonly httpsTriggerUrl: pulumi.Output<string>;
constructor(name: string, callback: HttpCallback, opts?: pulumi.ComponentResourceOptions);
constructor(name: string, args: HttpCallbackFunctionArgs, opts?: pulumi.ComponentResourceOptions);
constructor(name: string, callbackOrArgs: HttpCallback | HttpCallbackFunctionArgs, opts: pulumi.ComponentResourceOptions = {}) {
const argsCopy: CallbackFunctionArgs = callbackOrArgs instanceof Function
? { callback: callbackOrArgs, triggerHttp: true }
: { ...callbackOrArgs, triggerHttp: true };
super(name, argsCopy, opts)
this.httpsTriggerUrl = this.function.httpsTriggerUrl;
}
}
// computeCodePaths calculates an AssetMap of files to include in the Function package.
async function computeCodePaths(
closure: Promise<pulumi.runtime.SerializedFunction>,
serializedFileNameNoExtension: string,
codePathOptions: pulumi.runtime.CodePathOptions = {}): Promise<pulumi.asset.AssetMap> {
codePathOptions.extraIncludePaths = codePathOptions.extraIncludePaths || [];
codePathOptions.extraIncludePackages = codePathOptions.extraIncludePackages || [];
codePathOptions.extraExcludePackages = codePathOptions.extraExcludePackages || [];
if (codePathOptions.extraIncludePaths.length > 0) {
throw new pulumi.ResourceError("codePathOptions.extraIncludePaths not currently supported in GCP.", codePathOptions.logResource);
}
if (codePathOptions.extraIncludePackages.length > 0) {
throw new pulumi.ResourceError("codePathOptions.extraIncludePackages not currently supported in GCP.", codePathOptions.logResource);
}
const serializedFunction = await closure;
const excludedPackages = new Set<string>();
for (const p of codePathOptions.extraExcludePackages) {
excludedPackages.add(p);
}
// Include packages to package.json file
const packageJson = await producePackageJson(excludedPackages);
return {
// Always include the serialized function.
[serializedFileNameNoExtension + ".js"]: new pulumi.asset.StringAsset(serializedFunction.text),
// Include package.json and GCP will install packages for us
["package.json"]: new pulumi.asset.StringAsset(packageJson)
};
}
// Get the list of packages declare in package.json, exclude pulumi and exclusions made by user,
// generate the new package.json to be uploaded to GCP.
// GCP will restore the packages itself.
function producePackageJson(excludedPackages: Set<string>): Promise<string> {
return new Promise((resolve, reject) => {
const readPackageJson = require("read-package-json");
readPackageJson(filepath.basename('package.json'), null, false, (err: Error, packageJson: any) => {
if (err) {
return reject(err);
}
// Override dependencies by removing @pulumi and excludedPackages
const dependencies = Object.keys(packageJson.dependencies)
.filter(pkg => !excludedPackages.has(pkg) && !pkg.startsWith("@pulumi"))
.reduce((obj, key) => {
obj[key] = packageJson.dependencies[key];
return obj;
}, <Record<string, string>>{});
resolve(JSON.stringify({
dependencies: dependencies,
}));
});
});
}
/**
* Arguments that control both how a user function is serialized and how the final Cloud Function
* is created. Can be used to override values if the defaults are not desirable.
*/
export interface CallbackFunctionArgs {
/**
* Options to control which paths/packages should be included or excluded in the zip file containing
* the code for the GCP Function.
*/
codePathOptions?: pulumi.runtime.CodePathOptions;
/**
* Memory (in MB), available to the function. Default value is 256MB. Allowed values are: 128MB, 256MB, 512MB, 1024MB, and 2048MB.
*/
availableMemoryMb?: pulumi.Input<number>;
/**
* Description of the function.
*/
description?: pulumi.Input<string>;
/**
* A set of key/value environment variable pairs to assign to the function.
*/
environmentVariables?: pulumi.Input<{ [key: string]: any }>;
/**
* A source that fires events in response to a condition in another service. Structure is
* documented below. Cannot be used with `trigger_http`.
*/
eventTrigger?: pulumi.Input<{ eventType: pulumi.Input<string>, failurePolicy?: pulumi.Input<FailurePolicy>, resource: pulumi.Input<string> }>;
/**
* URL which triggers function execution. Returned only if `trigger_http` is used.
*/
httpsTriggerUrl?: pulumi.Input<string>;
/**
* A set of key/value label pairs to assign to the function.
*/
labels?: pulumi.Input<{ [key: string]: any }>;
/**
* Location of the function. If it is not provided, the provider location is used.
*/
location?: pulumi.Input<string>;
/**
* Project of the function. If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Region of function. Currently can be only "us-central1". If it is not provided, the provider region is used.
*/
region?: pulumi.Input<string>;
/**
* If provided, the self-provided service account to run the function with.
*/
serviceAccountEmail?: pulumi.Input<string>;
/**
* Timeout (in seconds) for the function. Default value is 60 seconds. Cannot be more than 540 seconds.
*/
timeout?: pulumi.Input<number>;
/**
* Boolean variable. Any HTTP request (of a supported type) to the endpoint will trigger function execution. Supported HTTP request types are: POST, PUT, GET, DELETE, and OPTIONS. Endpoint is returned as `https_trigger_url`. Cannot be used with `trigger_bucket` and `trigger_topic`.
*/
triggerHttp?: pulumi.Input<boolean>;
/**
* The Javascript callback to use as the entrypoint for the GCP CloudFunction out of. Either
* [callback] or [callbackFactory] must be provided.
*/
callback?: Function;
/**
* The Javascript function instance that will be called to produce the callback function that is
* the entrypoint for the GCP Cloud Function. Either [callback] or [callbackFactory] must be
* provided.
*
* This form is useful when there is expensive initialization work that should only be executed
* once. The factory-function will be invoked once when the final GCP Cloud Function module is
* loaded. It can run whatever code it needs, and will end by returning the actual function that
* Function will call into each time the Cloud Function is invoked.
*/
callbackFactory?: Function;
/**
* The bucket to use as the sourceArchiveBucket for the generated CloudFunctions Function source
* to be placed in. A fresh [storage.BucketObject] will be made there containing the serialized
* code.
*/
bucket?: storage.Bucket;
/**
* The specific runtime for the function. If not specified, a default will be applied
*/
runtime?: pulumi.Input<string>;
/**
* The specific member to grant access to the function. If not specifiedm then we default to `allUsers`.
* Available options are `allAuthenticatedUsers`, `user:{emailid}`, `serviceAccount:{emailid}`,
* `group:{emailid}` and `domain:{domain}:`
*/
iamMember?: pulumi.Input<string>;
/**
* The specific role to attach to the function. If not specified, then we default to `roles/cloudfunctions.invoker`.
* Role must be in the format `roles/{role-name}`
*/
iamRole?: pulumi.Input<string>;
}
/**
* HttpCallback is the signature for an http triggered GCP CloudFunction entrypoint.
*
* [req] is the data passed in by specific services calling the CloudFunction. See
* https://expressjs.com/en/api.html#req for more details.
*
* [res] is the object that be used to supply the response. See
* https://expressjs.com/en/api.html#res for more details.
*/
export type HttpCallback = (req: express.Request, res: express.Response) => void;
export type HttpCallbackFactory = () => HttpCallback;
/**
* Specialized arguments to use when specifically creating an [HttpCallbackFunction].
*/
export interface HttpCallbackFunctionArgs extends CallbackFunctionArgs {
/**
* The Javascript callback to use as the entrypoint for the GCP CloudFunction out of. Either
* [callback] or [callbackFactory] must be provided.
*/
callback?: HttpCallback;
/**
* The Javascript function instance that will be called to produce the callback function that is
* the entrypoint for the GCP CloudFunction. Either [callback] or [callbackFactory] must be
* provided.
*
* This form is useful when there is expensive initialization work that should only be executed
* once. The factory-function will be invoked once when the final GCP CloudFunction module is
* loaded. It can run whatever code it needs, and will end by returning the actual function that
* Function will call into each time the Function is invoked.
*/
callbackFactory?: HttpCallbackFactory;
triggerHttp?: never
eventTrigger?: never;
} | the_stack |
import { Injectable } from '@angular/core';
import { ShortAnswerQuestion } from 'app/entities/quiz/short-answer-question.model';
import { ShortAnswerMapping } from 'app/entities/quiz/short-answer-mapping.model';
import { ShortAnswerSpot } from 'app/entities/quiz/short-answer-spot.model';
import { ShortAnswerSolution } from 'app/entities/quiz/short-answer-solution.model';
import { cloneDeep } from 'lodash-es';
import { htmlForMarkdown } from 'app/shared/util/markdown.conversion.util';
@Injectable({ providedIn: 'root' })
export class ShortAnswerQuestionUtil {
constructor() {}
/**
* Validate that no mapping exists that makes it impossible to solve the question.
* We iterate through all spots and remove all possible mappings (solutions) for that spot.
* If there are still mappings (solutions) left for the other spots everything is ok.
* In case we have multiple mappings for spots, we check whether there are an equal or greater amount of mappings than spots.
*
* @param question {object} the question to check
* @return {boolean} true, if the condition is met, otherwise false
*/
validateNoMisleadingShortAnswerMapping(question: ShortAnswerQuestion) {
if (!question.correctMappings) {
// no correct mappings at all means there can be no misleading mappings
return true;
}
let unusedMappings: ShortAnswerMapping[] = cloneDeep(question.correctMappings);
const spotsCanBeSolved: boolean[] = [];
for (const spot of question.spots!) {
let atLeastOneMapping = false;
const solutionsForSpots = this.getAllSolutionsForSpot(question.correctMappings, spot)!;
solutionsForSpots.forEach((solution) => {
if (unusedMappings.length > 0 && unusedMappings.length !== question.correctMappings!.length) {
atLeastOneMapping = true;
}
// unusedMappings.length > 0 will be always true for the first iteration, therefore we need a special check
if (unusedMappings.length === question.correctMappings!.length) {
// We need to verify if the first spot has mappings (solutions) that is only for itself
// In case there are multiple mappings (solutions) for spots, we use hasSpotEnoughSolutions
const allSolutionsForSpot = this.getAllSolutionsForSpot(question.correctMappings, spot)!;
const allSolutionsOnlyForSpot = allSolutionsForSpot.filter(
(solutionForSpot) => this.getAllSpotsForSolutions(question.correctMappings, solutionForSpot)!.length === 1,
);
if (allSolutionsOnlyForSpot.length > 0) {
atLeastOneMapping = true;
}
}
// Remove every solution for a spot in the mapping
unusedMappings = unusedMappings.filter((mapping) => !this.isSameSolution(solution, mapping.solution));
});
// In case there are multiple mappings for the spots there have to be at least as many solutions as spots
const hasSpotEnoughSolutions = this.getAllSolutionsForSpot(question.correctMappings, spot)!.length >= question.spots!.length;
// Check whether a mapping is still left to solve a spot correctly.
if (atLeastOneMapping || hasSpotEnoughSolutions) {
spotsCanBeSolved.push(true);
} else {
spotsCanBeSolved.push(false);
}
}
return !spotsCanBeSolved.includes(false);
}
/**
* Check if the given solution and spot are mapped together in the given mappings
*
* @param mappings {Array} the existing mappings to consider
* @param solution {object} the solution to search for
* @param spot {object} the spot to search for
* @return {boolean} true if they are mapped together, otherwise false
*/
isMappedTogether(mappings?: ShortAnswerMapping[], solution?: ShortAnswerSolution, spot?: ShortAnswerSpot) {
return !!this.getShortAnswerMapping(mappings, solution, spot);
}
/**
* Get all spots that are mapped to the given solutions
*
* @param mappings {Array} the existing mappings to consider
* @param solution {object} the solution that the returned spots have to be mapped to
* @return {Array} the resulting spots
*/
getAllSpotsForSolutions(mappings?: ShortAnswerMapping[], solution?: ShortAnswerSolution) {
return mappings
?.filter(function (mapping) {
return this.isSameSolution(mapping.solution, solution);
}, this)
.map(function (mapping) {
return mapping.spot!;
});
}
/**
* Get all solutions that are mapped to the given spot
*
* @param mappings {Array} the existing mappings to consider
* @param spot {object} the spot for which to get the solutions
* @return {Array} the resulting solutions
*/
getAllSolutionsForSpot(mappings?: ShortAnswerMapping[], spot?: ShortAnswerSpot) {
return mappings
?.filter((mapping) => {
return this.isSameSpot(mapping.spot, spot);
}, this)
.map((mapping) => {
return mapping.solution!;
});
}
/**
* Check if set1 and set2 contain the same solutions or spots
*
* @param set1 {Array} one set of solutions or spots
* @param set2 {Array} another set of solutions or spots
* @return {boolean} true if the sets contain the same items, otherwise false
*/
isSameSetOfSpots(set1?: ShortAnswerSpot[], set2?: ShortAnswerSpot[]) {
const service = this;
if (set1?.length !== set2?.length) {
// different number of elements => impossible to contain the same elements
return false;
}
return (
// for every element in set1 there has to be an identical element in set2 and vice versa
set1?.every((spot1) => {
return set2?.some((spot2) => {
return service.isSameSpot(spot1, spot2);
});
}) &&
set2?.every((spot2) => {
return set1?.some((spot1) => {
return service.isSameSpot(spot1, spot2);
});
})
);
}
/**
* Get the mapping that maps the given solution and spot together
*
* @param mappings {Array} the existing mappings to consider
* @param solution {object} the solution to search for
* @param spot {object} the spot to search for
* @return the found mapping, or undefined if it doesn't exist
*/
getShortAnswerMapping(mappings?: ShortAnswerMapping[], solution?: ShortAnswerSolution, spot?: ShortAnswerSpot) {
const that = this;
return mappings?.find((mapping: ShortAnswerMapping) => {
return that.isSameSpot(spot, mapping.spot) && that.isSameSolution(solution, mapping.solution);
}, this);
}
/**
* compare if the two objects are the same spot
*
* @param a {object} a spot
* @param b {object} another spot
* @return {boolean}
*/
isSameSpot(a?: ShortAnswerSpot, b?: ShortAnswerSpot): boolean {
return a === b || (a !== undefined && b !== undefined && ((a.id && b.id && a.id === b.id) || (a.tempID != undefined && b.tempID != undefined && a.tempID === b.tempID)));
}
/**
* compare if the two objects are the same solution
*
* @param a {object} a solution
* @param b {object} another solution
* @return {boolean}
*/
isSameSolution(a?: ShortAnswerSolution, b?: ShortAnswerSolution): boolean {
return a === b || (a !== undefined && b !== undefined && ((a.id && b.id && a.id === b.id) || (a.tempID != undefined && b.tempID != undefined && a.tempID === b.tempID)));
}
/**
* checks if every spot has a solution
*
* @param mappings {object} mappings
* @param spots {object} spots
* @return {boolean}
*/
everySpotHasASolution(mappings: ShortAnswerMapping[], spots: ShortAnswerSpot[]): boolean {
let i = 0;
for (const spot of spots) {
const solutions = this.getAllSolutionsForSpot(mappings, spot);
if (solutions && solutions.length > 0) {
i++;
}
}
return i === spots.length;
}
/**
* checks if every mapped solution has a spot
*
* @param mappings {object} mappings
* @return {boolean}
*/
everyMappedSolutionHasASpot(mappings: ShortAnswerMapping[]): boolean {
return !(mappings.filter((mapping) => mapping.spot === undefined).length > 0);
}
/**
* checks if mappings have duplicate values
*
* @param mappings
* @return {boolean}
*/
hasMappingDuplicateValues(mappings: ShortAnswerMapping[]): boolean {
if (mappings.filter((mapping) => mapping.spot === undefined).length > 0) {
return false;
}
let duplicateValues = 0;
for (let i = 0; i < mappings.length - 1; i++) {
for (let j = i + 1; j < mappings.length; j++) {
if (mappings[i].spot!.spotNr === mappings[j].spot!.spotNr && mappings[i].solution!.text! === mappings[j].solution!.text!) {
duplicateValues++;
}
}
}
return duplicateValues > 0;
}
/**
* Display a sample solution instead of the student's answer
*
* @param {ShortAnswerQuestion} question
* @returns {ShortAnswerSolution[]}
*/
getSampleSolutions(question: ShortAnswerQuestion): ShortAnswerSolution[] {
const sampleSolutions: ShortAnswerSolution[] = [];
for (const spot of question.spots!) {
const solutionsForSpot = this.getAllSolutionsForSpot(question.correctMappings!, spot);
for (const mapping of question.correctMappings!) {
if (
mapping.spot!.id === spot.id &&
!sampleSolutions.some(
(sampleSolution) => sampleSolution.text === mapping.solution!.text && !this.allSolutionsAreInSampleSolution(solutionsForSpot, sampleSolutions),
)
) {
sampleSolutions.push(mapping.solution!);
break;
}
}
}
return sampleSolutions;
}
/**
* checks if all solutions are in the sample solution
*
* @param {ShortAnswerSolution[]} solutionsForSpot
* @param {ShortAnswerSolution[]} sampleSolutions
* @returns {boolean}
*/
allSolutionsAreInSampleSolution(solutionsForSpot?: ShortAnswerSolution[], sampleSolutions?: ShortAnswerSolution[]): boolean {
let i = 0;
for (const solutionForSpot of solutionsForSpot || []) {
for (const sampleSolution of sampleSolutions || []) {
if (solutionForSpot.text === sampleSolution.text) {
i++;
break;
}
}
}
return i === solutionsForSpot?.length;
}
/**
* checks if at least there are as many solutions as spots
*
* @param {ShortAnswerQuestion} question
* @returns {boolean}
*/
atLeastAsManySolutionsAsSpots(question: ShortAnswerQuestion): boolean {
return question.spots!.length <= question.solutions!.length;
}
/**
* We create now the structure on how to display the text of the question
* 1. The question text is split at every new line. The first element of the array would be then the first line of the question text.
* 2. Now each line of the question text will be divided into text before spot tag, spot tag and text after spot tag.
* (e.g 'Enter [-spot 1] long [-spot 2] if needed' will be transformed to [["Enter", "[-spot 1]", "long", "[-spot 2]", "if needed"]])
*
* @param questionText
* @returns {string[][]}
*/
divideQuestionTextIntoTextParts(questionText: string): string[][] {
const spotRegExpo = /\[-spot\s*[0-9]+\]/g;
/**
* Interleaves elements of two lists xs and ys recursively
* @param x First element
* @param xs Rest of the list
* @param ys Other list
*/
function interleave([x, ...xs]: string[], ys: string[] = []): string[] {
return x === undefined
? ys // base: no x
: [x, ...interleave(ys, xs)]; // inductive: some x
}
return questionText.split(/\n/g).map((line) => {
const spots = line.match(spotRegExpo) || [];
const texts = line.split(spotRegExpo);
return interleave(texts, spots).filter((x) => x.length > 0);
});
}
/**
* checks if text is an input field (check for spot tag)
* @param text
*/
isInputField(text: string): boolean {
return !(text.search(/\[-spot/g) === -1);
}
/**
* gets just the spot number
* @param text
*/
getSpotNr(text: string): number {
// separate "[-spot 1]" into just "1"
return +text
.split(/\[-spot/g)[1]
.split(']')[0]
.trim();
}
/**
* gets the spot for a specific spotNr
* @param spotNr the spot number for which the sport should be retrived
* @param question
*/
getSpot(spotNr: number, question: ShortAnswerQuestion): ShortAnswerSpot {
return question.spots!.filter((spot) => spot.spotNr === spotNr)[0];
}
/**
* We transform now the different text parts of the question text to HTML.
* 1. We iterate through every line of the question text.
* 2. We iterate through every element of each line of the question text and set each element with the new HTML.
* @param textParts
* @returns {string[][]}
*/
transformTextPartsIntoHTML(textParts: string[][]): string[][] {
const formattedTextParts = textParts.map((textPart) => textPart.map((element) => htmlForMarkdown(element.trim())));
return this.addIndentationToTextParts(textParts, formattedTextParts);
}
/**
* @function addIndentationToTextParts
* @desc Formats the first word of each line with the indentation it originally had.
* @param originalTextParts {string[][]} the text parts without html formatting
* @param formattedTextParts {string[][]} the text parts with html formatting
*/
addIndentationToTextParts(originalTextParts: string[][], formattedTextParts: string[][]): string[][] {
for (let i = 0; i < formattedTextParts.length; i++) {
const element = formattedTextParts[i][0];
let firstWord = '';
// check if first word is a spot (first array element will be an empty string)
if (originalTextParts[i].length > 1) {
firstWord =
formattedTextParts[i][0] === '' && originalTextParts[i][1].startsWith('[-spot')
? this.getFirstWord(originalTextParts[i][1])
: this.getFirstWord(originalTextParts[i][0]);
} else {
firstWord = this.getFirstWord(originalTextParts[i][0]);
}
if (firstWord === '') {
continue;
}
const firstWordIndex = element.indexOf(firstWord);
const whitespace = ' '.repeat(this.getIndentation(originalTextParts[i][0]).length);
formattedTextParts[i][0] = [element.substring(0, firstWordIndex), whitespace, element.substring(firstWordIndex).trim()].join('');
}
return formattedTextParts;
}
/**
* @function getIndentation
* @desc Returns the whitespace in front of the text.
* @param text {string} the text for which we get the indentation
*/
public getIndentation(text: string): string {
if (!text) {
return '';
}
if (text.startsWith('`')) {
text = text.substring(1);
}
let index = 0;
let indentation = '';
while (text[index] === ' ') {
indentation = indentation.concat(' ');
index++;
}
return indentation;
}
/**
* @function getFirstWord
* @desc Returns the first word in a text.
* @param text {string} for which the first word is returned
*/
getFirstWord(text: string): string {
if (!text) {
return '';
}
const words = text
.trim()
.split(' ')
.filter((word) => word !== '');
if (words.length === 0) {
return '';
} else if (words[0] === '`') {
return words[1];
} else {
return words[0].startsWith('`') ? words[0].substring(1) : words[0];
}
}
} | the_stack |
const savedObject = Object /* {
defineProperty: Object.defineProperty,
getOwnPropertyDescriptors: Object.getOwnPropertyDescriptors,
assign: Object.assign,
create: Object.create,
setPrototypeOf: Object.setPrototypeOf,
getPrototypeOf: Object.getPrototypeOf,
getOwnPropertySymbols: Object.getOwnPropertySymbols,
getOwnPropertyNames: Object.getOwnPropertyNames,
getOwnPropertyDescriptor: Object.getOwnPropertyDescriptor
}*/;
// tslint:disable-next-line
const savedConsole = { log: console.log, warn: console.warn };
const weakMapSet = WeakMap.prototype.set;
function showStack(ctx: WriteContext, key: string | number, value: any) {
savedConsole.warn("Not serializable ", key, debCtx, value);
let i = ctx.jobs;
let num = 0;
for (;;) {
while (i && !i.started) i = i.nextJob;
if (!i) break;
savedConsole.warn(`SF#${++num}:`, i.index, i.debCtx, ":", i.value);
if (num > 200) break;
i = i.nextJob;
}
}
const LocMap = Map;
const LocWeakMap = WeakMap;
const LocSet = Set;
export interface State {
/** name for a property storing descriptor */
symbol: symbol;
/** descriptors registered by type's name */
byName: Map<string, Descriptor>;
/** descriptors registered by some primitive value */
byValue: Map<any, Descriptor>;
/** descriptors registered by some value */
byObject: WeakMap<any, Descriptor>;
/** descriptors registered by its prototype value */
byPrototype: WeakMap<any, Descriptor>;
/**
* react uses `$$typeof` property for its values, it is the mapping
* @private
*/
byTypeOfProp: Map<symbol, Descriptor>;
}
export interface IncompleteState {
symbol?: symbol;
byName?: Map<string, Descriptor>;
byValue?: Map<any, Descriptor>;
byObject?: WeakMap<any, Descriptor>;
byPrototype?: WeakMap<any, Descriptor>;
byTypeOfProp?: Map<symbol, Descriptor>;
}
/** symbol for storing global state */
declare let __effectfulSerializationState: IncompleteState;
function initializeState(init: IncompleteState): State {
if (!init.symbol) init.symbol = Symbol("@effectful/serialization/descriptor");
if (!init.byName) init.byName = new LocMap();
if (!init.byValue) init.byValue = new LocMap();
if (!init.byObject) init.byObject = new LocWeakMap();
if (!init.byPrototype) init.byPrototype = new LocWeakMap();
if (!init.byTypeOfProp) init.byTypeOfProp = new LocMap();
return <State>init;
}
if (!(<any>global).__effectfulSerializationState)
(<any>global).__effectfulSerializationState = {};
let state: State = initializeState(__effectfulSerializationState);
let ObjectConstr = Object;
/** name of a property to specify `Descriptor` for JS value */
export let descriptorSymbol: symbol = state.symbol;
let descriptorByName: Map<string, Descriptor> = state.byName;
let descriptorByValue: Map<any, Descriptor> = state.byValue;
let descriptorByObject: WeakMap<any, Descriptor> = state.byObject;
let descriptorByPrototype: WeakMap<any, Descriptor> = state.byPrototype;
let descriptorByTypeOfProp: Map<symbol, Descriptor> = state.byTypeOfProp;
/**
* Sets new state value
*
* After setting this each instance of this module will have own state
*/
export function resetState(init: IncompleteState = {}) {
state = initializeState(init);
descriptorSymbol = state.symbol;
descriptorByName = state.byName;
descriptorByValue = state.byValue;
descriptorByObject = state.byObject;
descriptorByPrototype = state.byPrototype;
descriptorByTypeOfProp = state.byTypeOfProp;
}
export function getState(): State {
return state;
}
/**
* Conversion between JSON values and JS values. JSON values set is a subset
* of JS values which can be converted to string using `JSON.stringify`
* function and read back with `JSON.parse`.
*/
/** Options to amend `write` behavior */
export interface WriteOptions {
/**
* don't throw exception if there is any writting error
*/
ignore?: boolean | "opaque" | "placeholder";
/**
* execute `console.warn` for each ignored value (if `ignore` isn't falsy)
*/
warnIgnored?: boolean;
/**
* current reference's id assignment state,
* this can be copied between writes to keep same refs ids
*/
sharedRefsMap?: Map<any, SharedRefInfo>;
/* resulting refs by their id */
sharedRefs?: SharedRefInfo[];
/**
* holds information about seen local Symbols, it can be copied between runs
*/
symsByName?: Map<string, SymbolDescr[]>;
/**
* holds information about seen local Symbols, it can be copied between runs
*/
knownSyms?: Map<symbol, SymbolDescr>;
/**
* by default the serializer uses references only if the object is referred more than once
* this may still lead to stack overflow in `JSON.stringify` esp. if the data has some
* structures like linked lists, this option will always generate a reference
*/
alwaysByRef?: boolean;
verbose?: boolean;
/** if this array is initialized it will be filled with the shared object's values */
refs?: any[];
weakMaps?: [WeakMap<any, any>, JSONObject][];
weakSets?: [WeakSet<any>, JSONObject][];
}
/** Options to amend `write` behavior */
export interface ReadOptions {
/** don't throw exception if there is any reading error */
ignore?: boolean | "placeholder";
warnIgnored?: boolean;
/**
* holds information about seen local Symbols, it can be copied between runs
*/
symsByName?: Map<string, SymbolDescr[]>;
/**
* holds information about seen local Symbols, it can be copied between runs
*/
knownSyms?: Map<symbol, SymbolDescr>;
/** references to shared object values */
refs?: any[];
}
/** `JSON.stringify` serializable value */
export type JSONValue =
| boolean
| number
| string
| JSONObject
| JSONArray
| null;
/** `JSON.stringify` serializable Object */
export interface JSONObject {
[name: string]: JSONValue;
}
/** `JSON.stringify` serializable Array */
export interface JSONArray extends Array<JSONValue> {}
/* TODO after TS supports symbol indexes `{ [name: string | symbol]: boolean } */
const defaultOverrideProps: any = {
[descriptorSymbol]: false
};
const funcOverrideProps: { [name: string]: boolean } = {
arguments: false,
caller: false,
length: false,
name: false
};
/** Describes how to read values of a type */
export interface ReadDescriptor<T = unknown> {
/**
* Reads value from `json` value
* @param ctx - recursive reads handling for sub-values
* @param json - input JSON
* @returns - resulting JS value
*/
read: (ctx: ReadContext, json: JSONValue) => T;
/**
* The first part of `read`, just creates a corresponding value without traversing into children.
* This is needed to avoid infinite loops on recursive values.
* @param ctx - recursive reads handling for sub-values
* @param json - input JSON
* @returns - resulting JS value
*/
create: (ctx: ReadContext, json: JSONValue) => T;
/**
* The second part of `read`, creates children and sets them into `value`.
* This is needed to avoid infinite loops on recursive values.
* @param ctx - recursive reads handling for sub-values
* @param json - input JSON
* @param value - resulting JS value
*/
readContent: (ctx: ReadContext, json: JSONValue, value: T) => void;
}
export interface WithTypeofTag {
$$typeof?: symbol;
}
export interface DescriptorOpts<T = unknown> {
/** Unique type name */
name?: string;
/** dispatching descriptor by value of `$$typeof` property */
typeofTag?: symbol;
/**
* If !== false, the descriptor recognizes shared objects and uses only references for them.
* The default is `true`.
*/
refAware?: boolean;
/**
* If !== false the descriptor will traverse own properties too
*/
props?: boolean;
/**
* Make a snapshot of its original property values and won't write
* them if they aren't changed
*/
propsSnapshot?: boolean;
/**
* If !== false the descriptor will add property `$` equal to `name` by default
*/
default$?: boolean;
/**
* `typeof value` for the values this serializes
*/
typeofHint?: string;
/** if `props !== false` this is a predicate to specify which properties should be output. */
overrideProps?: { [name: string /*|symbol*/]: boolean };
/** don't change the `name` to make it unique */
strictName?: boolean;
/** a prototype to be assigned with `Object.setPrototype` in reads */
valuePrototype?: object | null | false;
/** Serialized value's constructor */
valueConstructor?: ValueConstructor<T>;
/** constant value */
value?: T;
/** mask for property descriptor flags (configurable:1,enumerable:2,writable:4,no value = 8) */
propsDescrMask?: number;
/**
* if an object has this prototype it won't be recorded
*/
defaultPrototype?: any;
/**
* for descriptors traversing properties with stores
* original values which shouldn't be output
*/
snapshot?: { [name: string]: PropertyDescriptor };
/** if it is a value in a global scope this will store its name */
globalName?: string;
}
interface ValueConstructor<T = unknown> {
name?: string;
new (...args: any[]): T;
}
/** Describes how write values of a type */
export interface WriteDescriptor<T = unknown> {
/**
* Sets `value` into `parent` on `index` position
* @param ctx - recursive writes for sub-values
* @param parent - container for the value output
* @param index - either name of a field if parent is an object
* or number index if it is an array
*/
write: (
ctx: WriteContext,
value: T,
parent: JSONObject | JSONArray,
index: number | string
) => JSONValue;
}
export type Descriptor<T = any> = WriteDescriptor<T> &
ReadDescriptor<T> &
DescriptorOpts<T>;
/**
* simplified version of a descriptor where missed properties can be calculated
*/
export type IncompleteDescriptor<T = unknown> = DescriptorOpts<T> & {
create?: (ctx: ReadContext, json: JSONValue) => T;
readContent?: (ctx: ReadContext, json: JSONValue, value: T) => void;
read?: (ctx: ReadContext, json: JSONValue) => T;
write?: (
ctx: WriteContext,
value: T,
parent: JSONObject | JSONArray,
index: number | string
) => JSONValue;
};
/**
* Conversion between JSON values and JS values. JSON values set a subset of JS
* values which can be converted to a string using `JSON.stringify` function and
* read back with `JSON.parse`
*/
/**
* Converts JS Plain Object into JSON Object
*
* It supports only plain objects as root value. To serialize anything else
* just wrap it, e.g. `write({arr:[1]})`
*
* @param value - original object
* @param opts - options
*/
export function write(value: object, opts: WriteOptions = {}): JSONObject {
if (typeof value !== "object" || Array.isArray(value))
throw new TypeError("wrong argument type");
const ctx = new WriteContext(opts);
const res: JSONArray = [];
res.push(ctx.step(value, res, 0));
const { sharedRefs: refs } = ctx;
const alwaysByRef = opts.alwaysByRef;
const x: any[] = [];
const resRefs = opts.refs;
const weakMaps = ctx.weakMaps;
for (let job; (job = ctx.jobs) != null; ) {
if (job.started) {
if (alwaysByRef) {
if (job.ref) job.ref.r = x.push(job.data) - 1;
if (resRefs) resRefs.push(job.value);
} else refs.push(job);
job = ctx.jobs = job.nextJob;
continue;
}
job.started = true;
const value = job.value;
job.data = <JSONObject>(
(<any>job.descriptor).write(ctx, value, job.parent, job.index)
);
for (const [map, json] of weakMaps) {
if (map.has(value)) {
const { k, v } = <any>json;
k.push(ctx.step(value, k, k.length));
v.push(ctx.step(map.get(value), v, v.length));
}
}
}
if (ctx.weakSets.length) {
for (const info of ctx.sharedRefs.values()) {
const ty = typeof info.value;
if (ty !== "object" && ty !== "function") continue;
for (const [wm, val] of ctx.weakSets) {
if (!wm.has(info.value)) continue;
if (!info.ref) info.ref = {};
(<any>val).v.push(info.ref);
}
}
}
if (!alwaysByRef && refs.length) {
for (const info of refs) {
if (info.ref) {
info.ref.r = x.push(info.data) - 1;
if (info.parent) (<any>info.parent)[<any>info.index] = info.ref;
} else if (info.parent) (<any>info.parent)[<any>info.index] = info.data;
}
if (resRefs != null) for (const info of refs) resRefs.push(info.value);
}
return x.length
? savedObject.assign({ x }, <JSONObject>res[0])
: <JSONObject>res[0];
}
/**
* Converts JSON Object returned by {@link write} back to JS Object
*
* @param json - object to read
*/
const emptyArr: any[] = [];
export function read(json: JSONObject, opts: ReadOptions = {}) {
if (typeof json !== "object")
throw new TypeError("root value must be Object");
const jsons = <any>json.x;
const len = jsons ? jsons.length : 0;
const ctx = new ReadContext(opts, jsons || emptyArr);
if (len) {
const vals = ctx.sharedVals;
const descriptors = ctx.sharedDescriptors;
for (let i = 0; i < len; ++i) {
const propJson = jsons[i];
descriptors[i] = getJsonDescriptor(ctx, propJson);
}
for (let i = 0; i < len; ++i) {
const value = vals[i];
if (value !== undef) continue;
vals[i] = descriptors[i].create(ctx, jsons[i]);
}
for (let i = 0; i < len; ++i)
descriptors[i].readContent(ctx, jsons[i], vals[i]);
}
return getJsonDescriptor(ctx, json).read(ctx, json);
}
/**
* `write` followed by `JSON.stringify`,
* with same parameters as for `JSON.stringify`
*/
export function stringify(
value: any,
replacer?: (key: string, value: any) => any,
spaces?: string | number
): string {
return JSON.stringify(write(value), replacer, spaces);
}
/** `JSON.parse` followed by `read` */
export function parse(json: string): any {
return read(JSON.parse(json));
}
export const boundThisSymbol = Symbol("@effectful/bind/this");
export const boundArgsSymbol = Symbol("@effectful/bind/args");
export const boundFunSymbol = Symbol("@effectful/bind/fun");
function makeBind(): (...args: any[]) => any {
function bind(...rest: any[]): any {
return (<any>bind)[boundFunSymbol].apply((<any>bind)[boundThisSymbol], [
...(<any>bind)[boundArgsSymbol],
...rest
]);
}
weakMapSet.call(descriptorByObject, bind, BindDescriptor);
return bind;
}
export function setObjectDescriptor(object: any, descriptor: Descriptor) {
weakMapSet.call(descriptorByObject, object, descriptor);
}
export const BindDescriptor = regDescriptor({
name: "Bind",
create() {
return makeBind();
},
write() {
return {};
},
overrideProps: { ...funcOverrideProps, prototype: false }
});
/**
* like `Function.prototype.bind` but returs serializable object if all
* arguments are serializable
*
* @param func
* @param self - bound `this`
* @param args - bound arguments
*/
export function bind(
func: (...args: any[]) => any,
self: any,
...args: any[]
): (...args: any[]) => any {
const res = <any>makeBind();
res[boundThisSymbol] = self;
res[boundFunSymbol] = func;
res[boundArgsSymbol] = args;
return res;
}
interface SharedRefInfo {
ref: JSONObject | null;
data: JSONObject | null;
parent?: JSONObject | JSONArray;
index?: string | number;
value?: any;
descriptor?: Descriptor<any>;
nextJob?: SharedRefInfo;
started?: boolean;
debCtx?: any;
}
let debCtx: any = null;
/**
* An object passed to Descriptor's `write` method to support recursive
* invocation for nested values
*/
export class WriteContext {
sharedRefsMap: Map<any, SharedRefInfo>;
sharedRefs: SharedRefInfo[];
opts: WriteOptions;
symsByName?: Map<string, SymbolDescr[]>;
knownSyms?: Map<symbol, SymbolDescr>;
jobs?: SharedRefInfo;
weakMaps: [WeakMap<any, any>, JSONObject][];
weakSets: [WeakSet<any>, JSONObject][];
constructor(opts: WriteOptions) {
this.sharedRefsMap =
opts.sharedRefsMap || (opts.sharedRefsMap = new LocMap());
this.sharedRefs = opts.sharedRefs || [];
this.opts = opts;
this.symsByName = opts.symsByName || (opts.symsByName = new LocMap());
this.knownSyms = opts.knownSyms || (opts.knownSyms = new LocMap());
this.weakMaps = opts.weakMaps || (opts.weakMaps = []);
this.weakSets = opts.weakSets || (opts.weakSets = []);
this.jobs = void 0;
}
/**
* Invokes write recursively for nested values
* @param value - value to write
* @param parent - container for the value output
* @param key - either name of a field if parent is an object
* or number index if it is an array
*/
step(
value: any,
parent: JSONArray | JSONObject,
key: number | string
): JSONValue {
let descriptor = getValueDescriptor(value);
if (!descriptor) {
const { opts } = this;
if (opts.warnIgnored && opts.verbose) showStack(this, key, value);
if (!opts.ignore)
throw new TypeError(
`not serializable value "${value}" at "${key}"(${debCtx}) of "${parent}"`
);
// tslint:disable-next-line
if (opts.warnIgnored && savedConsole.warn && !opts.verbose) {
// tslint:disable-next-line
savedConsole.warn(
`not serializable value "${value}" at "${key}"(${debCtx}) of "${parent}"`
);
}
if (opts.ignore === true) return NotSerializableToken;
if (opts.ignore === "opaque") {
descriptor =
typeof value === "object" || typeof value === "function"
? regOpaqueObject(value)
: regOpaquePrim(value);
} else if (opts.ignore === "placeholder") {
descriptor = NotSerializablePlaceholderDescriptor;
} else
throw new TypeError(
`unsupported value for ignore option = ${opts.ignore}`
);
}
if (descriptor) {
return descriptor.write(this, value, parent, key);
}
return {};
}
}
(<any>WriteContext.prototype).showStack = function (
key: string | number,
value: any
) {
showStack(this, key, value);
};
const undef = { _undef: true };
/**
* An object passed to Descriptor's `read` method to support recursive invocation
* for nested values
*/
export class ReadContext {
symsByName?: Map<string, SymbolDescr[]>;
knownSyms: Map<symbol, SymbolDescr>;
sharedJsons: JSONValue[];
sharedVals: any[];
sharedDescriptors: Descriptor[];
opts: ReadOptions;
constructor(opts: ReadOptions, sharedJsons: JSONValue[]) {
this.knownSyms = opts.knownSyms || (opts.knownSyms = new LocMap());
this.symsByName = opts.symsByName || (opts.symsByName = new LocMap());
this.opts = opts;
const len = sharedJsons.length;
this.sharedJsons = sharedJsons;
this.sharedVals = opts.refs || (opts.refs = Array(len).fill(undef));
this.sharedDescriptors = Array(len);
}
/**
* Invokes read recursively for nested values
* @param json - value to read
*/
step(json: JSONValue): any {
return getJsonDescriptor(this, json).read(this, json);
}
/**
* Invokes create recursively for nested values.
* @param json - value to read
*/
createStep(json: JSONValue) {
return getJsonDescriptor(this, json).create(this, json);
}
}
function defaultWrite<T>(
this: Descriptor<T>,
ctx: WriteContext,
value: T
): JSONValue {
const json: JSONObject = {};
if (this.valuePrototype !== void 0) return json;
const proto = savedObject.getPrototypeOf(value);
if (proto === ObjectConstr.prototype || proto === this.defaultPrototype)
return json;
// ensuring prototype reference is ahead
json.p = ctx.step(proto, json, "p");
return json;
}
function defaultCreate<T>(
this: Descriptor<T>,
ctx: ReadContext,
json: JSONValue
): T {
if (this.valueConstructor) return new this.valueConstructor();
if (this.valuePrototype !== void 0 && this.valuePrototype !== false)
return savedObject.create(this.valuePrototype);
const protoJson = <JSONObject>(<JSONObject>json).p;
if (protoJson === void 0)
return <T>(
(this.defaultPrototype ? savedObject.create(this.defaultPrototype) : {})
);
if (protoJson === null) return savedObject.create(null);
let protoValue;
// TODO: since prototypes cannot be cyclic it could ensure this
// on proper ordering objects in `r`, this way there are no needs
// for `Object.setPrototype`
if (protoJson.r != null) {
protoValue = ctx.sharedVals[<number>protoJson.r];
if (protoValue === undef) protoValue = null;
} else if (protoJson.$ && !protoJson.f) protoValue = ctx.step(protoJson);
return savedObject.create(protoValue || null);
}
/**
* default implementaiton of {@link Descriptor}
*/
export const descriptorTemplate: Descriptor = {
read: defaultRead,
write: defaultWrite,
create: defaultCreate,
readContent(ctx: ReadContext, json: JSONValue, value: any) {
if ((<JSONObject>json).p && savedObject.getPrototypeOf(value) === null) {
savedObject.setPrototypeOf(value, ctx.step((<JSONObject>json).p));
}
}
};
/**
* Enhances descriptor by adding reference handling. It some value is referenced
* in more than one sub-value it will have a unique value id instead of the
* value in the output.
*/
function refAwareDescriptor<T>(descriptor: Descriptor<T>): Descriptor<T> {
return savedObject.assign({}, descriptor, {
name: descriptor.name,
read(ctx: ReadContext, json: JSONValue) {
const ref = <number>(<JSONObject>json).r;
if (ref != null) {
const res = this.create(ctx, json);
this.readContent(ctx, json, res);
return res;
}
return descriptor.read(ctx, json);
},
write(
ctx: WriteContext,
value: any,
parent: JSONArray | JSONObject,
index: string | number
): JSONValue {
let info = ctx.sharedRefsMap.get(value);
if (info == null) {
ctx.sharedRefsMap.set(
value,
(ctx.jobs = info = {
ref: null,
data: null,
parent,
value,
descriptor,
index,
nextJob: ctx.jobs,
started: false,
debCtx
})
);
ctx.jobs = info;
if (!ctx.opts.alwaysByRef) return null;
}
if (info.ref == null) info.ref = {};
return info.ref;
},
create(ctx: ReadContext, json: JSONValue): T {
const ref = <number>(<JSONObject>json).r;
if (ref != null) {
const value = ctx.sharedVals[ref];
if (value !== undef) return value;
return (ctx.sharedVals[ref] = ctx.sharedDescriptors[ref].create(
ctx,
ctx.sharedJsons[ref]
));
}
return descriptor.create(ctx, json);
},
readContent(ctx: ReadContext, json: JSONValue, value: any) {
if ((<JSONObject>json).r != null) return;
descriptor.readContent(ctx, json, value);
}
});
}
/**
* Adds a descriptor to an internal global registry for creating value instances
* by type names on reading.
*
* The name will be changed to a unique value if some other descriptor with the
* same name is already registered.
*
* Adds missed functionality into the descriptor. This includes:
* - This includes reference awareness (if `descriptor.refAware !== false`)
* - Saving object's properties (if `descriptor.props !== false`)
* - Default methods (`read` from `create` and `readContent`)
* - Adding "$" property (if `descriptor.default$ !== false`)
*
* @param descriptor
* @returns
*/
export function regDescriptor<T>(
descriptor: IncompleteDescriptor<T>
): Descriptor<T> {
let {
read: readImpl,
readContent: readContentImpl,
create: createImpl,
write: writeImpl
} = descriptor;
if (!readImpl) {
if (descriptor.create)
readImpl = descriptor.readContent ? defaultRead : descriptor.create;
}
if (
!descriptor.defaultPrototype &&
descriptor.props !== false &&
descriptor.propsSnapshot !== false &&
descriptor.value
)
descriptor.defaultPrototype = savedObject.getPrototypeOf(descriptor.value);
const overrideProps = savedObject.assign(
{},
defaultOverrideProps,
descriptor.typeofHint === "function" && funcOverrideProps,
descriptor.overrideProps
);
if (!readContentImpl) readContentImpl = function readContent() {};
if (!readImpl)
readImpl = function readCreate(
this: ReadDescriptor<T>,
ctx: ReadContext,
json: JSONValue
): T {
return this.create(ctx, json);
};
if (!createImpl) createImpl = descriptorTemplate.create;
if (!writeImpl)
writeImpl = function noWrite(_: WriteContext, val: any): any {
throw new TypeError(`not writable ${val}`);
};
const name = guessDescriptorName(descriptor);
let uniq = name;
let i = 0;
if (!descriptor.strictName)
for (; descriptorByName.get(uniq) != null; uniq = `${name}_${++i}`) {}
let final: Descriptor = savedObject.assign({}, descriptor, {
read: readImpl,
readContent: readContentImpl,
create: createImpl,
write: writeImpl,
name: uniq,
overrideProps
});
if (descriptor.props !== false) final = propsDescriptor(final);
if (descriptor.default$ !== false && uniq !== "Object") {
const saved = final;
final = savedObject.assign({}, final, {
write(
ctx: WriteContext,
val: any,
parent: JSONObject | JSONArray,
index: number | string
): JSONValue {
const json = <JSONObject>saved.write(ctx, val, parent, index);
if (!json.$) json.$ = uniq;
return json;
}
});
}
const noRefs = final;
descriptorByName.set(uniq, noRefs);
if (descriptor.typeofTag)
descriptorByTypeOfProp.set(descriptor.typeofTag, noRefs);
if (descriptor.refAware !== false) final = refAwareDescriptor(final);
final = {
name: uniq,
read: final.read,
write: final.write,
readContent: final.readContent,
create: final.create,
overrideProps,
value: descriptor.value,
props: descriptor.props,
default$: descriptor.default$,
snapshot: final.snapshot
};
return final;
}
/**
* updates `snapshot` with the current values of its properties
*
* @param value - an object registered by `regOpaqueObject` before
*/
export function updateInitialSnapshot(value: any) {
const descriptor = getValueDescriptor(value);
if (!descriptor) throw new TypeError("not serializable value");
if (!descriptor.snapshot || !descriptor.value || descriptor.value !== value)
throw new TypeError("the object doesn't contain another snapshot");
savedObject.assign(
descriptor.snapshot,
savedObject.getOwnPropertyDescriptors(value)
);
}
/**
* Tries to derive name for the `value`
*
* @param value
*/
function guessObjectName(value: any): string {
return (
value.name || (value.constructor && value.constructor.name) || "Object"
);
}
/**
* Tries to derive name for the `descriptor`.
*
* @param descriptor
*/
function guessDescriptorName(descriptor: DescriptorOpts): string {
if (descriptor.name) return descriptor.name;
if (descriptor.valuePrototype && (<any>descriptor.valuePrototype).name)
return (<any>descriptor.valuePrototype).name;
if (descriptor.valueConstructor && descriptor.valueConstructor.name)
return descriptor.valueConstructor.name;
if (
descriptor.valuePrototype &&
descriptor.valuePrototype.constructor &&
descriptor.valuePrototype.constructor.name
)
return descriptor.valuePrototype.constructor.name;
return "Object";
}
/**
* This function registers `value` as opaque. The library outputs names instead
* of stored data for them. The values should be registered with the same name
* on writing and reading sides.
*
* @param value
* @param name
* @param props - should the properties of the object be output too
*/
export function regOpaqueObject(
value: any,
name: string = guessObjectName(value),
descriptor: IncompleteDescriptor<any> = { props: true, propsSnapshot: true }
): Descriptor {
if (!value) return <any>null;
let descr: Descriptor | undefined;
if ((descr = descriptorByObject.get(value)) != null) return descr;
descr = regDescriptor(
savedObject.assign(
{},
OpaqueDescriptor,
{ name, typeofHint: typeof value },
descriptor,
{ value }
)
);
weakMapSet.call(descriptorByObject, value, descr);
return descr;
}
/**
* Same as `regOpaqueObject` but for non-object types, uses `Map` registry instead of `WeakMap`
* @see regOpaqObject
*/
export function regOpaquePrim<T>(
value: T,
name: string = String(value)
): Descriptor<T> {
let descriptor = descriptorByValue.get(value);
if (descriptor) return descriptor;
descriptor = regDescriptor(
savedObject.assign({}, OpaquePrimDescriptor, {
name,
value,
refAware: false
})
);
descriptorByValue.set(value, descriptor);
return descriptor;
}
export function regPrim<T>(
descriptor: Descriptor<T>,
value: any,
name: string = String(value)
) {
descriptor = regDescriptor(
savedObject.assign({}, descriptor, { name, value, refAware: false })
);
descriptorByValue.set(value, descriptor);
return descriptor;
}
/**
* Registers `prototype` of `constructor` as opaque value and use it
* as the value's type in output.
* into a prototype.
*
* @see regOpaqueObject
* @param constructor - plain JS constructor function or class
* @param descriptor
*/
export function regConstructor<T>(
constr: ValueConstructor<T>,
descriptor: IncompleteDescriptor<T> = {},
inherit?: boolean
): Descriptor<T> {
const descr = regDescriptor(
savedObject.assign(
{ valuePrototype: constr.prototype, name: constr.name },
descriptorTemplate,
descriptor,
{
overrideProps: savedObject.assign({}, descriptor.overrideProps),
propsSnapshot: descriptor.propsSnapshot
}
)
);
if (inherit)
savedObject.defineProperty(constr.prototype, descriptorSymbol, {
value: descr,
configurable: true
});
else weakMapSet.call(descriptorByPrototype, constr.prototype, descr);
return descr;
}
export const NotSerializableDescriptor = regDescriptor({
name: "NotSerializableToken",
read() {
throw new TypeError("Trying to use not serializable value");
},
create() {},
readContent() {},
write(): JSONValue {
return NotSerializableToken;
},
props: false,
refAware: false,
default$: false
});
const NotSerializablePlaceholderDescriptor = regDescriptor({
name: "NotSerializable",
read: notSerializableRead,
create: notSerializableRead,
readContent() {},
write(): JSONValue {
return {};
},
props: false,
refAware: false
});
function notSerializableRead(this: Descriptor) {
if (this.name === "NotSerializable") return notSerializablePlaceholder;
const res: any = function () {};
weakMapSet.call(descriptorByObject, res, this);
return new Proxy(res, notSerializableTraps);
}
/** same as `regConstructor` but it also uses `constr` with new to build the object */
export function regNewConstructor<T>(
constr: ValueConstructor<T>,
descriptor: IncompleteDescriptor<T> = {}
): Descriptor {
return regConstructor(
constr,
savedObject.assign(
{ valueConstructor: constr },
descriptorTemplate,
descriptor
)
);
}
const PojsoDescriptor = regDescriptor({
...descriptorTemplate,
name: "Object"
});
export const PrimDescriptor: Descriptor = regDescriptor({
name: "Prim",
read(_: ReadContext, json: JSONValue): any {
return json;
},
create(_: ReadContext, json: JSONValue): any {
return json;
},
write(_: WriteContext, value: any): JSONValue {
return value;
},
refAware: false,
props: false,
default$: false
});
const RefDescriptor: Descriptor = regDescriptor({
name: "Ref",
read(ctx: ReadContext, json: JSONValue): any {
return ctx.sharedVals[<number>(<JSONObject>json).r];
}
});
export const NotSerializableToken = { _notSerializable: true };
function writeProp(
ctx: WriteContext,
info: JSONArray,
descr: PropertyDescriptor,
flags: number
): JSONArray | undefined {
if ((flags & 8) === 0) {
const valueJson = ctx.step(descr.value, info, 1);
if (valueJson === NotSerializableToken) return;
info.push(valueJson);
} else {
info.push(null);
}
if (flags || descr.set || descr.get) info.push(flags);
if (descr.get) info[3] = ctx.step(descr.get, info, 3);
if (descr.set) info[4] = ctx.step(descr.set, info, 4);
return info;
}
function descrFlags(descr: PropertyDescriptor): number {
let flags = 0;
if (!descr.configurable) flags = flags | 1;
if (!descr.enumerable) flags = flags | 2;
if (!descr.writable) flags = flags | 4;
if (!("value" in descr)) {
flags = flags | 8;
}
return flags;
}
function propFlags(
snapshot: { [name: string]: PropertyDescriptor } | undefined,
pred: { [name: string]: boolean },
name: string,
descr: PropertyDescriptor,
mask: number
): number | undefined {
let flags: number | undefined;
if (pred[name] === false || ((flags = descrFlags(descr)) & mask) !== 0)
return void 0;
if (snapshot) {
const init = snapshot[name];
if (
init &&
(("value" in init && Object.is(init.value, descr.value)) ||
("get" in init && init.get === descr.get))
)
return void 0;
}
return flags;
}
/** Writing serialized `Object.defineProperty` descriptors to JSON */
export function writeProps(
ctx: WriteContext,
descrs: { [name: string]: PropertyDescriptor },
pred: { [name: string]: boolean },
mask: number,
snapshot?: { [name: string]: PropertyDescriptor }
) {
const props = [];
let flags: number;
for (const name of savedObject.getOwnPropertyNames(descrs)) {
const descr = descrs[name];
// TODO: check why with jest + jsdom this sometimes returns `undefined`
if (!descr) continue;
if (
(flags = <number>propFlags(snapshot, pred, name, descr, mask)) === void 0
)
continue;
debCtx = name;
const propInfo = writeProp(ctx, [name], descr, flags);
if (propInfo) props.push(propInfo);
}
for (const name of savedObject.getOwnPropertySymbols(descrs)) {
const descr = descrs[<any>name];
if (
(flags = <number>propFlags(snapshot, pred, <any>name, descr, mask)) ===
void 0
)
continue;
debCtx = name;
const propJson: JSONArray = [];
const sym = writeSym(
ctx,
name,
propJson,
0,
!ctx.opts.ignore && !ctx.knownSyms
);
if (sym === NotSerializableToken) continue;
propJson.push(sym);
writeProp(ctx, propJson, descr, flags);
if (propJson.length) props.push(propJson);
}
debCtx = null;
return props;
}
function readPropName(ctx: ReadContext, key: any): any {
let name: any;
if (key.substr) {
name = key;
} else if (key.$) {
const descr = descriptorByName.get(key.$);
if (descr) name = descr.read(ctx, key);
}
if (!name) name = readSym(ctx, key);
return name;
}
function readPropDescriptor(
ctx: ReadContext,
pjson: JSONValue,
flags: number,
get: JSONValue,
set: JSONValue,
pdescr: PropertyDescriptor
): PropertyDescriptor {
pdescr.configurable = (flags & 1) === 0;
pdescr.enumerable = (flags & 2) === 0;
if ((flags & 4) === 0) pdescr.writable = true;
if ((flags & 8) === 0) pdescr.value = ctx.step(pjson);
if (get) pdescr.get = ctx.step(get);
if (set) pdescr.set = ctx.step(set);
weakMapSet.call(descriptorByObject, pdescr, PropertyDescriptorDescriptor);
return pdescr;
}
/** Reading serialized `Object.defineProperty` descriptors from JSON */
export function readProps<T>(ctx: ReadContext, props: any[], value: T) {
for (const [key, pjson, flags, get, set] of props) {
const name = readPropName(ctx, key);
if (flags != null) {
const pdescr = readPropDescriptor(ctx, pjson, flags, get, set, {});
try {
savedObject.defineProperty(value, name, pdescr);
continue;
} catch (e) {
const sdescr = savedObject.getOwnPropertyDescriptor(value, name);
if (!sdescr || sdescr.configurable || !sdescr.writable) throw e;
}
}
(<any>value)[name] = ctx.step(pjson);
}
}
/** A descriptor for `Object.getOwnPropertyDescriptors` object */
export const ObjectPropertiesDescriptor = {
write(ctx: WriteContext, value: any): JSONValue {
return {
f: writeProps(ctx, value, defaultOverrideProps, 0)
};
},
create() {
return {};
},
readContent(ctx: ReadContext, json: JSONValue, value: any) {
for (const [key, pjson, flags, get, set] of (<any>json).f) {
value[readPropName(ctx, key)] = readPropDescriptor(
ctx,
pjson,
flags,
get,
set,
{}
);
}
}
};
/** wraps descriptor by adding its own property into the saved dictionary */
function propsDescriptor<T>(descriptor: Descriptor<T>): Descriptor<T> {
const pred = descriptor.overrideProps || defaultOverrideProps;
let snapshot: any;
if (
descriptor.props !== false &&
descriptor.propsSnapshot !== false &&
descriptor.value
) {
snapshot = savedObject.getOwnPropertyDescriptors(descriptor.value);
}
return {
name: descriptor.name,
write(
ctx: WriteContext,
value: T,
parent: JSONArray | JSONObject,
index: number | string
): JSONValue {
const json = <JSONObject>descriptor.write(ctx, value, parent, index);
const props = writeProps(
ctx,
savedObject.getOwnPropertyDescriptors(value),
pred,
descriptor.propsDescrMask || 0,
this.snapshot
);
if (props.length) json.f = props;
return json;
},
read: defaultRead,
readContent(ctx: ReadContext, json: JSONValue, value: T) {
descriptor.readContent(ctx, json, value);
const props = <JSONArray>(<JSONObject>json).f;
if (props) readProps(ctx, props, value);
},
create(ctx, json) {
return descriptor.create(ctx, json);
},
snapshot
};
}
function defaultRead<T>(
this: ReadDescriptor<T>,
ctx: ReadContext,
json: JSONValue
): T {
const value = this.create(ctx, json);
this.readContent(ctx, json, value);
return value;
}
const OpaqueDescriptor: IncompleteDescriptor<any> = {
write(ctx, value): JSONValue {
if (value !== this.value || !this.name)
return defaultWrite.call(<any>this, ctx, value); // PojsoPropsDescriptor.write(ctx, value, par, index);
return { $: this.name };
},
create(): any {
return this.value;
},
default$: false
};
const OpaquePrimDescriptor: IncompleteDescriptor<any> = {
...OpaqueDescriptor,
props: false
};
function writeSym(
ctx: WriteContext,
sym: symbol,
parent: JSONArray | JSONObject,
index: number | string,
ignore?: boolean
): JSONValue {
const key = Symbol.keyFor(sym);
if (key) return { key };
const global = descriptorByValue.get(sym);
if (global) return global.write(ctx, sym, parent, index);
if (!ignore && ctx.knownSyms) {
let descr = ctx.knownSyms.get(sym);
if (!descr) {
if (!ctx.symsByName)
throw new TypeError(`couldn't write "${String(sym)}"`);
let name = sym.description;
if (!name) {
const text = String(sym);
name = text.substring(7 /*"Symbol("*/, text.length - 1);
}
let tup = ctx.symsByName.get(name);
if (!tup) ctx.symsByName.set(name, (tup = []));
descr = { name, id: tup.length, value: sym };
tup.push(descr);
ctx.knownSyms.set(sym, descr);
}
const res: JSONObject = { name: descr.name };
if (descr.id) res.id = descr.id;
return res;
}
if (!ignore && !ctx.opts.ignore)
throw new TypeError(`couldn't write "${String(sym)}"`);
return NotSerializableToken;
}
export const undefinedSymbol = Symbol("@effectful/serialization/undefined");
interface SymbolDescr {
name: string;
id: number;
value: symbol;
}
function readSym(ctx: ReadContext, json: JSONValue): symbol {
if ((<JSONObject>json).key) return Symbol.for(<string>(<JSONObject>json).key);
const { name } = <JSONObject>json;
if (name && ctx.symsByName) {
let local = ctx.symsByName.get(<string>name);
const id = <number>(<JSONObject>json).id || 0;
if (local) {
const descr = local[id];
if (descr) return descr.value;
}
// creating new symbols
const descr = {
name: <string>name,
id,
value: Symbol(<string>(<JSONObject>json).name)
};
if (!local) ctx.symsByName.set(<string>name, (local = []));
local[id] = descr;
if (ctx.knownSyms) ctx.knownSyms.set(descr.value, descr);
return descr.value;
}
if (!ctx.opts.ignore)
throw new TypeError(`couldn't read "${JSON.stringify(json)}"`);
return undefinedSymbol;
}
function specValueDescriptor<T>(name: string, value: T): Descriptor<T> {
return regDescriptor({
name,
write(): JSONValue {
return { $: name };
},
create(): any {
return value;
},
refAware: false,
props: false,
default$: false
});
}
const NaNDescriptor = specValueDescriptor("NaN", NaN);
const UndefDescriptor = specValueDescriptor("undefined", void 0);
const SymbolDescriptor = regDescriptor<symbol>({
write: writeSym,
read: readSym,
name: "Symbol",
refAware: false,
props: false
});
export const BigIntDescriptor =
typeof BigInt === "function"
? regDescriptor({
read(_: ReadContext, json: JSONValue): BigInt {
return BigInt(<number>(<JSONObject>json).int);
},
write(_: WriteContext, value: BigInt) {
return { int: value.toString() };
},
name: "Int",
refAware: false,
props: false
})
: regDescriptor({
name: "Int",
read(_: ReadContext, json: JSONValue): number {
return <number>(<JSONObject>json).int;
},
write(_: WriteContext, value: number): JSONValue {
return { int: String(value) };
},
refAware: false,
props: false
});
export let getObjectDescriptor: (
value: any
) => Descriptor | undefined = function getObjectDescriptorImpl<
T extends WithTypeofTag
>(value: T): Descriptor<T> | undefined {
let descriptor = descriptorByObject.get(value);
if (descriptor) return descriptor;
const proto = savedObject.getPrototypeOf(value);
descriptor = descriptorByPrototype.get(proto);
if (descriptor) return descriptor;
if (proto && proto !== Object && descriptorSymbol in proto)
return (<any>proto)[descriptorSymbol];
if (value.$$typeof) descriptor = descriptorByTypeOfProp.get(value.$$typeof);
return descriptor;
};
export function regObjectDescriptorGetter(
impl: (value: any) => Descriptor | undefined
) {
getObjectDescriptor = impl;
}
export let getValueDescriptor: (
value: any
) => Descriptor | undefined = function getValueDescriptorImpl(
value: any
): Descriptor | undefined {
if (value === void 0) return UndefDescriptor;
switch (typeof value) {
case "number":
if (isNaN(value)) return NaNDescriptor;
case "undefined":
case "boolean":
case "string":
return PrimDescriptor;
case "object":
if (!value) return PrimDescriptor;
return getObjectDescriptor(value) || PojsoDescriptor;
case "function":
return getObjectDescriptor(value);
case "symbol":
return SymbolDescriptor;
case "bigint":
return BigIntDescriptor;
}
return descriptorByValue.get(value);
};
export function regValueDescriptorGetter(
impl: (value: any) => Descriptor | undefined
) {
getValueDescriptor = impl;
}
export function getJsonDescriptor(
ctx: ReadContext,
json: JSONValue
): Descriptor {
if (typeof json !== "object" || json === null) return PrimDescriptor;
if (Array.isArray(json)) return ArrayDescriptor;
if ("$" in json) {
const descriptor = descriptorByName.get(<string>json.$);
if (!descriptor) {
if (ctx.opts.warnIgnored)
// tslint:disable-next-line
console.warn(
`reading value with not registered type "${json.$}"`,
json
);
if (!ctx.opts.ignore)
throw new TypeError(`not registered type:${json.$}`);
if (ctx.opts.ignore === "placeholder")
return regDescriptor(
savedObject.assign({}, NotSerializablePlaceholderDescriptor, {
name: <string>json.$
})
);
return UndefDescriptor;
}
return descriptor;
}
if ("r" in json) return RefDescriptor;
return PojsoDescriptor;
}
// TODO: holes
const ArrayDescriptor = regNewConstructor(Array, {
...descriptorTemplate,
write(ctx: WriteContext, value: unknown[]): JSONArray {
const json: JSONArray = [];
for (const i of value) json.push(ctx.step(i, json, json.length));
return json;
},
readContent(ctx: ReadContext, json: JSONValue, value: unknown[]) {
for (const i of <JSONArray>json) value.push(ctx.step(i));
},
props: false,
default$: false,
globalName: "Array"
});
function iterableDescriptor<T extends Iterable<unknown>>(
descriptor: IncompleteDescriptor<T>
): IncompleteDescriptor<T> {
return savedObject.assign(
{},
descriptorTemplate,
{
write(
this: Descriptor,
ctx: WriteContext,
value: Iterable<unknown>
): JSONValue {
const json: JSONArray = [];
for (const i of value) json.push(ctx.step(i, json, json.length));
return { $: this.name || "Iterable", l: json };
}
},
descriptor
);
}
export const WeakSetWorkaround = class WeakSet {
prop: symbol;
constructor() {
this.prop = Symbol("@effectful/weakset");
}
add(value: any) {
switch (typeof value) {
case "function":
case "object":
savedObject.defineProperty(value, this.prop, {
configurable: true,
writable: true,
value: true
});
break;
default:
throw TypeError("Invalid value used in weak set");
}
return this;
}
delete(value: any) {
if (!value[this.prop]) return false;
delete value[this.prop];
return true;
}
has(value: any) {
return !!value[this.prop];
}
};
export const WeakMapWorkaround = class WeakMap {
prop: symbol;
constructor() {
this.prop = Symbol("@effectful/weakmap");
}
set(key: any, value: any) {
switch (typeof key) {
case "function":
case "object":
savedObject.defineProperty(key, this.prop, {
configurable: true,
writable: true,
value
});
break;
default:
throw TypeError("Invalid value used in weak map");
}
return this;
}
get(key: any) {
return key[this.prop];
}
delete(key: any) {
if (!key[this.prop]) return false;
delete key[this.prop];
return true;
}
has(value: any) {
return Object.prototype.hasOwnProperty.call(value, this.prop);
}
};
regConstructor(WeakSetWorkaround, { name: "WeakSet#" });
regConstructor(WeakMapWorkaround, { name: "WeakMap#" });
const weakSetAdd = WeakSet.prototype.add;
export const WeakSetDescriptor = regConstructor(WeakSet, {
name: "WeakSet",
write(ctx, value) {
const res = { v: [] };
ctx.weakSets.push([value, res]);
return res;
},
create() {
return new WeakSet();
},
readContent(ctx, json, value) {
const { v } = <any>json;
for (const i of v) weakSetAdd.call(value, ctx.step(i));
}
});
export const WeakMapDescriptor: IncompleteDescriptor<WeakMap<any, any>> = {
name: "WeakMap",
write(ctx, value) {
const k: any[] = [];
const v: any[] = [];
const res = { k, v };
for (const i of ctx.sharedRefsMap.values()) {
if (value.has(i.value)) {
k.push(ctx.step(i.value, k, k.length));
v.push(ctx.step(value.get(i.value), v, v.length));
}
}
ctx.weakMaps.push([value, res]);
return res;
},
create() {
return new WeakMap();
},
readContent(ctx, json, value) {
const { k, v } = <any>json;
for (let i = 0, len = k.length; i < len; ++i)
weakMapSet.call(value, ctx.step(k[i]), ctx.step(v[i]));
}
};
regConstructor(WeakMap, WeakMapDescriptor);
regNewConstructor<Set<unknown>>(
LocSet,
iterableDescriptor({
readContent(ctx: ReadContext, json: JSONValue, value: Set<unknown>) {
for (const i of <JSONArray>(<JSONObject>json).l) value.add(ctx.step(i));
},
globalName: "Set"
})
);
regNewConstructor(
LocMap,
iterableDescriptor({
write(ctx: WriteContext, value: Map<unknown, unknown>): JSONObject {
const k: JSONArray = [];
const v: JSONArray = [];
for (const [ki, vi] of value) {
k.push(ctx.step(ki, k, k.length));
v.push(ctx.step(vi, v, v.length));
}
return { k, v };
},
readContent(
ctx: ReadContext,
json: JSONValue,
value: Map<unknown, unknown>
) {
const { k, v } = <JSONObject>json;
for (let i = 0, len = (<JSONArray>k).length; i < len; ++i)
value.set(ctx.step((<JSONArray>k)[i]), ctx.step((<JSONArray>v)[i]));
},
globalName: "Map"
})
);
regNewConstructor(RegExp, {
name: "RegExp",
write(_: WriteContext, value: RegExp): JSONObject {
const json: JSONObject = { src: value.source, flags: value.flags };
if (value.lastIndex) json.last = value.lastIndex;
return json;
},
create(_: ReadContext, json: JSONValue): RegExp {
const value = new RegExp(
<string>(<JSONObject>json).src,
<string>(<JSONObject>json).flags
);
if ((<JSONObject>json).last)
value.lastIndex = <number>(<JSONObject>json).last;
return value;
},
props: false,
refAware: false,
globalName: "RegExp"
});
/**
* registers an object as opaque along with all other
* values accessible from this object
*/
export function regOpaqueRec(
value: any,
prefix: string = value.constructor.name,
opts: {
deep?: boolean;
descriptor?: IncompleteDescriptor<any>;
} = {}
) {
if (
!value ||
!(typeof value === "function" || typeof value === "object") ||
descriptorByObject.has(value)
)
return;
const descrs = savedObject.getOwnPropertyDescriptors(value);
for (const i of savedObject.getOwnPropertySymbols(descrs)) {
reg(descrs[<any>i], `${prefix}#${String(i)}`);
}
regOpaqueObject(value, prefix, opts.descriptor || { props: false });
for (const i of savedObject.getOwnPropertyNames(descrs))
reg(descrs[i], `${prefix}#${i}`);
if (opts.deep) {
const proto = savedObject.getPrototypeOf(value);
if (proto) regOpaqueRec(proto, `${prefix}#proto`, opts);
}
function reg(descr: PropertyDescriptor, name: string) {
const val = descr.value;
if (!val) return;
const ty = typeof val;
if (ty === "function" || ty === "object") {
if (opts.deep) {
regOpaqueRec(val, name, opts);
} else {
regOpaqueObject(val, name, opts.descriptor);
}
} else if (ty === "symbol" && Symbol.keyFor(val) == null)
regOpaquePrim(val, `${prefix}#${name}#${String(val)}`);
}
}
/**
* Opaque object will be added automatically if not known object built with
* `constr` is encountered when writing.
*/
export function regAutoOpaqueConstr(constr: any, silent?: boolean) {
return (constr.prototype[descriptorSymbol] = {
write(
ctx: WriteContext,
value: any,
parent: any,
index: string | number
): JSONValue {
let name = constr.name;
if (value.name) name += `:${value.name}`;
else if (value.constructor !== constr) name += value.constructor.name;
// tslint:disable-next-line
if (!silent && console.warn) {
showStack(ctx, name, value);
// tslint:disable-next-line
console.warn("auto opaque", name, value, new Error().stack);
}
return regOpaqueObject(value, name).write(ctx, value, parent, index);
}
});
}
export function rebindGlobal() {
if (descriptorByObject.has(global)) return;
const oldState = state;
ObjectConstr = (<any>global).Object;
state = <State>{
byName: new LocMap(),
byValue: new LocMap(state.byValue),
byObject: state.byObject,
byTypeOfProp: new LocMap(state.byTypeOfProp)
};
(<any>global).__effectfulSerializationState = {};
for (let [name, descriptor] of oldState.byName) {
if (descriptor.globalName) {
const value = (<any>global)[descriptor.globalName];
if (!value) continue;
descriptor = savedObject.assign({}, descriptor, { value });
weakMapSet.call(descriptorByObject, value, descriptor);
}
state.byName.set(name, descriptor);
}
state = initializeState(__effectfulSerializationState);
}
/**
* Monkey patching platform objects to make them serializable,
* run it as soon as possible if a global serialization is needed
*/
export function regGlobal() {
if (descriptorByObject.has(global)) return;
regOpaqueObject(<any>global, "#global", {
props: true,
propsSnapshot: true,
overrideProps: { AnonymousContent: false }
});
for (const name of savedObject.getOwnPropertyNames(global)) {
try {
const obj = (<any>global)[name];
if (!obj) continue;
if (typeof obj !== "function" && typeof obj !== "object") continue;
if (name === "location") {
regOpaqueObject((<any>global).location, "location", { props: false });
continue;
}
const descr = descriptorByObject.get(obj);
if (descr && descr.props === false) continue;
regOpaqueObject(obj, `#${name}`);
for (const i of savedObject.getOwnPropertyNames(obj)) {
// not registering prototypes to avoid unintended descriptor's inheritance
if (i === "prototype") continue;
const descr = <any>savedObject.getOwnPropertyDescriptor(obj, i);
if (typeof descr.value !== "function") continue;
regOpaqueObject(descr.value, `#G#${name}#{j}`);
}
if (typeof obj === "function" && obj.prototype) {
for (const j of savedObject.getOwnPropertyNames(obj.prototype)) {
if (j === "prototype") continue;
const descr = <any>(
savedObject.getOwnPropertyDescriptor(obj.prototype, j)
);
if (typeof descr.value !== "function") continue;
regOpaqueObject(descr.value, `#G##${name}#{j}`);
}
}
} catch (e) {
continue;
}
}
}
regOpaquePrim(boundThisSymbol, "#this");
regOpaquePrim(boundArgsSymbol, "#args");
regOpaquePrim(boundFunSymbol, "#fun");
const notSerializableTraps: any = {};
for (const i of [
"apply",
"construct",
"defineProperty",
"deleteProperty",
"enumerate",
"getOwnPropertyDescriptor",
"getPrototypeOf",
"has",
"isExtensible",
"ownKeys",
"preventExtensions",
"set",
"setPrototypeOf"
]) {
notSerializableTraps[i] = function (target: any) {
const descriptor = descriptorByObject.get(target);
throw new TypeError(
`${i} in a not restored object${
descriptor ? ` (${descriptor.name})` : ""
}`
);
};
}
notSerializableTraps.get = function (target: any, prop: any) {
const descriptor = descriptorByObject.get(target);
throw new TypeError(
`getting ${prop} in a not restored object${
descriptor ? ` (${descriptor.name})` : ""
}`
);
};
/** an object which is replaces all not serializable values after read */
const notSerializablePlaceholder: any = new Proxy(function () {},
notSerializableTraps);
/** shorter format for properties descriptors */
export const PropertyDescriptorDescriptor = regDescriptor({
read(_ctx: ReadContext, _json: JSONValue): PropertyDescriptor {
return {};
},
readContent(ctx: ReadContext, json: JSONValue, value: PropertyDescriptor) {
readPropDescriptor(
ctx,
(<any>json).v,
(<any>json).f || 0,
(<any>json).s,
(<any>json).g,
value
);
},
write(ctx: WriteContext, value: PropertyDescriptor) {
const res = writeProp(ctx, [], value, descrFlags(value));
if (!res) return {};
return <any>{ v: res[0], f: res[1], s: res[2], g: res[3] };
},
name: "PD",
props: false
});
regConstructor(String, {
create(_ctx, json) {
return new String((<any>json).v);
},
write(_ctx, value: String) {
return { v: String(value) };
}
});
regConstructor(Number, {
create(_ctx, json) {
return new Number((<any>json).v);
},
write(_ctx, value: Number) {
return { v: Number(value) };
}
});
if (typeof ArrayBuffer !== "undefined") {
const { encode, decode } = <any>require("base64-arraybuffer");
const ArrayBufferDescr = regConstructor(ArrayBuffer, {
name: "ArrayBuffer",
write(_ctx, value: ArrayBuffer) {
return { d: encode(value) };
},
create(_ctx, json) {
return decode((<any>json).d);
},
props: false
});
for (const name of [
"DataView",
"Int8Array",
"Uint8Array",
"Uint8ClampedArray",
"Int16Array",
"Uint16Array",
"Int32Array",
"Uint32Array",
"Float32Array",
"Float64Array",
"BigInt64Array",
"BigUint64Array"
]) {
const Constr = (<any>global)[name];
if (!Constr) continue;
regConstructor(Constr, {
name,
write(ctx, value: any) {
const res: any = { o: value.byteOffset, l: value.length };
res.b = ArrayBufferDescr.write(ctx, value.buffer, res, "b");
return res;
},
create(ctx, json) {
return new Constr(
ArrayBufferDescr.read(ctx, (<any>json).b),
(<any>json).o,
(<any>json).l
);
},
props: false
});
}
} | the_stack |
import { log } from "@ledgerhq/logs";
import shuffle from "lodash/shuffle";
import priorityQueue from "async/priorityQueue";
import { concat, from } from "rxjs";
import { ignoreElements } from "rxjs/operators";
import React, {
useEffect,
useCallback,
useState,
useRef,
useMemo,
} from "react";
import { getVotesCount, isUpToDateAccount } from "../../account";
import type { SubAccount, Account, CryptoCurrency } from "../../types";
import { getAccountBridge } from "..";
import { getAccountCurrency } from "../../account";
import { getEnv } from "../../env";
import type { SyncAction, SyncState, BridgeSyncState } from "./types";
import { BridgeSyncContext, BridgeSyncStateContext } from "./context";
export type Props = {
// this is a wrapping component that you need to put in your tree
children: React.ReactNode;
// you need to inject the accounts to sync on
accounts: Account[];
// provide a way to save the result of an account sync update
updateAccountWithUpdater: (
accountId: string,
updater: (arg0: Account) => Account
) => void;
// handles an error / log / do action with it
// if the function returns falsy, the sync will ignore error, otherwise it's treated as error with the error you return (likely the same)
recoverError: (arg0: Error) => Error | null | undefined;
// track sync lifecycle for analytics
trackAnalytics: (
arg0: string,
arg1: Record<string, any> | null | undefined
) => void;
// load all data needed for a currency (it's calling currencyBridge prepare mechanism)
prepareCurrency: (currency: CryptoCurrency) => Promise<any>;
// provide an implementation of hydrate (it preload from a local storage impl the data cached from a previous prepare)
hydrateCurrency: (currency: CryptoCurrency) => Promise<any>;
// an array of token ids to blacklist from the account sync
blacklistedTokenIds?: string[];
};
export const BridgeSync = ({
children,
accounts,
updateAccountWithUpdater,
recoverError,
trackAnalytics,
prepareCurrency,
hydrateCurrency,
blacklistedTokenIds,
}: Props) => {
useHydrate({
accounts,
hydrateCurrency,
});
const [syncQueue, syncState] = useSyncQueue({
accounts,
prepareCurrency,
recoverError,
trackAnalytics,
updateAccountWithUpdater,
blacklistedTokenIds,
});
const sync = useSync({
syncQueue,
accounts,
});
useSyncBackground({
sync,
});
useSyncContinouslyPendingOperations({
sync,
accounts,
});
return (
<BridgeSyncStateContext.Provider value={syncState}>
<BridgeSyncContext.Provider value={sync}>
{children}
</BridgeSyncContext.Provider>
</BridgeSyncStateContext.Provider>
);
};
// utility internal hooks for <BridgeSync>
// useHydrate: bridge.hydrate once for each currency
function useHydrate({ accounts, hydrateCurrency }) {
const hydratedCurrencies = useRef({});
useEffect(() => {
const hydrated = hydratedCurrencies.current;
for (const account of accounts) {
const { currency } = account;
if (!hydrated[currency.id]) {
hydrated[currency.id] = true;
hydrateCurrency(currency);
}
}
}, [accounts, hydrateCurrency]);
}
const lastTimeAnalyticsTrackPerAccountId: Record<string, number> = {};
const nothingState = {
pending: false,
error: null,
};
// useHydrate: returns a sync queue and bridge sync state
function useSyncQueue({
accounts,
prepareCurrency,
recoverError,
trackAnalytics,
updateAccountWithUpdater,
blacklistedTokenIds,
}) {
const [bridgeSyncState, setBridgeSyncState]: [BridgeSyncState, any] =
useState({});
const setAccountSyncState = useCallback((accountId: string, s: SyncState) => {
setBridgeSyncState((state) => ({ ...state, [accountId]: s }));
}, []);
const synchronize = useCallback(
(accountId: string, next: () => void) => {
const state = bridgeSyncState[accountId] || nothingState;
if (state.pending) {
next();
return;
}
const account = accounts.find((a) => a.id === accountId);
if (!account) {
next();
return;
}
// FIXME if we want to stop syncs for specific currency (e.g. api down) we would do it here
try {
const bridge = getAccountBridge(account);
setAccountSyncState(accountId, {
pending: true,
error: null,
});
const startSyncTime = Date.now();
const trackedRecently =
lastTimeAnalyticsTrackPerAccountId[accountId] &&
startSyncTime - lastTimeAnalyticsTrackPerAccountId[accountId] <
90 * 1000;
if (!trackedRecently) {
lastTimeAnalyticsTrackPerAccountId[accountId] = startSyncTime;
}
const trackEnd = (event) => {
if (trackedRecently) return;
const account = accounts.find((a) => a.id === accountId);
if (!account) return;
const subAccounts: SubAccount[] = account.subAccounts || [];
trackAnalytics(event, {
duration: (Date.now() - startSyncTime) / 1000,
currencyName: account.currency.name,
derivationMode: account.derivationMode,
freshAddressPath: account.freshAddressPath,
operationsLength: account.operationsCount,
accountsCountForCurrency: accounts.filter(
(a) => a.currency === account.currency
).length,
tokensLength: subAccounts.length,
votesCount: getVotesCount(account),
});
if (event === "SyncSuccess") {
subAccounts.forEach((a) => {
const tokenId =
a.type === "TokenAccount"
? getAccountCurrency(a).id
: account.currency.name;
trackAnalytics("SyncSuccessToken", {
tokenId,
tokenTicker: getAccountCurrency(a).ticker,
operationsLength: a.operationsCount,
parentCurrencyName: account.currency.name,
parentDerivationMode: account.derivationMode,
votesCount: getVotesCount(a, account),
});
});
}
};
const syncConfig = {
paginationConfig: {},
blacklistedTokenIds,
};
concat(
from(prepareCurrency(account.currency)).pipe(ignoreElements()),
bridge.sync(account, syncConfig)
).subscribe({
next: (accountUpdater) => {
updateAccountWithUpdater(accountId, accountUpdater);
},
complete: () => {
trackEnd("SyncSuccess");
setAccountSyncState(accountId, {
pending: false,
error: null,
});
next();
},
error: (raw: Error) => {
const error = recoverError(raw);
if (!error) {
// This error is normal because the thread was recently killed. we silent it for the user.
setAccountSyncState(accountId, {
pending: false,
error: null,
});
next();
return;
}
if (error && error.name !== "NetworkDown") {
trackEnd("SyncError");
}
setAccountSyncState(accountId, {
pending: false,
error,
});
next();
},
});
} catch (error: any) {
setAccountSyncState(accountId, {
pending: false,
error,
});
next();
}
},
[
accounts,
bridgeSyncState,
prepareCurrency,
recoverError,
setAccountSyncState,
trackAnalytics,
updateAccountWithUpdater,
blacklistedTokenIds,
]
);
const synchronizeRef = useRef(synchronize);
useEffect(() => {
synchronizeRef.current = synchronize;
}, [synchronize]);
const [syncQueue] = useState(() =>
priorityQueue(
(accountId: string, next: () => void) =>
synchronizeRef.current(accountId, next),
getEnv("SYNC_MAX_CONCURRENT")
)
);
return [syncQueue, bridgeSyncState];
}
// useSync: returns a sync function with the syncQueue
function useSync({ syncQueue, accounts }) {
const skipUnderPriority = useRef(-1);
const sync = useMemo(() => {
const schedule = (ids: string[], priority: number) => {
if (priority < skipUnderPriority.current) return;
// by convention we remove concurrent tasks with same priority
// FIXME this is somehow a hack. ideally we should just dedup the account ids in the pending queue...
syncQueue.remove((o) => priority === o.priority);
log("bridge", "schedule " + ids.join(", "));
syncQueue.push(ids, -priority);
};
// don't always sync in the same order to avoid potential "account never reached"
const shuffledAccountIds = () => shuffle(accounts.map((a) => a.id));
const handlers = {
BACKGROUND_TICK: () => {
if (syncQueue.idle()) {
schedule(shuffledAccountIds(), -1);
}
},
SET_SKIP_UNDER_PRIORITY: ({ priority }: { priority: number }) => {
if (priority === skipUnderPriority.current) return;
skipUnderPriority.current = priority;
syncQueue.remove(({ priority }) => priority < skipUnderPriority);
if (priority === -1 && !accounts.every(isUpToDateAccount)) {
// going back to -1 priority => retriggering a background sync if it is "Paused"
schedule(shuffledAccountIds(), -1);
}
},
SYNC_ALL_ACCOUNTS: ({ priority }: { priority: number }) => {
schedule(shuffledAccountIds(), priority);
},
SYNC_ONE_ACCOUNT: ({
accountId,
priority,
}: {
accountId: string;
priority: number;
}) => {
schedule([accountId], priority);
},
SYNC_SOME_ACCOUNTS: ({
accountIds,
priority,
}: {
accountIds: string[];
priority: number;
}) => {
schedule(accountIds, priority);
},
};
return (action: SyncAction) => {
const handler = handlers[action.type];
if (handler) {
log("bridge", `action ${action.type}`, {
action,
type: "syncQueue",
});
handler(action as any);
} else {
log("warn", "BridgeSyncContext unsupported action", {
action,
type: "syncQueue",
});
}
};
}, [accounts, syncQueue]);
const ref = useRef(sync);
useEffect(() => {
ref.current = sync;
}, [sync]);
const syncFn = useCallback((action) => ref.current(action), [ref]);
return syncFn;
}
// useSyncBackground: continuously synchronize accounts in background
function useSyncBackground({ sync }) {
useEffect(() => {
let syncTimeout;
const syncLoop = async () => {
sync({
type: "BACKGROUND_TICK",
});
syncTimeout = setTimeout(syncLoop, getEnv("SYNC_ALL_INTERVAL"));
};
syncTimeout = setTimeout(syncLoop, getEnv("SYNC_BOOT_DELAY"));
return () => clearTimeout(syncTimeout);
}, [sync]);
}
// useSyncContinouslyPendingOperations: continously sync accounts with pending operations
function useSyncContinouslyPendingOperations({ sync, accounts }) {
const ids = useMemo(
() =>
accounts.filter((a) => a.pendingOperations.length > 0).map((a) => a.id),
[accounts]
);
const refIds = useRef(ids);
useEffect(() => {
refIds.current = ids;
}, [ids]);
useEffect(() => {
let timeout;
const update = () => {
sync({
type: "SYNC_SOME_ACCOUNTS",
accountIds: refIds.current,
priority: 20,
});
timeout = setTimeout(update, getEnv("SYNC_PENDING_INTERVAL"));
};
timeout = setTimeout(update, getEnv("SYNC_PENDING_INTERVAL"));
return () => clearTimeout(timeout);
}, [sync]);
} | the_stack |
import MemoryManager from '../core/MemoryManager';
import EntityRepository from './EntityRepository';
import BufferView from '../memory/BufferView';
import Accessor from '../memory/Accessor';
import {BufferUseEnum} from '../definitions/BufferUse';
import {ComponentTypeEnum} from '../../foundation/definitions/ComponentType';
import {
CompositionType,
CompositionTypeEnum,
} from '../../foundation/definitions/CompositionType';
import {ProcessStage, ProcessStageEnum} from '../definitions/ProcessStage';
import {ProcessApproachEnum} from '../definitions/ProcessApproach';
import ComponentRepository from './ComponentRepository';
import Config from './Config';
import WebGLStrategy from '../../webgl/WebGLStrategy';
import RenderPass from '../renderer/RenderPass';
import RnObject from './RnObject';
import {
EntityUID,
ComponentSID,
TypedArray,
Count,
Byte,
} from '../../types/CommonTypes';
import Entity from './Entity';
export function fromTensorToCompositionType(tensorClass: any) {
switch (tensorClass.name) {
case 'Scalar':
case 'MutableScalar':
return CompositionType.Scalar;
case 'Vector2':
case 'MutableVector2':
return CompositionType.Vec2;
case 'Vector3':
case 'MutableVector3':
return CompositionType.Vec3;
case 'Vector4':
case 'MutableVector4':
case 'Quaternion':
case 'MutableQuaternion':
return CompositionType.Vec4;
case 'Matrix22':
case 'MutableMatrix22':
return CompositionType.Mat2;
case 'Matrix33':
case 'MutableMatrix33':
return CompositionType.Mat3;
case 'Matrix44':
case 'MutableMatrix44':
return CompositionType.Mat4;
default:
return CompositionType.Unknown;
}
}
type MemberInfo = {
memberName: string;
bufferUse: BufferUseEnum;
dataClassType: unknown;
compositionType: CompositionTypeEnum;
componentType: ComponentTypeEnum;
initValues: number[];
};
/**
* Component is a functional unit that can be added to an Entity instance.
*/
export default class Component extends RnObject {
private _component_sid: number;
static readonly invalidComponentSID = -1;
protected __currentProcessStage: ProcessStageEnum = ProcessStage.Create;
protected static __componentsOfProcessStages: Map<
ProcessStageEnum,
Int32Array
> = new Map();
protected static __lengthOfArrayOfProcessStages: Map<
ProcessStageEnum,
number
> = new Map();
// protected static __dirtyOfArrayOfProcessStages: Map<ProcessStageEnum, boolean> = new Map();
private static __bufferViews: Map<
Function,
Map<BufferUseEnum, BufferView>
> = new Map();
private static __accessors: Map<Function, Map<string, Accessor>> = new Map();
private static __byteLengthSumOfMembers: Map<
Function,
Map<BufferUseEnum, Byte>
> = new Map();
private static __memberInfo: Map<Function, MemberInfo[]> = new Map();
private static __members: Map<
Function,
Map<BufferUseEnum, Array<MemberInfo>>
> = new Map();
private __byteOffsetOfThisComponent: Byte = -1;
private __isAlive: Boolean;
protected __entityUid: EntityUID;
protected __memoryManager: MemoryManager;
protected __entityRepository: EntityRepository;
private __maxComponentNumber: Count = Config.maxEntityNumber;
public static readonly _processStages: Array<ProcessStageEnum> = [
ProcessStage.Create,
ProcessStage.Load,
// ProcessStage.Mount,
ProcessStage.Logic,
ProcessStage.PreRender,
ProcessStage.Render,
// ProcessStage.Unmount,
// ProcessStage.Discard
];
/**
* The constructor of the Component class.
* When creating an Component, use the createComponent method of the ComponentRepository class
* instead of directly calling this constructor.
* @param entityUid Unique ID of the corresponding entity
* @param componentSid Scoped ID of the Component
* @param entityRepository The instance of the EntityRepository class (Dependency Injection)
*/
constructor(
entityUid: EntityUID,
componentSid: ComponentSID,
entityRepository: EntityRepository
) {
super();
this.__entityUid = entityUid;
this._component_sid = componentSid;
this.__isAlive = true;
const stages = Component._processStages;
stages.forEach(stage => {
if (this.isExistProcessStageMethod(stage)) {
if (Component.__componentsOfProcessStages.get(stage) == null) {
Component.__componentsOfProcessStages.set(
stage,
new Int32Array(Config.maxEntityNumber)
);
// Component.__dirtyOfArrayOfProcessStages.set(stage, false);
Component.__lengthOfArrayOfProcessStages.set(stage, 0);
}
}
});
this.__memoryManager = MemoryManager.getInstance();
this.__entityRepository = entityRepository;
}
set maxNumberOfComponent(value: number) {
this.__maxComponentNumber = value;
}
get maxNumberOfComponent() {
return this.__maxComponentNumber;
}
/**
* Move to the other stages of process
* @param processStage stage of component's process
*/
moveStageTo(processStage: ProcessStageEnum) {
// Component.__dirtyOfArrayOfProcessStages.set(this.__currentProcessStage, false);
// Component.__dirtyOfArrayOfProcessStages.set(processStage, true);
this.__currentProcessStage = processStage;
}
/**
* Get the Type ID of the Component
*/
static get componentTID() {
return 0;
}
/**
* Get the Scoped ID of the Component
*/
get componentSID() {
return this._component_sid;
}
/**
* Get the unique ID of the entity corresponding to the component.
*/
get entityUID() {
return this.__entityUid;
}
/**
* Get the current process stage of the component.
*/
get currentProcessStage() {
return this.__currentProcessStage;
}
/**
* Get true or false whether the specified ProcessStage exists in Component.
*/
static isExistProcessStageMethod(
componentType: typeof Component,
processStage: ProcessStageEnum,
componentRepository: ComponentRepository
) {
if ((componentType.prototype as any)[processStage.methodName] == null) {
return false;
}
return true;
}
/**
* Get true or false whether the specified ProcessStage exists in Component.
*/
isExistProcessStageMethod(processStage: ProcessStageEnum) {
if ((this as any)[processStage.methodName] == null) {
return false;
}
return true;
}
/**
* Process the components
* @param param0 params
*/
static process({
componentType,
processStage,
processApproach,
componentRepository,
strategy,
renderPass,
renderPassTickCount,
}: {
componentType: typeof Component;
processStage: ProcessStageEnum;
processApproach: ProcessApproachEnum;
componentRepository: ComponentRepository;
strategy: WebGLStrategy;
renderPass?: RenderPass;
renderPassTickCount: Count;
}) {
if (
!Component.isExistProcessStageMethod(
componentType,
processStage,
componentRepository
)
) {
return;
}
const methodName = processStage.methodName;
const array = this.__componentsOfProcessStages.get(processStage)!;
const components:
| Component[]
| undefined = componentRepository._getComponents(componentType);
for (let i = 0; i < array.length; ++i) {
const componentSid = array[i];
if (componentSid === Component.invalidComponentSID) {
return;
}
const component = components![componentSid];
(component! as any)[methodName]({
i,
processStage,
processApproach,
strategy,
renderPass,
renderPassTickCount,
});
}
}
/**
* Update all components at each process stage.
*/
static updateComponentsOfEachProcessStage(
componentClass: typeof Component,
processStage: ProcessStageEnum,
componentRepository: ComponentRepository,
renderPass?: RenderPass
) {
if (
!Component.isExistProcessStageMethod(
componentClass,
processStage,
componentRepository
)
) {
return;
}
const array = Component.__componentsOfProcessStages.get(processStage)!;
if (array) {
const method = (componentClass as any)['sort_' + processStage.methodName];
if (method != null) {
let sids = [];
sids = method(renderPass);
for (let i = 0; i < sids.length; i++) {
array[i] = sids[i];
}
} else {
let count = 0;
const components = componentRepository.getComponentsWithType(
componentClass
)!;
for (let i = 0; i < components.length; ++i) {
const component = components[i];
if (processStage === component.__currentProcessStage) {
array[count++] = i;
}
}
array[count] = Component.invalidComponentSID;
}
}
}
/**
* get byte length of sum of member fields in the component class
*/
static getByteLengthSumOfMembers(
bufferUse: BufferUseEnum,
componentClass: Function
) {
const byteLengthSumOfMembers = this.__byteLengthSumOfMembers.get(
componentClass
)!;
return byteLengthSumOfMembers.get(bufferUse)!;
}
static setupBufferView() {}
/**
* register a dependency for the other components.
*/
registerDependency(component: Component, isMust: boolean) {}
/**
* take a buffer view from the buffer.
*/
static takeBufferView(
bufferUse: BufferUseEnum,
componentClass: Function,
byteLengthSumOfMembers: Byte,
count: Count
) {
const buffer = MemoryManager.getInstance().createOrGetBuffer(bufferUse);
if (!this.__bufferViews.has(componentClass)) {
this.__bufferViews.set(componentClass, new Map());
}
const bufferViews = this.__bufferViews.get(componentClass)!;
if (!bufferViews.has(bufferUse)) {
const bufferView = buffer.takeBufferView({
byteLengthToNeed: byteLengthSumOfMembers * count,
byteStride: 0,
});
bufferViews.set(bufferUse, bufferView);
return bufferView;
}
return void 0;
}
/**
* take one memory area for the specified member for all same type of the component instances.
*/
takeOne(memberName: string, dataClassType: any, initValues: number[]): any {
if (!(this as any)['_' + memberName].isDummy()) {
return;
}
const taken = Component.__accessors
.get(this.constructor)!
.get(memberName)!
.takeOne();
(this as any)['_' + memberName] = new dataClassType(taken, false, true);
for (let i = 0; i < (this as any)['_' + memberName]._v.length; ++i) {
(this as any)['_' + memberName]._v[i] = initValues[i];
}
return null;
}
/**
* get the taken accessor for the member field.
*/
static getAccessor(memberName: string, componentClass: Function): Accessor {
return this.__accessors.get(componentClass)!.get(memberName)!;
}
/**
* take one accessor for the member field.
*/
static takeAccessor(
bufferUse: BufferUseEnum,
memberName: string,
componentClass: Function,
compositionType: CompositionTypeEnum,
componentType: ComponentTypeEnum,
count: Count
) {
if (!this.__accessors.has(componentClass)) {
this.__accessors.set(componentClass, new Map());
}
const accessors = this.__accessors.get(componentClass)!;
if (!accessors.has(memberName)) {
const bufferViews = this.__bufferViews.get(componentClass)!;
const bytes =
compositionType.getNumberOfComponents() *
componentType.getSizeInBytes();
let alignedBytes = bytes;
if (bytes % 16 !== 0) {
alignedBytes += bytes % 16 === 0 ? 0 : 16 - (bytes % 16);
}
const accessor = bufferViews.get(bufferUse)!.takeAccessor({
compositionType: compositionType,
componentType,
count: count,
byteStride: alignedBytes,
});
accessors.set(memberName, accessor);
return accessor;
} else {
return void 0;
}
}
static getByteOffsetOfThisComponentTypeInBuffer(
bufferUse: BufferUseEnum,
componentClass: Function
): Byte {
return this.__bufferViews.get(componentClass)!.get(bufferUse)!
.byteOffsetInBuffer;
}
static getByteOffsetOfFirstOfThisMemberInBuffer(
memberName: string,
componentClass: Function
): Byte {
return this.__accessors.get(componentClass)!.get(memberName)!
.byteOffsetInBuffer;
}
static getByteOffsetOfFirstOfThisMemberInBufferView(
memberName: string,
componentClass: Function
): Byte {
return this.__accessors.get(componentClass)!.get(memberName)!
.byteOffsetInBufferView;
}
static getCompositionTypeOfMember(
memberName: string,
componentClass: Function
): CompositionTypeEnum | null {
const memberInfoArray = this.__memberInfo.get(componentClass)!;
const info = memberInfoArray.find(info => {
return info.memberName === memberName;
});
if (info != null) {
return info.compositionType;
} else {
return null;
}
}
static getComponentTypeOfMember(
memberName: string,
componentClass: Function
): ComponentTypeEnum | null {
const memberInfoArray = this.__memberInfo.get(componentClass)!;
const info = memberInfoArray.find(info => {
return info.memberName === memberName;
});
if (info != null) {
return info.componentType;
} else {
return null;
}
}
/**
* Register a member field of component class for memory allocation.
* @param bufferUse purpose type of buffer use
* @param memberName the name of member field
* @param dataClassType a class of data
* @param componentType a type of number
* @param initValues a initial value
*/
registerMember(
bufferUse: BufferUseEnum,
memberName: string,
dataClassType: unknown,
componentType: ComponentTypeEnum,
initValues: number[]
) {
if (!Component.__memberInfo.has(this.constructor)) {
Component.__memberInfo.set(this.constructor, []);
}
const memberInfoArray = Component.__memberInfo.get(this.constructor);
memberInfoArray!.push({
bufferUse: bufferUse,
memberName: memberName,
dataClassType: dataClassType as never,
compositionType: (dataClassType as any).compositionType,
componentType: componentType,
initValues: initValues,
});
}
/**
* Allocate memory of self member fields
* @param count a number of entities to need allocate
*/
submitToAllocation(count: Count) {
const componentClass = this.constructor;
const memberInfoArray = Component.__memberInfo.get(componentClass)!;
if (this._component_sid === 0) {
if (!Component.__members.has(componentClass)) {
Component.__members.set(componentClass, new Map());
}
const member = Component.__members.get(componentClass)!;
memberInfoArray.forEach(info => {
member.set(info.bufferUse, []);
});
memberInfoArray.forEach(info => {
member.get(info.bufferUse)!.push(info);
});
// take a BufferView for all entities for each member fields.
for (const bufferUse of member.keys()) {
const infoArray = member.get(bufferUse)!;
if (!Component.__byteLengthSumOfMembers.has(componentClass)) {
Component.__byteLengthSumOfMembers.set(componentClass, new Map());
}
const byteLengthSumOfMembers = Component.__byteLengthSumOfMembers.get(
componentClass
)!;
if (!byteLengthSumOfMembers.has(bufferUse)) {
byteLengthSumOfMembers.set(bufferUse, 0);
}
infoArray.forEach(info => {
byteLengthSumOfMembers.set(
bufferUse,
byteLengthSumOfMembers.get(bufferUse)! +
info.compositionType.getNumberOfComponents() *
info.componentType.getSizeInBytes()
);
});
if (infoArray.length > 0) {
const bufferView = Component.takeBufferView(
bufferUse,
componentClass,
byteLengthSumOfMembers.get(bufferUse)!,
count
);
this.__byteOffsetOfThisComponent = bufferView!.byteOffsetInBuffer;
}
}
// take a Accessor for all entities for each member fields (same as BufferView)
for (const bufferUse of member.keys()) {
const infoArray = member.get(bufferUse)!;
infoArray.forEach(info => {
const accessor = Component.takeAccessor(
info.bufferUse,
info.memberName,
componentClass,
info.compositionType,
info.componentType,
count
);
(this as any)[
'_byteOffsetOfAccessorInBuffer_' + info.memberName
] = accessor!.byteOffsetInBuffer;
(this as any)[
'_byteOffsetOfAccessorInComponent_' + info.memberName
] = accessor!.byteOffsetInBufferView;
});
}
}
const member = Component.__members.get(componentClass)!;
// take a field value allocation for each entity for each member field
for (const bufferUse of member.keys()) {
const infoArray = member.get(bufferUse)!;
infoArray.forEach(info => {
this.takeOne(info.memberName, info.dataClassType, info.initValues);
});
}
}
/**
* get the entity which has this component.
* @returns the entity which has this component
*/
get entity(): Entity {
return this.__entityRepository.getEntity(this.__entityUid);
}
/**
* get the bytes Information of the member
* @param component a instance of the component
* @param memberName the member of component in string
* @returns bytes information
*/
static getDataByteInfoInner(component: Component, memberName: string) {
const data = (component as any)['_' + memberName];
const typedArray = data._v as TypedArray;
const byteOffsetInBuffer = typedArray.byteOffset;
const byteLength = typedArray.byteLength;
const componentNumber = typedArray.length;
const locationOffsetInBuffer = byteOffsetInBuffer / 4 / 4; // 4byte is the size of Float32Array, and texel fetch is 4 components unit.
const byteOffsetInThisComponent =
(this as any)['_byteOffsetOfAccessorInComponent_' + memberName] +
component.componentSID * componentNumber * 4;
const locationOffsetInThisComponent =
(this as any)['_byteOffsetOfAccessorInComponent_' + memberName] +
component.componentSID * componentNumber;
const thisComponentByteOffsetInBuffer =
component.__byteOffsetOfThisComponent;
const thisComponentLocationOffsetInBuffer =
component.__byteOffsetOfThisComponent / 4 / 4;
return {
byteLength,
byteOffsetInBuffer,
byteOffsetInThisComponent,
locationOffsetInBuffer,
locationOffsetInThisComponent,
thisComponentByteOffsetInBuffer,
thisComponentLocationOffsetInBuffer,
componentNumber,
};
}
/**
* get the bytes Information of the member
* @param memberName the member of component in string
* @returns bytes information
*/
getDataByteInfo(memberName: string) {
return Component.getDataByteInfoInner(this, memberName);
}
/**
* get the bytes Information of the member (static version) by ComponentSID
* @param componentType the Component type
* @param componentSID the ComponentSID of the component
* @param memberName the member of component in string
* @returns bytes information
*/
static getDataByteInfoByComponentSID(
componentType: typeof Component,
componentSID: ComponentSID,
memberName: string
) {
const component = ComponentRepository.getInstance().getComponent(
componentType,
componentSID
);
if (component) {
return Component.getDataByteInfoInner(component, memberName);
}
return void 0;
}
/**
* get the bytes Information of the member (static version) by EntityUID
* @param componentType the component type
* @param entityUID the EntityUID
* @param memberName the member of component in string
* @returns bytes information
*/
static getDataByteInfoByEntityUID(
componentType: typeof Component,
entityUID: EntityUID,
memberName: string
) {
const component = EntityRepository.getInstance().getComponentOfEntity(
entityUID,
componentType
);
if (component) {
return Component.getDataByteInfoInner(component, memberName);
}
return void 0;
}
/**
* get the Pixel Location Offset in the Buffer of the Member
* @param componentType the component type (e.g. TransformComponent )
* @param memberName the member name in string
* @returns the pixel offsets
*/
static getLocationOffsetOfMemberOfComponent(
componentType: typeof Component,
memberName: string
) {
const component = ComponentRepository.getInstance().getComponent(
componentType,
0
);
return (
(component as any)['_byteOffsetOfAccessorInBuffer_' + memberName] / 4 / 4
);
}
// $create() {
// // Define process dependencies with other components.
// // If circular dependencies are detected, the error will be reported.
// // this.registerDependency(TransformComponent);
// }
// $load() {}
// $mount() {}
// $logic() {}
// $prerender(instanceIDBufferUid: CGAPIResourceHandle) {}
// $render() {}
// $unmount() {}
// $discard() {}
} | the_stack |
import { HookParams } from '../../../../app/v2/operator/interfaces/params.interface'
export const reconcileFixtures = {
currentDeploymentId: '8210509b-2432-4e2c-bfc3-af01be918816',
previousDeploymentId: '7c182579-7e69-414b-aae9-000a471b5549'
}
const previousDeploymentparams : HookParams = {
'controller': {
'kind': 'CompositeController',
'apiVersion': 'metacontroller.k8s.io/v1alpha1',
'metadata': {
'name': 'charlesdeployments-controller',
'uid': 'a486b001-f635-4c40-b807-6f725953a07e',
'resourceVersion': '832',
'generation': 1,
'creationTimestamp': '2021-01-15T19:48:24Z',
'labels': {
'app.kubernetes.io/managed-by': 'Helm'
},
'annotations': {
'meta.helm.sh/release-name': 'charlescd',
'meta.helm.sh/release-namespace': 'default'
}
},
'spec': {
'parentResource': {
'apiVersion': 'charlescd.io/v1',
'resource': 'charlesdeployments'
},
'childResources': [
{
'apiVersion': 'v1',
'resource': 'services',
'updateStrategy': {
'method': 'Recreate',
'statusChecks': {}
}
},
{
'apiVersion': 'apps/v1',
'resource': 'deployments',
'updateStrategy': {
'method': 'Recreate',
'statusChecks': {}
}
}
],
'hooks': {
'sync': {
'webhook': {
'url': 'http://charlescd-butler.default.svc.cluster.local:3000/v2/operator/deployment/hook/reconcile'
}
},
'finalize': {
'webhook': {
'url': 'http://charlescd-butler.default.svc.cluster.local:3000/v2/operator/deployment/hook/finalize'
}
}
},
'generateSelector': true
},
'status': {}
},
'parent': {
'apiVersion': 'charlescd.io/v1',
'kind': 'CharlesDeployment',
'metadata': {
'creationTimestamp': '2021-01-15T20:59:17Z',
'finalizers': [
'metacontroller.app/compositecontroller-charlesdeployments-controller'
],
'generation': 3,
'labels': {
'deployment_id': reconcileFixtures.currentDeploymentId
},
'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'namespace': 'default',
'resourceVersion': '10537',
'uid': '5c6e0a99-f05b-4198-8499-469fa34f755b'
},
'spec': {
'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'components': [
{
'chart': 'http://fake-repo/repos/charlescd-fake/helm-chart',
'name': 'abobora',
'tag': 'latest'
},
{
'chart': 'http://fake-repo/repos/charlescd-fake/helm-chart',
'name': 'jilo',
'tag': 'latest'
}
],
'deploymentId': reconcileFixtures.currentDeploymentId
}
},
'children': {
'Deployment.apps/v1': {
'batata-ed2a1669-34b8-4af2-b42c-acbad2ec6b60': {
'apiVersion': 'apps/v1',
'kind': 'Deployment',
'metadata': {
'creationTimestamp': '2021-01-15T21:01:22Z',
'generation': 1,
'labels': {
'app': 'batata',
'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'controller-uid': '5c6e0a99-f05b-4198-8499-469fa34f755b',
'deploymentId': reconcileFixtures.previousDeploymentId,
'version': 'batata'
},
'name': 'batata-ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'namespace': 'default',
'ownerReferences': [
{
'apiVersion': 'charlescd.io/v1',
'blockOwnerDeletion': true,
'controller': true,
'kind': 'CharlesDeployment',
'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'uid': '5c6e0a99-f05b-4198-8499-469fa34f755b'
}
],
'resourceVersion': '6755',
'uid': '1127f97a-4288-4dfc-8cc3-6c9a039b26cf'
},
'spec': {
'progressDeadlineSeconds': 600,
'replicas': 1,
'revisionHistoryLimit': 10,
'selector': {
'matchLabels': {
'app': 'batata',
'version': 'batata'
}
},
'strategy': {
'rollingUpdate': {
'maxSurge': '25%',
'maxUnavailable': '25%'
},
'type': 'RollingUpdate'
},
'template': {
'metadata': {
'annotations': {
'sidecar.istio.io/inject': 'true'
},
'creationTimestamp': null,
'labels': {
'app': 'batata',
'version': 'batata'
}
},
'spec': {
'containers': [
{
'args': [
'-text',
'hello'
],
'image': 'hashicorp/http-echo',
'imagePullPolicy': 'Always',
'livenessProbe': {
'failureThreshold': 3,
'httpGet': {
'path': '/',
'port': 5678,
'scheme': 'HTTP'
},
'initialDelaySeconds': 30,
'periodSeconds': 20,
'successThreshold': 1,
'timeoutSeconds': 1
},
'name': 'batata',
'readinessProbe': {
'failureThreshold': 3,
'httpGet': {
'path': '/',
'port': 5678,
'scheme': 'HTTP'
},
'initialDelaySeconds': 30,
'periodSeconds': 20,
'successThreshold': 1,
'timeoutSeconds': 1
},
'resources': {
'limits': {
'cpu': '128m',
'memory': '128Mi'
},
'requests': {
'cpu': '64m',
'memory': '64Mi'
}
},
'terminationMessagePath': '/dev/termination-log',
'terminationMessagePolicy': 'File'
}
],
'dnsPolicy': 'ClusterFirst',
'restartPolicy': 'Always',
'schedulerName': 'default-scheduler',
'securityContext': {},
'terminationGracePeriodSeconds': 30
}
}
},
'status': {
'availableReplicas': 1,
'conditions': [
{
'lastTransitionTime': '2021-01-15T21:02:06Z',
'lastUpdateTime': '2021-01-15T21:02:06Z',
'message': 'Deployment has minimum availability.',
'reason': 'MinimumReplicasAvailable',
'status': 'True',
'type': 'Available'
},
{
'lastTransitionTime': '2021-01-15T21:01:22Z',
'lastUpdateTime': '2021-01-15T21:02:06Z',
'message': 'ReplicaSet "batata-ed2a1669-34b8-4af2-b42c-acbad2ec6b60-7f7dfc545f" has successfully progressed.',
'reason': 'NewReplicaSetAvailable',
'status': 'True',
'type': 'Progressing'
}
],
'observedGeneration': 1,
'readyReplicas': 1,
'replicas': 1,
'updatedReplicas': 1
}
},
'jilo-ed2a1669-34b8-4af2-b42c-acbad2ec6b60': {
'apiVersion': 'apps/v1',
'kind': 'Deployment',
'metadata': {
'creationTimestamp': '2021-01-15T21:01:21Z',
'generation': 1,
'labels': {
'app': 'jilo',
'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'controller-uid': '5c6e0a99-f05b-4198-8499-469fa34f755b',
'deploymentId': reconcileFixtures.previousDeploymentId,
'version': 'jilo'
},
'name': 'jilo-ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'namespace': 'default',
'ownerReferences': [
{
'apiVersion': 'charlescd.io/v1',
'blockOwnerDeletion': true,
'controller': true,
'kind': 'CharlesDeployment',
'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'uid': '5c6e0a99-f05b-4198-8499-469fa34f755b'
}
],
'resourceVersion': '6734',
'uid': 'dfdfa186-2f7b-4e45-b740-0d87c2c0d6bf'
},
'spec': {
'progressDeadlineSeconds': 600,
'replicas': 1,
'revisionHistoryLimit': 10,
'selector': {
'matchLabels': {
'app': 'jilo',
'version': 'jilo'
}
},
'strategy': {
'rollingUpdate': {
'maxSurge': '25%',
'maxUnavailable': '25%'
},
'type': 'RollingUpdate'
},
'template': {
'metadata': {
'annotations': {
'sidecar.istio.io/inject': 'true'
},
'creationTimestamp': null,
'labels': {
'app': 'jilo',
'version': 'jilo'
}
},
'spec': {
'containers': [
{
'args': [
'-text',
'hello'
],
'image': 'hashicorp/http-echo',
'imagePullPolicy': 'Always',
'livenessProbe': {
'failureThreshold': 3,
'httpGet': {
'path': '/',
'port': 5678,
'scheme': 'HTTP'
},
'initialDelaySeconds': 30,
'periodSeconds': 20,
'successThreshold': 1,
'timeoutSeconds': 1
},
'name': 'jilo',
'readinessProbe': {
'failureThreshold': 3,
'httpGet': {
'path': '/',
'port': 5678,
'scheme': 'HTTP'
},
'initialDelaySeconds': 30,
'periodSeconds': 20,
'successThreshold': 1,
'timeoutSeconds': 1
},
'resources': {
'limits': {
'cpu': '128m',
'memory': '128Mi'
},
'requests': {
'cpu': '64m',
'memory': '64Mi'
}
},
'terminationMessagePath': '/dev/termination-log',
'terminationMessagePolicy': 'File'
}
],
'dnsPolicy': 'ClusterFirst',
'restartPolicy': 'Always',
'schedulerName': 'default-scheduler',
'securityContext': {},
'terminationGracePeriodSeconds': 30
}
}
},
'status': {
'availableReplicas': 1,
'conditions': [
{
'lastTransitionTime': '2021-01-15T21:01:56Z',
'lastUpdateTime': '2021-01-15T21:01:56Z',
'message': 'Deployment has minimum availability.',
'reason': 'MinimumReplicasAvailable',
'status': 'True',
'type': 'Available'
},
{
'lastTransitionTime': '2021-01-15T21:01:21Z',
'lastUpdateTime': '2021-01-15T21:01:56Z',
'message': 'ReplicaSet "jilo-ed2a1669-34b8-4af2-b42c-acbad2ec6b60-76fcc6c494" has successfully progressed.',
'reason': 'NewReplicaSetAvailable',
'status': 'True',
'type': 'Progressing'
}
],
'observedGeneration': 1,
'readyReplicas': 1,
'replicas': 1,
'updatedReplicas': 1
}
}
},
'Service.v1': {
'batata-ed2a1669-34b8-4af2-b42c-acbad2ec6b60': {
'apiVersion': 'v1',
'kind': 'Service',
'metadata': {
'creationTimestamp': '2021-01-15T21:02:06Z',
'labels': {
'app': 'batata',
'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'controller-uid': '5c6e0a99-f05b-4198-8499-469fa34f755b',
'deploymentId': reconcileFixtures.previousDeploymentId,
'service': 'batata'
},
'name': 'batata-ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'namespace': 'default',
'ownerReferences': [
{
'apiVersion': 'charlescd.io/v1',
'blockOwnerDeletion': true,
'controller': true,
'kind': 'CharlesDeployment',
'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'uid': '5c6e0a99-f05b-4198-8499-469fa34f755b'
}
],
'resourceVersion': '6763',
'uid': '1f2aa658-20aa-4a93-9c33-a2f2d2234d21'
},
'spec': {
'clusterIP': '10.97.147.13',
'clusterIPs': [
'10.97.147.13'
],
'ports': [
{
'name': 'http',
'port': 80,
'protocol': 'TCP',
'targetPort': 80
}
],
'selector': {
'app': 'batata'
},
'sessionAffinity': 'None',
'type': 'ClusterIP'
},
'status': {
'loadBalancer': {}
}
},
'jilo-ed2a1669-34b8-4af2-b42c-acbad2ec6b60': {
'apiVersion': 'v1',
'kind': 'Service',
'metadata': {
'creationTimestamp': '2021-01-15T21:01:21Z',
'labels': {
'app': 'jilo',
'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'controller-uid': '5c6e0a99-f05b-4198-8499-469fa34f755b',
'deploymentId': reconcileFixtures.previousDeploymentId,
'service': 'jilo'
},
'name': 'jilo-ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'namespace': 'default',
'ownerReferences': [
{
'apiVersion': 'charlescd.io/v1',
'blockOwnerDeletion': true,
'controller': true,
'kind': 'CharlesDeployment',
'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'uid': '5c6e0a99-f05b-4198-8499-469fa34f755b'
}
],
'resourceVersion': '6616',
'uid': '6f0190a9-2bf0-4531-8adb-0d94ed883c02'
},
'spec': {
'clusterIP': '10.98.248.219',
'clusterIPs': [
'10.98.248.219'
],
'ports': [
{
'name': 'http',
'port': 80,
'protocol': 'TCP',
'targetPort': 80
}
],
'selector': {
'app': 'jilo'
},
'sessionAffinity': 'None',
'type': 'ClusterIP'
},
'status': {
'loadBalancer': {}
}
}
}
},
'finalizing': false
}
export const reconcileFixturesParams = {
paramsWithPreviousDeployment: previousDeploymentparams
}
const firstDeploymentParams: HookParams = {
'controller': {
'kind': 'CompositeController',
'apiVersion': 'metacontroller.k8s.io/v1alpha1',
'metadata': {
'name': 'charlesdeployments-controller',
'uid': '67a4c2e9-4a27-4c8c-8c99-735c96ead809',
'resourceVersion': '834',
'generation': 1,
'creationTimestamp': '2021-01-18T13:29:13Z',
'labels': {
'app.kubernetes.io/managed-by': 'Helm'
},
'annotations': {
'meta.helm.sh/release-name': 'charlescd',
'meta.helm.sh/release-namespace': 'default'
}
},
'spec': {
'parentResource': {
'apiVersion': 'charlescd.io/v1',
'resource': 'charlesdeployments'
},
'childResources': [
{
'apiVersion': 'v1',
'resource': 'services',
'updateStrategy': {
'method': 'Recreate',
'statusChecks': {}
}
},
{
'apiVersion': 'apps/v1',
'resource': 'deployments',
'updateStrategy': {
'method': 'Recreate',
'statusChecks': {}
}
}
],
'hooks': {
'sync': {
'webhook': {
'url': 'http://charlescd-butler.default.svc.cluster.local:3000/v2/operator/deployment/hook/reconcile'
}
},
'finalize': {
'webhook': {
'url': 'http://charlescd-butler.default.svc.cluster.local:3000/v2/operator/deployment/hook/finalize'
}
}
},
'generateSelector': true
},
'status': {}
},
'parent': {
'apiVersion': 'charlescd.io/v1',
'kind': 'CharlesDeployment',
'metadata': {
'creationTimestamp': '2021-01-18T13:33:14Z',
'finalizers': [
'metacontroller.app/compositecontroller-charlesdeployments-controller'
],
'generation': 1,
'labels': {
'deployment_id': 'b1e16c7d-15dd-4e4d-8d4b-d8c73ddf847c'
},
'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'namespace': 'default',
'resourceVersion': '1368',
'uid': 'aeb60d21-75d8-40d5-8639-9c5623c35921'
},
'spec': {
'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60',
'components': [
{
'chart': 'http://fake-repo/repos/charlescd-fake/helm-chart',
'name': 'batata',
'tag': 'latest'
},
{
'chart': 'http://fake-repo/repos/charlescd-fake/helm-chart',
'name': 'jilo',
'tag': 'latest'
}
],
'deploymentId': 'b1e16c7d-15dd-4e4d-8d4b-d8c73ddf847c'
}
},
'children': {
'Deployment.apps/v1': {},
'Service.v1': {}
},
'finalizing': false
}
export const reconcileFirstDeploymentParams = {
paramsWithEmptyCircle: firstDeploymentParams
}
export const componentRawSpecs = [
{
apiVersion: 'apps/v1',
kind: 'Deployment',
metadata: {
generation: 1,
labels: {
app: 'jilo',
version: 'jilo'
},
name: 'jilo',
namespace: 'default',
resourceVersion: '6734',
uid: 'dfdfa186-2f7b-4e45-b740-0d87c2c0d6bf'
},
spec: {
progressDeadlineSeconds: 600,
replicas: 1,
revisionHistoryLimit: 10,
selector: {
matchLabels: {
app: 'jilo',
version: 'jilo'
}
},
strategy: {
rollingUpdate: {
maxSurge: '25%',
maxUnavailable: '25%'
},
type: 'RollingUpdate'
},
template: {
metadata: {
annotations: {
'sidecar.istio.io/inject': 'true'
},
creationTimestamp: null,
labels: {
app: 'jilo',
version: 'jilo'
}
},
spec: {
containers: [
{
args: [
'-text',
'hello'
],
image: 'hashicorp/http-echo',
imagePullPolicy: 'Always',
livenessProbe: {
failureThreshold: 3,
httpGet: {
path: '/',
port: 5678,
scheme: 'HTTP'
},
initialDelaySeconds: 30,
periodSeconds: 20,
successThreshold: 1,
timeoutSeconds: 1
},
name: 'jilo',
readinessProbe: {
failureThreshold: 3,
httpGet: {
path: '/',
port: 5678,
scheme: 'HTTP'
},
initialDelaySeconds: 30,
periodSeconds: 20,
successThreshold: 1,
timeoutSeconds: 1
},
resources: {
limits: {
cpu: '128m',
memory: '128Mi'
},
requests: {
cpu: '64m',
memory: '64Mi'
}
},
terminationMessagePath: '/dev/termination-log',
terminationMessagePolicy: 'File'
}
],
dnsPolicy: 'ClusterFirst',
restartPolicy: 'Always',
schedulerName: 'default-scheduler',
securityContext: {},
terminationGracePeriodSeconds: 30
}
}
}
},
{
apiVersion: 'v1',
kind: 'Service',
metadata: {
labels: {
app: 'jilo',
version: 'jilo'
},
name: 'jilo',
namespace: 'default',
resourceVersion: '6763',
uid: '1f2aa658-20aa-4a93-9c33-a2f2d2234d21'
},
spec: {
clusterIP: '10.97.147.13',
clusterIPs: [
'10.97.147.13'
],
ports: [
{
name: 'http',
port: 80,
protocol: 'TCP',
targetPort: 80
}
],
selector: {
app: 'jilo'
},
sessionAffinity: 'None',
type: 'ClusterIP'
},
status: {
loadBalancer: {}
}
}
] | the_stack |
import {
Component,
HostBinding,
Input,
ViewChild,
QueryList,
ViewChildren,
forwardRef,
ChangeDetectionStrategy,
ChangeDetectorRef,
DoCheck,
ElementRef,
HostListener
} from '@angular/core';
import { IgxColumnComponent } from '../columns/column.component';
import { IgxFilteringService } from '../filtering/grid-filtering.service';
import { GridBaseAPIService } from '../api.service';
import { IgxGridBaseDirective } from '../grid-base.directive';
import { IgxColumnResizingService } from '../resizing/resizing.service';
import { IgxGridHeaderComponent } from './grid-header.component';
import { IgxGridFilteringCellComponent } from '../filtering/base/grid-filtering-cell.component';
import { GridType } from '../common/grid.interface';
import { GridSelectionMode } from '../common/enums';
import { PlatformUtil } from '../../core/utils';
const Z_INDEX = 9999;
/**
* @hidden
*/
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'igx-grid-header-group',
templateUrl: './grid-header-group.component.html'
})
export class IgxGridHeaderGroupComponent implements DoCheck {
@HostBinding('style.-ms-grid-row-span')
public get gridRowSpan(): number {
return this.column.gridRowSpan;
}
@HostBinding('style.-ms-grid-column-span')
public get gridColumnSpan(): number {
return this.column.gridColumnSpan;
}
@HostBinding('style.grid-row-end')
public get rowEnd(): number {
return this.column.rowEnd;
}
@HostBinding('style.grid-column-end')
public get colEnd(): number {
return this.column.colEnd;
}
@HostBinding('style.-ms-grid-row')
@HostBinding('style.grid-row-start')
public get rowStart(): number {
return this.column.rowStart;
}
@HostBinding('style.-ms-grid-column')
@HostBinding('style.grid-column-start')
public get colStart(): number {
return this.column.colStart;
}
@HostBinding('attr.id')
public get headerID() {
return `${this.grid.id}_-1_${this.column.level}_${this.column.visibleIndex}`;
}
/**
* Gets the column of the header group.
*
* @memberof IgxGridHeaderGroupComponent
*/
@Input()
public column: IgxColumnComponent;
@HostBinding('class.igx-grid-th--active')
public get active() {
const node = this.grid.navigation.activeNode;
return node && !this.column.columnGroup ?
node.row === -1 && node.column === this.column.visibleIndex && node.level === this.column.level : false;
}
public get activeGroup() {
const node = this.grid.navigation.activeNode;
return node ? node.row === -1 && node.column === this.column.visibleIndex && node.level === this.column.level : false;
}
/**
* @hidden
*/
@ViewChild(IgxGridHeaderComponent)
public header: IgxGridHeaderComponent;
/**
* @hidden
*/
@ViewChild(IgxGridFilteringCellComponent)
public filter: IgxGridFilteringCellComponent;
/**
* @hidden
*/
@ViewChildren(forwardRef(() => IgxGridHeaderGroupComponent), { read: IgxGridHeaderGroupComponent })
public children: QueryList<IgxGridHeaderGroupComponent>;
/**
* Gets the width of the header group.
*
* @memberof IgxGridHeaderGroupComponent
*/
public get width() {
return this.grid.getHeaderGroupWidth(this.column);
}
@HostBinding('class.igx-grid-thead__item')
public defaultCss = true;
constructor(private cdr: ChangeDetectorRef,
public gridAPI: GridBaseAPIService<IgxGridBaseDirective & GridType>,
private ref: ElementRef<HTMLElement>,
public colResizingService: IgxColumnResizingService,
public filteringService: IgxFilteringService,
protected platform: PlatformUtil) { }
@HostBinding('class.igx-grid-th--pinned')
public get pinnedCss() {
return this.isPinned;
}
@HostBinding('class.igx-grid-th--pinned-last')
public get pinnedLastCss() {
return this.isLastPinned;
}
@HostBinding('class.igx-grid-th--pinned-first')
public get pinnedFirstCSS() {
return this.isFirstPinned;
}
@HostBinding('class.igx-grid__drag-col-header')
public get headerDragCss() {
return this.isHeaderDragged;
}
@HostBinding('class.igx-grid-th--filtering')
public get filteringCss() {
return this.isFiltered;
}
/**
* @hidden
*/
@HostBinding('style.z-index')
public get zIndex() {
if (!this.column.pinned) {
return null;
}
return Z_INDEX - this.grid.pinnedColumns.indexOf(this.column);
}
/**
* Gets the grid of the header group.
*
* @memberof IgxGridHeaderGroupComponent
*/
public get grid(): any {
return this.gridAPI.grid;
}
/**
* Gets whether the header group belongs to a column that is filtered.
*
* @memberof IgxGridHeaderGroupComponent
*/
public get isFiltered(): boolean {
return this.filteringService.filteredColumn === this.column;
}
/**
* Gets whether the header group is stored in the last column in the pinned area.
*
* @memberof IgxGridHeaderGroupComponent
*/
public get isLastPinned(): boolean {
return !this.grid.hasColumnLayouts ? this.column.isLastPinned : false;
}
/**
* Gets whether the header group is stored in the first column of the right pinned area.
*/
public get isFirstPinned(): boolean {
return !this.grid.hasColumnLayouts ? this.column.isFirstPinned : false;
}
@HostBinding('style.display')
public get groupDisplayStyle(): string {
return this.grid.hasColumnLayouts && this.column.children && !this.platform.isIE ? 'flex' : '';
}
/**
* Gets whether the header group is stored in a pinned column.
*
* @memberof IgxGridHeaderGroupComponent
*/
public get isPinned(): boolean {
return this.column.pinned;
}
/**
* Gets whether the header group belongs to a column that is moved.
*
* @memberof IgxGridHeaderGroupComponent
*/
public get isHeaderDragged(): boolean {
return this.grid.columnInDrag === this.column;
}
/**
* @hidden
*/
public get hasLastPinnedChildColumn(): boolean {
return this.column.allChildren.some(child => child.isLastPinned);
}
/**
* @hidden
*/
public get hasFirstPinnedChildColumn(): boolean {
return this.column.allChildren.some(child => child.isFirstPinned);
}
/**
* @hidden
*/
public get selectable() {
const selectableChildren = this.column.allChildren.filter(c => !c.hidden && c.selectable && !c.columnGroup);
return this.grid.columnSelection !== GridSelectionMode.none &&
this.column.applySelectableClass
&& !this.selected && selectableChildren.length > 0
&& !this.grid.filteringService.isFilterRowVisible;
}
/**
* @hidden
*/
public get selected() {
return this.column.selected;
}
/**
* @hidden
*/
public get height() {
return this.nativeElement.getBoundingClientRect().height;
}
/**
* @hidden
*/
public get title() {
return this.column.title || this.column.header;
}
public get nativeElement() {
return this.ref.nativeElement;
}
/**
* @hidden
*/
@HostListener('mousedown', ['$event'])
public onMouseDown(event: MouseEvent): void {
// hack for preventing text selection in IE and Edge while dragging the resize element
event.preventDefault();
}
/**
* @hidden
*/
public groupClicked(event: MouseEvent): void {
const columnsToSelect = this.column.allChildren.filter(c => !c.hidden && c.selectable && !c.columnGroup).map(c => c.field);
if (this.grid.columnSelection !== GridSelectionMode.none
&& columnsToSelect.length > 0 && !this.grid.filteringService.isFilterRowVisible) {
const clearSelection = this.grid.columnSelection === GridSelectionMode.single || !event.ctrlKey;
const rangeSelection = this.grid.columnSelection === GridSelectionMode.multiple && event.shiftKey;
if (!this.selected) {
this.grid.selectionService.selectColumns(columnsToSelect, clearSelection, rangeSelection, event);
} else {
const selectedFields = this.grid.selectionService.getSelectedColumns();
if ((selectedFields.length === columnsToSelect.length) && selectedFields.every(el => columnsToSelect.includes(el))
|| !clearSelection) {
this.grid.selectionService.deselectColumns(columnsToSelect, event);
} else {
this.grid.selectionService.selectColumns(columnsToSelect, clearSelection, rangeSelection, event);
}
}
}
}
/**
* @hidden @internal
*/
public toggleExpandState(event: MouseEvent): void {
event.stopPropagation();
this.column.expanded = !this.column.expanded;
}
/**
* @hidden @internal
*/
public pointerdown(event: PointerEvent): void {
event.stopPropagation();
this.activate();
this.grid.theadRow.nativeElement.focus();
}
/*
* This method is necessary due to some specifics related with implementation of column moving
* @hidden
*/
public activate() {
this.grid.navigation.setActiveNode(this.activeNode);
this.grid.theadRow.nativeElement.focus();
}
public ngDoCheck() {
this.cdr.markForCheck();
}
/**
* @hidden
*/
public onPinterEnter() {
this.column.applySelectableClass = true;
}
/**
* @hidden
*/
public onPointerLeave() {
this.column.applySelectableClass = false;
}
private get activeNode() {
return {
row: -1, column: this.column.visibleIndex, level: this.column.level,
mchCache: { level: this.column.level, visibleIndex: this.column.visibleIndex },
layout: this.column.columnLayoutChild ? {
rowStart: this.column.rowStart,
colStart: this.column.colStart,
rowEnd: this.column.rowEnd,
colEnd: this.column.colEnd,
columnVisibleIndex: this.column.visibleIndex
} : null
};
}
} | the_stack |
import Path from "path";
import Fs from "fs";
import webpack from "webpack";
import hotHelpers from "webpack-hot-middleware/helpers";
import Url from "url";
import { devProxy } from "../../config/dev-proxy";
import { formUrl } from "../utils";
import getFilenameFromUrl from "webpack-dev-middleware/dist/utils/getFilenameFromUrl";
import { injectEntry } from "@xarc/webpack/lib/util/inject-entry";
const { getWebpackStartConfig } = require("@xarc/webpack/lib/util/custom-check"); // eslint-disable-line
hotHelpers.pathMatch = (url, path) => {
try {
return Url.parse(url).pathname === Url.parse(path).pathname;
} catch (e) {
return false;
}
};
import webpackDevMiddleware from "webpack-dev-middleware";
import webpackHotMiddleware from "webpack-hot-middleware";
import serveIndex from "serve-index-fs";
import ck from "chalker";
import _ from "lodash";
import { jsonToHtml } from "../stats-utils";
import { getBundles } from "../stats-mapper";
const { fullDevServer, controlPaths } = devProxy;
/**
* @param {...any} args
*/
function urlJoin(...args) {
if (args.length < 1) return undefined;
const base = args[0];
if (!base) return undefined;
const ix = base.indexOf("://");
let saved = "";
if (ix > 0) {
args[0] = base.substr(ix + 3);
saved = base.substring(0, ix + 3);
}
return saved + Path.posix.join(...args);
}
//
// skip webpack-dev-middleware if
//
// - http header FORCE_WEBPACK_DEV_MIDDLEWARE is not "true"
// AND
// - request is from https://github.com/hapijs/shot
// - or if http header SKIP_WEBPACK_DEV_MIDDLEWARE is set to true
//
// Param: req is the Node HTTP raw request (framework agnostic)
//
const skipWebpackDevMiddleware = req => {
const h = req.headers || {};
return (
h.FORCE_WEBPACK_DEV_MIDDLEWARE !== "true" &&
(h["user-agent"] === "shot" || h.SKIP_WEBPACK_DEV_MIDDLEWARE === "true")
);
};
export class Middleware {
_options: any;
canContinue: symbol;
_instanceId: number;
_hmrPath: string;
_webpackHotOptions: any;
devMiddleware: any;
hotMiddleware: any;
listAssetPath: string;
publicPath: string;
memFsCwd: string;
cwdMemIndex: any;
cwdIndex: any;
devBaseUrl: string;
devBaseUrlSlash: string;
cwdBaseUrl: string;
cwdContextBaseUrl: string;
reporterUrl: string;
dllDevUrl: string;
webpackDev: any;
returnReporter: any;
constructor(options) {
this._options = options;
this.canContinue = Symbol("webpack dev middleware continue");
this._instanceId = Date.now();
}
setup() {
const options = this._options;
let config = require(getWebpackStartConfig("webpack.config.dev.js", false)); // eslint-disable-line
if (config.__esModule) {
config = config.default;
}
this._hmrPath = controlPaths.hmr;
const webpackHotOptions = _.merge(
{
log: false,
path: formUrl({ ...fullDevServer, path: this._hmrPath }),
heartbeat: 2000
},
options.hot
);
this._webpackHotOptions = webpackHotOptions;
const encodeHmrPath = encodeURIComponent(webpackHotOptions.path);
// webpack 5 entry config: https://webpack.js.org/concepts/entry-points/
injectEntry(config, [`webpack-hot-middleware/client?path=${encodeHmrPath}`]);
console.log("Webpack config entry updated with HMR client");
config.plugins = [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
options.progress !== false && new webpack.ProgressPlugin({ profile: options.progressProfile })
]
.concat(config.plugins)
.filter(x => x);
const compiler = webpack(config);
const webpackDevOptions = _.merge(
{
// https: false,
// disableHostCheck: true,
headers: {
"Access-Control-Allow-Origin": "*"
},
// port: archetype.webpack.devPort,
// host: archetype.webpack.devHostname,
// quiet: false,
// lazy: false,
// watchOptions: {
// aggregateTimeout: 2000,
// poll: false
// },
stats: "errors-warnings",
publicPath: "/js",
serverSideRender: false
// clientLogLevel: "info"
},
options.common,
options.dev
);
this.devMiddleware = webpackDevMiddleware(compiler, webpackDevOptions);
this.hotMiddleware = webpackHotMiddleware(compiler, webpackHotOptions);
this.publicPath = webpackDevOptions.publicPath || "/";
this.listAssetPath = urlJoin(this.publicPath, "/");
const outputFileSystem: any = this.devMiddleware.context.outputFileSystem;
this.memFsCwd = outputFileSystem.existsSync(process.cwd()) ? process.cwd() : "/";
this.cwdMemIndex = serveIndex(this.memFsCwd, {
icons: true,
hidden: true,
fs: outputFileSystem,
path: Path.posix
});
this.cwdIndex = serveIndex(process.cwd(), { icons: true, hidden: true });
this.devBaseUrl = urlJoin(options.devBaseUrl || controlPaths.dev);
this.devBaseUrlSlash = urlJoin(this.devBaseUrl, "/");
this.cwdBaseUrl = urlJoin(this.devBaseUrl, "/cwd");
this.cwdContextBaseUrl = urlJoin(this.devBaseUrl, "/memfs");
this.reporterUrl = urlJoin(this.devBaseUrl, "/reporter");
this.dllDevUrl = urlJoin(this.devBaseUrl, "/dll");
this.webpackDev = {
lastReporterOptions: undefined,
hasErrors: false,
valid: false,
compileTime: 0
};
this.returnReporter = undefined;
const defaultReporter = (_middlewareOptions, reporterOptions) => {
if (!reporterOptions.state) {
process.send({
name: "webpack-report",
valid: false
});
console.log(ck`webpack bundle is now <magenta>INVALID</>`);
this.webpackDev.valid = false;
this.webpackDev.lastReporterOptions = false;
return;
}
const stats = reporterOptions.stats;
const error = stats.hasErrors() ? "<red> ERRORS</>" : "";
const warning = stats.hasWarnings() ? "<yellow> WARNINGS</>" : "";
const notOk = Boolean(error || warning);
const but = (notOk && "<yellow> but has</>") || "";
const showError = Boolean(error);
console.log(ck`webpack bundle is now <green>VALID</>${but}${error}${warning}`);
this.webpackDev.valid = true;
this.webpackDev.hasErrors = stats.hasErrors();
this.webpackDev.compileTime = Date.now();
const baseUrl = this._options.baseUrl;
if (notOk) {
console.log(ck`<cyan.underline>${urlJoin(baseUrl(), this.reporterUrl)}</> \
- View status and errors/warnings from your browser`);
}
if (this.webpackDev.lastReporterOptions === undefined) {
this.returnReporter = showError;
} else {
// keep returning reporter until a first success compile
this.returnReporter = this.returnReporter ? showError : false;
}
const refreshModules = [];
if (!this.webpackDev.hasErrors) {
const cwd = process.cwd() + "/";
const bundles = getBundles(reporterOptions.stats);
bundles.forEach(b => {
b.modules.forEach(m => {
if (m.indexOf("node_modules") >= 0) return;
if (m.indexOf("(webpack)") >= 0) return;
if (m.startsWith("multi ")) return;
// webpack4 output like "./routes.jsx + 9 modules"
const plusIx = m.indexOf(" + ");
let n = m;
if (plusIx > 0) n = m.substring(0, plusIx);
refreshModules.push(n.replace(cwd, ""));
});
});
}
this.webpackDev.lastReporterOptions = reporterOptions;
process.send({
name: "webpack-report",
valid: true,
hasErrors: stats.hasErrors(),
hasWarnings: stats.hasWarnings(),
refreshModules
});
};
compiler.hooks.done.tap("webpack-dev-middleware", stats => {
defaultReporter({}, { state: true, stats });
});
compiler.hooks.invalid.tap("webpack-dev-middleware", () => {
defaultReporter({}, { state: false });
});
}
process(req, res, cycle) {
const isHmrRequest =
req.url === this._hmrPath ||
(req.url.startsWith(this.publicPath) && req.url.indexOf(".hot-update.") >= 0);
if (skipWebpackDevMiddleware(req)) {
return Promise.resolve(cycle.skip());
}
if (!this.webpackDev.lastReporterOptions && !isHmrRequest) {
return Promise.resolve(
cycle.replyHtml(`<html><body>
<div style="margin-top: 50px; padding: 20px; border-radius: 10px; border: 2px solid red;">
<h2>Waiting for webpack dev middleware to finish compiling</h2>
</div><script>function doReload(x){ if (!x) location.reload(); setTimeout(doReload, 1000); }
doReload(1); </script></body></html>`)
);
}
const serveStatic = (
baseUrl,
fileSystem,
_serveIndex,
cwd = process.cwd(),
isMemFs = false
) => {
req.originalUrl = req.url; // this is what express saves to, else serve-index nukes
req.url = req.url.substr(baseUrl.length) || "/";
const PathLib = isMemFs ? Path.posix : Path;
const fullPath = PathLib.join(cwd, req.url);
return new Promise((resolve, reject) => {
fileSystem.stat(fullPath, (err, stats) => {
if (err) {
return reject(err);
} else if (stats.isDirectory()) {
res.once("end", resolve);
return _serveIndex(req, res, reject);
} else {
return fileSystem.readFile(fullPath, (err2, data) => {
if (err2) {
return reject(err);
} else {
return resolve(cycle.replyStaticData(data));
}
});
}
});
});
};
const sendStaticServeError = (msg, err) => {
return cycle.replyHtml(
`<html><body>
<div style="margin-top:50px;padding:20px;border-radius:10px;border:2px solid red;">
<h2>Error ${msg}</h2>
<div style="color: red;">${err.message}</div>
<h3>check <a href="${this.reporterUrl}">webpack reporter</a> to see if there're any errors.</h3>
</div></body></html>`
);
};
const serveReporter = reporterOptions => {
const stats = reporterOptions.stats;
const jsonData = stats.toJson({}, true);
const html = jsonToHtml(jsonData, true, undefined);
const jumpToError =
html.indexOf(`a name="error"`) > 0 || html.indexOf(`a name="warning"`) > 0
? `<script>(function(){var t = document.getElementById("anchor_warning") ||
document.getElementById("anchor_error");if (t) t.scrollIntoView();})();</script>`
: "";
return Promise.resolve(
cycle.replyHtml(`<html><body>
<div style="border-radius: 10px; background: black; color: gray; padding: 10px;">
<pre style="white-space: pre-wrap;">${html}</pre></div>
${jumpToError}</body></html>
`)
);
};
if (isHmrRequest) {
// do nothing and continue to webpack dev middleware
return Promise.resolve(this.canContinue);
} else if (req.url === this.publicPath || req.url === this.listAssetPath) {
const outputPath = Path.dirname(
getFilenameFromUrl(this.devMiddleware.context, this.publicPath)
);
const outputFileSystem = this.devMiddleware.context.outputFileSystem;
const listDirectoryHtml = (baseUrl, basePath) => {
return (
outputFileSystem.readdirSync(basePath).reduce((a, item) => {
const p = `${basePath}/${item}`;
if (outputFileSystem.statSync(p).isFile()) {
return `${a}<li><a href="${baseUrl}${item}">${item}</a></li>\n`;
} else {
return `${a}<li>${item}<br>` + listDirectoryHtml(`${baseUrl}${item}/`, p) + "</li>\n";
}
}, "<ul>") + "</ul>"
);
};
const html = `<html><head><meta charset="utf-8"/></head><body>
${listDirectoryHtml(this.listAssetPath, outputPath)}
</body></html>`;
return Promise.resolve(cycle.replyHtml(html));
} else if (req.url.startsWith(this.cwdBaseUrl)) {
return serveStatic(this.cwdBaseUrl, Fs, this.cwdIndex).catch(err => {
return sendStaticServeError(`reading file under CWD`, err);
});
} else if (req.url.startsWith(this.cwdContextBaseUrl)) {
const isMemFs = true;
return serveStatic(
this.cwdContextBaseUrl,
this.devMiddleware.context.outputFileSystem,
this.cwdMemIndex,
this.memFsCwd,
isMemFs
).catch(err => sendStaticServeError("reading webpack mem fs", err));
} else if (req.url.startsWith(this.reporterUrl) || this.returnReporter) {
return serveReporter(this.webpackDev.lastReporterOptions);
} else if (req.url.startsWith(this.dllDevUrl)) {
// App is requesting for Electrode DLL JS bundle
// extract DLL module and bundle name
const dllParts = req.url
.substr(this.dllDevUrl.length + 1)
.split("/")
.filter(x => x);
// module name is first
const modName = decodeURIComponent(dllParts[0]);
// bundle name is second
const bundle = require.resolve(`${modName}/dist/${dllParts[1]}`);
return Promise.resolve(cycle.replyFile(bundle));
} else if (req.url === this.devBaseUrl || req.url === this.devBaseUrlSlash) {
const html = `<html><head><meta charset="utf-8"/></head><body>
<h1>xarc Webpack Dev Server Dashboard</h1>
<h3><a href="${this.cwdBaseUrl}">View current working directory files</a></h3>
<h3><a href="${this.cwdContextBaseUrl}">View webpack dev memfs files</a></h3>
</body></html>`;
return Promise.resolve(cycle.replyHtml(html));
}
return Promise.resolve(this.canContinue);
}
} | the_stack |
import { ObjectUtils, OnInit } from '@plugcore/core';
import { AggregateOptions, BulkWriteOptions, CountDocumentsOptions, DeleteOptions, Filter, FindOptions, InsertOneOptions, OptionalUnlessRequiredId, UpdateFilter, UpdateOptions } from 'mongodb';
import { AuditedDocument, Collection, MongoDbRepositoryCfg, PaginationConf, PaginationResponse } from './mongodb.interfaces';
export class MongoDbRepository<Entity extends (Record<string, any> & AuditedDocument & { _id?: any }), EntityId extends keyof Entity> implements OnInit {
//
// Public attributes
//
private collection: Collection<Entity>;
private collectionDeletedEntries: Collection<Entity>;
//
// Private attributes
//
private configuration: MongoDbRepositoryCfg<Entity, EntityId>;
private deletedCollectionPrefix = 'deleted';
private userNotProvided = null;
/**
* In order to use this util class you have
* to provide a list of id fields, which will be
* used for update/query purposes
*/
constructor(configuration: MongoDbRepositoryCfg<Entity, EntityId>) {
this.configuration = configuration;
}
//
// DI Events
//
public async onInit() {
// Entity collection
this.collection = await this.configuration.dataSource.getCollection<Entity>(
this.configuration.collectionName
);
if (
this.configuration.indexes &&
Array.isArray(this.configuration.indexes) &&
this.configuration.indexes.length > 0
) {
await this.collection.createIndexes(this.configuration.indexes);
}
if (this.configuration.auditDeletedEntries) {
// Deleted entitities collection
this.collectionDeletedEntries = await this.configuration.dataSource.getCollection<Entity>(
this.deletedCollectionPrefix + this.capitalize(this.configuration.collectionName)
);
}
}
public static async create<Entity, EntityId extends keyof Entity>(
configuration: MongoDbRepositoryCfg<Entity, EntityId>
) {
const newInstance = new MongoDbRepository<Entity, EntityId>(configuration);
await newInstance.onInit();
return newInstance;
}
//
// Public methods
//
public async exists(id: Entity[EntityId], options?: CountDocumentsOptions) {
const result = await this.collection.countDocuments(
<any>{ [this.configuration.idAttribute]: id },
Object.assign(options || {}, { limit: 1 })
);
return result > 0;
}
public async existsWithQuery(query: Filter<Entity>, options?: CountDocumentsOptions) {
const result = await this.collection.countDocuments(
query,
Object.assign(options || {}, { limit: 1 })
);
return result > 0;
}
public async findAll(options?: FindOptions<Entity>) {
return this.collection.find({}, options).toArray();
}
public async findById(id: Entity[EntityId], options?: FindOptions<Entity>) {
return this.collection.findOne(<Entity>{ [this.configuration.idAttribute]: id }, options);
}
public async findByIds(ids: Entity[EntityId][], options?: FindOptions<Entity>) {
return this.collection.find(<Entity>{ [this.configuration.idAttribute]: { $in: ids } }, options).toArray();
}
public async paginate(
conf: PaginationConf<Entity>, options?: AggregateOptions
) {
const aggr: any[] = conf.previousAggregationSteps || [];
// Step 1: match
const match: Filter<Entity> = conf.customQuery || {};
if (conf.fieldsAsLike) {
for (const fieldKey of Object.keys(conf.fieldsAsLike)) {
if (conf.fieldsAsLike[fieldKey] !== undefined) {
(<any>match)[fieldKey] = new RegExp(`.*${conf.fieldsAsLike[fieldKey]}.*`, 'i');
}
}
}
if (conf.textSearch) {
match.$text = {
$search: typeof conf.textSearch === 'string' ?
conf.textSearch : `${conf.textSearch}`
};
}
if (Object.keys(match).length > 0) {
aggr.push({ $match: match });
}
// Step 2: Sort
if (conf.context && conf.context.sortField) {
aggr.push({
$sort: {
[conf.context.sortField]: conf.context.sortDirection || -1
}
});
} else if (conf.textSearch) {
aggr.push({
$sort: { score: { $meta: 'textScore' } }
});
} else if (conf.defaultSort) {
aggr.push({
$sort: {
[conf.defaultSort.field]: conf.defaultSort.direction || -1
}
});
}
// Step 3: Facet
const page = conf.context ? (conf.context.page || 0) : 0;
const delta = conf.context ? (conf.context.delta || 10) : 10;
const dontPaginate = conf.context && conf.context.page === -1 && conf.context.delta === -1;
aggr.push({
$facet: {
metadata: [{ $count: 'total' }],
data: dontPaginate ? [{ $match: {} }] : [{ $skip: page * delta }, { $limit: delta }]
}
});
const result: any[] = await this.collection.aggregate(aggr, options).toArray();
return <PaginationResponse<Entity>>{
data: result[0].data ? result[0].data : [],
totalDocuments: result[0].metadata[0] ? result[0].metadata[0].total : 0
};
}
public async createIfDoesntExists(
document: Entity,
user?: string, options?: UpdateOptions
) {
const copy = ObjectUtils.deepClone(document);
const pOptions = options || {};
pOptions.upsert = true;
const now = this.getNowDate();
return this.collection.updateOne(
{ [this.configuration.idAttribute]: copy[this.configuration.idAttribute] } as any,
{
$setOnInsert: {
...copy,
...(this.configuration.auditEditedEntries ? {
[<keyof AuditedDocument>'_auditCreate']: this.auditUpdateField(user, now),
[<keyof AuditedDocument>'_auditUpdate']: this.auditUpdateField(user, now)
} : {})
}
},
pOptions
);
}
public async insertOrUpdateOne(
document: Entity,
user?: string, options?: UpdateOptions,
ignoreAuditUpdate?: boolean
) {
const copy = ObjectUtils.deepClone(document);
delete copy._id;
const pOptions = options || {};
pOptions.upsert = true;
const now = this.getNowDate();
return this.collection.updateOne(
<any>{ [this.configuration.idAttribute]: copy[this.configuration.idAttribute] },
<any>{
$set: ignoreAuditUpdate ? copy : {
[<keyof AuditedDocument>'_auditUpdate']: this.auditUpdateField(user, now),
...copy
},
$setOnInsert: ignoreAuditUpdate ? {
[<keyof AuditedDocument>'_auditCreate']: this.auditUpdateField(user, now),
[<keyof AuditedDocument>'_auditUpdate']: this.auditUpdateField(user, now)
} :
{ [<keyof AuditedDocument>'_auditCreate']: this.auditUpdateField(user, now) }
},
pOptions
);
}
public async insertOrUpdateMany(
documents: Entity[],
user?: string, options?: BulkWriteOptions,
ignoreAuditUpdate?: boolean
) {
const nOptions = options || {};
nOptions.ordered = false;
const now = this.getNowDate();
return this.collection.bulkWrite(
documents.map(d => {
const copy = ObjectUtils.deepClone(d);
delete copy._id;
return <any>{ // TODO check why
updateOne: {
filter: { [this.configuration.idAttribute]: d[this.configuration.idAttribute] },
update: {
$set: ignoreAuditUpdate ? copy : {
[<keyof AuditedDocument>'_auditUpdate']: this.auditUpdateField(user, now),
...copy
},
$setOnInsert: ignoreAuditUpdate ? {
[<keyof AuditedDocument>'_auditCreate']: this.auditUpdateField(user, now),
[<keyof AuditedDocument>'_auditUpdate']: this.auditUpdateField(user, now)
} :
{ [<keyof AuditedDocument>'_auditCreate']: this.auditUpdateField(user, now) }
},
upsert: true
}
};
}),
nOptions
);
}
public async insertOne(
document: OptionalUnlessRequiredId<Entity>,
user?: string, options?: InsertOneOptions
) {
if (this.configuration.auditEditedEntries) {
document = this.addAuditFields(document, user);
}
if (document._id) {
delete (<any>document)._id;
}
if (options) {
return this.collection.insertOne(document, options);
} else {
return this.collection.insertOne(document);
}
}
public async insertMany(
documents: OptionalUnlessRequiredId<Entity>[],
user?: string, options?: BulkWriteOptions
) {
let documentsToInsert = documents;
if (this.configuration.auditEditedEntries) {
documentsToInsert = documentsToInsert.map(document => this.addAuditFields(document, user));
}
if (options) {
return this.collection.insertMany(documentsToInsert, options);
} else {
return this.collection.insertMany(documentsToInsert);
}
}
public async updateOne(
filter: Filter<Entity>,
update: UpdateFilter<Entity> | Partial<Entity>,
user?: string, options?: UpdateOptions
) {
if (this.configuration.auditEditedEntries) {
this.applyUpdateField(update, user);
}
if (options) {
return this.collection.updateOne(filter, update, options);
} else {
return this.collection.updateOne(filter, update);
}
}
public async updateMany(
filter: Filter<Entity>,
update: UpdateFilter<Entity> | Partial<Entity>,
user?: string, options?: UpdateOptions
) {
if (this.configuration.auditEditedEntries) {
this.applyUpdateField(update, user);
}
if (options) {
return this.collection.updateMany(filter, update, options);
} else {
return this.collection.updateMany(filter, update);
}
}
/**
* Updates an entity using it's id
* @param document
* @param user
*/
public async updateDocument(
document: (Pick<Entity, EntityId> & Partial<Entity>),
user?: string, options?: UpdateOptions
) {
if (document._id) {
delete document._id;
}
return this.updateOne(
<any>{ [this.configuration.idAttribute]: document[this.configuration.idAttribute] },
{ $set: document },
user, options
);
}
/**
* Updates an array of entities using it's id for each entitiy
* @param documents
* @param user
*/
public async updateDocuments(
documents: (Pick<Entity, EntityId> & Partial<Entity>)[],
user?: string, options?: BulkWriteOptions
) {
const nOptions = options || {};
nOptions.ordered = true;
return this.collection.bulkWrite(
documents.map(d => {
const copy = ObjectUtils.deepClone(d);
delete copy._id;
return <any>{ // TODO check why
updateOne: {
filter: { [this.configuration.idAttribute]: d[this.configuration.idAttribute] },
update: {
$set: {
[<keyof AuditedDocument>'_auditUpdate']: this.auditUpdateField(user),
...copy
},
}
}
};
}),
nOptions
);
}
public async deleteOne(
filter: Filter<Entity>,
user?: string, options?: DeleteOptions,
) {
if (this.configuration.auditDeletedEntries) {
const docToBelDEleted = await this.collection.findOne(filter);
if (docToBelDEleted) {
docToBelDEleted[<keyof AuditedDocument>'_auditUpdate'] = this.auditUpdateField(user);
try {
if (options) {
await this.collectionDeletedEntries.insertOne(
<any>docToBelDEleted, options
);
}
else {
await this.collectionDeletedEntries.insertOne(
<any>docToBelDEleted
);
}
} catch (error) {
if (options && options.session) {
this.collectionDeletedEntries = await this.configuration.dataSource.getConnection().createCollection(
this.deletedCollectionPrefix + this.capitalize(this.configuration.collectionName)
);
await this.collectionDeletedEntries.insertOne(
<any>docToBelDEleted, options
);
} else {
throw error;
}
}
}
}
if (options) {
return this.collection.deleteOne(filter, options);
} else {
return this.collection.deleteOne(filter);
}
}
public async deleteMany(
filter: Filter<Entity>,
user?: string, options?: DeleteOptions
) {
if (this.configuration.auditDeletedEntries) {
const docsToBelDEleted = await this.collection.find(filter as any).toArray();
if (docsToBelDEleted && docsToBelDEleted.length > 0) {
await this.collectionDeletedEntries.bulkWrite(docsToBelDEleted.map((d: any) => {
delete d._id;
d = this.addAuditFields(d, user);
return <any>{
insertOne: { document: d }
};
}), { ordered: false });
}
}
if (options) {
return this.collection.deleteMany(filter, options);
} else {
return this.collection.deleteMany(filter,);
}
}
public async deleteDocument(
id: Entity[EntityId],
user?: string, options?: DeleteOptions
) {
return this.deleteOne(<any>{ [this.configuration.idAttribute]: id }, user, options);
}
public async deleteDocuments(
ids: Entity[EntityId][],
user?: string, options?: DeleteOptions
) {
return this.deleteMany(<any>{ [this.configuration.idAttribute]: { $in: ids } }, user, options);
}
public getCollection() {
return this.collection;
}
public getConfiguration() {
return this.configuration;
}
// Private methods
private getNowDate() {
const now = new Date();
return now.getTime();
}
private capitalize(inp: string) {
return inp.charAt(0).toUpperCase() + inp.slice(1);
}
private isUpdateQuery(update: Filter<Entity> | Partial<Entity>): update is Filter<Entity> {
return (
update.$set !== undefined ||
update.$unset !== undefined ||
update.$inc !== undefined ||
update.$setOnInsert !== undefined ||
update.$addToSet !== undefined ||
update.$max !== undefined ||
update.$min !== undefined ||
update.$pull !== undefined ||
update.$pullAll !== undefined ||
update.$pop !== undefined ||
update.$push !== undefined ||
update.$rename !== undefined ||
update.$currentDate !== undefined ||
update.$bit !== undefined
);
}
private applyUpdateField(update: UpdateFilter<Entity> | Partial<Entity>, user?: string) {
if (this.isUpdateQuery(update)) {
if (update.$set) {
(<any>update.$set)[<keyof AuditedDocument>'_auditUpdate'] = this.auditUpdateField(user);
} else {
(update as UpdateFilter<Entity>).$set = <any>{
[<keyof AuditedDocument>'_auditUpdate']: this.auditUpdateField(user)
};
}
} else {
update[<keyof AuditedDocument>'_auditUpdate'] = this.auditUpdateField(user);
}
}
private auditUpdateField(user?: string, useNow?: number): AuditedDocument['_auditUpdate'] {
const now = useNow || this.getNowDate();
return {
date: now,
user: user || this.userNotProvided
};
}
private addAuditFields(document?: OptionalUnlessRequiredId<Entity>, user?: string, useNow?: number): OptionalUnlessRequiredId<Entity> {
const copy = document ? ObjectUtils.deepClone(document) : <OptionalUnlessRequiredId<Entity>>{};
const now = useNow || this.getNowDate();
copy._auditCreate = copy._auditCreate || {
date: now,
user: user || this.userNotProvided
};
copy._auditUpdate = copy._auditCreate || {
date: now,
user: user || this.userNotProvided
};
return copy;
}
} | the_stack |
import { DynamsoftEnums } from "./Dynamsoft.Enum";
import { WebTwain } from "./WebTwain";
import { Settings } from "./Addon.OCRPro";
import { FileUploader } from "./Dynamsoft.FileUploader";
export namespace DynamsoftStatic {
let Lib: DynamsoftLib;
let MSG: Messages;
let WebTwainEnv: WebTwainEnv;
let managerEnv: ManagerEnv;
let FileUploader: FileUploader;
namespace WebTwain {
namespace Addon {
namespace OCRPro {
function NewSettings(): Settings;
}
}
}
}
export interface DWTInitialConfig {
WebTwainId: string;
Host?: string | undefined;
Port?: string | undefined;
SSLPort?: string | undefined;
}
export interface DynamsoftLib {
/**
* A built-in method to set up a listener for the specified event type on the target element.
* @param target Specify the HTML element.
* @param type Specify the event
* @param listener Specify the callback
*/
addEventListener(target: HTMLElement, type: string, listener: EventListenerOrEventListenerObject): void;
/**
* Whether to enable debugging. Once enabled, debugging inforamtion is printed out in the browser console.
*/
debug: boolean;
detect: DSLibDetect;
env: DSLibEnv;
/**
* Hide the built-in page mask
*/
hideMask(): void;
/**
* Show the built-in page mask
*/
showMask(): void;
/**
* Load the specified script.
* @param url Specify the URL of the script.
* @param bAsync Whether to load the script asynchronously.
* @param callback Callback function triggered when the script is loaded.
*/
getScript(url: string, bAsync: boolean, callback: () => void): void;
/**
* Load the specified scripts.
* @param urls Specify the URLs of the scripts.
* @param bAsync Whether to load the script asynchronously.
* @param callback Callback function triggered when the scripts are all loaded.
*/
getScripts(urls: string[], bAsync: boolean, callback: () => void): void;
dlgLoadingShowStatus: boolean;
product: Product;
/**
* The following Functions & Options are internal & ignored
*
* Addon_Events, Addon_Sendback_Events, Attributes, BGR2RGB, BIO, DOM,
* DynamicLoadAddonFuns, DynamicWebTwain, EnumMouseButton, Errors,
* Events, File, Index, IntToColorStr, LS, License, MobileFuns, Path,
* ProgressBar, RGB2BGR, ShowLicenseDialog, UI, Uri
* ajax, all, appendMessage, appendRichMessage, asyncQueue, atob,
* attachAddon, attachProperty, attachPropertyUI, base64, bio, btoa,
* cancelFrome, checkDomReady, checkNavInfoReady, clearMessage, clone,
* closeAll, closeLoadingMsg, closeProgress, colorStrToInt, config,css,
* currentStyle, detectButton, dialog, dialogShowStatus, dlgLoading,
* dlgLoadingShowStatus, dlgProgress, dlgRef, doc, domReady,
* each, empty, endsWith, error, escapeHtml, escapeRegExp, extend,
* filter, fireEvent, fromUnicode, get, getAllCss, getColor, getCss,
* getElDimensions, getHex, getHttpUrl, getLogger, getNavInfo,
* getNavInfoByUAData, getNavInfoByUserAgent, getNavInfoSync, getRandom,
* getRealPath, getWS, getWSUrl, getWheelDelta, globalEval, guid, hide,
* html5, indexOf, initProgress, install,io, isArray, isBoolean, isDef,
* isFunction, isLocalIP, isNaN, isNodeList, isNull, isNumber, isObject,
* isPlainObject, isString, isUndef, isUndefined, isWindow, keys, makeArray,
* mask, mix, needShowTwiceShowDialog, nil, noop, now, obj, one, openLoadingMsg,
* page, param, parse, parseHTML, progressMessage, ready,
* removeEventListener, replaceAll, replaceControl, setBtnCancelVisibleForProgress,
* show, showLoadingMsg, showProgress, showProgressMsg, sizzle, sprintf, startWS,
* startWSByIP, startsWith, stopPropagation, stringify, style, support, switchEvent,
* tmp, toggle, trim, type, unEscapeHtml, uniq, unparam, upperCaseFirst, uriQuery,
* urlDecode, urlEncode, utf8, vsprintf, win
*/
}
export interface DSLibDetect {
/**
* Whether or not the site is secure (Https://).
*/
readonly ssl: boolean;
readonly scriptLoaded: boolean;
/**
* The following Functions & Options are internal & ignored
* OnCreatWS, OnDetectNext, StartWSByIPTimeoutId, StartWSTimeoutId,
* aryReconnectSTwains, arySTwains, arySTwainsByIP, bFirst,
* bNeedUpgradeEvent, bNoControlEvent, bOK, bPromptJSOrServerOutdated,
* cUrlIndex, cssLoaded, dcpCallbackType, dcpStatus, detectType, getVersionArray,
* isDWTVersionLatest, needUpgrade, onNoControl, onNotAllowedForChrome, ports,
* starting, tryTimes, urls, viewerScriptLoaded, wasmScriptLoaded,
* OnWebTwainPostExecute, OnWebTwainPreExecute, hideMask, showMask,
* win64Ports, __WebTwainMain, __dialog
*/
}
export interface DSLibEnv {
/**
* Whether the browser is Chrome.
*/
readonly bChrome: boolean;
/**
* Whether the browser is Edge.
*/
readonly bEdge: boolean;
/**
* Whether the page is opening from the disk.
*/
readonly bFileSystem: boolean;
/**
* Whether the browser is Firefox.
*/
readonly bFirefox: boolean;
/**
* Whether the browser is IE.
*/
readonly bIE: boolean;
/**
* Whether the browser is Safari.
*/
readonly bSafari: boolean;
/**
* Whether the operating system is Linux.
*/
readonly bLinux: boolean;
/**
* Whether the operating system is macOS.
*/
readonly bMac: boolean;
/**
* Whether the operating system is mobile (Android & iOS & iPadOS).
*/
readonly bMobile: boolean;
/**
* Whether the operating system is Windows.
*/
readonly bWin: boolean;
/**
* Whether the operating system is 64bit Windows.
*/
readonly bWin64: boolean;
/**
* The base path.
*/
readonly basePath: string;
/**
* The WebSocket session id.
*/
readonly WSSession: number;
/**
* The WebSocket version.
*/
readonly WSVersion: string;
/**
* The plugin lenghth.
*/
readonly iPluginLength: number;
/**
* Whether it is a desktop viewer.
*/
isDesktopViewer(): boolean;
/**
* Whether it is a mobile viewer.
*/
isMobileViewer(): boolean;
/**
* Whether it is a pad viewer.
*/
isPadViewer(): boolean;
/**
* Whether the platform is 64bit.
*/
readonly isX64: boolean;
/**
* Information about macOSX.
*/
readonly macOSX: string;
/**
* OS version.
*/
readonly osVersion: string;
/**
* The path type used to calculate the real path.
*/
readonly pathType: number;
/**
* The version of Chrome.
*/
readonly strChromeVersion: number | string;
/**
* The version of Firefox.
*/
readonly strFirefoxVersion: number | string;
/**
* The version of IE.
*/
readonly strIEVersion: number | string;
}
export interface WebTwainEnv {
/**
* Whether to install the ActiveX with CAB.
*/
ActiveXInstallWithCAB: boolean;
/**
* The version of the ActiveX;
*/
readonly ActiveXVersion: string;
/**
* Whether to create a WebTwain instance automatically upon page load.
*/
AutoLoad: boolean;
/**
* Close a dialog opened by the method ShowDialog.
*/
CloseDialog(): void;
/**
* A map of all WebTwain instances.
*/
ContainerMap: any;
/**
* Define the Id and UI of the WebTwain instances.
*/
Containers: Container[];
/**
* Create a WebTwain instance with UI.
* @param ContainerId Specify the HTML element (typically of the type HTMLDivElement) to hold the UI.
* @param host Specify the host.
* @param port Specify the port.
* @param portSSL Specify the SSL port.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
*/
CreateDWTObject(
ContainerId: string,
host: string,
port: string | number,
portSSL: string | number,
successCallBack: (DWObject: WebTwain) => void,
failureCallBack: (errorString: string) => void): void;
/**
* Create a WebTwain instance with UI.
* @param ContainerId Specify the HTML element (typically of the type HTMLDivElement) to hold the UI.
* @param host Specify the host.
* @param port Specify the port.
* @param portSSL Specify the SSL port.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
*/
CreateDWTObject(ContainerId: string, successCallBack: (DWObject: WebTwain) => void, failureCallBack: (errorString: string) => void): void;
/**
* Create a WebTwain instance without UI.
* @param WebTwainId Specify the Id of the instance.
* @param successCallback A callback function that is executed if the request succeeds.
* @param failureCallback A callback function that is executed if the request fails.
*/
CreateDWTObjectEx(dwtInitialConfig: DWTInitialConfig, successCallBack: (DWObject: WebTwain) => void, failureCallBack: (errorString: string) => void): void;
/**
* Define the display info.
*/
CustomizableDisplayInfo: DisplayInfo;
/**
* Remove and destroy a WebTwain instance.
* @param Id Specify the instance with its ContainerId or WebTwainId.
*/
DeleteDWTObject(Id: string): boolean;
/**
* Return the WebTwain instance specified by its ContainerId. If no parameter is provided, the first valid WebTwain instance is returnd.
* @param ContainerId The ContainerId.
*/
GetWebTwain(ContainerId?: string): WebTwain;
/**
* Return the WebTwain instance specified by its WebTwainId. If no parameter is provided, the first valid WebTwain instance is returnd.
* @param WebTwainId The WebTwainId.
*/
GetWebTwainEx(WebTwainId?: string): WebTwain;
/**
* Whether or not an md5 header `dwt-md5` should be included in HTTP upload requests.
*/
IfAddMD5InUploadHeader: boolean;
/**
* Whether to confine the mask within the viewer element.
*/
IfConfineMaskWithinTheViewer: boolean;
/**
* Whether to use ActiveX for IE 10 & 11.
*/
IfUseActiveXForIE10Plus: boolean;
/**
* The version of the JavaScript script.
*/
readonly JSVersion: string;
/**
* Create a WebTwain instance(s).
*/
Load(): void;
/**
* A callback function that is executed when the WebTwain related files are not found.
*/
OnWebTwainNotFound: () => {};
/**
* A callback function that is executed after a time-consuming operation.
*/
OnWebTwainPostExecute: () => {};
/**
* A callback function that is executed before a time-consuming operation.
*/
OnWebTwainPreExecute: () => {};
/**
* A callback function that is executed when a WebTwain instance is created.
*/
OnWebTwainReady: () => {};
/**
* A callback function that is executed right before the creation of a WebTwain instance.
*/
OnWebTwainWillInit: () => {};
/**
* The version of the PDF module (not the rasterizer).
*/
PdfVersion: string;
/**
* The version of the plug-in edition.
*/
PluginVersion: string;
/**
* Set or return the product key for the library. A product key is required to enables certain modules of the library.
*/
ProductKey: string;
/**
* The product name.
*/
readonly ProductName: string;
/**
* Attach the callback function to the specified event.
* @param event Specify the event.
* @param callback Specify the callback.
*/
RegisterEvent(event: string, callback: (...args: any[]) => void): void;
/**
* Remove all authorizations for accessing local resources.
*/
RemoveAllAuthorizations(): void;
/**
* Set or return where the library looks for resources files including service installers, CSS, etc.
*/
ResourcesPath: string;
/**
* The version of the Linux edition (the service, not wasm).
*/
ServerLinuxVersionInfo: string;
/**
* The version of the macOS edition (the service, not wasm).
*/
ServerMacVersionInfo: string;
/**
* The version of the Windows edition (the service, not wasm).
*/
ServerVersionInfo: string;
/**
* Built-in method to show a modal dialog.
* @param width Width of the dialog.
* @param height Height of the dialog.
* @param content Content of the dialog.
* @param simple Whether to show a simple dialog with no header.
* @param hideCloseButton Whether to hide the close button.
*/
ShowDialog(width: number, height: number, content: string, simple: boolean, hideCloseButton: boolean): void;
/**
* Remove and destroy all WebTwain instances.
*/
Unload(): void;
/**
* Whether to download the wasm for Camera Addon to use on initialization.
*/
UseCameraAddonWasm: boolean;
/**
* Whether to use the library in Local-Service mode or WASM mode.
*/
UseLocalService: boolean;
ConnectToTheService: () => void;
initQueue: any[];
/**
* The following Functions & Options are internal & ignored
* ActiveXIntegerited, CheckConnectToTheService,
* ContainerMap, Debug, DynamicContainers,
* DynamicDWTMap, GetLocalServiceStatus,IfCheck64bitServiceFirst,
* IfCheckDCP, IfCheckDWT,
* IfDisableDefaultSettings, IfDownload64bitService,
* IfInstallDWTModuleWithZIP, IfUpdateService,
* IfUseEmbeddedDownloadNoticeForActiveX, IfUseViewer,
* OnWebTwainInitMessage, OnWebTwainNeedUpgrade,
* OnWebTwainNeedUpgradeWebJavascript, OnWebTwainInitMessage
* OnWebTwainOldPluginNotAllowed, OnWebTwainOldPluginNotAllowed
* Trial, UseDefaultInstallUI, ViewerJSIntegerited,
* inited, _srcUseLocalService
*/
}
export interface DisplayInfo {
buttons: any;
customProgressText: any;
dialogText: any;
errorMessages: any;
generalMessages: any;
}
/**
* Define default messages.
*/
export interface Messages {
ConvertingToBase64: string;
ConvertingToBlob: string;
Downloading: string;
Encoding: string;
Err_BrowserNotSupportWasm: string;
Init_AllJsLoaded: string;
Init_CheckDWT: string;
Init_CheckDWTVersion: string;
Init_CheckingLicense: string;
Init_CompilingWasm: string;
Init_ConfiguringDWT: string;
Init_CreatingDWT: string;
Init_DownloadingWasm: string;
Init_FireBeforeInitEvt: string;
Init_GetLicenseInfoForDWT: string;
Init_InitActiveX: string;
Init_InitDynamsoftService: string;
Init_InitH5: string;
Init_InitWasm: string;
Init_LoadingViewerJs: string;
Init_LookingLicense: string;
Init_SetLicenseForDWT: string;
Loading: string;
LoadingPdf: string;
LoadingTiff: string;
SavingPdf: string;
SavingTiff: string;
Uploading: string;
}
export interface ManagerEnv {
IfUpdateService: boolean;
resourcesPath: string;
}
/**
* Interface for a WebTwain profile.
*/
export interface Container {
WebTwainId: string;
ContainerId?: string | undefined;
Width?: string | number | undefined;
Height?: string | number | undefined;
bNoUI?: boolean | undefined;
bLocalService?: boolean | undefined;
}
export interface Product {
bActiveXEdition: boolean;
bChromeEdition: boolean;
bHTML5Edition: boolean;
bPluginEdition: boolean;
host: string;
name: string;
}
declare const Dynamsoft: (typeof DynamsoftEnums & typeof DynamsoftStatic);
export default Dynamsoft; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Logger } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ApiManagementClient } from "../apiManagementClient";
import {
LoggerContract,
LoggerListByServiceNextOptionalParams,
LoggerListByServiceOptionalParams,
LoggerListByServiceResponse,
LoggerGetEntityTagOptionalParams,
LoggerGetEntityTagResponse,
LoggerGetOptionalParams,
LoggerGetResponse,
LoggerCreateOrUpdateOptionalParams,
LoggerCreateOrUpdateResponse,
LoggerUpdateContract,
LoggerUpdateOptionalParams,
LoggerUpdateResponse,
LoggerDeleteOptionalParams,
LoggerListByServiceNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Logger operations. */
export class LoggerImpl implements Logger {
private readonly client: ApiManagementClient;
/**
* Initialize a new instance of the class Logger class.
* @param client Reference to the service client
*/
constructor(client: ApiManagementClient) {
this.client = client;
}
/**
* Lists a collection of loggers in the specified service instance.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
public listByService(
resourceGroupName: string,
serviceName: string,
options?: LoggerListByServiceOptionalParams
): PagedAsyncIterableIterator<LoggerContract> {
const iter = this.listByServicePagingAll(
resourceGroupName,
serviceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
);
}
};
}
private async *listByServicePagingPage(
resourceGroupName: string,
serviceName: string,
options?: LoggerListByServiceOptionalParams
): AsyncIterableIterator<LoggerContract[]> {
let result = await this._listByService(
resourceGroupName,
serviceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByServiceNext(
resourceGroupName,
serviceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByServicePagingAll(
resourceGroupName: string,
serviceName: string,
options?: LoggerListByServiceOptionalParams
): AsyncIterableIterator<LoggerContract> {
for await (const page of this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
)) {
yield* page;
}
}
/**
* Lists a collection of loggers in the specified service instance.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
private _listByService(
resourceGroupName: string,
serviceName: string,
options?: LoggerListByServiceOptionalParams
): Promise<LoggerListByServiceResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, options },
listByServiceOperationSpec
);
}
/**
* Gets the entity state (Etag) version of the logger specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param loggerId Logger identifier. Must be unique in the API Management service instance.
* @param options The options parameters.
*/
getEntityTag(
resourceGroupName: string,
serviceName: string,
loggerId: string,
options?: LoggerGetEntityTagOptionalParams
): Promise<LoggerGetEntityTagResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, loggerId, options },
getEntityTagOperationSpec
);
}
/**
* Gets the details of the logger specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param loggerId Logger identifier. Must be unique in the API Management service instance.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serviceName: string,
loggerId: string,
options?: LoggerGetOptionalParams
): Promise<LoggerGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, loggerId, options },
getOperationSpec
);
}
/**
* Creates or Updates a logger.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param loggerId Logger identifier. Must be unique in the API Management service instance.
* @param parameters Create parameters.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
serviceName: string,
loggerId: string,
parameters: LoggerContract,
options?: LoggerCreateOrUpdateOptionalParams
): Promise<LoggerCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, loggerId, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* Updates an existing logger.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param loggerId Logger identifier. Must be unique in the API Management service instance.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param parameters Update parameters.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
serviceName: string,
loggerId: string,
ifMatch: string,
parameters: LoggerUpdateContract,
options?: LoggerUpdateOptionalParams
): Promise<LoggerUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
serviceName,
loggerId,
ifMatch,
parameters,
options
},
updateOperationSpec
);
}
/**
* Deletes the specified logger.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param loggerId Logger identifier. Must be unique in the API Management service instance.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
serviceName: string,
loggerId: string,
ifMatch: string,
options?: LoggerDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, loggerId, ifMatch, options },
deleteOperationSpec
);
}
/**
* ListByServiceNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param nextLink The nextLink from the previous successful call to the ListByService method.
* @param options The options parameters.
*/
private _listByServiceNext(
resourceGroupName: string,
serviceName: string,
nextLink: string,
options?: LoggerListByServiceNextOptionalParams
): Promise<LoggerListByServiceNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, nextLink, options },
listByServiceNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByServiceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.LoggerCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.filter,
Parameters.top,
Parameters.skip,
Parameters.apiVersion
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const getEntityTagOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers/{loggerId}",
httpMethod: "HEAD",
responses: {
200: {
headersMapper: Mappers.LoggerGetEntityTagHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.loggerId
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers/{loggerId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.LoggerContract,
headersMapper: Mappers.LoggerGetHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.loggerId
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers/{loggerId}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.LoggerContract,
headersMapper: Mappers.LoggerCreateOrUpdateHeaders
},
201: {
bodyMapper: Mappers.LoggerContract,
headersMapper: Mappers.LoggerCreateOrUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters40,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.loggerId
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch
],
mediaType: "json",
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers/{loggerId}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.LoggerContract,
headersMapper: Mappers.LoggerUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters41,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.loggerId
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch1
],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers/{loggerId}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.loggerId
],
headerParameters: [Parameters.accept, Parameters.ifMatch1],
serializer
};
const listByServiceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.LoggerCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.filter,
Parameters.top,
Parameters.skip,
Parameters.apiVersion
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
namespace com.keyman.osk {
// Base class for a banner above the keyboard in the OSK
export abstract class Banner {
private _height: number; // pixels
private div: HTMLDivElement;
public static DEFAULT_HEIGHT: number = 37; // pixels; embedded apps can modify
public static readonly BANNER_CLASS: string = 'kmw-banner-bar';
public static readonly BANNER_ID: string = 'kmw-banner-bar';
/**
* Function height
* Scope Public
* @returns {number} height in pixels
* Description Returns the height of the banner in pixels
*/
public get height(): number {
return this._height;
}
/**
* Function height
* Scope Public
* @param {number} height the height in pixels
* Description Sets the height of the banner in pixels. If a negative
* height is given, set height to 0 pixels.
* Also updates the banner styling.
*/
public set height(height: number) {
this._height = (height > 0) ? height : 0;
this.update();
}
/**
* Function update
* @return {boolean} true if the banner styling changed
* Description Update the height and display styling of the banner
*/
private update() : boolean {
let ds = this.div.style;
let currentHeightStyle = ds.height;
let currentDisplayStyle = ds.display;
if (this._height > 0) {
ds.height = this._height + 'px';
ds.display = 'block';
} else {
ds.height = '0px';
ds.display = 'none';
}
return (!(currentHeightStyle === ds.height) ||
!(currentDisplayStyle === ds.display));
}
public constructor(height?: number) {
let keymanweb = com.keyman.singleton;
let util = keymanweb.util;
let d = util._CreateElement('div');
d.id = Banner.BANNER_ID;
d.className = Banner.BANNER_CLASS;
this.div = d;
this.height = height;
this.update();
}
public appendStyleSheet() {
let keymanweb = com.keyman.singleton;
let util = keymanweb.util;
// TODO: add stylesheets
}
/**
* Function getDiv
* Scope Public
* @returns {HTMLElement} Base element of the banner
* Description Returns the HTMLElelemnt of the banner
*/
public getDiv(): HTMLElement {
return this.div;
}
/**
* Function activate
* Scope Public
* Description Adds any relevant event listeners needed by this banner type.
*/
public activate() {
// Default implementation - no listeners.
}
/**
* Function activate
* Scope Public
* Description Removes any relevant event listeners previously added by this banner.
*/
public deactivate() {
// Default implementation - no listeners.
}
}
/**
* Function BlankBanner
* Description A banner of height 0 that should not be shown
*/
export class BlankBanner extends Banner {
constructor() {
super(0);
}
}
/**
* Function ImageBanner
* @param {string} imagePath Path of image to display in the banner
* @param {number} height If provided, the height of the banner in pixels
* Description Display an image in the banner
*/
export class ImageBanner extends Banner {
private img: HTMLElement;
constructor(imagePath: string, height?: number) {
if (imagePath.length > 0) {
super();
if (height) {
this.height = height;
}
} else {
super(0);
}
if(imagePath.indexOf('base64') >=0) {
console.log("Loading img from base64 data");
} else {
console.log("Loading img with src '" + imagePath + "'");
}
this.img = document.createElement('img');
this.img.setAttribute('src', imagePath);
let ds = this.img.style;
ds.width = '100%';
ds.height = '100%';
this.getDiv().appendChild(this.img);
console.log("Image loaded.");
}
/**
* Function setImagePath
* Scope Public
* @param {string} imagePath Path of image to display in the banner
* Description Update the image in the banner
*/
public setImagePath(imagePath: string) {
if (this.img) {
this.img.setAttribute('src', imagePath);
}
}
}
export class BannerSuggestion {
div: HTMLDivElement;
private display: HTMLSpanElement;
private fontFamily?: string;
private _suggestion: Suggestion;
private index: number;
static readonly BASE_ID = 'kmw-suggestion-';
constructor(index: number) {
let keyman = com.keyman.singleton;
this.index = index;
this.constructRoot();
// Provides an empty, base SPAN for text display. We'll swap these out regularly;
// `Suggestion`s will have varying length and may need different styling.
let display = this.display = keyman.util._CreateElement('span');
this.div.appendChild(display);
}
private constructRoot() {
let keyman = com.keyman.singleton;
// Add OSK suggestion labels
let div = this.div = keyman.util._CreateElement('div'), ds=div.style;
div.className = "kmw-suggest-option";
div.id = BannerSuggestion.BASE_ID + this.index;
let kbdDetails = keyman.keyboardManager.activeStub;
if(kbdDetails) {
if (kbdDetails['KLC']) {
div.lang = kbdDetails['KLC'];
}
// Establish base font settings
let font = kbdDetails['KFont'];
if(font && font.family && font.family != '') {
ds.fontFamily = this.fontFamily = font.family;
}
}
// Ensures that a reasonable width % is set.
let usableWidth = 100 - SuggestionBanner.MARGIN * (SuggestionBanner.SUGGESTION_LIMIT - 1);
let widthpc = usableWidth / SuggestionBanner.SUGGESTION_LIMIT;
ds.width = widthpc + '%';
this.div['suggestion'] = this;
}
get suggestion(): Suggestion {
return this._suggestion;
}
/**
* Function update
* @param {string} id Element ID for the suggestion span
* @param {Suggestion} suggestion Suggestion from the lexical model
* Description Update the ID and text of the BannerSuggestionSpec
*/
public update(suggestion: Suggestion) {
this._suggestion = suggestion;
this.updateText();
}
private updateText() {
let display = this.generateSuggestionText();
this.div.replaceChild(display, this.display);
this.display = display;
}
/**
* Function apply
* @param target (Optional) The OutputTarget to which the `Suggestion` ought be applied.
* Description Applies the predictive `Suggestion` represented by this `BannerSuggestion`.
*/
public apply(target?: text.OutputTarget): Promise<Reversion> {
let keyman = com.keyman.singleton;
if(this.isEmpty()) {
return null;
}
if(!target) {
/* Assume it's the currently-active `OutputTarget`. We should probably invalidate
* everything if/when the active `OutputTarget` changes, though we haven't gotten that
* far in implementation yet.
*/
target = dom.Utils.getOutputTarget();
}
if(this._suggestion.tag == 'revert') {
keyman.core.languageProcessor.applyReversion(this._suggestion as Reversion, target);
return null;
} else {
return keyman.core.languageProcessor.applySuggestion(this.suggestion, target);
}
}
public isEmpty(): boolean {
return !this._suggestion;
}
/**
* Function generateSuggestionText
* @return {HTMLSpanElement} Span element of the suggestion
* Description Produces a HTMLSpanElement with the key's actual text.
*/
//
public generateSuggestionText(): HTMLSpanElement {
let keyman = com.keyman.singleton;
let util = keyman.util;
let suggestion = this._suggestion;
var suggestionText: string;
var s=util._CreateElement('span');
s.className = 'kmw-suggestion-text';
if(suggestion == null) {
return s;
}
if(suggestion.displayAs == null || suggestion.displayAs == '') {
suggestionText = '\xa0'; // default: nbsp.
} else {
// Default the LTR ordering to match that of the active keyboard.
let activeKeyboard = keyman.core.activeKeyboard;
let rtl = activeKeyboard && activeKeyboard.isRTL;
let orderCode = rtl ? 0x202e /* RTL */ : 0x202d /* LTR */;
suggestionText = String.fromCharCode(orderCode) + suggestion.displayAs;
}
// TODO: Dynamic suggestion text resizing. (Refer to OSKKey.getTextWidth in visualKeyboard.ts.)
// Finalize the suggestion text
s.innerHTML = suggestionText;
return s;
}
}
/**
* Function SuggestionBanner
* Scope Public
* @param {number} height - If provided, the height of the banner in pixels
* Description Display lexical model suggestions in the banner
*/
export class SuggestionBanner extends Banner {
public static readonly SUGGESTION_LIMIT: number = 3;
public static readonly MARGIN = 1;
private options : BannerSuggestion[];
private hostDevice: utils.DeviceSpec;
private manager: SuggestionManager;
static readonly TOUCHED_CLASS: string = 'kmw-suggest-touched';
static readonly BANNER_CLASS: string = 'kmw-suggest-banner';
constructor(hostDevice: utils.DeviceSpec, height?: number) {
super(height || Banner.DEFAULT_HEIGHT);
this.hostDevice = hostDevice;
this.getDiv().className = this.getDiv().className + ' ' + SuggestionBanner.BANNER_CLASS;
this.options = new Array();
for (var i=0; i<SuggestionBanner.SUGGESTION_LIMIT; i++) {
let d = new BannerSuggestion(i);
this.options[i] = d;
}
/* LTR behavior: the default (index 0) suggestion should be at the left
* RTL behavior: the default (index 0) suggestion should be at the right
*
* The cleanest way to make it work - simply invert the order in which
* the elements are inserted for RTL. This allows the banner to be RTL
* for visuals/UI while still being internally LTR.
*/
let activeKeyboard = com.keyman.singleton.core.activeKeyboard;
let rtl = activeKeyboard && activeKeyboard.isRTL;
for (var i=0; i<SuggestionBanner.SUGGESTION_LIMIT; i++) {
let indexToInsert = rtl ? SuggestionBanner.SUGGESTION_LIMIT - i -1 : i;
this.getDiv().appendChild(this.options[indexToInsert].div);
if(i != SuggestionBanner.SUGGESTION_LIMIT) {
// Adds a 'separator' div element for UI purposes.
let separatorDiv = com.keyman.singleton.util._CreateElement('div');
separatorDiv.className = 'kmw-banner-separator';
let ds = separatorDiv.style;
ds.marginLeft = (SuggestionBanner.MARGIN / 2) + '%';
ds.marginRight = (SuggestionBanner.MARGIN / 2) + '%';
this.getDiv().appendChild(separatorDiv);
}
}
this.manager = new SuggestionManager(this.getDiv(), this.options);
this.setupInputHandling();
}
private setupInputHandling() {
let inputEngine: InputEventEngine;
if(this.hostDevice.touchable) { // /*&& ('ontouchstart' in window)*/ // Except Chrome emulation doesn't set this.
// Not to mention, it's rather redundant.
inputEngine = TouchEventEngine.forPredictiveBanner(this, this.manager);
} else {
inputEngine = MouseEventEngine.forPredictiveBanner(this, this.manager);
}
inputEngine.registerEventHandlers();
}
activate() {
let keyman = com.keyman.singleton;
let manager = this.manager;
keyman.core.languageProcessor.addListener('invalidatesuggestions', manager.invalidateSuggestions);
keyman.core.languageProcessor.addListener('suggestionsready', manager.updateSuggestions);
keyman.core.languageProcessor.addListener('tryaccept', manager.tryAccept);
keyman.core.languageProcessor.addListener('tryrevert', manager.tryRevert);
}
postConfigure() {
let keyman = com.keyman.singleton;
// Trigger a null-based initial prediction to kick things off.
keyman.core.languageProcessor.predictFromTarget(dom.Utils.getOutputTarget());
}
deactivate() {
let keyman = com.keyman.singleton;
let manager = this.manager;
keyman.core.languageProcessor.removeListener('invalidatesuggestions', manager.invalidateSuggestions);
keyman.core.languageProcessor.removeListener('suggestionsready', manager.updateSuggestions);
keyman.core.languageProcessor.removeListener('tryaccept', manager.tryAccept);
keyman.core.languageProcessor.removeListener('tryrevert', manager.tryRevert);
}
}
export class SuggestionManager extends UITouchHandlerBase<HTMLDivElement> {
private selected: BannerSuggestion;
platformHold: (suggestion: BannerSuggestion, isCustom: boolean) => void;
//#region Touch handling implementation
findTargetFrom(e: HTMLElement): HTMLDivElement {
let keyman = com.keyman.singleton;
let util = keyman.util;
try {
if(e) {
if(util.hasClass(e,'kmw-suggest-option')) {
return e as HTMLDivElement;
}
if(e.parentNode && util.hasClass(<HTMLElement> e.parentNode,'kmw-suggest-option')) {
return e.parentNode as HTMLDivElement;
}
// if(e.firstChild && util.hasClass(<HTMLElement> e.firstChild,'kmw-suggest-option')) {
// return e.firstChild as HTMLDivElement;
// }
}
} catch(ex) {}
return null;
}
protected highlight(t: HTMLDivElement, on: boolean): void {
let classes = t.className;
let cs = ' ' + SuggestionBanner.TOUCHED_CLASS;
if(t.id.indexOf(BannerSuggestion.BASE_ID) == -1) {
console.warn("Cannot find BannerSuggestion object for element to highlight!");
} else {
// Never highlight an empty suggestion button.
let suggestion = this.selected = t['suggestion'] as BannerSuggestion;
if(suggestion.isEmpty()) {
on = false;
this.selected = null;
}
}
if(on && classes.indexOf(cs) < 0) {
t.className=classes+cs;
} else {
t.className=classes.replace(cs,'');
}
}
protected select(t: HTMLDivElement): void {
this.doAccept(t['suggestion'] as BannerSuggestion);
}
//#region Long-press support
protected hold(t: HTMLDivElement): void {
let suggestionObj = t['suggestion'] as BannerSuggestion;
// Is this the <keep> suggestion? It's never in this.currentSuggestions, so check against that.
let isCustom = this.currentSuggestions.indexOf(suggestionObj.suggestion) == -1;
if(this.platformHold) {
// Implemented separately for native + embedded mode branches.
// Embedded mode should pass any info needed to show a submenu IMMEDIATELY.
this.platformHold(suggestionObj, isCustom); // No implementation yet for native.
}
}
protected clearHolds(): void {
// Temp, pending implementation of suggestion longpress submenus
// - nothing to clear without them -
// only really used in native-KMW
}
protected hasModalPopup(): boolean {
// Utilized by the mobile apps; allows them to 'take over' touch handling,
// blocking it within KMW when the apps are already managing an ongoing touch-hold.
let keyman = com.keyman.singleton;
return keyman['osk'].vkbd.subkeyGesture && keyman.isEmbedded;
}
protected dealiasSubTarget(target: HTMLDivElement): HTMLDivElement {
return target;
}
protected hasSubmenu(t: HTMLDivElement): boolean {
// Temp, pending implementation of suggestion longpress submenus
// Only really used by native-KMW - see kmwnative's highlightSubKeys func.
return false;
}
protected isSubmenuActive(): boolean {
// Temp, pending implementation of suggestion longpress submenus
// Utilized only by native-KMW - it parallels hasModalPopup() in purpose.
return false;
}
protected displaySubmenuFor(target: HTMLDivElement) {
// Utilized only by native-KMW to show submenus.
throw new Error("Method not implemented.");
}
//#endregion
//#endregion
private options: BannerSuggestion[];
private initNewContext: boolean = true;
private currentSuggestions: Suggestion[] = [];
private keepSuggestion: Keep;
private revertSuggestion: Reversion;
private recentAccept: boolean = false;
private revertAcceptancePromise: Promise<Reversion>;
private swallowPrediction: boolean = false;
private doRevert: boolean = false;
private recentRevert: boolean = false;
constructor(div: HTMLElement, options: BannerSuggestion[]) {
// TODO: Determine appropriate CSS styling names, etc.
super(div, Banner.BANNER_CLASS, SuggestionBanner.TOUCHED_CLASS);
this.options = options;
}
private doAccept(suggestion: BannerSuggestion) {
let _this = this;
this.revertAcceptancePromise = suggestion.apply();
if(!this.revertAcceptancePromise) {
// We get here either if suggestion acceptance fails or if it was a reversion.
if(suggestion.suggestion && suggestion.suggestion.tag == 'revert') {
// Reversion state management
this.recentAccept = false;
this.doRevert = false;
this.recentRevert = true;
this.doUpdate();
}
return;
}
this.revertAcceptancePromise.then(function(suggestion) {
// Always null-check!
if(suggestion) {
_this.revertSuggestion = suggestion;
}
});
this.selected = null;
this.recentAccept = true;
this.doRevert = false;
this.recentRevert = false;
this.swallowPrediction = true;
this.doUpdate();
}
private showRevert() {
// Construct a 'revert suggestion' to facilitate a reversion UI component.
this.doRevert = true;
this.doUpdate();
}
/**
* Receives messages from the keyboard that the 'accept' keystroke has been entered.
* Should return 'false' if the current state allows accepting a suggestion and act accordingly.
* Otherwise, return true.
*/
tryAccept: (source: string) => boolean = function(this: SuggestionManager, source: string, returnObj: {shouldSwallow: boolean}) {
let keyman = com.keyman.singleton;
if(!this.recentAccept && this.selected) {
this.doAccept(this.selected);
returnObj.shouldSwallow = true;
} else if(this.recentAccept && source == 'space') {
this.recentAccept = false;
// If the model doesn't insert wordbreaks, don't swallow the space. If it does,
// we consider that insertion to be the results of the first post-accept space.
returnObj.shouldSwallow = !!keyman.core.languageProcessor.wordbreaksAfterSuggestions;
} else {
returnObj.shouldSwallow = false;
}
}.bind(this);
/**
* Receives messages from the keyboard that the 'revert' keystroke has been entered.
* Should return 'false' if the current state allows reverting a recently-applied suggestion and act accordingly.
* Otherwise, return true.
*/
tryRevert: () => boolean = function(this: SuggestionManager, returnObj: {shouldSwallow: boolean}) {
// Has the revert keystroke (BKSP) already been sent once since the last accept?
if(this.doRevert) {
// If so, clear the 'revert' option and start doing normal predictions again.
this.doRevert = false;
this.recentAccept = false;
// Otherwise, did we just accept something before the revert signal was received?
} else if(this.recentAccept) {
this.showRevert();
this.swallowPrediction = true;
}
// We don't yet actually do key-based reversions.
returnObj.shouldSwallow = false;
return;
}.bind(this);
/**
* Function invalidateSuggestions
* Scope Public
* Description Clears the suggestions in the suggestion banner
*/
public invalidateSuggestions: (this: SuggestionManager, source: text.prediction.InvalidateSourceEnum) => boolean =
function(this: SuggestionManager, source: string) {
// By default, we assume that the context is the same until we notice otherwise.
this.initNewContext = false;
if(!this.swallowPrediction || source == 'context') {
this.recentAccept = false;
this.doRevert = false;
this.recentRevert = false;
if(source == 'context') {
this.swallowPrediction = false;
this.initNewContext = true;
}
}
this.options.forEach((option: BannerSuggestion) => {
option.update(null);
});
}.bind(this);
public activateKeep(): boolean {
return !this.recentAccept && !this.recentRevert && !this.initNewContext;
}
private doUpdate() {
let suggestions = [];
// Insert 'current text' if/when valid as the leading option.
// Since we don't yet do auto-corrections, we only show 'keep' whenever it's
// a valid word (according to the model).
if(this.activateKeep() && this.keepSuggestion && this.keepSuggestion.matchesModel) {
suggestions.push(this.keepSuggestion);
} else if(this.doRevert) {
suggestions.push(this.revertSuggestion);
}
suggestions = suggestions.concat(this.currentSuggestions);
this.options.forEach((option: BannerSuggestion, i: number) => {
if(i < suggestions.length) {
option.update(suggestions[i]);
} else {
option.update(null);
}
});
}
/**
* Function updateSuggestions
* Scope Public
* @param {Suggestion[]} suggestions Array of suggestions from the lexical model.
* Description Update the displayed suggestions in the SuggestionBanner
*/
public updateSuggestions: (this: SuggestionManager, prediction: text.prediction.ReadySuggestions) => boolean =
function(this: SuggestionManager, prediction: text.prediction.ReadySuggestions) {
let suggestions = prediction.suggestions;
this.currentSuggestions = suggestions;
// Do we have a keep suggestion? If so, remove it from the list so that we can control its display position
// and prevent it from being hidden after reversion operations.
this.keepSuggestion = null;
for(let s of suggestions) {
if(s.tag == 'keep') {
this.keepSuggestion = s as Keep;
}
}
if(this.keepSuggestion) {
this.currentSuggestions.splice(this.currentSuggestions.indexOf(this.keepSuggestion), 1);
}
// If we've gotten an update request like this, it's almost always user-triggered and means the context has shifted.
if(!this.swallowPrediction) {
this.recentAccept = false;
this.doRevert = false;
this.recentRevert = false;
} else { // This prediction was triggered by a recent 'accept.' Now that it's fulfilled, we clear the flag.
this.swallowPrediction = false;
}
// The rest is the same, whether from input or from "self-updating" after a reversion to provide new suggestions.
this.doUpdate();
}.bind(this);
}
} | the_stack |
'use strict';
import URI from 'vs/base/common/uri';
import {TPromise} from 'vs/base/common/winjs.base';
import {IDisposable} from 'vs/base/common/lifecycle';
import {IRequestHandler} from 'vs/base/common/worker/simpleWorker';
import {Range} from 'vs/editor/common/core/range';
import {fuzzyContiguousFilter} from 'vs/base/common/filters';
import {DiffComputer} from 'vs/editor/common/diff/diffComputer';
import * as editorCommon from 'vs/editor/common/editorCommon';
import {MirrorModel2} from 'vs/editor/common/model/mirrorModel2';
import {IInplaceReplaceSupportResult, ILink, ISuggestResult, ISuggestion} from 'vs/editor/common/modes';
import {computeLinks} from 'vs/editor/common/modes/linkComputer';
import {BasicInplaceReplace} from 'vs/editor/common/modes/supports/inplaceReplaceSupport';
import {IRawModelData} from 'vs/editor/common/services/editorSimpleWorkerCommon';
import {getWordAtText, ensureValidWordDefinition} from 'vs/editor/common/model/wordHelper';
import {createMonacoBaseAPI} from 'vs/editor/common/standalone/standaloneBase';
export interface IMirrorModel {
uri: URI;
version: number;
getValue(): string;
}
export interface IWorkerContext {
/**
* Get all available mirror models in this worker.
*/
getMirrorModels(): IMirrorModel[];
}
/**
* @internal
*/
export interface ICommonModel {
uri: URI;
version: number;
getValue(): string;
getLinesContent(): string[];
getLineCount(): number;
getLineContent(lineNumber:number): string;
getWordUntilPosition(position: editorCommon.IPosition, wordDefinition:RegExp): editorCommon.IWordAtPosition;
getAllUniqueWords(wordDefinition:RegExp, skipWordOnce?:string) : string[];
getValueInRange(range:editorCommon.IRange): string;
getWordAtPosition(position:editorCommon.IPosition, wordDefinition:RegExp): Range;
}
/**
* @internal
*/
export class MirrorModel extends MirrorModel2 implements ICommonModel {
public get uri(): URI {
return this._uri;
}
public get version(): number {
return this._versionId;
}
public getValue(): string {
return this.getText();
}
public getLinesContent(): string[] {
return this._lines.slice(0);
}
public getLineCount(): number {
return this._lines.length;
}
public getLineContent(lineNumber:number): string {
return this._lines[lineNumber - 1];
}
public getWordAtPosition(position:editorCommon.IPosition, wordDefinition:RegExp): Range {
let wordAtText = getWordAtText(
position.column,
ensureValidWordDefinition(wordDefinition),
this._lines[position.lineNumber - 1],
0
);
if (wordAtText) {
return new Range(position.lineNumber, wordAtText.startColumn, position.lineNumber, wordAtText.endColumn);
}
return null;
}
public getWordUntilPosition(position: editorCommon.IPosition, wordDefinition:RegExp): editorCommon.IWordAtPosition {
var wordAtPosition = this.getWordAtPosition(position, wordDefinition);
if (!wordAtPosition) {
return {
word: '',
startColumn: position.column,
endColumn: position.column
};
}
return {
word: this._lines[position.lineNumber - 1].substring(wordAtPosition.startColumn - 1, position.column - 1),
startColumn: wordAtPosition.startColumn,
endColumn: position.column
};
}
private _getAllWords(wordDefinition:RegExp): string[] {
var result:string[] = [];
this._lines.forEach((line) => {
this._wordenize(line, wordDefinition).forEach((info) => {
result.push(line.substring(info.start, info.end));
});
});
return result;
}
public getAllUniqueWords(wordDefinition:RegExp, skipWordOnce?:string) : string[] {
var foundSkipWord = false;
var uniqueWords = {};
return this._getAllWords(wordDefinition).filter((word) => {
if (skipWordOnce && !foundSkipWord && skipWordOnce === word) {
foundSkipWord = true;
return false;
} else if (uniqueWords[word]) {
return false;
} else {
uniqueWords[word] = true;
return true;
}
});
}
// TODO@Joh, TODO@Alex - remove these and make sure the super-things work
private _wordenize(content:string, wordDefinition:RegExp): editorCommon.IWordRange[] {
var result:editorCommon.IWordRange[] = [];
var match:RegExpExecArray;
while (match = wordDefinition.exec(content)) {
if (match[0].length === 0) {
// it did match the empty string
break;
}
result.push({ start: match.index, end: match.index + match[0].length });
}
return result;
}
public getValueInRange(range:editorCommon.IRange): string {
if (range.startLineNumber === range.endLineNumber) {
return this._lines[range.startLineNumber - 1].substring(range.startColumn - 1, range.endColumn - 1);
}
var lineEnding = this._eol,
startLineIndex = range.startLineNumber - 1,
endLineIndex = range.endLineNumber - 1,
resultLines:string[] = [];
resultLines.push(this._lines[startLineIndex].substring(range.startColumn - 1));
for (var i = startLineIndex + 1; i < endLineIndex; i++) {
resultLines.push(this._lines[i]);
}
resultLines.push(this._lines[endLineIndex].substring(0, range.endColumn - 1));
return resultLines.join(lineEnding);
}
}
/**
* @internal
*/
export abstract class BaseEditorSimpleWorker {
private _foreignModule: any;
constructor() {
this._foreignModule = null;
}
protected abstract _getModel(uri:string): ICommonModel;
protected abstract _getModels(): ICommonModel[];
// ---- BEGIN diff --------------------------------------------------------------------------
public computeDiff(originalUrl:string, modifiedUrl:string, ignoreTrimWhitespace:boolean): TPromise<editorCommon.ILineChange[]> {
let original = this._getModel(originalUrl);
let modified = this._getModel(modifiedUrl);
if (!original || !modified) {
return null;
}
let originalLines = original.getLinesContent();
let modifiedLines = modified.getLinesContent();
let diffComputer = new DiffComputer(originalLines, modifiedLines, {
shouldPostProcessCharChanges: true,
shouldIgnoreTrimWhitespace: ignoreTrimWhitespace,
shouldConsiderTrimWhitespaceInEmptyCase: true
});
return TPromise.as(diffComputer.computeDiff());
}
public computeDirtyDiff(originalUrl:string, modifiedUrl:string, ignoreTrimWhitespace:boolean):TPromise<editorCommon.IChange[]> {
let original = this._getModel(originalUrl);
let modified = this._getModel(modifiedUrl);
if (!original || !modified) {
return null;
}
let originalLines = original.getLinesContent();
let modifiedLines = modified.getLinesContent();
let diffComputer = new DiffComputer(originalLines, modifiedLines, {
shouldPostProcessCharChanges: false,
shouldIgnoreTrimWhitespace: ignoreTrimWhitespace,
shouldConsiderTrimWhitespaceInEmptyCase: false
});
return TPromise.as(diffComputer.computeDiff());
}
// ---- END diff --------------------------------------------------------------------------
public computeLinks(modelUrl:string):TPromise<ILink[]> {
let model = this._getModel(modelUrl);
if (!model) {
return null;
}
return TPromise.as(computeLinks(model));
}
// ---- BEGIN suggest --------------------------------------------------------------------------
public textualSuggest(modelUrl:string, position: editorCommon.IPosition, wordDef:string, wordDefFlags:string): TPromise<ISuggestResult> {
let model = this._getModel(modelUrl);
if (!model) {
return null;
}
return TPromise.as(this._suggestFiltered(model, position, new RegExp(wordDef, wordDefFlags)));
}
private _suggestFiltered(model:ICommonModel, position: editorCommon.IPosition, wordDefRegExp: RegExp): ISuggestResult {
let value = this._suggestUnfiltered(model, position, wordDefRegExp);
// filter suggestions
return {
currentWord: value.currentWord,
suggestions: value.suggestions.filter((element) => !!fuzzyContiguousFilter(value.currentWord, element.label)),
incomplete: value.incomplete
};
}
private _suggestUnfiltered(model:ICommonModel, position:editorCommon.IPosition, wordDefRegExp: RegExp): ISuggestResult {
let currentWord = model.getWordUntilPosition(position, wordDefRegExp).word;
let allWords = model.getAllUniqueWords(wordDefRegExp, currentWord);
let suggestions = allWords.filter((word) => {
return !(/^-?\d*\.?\d/.test(word)); // filter out numbers
}).map((word) => {
return <ISuggestion> {
type: 'text',
label: word,
insertText: word,
noAutoAccept: true
};
});
return {
currentWord: currentWord,
suggestions: suggestions
};
}
// ---- END suggest --------------------------------------------------------------------------
public navigateValueSet(modelUrl:string, range:editorCommon.IRange, up:boolean, wordDef:string, wordDefFlags:string): TPromise<IInplaceReplaceSupportResult> {
let model = this._getModel(modelUrl);
if (!model) {
return null;
}
let wordDefRegExp = new RegExp(wordDef, wordDefFlags);
if (range.startColumn === range.endColumn) {
range.endColumn += 1;
}
let selectionText = model.getValueInRange(range);
let wordRange = model.getWordAtPosition({ lineNumber: range.startLineNumber, column: range.startColumn }, wordDefRegExp);
let word: string = null;
if (wordRange !== null) {
word = model.getValueInRange(wordRange);
}
let result = BasicInplaceReplace.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up);
return TPromise.as(result);
}
// ---- BEGIN foreign module support --------------------------------------------------------------------------
public loadForeignModule(moduleId:string, createData:any): TPromise<string[]> {
return new TPromise<any>((c, e) => {
// Use the global require to be sure to get the global config
(<any>self).require([moduleId], (foreignModule) => {
let ctx: IWorkerContext = {
getMirrorModels: ():IMirrorModel[] => {
return this._getModels();
}
};
this._foreignModule = foreignModule.create(ctx, createData);
let methods: string[] = [];
for (let prop in this._foreignModule) {
if (typeof this._foreignModule[prop] === 'function') {
methods.push(prop);
}
}
c(methods);
}, e);
});
}
// foreign method request
public fmr(method:string, args:any[]): TPromise<any> {
if (!this._foreignModule || typeof this._foreignModule[method] !== 'function') {
return TPromise.wrapError(new Error('Missing requestHandler or method: ' + method));
}
try {
return TPromise.as(this._foreignModule[method].apply(this._foreignModule, args));
} catch (e) {
return TPromise.wrapError(e);
}
}
// ---- END foreign module support --------------------------------------------------------------------------
}
/**
* @internal
*/
export class EditorSimpleWorkerImpl extends BaseEditorSimpleWorker implements IRequestHandler, IDisposable {
_requestHandlerTrait: any;
private _models:{[uri:string]:MirrorModel;};
constructor() {
super();
this._models = Object.create(null);
}
public dispose(): void {
this._models = Object.create(null);
}
protected _getModel(uri:string): ICommonModel {
return this._models[uri];
}
protected _getModels(): ICommonModel[] {
let all: MirrorModel[] = [];
Object.keys(this._models).forEach((key) => all.push(this._models[key]));
return all;
}
public acceptNewModel(data:IRawModelData): void {
this._models[data.url] = new MirrorModel(URI.parse(data.url), data.value.lines, data.value.EOL, data.versionId);
}
public acceptModelChanged(strURL: string, events: editorCommon.IModelContentChangedEvent2[]): void {
if (!this._models[strURL]) {
return;
}
let model = this._models[strURL];
model.onEvents(events);
}
public acceptRemovedModel(strURL: string): void {
if (!this._models[strURL]) {
return;
}
delete this._models[strURL];
}
}
/**
* Called on the worker side
* @internal
*/
export function create(): IRequestHandler {
return new EditorSimpleWorkerImpl();
}
var global:any = self;
let isWebWorker = (typeof global.importScripts === 'function');
if (isWebWorker) {
global.monaco = createMonacoBaseAPI();
} | the_stack |
import electron, { app, BrowserWindow, dialog, shell, session } from 'electron'
import path from "path"
import url from 'url'
import fs from 'fs'
import process from 'process'
import child_process from 'child_process'
import Electron from 'electron'
const Menu = electron.Menu;
const Tray = electron.Tray;
const ipc = electron.ipcMain;
const exec = child_process.exec;
var appTray : Electron.Tray = null;
var appQuit = false
var appIco : Electron.NativeImage = null;
var appDir = process.cwd().replace(/\\/g, '/') ;
var appCanQuit = false;
var mainWindow : Electron.BrowserWindow = null;
var crashedWindow : Electron.BrowserWindow = null;
async function createMainWindow () {
appIco = Electron.nativeImage.createFromPath(path.posix.join(appDir, require('../assets/images/logo.ico')));
console.log('createMainWindow');
mainWindow = new BrowserWindow({
minWidth: 710,
minHeight: 500,
frame: false,
transparent: false,
fullscreen: false,
resizable: true,
show: false,
icon: appIco,
webPreferences: {
webSecurity: false,
nodeIntegration: true,
enableRemoteModule: true,
},
})
mainWindow.setMenu(null)
mainWindow.webContents.on('render-process-gone', (event, detail) => {
genErrorReport();
showCrashedWindow();
destroyMainWindow();
});
mainWindow.webContents.on('devtools-reload-page', () => {
if(!mainWindow.isMinimized()) mainWindow.restore();
if(!mainWindow.isFocused()) mainWindow.focus();
});
mainWindow.on('closed', () => {
if(appTray != null) {
appTray.destroy();
appTray = null;
}
mainWindow = null
})
mainWindow.on('unresponsive', () => {
dialog.showMessageBox(mainWindow, {
type: 'info',
message: '软件可能卡住了,需要一些时间让其完成工作。',
title: '抱歉,软件出现了一些故障',
detail: '如果它长时间没有响应,可能是软件故障。您可以尝试强制重新加载页面',
noLink: true,
buttons: [ '等待其响应', '强制重新加载页面' ],
}).then((value) => {
if(value.response == 1) {
mainWindow.reload();
}
})
});
mainWindow.on('close',(e) => {
if(!appQuit){
e.preventDefault();
mainWindow.hide();
}
});
mainWindow.once('ready-to-show', () => mainWindow.show())
await mainWindow.loadURL(getPagePath('renderer.html'));
if(process.env.NODE_ENV == 'development') {
mainWindow.webContents.once('devtools-opened', () => mainWindow.focus());
mainWindow.webContents.openDevTools();
}
createMainMenu();
}
function createMainMenu() {
var trayMenuTemplate = [
{
label: '显示主界面',
click: function () { mainWindow.show(); mainWindow.focus(); }
},
{
label: '退出',
click: function () {
if(appCanQuit) {
mainWindow.show();
mainWindow.webContents.send('main-window-act', 'show-exit-dialog');
}else {
dialog.showMessageBox(mainWindow, {
message: '是否要退出程序',
noLink: true,
buttons: [ '取消', '退出' ]
}).then((value) => {
if(value.response == 1) {
appQuit = true;
app.quit();
}
}).catch(() => {})
}
}
}
];
const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
appTray = new Tray(appIco);
appTray.setToolTip('Blueprint');
appTray.setContextMenu(contextMenu);
appTray.on('click', () => mainWindow.show())
}
function destroyMainWindow() {
appQuit = true;
appCanQuit = false;
mainWindow.removeAllListeners();
mainWindow.close();
mainWindow = null;
}
function recreateWindow(event : Event, submitErrReport : boolean) {
if(mainWindow == null) createMainWindow();
if(submitErrReport) submitErrorReport();
if(crashedWindow != null) crashedWindow.close();
}
/**
* Get page path at dist
* @param basePath
* @param hash
*/
function getPagePath(basePath : string, hash? : string) {
return url.format({
pathname: path.join(appDir, basePath),
protocol: 'file:',
slashes: true,
hash: hash
})
}
function showCrashedWindow() {
crashedWindow = new BrowserWindow({
width: 560,
height: 410,
frame: true,
transparent: false,
fullscreen: false,
resizable: false,
minimizable: false,
icon: appIco,
webPreferences: {
webSecurity: false,
nodeIntegration: true,
disableBlinkFeatures: "",
},
})
crashedWindow.setMenu(null)
crashedWindow.loadURL(getPagePath('crashed.html'));
crashedWindow.on('close', () => crashedWindow = null);
}
function genErrorReport() {
}
function submitErrorReport() {
}
//Inits
function initBasePath(callback : () => void) {
appDir = appDir.replace(/\\/g, '/');
if(fs.existsSync(appDir + '/dist/renderer.html')) appDir = appDir + '/dist/';
else if(fs.existsSync(appDir + '/dist/development/renderer.html')) appDir = appDir + '/dist/development/';
else if(fs.existsSync(appDir + '/resources/app/renderer.html')) appDir = appDir + '/resources/app/';
else if(fs.existsSync(appDir + '/resources/app.asar')) appDir = appDir + '/resources/app.asar/';
console.log(`appDir: ${appDir}`);
callback();
}
function initApp() {
app.on('ready', async () => {
//installVueDevTools
let devtoolsPath = appDir + 'extensions/vue-devtools';
//Old api
//BrowserWindow.addDevToolsExtension(devtoolsPath);
//For new version
try {
if(fs.existsSync(devtoolsPath))
await session.defaultSession.loadExtension(devtoolsPath).then((e) => {
console.log('vue-devtools Extension : ' + e.id);
}).catch((e) => {
console.error(e);
})
}catch(e) {
console.error(e);
}
try { await createMainWindow(); }
catch(e) {
dialog.showErrorBox("发生了错误", "抱歉,应用发生了一个错误,现在应用将会关闭\n" + e);
app.exit(-1);
}
})
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) createMainWindow()
})
app.on('web-contents-created', (event, contents) => {
let errCount = 0;
contents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame, frameProcessId, frameRoutingId) => {
if(contents == mainWindow.webContents)
appCanQuit = false;
let failedPageUrl = getPagePath('neterr.html');
errCount ++;
if(errCount < 10 && contents.getURL() != failedPageUrl) {
contents.loadURL(failedPageUrl);
contents.executeJavaScript('document.getElementById(\'global-error-info-code\').innerText = \''+errorDescription+'('+errorCode+')\'');
}else {
dialog.showErrorBox('发生了错误', '加载页面时发生错误\nURL: ' +
validatedURL + '\n错误代码: ' + errorDescription + ' (' + errorCode + ')');
}
});
contents.on('will-navigate', (event, navigationUrl) => {
const parsedUrl = new URL(navigationUrl)
if(parsedUrl.protocol == 'file:') {
console.log('navigate to file : ' + parsedUrl.pathname);
}else if(parsedUrl.protocol == 'http:' || parsedUrl.protocol == 'https:') {
event.preventDefault();
dialog.showMessageBox(mainWindow, {
title: '打开外部链接',
message: '您是否需要在浏览器中打开外部链接?',
detail: '目标链接:' + navigationUrl,
buttons: [ '在浏览器中打开此页面', '取消打开' ]
}).then((value) => {
if(value.response == 0) shell.openExternal(navigationUrl)
}).catch(() => {});
}
});
contents.on('new-window', async (event, navigationUrl) => {
const parsedUrl = new URL(navigationUrl);
if(parsedUrl.protocol != 'devtools:' && parsedUrl.protocol != 'file:'){
console.log(parsedUrl);
event.preventDefault();
shell.openExternal(navigationUrl)
}
})
})
}
function initIpcs() {
ipc.on('main-open-file-dialog-image', (event, arg) => {
var properties = ['openFile'];
dialog.showOpenDialog(mainWindow, {
properties: <any>properties,
title: '选择图片文件',
filters: [
{ name: '图像文件', extensions: ['bmp', 'jpg', 'png'] },
{ name: '所有文件', extensions: ['*'] }
],
}).then((value) => {
if (value) event.sender.send('selected-image', arg, value.filePaths)
}).catch((e) => console.log(e))
})
ipc.on('main-open-file-dialog-json', (event, arg) => {
var properties = ['openFile'];
dialog.showOpenDialog(mainWindow, {
properties: <any>properties,
title: '选择 JSON 数据文件',
filters: [
{ name: 'JSON 数据文件', extensions: ['json'] },
{ name: '所有文件', extensions: ['*'] }
],
}).then((value) => {
if (value) event.sender.send('selected-json', arg, value.filePaths)
}).catch((e) => console.log(e))
})
ipc.on('main-save-file-dialog-json', (event, arg) => {
dialog.showSaveDialog(mainWindow, {
title: '保存 JSON 数据文件',
filters: [
{ name: arg.filename ? arg.filename : 'JSON 数据文件', extensions: ['json'] }
]
}).then((value) => {
if (arg) arg.isSave = true;
if (value) event.sender.send('selected-json', arg, value.filePath)
}).catch((e) => console.log(e));
})
ipc.on('main-act-recreate', recreateWindow);
ipc.on('main-act-main-standby', (event, arg) => appCanQuit = arg);
ipc.on('main-act-quit', (event, arg) => { appQuit = true; app.quit(); });
ipc.on('main-act-reload', (event) => {
if(mainWindow && event.sender == mainWindow.webContents)
mainWindow.webContents.loadURL(getPagePath('renderer.html'))
});
ipc.on('main-act-toggle-devtools', (event) => {
if(mainWindow)
if(mainWindow.webContents.isDevToolsOpened()) mainWindow.webContents.closeDevTools();
else mainWindow.webContents.openDevTools();
});
ipc.on('main-act-run-shell', (event, arg) => {
let workerProcess
//console.log('run command : ' + arg.command);
workerProcess = exec(arg.command)
workerProcess.stdout.on('data', function (data) {
event.sender.send('shell-data', arg, data)
});
});
}
//Init start
try {
initBasePath(() => {
initApp();
initIpcs();
})
}catch(e) {
dialog.showErrorBox("发生了错误", "抱歉,应用发生了一个错误,现在应用将会关闭\n" + e);
app.exit(-1);
} | the_stack |
module CriticalEffects {
interface Dict<T> {
[key: string]: T;
}
interface NumDict<T> {
[key: number]: T;
}
type EffectsFunction = (target: Critter) => void;
const generalRegionName: { [region: number]: string } = {
0: "head", 1: "leftArm", 2: "rightArm", 3: "torso", 4: "rightLeg", 5: "leftLeg", 6: "eyes", 7: "groin", 8: "uncalled"
};
// TODO: make this table account for different weapon types. It appears melee weapons use a second one
// though it appears to only be a /2 for melee
export const regionHitChanceDecTable: { [region: string]: number } = {
"torso": 0, "leftLeg": 20, "rightLeg": 20, "groin": 30, "leftArm": 30, "rightArm": 30, "head": 40, "eyes": 60
};
let critterTable: Dict<CritType[]>[];
const critFailEffects: Dict<EffectsFunction> = {
damageSelf: function(target: Critter) {
console.log(target.name + " has damaged themselves. This does not do anything yet")
},
crippleRandomAppendage: function(target: Critter) {
console.log(target.name + " has crippled a random appendage. This does not do anything yet")
},
hitRandomly: function(target: Critter) {
console.log(target.name + " has hit randomly. This does not do anything yet")
},
hitSelf: function(target: Critter) {
console.log(target.name + " has hit themselves. This does not do anything yet")
},
loseAmmo: function(target: Critter) {
console.log(target.name + " has lost their ammo. This does not do anything yet")
},
destroyWeapon: function(target: Critter) {
console.log(target.name + " has had their weapon blow up in their face. Ouch. This does not do anything yet")
}
}
const critterEffects: Dict<(target: Critter) => void> = {
knockout: function(target: Critter) {
console.log(target.name + " has been knocked out. This does not do anything yet")
},
knockdown: function(target: Critter) {
console.log(target.name + " has been knocked down. This does not do anything yet")
},
crippledLeftLeg: function(target: Critter) {
console.log(target.name + " has been crippled in the left leg. This does not do anything yet")
},
crippledRightLeg: function(target: Critter) {
console.log(target.name + " has been crippled in the right leg. This does not do anything yet")
},
crippledLeftArm: function(target: Critter) {
console.log(target.name + " has been crippled in the left arm. This does not do anything yet")
},
crippledRightArm: function(target: Critter) {
console.log(target.name + " has been crippled in the right arm. This does not do anything yet")
},
blinded: function(target: Critter) {
console.log(target.name + " has been blinded by delight. This does not do anything yet")
},
death: function(target: Critter) {
console.log(target.name + " has met the reaperpony. This does not do anything yet")
},
onFire: function(target: Critter) {
console.log(target.name + " just got a flame lit in their heart. This does not do anything yet")
},
bypassArmor: function(target: Critter) {
console.log(target.name + " is being hit by an armor bypassing bullet, blame the Zebras. This does not do anything yet")
},
droppedWeapon: function(target: Critter) {
console.log(target.name + " needs to drop their weapon like it's hot. The documentation claims this is broken. This does not do anything yet")
},
loseNextTurn: function(target: Critter) {
console.log(target.name + " lost their next turn. This does not do anything yet")
},
random: function(target: Critter) {
console.log(target.name + " is affected by a random effect. How random! This does not do anything yet")
}
}
class Effects {
effects : EffectsFunction[]
constructor(effectCallbackList : EffectsFunction[]) {
this.effects = effectCallbackList
}
doEffectsOn(target: any): void {
for(var i = 0; i < this.effects.length; i++)
this.effects[i](target)
}
}
class StatCheck {
stat: string;
modifier: number;
effects: Effects;
failEffectMessageID: number;
//stat = number, probably
constructor(stat: string, modifier: number, effects: Effects, failEffectMessageID: number) {
this.stat = stat
this.modifier = modifier
this.effects = effects
this.failEffectMessageID = failEffectMessageID
}
// This should return "Maybe msgID"
doEffectsOn(target: Critter): any {
// stat being undefined means there is no stat check to be done
if(this.stat === undefined)
return {success: false}
var statToRollAgainst = critterGetStat(target, this.stat)
statToRollAgainst += this.modifier
// if our target fails their skillcheck, they have to suffer the added effects.
// We do *10 so we can reuse the skillCheck function which goes from 0 to 100, while stat is 1 to 10
if(!rollSkillCheck(statToRollAgainst*10, 0, false)) {
this.effects.doEffectsOn(target)
return {success: true, msgID: this.failEffectMessageID}
}
return {success: false}
}
}
class CritType {
DM: number
effects: Effects
statCheck: StatCheck
msgID: number
constructor(damageMultiplier: number, effects: Effects, statCheck: StatCheck, effectMsg: number) {
this.DM = damageMultiplier
this.effects = effects
this.statCheck = statCheck
this.msgID = effectMsg
}
doEffectsOn(target: Critter) {
var returnMsgID = this.msgID
//we need to check for results before we apply the other effects, to ensure the checks in statCheck aren't modified by the effects of the crit.
var statCheckResults = this.statCheck.doEffectsOn(target)
this.effects.doEffectsOn(target)
//did statCheck do its effects as well?
if(statCheckResults.success === true)
returnMsgID = statCheckResults.msgID
return {DM: this.DM, msgID: returnMsgID}
}
}
interface CritLevelData {
statCheck: { stat: number, checkModifier: number, failureEffect: string[], failureMessage: number };
dmgMultiplier: number;
critEffect: string[];
msg: number;
}
function parseCritLevel(critLevel: CritLevelData): CritType {
var stat = critLevel.statCheck
var statVal: string|undefined = undefined
if(stat.stat != -1)
statVal = StatType[stat.stat]
var tempStatCheck = new StatCheck(statVal, stat.checkModifier, parseEffects(stat.failureEffect), stat.failureMessage)
var retCritLevel = new CritType(critLevel.dmgMultiplier, parseEffects(critLevel.critEffect), tempStatCheck, critLevel.msg)
return retCritLevel
}
// takes a List of effect names, gets the appropriate effects from the table and stores it in a Effects object
function parseEffects(effects: string[]): Effects {
var tempEffects = []
for(var i = 0; i < effects.length; i++)
tempEffects[i] = critterEffects[effects[i]]
return new Effects(tempEffects)
}
// tries to obtain the CritType object partaining to the critLevel of the region of the critterType in question, returns a default CritType object otherwise
export function getCritical(critterKillType: number, region: string, critLevel: number): CritType {
let ret: CritType|undefined = undefined;
try {
// ensure we aren't exceeding the highest crit level existing for this type of critter and region
const actualLevel = Math.min(critLevel, critterTable[critterKillType][region].length - 1)
// get the appropriate CritType from the table
ret = critterTable[critterKillType][region][actualLevel]
}
catch(e) {
}
if(ret === undefined) {
console.log("error: could not find critical: " + critterKillType + "/" + region + "/" + critLevel)
ret = defaultCritType(critterKillType, region, critLevel)
}
return ret
}
// constructs a default Crit Type object which doesn't apply any modifications to the shot, only changes the logging.
function defaultCritType(critterKillType: number, region: string, critLevel: number): CritType
{
return new CritType(2, new Effects([]), new StatCheck(undefined, undefined, undefined, undefined), undefined)
}
export function getCriticalFail(weaponType: string, failLevel: number): EffectsFunction[]
{
var ret: EffectsFunction[]|undefined = undefined
try {
// get the appropriate Critical Fail from the table
ret = criticalFailTable[weaponType][failLevel]
}
catch(e) {
}
if(ret === undefined)
//default crit fail error, which doesn't do anything but print an error message
ret = [(critter) => { console.log("error: could not find critical fail: " + weaponType + "/" + failLevel); }];
return ret;
}
export function loadTable() {
// read in the global table
var haveTable = true;
//console.log("loading critical table...");
var table = getFileJSON("lut/criticalTables.json", () => {
haveTable = false;
});
if(!haveTable) {
console.log("lut/criticalTables.json not found, not loading critical hit/miss table");
return;
}
critterTable = new Array(table.length);
for(var i = 0; i < table.length; i++) {
critterTable[i] = {};
for(var region in table[i]) {
critterTable[i][region] = new Array(table[i][region].length);
for(var critLevel = 0; critLevel < table[i][region].length; critLevel++)
critterTable[i][region][critLevel] = parseCritLevel(table[i][region][critLevel]);
}
}
//console.log("parsed critical table with " + critterTable.length + " entries")
}
export const criticalFailTable: Dict<NumDict<EffectsFunction[]>> = {
unarmed: {
1: [],
2: [critterEffects.loseNextTurn],
3: [critterEffects.loseNextTurn],
4: [critFailEffects.damageSelf, critterEffects.knockdown],
5: [critFailEffects.crippleRandomAppendage]
},
melee: {
1: [],
2: [critterEffects.loseNextTurn],
3: [critterEffects.droppedWeapon],
4: [critFailEffects.hitRandomly],
5: [critFailEffects.hitSelf]
},
firearms: {
1: [],
2: [critFailEffects.loseAmmo],
3: [critterEffects.droppedWeapon],
4: [critFailEffects.hitRandomly],
5: [critFailEffects.destroyWeapon]
},
energy: {
1: [critterEffects.loseNextTurn],
2: [critFailEffects.loseAmmo, critterEffects.loseNextTurn],
3: [critterEffects.droppedWeapon, critterEffects.loseNextTurn],
4: [critFailEffects.hitRandomly],
5: [critFailEffects.destroyWeapon, critterEffects.loseNextTurn]
},
grenades: {
1: [],
2: [critterEffects.droppedWeapon],
3: [critFailEffects.damageSelf, critterEffects.droppedWeapon],
4: [critFailEffects.hitRandomly],
5: [critFailEffects.destroyWeapon]
},
rocketlauncher: {
1: [critterEffects.loseNextTurn],
2: [], //yes that appears backwards but seems to be the case in FO
3: [critFailEffects.destroyWeapon],
4: [critFailEffects.hitRandomly],
5: [critFailEffects.destroyWeapon, critterEffects.loseNextTurn, critterEffects.knockdown]
},
flamers: {
1: [],
2: [critterEffects.loseNextTurn],
3: [critFailEffects.hitRandomly],
4: [critFailEffects.destroyWeapon],
5: [critFailEffects.destroyWeapon, critterEffects.loseNextTurn, critterEffects.onFire]
}
}
export function temporaryDoCritFail(critFail: EffectsFunction[], target: Critter) {
for (var i = 0; i < critFail.length; i++) {
critFail[i](target)
}
}
} | the_stack |
namespace eui {
/**
* Linear layout base class, usually as the parent class of
* <code>HorizontalLayout</code> and <code>VerticalLayout</code>.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 线性布局基类,通常作为 <code>HorizontalLayout</code> 和 <code>VerticalLayout</code> 的父类。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
export class LinearLayoutBase extends LayoutBase {
/**
* @private
*/
$horizontalAlign:string = "left";
/**
* The horizontal alignment of layout elements.
* <p>The <code>egret.HorizontalAlign</code> and <code>eui.JustifyAlign</code> class
* defines the possible values for this property.</p>
*
* @default "left"
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 布局元素的水平对齐策略。
* <p><code>egret.HorizontalAlign</code> 和
* <code>eui.JustifyAlign</code>类定义此属性的可能值。<p>
*
* @default "left"
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get horizontalAlign():string {
return this.$horizontalAlign;
}
public set horizontalAlign(value:string) {
if (this.$horizontalAlign == value)
return;
this.$horizontalAlign = value;
if (this.$target)
this.$target.invalidateDisplayList();
}
/**
* @private
*/
$verticalAlign:string = "top";
/**
* The vertical alignment of layout elements.
* <p>The <code>egret.VerticalAlign</code> and <code>eui.JustifyAlign</code> class
* defines the possible values for this property.</p>
*
* @default "top"
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 布局元素的垂直对齐策略。请使用 VerticalAlign 定义的常量。
* <p><code>egret.VerticalAlign</code> 和
* <code>eui.JustifyAlign</code>类定义此属性的可能值。<p>
*
* @default "top"
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get verticalAlign():string {
return this.$verticalAlign;
}
public set verticalAlign(value:string) {
if (this.$verticalAlign == value)
return;
this.$verticalAlign = value;
if (this.$target)
this.$target.invalidateDisplayList();
}
/**
* @private
*/
$gap:number = 6;
/**
* The space between layout elements, in pixels.
*
* @default 6
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 布局元素之间的间隔(以像素为单位)。
*
* @default 6
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get gap():number {
return this.$gap;
}
public set gap(value:number) {
value = +value || 0;
if (this.$gap === value)
return;
this.$gap = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
$paddingLeft:number = 0;
/**
* Number of pixels between the container's left edge
* and the left edge of the first layout element.
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 容器的左边缘与第一个布局元素的左边缘之间的像素数。
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get paddingLeft():number {
return this.$paddingLeft;
}
public set paddingLeft(value:number) {
value = +value || 0;
if (this.$paddingLeft === value)
return;
this.$paddingLeft = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
$paddingRight:number = 0;
/**
* Number of pixels between the container's right edge
* and the right edge of the last layout element.
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 容器的右边缘与最后一个布局元素的右边缘之间的像素数。
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get paddingRight():number {
return this.$paddingRight;
}
public set paddingRight(value:number) {
value = +value || 0;
if (this.$paddingRight === value)
return;
this.$paddingRight = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
$paddingTop:number = 0;
/**
* The minimum number of pixels between the container's top edge and
* the top of all the container's layout elements.
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 容器的顶边缘与所有容器的布局元素的顶边缘之间的最少像素数。
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get paddingTop():number {
return this.$paddingTop;
}
public set paddingTop(value:number) {
value = +value || 0;
if (this.$paddingTop === value)
return;
this.$paddingTop = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
$paddingBottom:number = 0;
/**
* The minimum number of pixels between the container's bottom edge and
* the bottom of all the container's layout elements.
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 容器的底边缘与所有容器的布局元素的底边缘之间的最少像素数。
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get paddingBottom():number {
return this.$paddingBottom;
}
public set paddingBottom(value:number) {
value = +value || 0;
if (this.$paddingBottom === value)
return;
this.$paddingBottom = value;
this.invalidateTargetLayout();
}
/**
* Convenience function for subclasses that invalidates the
* target's size and displayList so that both layout's <code>measure()</code>
* and <code>updateDisplayList</code> methods get called.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 失效目标容器的尺寸和显示列表的简便方法,调用目标容器的
* <code>measure()</code>和<code>updateDisplayList</code>方法
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected invalidateTargetLayout():void {
let target = this.$target;
if (target) {
target.invalidateSize();
target.invalidateDisplayList();
}
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public measure():void {
if (!this.$target)
return;
if (this.$useVirtualLayout) {
this.measureVirtual();
}
else {
this.measureReal();
}
}
/**
* Compute exact values for measuredWidth and measuredHeight.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 计算目标容器 measuredWidth 和 measuredHeight 的精确值
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected measureReal():void {
}
/**
* Compute potentially approximate values for measuredWidth and measuredHeight.
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 计算目标容器 measuredWidth 和 measuredHeight 的近似值
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected measureVirtual():void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public updateDisplayList(width:number, height:number):void {
let target = this.$target;
if (!target)
return;
if (target.numElements == 0) {
target.setContentSize(Math.ceil(this.$paddingLeft + this.$paddingRight),
Math.ceil(this.$paddingTop + this.$paddingBottom));
return;
}
if (this.$useVirtualLayout) {
this.updateDisplayListVirtual(width, height);
}
else {
this.updateDisplayListReal(width, height);
}
}
/**
* An Array of the virtual layout elements size cache.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 虚拟布局使用的尺寸缓存。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected elementSizeTable:number[] = [];
/**
* Gets the starting position of the specified index element
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 获取指定索引元素的起始位置
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected getStartPosition(index:number):number {
return 0;
}
/**
* Gets the size of the specified index element
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 获取指定索引元素的尺寸
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected getElementSize(index:number):number {
return 0;
}
/**
* Gets the sum of the size of cached elements
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 获取缓存的子对象尺寸总和
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected getElementTotalSize():number {
return 0;
}
/**
* @inheritDoc
*
* @param index
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public elementRemoved(index:number):void {
if (!this.$useVirtualLayout)
return;
super.elementRemoved(index);
this.elementSizeTable.splice(index, 1);
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public clearVirtualLayoutCache():void {
if (!this.$useVirtualLayout)
return;
this.elementSizeTable = [];
this.maxElementSize = 0;
}
/**
* The binary search to find the specified index position of the display object
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 折半查找法寻找指定位置的显示对象索引
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected findIndexAt(x:number, i0:number, i1:number):number {
let index = ((i0 + i1) * 0.5)|0;
let elementX = this.getStartPosition(index);
let elementWidth = this.getElementSize(index);
if ((x >= elementX) && (x < elementX + elementWidth + this.$gap))
return index;
else if (i0 == i1)
return -1;
else if (x < elementX)
return this.findIndexAt(x, i0, Math.max(i0, index - 1));
else
return this.findIndexAt(x, Math.min(index + 1, i1), i1);
}
/**
* The first element index in the view of the virtual layout
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 虚拟布局使用的当前视图中的第一个元素索引
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected startIndex:number = -1;
/**
* The last element index in the view of the virtual layout
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 虚拟布局使用的当前视图中的最后一个元素的索引
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected endIndex:number = -1;
/**
* A Flag of the first element and the end element has been calculated.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 视图的第一个和最后一个元素的索引值已经计算好的标志
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected indexInViewCalculated:boolean = false;
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public scrollPositionChanged():void {
super.scrollPositionChanged();
if (this.$useVirtualLayout) {
let changed = this.getIndexInView();
if (changed) {
this.indexInViewCalculated = true;
this.target.invalidateDisplayList();
}
}
}
/**
* Get the index of the first and last element in the view,
* and to return whether or not to change.
*
* @return has the index changed
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 获取视图中第一个和最后一个元素的索引,返回是否发生改变。
*
* @return 索引是否已改变
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected getIndexInView():boolean {
return false;
}
/**
* The maximum size of elements
*
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 子元素最大的尺寸
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected maxElementSize:number = 0;
/**
* Update the layout of the virtualized elements
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 更新虚拟布局的显示列表
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected updateDisplayListVirtual(width:number, height:number):void {
}
/**
* Update the layout of the reality elements
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 更新真实布局的显示列表
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected updateDisplayListReal(width:number, height:number):void {
}
/**
* Allocate blank area for each variable size element.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 为每个可变尺寸的子项分配空白区域。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected flexChildrenProportionally(spaceForChildren:number, spaceToDistribute:number,
totalPercent:number, childInfoArray:any[]):void {
let numElements:number = childInfoArray.length;
let done:boolean;
do {
done = true;
let unused:number = spaceToDistribute -
(spaceForChildren * totalPercent / 100);
if (unused > 0)
spaceToDistribute -= unused;
else
unused = 0;
let spacePerPercent:number = spaceToDistribute / totalPercent;
for (let i:number = 0; i < numElements; i++) {
let childInfo:sys.ChildInfo = childInfoArray[i];
let size:number = childInfo.percent * spacePerPercent;
if (size < childInfo.min) {
let min:number = childInfo.min;
childInfo.size = min;
childInfoArray[i] = childInfoArray[--numElements];
childInfoArray[numElements] = childInfo;
totalPercent -= childInfo.percent;
if (unused >= min) {
unused -= min;
}
else {
spaceToDistribute -= min - unused;
unused = 0;
}
done = false;
break;
}
else if (size > childInfo.max) {
let max:number = childInfo.max;
childInfo.size = max;
childInfoArray[i] = childInfoArray[--numElements];
childInfoArray[numElements] = childInfo;
totalPercent -= childInfo.percent;
if (unused >= max) {
unused -= max;
}
else {
spaceToDistribute -= max - unused;
unused = 0;
}
done = false;
break;
}
else {
childInfo.size = size;
}
}
}
while (!done);
}
}
}
namespace eui.sys {
/**
* @private
*/
export class ChildInfo {
/**
* @private
*/
public layoutElement:eui.UIComponent = null;
/**
* @private
*/
public size:number = 0;
/**
* @private
*/
public percent:number = NaN;
/**
* @private
*/
public min:number = NaN;
/**
* @private
*/
public max:number = NaN;
}
} | the_stack |
export interface DescribeCloudStorageDateRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 用户ID
*/
UserId?: string;
}
/**
* 云存时间轴接口返回数据
*/
export interface CloudStorageTimeData {
/**
* 云存时间轴信息列表
*/
TimeList: Array<CloudStorageTimeInfo>;
/**
* 播放地址
*/
VideoURL: string;
}
/**
* RetryDeviceFirmwareTask请求参数结构体
*/
export interface RetryDeviceFirmwareTaskRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 固件版本号
*/
FirmwareVersion: string;
/**
* 固件升级任务ID
*/
TaskId: number;
}
/**
* CreateCloudStorage请求参数结构体
*/
export interface CreateCloudStorageRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 云存套餐ID:
yc1m3d : 全时3天存储月套餐。
yc1m7d : 全时7天存储月套餐。
yc1m30d :全时30天存储月套餐。
yc1y3d :全时3天存储年套餐。
yc1y7d :全时7天存储年套餐。
yc1y30d :全时30天存储年套餐。
ye1m3d :事件3天存储月套餐。
ye1m7d :事件7天存储月套餐。
ye1m30d :事件30天存储月套餐 。
ye1y3d :事件3天存储年套餐。
ye1y7d :事件7天存储年套餐。
ye1y30d :事件30天存储年套餐。
yc1w7d : 全时7天存储周套餐。
ye1w7d : 事件7天存储周套餐。
*/
PackageId: string;
/**
* 如果当前设备已开启云存套餐,Override=1会使用新套餐覆盖原有套餐。不传此参数则默认为0。
*/
Override?: number;
}
/**
* 批次元数据
*/
export interface VideoBatch {
/**
* 批次ID
*/
Id: number;
/**
* 用户ID
*/
UserId: string;
/**
* 产品ID
*/
ProductId: string;
/**
* 状态:1:待创建设备 2:创建中 3:已完成
*/
Status: number;
/**
* 设备前缀
*/
DevPre: string;
/**
* 设备数量
*/
DevNum: number;
/**
* 已创建设备数量
*/
DevNumCreated: number;
/**
* 批次下载地址
*/
BatchURL: string;
/**
* 创建时间。unix时间戳
*/
CreateTime: number;
/**
* 修改时间。unix时间戳
*/
UpdateTime: number;
}
/**
* ImportModelDefinition返回参数结构体
*/
export interface ImportModelDefinitionResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ApplyAIModel请求参数结构体
*/
export interface ApplyAIModelRequest {
/**
* AI模型ID
*/
ModelId: string;
/**
* 产品ID
*/
ProductId: string;
}
/**
* CreateBatch请求参数结构体
*/
export interface CreateBatchRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 批次创建的设备数量
*/
DevNum: number;
/**
* 批次创建的设备前缀。不超过24个字符
*/
DevPre: string;
}
/**
* CancelAIModelApplication返回参数结构体
*/
export interface CancelAIModelApplicationResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCloudStorageTime返回参数结构体
*/
export interface DescribeCloudStorageTimeResponse {
/**
* 接口返回数据
*/
Data: CloudStorageTimeData;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDeviceStatusLog返回参数结构体
*/
export interface DescribeDeviceStatusLogResponse {
/**
* 数据是否已全部返回,true 表示数据全部返回,false 表示还有数据待返回,可将 Context 作为入参,继续查询返回结果。
注意:此字段可能返回 null,表示取不到有效值。
*/
Listover: boolean;
/**
* 检索上下文,当 ListOver 为false时,可以用此上下文,继续读取后续数据
注意:此字段可能返回 null,表示取不到有效值。
*/
Context: string;
/**
* 日志数据结果数组,返回对应时间点及取值。
注意:此字段可能返回 null,表示取不到有效值。
*/
Results: Array<DeviceStatusLogItem>;
/**
* 日志数据结果总条数
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalCount: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ReportAliveDevice请求参数结构体
*/
export interface ReportAliveDeviceRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
}
/**
* DescribeProducts请求参数结构体
*/
export interface DescribeProductsRequest {
/**
* 分页的大小,最大100
*/
Limit: number;
/**
* 偏移量,Offset从0开始
*/
Offset: number;
}
/**
* DescribeAIModelChannel返回参数结构体
*/
export interface DescribeAIModelChannelResponse {
/**
* 推送类型。ckafka:消息队列;forward:http/https推送
*/
Type: string;
/**
* 第三方推送地址
注意:此字段可能返回 null,表示取不到有效值。
*/
ForwardAddress: string;
/**
* 第三方推送密钥
注意:此字段可能返回 null,表示取不到有效值。
*/
ForwardKey: string;
/**
* ckafka地域
注意:此字段可能返回 null,表示取不到有效值。
*/
CKafkaRegion: string;
/**
* ckafka实例
注意:此字段可能返回 null,表示取不到有效值。
*/
CKafkaInstance: string;
/**
* ckafka订阅主题
注意:此字段可能返回 null,表示取不到有效值。
*/
CKafkaTopic: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDeviceActionHistory请求参数结构体
*/
export interface DescribeDeviceActionHistoryRequest {
/**
* 产品Id
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 开始范围的 unix 毫秒时间戳
*/
MinTime: number;
/**
* 结束范围的 unix 毫秒时间戳
*/
MaxTime: number;
/**
* 动作Id
*/
ActionId?: string;
/**
* 查询条数 默认为0 最大不超过500
*/
Limit?: number;
/**
* 游标,标识查询位置。
*/
Context?: string;
}
/**
* ModifyDataForward请求参数结构体
*/
export interface ModifyDataForwardRequest {
/**
* 产品ID。
*/
ProductId: string;
/**
* 转发地址。如果有鉴权Token,则需要自行传入,例如 [{\"forward\":{\"api\":\"http://123.207.117.108:1080/sub.php\",\"token\":\"testtoken\"}}]
*/
ForwardAddr: string;
/**
* 1-数据信息转发 2-设备上下线状态转发 3-数据信息转发&设备上下线状态转发
*/
DataChose?: number;
}
/**
* DescribeDevices返回参数结构体
*/
export interface DescribeDevicesResponse {
/**
* 设备总数
*/
TotalCount: number;
/**
* 设备详细信息列表
*/
Devices: Array<DeviceInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyProduct返回参数结构体
*/
export interface ModifyProductResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyProduct请求参数结构体
*/
export interface ModifyProductRequest {
/**
* 产品id
*/
ProductId: string;
/**
* 修改的产品名称 (支持中文、英文、数字、下划线组合,最多不超过20个字符)
*/
ProductName?: string;
/**
* 修改的产品描述 (最多不超过128个字符)
*/
ProductDescription?: string;
}
/**
* ModifyModelDefinition请求参数结构体
*/
export interface ModifyModelDefinitionRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 数据模板定义
*/
ModelSchema: string;
}
/**
* DescribeBatchs返回参数结构体
*/
export interface DescribeBatchsResponse {
/**
* 批次数量
*/
TotalCount: number;
/**
* 批次列表详情
*/
Data: Array<VideoBatch>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CancelAIModelApplication请求参数结构体
*/
export interface CancelAIModelApplicationRequest {
/**
* AI模型ID
*/
ModelId: string;
/**
* 产品ID
*/
ProductId: string;
}
/**
* TransferCloudStorage返回参数结构体
*/
export interface TransferCloudStorageResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeForwardRule返回参数结构体
*/
export interface DescribeForwardRuleResponse {
/**
* 腾讯云账号
*/
Endpoint: string;
/**
* 队列名称
*/
QueueName: string;
/**
* 产品ID
*/
ProductID: string;
/**
* 消息类型 1设备上报信息 2设备状态变化通知 3为全选
*/
MsgType: number;
/**
* 结果 2表示禁用 其他为成功
*/
Result: number;
/**
* 角色名
*/
RoleName: string;
/**
* 角色ID
*/
RoleID: number;
/**
* 队列区域
*/
QueueRegion: string;
/**
* 队列类型,0:CMQ,1:Ckafka
*/
QueueType: number;
/**
* 实例id, 目前只有Ckafaka会用到
*/
InstanceId: string;
/**
* 实例名称,目前只有Ckafaka会用到
*/
InstanceName: string;
/**
* 错误消息
*/
ErrMsg: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDeviceLogLevel请求参数结构体
*/
export interface ModifyDeviceLogLevelRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 日志级别,0:关闭,1:错误,2:告警,3:信息,4:调试
*/
LogLevel: number;
}
/**
* DescribeBatch请求参数结构体
*/
export interface DescribeBatchRequest {
/**
* 批次ID
*/
BatchId: number;
}
/**
* DescribeForwardRule请求参数结构体
*/
export interface DescribeForwardRuleRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 控制台Skey
*/
Skey: string;
/**
* 队列类型,0:CMQ,1:Ckafka
*/
QueueType: number;
/**
* 临时密钥
*/
Consecretid?: string;
}
/**
* ModifyDevice请求参数结构体
*/
export interface ModifyDeviceRequest {
/**
* 设备所属产品id
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 要设置的设备状态,1为启用,0为禁用
*/
EnableState?: number;
}
/**
* CreateCOSCredentials返回参数结构体
*/
export interface CreateCOSCredentialsResponse {
/**
* COS存储桶名称
*/
StorageBucket: string;
/**
* COS存储桶区域
*/
StorageRegion: string;
/**
* COS存储桶路径
*/
StoragePath: string;
/**
* COS上传用的SecretID
*/
SecretID: string;
/**
* COS上传用的SecretKey
*/
SecretKey: string;
/**
* COS上传用的Token
*/
Token: string;
/**
* 密钥信息过期时间
*/
ExpiredTime: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 产品模型定义
*/
export interface ProductModelDefinition {
/**
* 产品ID
*/
ProductId: string;
/**
* 模型定义
*/
ModelDefine: string;
/**
* 更新时间,秒级时间戳
*/
UpdateTime: number;
/**
* 创建时间,秒级时间戳
*/
CreateTime: number;
/**
* 产品所属分类的模型快照(产品创建时刻的)
注意:此字段可能返回 null,表示取不到有效值。
*/
CategoryModel: string;
/**
* 产品的连接类型的模型
注意:此字段可能返回 null,表示取不到有效值。
*/
NetTypeModel: string;
}
/**
* 查询设备历史
*/
export interface ActionHistory {
/**
* 设备名称
*/
DeviceName: string;
/**
* 动作Id
*/
ActionId: string;
/**
* 动作名称
*/
ActionName: string;
/**
* 请求时间
*/
ReqTime: number;
/**
* 响应时间
*/
RspTime: number;
/**
* 输入参数
注意:此字段可能返回 null,表示取不到有效值。
*/
InputParams: string;
/**
* 输出参数
注意:此字段可能返回 null,表示取不到有效值。
*/
OutputParams: string;
/**
* 调用方式
*/
Calling: string;
/**
* 调用Id
*/
ClientToken: string;
/**
* 调用状态
*/
Status: string;
}
/**
* CreateDataForward返回参数结构体
*/
export interface CreateDataForwardResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeFirmware请求参数结构体
*/
export interface DescribeFirmwareRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 固件版本号
*/
FirmwareVersion: string;
}
/**
* DescribeCloudStorageUsers返回参数结构体
*/
export interface DescribeCloudStorageUsersResponse {
/**
* 用户总数
*/
TotalCount: number;
/**
* 用户信息
*/
Users: Array<CloudStorageUserInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeProduct请求参数结构体
*/
export interface DescribeProductRequest {
/**
* 产品id
*/
ProductId: string;
}
/**
* DescribeProducts返回参数结构体
*/
export interface DescribeProductsResponse {
/**
* 总数
*/
TotalCount: number;
/**
* 产品详情列表
*/
Data: Array<VideoProduct>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CheckForwardAuth请求参数结构体
*/
export interface CheckForwardAuthRequest {
/**
* 控制台Skey
*/
Skey: string;
/**
* 队列类型 0.CMQ 1.Ckafka
*/
QueueType: number;
}
/**
* DescribeDeviceData请求参数结构体
*/
export interface DescribeDeviceDataRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
}
/**
* CreateBatch返回参数结构体
*/
export interface CreateBatchResponse {
/**
* 批次ID
*/
BatchId: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDeviceActionHistory返回参数结构体
*/
export interface DescribeDeviceActionHistoryResponse {
/**
* 总条数
*/
TotalCounts: number;
/**
* 动作历史
注意:此字段可能返回 null,表示取不到有效值。
*/
ActionHistories: Array<ActionHistory>;
/**
* 用于标识查询结果的上下文,翻页用。
注意:此字段可能返回 null,表示取不到有效值。
*/
Context: string;
/**
* 搜索结果是否已经结束。
注意:此字段可能返回 null,表示取不到有效值。
*/
Listover: boolean;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* GetAllFirmwareVersion请求参数结构体
*/
export interface GetAllFirmwareVersionRequest {
/**
* 产品ID
*/
ProductID: string;
}
/**
* CreateCOSCredentials请求参数结构体
*/
export interface CreateCOSCredentialsRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
}
/**
* 设备通讯日志查询返回条目
*/
export interface DeviceCommLogItem {
/**
* 时间
*/
Time: string;
/**
* 日志类型,device 设备上行,shadow 服务端下行。
*/
Type: string;
/**
* 通讯数据。
*/
Data: string;
}
/**
* 设备固件更新状态
*/
export interface DeviceUpdateStatus {
/**
* 设备名
*/
DeviceName: string;
/**
* 最后处理时间
*/
LastProcessTime: number;
/**
* 状态
*/
Status: number;
/**
* 错误消息
*/
ErrMsg: string;
/**
* 返回码
*/
Retcode: number;
/**
* 目标更新版本
*/
DstVersion: string;
/**
* 下载中状态时的下载进度
注意:此字段可能返回 null,表示取不到有效值。
*/
Percent: number;
/**
* 原版本号
注意:此字段可能返回 null,表示取不到有效值。
*/
OriVersion: string;
/**
* 任务ID
注意:此字段可能返回 null,表示取不到有效值。
*/
TaskId: number;
}
/**
* DescribeDataForwardList返回参数结构体
*/
export interface DescribeDataForwardListResponse {
/**
* 数据转发列表。
注意:此字段可能返回 null,表示取不到有效值。
*/
DataForwardList: Array<DataForward>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteFirmware返回参数结构体
*/
export interface DeleteFirmwareResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateForwardRule返回参数结构体
*/
export interface CreateForwardRuleResponse {
/**
* 腾讯云账号
*/
Endpoint: string;
/**
* 队列名
*/
QueueName: string;
/**
* 产品ID
*/
ProductID: string;
/**
* 消息类型
*/
MsgType: number;
/**
* 结果
*/
Result: number;
/**
* 角色名称
*/
RoleName: string;
/**
* 角色ID
*/
RoleID: number;
/**
* 队列区
*/
QueueRegion: string;
/**
* 消息队列的类型。 0:CMQ,1:CKafaka
*/
QueueType: number;
/**
* 实例id, 目前只有Ckafaka会用到
*/
InstanceId: string;
/**
* 实例名称,目前只有Ckafaka会用到
*/
InstanceName: string;
/**
* 错误消息
*/
ErrMsg: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* BatchUpdateFirmware返回参数结构体
*/
export interface BatchUpdateFirmwareResponse {
/**
* 任务ID
*/
TaskId: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeModelDefinition返回参数结构体
*/
export interface DescribeModelDefinitionResponse {
/**
* 产品数据模板
*/
Model: ProductModelDefinition;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteProduct请求参数结构体
*/
export interface DeleteProductRequest {
/**
* 产品ID
*/
ProductId: string;
}
/**
* 状态统计信息
*/
export interface StatusStatistic {
/**
* 任务状态
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: number;
/**
* 统计总数
注意:此字段可能返回 null,表示取不到有效值。
*/
Total: number;
}
/**
* PublishMessage返回参数结构体
*/
export interface PublishMessageResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* SetForwardAuth返回参数结构体
*/
export interface SetForwardAuthResponse {
/**
* 腾讯云账号
*/
Endpoint: string;
/**
* 结果
*/
Result: number;
/**
* 角色名
*/
RoleName: string;
/**
* 角色ID
*/
RoleID: number;
/**
* 消息队列类型 0.CMQ 1.CKafka
*/
QueueType: number;
/**
* 错误消息
*/
ErrMsg: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* EditFirmware请求参数结构体
*/
export interface EditFirmwareRequest {
/**
* 产品ID。
*/
ProductID: string;
/**
* 固件版本号。
*/
FirmwareVersion: string;
/**
* 固件名称。
*/
FirmwareName: string;
/**
* 固件描述。
*/
FirmwareDescription?: string;
}
/**
* 设备历史数据结构
*/
export interface DeviceDataHistoryItem {
/**
* 时间点,毫秒时间戳
*/
Time: string;
/**
* 字段取值
*/
Value: string;
}
/**
* ReportAliveDevice返回参数结构体
*/
export interface ReportAliveDeviceResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDeviceEventHistory请求参数结构体
*/
export interface DescribeDeviceEventHistoryRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 搜索的事件类型:alert 表示告警,fault 表示故障,info 表示信息,为空则表示查询上述所有类型事件
*/
Type?: string;
/**
* 起始时间(Unix 时间戳,秒级), 为0 表示 当前时间 - 24h
*/
StartTime?: number;
/**
* 结束时间(Unix 时间戳,秒级), 为0 表示当前时间
*/
EndTime?: number;
/**
* 搜索上下文, 用作查询游标
*/
Context?: string;
/**
* 单次获取的历史数据项目的最大数量, 缺省10
*/
Size?: number;
/**
* 事件标识符,可以用来指定查询特定的事件,如果不指定,则查询所有事件。
*/
EventId?: string;
}
/**
* DescribeCategory返回参数结构体
*/
export interface DescribeCategoryResponse {
/**
* Category详情
*/
Data: ProductTemplate;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeSDKLog请求参数结构体
*/
export interface DescribeSDKLogRequest {
/**
* 日志开始时间
*/
MinTime: number;
/**
* 日志结束时间
*/
MaxTime: number;
/**
* 查询关键字,可以同时支持键值查询和文本查询,
例如,查询某key的值为value,并且包含某word的日志,该参数为:key:value word。
键值或文本可以包含多个,以空格隔开。
其中可以索引的key包括:productid、devicename、loglevel
一个典型的查询示例:productid:7JK1G72JNE devicename:name publish loglevel:WARN一个典型的查询示例:productid:ABCDE12345 devicename:test scene:SHADOW publish
*/
Keywords: string;
/**
* 日志检索上下文
*/
Context?: string;
/**
* 查询条数
*/
MaxNum?: number;
}
/**
* DescribeBalance请求参数结构体
*/
export interface DescribeBalanceRequest {
/**
* 账户类型:1-设备接入;2-云存。
*/
AccountType: number;
}
/**
* ImportModelDefinition请求参数结构体
*/
export interface ImportModelDefinitionRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 数据模板定义
*/
ModelSchema: string;
}
/**
* DescribeDataForwardList请求参数结构体
*/
export interface DescribeDataForwardListRequest {
/**
* 产品ID列表
*/
ProductIds: string;
}
/**
* DescribeDeviceCommLog返回参数结构体
*/
export interface DescribeDeviceCommLogResponse {
/**
* 数据是否已全部返回,true 表示数据全部返回,false 表示还有数据待返回,可将 Context 作为入参,继续查询返回结果。
*/
Listover: boolean;
/**
* 检索上下文,当 ListOver 为false时,可以用此上下文,继续读取后续数据
*/
Context: string;
/**
* 日志数据结果数组,返回对应时间点及取值。
*/
Results: Array<DeviceCommLogItem>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteDevice请求参数结构体
*/
export interface DeleteDeviceRequest {
/**
* 产品ID。
*/
ProductId: string;
/**
* 设备名称。
*/
DeviceName: string;
}
/**
* GenerateSignedVideoURL返回参数结构体
*/
export interface GenerateSignedVideoURLResponse {
/**
* 视频防盗链播放URL
*/
SignedVideoURL: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ControlDeviceData请求参数结构体
*/
export interface ControlDeviceDataRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 属性数据, JSON格式字符串, 注意字段需要在物模型属性里定义
*/
Data: string;
/**
* 请求类型 , 不填该参数或者 desired 表示下发属性给设备, reported 表示模拟设备上报属性
*/
Method?: string;
/**
* 上报数据UNIX时间戳(毫秒), 仅对Method:reported有效
*/
DataTimestamp?: number;
}
/**
* AI模型资源使用信息
*/
export interface AIModelUsageInfo {
/**
* 开通时间
*/
CreateTime: number;
/**
* 资源总量
*/
Total: number;
/**
* 已使用资源数量
*/
Used: number;
}
/**
* DescribeFirmwareTaskDevices请求参数结构体
*/
export interface DescribeFirmwareTaskDevicesRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 固件版本
*/
FirmwareVersion?: string;
/**
* 筛选条件
*/
Filters?: Array<SearchKeyword>;
/**
* 查询偏移量 默认为0
*/
Offset?: number;
/**
* 查询的数量 默认为50
*/
Limit?: number;
}
/**
* DescribeFirmware返回参数结构体
*/
export interface DescribeFirmwareResponse {
/**
* 固件版本号
*/
Version: string;
/**
* 产品ID
*/
ProductId: string;
/**
* 固件名称
注意:此字段可能返回 null,表示取不到有效值。
*/
Name: string;
/**
* 固件描述
注意:此字段可能返回 null,表示取不到有效值。
*/
Description: string;
/**
* 固件Md5值
注意:此字段可能返回 null,表示取不到有效值。
*/
Md5sum: string;
/**
* 固件上传的秒级时间戳
注意:此字段可能返回 null,表示取不到有效值。
*/
Createtime: number;
/**
* 产品名称
*/
ProductName: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDeviceCommLog请求参数结构体
*/
export interface DescribeDeviceCommLogRequest {
/**
* 开始时间 13位时间戳 单位毫秒
*/
MinTime: number;
/**
* 结束时间 13位时间戳 单位毫秒
*/
MaxTime: number;
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 返回条数 默认为50
*/
Limit?: number;
/**
* 检索上下文
*/
Context?: string;
/**
* 类型:shadow 下行,device 上行 默认为空则全部查询
*/
Type?: string;
}
/**
* WakeUpDevice返回参数结构体
*/
export interface WakeUpDeviceResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteForwardRule请求参数结构体
*/
export interface DeleteForwardRuleRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 控制台Skey
*/
Skey: string;
/**
* 队列类型
*/
QueueType: number;
/**
* 队列名称
*/
QueueName: string;
}
/**
* UpdateAIModelChannel返回参数结构体
*/
export interface UpdateAIModelChannelResponse {
/**
* 第三方推送密钥,如果选择自动生成则会返回此字段
注意:此字段可能返回 null,表示取不到有效值。
*/
ForwardKey: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeAIModelUsage返回参数结构体
*/
export interface DescribeAIModelUsageResponse {
/**
* AI模型资源包总量
*/
TotalCount: number;
/**
* AI模型资源包信息数组
*/
UsageInfo: Array<AIModelUsageInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeBalanceTransactions请求参数结构体
*/
export interface DescribeBalanceTransactionsRequest {
/**
* 账户类型:1-设备接入;2-云存。
*/
AccountType: number;
/**
* 分页游标开始,默认为0开始拉取第一条。
*/
Offset: number;
/**
* 分页每页数量。
*/
Limit: number;
/**
* 流水类型:All-全部类型;Recharge-充值;CreateOrder-新购。默认为All
*/
Operation?: string;
}
/**
* BindCloudStorageUser请求参数结构体
*/
export interface BindCloudStorageUserRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 用户ID
*/
UserId: string;
}
/**
* CreateProduct返回参数结构体
*/
export interface CreateProductResponse {
/**
* 产品详情
*/
Data: VideoProduct;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeFirmwareTaskDevices返回参数结构体
*/
export interface DescribeFirmwareTaskDevicesResponse {
/**
* 固件升级任务的设备总数
注意:此字段可能返回 null,表示取不到有效值。
*/
Total: number;
/**
* 固件升级任务的设备列表
*/
Devices: Array<DeviceUpdateStatus>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDataForward返回参数结构体
*/
export interface ModifyDataForwardResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCloudStorageThumbnail返回参数结构体
*/
export interface DescribeCloudStorageThumbnailResponse {
/**
* 缩略图访问地址
*/
ThumbnailURL: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeAIModels请求参数结构体
*/
export interface DescribeAIModelsRequest {
/**
* 模型ID
*/
ModelId: string;
/**
* 申请状态:1-已申请;2-已取消;3-已拒绝;4-已通过
*/
Status: number;
/**
* 偏移量,Offset从0开始
*/
Offset: number;
/**
* 分页的大小,最大100
*/
Limit: number;
}
/**
* RetryDeviceFirmwareTask返回参数结构体
*/
export interface RetryDeviceFirmwareTaskResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* GenerateSignedVideoURL请求参数结构体
*/
export interface GenerateSignedVideoURLRequest {
/**
* 视频播放原始URL地址
*/
VideoURL: string;
/**
* 播放链接过期时间
*/
ExpireTime: number;
}
/**
* ResetCloudStorage返回参数结构体
*/
export interface ResetCloudStorageResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* InheritCloudStorageUser返回参数结构体
*/
export interface InheritCloudStorageUserResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDeviceEventHistory返回参数结构体
*/
export interface DescribeDeviceEventHistoryResponse {
/**
* 搜索上下文, 用作查询游标
注意:此字段可能返回 null,表示取不到有效值。
*/
Context: string;
/**
* 搜索结果数量
注意:此字段可能返回 null,表示取不到有效值。
*/
Total: number;
/**
* 搜索结果是否已经结束
注意:此字段可能返回 null,表示取不到有效值。
*/
Listover: boolean;
/**
* 搜集结果集
注意:此字段可能返回 null,表示取不到有效值。
*/
EventHistory: Array<EventHistoryItem>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeFirmwareTask返回参数结构体
*/
export interface DescribeFirmwareTaskResponse {
/**
* 固件任务ID
注意:此字段可能返回 null,表示取不到有效值。
*/
TaskId: number;
/**
* 固件任务状态
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: number;
/**
* 固件任务创建时间,单位:秒
注意:此字段可能返回 null,表示取不到有效值。
*/
CreateTime: number;
/**
* 固件任务升级类型
注意:此字段可能返回 null,表示取不到有效值。
*/
Type: number;
/**
* 产品名称
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductName: string;
/**
* 固件任务升级模式。originalVersion(按版本号升级)、filename(提交文件升级)、devicenames(按设备名称升级)
注意:此字段可能返回 null,表示取不到有效值。
*/
UpgradeMode: string;
/**
* 产品ID
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductId: string;
/**
* 原始固件版本号,在UpgradeMode是originalVersion升级模式下会返回
注意:此字段可能返回 null,表示取不到有效值。
*/
OriginalVersion: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 设备固件详细信息
*/
export interface FirmwareInfo {
/**
* 固件版本
*/
Version: string;
/**
* 固件MD5值
*/
Md5sum: string;
/**
* 固件创建时间
*/
CreateTime: number;
/**
* 产品名称
*/
ProductName: string;
/**
* 固件名称
*/
Name: string;
/**
* 固件描述
*/
Description: string;
/**
* 产品ID
*/
ProductId: string;
}
/**
* CreateProduct请求参数结构体
*/
export interface CreateProductRequest {
/**
* 产品名称
*/
ProductName: string;
/**
* 产品设备类型 1.普通设备 2.NVR设备
*/
DeviceType: number;
/**
* 产品有效期
*/
ProductVaildYears: number;
/**
* 设备功能码 ypsxth音频双向通话 spdxth视频单向通话
*/
Features: Array<string>;
/**
* 设备操作系统,通用设备填default
*/
ChipOs: string;
/**
* 芯片厂商id,通用设备填default
*/
ChipManufactureId: string;
/**
* 芯片id,通用设备填default
*/
ChipId: string;
/**
* 产品描述信息
*/
ProductDescription: string;
/**
* 认证方式 只支持取值为2 psk认证
*/
EncryptionType?: number;
}
/**
* DescribeFirmwareTasks请求参数结构体
*/
export interface DescribeFirmwareTasksRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 固件版本号
*/
FirmwareVersion: string;
/**
* 查询偏移量
*/
Offset: number;
/**
* 返回查询结果条数
*/
Limit: number;
/**
* 搜索过滤条件
*/
Filters?: Array<SearchKeyword>;
}
/**
* GetFirmwareURL返回参数结构体
*/
export interface GetFirmwareURLResponse {
/**
* 固件URL
*/
Url: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeAIModelApplications请求参数结构体
*/
export interface DescribeAIModelApplicationsRequest {
/**
* 模型ID
*/
ModelId: string;
/**
* 分页的大小,最大100
*/
Limit: number;
/**
* 偏移量,Offset从0开始
*/
Offset: number;
/**
* 产品ID
*/
ProductId?: string;
}
/**
* DescribeCloudStorageEvents请求参数结构体
*/
export interface DescribeCloudStorageEventsRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 起始时间(Unix 时间戳,秒级), 为0 表示 当前时间 - 24h
*/
StartTime?: number;
/**
* 结束时间(Unix 时间戳,秒级), 为0 表示当前时间
*/
EndTime?: number;
/**
* 请求上下文, 用作查询游标
*/
Context?: string;
/**
* 单次获取的历史数据项目的最大数量, 缺省10
*/
Size?: number;
/**
* 事件标识符,可以用来指定查询特定的事件,如果不指定,则查询所有事件。
*/
EventId?: string;
/**
* 用户ID
*/
UserId?: string;
}
/**
* ListFirmwares请求参数结构体
*/
export interface ListFirmwaresRequest {
/**
* 获取的页数
*/
PageNum: number;
/**
* 分页的大小
*/
PageSize: number;
/**
* 产品ID
*/
ProductID?: string;
/**
* 搜索过滤条件
*/
Filters?: Array<SearchKeyword>;
}
/**
* PublishMessage请求参数结构体
*/
export interface PublishMessageRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 消息发往的主题
*/
Topic: string;
/**
* 云端下发到设备的控制报文
*/
Payload: string;
/**
* 消息服务质量等级,取值为0或1
*/
Qos?: number;
/**
* Payload的内容编码格式,取值为base64或空。base64表示云端将接收到的base64编码后的报文再转换成二进制报文下发至设备,为空表示不作转换,透传下发至设备
*/
PayloadEncoding?: string;
}
/**
* DescribeDeviceStatusLog请求参数结构体
*/
export interface DescribeDeviceStatusLogRequest {
/**
* 开始时间(毫秒)
*/
MinTime: number;
/**
* 结束时间(毫秒)
*/
MaxTime: number;
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 返回条数
*/
Limit?: number;
/**
* 检索上下文
*/
Context?: string;
}
/**
* DescribeSDKLog返回参数结构体
*/
export interface DescribeSDKLogResponse {
/**
* 日志检索上下文
*/
Context: string;
/**
* 是否还有日志,如有仍有日志,下次查询的请求带上当前请求返回的Context
*/
Listover: boolean;
/**
* 日志列表
*/
Results: Array<SDKLogItem>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeBalance返回参数结构体
*/
export interface DescribeBalanceResponse {
/**
* 账户余额,单位:分(人民币)。
*/
Balance: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* UploadFirmware请求参数结构体
*/
export interface UploadFirmwareRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 固件版本号
*/
FirmwareVersion: string;
/**
* 固件的MD5值
*/
Md5sum: string;
/**
* 固件的大小
*/
FileSize: number;
/**
* 固件名称
*/
FirmwareName?: string;
/**
* 固件描述
*/
FirmwareDescription?: string;
}
/**
* DescribeFirmwareTasks返回参数结构体
*/
export interface DescribeFirmwareTasksResponse {
/**
* 固件升级任务列表
注意:此字段可能返回 null,表示取不到有效值。
*/
TaskInfos: Array<FirmwareTaskInfo>;
/**
* 固件升级任务总数
注意:此字段可能返回 null,表示取不到有效值。
*/
Total: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 云存用户信息
*/
export interface CloudStorageUserInfo {
/**
* 用户ID
*/
UserId: string;
}
/**
* EditFirmware返回参数结构体
*/
export interface EditFirmwareResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeFirmwareTaskDistribution请求参数结构体
*/
export interface DescribeFirmwareTaskDistributionRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 固件版本号
*/
FirmwareVersion: string;
/**
* 固件升级任务ID
*/
TaskId: number;
}
/**
* 产品分类实体
*/
export interface ProductTemplate {
/**
* 实体ID
*/
Id: number;
/**
* 分类字段
*/
CategoryKey: string;
/**
* 分类名称
*/
CategoryName: string;
/**
* 上层实体ID
*/
ParentId: number;
/**
* 物模型
*/
ModelTemplate: string;
/**
* 排列顺序
注意:此字段可能返回 null,表示取不到有效值。
*/
ListOrder: number;
/**
* 分类图标地址
注意:此字段可能返回 null,表示取不到有效值。
*/
IconUrl: string;
/**
* 九宫格图片地址
注意:此字段可能返回 null,表示取不到有效值。
*/
IconUrlGrid: string;
}
/**
* DeleteProduct返回参数结构体
*/
export interface DeleteProductResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyForwardRule返回参数结构体
*/
export interface ModifyForwardRuleResponse {
/**
* 腾讯云账号
*/
Endpoint: string;
/**
* 产品ID
*/
ProductID: string;
/**
* 结果
*/
Result: number;
/**
* 错误信息
*/
ErrMsg: string;
/**
* 队列类型 0.CMQ 1.CKafka
*/
QueueType: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 账户流水
*/
export interface BalanceTransaction {
/**
* 账户类型:1-设备接入 2-云存。
*/
AccountType: number;
/**
* 账户变更类型:Rechareg-充值;CreateOrder-新购。
*/
Operation: string;
/**
* 流水ID。
*/
DealId: string;
/**
* 变更金额,单位:分(人民币)。
*/
Amount: number;
/**
* 变更后账户余额,单位:分(人民币)。
*/
Balance: number;
/**
* 变更时间。
*/
OperationTime: number;
}
/**
* 固件升级任务信息
*/
export interface FirmwareTaskInfo {
/**
* 任务ID
注意:此字段可能返回 null,表示取不到有效值。
*/
TaskId: number;
/**
* 任务状态
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: number;
/**
* 任务类型
注意:此字段可能返回 null,表示取不到有效值。
*/
Type: number;
/**
* 任务创建时间
注意:此字段可能返回 null,表示取不到有效值。
*/
CreateTime: number;
}
/**
* AI模型申请信息
*/
export interface AIModelApplication {
/**
* 产品ID
*/
ProductId: string;
/**
* 产品名称
*/
ProductName: string;
/**
* 申请状态:1-已申请;2-已取消;3-已拒绝;4-已通过
*/
Status: number;
}
/**
* DescribeFirmwareTaskDistribution返回参数结构体
*/
export interface DescribeFirmwareTaskDistributionResponse {
/**
* 固件升级任务状态分布信息
*/
StatusInfos: Array<StatusStatistic>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeBatch返回参数结构体
*/
export interface DescribeBatchResponse {
/**
* 批次详情
*/
Data: VideoBatch;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 数据转发描述
*/
export interface DataForward {
/**
* 产品ID。
*/
ProductId: string;
/**
* 转发地址。
*/
ForwardAddr: string;
/**
* 转发状态。
*/
Status: number;
/**
* 创建时间。
*/
CreateTime: number;
/**
* 更新时间。
*/
UpdateTime: number;
/**
* 1-数据信息转发 2-设备上下线状态转发 3-数据信息转发&设备上下线状态转发
注意:此字段可能返回 null,表示取不到有效值。
*/
DataChose: number;
}
/**
* DescribeDevice请求参数结构体
*/
export interface DescribeDeviceRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名
*/
DeviceName: string;
}
/**
* ModifyForwardRule请求参数结构体
*/
export interface ModifyForwardRuleRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 消息类型
*/
MsgType: number;
/**
* 控制台Skey
*/
Skey: string;
/**
* 队列区域
*/
QueueRegion: string;
/**
* 队列类型 0.CMQ 1.CKafka
*/
QueueType: number;
/**
* 临时密钥
*/
Consecretid?: string;
/**
* 实例ID
*/
InstanceId?: string;
/**
* 实例名称
*/
InstanceName?: string;
/**
* 队列或主题ID
*/
QueueID?: string;
/**
* 队列或主题名称
*/
QueueName?: string;
}
/**
* CreateAIDetection返回参数结构体
*/
export interface CreateAIDetectionResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCloudStorageEvents返回参数结构体
*/
export interface DescribeCloudStorageEventsResponse {
/**
* 云存事件列表
*/
Events: Array<CloudStorageEvent>;
/**
* 请求上下文, 用作查询游标
*/
Context: string;
/**
* 拉取结果是否已经结束
*/
Listover: boolean;
/**
* 拉取结果数量
*/
Total: number;
/**
* 视频播放URL
*/
VideoURL: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* video产品元数据
*/
export interface VideoProduct {
/**
* 产品ID
*/
ProductId: string;
/**
* 产品名称
*/
ProductName: string;
/**
* 产品设备类型(普通设备) 1.普通设备
*/
DeviceType: number;
/**
* 认证方式:2:PSK
*/
EncryptionType: number;
/**
* 设备功能码
*/
Features: Array<string>;
/**
* 操作系统
*/
ChipOs: string;
/**
* 芯片厂商id
*/
ChipManufactureId: string;
/**
* 芯片id
*/
ChipId: string;
/**
* 产品描述信息
*/
ProductDescription: string;
/**
* 创建时间unix时间戳
*/
CreateTime: number;
/**
* 修改时间unix时间戳
*/
UpdateTime: number;
}
/**
* 云存事件
*/
export interface CloudStorageEvent {
/**
* 事件起始时间(Unix 时间戳,秒级
*/
StartTime: number;
/**
* 事件结束时间(Unix 时间戳,秒级
*/
EndTime: number;
/**
* 事件缩略图
*/
Thumbnail: string;
/**
* 事件ID
*/
EventId: string;
}
/**
* DescribeCloudStorageDate返回参数结构体
*/
export interface DescribeCloudStorageDateResponse {
/**
* 云存日期数组,["2021-01-05","2021-01-06"]
*/
Data: Array<string>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDataForwardStatus返回参数结构体
*/
export interface ModifyDataForwardStatusResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 云存时间轴信息
*/
export interface CloudStorageTimeInfo {
/**
* 开始时间
*/
StartTime: number;
/**
* 结束时间
*/
EndTime: number;
}
/**
* UploadFirmware返回参数结构体
*/
export interface UploadFirmwareResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* UpdateAIModelChannel请求参数结构体
*/
export interface UpdateAIModelChannelRequest {
/**
* 模型ID
*/
ModelId: string;
/**
* 产品ID
*/
ProductId: string;
/**
* 推送类型。ckafka:消息队列;forward:http/https推送
*/
Type: string;
/**
* 第三方推送地址
*/
ForwardAddress?: string;
/**
* 第三方推送密钥,不填写则腾讯云自动生成。
*/
ForwardKey?: string;
/**
* ckafka地域
*/
CKafkaRegion?: string;
/**
* ckafka实例
*/
CKafkaInstance?: string;
/**
* ckafka订阅主题
*/
CKafkaTopic?: string;
}
/**
* CreateCloudStorage返回参数结构体
*/
export interface CreateCloudStorageResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* BindCloudStorageUser返回参数结构体
*/
export interface BindCloudStorageUserResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CancelDeviceFirmwareTask请求参数结构体
*/
export interface CancelDeviceFirmwareTaskRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 固件版本号
*/
FirmwareVersion: string;
/**
* 固件升级任务ID
*/
TaskId: number;
}
/**
* CancelDeviceFirmwareTask返回参数结构体
*/
export interface CancelDeviceFirmwareTaskResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteDevice返回参数结构体
*/
export interface DeleteDeviceResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* WakeUpDevice请求参数结构体
*/
export interface WakeUpDeviceRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
}
/**
* ApplyAIModel返回参数结构体
*/
export interface ApplyAIModelResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ControlDeviceData返回参数结构体
*/
export interface ControlDeviceDataResponse {
/**
* 返回信息
*/
Data: string;
/**
* JSON字符串, 返回下发控制的结果信息,
Sent = 1 表示设备已经在线并且订阅了控制下发的mqtt topic
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDeviceDataHistory请求参数结构体
*/
export interface DescribeDeviceDataHistoryRequest {
/**
* 区间开始时间(Unix 时间戳,毫秒级)
*/
MinTime: number;
/**
* 区间结束时间(Unix 时间戳,毫秒级)
*/
MaxTime: number;
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 属性字段名称,对应数据模板中功能属性的标识符
*/
FieldName: string;
/**
* 返回条数
*/
Limit?: Array<number>;
/**
* 检索上下文
*/
Context?: string;
}
/**
* 设备事件的搜索结果项
*/
export interface EventHistoryItem {
/**
* 事件的时间戳
注意:此字段可能返回 null,表示取不到有效值。
*/
TimeStamp: number;
/**
* 事件的产品ID
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductId: string;
/**
* 事件的设备名称
注意:此字段可能返回 null,表示取不到有效值。
*/
DeviceName: string;
/**
* 事件的标识符ID
注意:此字段可能返回 null,表示取不到有效值。
*/
EventId: string;
/**
* 事件的类型
注意:此字段可能返回 null,表示取不到有效值。
*/
Type: string;
/**
* 事件的数据
注意:此字段可能返回 null,表示取不到有效值。
*/
Data: string;
}
/**
* CreateForwardRule请求参数结构体
*/
export interface CreateForwardRuleRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 消息类型
*/
MsgType: number;
/**
* 控制台Skey
*/
Skey: string;
/**
* 队列区域
*/
QueueRegion: string;
/**
* 队列类型 0.CMQ 1.Ckafka
*/
QueueType: number;
/**
* 临时密钥
*/
Consecretid?: string;
/**
* 实例ID
*/
InstanceId?: string;
/**
* 实例名称
*/
InstanceName?: string;
/**
* 队列或主题ID
*/
QueueID?: string;
/**
* 队列或主题名称
*/
QueueName?: string;
}
/**
* 设备详细信息
*/
export interface DeviceInfo {
/**
* 设备名
*/
DeviceName: string;
/**
* 设备是否在线,0不在线,1在线,2获取失败,3未激活
*/
Online: number;
/**
* 设备最后上线时间
*/
LoginTime: number;
/**
* 设备密钥
*/
DevicePsk: string;
/**
* 设备启用状态 0为停用 1为可用
*/
EnableState: number;
/**
* 设备过期时间
*/
ExpireTime: number;
}
/**
* SetForwardAuth请求参数结构体
*/
export interface SetForwardAuthRequest {
/**
* 控制台Skey
*/
Skey: string;
/**
* 消息队列类型 0.CMQ 1.CKafka
*/
QueueType: number;
}
/**
* DescribeBalanceTransactions返回参数结构体
*/
export interface DescribeBalanceTransactionsResponse {
/**
* 账户流水总数。
*/
TotalCount: number;
/**
* 账户流水详情数组。
*/
Transactions: Array<BalanceTransaction>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyDevice返回参数结构体
*/
export interface ModifyDeviceResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateTaskFileUrl请求参数结构体
*/
export interface CreateTaskFileUrlRequest {
/**
* 产品ID
*/
ProductId: string;
}
/**
* ModifyDeviceLogLevel返回参数结构体
*/
export interface ModifyDeviceLogLevelResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateDataForward请求参数结构体
*/
export interface CreateDataForwardRequest {
/**
* 产品ID。
*/
ProductId: string;
/**
* 转发地址。如果有鉴权Token,则需要自行传入,例如 [{\"forward\":{\"api\":\"http://123.207.117.108:1080/sub.php\",\"token\":\"testtoken\"}}]
*/
ForwardAddr: string;
/**
* 1-数据信息转发 2-设备上下线状态转发 3-数据信息转发&设备上下线状态转发
*/
DataChose?: number;
}
/**
* BatchUpdateFirmware请求参数结构体
*/
export interface BatchUpdateFirmwareRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 固件新版本号
*/
FirmwareVersion: string;
/**
* 固件原版本号,根据文件列表升级固件不需要填写此参数
*/
FirmwareOriVersion?: string;
/**
* 升级方式,0 静默升级 1 用户确认升级。 不填默认为静默升级方式
*/
UpgradeMethod?: number;
/**
* 设备列表文件名称,根据文件列表升级固件需要填写此参数
*/
FileName?: string;
/**
* 设备列表的文件md5值
*/
FileMd5?: string;
/**
* 设备列表的文件大小值
*/
FileSize?: number;
/**
* 需要升级的设备名称列表
*/
DeviceNames?: Array<string>;
}
/**
* DescribeCloudStorageThumbnail请求参数结构体
*/
export interface DescribeCloudStorageThumbnailRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 缩略图文件名
*/
Thumbnail: string;
}
/**
* GetFirmwareURL请求参数结构体
*/
export interface GetFirmwareURLRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 固件版本
*/
FirmwareVersion: string;
}
/**
* CreateAIDetection请求参数结构体
*/
export interface CreateAIDetectionRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* AI模型ID
*/
ModelId: string;
/**
* 图片上传的开始时间
*/
StartTime: number;
/**
* 图片上传的结束时间
*/
EndTime: number;
}
/**
* DescribeCloudStorage返回参数结构体
*/
export interface DescribeCloudStorageResponse {
/**
* 云存开启状态,1为开启,0为未开启或已过期
*/
Status: number;
/**
* 云存类型,1为全时云存,2为事件云存
*/
Type: number;
/**
* 云存套餐过期时间
*/
ExpireTime: number;
/**
* 云存回看时长
*/
ShiftDuration: number;
/**
* 云存用户ID
注意:此字段可能返回 null,表示取不到有效值。
*/
UserId: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ResetCloudStorage请求参数结构体
*/
export interface ResetCloudStorageRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
}
/**
* DescribeProduct返回参数结构体
*/
export interface DescribeProductResponse {
/**
* 产品详情
*/
Data: VideoProduct;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* SDK日志项
*/
export interface SDKLogItem {
/**
* 产品ID
*/
ProductID: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 日志等级
*/
Level: string;
/**
* 日志时间
*/
DateTime: string;
/**
* 日志内容
*/
Content: string;
}
/**
* DescribeAIModels返回参数结构体
*/
export interface DescribeAIModelsResponse {
/**
* AI模型数量
*/
TotalCount: number;
/**
* AI模型信息数组
*/
Models: Array<AIModelInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* InheritCloudStorageUser请求参数结构体
*/
export interface InheritCloudStorageUserRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 原始用户ID
*/
UserId: string;
/**
* 目标用户ID
*/
ToUserId: string;
}
/**
* DescribeAIModelChannel请求参数结构体
*/
export interface DescribeAIModelChannelRequest {
/**
* 模型ID
*/
ModelId: string;
/**
* 产品ID
*/
ProductId: string;
}
/**
* DescribeAIModelUsage请求参数结构体
*/
export interface DescribeAIModelUsageRequest {
/**
* 模型ID
*/
ModelId: string;
/**
* 产品ID
*/
ProductId: string;
/**
* 偏移量,从0开始
*/
Offset: number;
/**
* 分页的大小,最大100
*/
Limit: number;
}
/**
* DescribeCategory请求参数结构体
*/
export interface DescribeCategoryRequest {
/**
* Category ID。
*/
Id: number;
}
/**
* DeleteFirmware请求参数结构体
*/
export interface DeleteFirmwareRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 固件版本
*/
FirmwareVersion: string;
}
/**
* DescribeCloudStorage请求参数结构体
*/
export interface DescribeCloudStorageRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 云存用户ID
*/
UserId?: string;
}
/**
* GetAllFirmwareVersion返回参数结构体
*/
export interface GetAllFirmwareVersionResponse {
/**
* 固件可用版本列表
*/
Version: Array<string>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* AI模型信息
*/
export interface AIModelInfo {
/**
* 产品ID
*/
ProductId: string;
/**
* 产品名称
*/
ProductName: string;
/**
* 申请状态:1-已申请;2-已取消;3-已拒绝;4-已通过
*/
Status: number;
/**
* 可调用数量
*/
Total: number;
/**
* 已调用数量
*/
Used: number;
/**
* 申请时间
*/
ApplyTime: number;
/**
* 审批通过时间
*/
ApprovalTime: number;
}
/**
* DescribeDeviceDataHistory返回参数结构体
*/
export interface DescribeDeviceDataHistoryResponse {
/**
* 属性字段名称,对应数据模板中功能属性的标识符
注意:此字段可能返回 null,表示取不到有效值。
*/
FieldName: string;
/**
* 数据是否已全部返回,true 表示数据全部返回,false 表示还有数据待返回,可将 Context 作为入参,继续查询返回结果。
注意:此字段可能返回 null,表示取不到有效值。
*/
Listover: boolean;
/**
* 检索上下文,当 ListOver 为false时,可以用此上下文,继续读取后续数据
注意:此字段可能返回 null,表示取不到有效值。
*/
Context: string;
/**
* 历史数据结果数组,返回对应时间点及取值。
注意:此字段可能返回 null,表示取不到有效值。
*/
Results: Array<DeviceDataHistoryItem>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 搜索关键词
*/
export interface SearchKeyword {
/**
* 搜索条件的Key
*/
Key: string;
/**
* 搜索条件的值
*/
Value?: string;
}
/**
* DescribeDevices请求参数结构体
*/
export interface DescribeDevicesRequest {
/**
* 需要查看设备列表的产品 ID
*/
ProductId: string;
/**
* 偏移量,Offset从0开始
*/
Offset: number;
/**
* 分页的大小,最大100
*/
Limit: number;
/**
* 需要过滤的设备名称
*/
DeviceName?: string;
}
/**
* DescribeModelDefinition请求参数结构体
*/
export interface DescribeModelDefinitionRequest {
/**
* 产品ID
*/
ProductId: string;
}
/**
* DescribeFirmwareTaskStatistics返回参数结构体
*/
export interface DescribeFirmwareTaskStatisticsResponse {
/**
* 升级成功的设备总数
注意:此字段可能返回 null,表示取不到有效值。
*/
SuccessTotal: number;
/**
* 升级失败的设备总数
注意:此字段可能返回 null,表示取不到有效值。
*/
FailureTotal: number;
/**
* 正在升级的设备总数
注意:此字段可能返回 null,表示取不到有效值。
*/
UpgradingTotal: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CheckForwardAuth返回参数结构体
*/
export interface CheckForwardAuthResponse {
/**
* 腾讯云账号
*/
Endpoint: string;
/**
* 结果
*/
Result: number;
/**
* 产品ID
*/
Productid: string;
/**
* 错误消息
*/
ErrMsg: string;
/**
* 队列类型 0.CMQ 1.Ckafka
*/
QueueType: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDevice返回参数结构体
*/
export interface DescribeDeviceResponse {
/**
* 设备名
*/
DeviceName: string;
/**
* 设备是否在线,0不在线,1在线,2获取失败,3未激活
*/
Online: number;
/**
* 设备最后上线时间
*/
LoginTime: number;
/**
* 设备密钥
*/
DevicePsk: string;
/**
* 设备启用状态
*/
EnableState: number;
/**
* 设备过期时间
*/
ExpireTime: number;
/**
* 设备的sdk日志等级,0:关闭,1:错误,2:告警,3:信息,4:调试
注意:此字段可能返回 null,表示取不到有效值。
*/
LogLevel: number;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeDeviceData返回参数结构体
*/
export interface DescribeDeviceDataResponse {
/**
* 设备数据
*/
Data: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteForwardRule返回参数结构体
*/
export interface DeleteForwardRuleResponse {
/**
* 腾讯云账号
*/
Endpoint: string;
/**
* 队列名称
*/
QueueName: string;
/**
* 产品ID
*/
ProductID: string;
/**
* 删除结果 0成功 其他不成功
*/
Result: number;
/**
* 错误消息
*/
ErrMsg: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 设备上下线日志记录
*/
export interface DeviceStatusLogItem {
/**
* 时间
*/
Time: string;
/**
* 状态类型: Online 上线,Offline 下线
*/
Type: string;
/**
* 日志信息
*/
Data: string;
}
/**
* ListFirmwares返回参数结构体
*/
export interface ListFirmwaresResponse {
/**
* 固件总数
*/
TotalCount: number;
/**
* 固件列表
*/
Firmwares: Array<FirmwareInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* TransferCloudStorage请求参数结构体
*/
export interface TransferCloudStorageRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 已开通云存的设备名称
*/
DeviceName: string;
/**
* 未开通云存的设备名称
*/
ToDeviceName: string;
}
/**
* DescribeFirmwareTaskStatistics请求参数结构体
*/
export interface DescribeFirmwareTaskStatisticsRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 固件版本号
*/
FirmwareVersion: string;
}
/**
* DescribeBatchs请求参数结构体
*/
export interface DescribeBatchsRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 分页的大小,最大100
*/
Limit: number;
/**
* 偏移量,Offset从0开始
*/
Offset: number;
}
/**
* CreateTaskFileUrl返回参数结构体
*/
export interface CreateTaskFileUrlResponse {
/**
* 任务文件上传链接
*/
Url: string;
/**
* 任务文件名
*/
FileName: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyModelDefinition返回参数结构体
*/
export interface ModifyModelDefinitionResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCloudStorageTime请求参数结构体
*/
export interface DescribeCloudStorageTimeRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 云存日期,例如"2020-01-05"
*/
Date: string;
/**
* 开始时间,unix时间
*/
StartTime?: number;
/**
* 结束时间,unix时间
*/
EndTime?: number;
/**
* 用户ID
*/
UserId?: string;
}
/**
* ModifyDataForwardStatus请求参数结构体
*/
export interface ModifyDataForwardStatusRequest {
/**
* 产品ID。
*/
ProductId: string;
/**
* 转发状态,1启用,0禁用。
*/
Status: number;
}
/**
* DescribeFirmwareTask请求参数结构体
*/
export interface DescribeFirmwareTaskRequest {
/**
* 产品ID
*/
ProductID: string;
/**
* 固件版本号
*/
FirmwareVersion: string;
/**
* 固件任务ID
*/
TaskId: number;
}
/**
* DescribeCloudStorageUsers请求参数结构体
*/
export interface DescribeCloudStorageUsersRequest {
/**
* 产品ID
*/
ProductId: string;
/**
* 设备名称
*/
DeviceName: string;
/**
* 分页拉取数量
*/
Limit: number;
/**
* 分页拉取偏移
*/
Offset: number;
}
/**
* DescribeAIModelApplications返回参数结构体
*/
export interface DescribeAIModelApplicationsResponse {
/**
* 申请记录数量
*/
TotalCount: number;
/**
* 申请记录数组
*/
Applications: Array<AIModelApplication>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
} | the_stack |
import { createBuilder } from '@develohpanda/fluent-builder';
import * as grpcJs from '@grpc/grpc-js';
import { afterEach, beforeEach, describe, expect, it, jest } from '@jest/globals';
import { globalBeforeEach } from '../../../__jest__/before-each';
import { grpcMocks } from '../../../__mocks__/@grpc/grpc-js';
import { grpcMethodDefinitionSchema } from '../../../ui/context/grpc/__schemas__';
import { grpcIpcMessageParamsSchema } from '../__schemas__/grpc-ipc-message-params-schema';
import { grpcIpcRequestParamsSchema } from '../__schemas__/grpc-ipc-request-params-schema';
import callCache from '../call-cache';
import * as grpc from '../index';
import * as protoLoader from '../proto-loader';
import { ResponseCallbacks as ResponseCallbacksMock } from '../response-callbacks';
jest.mock('../response-callbacks');
jest.mock('../proto-loader');
jest.mock('@grpc/grpc-js');
const requestParamsBuilder = createBuilder(grpcIpcRequestParamsSchema);
const messageParamsBuilder = createBuilder(grpcIpcMessageParamsSchema);
const methodBuilder = createBuilder(grpcMethodDefinitionSchema);
const respond = new ResponseCallbacksMock();
describe('grpc', () => {
beforeEach(() => {
globalBeforeEach();
jest.resetAllMocks();
requestParamsBuilder.reset();
messageParamsBuilder.reset();
methodBuilder.reset();
});
describe('grpc.start', () => {
afterEach(() => {
// Call cache should always be clear at the end of each test
expect(callCache.activeCount()).toBe(0);
});
it('should exit if method not found', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
protoMethodName: 'SayHi',
metadata: [],
})
.build();
protoLoader.getSelectedMethod.mockResolvedValue(null);
// Act
await grpc.start(params, respond);
// Assert
expect(respond.sendStart).not.toHaveBeenCalled();
expect(respond.sendError).toHaveBeenCalledWith(
params.request._id,
new Error(`The gRPC method ${params.request.protoMethodName} could not be found`),
);
});
it('should exit if no url is specified', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: '',
metadata: [],
})
.build();
protoLoader.getSelectedMethod.mockResolvedValue(methodBuilder.build());
// Act
await grpc.start(params, respond);
// Assert
expect(respond.sendStart).not.toHaveBeenCalled();
expect(respond.sendError).toHaveBeenCalledWith(
params.request._id,
new Error('URL not specified'),
);
});
it('should make a client', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
metadata: [],
})
.build();
const bidiMethod = methodBuilder.requestStream(true).responseStream(true).build();
protoLoader.getSelectedMethod.mockResolvedValue(bidiMethod);
// Act
await grpc.start(params, respond);
// Assert
expect(grpcMocks.mockConstructor).toHaveBeenCalledTimes(1);
expect(grpcMocks.mockConstructor.mock.calls[0][0]).toBe('grpcb.in:9000');
expect(grpcMocks.mockCreateInsecure).toHaveBeenCalled();
expect(grpcMocks.mockCreateSsl).not.toHaveBeenCalled();
// Cleanup / End the stream
grpcMocks.getMockCall().emit('end');
});
it('should make a secure client', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcs://grpcb.in:9000',
metadata: [],
})
.build();
const bidiMethod = methodBuilder.requestStream(true).responseStream(true).build();
protoLoader.getSelectedMethod.mockResolvedValue(bidiMethod);
// Act
await grpc.start(params, respond);
// Assert
expect(grpcMocks.mockConstructor).toHaveBeenCalledTimes(1);
expect(grpcMocks.mockConstructor.mock.calls[0][0]).toBe('grpcb.in:9000');
expect(grpcMocks.mockCreateInsecure).not.toHaveBeenCalled();
expect(grpcMocks.mockCreateSsl).toHaveBeenCalled();
// Cleanup / End the stream
grpcMocks.getMockCall().emit('end');
});
it('should attach status listener', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
metadata: [],
})
.build();
const bidiMethod = methodBuilder.requestStream(true).responseStream(true).build();
protoLoader.getSelectedMethod.mockResolvedValue(bidiMethod);
// Act
await grpc.start(params, respond);
// Emit stats
const status = {
code: grpcJs.status.OK,
details: 'OK',
};
grpcMocks.getMockCall().emit('status', status);
// Assert
expect(respond.sendStatus).toHaveBeenCalledWith(params.request._id, status);
// Cleanup / End the stream
grpcMocks.getMockCall().emit('end');
});
describe('unary', () => {
it('should make no request if invalid body', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
body: {
text: undefined,
},
})
.build();
const unaryMethod = methodBuilder.requestStream(false).responseStream(false).build();
protoLoader.getSelectedMethod.mockResolvedValue(unaryMethod);
// Act
await grpc.start(params, respond);
// Assert
expect(respond.sendStart).not.toHaveBeenCalled();
expect(respond.sendError).toHaveBeenCalledWith(
params.request._id,
new SyntaxError('Unexpected end of JSON input'),
);
expect(grpcMocks.mockMakeUnaryRequest).not.toHaveBeenCalled();
});
it('should make unary request with error response', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
body: {
text: '{}',
},
metadata: [],
})
.build();
const unaryMethod = methodBuilder.requestStream(false).responseStream(false).build();
protoLoader.getSelectedMethod.mockResolvedValue(unaryMethod);
// Act
await grpc.start(params, respond);
// Assert
expect(respond.sendStart).toHaveBeenCalledWith(params.request._id);
expect(grpcMocks.mockMakeUnaryRequest).toHaveBeenLastCalledWith(
unaryMethod.path,
unaryMethod.requestSerialize,
unaryMethod.responseDeserialize,
{},
expect.anything(),
expect.anything(),
);
// Trigger response
const err = {
code: grpcJs.status.DATA_LOSS,
};
const val = undefined;
grpcMocks.mockMakeUnaryRequest.mock.calls[0][5](err, val);
// Assert
expect(respond.sendData).not.toHaveBeenCalled();
expect(respond.sendError).toHaveBeenCalledWith(params.request._id, err);
expect(respond.sendEnd).toHaveBeenCalledWith(params.request._id);
});
it('should make unary request with valid response', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
body: {
text: '{}',
},
metadata: [],
})
.build();
const unaryMethod = methodBuilder.requestStream(false).responseStream(false).build();
protoLoader.getSelectedMethod.mockResolvedValue(unaryMethod);
// Act
await grpc.start(params, respond);
// Assert
expect(respond.sendStart).toHaveBeenCalledWith(params.request._id);
expect(grpcMocks.mockMakeUnaryRequest).toHaveBeenLastCalledWith(
unaryMethod.path,
unaryMethod.requestSerialize,
unaryMethod.responseDeserialize,
{},
expect.anything(),
expect.anything(),
);
// Trigger response
const err = undefined;
const val = {
foo: 'bar',
};
grpcMocks.mockMakeUnaryRequest.mock.calls[0][5](err, val);
// Assert
expect(respond.sendError).not.toHaveBeenCalled();
expect(respond.sendData).toHaveBeenCalledWith(params.request._id, val);
expect(respond.sendEnd).toHaveBeenCalledWith(params.request._id);
});
});
describe('server streaming', () => {
it('should make no request if invalid body', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
body: {
text: undefined,
},
metadata: [],
})
.build();
const serverMethod = methodBuilder.requestStream(false).responseStream(true).build();
protoLoader.getSelectedMethod.mockResolvedValue(serverMethod);
// Act
await grpc.start(params, respond);
// Assert
expect(respond.sendStart).not.toHaveBeenCalled();
expect(respond.sendError).toHaveBeenCalledWith(
params.request._id,
new SyntaxError('Unexpected end of JSON input'),
);
expect(grpcMocks.mockMakeServerStreamRequest).not.toHaveBeenCalled();
});
it('should make server streaming request with valid and error response', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
body: {
text: '{}',
},
metadata: [],
})
.build();
const serverMethod = methodBuilder.requestStream(false).responseStream(true).build();
protoLoader.getSelectedMethod.mockResolvedValue(serverMethod);
// Act
await grpc.start(params, respond);
// Assert
expect(respond.sendStart).toHaveBeenCalledWith(params.request._id);
expect(grpcMocks.mockMakeServerStreamRequest).toHaveBeenLastCalledWith(
serverMethod.path,
serverMethod.requestSerialize,
serverMethod.responseDeserialize,
{},
expect.anything(),
);
// Trigger valid response
const val = {
foo: 'bar',
};
grpcMocks.getMockCall().emit('data', val);
grpcMocks.getMockCall().emit('data', val);
// Trigger error response
const err = {
code: grpcJs.status.DATA_LOSS,
};
grpcMocks.getMockCall().emit('error', err);
grpcMocks.getMockCall().emit('end');
// Assert
expect(respond.sendData).toHaveBeenNthCalledWith(1, params.request._id, val);
expect(respond.sendData).toHaveBeenNthCalledWith(2, params.request._id, val);
expect(respond.sendError).toHaveBeenCalledWith(params.request._id, err);
expect(respond.sendEnd).toHaveBeenCalledWith(params.request._id);
});
});
describe('client streaming', () => {
it('should make client streaming request with error response', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
metadata: [],
})
.build();
const clientMethod = methodBuilder.requestStream(true).responseStream(false).build();
protoLoader.getSelectedMethod.mockResolvedValue(clientMethod);
// Act
await grpc.start(params, respond);
// Assert
expect(respond.sendStart).toHaveBeenCalledWith(params.request._id);
expect(grpcMocks.mockMakeClientStreamRequest).toHaveBeenLastCalledWith(
clientMethod.path,
clientMethod.requestSerialize,
clientMethod.responseDeserialize,
expect.anything(),
expect.anything(),
);
// Trigger response
const err = {
code: grpcJs.status.DATA_LOSS,
};
const val = undefined;
grpcMocks.mockMakeClientStreamRequest.mock.calls[0][4](err, val);
// Assert
expect(respond.sendData).not.toHaveBeenCalled();
expect(respond.sendError).toHaveBeenCalledWith(params.request._id, err);
expect(respond.sendEnd).toHaveBeenCalledWith(params.request._id);
});
it('should make client streaming request with valid response', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
metadata: [],
})
.build();
const clientMethod = methodBuilder.requestStream(true).responseStream(false).build();
protoLoader.getSelectedMethod.mockResolvedValue(clientMethod);
// Act
await grpc.start(params, respond);
// Assert
expect(respond.sendStart).toHaveBeenCalledWith(params.request._id);
expect(grpcMocks.mockMakeClientStreamRequest).toHaveBeenLastCalledWith(
clientMethod.path,
clientMethod.requestSerialize,
clientMethod.responseDeserialize,
expect.anything(),
expect.anything(),
);
// Trigger response
const err = undefined;
const val = {
foo: 'bar',
};
grpcMocks.mockMakeClientStreamRequest.mock.calls[0][4](err, val);
// Assert
expect(respond.sendError).not.toHaveBeenCalled();
expect(respond.sendData).toHaveBeenCalledWith(params.request._id, val);
expect(respond.sendEnd).toHaveBeenCalledWith(params.request._id);
});
});
describe('bidi streaming', () => {
it('should make bidi streaming request with valid and error response', async () => {
// Arrange
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
metadata: [],
})
.build();
const bidiMethod = methodBuilder.requestStream(true).responseStream(true).build();
protoLoader.getSelectedMethod.mockResolvedValue(bidiMethod);
// Act
await grpc.start(params, respond);
// Assert
expect(respond.sendStart).toHaveBeenCalledWith(params.request._id);
expect(grpcMocks.mockMakeBidiStreamRequest).toHaveBeenLastCalledWith(
bidiMethod.path,
bidiMethod.requestSerialize,
bidiMethod.responseDeserialize,
expect.anything()
);
// Trigger valid response
const val = {
foo: 'bar',
};
grpcMocks.getMockCall().emit('data', val);
grpcMocks.getMockCall().emit('data', val);
// Trigger error response
const err = {
code: grpcJs.status.DATA_LOSS,
};
grpcMocks.getMockCall().emit('error', err);
grpcMocks.getMockCall().emit('end');
// Assert
expect(respond.sendData).toHaveBeenNthCalledWith(1, params.request._id, val);
expect(respond.sendData).toHaveBeenNthCalledWith(2, params.request._id, val);
expect(respond.sendError).toHaveBeenCalledWith(params.request._id, err);
expect(respond.sendEnd).toHaveBeenCalledWith(params.request._id);
});
});
});
describe('grpc.sendMessage', () => {
const _makeClient = async () => {
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
metadata: [],
})
.build();
const clientMethod = methodBuilder.requestStream(true).responseStream(false).build();
protoLoader.getSelectedMethod.mockResolvedValue(clientMethod);
await grpc.start(params, respond);
return params;
};
it('should not send a message with invalid body contents', async () => {
// Arrange
const reqParams = await _makeClient();
const msgParams = messageParamsBuilder
.body({
text: undefined,
})
.requestId(reqParams.request._id)
.build();
// Act
grpc.sendMessage(msgParams, respond);
// Assert
expect(respond.sendError).toHaveBeenCalledWith(
msgParams.requestId,
new SyntaxError('Unexpected end of JSON input'),
);
});
it('should send a message', async () => {
// Arrange
const reqParams = await _makeClient();
const msgParams = messageParamsBuilder.requestId(reqParams.request._id).build();
// Act
grpc.sendMessage(msgParams, respond);
setTimeout(() => {
// Assert
expect(respond.sendError).not.toHaveBeenCalled();
expect(grpcMocks.mockCallWrite).toHaveBeenCalledWith({});
});
});
it('should not send a message if a call is not found', () => {
// Arrange
const msgParams = messageParamsBuilder.build();
const mockWrite = jest.fn();
grpcMocks.getMockCall().on('write', mockWrite);
// Act
grpc.sendMessage(msgParams, respond);
// Assert
setTimeout(() => {
// Assert
expect(respond.sendError).not.toHaveBeenCalled();
expect(grpcMocks.mockCallWrite).not.toHaveBeenCalled();
});
});
});
describe('grpc.commit', () => {
const _makeClient = async () => {
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
metadata: [],
})
.build();
const clientMethod = methodBuilder.requestStream(true).responseStream(false).build();
protoLoader.getSelectedMethod.mockResolvedValue(clientMethod);
await grpc.start(params, respond);
return params;
};
it('should commit', async () => {
// Arrange
const reqParams = await _makeClient();
// Act
grpc.commit(reqParams.request._id);
// Assert
expect(grpcMocks.mockCallEnd).toHaveBeenCalled();
});
it('should not commit if a call is not found', () => {
// Act
grpc.commit('another id');
// Assert
expect(grpcMocks.mockCallEnd).not.toHaveBeenCalled();
});
});
describe('grpc.cancel', () => {
const _makeClient = async () => {
const params = requestParamsBuilder
.request({
_id: 'id',
url: 'grpcb.in:9000',
metadata: [],
})
.build();
const clientMethod = methodBuilder.requestStream(true).responseStream(false).build();
protoLoader.getSelectedMethod.mockResolvedValue(clientMethod);
await grpc.start(params, respond);
return params;
};
it('should commit', async () => {
// Arrange
const reqParams = await _makeClient();
// Act
grpc.cancel(reqParams.request._id);
// Assert
expect(grpcMocks.mockCallCancel).toHaveBeenCalled();
});
it('should not commit if a call is not found', () => {
// Act
grpc.cancel('another id');
// Assert
expect(grpcMocks.mockCallCancel).not.toHaveBeenCalled();
});
});
}); | the_stack |
import {
ComputedParameter,
ConstantParameter,
Parameter,
ParameterComputeType,
TopicFactorParameter,
VariablePredefineFunctions
} from '@/services/data/tuples/factor-calculator-types';
import {isComputedParameter, isConstantParameter, isTopicFactorParameter} from '@/services/data/tuples/parameter-utils';
import {computeWeekOf} from '@/services/utils';
import dayjs from 'dayjs';
import {DataRow} from '../../../types';
import {InternalUnitRuntimeContext, PipelineRuntimeContext} from '../types';
import {computeJoint} from './condition-compute';
import {
castParameterValueType,
checkShouldBe,
checkSubParameters,
computeConstantByStatement,
getValueFromSourceData,
readTopicFactorParameter
} from './parameter-kits';
import {ParameterShouldBe} from './types';
const HALF_YEAR_FIRST: number = 1;
const HALF_YEAR_SECOND: number = 2;
const QUARTER_FIRST: number = 1;
const QUARTER_SECOND: number = 2;
const QUARTER_THIRD: number = 3;
const QUARTER_FOURTH: number = 4;
/**
* if there is alternative trigger data passed,
* which means data can be retrieved from another topic besides the topic which triggered this pipeline.
*
* note, the passed alternative trigger data must be same as the topic which is declared in this topic factor parameter.
* program will not check this.
*
* @param options
*/
export const computeTopicFactor = (options: {
parameter: TopicFactorParameter,
pipelineContext: PipelineRuntimeContext,
shouldBe: ParameterShouldBe,
/** data which can bed used to find **/
alternativeTriggerData: DataRow | null
}): any => {
const {parameter, pipelineContext, shouldBe, alternativeTriggerData} = options;
const {topic, factor} = readTopicFactorParameter({
parameter,
topics: pipelineContext.allTopics,
validOrThrow: (topicId) => {
// eslint-disable-next-line
if (!alternativeTriggerData && topicId != pipelineContext.pipeline.topicId) {
throw new Error(`Topic of parameter[${parameter}] must be source topic of pipeline.`);
}
}
});
let sourceData = pipelineContext.triggerData;
// eslint-disable-next-line
if (topic.topicId != pipelineContext.pipeline.topicId && alternativeTriggerData) {
sourceData = alternativeTriggerData;
}
const value = getValueFromSourceData(factor, sourceData);
return castParameterValueType({value, shouldBe, parameter});
};
const computeConstant = (options: {
parameter: ConstantParameter,
shouldBe: ParameterShouldBe,
getValue: (propertyName: string) => any
}): any => {
const {parameter, shouldBe, getValue} = options;
const statement = parameter.value;
let value: any;
if (statement == null) {
value = null;
} else if (statement.length === 0) {
if (shouldBe === ParameterShouldBe.ANY) {
value = '';
} else {
value = null;
}
} else if (statement.trim().length === 0) {
if (shouldBe === ParameterShouldBe.ANY) {
value = statement;
} else {
value = null;
}
} else {
value = computeConstantByStatement({statement, parameter, shouldBe, getValue});
}
return castParameterValueType({value, parameter, shouldBe});
};
const computeComputedToNumbers = (options: {
parameters: Array<Parameter>,
pipelineContext: PipelineRuntimeContext,
internalUnitContext?: InternalUnitRuntimeContext,
alternativeTriggerData: DataRow | null
}): Array<number | null> => {
const {parameters, pipelineContext, internalUnitContext, alternativeTriggerData} = options;
return parameters.map(sub => computeParameter({
parameter: sub,
pipelineContext,
internalUnitContext,
shouldBe: ParameterShouldBe.NUMBER,
alternativeTriggerData
}));
};
const computeComputed = (options: {
parameter: ComputedParameter,
pipelineContext: PipelineRuntimeContext,
shouldBe: ParameterShouldBe
internalUnitContext?: InternalUnitRuntimeContext,
alternativeTriggerData: DataRow | null
}): any => {
const {parameter, shouldBe, pipelineContext, internalUnitContext, alternativeTriggerData} = options;
checkSubParameters(parameter);
checkShouldBe(parameter, shouldBe);
const parameters = parameter.parameters;
let value: any;
switch (parameter.type) {
case ParameterComputeType.NONE:
throw new Error(`Operator of parameter[${parameter}] cannot be none.`);
case ParameterComputeType.ADD:
value = computeComputedToNumbers({parameters, pipelineContext, internalUnitContext, alternativeTriggerData})
.reduce((x, y) => (x ?? 0) + (y ?? 0));
break;
case ParameterComputeType.SUBTRACT:
value = computeComputedToNumbers({parameters, pipelineContext, internalUnitContext, alternativeTriggerData})
.filter(x => x != null)
.reduce((x, y) => (x as number) - (y as number));
break;
case ParameterComputeType.MULTIPLY:
value = computeComputedToNumbers({parameters, pipelineContext, internalUnitContext, alternativeTriggerData})
.reduce((x, y) => (x ?? 1) * (y ?? 1));
break;
case ParameterComputeType.DIVIDE:
value = computeComputedToNumbers({parameters, pipelineContext, internalUnitContext, alternativeTriggerData})
.filter(x => x != null)
.reduce((x, y) => (x as number) - (y as number));
break;
case ParameterComputeType.MODULUS:
const v0 = computeParameter({
parameter: parameters[0],
pipelineContext,
shouldBe: ParameterShouldBe.NUMBER,
internalUnitContext,
alternativeTriggerData
});
const v1 = computeParameter({
parameter: parameters[1],
pipelineContext,
shouldBe: ParameterShouldBe.NUMBER,
internalUnitContext,
alternativeTriggerData
});
value = v0 % v1;
break;
case ParameterComputeType.YEAR_OF: {
const date = computeParameter({
parameter: parameters[0],
pipelineContext,
shouldBe: ParameterShouldBe.DATE,
internalUnitContext,
alternativeTriggerData
});
value = date ? dayjs(date).year() : null;
break;
}
case ParameterComputeType.HALF_YEAR_OF: {
const date = computeParameter({
parameter: parameters[0],
pipelineContext,
shouldBe: ParameterShouldBe.DATE,
internalUnitContext,
alternativeTriggerData
});
if (date == null) {
value = null;
} else {
const month = dayjs(date).month();
value = month < 6 ? HALF_YEAR_FIRST : HALF_YEAR_SECOND;
}
break;
}
case ParameterComputeType.QUARTER_OF: {
const date = computeParameter({
parameter: parameters[0],
pipelineContext,
shouldBe: ParameterShouldBe.DATE,
internalUnitContext,
alternativeTriggerData
});
if (date == null) {
value = null;
} else {
const month = dayjs(date).month();
switch (true) {
case month < 3:
value = QUARTER_FIRST;
break;
case month < 6:
value = QUARTER_SECOND;
break;
case month < 9:
value = QUARTER_THIRD;
break;
default:
value = QUARTER_FOURTH;
break;
}
}
break;
}
case ParameterComputeType.MONTH_OF: {
const date = computeParameter({
parameter: parameters[0],
pipelineContext,
shouldBe: ParameterShouldBe.DATE,
internalUnitContext,
alternativeTriggerData
});
value = date ? (dayjs(date).month() + 1) : null;
break;
}
case ParameterComputeType.WEEK_OF_YEAR: {
const date = computeParameter({
parameter: parameters[0],
pipelineContext,
shouldBe: ParameterShouldBe.DATE,
internalUnitContext,
alternativeTriggerData
});
if (date == null) {
value = null;
} else {
value = computeWeekOf(date, 'year');
}
break;
}
case ParameterComputeType.WEEK_OF_MONTH: {
const date = computeParameter({
parameter: parameters[0],
pipelineContext,
shouldBe: ParameterShouldBe.DATE,
internalUnitContext,
alternativeTriggerData
});
if (date == null) {
value = null;
} else {
value = computeWeekOf(date, 'month');
}
break;
}
case ParameterComputeType.DAY_OF_MONTH: {
const date = computeParameter({
parameter: parameters[0],
pipelineContext,
shouldBe: ParameterShouldBe.DATE,
internalUnitContext,
alternativeTriggerData
});
value = date ? dayjs(date).date() : null;
break;
}
case ParameterComputeType.DAY_OF_WEEK: {
const date = computeParameter({
parameter: parameters[0],
pipelineContext,
shouldBe: ParameterShouldBe.DATE,
internalUnitContext,
alternativeTriggerData
});
value = date ? (dayjs(date).day() + 1) : null;
break;
}
case ParameterComputeType.CASE_THEN:
const route = parameters
.filter(parameter => parameter.conditional && !!parameter.on)
.find(parameter => {
return computeJoint({
joint: parameter.on!,
pipelineContext,
internalUnitContext,
alternativeTriggerData
});
});
// noinspection JSIncompatibleTypesComparison
if (route != null) {
return computeParameter({
parameter: route,
pipelineContext,
shouldBe,
internalUnitContext,
alternativeTriggerData
});
}
const defaultRoute = parameters.find(parameter => !parameter.on);
if (defaultRoute) {
value = computeParameter({
parameter: defaultRoute,
pipelineContext,
shouldBe,
internalUnitContext,
alternativeTriggerData
});
} else {
value = null;
}
break;
}
return castParameterValueType({value, shouldBe, parameter});
};
export const computeParameter = (options: {
parameter: Parameter,
pipelineContext: PipelineRuntimeContext,
shouldBe?: ParameterShouldBe,
internalUnitContext?: InternalUnitRuntimeContext,
/** data which can bed used to find in parameter **/
alternativeTriggerData: DataRow | null
}): any => {
const {
parameter,
pipelineContext,
shouldBe = ParameterShouldBe.ANY,
internalUnitContext,
alternativeTriggerData
} = options;
if (isTopicFactorParameter(parameter)) {
return computeTopicFactor({parameter, pipelineContext, shouldBe, alternativeTriggerData});
} else if (isConstantParameter(parameter)) {
return computeConstant({
parameter, shouldBe, getValue: (propertyName) => {
if (propertyName === VariablePredefineFunctions.FROM_PREVIOUS_TRIGGER_DATA) {
return pipelineContext.triggerDataOnce;
}
let value;
if (internalUnitContext && Object.keys(internalUnitContext.variables).includes(propertyName)) {
value = internalUnitContext.variables[propertyName];
} else if (Object.keys(pipelineContext.variables).includes(propertyName)) {
value = pipelineContext.variables[propertyName];
} else {
value = pipelineContext.triggerData[propertyName];
}
return value ?? null;
}
});
} else if (isComputedParameter(parameter)) {
return computeComputed({parameter, pipelineContext, shouldBe, internalUnitContext, alternativeTriggerData});
} else {
throw new Error(`Unsupported parameter[${parameter}].`);
}
}; | the_stack |
import {
Agile,
Observer,
RuntimeJob,
Item,
SubscriptionContainer,
Group,
Collection,
GroupObserver,
} from '../../../../src';
import * as Utils from '@agile-ts/utils';
import { LogMock } from '../../../helper/logMock';
describe('GroupObserver Tests', () => {
interface ItemInterface {
id: string;
name: string;
}
let dummyAgile: Agile;
let dummyCollection: Collection<ItemInterface>;
let dummyGroup: Group<ItemInterface>;
let dummyItem1: Item<ItemInterface>;
let dummyItem2: Item<ItemInterface>;
beforeEach(() => {
LogMock.mockLogs();
dummyAgile = new Agile();
dummyCollection = new Collection<ItemInterface>(dummyAgile);
dummyGroup = new Group<ItemInterface>(dummyCollection, [], {
key: 'dummyGroup',
});
dummyItem1 = new Item(dummyCollection, {
id: 'dummyItem1Key',
name: 'frank',
});
dummyItem2 = new Item(dummyCollection, {
id: 'dummyItem2Key',
name: 'jeff',
});
jest.clearAllMocks();
});
it('should create Group Observer (default config)', () => {
dummyGroup._output = [dummyItem1._value, dummyItem2._value];
const groupObserver = new GroupObserver(dummyGroup);
expect(groupObserver).toBeInstanceOf(GroupObserver);
expect(groupObserver.nextGroupValue).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(groupObserver.group()).toBe(dummyGroup);
// Check if Observer was called with correct parameters
expect(groupObserver.value).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(groupObserver.previousValue).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(groupObserver.key).toBeUndefined();
expect(Array.from(groupObserver.dependents)).toStrictEqual([]);
expect(Array.from(groupObserver.subscribedTo)).toStrictEqual([]);
});
it('should create Group Observer (specific config)', () => {
const dummyObserver1 = new Observer(dummyAgile, { key: 'dummyObserver1' });
const dummyObserver2 = new Observer(dummyAgile, { key: 'dummyObserver2' });
const dummySubscription1 = new SubscriptionContainer([]);
const dummySubscription2 = new SubscriptionContainer([]);
const groupObserver = new GroupObserver(dummyGroup, {
key: 'testKey',
dependents: [dummyObserver1, dummyObserver2],
subs: [dummySubscription1, dummySubscription2],
});
expect(groupObserver).toBeInstanceOf(GroupObserver);
expect(groupObserver.nextGroupValue).toStrictEqual([]);
expect(groupObserver.group()).toBe(dummyGroup);
// Check if Observer was called with correct parameters
expect(groupObserver.value).toStrictEqual([]);
expect(groupObserver.previousValue).toStrictEqual([]);
expect(groupObserver.key).toBe('testKey');
expect(Array.from(groupObserver.dependents)).toStrictEqual([
dummyObserver1,
dummyObserver2,
]);
expect(Array.from(groupObserver.subscribedTo)).toStrictEqual([
dummySubscription1,
dummySubscription2,
]);
});
describe('Group Observer Function Tests', () => {
let groupObserver: GroupObserver<ItemInterface>;
beforeEach(() => {
groupObserver = new GroupObserver(dummyGroup, {
key: 'groupObserverKey',
});
});
describe('ingest function tests', () => {
beforeEach(() => {
groupObserver.ingestOutput = jest.fn();
});
it('should call ingestOutput with nextGroupOutput (default config)', () => {
groupObserver.group().nextGroupOutput = 'jeff' as any;
groupObserver.ingest();
expect(groupObserver.ingestOutput).toHaveBeenCalledWith(
groupObserver.group().nextGroupOutput,
{}
);
});
it('should call ingestOutput with nextGroupOutput (specific config)', () => {
groupObserver.group().nextGroupOutput = 'jeff' as any;
groupObserver.ingest({
background: true,
force: true,
maxTriesToUpdate: 5,
});
expect(groupObserver.ingestOutput).toHaveBeenCalledWith(
groupObserver.group().nextGroupOutput,
{
background: true,
force: true,
maxTriesToUpdate: 5,
}
);
});
});
describe('ingestOutput function tests', () => {
beforeEach(() => {
dummyAgile.runtime.ingest = jest.fn();
});
it(
'should ingest the Group into the Runtime ' +
"if the new value isn't equal to the current value (default config)",
() => {
jest.spyOn(Utils, 'generateId').mockReturnValue('randomKey');
dummyAgile.runtime.ingest = jest.fn((job: RuntimeJob) => {
expect(job.key).toBe(`${groupObserver.key}_randomKey_output`);
expect(job.observer).toBe(groupObserver);
expect(job.config).toStrictEqual({
background: false,
sideEffects: {
enabled: true,
exclude: [],
},
force: false,
maxTriesToUpdate: 3,
any: {},
});
});
groupObserver.ingestOutput([dummyItem1._value, dummyItem2._value]);
expect(groupObserver.nextGroupValue).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(dummyAgile.runtime.ingest).toHaveBeenCalledWith(
expect.any(RuntimeJob),
{
perform: true,
}
);
}
);
it(
'should ingest the Group into the Runtime ' +
"if the new value isn't equal to the current value (specific config)",
() => {
dummyAgile.runtime.ingest = jest.fn((job: RuntimeJob) => {
expect(job.key).toBe('dummyJob');
expect(job.observer).toBe(groupObserver);
expect(job.config).toStrictEqual({
background: false,
sideEffects: {
enabled: false,
},
force: true,
maxTriesToUpdate: 5,
any: {},
});
});
groupObserver.ingestOutput([dummyItem1._value, dummyItem2._value], {
perform: false,
force: true,
sideEffects: {
enabled: false,
},
key: 'dummyJob',
maxTriesToUpdate: 5,
});
expect(groupObserver.nextGroupValue).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(dummyAgile.runtime.ingest).toHaveBeenCalledWith(
expect.any(RuntimeJob),
{
perform: false,
}
);
}
);
it(
"shouldn't ingest the Group into the Runtime " +
'if the new value is equal to the current value (default config)',
() => {
dummyGroup._output = [dummyItem1._value, dummyItem2._value];
groupObserver.ingestOutput([dummyItem1._value, dummyItem2._value]);
expect(groupObserver.nextGroupValue).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(dummyAgile.runtime.ingest).not.toHaveBeenCalled();
}
);
it(
'should ingest the Group into the Runtime ' +
'if the new value is equal to the current value (config.force = true)',
() => {
jest.spyOn(Utils, 'generateId').mockReturnValue('randomKey');
dummyGroup._output = [dummyItem1._value, dummyItem2._value];
dummyAgile.runtime.ingest = jest.fn((job: RuntimeJob) => {
expect(job.key).toBe(`${groupObserver.key}_randomKey_output`);
expect(job.observer).toBe(groupObserver);
expect(job.config).toStrictEqual({
background: false,
sideEffects: {
enabled: true,
exclude: [],
},
force: true,
maxTriesToUpdate: 3,
any: {},
});
});
groupObserver.ingestOutput([dummyItem1._value, dummyItem2._value], {
force: true,
});
expect(groupObserver.nextGroupValue).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(dummyAgile.runtime.ingest).toHaveBeenCalledWith(
expect.any(RuntimeJob),
{
perform: true,
}
);
}
);
it('should ingest placeholder Group into the Runtime (default config)', () => {
jest.spyOn(Utils, 'generateId').mockReturnValue('randomKey');
dummyAgile.runtime.ingest = jest.fn((job: RuntimeJob) => {
expect(job.key).toBe(`${groupObserver.key}_randomKey_output`);
expect(job.observer).toBe(groupObserver);
expect(job.config).toStrictEqual({
background: false,
sideEffects: {
enabled: true,
exclude: [],
},
force: true,
maxTriesToUpdate: 3,
any: {},
});
});
dummyGroup.isPlaceholder = true;
groupObserver.ingestOutput([dummyItem1._value, dummyItem2._value]);
expect(groupObserver.nextGroupValue).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(dummyAgile.runtime.ingest).toHaveBeenCalledWith(
expect.any(RuntimeJob),
{
perform: true,
}
);
});
});
describe('perform function tests', () => {
let dummyJob: RuntimeJob;
beforeEach(() => {
dummyJob = new RuntimeJob(groupObserver, {
key: 'dummyJob',
});
});
it('should perform the specified Job', () => {
(dummyJob.observer as GroupObserver).nextGroupValue = [
dummyItem1._value,
dummyItem2._value,
];
(dummyJob.observer as GroupObserver).value = [dummyItem1._value];
dummyGroup._output = [dummyItem1._value];
dummyGroup.nextGroupOutput = [dummyItem1._value];
groupObserver.perform(dummyJob);
expect(dummyGroup._output).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(dummyGroup.nextGroupOutput).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(groupObserver.value).toStrictEqual([
dummyItem1._value,
dummyItem2._value,
]);
expect(groupObserver.previousValue).toStrictEqual([dummyItem1._value]);
});
});
});
}); | the_stack |
namespace ts {
let checker: TypeChecker | null;
let sourceFiles: SourceFile[];
let rootFileNames: string[];
let dependencyMap: any;
let pathWeightMap: any;
let visitedBlocks: Block[];
let calledMethods: MethodDeclaration[] = [];
interface Map<T> {
[index: string]: T;
[index: number]: T;
}
function createMap<T>(): Map<T> {
const map: Map<T> = Object.create(null);
// Using 'delete' on an object causes V8 to put the object in dictionary mode.
// This disables creation of hidden classes, which are expensive when an object is
// constantly changing shape.
map["__"] = <T><any>undefined;
delete map["__"];
return map;
}
export interface SortingResult {
sortedFileNames: string[],
circularReferences: string[]
}
export function reorderSourceFiles(program: Program): SortingResult {
sourceFiles = <any>program.getSourceFiles();
rootFileNames = <any>program.getRootFileNames();
checker = program.getTypeChecker();
visitedBlocks = [];
buildDependencyMap();
let result = sortOnDependency();
sourceFiles = [];
rootFileNames = [];
checker = null;
dependencyMap = null;
visitedBlocks = [];
return result;
}
function addDependency(file: string, dependent: string): void {
if (file == dependent) {
return;
}
let list = dependencyMap[file];
if (!list) {
list = dependencyMap[file] = [];
}
if (list.indexOf(dependent) == -1) {
list.push(dependent);
}
}
function buildDependencyMap(): void {
dependencyMap = createMap<string[]>();
for (let i = 0; i < sourceFiles.length; i++) {
let sourceFile = sourceFiles[i];
if (sourceFile.isDeclarationFile) {
continue;
}
visitFile(sourceFile);
}
}
function visitFile(sourceFile: SourceFile): void {
let statements = sourceFile.statements;
let length = statements.length;
for (let i = 0; i < length; i++) {
let statement = statements[i];
if (hasModifier(statement, ModifierFlags.Ambient)) { // has the 'declare' keyword
continue;
}
visitStatement(statements[i]);
}
}
function visitStatement(statement?: Statement): void {
if (!statement) {
return;
}
switch (statement.kind) {
case SyntaxKind.ExpressionStatement:
let expression = <ExpressionStatement>statement;
visitExpression(expression.expression);
break;
case SyntaxKind.ClassDeclaration:
checkInheriting(<ClassDeclaration>statement);
visitStaticMember(<ClassDeclaration>statement);
if (statement.transformFlags & TransformFlags.ContainsDecorators) {
visitClassDecorators(<ClassDeclaration>statement);
}
break;
case SyntaxKind.VariableStatement:
visitVariableList((<VariableStatement>statement).declarationList);
break;
case SyntaxKind.ImportEqualsDeclaration:
let importDeclaration = <ImportEqualsDeclaration>statement;
checkDependencyAtLocation(importDeclaration.moduleReference);
break;
case SyntaxKind.ModuleDeclaration:
visitModule(<ModuleDeclaration>statement);
break;
case SyntaxKind.Block:
visitBlock(<Block>statement);
break;
case SyntaxKind.IfStatement:
const ifStatement = <IfStatement>statement;
visitExpression(ifStatement.expression);
visitStatement(ifStatement.thenStatement);
visitStatement(ifStatement.elseStatement);
break;
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.WithStatement:
const doStatement = <DoStatement>statement;
visitExpression(doStatement.expression);
visitStatement(doStatement.statement);
break;
case SyntaxKind.ForStatement:
const forStatement = <ForStatement>statement;
visitExpression(forStatement.condition);
visitExpression(forStatement.incrementor);
if (forStatement.initializer) {
if (forStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
visitVariableList(<VariableDeclarationList>forStatement.initializer);
}
else {
visitExpression(<Expression>forStatement.initializer);
}
}
break;
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
const forInStatement = <ForInStatement>statement;
visitExpression(forInStatement.expression);
if (forInStatement.initializer) {
if (forInStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
visitVariableList(<VariableDeclarationList>forInStatement.initializer);
}
else {
visitExpression(<Expression>forInStatement.initializer);
}
}
break;
case SyntaxKind.ReturnStatement:
visitExpression((<ReturnStatement>statement).expression);
break;
case SyntaxKind.SwitchStatement:
const switchStatment = <SwitchStatement>statement;
visitExpression(switchStatment.expression);
switchStatment.caseBlock.clauses.forEach(element => {
if (element.kind === SyntaxKind.CaseClause) {
visitExpression((<CaseClause>element).expression);
}
(<DefaultClause>element).statements.forEach(element => {
visitStatement(element);
})
});
break;
case SyntaxKind.LabeledStatement:
visitStatement((<LabeledStatement>statement).statement);
break;
case SyntaxKind.ThrowStatement:
visitExpression((<ThrowStatement>statement).expression);
break;
case SyntaxKind.TryStatement:
const tryStatement = <TryStatement>statement;
visitBlock(tryStatement.tryBlock);
visitBlock(tryStatement.finallyBlock);
if (tryStatement.catchClause) {
visitBlock(tryStatement.catchClause.block);
}
break;
}
}
function visitModule(node: ModuleDeclaration): void {
if (node.body!.kind === SyntaxKind.ModuleDeclaration) {
visitModule(<ModuleDeclaration>node.body);
return;
}
if (node.body!.kind === SyntaxKind.ModuleBlock) {
for (let statement of (<ModuleBlock>node.body).statements) {
if (hasModifier(statement, ModifierFlags.Ambient)) { // has the 'declare' keyword
continue;
}
visitStatement(statement);
}
}
}
function checkDependencyAtLocation(node: Node): void {
let symbol = checker!.getSymbolAtLocation(node);
if (!symbol || !symbol.declarations) {
return;
}
let sourceFile = getSourceFileOfNode(symbol.declarations[0]);
if (!sourceFile || sourceFile.isDeclarationFile) {
return;
}
addDependency(getSourceFileOfNode(node).fileName, sourceFile.fileName);
}
function checkInheriting(node: ClassDeclaration): void {
if (!node.heritageClauses) {
return;
}
let heritageClause: HeritageClause | null = null;
for (const clause of node.heritageClauses) {
if (clause.token === SyntaxKind.ExtendsKeyword) {
heritageClause = clause;
break;
}
}
if (!heritageClause) {
return;
}
let superClasses = heritageClause.types;
if (!superClasses) {
return;
}
superClasses.forEach(superClass => {
checkDependencyAtLocation(superClass.expression);
});
}
function visitStaticMember(node: ClassDeclaration): void {
let members = node.members;
if (!members) {
return;
}
for (let member of members) {
if (!hasModifier(member, ModifierFlags.Static)) {
continue;
}
if (member.kind == SyntaxKind.PropertyDeclaration) {
let property = <PropertyDeclaration>member;
visitExpression(property.initializer);
}
}
}
function visitClassDecorators(node: ClassDeclaration): void {
if (node.decorators) {
visitDecorators(node.decorators);
}
let members = node.members;
if (!members) {
return;
}
for (let member of members) {
let decorators: NodeArray<Decorator> | undefined;
let functionLikeMember: FunctionLikeDeclaration | undefined;
if (member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) {
const accessors = getAllAccessorDeclarations(node.members, <AccessorDeclaration>member);
if (member !== accessors.firstAccessor) {
continue;
}
decorators = accessors.firstAccessor.decorators;
if (!decorators && accessors.secondAccessor) {
decorators = accessors.secondAccessor.decorators;
}
functionLikeMember = accessors.setAccessor;
}
else {
decorators = member.decorators;
if (member.kind === SyntaxKind.MethodDeclaration) {
functionLikeMember = <MethodDeclaration>member;
}
}
if (decorators) {
visitDecorators(decorators);
}
if (functionLikeMember) {
for (const parameter of functionLikeMember.parameters) {
if (parameter.decorators) {
visitDecorators(parameter.decorators);
}
}
}
}
}
function visitDecorators(decorators: NodeArray<Decorator>): void {
for (let decorator of decorators) {
visitCallExpression(decorator.expression);
}
}
function visitExpression(expression?: Expression): void {
if (!expression) {
return;
}
switch (expression.kind) {
case SyntaxKind.NewExpression:
case SyntaxKind.CallExpression:
visitCallArguments(<CallExpression>expression);
visitCallExpression((<CallExpression>expression).expression);
break;
case SyntaxKind.Identifier:
checkDependencyAtLocation(expression);
break;
case SyntaxKind.PropertyAccessExpression:
checkDependencyAtLocation(expression);
break;
case SyntaxKind.ElementAccessExpression:
visitExpression((<PropertyAccessExpression>expression).expression);
break;
case SyntaxKind.ObjectLiteralExpression:
visitObjectLiteralExpression(<ObjectLiteralExpression>expression);
break;
case SyntaxKind.ArrayLiteralExpression:
let arrayLiteral = <ArrayLiteralExpression>expression;
arrayLiteral.elements.forEach(visitExpression);
break;
case SyntaxKind.TemplateExpression:
let template = <TemplateExpression>expression;
template.templateSpans.forEach(span => {
visitExpression(span.expression);
});
break;
case SyntaxKind.ParenthesizedExpression:
let parenthesized = <ParenthesizedExpression>expression;
visitExpression(parenthesized.expression);
break;
case SyntaxKind.BinaryExpression:
visitBinaryExpression(<BinaryExpression>expression);
break;
case SyntaxKind.PostfixUnaryExpression:
case SyntaxKind.PrefixUnaryExpression:
visitExpression((<PrefixUnaryExpression>expression).operand);
break;
case SyntaxKind.DeleteExpression:
visitExpression((<DeleteExpression>expression).expression);
break;
case ts.SyntaxKind.TaggedTemplateExpression:
visitExpression((<TaggedTemplateExpression>expression).tag);
visitExpression((<TaggedTemplateExpression>expression).template);
break;
case ts.SyntaxKind.ConditionalExpression:
visitExpression((<ts.ConditionalExpression>expression).condition);
visitExpression((<ts.ConditionalExpression>expression).whenTrue);
visitExpression((<ts.ConditionalExpression>expression).whenFalse);
break;
case ts.SyntaxKind.SpreadElement:
visitExpression((<SpreadElement>expression).expression);
break;
case ts.SyntaxKind.VoidExpression:
visitExpression((<VoidExpression>expression).expression);
break;
case ts.SyntaxKind.YieldExpression:
visitExpression((<YieldExpression>expression).expression);
break;
case ts.SyntaxKind.AwaitExpression:
visitExpression((<AwaitExpression>expression).expression);
break;
case ts.SyntaxKind.TypeOfExpression:
visitExpression((<TypeOfExpression>expression).expression);
break;
case ts.SyntaxKind.NonNullExpression:
visitExpression((<NonNullExpression>expression).expression);
break;
case ts.SyntaxKind.TypeAssertionExpression:
visitExpression((<TypeAssertion>expression).expression);
break;
}
// FunctionExpression
// ArrowFunction
// ClassExpression
// OmittedExpression
// ExpressionWithTypeArguments
// AsExpression
}
function visitBinaryExpression(binary: BinaryExpression): void {
let left = binary.left;
let right = binary.right;
visitExpression(left);
visitExpression(right);
if (binary.operatorToken.kind === SyntaxKind.EqualsToken &&
(left.kind === SyntaxKind.Identifier || left.kind === SyntaxKind.PropertyAccessExpression) &&
(right.kind === SyntaxKind.Identifier || right.kind === SyntaxKind.PropertyAccessExpression)) {
let symbol = checker!.getSymbolAtLocation(left);
if (!symbol || !symbol.declarations) {
return;
}
for (let declaration of symbol.declarations) {
if (declaration.kind === SyntaxKind.VariableDeclaration || declaration.kind === SyntaxKind.PropertyDeclaration) {
let variable = <VariableDeclaration>declaration;
if (variable.initializer) {
continue;
}
if (!variable.delayInitializerList) {
variable.delayInitializerList = [];
}
variable.delayInitializerList.push(right);
if (variable.callerList) {
for (let callerFileName of variable.callerList) {
checkCallTarget(callerFileName, right);
}
}
}
}
}
}
function visitObjectLiteralExpression(objectLiteral: ObjectLiteralExpression): void {
objectLiteral.properties.forEach(element => {
switch (element.kind) {
case SyntaxKind.PropertyAssignment:
visitExpression((<PropertyAssignment>element).initializer);
break;
case SyntaxKind.ShorthandPropertyAssignment:
visitExpression((<ShorthandPropertyAssignment>element).objectAssignmentInitializer);
break;
case SyntaxKind.SpreadAssignment:
visitExpression((<SpreadAssignment>element).expression);
break;
}
});
}
function visitCallArguments(callExpression: CallExpression): void {
if (callExpression.arguments) {
callExpression.arguments.forEach(argument => {
visitExpression(argument);
});
}
}
function visitCallExpression(expression: Expression): void {
expression = escapeParenthesized(expression);
visitExpression(expression);
switch (expression.kind) {
case SyntaxKind.FunctionExpression:
let functionExpression = <FunctionExpression>expression;
visitBlock(functionExpression.body);
break;
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.Identifier:
let callerFileName = getSourceFileOfNode(expression).fileName;
checkCallTarget(callerFileName, expression);
break;
case SyntaxKind.CallExpression:
visitReturnedFunction((<CallExpression>expression).expression);
break;
}
}
function visitReturnedFunction(expression: Expression): Expression[] {
expression = escapeParenthesized(expression);
let returnExpressions: Expression[] = [];
if (expression.kind === SyntaxKind.CallExpression) {
let expressions = visitReturnedFunction((<CallExpression>expression).expression);
for (let returnExpression of expressions) {
let returns = visitReturnedFunction(returnExpression);
returnExpressions = returnExpressions.concat(returns);
}
return returnExpressions;
}
let functionBlocks: Block[] = [];
switch (expression.kind) {
case SyntaxKind.FunctionExpression:
functionBlocks.push((<FunctionExpression>expression).body);
break;
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.Identifier:
let callerFileName = getSourceFileOfNode(expression).fileName;
let declarations: Declaration[] = [];
getForwardDeclarations(expression, declarations, callerFileName);
for (let declaration of declarations) {
let sourceFile = getSourceFileOfNode(declaration);
if (!sourceFile || sourceFile.isDeclarationFile) {
continue;
}
if (declaration.kind === SyntaxKind.FunctionDeclaration ||
declaration.kind === SyntaxKind.MethodDeclaration) {
functionBlocks.push((<FunctionDeclaration>declaration).body!);
}
}
break;
}
for (let block of functionBlocks) {
for (let statement of block.statements) {
if (statement.kind === SyntaxKind.ReturnStatement) {
let returnExpression = (<ReturnStatement>statement).expression;
returnExpressions.push(returnExpression!);
visitCallExpression(returnExpression!);
}
}
}
return returnExpressions;
}
function escapeParenthesized(expression: Expression): Expression {
if (expression.kind === SyntaxKind.ParenthesizedExpression) {
return escapeParenthesized((<ParenthesizedExpression>expression).expression);
}
return expression;
}
function checkCallTarget(callerFileName: string, target: Node): void {
let declarations: Declaration[] = [];
getForwardDeclarations(target, declarations, callerFileName);
for (let declaration of declarations) {
let sourceFile = getSourceFileOfNode(declaration);
if (!sourceFile || sourceFile.isDeclarationFile) {
continue;
}
addDependency(callerFileName, sourceFile.fileName);
if (declaration.kind === SyntaxKind.FunctionDeclaration) {
visitBlock((<FunctionDeclaration>declaration).body);
} else if (declaration.kind === SyntaxKind.MethodDeclaration) {
visitBlock((<MethodDeclaration>declaration).body);
calledMethods.push(<MethodDeclaration>declaration);
}
else if (declaration.kind === SyntaxKind.ClassDeclaration) {
checkClassInstantiation(<ClassDeclaration>declaration);
}
}
}
function getForwardDeclarations(reference: Node, declarations: Declaration[], callerFileName: string): void {
let symbol = checker!.getSymbolAtLocation(reference);
if (!symbol || !symbol.declarations) {
return;
}
for (let declaration of symbol.declarations) {
switch (declaration.kind) {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ClassDeclaration:
if (declarations.indexOf(declaration) == -1) {
declarations.push(declaration);
}
break;
case SyntaxKind.ImportEqualsDeclaration:
getForwardDeclarations((<ImportEqualsDeclaration>declaration).moduleReference, declarations, callerFileName);
break;
case SyntaxKind.VariableDeclaration:
case SyntaxKind.PropertyDeclaration:
const variable = <VariableDeclaration>declaration;
const initializer = variable.initializer;
if (initializer) {
if (initializer.kind === SyntaxKind.Identifier || initializer.kind === SyntaxKind.PropertyAccessExpression) {
getForwardDeclarations(initializer, declarations, callerFileName);
}
}
else {
if (variable.delayInitializerList) {
for (let expression of variable.delayInitializerList) {
getForwardDeclarations(expression, declarations, callerFileName);
}
}
if (variable.callerList) {
if (variable.callerList.indexOf(callerFileName) == -1) {
variable.callerList.push(callerFileName);
}
}
else {
variable.callerList = [callerFileName];
}
}
break;
}
}
}
function checkClassInstantiation(node: ClassDeclaration): string[] {
let methodNames: string[] = [];
let superClass = getClassExtendsHeritageElement(node);
if (superClass) {
let type = checker!.getTypeAtLocation(superClass);
if (type && type.symbol) {
let declaration = <ClassDeclaration>ts.getDeclarationOfKind(type.symbol, SyntaxKind.ClassDeclaration);
if (declaration) {
methodNames = checkClassInstantiation(declaration);
}
}
}
let members = node.members;
if (!members) {
return [];
}
let index = calledMethods.length;
for (let member of members) {
if (hasModifier(member, ModifierFlags.Static)) {
continue;
}
if (member.kind === SyntaxKind.MethodDeclaration) { // called by super class.
let methodName = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(member.name!));
if (methodNames.indexOf(methodName) != -1) {
visitBlock((<MethodDeclaration>member).body);
}
}
if (member.kind === SyntaxKind.PropertyDeclaration) {
let property = <PropertyDeclaration>member;
visitExpression(property.initializer);
}
else if (member.kind === SyntaxKind.Constructor) {
let constructor = <ConstructorDeclaration>member;
visitBlock(constructor.body);
}
}
for (let i = index; i < calledMethods.length; i++) {
let method = calledMethods[i];
for (let memeber of members) {
if (memeber === method) {
let methodName = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(method.name));
methodNames.push(methodName);
}
}
}
if (index == 0) {
calledMethods.length = 0;
}
return methodNames;
}
function visitBlock(block?: Block): void {
if (!block || visitedBlocks.indexOf(block) != -1) {
return;
}
visitedBlocks.push(block);
for (let statement of block.statements) {
visitStatement(statement);
}
visitedBlocks.pop();
}
function visitVariableList(variables?: VariableDeclarationList) {
if (!variables) {
return;
}
variables.declarations.forEach(declaration => {
visitExpression(declaration.initializer);
});
}
function sortOnDependency(): SortingResult {
let result: SortingResult = <any>{};
result.sortedFileNames = [];
result.circularReferences = [];
pathWeightMap = createMap<number>();
let dtsFiles: SourceFile[] = [];
let tsFiles: SourceFile[] = [];
for (let sourceFile of sourceFiles) {
let path = sourceFile.fileName;
if (sourceFile.isDeclarationFile) {
pathWeightMap[path] = 10000;
dtsFiles.push(sourceFile);
continue;
}
let references = updatePathWeight(path, 0, [path]);
if (references.length > 0) {
result.circularReferences = references;
break;
}
tsFiles.push(sourceFile);
}
if (result.circularReferences.length === 0) {
tsFiles.sort(function (a: SourceFile, b: SourceFile): number {
return pathWeightMap[b.fileName] - pathWeightMap[a.fileName];
});
sourceFiles.length = 0;
rootFileNames.length = 0;
dtsFiles.concat(tsFiles).forEach(sourceFile => {
sourceFiles.push(sourceFile);
rootFileNames.push(sourceFile.fileName);
result.sortedFileNames.push(sourceFile.fileName);
});
}
pathWeightMap = null;
return result;
}
function updatePathWeight(path: string, weight: number, references: string[]): string[] {
if (pathWeightMap[path] === undefined) {
pathWeightMap[path] = weight;
}
else {
if (pathWeightMap[path] < weight) {
pathWeightMap[path] = weight;
}
else {
return [];
}
}
let list = dependencyMap[path];
if (!list) {
return [];
}
for (let parentPath of list) {
if (references.indexOf(parentPath) != -1) {
references.push(parentPath);
return references;
}
let result = updatePathWeight(parentPath, weight + 1, references.concat(parentPath));
if (result.length > 0) {
return result;
}
}
return [];
}
function getSourceFileOfNode(node: Node): SourceFile {
while (node && node.kind !== SyntaxKind.SourceFile) {
node = node.parent;
}
return <SourceFile>node;
}
} | the_stack |
import * as assert from 'assert';
import rewire = require('rewire');
import * as sinon from 'sinon';
import uuid = require('uuid');
import * as vscode from 'vscode';
import { RequiredApps } from '../src/Constants';
import * as helpers from '../src/helpers';
import * as commands from '../src/helpers/command';
import { TestConstants } from './TestConstants';
const nodeValidVersion: commands.ICommandResult = {
cmdOutput: 'v11.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
const npmValidVersion: commands.ICommandResult = {
cmdOutput: '7.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
const gitValidVersion: commands.ICommandResult = {
cmdOutput: ' 3.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
const truffleValidVersion: commands.ICommandResult = {
cmdOutput: 'truffle@5.5.0',
cmdOutputIncludingStderr: '',
code: 0,
};
const ganacheValidVersion: commands.ICommandResult = {
cmdOutput: 'ganache-cli@6.5.0',
cmdOutputIncludingStderr: '',
code: 0,
};
describe('Required helper', () => {
describe('Unit test', () => {
let tryExecuteCommandMock: any;
let getWorkspaceRootMock: any;
let requiredRewire: any;
let showErrorMessageMock: any;
let executeVSCommandMock: any;
let executeCommandMock: any;
beforeEach(() => {
requiredRewire = rewire('../src/helpers/required');
tryExecuteCommandMock = sinon.stub(commands, 'tryExecuteCommand');
getWorkspaceRootMock = sinon.stub(helpers, 'getWorkspaceRoot');
showErrorMessageMock = sinon.stub(vscode.window, 'showErrorMessage');
executeVSCommandMock = sinon.stub(vscode.commands, 'executeCommand');
executeCommandMock = sinon.stub(commands, 'executeCommand');
});
afterEach(() => {
sinon.restore();
});
describe('getNodeVersion', () => {
it('should return empty string when tryExecuteCommand throw an error', async () => {
// Arrange
tryExecuteCommandMock.throws(TestConstants.testError);
// Act
const result = await requiredRewire.required.getNodeVersion();
// Assert
assert.strictEqual(result, '', 'returned result should be empty');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
});
it('should return empty string when tryExecuteCommand return not zero code', async () => {
// Arrange
const executionResult: commands.ICommandResult = {
cmdOutput: 'v11.0.0',
cmdOutputIncludingStderr: '',
code: 1,
};
tryExecuteCommandMock.returns(executionResult);
// Act
const result = await requiredRewire.required.getNodeVersion();
// Assert
assert.strictEqual(result, '', 'returned result should be empty');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
});
it('should return version', async () => {
// Arrange
const executionResult: commands.ICommandResult = {
cmdOutput: 'v11.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.returns(executionResult);
// Act
const result = await requiredRewire.required.getNodeVersion();
// Assert
assert.strictEqual(result, '11.0.0', 'returned result should be defined');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
});
});
describe('getNpmVersion', () => {
it('should return empty string when tryExecuteCommand throw an error', async () => {
// Arrange
tryExecuteCommandMock.throws(TestConstants.testError);
// Act
const result = await requiredRewire.required.getNpmVersion();
// Assert
assert.strictEqual(result, '', 'returned result should be empty');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
});
it('should return empty string when tryExecuteCommand return not zero code', async () => {
// Arrange
const executionResult: commands.ICommandResult = {
cmdOutput: 'v11.0.0',
cmdOutputIncludingStderr: '',
code: 1,
};
tryExecuteCommandMock.returns(executionResult);
// Act
const result = await requiredRewire.required.getNpmVersion();
// Assert
assert.strictEqual(result, '', 'returned result should be empty');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
});
it('should return version', async () => {
// Arrange
const executionResult: commands.ICommandResult = {
cmdOutput: 'v11.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.returns(executionResult);
// Act
const result = await requiredRewire.required.getNpmVersion();
// Assert
assert.strictEqual(result, '11.0.0', 'returned result should be defined');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
});
});
describe('getGitVersion', () => {
it('should return empty string when tryExecuteCommand throw an error', async () => {
// Arrange
tryExecuteCommandMock.throws(TestConstants.testError);
// Act
const result = await requiredRewire.required.getGitVersion();
// Assert
assert.strictEqual(result, '', 'returned result should be empty');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
});
it('should return empty string when tryExecuteCommand returns not zero code', async () => {
// Arrange
const executionResult: commands.ICommandResult = {
cmdOutput: ' 11.0.0',
cmdOutputIncludingStderr: '',
code: 1,
};
tryExecuteCommandMock.returns(executionResult);
// Act
const result = await requiredRewire.required.getGitVersion();
// Assert
assert.strictEqual(result, '', 'returned result should be empty');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
});
it('should return version', async () => {
// Arrange
const executionResult: commands.ICommandResult = {
cmdOutput: ' 11.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.returns(executionResult);
// Act
const result = await requiredRewire.required.getGitVersion();
// Assert
assert.strictEqual(result, '11.0.0', 'returned result should be defined');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
});
});
describe('getTruffleVersion', () => {
it('should return local version', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
const executionResult: commands.ICommandResult = {
cmdOutput: 'truffle@11.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.returns(executionResult);
// Act
const result = await requiredRewire.required.getTruffleVersion();
// Assert
assert.strictEqual(result, '11.0.0', 'returned result should be defined');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
assert.strictEqual(getWorkspaceRootMock.calledOnce, true, 'getWorkspaceRoot should be called once');
});
it('should return global version', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
const executionResult1: commands.ICommandResult = {
cmdOutput: '',
cmdOutputIncludingStderr: '',
code: 0,
};
const executionResult2: commands.ICommandResult = {
cmdOutput: 'Truffle v11.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.onCall(0).returns(executionResult1);
tryExecuteCommandMock.onCall(1).returns(executionResult2);
// Act
const result = await requiredRewire.required.getTruffleVersion();
// Assert
assert.strictEqual(result, '11.0.0', 'returned result should be defined');
assert.strictEqual(tryExecuteCommandMock.callCount, 2, 'tryExecuteCommand should be called twice');
assert.strictEqual(getWorkspaceRootMock.calledOnce, true, 'getWorkspaceRoot should be called once');
});
it('should throw an error when tryExecuteCommand throws an error on first call', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
tryExecuteCommandMock.onCall(0).throws(TestConstants.testError);
// Act and assert
await assert.rejects(requiredRewire.required.getTruffleVersion(), Error, TestConstants.testError);
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
assert.strictEqual(getWorkspaceRootMock.calledOnce, true, 'getWorkspaceRoot should be called once');
});
it('should return empty string when tryExecuteCommand throws an error on second call', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
const executionResult1: commands.ICommandResult = {
cmdOutput: '',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.onCall(0).returns(executionResult1);
tryExecuteCommandMock.onCall(1).throws(TestConstants.testError);
// Act
const result = await requiredRewire.required.getTruffleVersion();
// Assert
assert.strictEqual(result, '', 'returned result should be empty');
assert.strictEqual(tryExecuteCommandMock.callCount, 2, 'tryExecuteCommand should be called twice');
assert.strictEqual(getWorkspaceRootMock.calledOnce, true, 'getWorkspaceRoot should be called once');
});
});
describe('getGanacheVersion', () => {
it('should return local version', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
const executionResult: commands.ICommandResult = {
cmdOutput: 'ganache-cli@11.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.returns(executionResult);
// Act
const result = await requiredRewire.required.getGanacheVersion();
// Assert
assert.strictEqual(result, '11.0.0', 'returned result should be defined');
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
assert.strictEqual(getWorkspaceRootMock.calledOnce, true, 'getWorkspaceRoot should be called once');
});
it('should return global version', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
const executionResult1: commands.ICommandResult = {
cmdOutput: '',
cmdOutputIncludingStderr: '',
code: 0,
};
const executionResult2: commands.ICommandResult = {
cmdOutput: 'v11.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.onCall(0).returns(executionResult1);
tryExecuteCommandMock.onCall(1).returns(executionResult2);
// Act
const result = await requiredRewire.required.getGanacheVersion();
// Assert
assert.strictEqual(result, '11.0.0', 'returned result should be defined');
assert.strictEqual(tryExecuteCommandMock.callCount, 2, 'tryExecuteCommand should be called twice');
assert.strictEqual(getWorkspaceRootMock.calledOnce, true, 'getWorkspaceRoot should be called once');
});
it('should throw an error when tryExecuteCommand throw an error on first call', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
tryExecuteCommandMock.onCall(0).throws(TestConstants.testError);
// Act and assert
await assert.rejects(requiredRewire.required.getGanacheVersion(), Error, TestConstants.testError);
assert.strictEqual(tryExecuteCommandMock.calledOnce, true, 'tryExecuteCommand should be called once');
assert.strictEqual(getWorkspaceRootMock.calledOnce, true, 'getWorkspaceRoot should be called once');
});
it('should return empty string when tryExecuteCommand throw an error on second call', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
const executionResult1: commands.ICommandResult = {
cmdOutput: '',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.onCall(0).returns(executionResult1);
tryExecuteCommandMock.onCall(1).throws(TestConstants.testError);
// Act
const result = await requiredRewire.required.getGanacheVersion();
// Assert
assert.strictEqual(result, '', 'returned result should be empty');
assert.strictEqual(tryExecuteCommandMock.callCount, 2, 'tryExecuteCommand should be called twice');
assert.strictEqual(getWorkspaceRootMock.calledOnce, true, 'getWorkspaceRoot should be called once');
});
});
describe('isValid', () => {
const isValidCases = [
{
maxVersion: undefined,
minVersion: 'v6.0.0',
result: true,
version: 'v11.0.0',
},
{
maxVersion: 'v12.0.0',
minVersion: 'v6.0.0',
result: true,
version: 'v11.0.0',
},
{
maxVersion: 'v12.0.0',
minVersion: 'v6.0.0',
result: false,
version: 'v5.0.0',
},
{
maxVersion: 'v12.0.0',
minVersion: 'v6.0.0',
result: false,
version: 'v13.0.0',
},
];
isValidCases.forEach((element, index) => {
it(`should return correct result ${index + 1}`, () => {
// Act
const result = requiredRewire.required.isValid(element.version, element.minVersion, element.maxVersion);
// Assert
assert.strictEqual(result, element.result, 'returned result should be defined');
});
});
});
describe('getAllVersions', () => {
it('should return object with applications version', async () => {
// Arrange
tryExecuteCommandMock.onCall(0).returns(nodeValidVersion);
tryExecuteCommandMock.onCall(1).returns(npmValidVersion);
tryExecuteCommandMock.onCall(2).returns(gitValidVersion);
tryExecuteCommandMock.onCall(3).returns(truffleValidVersion);
tryExecuteCommandMock.onCall(4).returns(ganacheValidVersion);
// Act
const result = await requiredRewire.required.getAllVersions();
// Assert
assert.strictEqual(result.length, 5, 'returned result should have length 5');
assert.strictEqual(tryExecuteCommandMock.callCount, 5, 'tryExecuteCommand should be called 5 times');
});
});
describe('checkAppsSilent', () => {
it('should return true when all versions are valid', async () => {
// Arrange
tryExecuteCommandMock.onCall(0).returns(nodeValidVersion);
tryExecuteCommandMock.onCall(1).returns(npmValidVersion);
tryExecuteCommandMock.onCall(2).returns(gitValidVersion);
tryExecuteCommandMock.onCall(3).returns(truffleValidVersion);
tryExecuteCommandMock.onCall(4).returns(ganacheValidVersion);
// Act
const result = await requiredRewire.required.checkAppsSilent(
RequiredApps.node,
RequiredApps.npm,
RequiredApps.git,
);
// Assert
assert.strictEqual(result, true, 'returned result should be true');
assert.strictEqual(tryExecuteCommandMock.callCount, 3, 'tryExecuteCommand should be called 3 times');
});
it('should return false when there are invalid versions', async () => {
// Arrange
const executionResultGit: commands.ICommandResult = {
cmdOutput: ' 1.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.onCall(0).returns(nodeValidVersion);
tryExecuteCommandMock.onCall(1).returns(npmValidVersion);
tryExecuteCommandMock.onCall(2).returns(executionResultGit);
tryExecuteCommandMock.onCall(3).returns(truffleValidVersion);
tryExecuteCommandMock.onCall(4).returns(ganacheValidVersion);
// Act
const result = await requiredRewire.required.checkAppsSilent(
RequiredApps.node,
RequiredApps.npm,
RequiredApps.git,
);
// Assert
assert.strictEqual(result, false, 'returned result should be false');
assert.strictEqual(tryExecuteCommandMock.callCount, 3, 'tryExecuteCommand should be called 3 times');
});
});
describe('checkApps', () => {
it('should return true when all versions are valid', async () => {
// Arrange
tryExecuteCommandMock.onCall(0).returns(nodeValidVersion);
tryExecuteCommandMock.onCall(1).returns(npmValidVersion);
tryExecuteCommandMock.onCall(2).returns(gitValidVersion);
tryExecuteCommandMock.onCall(3).returns(truffleValidVersion);
tryExecuteCommandMock.onCall(4).returns(ganacheValidVersion);
// Act
const result = await requiredRewire.required.checkApps(
RequiredApps.node,
RequiredApps.npm,
RequiredApps.git,
);
// Assert
assert.strictEqual(result, true, 'returned result should be true');
assert.strictEqual(tryExecuteCommandMock.callCount, 3, 'tryExecuteCommand should be called 3 times');
assert.strictEqual(showErrorMessageMock.called, false, 'showErrorMessage shouldn\'t be called');
assert.strictEqual(executeVSCommandMock.called, false, 'executeVSCommand shouldn\'t be called');
});
it('should return false when there are invalid versions', async () => {
// Arrange
const executionResultGit: commands.ICommandResult = {
cmdOutput: ' 1.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.onCall(0).returns(nodeValidVersion);
tryExecuteCommandMock.onCall(1).returns(npmValidVersion);
tryExecuteCommandMock.onCall(2).returns(executionResultGit);
tryExecuteCommandMock.onCall(3).returns(truffleValidVersion);
tryExecuteCommandMock.onCall(4).returns(ganacheValidVersion);
// Act
const result = await requiredRewire.required.checkApps(
RequiredApps.node,
RequiredApps.npm,
RequiredApps.git,
);
// Assert
assert.strictEqual(result, false, 'returned result should be false');
assert.strictEqual(tryExecuteCommandMock.callCount, 3, 'tryExecuteCommand should be called 3 times');
assert.strictEqual(showErrorMessageMock.called, true, 'showErrorMessage should be called');
assert.strictEqual(executeVSCommandMock.called, true, 'executeVSCommand should be called');
});
});
describe('checkRequiredApps', () => {
it('should return true when all versions are valid', async () => {
// Arrange
tryExecuteCommandMock.onCall(0).returns(nodeValidVersion);
tryExecuteCommandMock.onCall(1).returns(npmValidVersion);
tryExecuteCommandMock.onCall(2).returns(gitValidVersion);
tryExecuteCommandMock.onCall(3).returns(truffleValidVersion);
tryExecuteCommandMock.onCall(4).returns(ganacheValidVersion);
// Act
const result = await requiredRewire.required.checkRequiredApps();
// Assert
assert.strictEqual(result, true, 'returned result should be true');
assert.strictEqual(tryExecuteCommandMock.callCount, 3, 'tryExecuteCommand should be called 3 times');
assert.strictEqual(showErrorMessageMock.called, false, 'showErrorMessage shouldn\'t be called');
assert.strictEqual(executeVSCommandMock.called, false, 'executeVSCommand shouldn\'t be called');
});
it('should return false when there are invalid versions', async () => {
// Arrange
const executionResultGit: commands.ICommandResult = {
cmdOutput: ' 1.0.0',
cmdOutputIncludingStderr: '',
code: 0,
};
tryExecuteCommandMock.onCall(0).returns(nodeValidVersion);
tryExecuteCommandMock.onCall(1).returns(npmValidVersion);
tryExecuteCommandMock.onCall(2).returns(executionResultGit);
tryExecuteCommandMock.onCall(3).returns(truffleValidVersion);
tryExecuteCommandMock.onCall(4).returns(ganacheValidVersion);
// Act
const result = await requiredRewire.required.checkRequiredApps();
// Assert
assert.strictEqual(result, false, 'returned result should be false');
assert.strictEqual(tryExecuteCommandMock.callCount, 3, 'tryExecuteCommand should be called 3 times');
assert.strictEqual(showErrorMessageMock.called, true, 'showErrorMessageMock should be called');
assert.strictEqual(executeVSCommandMock.called, true, 'executeVSCommand should be called');
});
});
describe('installNpm', () => {
it('should install npm', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
executeCommandMock.returns(uuid.v4());
tryExecuteCommandMock.returns(npmValidVersion);
// Act
await requiredRewire.required.installNpm();
// Assert
assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called');
assert.strictEqual(executeCommandMock.calledOnce, true, 'executeCommand should be called once');
assert.strictEqual(tryExecuteCommandMock.called, true, 'tryExecuteCommand should be called');
});
it('should catch errors', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
executeCommandMock.throws(TestConstants.testError);
tryExecuteCommandMock.returns(npmValidVersion);
// Act
await requiredRewire.required.installNpm();
// Assert
assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called');
assert.strictEqual(executeCommandMock.calledOnce, true, 'executeCommand should be called once');
assert.strictEqual(tryExecuteCommandMock.called, true, 'tryExecuteCommand should be called');
});
});
describe('installTruffle', () => {
it('should install truffle', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
executeCommandMock.returns(uuid.v4());
tryExecuteCommandMock.returns(truffleValidVersion);
// Act
await requiredRewire.required.installTruffle();
// Assert
assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called');
assert.strictEqual(executeCommandMock.calledOnce, true, 'executeCommand should be called once');
assert.strictEqual(tryExecuteCommandMock.called, true, 'tryExecuteCommand should be called');
});
it('should catch errors', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
executeCommandMock.throws(TestConstants.testError);
tryExecuteCommandMock.returns(truffleValidVersion);
// Act
await requiredRewire.required.installTruffle();
// Assert
assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called');
assert.strictEqual(executeCommandMock.calledOnce, true, 'executeCommand should be called once');
assert.strictEqual(tryExecuteCommandMock.called, true, 'tryExecuteCommand should be called');
});
});
describe('installGanache', () => {
it('should install ganache-cli', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
executeCommandMock.returns(uuid.v4());
tryExecuteCommandMock.returns(ganacheValidVersion);
// Act
await requiredRewire.required.installGanache();
// Assert
assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called');
assert.strictEqual(executeCommandMock.calledOnce, true, 'executeCommand should be called once');
assert.strictEqual(tryExecuteCommandMock.called, true, 'tryExecuteCommand should be called');
});
it('should catch errors', async () => {
// Arrange
getWorkspaceRootMock.returns(uuid.v4());
executeCommandMock.throws(TestConstants.testError);
tryExecuteCommandMock.returns(ganacheValidVersion);
// Act
await requiredRewire.required.installGanache();
// Assert
assert.strictEqual(getWorkspaceRootMock.called, true, 'getWorkspaceRoot should be called');
assert.strictEqual(executeCommandMock.calledOnce, true, 'executeCommand should be called once');
assert.strictEqual(tryExecuteCommandMock.called, true, 'tryExecuteCommand should be called');
});
});
});
}); | the_stack |
import type Ajv from ".."
import type {KeywordCxt, SchemaObject} from ".."
import _Ajv from "./ajv"
import {_} from "../dist/compile/codegen/code"
import assert = require("assert")
import chai from "./chai"
const should = chai.should()
describe("Ajv", () => {
let ajv: Ajv
beforeEach(() => {
ajv = new _Ajv({keywords: ["foo"], allowUnionTypes: true})
})
it("should create instance", () => {
ajv.should.be.instanceof(_Ajv)
})
describe("compile method", () => {
it("should compile schema and return validating function", () => {
const validate = ajv.compile({type: "integer"})
validate.should.be.a("function")
validate(1).should.equal(true)
validate(1.1).should.equal(false)
validate("1").should.equal(false)
})
it("should cache compiled functions for the same schema", () => {
const schema = {
$id: "//e.com/int.json",
type: "integer",
minimum: 1,
}
const v1 = ajv.compile(schema)
const v2 = ajv.compile(schema)
v1.should.equal(v2)
})
it("should throw if different schema has the same id", () => {
ajv.compile({$id: "//e.com/int.json", type: "integer"})
should.throw(() => {
ajv.compile({$id: "//e.com/int.json", type: "integer", minimum: 1})
}, /already exists/)
})
it("should throw if invalid schema is compiled", () => {
should.throw(() => {
ajv.compile({type: null})
}, /must be equal to one of the allowed values/)
})
it("should throw if compiled schema has an invalid JavaScript code", () => {
const _ajv = new _Ajv({logger: false})
_ajv.addKeyword({keyword: "even", code: badEvenCode})
let schema = {even: true}
const validate: any = _ajv.compile(schema)
validate(2).should.equal(true)
validate(3).should.equal(false)
schema = {even: false}
should.throw(() => {
_ajv.compile(schema)
}, /Unexpected token/)
function badEvenCode(cxt: KeywordCxt) {
const op = cxt.schema ? _`===` : _`!===` // invalid on purpose
cxt.pass(_`${cxt.data} % 2 ${op} 0`)
}
})
})
describe("validate method", () => {
it("should compile schema and validate data against it", () => {
ajv.validate({type: "integer"}, 1).should.equal(true)
ajv.validate({type: "integer"}, "1").should.equal(false)
ajv.validate({type: "string"}, "a").should.equal(true)
ajv.validate({type: "string"}, 1).should.equal(false)
})
it("should validate against previously compiled schema by id (also see addSchema)", () => {
ajv.validate({$id: "//e.com/int.json", type: "integer"}, 1).should.equal(true)
ajv.validate("//e.com/int.json", 1).should.equal(true)
ajv.validate("//e.com/int.json", "1").should.equal(false)
ajv.compile({$id: "//e.com/str.json", type: "string"}).should.be.a("function")
ajv.validate("//e.com/str.json", "a").should.equal(true)
ajv.validate("//e.com/str.json", 1).should.equal(false)
})
it("should throw exception if no schema with ref", () => {
ajv.validate({$id: "integer", type: "integer"}, 1).should.equal(true)
ajv.validate("integer", 1).should.equal(true)
should.throw(() => {
ajv.validate("string", "foo")
}, /no schema with key or ref/)
})
it("should validate schema fragment by ref", () => {
ajv.addSchema({
$id: "http://e.com/types.json",
definitions: {
int: {type: "integer"},
str: {type: "string"},
},
})
ajv.validate("http://e.com/types.json#/definitions/int", 1).should.equal(true)
ajv.validate("http://e.com/types.json#/definitions/int", "1").should.equal(false)
})
it("should return schema fragment by id", () => {
ajv.addSchema({
$id: "http://e.com/types.json",
definitions: {
int: {$id: "#int", type: "integer"},
str: {$id: "#str", type: "string"},
},
})
ajv.validate("http://e.com/types.json#int", 1).should.equal(true)
ajv.validate("http://e.com/types.json#int", "1").should.equal(false)
})
})
describe("addSchema method", () => {
it("should add and compile schema with key", () => {
ajv.addSchema({type: "integer"}, "int")
const validate = ajv.getSchema("int")
assert(typeof validate == "function")
validate(1).should.equal(true)
validate(1.1).should.equal(false)
validate("1").should.equal(false)
ajv.validate("int", 1).should.equal(true)
ajv.validate("int", "1").should.equal(false)
})
it("should add and compile schema without key", () => {
ajv.addSchema({type: "integer"})
ajv.validate("", 1).should.equal(true)
ajv.validate("", "1").should.equal(false)
})
it("should add and compile schema with id", () => {
ajv.addSchema({$id: "//e.com/int.json", type: "integer"})
ajv.validate("//e.com/int.json", 1).should.equal(true)
ajv.validate("//e.com/int.json", "1").should.equal(false)
})
it("should normalize schema keys and ids", () => {
ajv.addSchema({$id: "//e.com/int.json#", type: "integer"}, "int#")
ajv.validate("int", 1).should.equal(true)
ajv.validate("int", "1").should.equal(false)
ajv.validate("//e.com/int.json", 1).should.equal(true)
ajv.validate("//e.com/int.json", "1").should.equal(false)
ajv.validate("int#/", 1).should.equal(true)
ajv.validate("int#/", "1").should.equal(false)
ajv.validate("//e.com/int.json#/", 1).should.equal(true)
ajv.validate("//e.com/int.json#/", "1").should.equal(false)
})
it("should add and compile array of schemas with ids", () => {
ajv.addSchema([
{$id: "//e.com/int.json", type: "integer"},
{$id: "//e.com/str.json", type: "string"},
])
const validate0 = ajv.getSchema("//e.com/int.json")
const validate1 = ajv.getSchema("//e.com/str.json")
assert(typeof validate0 == "function")
assert(typeof validate1 == "function")
validate0(1).should.equal(true)
validate0("1").should.equal(false)
validate1("a").should.equal(true)
validate1(1).should.equal(false)
ajv.validate("//e.com/int.json", 1).should.equal(true)
ajv.validate("//e.com/int.json", "1").should.equal(false)
ajv.validate("//e.com/str.json", "a").should.equal(true)
ajv.validate("//e.com/str.json", 1).should.equal(false)
})
it("should throw on duplicate key", () => {
ajv.addSchema({type: "integer"}, "int")
should.throw(() => {
ajv.addSchema({type: "integer", minimum: 1}, "int")
}, /already exists/)
})
it("should throw on duplicate normalized key", () => {
ajv.addSchema({type: "number"}, "num")
should.throw(() => {
ajv.addSchema({type: "integer"}, "num#")
}, /already exists/)
should.throw(() => {
ajv.addSchema({type: "integer"}, "num#/")
}, /already exists/)
})
it("should allow only one schema without key and id", () => {
ajv.addSchema({type: "number"})
should.throw(() => {
ajv.addSchema({type: "integer"})
}, /already exists/)
should.throw(() => {
ajv.addSchema({type: "integer"}, "")
}, /already exists/)
should.throw(() => {
ajv.addSchema({type: "integer"}, "#")
}, /already exists/)
})
it("should throw if schema is not an object", () => {
should.throw(() => {
// @ts-expect-error
ajv.addSchema("foo")
}, /schema must be object or boolean/)
})
it("should throw if schema id is not a string", () => {
try {
// @ts-expect-error
ajv.addSchema({$id: 1, type: "integer"})
throw new Error("should have throw exception")
} catch (e) {
;(e as Error).message.should.equal("schema $id must be string")
}
})
it("should return instance of itself", () => {
const res = ajv.addSchema({type: "integer"}, "int")
res.should.equal(ajv)
})
})
describe("getSchema method", () => {
it("should return compiled schema by key", () => {
ajv.addSchema({type: "integer"}, "int")
const validate = ajv.getSchema("int")
assert(typeof validate == "function")
validate(1).should.equal(true)
validate("1").should.equal(false)
})
it("should return compiled schema by id or ref", () => {
ajv.addSchema({$id: "//e.com/int.json", type: "integer"})
const validate = ajv.getSchema("//e.com/int.json")
assert(typeof validate == "function")
validate(1).should.equal(true)
validate("1").should.equal(false)
})
it("should return compiled schema without key or with empty key", () => {
ajv.addSchema({type: "integer"})
const validate = ajv.getSchema("")
assert(typeof validate == "function")
validate(1).should.equal(true)
validate("1").should.equal(false)
})
it("should return schema fragment by ref", () => {
ajv.addSchema({
$id: "http://e.com/types.json",
definitions: {
int: {type: "integer"},
str: {type: "string"},
},
})
const vInt = ajv.getSchema("http://e.com/types.json#/definitions/int")
assert(typeof vInt == "function")
vInt(1).should.equal(true)
vInt("1").should.equal(false)
})
it("should return schema fragment by ref with protocol-relative URIs", () => {
ajv.addSchema({
$id: "//e.com/types.json",
definitions: {
int: {type: "integer"},
str: {type: "string"},
},
})
const vInt = ajv.getSchema("//e.com/types.json#/definitions/int")
assert(typeof vInt == "function")
vInt(1).should.equal(true)
vInt("1").should.equal(false)
})
it("should return schema fragment by id", () => {
ajv.addSchema({
$id: "http://e.com/types.json",
definitions: {
int: {$id: "#int", type: "integer"},
str: {$id: "#str", type: "string"},
},
})
const vInt = ajv.getSchema("http://e.com/types.json#int")
assert(typeof vInt == "function")
vInt(1).should.equal(true)
vInt("1").should.equal(false)
})
})
describe("removeSchema method", () => {
it("should remove schema by key", () => {
const schema = {type: "integer"}
ajv.addSchema(schema, "int")
const v = ajv.getSchema("int")
assert(typeof v == "function")
v.should.be.a("function")
//@ts-expect-error
ajv._cache.get(schema).validate.should.equal(v)
ajv.removeSchema("int")
should.not.exist(ajv.getSchema("int"))
//@ts-expect-error
should.not.exist(ajv._cache.get(schema))
})
it("should remove schema by id", () => {
const schema = {$id: "//e.com/int.json", type: "integer"}
ajv.addSchema(schema)
const v = ajv.getSchema("//e.com/int.json")
assert(typeof v == "function")
v.should.be.a("function")
//@ts-expect-error
ajv._cache.get(schema).validate.should.equal(v)
ajv.removeSchema("//e.com/int.json")
should.not.exist(ajv.getSchema("//e.com/int.json"))
//@ts-expect-error
should.not.exist(ajv._cache.get(schema))
})
it("should remove schema by schema object", () => {
const schema = {type: "integer"}
ajv.addSchema(schema)
//@ts-expect-error
ajv._cache.get(schema).should.be.an("object")
ajv.removeSchema(schema)
//@ts-expect-error
should.not.exist(ajv._cache.get(schema))
})
it("should remove schema with id by schema object", () => {
const schema = {$id: "//e.com/int.json", type: "integer"}
ajv.addSchema(schema)
//@ts-expect-error
ajv._cache.get(schema).should.be.an("object")
ajv.removeSchema(schema)
should.not.exist(ajv.getSchema("//e.com/int.json"))
//@ts-expect-error
should.not.exist(ajv._cache.get(schema))
})
it("should not throw if there is no schema with passed id", () => {
should.not.exist(ajv.getSchema("//e.com/int.json"))
should.not.throw(() => {
ajv.removeSchema("//e.com/int.json")
})
})
it("should remove all schemas but meta-schemas if called without an arguments", () => {
const schema1 = {$id: "//e.com/int.json", type: "integer"}
ajv.addSchema(schema1)
//@ts-expect-error
ajv._cache.get(schema1).should.be.an("object")
const schema2 = {type: "integer"}
ajv.addSchema(schema2)
//@ts-expect-error
ajv._cache.get(schema2).should.be.an("object")
ajv.removeSchema()
//@ts-expect-error
should.not.exist(ajv._cache.get(schema1))
//@ts-expect-error
should.not.exist(ajv._cache.get(schema2))
})
it("should remove all schemas but meta-schemas with key/id matching pattern", () => {
const schema1 = {$id: "//e.com/int.json", type: "integer"}
ajv.addSchema(schema1)
//@ts-expect-error
ajv._cache.get(schema1).should.be.an("object")
const schema2 = {$id: "str.json", type: "string"}
ajv.addSchema(schema2, "//e.com/str.json")
//@ts-expect-error
ajv._cache.get(schema2).should.be.an("object")
const schema3 = {type: "integer"}
ajv.addSchema(schema3)
//@ts-expect-error
ajv._cache.get(schema3).should.be.an("object")
ajv.removeSchema(/e\.com/)
//@ts-expect-error
should.not.exist(ajv._cache.get(schema1))
//@ts-expect-error
should.not.exist(ajv._cache.get(schema2))
//@ts-expect-error
ajv._cache.get(schema3).should.be.an("object")
})
it("should return instance of itself", () => {
const res = ajv.addSchema({type: "integer"}, "int").removeSchema("int")
res.should.equal(ajv)
})
})
describe("addFormat method", () => {
it("should add format as regular expression", () => {
ajv.addFormat("identifier", /^[a-z_$][a-z0-9_$]*$/i)
testFormat()
})
it("should add format as string", () => {
ajv.addFormat("identifier", "^[A-Za-z_$][A-Za-z0-9_$]*$")
testFormat()
})
it("should add format as function", () => {
ajv.addFormat("identifier", (str) => /^[a-z_$][a-z0-9_$]*$/i.test(str))
testFormat()
})
it("should add format as object", () => {
ajv.addFormat("identifier", {
validate: (str: string) => /^[a-z_$][a-z0-9_$]*$/i.test(str),
})
testFormat()
})
it("should return instance of itself", () => {
const res = ajv.addFormat("identifier", /^[a-z_$][a-z0-9_$]*$/i)
res.should.equal(ajv)
})
function testFormat() {
const validate = ajv.compile({
type: ["number", "string"],
format: "identifier",
})
validate("Abc1").should.equal(true)
validate("123").should.equal(false)
validate(123).should.equal(true)
}
describe("formats for number", () => {
it("should validate only numbers", () => {
ajv.addFormat("positive", {
type: "number",
validate: function (x: number) {
return x > 0
},
})
const validate = ajv.compile({
type: ["string", "number"],
format: "positive",
})
validate(-2).should.equal(false)
validate(0).should.equal(false)
validate(2).should.equal(true)
validate("abc").should.equal(true)
})
it("should validate numbers with format via $data", () => {
ajv = new _Ajv({$data: true, allowUnionTypes: true})
ajv.addFormat("positive", {
type: "number",
validate: function (x: number) {
return x > 0
},
})
const validate = ajv.compile({
type: "object",
properties: {
data: {
type: ["number", "string"],
format: {$data: "1/frmt"},
},
frmt: {type: "string"},
},
})
validate({data: -2, frmt: "positive"}).should.equal(false)
validate({data: 0, frmt: "positive"}).should.equal(false)
validate({data: 2, frmt: "positive"}).should.equal(true)
validate({data: "abc", frmt: "positive"}).should.equal(true)
})
})
})
describe("validateSchema method", () => {
it("should validate schema against meta-schema", () => {
let valid = ajv.validateSchema({
$schema: "http://json-schema.org/draft-07/schema#",
type: "number",
})
valid.should.equal(true)
should.equal(ajv.errors, null)
valid = ajv.validateSchema({
$schema: "http://json-schema.org/draft-07/schema#",
type: "wrong_type",
})
valid.should.equal(false)
assert(Array.isArray(ajv.errors))
ajv.errors.length.should.equal(3)
ajv.errors[0].keyword.should.equal("enum")
ajv.errors[1].keyword.should.equal("type")
ajv.errors[2].keyword.should.equal("anyOf")
})
it("should throw exception if meta-schema is unknown", () => {
should.throw(() => {
ajv.validateSchema({
$schema: "http://example.com/unknown/schema#",
type: "number",
})
}, /no schema with key or ref/)
})
it("should throw exception if $schema is not a string", () => {
should.throw(() => {
ajv.validateSchema({
//@ts-expect-error
$schema: {},
type: "number",
})
}, /\$schema must be a string/)
})
describe("sub-schema validation outside of definitions during compilation", () => {
it("maximum", () => {
passValidationThrowCompile({
$ref: "#/foo",
foo: {type: "number", maximum: "bar"},
})
})
it("exclusiveMaximum", () => {
passValidationThrowCompile({
$ref: "#/foo",
foo: {type: "number", exclusiveMaximum: "bar"},
})
})
it("maxItems", () => {
passValidationThrowCompile({
$ref: "#/foo",
foo: {type: "array", maxItems: "bar"},
})
})
it("maxLength", () => {
passValidationThrowCompile({
$ref: "#/foo",
foo: {type: "string", maxLength: "bar"},
})
})
it("maxProperties", () => {
passValidationThrowCompile({
$ref: "#/foo",
foo: {type: "object", maxProperties: "bar"},
})
})
it("multipleOf", () => {
passValidationThrowCompile({
$ref: "#/foo",
foo: {type: "number", multipleOf: "bar"},
})
})
function passValidationThrowCompile(schema: SchemaObject) {
ajv.validateSchema(schema).should.equal(true)
should.throw(() => {
ajv.compile(schema)
}, /value must be/)
}
})
})
}) | the_stack |
module webimmodel {
export class Conversation {
public title: string;
public targetId: string;
public targetType: any;
public lastTime: Date;
public lastMsg: string;
public unReadNum: number;
public draftMsg: string;
public firstchar: string;
public imgSrc: string;
public pinyin: string;
public everychar: string;
public mentionedInfo: RongIMLib.MentionedInfo;
public atStr: string;
constructor(item?: {
title: string,
targetId: string,
targetType: any,
lastTime: Date,
lastMsg: string,
unReadNum: number,
draftMsg: string,
firstchar?: string
}) {
if (item) {
this.title = item.title;
this.targetId = item.targetId;
this.targetType = item.targetType;
this.lastTime = item.lastTime;
this.lastMsg = item.lastMsg;
this.unReadNum = item.unReadNum;
this.draftMsg = item.draftMsg;
this.firstchar = item.firstchar;
}
}
setpinying(item: {
pinyin: string;
everychar: string;
firstchar: string;
}) {
this.pinyin = item.pinyin;
this.everychar = item.everychar;
}
static convertToWebIM(item: RongIMLib.Conversation, operatorid: string) {
var lasttime: Date;
if (item.latestMessage && item.sentTime) {
lasttime = new Date(item.sentTime);
}
var msgContent = ""
if (item.latestMessage) {
msgContent = Message.messageToNotification(item.latestMessage, operatorid, false)
}
return new Conversation({
title: item.conversationTitle || "",
targetId: item.targetId || "",
targetType: item.conversationType || "",
lastTime: lasttime || new Date(),
lastMsg: msgContent || "",
unReadNum: item.unreadMessageCount,
draftMsg: item.draft || ""
})
}
}
export enum MessageDirection {
SEND = 1,
RECEIVE = 2,
}
export enum ReceivedStatus {
READ = 0x1,
LISTENED = 0x2,
DOWNLOADED = 0x4
}
export enum SentStatus {
/**
* 发送中。
*/
SENDING = 10,
/**
* 发送失败。
*/
FAILED = 20,
/**
* 已发送。
*/
SENT = 30,
/**
* 对方已接收。
*/
RECEIVED = 40,
/**
* 对方已读。
*/
READ = 50,
/**
* 对方已销毁。
*/
DESTROYED = 60,
}
export enum PanelType {
Message = 1, InformationNotification = 2,
System = 103, Time = 104, getHistory = 105, getMore = 106,
Other = 0
}
export enum AtTarget {
All = 1, Part = 2
}
export var MessageType = {
DiscussionNotificationMessage: "DiscussionNotificationMessage",
TextMessage: "TextMessage",
ImageMessage: "ImageMessage",
VoiceMessage: "VoiceMessage",
RichContentMessage: "RichContentMessage",
HandshakeMessage: "HandshakeMessage",
HandShakeResponseMessage: "HandShakeResponseMessage",
UnknownMessage: "UnknownMessage",
SuspendMessage: "SuspendMessage",
LocationMessage: "LocationMessage",
InformationNotificationMessage: "InformationNotificationMessage",
ContactNotificationMessage: "ContactNotificationMessage",
ProfileNotificationMessage: "ProfileNotificationMessage",
CommandNotificationMessage: "CommandNotificationMessage",
ReadReceiptMessage: "ReadReceiptMessage",
TypingStatusMessage: "TypingStatusMessage",
FileMessage: "FileMessage",
GroupNotificationMessage: "GroupNotificationMessage",
RecallCommandMessage: "RecallCommandMessage",
InviteMessage: "InviteMessage",
HungupMessage: "HungupMessage",
ReadReceiptRequestMessage: "ReadReceiptRequestMessage",
ReadReceiptResponseMessage: "ReadReceiptResponseMessage",
SyncReadStatusMessage: "SyncReadStatusMessage"
}
export enum conversationType {
Private = 1, Discussion = 2, Group = 3, ChartRoom = 4, CustomerService = 5, System = 6, AppPublicService = 7, PublicService = 8
}
export enum NoticePanelType {
ApplyFriend = 1, AgreedFriend = 2,
WarningNotice = 101,
System = 102
}
export enum FriendStatus {
Requesting = 10, Requested = 11,
Agreed = 20, Ignored = 21, Deleted = 30,
GroupNotification = 101//群通知消息
}
export enum CommandNotificationMessageType {
ApplyGroup = 1, InviteAddGroup = 2, KickOutGroup = 3,
AcceptApplyGroup = 101, RejectApplyGroup = 102, AcceptInviteAddGroup = 201, RejectInviteAddGroup = 202
}
export enum FileState {
Uploading = 0, Canceled = 1, Failed = 2, Success = 3
}
export class ChatPanel {
panelType: PanelType
constructor(type: PanelType) {
this.panelType = type;
}
}
// function replacemy(ele: string) {
// return ele.replace(new RegExp("<[\\s\\S.]*?>", "ig"), "<amp>" + ele + "</amp>");
// // return '<xmp>' + e + '</xmp>';
// }
export class Message extends ChatPanel {
content: any;
conversationType: any;
extra: string;
objectName: string;
messageDirection: MessageDirection;
messageId: string;
messageUId: string;
receivedStatus: ReceivedStatus;
receivedTime: Date;
senderUserId: string;
sentStatus: SentStatus;
sentTime: Date;
targetId: string;
messageType: string;
senderUserName: string
senderUserImgSrc: string
imgSrc: string
mentionedInfo: any
isRead: boolean
receiptResponse: any;
constructor(content?: any, conversationType?: string, extra?: string, objectName?: string, messageDirection?: MessageDirection, messageId?: string, receivedStatus?: ReceivedStatus, receivedTime?: number, senderUserId?: string, sentStatus?: SentStatus, sentTime?: number, targetId?: string, messageType?: string) {
super(PanelType.Message);
}
static formatGIFMsg(data: any){
if(data.objectName == 'RC:GIFMsg' && data.messageType == "UnknownMessage"){
data.objectName = 'RC:ImgMsg';
var unknownMsg:any = data.content;
var _msg = unknownMsg.message;
var _content = _msg.content;
data.content = new RongIMLib.ImageMessage({
content: _content.remoteUrl,
imageUri: _content.remoteUrl
});
data.messageType = 'ImageMessage';
}
return data;
}
static convertMsg(SDKmsg: any) {
var msg = new Message();
msg.conversationType = SDKmsg.conversationType;
msg.extra = SDKmsg.extra;
msg.objectName = SDKmsg.objectName
msg.messageDirection = SDKmsg.messageDirection;
msg.messageId = SDKmsg.messageId;
msg.messageUId = SDKmsg.messageUId;
msg.receivedStatus = SDKmsg.receivedStatus;
msg.receivedTime = new Date(SDKmsg.receivedTime);
msg.senderUserId = SDKmsg.senderUserId;
msg.sentStatus = SDKmsg.sendStatusMessage;
msg.sentTime = new Date(SDKmsg.sentTime);
msg.targetId = SDKmsg.targetId;
msg.messageType = SDKmsg.messageType;
switch (msg.messageType) {
case MessageType.TextMessage:
var texmsg = new TextMessage();
var content = SDKmsg.content.content;
content = content.replace(/</gi, '<').replace(/>/gi, '>');
if (RongIMLib.RongIMEmoji && RongIMLib.RongIMEmoji.emojiToHTML) {
content = RongIMLib.RongIMEmoji.emojiToHTML(content);
}
texmsg.content = content;
// texmsg.content = '<xmp>' + content + '</xmp>';
msg.content = texmsg;
msg.mentionedInfo = SDKmsg.content.mentionedInfo;
msg.receiptResponse = SDKmsg.receiptResponse;
break;
case MessageType.ImageMessage:
var image = new ImageMessage();
var content = SDKmsg.content.content || "";
if (typeof content == "string" && content.indexOf("base64,") == -1 && content.indexOf('http') == -1) {
content = "data:image/png;base64," + content;
}
image.content = content;
image.imageUri = SDKmsg.content.imageUri;
msg.content = image;
break;
case MessageType.VoiceMessage:
var voice = new VoiceMessage();
voice.content = SDKmsg.content.content;
voice.duration = SDKmsg.content.duration;
msg.content = voice;
break;
case MessageType.RichContentMessage:
var rich = new RichContentMessage();
rich.content = SDKmsg.content.content;
rich.title = SDKmsg.content.title;
rich.imageUri = SDKmsg.content.imageUri;
rich.url = SDKmsg.content.url;
msg.content = rich;
break;
case MessageType.LocationMessage:
var location = new LocationMessage();
var content = SDKmsg.content.content || "";
if (typeof content == "string" && content.indexOf("base64,") == -1) {
content = "data:image/png;base64," + content;
}
location.content = content;
location.latiude = SDKmsg.content.latiude;
location.longitude = SDKmsg.content.longitude;
location.poi = SDKmsg.content.poi;
msg.content = location;
break;
case MessageType.FileMessage:
var file = new FileMessage();
var content = SDKmsg.content.content || "";
file.name = SDKmsg.content.name;
file.size = SDKmsg.content.size;
file.type = SDKmsg.content.type;
file.fileUrl = SDKmsg.content.fileUrl;
file.extra = SDKmsg.content.extra;
file.state = FileState.Success;
msg.content = file;
break;
case MessageType.InformationNotificationMessage:
// var info = new InformationNotificationMessage();
// info.content = SDKmsg.content.message;
// msg.content = info;
msg.content = SDKmsg.content.message;
msg.panelType = webimmodel.PanelType.InformationNotification;
break;
case MessageType.ContactNotificationMessage:
var contact = new ContactNotificationMessage();
contact.content = SDKmsg.content.message;
contact.operation = SDKmsg.content.operation;
contact.sourceUserId = SDKmsg.content.sourceUserId;
contact.targetUserId = SDKmsg.content.targetUserId;
contact.message = SDKmsg.content.content;
switch (contact.operation) {
case "Request":
contact.noticeType = NoticePanelType.ApplyFriend;
break;
case "AcceptResponse":
contact.noticeType = NoticePanelType.AgreedFriend;
contact.content = "同意加为好友"
break;
case "RejectResponse":
// tmp.noticeType = NoticePanelType.WarningNotice;
// tmp.content = "拒绝加为好友"
console.log("拒绝好友通知消息未支持");
break;
}
msg.content = contact;
break;
case MessageType.CommandNotificationMessage:
var comm = new CommandNotificationMessage();
comm.noticeType = NoticePanelType.WarningNotice;
comm.data = SDKmsg.content.data;
comm.name = SDKmsg.content.name;
msg.content = comm;
break;
case MessageType.DiscussionNotificationMessage:
// var discussion = new DiscussionNotificationMessage();
// discussion.extension = SDKmsg.content.extension;
// discussion.operation = SDKmsg.content.operation;
// discussion.type = SDKmsg.content.type;
// discussion.isHasReceived = SDKmsg.content.isHasReceived;
// msg.content = discussion;
// msg.panelType = webimmodel.PanelType.InformationNotification;
if (SDKmsg.objectName == "RC:DizNtf") {
var groupnot = new webimmodel.InformationNotificationMessage();
groupnot.content = SDKmsg.content.message;
msg.content = groupnot;
msg.panelType = webimmodel.PanelType.InformationNotification;
} else {
console.log("has unknown message type " + SDKmsg.messageType)
}
break;
case MessageType.ReadReceiptMessage:
case MessageType.TypingStatusMessage:
break;
case MessageType.RecallCommandMessage:
msg.content = '撤回了一条消息';
msg.panelType = webimmodel.PanelType.InformationNotification;
break;
case MessageType.InviteMessage:
case MessageType.HungupMessage:
// if(SDKmsg.content.mediaType == '1'){
// msg.content = '音频消息';
// }
// else if(SDKmsg.content.mediaType == '2'){
// msg.content = '视频消息';
// }
msg.content = '当前版本暂不支持查看此消息';
msg.panelType = webimmodel.PanelType.InformationNotification;
break;
case MessageType.ReadReceiptRequestMessage:
msg.content = SDKmsg.content.messageUId;
break;
case MessageType.ReadReceiptResponseMessage:
msg.content = SDKmsg.content.receiptMessageDic;
msg.receiptResponse = SDKmsg.receiptResponse;
break;
case MessageType.SyncReadStatusMessage:
break;
default:
if (SDKmsg.objectName == "ST:GrpNtf") {
var groupnot = new webimmodel.InformationNotificationMessage();
groupnot.content = SDKmsg.content.message;
msg.content = groupnot;
msg.panelType = webimmodel.PanelType.InformationNotification;
} else if(SDKmsg.objectName == "RC:RLStart" || SDKmsg.objectName == "RC:RL" || SDKmsg.objectName == "RC:RcCmd"){
}
else
{
msg.content = '当前版本暂不支持查看此消息';
msg.panelType = webimmodel.PanelType.InformationNotification;
console.log("has unknown message type " + SDKmsg.messageType)
}
break;
}
if (msg.content) {
msg.content.userInfo = SDKmsg.content.userInfo;
}
return msg;
}
static messageToNotification = function(msg: any, operatorid: string, isnotification: boolean) {
if (!msg)
return null;
var msgtype = msg.messageType, msgContent: string;
if (msgtype == MessageType.ImageMessage || msg.objectName == 'RC:GIFMsg') {
msgContent = "[图片]";
} else if (msgtype == MessageType.LocationMessage) {
msgContent = "[位置]";
} else if (msgtype == MessageType.RichContentMessage) {
msgContent = "[图文]";
} else if (msgtype == MessageType.VoiceMessage) {
msgContent = "[语音]";
}else if (msgtype == webimmodel.MessageType.FileMessage) {
msgContent = "[文件] " + msg.content.name;
} else if (msgtype == MessageType.ContactNotificationMessage || msgtype == MessageType.CommandNotificationMessage || msgtype == MessageType.InformationNotificationMessage) {
msgContent = "[通知消息]";
} else if (msg.objectName == "ST:GrpNtf") {
// var data = msg.content.message.content.data.data;
var data = msg.content.data;
// switch (msg.content.message.content.operation) {
switch (msg.content.operation) {
case "Add":
if(msg.content.operatorUserId == operatorid){
msgContent = data.targetUserDisplayNames ? ("你邀请" + data.targetUserDisplayNames.join("、") + "加入了群组") : "加入群组";
}else{
msgContent = data.targetUserDisplayNames ? (data.operatorNickname + "邀请" + data.targetUserDisplayNames.join("、") + "加入了群组") : "加入群组";
}
break;
case "Quit":
msgContent = data.operatorNickname + "退出了群组";
break;
case "Kicked":
//由于之前数据问题
if(msg.content.operatorUserId == operatorid){
msgContent = data.targetUserDisplayNames ? ("你将" + data.targetUserDisplayNames.join("、") + "移出了群组") : "移除群组";
}else{
msgContent = data.targetUserDisplayNames ? (data.operatorNickname + "将" + data.targetUserDisplayNames.join("、") + "移出了群组") : "移除群组";
}
break;
case "Rename":
if(msg.content.operatorUserId == operatorid){
msgContent = "你修改群名称为" + data.targetGroupName;
}else{
msgContent = data.operatorNickname + "修改群名称为" + data.targetGroupName;
}
break;
case "Create":
if(msg.content.operatorUserId == operatorid){
msgContent = "你创建了群组";
}else{
msgContent = data.operatorNickname + "创建了群组";
}
break;
case "Dismiss":
msgContent = data.operatorNickname + "解散了群组";
if(data.targetGroupName){
msgContent += data.targetGroupName;
}
break;
default:
break;
}
} else if (msg.objectName == "RC:DizNtf") {
var data = msg
// var members = msg.content.extension.split(',');
// for (var i = 0, len = members.length; i < len; i++) {
// mainServer.user.getInfo(members[i]).success(function (rep) {
// if (item.content === comment) {
// item.content = rep.result.nickname + item.content;
// }
// else {
// item.content = rep.result.nickname + "、" + item.content;
// }
// });
// }
switch (msg.content.type) {
case 1:
msgContent = " 加入了讨论组";
break;
case 2:
msgContent = " 退出了讨论组";
break;
case 4:
//由于之前数据问题
msgContent = " 被踢出讨论组";
break;
case 3:
msgContent = " 修改了讨论组名称";
break;
default:
break;
}
}
else if(msgtype == webimmodel.MessageType.TextMessage){
msgContent = msg.content ? msg.content.content : "";
msgContent = webimutil.Helper.escapeSymbol.escapeHtml(msgContent);
if(isnotification){
msgContent = RongIMLib.RongIMEmoji.emojiToSymbol(msgContent);
if (webimutil.Helper.os.mac){
msgContent = RongIMLib.RongIMEmoji.symbolToEmoji(msgContent);
}
}
else{
if (RongIMLib.RongIMEmoji && RongIMLib.RongIMEmoji.emojiToHTML) {
msgContent = RongIMLib.RongIMEmoji.emojiToHTML(msgContent);
}
}
// if (!webimutil.Helper.browser.chrome) {
msgContent = msgContent.replace(/\n/g, " ");
msgContent = msgContent.replace(/([\w]{49,50})/g, "$1 ");
// msgContent = msgContent.replace(/</gi, '<').replace(/>/gi, '>');
// }
}
else if(msgtype == webimmodel.MessageType.RecallCommandMessage){
msgContent = "撤回一条消息";
}
// else if(msgtype == webimmodel.MessageType.SyncReadStatusMessage){
// }
// else if(msgtype == webimmodel.MessageType.ReadReceiptRequestMessage){
//
// }
// else if(msgtype == webimmodel.MessageType.ReadReceiptResponseMessage){
//
// }
else {
msgContent = "[当前版本暂不支持查看此消息]";
}
return msgContent;
}
}
export class ContactNotificationMessage extends Message {
operation: string;
sourceUserId: string;
targetUserId: string;
message: string;
noticeType: number;
}
export class CommandNotificationMessage extends Message {
name: string;
data: any;
noticeType: number;
}
export class TextMessage {
userInfo: UserInfo;
content: string;
constructor(msg?: any) {
msg = msg || {};
this.content = msg.content;
this.userInfo = msg.userInfo;
}
}
export class InformationNotificationMessage {
userInfo: UserInfo;
content: string;
extra: string;
messageName: string;
}
export class ImageMessage {
userInfo: UserInfo;
content: string;
imageUri: string;
}
export class VoiceMessage {
userInfo: UserInfo;
content: string;
duration: string;
}
export class LocationMessage {
userInfo: UserInfo;
content: string;
latiude: number;
longitude: number;
poi: string;
}
export class RichContentMessage {
userInfo: UserInfo;
content: string;
title: string;
imageUri: string;
url: string;
}
export class DiscussionNotificationMessage {
userInfo: UserInfo;
extension: string;
type: number;
isHasReceived: boolean;
operation: string;
extra: string;
messageName: string;
}
export class FileMessage {
userInfo: UserInfo;
// content: string;
// title: string;
name: string;
size: number;
type: number;
fileUrl: string;
extra: string;
state: FileState;
progress: number; // 0-100
}
export class ReadReceiptRequestMessage {
messageUId: string;
}
export class ReadReceiptResponseMessage {
receiptMessageDic: any;
}
export class GetHistoryPanel extends ChatPanel {
constructor() {
super(PanelType.getHistory)
}
}
export class GetMoreMessagePanel extends ChatPanel {
constructor() {
super(PanelType.getMore)
}
}
export class TimePanl extends ChatPanel {
sendTime: Date
constructor(time: Date) {
super(PanelType.Time)
this.sendTime = time;
}
}
export class WarningNoticeMessage {
status: number;
content: string;
timestamp: number;//用于通知消息排序
constructor(content: string) {
this.content = content;
this.status = webimmodel.FriendStatus.GroupNotification
}
}
export class NotificationFriend {
id: string
name: string
portraitUri: string
content: string
status: string
timestamp: number//用于通知消息排序
firstchar: string
constructor(item: {
id: string,
name: string,
portraitUri: string,
content: string,
status: string
timestamp: number
}) {
this.id = item.id;
this.name = item.name;
this.portraitUri = item.portraitUri;
this.content = item.content;
this.status = item.status;
this.timestamp = item.timestamp;
}
}
export class UserInfo {
constructor(public id?: string,
public token?: string,
public nickName?: string,
public portraitUri?: string,
public phone?: string,
public region?: string,
public firstchar?: string) { }
}
export class Contact {
id: string;
name: string;
imgSrc: string;
pinyin: string;
everychar: string;
firstchar: string;
displayName: string;
constructor(item?: {
id: string;
name: string;
imgSrc: string;
}) {
this.id = item.id;
this.name = item.name;
this.imgSrc = item.imgSrc;
}
setpinying(item: {
pinyin: string;
everychar: string;
firstchar: string;
}) {
this.pinyin = item.pinyin;
this.everychar = item.everychar;
this.firstchar = item.firstchar;
}
}
export class Friend extends Contact {
displayName: string
mobile: string
constructor(item: {
id: string;
name: string;
imgSrc: string;
}) {
super(item);
}
}
export class Subgroup {
title: string
list: Friend[]
constructor(title: string, list: Friend[]) {
this.title = title;
this.list = list;
}
}
export class Group extends Contact {
upperlimit: number;
fact: number;
creater: string;
memberList: Member[];
constructor(item: {
id: string;
name: string;
imgSrc: string;
upperlimit: number;
fact: number;
creater: string;
}) {
super(item);
this.upperlimit = item.upperlimit;
this.fact = item.fact;
this.creater = item.creater;
this.memberList = []
}
}
export class Discussion extends Contact {
upperlimit: number;
fact: number;
creater: string;
memberList: Member[];
constructor(item: {
id: string;
name: string;
imgSrc: string;
upperlimit: number;
fact: number;
creater: string;
isOpen: boolean;
}) {
super(item);
this.upperlimit = item.upperlimit;
this.fact = item.fact;
this.creater = item.creater;
this.memberList = []
}
}
export class Member extends Contact {
id: string;
name: string;
imgSrc: string;
role: string;
displayName: string;
// pinyin: string;
// first: string;
constructor(item: {
id: string;
name: string;
imgSrc: string;
role?: string;
displayName?: string;
}) {
super(item);
this.role = item.role;
}
}
} | the_stack |
import * as os from 'os';
import * as fs from 'fs';
import * as pathmod from 'path';
import * as process from 'process';
import * as child_process from 'child_process';
import * as _ from 'lodash';
import * as crypto from 'crypto';
import * as handlebars from 'handlebars';
import * as handlebarsHelpers from 'handlebars-helpers';
import * as nameGenerator from 'project-name-generator';
import * as bluebird from 'bluebird';
global.Promise = bluebird;
import * as aws from 'aws-sdk'
import {ServiceConfigurationOptions} from 'aws-sdk/lib/service';
import * as url from 'url';
import * as request from 'request-promise-native';
import * as tv4 from 'tv4';
import * as yaml from '../yaml';
import {logger} from '../logger';
import normalizePath from '../normalizePath';
import filehash from '../filehash';
import paginateAwsCall from '../paginateAwsCall';
import {_getParamsByPath} from '../params';
import {Visitor} from './visitor';
// `tojson`, `tojsonPretty`, and `toyaml` are deprecated in favour of the camelCase version
handlebars.registerHelper('tojson', (context: any) => JSON.stringify(context));
handlebars.registerHelper('tojsonPretty', (context: any) => JSON.stringify(context, null, ' '));
handlebars.registerHelper('toyaml', (context: any) => yaml.dump(context));
handlebars.registerHelper('toJson', (context: any) => JSON.stringify(context));
handlebars.registerHelper('toJsonPretty', (context: any) => JSON.stringify(context, null, ' '));
handlebars.registerHelper('toYaml', (context: any) => yaml.dump(context));
handlebars.registerHelper('base64', (context: any) => Buffer.from(context).toString('base64'));
handlebars.registerHelper('toLowerCase', (str: string) => str.toLowerCase());
handlebars.registerHelper('toUpperCase', (str: string) => str.toUpperCase());
handlebarsHelpers(['string'], {handlebars});
export function interpolateHandlebarsString(templateString: string, env: object, errorContext: string) {
try {
const template = handlebars.compile(templateString, {noEscape: true, strict: true});
return template(env);
} catch (e) {
const errMessage = e instanceof Error ? e.message : `${e}`;
logger.debug(errMessage);
throw new Error(
`Error in string template at ${errorContext}:\n ${errMessage}\n Template: ${templateString}`)
}
}
export type SHA256Digest = string;
export type PreprocessOptions = {
omitMetadata?: boolean
};
export interface CfnDoc {
AWSTemplateFormatVersion?: '2010-09-09',
Description?: string,
Parameters?: object,
Conditions?: object,
Resources?: object,
Outputs?: object,
Mappings?: object,
Metadata?: object,
Transform?: object
};
export type AnyButUndefined = string | number | boolean | object | null | CfnDoc | ExtendedCfnDoc;
export type ImportLocation = string; // | {From: string, As: string}
export type ImportRecord = {
key: string | null,
"from": ImportLocation,
imported: ImportLocation,
sha256Digest: SHA256Digest,
};
export type $EnvValues = {[key: string]: AnyButUndefined} // TODO might need more general value type
export type $param = {
Name: string,
Default?: AnyButUndefined,
Type?: string,
Schema?: object,
AllowedValues?: any[],
AllowedPattern?: string,
};
// TODO find a better name for this Interface
export interface ExtendedCfnDoc extends CfnDoc {
$imports?: {[key: string]: any}, // TODO AnyButUndefined
$defs?: {[key: string]: AnyButUndefined},
$params?: $param[],
$location: string,
$envValues?: $EnvValues
};
// TODO definition of GlobalSections is a bit ugly. Investigate enum
// alternatives.
const GlobalSections = {
Parameters: 'Parameters',
Metadata: 'Metadata',
Mappings: 'Mappings',
Conditions: 'Conditions',
Transform: 'Transform',
Outputs: 'Outputs',
};
export type GlobalSection = keyof typeof GlobalSections;
export const GlobalSectionNames = _.values(GlobalSections) as GlobalSection[];
export type StackFrame = {location: string, path: string};
export type MaybeStackFrame = {location?: string, path: string};
export type Env = {
GlobalAccumulator: CfnDoc,
$envValues: $EnvValues,
Stack: StackFrame[]
};
export type ImportData = {
importType?: ImportType
resolvedLocation: ImportLocation // relative-> absolute, etc.
data: string
doc?: any
}
class ImportError<E extends Error> extends Error {
constructor(message: string, public location: string, public baseLocation: string, public wrappedError?: E) {
super(message);
}
}
// TODO timestamp
export type ImportType =
"file" | "env" | "git" | "random" | "filehash" | "filehash-base64" | "cfn" | "ssm" | "ssm-path" | "s3" | "http";
// https://github.com/kimamula/ts-transformer-enumerate is an alternative to this
// repetition. Could also use a keyboard macro.
const importTypes: ImportType[] = [
"file", "env", "git", "random", "filehash", "filehash-base64", "cfn", "ssm", "ssm-path", "s3", "http"];
const localOnlyImportTypes: ImportType[] = ["file", "env"];
// npm:version npm:project-name, etc. with equivs for lein/mvn
// cfn://stacks/{StackName}/[Outputs,Resources]
// cfn://exports/{ExportName}
// see https://github.com/ampedandwired/bora/blob/master/README.md
type GitValue = "branch" | "describe" | "sha";
const gitValues = ["branch", "describe", "sha"];
function gitValue(valueType: GitValue): string {
const command = {
branch: 'git rev-parse --abbrev-ref HEAD',
describe: 'git describe --dirty --tags',
sha: 'git rev-parse HEAD'
}[valueType];
const result = child_process
.spawnSync(command, [], {shell: true});
if (result.status) {
throw new Error('git value lookup failed. Are you inside a git repo?');
} else {
return result.stdout.toString().trim();
}
}
const sha256Digest = (content: string | Buffer): SHA256Digest =>
crypto.createHash('sha256').update(content.toString()).digest('hex');
////////////////////////////////////////////////////////////////////////////////
// Import handling
export function parseImportType(location: ImportLocation, baseLocation: ImportLocation): ImportType {
// TODO splitting by : will probably cause issues on Windows. Do we care?
const hasExplicitType = location.indexOf(':') > -1;
const importType0 = hasExplicitType
? location.toLowerCase().split(':')[0].replace('https', 'http')
: "file";
if (!_.includes(importTypes, importType0)) {
throw new Error(`Unknown import type ${location} in ${baseLocation}`);
}
const importType = importType0 as ImportType;
const baseImportType = baseLocation.indexOf(':') > -1
? baseLocation.toLowerCase().split(':')[0] as ImportType
: "file";
if (_.includes(['s3', 'http'], baseImportType)) {
if (!hasExplicitType) {
return baseImportType;
} else if (_.includes(localOnlyImportTypes, importType)) {
// security cross-check
throw new Error(`Import type ${location} in ${baseLocation} not allowed from remote template`);
} else {
return importType;
}
} else {
return importType;
}
}
function resolveDocFromImportData(data: string, location: ImportLocation): any {
const uri = url.parse(location);
let ext: string;
if ((uri.host && uri.path)) {
ext = pathmod.extname(uri.path);
} else {
ext = pathmod.extname(location);
}
if (_.includes(['.yaml', '.yml'], ext)) {
return yaml.loadString(data, location)
} else if (ext === '.json') {
return JSON.parse(data);
} else {
return data;
}
}
const parseDataFromParamStore = (payload: string, formatType?: string): any => {
// TODO merge this into resolveDocFromImportData
if (formatType === 'json') {
// TODO nicer error reporting
// `Invalid ssm parameter value ${s} import from ${location} in ${baseLocation}`
return JSON.parse(payload);
} else if (formatType === 'yaml') {
return yaml.loadString(payload, 'location');
} else {
return payload
}
}
export type ImportLoader = (location: ImportLocation, baseLocation: ImportLocation) => Promise<ImportData>;
export const filehashLoader = async (location0: ImportLocation, baseLocation: ImportLocation, format: 'hex' | 'base64' = 'hex') => {
let location = location0.split(':')[1];
const allowMissingFile: boolean = location.startsWith('?');
if (allowMissingFile) {
location = location.slice(1).trim();
}
const resolvedLocation = normalizePath(pathmod.dirname(baseLocation), location);
if (!fs.existsSync(resolvedLocation)) {
if (allowMissingFile) {
return {resolvedLocation, data: 'FILE_MISSING', doc: 'FILE_MISSING'};
} else {
throw new Error(`Invalid location ${resolvedLocation} for filehash in ${baseLocation}`);
}
} else {
const data = filehash(resolvedLocation, format);
return {resolvedLocation, data, doc: data};
}
};
export const importLoaders: {[key in ImportType]: ImportLoader} = {
file: async (location, baseLocation) => {
const resolvedLocation = pathmod.resolve(pathmod.dirname(baseLocation.replace('file:', '')), location.replace('file:', ''));
try {
const data = (await bluebird.promisify(fs.readFile)(resolvedLocation)).toString();
return {resolvedLocation, data, doc: resolveDocFromImportData(data, resolvedLocation)}
} catch (e) {
throw new Error(
`"${baseLocation}" has a bad import "$imports: ... ${location}". ${e}`);
}
},
filehash: filehashLoader, // hex
"filehash-base64": async (location, baseLocation) => filehashLoader(location, baseLocation, 'base64'),
s3: async (location, baseLocation) => {
let resolvedLocation: ImportLocation;
if (location.indexOf('s3:') === 0) {
resolvedLocation = location;
} else {
resolvedLocation = 's3:/' + pathmod.join(pathmod.dirname(baseLocation.replace('s3:/', '')), location)
}
const uri = url.parse(resolvedLocation);
if (uri.host && uri.path) {
const s3 = new aws.S3();
const s3response = await s3.getObject({
Bucket: uri.host,
Key: uri.path.slice(1) // doesn't like leading /
}).promise()
if (s3response.Body) {
const data = s3response.Body.toString();
const doc = resolveDocFromImportData(data, resolvedLocation);
return {importType: 's3', resolvedLocation, data, doc};
} else {
throw new Error(`Invalid s3 response from ${location} under ${baseLocation}`);
}
}
throw new Error(`Invalid s3 uri ${location} under ${baseLocation}`);
},
cfn: async (location, _baseLocation) => {
let resolvedLocationParts, StackName, field, fieldKey;
let data: any, doc: any;
const cfnOptions: ServiceConfigurationOptions = {};
const uri = url.parse(location);
const queryParameters = new url.URLSearchParams(uri.search);
const region = queryParameters.get('region');
if (region) {
cfnOptions.region = region;
}
const cfn = new aws.CloudFormation(cfnOptions);
[, field, ...resolvedLocationParts] = location.replace(/\?.*$/, '').split(':');
const resolvedLocation = resolvedLocationParts.join(':');
if (field === 'export') {
const exports0: aws.CloudFormation.Exports = await paginateAwsCall((args) => cfn.listExports(args), {}, 'Exports');
const exports = _.fromPairs(_.map(exports0, (ex) => [ex.Name, ex]));
const exportName = resolvedLocation;
if (exportName) {
if (!exports[exportName]) {
throw new Error(`${location} not found`);
}
data = exports[exportName];
doc = data.Value;
} else {
data = exports;
doc = data;
}
return {resolvedLocation: location, data, doc};
} else {
[StackName, fieldKey] = resolvedLocation.split('/');
const {Stacks} = await cfn.describeStacks({StackName}).promise();
if (Stacks && Stacks[0]) {
const stack = Stacks[0];
switch (field) {
case 'output':
const outputs = _.fromPairs(_.map(stack.Outputs, (output) => [output.OutputKey, output.OutputValue]));
data = fieldKey ? _.get(outputs, fieldKey) : outputs;
doc = data;
break;
case 'parameter':
const params = _.fromPairs(_.map(stack.Parameters, (p) => [p.ParameterKey, p.ParameterValue]));
data = fieldKey ? _.get(params, fieldKey) : params;
doc = data;
break;
case 'tag':
const tags = _.fromPairs(_.map(stack.Tags, (t) => [t.Key, t.Value]));
data = fieldKey ? _.get(tags, fieldKey) : tags;
doc = data;
break;
case 'resource':
const {StackResources} = await cfn.describeStackResources({StackName}).promise();
const resources = _.fromPairs(_.map(StackResources, (r) => [r.LogicalResourceId, r]));
data = fieldKey ? _.get(resources, fieldKey) : resources;
doc = data;
break;
case 'stack':
data = stack
doc = data;
break;
default:
throw new Error(`Invalid cfn $import: ${location}`);
}
return {resolvedLocation: location, data, doc};
} else {
throw new Error(`${location} not found`);
}
}
},
http: async (location, _baseLocation) => {
const resolvedLocation = location;
const data = await request.get(location);
const doc = resolveDocFromImportData(data, resolvedLocation);
return {resolvedLocation, data, doc};
},
env: async (location, baseLocation) => {
let resolvedLocation, defVal;
[, resolvedLocation, defVal] = location.split(':')
const data = _.get(process.env, resolvedLocation, defVal)
if (_.isUndefined(data)) {
throw new Error(`Env-var ${resolvedLocation} not found from ${baseLocation}`)
}
return {resolvedLocation, data, doc: data};
},
git: async (location, _baseLocation) => {
const resolvedLocation = location.split(':')[1]
if (_.includes(gitValues, resolvedLocation)) {
const data = gitValue(resolvedLocation as GitValue);
return {resolvedLocation, data, doc: data};
} else {
throw new Error(`Invalid git command: ${location}`);
}
},
random: async (location, baseLocation) => {
const resolvedLocation = location.split(':')[1];
let data: string;
if (resolvedLocation === 'dashed-name') {
data = nameGenerator().dashed;
} else if (resolvedLocation === 'name') {
data = nameGenerator().dashed.replace('-', '');
} else if (resolvedLocation === 'int') {
const max = 1000, min = 1;
data = (Math.floor(Math.random() * (max - min)) + min).toString();
} else {
throw new Error(`Invalid random type in ${location} at ${baseLocation}`);
}
return {resolvedLocation, data, doc: data};
},
ssm: async (location, baseLocation) => {
let resolvedLocation: ImportLocation, format: string;
[, resolvedLocation, format] = location.split(':')
const ssm = new aws.SSM();
const param = await ssm.getParameter({Name: resolvedLocation, WithDecryption: true}).promise();
if (param.Parameter && param.Parameter.Value) {
const data = parseDataFromParamStore(param.Parameter.Value, format);
return {resolvedLocation, data, doc: data};
} else {
throw new Error(
`Invalid ssm parameter ${resolvedLocation} import at ${baseLocation}`);
}
},
"ssm-path": async (location, _baseLocation) => {
let resolvedLocation: ImportLocation, format: string;
[, resolvedLocation, format] = location.split(':')
if (!resolvedLocation.endsWith('/')) {
resolvedLocation += '/';
}
const params = await _getParamsByPath(resolvedLocation);
const doc = _.fromPairs(_.map(params, ({Name, Value}) =>
[(Name as string).replace(resolvedLocation, ''),
parseDataFromParamStore(Value as string, format)]));
return {resolvedLocation, data: JSON.stringify(doc), doc};
}
};
export async function readFromImportLocation(location: ImportLocation, baseLocation: ImportLocation)
: Promise<ImportData> {
// TODO handle relative paths and non-file types
const importType = parseImportType(location, baseLocation);
try {
const importData: ImportData = await importLoaders[importType](location, baseLocation);
return _.merge({importType}, importData);
} catch (error) {
if (error instanceof Error) {
throw new ImportError(
error.message || `Invalid import ${location} import at ${baseLocation}`,
location, baseLocation, error
);
} else {
throw error;
}
}
}
export async function loadImports(
doc: ExtendedCfnDoc,
baseLocation: ImportLocation,
importsAccum: ImportRecord[],
importLoader = readFromImportLocation // for mocking in tests
): Promise<void> {
// recursively load the entire set of imports
doc.$envValues = doc.$envValues || {};
if (doc.$defs) {
for (const key in doc.$defs) {
if (_.includes(_.keys(doc.$envValues), key)) {
throw new Error(
`"${key}" in $defs collides with the same name in $imports of ${baseLocation}`)
}
doc.$envValues[key] = doc.$defs[key];
}
}
if (doc.$imports) {
if (!_.isPlainObject(doc.$imports)) {
throw Error(
`Invalid imports in ${baseLocation}:\n "${JSON.stringify(doc.$imports)}". \n Should be mapping.`);
}
for (const asKey in doc.$imports) {
let loc = doc.$imports[asKey];
if (!_.isString(loc)) {
throw new Error(`"${baseLocation}" has a bad import "$imports: ... ${asKey}".\n`
+ ` Import values must be strings but ${asKey}=${JSON.stringify(loc, null, ' ')}".`)
}
if (loc.search(/{{(.*?)}}/) > -1) {
loc = interpolateHandlebarsString(loc, doc.$envValues, `${baseLocation}: ${asKey}`);
}
logger.debug('loading import:', loc, asKey);
const importData = await importLoader(loc, baseLocation);
logger.debug('loaded import:', loc, asKey, importData);
if (_.isObject(importData.doc)) {
(importData.doc as any).$location = loc;
}
importsAccum.push({
from: baseLocation,
imported: importData.resolvedLocation,
sha256Digest: sha256Digest(importData.data),
key: asKey
});
if (_.includes(doc.$envValues, asKey)) {
throw new Error(
`"${asKey}" in $imports collides with the same name in $defs of ${baseLocation}`);
}
doc.$envValues[asKey] = importData.doc;
if (importData.doc.$imports || importData.doc.$defs) {
await loadImports(
importData.doc, importData.resolvedLocation, importsAccum, importLoader)
}
}
}
if (doc.$params) {
// guard against name clashes
for (const {Name} of doc.$params) {
if (_.includes(_.keys(doc.$envValues), Name)) {
throw new Error(
`"${Name}" in $params collides with "${Name}" in $imports or $defs of ${baseLocation}`)
}
}
}
};
// End: Import handling
////////////////////////////////////////////////////////////////////////////////
export const appendPath = (rootPath: string, suffix: string): string =>
rootPath ? rootPath + '.' + suffix : suffix;
export function validateTemplateParameter(param: $param, mergedParams: any, name: string, env: Env) {
const paramValue = mergedParams[param.Name];
if (_.isUndefined(paramValue)) {
throw new Error(`Missing required parameter ${param.Name} in ${name}`);
} else if (param.Schema) {
if (!_.isObject(param.Schema)) {
throw new Error(`Invalid schema "${param.Name}" in ${name}.`)
}
const validationResult = tv4.validateResult(paramValue, param.Schema)
if (!validationResult.valid) {
const errmsg = `Parameter validation error for "${param.Name}" in ${name}.`;
logger.error(errmsg);
logger.error(` ${env.Stack[env.Stack.length - 1].location || ''}`)
logger.error(validationResult.error.message);
logger.error('Here is the parameter JSON Schema:\n' + yaml.dump(param.Schema));
throw new Error(errmsg);
}
} else if (param.AllowedValues) {
// cfn style validation
if (!_.includes(param.AllowedValues, paramValue)) {
const errmsg = `Parameter validation error for "${param.Name}" in ${name}.`;
logger.error(errmsg);
logger.error(` ${env.Stack[env.Stack.length - 1].location || ''}`)
logger.error(`${paramValue} not in Allowed Values: ${yaml.dump(param.AllowedValues)}`);
throw new Error(errmsg);
}
} else if (param.AllowedPattern) {
// TODO test
const patternRegex = new RegExp(param.AllowedPattern);
if (!(typeof paramValue === 'string' && paramValue.match(patternRegex))) {
throw new Error(`Invalid value "${param.Name}" in ${name}. AllowedPattern: ${param.AllowedPattern}.`)
}
} else if (typeof param.Type === 'string') {
const throwParamTypeError = () => {
throw new Error(`Invalid parameter value "${JSON.stringify(paramValue, null, ' ')}". Expected a ${param.Type}`);
};
switch (param.Type) {
case 'string':
case 'String':
if (!_.isString(paramValue)) {
throwParamTypeError();
}
break;
case 'number':
case 'Number':
if (!_.isNumber(paramValue)) {
throwParamTypeError();
}
break;
case 'object':
case 'Object':
if (!_.isObject(paramValue)) {
throwParamTypeError();
}
break;
// see the full list of AWS CFN params here
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html
case 'CommaDelimitedList':
case 'List<Number>':
case 'AWS::EC2::AvailabilityZone::Name':
case 'AWS::EC2::Image::Id':
case 'AWS::EC2::Instance::Id':
case 'AWS::EC2::KeyPair::KeyName':
case 'AWS::EC2::SecurityGroup::GroupName':
case 'AWS::EC2::SecurityGroup::Id':
case 'AWS::EC2::Subnet::Id':
case 'AWS::EC2::Volume::Id':
case 'AWS::EC2::VPC::Id':
case 'AWS::Route53::HostedZone::Id':
case 'List<AWS::EC2::AvailabilityZone::Name>':
case 'List<AWS::EC2::Image::Id>':
case 'List<AWS::EC2::Instance::Id>':
case 'List<AWS::EC2::SecurityGroup::GroupName>':
case 'List<AWS::EC2::SecurityGroup::Id>':
case 'List<AWS::EC2::Subnet::Id>':
case 'List<AWS::EC2::Volume::Id>':
case 'List<AWS::EC2::VPC::Id>':
case 'List<AWS::Route53::HostedZone::Id>':
case 'AWS::SSM::Parameter::Name':
case 'AWS::SSM::Parameter::Value<String>':
case 'AWS::SSM::Parameter::Value<List<String>>':
case 'AWS::SSM::Parameter::Value<CommaDelimitedList>':
// TODO add the rest of the SSM types
// TODO validate these
break
default:
if (!(param.Type.startsWith('AWS:') || param.Type.startsWith('List<'))) {
throw new Error(`Unknown parameter type: ${param.Type}`);
}
}
}
}
export function transformPostImports(
root: ExtendedCfnDoc,
rootDocLocation: ImportLocation,
accumulatedImports: ImportRecord[],
options: PreprocessOptions = {}
): CfnDoc {
let globalAccum: CfnDoc;
if (options.omitMetadata) {
globalAccum = {};
} else {
// TODO add the rootDoc to the Imports record
globalAccum = {
Metadata: {
iidy: {
Host: os.hostname(),
Imports: accumulatedImports,
User: os.userInfo().username
}
}
}
};
const seedOutput: CfnDoc = {};
const isCFNDoc = root.AWSTemplateFormatVersion || root.Resources;
if (isCFNDoc) {
_.extend(globalAccum,
{
Parameters: {},
Conditions: {},
Mappings: {},
Outputs: {}
});
seedOutput.AWSTemplateFormatVersion = '2010-09-09';
}
const visitor = new Visitor();
const output = _.extend(
seedOutput,
visitor.visitNode(root, 'Root', {
GlobalAccumulator: globalAccum,
$envValues: root.$envValues || {},
Stack: [{location: rootDocLocation, path: 'Root'}]
}));
if (isCFNDoc) {
// TODO check for secondary cfn docs, or stack dependencies
_.forEach(
GlobalSectionNames,
(sectionName: GlobalSection) => {
if (!_.isEmpty(globalAccum[sectionName])) {
output[sectionName] = _.merge({}, output[sectionName], globalAccum[sectionName]);
}
});
}
// TODO merge/flatten singleton dependencies like shared custom resources
delete output.$imports;
delete output.$defs;
delete output.$envValues;
return output;
};
export async function transform(
root0: ExtendedCfnDoc,
rootDocLocation: ImportLocation,
options: PreprocessOptions = {},
importLoader = readFromImportLocation // for mocking in tests
): Promise<CfnDoc> {
const root = _.clone(root0);
const accumulatedImports: ImportRecord[] = [];
await loadImports(root, rootDocLocation, accumulatedImports, importLoader);
return transformPostImports(root, rootDocLocation, accumulatedImports, options);
}; | the_stack |
import moment from 'moment';
import * as React from 'react';
import HelpDoc from '@/components/helpDoc';
import {
COLLECTION_BPS_UNIT_TYPE,
SOURCE_INPUT_BPS_UNIT_TYPE,
UNIT_TYPE,
METRIC_STATUS_TYPE,
DATA_SOURCE_TEXT,
CHARTS_COLOR,
TASK_TYPE_ENUM,
DATA_SOURCE_ENUM,
} from '@/constant';
import stream from '@/api';
import { Utils } from '@dtinsight/dt-utils/lib';
import { Alert, Radio, Tooltip, Row, Col } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { compact, cloneDeep, chunk } from 'lodash';
import GraphTimeRange from '@/components/graphTime/graphTimeRange';
import GraphTimePicker from '@/components/graphTime/graphTimePicker';
import AlarmBaseGraph from './baseGraph';
import DataDelay from './dataDelay';
import MetricSelect from './metricSelect';
import './index.scss';
const Api = {
checkSourceStatus: (params: any) => Promise.resolve({ code: 1, data: null }),
getMetricStatus: (params: any) =>
Promise.resolve({
code: 1,
message: null,
data: { status: 1, msg: null },
space: 0,
version: null,
success: true,
}),
};
const defaultTimeValue = '10m';
export const metricsType = {
FAILOVER_RATE: 'fail_over_rate',
FAILOVER_HISTORY: 'fail_over_history',
DELAY: 'data_delay',
SOURCE_TPS: 'source_input_tps',
SINK_OUTPUT_RPS: 'sink_output_rps',
SOURCE_RPS: 'source_input_rps',
SOURCE_INPUT_BPS: 'source_input_bps',
SOURCE_DIRTY: 'source_dirty_data',
SOURCE_DIRTY_OUT: 'source_dirty_out',
DATA_COLLECTION_RPS: 'data_acquisition_rps',
DATA_COLLECTION_BPS: 'data_acquisition_bps',
DATA_DISABLE_TPS: 'data_discard_tps',
DATA_DISABLE_COUNT: 'data_discard_count',
DATA_COLLECTION_TOTAL_RPS: 'data_acquisition_record_sum',
DATA_COLLECTION_TOTAL_BPS: 'data_acquisition_byte_sum',
};
const defaultLineData: any = {
x: [],
y: [[]],
loading: true,
};
const defaultData: any = {
[metricsType.FAILOVER_HISTORY]: defaultLineData,
[metricsType.DELAY]: defaultLineData,
[metricsType.SOURCE_TPS]: defaultLineData,
[metricsType.SINK_OUTPUT_RPS]: defaultLineData,
[metricsType.SOURCE_RPS]: defaultLineData,
[metricsType.SOURCE_INPUT_BPS]: defaultLineData,
[metricsType.SOURCE_DIRTY]: defaultLineData,
[metricsType.SOURCE_DIRTY_OUT]: defaultLineData,
[metricsType.DATA_COLLECTION_RPS]: defaultLineData,
[metricsType.DATA_COLLECTION_BPS]: defaultLineData,
[metricsType.DATA_DISABLE_TPS]: defaultLineData,
[metricsType.DATA_DISABLE_COUNT]: defaultLineData,
[metricsType.DATA_COLLECTION_TOTAL_RPS]: defaultLineData,
[metricsType.DATA_COLLECTION_TOTAL_BPS]: defaultLineData,
};
function matchSourceInputUnit(metricsData: any = {}, type: string) {
function matchType(type: string, key: UNIT_TYPE) {
switch (type) {
case metricsType.DATA_COLLECTION_TOTAL_BPS: {
unit = COLLECTION_BPS_UNIT_TYPE[key];
break;
}
case metricsType.SOURCE_INPUT_BPS:
case metricsType.DATA_COLLECTION_BPS: {
unit = SOURCE_INPUT_BPS_UNIT_TYPE[key];
break;
}
}
}
const { y = [[]] } = metricsData;
let unit: string | undefined = '';
const depth = type == metricsType.SOURCE_INPUT_BPS ? 2 : 1;
const dataFlat = y.flat(depth) || [];
const maxVal = Math.max.apply(null, dataFlat);
const isBps = maxVal < 1024;
const isKbps = dataFlat.some((item: any) => item >= 1024 && item < Math.pow(1024, 2));
const isMbps = dataFlat.some(
(item: any) => item >= Math.pow(1024, 2) && item < Math.pow(1024, 3),
);
const isGbps = dataFlat.some(
(item: any) => item >= Math.pow(1024, 3) && item < Math.pow(1024, 4),
);
const isTbps = dataFlat.some((item: any) => item >= Math.pow(1024, 4));
if (isBps) {
matchType(type, UNIT_TYPE.B);
} else if (isKbps) {
matchType(type, UNIT_TYPE.KB);
} else if (isMbps) {
matchType(type, UNIT_TYPE.MB);
} else if (isGbps) {
matchType(type, UNIT_TYPE.GB);
} else if (isTbps) {
matchType(type, UNIT_TYPE.TB);
} else {
matchType(type, UNIT_TYPE.B);
}
return unit;
}
interface IProps {
data: any;
graph: { taskMetrics: any };
}
const initState = {
lineDatas: defaultData,
sourceStatusList: [] as any,
time: defaultTimeValue,
endTime: moment(),
metricValue: undefined as undefined | string,
metricLists: [],
metricDatas: {} as any,
metricStatus: {
status: METRIC_STATUS_TYPE.NORMAL, // 正常 1, 异常 2
msg: '',
},
tabKey: 'OverView',
};
type IState = typeof initState;
export default class StreamDetailGraph extends React.Component<IProps & any, IState> {
constructor(props: any) {
super(props);
this.state = {
lineDatas: defaultData,
sourceStatusList: [],
time: defaultTimeValue,
endTime: moment(),
metricValue: undefined,
metricLists: [],
metricDatas: {},
metricStatus: {
status: METRIC_STATUS_TYPE.NORMAL, // 正常 1, 异常 2
msg: '',
},
tabKey: 'OverView',
};
}
componentDidMount() {
this.getMetricValues();
this.initGraph();
this.checkSourceStatus();
this.checkMetricStatus();
}
// eslint-disable-next-line
UNSAFE_componentWillReceiveProps(nextProps: any) {
const data = nextProps.data;
const oldData = this.props.data;
if (oldData && data && oldData.id !== data.id) {
this.clear(() => {
this.initGraph(data);
this.checkSourceStatus(data);
this.getMetricValues(data);
this.checkMetricStatus(data);
});
}
}
clear(callback?: () => void) {
this.setState(
{
lineDatas: defaultData,
sourceStatusList: [],
time: defaultTimeValue,
endTime: moment(),
metricValue: undefined,
metricLists: [],
metricDatas: {},
tabKey: 'OverView',
},
callback,
);
}
// 获取 metric 状态
checkMetricStatus = (data?: any) => {
data = data || this.props.data;
if (!data?.id) {
return;
}
Api.getMetricStatus({
taskId: data?.id,
}).then((res: any) => {
const { code, data } = res;
if (code === 1) {
this.setState({ metricStatus: data });
}
});
};
// 获取指标列表
getMetricValues = (data?: any) => {
data = data || this.props.data;
if (!data.id) {
return;
}
stream
.getMetricValues({
taskId: data?.id,
})
.then((res: any) => {
const { code, data } = res;
if (code === 1) {
const metricLists = (data || []).map((item: string) => ({
text: item,
value: item,
}));
this.setState({ metricLists });
}
});
};
// 初始化缓存中有的自定义metrics
initCustomMetrics = (data?: any) => {
data = data || this.props.data;
if (!data.id) {
return;
}
const metrics = this.props.graph?.taskMetrics?.[data.id];
Array.isArray(metrics) &&
metrics.forEach((chartName: string) => {
this.queryTaskMetrics(chartName, data.id);
});
};
// 查询指标数据
queryTaskMetrics = (chartName: string, id: number) => {
const { time, endTime } = this.state;
stream
.queryTaskMetrics({
taskId: id,
chartName,
timespan: time,
end: endTime.valueOf(),
})
.then((res: any) => {
const { code, data } = res;
if (code === 1) {
this.setMetricData(chartName, data || []);
}
});
};
// 格式化数据
setMetricData = (chartName: string, data: any[]) => {
const { metricDatas } = this.state;
let xAxis: Array<any> = [];
let yAxis: Array<any> = [];
let legend: string[] = [];
data.forEach((item: any) => {
const { metric, values } = item;
const { x, y } = this.setChartValue(values);
const key = this.setMetricKey(metric);
if (xAxis.length === 0) {
xAxis = x;
}
yAxis.push(y);
legend.push(key);
});
const options = this.setCustomMetricOptions();
this.setState({
metricDatas: {
...metricDatas,
[chartName]: {
loading: false,
legend,
x: xAxis,
y: yAxis,
...options,
},
},
});
};
// 格式化图例名
setMetricKey = (metric: any): string => {
if (metric === undefined) {
return '';
}
const NAME_KEY = '__name__';
const SHOW_KEYS = ['job_id', 'job_name', 'exported_job', 'operator_name'];
const key = Object.entries(metric)
.filter((item: any[]) => SHOW_KEYS.includes(item[0]))
.map((item: any) => `${item[0]}="${item[1]}"`)
.join(', ');
return metric[NAME_KEY] + '{' + key + '}';
};
// 处理横纵坐标数据
setChartValue = (values: any[]) => {
let x: Array<string | number> = [];
let y: Array<string | number> = [];
Array.isArray(values) &&
values.forEach((value: any) => {
x.push(value.time);
y.push(value.value);
});
return { x, y };
};
// 设置自定义metric的Option
setCustomMetricOptions = () => {
const legendOption = {
left: '3%',
right: '4%',
top: '75%',
orient: 'vertical',
textStyle: {
width: 200,
overflow: 'truncate',
ellipsis: '...',
},
tooltip: {
show: true,
formatter: function (params: any) {
const { __name__, content } = breakUpParams(params.name);
return `<div><span>${__name__}</span><br/>${content}</div>`;
},
},
};
const gridOption = {
bottom: '30%',
};
const tooltipOption = {
trigger: 'item',
axisPointer: {
type: 'cross',
span: true,
},
formatter: function (params: any) {
const { seriesName, marker, name, value } = params;
const { __name__, content } = breakUpParams(seriesName);
return `<div><span>${moment(Number(name)).format(
'YYYY-MM-DD HH:mm:ss',
)}</span><br/><span>${marker}${__name__}: <span style="font-weight: 'bold'">${value}</span></span><br/>${content}</div>`;
},
};
return { legendOption, gridOption, tooltipOption };
// 参数拆分
function breakUpParams(seriesName: string) {
const [__name__, param] = seriesName.split('{');
const keys = param
.slice(0, -1)
.split(', ')
.map((item) => item.split('='));
let content = '';
keys.forEach(([key, value]) => {
content += `<span style="font-weight: bold">${key}</span>: <span>${value}</span><br/>`;
});
return { __name__, content };
}
};
checkSourceStatus(data?: any) {
data = data || this.props.data;
if (!data.id) {
return;
}
Api.checkSourceStatus({
taskId: data.id,
}).then((res: any) => {
if (res.code == 1) {
let data = res.data || {};
this.setState({
sourceStatusList: Object.entries(data),
});
}
});
}
setLineData(data = []) {
const { lineDatas } = this.state;
let stateLineData: any = { ...lineDatas };
for (let i = 0; i < data.length; i++) {
let item: any = data[i];
let lineData = item.data;
let type = item.chartName;
let x = [];
let y = [];
let ext: any = {};
x = lineData.map((data: any) => {
return data.time;
});
switch (type) {
case metricsType.SOURCE_INPUT_BPS:
case metricsType.SINK_OUTPUT_RPS:
case metricsType.SOURCE_TPS:
case metricsType.SOURCE_RPS:
case metricsType.SOURCE_DIRTY:
case metricsType.SOURCE_DIRTY_OUT:
case metricsType.DELAY: {
let tmpMap: any = {};
let legend = [];
for (let i = 0; i < lineData.length; i++) {
let chartData = lineData[i];
for (let key in chartData) {
if (key == 'time') {
continue;
}
if (tmpMap[key]) {
tmpMap[key].push([i, chartData[key]]);
} else {
tmpMap[key] = [[i, chartData[key]]];
}
}
}
for (let key in tmpMap) {
let datas = tmpMap[key];
y.push(datas);
legend.push(key);
}
ext.legend = legend;
break;
}
case metricsType.FAILOVER_HISTORY: {
y[0] = lineData.map((data: any) => {
return data.fail_over_history;
});
break;
}
case metricsType.DATA_COLLECTION_BPS: {
y[0] = lineData.map((data: any) => {
return data.data_acquisition_input_bps;
});
y[1] = lineData.map((data: any) => {
return data.data_acquisition_output_bps;
});
break;
}
case metricsType.DATA_COLLECTION_RPS: {
y[0] = lineData.map((data: any) => {
return data.data_acquisition_input_rps;
});
y[1] = lineData.map((data: any) => {
return data.data_acquisition_output_rps;
});
break;
}
case metricsType.DATA_DISABLE_TPS: {
y[0] = lineData.map((data: any) => {
return data.data_discard_tps;
});
break;
}
case metricsType.DATA_DISABLE_COUNT: {
y[0] = lineData.map((data: any) => {
return data.data_discard_count;
});
break;
}
case metricsType.DATA_COLLECTION_TOTAL_BPS: {
y[0] = lineData.map((data: any) => {
return data.data_acquisition_input_byte_sum;
});
y[1] = lineData.map((data: any) => {
return data.data_acquisition_output_byte_sum;
});
break;
}
case metricsType.DATA_COLLECTION_TOTAL_RPS: {
y[0] = lineData.map((data: any) => {
return data.data_acquisition_input_record_sum;
});
y[1] = lineData.map((data: any) => {
return data.data_acquisition_output_record_sum;
});
break;
}
default:
break;
}
stateLineData[type] = {
x,
y,
loading: false,
...ext,
};
}
this.setState({
lineDatas: stateLineData,
});
}
// 初始化图表
initGraph = (data?: any) => {
this.initData(data);
this.initCustomMetrics(data);
};
initData(data?: any) {
data = data || this.props.data;
if (!data.id) {
return;
}
const { taskType } = data;
const isDataCollection = taskType == TASK_TYPE_ENUM.DATA_ACQUISITION;
const { time, endTime } = this.state;
let metricsList = [];
if (isDataCollection) {
metricsList.push(metricsType.DATA_COLLECTION_BPS);
metricsList.push(metricsType.DATA_COLLECTION_RPS);
metricsList.push(metricsType.DATA_COLLECTION_TOTAL_BPS);
metricsList.push(metricsType.DATA_COLLECTION_TOTAL_RPS);
} else {
// 错误历史接口
metricsList.push(metricsType.FAILOVER_HISTORY);
metricsList.push(metricsType.DELAY);
metricsList.push(metricsType.SOURCE_TPS);
metricsList.push(metricsType.SINK_OUTPUT_RPS);
metricsList.push(metricsType.SOURCE_RPS);
metricsList.push(metricsType.SOURCE_INPUT_BPS);
metricsList.push(metricsType.SOURCE_DIRTY);
metricsList.push(metricsType.SOURCE_DIRTY_OUT);
metricsList.push(metricsType.DATA_DISABLE_COUNT);
metricsList.push(metricsType.DATA_DISABLE_TPS);
}
const successFunc = (res: any) => {
if (res.code == 1) {
this.setLineData(res.data);
}
};
for (let i = 0; i < metricsList.length; i++) {
let serverChart = metricsList[i];
// 间隔时间,防止卡顿
setTimeout(() => {
stream
.getTaskMetrics({
taskId: data.id,
timespan: time,
end: endTime.valueOf(),
chartNames: [serverChart],
})
.then(successFunc);
}, 100 + 25 * i);
}
}
renderAlertMsg() {
const { sourceStatusList = [], metricStatus } = this.state;
const { status, msg } = metricStatus;
const sourceMsg = Utils.textOverflowExchange(
sourceStatusList
.map(([sourceName, type]: any[]) => {
return `${sourceName}(${DATA_SOURCE_TEXT[type as DATA_SOURCE_ENUM]})`;
})
.join(','),
60,
);
const msgs = [
status === METRIC_STATUS_TYPE.ABNORMAL ? msg : '',
sourceMsg ? `数据源${sourceMsg}连接异常` : '',
];
const errorMsg = compact(msgs).join(', ');
return (
errorMsg && (
<Alert style={{ marginBottom: 8 }} message={errorMsg} type="warning" showIcon />
)
);
}
// 时间区间变更
graphTimeRangeChange = (time: string) => {
this.setState({ time }, this.initGraph);
};
// 自定义时间区间
graphTimeRangeInput = (value: string) => {
this.setState({ time: value }, this.initGraph);
};
// 结束时间变更
endTimeChange = (endTime: moment.Moment) => {
this.setState({ endTime }, this.initGraph);
};
// 选择metric
handleMetricSelect = (value: string) => {
if (value) {
const { data } = this.props;
// dispatch(GraphAction.saveTaskMetrics(data.id, value));
this.queryTaskMetrics(value, data.id);
this.setState({
metricValue: undefined,
});
}
};
// 删除metric
handleMetricDelete = (name: string) => {
// const { dispatch, data } = this.props;
const metricDatas: any = cloneDeep(this.state.metricDatas);
delete metricDatas[name];
this.setState({
metricDatas,
});
// dispatch(GraphAction.deleteTaskMetric(data.id, name));
};
// 刷新
refreshGraph = () => {
const initTime = {
time: defaultTimeValue,
endTime: moment(),
};
this.setState({ ...initTime }, this.initGraph);
};
render() {
const {
lineDatas,
time,
metricValue,
metricLists,
metricDatas = {},
tabKey,
endTime,
} = this.state;
const { data = {} } = this.props;
const { taskType } = data;
const isDataCollection = taskType == TASK_TYPE_ENUM.DATA_ACQUISITION;
const sourceIptUnit = matchSourceInputUnit(
{ ...lineDatas[metricsType.SOURCE_INPUT_BPS] },
metricsType.SOURCE_INPUT_BPS,
);
const colBpsUnit = matchSourceInputUnit(
{ ...lineDatas[metricsType.DATA_COLLECTION_BPS] },
metricsType.DATA_COLLECTION_BPS,
);
const colTotalBpsUnit = matchSourceInputUnit(
{ ...lineDatas[metricsType.DATA_COLLECTION_TOTAL_BPS] },
metricsType.DATA_COLLECTION_TOTAL_BPS,
);
return (
<div className="c-graph__container">
<header className="c-graph__header">
<div>{this.renderAlertMsg()}</div>
<div className="c-graph__time-picker">
<Radio.Group
style={{ marginRight: 'auto' }}
value={tabKey}
onChange={(e) => {
this.setState({ tabKey: e.target.value });
}}
>
<Radio.Button value="OverView">OverView</Radio.Button>
<Radio.Button value="WaterMark">WaterMark</Radio.Button>
{data.taskType === TASK_TYPE_ENUM.SQL && (
<Radio.Button value="dataDelay">
数据延迟
<HelpDoc
style={{
position: 'relative',
marginLeft: '5px',
right: 'initial',
top: 'initial',
marginRight: '0px',
}}
doc="delayTabWarning"
/>
</Radio.Button>
)}
<Radio.Button value="Metric">自定义Metric</Radio.Button>
</Radio.Group>
{['OverView', 'WaterMark', 'Metric'].includes(tabKey) && (
<>
<GraphTimeRange
value={time}
onRangeChange={this.graphTimeRangeChange}
onInputChange={this.graphTimeRangeInput}
/>
<GraphTimePicker
style={{ marginLeft: 20 }}
value={endTime}
timeRange={time}
onChange={this.endTimeChange}
/>
<Tooltip title="刷新">
<ReloadOutlined
onClick={this.refreshGraph.bind(this, null)}
style={{ color: '#666', marginLeft: 20, cursor: 'pointer' }}
/>
</Tooltip>
</>
)}
</div>
</header>
<div className="c-graph__content">
{tabKey === 'OverView' && (
<>
{isDataCollection ? (
<>
<div className="alarm-graph-row">
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.DATA_COLLECTION_RPS],
color: CHARTS_COLOR,
unit: 'rps',
legend: ['输入RPS', '输出RPS'],
}}
desc="输入/输出数据量,单位是RecordPerSecond。"
title="输入/输出RPS"
/>
</section>
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.DATA_COLLECTION_BPS],
color: CHARTS_COLOR,
unit: colBpsUnit,
legend: [
`输入${colBpsUnit.toLocaleUpperCase()}`,
`输出${colBpsUnit.toLocaleUpperCase()}`,
],
metricsType: metricsType.DATA_COLLECTION_BPS,
}}
desc="输入/输出数据量,单位是BytePerSecond。"
title="输入/输出BPS"
/>
</section>
</div>
<div className="alarm-graph-row">
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[
metricsType.DATA_COLLECTION_TOTAL_RPS
],
color: CHARTS_COLOR,
unit: '条',
legend: ['累计输入记录数', '累计输出记录数'],
}}
desc="累计输入/输出记录数,单位是条"
title="累计输入/输出记录数"
/>
</section>
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[
metricsType.DATA_COLLECTION_TOTAL_BPS
],
color: CHARTS_COLOR,
unit: colTotalBpsUnit,
legend: ['累计输入数据量', '累计输出数据量'],
metricsType:
metricsType.DATA_COLLECTION_TOTAL_BPS,
}}
desc="累计输入/输出数据量,单位是Bytes或其他存储单位"
title="累计输入/输出数据量"
/>
</section>
</div>
</>
) : (
<>
<div className="alarm-graph-row">
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.FAILOVER_HISTORY],
color: CHARTS_COLOR,
legend: ['History'],
}}
desc="当前任务出现 Failover(错误或者异常)的历史记录"
title="FailOver History"
/>
</section>
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.DELAY],
color: CHARTS_COLOR,
unit: 's',
}}
desc="业务延时 = 当前系统时间 – 当前系统处理的最后一条数据的事件时间(Event time)"
title="业务延时"
/>
</section>
</div>
<div className="alarm-graph-row">
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.SOURCE_RPS],
color: CHARTS_COLOR,
unit: 'rps',
}}
desc="对流式数据输入(Kafka)进行统计,单位是RPS(Record Per Second)。"
title="各Source的RPS数据输入"
/>
</section>
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.SOURCE_DIRTY],
color: CHARTS_COLOR,
}}
desc="各Source的脏数据,反映实时计算 Flink的Source段是否有脏数据的情况。"
title="各Source的脏数据"
/>
</section>
</div>
<div className="alarm-graph-row">
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.SINK_OUTPUT_RPS],
color: CHARTS_COLOR,
unit: 'rps',
}}
desc="对流式数据输出至MySQL、HBase、ElasticSearch等第三方存储系统的数据输出量,单位是RPS(Record Per Second)。"
title="各Sink的RPS数据输出"
/>
</section>
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.SOURCE_DIRTY_OUT],
color: CHARTS_COLOR,
}}
desc="各Sink的脏数据,反映实时计算 Flink的Sink段脏数据产生情况"
title="各Sink的脏数据输出"
/>
</section>
</div>
<div className="alarm-graph-row">
<section>
<AlarmBaseGraph
time={time}
lineData={{
color: CHARTS_COLOR,
...lineDatas[metricsType.SOURCE_TPS],
unit: 'tps',
}}
desc="对流式数据输入(Kafka)进行统计,单位是TPS(Transaction Per Second)。"
title="各Source的TPS数据输入"
/>
</section>
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.SOURCE_INPUT_BPS],
color: CHARTS_COLOR,
unit: sourceIptUnit,
metricsType: metricsType.SOURCE_INPUT_BPS,
}}
desc="对流式数据输入(Kafka)进行统计,单位是BPS(Byte Per Second),系统会根据实际数据量自动转化单位,如Mbps、Gbps。"
title="各Source的BPS数据输入"
/>
</section>
</div>
</>
)}
</>
)}
{tabKey === 'WaterMark' && (
<div className="alarm-graph-row">
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.DATA_DISABLE_TPS],
color: CHARTS_COLOR,
legend: ['数据迟到丢弃TPS'],
}}
desc="基于事件时间(EventTime)的流任务中,如果element的事件时间迟于允许的最大延迟时间,在窗口相关的操作中,该element将会被丢弃。"
title="数据迟到丢弃TPS"
/>
</section>
<section>
<AlarmBaseGraph
time={time}
lineData={{
...lineDatas[metricsType.DATA_DISABLE_COUNT],
color: CHARTS_COLOR,
legend: ['数据迟到累计丢弃数'],
}}
desc="数据因迟到被丢弃的累计数量。"
title="数据迟到累计丢弃数"
/>
</section>
</div>
)}
{tabKey === 'dataDelay' && <DataDelay data={data} tabKey={tabKey} />}
{tabKey === 'Metric' && (
<>
<MetricSelect
style={{ padding: '0 0 2px 2px' }}
placeholder="请选择Metric"
enterButton="Add Metric"
value={metricValue}
options={metricLists}
onChange={(value: string) => this.setState({ metricValue: value })}
onOk={this.handleMetricSelect}
/>
{chunk(Object.keys(metricDatas), 2).map(
(row: string[], index: number) => (
<Row
key={index}
gutter={10}
style={{ marginTop: 10, paddingLeft: 2 }}
className="alarm-graph-row"
>
{row.map((name: string) => (
<Col key={name} span={12}>
<AlarmBaseGraph
time={time}
lineData={{
...metricDatas[name],
color: CHARTS_COLOR,
}}
title={name}
allowDelete
onDelete={() => this.handleMetricDelete(name)}
/>
</Col>
))}
</Row>
),
)}
</>
)}
</div>
</div>
);
}
} | the_stack |
import * as dawg from '@/dawg';
import Vue from 'vue';
import * as t from '@/lib/io';
import { User } from 'firebase';
import backend, { ProjectInfo } from '@/extra/backup/backend';
import auth from '@/extra/backup/auth';
import firebase from 'firebase/app';
import 'firebase/database';
import 'firebase/auth';
import { computed, watch, ref, createComponent } from '@vue/composition-api';
import * as framework from '@/lib/framework';
import { project, ProjectType, IProject } from '@/core/project';
import { createExtension } from '@/lib/framework/extensions';
import { copy } from '@/lib/std';
export const extension = createExtension({
id: 'dawg.backup',
workspace: {
backup: {
type: t.boolean,
default: false,
},
},
activate(context) {
firebase.initializeApp({
apiKey: 'AIzaSyCg8BcL3EbQpOpXFLwMx4h6XmdKtStVKhU',
authDomain: 'dawg-backup.firebaseapp.com',
databaseURL: 'https://dawg-backup.firebaseio.com',
projectId: 'dawg-backup',
storageBucket: 'dawg-backup.appspot.com',
messagingSenderId: '540203128797',
});
const user = ref<User>();
const projects = ref<ProjectInfo[]>([]);
const error = ref<string>();
const syncing = ref(false);
const icon = computed(() => {
if (!backup.value) {
return 'cloud_off';
} else if (error.value) {
return 'error_outline';
} else if (syncing.value) {
return 'cloud_queue';
} else {
return 'cloud_done';
}
});
const tooltip = computed((): string => {
if (!backup.value) {
return 'Cloud Backup Disabled';
} else if (error.value) {
return error.value;
} else if (syncing.value) {
return 'Backup In Progress';
} else {
return 'Cloud Backup Enabled';
}
});
// flex centers the icons which is why we add it
const component = Vue.extend(createComponent({
props: {},
template: `
<dg-mat-icon
v-if="error"
class="flex text-default text-sm"
title="Cloud Backup Error"
icon="error_outline"
></dg-mat-icon>
<dg-spinner
v-else-if="syncing"
class="flex text-default w-4 h-4"
title="Syncing Backup"
></dg-spinner>
<dg-mat-icon
v-else
class="flex text-default text-sm"
:icon="icon"
:title="tooltip"
></dg-mat-icon>
`,
setup() {
return {
icon,
tooltip,
syncing,
theme: dawg.theme,
error,
};
},
}));
framework.ui.statusBar.push({
component,
position: 'right',
order: 1,
});
async function loadProjects(u: User) {
const res = await backend.getProjects(u);
if (res.type === 'success') {
projects.value = res.projects;
}
if (res.type === 'error') {
dawg.notify.error(res.message);
}
}
function backupAction(mode: 'open' | 'delete') {
handleUnauthenticated(async (u) => {
await loadProjects(u);
const projectLookup: { [name: string]: ProjectInfo } = {};
projects.value.forEach((p) => {
projectLookup[p.name] = p;
});
dawg.palette.selectFromObject(projectLookup, {
placeholder: 'Available Projects',
onDidInput: (projectInfo) => {
switch (mode) {
case 'delete':
deleteProject(projectInfo);
break;
case 'open':
openProject(projectInfo);
break;
}
},
});
});
}
async function openProject(info: ProjectInfo) {
handleUnauthenticated(async (u) => {
const res = await backend.getProject(u, info.id);
if (res.type === 'not-found') {
dawg.notify.warning('Uh, we were unable to find your project');
return;
}
if (res.type === 'error') {
dawg.notify.error('Unable to get project', { detail: res.message, duration: Infinity });
return;
}
const result = dawg.io.decodeItem(ProjectType, res.project);
if (result.type === 'error') {
dawg.notify.error('Unable to parse project from backup', {
detail: result.message,
duration: Infinity,
});
return;
}
dawg.project.openTempProject(result.decoded);
});
}
function handleUnauthenticated(authenticated: (user: User) => void) {
if (!user.value) {
dawg.notify.info('Please login first', { detail: 'Use the settings icon in the Activity Bar.' });
return;
}
authenticated(user.value);
}
function deleteProject(info: ProjectInfo) {
handleUnauthenticated(async (u) => {
const res = await backend.deleteProject(u, info.id);
if (res.type === 'success') {
// We are not taking advantage of firebase here
// Ideally firebase would send an event and we would update our project list
// Until we do that, this will suffice
projects.value = projects.value.filter((maybe) => maybe !== info);
} else if (res.type === 'not-found') {
dawg.notify.info(`Unable to delete ${info.name}`, { detail: 'The project was not found.' });
} else {
dawg.notify.info(`Unable to delete ${info.name}`, { detail: res.message });
}
});
}
async function updateProject(encoded: IProject) {
if (!backup.value) {
return;
}
if (!user.value) {
return;
}
if (encoded.name === '') {
dawg.notify.info('Please give your project a name to backup.');
return;
}
syncing.value = true;
// Copy because we can't upload undefined values to firebase
// Copying will remove these key/value pairs
const copyOfProject = copy(encoded);
const backupStatus = await backend.updateProject(user.value, encoded.id, copyOfProject);
switch (backupStatus.type) {
case 'error':
dawg.notify.error('Unable to backup', { detail: backupStatus.message, duration: Infinity });
error.value = 'Unable to backup';
break;
case 'success':
// Make sure to set it back to false if there was an error previously
error.value = undefined;
break;
}
// Just so the upload is always perceivable to the user!
setTimeout(() => syncing.value = false, 1000);
}
const backup = context.workspace.backup;
watch([backup, user], async () => {
updateProject(await dawg.project.serialize());
});
try {
auth.watchUser({
authenticated: (u) => {
projects.value = [];
user.value = u;
},
unauthenticated: () => {
projects.value = [];
user.value = undefined;
},
});
} catch (e) {
// Ignore this error, it means we can't connect to the server (ie. internet is down)
}
const open = dawg.menubar.defineMenuBarItem({
menu: 'File',
section: '0_newOpen',
text: 'Open From Backup',
callback: () => backupAction('open'),
});
context.subscriptions.push(dawg.commands.registerCommand(open));
context.subscriptions.push(dawg.menubar.addToMenu(open));
context.subscriptions.push(dawg.commands.registerCommand({
text: 'Delete Backup',
callback: () => backupAction('delete'),
}));
context.subscriptions.push(dawg.project.onDidSave(updateProject));
const googleButton = Vue.extend(createComponent({
props: {},
template: `
<div>
<google-button @click="signInOrSignOut">
{{ text }}
</google-button>
</div>
`,
setup() {
const logout = () => {
try {
auth.logout();
backup.value = false;
projects.value = [];
} catch (e) {
dawg.notify.error('Unable to sign out of Google.', { detail: e.message });
}
};
const signIn = () => {
try {
auth.signIn();
} catch (e) {
dawg.notify.error('Unable to sign into Google.', { detail: e.message });
}
};
const text = computed(() => {
if (user.value) {
return 'Sign Out';
} else {
return 'Sign in with Google';
}
});
const signInOrSignOut = () => {
if (user.value) {
logout();
} else {
signIn();
}
};
return {
text,
signInOrSignOut,
authenticated: computed(() => !!user.value),
};
},
}));
const name = computed(() => {
if (user.value) {
return user.value.displayName;
}
});
context.settings.push({
label: 'Google Login',
description: computed(() => {
if (name.value) {
return `Currently logged in as \`${name.value}\``;
} else {
return `Login with google.`;
}
}),
type: 'component',
component: googleButton,
});
const projectName = project.name;
const either = computed(() => !projectName.value || !user.value);
const both = computed(() => !projectName.value && !user.value);
const description = computed(() => {
let value = 'Whether to sync this project to the cloud.';
if (either.value) {
value += ' Before you can enable this, please ';
}
if (!project.name.value) {
value += 'give your project a name';
}
if (both.value) {
value += ' and ';
}
if (!user.value) {
value += 'login using your Google Account';
}
if (either.value) {
value += '.';
}
return value;
});
context.settings.push({
label: 'Cloud Backup',
description,
type: 'boolean',
value: backup,
disabled: either,
checkedValue: 'Syncing',
uncheckedValue: 'Not Syncing',
});
},
}); | the_stack |
import * as THREE from 'three';
import memoizeOne from 'memoize-one';
import {v4} from 'uuid';
import stringHash from 'string-hash';
import {clamp} from 'lodash';
import copyToClipboard from 'copy-to-clipboard';
import {
AnyProperties,
castMapProperties,
castMiniProperties,
DriveMetadata,
GridType,
isTemplateMetadata,
MapProperties,
MiniProperties,
ScenarioObjectProperties,
TemplateProperties
} from './googleDriveUtils';
import {CommsStyle} from './commsNode';
import * as constants from './constants';
import {TabletopPathPoint} from '../presentation/tabletopPathComponent';
import {ConnectedUserUsersType} from '../redux/connectedUserReducer';
import {buildEuler, buildVector3, isColourDark, reverseEuler} from './threeUtils';
import {isCloseTo} from './mathsUtils';
import {PaintToolEnum} from '../presentation/paintTools';
export interface WithMetadataType<T extends AnyProperties> {
metadata: DriveMetadata<void, T>;
}
export interface ObjectVector2 {
x: number;
y: number;
}
export interface ObjectVector3 {
x: number;
y: number;
z: number;
}
export interface ObjectEuler {
x: number;
y: number;
z: number;
order: string;
// For backwards compatibility - should be able to remove eventually.
_x?: number;
_y?: number;
_z?: number;
_order?: string;
}
export interface MapPaintOperation {
operationId: string;
selected: PaintToolEnum;
points: ObjectVector2[];
brushSize: number;
brushColour: string;
}
export interface MapPaintLayer {
operations: MapPaintOperation[];
}
export interface MapType extends WithMetadataType<MapProperties> {
name: string;
position: ObjectVector3;
rotation: ObjectEuler;
gmOnly: boolean;
selectedBy: string | null;
fogOfWar?: number[];
cameraFocusPoint?: ObjectVector3;
paintLayers: MapPaintLayer[];
transparent: boolean;
}
export type MovementPathPoint = ObjectVector3 & {elevation?: number, onMapId?: string};
export enum PieceVisibilityEnum {
HIDDEN = 1, FOGGED = 2, REVEALED = 3
}
export const MINI_VISIBILITY_OPTIONS = [
{displayName: 'Hide', value: PieceVisibilityEnum.HIDDEN},
{displayName: 'Fog', value: PieceVisibilityEnum.FOGGED},
{displayName: 'Show', value: PieceVisibilityEnum.REVEALED}
];
export type PiecesRosterValue = string | number | PiecesRosterFractionValue | boolean[];
export type PiecesRosterValues = {[columnId: string]: PiecesRosterValue | undefined};
export interface MiniType<T = MiniProperties | TemplateProperties> extends WithMetadataType<T> {
name: string;
position: ObjectVector3;
movementPath?: MovementPathPoint[];
rotation: ObjectEuler;
scale: number;
elevation: number;
visibility: PieceVisibilityEnum;
gmOnly: boolean;
selectedBy: string | null;
prone: boolean;
flat: boolean;
locked: boolean;
attachMiniId?: string;
hideBase: boolean;
baseColour?: number;
onMapId?: string;
piecesRosterValues: PiecesRosterValues;
piecesRosterGMValues: PiecesRosterValues;
piecesRosterSimple: boolean;
gmNoteMarkdown?: string;
}
export interface ScenarioType {
snapToGrid: boolean;
confirmMoves: boolean;
maps: {[key: string]: MapType};
minis: {[key: string]: MiniType};
startCameraAtOrigin?: boolean;
headActionIds: string[];
playerHeadActionIds: string[];
}
export enum DistanceMode {
STRAIGHT = 'STRAIGHT',
GRID_DIAGONAL_ONE_ONE = 'GRID_DIAGONAL_ONE_ONE',
GRID_DIAGONAL_THREE_EVERY_TWO = 'GRID_DIAGONAL_THREE_EVERY_TWO'
}
export enum DistanceRound {
ONE_DECIMAL = 'ONE_DECIMAL',
ROUND_OFF = 'ROUND_OFF',
ROUND_UP = 'ROUND_UP',
ROUND_DOWN = 'ROUND_DOWN'
}
export interface TabletopUserPreferencesType {
dieColour: string;
}
export interface TabletopUserControlType {
whitelist: string[];
blacklist: string[];
}
export enum PiecesRosterColumnType {
INTRINSIC = 'intrinsic',
STRING = 'string',
NUMBER = 'number',
BONUS = 'bonus',
FRACTION = 'fraction'
}
export interface PiecesRosterBaseColumn {
id: string;
name: string;
gmOnly: boolean;
showNear?: boolean;
}
export interface PiecesRosterIntrinsicColumn {
type: PiecesRosterColumnType.INTRINSIC;
}
export interface PiecesRosterStringColumn {
type: PiecesRosterColumnType.STRING;
}
export interface PiecesRosterNumberColumn {
type: PiecesRosterColumnType.NUMBER | PiecesRosterColumnType.BONUS;
}
export interface PiecesRosterFractionValue {
numerator?: number;
denominator: number;
}
export interface PiecesRosterFractionColumn {
type: PiecesRosterColumnType.FRACTION;
}
// export interface PiecesRosterStatusColumn {
// type: PiecesRosterColumnType.STATUS;
// icons: {
// icon: string;
// url: boolean;
// }[];
// }
export type PiecesRosterColumn = PiecesRosterBaseColumn & (
PiecesRosterIntrinsicColumn | PiecesRosterStringColumn | PiecesRosterNumberColumn | PiecesRosterFractionColumn // | PiecesRosterStatusColumn
);
export interface TabletopType {
gm: string;
gmSecret: string | null;
gmOnlyPing: boolean;
defaultGrid: GridType;
distanceMode: DistanceMode;
distanceRound: DistanceRound;
gridScale?: number;
gridUnit?: string;
commsStyle: CommsStyle;
baseColourSwatches?: string[];
templateColourSwatches?: string[];
gridColourSwatches?: string[];
paintToolColourSwatches?: string[];
tabletopLockedPeerId?: string;
tabletopUserControl?: TabletopUserControlType;
lastSavedHeadActionIds: null | string[];
lastSavedPlayerHeadActionIds: null | string[];
videoMuted: {[metadataId: string]: boolean};
userPreferences: {[key: string]: TabletopUserPreferencesType};
piecesRosterColumns: PiecesRosterColumn[];
}
function replaceMetadataWithId(all: {[key: string]: any}): {[key: string]: any} {
return Object.keys(all).reduce((result, guid) => {
result[guid] = {
...all[guid],
metadata: {id: all[guid].metadata.id, resourceKey: all[guid].metadata.resourceKey}
};
return result;
}, {});
}
function filterObject<T>(object: {[key: string]: T}, filterFn: (object: T) => (T | undefined)) {
return Object.keys(object).reduce((result, key) => {
const filtered = filterFn(object[key]);
if (filtered) {
result[key] = filtered;
}
return result;
}, {});
}
export function scenarioToJson(scenario: ScenarioType): ScenarioType[] {
// Split the scenario into private (everything) and public information.
const maps = replaceMetadataWithId(scenario.maps);
const minis = replaceMetadataWithId(scenario.minis);
return [
{
snapToGrid: scenario.snapToGrid,
confirmMoves: scenario.confirmMoves,
startCameraAtOrigin: scenario.startCameraAtOrigin,
maps,
minis,
headActionIds: scenario.playerHeadActionIds,
playerHeadActionIds: scenario.playerHeadActionIds
},
{
snapToGrid: scenario.snapToGrid,
confirmMoves: scenario.confirmMoves,
startCameraAtOrigin: scenario.startCameraAtOrigin,
maps: filterObject(maps, (map: MapType) => (map.gmOnly ? undefined : map)),
minis: filterObject(minis, (mini: MiniType) => (mini.gmOnly ? undefined : {...mini, piecesRosterGMValues: {}, gmNoteMarkdown: undefined})),
headActionIds: scenario.headActionIds,
playerHeadActionIds: scenario.playerHeadActionIds
}
]
}
function updateMetadata<T = ScenarioObjectProperties>(fullDriveMetadata: {[key: string]: DriveMetadata}, object: {[key: string]: WithMetadataType<T>}, converter: (properties: T) => T) {
Object.keys(object).forEach((id) => {
const metadata = fullDriveMetadata[object[id].metadata.id] as DriveMetadata<void, T>;
if (metadata) {
object[id] = {...object[id], metadata: {...metadata, properties: converter(metadata.properties)}};
}
});
}
export const INITIAL_PIECES_ROSTER_COLUMNS: PiecesRosterColumn[] = [
{name: 'Name', id: v4(), gmOnly: false, showNear: true, type: PiecesRosterColumnType.INTRINSIC},
{name: 'Focus', id: v4(), gmOnly: false, type: PiecesRosterColumnType.INTRINSIC},
{name: 'Visibility', id: v4(), gmOnly: true, type: PiecesRosterColumnType.INTRINSIC},
{name: 'Locked', id: v4(), gmOnly: true, type: PiecesRosterColumnType.INTRINSIC}
];
export function jsonToScenarioAndTabletop(combined: ScenarioType & TabletopType, fullDriveMetadata: {[key: string]: DriveMetadata}): [ScenarioType, TabletopType] {
Object.keys(combined.minis).forEach((miniId) => {
const mini = combined.minis[miniId];
// Convert minis with old-style startingPosition point to movementPath array
if (mini['startingPosition']) {
mini.movementPath = [mini['startingPosition']];
delete(mini['startingPosition']);
}
// If missing, set visibility based on gmOnly
if (mini.visibility === undefined) {
mini.visibility = (mini.gmOnly) ? PieceVisibilityEnum.HIDDEN : PieceVisibilityEnum.REVEALED;
}
});
Object.keys(combined.maps).forEach((mapId) => {
const map = combined.maps[mapId];
// Add empty paintLayers if missing
if (!map.paintLayers) {
map.paintLayers = [];
}
});
// Check for id-only metadata
updateMetadata(fullDriveMetadata, combined.maps, castMapProperties);
updateMetadata(fullDriveMetadata, combined.minis, castMiniProperties);
// Convert old-style lastActionId to headActionIds
const headActionIds = combined.headActionIds ? combined.headActionIds : [combined['lastActionId'] || 'legacyAction'];
const playerHeadActionIds = combined.playerHeadActionIds ? combined.playerHeadActionIds : [combined['lastActionId'] || 'legacyAction'];
// Update/default piecesRosterColumns if necessary.
const piecesRosterColumns = combined.piecesRosterColumns || INITIAL_PIECES_ROSTER_COLUMNS;
const nameColumn = piecesRosterColumns.find(isNameColumn);
if (nameColumn && nameColumn.showNear === undefined) {
nameColumn.showNear = true;
}
// Return scenario and tabletop
return [
{
snapToGrid: combined.snapToGrid,
confirmMoves: combined.confirmMoves,
startCameraAtOrigin: combined.startCameraAtOrigin,
maps: combined.maps,
minis: combined.minis,
headActionIds,
playerHeadActionIds
},
{
gm: combined.gm,
gmSecret: combined.gmSecret,
gmOnlyPing: combined.gmOnlyPing === undefined ? false : combined.gmOnlyPing,
defaultGrid: combined.defaultGrid || GridType.SQUARE,
distanceMode: combined.distanceMode,
distanceRound: combined.distanceRound,
gridScale: combined.gridScale,
gridUnit: combined.gridUnit,
commsStyle: combined.commsStyle || CommsStyle.PeerToPeer,
baseColourSwatches: combined.baseColourSwatches,
templateColourSwatches: combined.templateColourSwatches,
gridColourSwatches: combined.gridColourSwatches,
paintToolColourSwatches: combined.paintToolColourSwatches,
lastSavedHeadActionIds: null,
lastSavedPlayerHeadActionIds: null,
tabletopLockedPeerId: combined.tabletopLockedPeerId,
tabletopUserControl: combined.tabletopUserControl,
videoMuted: combined.videoMuted || {},
userPreferences: combined.userPreferences || {},
piecesRosterColumns
}
];
}
export function getAllScenarioMetadataIds(scenario: ScenarioType): string[] {
const metadataMap = Object.keys(scenario.maps).reduce((all, mapId) => {
all[scenario.maps[mapId].metadata.id] = true;
return all;
}, Object.keys(scenario.minis).reduce((all, miniId) => {
all[scenario.minis[miniId].metadata.id] = true;
return all;
}, {}));
return Object.keys(metadataMap);
}
function isAboveHexDiagonal(coordStraight: number, coordZigzag: number, hexStraight: number, hexZigzag: number, hexStraightSize: number, hexZigzagSize: number)
{
if ((hexZigzag%3) !== 0) {
return false;
} else if ((hexStraight + hexZigzag)&1) {
return (coordZigzag < hexZigzagSize / 3 * (coordStraight / hexStraightSize + hexZigzag - hexStraight));
} else {
return (coordZigzag < hexZigzagSize / 3 * (1 + hexZigzag + hexStraight - coordStraight / hexStraightSize));
}
}
export function getGridStride(type: GridType, half: boolean = true) {
switch (type) {
case GridType.HEX_VERT:
return half ? {strideX: constants.SQRT3 / 2, strideY: 0.5} : {strideX: constants.SQRT3, strideY: 1};
case GridType.HEX_HORZ:
return half ? {strideX: 0.5, strideY: constants.SQRT3 / 2} : {strideX: 1, strideY: constants.SQRT3};
default:
return {strideX: 1, strideY: 1};
}
}
export function getHexCoordinatesCentreOffset(type: GridType.HEX_HORZ | GridType.HEX_VERT) {
switch (type) {
case GridType.HEX_HORZ:
return {centreX: 1, centreY: 2/3};
case GridType.HEX_VERT:
return {centreX: 2/3, centreY: 1};
}
}
export function cartesianToHexCoords(x: number, y: number, type: GridType.HEX_VERT | GridType.HEX_HORZ) {
const {strideX, strideY} = getGridStride(type);
let hexStraight, hexZigzag, above, hexX, hexY;
if (type === GridType.HEX_VERT) {
hexZigzag = Math.floor(3 * x / strideX);
hexStraight = Math.floor(y / strideY);
above = isAboveHexDiagonal(y, x, hexStraight, hexZigzag, strideY, strideX);
} else {
hexStraight = Math.floor(x / strideX);
hexZigzag = Math.floor(3 * y / strideY);
above = isAboveHexDiagonal(x, y, hexStraight, hexZigzag, strideX, strideY);
}
hexZigzag = Math.floor(hexZigzag / 3);
if (above) {
hexZigzag--;
}
if (hexZigzag&1) {
hexStraight -= (hexStraight & 1) ? 0 : 1;
} else {
hexStraight &= ~1;
}
if (type === GridType.HEX_VERT) {
hexX = hexZigzag;
hexY = hexStraight;
} else {
hexX = hexStraight;
hexY = hexZigzag;
}
let {centreX, centreY} = getHexCoordinatesCentreOffset(type);
centreX += hexX;
centreY += hexY;
return {strideX, strideY, hexX, hexY, centreX, centreY};
}
const MAP_ROTATION_SNAP = Math.PI / 2;
const MAP_ROTATION_HEX_SNAP = Math.PI / 6;
// A hex map rotated by 30 degrees becomes a grid of the opposite type (horizontal <-> vertical)
export function effectiveHexGridType(mapRotation: number, gridType: GridType.HEX_VERT | GridType.HEX_HORZ): GridType.HEX_VERT | GridType.HEX_HORZ {
if (Math.round(mapRotation / MAP_ROTATION_HEX_SNAP) % 2 === 0) {
return gridType;
} else if (gridType === GridType.HEX_HORZ) {
return GridType.HEX_VERT;
} else {
return GridType.HEX_HORZ;
}
}
// Returns the coordinates of the map's rotation centre, relative to the map's pixel-based centre (the location that the
// map is anchored in the world space). Also returns the grid offsets.
export function getMapCentreOffsets(snap: boolean, properties: MapProperties) {
const {strideX, strideY} = getGridStride(properties.gridType, false);
const dx = (strideX + properties.gridOffsetX / properties.gridSize) % strideX;
const dy = (strideY + properties.gridOffsetY / properties.gridSize) % strideY;
let mapDX = 0, mapDZ = 0;
if (snap) {
const mapCentreX = properties.width / 2;
const mapCentreY = properties.height / 2;
switch (properties.gridType) {
case GridType.HEX_HORZ:
case GridType.HEX_VERT:
// A hex map should rotate around the centre of the hex closest to the map's centre.
const {centreX, centreY} = getHexCoordinatesCentreOffset(properties.gridType);
const {hexX, hexY} = cartesianToHexCoords(mapCentreX + strideX / 2 * centreX - dx, mapCentreY + strideY / 2 * centreY - dy, properties.gridType);
mapDX = hexX * strideX / 2 + dx - mapCentreX;
mapDZ = hexY * strideY / 2 + dy - mapCentreY;
break;
default:
// A square map should rotate around the grid intersection closest to the map's centre.
mapDX = (dx - mapCentreX) % strideX;
mapDZ = (dy - mapCentreY) % strideY;
break;
}
}
return {dx, dy, mapDX, mapDZ};
}
export function snapMap(snap: boolean, properties: MapProperties, position: ObjectVector3, rotation: ObjectEuler = {order: 'XYZ', x: 0, y: 0, z: 0}) {
if (!properties) {
return {positionObj: position, rotationObj: rotation, dx: 0, dy: 0, width: 10, height: 10};
}
const rotationSnap = (properties.gridType === GridType.HEX_HORZ || properties.gridType === GridType.HEX_VERT)
? MAP_ROTATION_HEX_SNAP : MAP_ROTATION_SNAP;
const {dx, dy, mapDX, mapDZ} = getMapCentreOffsets(snap, properties);
if (snap) {
const mapRotation = Math.round(rotation.y / rotationSnap) * rotationSnap;
const cos = Math.cos(mapRotation);
const sin = Math.sin(mapRotation);
let x, z;
switch (properties.gridType) {
case GridType.HEX_HORZ:
case GridType.HEX_VERT:
const snapGridType = effectiveHexGridType(mapRotation, properties.gridType);
const {strideX, strideY, centreX, centreY} = cartesianToHexCoords(position.x - cos * mapDX - sin * mapDZ, position.z - cos * mapDZ + sin * mapDX, snapGridType);
x = centreX * strideX - cos * mapDX - sin * mapDZ;
z = centreY * strideY - cos * mapDZ + sin * mapDX;
break;
default:
x = Math.round(position.x + cos * mapDX + sin * mapDZ) - cos * mapDX - sin * mapDZ;
z = Math.round(position.z + cos * mapDZ - sin * mapDX) - cos * mapDZ + sin * mapDX;
break;
}
const y = Math.round(+position.y);
return {
positionObj: {x, y, z},
rotationObj: {...rotation, y: mapRotation},
dx, dy, width: properties.width, height: properties.height
};
} else {
return {positionObj: position, rotationObj: rotation, dx, dy, width: properties.width, height: properties.height};
}
}
export function getAbsoluteMiniPosition(miniId: string | undefined, minis: {[miniId: string]: MiniType}, snap?: boolean, gridType?: GridType) {
if (!miniId || !minis[miniId]) {
return undefined;
}
let {position: positionObj, rotation: rotationObj, elevation, attachMiniId, selectedBy, scale} = minis[miniId];
if (attachMiniId) {
const baseMiniPosition = getAbsoluteMiniPosition(attachMiniId, minis, snap, gridType);
if (!baseMiniPosition) {
return undefined;
}
const {positionObj: attachedPosition, rotationObj: attachedRotation, elevation: attachedElevation} = baseMiniPosition;
positionObj = buildVector3(positionObj).applyEuler(buildEuler(attachedRotation)).add(attachedPosition as THREE.Vector3);
rotationObj = {x: rotationObj.x + attachedRotation.x, y: rotationObj.y + attachedRotation.y, z: rotationObj.z + attachedRotation.z, order: rotationObj.order};
elevation += attachedElevation;
}
return (snap && gridType) ? snapMini(snap && !!selectedBy, gridType, scale, positionObj, elevation, rotationObj) : {positionObj, rotationObj, elevation};
}
const MINI_SQUARE_ROTATION_SNAP = Math.PI / 4;
const MINI_HEX_ROTATION_SNAP = Math.PI / 3;
export function snapMini(snap: boolean, gridType: GridType, scaleFactor: number, position: ObjectVector3, elevation: number, rotation: ObjectEuler = {order: 'XYZ', x: 0, y: 0, z: 0}) {
if (snap) {
const scale = scaleFactor > 1 ? Math.round(scaleFactor) : 1.0 / (Math.round(1.0 / scaleFactor));
const gridSnap = scale > 1 ? 1 : scale;
let x, z;
let rotationSnap;
switch (gridType) {
case GridType.HEX_HORZ:
case GridType.HEX_VERT:
const {strideX, strideY, centreX, centreY} = cartesianToHexCoords(position.x / gridSnap, position.z / gridSnap, gridType);
x = centreX * strideX * gridSnap;
z = centreY * strideY * gridSnap;
rotationSnap = MINI_HEX_ROTATION_SNAP;
break;
default:
const offset = (scale / 2) % 1;
x = Math.round((position.x - offset) / gridSnap) * gridSnap + offset;
z = Math.round((position.z - offset) / gridSnap) * gridSnap + offset;
rotationSnap = MINI_SQUARE_ROTATION_SNAP;
}
const y = Math.round(+position.y);
return {
positionObj: {x, y, z},
rotationObj: {...rotation, y: Math.round(rotation.y / rotationSnap) * rotationSnap},
scaleFactor: scale,
elevation: Math.round(elevation)
};
} else {
return {positionObj: position, rotationObj: rotation, scaleFactor, elevation};
}
}
export function getGridTypeOfMap(map?: MapType, defaultGridType = GridType.NONE) {
if (!map || !map.metadata.properties) {
return defaultGridType;
}
const gridType = map.metadata.properties.gridType;
if (gridType === GridType.HEX_VERT || gridType === GridType.HEX_HORZ) {
return effectiveHexGridType(map.rotation.y, gridType);
} else {
return gridType;
}
}
export function generateMovementPath(movementPath: MovementPathPoint[], maps: {[mapId: string]: MapType}, defaultGridType: GridType): TabletopPathPoint[] {
return movementPath.map((point) => {
let gridType = defaultGridType;
if (point.onMapId) {
const onMap = maps[point.onMapId];
gridType = (onMap && onMap.metadata.properties) ? onMap.metadata.properties.gridType : defaultGridType;
if (onMap && (gridType === GridType.HEX_HORZ || gridType === GridType.HEX_VERT)) {
gridType = effectiveHexGridType(onMap.rotation.y, gridType);
}
}
return {x: point.x, y: point.y + (point.elevation || 0), z: point.z, gridType};
});
}
const GRID_COLOUR_TO_HEX = {
black: '#000000', grey: '#9b9b9b', white: '#ffffff', brown: '#8b572a',
tan: '#c77f16', red: '#ff0000', yellow: '#ffff00', green: '#00ff00',
cyan: '#00ffff', blue: '#0000ff', magenta: '#ff00ff'
};
export function getColourHex(colour: string | THREE.Color): number {
if (colour instanceof THREE.Color) {
return colour.getHex();
} else {
const hex = GRID_COLOUR_TO_HEX[colour] || colour || '#000000';
return Number.parseInt(hex[0] === '#' ? hex.substr(1) : hex, 16);
}
}
export function getColourHexString(colour: number | string): string {
if (typeof(colour) === 'string' && colour[0] === '#') {
colour = parseInt(colour.slice(1), 16);
}
const hexString = Number(colour).toString(16);
return '#' + ('000000' + hexString).slice(-6);
}
export const getNetworkHubId = memoizeOne((myUserId: string, myPeerId: string | null, gm: string, connectedUsers: ConnectedUserUsersType) => {
let networkHubId = (myUserId === gm) ? myPeerId : null;
for (let peerId of Object.keys(connectedUsers)) {
if (connectedUsers[peerId].user.emailAddress === gm && (!networkHubId || peerId < networkHubId)) {
networkHubId = peerId;
}
}
return networkHubId;
});
export function *spiralSquareGridGenerator(): IterableIterator<{x: number, y: number}> {
let horizontal = true, step = 1, delta = 1, x = 0, y = 0;
while (true) {
if (horizontal) {
x += delta;
if (2 * x * delta >= step) {
horizontal = false;
}
} else {
y += delta;
if (2 * y * delta >= step) {
horizontal = true;
delta = -delta;
step++;
}
}
yield {x, y};
}
}
const hexHorizontalGridPath = [
{dx: 1, dy: 0},
{dx: 0.5, dy: 1.5 * constants.INV_SQRT3},
{dx: -0.5, dy: 1.5 * constants.INV_SQRT3},
{dx: -1, dy: 0},
{dx: -0.5, dy: -1.5 * constants.INV_SQRT3},
{dx: 0.5, dy: -1.5 * constants.INV_SQRT3}
];
const hexVerticalGridPath = [
{dx: 1.5 * constants.INV_SQRT3, dy: 0.5},
{dx: 0, dy: 1},
{dx: -1.5 * constants.INV_SQRT3, dy: 0.5},
{dx: -1.5 * constants.INV_SQRT3, dy: -0.5},
{dx: 0, dy: -1},
{dx: 1.5 * constants.INV_SQRT3, dy: -0.5}
];
export function *spiralHexGridGenerator(gridType: GridType.HEX_HORZ | GridType.HEX_VERT): IterableIterator<{x: number, y: number}> {
const path = (gridType === GridType.HEX_HORZ) ? hexHorizontalGridPath : hexVerticalGridPath;
let x = 0, y = 0, sideLength = 1, direction = 0;
while (true) {
// The side length of the 2nd direction in the sequence needs to be one less, to make the circular sequence
// into a spiral around the centre.
const {dx, dy} = path[direction];
for (let step = (direction === 1) ? 1 : 0; step < sideLength; ++step) {
x += dx;
y += dy;
yield {x, y};
}
if (++direction >= path.length) {
direction = 0;
sideLength++;
}
}
}
const ROUND_VECTORS_DELTA = 0.01;
export function roundSquareVectors(start: THREE.Vector3, end: THREE.Vector3) {
if (start.x <= end.x) {
start.x = Math.floor(start.x);
end.x = Math.ceil(end.x + ROUND_VECTORS_DELTA) - ROUND_VECTORS_DELTA;
} else {
start.x = Math.ceil(start.x + ROUND_VECTORS_DELTA) - ROUND_VECTORS_DELTA;
end.x = Math.floor(end.x);
}
if (start.z <= end.z) {
start.z = Math.floor(start.z);
end.z = Math.ceil(end.z + ROUND_VECTORS_DELTA) - ROUND_VECTORS_DELTA;
} else {
start.z = Math.ceil(start.z + ROUND_VECTORS_DELTA) - ROUND_VECTORS_DELTA;
end.z = Math.floor(end.z);
}
}
function growHexVectors(startPos: THREE.Vector3, endPos: THREE.Vector3, gridType: GridType.HEX_VERT | GridType.HEX_HORZ, grow = 1) {
const {centreX, centreY} = getHexCoordinatesCentreOffset(gridType);
const xStartMore = (startPos.x > endPos.x ? 0.98 : -0.98) * grow;
startPos.x += centreX * xStartMore;
endPos.x -= centreX * xStartMore;
const zStartMore = (startPos.z > endPos.z ? 0.98 : -0.98) * grow;
startPos.z += centreY * zStartMore;
endPos.z -= centreY * zStartMore;
}
/**
* Round vectors in world coordinates so that they snap to the shape of a rectangle around the given map's tiles. Return
* vectors are relative to the map's world position.
*
* @param map The map to whose tiles the vectors should snap.
* @param rotation The map's current rotation.
* @param worldStart The world coordinates of the start of the rectangle.
* @param worldEnd The world coordinates of the end of the rectangle.
*/
export function getMapGridRoundedVectors(map: MapType, rotation: THREE.Euler, worldStart: THREE.Vector3 | ObjectVector3, worldEnd: THREE.Vector3 | ObjectVector3) {
// Counter-rotate start/end vectors around map position to get their un-rotated equivalent positions
const mapPosition = buildVector3(map.position);
const reverseRotation = reverseEuler(rotation);
const startPos = buildVector3(worldStart).sub(mapPosition).applyEuler(reverseRotation).add(mapPosition);
const endPos = buildVector3(worldEnd).sub(mapPosition).applyEuler(reverseRotation).add(mapPosition);
const properties = castMapProperties(map.metadata.properties);
const {mapDX, mapDZ} = getMapCentreOffsets(true, properties);
const mapCentre = new THREE.Vector3(mapDX, 0, mapDZ);
const centreOffset = mapPosition.clone().add(mapCentre);
startPos.sub(centreOffset);
endPos.sub(centreOffset);
if (properties.gridType === GridType.HEX_HORZ || properties.gridType === GridType.HEX_VERT) {
// At this point startPos/endPos are relative to the centre of the central hex. Need to align them to the hex grid.
const {strideX, strideY} = getGridStride(properties.gridType);
const {centreX, centreY} = getHexCoordinatesCentreOffset(properties.gridType);
const {hexX: startHexX, hexY: startHexY} = cartesianToHexCoords(startPos.x + strideX * centreX, startPos.z + strideY * centreY, properties.gridType);
const {hexX: endHexX, hexY: endHexY} = cartesianToHexCoords(endPos.x + strideX * centreX, endPos.z + strideY * centreY, properties.gridType);
startPos.set(startHexX, startPos.y, startHexY);
endPos.set(endHexX, endPos.y, endHexY);
growHexVectors(startPos, endPos, properties.gridType);
const hexScale = new THREE.Vector3(strideX, 1, strideY);
startPos.multiply(hexScale);
endPos.multiply(hexScale);
} else {
roundSquareVectors(startPos, endPos);
}
// Return the start/end positions as (un-rotated) points relative to the map position
startPos.add(mapCentre);
endPos.add(mapCentre);
return {startPos, endPos};
}
export function getShaderFogOffsets(gridType: GridType, dx: number, dy: number, mapWidth: number, mapHeight: number, fogWidth: number, fogHeight?: number) {
// Shader textures have their origin at the bottom left corner, so dx/dy need to be transformed to be the offset
// from the bottom left of the fogOfWar overlay image to the bottom left corner of the map image.
const {strideX, strideY} = getGridStride(gridType);
switch (gridType) {
// Hex grid: (dx, dy) is the offset in world units from the top left of the map mesh to the nearest hex
// centre on the map texture (+ve direction)
case GridType.HEX_HORZ:
return {
shaderDX: 2 * strideX - dx,
shaderDY: fogHeight ? (fogHeight * strideY - mapHeight - strideY * 5 / 3 + (dy % strideY)) : dy
};
case GridType.HEX_VERT:
return {
shaderDX: 4 * strideX / 3 - dx,
shaderDY: fogHeight ? (fogHeight - mapHeight + dy) % 1 : dy
};
default:
// Square grid: (dx, dy) is the offset in world units from the top left of the map mesh to the nearest grid
// intersection on the map texture (+ve direction).
return {
shaderDX: strideX - dx,
shaderDY: fogHeight ? (fogHeight - mapHeight - strideY + dy) : dy
};
}
}
/**
* Return a vector with integer x and z (and zero y) giving the coordinates on the fog map that corresponds with the
* calculated map centre of the map, and also a boolean indicating if the point on the fog map is offset (bumped left on
* a horizontal hex grid, bumped down on a vertical one).
*/
export function getFogMapCentre(properties: MapProperties): {fogMapCentre: THREE.Vector3, isCentreOffset: boolean} {
const {dx, dy, mapDX, mapDZ} = getMapCentreOffsets(true, properties);
const {shaderDX, shaderDY} = getShaderFogOffsets(properties.gridType, dx, dy, properties.width, properties.height, properties.fogWidth, properties.fogHeight);
let {strideX, strideY} = getGridStride(properties.gridType, false);
switch (properties.gridType) {
case GridType.HEX_HORZ:
strideY /= 2;
break;
case GridType.HEX_VERT:
strideX /= 2;
break;
}
const fogMapCentre = new THREE.Vector3(
Math.floor((properties.width / 2 + shaderDX + mapDX) / strideX + 0.1),
0,
Math.floor(properties.fogHeight - (properties.height / 2 + shaderDY - mapDZ) / strideY + 0.1)
);
let isCentreOffset = false;
switch (properties.gridType) {
case GridType.HEX_HORZ:
isCentreOffset = (fogMapCentre.z % 2) === 1;
break;
case GridType.HEX_VERT:
isCentreOffset = (fogMapCentre.x % 2) === 1;
if (isCentreOffset) {
fogMapCentre.z--;
}
break;
}
return {fogMapCentre, isCentreOffset};
}
/**
* Return vectors indicating the start and end coordinates of the fog rectangle on the map's fog bitmap (i.e.
* coordinates which are 0,0 at the top left corner of the fog bitmap)
* @param map The map whose fog bitmap we want to update.
* @param start A vector in world coordinates indicating the start of the fog rectangle.
* @param end A vector in world coordinates indicating the end of the fog rectangle.
*/
export function getMapFogRect(map: MapType, start: ObjectVector3, end: ObjectVector3) {
const rotation = buildEuler(map.rotation);
const properties = castMapProperties(map.metadata.properties);
const {startPos, endPos} = getMapGridRoundedVectors(map, rotation, start, end);
const {mapDX, mapDZ} = getMapCentreOffsets(true, properties);
const mapCentre = new THREE.Vector3(mapDX, 0, mapDZ);
startPos.sub(mapCentre);
endPos.sub(mapCentre);
const {fogMapCentre, isCentreOffset} = getFogMapCentre(properties);
if (properties.gridType === GridType.HEX_HORZ || properties.gridType === GridType.HEX_VERT) {
const {strideX, strideY} = getGridStride(properties.gridType);
const hexScale = new THREE.Vector3(strideX, 1, strideY);
startPos.divide(hexScale);
endPos.divide(hexScale);
growHexVectors(startPos, endPos, properties.gridType, -1);
// startPos/endPos are now in hex coordinates, which are doubled in one axis
if (properties.gridType === GridType.HEX_HORZ) {
// The pixel shader displaces every second row of the fog bitmap 0.5 left to form the hex pattern. If the
// fogCentre hex is on a row that isn't so displaced, hex coordinates with odd x values need to be rounded
// up as they're halved, rather than down, to correctly align with the fog bitmap.
const fogOriginBump = isCentreOffset ? 0 : 1;
startPos.x = Math.floor((Math.round(startPos.x) + fogOriginBump) / 2);
endPos.x = Math.floor((Math.round(endPos.x) + fogOriginBump) / 2);
} else {
// The pixel shader displaces every second column of the fog bitmap 0.5 down to from the hex pattern. We
// need to finesse the rounding as we halve the odd y coordinates as above, except that we need to round up
// when the fogCentre hex *is* on a row that's displaced.
const fogOriginBump = isCentreOffset ? 1 : 0;
startPos.z = Math.floor((Math.round(startPos.z) + fogOriginBump) / 2);
endPos.z = Math.floor((Math.round(endPos.z) + fogOriginBump) / 2);
}
}
startPos.add(fogMapCentre);
endPos.add(fogMapCentre);
const startX = clamp(Math.round(Math.min(startPos.x, endPos.x)), 0, properties.fogWidth);
const startY = clamp(Math.round(Math.min(startPos.z, endPos.z)), 0, properties.fogHeight);
const endX = Math.max(startX, clamp(Math.floor(Math.max(startPos.x, endPos.x)), 0, properties.fogWidth));
const endY = Math.max(startY, clamp(Math.floor(Math.max(startPos.z, endPos.z)), 0, properties.fogHeight));
return {startX, startY, endX, endY, fogWidth: properties.fogWidth, fogHeight: properties.fogHeight};
}
export function getUpdatedMapFogRect(map: MapType, start: ObjectVector3, end: ObjectVector3, reveal: boolean | null) {
let {startX, startY, endX, endY, fogWidth, fogHeight} = getMapFogRect(map, start, end);
// Now iterate over FoW bitmap and set or clear bits.
let fogOfWar = map.fogOfWar ? [...map.fogOfWar] : new Array(Math.ceil(fogWidth * fogHeight / 32.0)).fill(-1);
const gridType = map.metadata.properties.gridType;
// For hex grids, potentially skip every second cell on the edges, to update a rectangle of hexes which
// doesn't correspond to a strict rectangle of the fog bitmap.
const singlePoint = (startX === endX && startY === endY);
const startXOdd = (startX % 2) === 1;
const endXOdd = (endX % 2) === 1;
const startYOdd = (startY % 2) === 1;
const endYOdd = (endY % 2) === 1;
const pointsSouthEast = (((startX === endX && startYOdd) || start.x < end.x) === ((startY === endY && !startXOdd) || start.z < end.z));
const combTop = gridType !== GridType.HEX_VERT || singlePoint || (startXOdd ? (!endXOdd && !pointsSouthEast) : (!endXOdd || pointsSouthEast)) ? undefined : 0;
let combBottom = gridType !== GridType.HEX_VERT || singlePoint || (startXOdd ? (endXOdd || !pointsSouthEast) : (endXOdd && pointsSouthEast)) ? undefined : 1;
const combLeft = gridType !== GridType.HEX_HORZ || singlePoint || (startYOdd ? (endYOdd || pointsSouthEast) : (endYOdd && !pointsSouthEast)) ? undefined : 1;
let combRight = gridType !== GridType.HEX_HORZ || singlePoint || (startYOdd ? (!endYOdd && pointsSouthEast) : (!endYOdd || !pointsSouthEast)) ? undefined : 0;
// Special case: Change any purely horizontal/vertical selection which runs against the grain of the hex grid (which
// would normally just be every second hex) into a zigzagging line of hexes.
if (!singlePoint) {
if (gridType === GridType.HEX_VERT && startY === endY) {
if (startX % 2) {
combBottom = 1;
endY++;
} else {
combBottom = undefined;
}
} else if (gridType === GridType.HEX_HORZ && startX === endX) {
if (startY % 2) {
combRight = undefined;
} else {
combRight = 0;
endX++;
}
}
}
for (let y = startY; y <= endY; ++y) {
for (let x = startX; x <= endX; ++x) {
if ((y === startY && x % 2 === combTop) || (y === endY && x % 2 === combBottom)
|| (x === startX && y % 2 === combLeft) || (x === endX && y % 2 === combRight)
) {
continue;
}
const textureIndex = x + y * fogWidth;
const bitmaskIndex = textureIndex >> 5;
const mask = 1 << (textureIndex & 0x1f);
if (reveal === null) {
fogOfWar[bitmaskIndex] ^= mask;
} else if (reveal) {
fogOfWar[bitmaskIndex] |= mask;
} else {
fogOfWar[bitmaskIndex] &= ~mask;
}
}
}
return fogOfWar;
}
export function isMapFoggedAtPosition(map: MapType | undefined, position: ObjectVector3, fogOfWar: number[] | null = map ? map.fogOfWar || null : null): boolean {
if (map && fogOfWar) {
const {startX: mapX, startY: mapY, fogWidth, fogHeight} = getMapFogRect(map, position, position);
if (mapX < 0 || mapX >= fogWidth || mapY < 0 || mapY >= fogHeight) {
return false;
}
const textureIndex = mapX + mapY * fogWidth;
const bitmaskIndex = textureIndex >> 5;
const mask = 1 << (textureIndex & 0x1f);
return (fogOfWar[bitmaskIndex] & mask) === 0;
}
return false;
}
export function getMapIdAtPoint(point: THREE.Vector3 | ObjectVector3, maps: {[mapId: string]: MapType}, allowHidden: boolean): string | undefined {
return Object.keys(maps).reduce<string | undefined>((touching, mapId) => {
const map = maps[mapId];
if (touching || (!allowHidden && map.gmOnly) || !isCloseTo(point.y, map.position.y)) {
return touching;
}
const width = Number(map.metadata.properties.width);
const height = Number(map.metadata.properties.height);
const cos = Math.cos(+map.rotation.y);
const sin = Math.sin(+map.rotation.y);
const dx = point.x - map.position.x;
const dz = point.z - map.position.z;
const effectiveX = dx * cos - dz * sin;
const effectiveZ = dz * cos + dx * sin;
return (effectiveX >= -width / 2 && effectiveX < width / 2
&& effectiveZ >= -height / 2 && effectiveZ < height / 2) ? mapId : touching
}, undefined);
}
export function getRootAttachedMiniId(miniId: string, minis: {[miniId: string]: MiniType}): string {
while (minis[miniId].attachMiniId) {
miniId = minis[miniId].attachMiniId!;
}
return miniId;
}
export function isTabletopLockedForPeer(tabletop: TabletopType, connectedUsers: ConnectedUserUsersType, peerId: string | null, override = false): boolean {
const fromGm = (override && peerId) ? (connectedUsers[peerId] && connectedUsers[peerId].verifiedConnection && connectedUsers[peerId].user.emailAddress === tabletop.gm) : false;
return !!(tabletop.tabletopLockedPeerId && tabletop.tabletopLockedPeerId !== peerId && !fromGm);
}
export function isScenarioEmpty(scenario?: ScenarioType) {
return !scenario || (Object.keys(scenario.minis).length === 0 && Object.keys(scenario.maps).length === 0);
}
export const SAME_LEVEL_MAP_DELTA_Y = 1.5;
export const NEW_MAP_DELTA_Y = 6.0;
export const MAP_EPSILON = 0.01;
export const isMapIdHighest = memoizeOne((maps: {[key: string]: MapType}, mapId?: string): boolean => {
const map = mapId ? maps[mapId] : undefined;
return !map ? true : Object.keys(maps).reduce<boolean>((highest, otherMapId) => {
return highest && (mapId === otherMapId || maps[otherMapId].position.y <= map.position.y + SAME_LEVEL_MAP_DELTA_Y)
}, true);
});
export const isMapIdLowest = memoizeOne((maps: {[key: string]: MapType}, mapId?: string): boolean => {
const map = mapId ? maps[mapId] : undefined;
return !map ? true : Object.keys(maps).reduce<boolean>((lowest, otherMapId) => {
return lowest && (mapId === otherMapId || maps[otherMapId].position.y > map.position.y - SAME_LEVEL_MAP_DELTA_Y)
}, true);
});
export const getMapIdClosestToZero = memoizeOne((maps: {[key: string]: MapType}) => {
let closestElevation = 0;
return Object.keys(maps).reduce<string | undefined>((closestId, mapId) => {
const elevation = Math.abs(+maps[mapId].position.y);
if (closestId === undefined || elevation < closestElevation || (elevation === closestElevation && mapId < closestId)) {
closestElevation = elevation;
return mapId;
} else {
return closestId;
}
}, undefined);
});
export function arePositionsOnSameLevel(position1: ObjectVector3, position2: ObjectVector3): boolean {
return Math.abs(position1.y - position2.y) <= SAME_LEVEL_MAP_DELTA_Y;
}
export const getMapIdsAtLevel = memoizeOne((maps: {[key: string]: MapType}, elevation: number) => {
return Object.keys(maps).filter((mapId) => {
const map = maps[mapId];
return map.position.y >= elevation - SAME_LEVEL_MAP_DELTA_Y && map.position.y <= elevation + SAME_LEVEL_MAP_DELTA_Y;
});
});
/**
* Searches all maps near the given elevation for the best map to focus on, and the best explicitly selected camera
* point.
*
* @param maps The dictionary of all maps in the scenario.
* @param elevation The elevation of the maps to search. If undefined, searches the level closest to elevation 0.
* @returns {focusMapId, cameraFocusPoint} focusMapId: The mapId of the map on the level with the highest elevation and
* (if tied) the lowest mapId. cameraFocusPoint: The explicitly chosen map focus with the highest elevation on the
* level, and (if tied) the one on the lowest mapId, but then lifted to have the same y as the focusMapId.
*/
function _getFocusMapIdAndFocusPointAtLevel(maps: {[key: string]: MapType}, elevation?: number): {focusMapId?: string, cameraFocusPoint?: ObjectVector3} {
if (elevation === undefined) {
const closestId = getMapIdClosestToZero(maps);
elevation = closestId ? maps[closestId].position.y : 0;
}
const levelMapIds = getMapIdsAtLevel(maps, elevation);
let focusMapId: string | undefined = undefined;
let cameraFocusMapId: string | undefined = undefined;
for (let mapId of levelMapIds) {
const map = maps[mapId];
focusMapId = (
!focusMapId
|| map.position.y > maps[focusMapId].position.y
|| mapId < focusMapId
) ? mapId : focusMapId;
cameraFocusMapId = (
map.cameraFocusPoint && (!cameraFocusMapId
|| map.cameraFocusPoint.y > maps[cameraFocusMapId].cameraFocusPoint!.y
|| mapId < cameraFocusMapId
)
) ? mapId : cameraFocusMapId;
}
let cameraFocusPoint: ObjectVector3 | undefined = undefined;
if (focusMapId && cameraFocusMapId) {
const pointMap = maps[cameraFocusMapId];
const cameraFocusOffset = pointMap.cameraFocusPoint!;
cameraFocusPoint = {
x: pointMap.position.x + cameraFocusOffset.x,
y: maps[focusMapId].position.y,
z: pointMap.position.z + cameraFocusOffset.z
};
}
return {focusMapId, cameraFocusPoint};
}
export const getFocusMapIdAndFocusPointAtLevel = memoizeOne(_getFocusMapIdAndFocusPointAtLevel);
/**
* Get the first mapId in the nominated direction (up or down) from the level containing the given mapId.
*
* @param direction The direction to search: 1 = up, -1 = down
* @param maps The dictionary of maps for the scenario.
* @param mapId The mapId from which to search. If undefined, searches from 0.
* @param limit If true (default), the search will be limited to maps that are within NEW_MAP_DELTA_Y of the starting point.
*/
export function getMapIdOnNextLevel(direction: 1 | -1, maps: {[mapId: string]: MapType}, mapId?: string, limit = true) {
const mapY = mapId && maps[mapId] ? maps[mapId].position.y : 0;
const floor = direction > 0 ? mapY + SAME_LEVEL_MAP_DELTA_Y : (limit ? mapY - NEW_MAP_DELTA_Y : undefined);
const ceiling = direction > 0 ? (limit ? mapY + NEW_MAP_DELTA_Y : undefined) : mapY - SAME_LEVEL_MAP_DELTA_Y;
return Object.keys(maps).reduce<string | undefined>((result, otherMapId) => {
const mapY = maps[otherMapId].position.y;
return (floor === undefined || mapY >= floor) && (ceiling === undefined || mapY <= ceiling) && (
!result
|| (direction > 0 && mapY < maps[result].position.y)
|| (direction < 0 && mapY > maps[result].position.y)
) ? otherMapId : result;
}, undefined);
}
function _getHighestMapId(maps: {[mapId: string]: MapType}) {
return Object.keys(maps).reduce<string | undefined>((maxMapId, mapId) => (
maxMapId === undefined || maps[maxMapId].position.y < maps[mapId].position.y ? mapId : maxMapId
), undefined);
}
export const getHighestMapId = memoizeOne(_getHighestMapId);
function adjustMapPositionToNotCollide(scenario: ScenarioType, position: THREE.Vector3, properties: MapProperties, performAdjust: boolean): boolean {
// TODO this doesn't account for map rotation.
let adjusted = false;
for (let mapId of Object.keys(scenario.maps)) {
const map = scenario.maps[mapId];
const mapWidth = Number(map.metadata.properties.width);
const mapHeight = Number(map.metadata.properties.height);
if (arePositionsOnSameLevel(position, map.position)
&& position.x + properties.width / 2 >= map.position.x - mapWidth / 2 && position.x - properties.width / 2 < map.position.x + mapWidth / 2
&& position.z + properties.height / 2 >= map.position.z - mapHeight / 2 && position.z - properties.height / 2 < map.position.z + mapHeight / 2) {
adjusted = true;
if (performAdjust) {
const delta = position.clone().sub(map.position as THREE.Vector3);
const quadrant14 = (delta.x - delta.z > 0);
const quadrant12 = (delta.x + delta.z > 0);
if (quadrant12 && quadrant14) {
position.x = map.position.x + MAP_EPSILON + (mapWidth + properties.width) / 2;
} else if (quadrant12) {
position.z = map.position.z + MAP_EPSILON + (mapHeight + properties.height) / 2;
} else if (quadrant14) {
position.z = map.position.z - MAP_EPSILON - (mapHeight + properties.height) / 2;
} else {
position.x = map.position.x - MAP_EPSILON - (mapWidth + properties.width) / 2;
}
const {positionObj} = snapMap(true, properties, position);
position.copy(positionObj as THREE.Vector3);
}
}
}
return adjusted;
}
export function findPositionForNewMap(scenario: ScenarioType, rawProperties: MapProperties, position: THREE.Vector3): THREE.Vector3 {
const properties = castMapProperties(rawProperties) || {};
properties.width = properties.width || 10;
properties.height = properties.height || 10;
const {positionObj} = snapMap(true, properties, position);
while (true) {
const search = buildVector3(positionObj);
if (getMapIdAtPoint(search, scenario.maps, true) === undefined) {
// Attempt to find free space for the map at current elevation.
adjustMapPositionToNotCollide(scenario, search, properties, true);
if (!adjustMapPositionToNotCollide(scenario, search, properties, false)) {
return search;
}
}
// Try to fit the map at a higher elevation
positionObj.y += NEW_MAP_DELTA_Y;
}
}
function _getMaxCameraDistance(maps: {[mapId: string]: MapType}) {
const maxMapDimension = Object.keys(maps).reduce((max, mapId) => {
const {width, height} = maps[mapId].metadata.properties || {width: 10, height: 10};
return Math.max(max, width, height);
}, 0);
return Math.max(2 * maxMapDimension, 50);
}
export const getMaxCameraDistance = memoizeOne(_getMaxCameraDistance);
const CAMERA_INITIAL_OFFSET = new THREE.Vector3(0, Math.sqrt(0.5), Math.sqrt(0.5));
function _getBaseCameraParameters(map?: MapType, zoom = 1, cameraLookAt?: THREE.Vector3) {
cameraLookAt = cameraLookAt || buildVector3(map ? map.position : {x: 0, y: 0, z: 0});
const {width, height} = (map && map.metadata.properties) || {width: 10, height: 10};
const cameraDistance = 2 * Math.max(20, width, height);
const cameraPosition = cameraLookAt.clone().addScaledVector(CAMERA_INITIAL_OFFSET, zoom * Math.sqrt(cameraDistance));
return {cameraLookAt, cameraPosition};
}
export const getBaseCameraParameters = memoizeOne(_getBaseCameraParameters);
export function isUserAllowedOnTabletop(gm: string, email: string, tabletopUserControl?: TabletopUserControlType): boolean | null {
if (email !== gm && tabletopUserControl) {
const onWhitelist = tabletopUserControl.whitelist.reduce((match, value) => (
(value === email || (!match && value === '*')) ? value : match
), '');
const onBlacklist = tabletopUserControl.blacklist.reduce((match, value) => (
(value === email || (!match && value === '*')) ? value : match
), '');
if (!onWhitelist && !onBlacklist) {
return null;
} else if (!onWhitelist || onBlacklist === onWhitelist || onBlacklist === email) {
// Blacklist overrides whitelist if the same level (i.e. * or matching email on both)
return false;
}
}
return true;
}
export function getVisibilityString(visibility: PieceVisibilityEnum): string {
const option = MINI_VISIBILITY_OPTIONS.find((option) => (option.value === visibility));
return option ? option.displayName : '';
}
// === Pieces roster functions ===
export function isNameColumn(column: PiecesRosterColumn) {
return column.type === PiecesRosterColumnType.INTRINSIC && column.name === 'Name';
}
export const intrinsicFieldValueMap: {[name: string]: (mini: MiniType, minis: {[miniId: string]: MiniType}) => string} = {
Name: (mini) => (mini.name),
Focus: () => (''),
Visibility:
(mini) => (
mini.visibility === PieceVisibilityEnum.FOGGED ? (mini.gmOnly ? 'Fog (hide)' : 'Fog (show)')
: getVisibilityString(mini.visibility)
),
Locked: (mini) => (mini.locked ? 'Y' : 'N'),
Attached: (mini, minis) => (mini.attachMiniId ? 'to ' + minis[mini.attachMiniId].name : ''),
Prone: (mini) => (mini.prone ? 'Y' : 'N'),
Flat: (mini) => (mini.flat ? 'Y' : 'N'),
Base: (mini) => (mini.hideBase ? 'N' : 'Y'),
Scale: (mini) => (mini.scale.toString(10)),
Template: (mini) => (isTemplateMetadata(mini.metadata) ? 'Template' : 'Miniature')
};
const intrinsicFieldSortKeyMap: {[name: string]: (mini: MiniType) => string} = {
Visibility:
(mini) => {
switch (mini.visibility) {
case PieceVisibilityEnum.REVEALED:
return '1';
case PieceVisibilityEnum.FOGGED:
return mini.gmOnly ? '4' : '2';
case PieceVisibilityEnum.HIDDEN:
return '3';
}
}
};
export function getPiecesRosterValue(column: PiecesRosterColumn, mini: MiniType, minis: {[miniId: string]: MiniType}): PiecesRosterValue {
const values = (column.gmOnly ? mini.piecesRosterGMValues : mini.piecesRosterValues) || {};
const value = values[column.id];
switch (column.type) {
case PiecesRosterColumnType.INTRINSIC:
return intrinsicFieldValueMap[column.name] ? intrinsicFieldValueMap[column.name](mini, minis) : '';
case PiecesRosterColumnType.STRING:
return value === undefined ? '' : value;
case PiecesRosterColumnType.NUMBER:
return value === undefined ? 0 : value;
case PiecesRosterColumnType.BONUS:
const bonus = value === undefined ? 0 : value;
return bonus < 0 ? String(bonus) : '+' + String(bonus);
case PiecesRosterColumnType.FRACTION:
return (value === undefined ? {denominator: 0} : value) as PiecesRosterFractionValue;
}
}
export function getPiecesRosterDisplayValue(column: PiecesRosterColumn, values: PiecesRosterValues): string {
const value = values[column.id];
const header = column.name + ': ';
switch (column.type) {
case PiecesRosterColumnType.STRING:
return !value ? '' : header + value;
case PiecesRosterColumnType.NUMBER:
return header + (value === undefined ? '0' : String(value));
case PiecesRosterColumnType.BONUS:
const bonus = value === undefined ? 0 : value;
return header + (bonus < 0 ? String(bonus) : '+' + String(bonus));
case PiecesRosterColumnType.FRACTION:
const fraction = value as PiecesRosterFractionValue;
const {numerator, denominator} = value === undefined ? {numerator: 0, denominator: 0} :
fraction.numerator === undefined ? {numerator: fraction.denominator, denominator: fraction.denominator} :
fraction;
return denominator === 0 ? (
numerator === 0 ? `${header}full`
: `${header}${numerator! > 0 ? 'up' : 'down'} ${Math.abs(numerator!)}`
) : (
`${header}${numerator} / ${denominator}`
);
default:
return '';
}
}
export function getPiecesRosterSortString(column: PiecesRosterColumn, mini: MiniType, minis: {[miniId: string]: MiniType}): string {
if (column.type === PiecesRosterColumnType.INTRINSIC) {
if (intrinsicFieldSortKeyMap[column.name]) {
return intrinsicFieldSortKeyMap[column.name](mini);
}
} else if (mini.piecesRosterSimple) {
// Ignore custom roster column values in minis with custom values disabled
return '';
}
const value = getPiecesRosterValue(column, mini, minis);
if (column.type === PiecesRosterColumnType.FRACTION) {
const fraction = value as PiecesRosterFractionValue;
return ((fraction.denominator === 0) ? 0 : fraction.numerator === undefined ? 1 : fraction.numerator / fraction.denominator).toString()
+ ' ' + fraction.denominator;
} else {
return value === undefined ? '' : value.toString();
}
}
export function getUserDiceColours(tabletop: TabletopType, email: string) {
let diceColour: string;
if (tabletop.userPreferences[email]) {
diceColour = tabletop.userPreferences[email].dieColour;
} else {
diceColour = getColourHexString(Math.floor(stringHash(email) / 2));
}
const textColour = isColourDark(new THREE.Color(diceColour)) ? 'white' : 'black';
return {diceColour, textColour};
}
export function adjustScenarioOrigin(scenario: ScenarioType, defaultGrid: GridType, origin: THREE.Vector3, orientation: THREE.Euler): ScenarioType {
scenario.maps = Object.keys(scenario.maps).reduce((maps, mapId) => {
const map = scenario.maps[mapId];
const position = buildVector3(map.position).applyEuler(orientation).add(origin);
const rotation = {...map.rotation, y: map.rotation.y + orientation.y};
const {positionObj, rotationObj} = snapMap(true, map.metadata.properties, position, rotation);
maps[mapId] = {...map, position: positionObj, rotation: rotationObj};
return maps;
}, {});
scenario.minis = Object.keys(scenario.minis).reduce((minis, miniId) => {
const mini = scenario.minis[miniId];
if (mini.attachMiniId) {
minis[miniId] = mini;
} else {
const position = buildVector3(mini.position).applyEuler(orientation).add(origin);
const rotation = {...mini.rotation, y: mini.rotation.y + orientation.y};
const gridType = mini.onMapId ? getGridTypeOfMap(scenario.maps[mini.onMapId]) : defaultGrid;
const {positionObj, rotationObj, elevation} = snapMini(scenario.snapToGrid, gridType, mini.scale, position, mini.elevation, rotation);
minis[miniId] = {...mini, position: positionObj, rotation: rotationObj, elevation};
}
return minis;
}, {});
return scenario;
}
export function copyURLToClipboard(suffix: string) {
const location = window.location.href.replace(/[\\/][^/\\]*$/, '/' + suffix);
copyToClipboard(location);
} | the_stack |
import * as events from 'events';
import chalk from 'chalk';
import { join, sep, dirname, relative, normalize, extname, basename } from 'path';
import * as fse from 'fs-extra';
import {
IAppConfig,
IDatabaseConfig,
IServerConfig,
IAppOptions,
ITreeFile
} from '@materia/interfaces';
import { Logger } from './logger';
import { Config, ConfigType } from './config';
import { Server } from './server';
import { Entities } from './entities';
import { Database } from './database';
import { Synchronizer } from './synchronizer';
import { SelfMigration } from './self-migration';
import { History } from './history';
import { Client, ScriptMode } from './client';
import { Addons } from './addons';
import { Api } from './api';
import { MateriaError } from './error';
import { MateriaApi } from '../api';
import { Watcher } from './watcher';
import { Actions } from './actions';
export * from './addons/helpers';
export enum AppMode {
DEVELOPMENT = <any>'dev',
PRODUCTION = <any>'prod'
}
/**
* @class App
* @classdesc
* The main objects are available from this class.
* @property {Server} server - Access to the server's options
* @property {Api} api - Access to the server's endpoints
* @property {History} history - Access to the history and past actions
* @property {Database} database - Access to the database methods
* @property {Addons} addons - Access to the addons methods
* @property {Entities} entities - Access to the app's entities
*/
export class App extends events.EventEmitter {
id: string;
name: string;
package: string;
version?: string;
icon?: string;
zoom?: number;
// private packageJsonCache?: string
materia_path: string = __dirname;
mode = AppMode.DEVELOPMENT;
loaded = false;
// infos: IMateriaConfig
history: History;
entities: Entities;
addons: Addons;
database: Database;
api: Api;
server: Server;
// websocket: Websocket
client: Client;
logger: Logger;
config: Config;
selfMigration: SelfMigration;
materiaApi: MateriaApi;
watcher: Watcher;
// git: any
status: boolean;
live = false;
synchronizer: Synchronizer;
invalid: boolean;
error: string;
rootPassword: string;
actions: Actions;
constructor(public path: string, public options?: IAppOptions) {
super();
process.env.TZ = 'UTC';
if ( ! this.options ) {
this.options = {};
}
if ( this.options.prod ) {
this.options.mode = 'prod';
}
if ( ! this.options.mode ) {
this.mode = AppMode.DEVELOPMENT;
} else if (['development', 'dev', 'debug'].indexOf(this.options.mode) != -1) {
this.mode = AppMode.DEVELOPMENT;
} else if (this.options.mode == 'production' || this.options.mode == 'prod') {
this.mode = AppMode.PRODUCTION;
if ( ! this.options.runtimes) {
this.options.runtimes = 'core';
}
} else {
throw new MateriaError('Unknown mode', {
// tslint:disable-next-line:max-line-length
debug: 'Option --mode can be development (development/dev/debug) or production (production/prod). e.g. materia start --mode=prod or materia start --mode=dev'
});
}
this.logger = new Logger(this);
this.history = new History(this);
this.addons = new Addons(this);
this.entities = new Entities(this);
this.database = new Database(this);
this.api = new Api(this);
this.server = new Server(this);
this.client = new Client(this);
this.synchronizer = new Synchronizer(this);
this.config = new Config(this);
this.materiaApi = new MateriaApi(this);
this.watcher = new Watcher(this);
this.actions = new Actions(this);
this.status = false;
this.selfMigration = new SelfMigration(this);
}
loadMateria(): Promise<void> {
return this.doSelfMigrations()
.then(() => {
this.config.reloadConfig();
const appConfig = this.config.get<IAppConfig>(this.mode, ConfigType.APP);
if (appConfig) {
this.package = appConfig.package;
this.name = appConfig.name;
this.version = appConfig.version;
this.icon = appConfig.icon;
this.rootPassword = appConfig.rootPassword;
}
});
}
startFallback(): Promise<any> {
this.server.load();
this.materiaApi.initialize();
return this.server.start({
fallback: true
}).then(port => port);
}
load(): Promise<any> {
let elapsedTimeQueries, elapsedTimeEntities, elapsedTimeAPI;
const elapsedTimeGlobal = new Date().getTime();
this.api.removeAll({save: false});
if (require?.cache) {
Object.keys(require.cache).forEach(key => {
if (key.includes(join(this.path, 'server'))) {
delete require.cache[key];
}
});
}
return this.loadMateria()
.then(() => {
this.logger.log(`${chalk.bold('(Load)')} Application: ${chalk.yellow.bold(this.name || this.package)}`);
this.logger.log(` └── Path: ${chalk.bold(this.path)}`);
this.logger.log(` └── Mode: ${chalk.bold(this.mode == AppMode.DEVELOPMENT ? 'Development' : 'Production' )}`);
return this.database.load();
})
.then(() => this.database.start())
.then(() => this.client.load())
.then(() => this.server.load())
.then(() => this.entities.clear())
.then(() => this.server.session.initialize())
.then(() => this.materiaApi.initialize())
.then(() => this.logger.log(` └── Sessions: ${chalk.green.bold('OK')}`))
.then(() => this.addons.loadAddons())
.then(() => this.addons.loadFiles())
.then(() => this.entities.loadFiles())
.then(() => this.logger.log(' └─┬ Entities'))
.then(() => elapsedTimeEntities = new Date().getTime())
.then(() => this.addons.loadEntities())
.then(() => this.entities.loadEntities())
.then(() => this.entities.loadRelations())
.then(() =>
// tslint:disable-next-line:max-line-length
this.logger.log(` │ └── ${chalk.green.bold('OK') + ' - Completed in ' + chalk.bold(((new Date().getTime()) - elapsedTimeEntities).toString() + 'ms')}`)
)
.then(() => this.entities.resetModels())
.then(() => this.logger.log(' └─┬ Queries'))
.then(() => elapsedTimeQueries = new Date().getTime())
.then(() => this.addons.loadQueries())
.then(() => this.entities.loadQueries())
.then(() => this.logger.log(' └─┬ Actions'))
.then(() => elapsedTimeQueries = new Date().getTime())
.then(() => this.addons.loadActions())
.then(() => this.actions.load())
.then(() =>
// tslint:disable-next-line:max-line-length
this.logger.log(` │ └── ${chalk.green.bold('OK') + ' - Completed in ' + chalk.bold(((new Date().getTime()) - elapsedTimeQueries).toString() + 'ms')}`)
)
.then(() => this.api.resetControllers())
.then(() => this.logger.log(` └─┬ API`))
.then(() => elapsedTimeAPI = new Date().getTime())
.then(() => this.addons.loadAPI())
.then(() => this.api.load())
.then(() =>
// tslint:disable-next-line:max-line-length
this.logger.log(` │ └── ${chalk.green.bold('OK') + ' - Completed in ' + chalk.bold(((new Date().getTime()) - elapsedTimeAPI).toString() + 'ms')}`)
)
.then(() => this.watcher.load())
.then(() => this.history.load())
.then(() =>
this.logger.log(` └── ${chalk.green.bold('Successfully loaded in ' + ((new Date().getTime()) - elapsedTimeGlobal).toString() + 'ms')}\n`)
)
.then(() => null);
}
createDockerfile(options?) {
const dockerfile = join(this.path, 'Dockerfile');
const dbProd = this.config.get<IDatabaseConfig>(AppMode.PRODUCTION, ConfigType.DATABASE);
const webProd = this.config.get<IServerConfig>(AppMode.PRODUCTION, ConfigType.SERVER);
let setupScript = 'npm install';
if (this.server.hasStatic() && this.client.config.packageJsonPath != '') {
setupScript += ` && cd ${this.client.config.packageJsonPath} && npm install`;
if (this.client.hasBuildScript(ScriptMode.BUILD)) {
setupScript += ` && npm run ${this.client.config.scripts.build}`;
}
} else if (this.client.hasBuildScript(ScriptMode.BUILD)) {
setupScript += ` && npm run ${this.client.config.scripts.build}`;
}
fse.writeFileSync(dockerfile, `FROM node:10-alpine
RUN mkdir -p /app
# invalidate cache
RUN uptime
COPY . /app
WORKDIR /app
RUN ${setupScript}
ENV MATERIA_MODE production
EXPOSE ${webProd.port}
CMD ["npm", "start"]`);
let dbstr = '';
if (Database.isSQL(dbProd) && dbProd.type == 'postgres') {
// dbport = 5432
dbstr = `
image: postgres:9.6.3-alpine
environment:
POSTGRES_USER: "${dbProd.username}"
POSTGRES_PASSWORD: "${dbProd.password}"
POSTGRES_DB: "${dbProd.database}"`;
} else if (Database.isSQL(dbProd) && dbProd.type == 'mysql') {
// dbport = 3306
dbstr = `
image: mysql
environment:
MYSQL_ROOT_PASSWORD: "${dbProd.password}"
MYSQL_DATABASE: "${dbProd.database}"`;
if (dbProd.username != 'root') {
dbstr += `
MYSQL_USER: "${dbProd.username}"
MYSQL_PASSWORD: "${dbProd.password}"`;
}
}
fse.writeFileSync(join(this.path, 'docker-compose.yaml'), `version: "3"
services:
db: ${dbstr}
web:
build: .
ports:
- ${webProd.port}:${webProd.port}
links:
- db
depends_on:
- db
environment:
MATERIA_MODE: "production"
NO_HOST: "true"`);
}
createAppYaml(options) {
const appyaml = join(this.path, 'app.yaml');
fse.writeFileSync(appyaml, `runtime: nodejs
env: flex
skip_files:
- ^node_modules$
- ^.materia/live$
- ^.git$
env_variables:
MATERIA_MODE: 'production'
NO_HOST: true
beta_settings:
cloud_sql_instances: ${options.project}:${options.region}:${options.instance}
manual_scaling:
instances: ${options.scale}`);
}
saveGCloudSettings(settings) {
fse.writeFileSync(join(this.path, '.materia', 'gcloud.json'), JSON.stringify(settings, null, 2));
}
setPackageScript(name, script) {
let pkg;
try {
const content = fse.readFileSync(join(this.path, 'package.json')).toString();
pkg = JSON.parse(content);
pkg.scripts[name] = script;
fse.writeFileSync(join(this.path, 'package.json'), JSON.stringify(pkg, null, 2));
} catch (e) {
if (e.code != 'ENOENT') {
throw e;
}
}
}
saveMateria() {
let pkg;
try {
const content = fse.readFileSync(join(this.path, 'package.json')).toString();
pkg = JSON.parse(content);
} catch (e) {
if (e.code != 'ENOENT') {
throw e;
}
}
pkg.name = this.package;
fse.writeFileSync(join(this.path, 'package.json'), JSON.stringify(pkg, null, 2));
}
/**
Starts the materia app
@returns {Promise<number>}
*/
start(): Promise<number> {
const errors = {} as any;
this.logger.log(`${chalk.bold('(Start)')} Application ${chalk.yellow.bold(this.name)}`);
const p = this.database.started ? Promise.resolve() : this.database.start();
return p.catch((e) => {
errors.db = e;
}).then((e) => {
if (this.database.disabled) {
this.logger.log(` └── Database: ${chalk.red.bold('Disabled')}`);
} else {
this.logger.log(` └── Database: ${chalk.green.bold('OK')}`);
}
if (Object.keys(errors).length == 0) {
return this.entities.start().catch((err) => {
errors.entities = err;
});
} else {
return Promise.resolve();
}
}).then(() => {
if ( ! this.database.disabled ) {
this.logger.log(` └── Entities: ${chalk.green.bold('OK')}`);
}
if (Object.keys(errors).length == 0) {
return this.addons.start().catch((e) => {
errors.addons = e;
});
} else {
return Promise.resolve();
}
}).then(() => {
this.logger.log(` └── Addons: ${chalk.bold.green('OK')}`);
if (Object.keys(errors).length == 0 && this.mode == AppMode.PRODUCTION && ! this.live && ! this.database.disabled) {
return this.synchronizer.diff().then((diffs) => {
if (diffs && diffs.length == 0) {
this.logger.log(` └── Synchronize: ${chalk.bold('DB already up to date')}`);
return;
}
this.logger.log(` └─┬ Synchronize: ${chalk.yellow.bold('The database structure differs from entities.')}`);
return this.synchronizer.entitiesToDatabase(diffs, {}).then((actions) => {
// tslint:disable-next-line:max-line-length
this.logger.log(` │ └── Database: ${chalk.green.bold('Updated successfully')}. (Applied ${chalk.bold(actions.length.toString())} actions)`);
});
}).catch((e) => {
this.logger.log(` │ └── Database: ${chalk.red.bold('Fail - An action could not be applied: ' + e)}`);
e.errorType = 'sync';
throw e;
});
}
}).then(() =>
this.server.start({
fallback: Object.keys(errors).length > 0
})
);
}
startWithoutFailure() {
return this.server.start();
}
/**
Stops the materia app
@returns {Promise}
*/
stop(): Promise<void> {
return this.server.stop()
.then(() => this.database.stop())
.then(() => this.watcher.dispose())
.then(() => { this.status = false; });
}
getAllFiles(name, p) {
name = name || this.name;
p = p || this.path;
// let results = []
return new Promise((accept, reject) => {
fse.readdir(p, (err, files) => {
const promises = [];
if ( err ) {
return reject( err );
}
files.forEach((file) => {
if (file != '.DS_Store' &&
file != '.git' &&
file != 'history.json' &&
file != 'history' &&
file != 'node_modules' &&
file != 'bower_components' &&
file != '_site') {
promises.push(this._getFile(file, p));
}
});
Promise.all(promises).then((results) => {
accept({
filename: name,
path: p,
fullpath: p,
children: results
});
}, (reason) => {
reject(reason);
});
});
});
}
getFile(filepath: string): ITreeFile {
if ( ! filepath) {
throw new Error('You must provide a file path to retieve');
}
if ( ! fse.existsSync(filepath)) {
throw new Error('File with provided path not found');
}
const filename = basename(filepath);
const basePath = dirname(filepath);
const relativePath = normalize(relative(this.path, filepath));
return {
filename: filename,
fullpath: filepath,
path: basePath,
relativepath: relativePath,
isDir: false,
extension: extname(filepath).replace('.', '')
};
}
getFiles(depth: number, name?: string, p?: string): ITreeFile {
const splittedName = this.path.split(sep);
const length = splittedName.length;
const appFolder = splittedName[length - 1];
name = name || appFolder;
p = p || this.path;
const files = [];
const folders = [];
if (depth) {
const children = fse.readdirSync(p);
children.forEach((file) => {
if (file != '.DS_Store' && file != '.git') {
const stats = fse.lstatSync(join(p, file));
if (stats.isDirectory()) {
folders.push(this.getFiles(depth - 1, file, join(p, file)));
} else {
const fullpath = join(p, file);
const fileRelativepath = normalize(relative(this.path, fullpath));
files.push({
filename: file,
path: p,
isDir: false,
fullpath: fullpath,
relativepath: fileRelativepath,
extension: extname(file).replace('.', '')
});
}
}
});
}
const folderRelativepath = normalize(relative(this.path, p));
return {
filename: name,
path: dirname(p),
isDir: true,
fullpath: p,
relativepath: folderRelativepath,
incomplete: ! depth,
children: [...folders, ...files]
};
}
initializeStaticDirectory() {
let p = Promise.resolve();
if ( ! fse.existsSync(join(this.path, 'client'))) {
fse.mkdirSync(join(this.path, 'client'));
if ( ! fse.existsSync(join(this.path, 'client', 'index.html'))) {
fse.writeFileSync(join(this.path, 'client', 'index.html'), `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>`);
}
this.server.dynamicStatic.setPath(join(this.path , 'client'));
} else {
p = Promise.reject(new Error('Client folder already exists'));
}
return p;
}
getWatchableFiles() {
const files = this.getFiles(5);
return this._getWatchableFiles(files.children);
}
readFile(fullpath): string {
return fse.readFileSync(fullpath, 'utf-8');
}
saveFile(fullpath: string, content: string, opts?): Promise<any> {
let p = Promise.resolve();
if (opts && opts.mkdir) {
try {
fse.mkdirpSync(dirname(fullpath));
} catch (e) {
p = Promise.reject(e);
}
}
return p.then(() => {
fse.writeFileSync(fullpath, content);
}).catch((e) => {
throw e;
});
}
getMateriaVersion(): string {
const pkg = require('../package.json');
return pkg.version;
}
private doSelfMigrations() {
if ( this.selfMigration ) {
return this.selfMigration.check().then(() => {
delete this.selfMigration;
});
}
return Promise.resolve();
}
private _getFile(file, p) {
return new Promise((accept, reject) => {
fse.lstat(join(p, file), (err, stats) => {
if ( err ) {
return reject( err );
}
if (stats.isDirectory()) {
this.getAllFiles(file, join(p, file)).then((res) => {
accept(res);
}).catch((e) => {
reject(e);
});
} else {
accept({
filename: file,
path: p,
fullpath: join(p, file)
});
}
});
});
}
private _getWatchableFiles(files) {
const res = [];
for (const file of files) {
if ( ! Array.isArray(file.children)) {
const filenameSplit = file.filename.split('.');
if (['json', 'js', 'coffee', 'sql'].indexOf(filenameSplit[filenameSplit.length - 1]) != -1) {
res.push(file);
}
} else {
const t = this._getWatchableFiles(file.children);
t.forEach((a) => { res.push(a); });
}
}
return res;
}
} | the_stack |
namespace MxTests {
"use strict";
import Enumerator = mx.Enumerator;
import Enumerable = mx.Enumerable;
import Comparer = mx.Comparer;
import EqualityComparer = mx.EqualityComparer;
import Collection = mx.Collection;
import List = mx.List;
import ReadOnlyCollection = mx.ReadOnlyCollection;
import Dictionary = mx.Dictionary;
import SortedList = mx.SortedList;
import HashSet = mx.HashSet;
import LinkedList = mx.LinkedList;
import Queue = mx.Queue;
import Stack = mx.Stack;
import Lookup = mx.Lookup;
import RuntimeComparer = mx.RuntimeComparer;
var Enumerator = mx.Enumerator,
Enumerable = mx.Enumerable,
Comparer = mx.Comparer,
EqualityComparer = mx.EqualityComparer,
Collection = mx.Collection,
List = mx.List,
ReadOnlyCollection = mx.ReadOnlyCollection,
KeyValuePair = mx.KeyValuePair,
Dictionary = mx.Dictionary,
SortedList = mx.SortedList,
HashSet = mx.HashSet,
LinkedList = mx.LinkedList,
LinkedListNode = mx.LinkedListNode,
Queue = mx.Queue,
Stack = mx.Stack;
/* Classes
---------------------------------------------------------------------- */
interface SimpleObject {
name: string;
value: number;
}
// class without equality-comparer
class SimpleClass {
};
// class overriding '__hash__' and '__equals__' methods.
class SimpleClassWithComparer implements RuntimeComparer, SimpleObject {
constructor(val: number) {
this.value = val;
this.name = val.toString();
}
public name: string;
public value: number;
__hash__(): number {
return mx.hash(this.value, this.name);
}
__equals__(obj: any) {
return obj instanceof SimpleClassWithComparer && obj.value === this.value && obj.name === this.name;
}
};
/* Tests
---------------------------------------------------------------------- */
namespace MultiplexTests {
QUnit.module("Multiplex");
QUnit.test("Multiplex Array", function (assert) {
var _source = mx([1, 2, 3, 4]);
assert.ok(MxCount(_source) === 4, "Passed!");
});
QUnit.test("Multiplex String", function (assert) {
var _source = mx("Multiplex");
assert.ok(MxCount(_source) === 9, "Passed!");
});
QUnit.test("Multiplex Object", function (assert) {
var _source = mx({ name: "mx", id: 1 });
assert.ok(MxCount(_source) === 2, "Passed!");
});
QUnit.test("Multiplex Array-like", function (assert) {
var _source = mx(arguments);
assert.ok(MxCount(_source) === 1, "Passed!");
});
//QUnit.test("Multiplex Iterable", function (assert) {
// var _set = new Set<number>(),
// _source = mx(_set);
// _set.add(1);
// _set.add(2);
// _set.add(3);
// assert.ok(MxCount(_source) === 3, "Passed!");
//});
QUnit.test("Multiplex Custom Enumerator", function (assert) {
var _source = mx(<Enumerable<number>>{
getEnumerator: function (): Enumerator<number> {
var count = 3, index = 0;
return {
current: undefined,
next: function () {
if (index++ < count) {
this.current = index;
return true;
}
else {
this.current = undefined;
return false;
}
}
};
}
});
assert.ok(MxCount(_source) === 3, "Passed!");
});
QUnit.test("Multiplex Generator", function (assert) {
try {
var _source = eval("mx(function* () { yield 1; yield 2; yield 3; })");
assert.ok(MxCount(_source) === 3, "Passed!");
}
catch (e) { assert.ok(true, "Generator not implemented by the browser"); }
});
QUnit.test("Multiplex Legacy Generator", function (assert) {
var _source = mx(function () {
var count = 3,
index = 0;
return new Enumerator<number>(function (yielder) {
if (index++ < count) {
yielder(index);
}
});
});
assert.ok(MxCount(_source) === 3, "Passed!");
});
QUnit.test("mx.range", function (assert) {
var _source = mx.range(0, 4);
assert.deepEqual(_source.toArray(), [0, 1, 2, 3], "Passed!");
});
QUnit.test("mx.repeat", function (assert) {
var _source = mx.repeat(1, 4);
assert.deepEqual(_source.toArray(), [1, 1, 1, 1], "Passed!");
});
QUnit.test("mx.empty", function (assert) {
var _source = mx.empty();
assert.ok(MxCount(_source) === 0, "Passed!");
});
QUnit.test("mx.is", function (assert) {
assert.ok(mx.is(mx.range(1, 10)), "Enumerable Passed!");
assert.ok(mx.is([1]), "Array Passed!");
assert.ok(mx.is("mx"), "String Passed!");
//assert.ok(mx.is(new Set()), "Iterable Passed!");
assert.ok(mx.is({
getEnumerator: function (): Enumerator<number> {
var count = 3, index = 0;
return {
current: undefined,
next: function () {
if (index++ < count) {
this.current = index;
return true;
}
else {
this.current = undefined;
return false;
}
}
};
}
}), "Custom Enumerator Passed!");
try {
assert.ok(mx.is(eval("mx(function* () { yield 1; yield 2; yield 3; })")), "Generator Passed!");
}
catch (e) { assert.ok(true, "Generator not implemented by the browser"); }
});
/* Factory methods
---------------------------------------------------------------------- */
function MxCount(source: Enumerable<any>): number {
var _e = source.getEnumerator(),
_i = 0;
while (_e.next()) {
_i++;
}
return _i;
}
}
namespace RuntimeTests {
QUnit.module("Runtime");
QUnit.test("hash", function (assert) {
assert.ok(mx.hash(null) === 0, "hash null!");
assert.ok(mx.hash(undefined) === 0, "hash undefined!");
assert.ok(mx.hash(10) === mx.hash(10), "hash integer number!");
assert.ok(mx.hash(10.5) === mx.hash(10.5), "hash float number!");
assert.ok(mx.hash("string") === mx.hash("string"), "hash string!");
assert.ok(mx.hash(true) === mx.hash(true), "hash boolean!");
assert.ok(mx.hash(new Date(2015, 0, 1)) === mx.hash(new Date(2015, 0, 1)), "hash date!");
assert.ok(mx.hash({ name: "A" }) === mx.hash({ name: "A" }), "hash object literal!");
assert.ok(mx.hash(new SimpleClass()) !== mx.hash(new SimpleClass()), "hash class instance!");
assert.ok(mx.hash(new SimpleClassWithComparer(10)) === mx.hash(new SimpleClassWithComparer(10)), "hash class instance overriding __hash__ method!");
assert.ok(mx.hash(10, 10.5, "string", new Date(2015, 0, 1)) === mx.hash(10, 10.5, "string", new Date(2015, 0, 1)), "combine hash codes!");
});
QUnit.test("equals", function (assert) {
assert.ok(mx.equals(null, null) === true, "equals null!");
assert.ok(mx.equals(undefined, undefined) === true, "equals undefined!");
assert.ok(mx.equals(10, 10), "equals integer number!");
assert.ok(mx.equals(10.5, 10.5), "equals float number!");
assert.ok(mx.equals("string", "string"), "equals string!");
assert.ok(mx.equals(true, true), "equals boolean!");
assert.ok(mx.equals(new Date(2015, 0, 1), new Date(2015, 0, 1)), "equals date!");
assert.ok(mx.equals({ name: "A" }, { name: "A" }), "equals object literal!");
assert.ok(mx.equals(new SimpleClass(), new SimpleClass()) === false, "equals class instance!");
assert.ok(mx.equals(new SimpleClass(), new SimpleClass(), EqualityComparer.create((obj) => 0, (a, b) => true)), "equals class instance using comparer!");
assert.ok(mx.equals(new SimpleClassWithComparer(10), new SimpleClassWithComparer(10)), "equals class instance overriding __equals__ method!");
});
QUnit.test("compare", function (assert) {
assert.ok(mx.compare(1, null) === 1 && mx.compare(null, 1) === -1 && mx.compare(null, null) === 0, "compare null!");
assert.ok(mx.compare(1, 0) === 1 && mx.compare(0, 1) === -1 && mx.compare(1, 1) === 0, "compare numbers!");
assert.ok(mx.compare("B", "A") === 1 && mx.compare("A", "B") === -1 && mx.compare("A", "A") === 0, "compare string!");
assert.ok(mx.compare(true, false) === 1 && mx.compare(false, true) === -1 && mx.compare(true, true) === 0, "compare bolean!");
assert.ok(mx.compare(new Date(2015, 0, 2), new Date(2015, 0, 1)) === 1 && mx.compare(new Date(2015, 0, 1), new Date(2015, 0, 2)) === -1 && mx.compare(new Date(2015, 0, 1), new Date(2015, 0, 1)) === 0, "compare date!");
assert.ok(mx.compare({ name: "A" }, { name: "B" }) === 0, "compare objects!");
});
QUnit.test("lambda", function (assert) {
var _f1 = mx.runtime.lambda<number, number>("t => t * t"),
_f2 = mx.runtime.lambda<number, number, number>("(t, u) => t + u"),
_f3 = mx.runtime.lambda<number, number, number, number>("(t, u, r) => t + u + r"),
_f4 = mx.runtime.lambda<number, string, { id: number; name: string }>("(t, u) => {id:t, name:u}");
assert.ok(_f1(2) === 4, "square root lambda!");
assert.ok(_f2(1, 2) === 3, "sum of 2 numbers lambda!");
assert.ok(_f3(1, 2, 3) === 6, "sum of 3 numbers lambda!");
assert.ok(_f4(1, "A").id === 1 && _f4(1, "A").name === "A", "object literal lambda!");
});
}
namespace LinqTests {
QUnit.module("Linq");
QUnit.test("aggregate", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).aggregate((a, b) => a + b) === 45, "Aggregate 10 numbers without seed!");
assert.ok(mx(_arr).aggregate(10, (a, b) => a + b) === 55, "Aggregate 10 numbers with seed!");
assert.ok(mx(_arr).aggregate(10, (a, b) => a + b, t => t * 2) === 110, "Aggregate 10 numbers with seed and result selector!");
});
QUnit.test("all", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).all(t => t < 100) === true, "First 10 numbers less than 100!");
assert.ok(mx(_arr).all(t => t < 5) === false, "First 10 numbers less than 5!");
});
QUnit.test("any", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).any() === true, "First 10 numbers!");
assert.ok(mx(_arr).any(t => t % 2 === 0) === true, "Any of the first 10 numbers is even!");
assert.ok(mx(_arr).any(t => t > 10) === false, "Any of the first 10 numbers greater than 10!");
});
QUnit.test("average", function (assert) {
assert.ok(mx(CreateNumberArray()).average() === 4.5, "Average of the first 10 numbers!");
assert.throws(() => mx(CreateObjectLiteralArray()).average(), "throws an exception for average of non numeric values!");
assert.throws(() => mx([]).average(), "throws an exception for average of empty collection!");
});
QUnit.test("concat", function (assert) {
var _s1 = [1, 2, 3],
_s2 = [3, 4],
_arr = CreateNumberArray();
assert.deepEqual(mx(_s1).concat(_s2).toArray(), [1, 2, 3, 3, 4], "Concat two array!");
assert.ok(mx(_arr).concat(_arr).count() === 20, "Concat the first 10 numbers to itself!");
});
QUnit.test("contains", function (assert) {
var _arr1 = CreateNumberArray(),
_arr2 = CreateSimpleClassArray(),
_arr3 = CreateSimpleClassWithComparerArray(),
_arr4 = CreateComplexObjectLiteralArray();
assert.ok(mx(_arr1).contains(1) === true, "1 contains in the first 10 numbers!");
assert.ok(mx(_arr1).contains(10) === false, "10 does not contains in the first 10 numbers!");
assert.ok(mx(_arr2).contains(new SimpleClass()) === false, "Class instance without equality-comparer!");
assert.ok(mx(_arr2).contains(new SimpleClass(), { hash: () => 0, equals: () => true }) === true, "Class instance with equality-comparer!");
assert.ok(mx(_arr3).contains(new SimpleClassWithComparer(5)) === true, "Class instance overriding equality-comparer!");
assert.ok(mx(_arr4).contains({ name: "n5", inner: { index: 5, val: {} } }) === true, "Object literal without equality-comparer!");
assert.ok(mx(_arr4).contains({ name: "n5", inner: null }, {
hash: o => mx.hash(o.name),
equals: (a, b) => a.name === b.name
}) === true, "Object literal with equality-comparer!");
});
QUnit.test("count", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).count() === 10, "Count of the first 10 numbers!");
assert.ok(mx(_arr).count(t => t % 2 === 0) === 5, "Count of the first even 10 numbers!");
});
QUnit.test("defaultIfEmpty", function (assert) {
var _arr = CreateNumberArray();
assert.deepEqual(mx([]).defaultIfEmpty(1).toArray(), [1], "Empty array devalut value!");
assert.ok(mx(_arr).defaultIfEmpty(1).count() === 10, "Count of the first 10 numbers with defaultIfEmpty!");
assert.ok(mx(_arr).where(t => t > 100).defaultIfEmpty(10).count() === 1, "Count of the first 10 numbers greater than 100 with defaultIfEmpty!");
});
QUnit.test("distinct", function (assert) {
var _arr1 = CreateObjectLiteralArray(),
_arr2 = CreateComplexObjectLiteralArray(),
_arr3 = CreateNumberArray(),
_arr4 = CreateFloatNumberArray(),
_arr5 = CreateStringArray(),
_arr6 = CreateDateArray(),
_arr7 = CreateBooleanArray(),
_arr8 = CreateSimpleClassWithComparerArray(),
_arr9 = CreateSimpleClassArray();
assert.ok(mx(_arr1).distinct().count() === 1, "Array of 10 empty object literal!");
assert.ok(mx(_arr2).distinct().count() === 10, "Array of 10 distinct complex object literal!");
assert.ok(mx(_arr3).distinct().count() === 10, "Array of 10 distinct numbers!");
assert.ok(mx(_arr4).distinct().count() === 10, "Array of 10 distinct float numbers!");
assert.ok(mx(_arr5).distinct().count() === 10, "Array of 10 distinct strings!");
assert.ok(mx(_arr6).distinct().count() === 10, "Array of 10 distinct date objects!");
assert.ok(mx(_arr7).distinct().count() === 2, "Array of 10 boolean values!");
assert.ok(mx(_arr8).distinct().count() === 10, "Array of 10 distinct class instances overriding equality-comparer!");
assert.ok(mx(_arr9).distinct().count() === 10, "Array of 10 distinct class instances!");
assert.ok(mx(_arr2).distinct({
hash: o => mx.hash(o.name),
equals: (a, b) => a.name === b.name
}).count() === 10, "Array of 10 distinct complex object literal with equality-comparer!");
});
QUnit.test("except", function (assert) {
var _arr1 = CreateNumberArray(),
_arr2 = CreateObjectLiteralArray(),
_arr3 = CreateComplexObjectLiteralArray();
assert.ok(mx(_arr1).except(CreateNumberArray()).count() === 0, "Array of first 10 numbers except first 10 numbers!");
assert.deepEqual(mx(_arr1).except([0, 1, 2, 3, 4]).toArray(), [5, 6, 7, 8, 9], "Array of first 10 numbers except first 5 numbers!");
assert.ok(mx(_arr2).except([{}]).count() === 0, "Array of 10 empty object literal except an empty object literal!");
assert.ok(mx(_arr3).except([{ name: "n5", inner: null }]).count() === 10, "Array of 10 distinct complex object literal without equality-comparer!");
assert.ok(mx(_arr3).except([{ name: "n5", inner: null }], {
hash: o => mx.hash(o.name),
equals: (a, b) => a.name === b.name
}).count() === 9, "Array of 10 distinct complex object literal with equality-comparer!");
});
QUnit.test("elementAt", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).elementAt(0) === 0, "First element of the first 10 numbers!");
assert.throws(() => mx(_arr).elementAt(100), "throws an exception for 100th element of the first 10 numbers!");
});
QUnit.test("first", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).first() === 0, "First element of the first 10 numbers!");
assert.ok(mx(_arr).first(t => t > 5) === 6, "First element greater than 5 of the first 10 numbers!");
assert.throws(() => mx([]).first(), "throws an exception getting first element of an empty collection!");
assert.throws(() => mx(_arr).first(t => t > 100), "throws an exception getting first element greater than 100 of the first 10 numbers!");
});
QUnit.test("firstOrDefault", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).firstOrDefault() === 0, "First element of the first 10 numbers or default!");
assert.ok(mx(_arr).firstOrDefault(t => t > 5) === 6, "First element greater than 5 of the first 10 numbers or default!");
assert.ok(mx(_arr).firstOrDefault(t => t > 100) === null, "First element greater than 100 of the first 10 numbers or default!");
assert.ok(mx(_arr).firstOrDefault(t => t > 100, 100) === 100, "First element greater than 100 of the first 10 numbers or 100 as default!");
});
QUnit.test("forEach", function (assert) {
var _arr = CreateNumberArray(),
_sum = 0;
mx(_arr).forEach(t => _sum += t);
assert.ok(_sum === 45, "ForEach operation on the first 10 numbers!");
});
QUnit.test("groupBy", function (assert) {
var _arr1 = CreateObjectLiteralArray(),
_arr2 = CreateComplexObjectLiteralArray();
assert.ok(mx(_arr1).groupBy(t => t).count() === 1, "Group 10 distinct empty object literals!");
assert.ok(mx(_arr2).groupBy(t => t.name).count() === 10, "Group 10 distinct complex object literals by name!");
assert.ok(mx(_arr2).groupBy(t => t.name).first().key === "n0", "Group 10 distinct complex object literals by name, retrieve first key!");
assert.ok(mx(_arr2).groupBy(t => t.name).first().count() === 1, "Group 10 distinct complex object literals by name, retrieve first group count!");
});
QUnit.test("groupJoin", function (assert) {
var _arr1 = [{ name: "A", val: 1 }, { name: "B", val: 2 }, { name: "C", val: 3 }, { name: "D", val: 4 }],
_arr2 = [{ code: "A" }, { code: "A" }, { code: "B" }, { code: "B" }, { code: "C" }],
_result = mx(_arr1).groupJoin(_arr2, t => t.name, u => u.code, (t, u) => ({ item: t, group: u }));
assert.ok(_result.count() === 4, "groupJoin 2 complex-object array, getting count");
assert.ok(_result.first().item.name === "A", "groupJoin 2 complex-object array, getting item");
assert.ok(_result.first().group.count() === 2, "groupJoin 2 complex-object array, getting group count");
assert.ok(_result.last().group.count() === 0, "groupJoin 2 complex-object array, getting empty group count");
});
QUnit.test("intersect", function (assert) {
var _arr1 = CreateNumberArray(),
_arr2 = CreateObjectLiteralArray(),
_arr3 = CreateComplexObjectLiteralArray();
assert.ok(mx(_arr1).intersect(CreateNumberArray()).count() === 10, "Array of first 10 numbers intersect with first 10 numbers!");
assert.deepEqual(mx(_arr1).intersect([2, 3, 4]).toArray(), [2, 3, 4], "Array of first 10 numbers intersect with 3 numbers!");
assert.ok(mx(_arr2).intersect([{}]).count() === 10, "Array of 10 empty object literal intersect with an empty object literal!");
assert.ok(mx(_arr3).intersect([{ name: "n5", inner: null }]).count() === 0, "Array of 10 distinct complex object literal without equality-comparer!");
assert.ok(mx(_arr3).intersect([{ name: "n5", inner: null }], {
hash: o => mx.hash(o.name),
equals: (a, b) => a.name === b.name
}).count() === 1, "Array of 10 distinct complex object literal with equality-comparer!");
});
QUnit.test("join", function (assert) {
var _arr1 = [{ name: "A", val: 1 }, { name: "B", val: 2 }, { name: "C", val: 3 }, { name: "D", val: 4 }],
_arr2 = [{ code: "A" }, { code: "A" }, { code: "B" }, { code: "B" }, { code: "C" }],
_arr3 = CreateObjectLiteralArray(),
_result = mx(_arr1).join(_arr2, t => t.name, u => u.code, (t, u) => ({ item1: t, item2: u }));
assert.ok(_result.count() === 5, "join 2 complex-object array, getting count");
assert.ok(_result.first().item1.name === "A" && _result.first().item2.code === "A", "join 2 complex-object array, getting item");
assert.ok(mx(_arr3).join(mx(CreateObjectLiteralArray()), t => t, u => u, (t, u) => t).count() === 100, "join 2 empty object-literal array");
assert.ok(mx(mx.empty()).join(mx(_arr3), t => t, u => u, (t, u) => t).count() === 0, "join empty collection with an array");
});
QUnit.test("last", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).last() === 9, "Last element of the first 10 numbers!");
assert.ok(mx(_arr).last(t => t < 5) === 4, "Last element less than 5 of the first 10 numbers!");
assert.throws(() => mx([]).last(), "throws an exception getting last element of an empty collection!");
assert.throws(() => mx(_arr).last(t => t > 100), "throws an exception getting first element greater than 100 of the first 10 numbers!");
});
QUnit.test("lastOrDefault", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).lastOrDefault() === 9, "Last element of the first 10 numbers or default!");
assert.ok(mx(_arr).lastOrDefault(t => t < 5) === 4, "Last element greater than 5 of the first 10 numbers or default!");
assert.ok(mx(_arr).lastOrDefault(t => t > 100) === null, "Last element greater than 100 of the first 10 numbers or default!");
assert.ok(mx(_arr).lastOrDefault(t => t > 100, 100) === 100, "Last element greater than 100 of the first 10 numbers or 100 as default!");
});
QUnit.test("max", function (assert) {
var _arr1 = CreateNumberArray(),
_arr2 = CreateStringArray(),
_arr3 = CreateComplexObjectLiteralArray();
assert.ok(mx(_arr1).max() === 9, "Maximum of the first 10 numbers!");
assert.ok(mx(_arr2).max() === "9_string", "Maximum of the 10 string array!");
assert.ok(mx(_arr3).max(t => t.name) === "n9", "Maximum of a complex array by selector!");
assert.throws(() => mx([]).max(), "throws an exception getting maximum of an empty collection!");
});
QUnit.test("min", function (assert) {
var _arr1 = CreateNumberArray(),
_arr2 = CreateStringArray(),
_arr3 = CreateComplexObjectLiteralArray();
assert.ok(mx(_arr1).min() === 0, "Minimum of the first 10 numbers!");
assert.ok(mx(_arr2).min() === "0_string", "Minimum of the 10 string array!");
assert.ok(mx(_arr3).min(t => t.name) === "n0", "Minimum of a complex array by selector!");
assert.throws(() => mx([]).min(), "throws an exception getting minimum of an empty collection!");
});
QUnit.test("ofType", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).ofType(Number).count() === 10, "Cast array of numbers to number!");
assert.ok(mx(_arr).ofType(String).count() === 0, "Cast array of numbers to string!");
});
QUnit.test("orderBy", function (assert) {
var _arr1 = CreateNumberArray(),
_arr2 = CreateComplexObjectLiteralArray(),
_arr3 = [{ name: "a", val: 1 }, { name: "a", val: 2 }, { name: "b", val: 1 }, { name: "c", val: 2 }],
_result = [{ name: "a", val: 1 }, { name: "b", val: 1 }, { name: "a", val: 2 }, { name: "c", val: 2 }]
assert.deepEqual(mx(_arr1).orderBy(t => t).take(5).toArray(), [0, 1, 2, 3, 4], "Order array of numbers ascending!");
assert.ok(mx(_arr2).orderBy(t => t.name).thenByDescending(t => t.inner.index).first().name === "n0", "Order array of complex object by 'name' ascending then by 'inner.index' descending !");
assert.deepEqual(mx(_arr3).orderBy(t => t.val).thenBy(t => t.name).toArray(), _result, "Order and thenBy!");
assert.ok(mx(_arr2).orderBy(t => t.name, {
hash: o => mx.hash(o),
equals: (a, b) => a === b
}).first().name === "n0", "Order array of complex object ascending with comparer!");
});
QUnit.test("orderByDescending", function (assert) {
var _arr1 = CreateNumberArray(),
_arr2 = CreateComplexObjectLiteralArray(),
_arr3 = [{ name: "a", val: 1 }, { name: "a", val: 2 }, { name: "b", val: 1 }, { name: "c", val: 2 }],
_result = [{ name: "a", val: 2 }, { name: "c", val: 2 }, { name: "a", val: 1 }, { name: "b", val: 1 }];
assert.deepEqual(mx(_arr1).orderByDescending(t => t).take(5).toArray(), [9, 8, 7, 6, 5], "Order array of numbers descending!");
assert.ok(mx(_arr2).orderByDescending(t => t.name).thenByDescending(t => t.inner.index).first().name === "n9", "Order array of complex object by 'name' descending then by 'inner.index' descending !");
assert.deepEqual(mx(_arr3).orderByDescending(t => t.val).thenBy(t => t.name).toArray(), _result, "Order descending and thenBy!");
assert.ok(mx(_arr2).orderByDescending(t => t.name, {
hash: o => mx.hash(o),
equals: (a, b) => a === b
}).first().name === "n9", "Order array of complex object descending with comparer!");
});
QUnit.test("reverse", function (assert) {
var _arr1 = CreateNumberArray(),
_arr2 = CreateStringArray();
assert.deepEqual(mx(_arr1).reverse().take(5).toArray(), [9, 8, 7, 6, 5], "Reverse array of first 10 numbers!");
assert.ok(mx(_arr2).reverse().first() === "9_string", "Reverse array of strings!");
});
QUnit.test("sequenceEqual", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).sequenceEqual(mx(CreateNumberArray())), "sequenceEqual on array of numbers!");
assert.ok(mx([1, 2, 3]).sequenceEqual(mx([1, 2])) === false, "sequenceEqual on inharmonic arrays of numbers!");
assert.ok(mx([{ name: "a" }]).sequenceEqual(mx([{ name: "a", val: 1 }]), {
hash: o => mx.hash(o.name),
equals: (a, b) => a.name === b.name
}), "sequenceEqual on arrays of objects with comparer!");
});
QUnit.test("select", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).select(t => t + 100).first() === 100, "select first 10 numbers plus 100!");
assert.ok(mx(_arr).select((t, i) => i).last() === 9, "select index while enumerating 10 numbers!");
});
QUnit.test("selectMany", function (assert) {
var _arr = [{ name: "A", values: [1, 2, 3, 4] }, { name: "B", values: [5, 6, 7, 8] }];
assert.ok(mx(_arr).selectMany(t => t.values).count() === 8, "selectMany on complex objects!");
assert.deepEqual(mx(_arr).selectMany(t => t.values, (t, u) => ({ name: t.name, value: u })).first(), { name: "A", value: 1 }, "selectMany on complex objects with result selector!");
});
QUnit.test("single", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx([1]).single() === 1, "Single element of a single array!");
assert.ok(mx(_arr).single(t => t === 1) === 1, "Single element equal to 1 of the first 10 numbers!");
assert.throws(() => mx([]).single(), "throws an exception getting single element of an empty collection!");
assert.throws(() => mx(_arr).single(), "throws an exception getting single element of an collection containing more than one element!");
assert.throws(() => mx(_arr).single(t => t > 100), "throws an exception getting single element greater than 100 of the first 10 numbers!");
assert.throws(() => mx(_arr).single(t => t < 10), "throws an exception getting single element less than 10 of the first 10 numbers!");
});
QUnit.test("singleOrDefault", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx([1]).singleOrDefault() === 1, "Single element of a single array or default!");
assert.ok(mx([]).singleOrDefault() === null, "Single element of an empty array or default!");
assert.ok(mx(_arr).singleOrDefault(t => t === 1) === 1, "Single element equal to 1 of the first 10 numbers or default!");
assert.ok(mx(_arr).singleOrDefault(t => t === 100, 100) === 100, "Single element of an empty array or default!");
assert.throws(() => mx(_arr).singleOrDefault(), "throws an exception getting single element of an collection containing more than one element!");
assert.throws(() => mx(_arr).singleOrDefault(t => t < 10), "throws an exception getting single element less than 10 of the first 10 numbers!");
});
QUnit.test("skip", function (assert) {
var _arr = CreateNumberArray();
assert.deepEqual(mx(_arr).skip(5).toArray(), [5, 6, 7, 8, 9], "Skip 5 element of a the first 10 numbers!");
assert.deepEqual(mx(_arr).where(t => t % 2 === 0).skip(3).toArray(), [6, 8], "Skip 3 element of a the first 10 even numbers!");
assert.ok(mx(_arr).skip(0).count() === 10, "Skip no items!");
assert.ok(mx(_arr).skip(100).count() === 0, "Skip more than count of the collection!");
});
QUnit.test("skipWhile", function (assert) {
var _arr = CreateNumberArray();
assert.deepEqual(mx(_arr).skipWhile(t => t < 5).toArray(), [5, 6, 7, 8, 9], "Skip while elements are less than 5 from the first 10 even numbers!");
assert.ok(mx(_arr).skipWhile(t => t > 5).count() === 10, "Skip while elements are greater than 5 from the first 10 even numbers!");
});
QUnit.test("sum", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).sum() === 45, "Sum of the first 10 numbers!");
assert.ok(mx(_arr).sum(t => t * 2) === 90, "Sum of the first 10 numbers multiply by 2!");
assert.throws(() => mx(CreateObjectLiteralArray()).sum(), "throws an exception getting sum of non numeric elements!");
assert.throws(() => mx(CreateComplexObjectLiteralArray()).sum(t => <any>t.name), "throws an exception getting sum of non numeric properties!");
});
QUnit.test("take", function (assert) {
var _arr = CreateNumberArray();
assert.deepEqual(mx(_arr).take(5).toArray(), [0, 1, 2, 3, 4], "Take 5 element of a the first 10 numbers!");
assert.deepEqual(mx(_arr).where(t => t % 2 === 0).take(3).toArray(), [0, 2, 4], "Take 3 element of a the first 10 even numbers!");
assert.ok(mx(_arr).take(0).count() === 0, "Take no items!");
assert.ok(mx(_arr).take(100).count() === 10, "Take more than count of the collection!");
});
QUnit.test("takeWhile", function (assert) {
var _arr = CreateNumberArray();
assert.deepEqual(mx(_arr).takeWhile(t => t < 5).toArray(), [0, 1, 2, 3, 4], "Take while elements are less than 5 from the first 10 even numbers!");
assert.ok(mx(_arr).takeWhile(t => t > 5).count() === 0, "Take while elements are greater than 5 from the first 10 even numbers!");
});
QUnit.test("toArray", function (assert) {
var _arr = CreateNumberArray();
assert.deepEqual(mx(_arr).where(t => t < 5).toArray(), [0, 1, 2, 3, 4], "Elements less than 5 from the first 10 even numbers!");
});
QUnit.test("toDictionary", function (assert) {
var _arr = CreateComplexObjectLiteralArray();
assert.ok(mx(_arr).toDictionary(t => t.name).count() === 10, "toDictionary key-selector!");
assert.ok(mx(_arr).toDictionary(t => t.name, t => t.inner.index).first().value === 0, "toDictionary key-selector & element-selector!");
assert.ok(mx(_arr).toDictionary(t => t, {
hash: o => mx.hash(o.name),
equals: (a, b) => a.name === b.name
}).first().key.name === "n0", "toDictionary key-selector & comparer!");
assert.ok(mx(_arr).toDictionary(t => t, t => t.inner.index, {
hash: o => mx.hash(o.name),
equals: (a, b) => a.name === b.name
}).first().value === 0, "toDictionary key-selector, element-selector & comparer!");
assert.throws(() => mx([1, 1, 2]).toDictionary(t => t), "throws an exception with duplicate keys!");
});
QUnit.test("toList", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).toList().count() === 10, "toList first 10 numbers!");
assert.ok(mx(_arr).toList()[1] === 1, "toList indexer first 10 numbers!");
});
QUnit.test("toLookup", function (assert) {
var _arr1 = CreateNumberArray(),
_arr2 = CreateComplexObjectLiteralArray();
assert.ok(mx(_arr1).toLookup(t => t).count() === 10, "toLookup first 10 numbers!");
assert.ok(mx(_arr1).toLookup(t => t).get(1).count() === 1, "toLookup indexer first 10 numbers!");
assert.ok(mx(_arr2).toLookup(t => t, {
hash: o => mx.hash(o.name),
equals: (a, b) => a.name === b.name
}).first().first().name === "n0", "toLookup with key-selector and comparer!");
assert.ok(mx(_arr2).toLookup(t => t, t => t.name, {
hash: (o) => mx.hash(o.name),
equals: (a, b) => a.name === b.name
}).first().first() === "n0", "toLookup with key-selector, element-selector and comparer!");
});
QUnit.test("union", function (assert) {
var _arr = CreateNumberArray();
assert.ok(mx(_arr).union(CreateNumberArray()).count() === 10, "Union first 10 numbers with itself!");
assert.deepEqual(mx([1, 2]).union(mx([2, 3])).toArray(), [1, 2, 3], "Union two arrays!");
});
QUnit.test("where", function (assert) {
var _arr1 = CreateNumberArray(),
_arr2 = CreateComplexObjectLiteralArray();
assert.ok(mx(_arr1).where(t => t < 5).count() === 5, "Filter first 10 numbers less than 10!");
assert.ok(mx(_arr2).where(t => t.inner.index < 5).count() === 5, "Filter complex object by value!");
assert.deepEqual(mx(_arr1).where(t => t <= 1).toArray(), [0, 1], "Deep equal check!");
});
QUnit.test("zip", function (assert) {
assert.ok(mx([1, 2]).zip([3, 4], (t, u) => t + u).first() === 4, "Zip two numeric array!");
assert.ok(mx([1, 2]).zip([3], (t, u) => t + u).count() === 1, "Zip two inharmonic numeric array!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateObjectLiteralArray(): Object[] {
return mx.range(0, 10).select(t => ({})).toArray();
}
function CreateComplexObjectLiteralArray(): { name: string; inner: { index: number; val: Object } }[] {
return mx.range(0, 10).select(t => ({
name: "n" + t,
inner: {
index: t,
val: {}
}
})).toArray();
}
function CreateSimpleClassArray(): SimpleClass[] {
return mx.range(0, 10).select(t => new SimpleClass()).toArray();
}
function CreateSimpleClassWithComparerArray(): SimpleClassWithComparer[] {
return mx.range(0, 10).select(t => new SimpleClassWithComparer(t)).toArray();
}
function CreateNumberArray(): number[] {
return mx.range(0, 10).toArray();
}
function CreateFloatNumberArray(): number[] {
return mx.range(0, 10).select(t => t + 0.1).toArray();
}
function CreateStringArray(): string[] {
return mx.range(0, 10).select(t => t + "_string").toArray();
}
function CreateDateArray(): Date[] {
return mx.range(0, 10).select(t => new Date(new Date().getTime() + t)).toArray();
}
function CreateBooleanArray(): boolean[] {
return mx.range(0, 10).select(t => t % 2 === 0).toArray();
}
}
namespace CollectionTests {
QUnit.module("Collection");
QUnit.test("constructor", function (assert) {
assert.ok(CreateCollection().count() === 5, "initialize a Collection using specified collection!");
});
QUnit.test("count", function (assert) {
var _col = CreateCollection();
assert.ok(_col.count() === 5, "collection containing count!");
assert.throws(() => new Collection().count(), "throws an error getting count of an empty collection.");
});
QUnit.test("copyTo", function (assert) {
var _col = CreateCollection(),
_arr = new Array(_col.count());
_col.copyTo(_arr, 0);
assert.deepEqual(_arr, [1, 2, 3, 4, 5], "Collection copy to an array!");
assert.throws(() => _col.copyTo([], 0), "throws an error when the number of elements is greater than the number of elements that the destination array can contain!");
});
QUnit.test("collection enumerable", function (assert) {
var _col = CreateCollection();
assert.deepEqual(_col.select(t => t * 2).where(t => t > 5).toArray(), [6, 8, 10], "select-where-toArray over a collection!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateCollection(): Collection<number> {
return new Collection(mx.range(1, 5));
}
}
namespace ListTests {
QUnit.module("List");
QUnit.test("constructor", function (assert) {
assert.ok(new List<number>().count() === 0, "an empty list!");
assert.ok(new List<number>(10).count() === 10, "an empty list with initial capacity!");
assert.ok(new List<number>(1, 2, 3, 4, 5).count() === 5, "list initializer!");
assert.ok(new List<number>(mx.range(0, 10)).count() === 10, "list from an Enumerable!");
});
QUnit.test("indexer", function (assert) {
var _list = CreateList();
assert.ok(_list[0] === 1, "indexer get!");
_list[0] = 0;
assert.ok(_list[0] === 0 && _list.first() === 0, "indexer set!");
});
QUnit.test("add", function (assert) {
var _list = new List();
_list.add(1);
assert.ok(_list[0] === 1, "add!");
assert.ok(_list.count() === 1, "add count!");
});
QUnit.test("addRange", function (assert) {
var _list = new List();
_list.addRange(mx.range(0, 10));
assert.ok(_list.count() === 10, "add range of numbers!");
});
QUnit.test("asReadOnly", function (assert) {
var _rlist = new List<number>(mx.range(0, 10)).asReadOnly();
assert.ok(_rlist.count() === 10, "readOnlyCollection count!");
assert.ok(_rlist[0] === 0, "readOnlyCollection get!");
});
QUnit.test("binarySearch", function (assert) {
var _list1 = new List<number>(mx.range(0, 100)),
_list2 = new List<{ index: number }>(mx.range(0, 100).select(t => ({ index: t })));
assert.ok(_list1.binarySearch(50) === 50, "binary-search to find an item!");
assert.ok(_list1.binarySearch(100) < 0, "binary-search item not found!");
assert.ok(_list2.binarySearch({ index: 50 }, { compare: (a, b) => a.index - b.index }) === 50, "binary-search find an item with comparer!");
assert.ok(_list2.binarySearch({ index: 80 }, 50, 40, { compare: (a, b) => a.index - b.index }) === 80, "binary-search find an item with index, count and comparer!");
});
QUnit.test("clear", function (assert) {
var _list = CreateList();
_list.clear();
assert.ok(_list.count() === 0, "Clear list!");
});
QUnit.test("contains", function (assert) {
var _list = CreateList();
assert.ok(_list.contains(3) === true, "list contains!");
assert.ok(_list.contains(6) === false, "list not containing!");
});
QUnit.test("copyTo", function (assert) {
var _list = CreateList(),
_arr = new Array(_list.count());
_list.copyTo(_arr, 0);
assert.deepEqual(_arr, [1, 2, 3, 4, 5], "list copyTo an array!");
});
QUnit.test("exists", function (assert) {
var _list = CreateList();
assert.ok(_list.exists(t => t % 2 === 0), "an even number exists in a list of the first 5 number!");
assert.ok(_list.exists(t => t > 5) === false, "6 exists in a list of the first 5 number!");
});
QUnit.test("find", function (assert) {
var _list = CreateList();
assert.ok(_list.find(t => t % 2 === 0) === 2, "find an even number in a list of the first 5 number!");
assert.ok(_list.find(t => t > 5) === null, "find a number greater than 5 in a list of the first 5 number!");
});
QUnit.test("findIndex", function (assert) {
var _list = CreateList();
assert.ok(_list.findIndex(t => t % 2 === 0) === 1, "find index of an even numbers in a list of the first 5 number!");
assert.ok(_list.findIndex(2, t => t % 2 === 0) === 3, "find index of an even numbers in a list of the first 5 number, starting from 2!");
assert.ok(_list.findIndex(2, 1, t => t % 2 === 0) === -1, "find index of an even numbers in a list of the first 5 number, starting from 3, for 1 attempt!");
});
QUnit.test("findLast", function (assert) {
var _list = CreateList();
assert.ok(_list.findLast(t => t % 2 === 0) === 4, "find last even number in a list of the first 5 number!");
assert.ok(_list.findLast(t => t > 5) === null, "find last number greater than 5 in a list of the first 5 number!");
});
QUnit.test("findLastIndex", function (assert) {
var _list = new List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
assert.ok(_list.findLastIndex(t => t % 2 === 0) === 8, "find last index of an even numbers in a list of the first 10 number!");
assert.ok(_list.findLastIndex(5, t => t % 2 === 0) === 4, "find last index of an even numbers in a list of the first 10 number, starting from 5!");
assert.ok(_list.findLastIndex(5, 1, t => t % 2 === 0) === -1, "find last index of an even numbers in a list of the first 10 number, starting from 5, for 1 attempt!");
});
QUnit.test("forEach", function (assert) {
var _list = CreateList(),
_count = 0;
_list.forEach(t => _count += t);
assert.ok(_count === 15, "forEach to get sum of a the items in a list!");
});
QUnit.test("get", function (assert) {
var _list = CreateList();
assert.ok(_list.get(1) === 2, "get item at index 1 from a list of 5 numbers!");
assert.throws(() => _list.get(10), "throws an error when the number of elements is greater than the number of elements that the destination array can contain!");
});
QUnit.test("getRange", function (assert) {
var _list = CreateList();
assert.deepEqual(_list.getRange(0, 3).toArray(), [1, 2, 3], "get range of first 3 items of a list of first 5 numbers!");
assert.throws(() => _list.getRange(0, 10), "throws an error getting first 10 items from a list of 5 numbers!");
});
QUnit.test("indexOf", function (assert) {
var _list = CreateList();
assert.ok(_list.indexOf(3) === 2, "get index of 3 in a list of first 5 numbers!");
assert.ok(_list.indexOf(10) === -1, "get index of 10 in a list of first 5 numbers!");
assert.ok(_list.indexOf(3, 4) === -1, "get index of 3 in a list of first 5 numbers, starting from index 4!");
});
QUnit.test("insert", function (assert) {
var _list = CreateList();
_list.insert(3, 0);
assert.ok(_list.count() === 6, "insert an item in a list of 5 numbers, get count!");
assert.ok(_list[3] === 0, "insert an item in a list of 5 numbers, get item!");
assert.throws(() => _list.insert(10, 0), "throws an error inserting in 10th index of a list of 5 numbers!");
});
QUnit.test("insertRange", function (assert) {
var _list = CreateList();
_list.insertRange(3, mx.range(0, 3));
assert.ok(_list.count() === 8, "insert range of items in a list of 5 numbers, get count!");
assert.ok(_list[3] === 0 && _list[4] === 1 && _list[5] === 2, "insert range of items in a list of 5 numbers, get items!");
assert.throws(() => _list.insertRange(10, mx.range(0, 3)), "throws an error inserting range of items in 10th index of a list of 5 numbers!");
});
QUnit.test("lastIndexOf", function (assert) {
var _list = CreateList();
assert.ok(_list.lastIndexOf(3) === 2, "get last index of 3 in a list of first 5 numbers!");
assert.ok(_list.lastIndexOf(10) === -1, "get last index of 10 in a list of first 5 numbers!");
assert.ok(_list.lastIndexOf(3, 1) === -1, "get last index of 3 in a list of first 5 numbers, starting from index 1!");
});
QUnit.test("remove", function (assert) {
var _list = CreateList();
assert.ok(_list.remove(2) === true && _list.count() === 4, "remove an item from a list, get count!");
assert.ok(_list.remove(10) === false && _list.count() === 4, "remove an item which does not exist in a list, get count!");
});
QUnit.test("removeAll", function (assert) {
var _list = CreateList();
assert.ok(_list.removeAll(t => t % 2 === 0) === 2 && _list.count() === 3, "remove all even numbers from a list of first 5 numbers, get count!");
assert.ok(_list.removeAll(t => t % 2 === 0) === 0 && _list.count() === 3, "remove all even numbers from a list of first 3 odd numbers, get count!");
});
QUnit.test("removeAt", function (assert) {
var _list = CreateList();
_list.removeAt(2);
assert.ok(_list[2] === 4 && _list.count() === 4, "remove item from 2nd index of a list of first 5 numbers, get count!");
assert.throws(() => _list.removeAt(10), "throws an error removing item from 10th index of a list of first 5 numbers!");
});
QUnit.test("removeRange", function (assert) {
var _list = CreateList();
_list.removeRange(1, 3);
assert.ok(_list[0] === 1 && _list[1] === 5 && _list.count() === 2, "remove range of 3 items, starting from 1st index from a list of first 5 numbers, get count!");
assert.throws(() => _list.removeRange(10, 10), "throws an error removing a range of items starting from 10th index of a list of first 5 numbers!");
});
QUnit.test("reverse", function (assert) {
var _arr = [1, 2, 3, 4, 5],
_list1 = new List<number>(_arr),
_list2 = new List<number>(_arr);
_list1.reverse();
_list2.reverse(0, 3);
assert.deepEqual(_list1.toArray(), [5, 4, 3, 2, 1], "reverse list of 5 first numbers!");
assert.deepEqual(_list2.toArray(), [3, 2, 1, 4, 5], "reverse first 3 items of a list of 5 first numbers!");
});
QUnit.test("set", function (assert) {
var _list = CreateList();
_list.set(1, 0);
assert.ok(_list[1] === 0, "set value at index 1 of a list!");
assert.throws(() => _list.set(10, 1), "throws an error setting item at index 10 from a list of 5 numbers!");
});
QUnit.test("sort", function (assert) {
var _arr = [7, 1, 8, 3, 2, 0, 9, 6, 4, 5],
_list1 = new List<number>(_arr),
_list2 = new List<number>(_arr),
_list3 = new List<number>(_arr),
_list4 = new List<number>(_arr),
_sorter = (a: number, b: number) => a - b;
_list1.sort();
_list2.sort(_sorter);
_list3.sort({ compare: _sorter });
_list4.sort(0, 5, { compare: _sorter });
assert.deepEqual(_list1.toArray(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "sort list of first 10 numbers!");
assert.deepEqual(_list2.toArray(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "sort list of first 10 numbers with a comparison function!");
assert.deepEqual(_list3.toArray(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "sort list of first 10 numbers with a comparer!");
assert.deepEqual(_list4.toArray(), [1, 2, 3, 7, 8, 0, 9, 6, 4, 5], "sort 5 first items of list of first 10 numbers with a comparer!");
});
QUnit.test("toArray", function (assert) {
var _list = CreateList();
assert.deepEqual(_list.toArray(), [1, 2, 3, 4, 5], "converts a list of numbers to an array!");
});
QUnit.test("trueForAll", function (assert) {
var _list = CreateList();
assert.ok(_list.trueForAll(t => t < 10) === true, "checks whether all items in a list of 5 first numbers are less than 10!");
assert.ok(_list.trueForAll(t => t < 3) === false, "checks whether all items in a list of 5 first numbers are less than 3!");
});
QUnit.test("list enumerable", function (assert) {
var _list = CreateList();
assert.deepEqual(_list.select(t => t * 2).where(t => t > 5).toArray(), [6, 8, 10], "select-where-toArray over a list!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateList(): List<number> {
return new List(1, 2, 3, 4, 5);
}
}
namespace ReadOnlyCollectionTests {
QUnit.module("ReadOnlyCollection");
QUnit.test("constructor", function (assert) {
assert.ok(CreateReadOnlyCollection().count() === 5, "initialize a ReadOnlyCollection!");
assert.throws(() => new ReadOnlyCollection<number>(null), "throws an exception creating an ampty ReadOnlyCollection!");
});
QUnit.test("indexer", function (assert) {
var _col = CreateReadOnlyCollection();
assert.ok(_col[0] === 1, "indexer get!");
assert.ok(function () {
try { _col[0] = 0; }
catch (e) { }
return _col[0] === 1;
}, "indexer set!");
assert.ok(function () {
try { _col[10] = 0; }
catch (e) { }
return _col[10] === undefined;
}, "out of range indexer set!");
});
QUnit.test("get", function (assert) {
var _col = CreateReadOnlyCollection();
assert.ok(_col.get(1) === 2, "get item at index 1 from a collection of 5 numbers!");
assert.throws(() => _col.get(10), "throws error getting item at index 10 from a collection of 5 numbers!");
});
QUnit.test("contains", function (assert) {
var _col = CreateReadOnlyCollection();
assert.ok(_col.contains(3) === true, "collection contains!");
assert.ok(_col.contains(6) === false, "collection not containing!");
});
QUnit.test("copyTo", function (assert) {
var _col = CreateReadOnlyCollection(),
_arr = new Array(_col.count());
_col.copyTo(_arr, 0);
assert.deepEqual(_arr, [1, 2, 3, 4, 5], "collection copyTo an array!");
assert.throws(() => _col.copyTo([], 0), "throws an error when the number of elements is greater than the number of elements that the destination array can contain!");
});
QUnit.test("indexOf", function (assert) {
var _col = CreateReadOnlyCollection();
assert.ok(_col.indexOf(3) === 2, "get index of 3 in a collection of first 5 numbers!");
assert.ok(_col.indexOf(10) === -1, "get index of 10 in a collection of first 5 numbers!");
});
QUnit.test("collection enumerable", function (assert) {
var _col = CreateReadOnlyCollection();
assert.deepEqual(_col.select(t => t * 2).where(t => t > 5).toArray(), [6, 8, 10], "select-where-toArray over a collection!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateReadOnlyCollection(): ReadOnlyCollection<number> {
return new ReadOnlyCollection(new List<number>(1, 2, 3, 4, 5));
}
}
namespace SortedListTests {
QUnit.module("SortedList");
QUnit.test("constructor", function (assert) {
var _comparer = Comparer.create((a: number, b: number) => a - b),
_dic = CreateDictionary(),
_s1 = new SortedList(),
_s2 = new SortedList(5),
_s3 = new SortedList(_dic),
_s4 = new SortedList(_comparer),
_s5 = new SortedList(5, _comparer),
_s6 = new SortedList(_dic, _comparer);
assert.ok(_s1.count() === 0 && _s1.capacity() === 0, "initialize a SortedList!");
assert.ok(_s2.count() === 0 && _s2.capacity() === 5, "initialize a SortedList using initial capacity!");
assert.ok(_s3.count() === 5 && _s3.capacity() === 5, "initialize a SortedList using specified dictionary!");
assert.ok(_s4.count() === 0 && _s4.capacity() === 0, "initialize a SortedList using specified comparer!");
assert.ok(_s5.count() === 0 && _s5.capacity() === 5, "initialize a SortedList using using initial capacity and comparer!");
assert.ok(_s6.count() === 5 && _s6.capacity() === 5, "initialize a SortedList using specified dictionary and comparer!");
});
QUnit.test("add", function (assert) {
assert.ok(CreateSortedList().count() == 5, "sorted-list add!");
assert.throws(() => CreateSortedList().add(1, "AA"), "throws an error adding existing key to the list!");
});
QUnit.test("get", function (assert) {
var _list = CreateSortedList();
assert.ok(_list.get(1) === "A", "sorted-list get!");
assert.throws(() => _list.get(10), "throws an error getting invalid key!");
});
QUnit.test("capacity", function (assert) {
var _list = CreateSortedList();
assert.ok(_list.capacity() > 0, "get sorted-list capacity!");
_list.capacity(10);
assert.ok(_list.capacity() === 10, "set sorted-list capacity!");
});
QUnit.test("clear", function (assert) {
var _list = CreateSortedList();
_list.clear();
assert.ok(_list.count() === 0 && _list.capacity() === 0, "clear sorted-list!");
});
QUnit.test("comparer", function (assert) {
var _comparer = CreateSortedList().comparer();
assert.ok(_comparer.compare(5, 1) > 0 && _comparer.compare(1, 5) < 0 && _comparer.compare(1, 1) === 0, "sorted-list comparer!");
});
QUnit.test("containsKey", function (assert) {
var _list1 = CreateSortedList(),
_list2 = new SortedList<{ id: number; name: string }, number>({ compare: (a, b) => a.name.localeCompare(b.name) });
assert.ok(_list1.containsKey(1) === true, "sorted-list contains key!");
assert.ok(_list1.containsKey(10) === false, "sorted-list does not contain key!");
_list2.add({ id: 2, name: "B" }, 2);
_list2.add({ id: 5, name: "E" }, 5);
_list2.add({ id: 4, name: "D" }, 4);
_list2.add({ id: 3, name: "C" }, 3);
_list2.add({ id: 1, name: "A" }, 1);
assert.ok(_list2.containsKey({ id: 3, name: "C" }), "sorted-list contains key using specified comparer");
});
QUnit.test("containsValue", function (assert) {
var _list = CreateSortedList();
assert.ok(_list.containsValue("A") === true, "sorted-list contains value!");
assert.ok(_list.containsValue("Z") === false, "sorted-list does not contain value!");
});
QUnit.test("keys", function (assert) {
var _list = CreateSortedList();
assert.deepEqual(_list.keys().toArray(), [1, 2, 3, 4, 5], "sorted-list keys!");
assert.deepEqual(new SortedList().keys().toArray(), [], "empty sorted-list keys!");
});
QUnit.test("values", function (assert) {
var _list = CreateSortedList();
assert.deepEqual(_list.values().toArray(), ["A", "B", "C", "D", "E"], "sorted-list values!");
assert.deepEqual(new SortedList().values().toArray(), [], "empty sorted-list values!");
});
QUnit.test("indexOfKey", function (assert) {
var _list = CreateSortedList();
assert.ok(_list.indexOfKey(1) === 0, "sorted-list index of key!");
assert.ok(_list.indexOfKey(10) < 0, "sorted-list index of invalid key!");
});
QUnit.test("indexOfValue", function (assert) {
var _list = CreateSortedList();
assert.ok(_list.indexOfValue("A") === 0, "sorted-list index of value!");
assert.ok(_list.indexOfValue("Z") < 0, "sorted-list index of invalid value!");
});
QUnit.test("remove", function (assert) {
var _list = CreateSortedList();
assert.ok(_list.remove(1) === true && _list.count() === 4 && _list.indexOfKey(1) < 0, "sorted-list remove key!");
assert.ok(_list.remove(1) === false && _list.count() === 4, "sorted-list remove invalid key!");
});
QUnit.test("removeAt", function (assert) {
var _list = CreateSortedList();
_list.removeAt(0);
assert.ok(_list.count() === 4 && _list.indexOfKey(1) < 0, "sorted-list remove at index!");
assert.throws(() => _list.removeAt(10), "throws an error removing item at invalid index");
});
QUnit.test("set", function (assert) {
var _list = CreateSortedList();
_list.set(1, "AA");
assert.ok(_list.count() === 5 && _list.get(1) === "AA", "sorted-list set exisiting key's value!");
_list.set(6, "F");
assert.ok(_list.count() === 6 && _list.get(6) === "F", "sorted-list set new key and value!");
});
QUnit.test("tryGetValue", function (assert) {
var _list = CreateSortedList();
assert.ok(function () {
var value: string;
var res = _list.tryGetValue(1, val => value = val);
return res && value === "A";
}, "sorted-list tryGetValue, exisiting key!");
assert.ok(function () {
var value: string;
var res = _list.tryGetValue(10, val => value = val);
return res === false;
}, "sorted-list tryGetValue, invalid key!");
});
QUnit.test("sorted-list enumerable", function (assert) {
var _list = CreateSortedList();
assert.deepEqual(_list.select(t => t.key * 2).where(t => t > 5).toArray(), [6, 8, 10], "select-where-toArray over a sorted-list!");
assert.deepEqual(_list.where(t => t.key > 2).select(t => t.value).toArray(), ["C", "D", "E"], "where-select-toArray over a sorted-list!");
});
QUnit.test("evaluate sorting", function (assert) {
var _list1 = CreateSortedList(),
_list2 = new SortedList<{ id: number; name: string }, number>({ compare: (a, b) => a.name.localeCompare(b.name) });
_list1.remove(5);
_list1.add(6, "F");
_list1.remove(4);
_list1.add(7, "G");
_list1.remove(3);
_list1.add(8, "H");
_list1.remove(2);
_list1.add(9, "I");
_list1.remove(1);
_list1.add(10, "J");
assert.deepEqual(_list1.keys().toArray(), [6, 7, 8, 9, 10], "evaluate sorted keys after multiple add/remove");
assert.deepEqual(_list1.values().toArray(), ["F", "G", "H", "I", "J"], "evaluate sorted values after multiple add/remove");
_list2.add({ id: 2, name: "B" }, 2);
_list2.add({ id: 5, name: "E" }, 5);
_list2.add({ id: 4, name: "D" }, 4);
_list2.add({ id: 3, name: "C" }, 3);
_list2.add({ id: 1, name: "A" }, 1);
assert.deepEqual(_list2.keys().select(t => t.id).toArray(), [1, 2, 3, 4, 5], "evaluate sorted keys after multiple add/remove using specified comparer!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateDictionary(): Dictionary<number, string> {
var _dic = new Dictionary<number, string>();
_dic.add(1, "A");
_dic.add(2, "B");
_dic.add(3, "C");
_dic.add(4, "D");
_dic.add(5, "E");
return _dic;
}
function CreateSortedList(): SortedList<number, string> {
var _list = new SortedList<number, string>();
_list.add(5, "E");
_list.add(3, "C");
_list.add(2, "B");
_list.add(4, "D");
_list.add(1, "A");
return _list;
}
}
namespace DictionaryTests {
QUnit.module("Dictionary");
QUnit.test("constructor", function (assert) {
var _comparer = EqualityComparer.create(o => mx.hash(o), (a, b) => a === b),
_d1 = new Dictionary<number, string>(),
_d2 = new Dictionary<number, string>(CreateDictionary()),
_d3 = new Dictionary<number, string>(_comparer),
_d4 = new Dictionary<number, string>(5),
_d5 = new Dictionary<number, string>(5, _comparer),
_d6 = new Dictionary<number, string>(CreateDictionary(), _comparer);
assert.ok(_d1.count() === 0, "initialize a Dictionary!");
assert.ok(_d2.count() === 5, "initialize a Dictionary using specified dictionary!");
assert.ok(_d3.count() === 0, "initialize a Dictionary using specified comparer!");
assert.ok(_d4.count() === 0, "initialize a Dictionary using initial capacity!");
assert.ok(_d5.count() === 0, "initialize a Dictionary using using initial capacity and comparer!");
assert.ok(_d6.count() === 5, "initialize a Dictionary using specified dictionary and comparer!");
});
QUnit.test("add", function (assert) {
var _dic = new Dictionary<number, string>();
_dic.add(1, "A");
assert.ok(_dic.count() === 1, "ditionary add");
assert.throws(() => _dic.add(1, "B"), "throws an error adding duplicate key");
});
QUnit.test("clear", function (assert) {
var _dic = CreateDictionary();
_dic.clear();
assert.ok(_dic.count() === 0, "ditionary clear!");
});
QUnit.test("containsKey", function (assert) {
var _dic = CreateDictionary();
assert.ok(_dic.containsKey(1) === true, "dictionary contains key!");
assert.ok(_dic.containsKey(10) === false, "dictionary does not contain key!");
});
QUnit.test("containsValue", function (assert) {
var _dic = CreateDictionary();
assert.ok(_dic.containsValue("A") === true, "dictionary contains value!");
assert.ok(_dic.containsValue("Z") === false, "dictionary does not contain value!");
});
QUnit.test("copyTo", function (assert) {
var _dic = CreateDictionary(),
_arr = new Array(_dic.count());
_dic.copyTo(_arr, 0);
assert.deepEqual(_arr, [1, 2, 3, 4, 5], "dictionary copy to an array!");
assert.throws(() => _dic.copyTo([], 0), "throws an error when the number of elements is greater than the number of elements that the destination array can contain!");
});
QUnit.test("keys", function (assert) {
var _dic = CreateDictionary();
assert.deepEqual(_dic.keys().toArray(), [1, 2, 3, 4, 5], "dictionary keys!");
assert.deepEqual(new Dictionary().keys().toArray(), [], "empty dictionary keys!");
});
QUnit.test("values", function (assert) {
var _dic = CreateDictionary();
assert.deepEqual(_dic.values().toArray(), ["A", "B", "C", "D", "E"], "dictionary values!");
assert.deepEqual(new Dictionary().values().toArray(), [], "empty dictionary values!");
});
QUnit.test("get", function (assert) {
var _dic = CreateDictionary();
assert.ok(_dic.get(1) === "A", "dictionary get value!");
assert.throws(() => _dic.get(10), "throws an error getting non existing key!");
});
QUnit.test("set", function (assert) {
var _dic = CreateDictionary();
_dic.set(1, "AA");
assert.ok(_dic.get(1) === "AA", "dictionary set value!");
_dic.set(6, "F");
assert.ok(_dic.count() === 6 && _dic.get(6) === "F", "dictionary set new key and value!");
});
QUnit.test("tryGetValue", function (assert) {
var _dic = CreateDictionary();
assert.ok(function () {
var value: string;
var res = _dic.tryGetValue(1, val => value = val);
return res && value === "A";
}, "dictionary tryGetValue, exisiting key!");
assert.ok(function () {
var value: string;
var res = _dic.tryGetValue(10, val => value = val);
return res === false;
}, "dictionary tryGetValue, invalid key!");
});
QUnit.test("remove", function (assert) {
var _dic = CreateDictionary();
assert.ok(_dic.remove(1) === true && _dic.count() === 4, "dictionary remove key!");
assert.ok(_dic.remove(10) === false && _dic.count() === 4, "dictionary remove non existing key!");
});
QUnit.test("key-value pair", function (assert) {
var _pair1 = new KeyValuePair(1, "A"),
_pair2 = new KeyValuePair(1, "A");
assert.ok(_pair1.key === 1 && _pair1.value === "A", "KeyValuePair get key/value!");
assert.throws(() => _pair1.key = 2, "throws an error trysing to set KeyValuePair key!");
assert.throws(() => _pair1.value = "B", "throws an error trysing to set KeyValuePair value!");
assert.ok(mx.hash(_pair1) === mx.hash(_pair2), "KeyValuePair get hash code!");
assert.ok(mx.equals(_pair1, _pair2), "KeyValuePair equality check!");
});
QUnit.test("dictionary enumerable", function (assert) {
var _dic = CreateDictionary();
assert.deepEqual(_dic.select(t => t.key).toArray(), [1, 2, 3, 4, 5], "dictionary select keys, to array!");
assert.deepEqual(_dic.select(t => t.value).toArray(), ["A", "B", "C", "D", "E"], "dictionary select values, to array!");
assert.ok(_dic.toArray()[0].key === 1 && _dic.toArray()[0].value === "A", "dictionary select key-value items!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateDictionary(): Dictionary<number, string> {
var _dic = new Dictionary<number, string>();
_dic.add(1, "A");
_dic.add(2, "B");
_dic.add(3, "C");
_dic.add(4, "D");
_dic.add(5, "E");
return _dic;
}
}
namespace HashSetTests {
QUnit.module("Hashset");
QUnit.test("constructor", function (assert) {
assert.ok(new HashSet<number>().count() === 0, "initialize an empty HashSet!");
assert.ok(new HashSet<number>(mx.range(1, 5)).count() === 5, "initialize a HashSet using specified collection!");
assert.ok(new HashSet<number>(mx.EqualityComparer.defaultComparer).count() === 0, "initialize a HashSet using specified equality comparer!");
assert.ok(CreateObjectHashSet().count() === 2, "initialize a HashSet using specified collection and equality comparer!");
});
QUnit.test("add", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet();
assert.ok(_hash1.add(6) === true, "add item to a HashSet of numbers!");
assert.ok(_hash1.add(1) === false, "add existing item to a HashSet of numbers!");
assert.ok(_hash2.add({ name: "C", value: 5 }) === true, "add item to a HashSet of objects!");
assert.ok(_hash2.add({ name: "A", value: 5 }) === false, "add an existing item to a HashSet of objects!");
});
QUnit.test("clear", function (assert) {
var _hash = CreateNumericHashSet();
_hash.clear();
assert.ok(_hash.count() === 0, "clear a HashSet!");
});
QUnit.test("contains", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet();
assert.ok(_hash1.contains(1) === true, "HashSet of numbers contains an item!");
assert.ok(_hash1.contains(6) === false, "HashSet of numbers does not contain an item!");
assert.ok(_hash2.contains({ name: "A", value: 5 }) === true, "HashSet of objects contains an item!");
assert.ok(_hash2.contains({ name: "C", value: 5 }) === false, "HashSet of objects does not contain an item!");
});
QUnit.test("copyTo", function (assert) {
var _hash = CreateNumericHashSet(),
_arr = new Array(_hash.count());
_hash.copyTo(_arr, 0);
assert.deepEqual(_arr, [1, 2, 3, 4, 5], "HashSet copy to an array!");
assert.throws(() => _hash.copyTo([], 0), "throws an error when the number of elements is greater than the number of elements that the destination array can contain!");
});
QUnit.test("comparer", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet();
assert.ok(_hash1.comparer() === mx.EqualityComparer.defaultComparer, "HashSet default comparer!");
assert.ok(_hash2.comparer().equals({ name: "A", value: 1 }, { name: "A", value: 2 }), "HashSet custom comparer!");
});
QUnit.test("remove", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet();
assert.ok(_hash1.remove(1) === true, "HashSet of numbers remove an item!");
assert.ok(_hash1.remove(1) === false, "HashSet of numbers remove non existing item!");
assert.ok(_hash2.remove({ name: "A", value: 1 }) === true, "HashSet of objects remove an item!");
assert.ok(_hash2.remove({ name: "A", value: 1 }) === false, "HashSet of objects remove non existing item!");
});
QUnit.test("removeWhere", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet();
assert.ok(_hash1.removeWhere(t => t < 3) === 2, "HashSet of numbers remove with predicate, get number of items removed!");
assert.ok(_hash1.removeWhere(t => t < 3) === 0, "HashSet of numbers remove with invalid predicate, get number of items removed!");
assert.ok(_hash1.count() === 3, "HashSet of numbers remove with predicate, get count!");
assert.ok(_hash2.removeWhere(t => t.value < 3) === 1, "HashSet of objects remove with predicate, get number of items removed!");
assert.ok(_hash2.removeWhere(t => t.value < 3) === 0, "HashSet of objects remove with invalid predicate, get number of items removed!");
assert.ok(_hash2.count() === 1, "HashSet of objects remove with predicate, get count!");
});
QUnit.test("exceptWith", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet(),
_hash3 = CreateNumericHashSet();
_hash1.exceptWith([1, 2, 3]);
_hash2.exceptWith([{ name: "A", value: 0 }]);
_hash3.exceptWith(CreateNumericHashSet());
assert.ok(_hash1.count() === 2 && _hash1.contains(1) === false, "HashSet of numbers except a collection, get count!");
assert.ok(_hash2.count() === 1 && _hash2.contains({ name: "A", value: 0 }) === false, "HashSet of objects except a collection, get count!");
assert.ok(_hash3.count() === 0, "HashSet of numbers except an equal set, get count!");
});
QUnit.test("intersectWith", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet(),
_hash3 = CreateNumericHashSet();
_hash1.intersectWith([1, 2, 3]);
_hash2.intersectWith([{ name: "A", value: 0 }]);
_hash3.intersectWith(CreateNumericHashSet());
assert.ok(_hash1.count() === 3 && _hash1.contains(1) === true, "HashSet of numbers intersect with a collection, get count!");
assert.ok(_hash2.count() === 1 && _hash2.contains({ name: "A", value: 0 }) === true, "HashSet of objects intersect with a collection, get count!");
assert.ok(_hash3.count() === 5, "HashSet of numbers intersect with an equal set, get count!");
});
QUnit.test("isProperSubsetOf", function (assert) {
var _hash = CreateNumericHashSet();
assert.ok(new HashSet<number>().isProperSubsetOf([1, 2, 3]) === true, "an empty set is a proper subset of any other collection!");
assert.ok(new HashSet<number>().isProperSubsetOf([]) === false, "an empty set is not a proper subset of another empty collection!");
assert.ok(_hash.isProperSubsetOf([1, 2, 3, 4]) === false, "a hash set is not a proper subset of another collection when count is greater than the number of elements in other!");
assert.ok(_hash.isProperSubsetOf([1, 2, 3, 4, 5]) === false, "a hash set is not a proper subset of another collection when count is equal to the number of elements in other!");
assert.ok(_hash.isProperSubsetOf([1, 2, 3, 4, 5, 6]) === true, "hash set proper subset!");
});
QUnit.test("isProperSupersetOf", function (assert) {
var _hash = CreateNumericHashSet();
assert.ok(new HashSet<number>().isProperSupersetOf([1, 2, 3]) === false, "an empty set is a not superset of any other collection!");
assert.ok(new HashSet<number>().isProperSupersetOf([]) === false, "an empty set is not a proper superset of another empty collection!");
assert.ok(_hash.isProperSupersetOf([1, 2, 3, 4, 5, 6]) === false, "a hash set is not a proper superset of another collection when count is less than the number of elements in other!");
assert.ok(_hash.isProperSupersetOf([1, 2, 3, 4, 5]) === false, "a hash set is not a proper superset of another collection when count is equal to the number of elements in other!");
assert.ok(_hash.isProperSupersetOf([1, 2, 3]) === true, "hash set proper superset!");
});
QUnit.test("isSubsetOf", function (assert) {
var _hash = CreateNumericHashSet();
assert.ok(new HashSet<number>().isSubsetOf([1, 2, 3]) === true, "an empty set is a subset of any other collection!");
assert.ok(new HashSet<number>().isSubsetOf([]) === true, "an empty set is a subset of another empty collection!");
assert.ok(_hash.isSubsetOf([1, 2, 3, 4]) === false, "a hash set is not a subset of another collection when count is greater than the number of elements in other!");
assert.ok(_hash.isSubsetOf([1, 2, 3, 4, 5]) === true, "a hash set is a proper subset of another collection when count is equal to the number of elements in other!");
assert.ok(_hash.isSubsetOf([1, 2, 3, 4, 5, 6]) === true, "hash set subset!");
});
QUnit.test("isSupersetOf", function (assert) {
var _hash = CreateNumericHashSet();
assert.ok(new HashSet<number>().isSupersetOf([1, 2, 3]) === false, "an empty set is a not superset of any other collection!");
assert.ok(new HashSet<number>().isSupersetOf([]) === true, "an empty set is superset of another empty collection!");
assert.ok(_hash.isSupersetOf([1, 2, 3, 4, 5, 6]) === false, "a hash set is not a superset of another collection when count is less than the number of elements in other!");
assert.ok(_hash.isSupersetOf([1, 2, 3, 4, 5]) === true, "a hash set is a proper superset of another collection when count is equal to the number of elements in other!");
assert.ok(_hash.isSupersetOf([1, 2, 3]) === true, "hash set superset!");
});
QUnit.test("overlaps", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet();
assert.ok(_hash1.overlaps([1, 2, 3]) === true, "HashSet of numbers overlaps with another collection!");
assert.ok(_hash2.overlaps([{ name: "A", value: 0 }]) === true, "HashSet of objects overlaps with another collection!");
assert.ok(new HashSet().overlaps([1, 2, 3]) === false, "an empty HashSet does not overlap with another collection!");
});
QUnit.test("setEquals", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateNumericHashSet();
assert.ok(_hash1.setEquals(_hash2) === true, "HashSet of numbers equals with another HashSet!");
assert.ok(_hash1.setEquals([1, 2, 3, 4, 5]) === true, "HashSet of numbers equals with another collection!");
assert.ok(new HashSet<number>().setEquals([]) === true, "an empty HashSet equals with an empty collection!");
assert.ok(new HashSet<number>().setEquals([1, 2, 3]) === false, "an empty HashSet does not equals with another collection!");
});
QUnit.test("symmetricExceptWith", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet(),
_hash3 = CreateNumericHashSet();
_hash1.symmetricExceptWith([2, 3, 4]);
_hash2.symmetricExceptWith([{ name: "A", value: 0 }]);
_hash3.exceptWith(CreateNumericHashSet());
assert.ok(_hash1.count() === 2, "HashSet of numbers symmetric except another collection, get count!");
assert.ok(_hash1.contains(1) === true && _hash1.contains(5) === true, "HashSet of numbers symmetric except another collection, check contains!");
assert.ok(_hash2.count() === 1, "HashSet of objects symmetric except another collection, get count!");
assert.ok(_hash2.contains({ name: "A", value: 0 }) === false && _hash2.contains({ name: "B", value: 0 }) === true, "HashSet of objects symmetric except another collection, check contains!");
assert.ok(_hash3.count() === 0, "HashSet of numbers symmetric except an equal set, get count!");
});
QUnit.test("unionWith", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet(),
_hash3 = CreateNumericHashSet();
_hash1.unionWith([5, 6, 7, 8]);
_hash2.unionWith([{ name: "A", value: 5 }, { name: "B", value: 6 }, { name: "C", value: 7 }, { name: "D", value: 8 }]);
_hash3.unionWith(CreateNumericHashSet());
assert.ok(_hash1.count() === 8, "HashSet of numbers union with another collection, get count!");
assert.ok(_hash1.contains(1) === true && _hash1.contains(8) === true, "HashSet of numbers union with another collection, check contains!");
assert.ok(_hash2.count() === 4, "HashSet of objects union with another collection, get count!");
assert.ok(_hash2.contains({ name: "A", value: 0 }) === true && _hash2.contains({ name: "D", value: 0 }) === true, "HashSet of objects union with another collection, check contains!");
assert.ok(_hash3.count() === 5, "HashSet of numbers union with an equal set, get count!");
});
QUnit.test("set enumerable", function (assert) {
var _hash1 = CreateNumericHashSet(),
_hash2 = CreateObjectHashSet();
assert.deepEqual(_hash1.select(t => t * 2).where(t => t > 5).toArray(), [6, 8, 10], "select-where-toArray over a HashSet of numbers!");
assert.deepEqual(_hash2.select(t => t.value * 2).where(t => t > 5).toArray(), [6], "select-where-toArray over a HashSet of objects!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateNumericHashSet(): HashSet<number> {
return new HashSet<number>(mx.range(1, 5));
}
function CreateObjectHashSet(): HashSet<SimpleObject> {
var _items: SimpleObject[] = [{ name: "A", value: 1 }, { name: "A", value: 2 }, { name: "B", value: 3 }, { name: "B", value: 4 }],
_comparer = EqualityComparer.create<SimpleObject>(obj => mx.hash(obj.name), (a, b) => a.name === b.name);
return new HashSet<SimpleObject>(_items, _comparer);
}
}
namespace LinkedListTests {
QUnit.module("LinkedList");
QUnit.test("constructor", function (assert) {
assert.ok(new LinkedList<number>().count() === 0, "initialize an empty LinkedList!");
assert.ok(CreateLinkedList().count() === 5, "initialize a LinkedList using specified collection!");
});
QUnit.test("add", function (assert) {
var _list = CreateLinkedList();
_list.add(6);
assert.ok(_list.count() === 6, "add an item to a LinkedList!");
});
QUnit.test("clear", function (assert) {
var _list = CreateLinkedList();
_list.clear();
assert.ok(_list.count() === 0, "clear a LinkedList!");
});
QUnit.test("contains", function (assert) {
var _list = CreateLinkedList();
assert.ok(_list.contains(1) && _list.contains(5), "LinkedList contains an item!");
assert.ok(_list.contains(10) === false, "LinkedList does not contains an item!");
});
QUnit.test("copyTo", function (assert) {
var _list = CreateLinkedList(),
_arr = new Array(_list.count());
_list.copyTo(_arr, 0);
assert.deepEqual(_arr, [1, 2, 3, 4, 5], "LinkedList copy to an array!");
assert.throws(() => _list.copyTo([], 0), "throws an error when the number of elements is greater than the number of elements that the destination array can contain!");
});
QUnit.test("getFirst", function (assert) {
var _list = CreateLinkedList();
assert.ok(_list.getFirst().value() === 1, "LinkedList first item!");
assert.ok(new LinkedList<number>().getFirst() === null, "empty LinkedList first item!");
});
QUnit.test("getLast", function (assert) {
var _list = CreateLinkedList();
assert.ok(_list.getLast().value() === 5, "LinkedList last item!");
assert.ok(new LinkedList<number>().getLast() === null, "empty LinkedList last item!");
});
QUnit.test("addAfter", function (assert) {
var _list = CreateLinkedList(),
_first = _list.getFirst(),
_node = new LinkedListNode(6);
_list.addAfter(_first, _node);
_list.addAfter(_first, 7);
assert.ok(_list.count() === 7, "LinkedList add after item, get count!");
assert.ok(_list.contains(6) && _list.contains(7), "LinkedList add after item, check contains!");
});
QUnit.test("addBefore", function (assert) {
var _list = CreateLinkedList(),
_last = _list.getLast(),
_node = new LinkedListNode(6);
_list.addBefore(_last, _node);
_list.addBefore(_last, 7);
assert.ok(_list.count() === 7, "LinkedList add before item, get count!");
assert.ok(_list.contains(6) && _list.contains(7), "LinkedList add before item, check contains!");
});
QUnit.test("addFirst", function (assert) {
var _list = CreateLinkedList(),
_node = new LinkedListNode(0);
_list.addFirst(_node);
_list.addFirst(-1);
assert.ok(_list.count() === 7, "LinkedList add first, get count!");
assert.ok(_list.contains(0) && _list.contains(-1), "LinkedList add first, check contains!");
assert.ok(_list.getFirst().value() === -1, "LinkedList add first, get first!");
});
QUnit.test("addLast", function (assert) {
var _list = CreateLinkedList(),
_node = new LinkedListNode(6);
_list.addLast(_node);
_list.addLast(7);
assert.ok(_list.count() === 7, "LinkedList add last, get count!");
assert.ok(_list.contains(6) && _list.contains(7), "LinkedList add last, check contains!");
assert.ok(_list.getLast().value() === 7, "LinkedList add last, get last!");
});
QUnit.test("find", function (assert) {
var _list = CreateLinkedList();
assert.ok(_list.find(4).value() === 4, "LinkedList find an item!");
assert.ok(_list.find(10) === null, "LinkedList does not find an item!");
});
QUnit.test("findLast", function (assert) {
var _list = CreateLinkedList(),
_node = new LinkedListNode(1);
_list.addLast(_node);
assert.ok(_list.findLast(1) === _node, "LinkedList find last!");
assert.ok(_list.findLast(10) === null, "LinkedList does not find last item!");
});
QUnit.test("remove", function (assert) {
var _list = CreateLinkedList(),
_last = _list.getLast();
assert.ok(_list.remove(1) === true, "LinkedList remove an item!");
assert.ok(_list.remove(1) === false, "LinkedList remove non existing item!");
assert.ok(_list.remove(_last) === true, "LinkedList remove a node!");
assert.throws(() => _list.remove(_last), "throws an error when removing non existing or invalid node!");
assert.ok(_list.count() === 3, "LinkedList remove, get count!");
});
QUnit.test("removeFirst", function (assert) {
var _list = CreateLinkedList();
_list.removeFirst();
assert.ok(_list.count() === 4 && _list.contains(1) === false, "LinkedList remove first node!");
assert.throws(() => new LinkedList<number>().removeFirst(), "throws an error removing from an empty linked list!");
});
QUnit.test("removeLast", function (assert) {
var _list = CreateLinkedList();
_list.removeLast();
assert.ok(_list.count() === 4 && _list.contains(5) === false, "LinkedList remove last node!");
assert.throws(() => new LinkedList<number>().removeLast(), "throws an error removing from an empty linked list!");
});
QUnit.test("linked-list enumerable", function (assert) {
var _list = CreateLinkedList();
assert.deepEqual(_list.select(t => t * 2).where(t => t > 5).toArray(), [6, 8, 10], "select-where-toArray over a linked-list!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateLinkedList(): LinkedList<number> {
return new LinkedList(mx.range(1, 5));
}
}
namespace QueueTests {
QUnit.module("Queue");
QUnit.test("constructor", function (assert) {
assert.ok(new Queue<number>().count() === 0, "initialize an empty Queue!");
assert.ok(CreateQueue().count() === 5, "initialize a Queue using specified collection!");
});
QUnit.test("clear", function (assert) {
var _queue = CreateQueue();
_queue.clear();
assert.ok(_queue.count() === 0, "clears a Queue!");
});
QUnit.test("contains", function (assert) {
var _queue = CreateQueue();
assert.ok(_queue.contains(1) === true, "queue containing an item!");
assert.ok(_queue.contains(10) === false, "queue does not contain an item!");
});
QUnit.test("copyTo", function (assert) {
var _queue = CreateQueue(),
_arr = new Array(_queue.count());
_queue.copyTo(_arr, 0);
assert.deepEqual(_arr, [1, 2, 3, 4, 5], "queue copy to an array!");
assert.throws(() => _queue.copyTo([], 0), "throws an error when the number of elements is greater than the number of elements that the destination array can contain!");
});
QUnit.test("dequeue", function (assert) {
var _queue = CreateQueue();
assert.ok(_queue.dequeue() === 1, "queue dequeue an item!");
_queue.clear();
assert.throws(() => _queue.dequeue(), "throws an error dequeue from empty queue!");
});
QUnit.test("enqueue", function (assert) {
var _queue = CreateQueue();
_queue.enqueue(6);
assert.ok(_queue.count() === 6 && _queue.peek() === 1, "queue dequeue an item!");
});
QUnit.test("peek", function (assert) {
var _queue = CreateQueue();
assert.ok(_queue.peek() === 1, "queue peek an item!");
_queue.clear();
assert.throws(() => _queue.peek(), "throws an error peek from empty queue!");
});
QUnit.test("toArray", function (assert) {
var _queue = CreateQueue();
assert.deepEqual(_queue.toArray(), [1, 2, 3, 4, 5], "queue to array!");
});
QUnit.test("queue enumerable", function (assert) {
var _queue = CreateQueue();
assert.deepEqual(_queue.select(t => t * 2).where(t => t > 5).toArray(), [6, 8, 10], "select-where-toArray over a queue!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateQueue(): Queue<number> {
return new Queue(mx.range(1, 5));
}
}
namespace StackTests {
QUnit.module("Stack");
QUnit.test("constructor", function (assert) {
assert.ok(new Stack<number>().count() === 0, "initialize an empty Stack!");
assert.ok(CreateStack().count() === 5, "initialize a Stack using specified collection!");
});
QUnit.test("clear", function (assert) {
var _stack = CreateStack();
_stack.clear();
assert.ok(_stack.count() === 0, "clears a Stack!");
});
QUnit.test("contains", function (assert) {
var _stack = CreateStack();
assert.ok(_stack.contains(1) === true, "stack containing an item!");
assert.ok(_stack.contains(10) === false, "stack does not contain an item!");
});
QUnit.test("copyTo", function (assert) {
var _stack = CreateStack(),
_arr = new Array(_stack.count());
_stack.copyTo(_arr, 0);
assert.deepEqual(_arr, [1, 2, 3, 4, 5], "stack copy to an array!");
assert.throws(() => _stack.copyTo([], 0), "throws an error when the number of elements is greater than the number of elements that the destination array can contain!");
});
QUnit.test("peek", function (assert) {
var _stack = CreateStack();
assert.ok(_stack.peek() === 5, "stack peek an item!");
_stack.clear();
assert.throws(() => _stack.peek(), "throws an error peek from empty stack!");
});
QUnit.test("pop", function (assert) {
var _stack = CreateStack();
assert.ok(_stack.pop() === 5, "stack pop an item!");
_stack.clear();
assert.throws(() => _stack.pop(), "throws an error pop from empty stack!");
});
QUnit.test("push", function (assert) {
var _stack = CreateStack();
_stack.push(6);
assert.ok(_stack.count() === 6 && _stack.peek() === 6, "stack push an item!");
});
QUnit.test("toArray", function (assert) {
var _stack = CreateStack();
assert.deepEqual(_stack.toArray(), [1, 2, 3, 4, 5], "stack to array!");
});
QUnit.test("stack enumerable", function (assert) {
var _stack = CreateStack();
assert.deepEqual(_stack.select(t => t * 2).where(t => t > 5).toArray(), [6, 8, 10], "select-where-toArray over a stack!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateStack(): Stack<number> {
return new Stack(mx.range(1, 5));
}
}
namespace LookupTests {
QUnit.module("Lookup");
QUnit.test("contains", function (assert) {
var _lookup = CreateLookup();
assert.ok(_lookup.contains(1) === true, "lookup contains an item!");
assert.ok(_lookup.contains(10) === false, "lookup does not an item!");
});
QUnit.test("count", function (assert) {
var _lookup = CreateLookup();
assert.ok(_lookup.count() === 4, "lookup count!");
});
QUnit.test("get", function (assert) {
var _lookup = CreateLookup();
assert.ok(_lookup.get(1).count() === 2, "lookup get an item!");
assert.ok(_lookup.get(10).count() === 0, "lookup get non existing item!");
});
QUnit.test("lookup enumerable", function (assert) {
var _lookup = CreateLookup();
assert.deepEqual(_lookup.select(t => t.key).toArray(), [1, 2, 3, 4], "lookup select keys, to array!");
assert.deepEqual(_lookup.selectMany(t => t).toArray(), [1, 1, 2, 3, 3, 4, 4, 4], "lookup select all items, to array!");
assert.deepEqual(_lookup.select(t => t.count()).toArray(), [2, 1, 2, 3], "lookup select items count!");
});
/* Factory methods
---------------------------------------------------------------------- */
function CreateLookup(): Lookup<number, number> {
return mx([1, 1, 2, 3, 3, 4, 4, 4]).toLookup(t => t);
}
}
} | the_stack |
// Configuration support
import {extension} from './extension';
import * as logger from './logger';
import * as make from './make';
import * as ui from './ui';
import * as util from './util';
import * as vscode from 'vscode';
import * as path from 'path';
import * as telemetry from './telemetry';
let statusBar: ui.UI = ui.getUI();
// Each different scenario of building the same makefile, in the same environment, represents a configuration.
// Example: "make BUILD_TYPE=Debug" and "make BUILD_TYPE=Release" can be the debug and release configurations.
// The user can save several different such configurations in makefile.configurations setting,
// from which one can be picked via this extension and saved in settings.
// Priority rules for where is the Makefile Tools extension parsing the needed information from:
// 1. makefile.configurations.buildLog setting
// 2. makefile.buildLog setting
// 3. makefile.configurations.makePath, makefile.configurations.makeArgs
// 4. makefile.makePath and default args
// 5. default make tool and args
export interface MakefileConfiguration {
// A name associated with a particular build command process and args/options
name: string;
// The path (full or relative to the workspace folder) to the makefile
makefilePath?: string;
// make, nmake, specmake...
// This is sent to spawnChildProcess as process name
// It can have full path, relative path to the workspace folder or only tool name
// Don't include args in makePath
makePath?: string;
// a folder path (full or relative) containing the entrypoint makefile
makeDirectory?: string;
// options used in the build invocation
// don't use more than one argument in a string
makeArgs?: string[];
// a pre-generated build log, from which it is preffered to parse from,
// instead of the dry-run output of the make tool
buildLog?: string;
// TODO: investigate how flexible this is to integrate with other build systems than the MAKE family
// (basically anything that can produce a dry-run output is sufficient)
// Implement set-able dry-run, verbose, change-directory and always-make switches
// since different tools may use different arguments for the same behavior
}
// Last configuration name picked from the set defined in makefile.configurations setting.
// Saved into the workspace state. Also reflected in the configuration status bar button.
// If no particular current configuration is defined in settings, set to 'Default'.
let currentMakefileConfiguration: string;
export function getCurrentMakefileConfiguration(): string { return currentMakefileConfiguration; }
export function setCurrentMakefileConfiguration(configuration: string): void {
currentMakefileConfiguration = configuration;
statusBar.setConfiguration(currentMakefileConfiguration);
logger.message("Setting configuration - " + currentMakefileConfiguration);
analyzeConfigureParams();
}
// Read the current configuration from workspace state, update status bar item
function readCurrentMakefileConfiguration(): void {
let buildConfiguration : string | undefined = extension.getState().buildConfiguration;
if (!buildConfiguration) {
logger.message("No current configuration is defined in the workspace state. Assuming 'Default'.");
currentMakefileConfiguration = "Default";
} else {
logger.message(`Reading current configuration "${buildConfiguration}" from the workspace state.`);
currentMakefileConfiguration = buildConfiguration;
}
statusBar.setConfiguration(currentMakefileConfiguration);
}
let makePath: string | undefined;
export function getMakePath(): string | undefined { return makePath; }
export function setMakePath(path: string): void { makePath = path; }
// Read the path (full or directory only) of the make tool if defined in settings.
// It represents a default to look for if no other path is already included
// in "makefile.configurations.makePath".
function readMakePath(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
makePath = workspaceConfiguration.get<string>("makePath");
// Don't resolve makePath to root, because make needs to be searched in the path too.
if (!makePath) {
logger.message("No path to the make tool is defined in the settings file.");
}
}
let makefilePath: string | undefined;
export function getMakefilePath(): string | undefined { return makefilePath; }
export function setMakefilePath(path: string): void { makefilePath = path; }
// Read the full path to the makefile if defined in settings.
// It represents a default to look for if no other makefile is already provided
// in makefile.configurations.makefilePath.
// TODO: validate and integrate with "-f [Makefile]" passed in makefile.configurations.makeArgs.
function readMakefilePath(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
makefilePath = workspaceConfiguration.get<string>("makefilePath");
if (!makefilePath) {
logger.message("No path to the makefile is defined in the settings file.");
} else {
makefilePath = util.resolvePathToRoot(makefilePath);
}
}
let makeDirectory: string | undefined;
export function getMakeDirectory(): string | undefined { return makeDirectory; }
export function setMakeDirectory(dir: string): void { makeDirectory = dir; }
// Read the make working directory path if defined in settings.
// It represents a default to look for if no other makeDirectory is already provided
// in makefile.configurations.makeDirectory.
// TODO: validate and integrate with "-C [DIR_PATH]" passed in makefile.configurations.makeArgs.
function readMakeDirectory(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
makeDirectory = workspaceConfiguration.get<string>("makeDirectory");
if (!makeDirectory) {
logger.message("No folder path to the makefile is defined in the settings file.");
} else {
makeDirectory = util.resolvePathToRoot(makeDirectory);
}
}
let buildLog: string | undefined;
export function getBuildLog(): string | undefined { return buildLog; }
export function setBuildLog(path: string): void { buildLog = path; }
// Read from settings the path of the build log that is desired to be parsed
// instead of a dry-run command output.
// Useful for complex, tricky and corner case repos for which make --dry-run
// is not working as the extension expects.
// Example: --dry-run actually running configure commands, instead of only displaying them,
// possibly changing unexpectedly a previous configuration set by the repo developer.
// This scenario may also result in infinite loop, depending on how the makefile
// and the configuring process are written, thus making the extension unusable.
// Defining a build log to be parsed instead of a dry-run output represents a good alternative.
// Also useful for developing unit tests based on real world code,
// that would not clone a whole repo for testing.
// It is recommended to produce the build log with all the following commands,
// so that the extension has the best content to operate on.
// --always-make (to make sure no target is skipped because it is up to date)
// --keep-going (to not stumble on the first error)
// --print-data-base (special verbose printing which this extension is using for parsing the makefile targets)
// If any of the above switches is missing, the extension may have less log to parse from,
// therefore offering less intellisense information for source files,
// identifying less possible binaries to debug or not providing any makefile targets (other than the 'all' default).
function readBuildLog(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
buildLog = workspaceConfiguration.get<string>("buildLog");
if (buildLog) {
buildLog = util.resolvePathToRoot(buildLog);
logger.message('Build log defined at "' + buildLog + '"');
if (!util.checkFileExistsSync(buildLog)) {
logger.message("Build log not found on disk.");
}
}
}
let loggingLevel: string | undefined;
export function getLoggingLevel(): string | undefined { return loggingLevel; }
export function setLoggingLevel(logLevel: string): void { loggingLevel = logLevel; }
// Read from settings the desired logging level for the Makefile Tools extension.
export function readLoggingLevel(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
loggingLevel = workspaceConfiguration.get<string>("loggingLevel");
if (!loggingLevel) {
loggingLevel = "Normal";
}
logger.message(`Logging level: ${loggingLevel}`);
}
let extensionOutputFolder: string | undefined;
export function getExtensionOutputFolder(): string | undefined { return extensionOutputFolder; }
export function setExtensionOutputFolder(folder: string): void { extensionOutputFolder = folder; }
// Read from settings the path to a folder where the extension is dropping various output files
// (like extension.log, dry-run.log, targets.log).
// Useful to control where such potentially large files should reside.
export function readExtensionOutputFolder(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
const propKey: string = "extensionOutputFolder";
extensionOutputFolder = workspaceConfiguration.get<string>(propKey);
if (extensionOutputFolder) {
extensionOutputFolder = util.resolvePathToRoot(extensionOutputFolder);
if (!util.checkDirectoryExistsSync(extensionOutputFolder)) {
logger.message(`Provided extension output folder does not exist: ${extensionOutputFolder}.`);
let defaultExtensionOutputFolder: string | undefined = workspaceConfiguration.inspect<string>(propKey)?.defaultValue;
if (defaultExtensionOutputFolder) {
logger.message(`Switching to default: ${defaultExtensionOutputFolder}.`);
workspaceConfiguration.update(propKey, defaultExtensionOutputFolder);
extensionOutputFolder = util.resolvePathToRoot(defaultExtensionOutputFolder);
}
}
logger.message(`Dropping various extension output files at ${extensionOutputFolder}`);
}
}
let extensionLog: string | undefined;
export function getExtensionLog(): string | undefined { return extensionLog; }
export function setExtensionLog(path: string): void { extensionLog = path; }
// Read from settings the path to a log file capturing all the "Makefile Tools" output channel content.
// Useful for very large repos, which would produce with a single command a log larger
// than the "Makefile Tools" output channel capacity.
// Also useful for developing unit tests based on real world code,
// that would not clone a whole repo for testing.
// If an extension log is specified, its content is cleared during activation.
// Any messages that are being logged throughout the lifetime of the extension
// are going to be appended to this file.
export function readExtensionLog(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
extensionLog = workspaceConfiguration.get<string>("extensionLog");
if (extensionLog) {
// If there is a directory defined within the extension log path,
// honor it and don't append to extensionOutputFolder.
let parsePath: path.ParsedPath = path.parse(extensionLog);
if (extensionOutputFolder && !parsePath.dir) {
extensionLog = path.join(extensionOutputFolder, extensionLog);
} else {
extensionLog = util.resolvePathToRoot(extensionLog);
}
logger.message(`Writing extension log at ${extensionLog}`);
}
}
let preConfigureScript: string | undefined;
export function getPreConfigureScript(): string | undefined { return preConfigureScript; }
export function setPreConfigureScript(path: string): void { preConfigureScript = path; }
// Read from settings the path to a script file that needs to have been run at least once
// before a sucessful configure of this project.
export function readPreConfigureScript(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
preConfigureScript = workspaceConfiguration.get<string>("preConfigureScript");
if (preConfigureScript) {
preConfigureScript = util.resolvePathToRoot(preConfigureScript);
logger.message(`Found pre-configure script defined as ${preConfigureScript}`);
if (!util.checkFileExistsSync(preConfigureScript)) {
logger.message("Pre-configure script not found on disk.");
}
}
}
let alwaysPreConfigure: boolean | undefined;
export function getAlwaysPreConfigure(): boolean | undefined { return alwaysPreConfigure; }
export function setAlwaysPreConfigure(path: boolean): void { alwaysPreConfigure = path; }
// Read from settings whether the pre-configure step is supposed to be executed
// always before the configure operation.
export function readAlwaysPreConfigure(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
alwaysPreConfigure = workspaceConfiguration.get<boolean>("alwaysPreConfigure");
logger.message(`Always pre-configure: ${alwaysPreConfigure}`);
}
let configurationCachePath: string | undefined;
export function getConfigurationCachePath(): string | undefined { return configurationCachePath; }
export function setConfigurationCachePath(path: string): void { configurationCachePath = path; }
// Read from settings the path to a cache file containing the output of the last dry-run make command.
// This file is recreated when opening a project, when changing the build configuration or the build target
// and when the settings watcher detects a change of any properties that may impact the dryrun output.
export function readConfigurationCachePath(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
// how to get default from package.json to avoid problem with 'undefined' type?
configurationCachePath = workspaceConfiguration.get<string>("configurationCachePath");
if (configurationCachePath) {
// If there is a directory defined within the configuration cache path,
// honor it and don't append to extensionOutputFolder.
let parsePath: path.ParsedPath = path.parse(configurationCachePath);
if (extensionOutputFolder && !parsePath.dir) {
configurationCachePath = path.join(extensionOutputFolder, configurationCachePath);
} else {
configurationCachePath = util.resolvePathToRoot(configurationCachePath);
}
}
logger.message(`Configurations cached at ${configurationCachePath}`);
}
let compileCommandsPath: string | undefined;
export function getCompileCommandsPath(): string | undefined { return compileCommandsPath; }
export function setCompileCommandsPath(path: string): void { compileCommandsPath = path; }
export function readCompileCommandsPath(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
compileCommandsPath = workspaceConfiguration.get<string>("compileCommandsPath");
if (compileCommandsPath) {
compileCommandsPath = util.resolvePathToRoot(compileCommandsPath);
}
logger.message(`compile_commands.json path: ${compileCommandsPath}`);
}
let additionalCompilerNames: string[] | undefined;
export function getAdditionalCompilerNames(): string[] | undefined { return additionalCompilerNames; }
export function setAdditionalCompilerNames(compilerNames: string[]): void { additionalCompilerNames = compilerNames; }
export function readAdditionalCompilerNames(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
additionalCompilerNames = workspaceConfiguration.get<string[]>("additionalCompilerNames");
logger.message(`Additional compiler names: ${additionalCompilerNames}`);
}
let excludeCompilerNames: string[] | undefined;
export function getExcludeCompilerNames(): string[] | undefined { return excludeCompilerNames; }
export function setExcludeCompilerNames(compilerNames: string[]): void { excludeCompilerNames = compilerNames; }
export function readExcludeCompilerNames(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
excludeCompilerNames = workspaceConfiguration.get<string[]>("excludeCompilerNames");
logger.message(`Exclude compiler names: ${excludeCompilerNames}`);
}
let dryrunSwitches: string[] | undefined;
export function getDryrunSwitches(): string[] | undefined { return dryrunSwitches; }
export function setDryrunSwitches(switches: string[]): void { dryrunSwitches = switches; }
// Read from settings the dry-run switches array. If there is no user definition, the defaults are:
// --always-make: to not skip over up-to-date targets
// --keep-going: to not stop at the first error that is encountered
// --print-data-base: to generate verbose log output that can be parsed to identify all the makefile targets
// Some code bases have various issues with the above make parameters: infrastructure (not build) errors,
// infinite reconfiguration loops, resulting in the extension being unusable.
// To work around this, the setting makefile.dryrunSwitches is providing a way to skip over the problematic make arguments,
// even if this results in not ideal behavior: less information available to be parsed, which leads to incomplete IntelliSense or missing targets.
export function readDryrunSwitches(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
dryrunSwitches = workspaceConfiguration.get<string[]>("dryrunSwitches");
logger.message(`Dry-run switches: ${dryrunSwitches}`);
}
// Currently, the makefile extension supports debugging only an executable.
// TODO: Parse for symbol search paths
// TODO: support dll debugging.
export interface LaunchConfiguration {
// The following properties constitute a minimal launch configuration object.
// They all can be deduced from the dry-run output or build log.
// When the user is selecting a launch configuration, the extension is verifying
// whether there is an entry in the launch configurations array in settings
// and if not, it is generating a new one with the values computed by the parser.
binaryPath: string; // full path to the binary that this launch configuration is tied to
binaryArgs: string[]; // arguments that this binary is called with for this launch configuration
cwd: string; // folder from where the binary is run
// The following represent optional properties that can be additionally defined by the user in settings.
MIMode?: string;
miDebuggerPath?: string;
stopAtEntry?: boolean;
symbolSearchPath?: string;
}
let launchConfigurations: LaunchConfiguration[] = [];
export function getLaunchConfigurations(): LaunchConfiguration[] { return launchConfigurations; }
export function setLaunchConfigurations(configurations: LaunchConfiguration[]): void { launchConfigurations = configurations; }
// Read make configurations optionally defined by the user in settings: makefile.configurations.
function readLaunchConfigurations(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
launchConfigurations = workspaceConfiguration.get<LaunchConfiguration[]>("launchConfigurations") || [];
}
// Helper used to fill the launch configurations quick pick.
// The input object for this method is either read from the settings or it is an object
// constructed by the parser while analyzing the dry-run output (or the build log),
// when the extension is trying to determine if and how (from what folder, with what arguments)
// the makefile is invoking any of the programs that are built by the current target.
// Properties other than cwd, binary path and args could be manually defined by the user
// in settings (after the extension creates a first minimal launch configuration object) and are not relevant
// for the strings being used to populate the quick pick.
// Syntax:
// [CWD path]>[binaryPath]([binaryArg1,binaryArg2,binaryArg3,...])
export function launchConfigurationToString(configuration: LaunchConfiguration): string {
let binPath: string = util.makeRelPath(configuration.binaryPath, configuration.cwd);
let binArgs: string = configuration.binaryArgs.join(",");
return `${configuration.cwd}>${binPath}(${binArgs})`;
}
// Helper used to construct a minimal launch configuration object
// (only cwd, binary path and arguments) from a string that respects
// the syntax of its quick pick.
export async function stringToLaunchConfiguration(str: string): Promise<LaunchConfiguration | undefined> {
let regexp: RegExp = /(.*)\>(.*)\((.*)\)/mg;
let match: RegExpExecArray | null = regexp.exec(str);
if (match) {
let fullPath: string = await util.makeFullPath(match[2], match[1]);
let splitArgs: string[] = (match[3] === "") ? [] : match[3].split(",");
return {
cwd: match[1],
binaryPath: fullPath,
binaryArgs: splitArgs
};
} else {
return undefined;
}
}
let currentLaunchConfiguration: LaunchConfiguration | undefined;
export function getCurrentLaunchConfiguration(): LaunchConfiguration | undefined { return currentLaunchConfiguration; }
export async function setCurrentLaunchConfiguration(configuration: LaunchConfiguration): Promise<void> {
currentLaunchConfiguration = configuration;
let launchConfigStr: string = launchConfigurationToString(currentLaunchConfiguration);
statusBar.setLaunchConfiguration(launchConfigStr);
await extension._projectOutlineProvider.updateLaunchTarget(launchConfigStr);
}
function getLaunchConfiguration(name: string): LaunchConfiguration | undefined {
return launchConfigurations.find(k => {
if (launchConfigurationToString(k) === name) {
return { ...k, keep: true };
}
});
}
// Construct the current launch configuration object:
// Read the identifier from workspace state storage, then find the corresponding object
// in the launch configurations array from settings.
// Also update the status bar item.
async function readCurrentLaunchConfiguration(): Promise<void> {
readLaunchConfigurations();
let currentLaunchConfigurationName: string | undefined = extension.getState().launchConfiguration;
if (currentLaunchConfigurationName) {
currentLaunchConfiguration = getLaunchConfiguration(currentLaunchConfigurationName);
}
let launchConfigStr : string = "No launch configuration set.";
if (currentLaunchConfiguration) {
launchConfigStr = launchConfigurationToString(currentLaunchConfiguration);
logger.message(`Reading current launch configuration "${launchConfigStr}" from the workspace state.`);
} else {
// A null launch configuration after a non empty launch configuration string name
// means that the name stored in the project state does not match any of the entries in settings.
// This typically happens after the user modifies manually "makefile.launchConfigurations"
// in the .vscode/settings.json, specifically the entry that corresponds to the current launch configuration.
// Make sure to unset the launch configuration in this scenario.
if (currentLaunchConfigurationName !== undefined && currentLaunchConfigurationName !== "") {
logger.message(`Launch configuration "${currentLaunchConfigurationName}" is no longer defined in settings "makefile.launchConfigurations".`);
await setLaunchConfigurationByName("");
} else {
logger.message("No current launch configuration is set in the workspace state.");
}
}
statusBar.setLaunchConfiguration(launchConfigStr);
await extension._projectOutlineProvider.updateLaunchTarget(launchConfigStr);
}
export interface DefaultLaunchConfiguration {
MIMode?: string;
miDebuggerPath?: string;
stopAtEntry?: boolean;
symbolSearchPath?: string;
}
let defaultLaunchConfiguration: DefaultLaunchConfiguration | undefined;
export function getDefaultLaunchConfiguration(): DefaultLaunchConfiguration | undefined { return defaultLaunchConfiguration; }
// No setter needed. Currently only the user can define makefile.defaultLaunchConfiguration
export function readDefaultLaunchConfiguration(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
defaultLaunchConfiguration = workspaceConfiguration.get<DefaultLaunchConfiguration>("defaultLaunchConfiguration");
logger.message(`Default launch configuration: MIMode = ${defaultLaunchConfiguration?.MIMode},
miDebuggerPath = ${defaultLaunchConfiguration?.miDebuggerPath},
stopAtEntry = ${defaultLaunchConfiguration?.stopAtEntry},
symbolSearchPath = ${defaultLaunchConfiguration?.symbolSearchPath}`);
}
// Command name and args are used when building from within the VS Code Makefile Tools Extension,
// when parsing all the targets that exist and when updating the cpptools configuration provider
// for IntelliSense.
let configurationMakeCommand: string;
export function getConfigurationMakeCommand(): string { return configurationMakeCommand; }
export function setConfigurationMakeCommand(name: string): void { configurationMakeCommand = name; }
let configurationMakeArgs: string[] = [];
export function getConfigurationMakeArgs(): string[] { return configurationMakeArgs; }
export function setConfigurationMakeArgs(args: string[]): void { configurationMakeArgs = args; }
let configurationBuildLog: string | undefined;
export function getConfigurationBuildLog(): string | undefined { return configurationBuildLog; }
export function setConfigurationBuildLog(name: string): void { configurationBuildLog = name; }
// Analyze the settings of the current makefile configuration and the global workspace settings,
// according to various merging rules and decide what make command and build log
// apply to the current makefile configuration.
function analyzeConfigureParams(): void {
getBuildLogForConfiguration(currentMakefileConfiguration);
getCommandForConfiguration(currentMakefileConfiguration);
}
// Helper to find in the array of MakefileConfiguration which command/args correspond to a configuration name.
// Higher level settings (like makefile.makePath, makefile.makefilePath or makefile.makeDirectory)
// also have an additional effect on the final command.
export function getCommandForConfiguration(configuration: string | undefined): void {
let makefileConfiguration: MakefileConfiguration | undefined = makefileConfigurations.find(k => {
if (k.name === configuration) {
return k;
}
});
let makeParsedPathSettings: path.ParsedPath | undefined = makePath ? path.parse(makePath) : undefined;
let makeParsedPathConfigurations: path.ParsedPath | undefined = makefileConfiguration?.makePath ? path.parse(makefileConfiguration?.makePath) : undefined;
// Arguments for the make tool can be defined as makeArgs in makefile.configurations setting.
// When not defined, default to empty array.
// Make sure to copy from makefile.configurations.makeArgs because we are going to append more switches,
// which shouldn't be identified as read from settings.
// Make sure we start from a fresh empty configurationMakeArgs because there may be old arguments that don't apply anymore.
configurationMakeArgs = makefileConfiguration?.makeArgs?.concat() || [];
// Name of the make tool can be defined as makePath in makefile.configurations or as makefile.makePath.
// When none defined, default to "make".
configurationMakeCommand = makeParsedPathConfigurations?.base || makeParsedPathSettings?.base || "make";
let configurationMakeCommandExtension: string | undefined = makeParsedPathConfigurations?.ext || makeParsedPathSettings?.ext;
// Prepend the directory path, if defined in either makefile.configurations or makefile.makePath (first has priority).
let configurationCommandPath: string = makeParsedPathConfigurations?.dir || makeParsedPathSettings?.dir || "";
configurationMakeCommand = path.join(configurationCommandPath, configurationMakeCommand);
// Add the ".exe" extension on windows if no extension was specified, otherwise the file search APIs don't find it.
if (process.platform === "win32" && configurationMakeCommandExtension === "") {
configurationMakeCommand += ".exe";
}
// Add the makefile path via the -f make switch.
// makefile.configurations.makefilePath overwrites makefile.makefilePath.
let makefileUsed: string | undefined = makefileConfiguration?.makefilePath || makefilePath;
if (makefileUsed) {
configurationMakeArgs.push("-f");
configurationMakeArgs.push(`"${makefileUsed}"`);
// Need to rethink this (GitHub 59).
// Some repos don't work when we automatically add -C, others don't work when we don't.
// configurationMakeArgs.push("-C");
// configurationMakeArgs.push(path.parse(makefileUsed).dir);
}
// Add the working directory path via the -C switch.
// makefile.configurations.makeDirectory overwrites makefile.makeDirectory.
let makeDirectoryUsed: string | undefined = makefileConfiguration?.makeDirectory || makeDirectory;
if (makeDirectoryUsed) {
configurationMakeArgs.push("-C");
configurationMakeArgs.push(`"${makeDirectoryUsed}"`);
}
if (configurationMakeCommand) {
logger.message("Deduced command '" + configurationMakeCommand + " " + configurationMakeArgs.join(" ") + "' for configuration " + configuration);
}
// Validation and warnings about properly defining the makefile and make tool.
// These are not needed if the current configuration reads from a build log instead of dry-run output.
let buildLog: string | undefined = getConfigurationBuildLog();
let buildLogContent: string | undefined = buildLog ? util.readFile(buildLog) : undefined;
if (!buildLogContent) {
if ((!makeParsedPathSettings || makeParsedPathSettings.name === "") &&
(!makeParsedPathConfigurations || makeParsedPathConfigurations.name === "")) {
logger.message("Could not find any make tool file name in makefile.configurations.makePath, nor in makefile.makePath. Assuming make.");
}
// If configuration command has a path (absolute or relative), check if it exists on disk and error if not.
// If no path is given to the make tool, search all paths in the environment and error if make is not on the path.
if (configurationCommandPath !== "") {
if (!util.checkFileExistsSync(configurationMakeCommand)) {
vscode.window.showErrorMessage("Make not found.");
logger.message("Make was not found on disk at the location provided via makefile.makePath or makefile.configurations[].makePath.");
// How often location settings don't work (maybe because not yet expanding variables)?
const telemetryProperties: telemetry.Properties = {
reason: "not found at path given in settings"
};
telemetry.logEvent("makeNotFound", telemetryProperties);
}
} else {
if (!util.toolPathInEnv(path.parse(configurationMakeCommand).base)) {
vscode.window.showErrorMessage("Make not found.");
logger.message("Make was not given any path in settings and is also not found on the environment path.");
// Do the users need an environment automatically set by the extension?
// With a kits feature or expanding on the pre-configure script.
const telemetryProperties: telemetry.Properties = {
reason: "not found in environment path"
};
telemetry.logEvent("makeNotFound", telemetryProperties);
}
}
// Check for makefile path on disk: we search first for any makefile specified via the makefilePath setting,
// then via the makeDirectory setting and then in the root of the workspace. On linux/mac, it often is 'Makefile', so verify that we default to the right filename.
if (!makefileUsed) {
if (makeDirectoryUsed) {
makefileUsed = util.resolvePathToRoot(path.join(makeDirectoryUsed, "Makefile"));
if (!util.checkFileExistsSync(makefileUsed)) {
makefileUsed = util.resolvePathToRoot(path.join(makeDirectoryUsed, "makefile"));
}
} else {
makefileUsed = util.resolvePathToRoot("./Makefile");
if (!util.checkFileExistsSync(makefileUsed)) {
makefileUsed = util.resolvePathToRoot("./makefile");
}
}
}
if (!util.checkFileExistsSync(makefileUsed)) {
vscode.window.showErrorMessage("Makefile entry point not found.");
logger.message("The makefile entry point was not found. " +
"Make sure it exists at the location defined by makefile.makefilePath, makefile.configurations[].makefilePath, " +
"makefile.makeDirectory, makefile.configurations[].makeDirectory" +
"or in the root of the workspace.");
const telemetryProperties: telemetry.Properties = {
reason: makefileUsed ?
"not found at path given in settings" : // we may need more advanced ability to process settings
"not found in workspace root" // insight into different project structures
};
telemetry.logEvent("makefileNotFound", telemetryProperties);
}
}
}
// Helper to find in the array of MakefileConfiguration which buildLog correspond to a configuration name
export function getBuildLogForConfiguration(configuration: string | undefined): void {
let makefileConfiguration: MakefileConfiguration | undefined = makefileConfigurations.find(k => {
if (k.name === configuration) {
return { ...k, keep: true };
}
});
configurationBuildLog = makefileConfiguration?.buildLog;
if (configurationBuildLog) {
logger.message('Found build log path setting "' + configurationBuildLog + '" defined for configuration "' + configuration);
if (!path.isAbsolute(configurationBuildLog)) {
configurationBuildLog = path.join(util.getWorkspaceRoot(), configurationBuildLog);
logger.message('Resolving build log path to "' + configurationBuildLog + '"');
}
if (!util.checkFileExistsSync(configurationBuildLog)) {
logger.message("Build log not found. Remove the build log setting or provide a build log file on disk at the given location.");
}
} else {
// Default to an eventual build log defined in settings
// If that one is not found on disk, the setting reader already warned about it.
configurationBuildLog = buildLog;
}
}
let makefileConfigurations: MakefileConfiguration[] = [];
export function getMakefileConfigurations(): MakefileConfiguration[] { return makefileConfigurations; }
export function setMakefileConfigurations(configurations: MakefileConfiguration[]): void { makefileConfigurations = configurations; }
// Read make configurations optionally defined by the user in settings: makefile.configurations.
function readMakefileConfigurations(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
makefileConfigurations = workspaceConfiguration.get<MakefileConfiguration[]>("configurations") || [];
let detectedUnnamedConfigurations: boolean = false;
let unnamedConfigurationId: number = 0;
// Collect unnamed configurations (probably) defined by the extension earlier,
// to make sure we avoid duplicates in case any new configuration is in need of a name.
let unnamedConfigurationNames: string [] = makefileConfigurations.map((k => {
return k.name;
}));
unnamedConfigurationNames = unnamedConfigurationNames.filter(item => (item && item.startsWith("Unnamed configuration")));
makefileConfigurations.forEach(element => {
if (!element.name) {
detectedUnnamedConfigurations = true;
// Just considering the possibility that there are already unnamed configurations
// defined with IDs other than the rule we assume (like not consecutive numbers, but not only).
// This may happen when the user deletes configurations at some point without updating the IDs.
unnamedConfigurationId++;
let autoGeneratedName: string = `Unnamed configuration ${unnamedConfigurationId}`;
while (unnamedConfigurationNames.includes(autoGeneratedName)) {
unnamedConfigurationId++;
autoGeneratedName = `Unnamed configuration ${unnamedConfigurationId}`;
}
element.name = autoGeneratedName;
logger.message(`Defining name ${autoGeneratedName} for unnamed configuration ${element}.`);
}
});
if (detectedUnnamedConfigurations) {
logger.message("Updating makefile configurations in settings.");
workspaceConfiguration.update("configurations", makefileConfigurations);
}
// Log the updated list of configuration names
const makefileConfigurationNames: string[] = makefileConfigurations.map((k => {
return k.name;
}));
if (makefileConfigurationNames.length > 0) {
logger.message("Found the following configurations defined in makefile.configurations setting: " +
makefileConfigurationNames.join(";"));
}
// Verify if the current makefile configuration is still part of the list and unset otherwise.
// Exception: "Default" which means the user didn't set it and relies on whatever default
// the current set of makefiles support. "Default" is not going to be part of the list
// but we shouldn't log about it.
if (currentMakefileConfiguration !== "Default" && !makefileConfigurationNames.includes(currentMakefileConfiguration)) {
logger.message(`Current makefile configuration ${currentMakefileConfiguration} is no longer present in the available list.` +
` Re-setting the current makefile configuration to default.`);
setConfigurationByName("Default");
}
}
// Last target picked from the set of targets that are run by the makefiles
// when building for the current configuration.
// Saved into the settings storage. Also reflected in the configuration status bar button
let currentTarget: string | undefined;
export function getCurrentTarget(): string | undefined { return currentTarget; }
export function setCurrentTarget(target: string | undefined): void { currentTarget = target; }
// Read current target from workspace state, update status bar item
function readCurrentTarget(): void {
let buildTarget : string | undefined = extension.getState().buildTarget;
if (!buildTarget) {
logger.message("No target defined in the workspace state. Assuming 'Default'.");
statusBar.setTarget("Default");
// If no particular target is defined in settings, use 'Default' for the button
// but keep the variable empty, to not append it to the make command.
currentTarget = "";
} else {
currentTarget = buildTarget;
logger.message(`Reading current build target "${currentTarget}" from the workspace state.`);
statusBar.setTarget(currentTarget);
}
}
let configureOnOpen: boolean | undefined;
export function getConfigureOnOpen(): boolean | undefined { return configureOnOpen; }
export function setConfigureOnOpen(configure: boolean): void { configureOnOpen = configure; }
export function readConfigureOnOpen(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
// how to get default from package.json to avoid problem with 'undefined' type?
configureOnOpen = workspaceConfiguration.get<boolean>("configureOnOpen");
logger.message(`Configure on open: ${configureOnOpen}`);
}
let configureOnEdit: boolean | undefined;
export function getConfigureOnEdit(): boolean | undefined { return configureOnEdit; }
export function setConfigureOnEdit(configure: boolean): void { configureOnEdit = configure; }
export function readConfigureOnEdit(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
// how to get default from package.json to avoid problem with 'undefined' type?
configureOnEdit = workspaceConfiguration.get<boolean>("configureOnEdit");
logger.message(`Configure on edit: ${configureOnEdit}`);
}
let configureAfterCommand: boolean | undefined;
export function getConfigureAfterCommand(): boolean | undefined { return configureAfterCommand; }
export function setConfigureAfterCommand(configure: boolean): void { configureAfterCommand = configure; }
export function readConfigureAfterCommand(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
// how to get default from package.json to avoid problem with 'undefined' type?
configureAfterCommand = workspaceConfiguration.get<boolean>("configureAfterCommand");
logger.message(`Configure after command: ${configureAfterCommand}`);
}
let phonyOnlyTargets: boolean | undefined;
export function getPhonyOnlyTargets(): boolean | undefined { return phonyOnlyTargets; }
export function setPhonyOnlyTargets(phony: boolean): void { phonyOnlyTargets = phony; }
export function readPhonyOnlyTargets(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
// how to get default from package.json to avoid problem with 'undefined' type?
phonyOnlyTargets = workspaceConfiguration.get<boolean>("phonyOnlyTargets");
logger.message(`Only .PHONY targets: ${phonyOnlyTargets}`);
}
let saveBeforeBuildOrConfigure: boolean | undefined;
export function getSaveBeforeBuildOrConfigure(): boolean | undefined { return saveBeforeBuildOrConfigure; }
export function setSaveBeforeBuildOrConfigure(save: boolean): void { saveBeforeBuildOrConfigure = save; }
export function readSaveBeforeBuildOrConfigure(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
saveBeforeBuildOrConfigure = workspaceConfiguration.get<boolean>("saveBeforeBuildOrConfigure");
logger.message(`Save before build or configure: ${saveBeforeBuildOrConfigure}`);
}
let buildBeforeLaunch: boolean | undefined;
export function getBuildBeforeLaunch(): boolean | undefined { return buildBeforeLaunch; }
export function setBuildBeforeLaunch(build: boolean): void { buildBeforeLaunch = build; }
export function readBuildBeforeLaunch(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
buildBeforeLaunch = workspaceConfiguration.get<boolean>("buildBeforeLaunch");
logger.message(`Build before launch: ${buildBeforeLaunch}`);
}
let clearOutputBeforeBuild: boolean | undefined;
export function getClearOutputBeforeBuild(): boolean | undefined { return clearOutputBeforeBuild; }
export function setClearOutputBeforeBuild(clear: boolean): void { clearOutputBeforeBuild = clear; }
export function readClearOutputBeforeBuild(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
clearOutputBeforeBuild = workspaceConfiguration.get<boolean>("clearOutputBeforeBuild");
logger.message(`Clear output before build: ${clearOutputBeforeBuild}`);
}
// This setting is useful for some repos where directory changing commands (cd, push, pop)
// are missing or printed more than once, resulting in associating some IntelliSense information
// with the wrong file or even with a non existent URL.
// When this is set, the current path deduction relies only on --print-directory
// (which prints the messages regarding "Entering direcory" and "Leaving directory"),
// which is not perfect either for all repos.
let ignoreDirectoryCommands: boolean | undefined;
export function getIgnoreDirectoryCommands(): boolean | undefined { return ignoreDirectoryCommands; }
export function setIgnoreDirectoryCommands(ignore: boolean): void { ignoreDirectoryCommands = ignore; }
export function readIgnoreDirectoryCommands(): void {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
// how to get default from package.json to avoid problem with 'undefined' type?
ignoreDirectoryCommands = workspaceConfiguration.get<boolean>("ignoreDirectoryCommands");
logger.message(`Ignore directory commands: ${ignoreDirectoryCommands}`);
}
// Initialization from settings (or backup default rules), done at activation time
export async function initFromStateAndSettings(): Promise<void> {
readConfigurationCachePath();
readMakePath();
readMakefilePath();
readMakeDirectory();
readBuildLog();
readPreConfigureScript();
readAlwaysPreConfigure();
readDryrunSwitches();
readAdditionalCompilerNames();
readExcludeCompilerNames();
readCurrentMakefileConfiguration();
readMakefileConfigurations();
readCurrentTarget();
await readCurrentLaunchConfiguration();
readDefaultLaunchConfiguration();
readConfigureOnOpen();
readConfigureOnEdit();
readConfigureAfterCommand();
readPhonyOnlyTargets();
readSaveBeforeBuildOrConfigure();
readBuildBeforeLaunch();
readClearOutputBeforeBuild();
readIgnoreDirectoryCommands();
readCompileCommandsPath();
analyzeConfigureParams();
await extension._projectOutlineProvider.update(extension.getState().buildConfiguration || "unset",
extension.getState().buildTarget || "unset",
extension.getState().launchConfiguration || "unset");
// Verify the dirty state of the IntelliSense config provider and update accordingly.
// The makefile.configureOnEdit setting can be set to false when this behavior is inconvenient.
vscode.window.onDidChangeActiveTextEditor(async e => {
let language: string = "";
if (e) {
language = e.document.languageId;
}
// It is too annoying to generate a configure on any kind of editor focus change
// (for example even searching in the logging window generates this event).
// Since all the operations are guarded by the configureDirty state,
// the only "operation" left that we need to make sure it's up to date
// is IntelliSense, so trigger a configure when we switch editor focus
// into C/C++ source code.
switch (language) {
case "c":
case "cpp":
// If configureDirty is already set from a previous VSCode session,
// at workspace load this event (onDidChangeActiveTextEditor) is triggered automatically
// and if makefile.configureOnOpen is true, there is a race between two configure operations,
// one of which being unnecessary. If configureOnOpen is false, there is no race
// but still we don't want to override the behavior desired by the user.
// Additionally, if anything dirtied the configure state during a (pre)configure or build,
// skip this clean configure, to avoid annoying "blocked operation" notifications.
// The configure state remains dirty and a new configure will be triggered eventually:
// (selecting a new configuration, target or launch, build, editor focus change).
// Guarding only for not being blocked is not enough. For example,
// in the first scenario explained above, the race happens when nothing looks blocked
// here, but leading to a block notification soon.
if (extension.getState().configureDirty && configureOnEdit) {
if ((extension.getCompletedConfigureInSession())
&& !make.blockedByOp(make.Operations.configure, false)) {
logger.message("Configuring after settings or makefile changes...");
await make.configure(make.TriggeredBy.configureAfterEditorFocusChange); // this sets configureDirty back to false if it succeeds
}
}
break;
default:
break;
}
});
// Modifying any makefile should trigger an IntelliSense config provider update,
// so make the dirty state true.
// TODO: limit to makefiles relevant to this project, instead of any random makefile anywhere.
// We can't listen only to the makefile pointed to by makefile.makefilePath or makefile.makeDirectory,
// because that is only the entry point and can refer to other relevant makefiles.
// TODO: don't trigger an update for any dummy save, verify how the content changed.
vscode.workspace.onDidSaveTextDocument(e => {
if (e.uri.fsPath.toLowerCase().endsWith("makefile")) {
extension.getState().configureDirty = true;
}
});
// Watch for Makefile Tools setting updates that can change the IntelliSense config provider dirty state.
// More than one setting may be updated on one settings.json save,
// so make sure to OR the dirty state when it's calculated by a formula (not a simple TRUE value).
vscode.workspace.onDidChangeConfiguration(async e => {
if (vscode.workspace.workspaceFolders &&
e.affectsConfiguration('makefile', vscode.workspace.workspaceFolders[0].uri)) {
// We are interested in updating only some relevant properties.
// A subset of these should also trigger an IntelliSense config provider update.
// Avoid unnecessary updates (for example, when settings are modified via the extension quickPick).
let telemetryProperties: telemetry.Properties | null = {};
let updatedSettingsSubkeys: string[] = [];
let keyRoot: string = "makefile";
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration(keyRoot);
let subKey: string = "launchConfigurations";
let updatedLaunchConfigurations : LaunchConfiguration[] | undefined = workspaceConfiguration.get<LaunchConfiguration[]>(subKey);
if (!util.areEqual(updatedLaunchConfigurations, launchConfigurations)) {
// Changing a launch configuration does not impact the make or compiler tools invocations,
// so no IntelliSense update is needed.
await readCurrentLaunchConfiguration(); // this gets a refreshed view of all launch configurations
// and also updates the current one in case it was affected
updatedSettingsSubkeys.push(subKey);
}
subKey = "defaultLaunchConfiguration";
let updatedDefaultLaunchConfiguration : DefaultLaunchConfiguration | undefined = workspaceConfiguration.get<DefaultLaunchConfiguration>(subKey);
if (!util.areEqual(updatedDefaultLaunchConfiguration, defaultLaunchConfiguration)) {
// Changing a global debug configuration does not impact the make or compiler tools invocations,
// so no IntelliSense update is needed.
readDefaultLaunchConfiguration();
updatedSettingsSubkeys.push(subKey);
}
subKey = "loggingLevel";
let updatedLoggingLevel : string | undefined = workspaceConfiguration.get<string>(subKey);
if (updatedLoggingLevel !== loggingLevel) {
readLoggingLevel();
updatedSettingsSubkeys.push(subKey);
}
subKey = "buildLog";
let updatedBuildLog : string | undefined = workspaceConfiguration.get<string>(subKey);
if (updatedBuildLog) {
updatedBuildLog = util.resolvePathToRoot(updatedBuildLog);
}
if (updatedBuildLog !== buildLog) {
// Configure is dirty only if the current configuration
// doesn't have already another build log set
// (which overrides the global one).
let currentMakefileConfiguration: MakefileConfiguration | undefined = makefileConfigurations.find(k => {
if (k.name === getCurrentMakefileConfiguration()) {
return k;
}
});
extension.getState().configureDirty = extension.getState().configureDirty ||
!currentMakefileConfiguration || !currentMakefileConfiguration.buildLog;
readBuildLog();
updatedSettingsSubkeys.push(subKey);
}
subKey = "extensionOutputFolder";
let updatedExtensionOutputFolder : string | undefined = workspaceConfiguration.get<string>(subKey);
let switchedToDefault: boolean = false;
if (updatedExtensionOutputFolder) {
updatedExtensionOutputFolder = util.resolvePathToRoot(updatedExtensionOutputFolder);
if (!util.checkDirectoryExistsSync(updatedExtensionOutputFolder)) {
logger.message(`Provided extension output folder does not exist: ${updatedExtensionOutputFolder}.`);
let defaultExtensionOutputFolder: string | undefined = workspaceConfiguration.inspect<string>(subKey)?.defaultValue;
if (defaultExtensionOutputFolder) {
logger.message(`Switching to default: ${defaultExtensionOutputFolder}.`);
updatedExtensionOutputFolder = util.resolvePathToRoot(defaultExtensionOutputFolder);
// This will trigger another settings changed event
workspaceConfiguration.update(subKey, defaultExtensionOutputFolder);
updatedSettingsSubkeys.push(subKey);
// to prevent the below readExtensionOutputFolder to be executed now,
// it will during the next immediate changed event
switchedToDefault = true;
}
}
}
if (updatedExtensionOutputFolder !== extensionOutputFolder && !switchedToDefault) {
// No IntelliSense update needed.
readExtensionOutputFolder();
updatedSettingsSubkeys.push(subKey);
}
subKey = "extensionLog";
let updatedExtensionLog : string | undefined = workspaceConfiguration.get<string>(subKey);
if (updatedExtensionLog) {
// If there is a directory defined within the extension log path,
// honor it and don't append to extensionOutputFolder.
let parsePath: path.ParsedPath = path.parse(updatedExtensionLog);
if (extensionOutputFolder && !parsePath.dir) {
updatedExtensionLog = path.join(extensionOutputFolder, updatedExtensionLog);
} else {
updatedExtensionLog = util.resolvePathToRoot(updatedExtensionLog);
}
}
if (updatedExtensionLog !== extensionLog) {
// No IntelliSense update needed.
readExtensionLog();
updatedSettingsSubkeys.push(subKey);
}
subKey = "preConfigureScript";
let updatedPreConfigureScript : string | undefined = workspaceConfiguration.get<string>(subKey);
if (updatedPreConfigureScript) {
updatedPreConfigureScript = util.resolvePathToRoot(updatedPreConfigureScript);
}
if (updatedPreConfigureScript !== preConfigureScript) {
// No IntelliSense update needed.
readPreConfigureScript();
updatedSettingsSubkeys.push(subKey);
}
subKey = "alwaysPreConfigure";
let updatedAlwaysPreConfigure : boolean | undefined = workspaceConfiguration.get<boolean>(subKey);
if (updatedAlwaysPreConfigure !== alwaysPreConfigure) {
// No IntelliSense update needed.
readAlwaysPreConfigure();
updatedSettingsSubkeys.push(subKey);
}
subKey = "configurationCachePath";
let updatedConfigurationCachePath : string | undefined = workspaceConfiguration.get<string>(subKey);
if (updatedConfigurationCachePath) {
// If there is a directory defined within the configuration cache path,
// honor it and don't append to extensionOutputFolder.
let parsePath: path.ParsedPath = path.parse(updatedConfigurationCachePath);
if (extensionOutputFolder && !parsePath.dir) {
updatedConfigurationCachePath = path.join(extensionOutputFolder, updatedConfigurationCachePath);
} else {
updatedConfigurationCachePath = util.resolvePathToRoot(updatedConfigurationCachePath);
}
}
if (updatedConfigurationCachePath !== configurationCachePath) {
// A change in makefile.configurationCachePath should trigger an IntelliSense update
// only if the extension is not currently reading from a build log.
extension.getState().configureDirty = extension.getState().configureDirty ||
!buildLog || !util.checkFileExistsSync(buildLog);
readConfigurationCachePath();
updatedSettingsSubkeys.push(subKey);
}
subKey = "makePath";
let updatedMakePath : string | undefined = workspaceConfiguration.get<string>(subKey);
if (updatedMakePath !== makePath) {
// Not very likely, but it is safe to consider that a different make tool
// may produce a different dry-run output with potential impact on IntelliSense,
// so trigger an update (unless we read from a build log).
extension.getState().configureDirty = extension.getState().configureDirty ||
!buildLog || !util.checkFileExistsSync(buildLog);
readMakePath();
updatedSettingsSubkeys.push(subKey);
}
subKey = "makefilePath";
let updatedMakefilePath : string | undefined = workspaceConfiguration.get<string>(subKey);
if (updatedMakefilePath) {
updatedMakefilePath = util.resolvePathToRoot(updatedMakefilePath);
}
if (updatedMakefilePath !== makefilePath) {
// A change in makefile.makefilePath should trigger an IntelliSense update
// only if the extension is not currently reading from a build log.
extension.getState().configureDirty = extension.getState().configureDirty ||
!buildLog || !util.checkFileExistsSync(buildLog);
readMakefilePath();
updatedSettingsSubkeys.push(subKey);
}
subKey = "makeDirectory";
let updatedMakeDirectory : string | undefined = workspaceConfiguration.get<string>(subKey);
if (updatedMakeDirectory) {
updatedMakeDirectory = util.resolvePathToRoot(updatedMakeDirectory);
}
if (updatedMakeDirectory !== makeDirectory) {
// A change in makefile.makeDirectory should trigger an IntelliSense update
// only if the extension is not currently reading from a build log.
extension.getState().configureDirty = extension.getState().configureDirty ||
!buildLog || !util.checkFileExistsSync(buildLog);
readMakeDirectory();
updatedSettingsSubkeys.push(subKey);
}
subKey = "configurations";
let updatedMakefileConfigurations : MakefileConfiguration[] | undefined = workspaceConfiguration.get<MakefileConfiguration[]>(subKey);
if (!util.areEqual(updatedMakefileConfigurations, makefileConfigurations)) {
// todo: skip over updating the IntelliSense configuration provider if the current makefile configuration
// is not among the subobjects that suffered modifications.
extension.getState().configureDirty = true;
readMakefileConfigurations();
updatedSettingsSubkeys.push(subKey);
}
subKey = "dryrunSwitches";
let updatedDryrunSwitches : string[] | undefined = workspaceConfiguration.get<string[]>(subKey);
if (!util.areEqual(updatedDryrunSwitches, dryrunSwitches)) {
// A change in makefile.dryrunSwitches should trigger an IntelliSense update
// only if the extension is not currently reading from a build log.
extension.getState().configureDirty = extension.getState().configureDirty ||
!buildLog || !util.checkFileExistsSync(buildLog);
readDryrunSwitches();
updatedSettingsSubkeys.push(subKey);
}
subKey = "additionalCompilerNames";
let updatedAdditionalCompilerNames : string[] | undefined = workspaceConfiguration.get<string[]>(subKey);
if (!util.areEqual(updatedAdditionalCompilerNames, additionalCompilerNames)) {
readAdditionalCompilerNames();
updatedSettingsSubkeys.push(subKey);
}
subKey = "excludeCompilerNames";
let updatedExcludeCompilerNames : string[] | undefined = workspaceConfiguration.get<string[]>(subKey);
if (!util.areEqual(updatedExcludeCompilerNames, excludeCompilerNames)) {
readExcludeCompilerNames();
updatedSettingsSubkeys.push(subKey);
}
subKey = "configureOnOpen";
let updatedConfigureOnOpen : boolean | undefined = workspaceConfiguration.get<boolean>(subKey);
if (updatedConfigureOnOpen !== configureOnOpen) {
readConfigureOnOpen();
updatedSettingsSubkeys.push(subKey);
}
subKey = "configureOnEdit";
let updatedConfigureOnEdit : boolean | undefined = workspaceConfiguration.get<boolean>(subKey);
if (updatedConfigureOnEdit !== configureOnEdit) {
readConfigureOnEdit();
updatedSettingsSubkeys.push(subKey);
}
subKey = "configureAfterCommand";
let updatedConfigureAfterCommand : boolean | undefined = workspaceConfiguration.get<boolean>(subKey);
if (updatedConfigureAfterCommand !== configureAfterCommand) {
readConfigureAfterCommand();
updatedSettingsSubkeys.push(subKey);
}
subKey = "phonyOnlyTargets";
let updatedPhonyOnlyTargets : boolean | undefined = workspaceConfiguration.get<boolean>(subKey);
if (updatedPhonyOnlyTargets !== phonyOnlyTargets) {
readPhonyOnlyTargets();
updatedSettingsSubkeys.push(subKey);
}
subKey = "saveBeforeBuildOrConfigure";
let updatedSaveBeforeBuildOrConfigure : boolean | undefined = workspaceConfiguration.get<boolean>(subKey);
if (updatedSaveBeforeBuildOrConfigure !== saveBeforeBuildOrConfigure) {
readSaveBeforeBuildOrConfigure();
updatedSettingsSubkeys.push(subKey);
}
subKey = "buildBeforeLaunch";
let updatedBuildBeforeLaunch : boolean | undefined = workspaceConfiguration.get<boolean>(subKey);
if (updatedBuildBeforeLaunch !== buildBeforeLaunch) {
readBuildBeforeLaunch();
updatedSettingsSubkeys.push(subKey);
}
subKey = "clearOutputBeforeBuild";
let updatedClearOutputBeforeBuild : boolean | undefined = workspaceConfiguration.get<boolean>(subKey);
if (updatedClearOutputBeforeBuild !== clearOutputBeforeBuild) {
readClearOutputBeforeBuild();
updatedSettingsSubkeys.push(subKey);
}
subKey = "ignoreDirectoryCommands";
let updatedIgnoreDirectoryCommands : boolean | undefined = workspaceConfiguration.get<boolean>(subKey);
if (updatedIgnoreDirectoryCommands !== ignoreDirectoryCommands) {
readIgnoreDirectoryCommands();
updatedSettingsSubkeys.push(subKey);
}
subKey = "compileCommandsPath";
let updatedCompileCommandsPath: string | undefined = workspaceConfiguration.get<string>(subKey);
if (updatedCompileCommandsPath) {
updatedCompileCommandsPath = util.resolvePathToRoot(updatedCompileCommandsPath);
}
if (updatedCompileCommandsPath !== compileCommandsPath) {
readCompileCommandsPath();
updatedSettingsSubkeys.push(subKey);
}
// Final updates in some constructs that depend on more than one of the above settings.
if (extension.getState().configureDirty) {
analyzeConfigureParams();
}
// Report all the settings changes detected by now.
// TODO: to avoid unnecessary telemetry processing, evaluate whether the changes done
// in the object makefile.launchConfigurations and makefile.configurations
// apply exactly to the current launch configuration, since we don't collect and aggregate
// information from all the array yet.
updatedSettingsSubkeys.forEach(subKey => {
let key: string = keyRoot + "." + subKey;
logger.message(`${key} setting changed.`, "Verbose");
try {
telemetryProperties = telemetry.analyzeSettings(workspaceConfiguration[subKey], key,
util.thisExtensionPackage().contributes.configuration.properties[key],
false, telemetryProperties);
} catch (e) {
logger.message(e.message);
}
});
if (telemetryProperties && util.hasProperties(telemetryProperties)) {
telemetry.logEvent("settingsChanged", telemetryProperties);
}
}
});
}
export function setConfigurationByName(configurationName: string): void {
extension.getState().buildConfiguration = configurationName;
setCurrentMakefileConfiguration(configurationName);
extension._projectOutlineProvider.updateConfiguration(configurationName);
}
export function prepareConfigurationsQuickPick(): string[] {
const items: string[] = makefileConfigurations.map((k => {
return k.name;
}));
if (items.length === 0) {
logger.message("No configurations defined in makefile.configurations setting.");
items.push("Default");
}
return items;
}
// Fill a drop-down with all the configuration names defined by the user in makefile.configurations setting.
// Triggers a cpptools configuration provider update after selection.
export async function setNewConfiguration(): Promise<void> {
// Cannot set a new makefile configuration if the project is currently building or (pre-)configuring.
if (make.blockedByOp(make.Operations.changeConfiguration)) {
return;
}
const items: string[] = prepareConfigurationsQuickPick();
let options: vscode.QuickPickOptions = {};
options.ignoreFocusOut = true; // so that the logger and the quick pick don't compete over focus
const chosen: string | undefined = await vscode.window.showQuickPick(items, options);
if (chosen && chosen !== getCurrentMakefileConfiguration()) {
let telemetryProperties: telemetry.Properties | null = {
state: "makefileConfiguration"
};
telemetry.logEvent("stateChanged", telemetryProperties);
setConfigurationByName(chosen);
if (configureAfterCommand) {
logger.message("Automatically reconfiguring the project after a makefile configuration change.");
await make.configure(make.TriggeredBy.configureAfterConfigurationChange);
}
// Refresh telemetry for this new makefile configuration
// (this will find the corresponding item in the makefile.configurations array
// and report all the relevant settings of that object).
// Because of this, the event name is still "settingsChanged", even if
// we're doing a state change now.
let keyRoot: string = "makefile";
let subKey: string = "configurations";
let key: string = keyRoot + "." + subKey;
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration(keyRoot);
telemetryProperties = {};
// We should have at least one item in the configurations array
// if the extension changes state for launch configuration,
// but guard just in case.
let makefileonfigurationSetting: any = workspaceConfiguration[subKey];
if (makefileonfigurationSetting) {
try {
telemetryProperties = telemetry.analyzeSettings(makefileonfigurationSetting, key,
util.thisExtensionPackage().contributes.configuration.properties[key],
true, telemetryProperties);
} catch (e) {
logger.message(e.message);
}
if (telemetryProperties && util.hasProperties(telemetryProperties)) {
telemetry.logEvent("settingsChanged", telemetryProperties);
}
}
}
}
export function setTargetByName(targetName: string) : void {
currentTarget = targetName;
let displayTarget: string = targetName ? currentTarget : "Default";
statusBar.setTarget(displayTarget);
logger.message("Setting target " + displayTarget);
extension.getState().buildTarget = currentTarget;
extension._projectOutlineProvider.updateBuildTarget(targetName);
}
// Fill a drop-down with all the target names run by building the makefile for the current configuration
// Triggers a cpptools configuration provider update after selection.
// TODO: change the UI list to multiple selections mode and store an array of current active targets
export async function selectTarget(): Promise<void> {
// Cannot select a new target if the project is currently building or (pre-)configuring.
if (make.blockedByOp(make.Operations.changeBuildTarget)) {
return;
}
// warn about an out of date configure state and configure if makefile.configureAfterCommand allows.
if (extension.getState().configureDirty ||
// The configure state might not be dirty from the last session but if the project is set to skip
// configure on open and no configure happened yet we still must warn.
(configureOnOpen === false && !extension.getCompletedConfigureInSession())) {
logger.message("The project needs a configure to populate the build targets correctly.");
if (configureAfterCommand) {
let retc: number = await make.configure(make.TriggeredBy.configureBeforeTargetChange);
if (retc !== make.ConfigureBuildReturnCodeTypes.success) {
logger.message("The build targets list may not be accurate because configure failed.");
}
}
}
let options: vscode.QuickPickOptions = {};
options.ignoreFocusOut = true; // so that the logger and the quick pick don't compete over focus
// Ensure "all" is always available as a target to select.
// There are scenarios when "all" might not be present in the list of available targets,
// for example when the extension is using a build log or dryrun cache of a previous state
// when a particular target was selected and a dryrun applied on that is producing a subset of targets,
// making it impossible to select "all" back again without resetting the Makefile Tools state
// or switching to a different makefile configuration or implementing an editable target quick pick.
// Another situation where "all" would inconveniently miss from the quick pick is when the user is
// providing a build log without the required verbosity for parsing targets (-p or --print-data-base switches).
// When the extension is not reading from build log or dryrun cache, we have logic to prevent
// "all" from getting lost: make sure the target is not appended to the make invocation
// whose output is used to parse the targets (as opposed to parsing for IntelliSense or launch targets
// when the current target must be appended to the make command).
if (!buildTargets.includes("all")) {
buildTargets.push("all");
}
const chosen: string | undefined = await vscode.window.showQuickPick(buildTargets, options);
if (chosen && chosen !== getCurrentTarget()) {
const telemetryProperties: telemetry.Properties = {
state: "buildTarget"
};
telemetry.logEvent("stateChanged", telemetryProperties);
setTargetByName(chosen);
if (configureAfterCommand) {
// The set of build targets remains the same even if the current target has changed
logger.message("Automatically reconfiguring the project after a build target change.");
await make.configure(make.TriggeredBy.configureAfterTargetChange, false);
}
}
}
// The 'name' of a launch configuration is a string following this syntax:
// [cwd]>[binaryPath](binaryArg1,binaryArg2,...)
// These strings are found by the extension while parsing the output of the dry-run or build log,
// which reflect possible different ways of running the binaries built by the makefile.
// TODO: If we find that these strings are not unique (meaning the makefile may invoke
// the given binary in the exact same way more than once), incorporate also the containing target
// name in the syntax (or, since in theory one can write a makefile target to run the same binary
// in the same way more than once, add some number suffix).
export async function setLaunchConfigurationByName(launchConfigurationName: string) : Promise<void> {
// Find the matching entry in the array of launch configurations
// or generate a new entry in settings if none are found.
currentLaunchConfiguration = getLaunchConfiguration(launchConfigurationName);
if (!currentLaunchConfiguration) {
currentLaunchConfiguration = await stringToLaunchConfiguration(launchConfigurationName);
if (currentLaunchConfiguration) {
launchConfigurations.push(currentLaunchConfiguration);
// Avoid updating the launchConfigurations array in settings.json for regression tests.
if (process.env['MAKEFILE_TOOLS_TESTING'] !== '1') {
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("makefile");
workspaceConfiguration.update("launchConfigurations", launchConfigurations);
}
logger.message(`Inserting a new entry for ${launchConfigurationName} in the array of makefile.launchConfigurations. ` +
"You may define any additional debug properties for it in settings.");
}
}
if (currentLaunchConfiguration) {
logger.message('Setting current launch target "' + launchConfigurationName + '"');
extension.getState().launchConfiguration = launchConfigurationName;
statusBar.setLaunchConfiguration(launchConfigurationName);
} else {
if (launchConfigurationName === "") {
logger.message("Unsetting the current launch configuration.");
} else {
logger.message(`A problem occured while analyzing launch configuration name ${launchConfigurationName}. Current launch configuration is unset.`);
}
extension.getState().launchConfiguration = undefined;
statusBar.setLaunchConfiguration("No launch configuration set");
}
await extension._projectOutlineProvider.updateLaunchTarget(launchConfigurationName);
}
// Fill a drop-down with all the launch configurations found for binaries built by the makefile
// under the scope of the current build configuration and target
// Selection updates current launch configuration that will be ready for the next debug/run operation
export async function selectLaunchConfiguration(): Promise<void> {
// Cannot select a new launch configuration if the project is currently building or (pre-)configuring.
if (make.blockedByOp(make.Operations.changeLaunchTarget)) {
return;
}
// warn about an out of date configure state and configure if makefile.configureAfterCommand allows.
if (extension.getState().configureDirty ||
// The configure state might not be dirty from the last session but if the project is set to skip
// configure on open and no configure happened yet we still must warn.
(configureOnOpen === false && !extension.getCompletedConfigureInSession())) {
logger.message("The project needs a configure to populate the launch targets correctly.");
if (configureAfterCommand) {
let retc: number = await make.configure(make.TriggeredBy.configureBeforeLaunchTargetChange);
if (retc !== make.ConfigureBuildReturnCodeTypes.success) {
logger.message("The launch targets list may not be accurate because configure failed.");
}
}
}
// TODO: create a quick pick with description and details for items
// to better view the long targets commands
// In the quick pick, include also any makefile.launchConfigurations entries,
// as long as they exist on disk and without allowing duplicates.
let launchTargetsNames: string[] = [...launchTargets];
launchConfigurations.forEach(launchConfiguration => {
if (util.checkFileExistsSync(launchConfiguration.binaryPath)) {
launchTargetsNames.push(launchConfigurationToString(launchConfiguration));
}
});
launchTargetsNames = util.sortAndRemoveDuplicates(launchTargetsNames);
let options: vscode.QuickPickOptions = {};
options.ignoreFocusOut = true; // so that the logger and the quick pick don't compete over focus
if (launchTargets.length === 0) {
options.placeHolder = "No launch targets identified";
}
const chosen: string | undefined = await vscode.window.showQuickPick(launchTargetsNames, options);
if (chosen) {
let currentLaunchConfiguration: LaunchConfiguration | undefined = getCurrentLaunchConfiguration();
if (!currentLaunchConfiguration || chosen !== launchConfigurationToString(currentLaunchConfiguration)) {
let telemetryProperties: telemetry.Properties | null = {
state: "launchConfiguration"
};
telemetry.logEvent("stateChanged", telemetryProperties);
await setLaunchConfigurationByName(chosen);
// Refresh telemetry for this new launch configuration
// (this will find the corresponding item in the makefile.launchConfigurations array
// and report all the relevant settings of that object).
// Because of this, the event name is still "settingsChanged", even if
// we're doing a state change now.
let keyRoot: string = "makefile";
let subKey: string = "launchConfigurations";
let key: string = keyRoot + "." + subKey;
let workspaceConfiguration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration(keyRoot);
telemetryProperties = {};
// We should have at least one item in the launchConfigurations array
// if the extension changes state for launch configuration,
// but guard just in case.
let launchConfigurationSetting: any = workspaceConfiguration[subKey];
if (launchConfigurationSetting) {
try {
telemetryProperties = telemetry.analyzeSettings(launchConfigurationSetting, key,
util.thisExtensionPackage().contributes.configuration.properties[key],
true, telemetryProperties);
} catch (e) {
logger.message(e.message);
}
if (telemetryProperties && util.hasProperties(telemetryProperties)) {
telemetry.logEvent("settingsChanged", telemetryProperties);
}
}
}
}
}
// List of targets defined in the makefile project.
// Parsed from the build log, configuration cache or live dry-run output at configure time.
// Currently, this list contains any abstract intermediate target
// (like any object produced by the compiler from a source code file).
// TODO: filter only the relevant targets (binaries, libraries, etc...) from this list.
let buildTargets: string[] = [];
export function getBuildTargets(): string[] { return buildTargets; }
export function setBuildTargets(targets: string[]): void { buildTargets = targets; }
// List of all the binaries built by the current project and all the ways
// they may be invoked (from what cwd, with what arguments).
// This is parsed from the build log, configuration cache or live dry-run output at configure time.
// This is what populates the 'launch targets' quick pick and is different than the
// launch configurations defined in settings.
// A launch configuration extends a launch target with various debugger settings.
// Each launch configuration entry is written in settings by the extension
// when the user actively selects any launch target from the quick pick.
// Then the user can add any of the provided extra attributes (miMode, miDebuggerPath, etc...)
// under that entry. It is possible that not all launch targets have a launch configuration counterpart,
// but if they do it is only one. Technically, we can imagine one launch target may have
// more than one launch configurations defined in settings (same binary, location and arguments debugged
// with different scenarios)) but this is not yet supported because currently the launch configurations
// are uniquely referenced by a string formed by cwd, binary and args (which form a launch target).
// The quick pick is not populated by the launch configurations list because its entries may be
// out of date and most importantly a subset. We want the quick pick to reflect all the possibilities
// that are found available with the current configuration of the project.
let launchTargets: string[] = [];
export function getLaunchTargets(): string[] { return launchTargets; }
export function setLaunchTargets(targets: string[]): void { launchTargets = targets; } | the_stack |
import {
DiscriminantValue,
DiscriminatedUnionMember,
Nominal,
SelectUnionMember,
StringKeyOf,
getMemberTags,
unsafeCoerce,
} from './internal/Utils'
import {
GetType,
KeyOfTypeConstructorRegistry,
GetData,
GetSpec,
SpecData,
SpecType,
TypeConstructorRegistry0,
TypeConstructorRegistry1,
TypeConstructorRegistry2,
TypeConstructorRegistry3,
TypeConstructorRegistry4,
} from './Registry'
/**
* Used as configuration to set the `NullaryConstructorsMode` to 'constant'
*
* @since 0.2.0
*/
export const constant = 'constant'
/**
* The `NullaryConstructorsMode` setting for 'constant' nullary constructors
*
* @since 0.2.0
*/
export type NullaryConstructorsMode_Constant = typeof constant
/**
* Used as configuration to set the `NullaryConstructorsMode` to 'thunk'
*
* @since 0.2.0
*/
export const thunk = 'thunk'
/**
* The `NullaryConstructorsMode` setting for 'thunk' nullary constructors
*
* @since 0.2.0
*/
export type NullaryConstructorsMode_Thunk = typeof thunk
/**
* A union of the valid options used to set the nullary constructors mode
*
* @since 0.2.0
*/
export type NullaryConstructorsMode =
| NullaryConstructorsMode_Constant
| NullaryConstructorsMode_Thunk
/**
* NOT EXPORTED
*
* @since 0.2.0
*/
const mk__ = (a: void): __ => unsafeCoerce<void, __>(a)
/**
* NOT EXPORTED
*
* @since 0.2.0
*/
// tslint:disable-next-line class-name
interface __ extends Nominal<'__', void> {}
/**
* A value of type `__`, a Nominal type equivalent to the run-time type `void`
*
* Used as a placeholder when interacting with the library's generation functions
*
* @since 0.2.0
*/
export const __ = mk__(undefined)
// generated capabilities
/**
* A type-level representation of a tagged union's generated data constructors
*
* @since 0.2.0
*/
export type Constructors<
TypeURI extends KeyOfTypeConstructorRegistry,
T extends GetType<TypeURI>,
DiscriminantKey extends StringKeyOf<T>,
Mode extends NullaryConstructorsMode
> = {
[MemberURI in DiscriminantValue<T, DiscriminantKey>]: {} extends Omit<
DiscriminatedUnionMember<T, DiscriminantKey, MemberURI>,
DiscriminantKey
> // has no fields other than the discriminant field
? TypeURI extends keyof TypeConstructorRegistry0
? Mode extends NullaryConstructorsMode_Constant
? TypeConstructorRegistry0[TypeURI][SpecType]
: () => TypeConstructorRegistry0[TypeURI][SpecType]
: TypeURI extends keyof TypeConstructorRegistry1<unknown>
? Mode extends NullaryConstructorsMode_Constant
? TypeConstructorRegistry1<never>[TypeURI][SpecType]
: <A>() => TypeConstructorRegistry1<A>[TypeURI][SpecType]
: TypeURI extends keyof TypeConstructorRegistry2<unknown, unknown>
? Mode extends NullaryConstructorsMode_Constant
? TypeConstructorRegistry2<never, never>[TypeURI][SpecType]
: <E, A>() => TypeConstructorRegistry2<E, A>[TypeURI][SpecType]
: TypeURI extends keyof TypeConstructorRegistry3<
unknown,
unknown,
unknown
>
? Mode extends NullaryConstructorsMode_Constant
? TypeConstructorRegistry3<never, never, never>[TypeURI][SpecType]
: <R, E, A>() => TypeConstructorRegistry3<R, E, A>[TypeURI][SpecType]
: TypeURI extends keyof TypeConstructorRegistry4<
unknown,
unknown,
unknown,
unknown
>
? Mode extends NullaryConstructorsMode_Constant
? TypeConstructorRegistry4<
never,
never,
never,
never
>[TypeURI][SpecType]
: <S, R, E, A>() => TypeConstructorRegistry4<
S,
R,
E,
A
>[TypeURI][SpecType]
: never // has extra fields
: TypeURI extends keyof TypeConstructorRegistry0
? (
fields: {
[Field in keyof Omit<
DiscriminatedUnionMember<T, DiscriminantKey, MemberURI>,
DiscriminantKey
>]: MemberURI extends keyof TypeConstructorRegistry0[TypeURI][SpecData]
? Field extends keyof TypeConstructorRegistry0[TypeURI][SpecData][MemberURI]
? TypeConstructorRegistry0[TypeURI][SpecData][MemberURI][Field]
: never
: never
},
) => TypeConstructorRegistry0[TypeURI][SpecType]
: TypeURI extends keyof TypeConstructorRegistry1<unknown>
? <A>(
fields: {
[Field in keyof Omit<
DiscriminatedUnionMember<T, DiscriminantKey, MemberURI>,
DiscriminantKey
>]: MemberURI extends keyof TypeConstructorRegistry1<
A
>[TypeURI][SpecData]
? Field extends keyof TypeConstructorRegistry1<
A
>[TypeURI][SpecData][MemberURI]
? TypeConstructorRegistry1<A>[TypeURI][SpecData][MemberURI][Field]
: never
: never
},
) => TypeConstructorRegistry1<A>[TypeURI][SpecType]
: TypeURI extends keyof TypeConstructorRegistry2<unknown, unknown>
? <E, A>(
fields: {
[Field in keyof Omit<
DiscriminatedUnionMember<T, DiscriminantKey, MemberURI>,
DiscriminantKey
>]: MemberURI extends keyof TypeConstructorRegistry2<
E,
A
>[TypeURI][SpecData]
? Field extends keyof TypeConstructorRegistry2<
E,
A
>[TypeURI][SpecData][MemberURI]
? TypeConstructorRegistry2<
E,
A
>[TypeURI][SpecData][MemberURI][Field]
: never
: never
},
) => TypeConstructorRegistry2<E, A>[TypeURI][SpecType]
: TypeURI extends keyof TypeConstructorRegistry3<unknown, unknown, unknown>
? <R, E, A>(
fields: {
[Field in keyof Omit<
DiscriminatedUnionMember<T, DiscriminantKey, MemberURI>,
DiscriminantKey
>]: MemberURI extends keyof TypeConstructorRegistry3<
R,
E,
A
>[TypeURI][SpecData]
? Field extends keyof TypeConstructorRegistry3<
R,
E,
A
>[TypeURI][SpecData][MemberURI]
? TypeConstructorRegistry3<
R,
E,
A
>[TypeURI][SpecData][MemberURI][Field]
: never
: never
},
) => TypeConstructorRegistry3<R, E, A>[TypeURI][SpecType]
: TypeURI extends keyof TypeConstructorRegistry4<
unknown,
unknown,
unknown,
unknown
>
? <S, R, E, A>(
fields: {
[Field in keyof Omit<
DiscriminatedUnionMember<T, DiscriminantKey, MemberURI>,
DiscriminantKey
>]: MemberURI extends keyof TypeConstructorRegistry4<
S,
R,
E,
A
>[TypeURI][SpecData]
? Field extends keyof TypeConstructorRegistry4<
S,
R,
E,
A
>[TypeURI][SpecData][MemberURI]
? TypeConstructorRegistry4<
S,
R,
E,
A
>[TypeURI][SpecData][MemberURI][Field]
: never
: never
},
) => TypeConstructorRegistry4<S, R, E, A>[TypeURI][SpecType]
: never
}
/**
* Generates data constructors for the members of a tagged union
*
* @since 0.2.0
*/
export const mkConstructors = <
TypeURI extends KeyOfTypeConstructorRegistry
>() => <
T extends GetType<TypeURI>,
DiscriminantKey extends StringKeyOf<T>,
Mode extends NullaryConstructorsMode
>(
config: {
readonly discriminantKey: DiscriminantKey
readonly nullaryConstructorsMode: Mode
},
memberTagsRecord: Mode extends NullaryConstructorsMode_Constant
? {
[K in DiscriminantValue<T, DiscriminantKey>]: {
[Fields in keyof GetSpec<TypeURI>[SpecData][K &
keyof GetSpec<TypeURI>[SpecData]]]: __
}
}
: {
[K in DiscriminantValue<T, DiscriminantKey>]: __
},
): Constructors<TypeURI, T, DiscriminantKey, Mode> => {
const result = {} as {
[K in DiscriminantValue<T, DiscriminantKey>]: Constructors<
TypeURI,
T,
DiscriminantKey,
Mode
>[K]
}
if (config.nullaryConstructorsMode === constant) {
const pairs = <R extends typeof memberTagsRecord>(rec: R) =>
(Object.entries(rec) as unknown) as ReadonlyArray<
readonly [
DiscriminantValue<T, DiscriminantKey>,
{
[K in DiscriminantValue<T, DiscriminantKey>]: {
[Fields in keyof GetSpec<TypeURI>[SpecData][K &
keyof GetSpec<TypeURI>[SpecData]]]: __
}
}[DiscriminantValue<T, DiscriminantKey>],
]
>
for (const [memberTag, memberFields] of pairs(memberTagsRecord)) {
const discriminantPair = { [config.discriminantKey]: memberTag }
const isNullaryConstructor = Object.keys(memberFields).length === 1
const constructor = ((isNullaryConstructor
? discriminantPair
: (
fields: Omit<
DiscriminatedUnionMember<
T,
DiscriminantKey,
DiscriminantValue<T, DiscriminantKey>
>,
DiscriminantKey
>,
) => ({
...discriminantPair,
...fields,
})) as unknown) as Constructors<
TypeURI,
T,
DiscriminantKey,
Mode
>[typeof memberTag]
result[memberTag] = constructor
}
} else {
for (const memberTag of getMemberTags(
memberTagsRecord as {
[K in DiscriminantValue<T, DiscriminantKey>]: __
},
)) {
const discriminantPair = { [config.discriminantKey]: memberTag }
const constructor = (((
fields: Omit<
DiscriminatedUnionMember<
T,
DiscriminantKey,
DiscriminantValue<T, DiscriminantKey>
>,
DiscriminantKey
>,
) =>
// tslint:disable-next-line strict-type-predicates
fields === undefined || fields === null || typeof fields !== 'object'
? discriminantPair
: { ...discriminantPair, ...fields }) as unknown) as Constructors<
TypeURI,
T,
DiscriminantKey,
Mode
>[typeof memberTag]
result[memberTag] = constructor
}
}
return result
}
/**
* A type-level representation of a tagged union's generated `match` function
*
* @since 0.2.0
*/
export type Match<
TypeURI extends KeyOfTypeConstructorRegistry,
T extends GetType<TypeURI>,
DiscriminantKey extends StringKeyOf<T>
> = TypeURI extends keyof TypeConstructorRegistry0
? <B>(
a: TypeConstructorRegistry0[TypeURI][SpecType],
caseHandlers: {
[K in DiscriminantValue<T, DiscriminantKey>]: (
x: TypeConstructorRegistry0[TypeURI][SpecData][K &
keyof TypeConstructorRegistry0[TypeURI][SpecData]],
) => B
},
) => B
: TypeURI extends keyof TypeConstructorRegistry1<unknown>
? <A, B>(
a: TypeConstructorRegistry1<A>[TypeURI][SpecType],
caseHandlers: {
[K in DiscriminantValue<T, DiscriminantKey>]: (
x: TypeConstructorRegistry1<A>[TypeURI][SpecData][K &
keyof TypeConstructorRegistry1<A>[TypeURI][SpecData]],
) => B
},
) => B
: TypeURI extends keyof TypeConstructorRegistry2<unknown, unknown>
? <E, A, B>(
a: TypeConstructorRegistry2<E, A>[TypeURI][SpecType],
caseHandlers: {
[K in DiscriminantValue<T, DiscriminantKey>]: (
x: TypeConstructorRegistry2<E, A>[TypeURI][SpecData][K &
keyof TypeConstructorRegistry2<E, A>[TypeURI][SpecData]],
) => B
},
) => B
: TypeURI extends keyof TypeConstructorRegistry3<unknown, unknown, unknown>
? <R, E, A, B>(
a: TypeConstructorRegistry3<R, E, A>[TypeURI][SpecType],
caseHandlers: {
[K in DiscriminantValue<T, DiscriminantKey>]: (
x: TypeConstructorRegistry3<R, E, A>[TypeURI][SpecData][K &
keyof TypeConstructorRegistry3<R, E, A>[TypeURI][SpecData]],
) => B
},
) => B
: TypeURI extends keyof TypeConstructorRegistry4<
unknown,
unknown,
unknown,
unknown
>
? <S, R, E, A, B>(
caseHandlers: {
[K in DiscriminantValue<T, DiscriminantKey>]: (
x: TypeConstructorRegistry4<S, R, E, A>[TypeURI][SpecData][K &
keyof TypeConstructorRegistry4<S, R, E, A>[TypeURI][SpecData]],
) => B
},
) => (a: TypeConstructorRegistry4<S, R, E, A>[TypeURI][SpecType]) => B
: never
/**
* Generates a `match` function that simulates pattern matching
*
* NOTE: Some libraries call this `fold` or `cata` because of the similarity
* to a "generalized fold"
*
* @since 0.2.0
*/
export const mkMatch = <TypeURI extends KeyOfTypeConstructorRegistry>() => <
T extends GetType<TypeURI>,
DiscriminantKey extends StringKeyOf<T>
>(config: {
readonly discriminantKey: DiscriminantKey
}): Match<TypeURI, T, DiscriminantKey> =>
// internal representation is using loose types & assertions for simplicity
// the real type information is defined in Match<TypeURI, T, DiscriminantKey>
(<B>(
t: T,
caseHandlers: {
[K in DiscriminantValue<T, DiscriminantKey>]: (
x: GetData<TypeURI>[K & keyof GetData<TypeURI>],
) => B
},
) => {
const dataConstructorName = t[config.discriminantKey] as DiscriminantValue<
T,
DiscriminantKey
>
return caseHandlers[dataConstructorName](
(t as unknown) as GetSpec<TypeURI>[SpecData][T[DiscriminantKey] &
string &
keyof GetSpec<TypeURI>[SpecData]],
)
}) as Match<TypeURI, T, DiscriminantKey>
/**
* A type-level representation of a tagged union's generated type guard predicates
*
* @since 0.2.0
*/
export type Guards<
TypeURI extends KeyOfTypeConstructorRegistry,
T extends GetType<TypeURI>,
DiscriminantKey extends StringKeyOf<T>
> = TypeURI extends keyof TypeConstructorRegistry0
? {
[K in DiscriminantValue<T, DiscriminantKey>]: (
x: TypeConstructorRegistry0[TypeURI][SpecType],
) => x is SelectUnionMember<
DiscriminantKey,
K,
TypeConstructorRegistry0[TypeURI][SpecType]
>
} & {
readonly memberOfUnion: <U extends unknown>(
action: TypeConstructorRegistry0[TypeURI][SpecType] | U,
) => action is TypeConstructorRegistry0[TypeURI][SpecType]
}
: TypeURI extends keyof TypeConstructorRegistry1<unknown>
? {
[K in DiscriminantValue<T, DiscriminantKey>]: <A>(
x: TypeConstructorRegistry1<A>[TypeURI][SpecType],
) => x is SelectUnionMember<
DiscriminantKey,
K,
TypeConstructorRegistry1<A>[TypeURI][SpecType]
>
} & {
readonly memberOfUnion: <A, U extends unknown>(
action: TypeConstructorRegistry1<A>[TypeURI][SpecType] | U,
) => action is TypeConstructorRegistry1<A>[TypeURI][SpecType]
}
: TypeURI extends keyof TypeConstructorRegistry2<unknown, unknown>
? {
[K in DiscriminantValue<T, DiscriminantKey>]: <E, A>(
x: TypeConstructorRegistry2<E, A>[TypeURI][SpecType],
) => x is SelectUnionMember<
DiscriminantKey,
K,
TypeConstructorRegistry2<E, A>[TypeURI][SpecType]
>
} & {
readonly memberOfUnion: <E, A, U extends unknown>(
action: TypeConstructorRegistry2<E, A>[TypeURI][SpecType] | U,
) => action is TypeConstructorRegistry2<E, A>[TypeURI][SpecType]
}
: TypeURI extends keyof TypeConstructorRegistry3<unknown, unknown, unknown>
? {
[K in DiscriminantValue<T, DiscriminantKey>]: <R, E, A>(
x: TypeConstructorRegistry3<R, E, A>[TypeURI][SpecType],
) => x is SelectUnionMember<
DiscriminantKey,
K,
TypeConstructorRegistry3<R, E, A>[TypeURI][SpecType]
>
} & {
readonly memberOfUnion: <R, E, A, U extends unknown>(
action: TypeConstructorRegistry3<R, E, A>[TypeURI][SpecType] | U,
) => action is TypeConstructorRegistry3<R, E, A>[TypeURI][SpecType]
}
: TypeURI extends keyof TypeConstructorRegistry4<
unknown,
unknown,
unknown,
unknown
>
? {
[K in DiscriminantValue<T, DiscriminantKey>]: <S, R, E, A>(
x: TypeConstructorRegistry4<S, R, E, A>[TypeURI][SpecType],
) => x is SelectUnionMember<
DiscriminantKey,
K,
TypeConstructorRegistry4<S, R, E, A>[TypeURI][SpecType]
>
} & {
readonly memberOfUnion: <S, R, E, A, U extends unknown>(
action: TypeConstructorRegistry4<S, R, E, A>[TypeURI][SpecType] | U,
) => action is TypeConstructorRegistry4<S, R, E, A>[TypeURI][SpecType]
}
: never
/**
* Generates type guards for the members of a tagged union
*
* @since 0.2.0
*/
export const mkGuards = <TypeURI extends KeyOfTypeConstructorRegistry>() => <
T extends GetType<TypeURI>,
DiscriminantKey extends StringKeyOf<T>
>(
config: {
readonly discriminantKey: DiscriminantKey
},
// works with either nullary constructors mode
memberTagsRecord:
| {
[K in DiscriminantValue<T, DiscriminantKey>]: {
[Fields in keyof GetSpec<TypeURI>[SpecData][K &
keyof GetSpec<TypeURI>[SpecData]]]: __
}
}
| {
[K in DiscriminantValue<T, DiscriminantKey>]: __
},
): Guards<TypeURI, T, DiscriminantKey> => {
// internal representation is using loose types & assertions for simplicity
// the real type information is defined in Guards<TypeURI, T, DiscriminantKey>
const result = {} as Guards<TypeURI, T, DiscriminantKey>
for (const memberTag of getMemberTags(memberTagsRecord)) {
const guard = (((
member: T,
): member is Extract<
T,
{
[K in DiscriminantKey]: DiscriminantValue<T, DiscriminantKey>
}
> =>
(member[config.discriminantKey] as DiscriminantValue<
T,
DiscriminantKey
>) === memberTag) as unknown) as Guards<
TypeURI,
T,
DiscriminantKey
>[DiscriminantValue<T, DiscriminantKey>]
result[memberTag] = guard
}
return {
...result,
memberOfUnion: (
action:
| T
| {
[K in DiscriminantKey]: DiscriminantValue<T, DiscriminantKey>
},
): action is T => {
const guards = (Object.values(result) as unknown) as ReadonlyArray<
Guards<TypeURI, T, DiscriminantKey>['memberOfUnion'] &
// give a call signature for `guard(action)` down below
((x: unknown) => boolean)
>
if (!(config.discriminantKey in action)) {
return false
}
for (const guard of guards) {
if (guard(action)) {
return true
}
continue
}
return false
},
}
}
/**
* Generates useful functions for working with a tagged union
*
* The most configurable version of this function offered by the library, most
* useful to those who don't mind passing in a config each time & want maximum
* flexibility
*
* @since 0.2.0
*/
export const mkTaggedUnionCustom = <
TypeURI extends KeyOfTypeConstructorRegistry
>() => <
T extends GetType<TypeURI>,
DiscriminantKey extends StringKeyOf<T>,
Mode extends NullaryConstructorsMode
>(
config: {
readonly discriminantKey: DiscriminantKey
readonly nullaryConstructorsMode: Mode
},
memberTagsRecord: Mode extends NullaryConstructorsMode_Constant
? {
[K in DiscriminantValue<T, DiscriminantKey>]: {
[Fields in keyof GetSpec<TypeURI>[SpecData][K &
keyof GetSpec<TypeURI>[SpecData]]]: __
}
}
: {
[K in DiscriminantValue<T, DiscriminantKey>]: __
},
) => {
const constructors = mkConstructors<TypeURI>()(config, memberTagsRecord)
const basicConfig = { discriminantKey: config.discriminantKey }
const is = mkGuards<TypeURI>()<T, DiscriminantKey>(
basicConfig,
memberTagsRecord,
)
const match = mkMatch<TypeURI>()<T, DiscriminantKey>(basicConfig)
return { ...constructors, is, match }
}
/**
* Generates useful functions for working with a tagged union
*
* The default, go-to generation function provided by the library
*
* Discriminant key: `'tag'`
*
* Nullary constructors mode: `'constant'`
*
* Use `mkTaggedUnionBasic` instead if you're okay with nullary constructors being
* functions instead of constants and/or you desire less boilerplate
*
* @since 0.2.0
*/
export const mkTaggedUnion = <
TypeURI extends KeyOfTypeConstructorRegistry
>() => <
T extends GetType<TypeURI>,
DiscriminantKey extends 'tag' & StringKeyOf<T>
>(
memberTagsRecord: {
[K in DiscriminantValue<T, DiscriminantKey>]: {
[Fields in keyof GetSpec<TypeURI>[SpecData][K &
keyof GetSpec<TypeURI>[SpecData]]]: __
}
},
) => {
const defaultConfig = {
discriminantKey: 'tag' as DiscriminantKey,
nullaryConstructorsMode: constant as NullaryConstructorsMode_Constant,
}
// tslint:disable ter-func-call-spacing
return mkTaggedUnionCustom<TypeURI>()<
T,
DiscriminantKey,
NullaryConstructorsMode_Constant
>(defaultConfig, memberTagsRecord)
// tslint:enable ter-func-call-spacing
}
/**
* Generates useful functions for working with a tagged union
*
* An alternate version of `mkTaggedUnion` which represents nullary constructors
* as functions (thunks) instead of constants, requiring less boilerplate
*
* Discriminant key: `'tag'`
*
* Nullary constructors mode: `'thunk'`
*
* @since 0.2.0
*/
export const mkTaggedUnionBasic = <
TypeURI extends KeyOfTypeConstructorRegistry
>() => <
T extends GetType<TypeURI>,
DiscriminantKey extends 'tag' & StringKeyOf<T>
>(
memberTagsRecord: {
[K in DiscriminantValue<T, DiscriminantKey>]: __
},
) => {
const defaultConfig = {
discriminantKey: 'tag' as DiscriminantKey,
nullaryConstructorsMode: thunk as NullaryConstructorsMode_Thunk,
}
// tslint:disable ter-func-call-spacing
return mkTaggedUnionCustom<TypeURI>()<
T,
DiscriminantKey,
NullaryConstructorsMode_Thunk
>(defaultConfig, memberTagsRecord)
// tslint:enable ter-func-call-spacing
}
/**
* Generates useful functions for working with a tagged union
*
* A generation function preconfigured to the right defaults for working with
* Redux-style actions & action creators
*
* Discriminant key: `'type'`
*
* Nullary constructors mode: `'thunk'`
*
* @since 0.2.0
*/
export const mkTaggedUnionRedux = <
TypeURI extends KeyOfTypeConstructorRegistry
>() => <
T extends GetType<TypeURI>,
DiscriminantKey extends 'type' & StringKeyOf<T>
>(
memberTagsRecord: {
[K in DiscriminantValue<T, DiscriminantKey>]: __
},
) => {
const defaultConfig = {
discriminantKey: 'type' as DiscriminantKey,
nullaryConstructorsMode: thunk as NullaryConstructorsMode_Thunk,
}
// tslint:disable ter-func-call-spacing
return mkTaggedUnionCustom<TypeURI>()<
T,
DiscriminantKey,
NullaryConstructorsMode_Thunk
>(defaultConfig, memberTagsRecord)
// tslint:enable ter-func-call-spacing
// TODO: Add new `mkReducer` functionality
} | the_stack |
export = Openpay;
declare class Openpay {
/**
* Initializes the SDK in sandbox mode
* @param merchantId Your merchant ID
* @param privateKey Your private API key
* @param isProductionReady Optional environment mode flag, set to true to initialize the SDK in production mode. Default is false
*/
constructor(merchantId: string, privateKey: string, isProductionReady?: boolean);
/**
* Change the merchant ID in runtime
* @param merchantId Your merchant ID
*/
setMerchantId(merchantId: string): void;
/**
* Change the private key in runtime
* @param privateKey Your API private key
*/
setPrivateKey(privateKey: string): void;
/**
* Change the SDK environment mode in runtime
* @param isProductionReady Environment mode flag. Use true to indicate the SDK is running in production mode, use false for sandbox
*/
setProductionReady(isProductionReady: boolean): void;
/**
* Change the request timeout in runtime
* @param timeout The desired timeout in milliseconds for HTTP requests
*/
setTimeout(timeout: number): void;
groups: Openpay.SDK.Groups;
merchant: Openpay.SDK.Merchant;
charges: Openpay.SDK.Charges;
payouts: Openpay.SDK.Payouts;
fees: Openpay.SDK.Fees;
plans: Openpay.SDK.Plans;
cards: Openpay.SDK.Cards;
customers: Openpay.SDK.Customers;
webhooks: Openpay.SDK.Webhooks;
}
declare namespace Openpay {
namespace SDK {
interface Merchant {
get(callback: Callback<any>): void;
}
interface Charges {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
get(transactionId: string, callback: Callback<any>): void;
capture(transactionId: string, data: any, callback: Callback<any>): void;
refund(transactionId: string, data: any, callback: Callback<any>): void;
}
interface Payouts {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
get(transactionId: string, callback: Callback<any>): void;
}
interface Fees {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
}
interface Customers {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
get(customerId: string, callback: Callback<any>): void;
update(customerId: string, callback: Callback<any>): void;
delete(customerId: string, callback: Callback<any>): void;
charges: Customers.Charges;
transfers: Customers.Transfers;
payouts: Customers.Payouts;
subscriptions: Customers.Subscriptions;
cards: Customers.Cards;
bankaccounts: Customers.BankAccounts;
}
namespace Customers {
interface Charges {
create(customerId: string, data: any, callback: Callback<any>): void;
list(customerId: string, data: any, callback: Callback<any>): void;
get(customerId: string, transactionId: string, callback: Callback<any>): void;
capture(customerId: string, transactionId: string, callback: Callback<any>): void;
refund(customerId: string, transactionId: string, data: any, callback: Callback<any>): void;
}
interface Transfers {
create(customerId: string, data: any, callback: Callback<any>): void;
list(customerId: string, data: any, callback: Callback<any>): void;
get(customerId: string, transactionId: string, callback: Callback<any>): void;
}
interface Payouts {
create(customerId: string, data: any, callback: Callback<any>): void;
list(customerId: string, data: any, callback: Callback<any>): void;
get(customerId: string, transactionId: string, callback: Callback<any>): void;
}
interface Subscriptions {
create(customerId: string, data: any, callback: Callback<any>): void;
list(customerId: string, data: any, callback: Callback<any>): void;
get(customerId: string, subscriptionId: string, callback: Callback<any>): void;
update(customerId: string, subscriptionId: string, data: any, callback: Callback<any>): void;
delete(customerId: string, subscriptionId: string, callback: Callback<any>): void;
}
interface Cards {
create(customerId: string, data: any, callback: Callback<any>): void;
list(customerId: string, data: any, callback: Callback<any>): void;
get(customerId: string, cardId: string, callback: Callback<any>): void;
delete(customerId: string, cardId: string, callback: Callback<any>): void;
}
interface BankAccounts {
create(customerId: string, data: any, callback: Callback<any>): void;
list(customerId: string, data: any, callback: Callback<any>): void;
get(customerId: string, bankId: string, callback: Callback<any>): void;
delete(customerId: string, bankId: string, callback: Callback<any>): void;
}
}
interface Cards {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
get(cardId: string, callback: Callback<any>): void;
delete(cardId: string, callback: Callback<any>): void;
}
interface Plans {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
get(planId: string, callback: Callback<any>): void;
update(planId: string, data: any, callback: Callback<any>): void;
delete(planId: string, callback: Callback<any>): void;
listSubscriptions(planId: string, data: any, callback: Callback<any>): void;
}
interface Webhooks {
create(data: any, callback: Callback<any>): void;
verify(webhook_id: string, verification_code: string, callback: Callback<any>): void;
get(webhook_id: string, callback: Callback<any>): void;
delete(webhook_id: string, callback: Callback<any>): void;
list(callback: Callback<any>): void;
}
interface Groups {
charges: Groups.Charges;
customers: Groups.Customers;
}
namespace Groups {
interface Charges {
create(merchantId: string, data: any, callback: Callback<any>): void;
capture(merchantId: string, transactionId: string, data: any, callback: Callback<any>): void;
refund(merchantId: string, transactionId: string, data: any, callback: Callback<any>): void;
}
interface Customers {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
get(customerId: string, callback: Callback<any>): void;
update(customerId: string, data: any, callback: Callback<any>): void;
delete(customerId: string, callback: Callback<any>): void;
cards: Customers.Cards;
charges: Customers.Charges;
subscriptions: Customers.Subscriptions;
}
namespace Customers {
interface Cards {
create(customerId: string, data: any, callback: Callback<any>): void;
list(customerId: string, data: any, callback: Callback<any>): void;
get(customerId: string, cardId: string, callback: Callback<any>): void;
delete(customerId: string, cardId: string, callback: Callback<any>): void;
}
interface Charges {
create(merchantId: string, customerId: string, data: any, callback: Callback<any>): void;
capture(merchantId: string, customerId: string, transactionId: string, data: any, callback: Callback<any>): void;
refund(merchantId: string, customerId: string, transactionId: string, data: any, callback: Callback<any>): void;
}
interface Subscriptions {
create(merchantId: string, customerId: string, data: any, callback: Callback<any>): void;
list(merchantId: string, customerId: string, data: any, callback: Callback<any>): void;
get(merchantId: string, customerId: string, subscriptionId: string, callback: Callback<any>): void;
update(merchantId: string, customerId: string, subscriptionId: string, data: any, callback: Callback<any>): void;
delete(merchantId: string, customerId: string, subscriptionId: string, callback: Callback<any>): void;
}
}
}
interface Charges {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
get(transactionId: string, callback: Callback<any>): void;
capture(transactionId: string, callback: Callback<any>): void;
refund(transactionId: string, data: any, callback: Callback<any>): void;
}
interface Transfers {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
get(transactionId: string, callback: Callback<any>): void;
}
interface Payouts {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
get(transactionId: string, callback: Callback<any>): void;
}
interface BankAccounts {
create(data: any, callback: Callback<any>): void;
list(data: any, callback: Callback<any>): void;
get(bankId: string, callback: Callback<any>): void;
delete(bankId: string, callback: Callback<any>): void;
}
}
interface Callback<T> {
(error: ErrorResponse|null, body: T): void;
}
interface ErrorResponse {
category: string;
error_code: ResponseError|number;
description: string;
http_code: string;
request_id: string;
fraud_rules: string[];
}
enum ResponseError {
OpenpayInternalError = 1000,
BadRequest = 1001,
Unauthorized = 1002,
UnprocessableEntity = 1003,
ServiceUnavailable = 1004,
NotFound = 1005,
Conflict = 1006,
RejectedTransaction = 1007,
DisabledAccount = 1008,
RequestEntityTooLarge = 1009,
Forbidden = 1010,
BankAccountConflict = 2001,
CardConflict = 2002,
CustomerExternalIdConflict = 2003,
InvalidCardVerifyingCode = 2004,
CardExpiredOnSave = 2005,
MissingCardSecurityCode = 2006,
SandboxCard = 2007,
CardPointsUnavailable = 2008,
InvalidCardSecurityCode = 2009,
DeclinedCard = 3001,
CardExpiredOnCharge = 3002,
InsufficientCardFunds = 3003,
StolenCard = 3004,
FraudulentCard = 3005,
ForbiddenOperation = 3006,
UnsupportedCard = 3008,
LostCard = 3009,
RestrictedCard = 3010,
RetainedCard = 3011,
BankAuthorizationRequired = 3012,
InsufficientAccountFunds = 4001
}
} | the_stack |
import * as capnp from "capnp-ts";
import * as s from "capnp-ts/src/std/schema.capnp.js";
import { format } from "capnp-ts/src/util";
import initTrace from "debug";
import ts from "typescript";
import {
createClassExtends,
createConcreteListProperty,
createConstProperty,
createMethod,
createNestedNodeProperty,
createUnionConstProperty,
createValueExpression,
} from "./ast-creators";
import { CodeGeneratorFileContext } from "./code-generator-file-context";
import {
__,
BOOLEAN_TYPE,
CAPNP,
ConcreteListType,
EXPORT,
LENGTH,
NUMBER_TYPE,
Primitive,
READONLY,
STATIC,
STRING_TYPE,
STRUCT,
THIS,
TS_FILE_ID,
VALUE,
VOID_TYPE,
OBJECT_SIZE,
} from "./constants";
import * as E from "./errors";
import {
compareCodeOrder,
getConcreteListType,
getDisplayNamePrefix,
getFullClassName,
getJsType,
getUnnamedUnionFields,
hasNode,
lookupNode,
needsConcreteListClass,
} from "./file";
import * as util from "./util";
const trace = initTrace("capnpc:generators");
trace("load");
export function generateCapnpImport(ctx: CodeGeneratorFileContext): void {
// Look for the special importPath annotation on the file to see if we need a different import path for capnp-ts.
const fileNode = lookupNode(ctx, ctx.file);
const tsFileId = capnp.Uint64.fromHexString(TS_FILE_ID);
// This may be undefined if ts.capnp is not imported; fine, we'll just use the default.
const tsAnnotationFile = ctx.nodes.find((n) => n.getId().equals(tsFileId));
// We might not find the importPath annotation; that's definitely a bug but let's move on.
const tsImportPathAnnotation =
tsAnnotationFile && tsAnnotationFile.getNestedNodes().find((n) => n.getName() === "importPath");
// There may not necessarily be an import path annotation on the file node. That's fine.
const importAnnotation =
tsImportPathAnnotation && fileNode.getAnnotations().find((a) => a.getId().equals(tsImportPathAnnotation.getId()));
const importPath = importAnnotation === undefined ? "capnp-ts" : importAnnotation.getValue().getText();
let u: ts.Identifier | undefined;
// import * as capnp from '${importPath}';
ctx.statements.push(
ts.createImportDeclaration(
__,
__,
ts.createImportClause(u as ts.Identifier, ts.createNamespaceImport(CAPNP)),
ts.createLiteral(importPath)
)
);
// import { ObjectSize as __O, Struct as __S } from '${importPath}';
ctx.statements.push(
ts.createStatement(ts.createIdentifier(`import { ObjectSize as __O, Struct as __S } from '${importPath}'`))
);
}
export function generateNestedImports(ctx: CodeGeneratorFileContext): void {
ctx.imports.forEach((i) => {
const name = i.getName();
let importPath: string;
if (name.substr(0, 7) === "/capnp/") {
importPath = `capnp-ts/src/std/${name.substr(7)}.js`;
} else {
importPath = name[0] === "." ? `${name}.js` : `./${name}.js`;
}
const imports = getImportNodes(ctx, lookupNode(ctx, i)).map(getFullClassName).join(", ");
if (imports.length < 1) return;
const importStatement = `import { ${imports} } from "${importPath}"`;
trace("emitting import statement:", importStatement);
ctx.statements.push(ts.createStatement(ts.createIdentifier(importStatement)));
});
}
export function generateConcreteListInitializer(
ctx: CodeGeneratorFileContext,
fullClassName: string,
field: s.Field
): void {
const left = ts.createPropertyAccess(ts.createIdentifier(fullClassName), `_${util.c2t(field.getName())}`);
const right = ts.createIdentifier(getConcreteListType(ctx, field.getSlot().getType()));
ctx.statements.push(ts.createStatement(ts.createAssignment(left, right)));
}
export function generateDefaultValue(field: s.Field): ts.PropertyAssignment {
const name = field.getName();
const slot = field.getSlot();
const whichSlotType = slot.getType().which();
const p = Primitive[whichSlotType];
let initializer;
switch (whichSlotType) {
case s.Type_Which.ANY_POINTER:
case s.Type_Which.DATA:
case s.Type_Which.LIST:
case s.Type_Which.STRUCT:
initializer = createValueExpression(slot.getDefaultValue());
break;
case s.Type_Which.TEXT:
initializer = ts.createLiteral(slot.getDefaultValue().getText());
break;
case s.Type_Which.BOOL:
initializer = ts.createCall(ts.createPropertyAccess(CAPNP, p.mask), __, [
createValueExpression(slot.getDefaultValue()),
ts.createNumericLiteral((slot.getOffset() % 8).toString()),
]);
break;
case s.Type_Which.ENUM:
case s.Type_Which.FLOAT32:
case s.Type_Which.FLOAT64:
case s.Type_Which.INT16:
case s.Type_Which.INT32:
case s.Type_Which.INT64:
case s.Type_Which.INT8:
case s.Type_Which.UINT16:
case s.Type_Which.UINT32:
case s.Type_Which.UINT64:
case s.Type_Which.UINT8:
initializer = ts.createCall(ts.createPropertyAccess(CAPNP, p.mask), __, [
createValueExpression(slot.getDefaultValue()),
]);
break;
default:
throw new Error(format(E.GEN_UNKNOWN_DEFAULT, s.Type_Which[whichSlotType]));
}
return ts.createPropertyAssignment(`default${util.c2t(name)}`, initializer);
}
export function generateEnumNode(ctx: CodeGeneratorFileContext, node: s.Node): void {
trace("generateEnumNode(%s) [%s]", node, node.getDisplayName());
const members = node
.getEnum()
.getEnumerants()
.toArray()
.sort(compareCodeOrder)
.map((e) => ts.createEnumMember(util.c2s(e.getName())));
const d = ts.createEnumDeclaration(__, [EXPORT], getFullClassName(node), members);
ctx.statements.push(d);
}
export function generateFileId(ctx: CodeGeneratorFileContext): void {
trace("generateFileId()");
// export const _capnpFileId = 'abcdef';
const fileId = ts.createLiteral(ctx.file.getId().toHexString());
ctx.statements.push(
ts.createVariableStatement(
[EXPORT],
ts.createVariableDeclarationList([ts.createVariableDeclaration("_capnpFileId", __, fileId)], ts.NodeFlags.Const)
)
);
}
export function generateInterfaceClasses(_ctx: CodeGeneratorFileContext, node: s.Node): void {
trace("Interface generation is not yet implemented.");
/* tslint:disable-next-line */
console.error(`CAPNP-TS: Warning! Interface generation (${node.getDisplayName()}) is not yet implemented.`);
}
export function generateNode(ctx: CodeGeneratorFileContext, node: s.Node): void {
trace("generateNode(%s, %s)", ctx, node.getId().toHexString());
const nodeId = node.getId();
const nodeIdHex = nodeId.toHexString();
if (ctx.generatedNodeIds.indexOf(nodeIdHex) > -1) return;
ctx.generatedNodeIds.push(nodeIdHex);
/** An array of group structs formed as children of this struct. They appear before the struct node in the file. */
const groupNodes = ctx.nodes.filter(
(n) => n.getScopeId().equals(nodeId) && n.isStruct() && n.getStruct().getIsGroup()
);
/**
* An array of nodes that are nested within this node; these must appear first since those symbols will be
* refernced in the node's class definition.
*/
const nestedNodes = node.getNestedNodes().map((n) => lookupNode(ctx, n));
nestedNodes.forEach((n) => generateNode(ctx, n));
groupNodes.forEach((n) => generateNode(ctx, n));
const whichNode = node.which();
switch (whichNode) {
case s.Node.STRUCT:
generateStructNode(ctx, node, false);
break;
case s.Node.CONST:
// Const nodes are generated along with the containing class, ignore these.
break;
case s.Node.ENUM:
generateEnumNode(ctx, node);
break;
case s.Node.INTERFACE:
generateStructNode(ctx, node, true);
break;
case s.Node.ANNOTATION:
trace("ignoring unsupported annotation node: %s", node.getDisplayName());
break;
case s.Node.FILE:
default:
throw new Error(format(E.GEN_NODE_UNKNOWN_TYPE, s.Node_Which[whichNode]));
}
}
const listLengthParameterName = "length";
export function generateStructFieldMethods(
ctx: CodeGeneratorFileContext,
members: ts.ClassElement[],
node: s.Node,
field: s.Field
): void {
let jsType: string;
let whichType: s.Type_Which | string;
if (field.isSlot()) {
const slotType = field.getSlot().getType();
jsType = getJsType(ctx, slotType, false);
whichType = slotType.which();
} else if (field.isGroup()) {
jsType = getFullClassName(lookupNode(ctx, field.getGroup().getTypeId()));
whichType = "group";
} else {
throw new Error(format(E.GEN_UNKNOWN_STRUCT_FIELD, field.which()));
}
const jsTypeReference = ts.createTypeReferenceNode(jsType, __);
const discriminantOffset = node.getStruct().getDiscriminantOffset();
const name = field.getName();
const properName = util.c2t(name);
const hadExplicitDefault = field.isSlot() && field.getSlot().getHadExplicitDefault();
const discriminantValue = field.getDiscriminantValue();
const fullClassName = getFullClassName(node);
const union = discriminantValue !== s.Field.NO_DISCRIMINANT;
const offset = (field.isSlot() && field.getSlot().getOffset()) || 0;
const offsetLiteral = ts.createNumericLiteral(offset.toString());
/** __S.getPointer(0, this) */
const getPointer = ts.createCall(ts.createPropertyAccess(STRUCT, "getPointer"), __, [offsetLiteral, THIS]);
/** __S.copyFrom(value, __S.getPointer(0, this)) */
const copyFromValue = ts.createCall(ts.createPropertyAccess(STRUCT, "copyFrom"), __, [VALUE, getPointer]);
/** capnp.Orphan<Foo> */
const orphanType = ts.createTypeReferenceNode("capnp.Orphan", [jsTypeReference]);
const discriminantOffsetLiteral = ts.createNumericLiteral((discriminantOffset * 2).toString());
const discriminantValueLiteral = ts.createNumericLiteral(discriminantValue.toString());
/** __S.getUint16(0, this) */
const getDiscriminant = ts.createCall(ts.createPropertyAccess(STRUCT, "getUint16"), __, [
discriminantOffsetLiteral,
THIS,
]);
/** __S.setUint16(0, this) */
const setDiscriminant = ts.createCall(ts.createPropertyAccess(STRUCT, "setUint16"), __, [
discriminantOffsetLiteral,
discriminantValueLiteral,
THIS,
]);
const defaultValue = hadExplicitDefault
? ts.createIdentifier(`${fullClassName}._capnp.default${properName}`)
: undefined;
let adopt = false;
let disown = false;
let init;
let has = false;
let get;
let set;
let getArgs: ts.Expression[];
switch (whichType) {
case s.Type.ANY_POINTER:
getArgs = [offsetLiteral, THIS];
if (defaultValue) getArgs.push(defaultValue);
adopt = true;
disown = true;
/** __S.getPointer(0, this) */
get = ts.createCall(ts.createPropertyAccess(STRUCT, "getPointer"), __, getArgs);
has = true;
/** __S.copyFrom(value, __S.getPointer(0, this)) */
set = ts.createCall(ts.createPropertyAccess(STRUCT, "copyFrom"), __, [VALUE, get]);
break;
case s.Type.BOOL:
case s.Type.ENUM:
case s.Type.FLOAT32:
case s.Type.FLOAT64:
case s.Type.INT16:
case s.Type.INT32:
case s.Type.INT64:
case s.Type.INT8:
case s.Type.UINT16:
case s.Type.UINT32:
case s.Type.UINT64:
case s.Type.UINT8: {
const { byteLength, getter, setter } = Primitive[whichType as number];
// NOTE: For a BOOL type this is actually a bit offset; `byteLength` will be `1` in that case.
const byteOffset = ts.createNumericLiteral((offset * byteLength).toString());
getArgs = [byteOffset, THIS];
if (defaultValue) getArgs.push(defaultValue);
/** __S.getXYZ(0, this) */
get = ts.createCall(ts.createPropertyAccess(STRUCT, getter), __, getArgs);
/** __S.setXYZ(0, value, this) */
set = ts.createCall(ts.createPropertyAccess(STRUCT, setter), __, [byteOffset, VALUE, THIS]);
break;
}
case s.Type.DATA:
getArgs = [offsetLiteral, THIS];
if (defaultValue) getArgs.push(defaultValue);
adopt = true;
disown = true;
/** __S.getData(0, this) */
get = ts.createCall(ts.createPropertyAccess(STRUCT, "getData"), __, getArgs);
has = true;
/** __S.initData(0, length, this) */
init = ts.createCall(ts.createPropertyAccess(STRUCT, "initData"), __, [offsetLiteral, LENGTH, THIS]);
set = copyFromValue;
break;
case s.Type.INTERFACE:
if (hadExplicitDefault) {
throw new Error(format(E.GEN_EXPLICIT_DEFAULT_NON_PRIMITIVE, "INTERFACE"));
}
/** __S.getPointerAs(0, Foo, this) */
get = ts.createCall(ts.createPropertyAccess(STRUCT, "getPointerAs"), __, [
offsetLiteral,
ts.createIdentifier(jsType),
THIS,
]);
set = copyFromValue;
break;
case s.Type.LIST: {
const whichElementType = field.getSlot().getType().getList().getElementType().which();
let listClass = ConcreteListType[whichElementType];
if (whichElementType === s.Type.LIST || whichElementType === s.Type.STRUCT) {
listClass = `${fullClassName}._${properName}`;
} else if (listClass === void 0) {
/* istanbul ignore next */
throw new Error(format(E.GEN_UNSUPPORTED_LIST_ELEMENT_TYPE, whichElementType));
}
const listClassIdentifier = ts.createIdentifier(listClass);
getArgs = [offsetLiteral, listClassIdentifier, THIS];
if (defaultValue) getArgs.push(defaultValue);
adopt = true;
disown = true;
/** __S.getList(0, MyStruct._Foo, this) */
get = ts.createCall(ts.createPropertyAccess(STRUCT, "getList"), __, getArgs);
has = true;
/** __S.initList(0, MyStruct._Foo, length, this) */
init = ts.createCall(ts.createPropertyAccess(STRUCT, "initList"), __, [
offsetLiteral,
listClassIdentifier,
ts.createIdentifier(listLengthParameterName),
THIS,
]);
set = copyFromValue;
break;
}
case s.Type.STRUCT: {
const structType = ts.createIdentifier(getJsType(ctx, field.getSlot().getType(), false));
getArgs = [offsetLiteral, structType, THIS];
if (defaultValue) getArgs.push(defaultValue);
adopt = true;
disown = true;
/** __S.getStruct(0, Foo, this) */
get = ts.createCall(ts.createPropertyAccess(STRUCT, "getStruct"), __, getArgs);
has = true;
/** __S.initStruct(0, Foo, this) */
init = ts.createCall(ts.createPropertyAccess(STRUCT, "initStructAt"), __, [offsetLiteral, structType, THIS]);
set = copyFromValue;
break;
}
case s.Type.TEXT:
getArgs = [offsetLiteral, THIS];
if (defaultValue) getArgs.push(defaultValue);
/** __S.getText(0, this) */
get = ts.createCall(ts.createPropertyAccess(STRUCT, "getText"), __, getArgs);
/** __S.setText(0, value, this) */
set = ts.createCall(ts.createPropertyAccess(STRUCT, "setText"), __, [offsetLiteral, VALUE, THIS]);
break;
case s.Type.VOID:
break;
case "group": {
if (hadExplicitDefault) {
throw new Error(format(E.GEN_EXPLICIT_DEFAULT_NON_PRIMITIVE, "group"));
}
const groupType = ts.createIdentifier(jsType);
/** __S.getAs(Foo, this); */
get = ts.createCall(ts.createPropertyAccess(STRUCT, "getAs"), __, [groupType, THIS]);
init = get;
break;
}
default:
// TODO Maybe this should be an error?
break;
}
// adoptFoo(value: capnp.Orphan<Foo>): void { __S.adopt(value, this._getPointer(3)); }}
if (adopt) {
const parameters = [ts.createParameter(__, __, __, VALUE, __, orphanType, __)];
const expressions = [ts.createCall(ts.createPropertyAccess(STRUCT, "adopt"), __, [VALUE, getPointer])];
if (union) expressions.unshift(setDiscriminant);
members.push(createMethod(`adopt${properName}`, parameters, VOID_TYPE, expressions));
}
// disownFoo(): capnp.Orphan<Foo> { return __S.disown(this.getFoo()); }
if (disown) {
const getter = ts.createCall(ts.createPropertyAccess(THIS, `get${properName}`), __, []);
const expressions = [ts.createCall(ts.createPropertyAccess(STRUCT, "disown"), __, [getter])];
members.push(createMethod(`disown${properName}`, [], orphanType, expressions));
}
// getFoo(): FooType { ... }
if (get) {
const expressions = [get];
if (union) {
expressions.unshift(
ts.createCall(ts.createPropertyAccess(STRUCT, "testWhich"), __, [
ts.createLiteral(name),
getDiscriminant,
discriminantValueLiteral,
THIS,
])
);
}
members.push(createMethod(`get${properName}`, [], jsTypeReference, expressions));
}
// hasFoo(): boolean { ... }
if (has) {
// !__S.isNull(this._getPointer(8));
const expressions = [
ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(STRUCT, "isNull"), __, [getPointer])),
];
members.push(createMethod(`has${properName}`, [], BOOLEAN_TYPE, expressions));
}
// initFoo(): FooType { ... } / initFoo(length: number): capnp.List<FooElementType> { ... }
if (init) {
const parameters =
whichType === s.Type.DATA || whichType === s.Type.LIST
? [ts.createParameter(__, __, __, listLengthParameterName, __, NUMBER_TYPE, __)]
: [];
const expressions = [init];
if (union) expressions.unshift(setDiscriminant);
members.push(createMethod(`init${properName}`, parameters, jsTypeReference, expressions));
}
// isFoo(): boolean { ... }
if (union) {
const left = ts.createCall(ts.createPropertyAccess(STRUCT, "getUint16"), __, [discriminantOffsetLiteral, THIS]);
const right = discriminantValueLiteral;
const expressions = [ts.createBinary(left, ts.SyntaxKind.EqualsEqualsEqualsToken, right)];
members.push(createMethod(`is${properName}`, [], BOOLEAN_TYPE, expressions));
}
// setFoo(value: FooType): void { ... }
if (set || union) {
const expressions = [];
const parameters = [];
if (set) {
expressions.unshift(set);
parameters.unshift(ts.createParameter(__, __, __, VALUE, __, jsTypeReference, __));
}
if (union) {
expressions.unshift(setDiscriminant);
}
members.push(createMethod(`set${properName}`, parameters, VOID_TYPE, expressions));
}
}
export function generateStructNode(ctx: CodeGeneratorFileContext, node: s.Node, interfaceNode: boolean): void {
trace("generateStructNode(%s) [%s]", node, node.getDisplayName());
const displayNamePrefix = getDisplayNamePrefix(node);
const fullClassName = getFullClassName(node);
const nestedNodes = node
.getNestedNodes()
.map((n) => lookupNode(ctx, n))
.filter((n) => !n.isConst() && !n.isAnnotation());
const nodeId = node.getId();
const nodeIdHex = nodeId.toHexString();
const struct = node.which() === s.Node.STRUCT ? node.getStruct() : undefined;
const unionFields = getUnnamedUnionFields(node).sort(compareCodeOrder);
const dataWordCount = struct ? struct.getDataWordCount() : 0;
const dataByteLength = struct ? dataWordCount * 8 : 0;
const discriminantCount = struct ? struct.getDiscriminantCount() : 0;
const discriminantOffset = struct ? struct.getDiscriminantOffset() : 0;
const fields = struct ? struct.getFields().toArray().sort(compareCodeOrder) : [];
const pointerCount = struct ? struct.getPointerCount() : 0;
const concreteLists = fields.filter(needsConcreteListClass).sort(compareCodeOrder);
const consts = ctx.nodes.filter((n) => n.getScopeId().equals(nodeId) && n.isConst());
// const groups = ctx.nodes.filter(
// (n) => n.getScopeId().equals(nodeId) && n.isStruct() && n.getStruct().getIsGroup());
const hasUnnamedUnion = discriminantCount !== 0;
if (hasUnnamedUnion) {
generateUnnamedUnionEnum(ctx, fullClassName, unionFields);
}
const members: ts.ClassElement[] = [];
// static readonly CONSTANT = 'foo';
members.push(...consts.map(createConstProperty));
// static readonly WHICH = MyStruct_Which.WHICH;
members.push(...unionFields.map((f) => createUnionConstProperty(fullClassName, f)));
// static readonly NestedStruct = MyStruct_NestedStruct;
members.push(...nestedNodes.map(createNestedNodeProperty));
// static readonly Client = MyInterface_Client;
// static readonly Server = MyInterface_Server;
// if (interfaceNode) {
// members.push(
// ts.createProperty(__, [STATIC, READONLY], 'Client', __, __, ts.createLiteral(`${fullClassName}_Client`)));
// members.push(
// ts.createProperty(__, [STATIC, READONLY], 'Server', __, __, ts.createLiteral(`${fullClassName}_Server`)));
// }
const defaultValues = fields.reduce(
(acc, f) =>
f.isSlot() && f.getSlot().getHadExplicitDefault() && f.getSlot().getType().which() !== s.Type.VOID
? acc.concat(generateDefaultValue(f))
: acc,
[] as ts.PropertyAssignment[]
);
// static reaodnly _capnp = { displayName: 'MyStruct', id: '4732bab4310f81', size = new __O(8, 8) };
members.push(
ts.createProperty(
__,
[STATIC, READONLY],
"_capnp",
__,
__,
ts.createObjectLiteral(
[
ts.createPropertyAssignment("displayName", ts.createLiteral(displayNamePrefix)),
ts.createPropertyAssignment("id", ts.createLiteral(nodeIdHex)),
ts.createPropertyAssignment(
"size",
ts.createNew(OBJECT_SIZE, __, [
ts.createNumericLiteral(dataByteLength.toString()),
ts.createNumericLiteral(pointerCount.toString()),
])
),
].concat(defaultValues)
)
)
);
// private static _ConcreteListClass: MyStruct_ConcreteListClass;
members.push(...concreteLists.map((f) => createConcreteListProperty(ctx, f)));
// getFoo() { ... } initFoo() { ... } setFoo() { ... }
fields.forEach((f) => generateStructFieldMethods(ctx, members, node, f));
// toString(): string { return 'MyStruct_' + super.toString(); }
const toStringExpression = ts.createBinary(
ts.createLiteral(`${fullClassName}_`),
ts.SyntaxKind.PlusToken,
ts.createCall(ts.createIdentifier("super.toString"), __, [])
);
members.push(createMethod("toString", [], STRING_TYPE, [toStringExpression], true));
if (hasUnnamedUnion) {
// which(): MyStruct_Which { return __S.getUint16(12, this); }
const whichExpression = ts.createCall(ts.createPropertyAccess(STRUCT, "getUint16"), __, [
ts.createNumericLiteral((discriminantOffset * 2).toString()),
THIS,
]);
members.push(
createMethod("which", [], ts.createTypeReferenceNode(`${fullClassName}_Which`, __), [whichExpression], true)
);
}
const c = ts.createClassDeclaration(__, [EXPORT], fullClassName, __, [createClassExtends("__S")], members);
// Make sure the interface classes are generated first.
if (interfaceNode) {
generateInterfaceClasses(ctx, node);
}
ctx.statements.push(c);
// Write out the concrete list type initializer after all the class definitions. It can't be initialized within the
// class's static initializer because the nested type might not be defined yet.
// FIXME: This might be solvable with topological sorting?
ctx.concreteLists.push(...concreteLists.map<[string, s.Field]>((f) => [fullClassName, f]));
}
export function generateUnnamedUnionEnum(
ctx: CodeGeneratorFileContext,
fullClassName: string,
unionFields: s.Field[]
): void {
const members = unionFields
.sort(compareCodeOrder)
.map((f) =>
ts.createEnumMember(util.c2s(f.getName()), ts.createNumericLiteral(f.getDiscriminantValue().toString()))
);
const d = ts.createEnumDeclaration(__, [EXPORT], `${fullClassName}_Which`, members);
ctx.statements.push(d);
}
export function getImportNodes(ctx: CodeGeneratorFileContext, node: s.Node): s.Node[] {
return lookupNode(ctx, node)
.getNestedNodes()
.filter((n) => hasNode(ctx, n))
.map((n) => lookupNode(ctx, n))
.reduce((a, n) => a.concat([n], getImportNodes(ctx, n)), new Array<s.Node>())
.filter((n) => lookupNode(ctx, n).isStruct() || lookupNode(ctx, n).isEnum());
} | the_stack |
import * as JVMTypes from '../../includes/JVMTypes';
import * as Doppio from '../doppiojvm';
import JVMThread = Doppio.VM.Threading.JVMThread;
import ReferenceClassData = Doppio.VM.ClassFile.ReferenceClassData;
import ArrayClassData = Doppio.VM.ClassFile.ArrayClassData;
import ClassData = Doppio.VM.ClassFile.ClassData;
import IJVMConstructor = Doppio.VM.ClassFile.IJVMConstructor;
import logging = Doppio.Debug.Logging;
import util = Doppio.VM.Util;
import Long = Doppio.VM.Long;
import ThreadStatus = Doppio.VM.Enums.ThreadStatus;
import ClassLoader = Doppio.VM.ClassFile.ClassLoader;
import CustomClassLoader = Doppio.VM.ClassFile.CustomClassLoader;
import assert = Doppio.Debug.Assert;
export default function (): any {
function getFieldInfo(thread: JVMThread, unsafe: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long): [any, string] {
var fieldName: string, objBase: any, objCls = obj.getClass(), cls: ReferenceClassData<JVMTypes.java_lang_Object>, compName: string,
unsafeCons: typeof JVMTypes.sun_misc_Unsafe = <any> (<ReferenceClassData<JVMTypes.sun_misc_Unsafe>> unsafe.getClass()).getConstructor(thread),
stride = 1;
if (objCls.getInternalName() === "Ljava/lang/Object;") {
// Static field. The staticFieldBase is always a pure Object that has a
// class reference on it.
// There's no reason to get the field on an Object, as they have no fields.
cls = <ReferenceClassData<JVMTypes.java_lang_Object>> (<any> obj).$staticFieldBase;
objBase = <any> cls.getConstructor(thread);
fieldName = cls.getStaticFieldFromVMIndex(offset.toInt()).fullName;
} else if (objCls instanceof ArrayClassData) {
compName = util.internal2external[objCls.getInternalName()[1]];
if (!compName) {
compName = "OBJECT";
}
compName = compName.toUpperCase();
stride = (<any> unsafeCons)[`sun/misc/Unsafe/ARRAY_${compName}_INDEX_SCALE`];
if (!stride) {
stride = 1;
}
objBase = (<JVMTypes.JVMArray<any>> obj).array;
assert(offset.toInt() % stride === 0, `Invalid offset for stride ${stride}: ${offset.toInt()}`);
fieldName = "" + (offset.toInt() / stride);
} else {
cls = <ReferenceClassData<JVMTypes.java_lang_Object>> obj.getClass();
objBase = obj;
fieldName = cls.getObjectFieldFromVMIndex(offset.toInt()).fullName;
}
return [objBase, fieldName];
}
function unsafeCompareAndSwap<T>(thread: JVMThread, unsafe: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, expected: T, x: T): boolean {
var fi = getFieldInfo(thread, unsafe, obj, offset),
actual = fi[0][fi[1]];
if (actual === expected) {
fi[0][fi[1]] = x;
return true;
} else {
return false;
}
}
function getFromVMIndex<T>(thread: JVMThread, unsafe: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long): T {
var fi = getFieldInfo(thread, unsafe, obj, offset);
return fi[0][fi[1]];
}
function setFromVMIndex<T>(thread: JVMThread, unsafe: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, val: T): void {
var fi = getFieldInfo(thread, unsafe, obj, offset);
fi[0][fi[1]] = val;
}
class sun_misc_GC {
public static 'maxObjectInspectionAge()J'(thread: JVMThread): Long {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
}
class sun_misc_MessageUtils {
public static 'toStderr(Ljava/lang/String;)V'(thread: JVMThread, str: JVMTypes.java_lang_String): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'toStdout(Ljava/lang/String;)V'(thread: JVMThread, str: JVMTypes.java_lang_String): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
}
class sun_misc_NativeSignalHandler {
public static 'handle0(IJ)V'(thread: JVMThread, arg0: number, arg1: Long): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
}
class sun_misc_Perf {
public static 'attach(Ljava/lang/String;II)Ljava/nio/ByteBuffer;'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Perf, arg0: JVMTypes.java_lang_String, arg1: number, arg2: number): JVMTypes.java_nio_ByteBuffer {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'detach(Ljava/nio/ByteBuffer;)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Perf, arg0: JVMTypes.java_nio_ByteBuffer): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'createLong(Ljava/lang/String;IIJ)Ljava/nio/ByteBuffer;'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Perf, name: JVMTypes.java_lang_String, variability: number, units: number, value: Long): void {
thread.import('Ljava/nio/DirectByteBuffer;', (buffCons: IJVMConstructor<JVMTypes.java_nio_DirectByteBuffer>) => {
var buff = new buffCons(thread),
heap = thread.getJVM().getHeap(),
addr = heap.malloc(8);
buff['<init>(JI)V'](thread, [Long.fromNumber(addr), null, 8], (e?: JVMTypes.java_lang_Throwable) => {
if (e) {
thread.throwException(e);
} else {
heap.store_word(addr, value.getLowBits());
heap.store_word(addr + 4, value.getHighBits());
thread.asyncReturn(buff);
}
});
});
}
public static 'createByteArray(Ljava/lang/String;II[BI)Ljava/nio/ByteBuffer;'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Perf, arg0: JVMTypes.java_lang_String, arg1: number, arg2: number, arg3: JVMTypes.JVMArray<number>, arg4: number): JVMTypes.java_nio_ByteBuffer {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'highResCounter()J'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Perf): Long {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'highResFrequency()J'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Perf): Long {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'registerNatives()V'(thread: JVMThread): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
}
class sun_misc_Signal {
public static 'findSignal(Ljava/lang/String;)I'(thread: JVMThread, arg0: JVMTypes.java_lang_String): number {
// Signifies that we don't know the signal.
return -1;
}
public static 'handle0(IJ)J'(thread: JVMThread, arg0: number, arg1: Long): Long {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'raise0(I)V'(thread: JVMThread, arg0: number): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
}
class sun_misc_Unsafe {
public static 'getInt(Ljava/lang/Object;J)I': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putInt(Ljava/lang/Object;JI)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getObject(Ljava/lang/Object;J)Ljava/lang/Object;': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => JVMTypes.java_lang_Object = getFromVMIndex;
public static 'putObject(Ljava/lang/Object;JLjava/lang/Object;)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, new_obj: JVMTypes.java_lang_Object) => void = setFromVMIndex;
public static 'getBoolean(Ljava/lang/Object;J)Z': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putBoolean(Ljava/lang/Object;JZ)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getByte(Ljava/lang/Object;J)B': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putByte(Ljava/lang/Object;JB)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getShort(Ljava/lang/Object;J)S': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putShort(Ljava/lang/Object;JS)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getChar(Ljava/lang/Object;J)C': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putChar(Ljava/lang/Object;JC)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getLong(Ljava/lang/Object;J)J': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => Long = getFromVMIndex;
public static 'putLong(Ljava/lang/Object;JJ)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, x: Long) => void = setFromVMIndex;
public static 'getFloat(Ljava/lang/Object;J)F': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putFloat(Ljava/lang/Object;JF)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getDouble(Ljava/lang/Object;J)D': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putDouble(Ljava/lang/Object;JD)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getByte(J)B'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, address: Long): number {
var heap = thread.getJVM().getHeap();
return heap.get_signed_byte(address.toNumber());
}
public static 'putByte(JB)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, address: Long, val: number): void {
var heap = thread.getJVM().getHeap();
heap.set_signed_byte(address.toNumber(), val);
}
public static 'getShort(J)S'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
public static 'putShort(JS)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long, arg1: number): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'getChar(J)C'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
public static 'putChar(JC)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long, arg1: number): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'getInt(J)I'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
public static 'putInt(JI)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long, arg1: number): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'getLong(J)J'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, address: Long): Long {
var heap = thread.getJVM().getHeap(),
addr = address.toNumber();
return new Long(heap.get_word(addr), heap.get_word(addr + 4));
}
public static 'putLong(JJ)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, address: Long, value: Long): void {
var heap = thread.getJVM().getHeap(),
addr = address.toNumber();
// LE
heap.store_word(addr, value.getLowBits());
heap.store_word(addr + 4, value.getHighBits());
}
public static 'getFloat(J)F'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
public static 'putFloat(JF)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long, arg1: number): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'getDouble(J)D'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
public static 'putDouble(JD)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long, arg1: number): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'getAddress(J)J'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long): Long {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'putAddress(JJ)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long, arg1: Long): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'allocateMemory(J)J'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, size: Long): Long {
var heap = thread.getJVM().getHeap();
return Long.fromNumber(heap.malloc(size.toNumber()));
}
public static 'reallocateMemory(JJ)J'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: Long, arg1: Long): Long {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'setMemory(Ljava/lang/Object;JJB)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, address: Long, bytes: Long, value: number): void {
if (obj === null) {
// Address is absolute.
var i: number, addr = address.toNumber(),
bytesNum: number = bytes.toNumber(),
heap = thread.getJVM().getHeap();
for (i = 0; i < bytesNum; i++) {
heap.set_signed_byte(addr + i, value);
}
} else {
// I have no idea what the semantics are when the object is specified.
// I think it means use the object as the starting address... which doesn't
// make sense for us.
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
}
/**
* Sets all bytes in a given block of memory to a copy of another
* block.
*
* <p>This method determines each block's base address by means of two parameters,
* and so it provides (in effect) a <em>double-register</em> addressing mode,
* as discussed in {@link #getInt(Object,long)}. When the object reference is null,
* the offset supplies an absolute base address.
*
* <p>The transfers are in coherent (atomic) units of a size determined
* by the address and length parameters. If the effective addresses and
* length are all even modulo 8, the transfer takes place in 'long' units.
* If the effective addresses and length are (resp.) even modulo 4 or 2,
* the transfer takes place in units of 'int' or 'short'.
*
* @since 1.7
*/
public static 'copyMemory(Ljava/lang/Object;JLjava/lang/Object;JJ)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, srcBase: JVMTypes.java_lang_Object, srcOffset: Long, destBase: JVMTypes.java_lang_Object, destOffset: Long, bytes: Long): void {
const heap = thread.getJVM().getHeap(),
srcAddr = srcOffset.toNumber(),
destAddr = destOffset.toNumber(),
length = bytes.toNumber();
if (srcBase === null && destBase === null) {
// memcopy semantics w/ srcoffset/destoffset as absolute offsets.
heap.memcpy(srcAddr, destAddr, length);
} else if (srcBase === null && destBase !== null) {
// OK, so... destBase is an array, destOffset is a byte offset from the
// start of the array. Need to copy data from the heap directly into the array.
if (util.is_array_type(destBase.getClass().getInternalName()) && util.is_primitive_type((<ArrayClassData<any>> destBase.getClass()).getComponentClass().getInternalName())) {
const destArray: JVMTypes.JVMArray<any> = <any> destBase;
switch (destArray.getClass().getComponentClass().getInternalName()) {
case 'B':
for (let i = 0; i < length; i++) {
destArray.array[destAddr + i] = heap.get_signed_byte(srcAddr + i);
}
break;
/*case 'C':
break;
case 'D':
break;
case 'F':
break;
case 'I':
break;
case 'J':
break;
case 'S':
break;
case 'Z':
break;*/
default:
// I have no idea what the appropriate semantics are for this.
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented. destArray type: ' + destArray.getClass().getComponentClass().getInternalName());
break;
}
} else {
// I have no idea what the appropriate semantics are for this.
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
} else if (srcBase !== null && destBase === null) {
// srcBase is an array, destOffset is an address where the contents of srcBase should be copied.
if (util.is_array_type(srcBase.getClass().getInternalName()) && util.is_primitive_type((<ArrayClassData<any>> srcBase.getClass()).getComponentClass().getInternalName())) {
const srcArray: JVMTypes.JVMArray<any> = <any> srcBase;
switch (srcArray.getClass().getComponentClass().getInternalName()) {
case 'B':
case 'C':
for (let i = 0; i < length; i++) {
heap.set_signed_byte(destAddr + i, srcArray.array[srcAddr + i]);
}
break;
default:
// I have no idea what the appropriate semantics are for this.
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented. srcArray:' + srcArray.getClass().getComponentClass().getInternalName());
break;
}
} else {
// I have no idea what the appropriate semantics are for this.
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
} else {
// I have no idea what the appropriate semantics are for this.
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented. Both src and dest are arrays?');
}
}
public static 'freeMemory(J)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, address: Long): void {
var heap = thread.getJVM().getHeap();
heap.free(address.toNumber());
}
public static 'staticFieldOffset(Ljava/lang/reflect/Field;)J'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, field: JVMTypes.java_lang_reflect_Field): Long {
var cls = <ReferenceClassData<JVMTypes.java_lang_Object>> field['java/lang/reflect/Field/clazz'].$cls;
return Long.fromNumber(cls.getVMIndexForField(cls.getFieldFromSlot(field['java/lang/reflect/Field/slot'])));
}
public static 'objectFieldOffset(Ljava/lang/reflect/Field;)J'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, field: JVMTypes.java_lang_reflect_Field): Long {
var cls = <ReferenceClassData<JVMTypes.java_lang_Object>> field['java/lang/reflect/Field/clazz'].$cls;
return Long.fromNumber(cls.getVMIndexForField(cls.getFieldFromSlot(field['java/lang/reflect/Field/slot'])));
}
public static 'staticFieldBase(Ljava/lang/reflect/Field;)Ljava/lang/Object;'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, field: JVMTypes.java_lang_reflect_Field): JVMTypes.java_lang_Object {
// Return a special JVM object.
// TODO: Actually create a special DoppioJVM class for this.
var rv = new ((<ReferenceClassData<JVMTypes.java_lang_Object>> thread.getBsCl().getInitializedClass(thread, 'Ljava/lang/Object;')).getConstructor(thread))(thread);
(<any> rv).$staticFieldBase = field['java/lang/reflect/Field/clazz'].$cls;
return rv;
}
public static 'ensureClassInitialized(Ljava/lang/Class;)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, cls: JVMTypes.java_lang_Class): void {
if (cls.$cls.isInitialized(thread)) {
return;
}
thread.setStatus(ThreadStatus.ASYNC_WAITING);
cls.$cls.initialize(thread, (cdata: ClassData) => {
if (cdata != null) {
thread.asyncReturn();
}
}, true);
}
public static 'arrayBaseOffset(Ljava/lang/Class;)I'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: JVMTypes.java_lang_Class): number {
return 0;
}
/**
* Determines the size of elements in an array.
* e.g. if the array index scale of something is *4*, then each element is 4*minimal addressable unit large.
* Doppio emulates byte-addressable memory, so a return value of 4 indicates 4 bytes/32-bit large elements.
*/
public static 'arrayIndexScale(Ljava/lang/Class;)I'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: JVMTypes.java_lang_Class): number {
var cls = arg0.$cls;
if (cls instanceof ArrayClassData) {
switch(cls.getComponentClass().getInternalName()[0]) {
case 'L':
case '[':
case 'F':
case 'I':
// 32-bits
return 4;
case 'B':
case 'Z':
// 8 bit
return 1;
case 'C':
case 'S':
// 16-bit
return 2;
case 'D':
case 'J':
// 64-bit
return 8;
default:
// Erroneous input.
return -1;
}
} else {
// Erroneous input.
return -1;
}
}
public static 'addressSize()I'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe): number {
return 4;
}
public static 'pageSize()I'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe): number {
// Matches the heap.
return 4096;
}
public static 'defineClass(Ljava/lang/String;[BIILjava/lang/ClassLoader;Ljava/security/ProtectionDomain;)Ljava/lang/Class;'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, name: JVMTypes.java_lang_String, bytes: JVMTypes.JVMArray<number>, offset: number, len: number, loaderObj: JVMTypes.java_lang_ClassLoader, pd: JVMTypes.java_security_ProtectionDomain): void {
var loader = util.getLoader(thread, loaderObj),
cdata: ClassData = loader.defineClass(thread, util.int_classname(name.toString()), util.byteArray2Buffer(bytes.array, offset, len), pd);
if (cdata !== null) {
thread.setStatus(ThreadStatus.ASYNC_WAITING);
// Resolve the class, since we're handing it back to the application
// and we expect these things to be resolved.
cdata.resolve(thread, (cdata: ClassData) => {
if (cdata !== null) {
thread.asyncReturn(cdata.getClassObject(thread));
}
});
}
}
public static 'allocateInstance(Ljava/lang/Class;)Ljava/lang/Object;'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, jco: JVMTypes.java_lang_Class): JVMTypes.java_lang_Object {
// This can trigger class initialization, so check if the class is
// initialized.
var cls = <ReferenceClassData<JVMTypes.java_lang_Object>> jco.$cls;
if (cls.isInitialized(thread)) {
return new (cls.getConstructor(thread))(thread);
} else {
thread.setStatus(ThreadStatus.ASYNC_WAITING);
cls.initialize(thread, () => {
thread.asyncReturn(new (cls.getConstructor(thread))(thread));
});
}
}
public static 'monitorEnter(Ljava/lang/Object;)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: JVMTypes.java_lang_Object): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'monitorExit(Ljava/lang/Object;)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: JVMTypes.java_lang_Object): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'tryMonitorEnter(Ljava/lang/Object;)Z'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: JVMTypes.java_lang_Object): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
public static 'throwException(Ljava/lang/Throwable;)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, exception: JVMTypes.java_lang_Throwable): void {
thread.throwException(exception);
}
public static 'compareAndSwapObject(Ljava/lang/Object;JLjava/lang/Object;Ljava/lang/Object;)Z': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: JVMTypes.java_lang_Object, arg1: Long, arg2: JVMTypes.java_lang_Object, arg3: JVMTypes.java_lang_Object) => boolean = unsafeCompareAndSwap;
public static 'compareAndSwapInt(Ljava/lang/Object;JII)Z': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: JVMTypes.java_lang_Object, arg1: Long, arg2: number, arg3: number) => boolean = unsafeCompareAndSwap;
public static 'compareAndSwapLong(Ljava/lang/Object;JJJ)Z': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: JVMTypes.java_lang_Object, arg1: Long, arg2: Long, arg3: Long) => boolean = unsafeCompareAndSwap;
public static 'getObjectVolatile(Ljava/lang/Object;J)Ljava/lang/Object;': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => JVMTypes.java_lang_Object = getFromVMIndex;
public static 'putObjectVolatile(Ljava/lang/Object;JLjava/lang/Object;)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: JVMTypes.java_lang_Object) => void = setFromVMIndex;
public static 'getIntVolatile(Ljava/lang/Object;J)I': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putIntVolatile(Ljava/lang/Object;JI)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getBooleanVolatile(Ljava/lang/Object;J)Z': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putBooleanVolatile(Ljava/lang/Object;JZ)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getByteVolatile(Ljava/lang/Object;J)B': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putByteVolatile(Ljava/lang/Object;JB)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getShortVolatile(Ljava/lang/Object;J)S': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putShortVolatile(Ljava/lang/Object;JS)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getCharVolatile(Ljava/lang/Object;J)C': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putCharVolatile(Ljava/lang/Object;JC)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getLongVolatile(Ljava/lang/Object;J)J': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => Long = getFromVMIndex;
public static 'putLongVolatile(Ljava/lang/Object;JJ)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: Long) => void = setFromVMIndex;
public static 'getFloatVolatile(Ljava/lang/Object;J)F': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putFloatVolatile(Ljava/lang/Object;JF)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'getDoubleVolatile(Ljava/lang/Object;J)D': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long) => number = getFromVMIndex;
public static 'putDoubleVolatile(Ljava/lang/Object;JD)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'putOrderedObject(Ljava/lang/Object;JLjava/lang/Object;)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newObj: JVMTypes.java_lang_Object) => void = setFromVMIndex;
public static 'putOrderedInt(Ljava/lang/Object;JI)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: number) => void = setFromVMIndex;
public static 'putOrderedLong(Ljava/lang/Object;JJ)V': (thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, obj: JVMTypes.java_lang_Object, offset: Long, newValue: Long) => void = setFromVMIndex;
/**
* Unblock the given thread blocked on park, or, if it is not blocked, cause
* the subsequent call to park not to block.
*/
public static 'unpark(Ljava/lang/Object;)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, theThread: JVMTypes.java_lang_Thread): void {
thread.getJVM().getParker().unpark(theThread.$thread);
}
/**
* Block current thread, returning when a balancing unpark occurs, or a
* balancing unpark has already occurred, or the thread is interrupted, or,
* if not absolute and time is not zero, the given time nanoseconds have
* elapsed, or if absolute, the given deadline in milliseconds since Epoch
* has passed, or spuriously (i.e., returning for no "reason").
*/
public static 'park(ZJ)V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, absolute: number, time: Long): void {
var timeout = Infinity, parker = thread.getJVM().getParker();
if (absolute) {
// Time is an absolute time (milliseconds since Epoch).
// Calculate the timeout from the current time.
timeout = time.toNumber() - (new Date()).getTime();
if (timeout < 0) {
// Forbid negative timeouts.
timeout = 0;
}
} else {
// time is in nanoseconds, but we don't have that
// type of precision
if (time.toNumber() > 0) {
timeout = time.toNumber() / 1000000;
}
}
// Typed as any due to type discrepency between browser and node.
var timer: any;
if (timeout !== Infinity) {
timer = setTimeout(() => {
parker.completelyUnpark(thread);
}, timeout);
}
parker.park(thread, () => {
clearTimeout(timer);
thread.asyncReturn();
});
}
public static 'getLoadAverage([DI)I'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, arg0: JVMTypes.JVMArray<number>, arg1: number): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
/**
* Detect if the given class may need to be initialized. This is often
* needed in conjunction with obtaining the static field base of a
* class.
* @return false only if a call to {@code ensureClassInitialized} would have no effect
*/
public static 'shouldBeInitialized(Ljava/lang/Class;)Z'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, cls: JVMTypes.java_lang_Class): number {
return !cls.$cls.isInitialized(thread) ? 1 : 0;
}
/**
* Define a class but do not make it known to the class loader or system dictionary.
*
* For each CP entry, the corresponding CP patch must either be null or have
* the format that matches its tag:
*
* * Integer, Long, Float, Double: the corresponding wrapper object type from java.lang
* * Utf8: a string (must have suitable syntax if used as signature or name)
* * Class: any java.lang.Class object
* * String: any object (not just a java.lang.String)
* * InterfaceMethodRef: (NYI) a method handle to invoke on that call site's arguments
*
* @params hostClass context for linkage, access control, protection domain, and class loader
* @params data bytes of a class file
* @params cpPatches where non-null entries exist, they replace corresponding CP entries in data
*/
public static 'defineAnonymousClass(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe, hostClass: JVMTypes.java_lang_Class, data: JVMTypes.JVMArray<number>, cpPatches: JVMTypes.JVMArray<JVMTypes.java_lang_Object>): JVMTypes.java_lang_Class {
return new ReferenceClassData(new Buffer(data.array), null, hostClass.$cls.getLoader(), cpPatches).getClassObject(thread);
}
/**
* Ensures lack of reordering of loads before the fence
* with loads or stores after the fence.
* @since 1.8
*/
public static 'loadFence()V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe): void {
// NOP
}
/**
* Ensures lack of reordering of stores before the fence
* with loads or stores after the fence.
* @since 1.8
*/
public static 'storeFence()V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe): void {
// NOP
}
/**
* Ensures lack of reordering of loads or stores before the fence
* with loads or stores after the fence.
* @since 1.8
*/
public static 'fullFence()V'(thread: JVMThread, javaThis: JVMTypes.sun_misc_Unsafe): void {
// NOP
}
}
class sun_misc_Version {
public static 'getJvmSpecialVersion()Ljava/lang/String;'(thread: JVMThread): JVMTypes.java_lang_String {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'getJdkSpecialVersion()Ljava/lang/String;'(thread: JVMThread): JVMTypes.java_lang_String {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'getJvmVersionInfo()Z'(thread: JVMThread): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
public static 'getJdkVersionInfo()V'(thread: JVMThread): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
}
class sun_misc_VM {
public static 'initialize()V'(thread: JVMThread): void {
return;
}
/**
* Returns the first non-null class loader (not counting class loaders
* of generated reflection implementation classes) up the execution stack,
* or null if only code from the null class loader is on the stack.
*/
public static 'latestUserDefinedLoader()Ljava/lang/ClassLoader;'(thread: JVMThread): JVMTypes.java_lang_ClassLoader {
var stackTrace = thread.getStackTrace(), i: number,
bsCl = thread.getBsCl(), loader: ClassLoader;
for (i = stackTrace.length - 1; i >= 0; i--) {
loader = stackTrace[i].method.cls.getLoader();
if (loader !== bsCl) {
return (<CustomClassLoader> loader).getLoaderObject();
}
}
return null;
}
}
class sun_misc_VMSupport {
public static 'initAgentProperties(Ljava/util/Properties;)Ljava/util/Properties;'(thread: JVMThread, arg0: JVMTypes.java_util_Properties): JVMTypes.java_util_Properties {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
}
/**
* URLClassPath has optional support for a lookupcache, which we do not support.
*/
class sun_misc_URLClassPath {
public static 'getLookupCacheURLs(Ljava/lang/ClassLoader;)[Ljava/net/URL;'(thread: JVMThread, loader: JVMTypes.java_lang_ClassLoader): JVMTypes.JVMArray<JVMTypes.java_net_URL> {
return null;
}
public static 'getLookupCacheForClassLoader(Ljava/lang/ClassLoader;Ljava/lang/String;)[I'(thread: JVMThread, loader: JVMTypes.java_lang_ClassLoader, name: JVMTypes.java_lang_String): JVMTypes.JVMArray<number> {
return null;
}
public static 'knownToNotExist0(Ljava/lang/ClassLoader;Ljava/lang/String;)Z'(thread: JVMThread, loader: JVMTypes.java_lang_ClassLoader, name: JVMTypes.java_lang_String): boolean {
return false;
}
}
return {
'sun/misc/GC': sun_misc_GC,
'sun/misc/MessageUtils': sun_misc_MessageUtils,
'sun/misc/NativeSignalHandler': sun_misc_NativeSignalHandler,
'sun/misc/Perf': sun_misc_Perf,
'sun/misc/Signal': sun_misc_Signal,
'sun/misc/Unsafe': sun_misc_Unsafe,
'sun/misc/Version': sun_misc_Version,
'sun/misc/VM': sun_misc_VM,
'sun/misc/VMSupport': sun_misc_VMSupport,
'sun/misc/URLClassPath': sun_misc_URLClassPath
};
}; | the_stack |
import {Class, Creatable} from "@swim/util";
import {Provider} from "@swim/component";
import {R2Box, Transform} from "@swim/math";
import {AnyView, ViewInit, ViewFactory, ViewClass, ViewCreator, View, ModalService} from "@swim/view";
import {DomService} from "../service/DomService";
import {DomProvider} from "../service/DomProvider";
import type {NodeViewObserver} from "./NodeViewObserver";
import {TextView} from "../"; // forward import
import {ViewElement, ElementView} from "../"; // forward import
/** @public */
export type ViewNodeType<V extends NodeView> =
V extends {readonly node: infer N} ? N : never;
/** @public */
export interface ViewNode extends Node {
view?: NodeView;
}
/** @public */
export type AnyNodeView<V extends NodeView = NodeView> = AnyView<V> | ViewNodeType<V>;
/** @public */
export interface NodeViewInit extends ViewInit {
text?: string;
}
/** @public */
export interface NodeViewFactory<V extends NodeView = NodeView, U = AnyNodeView<V>> extends ViewFactory<V, U> {
fromNode(node: ViewNodeType<V>): V
}
/** @public */
export interface NodeViewClass<V extends NodeView = NodeView, U = AnyNodeView<V>> extends ViewClass<V, U>, NodeViewFactory<V, U> {
}
/** @public */
export interface NodeViewConstructor<V extends NodeView = NodeView, U = AnyNodeView<V>> extends NodeViewClass<V, U> {
new(node: ViewNodeType<V>): V;
}
/** @public */
export class NodeView extends View {
constructor(node: Node) {
super();
this.node = node;
(node as ViewNode).view = this;
}
override readonly observerType?: Class<NodeViewObserver>;
readonly node: Node;
override setChild<V extends View>(key: string, newChild: V): View | null;
override setChild<F extends ViewCreator<F>>(key: string, factory: F): View | null;
override setChild(key: string, newChild: AnyView | Node | null): View | null;
override setChild(key: string, newChild: AnyView | Node | null): View | null {
const oldChild = this.getChild(key);
let target: View | null;
if (newChild instanceof Node) {
newChild = NodeView.fromNode(newChild);
} else if (newChild !== null) {
newChild = View.fromAny(newChild);
}
if (oldChild !== null && newChild !== null && oldChild !== newChild) { // replace
newChild.remove();
target = oldChild.nextSibling;
if ((oldChild.flags & View.RemovingFlag) === 0) {
oldChild.setFlags(oldChild.flags | View.RemovingFlag);
this.willRemoveChild(oldChild);
oldChild.detachParent(this);
this.removeChildMap(oldChild);
this.onRemoveChild(oldChild);
this.didRemoveChild(oldChild);
oldChild.setKey(void 0);
oldChild.setFlags(oldChild.flags & ~View.RemovingFlag);
}
newChild.setKey(oldChild.key);
this.willInsertChild(newChild, target);
if (newChild instanceof NodeView) {
if (oldChild instanceof NodeView) {
this.node.replaceChild(newChild.node, oldChild.node);
} else if (target !== null) {
let targetNode: Node | null = null;
let next: View | null = target;
do {
if (next instanceof NodeView) {
targetNode = next.node;
break;
}
next = next.nextSibling;
} while (next !== null);
this.node.insertBefore(newChild.node, targetNode);
} else {
this.node.appendChild(newChild.node);
}
} else if (oldChild instanceof NodeView) {
this.node.removeChild(oldChild.node);
}
this.insertChildMap(newChild);
newChild.attachParent(this, target);
this.onInsertChild(newChild, target);
this.didInsertChild(newChild, target);
newChild.cascadeInsert();
} else if (newChild !== oldChild || newChild !== null && newChild.key !== key) {
if (oldChild !== null) { // remove
target = oldChild.nextSibling;
if ((oldChild.flags & View.RemovingFlag) === 0) {
oldChild.setFlags(oldChild.flags | View.RemovingFlag);
this.willRemoveChild(oldChild);
oldChild.detachParent(this);
this.removeChildMap(oldChild);
if (oldChild instanceof NodeView) {
this.node.removeChild(oldChild.node);
}
this.onRemoveChild(oldChild);
this.didRemoveChild(oldChild);
oldChild.setKey(void 0);
oldChild.setFlags(oldChild.flags & ~View.RemovingFlag);
}
} else {
target = null;
}
if (newChild !== null) { // insert
newChild.remove();
newChild.setKey(key);
this.willInsertChild(newChild, target);
if (newChild instanceof NodeView) {
let targetNode: Node | null = null;
if (target !== null) {
let next: View | null = target;
do {
if (next instanceof NodeView) {
targetNode = next.node;
break;
}
next = next.nextSibling;
} while (next !== null);
}
this.node.insertBefore(newChild.node, targetNode);
}
this.insertChildMap(newChild);
newChild.attachParent(this, target);
this.onInsertChild(newChild, target);
this.didInsertChild(newChild, target);
newChild.cascadeInsert();
}
}
return oldChild;
}
override appendChild<V extends View>(child: V, key?: string): V;
override appendChild<F extends ViewCreator<F>>(factory: F, key?: string): InstanceType<F>;
override appendChild(child: AnyView | Node, key?: string): View;
override appendChild(child: AnyView | Node, key?: string): View {
if (child instanceof Node) {
child = NodeView.fromNode(child);
} else {
child = View.fromAny(child);
}
child.remove();
if (key !== void 0) {
this.removeChild(key);
}
child.setKey(key);
this.willInsertChild(child, null);
if (child instanceof NodeView) {
this.node.appendChild(child.node);
}
this.insertChildMap(child);
child.attachParent(this, null);
this.onInsertChild(child, null);
this.didInsertChild(child, null);
child.cascadeInsert();
return child;
}
override prependChild<V extends View>(child: V, key?: string): V;
override prependChild<F extends ViewCreator<F>>(factory: F, key?: string): InstanceType<F>;
override prependChild(child: AnyView | Node, key?: string): View;
override prependChild(child: AnyView | Node, key?: string): View {
if (child instanceof Node) {
child = NodeView.fromNode(child);
} else {
child = View.fromAny(child);
}
child.remove();
if (key !== void 0) {
this.removeChild(key);
}
const target = this.firstChild;
child.setKey(key);
this.willInsertChild(child, target);
if (child instanceof NodeView) {
this.node.insertBefore(child.node, this.node.firstChild);
}
this.insertChildMap(child);
child.attachParent(this, target);
this.onInsertChild(child, target);
this.didInsertChild(child, target);
child.cascadeInsert();
return child;
}
override insertChild<V extends View>(child: V, target: View | Node | null, key?: string): V;
override insertChild<F extends ViewCreator<F>>(factory: F, target: View | null, key?: string): InstanceType<F>;
override insertChild(child: AnyView | Node, target: View | Node | null, key?: string): View;
override insertChild(child: AnyView | Node, target: View | Node | null, key?: string): View {
if (target instanceof View && target.parent !== this || target instanceof Node && target.parentNode !== this.node) {
throw new TypeError("" + target);
}
if (child instanceof Node) {
child = NodeView.fromNode(child);
} else {
child = View.fromAny(child);
}
child.remove();
if (key !== void 0) {
this.removeChild(key);
}
let targetView: View | null;
let targetNode: Node | null;
if (target instanceof Node) {
targetView = null;
targetNode = target;
let next: ViewNode | null = target;
do {
if (next.view !== void 0) {
targetView = next.view;
break;
}
next = next.nextSibling;
} while (next !== null);
} else {
targetView = target;
targetNode = null;
}
child.setKey(key);
this.willInsertChild(child, targetView);
if (child instanceof NodeView) {
if (targetNode === null && targetView !== null) {
let next: View | null = targetView;
do {
if (next instanceof NodeView) {
targetNode = next.node;
break;
}
next = next.nextSibling;
} while (next !== null);
}
this.node.insertBefore(child.node, targetNode);
}
this.insertChildMap(child);
child.attachParent(this, targetView);
this.onInsertChild(child, targetView);
this.didInsertChild(child, targetView);
child.cascadeInsert();
return child;
}
/** @internal */
injectChild<V extends NodeView>(child: V, target: View | Node | null, key?: string): V;
/** @internal */
injectChild(child: AnyNodeView, target: View | Node | null, key?: string): View;
injectChild(child: AnyNodeView, target: View | Node | null, key?: string): View {
if (target instanceof View && target.parent !== this || target instanceof Node && target.parentNode !== this.node) {
throw new TypeError("" + target);
}
child = NodeView.fromAny(child);
if (key !== void 0) {
this.removeChild(key);
}
if (target instanceof Node) {
let next: ViewNode | null = target;
target = null;
do {
if (next.view !== void 0) {
target = next.view;
break;
}
next = next.nextSibling;
} while (next !== null);
}
child.setKey(key);
this.willInsertChild(child, target);
this.insertChildMap(child);
child.attachParent(this, target);
this.onInsertChild(child, target);
this.didInsertChild(child, target);
child.cascadeInsert();
return child;
}
override replaceChild<V extends View>(newChild: View, oldChild: V): V;
override replaceChild<V extends View>(newChild: AnyView | Node, oldChild: V): V;
override replaceChild(newChild: AnyView | Node, oldChild: View): View {
if (oldChild.parent !== this) {
throw new TypeError("" + oldChild);
}
if (newChild instanceof Node) {
newChild = NodeView.fromNode(newChild);
} else {
newChild = View.fromAny(newChild);
}
if (newChild !== oldChild) {
newChild.remove();
const target = oldChild.nextSibling;
if ((oldChild.flags & View.RemovingFlag) === 0) {
oldChild.setFlags(oldChild.flags | View.RemovingFlag);
this.willRemoveChild(oldChild);
oldChild.detachParent(this);
this.removeChildMap(oldChild);
this.onRemoveChild(oldChild);
this.didRemoveChild(oldChild);
oldChild.setKey(void 0);
oldChild.setFlags(oldChild.flags & ~View.RemovingFlag);
}
newChild.setKey(oldChild.key);
this.willInsertChild(newChild, target);
if (newChild instanceof NodeView) {
if (oldChild instanceof NodeView) {
this.node.replaceChild(newChild.node, oldChild.node);
} else if (target !== null) {
let targetNode: Node | null = null;
let next: View | null = target;
do {
if (next instanceof NodeView) {
targetNode = next.node;
break;
}
next = next.nextSibling;
} while (next !== null);
this.node.insertBefore(newChild.node, targetNode);
} else {
this.node.appendChild(newChild.node);
}
} else if (oldChild instanceof NodeView) {
this.node.removeChild(oldChild.node);
}
this.insertChildMap(newChild);
newChild.attachParent(this, target);
this.onInsertChild(newChild, target);
this.didInsertChild(newChild, target);
newChild.cascadeInsert();
}
return oldChild;
}
override removeChild<V extends View | Node>(child: V): V;
override removeChild(key: string | View): View | null;
override removeChild(key: string | View | Node): View | Node | null;
override removeChild(key: string | View | ViewNode): View | Node | null {
let child: View | null;
if (typeof key === "string") {
child = this.getChild(key);
if (child === null) {
return null;
}
} else if (key instanceof Node) {
if (key.parentNode !== this.node) {
throw new Error("not a child node");
}
if (key.view !== void 0) {
child = key.view;
} else {
this.node.removeChild(key);
return key;
}
} else {
child = key;
if (child.parent !== this) {
throw new Error("not a child");
}
}
if ((child.flags & View.RemovingFlag) === 0) {
child.setFlags(child.flags | View.RemovingFlag);
this.willRemoveChild(child);
child.detachParent(this);
this.removeChildMap(child);
if (child instanceof NodeView) {
this.node.removeChild(child.node);
}
this.onRemoveChild(child);
this.didRemoveChild(child);
child.setKey(void 0);
child.setFlags(child.flags & ~View.RemovingFlag);
}
return child;
}
override removeChildren(): void {
let child: View | null;
while (child = this.lastChild, child !== null) {
if ((child.flags & View.RemovingFlag) !== 0) {
throw new Error("inconsistent removeChildren");
}
this.willRemoveChild(child);
child.detachParent(this);
this.removeChildMap(child);
if (child instanceof NodeView) {
this.node.removeChild(child.node);
}
this.onRemoveChild(child);
this.didRemoveChild(child);
child.setKey(void 0);
child.setFlags(child.flags & ~View.RemovingFlag);
}
}
/** @internal */
static isRootView(node: Node): boolean {
do {
const parentNode: ViewNode | null = node.parentNode;
if (parentNode !== null) {
const parentView = parentNode.view;
if (parentView !== void 0) {
return false;
}
node = parentNode;
continue;
}
break;
} while (true);
return true;
}
/** @internal */
static isNodeMounted(node: Node): boolean {
let isConnected: boolean | undefined = node.isConnected;
if (typeof isConnected !== "boolean") {
const ownerDocument = node.ownerDocument;
if (ownerDocument !== null) {
const position = ownerDocument.compareDocumentPosition(node);
isConnected = (position & node.DOCUMENT_POSITION_DISCONNECTED) === 0;
} else {
isConnected = false;
}
}
return isConnected;
}
/** @internal */
static mount(view: NodeView): void {
if (view.parent === null) {
const parentNode = view.node.parentNode as ViewNode | null;
const parentView = parentNode !== null && parentNode.view !== void 0 ? parentNode.view : null;
if (parentView !== null) {
let targetView: View | null = null;
let targetNode: ViewNode | null = view.node.nextSibling;
while (targetNode !== null) {
if (targetNode.view !== void 0) {
targetView = targetNode.view;
break;
}
targetNode = targetNode.nextSibling;
}
view.attachParent(parentView, targetView);
view.cascadeInsert();
} else {
view.mount();
}
}
}
/** @internal */
override mount(): void {
if (!this.mounted && NodeView.isNodeMounted(this.node) && NodeView.isRootView(this.node)) {
this.cascadeMount();
this.cascadeInsert();
}
}
@Provider({
extends: DomProvider,
type: DomService,
observes: false,
service: DomService.global(),
})
declare readonly domProvider: DomProvider<this>;
text(): string | undefined;
text(value: string | null | undefined): this;
text(value?: string | null | undefined): string | undefined | this {
if (arguments.length === 0) {
value = this.node.textContent;
if (value === null) {
value = void 0;
}
return value;
} else {
if (value === void 0) {
value = null;
}
this.node.textContent = value;
return this;
}
}
override get parentTransform(): Transform {
return Transform.identity();
}
override get clientBounds(): R2Box {
const range = document.createRange();
range.selectNode(this.node);
const bounds = range.getBoundingClientRect();
range.detach();
return new R2Box(bounds.left, bounds.top, bounds.right, bounds.bottom);
}
override get pageBounds(): R2Box {
const range = document.createRange();
range.selectNode(this.node);
const bounds = range.getBoundingClientRect();
range.detach();
const scrollX = window.pageXOffset;
const scrollY = window.pageYOffset;
return new R2Box(bounds.left + scrollX, bounds.top + scrollY,
bounds.right + scrollX, bounds.bottom + scrollY);
}
override dispatchEvent(event: Event): boolean {
return this.node.dispatchEvent(event);
}
override on(type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): this {
this.node.addEventListener(type, listener, options);
return this;
}
override off(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): this {
this.node.removeEventListener(type, listener, options);
return this;
}
override init(init: NodeViewInit): void {
super.init(init);
if (init.text !== void 0) {
this.text(init.text);
}
}
static fromNode<S extends new (node: Node) => InstanceType<S>>(this: S, node: ViewNodeType<InstanceType<S>>): InstanceType<S>;
static fromNode(node: Node): NodeView;
static fromNode(node: Node): NodeView {
let view = (node as ViewNode).view;
if (view === void 0) {
if (node instanceof Element) {
view = ElementView.fromNode(node as ViewElement);
} else if (node instanceof Text) {
view = TextView.fromNode(node);
} else {
view = new this(node);
this.mount(view);
}
} else if (!(view instanceof this)) {
throw new TypeError(view + " not an instance of " + this);
}
return view;
}
static override fromAny<S extends abstract new (...args: any) => InstanceType<S>>(this: S, value: AnyNodeView<InstanceType<S>>): InstanceType<S>;
static override fromAny(value: AnyNodeView): NodeView;
static override fromAny(value: AnyNodeView): NodeView {
if (value === void 0 || value === null) {
return value;
} else if (value instanceof View) {
if (value instanceof this) {
return value;
} else {
throw new TypeError(value + " not an instance of " + this);
}
} else if (value instanceof Node) {
return this.fromNode(value);
} else if (Creatable.is(value)) {
return value.create();
} else {
return this.fromInit(value);
}
}
}
ModalService.insertModalView = function (modalView: NodeView): void {
const matteNode = document.body as ViewNode;
const matteView = matteNode.view;
if (matteView !== void 0) {
matteView.appendChild(modalView);
} else if (modalView instanceof NodeView) {
matteNode.appendChild(modalView.node);
modalView.mount();
} else {
throw new TypeError("" + modalView);
}
}; | the_stack |
import { PdfColorSpace } from './../enum';
import { PdfColor } from './../pdf-color';
import { PdfColorBlend } from './pdf-color-blend';
/**
* `PdfBlend` Represents the blend color space
* @private
*/
export class PdfBlend {
//Constants
/**
* precision of the GCD calculations.
* @private
*/
private precision: number = 1000;
//Fields
/**
* Local variable to store the count.
* @private
*/
private mCount: number;
/**
* Local variable to store the positions.
* @private
*/
private mPositions: number[];
/**
* Local variable to store the factors
* @private.
*/
private mFactors: number[];
//Constructor
/**
* Initializes a new instance of the `PdfBlend` class.
* @public
*/
public constructor ()
/**
* Initializes a new instance of the `PdfBlend` class.
* @public
*/
public constructor (count : number)
public constructor (count ?: number) {
//
}
//Properties
/**
* Gets or sets the array of factor to the blend.
* @public
*/
public get factors(): number[] {
return this.mFactors;
}
public set factors(value: number[]) {
if ((value == null)) {
throw new Error('ArgumentNullException : Factors');
}
this.mFactors = value;
}
/**
* 'positions' Gets or sets the array of positions
* @public
*/
public get positions(): number[] {
return this.mPositions;
}
public set positions(value: number[]) {
let positionarray: number[] = value;
for (let i: number = 0; i < positionarray.length; i++) {
if (((positionarray[i] < 0) || (positionarray[i] > 1))) {
positionarray[i] = 0;
}
}
this.mPositions = positionarray;
this.mPositions = value;
}
/**
* Gets the number of elements that specify the blend.
* @protected
*/
protected get count(): number {
return this.mCount;
}
//Implementation
/**
* Generates a correct color blend.
* @param colours The colours.
* @param colorSpace The color space.
*/
public generateColorBlend(colours: PdfColor[], colorSpace: PdfColorSpace): PdfColorBlend {
if ((colours == null)) {
throw new Error('ArgumentNullException : colours');
}
if ((this.positions == null)) {
this.positions = [0];
}
let cBlend: PdfColorBlend = new PdfColorBlend(this.count);
let positions: number[] = this.positions;
let clrs: PdfColor[] = null;
if ((positions.length === 1)) {
positions = [3];
positions[0] = 0;
positions[1] = this.positions[0];
positions[2] = 1;
/* tslint:disable */
clrs = new Array(3);
clrs[0] = colours[0];
clrs[1] = colours[0];
clrs[2] = colours[1];
} else {
let c1: PdfColor = colours[0];
let c2: PdfColor = colours[1];
/* tslint:disable */
clrs = new Array(this.count);
let i: number = 0;
let count : number = this.count;
for (i = 0; i < count; ++i) {
clrs[i] = this.interpolate(this.mFactors[i], c1, c2, colorSpace);
}
}
cBlend.positions = positions;
cBlend.colors = clrs;
return cBlend;
}
/**
* 'clonePdfBlend' Clones this instance.
* @public
*/
public clonePdfBlend(): PdfBlend {
let blend: PdfBlend = this;
if ((this.mFactors != null)) {
blend.factors = (<number[]>(this.mFactors));
}
if ((this.positions != null)) {
blend.positions = (<number[]>(this.positions));
}
return blend;
}
/**
* Calculate the GCD of the specified values.
* @param u The values.
*/
protected gcd(u: number[]): number
/**
* Determines greatest common divisor of the specified u and v.
* @param u The u.
* @param v The v.
*/
protected gcd(u: number, v: number): number
protected gcd(u?: number|number[], v?: number): number {
if ( typeof u === 'number' && typeof v === 'number' && typeof v !== 'undefined') {
if (((u < 0) || (u > 1))) {
throw new Error('ArgumentOutOfRangeException : u');
}
if (((v < 0) || (v > 1))) {
throw new Error('ArgumentOutOfRangeException : v');
}
let iU: number = (<number>(Math.max(1, (u * this.precision))));
let iV: number = (<number>(Math.max(1, (v * this.precision))));
let iResult: number = this.gcdInt(iU, iV);
let result: number = ((<number>(iResult)) / this.precision);
return result;
} else {
let values : number[] = u as number[];
if ((values == null)) {
throw new Error('ArgumentNullException : values');
}
if ((values.length < 1)) {
throw new Error('ArgumentException : Not enough values in the array. - values');
}
let gcd: number = values[0];
if ((values.length > 1)) {
let count: number = values.length;
for (let i : number = 1; i < count; ++i) {
gcd = this.gcd(values[i], gcd);
if ((gcd === (1 / this.precision))) {
break;
}
}
}
return gcd;
}
}
/**
* Calculate the GCD int of the specified values.
* @param u The u.
* @param v The v.
*/
protected gcdInt(u: number, v: number): number {
if ((u <= 0)) {
throw new Error('ArgumentOutOfRangeException' + u + 'The arguments cannot be less or equal to zero.');
}
if ((v <= 0)) {
throw new Error('ArgumentOutOfRangeException' + v + 'The arguments cannot be less or equal to zero.');
}
if (((u === 1) || (v === 1))) {
return 1;
}
let shift: number = 0;
while (this.isEven(u, v)) {
++shift;
u >>= 1;
v >>= 1;
}
while (((u & 1) <= 0)) {
u >>= 1;
}
do {
while ((v & 1) <= 0) {
v >>= 1;
}
if (u > v) {
let t : number = v; v = u; u = t;
}
v = v - u;
} while (v !== 0);
return (u << shift);
}
/**
* Determines if the u value is even.
* @param u The u value.
*/
private isEven(u: number): boolean
/**
* Determines if both parameters are even numbers.
* @param u The first value.
* @param v The second value.
*/
private isEven(u: number, v: number): boolean
private isEven(arg1?: number, arg2?: number): boolean {
if (typeof arg2 === 'number' && typeof arg2 !== 'undefined') {
let result : boolean = true;
result = (result && ((arg1 & 1) <= 0)); // Is u even?
result = (result && ((arg2 & 1) <= 0)); // Is v even?
return result;
} else {
return ((arg1 & 1) <= 0);
}
}
/**
* Interpolates the specified colours according to the t value.
* @param t The t value, which show the imagine position on a line from 0 to 1.
* @param v1 The minimal value.
* @param v2 The maximal value.
*/
protected interpolate(t: number, v1: number, v2: number): number
/**
* Interpolates the specified colours according to the t value.
* @param t The t value, which show the imagine position on a line from 0 to 1.
* @param color1 The minimal colour.
* @param color2 The maximal colour.
* @param colorSpace The color space.
*/
protected interpolate(t: number, color1: PdfColor, color2: PdfColor, colorSpace: PdfColorSpace): PdfColor
protected interpolate(t: number, color1: number|PdfColor, color2: number|PdfColor, colorSpace?: PdfColorSpace): PdfColor|number {
if (color1 instanceof PdfColor) {
let color: PdfColor = new PdfColor();
switch (colorSpace) {
case PdfColorSpace.Rgb:
let red: number = (<number>(this.interpolate(t, color1.red, (color2 as PdfColor).red)));
let green: number = (<number>(this.interpolate(t, color1.green, (color2 as PdfColor).green)));
let blue: number = (<number>(this.interpolate(t, color1.blue, (color2 as PdfColor).blue)));
color = new PdfColor(red, green, blue);
break;
case PdfColorSpace.GrayScale:
let gray: number = (<number>(this.interpolate(t, color1.gray, (color2 as PdfColor).gray)));
color = new PdfColor(gray);
break;
case PdfColorSpace.Cmyk:
let cyan: number = (<number>(this.interpolate(t, color1.c, (color2 as PdfColor).c)));
let magenta: number = (<number>(this.interpolate(t, color1.m, (color2 as PdfColor).m)));
let yellow: number = (<number>(this.interpolate(t, color1.y, (color2 as PdfColor).y)));
let black: number = (<number>(this.interpolate(t, color1.k, (color2 as PdfColor).k)));
color = new PdfColor(cyan, magenta, yellow, black);
break;
}
return color;
} else {
let t0: number = 0;
let t1: number = 1;
let result: number = 0;
if ((t === t0)) {
result = color1;
} else if ((t === t1)) {
result = <number>color2;
} else {
result = (color1 + ((t - t0) * (((color2 as number) - color1) / (t1 - t0))));
}
return result;
}
}
} | the_stack |
import { Rhum } from "../../deps.ts";
import members from "../../members.ts";
import { Drash } from "../../../mod.ts";
Rhum.testPlan("decorators/middleware_test.ts", () => {
Rhum.testSuite("ResourceWithMiddlewareBeforeClass", () => {
Rhum.testCase("header not specified", async () => {
const server = new Drash.Http.Server({
resources: [ResourceWithMiddlewareBeforeClass],
});
const request = members.mockRequest("/users/1");
const response = await server.handleHttpRequest(request);
members.assertResponseJsonEquals(
members.responseBody(response),
"'header' not specified.",
);
});
Rhum.testCase("valid", async () => {
const server = new Drash.Http.Server({
resources: [ResourceWithMiddlewareBeforeClass],
});
const request = members.mockRequest("/users/1", "get", {
headers: {
csrf_token: "all your base",
},
});
const response = await server.handleHttpRequest(request);
members.assertResponseJsonEquals(
members.responseBody(response),
{ name: "Thor" },
);
});
});
Rhum.testSuite("ResourceWithMultipleMiddlewareBeforeClass", () => {
Rhum.testCase("correct header, custom response and value", async () => {
const server = new Drash.Http.Server({
resources: [ResourceWithMultipleMiddlewareBeforeClass],
});
const request = members.mockRequest("/users/1", "get", {
headers: {
csrf_token: "all your base",
},
});
const response = await server.handleHttpRequest(request);
members.assertResponseJsonEquals(
members.responseBody(response),
{ name: "Thor" },
);
Rhum.asserts.assertEquals(response.headers!.get("MYCUSTOM"), "hey");
});
});
Rhum.testSuite("ResourceWithMultipleMiddlewareAfterClass", () => {
Rhum.testCase("response is html, custom header and value", async () => {
const server = new Drash.Http.Server({
resources: [ResourceWithMultipleMiddlewareAfterClass],
});
const request = members.mockRequest("/users/1", "get", {
headers: {
csrf_token: "all your base",
},
});
const response = await server.handleHttpRequest(request);
Rhum.asserts.assertEquals(members.responseBody(response), "<h1>hey</h1>");
Rhum.asserts.assertEquals(
response.headers!.get("Content-Type"),
"text/html",
);
Rhum.asserts.assertEquals(response.headers!.get("MYCUSTOM"), "hey");
});
});
Rhum.testSuite("ResourceWithMiddlewareClass", () => {
Rhum.testCase("custom header and swap to html", async () => {
const server = new Drash.Http.Server({
resources: [ResourceWithMiddlewareClass],
});
const request = members.mockRequest("/users/1", "get", {
headers: {
csrf_token: "all your base",
},
});
const response = await server.handleHttpRequest(request);
Rhum.asserts.assertEquals(members.responseBody(response), "<h1>hey</h1>");
Rhum.asserts.assertEquals(
response.headers!.get("Content-Type"),
"text/html",
);
Rhum.asserts.assertEquals(response.headers!.get("MYCUSTOM"), "hey");
});
});
Rhum.testSuite("ResourceWithMiddlewareBeforeMethod", () => {
Rhum.testCase("custom header", async () => {
const server = new Drash.Http.Server({
resources: [ResourceWithMiddlewareBeforeMethod],
});
const request = members.mockRequest("/users/1", "get", {
headers: {
csrf_token: "all your base",
},
});
const response = await server.handleHttpRequest(request);
members.assertResponseJsonEquals(
members.responseBody(response),
{ name: "Thor" },
);
});
});
Rhum.testSuite("ResourceWithMultipleMiddlewareBeforeMethod", () => {
Rhum.testCase("custom header", async () => {
const server = new Drash.Http.Server({
resources: [ResourceWithMultipleMiddlewareBeforeMethod],
});
const request = members.mockRequest("/users/1", "get", {
headers: {
csrf_token: "all your base",
},
});
const response = await server.handleHttpRequest(request);
members.assertResponseJsonEquals(
members.responseBody(response),
{ name: "Thor" },
);
Rhum.asserts.assertEquals(response.headers!.get("MYCUSTOM"), "hey");
});
});
Rhum.testSuite("ResourceWithMiddlewareAfterMethod", () => {
Rhum.testCase("swap to html", async () => {
const server = new Drash.Http.Server({
resources: [ResourceWithMiddlewareAfterMethod],
});
const request = members.mockRequest("/users/1", "get", {
headers: {
csrf_token: "all your base",
},
});
const response = await server.handleHttpRequest(request);
Rhum.asserts.assertEquals(members.responseBody(response), "<h1>hey</h1>");
Rhum.asserts.assertEquals(
response.headers!.get("Content-Type"),
"text/html",
);
});
});
Rhum.testSuite("ResourceWithMultipleMiddlewareAfterMethod", () => {
Rhum.testCase("custom header and swap to html", async () => {
const server = new Drash.Http.Server({
resources: [ResourceWithMultipleMiddlewareAfterMethod],
});
const request = members.mockRequest("/users/1", "get", {
headers: {
csrf_token: "all your base",
},
});
const response = await server.handleHttpRequest(request);
Rhum.asserts.assertEquals(members.responseBody(response), "<h1>hey</h1>");
Rhum.asserts.assertEquals(
response.headers!.get("Content-Type"),
"text/html",
);
Rhum.asserts.assertEquals(response.headers!.get("MYCUSTOM"), "hey");
});
});
});
Rhum.run();
////////////////////////////////////////////////////////////////////////////////
// FILE MARKER - DATA //////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
interface IUser {
name: string;
}
function CustomHeader(
request: Drash.Http.Request,
response: Drash.Http.Response,
) {
if (request.getHeaderParam("csrf_token") == null) {
throw new Drash.Exceptions.HttpMiddlewareException(
400,
"'header' not specified.",
);
}
}
function SwapResponseToHtml(
request: Drash.Http.Request,
response: Drash.Http.Response,
) {
response.headers.set("Content-Type", "text/html");
response.body = "<h1>hey</h1>";
}
function ResponseCustomHeaderAdded(
request: Drash.Http.Request,
response: Drash.Http.Response,
) {
response.headers.set("MYCUSTOM", "hey");
}
@Drash.Http.Middleware({ before_request: [CustomHeader] })
class ResourceWithMiddlewareBeforeClass extends Drash.Http.Resource {
static paths = ["/users/:id", "/users/:id/"];
public users = new Map<number, IUser>([
[1, { name: "Thor" }],
[2, { name: "Hulk" }],
]);
public GET() {
const param = this.request.getPathParam("id");
if (param) {
this.response.body = this.users.get(
parseInt(param),
);
}
return this.response;
}
}
@Drash.Http.Middleware(
{ before_request: [ResponseCustomHeaderAdded, CustomHeader] },
)
class ResourceWithMultipleMiddlewareBeforeClass extends Drash.Http.Resource {
static paths = ["/users/:id", "/users/:id/"];
public users = new Map<number, IUser>([
[1, { name: "Thor" }],
[2, { name: "Hulk" }],
]);
public GET() {
const param = this.request.getPathParam("id");
if (param) {
this.response.body = this.users.get(
parseInt(param),
);
}
return this.response;
}
}
@Drash.Http.Middleware(
{ after_request: [SwapResponseToHtml, ResponseCustomHeaderAdded] },
)
class ResourceWithMultipleMiddlewareAfterClass extends Drash.Http.Resource {
static paths = ["/users/:id", "/users/:id/"];
public users = new Map<number, IUser>([
[1, { name: "Thor" }],
[2, { name: "Hulk" }],
]);
public GET() {
return this.response;
}
}
@Drash.Http.Middleware(
{
before_request: [SwapResponseToHtml],
after_request: [ResponseCustomHeaderAdded],
},
)
class ResourceWithMiddlewareClass extends Drash.Http.Resource {
static paths = ["/users/:id", "/users/:id/"];
public users = new Map<number, IUser>([
[1, { name: "Thor" }],
[2, { name: "Hulk" }],
]);
public GET() {
return this.response;
}
}
class ResourceWithMiddlewareBeforeMethod extends Drash.Http.Resource {
static paths = ["/users/:id", "/users/:id/"];
public users = new Map<number, IUser>([
[1, { name: "Thor" }],
[2, { name: "Hulk" }],
]);
@Drash.Http.Middleware({ before_request: [CustomHeader] })
public GET() {
const param = this.request.getPathParam("id");
if (param) {
this.response.body = this.users.get(
parseInt(param),
);
}
return this.response;
}
}
class ResourceWithMiddlewareAfterMethod extends Drash.Http.Resource {
static paths = ["/users/:id", "/users/:id/"];
public users = new Map<number, IUser>([
[1, { name: "Thor" }],
[2, { name: "Hulk" }],
]);
@Drash.Http.Middleware({ after_request: [SwapResponseToHtml] })
public GET() {
return this.response;
}
}
class ResourceWithMultipleMiddlewareBeforeMethod extends Drash.Http.Resource {
static paths = ["/users/:id", "/users/:id/"];
public users = new Map<number, IUser>([
[1, { name: "Thor" }],
[2, { name: "Hulk" }],
]);
@Drash.Http.Middleware(
{ before_request: [ResponseCustomHeaderAdded, CustomHeader] },
)
public GET() {
const param = this.request.getPathParam("id");
if (param) {
this.response.body = this.users.get(
parseInt(param),
);
}
return this.response;
}
}
class ResourceWithMultipleMiddlewareAfterMethod extends Drash.Http.Resource {
static paths = ["/users/:id", "/users/:id/"];
public users = new Map<number, IUser>([
[1, { name: "Thor" }],
[2, { name: "Hulk" }],
]);
@Drash.Http.Middleware(
{ after_request: [SwapResponseToHtml, ResponseCustomHeaderAdded] },
)
public GET() {
return this.response;
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [qldb](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonqldb.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Qldb extends PolicyStatement {
public servicePrefix = 'qldb';
/**
* Statement provider for service [qldb](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonqldb.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 cancel a journal kinesis stream
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_CancelJournalKinesisStream.html
*/
public toCancelJournalKinesisStream() {
return this.to('CancelJournalKinesisStream');
}
/**
* Grants permission to create a ledger
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_CreateLedger.html
*/
public toCreateLedger() {
return this.to('CreateLedger');
}
/**
* Grants permission to delete a ledger
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_DeleteLedger.html
*/
public toDeleteLedger() {
return this.to('DeleteLedger');
}
/**
* Grants permission to describe information about a journal kinesis stream
*
* Access Level: Read
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_DescribeJournalKinesisStream.html
*/
public toDescribeJournalKinesisStream() {
return this.to('DescribeJournalKinesisStream');
}
/**
* Grants permission to describe information about a journal export job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_DescribeJournalS3Export.html
*/
public toDescribeJournalS3Export() {
return this.to('DescribeJournalS3Export');
}
/**
* Grants permission to describe a ledger
*
* Access Level: Read
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_DescribeLedger.html
*/
public toDescribeLedger() {
return this.to('DescribeLedger');
}
/**
* Grants permission to send commands to a ledger via the console
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/console_QLDB.html
*/
public toExecuteStatement() {
return this.to('ExecuteStatement');
}
/**
* Grants permission to export journal contents to an Amazon S3 bucket
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_ExportJournalToS3.html
*/
public toExportJournalToS3() {
return this.to('ExportJournalToS3');
}
/**
* Grants permission to retrieve a block from a ledger for a given BlockAddress
*
* Access Level: Read
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_GetBlock.html
*/
public toGetBlock() {
return this.to('GetBlock');
}
/**
* Grants permission to retrieve a digest from a ledger for a given BlockAddress
*
* Access Level: Read
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_GetDigest.html
*/
public toGetDigest() {
return this.to('GetDigest');
}
/**
* Grants permission to retrieve a revision for a given document ID and a given BlockAddress
*
* Access Level: Read
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_GetRevision.html
*/
public toGetRevision() {
return this.to('GetRevision');
}
/**
* Grants permission to insert sample application data via the console
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/console_QLDB.html
*/
public toInsertSampleData() {
return this.to('InsertSampleData');
}
/**
* Grants permission to list journal kinesis streams for a specified ledger
*
* Access Level: List
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_ListJournalKinesisStreamsForLedger.html
*/
public toListJournalKinesisStreamsForLedger() {
return this.to('ListJournalKinesisStreamsForLedger');
}
/**
* Grants permission to list journal export jobs for all ledgers
*
* Access Level: List
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_ListJournalS3Exports.html
*/
public toListJournalS3Exports() {
return this.to('ListJournalS3Exports');
}
/**
* Grants permission to list journal export jobs for a specified ledger
*
* Access Level: List
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_ListJournalS3ExportsForLedger.html
*/
public toListJournalS3ExportsForLedger() {
return this.to('ListJournalS3ExportsForLedger');
}
/**
* Grants permission to list existing ledgers
*
* Access Level: List
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_ListLedgers.html
*/
public toListLedgers() {
return this.to('ListLedgers');
}
/**
* Grants permission to list tags for a resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to create an index on a table
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/ql-reference.create-index.html
*/
public toPartiQLCreateIndex() {
return this.to('PartiQLCreateIndex');
}
/**
* Grants permission to create a table
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/ql-reference.create-table.html
*/
public toPartiQLCreateTable() {
return this.to('PartiQLCreateTable');
}
/**
* Grants permission to delete documents from a table
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/ql-reference.delete.html
*/
public toPartiQLDelete() {
return this.to('PartiQLDelete');
}
/**
* Grants permission to drop an index from a table
*
* Access Level: Write
*
* Possible conditions:
* - .ifPurge()
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/ql-reference.drop-index.html
*/
public toPartiQLDropIndex() {
return this.to('PartiQLDropIndex');
}
/**
* Grants permission to drop a table
*
* Access Level: Write
*
* Possible conditions:
* - .ifPurge()
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/ql-reference.drop-table.html
*/
public toPartiQLDropTable() {
return this.to('PartiQLDropTable');
}
/**
* Grants permission to use the history function on a table
*
* Access Level: Read
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/working.history.html
*/
public toPartiQLHistoryFunction() {
return this.to('PartiQLHistoryFunction');
}
/**
* Grants permission to insert documents into a table
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/ql-reference.insert.html
*/
public toPartiQLInsert() {
return this.to('PartiQLInsert');
}
/**
* Grants permission to select documents from a table
*
* Access Level: Read
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/ql-reference.select.html
*/
public toPartiQLSelect() {
return this.to('PartiQLSelect');
}
/**
* Grants permission to undrop a table
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/ql-reference.undrop-table.html
*/
public toPartiQLUndropTable() {
return this.to('PartiQLUndropTable');
}
/**
* Grants permission to update existing documents in a table
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/ql-reference.update.html
*/
public toPartiQLUpdate() {
return this.to('PartiQLUpdate');
}
/**
* Grants permission to send commands to a ledger
*
* Access Level: Write
*/
public toSendCommand() {
return this.to('SendCommand');
}
/**
* Grants permission to view a ledger's catalog via the console
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/console_QLDB.html
*/
public toShowCatalog() {
return this.to('ShowCatalog');
}
/**
* Grants permission to stream journal contents to a Kinesis Data Stream
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_StreamJournalToKinesis.html
*/
public toStreamJournalToKinesis() {
return this.to('StreamJournalToKinesis');
}
/**
* Grants permission to add one or more tags to a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove one or more tags from a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update properties on a ledger
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_UpdateLedger.html
*/
public toUpdateLedger() {
return this.to('UpdateLedger');
}
/**
* Grants permission to update the permissions mode on a ledger
*
* Access Level: Write
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/API_UpdateLedgerPermissionsMode.html
*/
public toUpdateLedgerPermissionsMode() {
return this.to('UpdateLedgerPermissionsMode');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CancelJournalKinesisStream",
"CreateLedger",
"DeleteLedger",
"ExecuteStatement",
"ExportJournalToS3",
"InsertSampleData",
"PartiQLCreateIndex",
"PartiQLCreateTable",
"PartiQLDelete",
"PartiQLDropIndex",
"PartiQLDropTable",
"PartiQLInsert",
"PartiQLUndropTable",
"PartiQLUpdate",
"SendCommand",
"ShowCatalog",
"StreamJournalToKinesis",
"UpdateLedger",
"UpdateLedgerPermissionsMode"
],
"Read": [
"DescribeJournalKinesisStream",
"DescribeJournalS3Export",
"DescribeLedger",
"GetBlock",
"GetDigest",
"GetRevision",
"ListTagsForResource",
"PartiQLHistoryFunction",
"PartiQLSelect"
],
"List": [
"ListJournalKinesisStreamsForLedger",
"ListJournalS3Exports",
"ListJournalS3ExportsForLedger",
"ListLedgers"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type ledger to the statement
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/ledger-structure.html
*
* @param ledgerName - Identifier for the ledgerName.
* @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 onLedger(ledgerName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:qldb:${Region}:${Account}:ledger/${LedgerName}';
arn = arn.replace('${LedgerName}', ledgerName);
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 stream to the statement
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/streams.html
*
* @param ledgerName - Identifier for the ledgerName.
* @param streamId - Identifier for the streamId.
* @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 onStream(ledgerName: string, streamId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:qldb:${Region}:${Account}:stream/${LedgerName}/${StreamId}';
arn = arn.replace('${LedgerName}', ledgerName);
arn = arn.replace('${StreamId}', streamId);
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 table to the statement
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/working.manage-tables.html
*
* @param ledgerName - Identifier for the ledgerName.
* @param tableId - Identifier for the tableId.
* @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 onTable(ledgerName: string, tableId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:qldb:${Region}:${Account}:ledger/${LedgerName}/table/${TableId}';
arn = arn.replace('${LedgerName}', ledgerName);
arn = arn.replace('${TableId}', tableId);
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 catalog to the statement
*
* https://docs.aws.amazon.com/qldb/latest/developerguide/working.catalog.html
*
* @param ledgerName - Identifier for the ledgerName.
* @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 onCatalog(ledgerName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:qldb:${Region}:${Account}:ledger/${LedgerName}/information_schema/user_tables';
arn = arn.replace('${LedgerName}', ledgerName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access by the value of purge that is specified in a PartiQL DROP statement
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-purge
*
* Applies to actions:
* - .toPartiQLDropIndex()
* - .toPartiQLDropTable()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifPurge(value: string | string[], operator?: Operator | string) {
return this.if(`Purge`, value, operator || 'StringLike');
}
} | the_stack |
module TDev {
export var currentScreen: Screen = null;
export var allScreens: Screen[] = [];
interface HistoryEntry {
url: string;
onPop: () => void;
}
export class HistoryMgr
{
private lastSetHash: string;
// hack to filter out hash change that wasn't according to us
private previousHash: string;
public replaceNext: boolean;
// seems to be used to determine if this is the first loadHash ever
public numReloads = 0;
static instance: HistoryMgr;
private urlStack : HistoryEntry[] = [];
constructor() {
this.lastSetHash = "";
this.replaceNext = false;
Screen.pushModalHash = (s, f) => this.pushModalHash(s, f);
Screen.popModalHash = (s) => this.popModalHash(s);
HistoryMgr.instance = this;
Util.onSetHash = (s, r) => this.setHashHandler(s, r);
Util.onGoBack = () => this.back();
}
/// Used for debugging.
public currentHash() { return this.lastSetHash; }
static urlHash(url: string): string {
var i = url.indexOf('#')
if (i > 0 && i < url.length - 1)
return url.slice(i);
else
return "#" + TDev.hubHash;
}
static windowHash() {
var h = window.location.href;
return HistoryMgr.urlHash(h);
}
private pushState(h:string)
{
try {
Util.log("pushState: " + h)
h = window.location.href.replace(/#.*/, "") + (h || "")
window.history.pushState(++this.numPush, null, h)
} catch (e) {
// this doesn't work in embedded iframe
}
}
// Called to tell the history manager where we are
// Not expected to change the appearance of the UI
public setHash(h: string, t: string) {
Util.log("sethash: " + h + " - " + t)
Ticker.dbg("History.setHash|" + h);
var repl = this.replaceNext;
this.replaceNext = false;
if (repl) {
Ticker.dbg("History.setHash is a replace");
}
this.numReloads++;
if (!/^#/.test(h)) h = "#" + h;
if (h == "#" + TDev.hubHash) h = "#"
this.clearModalSuffix();
Screen.arrivedAtHash(h);
if (this.urlStack.length == 0 || this.urlStack.peek().url != h) {
this.urlStack.push({ url: h, onPop: () => { } });
this.pushState(h)
}
else {
Ticker.dbg("setHash.. ignoring same hash");
}
if (t !== null) {
if (t)
document.title = t + " - " + Runtime.appName;
else
document.title = Runtime.appName;
}
}
private pushModalHash(s: string, f: () => void) {
var hash = '#modal-' + s;
if (this.urlStack.length > 0 && this.urlStack.peek().url == hash) {
this.urlStack.pop();
}
this.urlStack.push({ url: hash, onPop: f });
this.pushState(this.topHash())
Screen.arrivedAtHash(hash); // inform the WAB shell there is a modal dialog
}
private popModalHash(s: string) {
Ticker.dbg("popModal " + s);
var hash = '#modal-' + s;
var index = -1;
for (var i = 0; i < this.urlStack.length; i++) {
if (this.urlStack[i].url == hash) {
index = i;
this.urlStack[i].onPop = null;
break;
}
}
if (index < 0) return;
this.popBack(this.urlStack.length - index)
}
private popBack(toPop = 1) {
Ticker.dbg("historyMgr: popBack " + toPop);
var popped = this.urlStack.splice(this.urlStack.length - toPop, toPop);
var seenNonModal = false
for (var i = popped.length - 1; i >= 0; i--) {
var entry = popped[i];
if (!/#modal-/.test(entry.url))
seenNonModal = true
if (entry.onPop) {
var f = entry.onPop;
entry.onPop = null;
f();
}
}
// inform the WAB shell whether the current url is the top page
var last = this.urlStack.peek()
Screen.arrivedAtHash(last ? last.url : "#")
if (seenNonModal)
this.dispatch(this.topHash())
else
this.hashReloaded()
}
public hashReloaded()
{
this.pushState(this.topHash())
}
private topHash()
{
for (var i = this.urlStack.length - 1; i >= 0; i--) {
var t = this.urlStack[i]
if (t && !/^#modal-/.test(t.url)) return t.url
}
return "#"
}
private dispatch(h:string)
{
Util.log("dispatch: " + h)
ModalDialog.dismissCurrent()
this.pushState(h)
this.reload(h)
}
public initialHash()
{
this.setHashHandler(HistoryMgr.windowHash(), true);
if (this.lastSetHash == "" && !this.replaceNext) {
// make sure we get a pop event
this.pushState(null)
this.replaceNext = true;
this.showStartScreen();
}
}
public showStartScreen()
{
}
public reload(hash:string)
{
}
public confirmLoadHash()
{
Ticker.dbg("History.confirmLoadHash");
this.replaceNext = false;
}
public clearModalSuffix(): number {
for (var i = 0; i < this.urlStack.length; i++) {
if (/^#modal-/.test(this.urlStack[i].url)) {
var removed = this.urlStack.splice(i, this.urlStack.length - i);
return removed.length;
}
}
return 0;
}
public clearModalStack()
{
var n = this.clearModalSuffix();
// this.popBack(n)
}
private numPush = 1;
public commandHandler(h:string)
{
}
public popState(event:any) {
Ticker.dbg("popState: " + event.state);
// exiting the app?
if (this.urlStack.length == 1) {
window.history.back()
return
}
var h = HistoryMgr.windowHash()
if (/^#cmd:/.test(h)) {
var nh = this.topHash()
this.whenSafe(() => {
this.pushState(nh)
this.commandHandler(h)
})
} else {
this.back();
}
}
public back()
{
this.whenSafe(() => this.popBack())
}
private whenSafe(f:()=>void)
{
if (ProgressOverlay.isActive())
Util.setTimeout(500, () => this.whenSafe(f))
else
f();
}
private setHashHandler(h:string, replace:boolean)
{
this.whenSafe(() => {
if (!h) h = "#"
if (!/^#/.test(h)) h = "#" + h
if (replace) { // try to pop history until h is found
for (var i = this.urlStack.length - 1; i >= 0; --i) {
if (this.urlStack[i].url == h) {
if (i == this.urlStack.length - 1) { // nothing to do.
Util.log("replaced hash already current, skipping " + h)
return;
}
else {
Util.log("found hash to replace in stack, popping " + h)
this.popBack(this.urlStack.length - 1 - i);
return;
}
}
}
}
this.dispatch(h)
})
}
public scriptOrHub(h:string[])
{
var id = h.filter((s) => /^id=/.test(s))[0]
if (id) {
// HTML.showProgressNotification("script not installed yet");
var scr = id.replace(/^id=/, "script:")
if (h[0] == "list")
Util.setHash(h[0] + ":" + h[1] + ":" + scr, true)
else
Util.setHash(scr, true)
} else {
Util.setHash(TDev.hubHash, true)
}
}
public hashChange()
{
Util.log("hashChange: " + HistoryMgr.windowHash())
}
}
export class Screen
{
public init() {}
public hide() {}
public screenId() { return ""; }
public loadHash(h:string[]) {}
public keyDown(e:KeyboardEvent):boolean { return false; }
public applySizes() {}
static pushModalHash = (s:string, removeCb:()=>void) => {};
static popModalHash = (s: string) => { };
static arrivedAtHash = (s:string) => {};
public syncDone() {}
public hashReloaded() {}
private paneState = 0;
public autoHide() { return SizeMgr.portraitMode; }
public sidePaneVisible() { return !this.autoHide() || this.sidePane().style.display == "block"; }
public sidePaneVisibleNow() { return !this.autoHide() || this.paneState > 0; }
public updateSidePane() {
var pane = this.sidePane();
if (!this.autoHide()) {
pane.style.display = "block";
pane.style.opacity = "1";
} else if (this.autoHide() && this.paneState < 0) {
pane.style.display = "none";
}
elt("root").setFlag("pane-hidden", pane.style.display == "none");
}
public showSidePane()
{
if (!this.autoHide() || this.paneState > 0) return;
Screen.pushModalHash("side", () => this.hideSidePane());
elt("root").setFlag("pane-hidden", false);
this.paneState = 1;
var pane = this.sidePane();
pane.style.display = "block";
pane.style.opacity = "1";
Util.showRightPanel(pane);
}
public sidePane():HTMLElement { return null; }
public hideSidePane()
{
var pane = this.sidePane();
if (!this.autoHide()) {
pane.style.display = "block";
pane.style.opacity = "1";
return;
}
if (this.paneState < 0) return;
Screen.popModalHash("side");
elt("root").setFlag("pane-hidden", true);
this.paneState = -1;
Util.hidePopup(pane, () => {
if (this.paneState < 0 && this.autoHide())
pane.style.display = "none";
});
}
public hashCommandHandler(h:string)
{
}
}
export class KeyboardMgr
{
static instance = new KeyboardMgr();
private handlers:any = {};
public register(key:string, cb:(e:KeyboardEvent)=>boolean)
{
if (/^-/.test(key)) return;
this.handlers[key] = cb;
}
public saveState()
{
return Util.flatClone(this.handlers);
}
public loadState(s:any)
{
if (!Util.check(!!s)) return;
this.handlers = s;
}
public triggerKey(name:string)
{
var h = this.handlers[name];
if (h && h.isBtnShortcut)
h();
}
static triggerClick(e:HTMLElement)
{
var h = <ClickHandler>(<any>e).clickHandler;
if (!!h) {
var active = <HTMLElement> document.activeElement;
if (!!active && !!active.blur) active.blur();
e.setFlag("active", true);
Util.setTimeout(150, () => { e.setFlag("active", false) });
h.fireClick(<any>{});
}
}
static elementVisible(e:HTMLElement)
{
while (e) {
if (e.id == "root") return true;
if (window.getComputedStyle(e).display == "none") return false;
e = <HTMLElement> e.parentNode;
}
return false;
}
public btnShortcut(e:HTMLElement, key:string)
{
if (!key) return;
var handle = () => {
if (KeyboardMgr.elementVisible(e)) {
KeyboardMgr.triggerClick(e);
return true;
}
return false;
}
(<any>handle).isBtnShortcut = true;
if (!/^ /.test(key))
key.split(", ").forEach((k) => this.register(k, handle));
e.title = key.replace(/(^| )-/g, "");
}
private previousStoppedEvent:KeyboardEvent;
public keyUp(e:KeyboardEvent) : any
{
Util.normalizeKeyEvent(e);
if (/-(Control|Alt)$/.test(e.keyName))
return true;
var h = this.handlers["*keyup*"];
if (h) {
Ticker.dbg("keyUp.run");
if (h(e)) return true;
}
}
public processKey(e:KeyboardEvent) : any
{
Util.normalizeKeyEvent(e);
if (/-(Control|Alt)$/.test(e.keyName))
return true;
if (Browser.isGecko) {
var isRepeated =
e.type == "keypress" &&
this.previousStoppedEvent &&
this.previousStoppedEvent.type == "keydown";
this.previousStoppedEvent = null;
if (isRepeated)
return e.stopIt();
}
if (this.keyHandler(e)) {
if (Browser.isGecko)
this.previousStoppedEvent = e;
return e.stopIt();
}
}
public attach(inp:HTMLInputElement)
{
inp.onkeydown = Util.catchErrors("textboxKey", (e:KeyboardEvent) => {
e.fromTextBox = true;
return this.processKey(e);
});
}
private keyHandler(e:KeyboardEvent) : boolean
{
if (ProgressOverlay.isKeyboardBlocked()) return true;
if (e.keyName == "Ctrl-Control") return false;
if (/^(Del|Ctrl-[CXVA]|Shift-(Left|Right)|(Ctrl|Shift)-(Ins|Del))$/.test(e.keyName) && e.fromTextBox) return false;
if (TDev.dbg && e.keyName) tick(Ticks.mainKeyEvent)
h = this.handlers["*keydown*"];
if (h) {
if (TDev.dbg && e.keyName)
Ticker.dbg("keyHandler.preCatchAll." + e.keyName)
if (h(e)) return true;
}
var h = this.handlers[e.keyName];
if (h) {
if (TDev.dbg && e.keyName)
Ticker.dbg("keyHandler.byName." + e.keyName);
if (h(e)) return true;
}
h = this.handlers["***"];
if (h) {
if (TDev.dbg && e.keyName)
Ticker.dbg("keyHandler.catchAll." + e.keyName)
if (h(e)) return true;
}
if (currentScreen) {
if (TDev.dbg && e.keyName)
Ticker.dbg("keyHandler.currentScreen." + e.keyName)
if (currentScreen.keyDown(e)) return true;
}
if (e.keyCode == 8 && !e.fromTextBox)
return true;
return false;
}
}
} | the_stack |
import React from "react";
import {
OrgComponent,
OrgComponentProps,
RouterTree,
RouterNode,
} from "@ui_types";
import { Route, Switch, Redirect, RouteComponentProps } from "react-router-dom";
import * as R from "ramda";
import * as ui from "@ui";
import { Model } from "@core/types";
const getRouterTree = (): RouterTree => [
{
routerPath: "/welcome",
component: ui.Welcome,
},
{
routerPath: "/new-app",
component: ui.NewApp,
},
{
routerPath: "/new-block",
component: ui.NewBlock,
},
{
routerPath: "/new-team",
component: ui.NewTeam,
},
// Org-level invites
...getInviteRoutes(),
// Org-level cli keys
...getCliKeyRoutes(),
// Apps
{
routerPath: "/apps/:appId",
component: ui.AppContainer,
redirect: envParentRedirectFn,
tree: getEnvParentTree("app"),
},
// Blocks
{
routerPath: "/blocks/:blockId",
component: ui.BlockContainer,
redirect: envParentRedirectFn,
tree: getEnvParentTree("block"),
},
// Org Users
{
routerPath: "/orgUsers/:userId",
component: ui.UserContainer,
redirect: userRedirectFn,
tree: getUserTree("orgUser"),
},
// teams
{
routerPath: "/teams/:groupId",
component: ui.TeamContainer,
redirect: getGroupRedirectFn("orgUser"),
tree: [
{
routerPath: "/members-add",
component: ui.TeamAddMembers,
},
{
routerPath: "/members",
component: ui.TeamMembers,
},
{
routerPath: "/apps-add",
component: ui.TeamAddApps,
},
{
routerPath: "/apps",
component: ui.TeamApps,
},
{
routerPath: "/settings",
component: ui.GroupSettings,
},
],
},
// Cli Users
{
routerPath: "/cliUsers/:userId",
component: ui.UserContainer,
redirect: userRedirectFn,
tree: getUserTree("cliUser"),
},
// My Org
{
routerPath: "/my-org",
component: ui.MyOrgContainer,
tree: [
{
routerPath: "/settings",
component: ui.OrgSettings,
},
{
routerPath: "/environment-settings/environment-role-form/:editingId?",
component: ui.EnvironmentRoleForm,
},
{
routerPath: "/environment-settings",
component: ui.ManageOrgEnvironmentRoles,
},
{
routerPath: "/firewall",
component: ui.OrgFirewall,
},
// SAML Routes
{
routerPath: "/sso/new-saml/create",
component: ui.SamlCreateStep,
},
{
routerPath: "/sso/new-saml/sp/:providerId",
component: ui.SamlSPStep,
},
{
routerPath: "/sso/new-saml/idp/:providerId",
component: ui.SamlIDPStep,
},
{
routerPath: "/sso/new-saml/success/:providerId",
component: ui.SamlSuccess,
},
{
routerPath: "/sso/saml/:providerId",
component: ui.SamlForm,
},
// SCIM Routes
{
routerPath: "/sso/scim/success/:providerId/:authSecret?",
component: ui.ScimSuccess,
},
{
routerPath: "/sso/scim/:providerId?",
component: ui.ScimForm,
},
{
routerPath: "/sso",
component: ui.SSOSettings,
},
// remaining org routes
{
routerPath: `/billing`,
component: ui.BillingUI,
},
{
routerPath: `/logs/:logManagerStateBs58?`,
component: ui.LogManager,
},
{
routerPath: `/recovery-key`,
component: ui.ManageRecoveryKey,
},
{
routerPath: "/archive",
component: ui.OrgArchiveV1,
},
],
},
// Org Devices
{
routerPath: `/devices/:userId?`,
component: ui.OrgDevices,
},
// Fallback Routes
{
routerPath: "/no-apps-or-blocks",
component: ui.NoAppsOrBlocks,
},
{
routerPath: "/not-found",
component: ui.ObjectNotFound,
},
];
const getInviteRoutes = (): RouterTree => [
{
routerPath: "/invite-users/form/:editIndex?",
component: ui.InviteForm,
},
{
routerPath: "/invite-users/generated",
component: ui.GeneratedInvites,
},
{
routerPath: "/invite-users",
component: ui.InviteUsers,
},
];
const getCliKeyRoutes = (): RouterTree => [
{
routerPath: "/new-cli-key/generated",
component: ui.GeneratedCliUsers,
},
{
routerPath: "/new-cli-key",
component: ui.NewCliUser,
},
];
const getEnvParentTree = (envParentType: Model.EnvParent["type"]): RouterTree =>
[
{
routerPath: "/environments/:environmentId?/:subRoute?/:subEnvironmentId?",
component: ui.EnvManager,
},
getCollaboratorNode(envParentType, "orgUser"),
getCollaboratorNode(envParentType, "cliUser"),
envParentType == "app"
? {
routerPath: "/envkeys",
component: ui.AppEnvkeysContainer,
}
: undefined,
envParentType == "app"
? {
routerPath: "/firewall",
component: ui.AppFirewall,
}
: undefined,
envParentType == "block"
? {
routerPath: "/apps-add",
component: ui.BlockAddApps,
}
: undefined,
envParentType == "block"
? {
routerPath: "/apps",
component: ui.BlockApps,
}
: undefined,
{
routerPath: "/settings/environment-role-form/:editingId?",
component: ui.EnvironmentRoleForm,
},
{
routerPath: "/settings",
component: {
app: ui.AppSettings,
block: ui.BlockSettings,
}[envParentType],
},
{
routerPath: "/versions/:environmentOrLocalsUserId?/:filterEntryKeys?",
component: ui.Versions,
},
{
routerPath: `/logs/:logManagerStateBs58?`,
component: ui.LogManager,
},
].filter((node): node is RouterNode => Boolean(node));
const getUserTree = (
userType: (Model.OrgUser | Model.CliUser)["type"]
): RouterTree => [
{
routerPath: "/apps-add",
component: ui.UserAddApps,
},
{
component: ui.UserApps,
routerPath: `/apps/:appId?`,
},
...(userType == "orgUser"
? [
{
routerPath: "/teams-add",
component: ui.UserAddTeams,
},
{
component: ui.UserTeams,
routerPath: `/teams/:userGroupId?`,
},
]
: []),
{
component: ui.UserBlocks,
routerPath: `/blocks/:blockId?`,
},
{
routerPath: "/devices",
component: ui.UserDevices,
},
{
routerPath: "/settings",
component: {
orgUser: ui.OrgUserSettings,
cliUser: ui.CliUserSettings,
}[userType],
},
{
routerPath: `/logs/:logManagerStateBs58?`,
component: ui.LogManager,
},
];
const getCollaboratorNode = (
envParentType: Model.EnvParent["type"],
userType: (Model.OrgUser | Model.CliUser)["type"]
): RouterNode => ({
routerPath: `/${
{
orgUser: "collaborators",
cliUser: "cli-keys",
}[userType]
}`,
component: {
orgUser: {
app: ui.AppCollaboratorsContainer,
block: ui.BlockOrgUsers,
},
cliUser: {
app: ui.AppCliUsersContainer,
block: ui.BlockCliUsers,
},
}[userType][envParentType],
tree: [
...(envParentType == "app" && userType == "orgUser"
? [
{
routerPath: "/list/add",
component: ui.AppAddOrgUsersContainer,
tree: [
{ routerPath: "/existing", component: ui.AppAddOrgUsers },
...getInviteRoutes(),
],
},
{
routerPath: "/list",
component: ui.AppOrgUsers,
},
{
routerPath: "/teams",
component: ui.AppTeams,
tree: [
{
routerPath: "/add",
component: ui.AppAddTeams,
},
],
},
]
: []),
...(envParentType == "app" && userType == "cliUser"
? [
{
routerPath: "/list/add",
component: ui.AppAddCliUsersContainer,
tree: [
{ routerPath: "/existing", component: ui.AppAddCliUsers },
...getCliKeyRoutes(),
],
},
{
routerPath: "/list",
component: ui.AppCliUsers,
},
]
: []),
],
});
type Props = {
nested?: true;
routerTree?: RouterTree;
};
export const OrgRoutes: OrgComponent<{}, Props> = (componentProps) => {
const routes = (
routesProps: OrgComponentProps<{}, { routerTree?: RouterTree }>
): Route[] => {
const routerTree = routesProps.routerTree ?? getRouterTree();
return R.flatten(
routerTree
.map((node, i) => {
const path =
(routesProps.baseRouterPath ?? componentProps.match.path ?? "") +
(node.routerPath ?? "");
if (node.routerPath) {
return (
<Route
key={i}
path={path}
render={getRenderFn(componentProps, routesProps, node, path)}
/>
);
} else if (node.tree) {
return routes({
...routesProps,
routerTree: node.tree,
baseRouterPath: path,
});
}
})
.filter(Boolean)
) as Route[];
};
return (
<div>
<Switch>
{routes(componentProps)}
{componentProps.nested ? (
""
) : (
<Redirect to={componentProps.orgRoute("/not-found")} />
)}
</Switch>
</div>
);
};
const getRenderFn =
(
componentProps: OrgComponentProps<{ orgId: string }, Props>,
routesProps: OrgComponentProps,
node: RouterNode,
path: string
) =>
(routeProps: RouteComponentProps<{ orgId: string }>) => {
const childProps = {
...routesProps,
...routeProps,
baseRouterPath: path,
routeParams: {
...componentProps.routeParams,
...(routeProps.match?.params ?? {}),
},
routerTree: node.tree ?? [],
};
if (node.redirect) {
const redirect = node.redirect(childProps);
if (redirect) {
return <Redirect to={redirect} />;
}
}
if (!node.component) {
return <OrgRoutes {...childProps} nested={true} />;
}
return routesProps.ui.loadedAccountId ? (
<div>
{React.createElement(node.component!, childProps)}
{node.tree ? <OrgRoutes {...childProps} nested={true} /> : ""}
</div>
) : (
<div></div>
);
};
const envParentRedirectFn = (
props: OrgComponentProps<{ appId: string } | { blockId: string }>
) => {
const { graph } = props.core;
let envParentId: string;
let envParentType: Model.EnvParent["type"];
if ("appId" in props.routeParams) {
envParentId = props.routeParams.appId;
envParentType = "app";
} else {
envParentId = props.routeParams.blockId;
envParentType = "block";
}
const envParent = graph[envParentId] as Model.EnvParent | undefined;
if (!envParent) {
if (props.ui.justDeletedObjectId == envParentId) {
props.setUiState(R.omit(["justDeletedObjectId"], props.ui));
} else {
alert(`This ${envParentType} has been removed or you have lost access.`);
}
return props.orgRoute("");
}
return false;
};
const getGroupRedirectFn =
(objectType: Model.Group["objectType"]) =>
(props: OrgComponentProps<{ groupId: string }>) => {
const { graph } = props.core;
const groupId = props.routeParams.groupId;
const group = graph[groupId] as Model.Group;
if (!group) {
if (props.ui.justDeletedObjectId == groupId) {
props.setUiState(R.omit(["justDeletedObjectId"], props.ui));
} else {
alert(`This ${objectType} has been removed or you have lost access.`);
}
return props.orgRoute("");
}
return false;
};
const userRedirectFn = (props: OrgComponentProps<{ userId: string }>) => {
if (props.ui.justRegeneratedInviteForUserId == props.routeParams.userId) {
return false;
}
const { graph } = props.core;
const user = graph[props.routeParams.userId] as
| Model.OrgUser
| Model.CliUser
| undefined;
if (!user || user.deactivatedAt) {
return props.orgRoute("");
}
return false;
}; | the_stack |
import {
IconFile,
IconFlowChartStroked,
IconServerStroked,
IconTemplateStroked,
} from "@douyinfe/semi-icons";
import { Tree, Typography } from "@douyinfe/semi-ui";
import { CanvasChart, MetricStatus } from "@src/components";
import { ChartStatus, ExplainResult, UnitEnum } from "@src/models";
import { ChartStore } from "@src/stores";
import { formatter } from "@src/utils";
import { reaction } from "mobx";
import React, { useEffect, useState } from "react";
const Text = Typography.Text;
interface ExplainStatsViewProps {
chartId: string;
}
const ExplainStatsView: React.FC<ExplainStatsViewProps> = (
props: ExplainStatsViewProps
) => {
const { chartId } = props;
const [state, setState] = useState<ExplainResult>();
const renderCost = (cost: any, total: any) => {
const percent = (cost * 100.0) / total;
let type: any = "success";
if (percent > 50) {
type = "danger";
} else if (percent > 30) {
type = "warning";
}
return <Text type={type}>{formatter(cost, UnitEnum.Nanoseconds)}</Text>;
};
const buildCollectValueStats = (total: any, key: string, stats: any) => {
let children: any = [];
const loadNodes = {
label: <Text strong>Collect Tag Values(Async)</Text>,
key: `${key}collect tag values`,
children: children,
};
for (let groupgTagKey of Object.keys(stats)) {
const cost = stats[groupgTagKey];
children.push({
label: (
<span>
<Text link strong>
{groupgTagKey}
</Text>
: {renderCost(cost, total)}
</span>
),
key: `${key + groupgTagKey}cost`,
// icon: <HddOutlined />,
});
}
return loadNodes;
};
const buildLoadStats = (total: any, key: string, loadStats: any) => {
let children: any = [];
const loadNodes = {
label: <Text strong>Load Data(Async)</Text>,
key: `${key}load data`,
children: children,
};
for (let id of Object.keys(loadStats)) {
const stats = loadStats[id];
children.push({
label: (
<span>
<Text strong link>
{id}
</Text>
: [ Count: <Text link>{formatter(stats.count, UnitEnum.None)}</Text>
, Total Cost: {renderCost(stats.totalCost, total)}, Min:{" "}
{renderCost(stats.min, total)}, Max: {renderCost(stats.min, total)},
Num. Of Series:{" "}
<Text link>{formatter(stats.series, UnitEnum.None)}</Text> ]
</span>
),
key: `${key + id}cost`,
icon: <IconFile />,
});
}
return loadNodes;
};
const buildShardNodes = (total: any, key: string, shards: any) => {
let children: any = [];
const shardNodes = {
label: <Text strong>Shards(Async)</Text>,
key: `${key}shards`,
children: children,
};
for (let shardID of Object.keys(shards)) {
const shardStats = shards[shardID];
let nodeStats = {
label: (
<span>
<Text strong link>
{shardID}{" "}
</Text>
: Series Filtering: [ Cost:{" "}
{renderCost(shardStats.seriesFilterCost, total)}, Num. Of Series:{" "}
<Text link>{formatter(shardStats.numOfSeries, UnitEnum.None)}</Text>{" "}
]
</span>
),
key: key + shardID,
icon: <IconFlowChartStroked />,
children: [
{
label: (
<span>
<Text strong> Memory Filtering</Text>:{" "}
{renderCost(shardStats.memFilterCost, total)}
</span>
),
key: `${key + shardID}memory filtering`,
},
{
label: (
<span>
<Text strong>KV Store Filtering:</Text>{" "}
{renderCost(shardStats.kvFilterCost, total)}
</span>
),
key: `${key + shardID}kv store filtering`,
},
{
label: (
<span>
<Text strong>Grouping</Text>:{" "}
{renderCost(shardStats.groupingCost, total)}
</span>
),
key: `${key + shardID}Grouping`,
},
],
};
if (shardStats.groupBuildStats) {
nodeStats.children.push({
label: (
<span>
<Text strong>Group Build(Async)</Text>: [ Count:{" "}
<Text link>
{formatter(shardStats.groupBuildStats.count, UnitEnum.None)}
</Text>
, Total Cost:{" "}
{renderCost(shardStats.groupBuildStats.totalCost, total)}, Min:{" "}
{renderCost(shardStats.groupBuildStats.min, total)}, Max:{" "}
{renderCost(shardStats.groupBuildStats.min, total)} ]
</span>
),
key: `${key + shardID}group build`,
});
}
children.push(nodeStats);
if (shardStats.scanStats) {
nodeStats.children.push(
buildLoadStats(total, key + shardID, shardStats.scanStats)
);
}
}
return shardNodes;
};
const buildStorageNodes = (parent: string, total: any, storageNodes: any) => {
let children: any = [];
let storageNode = {
label: <Text strong>Storage Nodes</Text>,
key: `${parent}-Storage-Nodes`,
children: children,
};
for (let key of Object.keys(storageNodes)) {
const storageNodeStats = storageNodes[key];
let nodeStats = {
label: (
<span>
<Text strong link>
{key}
</Text>
: [ Cost: {renderCost(storageNodeStats.totalCost, total)}, Network
Payload:{" "}
<Text link>
{" "}
{formatter(storageNodeStats.netPayload, UnitEnum.Bytes)})
</Text>{" "}
]
</span>
),
key: `${parent}-Storage-Nodes-${key}`,
icon: <IconServerStroked />,
children: [
{
label: (
<span>
<Text strong>Execute Plan</Text>:{" "}
{renderCost(storageNodeStats.planCost, total)}
</span>
),
key: `${parent}-${key}plan-execute`,
},
{
label: (
<span>
<Text strong>Tag Metadata Filtering</Text>:{" "}
{renderCost(storageNodeStats.tagFilterCost, total)}
</span>
),
key: `${parent}-${key}tag-filtering`,
},
],
};
children.push(nodeStats);
if (storageNodeStats.collectTagValuesStats) {
nodeStats.children.push(
buildCollectValueStats(
total,
`${parent}-${key}`,
storageNodeStats.collectTagValuesStats
)
);
}
if (storageNodeStats.shards) {
nodeStats.children.push(
buildShardNodes(total, `${parent}-${key}`, storageNodeStats.shards)
);
}
}
return storageNode;
};
const buildIntermediateBrokers = (total: any, brokerNodes: any) => {
let children: any = [];
let IntermediateNode = {
label: <Text strong>Intermediate Nodes</Text>,
key: "Intermediate-Nodes",
children: children,
};
for (let key of Object.keys(brokerNodes)) {
const brokerNodeStats = brokerNodes[key];
const nodeStats = {
label: (
<span>
<Text strong link>
{key}
</Text>
: [ Waiting: {renderCost(brokerNodeStats.waitCost, total)}, Cost:{" "}
{renderCost(brokerNodeStats.totalCost, total)}, Network Payload:{" "}
<Text link>
{" "}
{formatter(brokerNodeStats.netPayload, UnitEnum.Bytes)})
</Text>{" "}
]
</span>
),
icon: <IconTemplateStroked />,
key: `Intermediate-${key}`,
children: [] as any,
};
children.push(nodeStats);
if (brokerNodeStats.storageNodes) {
nodeStats.children.push(
buildStorageNodes(key, total, brokerNodeStats.storageNodes)
);
}
}
console.log("IntermediateNode", IntermediateNode);
return IntermediateNode;
};
const buildStatsData = () => {
if (!state) {
return [];
}
let root = {
label: (
<>
<Text strong>Root</Text>:{" "}
<Text link>{formatter(state.totalCost, UnitEnum.Nanoseconds)}</Text>
</>
),
key: "Root",
children: [
{
label: (
<span>
<Text strong>Execute Plan</Text> :{" "}
{renderCost(state.planCost, state.totalCost)}
</span>
),
key: "Execute Plan",
},
{
label: (
<span>
<Text strong>Waiting Response</Text>:{" "}
{renderCost(state.waitCost, state.totalCost)}
</span>
),
key: "Waiting Intermediate Response",
},
{
label: (
<span>
<Text strong>Expression Eval</Text>:{" "}
{renderCost(state.expressCost, state.totalCost)}
</span>
),
key: "Expression Eval",
},
],
};
if (state.brokerNodes) {
root.children.push(
buildIntermediateBrokers(state.totalCost, state.brokerNodes)
);
}
if (state.storageNodes) {
root.children.push(
buildStorageNodes("root", state.totalCost, state.storageNodes)
);
}
return [root];
};
useEffect(() => {
const disposer = [
reaction(
() => ChartStore.chartStatusMap.get(chartId),
(s: ChartStatus | undefined) => {
if (!s || s == ChartStatus.Loading) {
return;
}
const state = ChartStore.stateCache.get(chartId);
setState(state);
}
),
];
return () => {
disposer.forEach((d) => d());
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
console.log("buildStatsData", buildStatsData());
return (
<>
<MetricStatus chartId={chartId} showMsg />
<Tree
expandAll
// icon
defaultExpandAll
treeData={buildStatsData()}
style={{ display: state ? "block" : "none" }}
/>
<div style={{ display: !state ? "block" : "none" }}>
<CanvasChart chartId={chartId} height={300} />
</div>
</>
);
};
export default ExplainStatsView; | the_stack |
type AnyTable = Record<any, any>;
// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/consistent-type-definitions
type AnyNotNil = {};
/**
* Indicates a type is a language extension provided by TypescriptToLua.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TBrand A string used to uniquely identify the language extension type
*/
declare type LuaExtension<TBrand extends string> = { [T in TBrand]: { readonly __luaExtensionSymbol: unique symbol } };
/**
* Returns multiple values from a function, by wrapping them in a LuaMultiReturn tuple.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param T A tuple type with each element type representing a return value's type.
* @param values Return values.
*/
declare const $multi: (<T extends any[]>(...values: T) => LuaMultiReturn<T>) & LuaExtension<"__luaMultiFunctionBrand">;
/**
* Represents multiple return values as a tuple.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param T A tuple type with each element type representing a return value's type.
*/
declare type LuaMultiReturn<T extends any[]> = T & LuaExtension<"__luaMultiReturnBrand">;
/**
* Creates a Lua-style numeric for loop (for i=start,limit,step) when used in for...of. Not valid in any other context.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param start The first number in the sequence to iterate over.
* @param limit The last number in the sequence to iterate over.
* @param step The amount to increment each iteration.
*/
declare const $range: ((start: number, limit: number, step?: number) => Iterable<number>) &
LuaExtension<"__luaRangeFunctionBrand">;
/**
* Transpiles to the global vararg (`...`)
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*/
declare const $vararg: string[] & LuaExtension<"__luaVarargConstantBrand">;
/**
* Represents a Lua-style iterator which is returned from a LuaIterable.
* For simple iterators (with no state), this is just a function.
* For complex iterators that use a state, this is a LuaMultiReturn tuple containing a function, the state, and the initial value to pass to the function.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param state The state object returned from the LuaIterable.
* @param lastValue The last value returned from this function. If iterating LuaMultiReturn values, this is the first value of the tuple.
*/
declare type LuaIterator<TValue, TState> = TState extends undefined
? (this: void) => TValue
: LuaMultiReturn<
[
(
this: void,
state: TState,
lastValue: TValue extends LuaMultiReturn<infer TTuple> ? TTuple[0] : TValue
) => TValue,
TState,
TValue extends LuaMultiReturn<infer TTuple> ? TTuple[0] : TValue
]
>;
/**
* Represents a Lua-style iteratable which iterates single values in a `for...in` loop (ex. `for x in iter() do`).
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TValue The type of value returned each iteration. If this is LuaMultiReturn, multiple values will be returned each iteration.
* @param TState The type of the state value passed back to the iterator function each iteration.
*/
declare type LuaIterable<TValue, TState = undefined> = Iterable<TValue> &
LuaIterator<TValue, TState> &
LuaExtension<"__luaIterableBrand">;
/**
* Represents an object that can be iterated with pairs()
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TKey The type of the key returned each iteration.
* @param TValue The type of the value returned each iteration.
*/
declare type LuaPairsIterable<TKey extends AnyNotNil, TValue> = Iterable<[TKey, TValue]> &
LuaExtension<"__luaPairsIterableBrand">;
/**
* Calls to functions with this type are translated to `left + right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaAddition<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaAdditionBrand">;
/**
* Calls to methods with this type are translated to `left + right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaAdditionMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaAdditionMethodBrand">;
/**
* Calls to functions with this type are translated to `left - right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaSubtraction<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaSubtractionBrand">;
/**
* Calls to methods with this type are translated to `left - right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaSubtractionMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaSubtractionMethodBrand">;
/**
* Calls to functions with this type are translated to `left * right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaMultiplication<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaMultiplicationBrand">;
/**
* Calls to methods with this type are translated to `left * right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaMultiplicationMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaMultiplicationMethodBrand">;
/**
* Calls to functions with this type are translated to `left / right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaDivision<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaDivisionBrand">;
/**
* Calls to methods with this type are translated to `left / right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaDivisionMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaDivisionMethodBrand">;
/**
* Calls to functions with this type are translated to `left % right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaModulo<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaModuloBrand">;
/**
* Calls to methods with this type are translated to `left % right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaModuloMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"__luaModuloMethodBrand">;
/**
* Calls to functions with this type are translated to `left ^ right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaPower<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaPowerBrand">;
/**
* Calls to methods with this type are translated to `left ^ right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaPowerMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"__luaPowerMethodBrand">;
/**
* Calls to functions with this type are translated to `left // right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaFloorDivision<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaFloorDivisionBrand">;
/**
* Calls to methods with this type are translated to `left // right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaFloorDivisionMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaFloorDivisionMethodBrand">;
/**
* Calls to functions with this type are translated to `left & right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseAnd<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseAndBrand">;
/**
* Calls to methods with this type are translated to `left & right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseAndMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseAndMethodBrand">;
/**
* Calls to functions with this type are translated to `left | right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseOr<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseOrBrand">;
/**
* Calls to methods with this type are translated to `left | right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseOrMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseOrMethodBrand">;
/**
* Calls to functions with this type are translated to `left ~ right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseExclusiveOr<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseExclusiveOrBrand">;
/**
* Calls to methods with this type are translated to `left ~ right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseExclusiveOrMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseExclusiveOrMethodBrand">;
/**
* Calls to functions with this type are translated to `left << right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseLeftShift<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseLeftShiftBrand">;
/**
* Calls to methods with this type are translated to `left << right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseLeftShiftMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseLeftShiftMethodBrand">;
/**
* Calls to functions with this type are translated to `left >> right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseRightShift<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseRightShiftBrand">;
/**
* Calls to methods with this type are translated to `left >> right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseRightShiftMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaBitwiseRightShiftMethodBrand">;
/**
* Calls to functions with this type are translated to `left .. right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaConcat<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaConcatBrand">;
/**
* Calls to methods with this type are translated to `left .. right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaConcatMethod<TRight, TReturn> = ((right: TRight) => TReturn) & LuaExtension<"__luaConcatMethodBrand">;
/**
* Calls to functions with this type are translated to `left < right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaLessThan<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaLessThanBrand">;
/**
* Calls to methods with this type are translated to `left < right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaLessThanMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaLessThanMethodBrand">;
/**
* Calls to functions with this type are translated to `left > right`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TLeft The type of the left-hand-side of the operation.
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaGreaterThan<TLeft, TRight, TReturn> = ((left: TLeft, right: TRight) => TReturn) &
LuaExtension<"__luaGreaterThanBrand">;
/**
* Calls to methods with this type are translated to `left > right`, where `left` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TRight The type of the right-hand-side of the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaGreaterThanMethod<TRight, TReturn> = ((right: TRight) => TReturn) &
LuaExtension<"__luaGreaterThanMethodBrand">;
/**
* Calls to functions with this type are translated to `-operand`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TOperand The type of the value in the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaNegation<TOperand, TReturn> = ((operand: TOperand) => TReturn) & LuaExtension<"__luaNegationBrand">;
/**
* Calls to method with this type are translated to `-operand`, where `operand` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaNegationMethod<TReturn> = (() => TReturn) & LuaExtension<"__luaNegationMethodBrand">;
/**
* Calls to functions with this type are translated to `~operand`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TOperand The type of the value in the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseNot<TOperand, TReturn> = ((operand: TOperand) => TReturn) & LuaExtension<"__luaBitwiseNotBrand">;
/**
* Calls to method with this type are translated to `~operand`, where `operand` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaBitwiseNotMethod<TReturn> = (() => TReturn) & LuaExtension<"__luaBitwiseNotMethodBrand">;
/**
* Calls to functions with this type are translated to `#operand`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TOperand The type of the value in the operation.
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaLength<TOperand, TReturn> = ((operand: TOperand) => TReturn) & LuaExtension<"__luaLengthBrand">;
/**
* Calls to method with this type are translated to `#operand`, where `operand` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TReturn The resulting (return) type of the operation.
*/
declare type LuaLengthMethod<TReturn> = (() => TReturn) & LuaExtension<"__luaLengthMethodBrand">;
/**
* Calls to functions with this type are translated to `table[key]`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TTable The type to access as a Lua table.
* @param TKey The type of the key to use to access the table.
* @param TValue The type of the value stored in the table.
*/
declare type LuaTableGet<TTable extends AnyTable, TKey extends AnyNotNil, TValue> = ((
table: TTable,
key: TKey
) => TValue) &
LuaExtension<"__luaTableGetBrand">;
/**
* Calls to methods with this type are translated to `table[key]`, where `table` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TKey The type of the key to use to access the table.
* @param TValue The type of the value stored in the table.
*/
declare type LuaTableGetMethod<TKey extends AnyNotNil, TValue> = ((key: TKey) => TValue) &
LuaExtension<"__luaTableGetMethodBrand">;
/**
* Calls to functions with this type are translated to `table[key] = value`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TTable The type to access as a Lua table.
* @param TKey The type of the key to use to access the table.
* @param TValue The type of the value to assign to the table.
*/
declare type LuaTableSet<TTable extends AnyTable, TKey extends AnyNotNil, TValue> = ((
table: TTable,
key: TKey,
value: TValue
) => void) &
LuaExtension<"__luaTableSetBrand">;
/**
* Calls to methods with this type are translated to `table[key] = value`, where `table` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TKey The type of the key to use to access the table.
* @param TValue The type of the value to assign to the table.
*/
declare type LuaTableSetMethod<TKey extends AnyNotNil, TValue> = ((key: TKey, value: TValue) => void) &
LuaExtension<"__luaTableSetMethodBrand">;
/**
* Calls to functions with this type are translated to `table[key] ~= nil`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TTable The type to access as a Lua table.
* @param TKey The type of the key to use to access the table.
*/
declare type LuaTableHas<TTable extends AnyTable, TKey extends AnyNotNil> = ((table: TTable, key: TKey) => boolean) &
LuaExtension<"__luaTableHasBrand">;
/**
* Calls to methods with this type are translated to `table[key] ~= nil`, where `table` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TKey The type of the key to use to access the table.
*/
declare type LuaTableHasMethod<TKey extends AnyNotNil> = ((key: TKey) => boolean) &
LuaExtension<"__luaTableHasMethodBrand">;
/**
* Calls to functions with this type are translated to `table[key] = nil`.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TTable The type to access as a Lua table.
* @param TKey The type of the key to use to access the table.
*/
declare type LuaTableDelete<TTable extends AnyTable, TKey extends AnyNotNil> = ((table: TTable, key: TKey) => boolean) &
LuaExtension<"__luaTableDeleteBrand">;
/**
* Calls to methods with this type are translated to `table[key] = nil`, where `table` is the object with the method.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TKey The type of the key to use to access the table.
*/
declare type LuaTableDeleteMethod<TKey extends AnyNotNil> = ((key: TKey) => boolean) &
LuaExtension<"__luaTableDeleteMethodBrand">;
/**
* A convenience type for working directly with a Lua table.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TKey The type of the keys used to access the table.
* @param TValue The type of the values stored in the table.
*/
declare interface LuaTable<TKey extends AnyNotNil = AnyNotNil, TValue = any> extends LuaPairsIterable<TKey, TValue> {
length: LuaLengthMethod<number>;
get: LuaTableGetMethod<TKey, TValue>;
set: LuaTableSetMethod<TKey, TValue>;
has: LuaTableHasMethod<TKey>;
delete: LuaTableDeleteMethod<TKey>;
}
/**
* A convenience type for working directly with a Lua table.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TKey The type of the keys used to access the table.
* @param TValue The type of the values stored in the table.
*/
declare type LuaTableConstructor = (new <TKey extends AnyNotNil = AnyNotNil, TValue = any>() => LuaTable<
TKey,
TValue
>) &
LuaExtension<"__luaTableNewBrand">;
/**
* A convenience type for working directly with a Lua table.
* For more information see: https://typescripttolua.github.io/docs/advanced/language-extensions
*
* @param TKey The type of the keys used to access the table.
* @param TValue The type of the values stored in the table.
*/
declare const LuaTable: LuaTableConstructor; | the_stack |
import Ajv from 'ajv';
import { ValidateFunction } from 'ajv';
import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
import * as migrations from './config-migration/migrations';
import { rootPath } from '../paths';
type Configuration = { [key: string]: any };
type ConfigurationDefaults = { [namespaceId: string]: Configuration };
export type Migration = (
configRootFullPath: string,
configRootTemplateFullPath: string
) => void;
type MigrationFunctions = {
[key: string]: Migration;
};
interface _ConfigurationNamespaceDefinition {
configurationPath: string;
schemaPath: string;
}
type ConfigurationNamespaceDefinition = _ConfigurationNamespaceDefinition & {
[key: string]: string;
};
type ConfigurationNamespaceDefinitions = {
[namespaceId: string]: ConfigurationNamespaceDefinition;
};
interface ConfigurationRoot {
version: number;
configurations: ConfigurationNamespaceDefinitions;
}
const NamespaceTag: string = '$namespace ';
export const ConfigRootSchemaPath: string = path.join(
__dirname,
'schema/configuration-root-schema.json'
);
const ConfigTemplatesDir: string = path.join(__dirname, '../templates/');
const ConfigDir: string = path.join(rootPath(), 'conf/');
interface UnpackedConfigNamespace {
namespace: ConfigurationNamespace;
configPath: string;
}
export function deepCopy(srcObject: any, dstObject: any): any {
for (const [key, value] of Object.entries(srcObject)) {
if (srcObject[key] instanceof Array) {
if (!dstObject[key]) dstObject[key] = [];
deepCopy(srcObject[key], dstObject[key]);
} else if (srcObject[key] instanceof Object) {
if (!dstObject[key]) dstObject[key] = {};
deepCopy(srcObject[key], dstObject[key]);
} else if (
typeof srcObject[key] === typeof dstObject[key] ||
!dstObject[key]
) {
dstObject[key] = value;
}
}
}
export function initiateWithTemplate(templateFile: string, configFile: string) {
fs.copyFileSync(templateFile, configFile);
}
const ajv: Ajv = new Ajv();
export const percentRegexp = new RegExp(/^(\d+)\/(\d+)$/);
export class ConfigurationNamespace {
/**
* This class encapsulates a namespace under the configuration tree.
* A namespace represents the top-level component of a configuration path.
* e.g. if the config path is "ssl.certificatePath", then "ssl" is the
* namespace.
*
* Each namespace contains a JSON schema and a YAML configuration file.
*
* The JSON schema specifies the properties and data types allowed within the
* namespace. e.g. you may specify that the "ssl" namespace has a few
* mandatory properties dealing with certificates and private keys. This means
* any missing properties or any properties outsides of the JSON schema would
* cause a failure to initialize the namespace, and also cannot be set into
* the namespace.
*
* The YAML configuration file is where the actual configuration tree goes
* to. It is automatically validated against the JSON schema at namespace
* initiation. It is automatically saved to and validated against JSON schema
* again at every set() call.
*
* Note that configuration paths may have multiple levels. What it implies
* is those configurations are stored in nested dictionaries - aka. a tree.
* e.g. if the config path is "ethereum.networks.kovan.networkID", then,
* what it means you're accessing ["networks"]["kovan"]["networkID"] under
* the "ethereum" namespace.
*/
readonly #namespaceId: string;
readonly #schemaPath: string;
readonly #configurationPath: string;
readonly #templatePath: string;
readonly #validator: ValidateFunction;
#configuration: Configuration;
constructor(
id: string,
schemaPath: string,
configurationPath: string,
templatePath: string
) {
this.#namespaceId = id;
this.#schemaPath = schemaPath;
this.#configurationPath = configurationPath;
this.#templatePath = templatePath;
this.#configuration = {};
if (!fs.existsSync(schemaPath)) {
throw new Error(
`The JSON schema for namespace ${id} (${schemaPath}) does not exist.`
);
}
this.#validator = ajv.compile(
JSON.parse(fs.readFileSync(schemaPath).toString())
);
if (!fs.existsSync(configurationPath)) {
// copy from template
initiateWithTemplate(this.templatePath, this.configurationPath);
}
this.loadConfig();
}
get id(): string {
return this.#namespaceId;
}
get schemaPath(): string {
return this.#schemaPath;
}
get configurationPath(): string {
return this.#configurationPath;
}
get configuration(): Configuration {
return this.#configuration;
}
get templatePath(): string {
return this.#templatePath;
}
loadConfig() {
const configCandidate: Configuration = yaml.load(
fs.readFileSync(this.#configurationPath, 'utf8')
) as Configuration;
if (!this.#validator(configCandidate)) {
// merge with template file and try validating again
const configTemplateCandidate: Configuration = yaml.load(
fs.readFileSync(this.#templatePath, 'utf8')
) as Configuration;
deepCopy(configCandidate, configTemplateCandidate);
if (!this.#validator(configTemplateCandidate)) {
throw new Error(
`Configuration for namespace ${this.id} seems to be outdated/broken. Kindly fix manually.`
);
}
this.#configuration = configTemplateCandidate;
this.saveConfig();
return;
}
this.#configuration = configCandidate;
}
saveConfig() {
fs.writeFileSync(this.#configurationPath, yaml.dump(this.#configuration));
}
get(configPath: string): any {
const pathComponents: Array<string> = configPath.split('.');
let cursor: Configuration | any = this.#configuration;
for (const component of pathComponents) {
cursor = cursor[component];
if (cursor === undefined) {
return cursor;
}
}
return cursor;
}
set(configPath: string, value: any): void {
const pathComponents: Array<string> = configPath.split('.');
const configClone: Configuration = JSON.parse(
JSON.stringify(this.#configuration)
);
let cursor: Configuration | any = configClone;
let parent: Configuration = configClone;
for (const component of pathComponents.slice(0, -1)) {
parent = cursor;
cursor = cursor[component];
if (cursor === undefined) {
parent[component] = {};
cursor = parent[component];
}
}
const lastComponent: string = pathComponents[pathComponents.length - 1];
cursor[lastComponent] = value;
if (!this.#validator(configClone)) {
throw new Error(
`Cannot set ${this.id}.${configPath} to ${value}: ` +
'JSON schema violation.'
);
}
this.#configuration = configClone;
this.saveConfig();
}
}
export class ConfigManagerV2 {
/**
* This class encapsulates the configuration tree and all the contained
* namespaces and files for Hummingbot Gateway. It also contains a defaults
* mechanism for modules to set default configurations under their namespaces.
*
* The configuration manager starts by loading the root configuration file,
* which defines all the configuration namespaces. The root configuration file
* has a fixed JSON schema, that only allows namespaces to be defined there.
*
* After the namespaces are loaded into the configuration manager during
* initiation, the get() and set() functions will map configuration keys and
* values to the appropriate namespaces.
*
* e.g. get('ethereum.networks.kovan.networkID') will be mapped to
* ethereumNamespace.get('networks.kovan.networkID')
* e.g. set('ethereum.networks.kovan.networkID', 42) will be mapped to
* ethereumNamespace.set('networks.kovan.networkID', 42)
*
* File paths in the root configuration file may be defined as absolute paths
* or relative paths. Any relative paths would be rebased to the root
* configuration file's parent directory.
*
* The static function `setDefaults()` is expected to be called by gateway
* modules, to set default configurations under their own namespaces. Default
* configurations are used in the `get()` function if the corresponding config
* key is not found in its configuration namespace.
*/
readonly #namespaces: { [key: string]: ConfigurationNamespace };
private static _instance: ConfigManagerV2;
public static getInstance(): ConfigManagerV2 {
if (!ConfigManagerV2._instance) {
const rootPath = path.join(ConfigDir, 'root.yml');
if (!fs.existsSync(rootPath)) {
// copy from template
fs.copyFileSync(path.join(ConfigTemplatesDir, 'root.yml'), rootPath);
}
ConfigManagerV2._instance = new ConfigManagerV2(rootPath);
}
return ConfigManagerV2._instance;
}
static defaults: ConfigurationDefaults = {};
constructor(configRootPath: string) {
this.#namespaces = {};
this.loadConfigRoot(configRootPath);
}
static setDefaults(namespaceId: string, defaultTree: Configuration) {
ConfigManagerV2.defaults[namespaceId] = defaultTree;
}
static getFromDefaults(namespaceId: string, configPath: string): any {
if (!(namespaceId in ConfigManagerV2.defaults)) {
return undefined;
}
const pathComponents: Array<string> = configPath.split('.');
const defaultConfig: Configuration = ConfigManagerV2.defaults[namespaceId];
let cursor: Configuration | any = defaultConfig;
for (const pathComponent of pathComponents) {
cursor = cursor[pathComponent];
if (cursor === undefined) {
return cursor;
}
}
return cursor;
}
get namespaces(): { [key: string]: ConfigurationNamespace } {
return this.#namespaces;
}
get allConfigurations(): { [key: string]: Configuration } {
const result: { [key: string]: Configuration } = {};
for (const [key, value] of Object.entries(this.#namespaces)) {
result[key] = value.configuration;
}
return result;
}
getNamespace(id: string): ConfigurationNamespace | undefined {
return this.#namespaces[id];
}
addNamespace(
id: string,
schemaPath: string,
configurationPath: string,
templatePath: string
): void {
this.#namespaces[id] = new ConfigurationNamespace(
id,
schemaPath,
configurationPath,
templatePath
);
}
unpackFullConfigPath(fullConfigPath: string): UnpackedConfigNamespace {
const pathComponents: Array<string> = fullConfigPath.split('.');
if (pathComponents.length < 2) {
throw new Error('Configuration paths must have at least two components.');
}
const namespaceComponent: string = pathComponents[0];
const namespace: ConfigurationNamespace | undefined =
this.#namespaces[namespaceComponent];
if (namespace === undefined) {
throw new Error(
`The configuration namespace ${namespaceComponent} does not exist.`
);
}
const configPath: string = pathComponents.slice(1).join('.');
return {
namespace,
configPath,
};
}
get(fullConfigPath: string): any {
const { namespace, configPath } = this.unpackFullConfigPath(fullConfigPath);
const configValue: any = namespace.get(configPath);
if (configValue === undefined) {
return ConfigManagerV2.getFromDefaults(namespace.id, configPath);
}
return configValue;
}
set(fullConfigPath: string, value: any) {
const { namespace, configPath } = this.unpackFullConfigPath(fullConfigPath);
namespace.set(configPath, value);
}
loadConfigRoot(configRootPath: string) {
// Load the config root file.
const configRootFullPath: string = fs.realpathSync(configRootPath);
const configRootTemplateFullPath: string = path.join(
ConfigTemplatesDir,
'root.yml'
);
const configRootDir: string = path.dirname(configRootFullPath);
const configRoot: ConfigurationRoot = yaml.load(
fs.readFileSync(configRootFullPath, 'utf8')
) as ConfigurationRoot;
const configRootTemplate: ConfigurationRoot = yaml.load(
fs.readFileSync(configRootTemplateFullPath, 'utf8')
) as ConfigurationRoot;
// version control to only handle upgrades
if (configRootTemplate.version > configRoot.version) {
// run migration in order if available
for (
let num = configRoot.version + 1;
num <= configRootTemplate.version;
num++
) {
if ((migrations as MigrationFunctions)[`updateToVersion${num}`]) {
(migrations as MigrationFunctions)[`updateToVersion${num}`](
configRootFullPath,
configRootTemplateFullPath
);
}
}
}
// Validate the config root file.
const validator: ValidateFunction = ajv.compile(
JSON.parse(fs.readFileSync(ConfigRootSchemaPath).toString())
);
if (!validator(configRoot)) {
throw new Error('Configuration root file is invalid.');
}
// Extract the namespace ids.
const namespaceMap: ConfigurationNamespaceDefinitions = {};
for (const namespaceKey of Object.keys(configRoot.configurations)) {
namespaceMap[namespaceKey.slice(NamespaceTag.length)] =
configRoot.configurations[namespaceKey];
}
// Rebase the file paths in config & template roots if they're relative paths.
for (const namespaceDefinition of Object.values(namespaceMap)) {
for (const [key, filePath] of Object.entries(namespaceDefinition)) {
if (!path.isAbsolute(filePath)) {
if (key === 'configurationPath') {
namespaceDefinition['templatePath'] = path.join(
ConfigTemplatesDir,
filePath
);
namespaceDefinition[key] = path.join(configRootDir, filePath);
} else if (key === 'schemaPath') {
namespaceDefinition[key] = path.join(
path.dirname(ConfigRootSchemaPath),
filePath
);
}
} else {
throw new Error(`Absolute path not allowed for ${key}.`);
}
}
}
// Add the namespaces according to config root.
for (const [namespaceId, namespaceDefinition] of Object.entries(
namespaceMap
)) {
this.addNamespace(
namespaceId,
namespaceDefinition.schemaPath,
namespaceDefinition.configurationPath,
namespaceDefinition.templatePath
);
}
}
} | the_stack |
import { useEffect, useState, useCallback } from "react";
import { DropdownOptions } from "../constants";
import { Datasource } from "entities/Datasource";
import { GenerateCRUDEnabledPluginMap } from "api/PluginApi";
import { CONNECT_NEW_DATASOURCE_OPTION_ID } from "../DataSourceOption";
import {
executeDatasourceQuery,
executeDatasourceQuerySuccessPayload,
} from "actions/datasourceActions";
import { DropdownOption } from "components/ads/Dropdown";
import { useDispatch } from "react-redux";
import { isObject } from "lodash";
export const FAKE_DATASOURCE_OPTION = {
CONNECT_NEW_DATASOURCE_OPTION: {
id: CONNECT_NEW_DATASOURCE_OPTION_ID,
label: "Connect New Datasource",
value: "Connect New Datasource",
data: {
pluginId: "",
},
},
};
export const useDatasourceOptions = ({
datasources,
generateCRUDSupportedPlugin,
}: {
datasources: Datasource[];
generateCRUDSupportedPlugin: GenerateCRUDEnabledPluginMap;
}) => {
const [dataSourceOptions, setDataSourceOptions] = useState<DropdownOptions>(
[],
);
useEffect(() => {
// On mount of component and on change of datasources, Update the list.
const unSupportedDatasourceOptions: DropdownOptions = [];
const supportedDatasourceOptions: DropdownOptions = [];
let newDataSourceOptions: DropdownOptions = [];
newDataSourceOptions.push(
FAKE_DATASOURCE_OPTION.CONNECT_NEW_DATASOURCE_OPTION,
);
datasources.forEach(({ id, isValid, name, pluginId }) => {
const datasourceObject = {
id,
label: name,
value: name,
data: {
pluginId,
isSupportedForTemplate: !!generateCRUDSupportedPlugin[pluginId],
isValid,
},
};
if (generateCRUDSupportedPlugin[pluginId])
supportedDatasourceOptions.push(datasourceObject);
else {
unSupportedDatasourceOptions.push(datasourceObject);
}
});
newDataSourceOptions = newDataSourceOptions.concat(
supportedDatasourceOptions,
unSupportedDatasourceOptions,
);
setDataSourceOptions(newDataSourceOptions);
}, [datasources, setDataSourceOptions, generateCRUDSupportedPlugin]);
return dataSourceOptions;
};
const GOOGLE_SHEET_METHODS = {
GET_ALL_SPREADSHEETS: "LIST", // Get all the spreadsheets
GET_ALL_SHEETS: "INFO", // fetch all the sub-sheets
GET_ALL_COLUMNS: "GET", // Get column names
};
const demoRequest: Record<any, string> = {
method: "",
sheetUrl: "",
range: "",
spreadsheetName: "",
tableHeaderIndex: "1",
queryFormat: "ROWS",
rowLimit: "",
sheetName: "",
rowOffset: "",
rowObject: "",
rowObjects: "",
rowIndex: "",
deleteFormat: "SHEET",
};
type FetchAllSpreadSheets = {
selectedDatasourceId: string;
requestObject?: Record<any, string>;
};
export type UseSpreadSheetsReturn = {
fetchAllSpreadsheets: ({
requestObject,
selectedDatasourceId,
}: FetchAllSpreadSheets) => void;
isFetchingSpreadsheets: boolean;
failedFetchingSpreadsheets: boolean;
};
export const useSpreadSheets = ({
setSelectedDatasourceIsInvalid,
setSelectedDatasourceTableOptions,
}: {
setSelectedDatasourceIsInvalid: (isInvalid: boolean) => void;
setSelectedDatasourceTableOptions: (tableOptions: DropdownOptions) => void;
}): UseSpreadSheetsReturn => {
const dispatch = useDispatch();
// const [spreadsheetsList, setSpreadsheets] = useState<DropdownOption[]>([]);
const [isFetchingSpreadsheets, setIsFetchingSpreadsheets] = useState<boolean>(
false,
);
const [failedFetchingSpreadsheets, setFailedFetchingSpreadsheets] = useState<
boolean
>(false);
// TODO :- Create loading state and set Loading state false on success or error
const onFetchAllSpreadsheetFailure = useCallback(() => {
setIsFetchingSpreadsheets(false);
setFailedFetchingSpreadsheets(true);
}, [setIsFetchingSpreadsheets]);
const onFetchAllSpreadsheetSuccess = useCallback(
(
payload: executeDatasourceQuerySuccessPayload<
Array<{ id: string; name: string }>
>,
) => {
setIsFetchingSpreadsheets(false);
const tableOptions: DropdownOptions = [];
if (payload.data && payload.data.body) {
const spreadSheets = payload.data.body;
if (Array.isArray(spreadSheets)) {
spreadSheets.map(({ id, name }) => {
tableOptions.push({
id,
label: name,
value: name,
});
setSelectedDatasourceTableOptions(tableOptions);
});
} else {
// to handle error like "401 Unauthorized"
setSelectedDatasourceIsInvalid(true);
}
}
},
[
setSelectedDatasourceIsInvalid,
setSelectedDatasourceTableOptions,
setIsFetchingSpreadsheets,
],
);
const fetchAllSpreadsheets = useCallback(
({ requestObject, selectedDatasourceId }: FetchAllSpreadSheets) => {
setIsFetchingSpreadsheets(true);
setFailedFetchingSpreadsheets(false);
let requestData = { ...demoRequest };
if (isObject(requestObject) && Object.keys(requestObject).length) {
requestData = { ...requestObject };
}
requestData.method = GOOGLE_SHEET_METHODS.GET_ALL_SPREADSHEETS;
const formattedRequestData = Object.entries(
requestData,
).map(([dataKey, dataValue]) => ({ key: dataKey, value: dataValue }));
dispatch(
executeDatasourceQuery({
payload: {
datasourceId: selectedDatasourceId,
data: formattedRequestData,
},
onSuccessCallback: onFetchAllSpreadsheetSuccess,
onErrorCallback: onFetchAllSpreadsheetFailure,
}),
);
},
[
onFetchAllSpreadsheetSuccess,
onFetchAllSpreadsheetFailure,
setIsFetchingSpreadsheets,
setFailedFetchingSpreadsheets,
],
);
return {
fetchAllSpreadsheets,
// spreadsheetsList,
isFetchingSpreadsheets,
failedFetchingSpreadsheets,
};
};
// Types
export interface GridProperties {
rowCount: number;
columnCount: number;
}
export interface Sheet {
sheetId: number;
title: string;
index: number;
sheetType: string;
gridProperties: GridProperties;
}
export type Sheets = Sheet[];
export const getSheetUrl = (sheetId: string): string =>
`https://docs.google.com/spreadsheets/d/${sheetId}/edit#gid=0`;
export type FetchSheetsList = {
selectedDatasourceId: string;
selectedSpreadsheetId: string;
requestObject?: Record<any, string>;
};
export type UseSheetListReturn = {
sheetsList: DropdownOption[];
isFetchingSheetsList: boolean;
failedFetchingSheetsList: boolean;
fetchSheetsList: ({
requestObject,
selectedDatasourceId,
selectedSpreadsheetId,
}: FetchSheetsList) => void;
};
export const useSheetsList = (): UseSheetListReturn => {
const dispatch = useDispatch();
const [sheetsList, setSheetsList] = useState<DropdownOption[]>([]);
const [isFetchingSheetsList, setIsFetchingSheetsList] = useState<boolean>(
false,
);
const [failedFetchingSheetsList, setFailedFetchingSheetsList] = useState<
boolean
>(false);
const onFetchAllSheetFailure = useCallback(() => {
setIsFetchingSheetsList(false);
setFailedFetchingSheetsList(true);
}, [setIsFetchingSheetsList]);
const onFetchAllSheetSuccess = useCallback(
(
payload: executeDatasourceQuerySuccessPayload<{
sheets: Sheets;
name: string;
id: string;
}>,
) => {
setIsFetchingSheetsList(false);
const sheetOptions: DropdownOptions = [];
if (payload.data && payload.data.body) {
const responseBody = payload.data.body;
if (isObject(responseBody)) {
const { sheets = [] } = responseBody;
if (Array.isArray(sheets)) {
sheets.map(({ title }) => {
sheetOptions.push({
id: title,
label: title,
value: title,
});
setSheetsList(sheetOptions);
});
} else {
// to handle error like "401 Unauthorized"
}
}
}
},
[setSheetsList, setIsFetchingSheetsList],
);
const fetchSheetsList = useCallback(
({
requestObject,
selectedDatasourceId,
selectedSpreadsheetId,
}: FetchSheetsList) => {
setSheetsList([]);
setIsFetchingSheetsList(true);
setFailedFetchingSheetsList(false);
let requestData = { ...demoRequest };
if (isObject(requestObject) && Object.keys(requestObject).length) {
requestData = { ...requestObject };
}
requestData.method = GOOGLE_SHEET_METHODS.GET_ALL_SHEETS;
requestData.sheetUrl = getSheetUrl(selectedSpreadsheetId);
const formattedRequestData = Object.entries(
requestData,
).map(([dataKey, dataValue]) => ({ key: dataKey, value: dataValue }));
dispatch(
executeDatasourceQuery({
payload: {
datasourceId: selectedDatasourceId,
data: formattedRequestData,
},
onSuccessCallback: onFetchAllSheetSuccess,
onErrorCallback: onFetchAllSheetFailure,
}),
);
},
[
setSheetsList,
onFetchAllSheetSuccess,
onFetchAllSheetFailure,
setIsFetchingSheetsList,
setFailedFetchingSheetsList,
],
);
return {
sheetsList,
isFetchingSheetsList,
failedFetchingSheetsList,
fetchSheetsList,
};
};
export type FetchColumnHeaderListParams = {
selectedDatasourceId: string;
selectedSpreadsheetId: string;
sheetName: string;
tableHeaderIndex: string;
requestObject?: Record<any, string>;
};
export type UseSheetColumnHeadersReturn = {
columnHeaderList: DropdownOption[];
isFetchingColumnHeaderList: boolean;
errorFetchingColumnHeaderList: string;
fetchColumnHeaderList: ({
selectedDatasourceId,
selectedSpreadsheetId,
sheetName,
tableHeaderIndex,
}: FetchColumnHeaderListParams) => void;
};
export const useSheetColumnHeaders = () => {
const dispatch = useDispatch();
const [columnHeaderList, setColumnHeaderList] = useState<DropdownOption[]>(
[],
);
const [isFetchingColumnHeaderList, setIsFetchingColumnHeaderList] = useState<
boolean
>(false);
const [
errorFetchingColumnHeaderList,
setErrorFetchingColumnHeaderList,
] = useState<string>("");
const onFetchColumnHeadersFailure = useCallback(
(error: string) => {
setIsFetchingColumnHeaderList(false);
setErrorFetchingColumnHeaderList(error);
},
[setErrorFetchingColumnHeaderList, setIsFetchingColumnHeaderList],
);
const onFetchColumnHeadersSuccess = useCallback(
(
payload: executeDatasourceQuerySuccessPayload<Record<string, string>[]>,
) => {
setIsFetchingColumnHeaderList(false);
const columnHeaders: DropdownOptions = [];
if (payload.data && payload.data.body) {
const responseBody = payload.data.body;
if (Array.isArray(responseBody) && responseBody.length) {
const headersObject = responseBody[0];
delete headersObject.rowIndex;
const headers = Object.keys(headersObject);
if (Array.isArray(headers) && headers.length) {
headers.map((header, index) => {
columnHeaders.push({
id: `${header}_${index}`,
label: header,
value: header,
});
});
setColumnHeaderList(columnHeaders);
}
} else {
let error = "Failed fetching Column headers";
if (typeof responseBody === "string") {
error = responseBody;
}
setColumnHeaderList([]);
setErrorFetchingColumnHeaderList(error);
}
}
},
[
setColumnHeaderList,
setIsFetchingColumnHeaderList,
setErrorFetchingColumnHeaderList,
],
);
const fetchColumnHeaderList = useCallback(
(params: FetchColumnHeaderListParams) => {
setIsFetchingColumnHeaderList(true);
setErrorFetchingColumnHeaderList("");
let requestData = { ...demoRequest };
if (
isObject(params.requestObject) &&
Object.keys(params.requestObject).length
) {
requestData = { ...params.requestObject };
}
requestData.method = GOOGLE_SHEET_METHODS.GET_ALL_COLUMNS;
requestData.sheetUrl = getSheetUrl(params.selectedSpreadsheetId);
requestData.tableHeaderIndex = params.tableHeaderIndex;
requestData.rowLimit = "1";
requestData.rowOffset = "0";
requestData.sheetName = params.sheetName;
const formattedRequestData = Object.entries(
requestData,
).map(([dataKey, dataValue]) => ({ key: dataKey, value: dataValue }));
dispatch(
executeDatasourceQuery({
payload: {
datasourceId: params.selectedDatasourceId,
data: formattedRequestData,
},
onSuccessCallback: onFetchColumnHeadersSuccess,
onErrorCallback: onFetchColumnHeadersFailure,
}),
);
},
[
onFetchColumnHeadersSuccess,
onFetchColumnHeadersFailure,
setIsFetchingColumnHeaderList,
setErrorFetchingColumnHeaderList,
],
);
return {
columnHeaderList,
isFetchingColumnHeaderList,
errorFetchingColumnHeaderList,
fetchColumnHeaderList,
};
};
const payload = [
{
value: "LIST_BUCKETS",
},
];
export const useS3BucketList = () => {
const dispatch = useDispatch();
const [bucketList, setBucketList] = useState<Array<string>>([]);
const [isFetchingBucketList, setIsFetchingBucketList] = useState<boolean>(
false,
);
const [failedFetchingBucketList, setFailedFetchingBucketList] = useState<
boolean
>(false);
const onFetchBucketSuccess = useCallback(
(
payload: executeDatasourceQuerySuccessPayload<{
bucketList: Array<string>;
}>,
) => {
setIsFetchingBucketList(false);
if (payload.data && payload.data.body) {
const payloadBody = payload.data.body;
if (Array.isArray(payloadBody.bucketList)) {
const { bucketList: list = [] } = payloadBody;
setBucketList(list);
}
}
},
[setBucketList, setIsFetchingBucketList],
);
const onFetchBucketFailure = useCallback(() => {
setIsFetchingBucketList(false);
setFailedFetchingBucketList(true);
}, [setIsFetchingBucketList]);
const fetchBucketList = useCallback(
({ selectedDatasource }: { selectedDatasource: DropdownOption }) => {
if (selectedDatasource.id) {
setIsFetchingBucketList(true);
setFailedFetchingBucketList(false);
dispatch(
executeDatasourceQuery({
payload: {
datasourceId: selectedDatasource.id,
data: payload,
},
onSuccessCallback: onFetchBucketSuccess,
onErrorCallback: onFetchBucketFailure,
}),
);
}
},
[onFetchBucketSuccess, onFetchBucketFailure, setIsFetchingBucketList],
);
return {
bucketList,
isFetchingBucketList,
failedFetchingBucketList,
fetchBucketList,
};
}; | the_stack |
import type { ContactMaterialOptions, MaterialOptions } from 'p2-es'
import type { DependencyList, MutableRefObject, Ref, RefObject } from 'react'
import { useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { DynamicDrawUsage, InstancedMesh, MathUtils, Object3D } from 'three'
import type {
AtomicName,
CollideBeginEvent,
CollideEndEvent,
CollideEvent,
ConstraintOptns,
ConstraintTypes,
DistanceConstraintOpts,
Duplet,
GearConstraintOpts,
LockConstraintOpts,
PrismaticConstraintOpts,
PropValue,
ProviderContext,
RayhitEvent,
RayMode,
RayOptions,
RevoluteConstraintOpts,
SetOpName,
SpringOptns,
SubscriptionName,
SubscriptionTarget,
VectorName,
WheelInfoOptions,
} from './setup'
import { context, debugContext } from './setup'
import type { CannonWorkerAPI } from './cannon-worker-api'
export type AtomicProps = {
allowSleep: boolean
angle: number
angularDamping: number
angularVelocity: number
collisionFilterGroup: number
collisionFilterMask: number
collisionResponse: boolean
fixedRotation: boolean
isTrigger: boolean
linearDamping: number
mass: number
material: MaterialOptions
sleepSpeedLimit: number
sleepTimeLimit: number
userData: Record<PropertyKey, any>
}
export type VectorProps = Record<VectorName, Duplet>
export type BodyProps<T extends any[] = unknown[]> = Partial<AtomicProps> &
Partial<VectorProps> & {
args?: T
onCollide?: (e: CollideEvent) => void
onCollideBegin?: (e: CollideBeginEvent) => void
onCollideEnd?: (e: CollideEndEvent) => void
type?: 'Dynamic' | 'Static' | 'Kinematic'
}
export type BodyPropsArgsRequired<T extends any[] = unknown[]> = BodyProps<T> & {
args: T
}
export type ShapeType =
| 'Box'
| 'Circle'
| 'Capsule'
| 'Particle'
| 'Plane'
| 'Convex'
| 'Line'
| 'Heightfield'
export type BodyShapeType = ShapeType | 'Compound'
export type BoxArgs = [width?: number, height?: number]
export type CapsuleArgs = [length?: number, radius?: number]
export type CircleArgs = [radius?: number]
export type ConvexArgs = [vertices: number[][], axes?: number[][]]
export type LineArgs = [length?: number]
export type HeightfieldArgs = [
heights: number[],
options?: { elementWidth?: number; maxValue?: number; minValue?: number },
]
export type BoxProps = BodyProps<BoxArgs>
export type CapsuleProps = BodyProps<CapsuleArgs>
export type CircleProps = BodyProps<CircleArgs>
export type ConvexProps = BodyProps<ConvexArgs>
export type LineProps = BodyProps<LineArgs>
export type HeightfieldProps = BodyPropsArgsRequired<HeightfieldArgs>
export interface CompoundBodyProps extends BodyProps {
shapes: BodyProps & { type: ShapeType }[]
}
export type AtomicApi<K extends AtomicName> = {
set: (value: AtomicProps[K]) => void
subscribe: (callback: (value: AtomicProps[K]) => void) => () => void
}
export type VectorApi = {
copy: (array: Duplet) => void
set: (x: number, y: number) => void
subscribe: (callback: (value: Duplet) => void) => () => void
}
export type WorkerApi = {
[K in AtomicName]: AtomicApi<K>
} & {
[K in VectorName]: VectorApi
} & {
applyForce: (force: Duplet, worldPoint: Duplet) => void
applyImpulse: (impulse: Duplet, worldPoint: Duplet) => void
applyLocalForce: (force: Duplet, localPoint: Duplet) => void
applyLocalImpulse: (impulse: Duplet, localPoint: Duplet) => void
applyTorque: (torque: Duplet) => void
sleep: () => void
wakeUp: () => void
}
export interface PublicApi extends WorkerApi {
at: (index: number) => WorkerApi
}
export type Api = [RefObject<Object3D>, PublicApi]
const temp = new Object3D()
function useForwardedRef<T>(ref: Ref<T>): MutableRefObject<T | null> {
const nullRef = useRef<T>(null)
return ref && typeof ref !== 'function' ? ref : nullRef
}
function capitalize<T extends string>(str: T): Capitalize<T> {
return (str.charAt(0).toUpperCase() + str.slice(1)) as Capitalize<T>
}
function getUUID(ref: Ref<Object3D>, index?: number): string | null {
const suffix = index === undefined ? '' : `/${index}`
if (typeof ref === 'function') return null
return ref && ref.current && `${ref.current.uuid}${suffix}`
}
let incrementingId = 0
function subscribe<T extends SubscriptionName>(
ref: RefObject<Object3D>,
worker: CannonWorkerAPI,
subscriptions: ProviderContext['subscriptions'],
type: T,
index?: number,
target: SubscriptionTarget = 'bodies',
) {
return (callback: (value: PropValue<T>) => void) => {
const id = incrementingId++
subscriptions[id] = { [type]: callback }
const uuid = getUUID(ref, index)
uuid && worker.subscribe({ props: { id, target, type }, uuid })
return () => {
delete subscriptions[id]
worker.unsubscribe({ props: id })
}
}
}
function prepare(object: Object3D, props: BodyProps) {
object.userData = props.userData || {}
// @todo match normal
// object.position.set(...(props.position || [0, 0, 0]))
// object.rotation.set(...(props.rotation || [0, 0, 0]))
object.updateMatrix()
}
function setupCollision(
events: ProviderContext['events'],
{ onCollide, onCollideBegin, onCollideEnd }: Partial<BodyProps>,
uuid: string,
) {
events[uuid] = {
collide: onCollide,
collideBegin: onCollideBegin,
collideEnd: onCollideEnd,
}
}
type GetByIndex<T extends BodyProps> = (index: number) => T
type ArgFn<T> = (args: T) => unknown[]
function useBody<B extends BodyProps<unknown[]>>(
type: BodyShapeType,
fn: GetByIndex<B>,
argsFn: ArgFn<B['args']>,
fwdRef: Ref<Object3D>,
deps: DependencyList = [],
): Api {
const ref = useForwardedRef(fwdRef)
const { worker, refs, events, subscriptions } = useContext(context)
const debugApi = useContext(debugContext)
useLayoutEffect(() => {
if (!ref.current) {
// When the reference isn't used we create a stub
// The body doesn't have a visual representation but can still be constrained
ref.current = new Object3D()
}
const object = ref.current
const currentWorker = worker
const objectCount =
object instanceof InstancedMesh ? (object.instanceMatrix.setUsage(DynamicDrawUsage), object.count) : 1
const uuid =
object instanceof InstancedMesh
? new Array(objectCount).fill(0).map((_, i) => `${object.uuid}/${i}`)
: [object.uuid]
const props: (B & { args: unknown })[] =
object instanceof InstancedMesh
? uuid.map((id, i) => {
const props = fn(i)
prepare(temp, props)
object.setMatrixAt(i, temp.matrix)
object.instanceMatrix.needsUpdate = true
refs[id] = object
if (debugApi) debugApi.add(id, props, type)
setupCollision(events, props, id)
return { ...props, args: argsFn(props.args) }
})
: uuid.map((id, i) => {
const props = fn(i)
prepare(object, props)
refs[id] = object
if (debugApi) debugApi.add(id, props, type)
setupCollision(events, props, id)
return { ...props, args: argsFn(props.args) }
})
// Register on mount, unregister on unmount
currentWorker.addBodies({
props: props.map(({ onCollide, onCollideBegin, onCollideEnd, ...serializableProps }) => {
return { onCollide: Boolean(onCollide), ...serializableProps }
}),
type,
uuid,
})
return () => {
uuid.forEach((id) => {
delete refs[id]
if (debugApi) debugApi.remove(id)
delete events[id]
})
currentWorker.removeBodies({ uuid })
}
}, deps)
const api = useMemo(() => {
const makeAtomic = <T extends AtomicName>(type: T, index?: number) => {
const op: SetOpName<T> = `set${capitalize(type)}`
return {
set: (value: PropValue<T>) => {
const uuid = getUUID(ref, index)
uuid &&
worker[op]({
props: value,
uuid,
} as never)
},
subscribe: subscribe(ref, worker, subscriptions, type, index),
}
}
const makeVec = (type: VectorName, index?: number) => {
const op: SetOpName<VectorName> = `set${capitalize(type)}`
return {
copy: (vec: number[]) => {
const uuid = getUUID(ref, index)
uuid && worker[op]({ props: [vec[0], vec[1]], uuid })
},
set: (x: number, y: number) => {
const uuid = getUUID(ref, index)
uuid && worker[op]({ props: [x, y], uuid })
},
subscribe: subscribe(ref, worker, subscriptions, type, index),
}
}
function makeApi(index?: number): WorkerApi {
return {
allowSleep: makeAtomic('allowSleep', index),
angle: makeAtomic('angle', index),
angularDamping: makeAtomic('angularDamping', index),
angularVelocity: makeAtomic('angularVelocity', index),
applyForce(force: Duplet, worldPoint: Duplet) {
const uuid = getUUID(ref, index)
uuid && worker.applyForce({ props: [force, worldPoint], uuid })
},
applyImpulse(impulse: Duplet, worldPoint: Duplet) {
const uuid = getUUID(ref, index)
uuid && worker.applyImpulse({ props: [impulse, worldPoint], uuid })
},
applyLocalForce(force: Duplet, localPoint: Duplet) {
const uuid = getUUID(ref, index)
uuid && worker.applyLocalForce({ props: [force, localPoint], uuid })
},
applyLocalImpulse(impulse: Duplet, localPoint: Duplet) {
const uuid = getUUID(ref, index)
uuid && worker.applyLocalImpulse({ props: [impulse, localPoint], uuid })
},
applyTorque(torque: Duplet) {
const uuid = getUUID(ref, index)
uuid && worker.applyTorque({ props: [torque], uuid })
},
collisionFilterGroup: makeAtomic('collisionFilterGroup', index),
collisionFilterMask: makeAtomic('collisionFilterMask', index),
collisionResponse: makeAtomic('collisionResponse', index),
fixedRotation: makeAtomic('fixedRotation', index),
isTrigger: makeAtomic('isTrigger', index),
linearDamping: makeAtomic('linearDamping', index),
mass: makeAtomic('mass', index),
material: makeAtomic('material', index),
position: makeVec('position', index),
sleep() {
const uuid = getUUID(ref, index)
uuid && worker.sleep({ uuid })
},
sleepSpeedLimit: makeAtomic('sleepSpeedLimit', index),
sleepTimeLimit: makeAtomic('sleepTimeLimit', index),
userData: makeAtomic('userData', index),
velocity: makeVec('velocity', index),
wakeUp() {
const uuid = getUUID(ref, index)
uuid && worker.wakeUp({ uuid })
},
}
}
const cache: { [index: number]: WorkerApi } = {}
return {
...makeApi(undefined),
at: (index: number) => cache[index] || (cache[index] = makeApi(index)),
}
}, [])
return [ref, api]
}
export function usePlane(fn: GetByIndex<BodyProps>, fwdRef: Ref<Object3D> = null, deps?: DependencyList) {
return useBody('Plane', fn, () => [], fwdRef, deps)
}
export function useBox(fn: GetByIndex<BoxProps>, fwdRef: Ref<Object3D> = null, deps?: DependencyList) {
return useBody('Box', fn, (args = [] as BoxArgs) => args, fwdRef, deps)
}
export function useCapsule(
fn: GetByIndex<CapsuleProps>,
fwdRef: Ref<Object3D> = null,
deps?: DependencyList,
) {
return useBody('Capsule', fn, (args = [] as CapsuleArgs) => args, fwdRef, deps)
}
export function useCircle(fn: GetByIndex<CircleProps>, fwdRef: Ref<Object3D> = null, deps?: DependencyList) {
return useBody('Circle', fn, (args = [] as CircleArgs) => args, fwdRef, deps)
}
export function useConvex(fn: GetByIndex<ConvexProps>, fwdRef: Ref<Object3D> = null, deps?: DependencyList) {
return useBody('Convex', fn, (args = [[], []] as ConvexArgs) => args, fwdRef, deps)
}
export function useHeightfield(
fn: GetByIndex<HeightfieldProps>,
fwdRef: Ref<Object3D> = null,
deps?: DependencyList,
) {
return useBody('Heightfield', fn, (args = [[], {}] as HeightfieldArgs) => args, fwdRef, deps)
}
export function useLine(fn: GetByIndex<LineProps>, fwdRef: Ref<Object3D> = null, deps?: DependencyList) {
return useBody('Line', fn, (args = [] as LineArgs) => args, fwdRef, deps)
}
export function useParticle(fn: GetByIndex<BodyProps>, fwdRef: Ref<Object3D> = null, deps?: DependencyList) {
return useBody('Particle', fn, () => [], fwdRef, deps)
}
export function useCompoundBody(
fn: GetByIndex<CompoundBodyProps>,
fwdRef: Ref<Object3D> = null,
deps?: DependencyList,
) {
return useBody('Compound', fn, (args) => args as unknown[], fwdRef, deps)
}
type ConstraintApi = [
RefObject<Object3D>,
RefObject<Object3D>,
{
disable: () => void
enable: () => void
},
]
type MotorConstraintApi = [
RefObject<Object3D>,
RefObject<Object3D>,
{
disable: () => void
disableMotor: () => void
enable: () => void
enableMotor: () => void
setMotorMaxForce: (value: number) => void
setMotorSpeed: (value: number) => void
},
]
type SpringApi = [
RefObject<Object3D>,
RefObject<Object3D>,
{
setDamping: (value: number) => void
setRestLength: (value: number) => void
setStiffness: (value: number) => void
},
]
type ConstraintORHingeApi<T extends 'Prismatic' | 'Revolute' | ConstraintTypes> = T extends ConstraintTypes
? ConstraintApi
: MotorConstraintApi
function useConstraint<T extends 'Prismatic' | 'Revolute' | ConstraintTypes>(
type: T,
bodyA: Ref<Object3D>,
bodyB: Ref<Object3D>,
optns: ConstraintOptns | PrismaticConstraintOpts | RevoluteConstraintOpts = {},
deps: DependencyList = [],
): ConstraintORHingeApi<T> {
const { worker } = useContext(context)
const uuid = MathUtils.generateUUID()
const refA = useForwardedRef(bodyA)
const refB = useForwardedRef(bodyB)
useEffect(() => {
if (refA.current && refB.current) {
worker.addConstraint({
props: [refA.current.uuid, refB.current.uuid, optns],
type,
uuid,
})
return () => worker.removeConstraint({ uuid })
}
}, deps)
const api = useMemo(() => {
if (type === 'Prismatic' || type === 'Revolute') {
return {
disableMotor: () => worker.disableConstraintMotor({ uuid }),
enableMotor: () => worker.enableConstraintMotor({ uuid }),
setMotorSpeed: (value: number) => worker.setConstraintMotorSpeed({ props: value, uuid }),
}
}
return {}
}, deps)
return [refA, refB, api] as ConstraintORHingeApi<T>
}
export function useDistanceConstraint(
bodyA: Ref<Object3D> = null,
bodyB: Ref<Object3D> = null,
optns: DistanceConstraintOpts,
deps: DependencyList = [],
) {
return useConstraint('Distance', bodyA, bodyB, optns, deps)
}
export function useGearConstraint(
bodyA: Ref<Object3D> = null,
bodyB: Ref<Object3D> = null,
optns: GearConstraintOpts,
deps: DependencyList = [],
) {
return useConstraint('Gear', bodyA, bodyB, optns, deps)
}
export function useLockConstraint(
bodyA: Ref<Object3D> = null,
bodyB: Ref<Object3D> = null,
optns: LockConstraintOpts,
deps: DependencyList = [],
) {
return useConstraint('Lock', bodyA, bodyB, optns, deps)
}
export function usePrismaticConstraint(
bodyA: Ref<Object3D> = null,
bodyB: Ref<Object3D> = null,
optns: PrismaticConstraintOpts,
deps: DependencyList = [],
) {
return useConstraint('Prismatic', bodyA, bodyB, optns, deps)
}
export function useRevoluteConstraint(
bodyA: Ref<Object3D> = null,
bodyB: Ref<Object3D> = null,
optns: RevoluteConstraintOpts,
deps: DependencyList = [],
) {
return useConstraint('Revolute', bodyA, bodyB, optns, deps)
}
export function useSpring(
bodyA: Ref<Object3D> = null,
bodyB: Ref<Object3D> = null,
optns: SpringOptns,
deps: DependencyList = [],
): SpringApi {
const { worker } = useContext(context)
const [uuid] = useState(() => MathUtils.generateUUID())
const refA = useForwardedRef(bodyA)
const refB = useForwardedRef(bodyB)
useEffect(() => {
if (refA.current && refB.current) {
worker.addSpring({
props: [refA.current.uuid, refB.current.uuid, optns],
uuid,
})
return () => {
worker.removeSpring({ uuid })
}
}
}, deps)
const api = useMemo(
() => ({
setDamping: (value: number) => worker.setSpringDamping({ props: value, uuid }),
setRestLength: (value: number) => worker.setSpringRestLength({ props: value, uuid }),
setStiffness: (value: number) => worker.setSpringStiffness({ props: value, uuid }),
}),
deps,
)
return [refA, refB, api]
}
function useRay(
mode: RayMode,
options: RayOptions,
callback: (e: RayhitEvent) => void,
deps: DependencyList = [],
) {
const { worker, events } = useContext(context)
const [uuid] = useState(() => MathUtils.generateUUID())
useEffect(() => {
events[uuid] = { rayhit: callback }
worker.addRay({ props: { ...options, mode }, uuid })
return () => {
worker.removeRay({ uuid })
delete events[uuid]
}
}, deps)
}
export function useRaycastClosest(
options: RayOptions,
callback: (e: RayhitEvent) => void,
deps: DependencyList = [],
) {
useRay('Closest', options, callback, deps)
}
export function useRaycastAny(
options: RayOptions,
callback: (e: RayhitEvent) => void,
deps: DependencyList = [],
) {
useRay('Any', options, callback, deps)
}
export function useRaycastAll(
options: RayOptions,
callback: (e: RayhitEvent) => void,
deps: DependencyList = [],
) {
useRay('All', options, callback, deps)
}
export interface TopDownVehiclePublicApi {
applyEngineForce: (value: number, wheelIndex: number) => void
setBrake: (brake: number, wheelIndex: number) => void
setSteeringValue: (value: number, wheelIndex: number) => void
}
export interface TopDownVehicleProps {
chassisBody: Ref<Object3D>
wheels: WheelInfoOptions[]
}
export function useTopDownVehicle(
fn: () => TopDownVehicleProps,
fwdRef: Ref<Object3D> = null,
deps: DependencyList = [],
): [RefObject<Object3D>, TopDownVehiclePublicApi] {
const ref = useForwardedRef(fwdRef)
const { worker } = useContext(context)
useLayoutEffect(() => {
if (!ref.current) {
// When the reference isn't used we create a stub
// The body doesn't have a visual representation but can still be constrained
ref.current = new Object3D()
}
const currentWorker = worker
const uuid: string = ref.current.uuid
const { chassisBody, wheels } = fn()
const chassisBodyUUID = getUUID(chassisBody)
if (!chassisBodyUUID) return
currentWorker.addTopDownVehicle({
props: [chassisBodyUUID, wheels],
uuid,
})
return () => {
currentWorker.removeTopDownVehicle({ uuid })
}
}, deps)
const api = useMemo<TopDownVehiclePublicApi>(() => {
return {
applyEngineForce(value: number, wheelIndex: number) {
const uuid = getUUID(ref)
uuid && worker.applyTopDownVehicleEngineForce({ props: [value, wheelIndex], uuid })
},
setBrake(brake: number, wheelIndex: number) {
const uuid = getUUID(ref)
uuid && worker.setTopDownVehicleBrake({ props: [brake, wheelIndex], uuid })
},
setSteeringValue(value: number, wheelIndex: number) {
const uuid = getUUID(ref)
uuid && worker.setTopDownVehicleSteeringValue({ props: [value, wheelIndex], uuid })
},
}
}, deps)
return [ref, api]
}
export function useContactMaterial(
materialA: MaterialOptions,
materialB: MaterialOptions,
options: ContactMaterialOptions,
deps: DependencyList = [],
): void {
const { worker } = useContext(context)
const [uuid] = useState(() => MathUtils.generateUUID())
useEffect(() => {
worker.addContactMaterial({
props: [materialA, materialB, options],
uuid,
})
return () => {
worker.removeContactMaterial({ uuid })
}
}, deps)
}
type KinematicCharacterControllerCollisions = {
above: boolean
below: boolean
climbingSlope: boolean
descendingSlope: boolean
faceDir: number
fallingThroughPlatform: boolean
left: boolean
right: boolean
slopeAngle: number
slopeAngleOld: number
velocityOld: Duplet
}
export interface KinematicCharacterControllerPublicApi {
collisions: {
subscribe: (callback: (collisions: KinematicCharacterControllerCollisions) => void) => void
}
raysData: {
subscribe: (callback: (raysData: []) => void) => void
}
setInput: (input: [x: number, y: number]) => void
setJump: (isDown: boolean) => void
}
export interface KinematicCharacterControllerProps {
accelerationTimeAirborne?: number
accelerationTimeGrounded?: number
body: Ref<Object3D>
collisionMask: number
dstBetweenRays?: number
maxClimbAngle?: number
maxDescendAngle?: number
maxJumpHeight?: number
minJumpHeight?: number
moveSpeed?: number
skinWidth?: number
timeToJumpApex?: number
velocityXMin?: number
velocityXSmoothing?: number
wallJumpClimb?: Duplet
wallJumpOff?: Duplet
wallLeap?: Duplet
wallSlideSpeedMax?: number
wallStickTime?: number
}
export function useKinematicCharacterController(
fn: () => KinematicCharacterControllerProps,
fwdRef: Ref<Object3D> = null,
deps: DependencyList = [],
): [RefObject<Object3D>, KinematicCharacterControllerPublicApi] {
const ref = useForwardedRef(fwdRef)
const { worker, subscriptions } = useContext(context)
useLayoutEffect(() => {
if (!ref.current) {
// When the reference isn't used we create a stub
// The body doesn't have a visual representation but can still be constrained
ref.current = new Object3D()
}
const currentWorker = worker
const uuid: string = ref.current.uuid
const kinematicCharacterControllerProps = fn()
const bodyUUID = getUUID(kinematicCharacterControllerProps.body)
if (!bodyUUID) return
currentWorker.addKinematicCharacterController({
props: [
bodyUUID,
kinematicCharacterControllerProps.collisionMask,
kinematicCharacterControllerProps.accelerationTimeAirborne,
kinematicCharacterControllerProps.accelerationTimeGrounded,
kinematicCharacterControllerProps.moveSpeed,
kinematicCharacterControllerProps.wallSlideSpeedMax,
kinematicCharacterControllerProps.wallStickTime,
kinematicCharacterControllerProps.wallJumpClimb,
kinematicCharacterControllerProps.wallJumpOff,
kinematicCharacterControllerProps.wallLeap,
kinematicCharacterControllerProps.timeToJumpApex,
kinematicCharacterControllerProps.maxJumpHeight,
kinematicCharacterControllerProps.minJumpHeight,
kinematicCharacterControllerProps.velocityXSmoothing,
kinematicCharacterControllerProps.velocityXMin,
kinematicCharacterControllerProps.maxClimbAngle,
kinematicCharacterControllerProps.maxDescendAngle,
kinematicCharacterControllerProps.skinWidth,
kinematicCharacterControllerProps.dstBetweenRays,
],
uuid,
})
return () => {
currentWorker.removeKinematicCharacterController({ uuid })
}
}, deps)
const api = useMemo<KinematicCharacterControllerPublicApi>(() => {
return {
collisions: {
subscribe: subscribe(ref, worker, subscriptions, 'collisions', undefined, 'controllers'),
},
raysData: {
subscribe: subscribe(ref, worker, subscriptions, 'raysData', undefined, 'controllers'),
},
setInput(input: [x: number, y: number]) {
const uuid = getUUID(ref)
uuid && worker.setKinematicCharacterControllerInput({ props: input, uuid })
},
setJump(isDown: boolean) {
const uuid = getUUID(ref)
uuid && worker.setKinematicCharacterControllerJump({ props: isDown, uuid })
},
}
}, deps)
return [ref, api]
}
export interface PlatformControllerPublicApi {
collisions: {
subscribe: (callback: (collisions: {}) => void) => void
}
raysData: {
subscribe: (callback: (raysData: []) => void) => void
}
}
export interface PlatformControllerProps {
body: Ref<Object3D>
dstBetweenRays?: number
localWaypoints: Duplet[]
passengerMask: number
skinWidth?: number
speed?: number
}
export function usePlatformController(
fn: () => PlatformControllerProps,
fwdRef: Ref<Object3D> = null,
deps: DependencyList = [],
): [RefObject<Object3D>, PlatformControllerPublicApi] {
const ref = useForwardedRef(fwdRef)
const { worker, subscriptions } = useContext(context)
useLayoutEffect(() => {
if (!ref.current) {
// When the reference isn't used we create a stub
// The body doesn't have a visual representation but can still be constrained
ref.current = new Object3D()
}
const currentWorker = worker
const uuid: string = ref.current.uuid
const platformControllerProps = fn()
const bodyUUID = getUUID(platformControllerProps.body)
if (!bodyUUID) return
currentWorker.addPlatformController({
props: [
bodyUUID,
platformControllerProps.passengerMask,
platformControllerProps.localWaypoints,
platformControllerProps.speed,
platformControllerProps.skinWidth,
platformControllerProps.dstBetweenRays,
],
uuid,
})
return () => {
currentWorker.removePlatformController({ uuid })
}
}, deps)
const api = useMemo<PlatformControllerPublicApi>(() => {
return {
collisions: {
subscribe: subscribe(ref, worker, subscriptions, 'collisions', undefined, 'controllers'),
},
raysData: {
subscribe: subscribe(ref, worker, subscriptions, 'raysData', undefined, 'controllers'),
},
}
}, deps)
return [ref, api]
} | the_stack |
import { TokenError } from 'ebnf';
import { Scope } from './Scope';
import { Type, NativeTypes, FunctionType } from './types';
import { Annotation, IAnnotationConstructor, annotations } from './annotations';
import { Reference } from './Reference';
export interface LocalGlobalHeapReference {
type?: Type;
name: string;
declarationNode?: Nodes.Node;
}
export class Global implements LocalGlobalHeapReference {
type?: Type;
name: string;
constructor(public declarationNode: Nodes.NameIdentifierNode) {
this.name = declarationNode.internalIdentifier!;
}
}
export class Local implements LocalGlobalHeapReference {
type?: Type;
/** index in the function */
constructor(public index: number, public name: string, public declarationNode?: Nodes.Node) {}
}
export enum PhaseFlags {
Semantic = 0,
NameInitialization,
Scope,
TypeInitialization,
TypeCheck,
PreCompilation,
Compilation,
CodeGeneration
}
export namespace Nodes {
export interface ASTNode {
readonly type: string;
readonly text: string;
readonly start: number;
readonly end: number;
readonly errors: TokenError[];
readonly moduleName: string;
readonly children: ReadonlyArray<ASTNode>;
}
export abstract class Node {
// TODO: remove this VVVVVVVVVV
hasParentheses: boolean = false;
isTypeResolved = false;
parent?: Node;
private ownScope: Scope | undefined;
private annotations?: Set<Annotation>;
constructor(public astNode: ASTNode) {}
get scope(): Scope | undefined {
if (this.ownScope) return this.ownScope;
if (this.parent) return this.parent.scope;
return undefined;
}
set scope(scope: Scope | undefined) {
this.ownScope = scope;
}
/** Name of the node constructor */
get nodeName(): string {
return this.constructor.name;
}
get children(): Node[] {
return this.childrenOrEmpty.filter($ => !!$) as Node[];
}
abstract get childrenOrEmpty(): (Node | void)[];
hasAnnotation<T extends Annotation = Annotation>(name: Annotation | IAnnotationConstructor<T>) {
if (!this.annotations) return false;
if (typeof name === 'object') {
return this.annotations.has(name);
} else {
return !!this.getAnnotation(name);
}
}
getAnnotationsByClass<T extends Annotation>(klass: IAnnotationConstructor<T>): T[] {
const ret: T[] = [];
if (this.annotations) {
this.annotations.forEach($ => {
if ($ instanceof klass) ret.push($);
});
}
return ret;
}
getAnnotation<T extends Annotation>(klass: IAnnotationConstructor<T>): T | null {
const ret: T[] = [];
if (this.annotations) {
this.annotations.forEach($ => {
if ($ instanceof klass) ret.push($);
});
}
return ret[ret.length - 1] || null;
}
removeAnnotation<T extends Annotation = Annotation>(name: Annotation | IAnnotationConstructor<T>) {
if (typeof name === 'object') {
this.annotations && this.annotations.delete(name);
} else {
this.annotations &&
this.getAnnotationsByClass(name).forEach($ => this.annotations && this.annotations.delete($));
}
}
annotate(annotation: Annotation) {
if (!this.annotations) this.annotations = new Set();
this.annotations.add(annotation);
}
getAnnotations(): Annotation[];
getAnnotations<T extends Annotation>(klass: IAnnotationConstructor<T>): T[];
getAnnotations<T extends Annotation>(klass?: IAnnotationConstructor<T>): T[] {
const ret: T[] = [];
if (this.annotations) {
this.annotations.forEach($ => {
if (!klass || $ instanceof klass) ret.push($ as T);
});
}
return ret;
}
toString(): string {
console.trace();
throw new Error('Cannot print nodes with toString');
}
}
export abstract class ExpressionNode extends Node {}
export class NameIdentifierNode extends Node {
impls = new Set<ImplDirective>();
internalIdentifier?: string;
get childrenOrEmpty(): Node[] {
return [];
}
constructor(astNode: ASTNode, public name: string) {
super(astNode);
}
static fromString(name: string, astNode: ASTNode) {
const r = new NameIdentifierNode(astNode, name);
return r;
}
}
export class QNameNode extends Node {
constructor(astNode: ASTNode, public readonly names: NameIdentifierNode[]) {
super(astNode);
}
static fromString(name: string, astNode: ASTNode): QNameNode {
const names = name.split('::').map($ => NameIdentifierNode.fromString($, astNode));
const r = new QNameNode(astNode, names);
return r;
}
get childrenOrEmpty() {
return this.names || [];
}
deconstruct() {
const moduleName = this.names
.slice(0, -1)
.map($ => $.name)
.join('::');
const variable = this.names[this.names.length - 1].name;
return { moduleName, variable };
}
get text() {
return this.names.map($ => $.name).join('::');
}
}
export abstract class TypeNode extends Node {}
export class TypeReducerNode extends Node {
get childrenOrEmpty(): Node[] {
return [];
}
}
export class SignatureParameterNode extends TypeNode {
parameterName?: NameIdentifierNode;
constructor(astNode: ASTNode, public readonly parameterType: TypeNode) {
super(astNode);
}
get childrenOrEmpty() {
return [this.parameterName, this.parameterType];
}
}
export class FunctionTypeNode extends TypeNode {
typeParameters?: string[];
effect?: TypeNode;
returnType?: TypeNode;
constructor(astNode: ASTNode, public readonly parameters: SignatureParameterNode[]) {
super(astNode);
}
get childrenOrEmpty() {
return [...(this.parameters || []), this.returnType, this.effect];
}
}
export class EffectMemberDeclarationNode extends TypeNode {
name?: NameIdentifierNode;
typeParameters?: string[];
parameters?: SignatureParameterNode[];
returnType?: TypeNode;
get childrenOrEmpty() {
return [this.name];
}
}
export class ReferenceNode extends ExpressionNode {
isLocal: boolean = false;
resolvedReference?: Reference;
constructor(astNode: ASTNode, public readonly variable: QNameNode) {
super(astNode);
}
get childrenOrEmpty() {
return [this.variable];
}
}
export class BlockNode extends ExpressionNode {
label?: string;
constructor(astNode: ASTNode, public readonly statements: Node[]) {
super(astNode);
}
get childrenOrEmpty() {
return this.statements || [];
}
}
export class MemberNode extends ExpressionNode {
resolvedReference?: Reference;
constructor(
astNode: ASTNode,
public readonly lhs: ExpressionNode,
public readonly operator: string,
public readonly memberName: NameIdentifierNode
) {
super(astNode);
}
get childrenOrEmpty() {
return [this.lhs, this.memberName];
}
}
export class DecoratorNode extends Node {
constructor(
astNode: ASTNode,
public readonly decoratorName: NameIdentifierNode,
public readonly args: LiteralNode<any>[]
) {
super(astNode);
}
get childrenOrEmpty() {
return [this.decoratorName, ...(this.args || [])];
}
}
export abstract class DirectiveNode extends Node {
decorators?: DecoratorNode[];
isPublic: boolean = false;
}
export class DocumentNode extends Node {
readonly directives: DirectiveNode[] = [];
moduleName!: string;
fileName!: string;
content!: string;
analysis = {
version: 0,
nextPhase: PhaseFlags.Semantic,
isTypeAnalysisPassNeeded: true,
areTypesResolved: false
};
typeNumbers: Map<string, number> = new Map();
nameIdentifiers: Set<string> = new Set();
importedModules: Set<string> = new Set<string>();
importedBy: Set<string> = new Set<string>();
get childrenOrEmpty() {
return this.directives;
}
}
export class ParameterNode extends Node {
parameterType?: TypeNode;
defaultValue?: ExpressionNode;
constructor(astNode: ASTNode, public readonly parameterName: NameIdentifierNode) {
super(astNode);
}
get childrenOrEmpty() {
return [this.parameterName, this.parameterType, this.defaultValue];
}
}
export class FunctionNode extends Node {
functionReturnType?: TypeNode;
parameters: ParameterNode[] = [];
body?: ExpressionNode;
get childrenOrEmpty() {
return [this.functionName, ...this.parameters, this.functionReturnType, this.body];
}
/** Array of locals by index. */
localsByIndex: Local[] = [];
/** List of additional non-parameter locals. */
additionalLocals: Local[] = [];
private tempI32s: Local[] | null = null;
private tempI64s: Local[] | null = null;
private tempF32s: Local[] | null = null;
private tempF64s: Local[] | null = null;
constructor(astNode: ASTNode, public readonly functionName: NameIdentifierNode) {
super(astNode);
}
processParameters() {
let localIndex = 0;
this.parameters.forEach(parameter => {
let local = new Local(localIndex++, parameter.parameterName.name, parameter.parameterName);
this.localsByIndex[local.index] = local;
parameter.annotate(new annotations.LocalIdentifier(local));
});
}
/** Adds a local of the specified type. */
addLocal(type: Type, declaration?: NameIdentifierNode): Local {
// if it has a name, check previously as this method will throw otherwise
let localIndex = this.parameters.length + this.additionalLocals.length;
let local = new Local(
localIndex,
declaration ? declaration.internalIdentifier! : 'var$' + localIndex.toString(10),
declaration
);
local.type = type;
this.localsByIndex[local.index] = local;
this.additionalLocals.push(local);
return local;
}
/** Gets a free temporary local of the specified type. */
getTempLocal(type: Type): Local {
let temps: Local[] | null;
switch (type.binaryenType) {
case NativeTypes.i32: {
temps = this.tempI32s;
break;
}
case NativeTypes.i64: {
temps = this.tempI64s;
break;
}
case NativeTypes.f32: {
temps = this.tempF32s;
break;
}
case NativeTypes.f64: {
temps = this.tempF64s;
break;
}
default:
console.trace('concrete type expected ' + type.toString());
throw new Error('concrete type expected');
}
let local: Local;
if (temps && temps.length) {
local = temps.pop()!;
local.type = type;
} else {
local = this.addLocal(type);
}
return local;
}
/** Frees the temporary local for reuse. */
freeTempLocal(local: Local): void {
let temps: Local[];
if (!local.type) throw new Error('type is null'); // internal error
switch (local.type.binaryenType) {
case NativeTypes.i32: {
temps = this.tempI32s || (this.tempI32s = []);
break;
}
case NativeTypes.i64: {
temps = this.tempI64s || (this.tempI64s = []);
break;
}
case NativeTypes.f32: {
temps = this.tempF32s || (this.tempF32s = []);
break;
}
case NativeTypes.f64: {
temps = this.tempF64s || (this.tempF64s = []);
break;
}
default:
console.trace('concrete type expected');
throw new Error('concrete type expected');
}
if (local.index < 0) throw new Error('invalid local index');
temps.push(local);
}
/** Gets and immediately frees a temporary local of the specified type. */
getAndFreeTempLocal(type: Type): Local {
let temps: Local[];
switch (type.binaryenType) {
case NativeTypes.i32: {
temps = this.tempI32s || (this.tempI32s = []);
break;
}
case NativeTypes.i64: {
temps = this.tempI64s || (this.tempI64s = []);
break;
}
case NativeTypes.f32: {
temps = this.tempF32s || (this.tempF32s = []);
break;
}
case NativeTypes.f64: {
temps = this.tempF64s || (this.tempF64s = []);
break;
}
default:
console.trace('concrete type expected');
throw new Error('concrete type expected');
}
let local: Local;
if (temps.length) {
local = temps[temps.length - 1];
local.type = type;
} else {
local = this.addLocal(type);
temps.push(local);
}
return local;
}
}
export class ImplDirective extends DirectiveNode {
baseImpl?: ReferenceNode;
selfTypeName?: NameIdentifierNode;
readonly namespaceNames: Map<string, NameIdentifierNode> = new Map();
constructor(
astNode: ASTNode,
public readonly targetImpl: ReferenceNode,
public readonly directives: DirectiveNode[]
) {
super(astNode);
}
get childrenOrEmpty() {
return [
...(this.decorators || []),
this.targetImpl,
...(this.baseImpl ? [this.baseImpl] : []),
...(this.directives || [])
];
}
}
export class ImportDirectiveNode extends DirectiveNode {
allItems: boolean = true;
alias: NameIdentifierNode | null = null;
constructor(astNode: ASTNode, public readonly module: QNameNode) {
super(astNode);
}
get childrenOrEmpty() {
return [...(this.decorators || []), this.module, this.alias || void 0];
}
}
export class FunDirectiveNode extends DirectiveNode {
constructor(
astNode: ASTNode,
public readonly functionNode: FunctionNode,
public readonly decorators: DecoratorNode[]
) {
super(astNode);
}
get childrenOrEmpty() {
return [...(this.decorators || []), this.functionNode];
}
}
export class EffectDirectiveNode extends DirectiveNode {
effect?: EffectDeclarationNode;
get childrenOrEmpty() {
return [...(this.decorators || []), this.effect];
}
}
export class OverloadedFunctionNode extends DirectiveNode {
functions: FunDirectiveNode[] = [];
constructor(astNode: ASTNode, public readonly functionName: NameIdentifierNode) {
super(astNode);
}
get childrenOrEmpty() {
return [...(this.decorators || []), this.functionName, ...this.functions];
}
}
export class VarDeclarationNode extends Node {
variableType?: TypeNode;
constructor(astNode: ASTNode, public readonly variableName: NameIdentifierNode, public value: ExpressionNode) {
super(astNode);
}
get childrenOrEmpty() {
return [this.variableName, this.variableType, this.value];
}
}
export class VarDirectiveNode extends DirectiveNode {
constructor(astNode: ASTNode, public readonly decl: VarDeclarationNode) {
super(astNode);
}
get childrenOrEmpty() {
return [...(this.decorators || []), this.decl];
}
}
export class AssignmentNode extends Node {
constructor(astNode: ASTNode, public readonly lhs: ExpressionNode, public readonly rhs: ExpressionNode) {
super(astNode);
}
get childrenOrEmpty() {
return [this.lhs, this.rhs];
}
}
export class TypeDirectiveNode extends DirectiveNode {
valueType?: TypeNode;
constructor(astNode: ASTNode, public readonly variableName: NameIdentifierNode) {
super(astNode);
}
get childrenOrEmpty() {
return [...(this.decorators || []), this.variableName, this.valueType];
}
}
export class TraitDirectiveNode extends DirectiveNode {
readonly namespaceNames: Map<string, NameIdentifierNode> = new Map();
selfTypeName?: NameIdentifierNode;
constructor(astNode: ASTNode, public readonly traitName: NameIdentifierNode, public directives: DirectiveNode[]) {
super(astNode);
}
get childrenOrEmpty() {
return [...(this.decorators || []), this.traitName, ...this.directives];
}
}
export class EnumDirectiveNode extends DirectiveNode {
constructor(
astNode: ASTNode,
public readonly variableName: NameIdentifierNode,
public readonly declarations: StructDeclarationNode[]
) {
super(astNode);
}
get childrenOrEmpty() {
return [...(this.decorators || []), this.variableName, ...(this.declarations || [])];
}
}
export abstract class LiteralNode<T> extends ExpressionNode {
value?: T;
rawValue: string = '';
resolvedReference?: Reference;
constructor(astNode: ASTNode, public typeName: string) {
super(astNode);
if (astNode) {
this.rawValue = astNode.text;
}
}
}
export class FloatLiteral extends LiteralNode<number> {
suffixReference?: ReferenceNode;
get value(): number {
return parseFloat(this.rawValue);
}
set value(value: number) {
this.rawValue = value.toString();
}
get childrenOrEmpty() {
return [this.suffixReference];
}
}
export class IntegerLiteral extends LiteralNode<number> {
suffixReference?: ReferenceNode;
get value(): number {
return parseInt(this.rawValue, 10);
}
set value(value: number) {
this.rawValue = value.toString();
}
get childrenOrEmpty() {
return [this.suffixReference];
}
}
export class UnknownExpressionNode extends ExpressionNode {
get childrenOrEmpty() {
return [];
}
}
export class StructTypeNode extends TypeNode {
constructor(astNode: ASTNode, public readonly parameters: ParameterNode[]) {
super(astNode);
}
get childrenOrEmpty() {
return this.parameters;
}
}
export class StackTypeNode extends TypeNode {
metadata: Record<string, LiteralNode<any>> = {};
get childrenOrEmpty() {
return [];
}
}
export class InjectedTypeNode extends TypeNode {
get childrenOrEmpty() {
return [];
}
}
export class HexLiteral extends IntegerLiteral {
suffixReference?: ReferenceNode;
get value(): number {
return parseInt(this.rawValue, 16);
}
set value(value: number) {
this.rawValue = value.toString(16);
}
get childrenOrEmpty() {
return [this.suffixReference];
}
}
export class BooleanLiteral extends LiteralNode<boolean> {
get value(): boolean {
return this.rawValue.trim() === 'true';
}
set value(value: boolean) {
this.rawValue = value.toString();
}
get childrenOrEmpty() {
return [];
}
}
export class StringLiteral extends LiteralNode<string> {
value?: string;
offset?: number;
length?: number;
get childrenOrEmpty() {
return [];
}
}
export abstract class AbstractFunctionCallNode extends ExpressionNode {
abstract argumentsNode: ExpressionNode[];
resolvedFunctionType?: FunctionType;
}
export class InjectedFunctionCallNode extends AbstractFunctionCallNode {
argumentsNode: ExpressionNode[] = [];
get childrenOrEmpty() {
return this.argumentsNode;
}
}
export class FunctionCallNode extends AbstractFunctionCallNode {
isInfix: boolean = false;
constructor(
astNode: ASTNode,
public functionNode: ExpressionNode,
public readonly argumentsNode: ExpressionNode[]
) {
super(astNode);
}
get childrenOrEmpty() {
return [this.functionNode, ...this.argumentsNode];
}
}
export class BinaryExpressionNode extends ExpressionNode {
constructor(
astNode: ASTNode,
public readonly operator: NameIdentifierNode,
public lhs: ExpressionNode,
public rhs: ExpressionNode
) {
super(astNode);
}
get childrenOrEmpty() {
return [this.lhs, this.operator, this.rhs];
}
}
export class AsExpressionNode extends AbstractFunctionCallNode {
get lhs() {
return this.argumentsNode[0];
}
set lhs(value: ExpressionNode) {
this.argumentsNode[0] = value;
}
argumentsNode: ExpressionNode[] = [];
rhs: TypeNode;
constructor(astNode: ASTNode, lhs: ExpressionNode, rhs: TypeNode) {
super(astNode);
this.lhs = lhs;
this.rhs = rhs;
}
get childrenOrEmpty() {
return [this.lhs, this.rhs];
}
}
export class IsExpressionNode extends AbstractFunctionCallNode {
get lhs() {
return this.argumentsNode[0];
}
set lhs(value: ExpressionNode) {
this.argumentsNode[0] = value;
}
booleanReference?: Reference;
argumentsNode: ExpressionNode[] = [];
rhs: TypeNode;
constructor(astNode: ASTNode, lhs: ExpressionNode, rhs: TypeNode) {
super(astNode);
this.lhs = lhs;
this.rhs = rhs;
}
get childrenOrEmpty() {
return [this.lhs, this.rhs];
}
}
export class UnaryExpressionNode extends AbstractFunctionCallNode {
get rhs() {
return this.argumentsNode[0];
}
set rhs(value: TypeNode) {
this.argumentsNode[0] = value;
}
argumentsNode: Node[] = [];
constructor(astNode: ASTNode, public readonly operator: NameIdentifierNode, rhs: TypeNode) {
super(astNode);
this.rhs = rhs;
}
get childrenOrEmpty() {
return [this.rhs];
}
}
export class WasmAtomNode extends Node {
constructor(astNode: ASTNode, public readonly symbol: string, public readonly args: ExpressionNode[]) {
super(astNode);
}
get childrenOrEmpty() {
return [...this.args];
}
}
export class WasmExpressionNode extends ExpressionNode {
constructor(astNode: ASTNode, public readonly atoms: WasmAtomNode[]) {
super(astNode);
}
get childrenOrEmpty() {
return this.atoms || [];
}
}
export abstract class MatcherNode extends ExpressionNode {
declaredName?: NameIdentifierNode;
parent?: PatternMatcherNode;
booleanReference?: Reference;
constructor(astNode: ASTNode, public readonly rhs: ExpressionNode) {
super(astNode);
}
get childrenOrEmpty() {
return [this.declaredName, this.rhs];
}
}
export class IfNode extends ExpressionNode {
booleanReference?: Reference;
constructor(
astNode: ASTNode,
public readonly condition: ExpressionNode,
public readonly truePart: ExpressionNode,
public readonly falsePart?: ExpressionNode
) {
super(astNode);
}
get childrenOrEmpty() {
return [this.condition, this.truePart, this.falsePart];
}
}
export class MatchConditionNode extends MatcherNode {
constructor(astNode: ASTNode, public readonly condition: ExpressionNode, public readonly rhs: ExpressionNode) {
super(astNode, rhs);
}
get childrenOrEmpty() {
return [...super.childrenOrEmpty, this.condition];
}
}
export class MatchCaseIsNode extends MatcherNode {
deconstructorNames?: NameIdentifierNode[];
resolvedFunctionType?: FunctionType;
constructor(astNode: ASTNode, public readonly typeReference: ReferenceNode, public rhs: ExpressionNode) {
super(astNode, rhs);
}
get childrenOrEmpty() {
return [...super.childrenOrEmpty, this.typeReference, ...(this.deconstructorNames || [])];
}
}
export class MatchLiteralNode extends MatcherNode {
resolvedFunctionType?: FunctionType;
constructor(astNode: ASTNode, public readonly literal: LiteralNode<any>, public readonly rhs: ExpressionNode) {
super(astNode, rhs);
}
get childrenOrEmpty() {
return [...super.childrenOrEmpty, this.literal];
}
}
export class UnionTypeNode extends TypeNode {
of: TypeNode[] = [];
get childrenOrEmpty() {
return this.of;
}
}
export class IntersectionTypeNode extends TypeNode {
of: TypeNode[] = [];
get childrenOrEmpty() {
return this.of || [];
}
}
export class StructDeclarationNode extends TypeNode {
isPublic: boolean = true;
constructor(
astNode: ASTNode,
public readonly declaredName: NameIdentifierNode,
public readonly parameters: ParameterNode[]
) {
super(astNode);
}
get childrenOrEmpty() {
return [this.declaredName, ...(this.parameters || [])];
}
}
export class EffectDeclarationNode extends Node {
elements?: FunctionTypeNode[];
constructor(astNode: ASTNode, public readonly name: NameIdentifierNode) {
super(astNode);
}
get childrenOrEmpty() {
return [this.name, ...(this.elements || [])];
}
}
export class MatchDefaultNode extends MatcherNode {}
export class PatternMatcherNode extends ExpressionNode {
carryType?: Type;
constructor(astNode: ASTNode, public readonly lhs: ExpressionNode, public readonly matchingSet: MatcherNode[]) {
super(astNode);
}
get childrenOrEmpty(): Node[] {
return [this.lhs, ...(this.matchingSet || [])];
}
}
export class LoopNode extends ExpressionNode {
constructor(astNode: ASTNode, public readonly body: ExpressionNode) {
super(astNode);
}
get childrenOrEmpty() {
return [this.body];
}
}
export class ContinueNode extends Node {
get childrenOrEmpty() {
return [];
}
}
export class BreakNode extends Node {
get childrenOrEmpty() {
return [];
}
}
}
export function findNodesByType<T>(
astRoot: { children: any[] },
type: { new (...args: any[]): T },
list: T[] = []
): T[] {
if (astRoot instanceof type) {
list.push(astRoot);
}
astRoot.children.forEach($ => findNodesByType($, type, list));
return list;
}
export function findNodesByTypeInChildren<T>(
astRoot: { children: any[] },
type: { new (...args: any[]): T },
list: T[] = []
): T[] {
astRoot.children.forEach($ => {
if ($ instanceof type) {
list.push($);
}
});
return list;
} | the_stack |
import {
lambda1,
StreamSink,
StreamLoop,
CellSink,
Transaction,
Tuple2,
Operational,
Cell,
CellLoop,
getTotalRegistrations
} from '../../lib/Lib';
afterEach(() => {
if (getTotalRegistrations() != 0) {
throw new Error('listeners were not deregistered');
}
});
test('should test map()', (done) => {
const s = new StreamSink<number>();
const out: number[] = [];
const kill = s.map(a => a + 1)
.listen(a => {
out.push(a);
done();
});
s.send(7);
kill();
expect([8]).toEqual(out);
});
test('should throw an error send_with_no_listener_1', () => {
const s = new StreamSink<number>();
try {
s.send(7);
} catch (e) {
expect(e.message).toBe('send() was invoked before listeners were registered');
}
});
test('should (not?) throw an error send_with_no_listener_2', () => {
const s = new StreamSink<number>();
const out: number[] = [];
const kill = s.map(a => a + 1)
.listen(a => out.push(a));
s.send(7);
kill();
try {
// TODO: the message below is bit misleading, need to verify with Stephen B.
// - "this should not throw, because once() uses this mechanism"
s.send(9);
} catch (e) {
expect(e.message).toBe('send() was invoked before listeners were registered');
}
});
test('should map_tack', (done) => {
const s = new StreamSink<number>(),
t = new StreamSink<string>(),
out: number[] = [],
kill = s.map(lambda1((a: number) => a + 1, [t]))
.listen(a => {
out.push(a);
done();
});
s.send(7);
t.send("banana");
kill();
expect([8]).toEqual(out);
});
test('should test mapTo()', (done) => {
const s = new StreamSink<number>(),
out: string[] = [],
kill = s.mapTo("fusebox")
.listen(a => {
out.push(a);
if (out.length === 2) {
done();
}
});
s.send(7);
s.send(9);
kill();
expect(['fusebox', 'fusebox']).toEqual(out);
});
test('should do mergeNonSimultaneous', (done) => {
const s1 = new StreamSink<number>(),
s2 = new StreamSink<number>(),
out: number[] = [];
const kill = s2.orElse(s1)
.listen(a => {
out.push(a);
if (out.length === 3) {
done();
}
});
s1.send(7);
s2.send(9);
s1.send(8);
kill();
expect([7, 9, 8]).toEqual(out);
});
test('should do mergeSimultaneous', (done) => {
const s1 = new StreamSink<number>((l: number, r: number) => { return r; }),
s2 = new StreamSink<number>((l: number, r: number) => { return r; }),
out: number[] = [],
kill = s2.orElse(s1)
.listen(a => {
out.push(a);
if (out.length === 5) {
done();
}
});
Transaction.run<void>(() => {
s1.send(7);
s2.send(60);
});
Transaction.run<void>(() => {
s1.send(9);
});
Transaction.run<void>(() => {
s1.send(7);
s1.send(60);
s2.send(8);
s2.send(90);
});
Transaction.run<void>(() => {
s2.send(8);
s2.send(90);
s1.send(7);
s1.send(60);
});
Transaction.run<void>(() => {
s2.send(8);
s1.send(7);
s2.send(90);
s1.send(60);
});
kill();
expect([60, 9, 90, 90, 90]).toEqual(out);
});
test('should do coalesce', (done) => {
const s = new StreamSink<number>((a, b) => a + b),
out: number[] = [],
kill = s.listen(a => {
out.push(a);
if (out.length === 2) {
done();
}
});
Transaction.run<void>(() => {
s.send(2);
});
Transaction.run<void>(() => {
s.send(8);
s.send(40);
});
kill();
expect([2, 48]).toEqual(out);
});
test('should test filter()', (done) => {
const s = new StreamSink<number>(),
out: number[] = [],
kill = s.filter(a => a < 10)
.listen(a => {
out.push(a);
if (out.length === 2) {
done();
}
});
s.send(2);
s.send(16);
s.send(9);
kill();
expect([2, 9]).toEqual(out);
});
test('should test filterNotNull()', (done) => {
const s = new StreamSink<string>(),
out: string[] = [],
kill = s.filterNotNull()
.listen(a => {
out.push(a);
if (out.length === 2) {
done();
}
});
s.send("tomato");
s.send(null);
s.send("peach");
kill();
expect(["tomato", "peach"]).toEqual(out);
});
test('should test merge()', (done) => {
const sa = new StreamSink<number>(),
sb = sa.map(x => Math.floor(x / 10))
.filter(x => x != 0),
sc = sa.map(x => x % 10)
.merge(sb, (x, y) => x + y),
out: number[] = [],
kill = sc.listen(a => {
out.push(a);
if (out.length === 2) {
done();
}
});
sa.send(2);
sa.send(52);
kill();
expect([2, 7]).toEqual(out);
});
test('should test loop()', (done) => {
const sa = new StreamSink<number>(),
sc = Transaction.run(() => {
const sb = new StreamLoop<number>(),
sc_ = sa.map(x => x % 10).merge(sb,
(x, y) => x + y),
sb_out = sa.map(x => Math.floor(x / 10))
.filter(x => x != 0);
sb.loop(sb_out);
return sc_;
}),
out: number[] = [],
kill = sc.listen(a => {
out.push(a);
if (out.length === 2) {
done();
}
});
sa.send(2);
sa.send(52);
kill();
expect([2, 7]).toEqual(out);
});
test('should test gate()', (done) => {
const s = new StreamSink<string>(),
pred = new CellSink<boolean>(true),
out: string[] = [],
kill = s.gate(pred).listen(a => {
out.push(a);
if (out.length === 2) {
done();
}
});
s.send("H");
pred.send(false);
s.send('O');
pred.send(true);
s.send('I');
kill();
expect(["H", "I"]).toEqual(out);
});
test('should test collect()', (done) => {
const ea = new StreamSink<number>(),
out: number[] = [],
sum = ea.collect(0, (a, s) => new Tuple2(a + s + 100, a + s)),
kill = sum.listen(a => {
out.push(a);
if (out.length === 5) {
done();
}
});
ea.send(5);
ea.send(7);
ea.send(1);
ea.send(2);
ea.send(3);
kill();
expect([105, 112, 113, 115, 118]).toEqual(out);
});
test('should test accum()', (done) => {
const ea = new StreamSink<number>(),
out: number[] = [],
sum = ea.accum(100, (a, s) => a + s),
kill = sum.listen(a => {
out.push(a);
if (out.length === 6) {
done();
}
});
ea.send(5);
ea.send(7);
ea.send(1);
ea.send(2);
ea.send(3);
kill();
expect([100, 105, 112, 113, 115, 118]).toEqual(out);
});
test('should test once()', (done) => {
const s = new StreamSink<string>(),
out: string[] = [],
kill = s.once().listen(a => {
out.push(a);
done();
});
s.send("A");
s.send("B");
s.send("C");
kill();
expect(["A"]).toEqual(out);
});
test('should test defer()', (done) => {
const s = new StreamSink<string>(),
c = s.hold(" "),
out: string[] = [],
kill = Operational.defer(s).snapshot1(c)
.listen(a => {
out.push(a);
if (out.length === 3) {
done();
}
});
s.send("C");
s.send("B");
s.send("A");
kill();
expect(["C", "B", "A"]).toEqual(out);
});
test('should test hold()', (done) => {
const s = new StreamSink<number>(),
c = s.hold(0),
out: number[] = [],
kill = Operational.updates(c)
.listen(a => {
out.push(a);
if (out.length === 2) {
done();
}
});
s.send(2);
s.send(9);
kill();
expect([2, 9]).toEqual(out);
});
test('should do holdIsDelayed', (done) => {
const s = new StreamSink<number>(),
h = s.hold(0),
sPair = s.snapshot(h, (a, b) => a + " " + b),
out: string[] = [],
kill = sPair.listen(a => {
out.push(a);
if (out.length === 2) {
done();
}
});
s.send(2);
s.send(3);
kill();
expect(["2 0", "3 2"]).toEqual(out);
});
test('should test switchC()', (done) => {
class SC {
constructor(a: string, b: string, sw: string) {
this.a = a;
this.b = b;
this.sw = sw;
}
a: string;
b: string;
sw: string;
}
const ssc = new StreamSink<SC>(),
// Split each field out of SC so we can update multiple cells in a
// single transaction.
ca = ssc.map(s => s.a).filterNotNull().hold("A"),
cb = ssc.map(s => s.b).filterNotNull().hold("a"),
csw_str = ssc.map(s => s.sw).filterNotNull().hold("ca"),
// ****
// NOTE! Because this lambda contains references to Sodium objects, we
// must declare them explicitly using lambda1() so that Sodium knows
// about the dependency, otherwise it can't manage the memory.
// ****
csw = csw_str.map(lambda1(s => s == "ca" ? ca : cb, [ca, cb])),
co = Cell.switchC(csw),
out: string[] = [],
kill = co.listen(c => {
out.push(c);
if (out.length === 11) {
done();
}
});
ssc.send(new SC("B", "b", null));
ssc.send(new SC("C", "c", "cb"));
ssc.send(new SC("D", "d", null));
ssc.send(new SC("E", "e", "ca"));
ssc.send(new SC("F", "f", null));
ssc.send(new SC(null, null, "cb"));
ssc.send(new SC(null, null, "ca"));
ssc.send(new SC("G", "g", "cb"));
ssc.send(new SC("H", "h", "ca"));
ssc.send(new SC("I", "i", "ca"));
kill();
expect(["A", "B", "c", "d", "E", "F", "f", "F", "g", "H", "I"]).toEqual(out);
});
test('should test switchS()', (done) => {
class SS {
constructor(a: string, b: string, sw: string) {
this.a = a;
this.b = b;
this.sw = sw;
}
a: string;
b: string;
sw: string;
}
const sss = new StreamSink<SS>(),
sa = sss.map(s => s.a),
sb = sss.map(s => s.b),
csw_str = sss.map(s => s.sw).filterNotNull().hold("sa"),
// ****
// NOTE! Because this lambda contains references to Sodium objects, we
// must declare them explicitly using lambda1() so that Sodium knows
// about the dependency, otherwise it can't manage the memory.
// ****
csw = csw_str.map(lambda1(sw => sw == "sa" ? sa : sb, [sa, sb])),
so = Cell.switchS(csw),
out: string[] = [],
kill = so.listen(x => {
out.push(x);
if (out.length === 9) {
done();
}
});
sss.send(new SS("A", "a", null));
sss.send(new SS("B", "b", null));
sss.send(new SS("C", "c", "sb"));
sss.send(new SS("D", "d", null));
sss.send(new SS("E", "e", "sa"));
sss.send(new SS("F", "f", null));
sss.send(new SS("G", "g", "sb"));
sss.send(new SS("H", "h", "sa"));
sss.send(new SS("I", "i", "sa"));
kill();
expect(["A", "B", "C", "d", "e", "F", "G", "h", "I"]).toEqual(out);
});
test('should do switchSSimultaneous', (done) => {
class SS2 {
s: StreamSink<number> = new StreamSink<number>();
}
const ss1 = new SS2(),
ss2 = new SS2(),
ss3 = new SS2(),
ss4 = new SS2(),
css = new CellSink<SS2>(ss1),
// ****
// NOTE! Because this lambda contains references to Sodium objects, we
// must declare them explicitly using lambda1() so that Sodium knows
// about the dependency, otherwise it can't manage the memory.
// ****
so = Cell.switchS(css.map(lambda1((b: SS2) => b.s, [ss1.s, ss2.s, ss3.s, ss4.s]))),
out: number[] = [],
kill = so.listen(c => {
out.push(c);
if (out.length === 10) {
done();
}
});
ss1.s.send(0);
ss1.s.send(1);
ss1.s.send(2);
css.send(ss2);
ss1.s.send(7);
ss2.s.send(3);
ss2.s.send(4);
ss3.s.send(2);
css.send(ss3);
ss3.s.send(5);
ss3.s.send(6);
ss3.s.send(7);
Transaction.run(() => {
ss3.s.send(8);
css.send(ss4);
ss4.s.send(2);
});
ss4.s.send(9);
kill();
expect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).toEqual(out);
});
test('should test loopCell', (done) => {
const sa = new StreamSink<number>(),
sum_out = Transaction.run(() => {
const sum = new CellLoop<number>(),
sum_out_ = sa.snapshot(sum, (x, y) => x + y).hold(0);
sum.loop(sum_out_);
return sum_out_;
}),
out: number[] = [],
kill = sum_out.listen(a => {
out.push(a);
if (out.length === 4) {
done();
}
});
sa.send(2);
sa.send(3);
sa.send(1);
kill();
expect([0, 2, 5, 6]).toEqual(out);
expect(6).toBe(sum_out.sample());
});
test('should test defer/split memory cycle', done => {
// We do not fire through sl here, as it would cause an infinite loop.
// This is just a memory management test.
let sl : StreamLoop<number>;
Transaction.run(() => {
sl = new StreamLoop<number>();
sl.loop(Operational.defer(sl));
});
let kill = sl.listen(() => {});
kill();
done();
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/billingPermissionsMappers";
import * as Parameters from "../models/parameters";
import { BillingManagementClientContext } from "../billingManagementClientContext";
/** Class representing a BillingPermissions. */
export class BillingPermissions {
private readonly client: BillingManagementClientContext;
/**
* Create a BillingPermissions.
* @param {BillingManagementClientContext} client Reference to the service client.
*/
constructor(client: BillingManagementClientContext) {
this.client = client;
}
/**
* Lists the billing permissions the caller has for a customer.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param customerName The ID that uniquely identifies a customer.
* @param [options] The optional parameters
* @returns Promise<Models.BillingPermissionsListByCustomerResponse>
*/
listByCustomer(billingAccountName: string, customerName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingPermissionsListByCustomerResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param customerName The ID that uniquely identifies a customer.
* @param callback The callback
*/
listByCustomer(billingAccountName: string, customerName: string, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param customerName The ID that uniquely identifies a customer.
* @param options The optional parameters
* @param callback The callback
*/
listByCustomer(billingAccountName: string, customerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
listByCustomer(billingAccountName: string, customerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingPermissionsListResult>, callback?: msRest.ServiceCallback<Models.BillingPermissionsListResult>): Promise<Models.BillingPermissionsListByCustomerResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
customerName,
options
},
listByCustomerOperationSpec,
callback) as Promise<Models.BillingPermissionsListByCustomerResponse>;
}
/**
* Lists the billing permissions the caller has on a billing account.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param [options] The optional parameters
* @returns Promise<Models.BillingPermissionsListByBillingAccountResponse>
*/
listByBillingAccount(billingAccountName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingPermissionsListByBillingAccountResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param callback The callback
*/
listByBillingAccount(billingAccountName: string, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingAccount(billingAccountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
listByBillingAccount(billingAccountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingPermissionsListResult>, callback?: msRest.ServiceCallback<Models.BillingPermissionsListResult>): Promise<Models.BillingPermissionsListByBillingAccountResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
options
},
listByBillingAccountOperationSpec,
callback) as Promise<Models.BillingPermissionsListByBillingAccountResponse>;
}
/**
* Lists the billing permissions the caller has on an invoice section.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param invoiceSectionName The ID that uniquely identifies an invoice section.
* @param [options] The optional parameters
* @returns Promise<Models.BillingPermissionsListByInvoiceSectionsResponse>
*/
listByInvoiceSections(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingPermissionsListByInvoiceSectionsResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param invoiceSectionName The ID that uniquely identifies an invoice section.
* @param callback The callback
*/
listByInvoiceSections(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param invoiceSectionName The ID that uniquely identifies an invoice section.
* @param options The optional parameters
* @param callback The callback
*/
listByInvoiceSections(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
listByInvoiceSections(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingPermissionsListResult>, callback?: msRest.ServiceCallback<Models.BillingPermissionsListResult>): Promise<Models.BillingPermissionsListByInvoiceSectionsResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
billingProfileName,
invoiceSectionName,
options
},
listByInvoiceSectionsOperationSpec,
callback) as Promise<Models.BillingPermissionsListByInvoiceSectionsResponse>;
}
/**
* Lists the billing permissions the caller has on a billing profile.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param [options] The optional parameters
* @returns Promise<Models.BillingPermissionsListByBillingProfileResponse>
*/
listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingPermissionsListByBillingProfileResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param callback The callback
*/
listByBillingProfile(billingAccountName: string, billingProfileName: string, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingProfile(billingAccountName: string, billingProfileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingPermissionsListResult>, callback?: msRest.ServiceCallback<Models.BillingPermissionsListResult>): Promise<Models.BillingPermissionsListByBillingProfileResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
billingProfileName,
options
},
listByBillingProfileOperationSpec,
callback) as Promise<Models.BillingPermissionsListByBillingProfileResponse>;
}
/**
* Lists the billing permissions the caller has for a customer.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.BillingPermissionsListByCustomerNextResponse>
*/
listByCustomerNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingPermissionsListByCustomerNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByCustomerNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByCustomerNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
listByCustomerNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingPermissionsListResult>, callback?: msRest.ServiceCallback<Models.BillingPermissionsListResult>): Promise<Models.BillingPermissionsListByCustomerNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByCustomerNextOperationSpec,
callback) as Promise<Models.BillingPermissionsListByCustomerNextResponse>;
}
/**
* Lists the billing permissions the caller has on a billing account.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.BillingPermissionsListByBillingAccountNextResponse>
*/
listByBillingAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingPermissionsListByBillingAccountNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByBillingAccountNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingAccountNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
listByBillingAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingPermissionsListResult>, callback?: msRest.ServiceCallback<Models.BillingPermissionsListResult>): Promise<Models.BillingPermissionsListByBillingAccountNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByBillingAccountNextOperationSpec,
callback) as Promise<Models.BillingPermissionsListByBillingAccountNextResponse>;
}
/**
* Lists the billing permissions the caller has on an invoice section.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.BillingPermissionsListByInvoiceSectionsNextResponse>
*/
listByInvoiceSectionsNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingPermissionsListByInvoiceSectionsNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByInvoiceSectionsNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByInvoiceSectionsNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
listByInvoiceSectionsNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingPermissionsListResult>, callback?: msRest.ServiceCallback<Models.BillingPermissionsListResult>): Promise<Models.BillingPermissionsListByInvoiceSectionsNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByInvoiceSectionsNextOperationSpec,
callback) as Promise<Models.BillingPermissionsListByInvoiceSectionsNextResponse>;
}
/**
* Lists the billing permissions the caller has on a billing profile.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.BillingPermissionsListByBillingProfileNextResponse>
*/
listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingPermissionsListByBillingProfileNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByBillingProfileNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingProfileNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingPermissionsListResult>): void;
listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingPermissionsListResult>, callback?: msRest.ServiceCallback<Models.BillingPermissionsListResult>): Promise<Models.BillingPermissionsListByBillingProfileNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByBillingProfileNextOperationSpec,
callback) as Promise<Models.BillingPermissionsListByBillingProfileNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByCustomerOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions",
urlParameters: [
Parameters.billingAccountName,
Parameters.customerName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingPermissionsListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByBillingAccountOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions",
urlParameters: [
Parameters.billingAccountName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingPermissionsListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByInvoiceSectionsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions",
urlParameters: [
Parameters.billingAccountName,
Parameters.billingProfileName,
Parameters.invoiceSectionName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingPermissionsListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByBillingProfileOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions",
urlParameters: [
Parameters.billingAccountName,
Parameters.billingProfileName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingPermissionsListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByCustomerNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingPermissionsListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByBillingAccountNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingPermissionsListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByInvoiceSectionsNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingPermissionsListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByBillingProfileNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingPermissionsListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
let title: string = unsafeWindow.document.title;
// GM_addStyle
const scriptTag: HTMLStyleElement = GM_addStyle('a { font-wight: bold }');
// GM_setValue
interface AppState {
form: { name: string };
}
GM_setValue('a', 'foobar');
GM_setValue('b', 123);
GM_setValue('c', true);
GM_setValue('d', { form: { name: 'Bob' } });
// GM_addValueChangeListener
GM_addValueChangeListener(
'a',
(name: string, oldValue: string, newValue: string, remote: boolean) => {}
);
GM_addValueChangeListener(
'b',
(name, oldValue: number, newValue: number, remote) => {}
);
GM_addValueChangeListener(
'c',
(name, oldValue: boolean, newValue: boolean, remote) => {}
);
const dValueChangeListenerId = GM_addValueChangeListener(
'd',
(name, oldValue: AppState, newValue: AppState, remote) => {}
);
// GM_removeValueChangeListener
GM_removeValueChangeListener(dValueChangeListenerId);
// GM_getValue
const a: string = GM_getValue('a', 'foobar');
const b: number = GM_getValue('b', 123);
const c: boolean = GM_getValue('c', true);
const d: any = GM_getValue('d', null);
const e: string = GM_getValue('e');
const f: number = GM_getValue('f');
const g: boolean = GM_getValue('g');
const h: AppState = GM_getValue('h');
// GM_deleteValue
GM_deleteValue('d');
// GM_listValues
GM_listValues().forEach((name: string) => {
console.log(name + ':', GM_getValue(name));
});
// GM_getResourceText
const template: string = GM_getResourceText('template');
// GM_getResourceURL
const templateURL: string = GM_getResourceURL('template');
// GM_registerMenuCommand
GM_registerMenuCommand('Hello, world (simple)', () => {
GM_log('Hello, world (simple) clicked');
});
const commandId = GM_registerMenuCommand(
'Hello, world!',
() => {
GM_log('Hello, world clicked');
},
'h'
);
// GM_unregisterMenuCommand
GM_unregisterMenuCommand(commandId);
// GM_xmlhttpRequest
// Bare Minimum
const abortHandle = GM_xmlhttpRequest({
method: 'GET',
url: 'http://www.example.com/',
onload(response) {
alert(response.responseText);
}
});
abortHandle.abort();
// GET request
GM_xmlhttpRequest({
method: 'GET',
url: 'http://www.example.net/',
headers: {
'User-Agent': 'Mozilla/5.0',
Accept: 'text/xml'
},
onload(response) {
let responseXML = response.responseXML;
// Inject responseXML into existing Object (only appropriate for XML content).
if (!responseXML) {
responseXML = new DOMParser().parseFromString(
response.responseText,
'text/xml'
);
}
GM_log(
[
response.status,
response.statusText,
response.readyState,
response.responseHeaders,
response.responseText,
response.finalUrl,
responseXML
].join('\n')
);
}
});
// POST request
GM_xmlhttpRequest({
method: 'POST',
url: 'http://www.example.net/login',
data: 'username=johndoe&password=xyz123',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
onload(response) {
if (response.responseText.indexOf('Logged in as') > -1) {
location.href = 'http://www.example.net/dashboard';
}
}
});
// HEAD request
GM_xmlhttpRequest({
url: 'http://www.example.com',
method: 'HEAD',
onload(response) {
GM_log(response.responseHeaders);
}
});
// All options
interface RequestContext {
form: {
name: string
};
}
GM_xmlhttpRequest<RequestContext>({
method: 'POST',
url: 'http://example.com/',
headers: { 'User-Agent': 'greasemonkey' },
data: 'foo=1&bar=2',
cookie: 'secret=42',
nocache: true,
revalidate: true,
binary: false,
timeout: 10,
context: {
form: {
name: 'Alice'
}
},
responseType: 'json',
overrideMimeType: 'text/plain',
anonymous: false,
user: 'guest',
password: 'abc123',
onabort() {},
onerror(response) {
GM_log(response.error);
},
onloadstart(response) {
GM_log(response.context.form.name);
},
onload(response) {
GM_log(response.context.form.name);
},
onprogress(response) {
GM_log(response.context.form.name, response.loaded);
},
onreadystatechange(response) {
GM_log(response.context.form.name);
},
ontimeout() {}
});
// Responses
GM_xmlhttpRequest({
method: 'GET',
url: 'http://example.com/',
onload: response => {
const readyState: number = response.readyState;
const responseHeaders: string = response.responseHeaders;
const responseText: string = response.responseText;
const status: number = response.status;
const statusText: string = response.statusText;
const context: any = response.context;
const finalUrl: string = response.finalUrl;
},
onprogress: response => {
const status: number = response.status;
const lengthComputable: boolean = response.lengthComputable;
const loaded: number = response.loaded;
const total: number = response.total;
}
});
// GM_download
const downloadHandle = GM_download({
url: 'http://tampermonkey.net/crx/tampermonkey.xml',
name: 'tampermonkey.xml',
headers: { 'User-Agent': 'greasemonkey' },
saveAs: true,
timeout: 3000,
onerror(response) {
GM_log(response.error, response.details);
},
ontimeout() {},
onload() {},
onprogress(response) {
GM_log(response.finalUrl, response.loaded, response.total);
}
});
downloadHandle.abort();
GM_download('http://tampermonkey.net/crx/tampermonkey.xml', 'tampermonkey.xml');
// GM_saveTab
interface TabState {
form: { name: string };
}
const tabState: TabState = {
form: {
name: 'Alice'
}
};
GM_saveTab(tabState);
// GM_getTab
GM_getTab((savedTabState: TabState) => {
GM_log(savedTabState.form.name);
});
// GM_getTabs
GM_getTabs(tabsMap => {
GM_log(tabsMap[0]);
});
// GM_log
GM_log('Hello, World!');
GM_log('Hello, World!', 'Again');
// GM_openInTab
GM_openInTab('http://www.example.com/');
GM_openInTab('http://www.example.com/', true);
const openTabObject = GM_openInTab('http://www.example.com/', {
active: true,
insert: true,
setParent: true
});
openTabObject.onclose = () => {
GM_log('Tab closed', openTabObject.closed);
};
openTabObject.close();
// GM_notification
const textNotification: Tampermonkey.NotificationDetails = {
text: 'Notification text',
title: 'Notification title',
image: 'https://tampermonkey.net/favicon.ico',
timeout: 5000,
silent: true,
onclick() {
GM_log(`Notification with id ${this.id} is clicked`);
},
ondone(clicked) {
GM_log(`Notification with id ${this.id} is clicked ${clicked}`);
}
};
const highlightNotification: Tampermonkey.NotificationDetails = {
highlight: true,
onclick: textNotification.onclick,
ondone: textNotification.ondone
};
GM_notification(textNotification);
GM_notification(highlightNotification);
GM_notification(textNotification, textNotification.ondone);
GM_notification(
'Notification text',
'Notification title',
'https://tampermonkey.net/favicon.ico',
function() {
GM_log(`Notification with id ${this.id} is clicked`);
}
);
// GM_setClipboard
GM_setClipboard('Some text in clipboard');
GM_setClipboard('<b>Some text in clipboard</b>', 'text');
GM_setClipboard('<b>Some text in clipboard</b>', {
type: 'text',
mimetype: 'text/plain'
});
// GM_info
// I created a basic userscript and copied GM_info from there for testing if the real thing fits the types
// I don't think there's a real way of testing this other than testing if it fits the original
const exampleInfo: Tampermonkey.ScriptInfo = {
isFirstPartyIsolation: undefined,
script: {
antifeatures: {},
author: null,
blockers: [],
copyright: null,
description: 'A description',
description_i18n: {},
downloadURL: null,
evilness: 0,
excludes: [],
grant: ['GM_setValue', 'GM_getValue', 'GM_deleteValue'],
header: 'headers',
homepage: null,
icon: null,
icon64: null,
includes: [],
lastModified: 1630000000000,
matches: ['https://*/*'],
name: 'Example userscript',
name_i18n: {},
namespace: 'namespace',
options: {
check_for_updates: false,
comment: '',
compat_foreach: false,
compat_metadata: false,
compat_prototypes: false,
compat_wrappedjsobject: false,
compatopts_for_requires: true,
noframes: null,
override: {
merge_connects: true,
merge_excludes: true,
merge_includes: true,
merge_matches: true,
orig_connects: ['https://google.com'],
orig_excludes: [],
orig_includes: [],
orig_matches: ['https://*/*'],
orig_noframes: null,
orig_run_at: 'document-idle',
use_blockers: [],
use_connects: [],
use_excludes: [],
use_includes: [],
use_matches: [],
},
run_at: 'document-idle',
},
position: 1,
resources: [
{
content: 'robots.txt',
meta: 'application',
name: 'github-robots.txt',
url: 'https://github.com/robots.txt',
},
],
'run-at': 'document-idle',
supportURL: null,
sync: {
imported: false,
},
unwrap: false,
updateURL: null,
uuid: 'c0ffeec0-ffee-c0ff-eec0-ffeec0ffeec0',
version: '1.0',
webRequest: [],
},
scriptMetaStr: 'metadata',
scriptSource: 'console.log(GM_info);',
scriptUpdateURL: undefined,
scriptWillUpdate: false,
version: '4.13.6136',
scriptHandler: 'Tampermonkey',
isIncognito: false,
downloadMode: 'native',
};
// GM.*
// GM.info
const exampleInfo1: Tampermonkey.ScriptInfo = GM.info;
async () => {
// GM.addStyle
// $ExpectType HTMLStyleElement
await GM.addStyle('div {color: #000;}');
// GM.setValue
// $ExpectType void
await GM.setValue('str', 'string');
await GM.setValue('num', 0);
await GM.setValue('bool', true);
await GM.setValue('obj', {
nested: {
values: true,
},
});
// GM.getValue
// $ExpectType string
await GM.getValue<string>('str');
// GM.deleteValue
await GM.deleteValue('a');
// GM.listValues
// $ExpectType string[]
await GM.listValues();
// GM.addValueChangeListener
// $ExpectType number
await GM.addValueChangeListener('a', (name: string, oldValue: string, newValue: string, remote: boolean) => {});
// $ExpectType number
await GM.addValueChangeListener('a', (name: string, oldValue: number, newValue: number, remote: boolean) => {});
// GM.removeValueChangeListener
// $ExpectType void
await GM.removeValueChangeListener(2);
// GM.getResourceText
// $ExpectType string
await GM.getResourceText('template');
// GM.getResourceUrl
// $ExpectType string
await GM.getResourceUrl('template');
// GM.registerMenuCommand
// $ExpectType number
await GM.registerMenuCommand('Do thing', () => {});
// $ExpectType number
await GM.registerMenuCommand('Do other thing', () => {}, 'T');
// GM.unregisterMenuCommand
// $ExpectType void
await GM.unregisterMenuCommand(1);
// GM.xmlHttpRequest
// Bare minimum
const minResponse = await GM.xmlHttpRequest({
url: 'https://github.com/',
method: 'GET',
});
// $ExpectType string
minResponse.finalUrl;
// $ExpectType number
minResponse.status;
// $ExpectType string
minResponse.responseText;
// GET request
await GM.xmlHttpRequest({
method: 'GET',
url: 'http://www.example.net/',
headers: {
'User-Agent': 'Mozilla/5.0',
Accept: 'text/xml',
},
});
// POST request
await GM.xmlHttpRequest({
method: 'POST',
url: 'http://www.example.net/login',
data: 'username=johndoe&password=xyz123',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
// HEAD request
await GM.xmlHttpRequest({
url: 'http://www.example.com',
method: 'HEAD',
});
// All options
interface RequestContext {
form: {
name: string;
};
}
const allOptionsResponse = await GM.xmlHttpRequest<RequestContext>({
method: 'POST',
url: 'http://example.com/',
headers: { 'User-Agent': 'greasemonkey' },
data: 'foo=1&bar=2',
cookie: 'secret=42',
nocache: true,
revalidate: true,
binary: false,
timeout: 10,
context: {
form: {
name: 'Alice',
},
},
responseType: 'json',
overrideMimeType: 'text/plain',
anonymous: false,
user: 'guest',
password: 'abc123',
onabort() {},
onerror(response) {
// $ExpectType string
response.error;
},
onloadstart(response) {
// $ExpectType RequestContext
response.context;
},
onload(response) {
// $ExpectType RequestContext
response.context;
},
onprogress(response) {
// $ExpectType number
response.status;
// $ExpectType boolean
response.lengthComputable;
// $ExpectType number
response.loaded;
// $ExpectType number
response.total;
},
onreadystatechange(response) {
GM_log(response.context.form.name);
},
ontimeout() {},
});
// $ExpectType string
allOptionsResponse.finalUrl;
// $ExpectType RequestContext
allOptionsResponse.context;
// $ExpectType number
allOptionsResponse.status;
// $ExpectType string
allOptionsResponse.statusText;
// $ExpectType string
allOptionsResponse.responseText;
// $ExpectType ReadyState
allOptionsResponse.readyState;
// $ExpectType string
allOptionsResponse.responseHeaders;
// $ExpectType string
allOptionsResponse.responseText;
// $ExpectType Document | null
allOptionsResponse.responseXML;
// GM.download
// $ExpectType void
await GM.download({
url: 'http://tampermonkey.net/crx/tampermonkey.xml',
name: 'tampermonkey.xml',
headers: { 'User-Agent': 'greasemonkey' },
saveAs: true,
timeout: 3000,
onerror(response) {
response.error.toUpperCase();
// $ExpectType string | undefined
response.details;
},
ontimeout() {},
onload() {},
onprogress(response) {
// $ExpectType string
response.finalUrl;
// $ExpectType number
response.loaded;
// $ExpectType number
response.total;
},
});
interface TabState {
form: { name: string };
}
const tabState: TabState = {
form: {
name: 'Alice',
},
};
// GM.saveTab
// $ExpectType void
await GM.saveTab(tabState);
// GM.getTab
// $ExpectType any
await GM.getTab();
const tab: Record<string, string> = await GM.getTab();
// GM.getTabs
const tab0 = (await GM.getTabs())[0];
// GM.log
// $ExpectType void
await GM.log(42);
await GM.log('Hello', 'World!');
// GM.openInTab
await GM.openInTab('https://example.org');
await GM.openInTab('https://example.org', true);
const openTabObject = await GM.openInTab('https://example.org', {
active: true,
insert: false,
setParent: true,
});
openTabObject.onclose = () => {};
// $ExpectType boolean
openTabObject.closed;
openTabObject.close();
// GM.notification
// Using globals from GM_notification tests above
// specifically textNotification and highlightNotification
// $ExpectType boolean
await GM.notification(textNotification);
// $ExpectType boolean
await GM.notification(highlightNotification);
// $ExpectType boolean
await GM.notification(textNotification, textNotification.ondone);
await GM.notification('text', 'title', 'https://tampermonkey.net/favicon.ico', () => {});
// GM.setClipboard
// $ExpectType void
await GM.setClipboard('Some text');
await GM.setClipboard('Some text', 'text');
await GM.setClipboard('Some text', {
type: 'text',
mimetype: 'text/plain',
});
}; | the_stack |
import { DEBUG } from 'internal:constants';
import { AnimationGraph, Layer, StateMachine, State, Transition, isAnimationTransition, SubStateMachine } from './animation-graph';
import { assertIsTrue, assertIsNonNullable } from '../../data/utils/asserts';
import { MotionEval, MotionEvalContext } from './motion';
import type { Node } from '../../scene-graph/node';
import { createEval } from './create-eval';
import { Value } from './variable';
import { BindContext, bindOr, VariableType } from './parametric';
import { ConditionEval, TriggerCondition } from './condition';
import { VariableNotDefinedError, VariableTypeMismatchedError } from './errors';
import { MotionState } from './motion-state';
import { SkeletonMask } from '../skeleton-mask';
import { debug, warnID } from '../../platform/debug';
import { BlendStateBuffer } from '../../../3d/skeletal-animation/skeletal-animation-blending';
import { clearWeightsStats, getWeightsStats, graphDebug, graphDebugGroup, graphDebugGroupEnd, GRAPH_DEBUG_ENABLED } from './graph-debug';
import { AnimationClip } from '../animation-clip';
import type { AnimationController } from './animation-controller';
import { StateMachineComponent } from './state-machine-component';
import { InteractiveState } from './state';
export class AnimationGraphEval {
private declare _layerEvaluations: LayerEval[];
private _blendBuffer = new BlendStateBuffer();
private _currentTransitionCache: TransitionStatus = {
duration: 0.0,
time: 0.0,
};
constructor (graph: AnimationGraph, root: Node, newGenAnim: AnimationController) {
for (const [name, { type, value }] of graph.variables) {
this._varInstances[name] = new VarInstance(type, value);
}
const context: LayerContext = {
newGenAnim,
blendBuffer: this._blendBuffer,
node: root,
getVar: (id: string): VarInstance | undefined => this._varInstances[id],
triggerResetFn: (name: string) => {
this.setValue(name, false);
},
};
this._layerEvaluations = Array.from(graph.layers).map((layer) => {
const layerEval = new LayerEval(layer, {
...context,
mask: layer.mask ?? undefined,
});
return layerEval;
});
}
public update (deltaTime: number) {
graphDebugGroup(`New frame started.`);
if (GRAPH_DEBUG_ENABLED) {
clearWeightsStats();
}
for (const layerEval of this._layerEvaluations) {
layerEval.update(deltaTime);
}
if (GRAPH_DEBUG_ENABLED) {
graphDebug(`Weights: ${getWeightsStats()}`);
}
this._blendBuffer.apply();
graphDebugGroupEnd();
}
public getCurrentStateStatus (layer: number): Readonly<StateStatus> | null {
// TODO optimize object
const stats: StateStatus = { __DEBUG_ID__: '' };
if (this._layerEvaluations[layer].getCurrentStateStatus(stats)) {
return stats;
} else {
return null;
}
}
public getCurrentClipStatuses (layer: number): Iterable<Readonly<ClipStatus>> {
return this._layerEvaluations[layer].getCurrentClipStatuses();
}
public getCurrentTransition (layer: number): Readonly<TransitionStatus> | null {
const {
_layerEvaluations: layers,
_currentTransitionCache: currentTransition,
} = this;
const isInTransition = layers[layer].getCurrentTransition(currentTransition);
return isInTransition ? currentTransition : null;
}
public getNextStateStatus (layer: number): Readonly<StateStatus> | null {
// TODO optimize object
const stats: StateStatus = { __DEBUG_ID__: '' };
if (this._layerEvaluations[layer].getNextStateStatus(stats)) {
return stats;
} else {
return null;
}
}
public getNextClipStatuses (layer: number): Iterable<Readonly<ClipStatus>> {
assertIsNonNullable(this.getCurrentTransition(layer), '!!this.getCurrentTransition(layer)');
return this._layerEvaluations[layer].getNextClipStatuses();
}
public getValue (name: string) {
const varInstance = this._varInstances[name];
if (!varInstance) {
return undefined;
} else {
return varInstance.value;
}
}
public setValue (name: string, value: Value) {
const varInstance = this._varInstances[name];
if (!varInstance) {
return;
}
varInstance.value = value;
}
private _varInstances: Record<string, VarInstance> = {};
}
export interface TransitionStatus {
duration: number;
time: number;
}
export interface ClipStatus {
clip: AnimationClip;
weight: number;
}
export interface StateStatus {
/**
* For testing.
* TODO: remove it.
*/
__DEBUG_ID__: string | undefined;
}
type TriggerResetFn = (name: string) => void;
interface LayerContext extends BindContext {
newGenAnim: AnimationController;
/**
* The root node bind to the graph.
*/
node: Node;
/**
* The blend buffer.
*/
blendBuffer: BlendStateBuffer;
/**
* The mask applied to this layer.
*/
mask?: SkeletonMask;
/**
* TODO: A little hacky.
* A function which resets specified trigger. This function can be stored.
*/
triggerResetFn: TriggerResetFn;
}
class LayerEval {
public declare name: string;
constructor (layer: Layer, context: LayerContext) {
this.name = layer.name;
this._newGenAnim = context.newGenAnim;
this._weight = layer.weight;
const { entry, exit } = this._addStateMachine(layer.stateMachine, null, {
...context,
}, layer.name);
this._topLevelEntry = entry;
this._topLevelExit = exit;
this._currentNode = entry;
this._resetTrigger = context.triggerResetFn;
}
/**
* Indicates if this layer's top level graph reached its exit.
*/
get exited () {
return this._currentNode === this._topLevelExit;
}
public update (deltaTime: number) {
if (!this.exited) {
this._fromWeight = 1.0;
this._toWeight = 0.0;
this._eval(deltaTime);
this._sample();
}
}
public getCurrentStateStatus (status: StateStatus): boolean {
const { _currentNode: currentNode } = this;
if (currentNode.kind === NodeKind.animation) {
status.__DEBUG_ID__ = currentNode.name;
return true;
} else {
return false;
}
}
public getCurrentClipStatuses (): Iterable<ClipStatus> {
const { _currentNode: currentNode } = this;
if (currentNode.kind === NodeKind.animation) {
return currentNode.getClipStatuses(this._fromWeight);
} else {
return emptyClipStatusesIterable;
}
}
public getCurrentTransition (transitionStatus: TransitionStatus): boolean {
const { _currentTransitionPath: currentTransitionPath } = this;
if (currentTransitionPath.length !== 0) {
const lastNode = currentTransitionPath[currentTransitionPath.length - 1];
if (lastNode.to.kind !== NodeKind.animation) {
return false;
}
const {
duration,
normalizedDuration,
} = currentTransitionPath[0];
const durationInSeconds = transitionStatus.duration = normalizedDuration
? duration * (this._currentNode.kind === NodeKind.animation ? this._currentNode.duration : 0.0)
: duration;
transitionStatus.time = this._transitionProgress * durationInSeconds;
return true;
} else {
return false;
}
}
public getNextStateStatus (status: StateStatus): boolean {
assertIsTrue(this._currentTransitionToNode, 'There is no transition currently in layer.');
status.__DEBUG_ID__ = this._currentTransitionToNode.name;
return true;
}
public getNextClipStatuses (): Iterable<ClipStatus> {
const { _currentTransitionPath: currentTransitionPath } = this;
const nCurrentTransitionPath = currentTransitionPath.length;
assertIsTrue(nCurrentTransitionPath > 0, 'There is no transition currently in layer.');
const to = currentTransitionPath[nCurrentTransitionPath - 1].to;
assertIsTrue(to.kind === NodeKind.animation);
return to.getClipStatuses(this._toWeight) ?? emptyClipStatusesIterable;
}
private declare _newGenAnim: AnimationController;
private _weight: number;
private _nodes: NodeEval[] = [];
private _topLevelEntry: NodeEval;
private _topLevelExit: NodeEval;
private _currentNode: NodeEval;
private _currentTransitionToNode: MotionStateEval | null = null;
private _currentTransitionPath: TransitionEval[] = [];
private _transitionProgress = 0;
private declare _triggerReset: TriggerResetFn;
private _fromWeight = 0.0;
private _toWeight = 0.0;
private _addStateMachine (
graph: StateMachine, parentStateMachineInfo: StateMachineInfo | null, context: LayerContext, __DEBUG_ID__: string,
): StateMachineInfo {
const nodes = Array.from(graph.states());
let entryEval: SpecialStateEval | undefined;
let anyNode: SpecialStateEval | undefined;
let exitEval: SpecialStateEval | undefined;
const nodeEvaluations = nodes.map((node): NodeEval | null => {
if (node instanceof MotionState) {
return new MotionStateEval(node, context);
} else if (node === graph.entryState) {
return entryEval = new SpecialStateEval(node, NodeKind.entry, node.name);
} else if (node === graph.exitState) {
return exitEval = new SpecialStateEval(node, NodeKind.exit, node.name);
} else if (node === graph.anyState) {
return anyNode = new SpecialStateEval(node, NodeKind.any, node.name);
} else {
assertIsTrue(node instanceof SubStateMachine);
return null;
}
});
assertIsNonNullable(entryEval, 'Entry node is missing');
assertIsNonNullable(exitEval, 'Exit node is missing');
assertIsNonNullable(anyNode, 'Any node is missing');
const stateMachineInfo: StateMachineInfo = {
components: null,
parent: parentStateMachineInfo,
entry: entryEval,
exit: exitEval,
any: anyNode,
};
for (let iNode = 0; iNode < nodes.length; ++iNode) {
const nodeEval = nodeEvaluations[iNode];
if (nodeEval) {
nodeEval.stateMachine = stateMachineInfo;
}
}
const subStateMachineInfos = nodes.map((node) => {
if (node instanceof SubStateMachine) {
const subStateMachineInfo = this._addStateMachine(node.stateMachine, stateMachineInfo, context, `${__DEBUG_ID__}/${node.name}`);
subStateMachineInfo.components = new InstantiatedComponents(node);
return subStateMachineInfo;
} else {
return null;
}
});
if (DEBUG) {
for (const nodeEval of nodeEvaluations) {
if (nodeEval) {
nodeEval.__DEBUG_ID__ = `${nodeEval.name}(from ${__DEBUG_ID__})`;
}
}
}
for (let iNode = 0; iNode < nodes.length; ++iNode) {
const node = nodes[iNode];
const outgoingTemplates = graph.getOutgoings(node);
const outgoingTransitions: TransitionEval[] = [];
let fromNode: NodeEval;
if (node instanceof SubStateMachine) {
const subStateMachineInfo = subStateMachineInfos[iNode];
assertIsNonNullable(subStateMachineInfo);
fromNode = subStateMachineInfo.exit;
} else {
const nodeEval = nodeEvaluations[iNode];
assertIsNonNullable(nodeEval);
fromNode = nodeEval;
}
for (const outgoing of outgoingTemplates) {
const outgoingNode = outgoing.to;
const iOutgoingNode = nodes.findIndex((nodeTemplate) => nodeTemplate === outgoing.to);
if (iOutgoingNode < 0) {
assertIsTrue(false, 'Bad animation data');
}
let toNode: NodeEval;
if (outgoingNode instanceof SubStateMachine) {
const subStateMachineInfo = subStateMachineInfos[iOutgoingNode];
assertIsNonNullable(subStateMachineInfo);
toNode = subStateMachineInfo.entry;
} else {
const nodeEval = nodeEvaluations[iOutgoingNode];
assertIsNonNullable(nodeEval);
toNode = nodeEval;
}
const transitionEval: TransitionEval = {
to: toNode,
conditions: outgoing.conditions.map((condition) => condition[createEval](context)),
duration: isAnimationTransition(outgoing) ? outgoing.duration : 0.0,
normalizedDuration: isAnimationTransition(outgoing) ? outgoing.relativeDuration : false,
exitConditionEnabled: isAnimationTransition(outgoing) ? outgoing.exitConditionEnabled : false,
exitCondition: isAnimationTransition(outgoing) ? outgoing.exitCondition : 0.0,
triggers: undefined,
};
transitionEval.conditions.forEach((conditionEval, iCondition) => {
const condition = outgoing.conditions[iCondition];
if (condition instanceof TriggerCondition && condition.trigger) {
// TODO: validates the existence of trigger?
(transitionEval.triggers ??= []).push(condition.trigger);
}
});
outgoingTransitions.push(transitionEval);
}
fromNode.outgoingTransitions = outgoingTransitions;
}
return stateMachineInfo;
}
/**
* Updates this layer, return when the time piece exhausted or the graph reached exit state.
* @param deltaTime The time piece to update.
* @returns Remain time piece.
*/
private _eval (deltaTime: Readonly<number>) {
assertIsTrue(!this.exited);
graphDebugGroup(`[Layer ${this.name}]: UpdateStart ${deltaTime}s`);
const haltOnNonMotionState = this._continueDanglingTransition();
if (haltOnNonMotionState) {
return 0.0;
}
const MAX_ITERATIONS = 100;
let passConsumed = 0.0;
let remainTimePiece = deltaTime;
for (let continueNextIterationForce = true, // Force next iteration even remain time piece is zero
iterations = 0;
continueNextIterationForce || remainTimePiece > 0.0;
) {
continueNextIterationForce = false;
if (iterations !== 0) {
graphDebug(`Pass end. Consumed ${passConsumed}s, remain: ${remainTimePiece}s`);
}
if (iterations === MAX_ITERATIONS) {
warnID(14000, MAX_ITERATIONS);
break;
}
graphDebug(`Pass ${iterations} started.`);
if (GRAPH_DEBUG_ENABLED) {
passConsumed = 0.0;
}
++iterations;
// Update current transition if we're in transition.
// If currently no transition, we simple fallthrough.
if (this._currentTransitionPath.length > 0) {
const currentUpdatingConsume = this._updateCurrentTransition(remainTimePiece);
if (GRAPH_DEBUG_ENABLED) {
passConsumed = currentUpdatingConsume;
}
remainTimePiece -= currentUpdatingConsume;
if (this._currentNode.kind === NodeKind.exit) {
break;
}
if (this._currentTransitionPath.length === 0) {
// If the update invocation finished the transition,
// We force restart the iteration
continueNextIterationForce = true;
}
continue;
}
const { _currentNode: currentNode } = this;
const transitionMatch = this._matchCurrentNodeTransition(remainTimePiece);
if (transitionMatch) {
const {
transition,
requires: updateRequires,
} = transitionMatch;
graphDebug(`[SubStateMachine ${this.name}]: CurrentNodeUpdate: ${currentNode.name}`);
if (currentNode.kind === NodeKind.animation) {
currentNode.updateFromPort(updateRequires);
}
if (GRAPH_DEBUG_ENABLED) {
passConsumed = remainTimePiece;
}
remainTimePiece -= updateRequires;
const ranIntoNonMotionState = this._switchTo(transition);
if (ranIntoNonMotionState) {
break;
}
continueNextIterationForce = true;
} else { // If no transition matched, we update current node.
graphDebug(`[SubStateMachine ${this.name}]: CurrentNodeUpdate: ${currentNode.name}`);
if (currentNode.kind === NodeKind.animation) {
currentNode.updateFromPort(remainTimePiece);
// Animation play eat all times.
remainTimePiece = 0.0;
}
if (GRAPH_DEBUG_ENABLED) {
passConsumed = remainTimePiece;
}
continue;
}
}
graphDebug(`[SubStateMachine ${this.name}]: UpdateEnd`);
graphDebugGroupEnd();
return remainTimePiece;
}
private _sample () {
const {
_currentNode: currentNode,
_currentTransitionToNode: currentTransitionToNode,
_fromWeight: fromWeight,
} = this;
if (currentNode.kind === NodeKind.animation) {
currentNode.sampleFromPort(fromWeight);
}
if (currentTransitionToNode) {
if (currentTransitionToNode.kind === NodeKind.animation) {
currentTransitionToNode.sampleToPort(this._toWeight);
}
}
}
/**
* Searches for a transition which should be performed
* if current node update for no more than `deltaTime`.
* @param deltaTime
* @returns
*/
private _matchCurrentNodeTransition (deltaTime: Readonly<number>) {
const currentNode = this._currentNode;
let minDeltaTimeRequired = Infinity;
let transitionRequiringMinDeltaTime: TransitionEval | null = null;
const match0 = this._matchTransition(
currentNode,
currentNode,
deltaTime,
transitionMatchCacheRegular,
);
if (match0) {
({
requires: minDeltaTimeRequired,
transition: transitionRequiringMinDeltaTime,
} = match0);
}
if (currentNode.kind === NodeKind.animation) {
for (let ancestor: StateMachineInfo | null = currentNode.stateMachine;
ancestor !== null;
ancestor = ancestor.parent) {
const anyMatch = this._matchTransition(
ancestor.any,
currentNode,
deltaTime,
transitionMatchCacheAny,
);
if (anyMatch && anyMatch.requires < minDeltaTimeRequired) {
({
requires: minDeltaTimeRequired,
transition: transitionRequiringMinDeltaTime,
} = anyMatch);
}
}
}
const result = transitionMatchCache;
if (transitionRequiringMinDeltaTime) {
return result.set(transitionRequiringMinDeltaTime, minDeltaTimeRequired);
}
return null;
}
/**
* Searches for a transition which should be performed
* if specified node update for no more than `deltaTime`.
* @param node
* @param realNode
* @param deltaTime
* @returns
*/
private _matchTransition (
node: NodeEval, realNode: NodeEval, deltaTime: Readonly<number>, result: TransitionMatchCache,
): TransitionMatch | null {
assertIsTrue(node === realNode || node.kind === NodeKind.any);
const { outgoingTransitions } = node;
const nTransitions = outgoingTransitions.length;
let minDeltaTimeRequired = Infinity;
let transitionRequiringMinDeltaTime: TransitionEval | null = null;
for (let iTransition = 0; iTransition < nTransitions; ++iTransition) {
const transition = outgoingTransitions[iTransition];
const { conditions } = transition;
const nConditions = conditions.length;
// Handle empty condition case.
if (nConditions === 0) {
if (node.kind === NodeKind.entry || node.kind === NodeKind.exit) {
// These kinds of transition is definitely chosen.
return result.set(transition, 0.0);
}
if (!transition.exitConditionEnabled) {
// Invalid transition, ignored.
continue;
}
}
let deltaTimeRequired = 0.0;
if (realNode.kind === NodeKind.animation && transition.exitConditionEnabled) {
const exitTime = realNode.duration * transition.exitCondition;
deltaTimeRequired = Math.max(exitTime - realNode.fromPortTime, 0.0);
if (deltaTimeRequired > deltaTime) {
continue;
}
}
let satisfied = true;
for (let iCondition = 0; iCondition < nConditions; ++iCondition) {
const condition = conditions[iCondition];
if (!condition.eval()) {
satisfied = false;
break;
}
}
if (!satisfied) {
continue;
}
if (deltaTimeRequired === 0.0) {
// Exit condition is disabled or the exit condition is just 0.0.
return result.set(transition, 0.0);
}
if (deltaTimeRequired < minDeltaTimeRequired) {
minDeltaTimeRequired = deltaTimeRequired;
transitionRequiringMinDeltaTime = transition;
}
}
if (transitionRequiringMinDeltaTime) {
return result.set(transitionRequiringMinDeltaTime, minDeltaTimeRequired);
}
return null;
}
/**
* Try switch current node using specified transition.
* @param transition The transition.
* @returns If the transition finally ran into entry/exit state.
*/
private _switchTo (transition: TransitionEval) {
const { _currentNode: currentNode } = this;
graphDebugGroup(`[SubStateMachine ${this.name}]: STARTED ${currentNode.name} -> ${transition.to.name}.`);
const { _currentTransitionPath: currentTransitionPath } = this;
this._consumeTransition(transition);
currentTransitionPath.push(transition);
const motionNode = this._matchTransitionPathUntilMotion();
if (motionNode) {
// Apply transitions
this._doTransitionToMotion(motionNode);
return false;
} else {
return true;
}
}
/**
* Called every frame(not every iteration).
* Returns if we ran into an entry/exit node and still no satisfied transition matched this frame.
*/
private _continueDanglingTransition () {
const {
_currentTransitionPath: currentTransitionPath,
} = this;
const lenCurrentTransitionPath = currentTransitionPath.length;
if (lenCurrentTransitionPath === 0) {
return false;
}
const lastTransition = currentTransitionPath[lenCurrentTransitionPath - 1];
const tailNode = lastTransition.to;
if (tailNode.kind !== NodeKind.animation) {
const motionNode = this._matchTransitionPathUntilMotion();
if (motionNode) {
// Apply transitions
this._doTransitionToMotion(motionNode);
return false;
} else {
return true;
}
}
return false;
}
private _matchTransitionPathUntilMotion () {
const {
_currentTransitionPath: currentTransitionPath,
} = this;
const lenCurrentTransitionPath = currentTransitionPath.length;
assertIsTrue(lenCurrentTransitionPath !== 0);
const lastTransition = currentTransitionPath[lenCurrentTransitionPath - 1];
let tailNode = lastTransition.to;
for (; tailNode.kind !== NodeKind.animation;) {
const transitionMatch = this._matchTransition(
tailNode,
tailNode,
0.0,
transitionMatchCache,
);
if (!transitionMatch) {
break;
}
const transition = transitionMatch.transition;
this._consumeTransition(transition);
currentTransitionPath.push(transition);
tailNode = transition.to;
}
return tailNode.kind === NodeKind.animation ? tailNode : null;
}
private _consumeTransition (transition: TransitionEval) {
const { to } = transition;
// Reset triggers
this._resetTriggersOnTransition(transition);
if (to.kind === NodeKind.entry) {
// We're entering a state machine
this._callEnterMethods(to);
}
}
private _doTransitionToMotion (targetNode: MotionStateEval) {
this._transitionProgress = 0.0;
this._currentTransitionToNode = targetNode;
targetNode.resetToPort();
this._callEnterMethods(targetNode);
}
/**
* Update current transition.
* Asserts: `!!this._currentTransition`.
* @param deltaTime Time piece.
* @returns
*/
private _updateCurrentTransition (deltaTime: number) {
const {
_currentTransitionPath: currentTransitionPath,
_currentTransitionToNode: currentTransitionToNode,
} = this;
assertIsNonNullable(currentTransitionPath.length > 0);
assertIsNonNullable(currentTransitionToNode);
const currentTransition = currentTransitionPath[0];
const {
duration: transitionDuration,
normalizedDuration,
} = currentTransition;
const fromNode = this._currentNode;
const toNode = currentTransitionToNode;
let contrib = 0.0;
let ratio = 0.0;
if (transitionDuration <= 0) {
contrib = 0.0;
ratio = 1.0;
} else {
assertIsTrue(fromNode.kind === NodeKind.animation);
const { _transitionProgress: transitionProgress } = this;
const durationSeconds = normalizedDuration ? transitionDuration * fromNode.duration : transitionDuration;
const progressSeconds = transitionProgress * durationSeconds;
const remain = durationSeconds - progressSeconds;
assertIsTrue(remain >= 0.0);
contrib = Math.min(remain, deltaTime);
ratio = this._transitionProgress = (progressSeconds + contrib) / durationSeconds;
assertIsTrue(ratio >= 0.0 && ratio <= 1.0);
}
const toNodeName = toNode?.name ?? '<Empty>';
const weight = this._weight;
graphDebugGroup(
`[SubStateMachine ${this.name}]: TransitionUpdate: ${fromNode.name} -> ${toNodeName}`
+ `with ratio ${ratio} in base weight ${this._weight}.`,
);
this._fromWeight = weight * (1.0 - ratio);
this._toWeight = weight * ratio;
if (fromNode.kind === NodeKind.animation) {
graphDebugGroup(`Update ${fromNode.name}`);
fromNode.updateFromPort(contrib);
graphDebugGroupEnd();
}
if (toNode) {
graphDebugGroup(`Update ${toNode.name}`);
toNode.updateToPort(contrib);
graphDebugGroupEnd();
}
graphDebugGroupEnd();
if (ratio === 1.0) {
// Transition done.
graphDebug(`[SubStateMachine ${this.name}]: Transition finished: ${fromNode.name} -> ${toNodeName}.`);
this._callExitMethods(fromNode);
const { _currentTransitionPath: transitions } = this;
const nTransition = transitions.length;
for (let iTransition = 0; iTransition < nTransition; ++iTransition) {
const { to } = transitions[iTransition];
if (to.kind === NodeKind.exit) {
this._callExitMethods(to);
}
}
toNode.finishTransition();
this._currentNode = toNode;
this._currentTransitionToNode = null;
this._currentTransitionPath.length = 0;
this._fromWeight = 1.0;
this._toWeight = 0.0;
}
return contrib;
}
private _resetTriggersOnTransition (transition: TransitionEval) {
if (transition.to.kind === NodeKind.exit) {
// Exit transition(transitions whose target is exit)
return;
}
const { triggers } = transition;
if (triggers) {
const nTriggers = triggers.length;
for (let iTrigger = 0; iTrigger < nTriggers; ++iTrigger) {
const trigger = triggers[iTrigger];
this._resetTrigger(trigger);
}
}
}
private _resetTrigger (name: string) {
const { _triggerReset: triggerResetFn } = this;
triggerResetFn(name);
}
private _callEnterMethods (node: NodeEval) {
const { _newGenAnim: newGenAnim } = this;
switch (node.kind) {
default:
break;
case NodeKind.animation:
node.components.callEnterMethods(newGenAnim);
break;
case NodeKind.entry:
node.stateMachine.components?.callEnterMethods(newGenAnim);
break;
}
}
private _callExitMethods (node: NodeEval) {
const { _newGenAnim: newGenAnim } = this;
switch (node.kind) {
default:
break;
case NodeKind.animation:
node.components.callExitMethods(newGenAnim);
break;
case NodeKind.exit:
node.stateMachine.components?.callExitMethods(newGenAnim);
break;
}
}
}
const emptyClipStatusesIterator: Iterator<ClipStatus> = Object.freeze({
next () {
return {
done: true,
value: undefined,
};
},
});
const emptyClipStatusesIterable: Iterable<ClipStatus> = Object.freeze({
[Symbol.iterator] () {
return emptyClipStatusesIterator;
},
});
interface TransitionMatch {
/**
* The matched result.
*/
transition: TransitionEval;
/**
* The after after which the transition can happen.
*/
requires: number;
}
class TransitionMatchCache {
public transition: TransitionMatch['transition'] | null = null;
public requires = 0.0;
public set (transition: TransitionMatch['transition'], requires: number) {
this.transition = transition;
this.requires = requires;
return this as TransitionMatch;
}
}
const transitionMatchCache = new TransitionMatchCache();
const transitionMatchCacheRegular = new TransitionMatchCache();
const transitionMatchCacheAny = new TransitionMatchCache();
enum NodeKind {
entry, exit, any, animation,
}
export class StateEval {
public declare __DEBUG_ID__?: string;
public declare stateMachine: StateMachineInfo;
constructor (node: State) {
this.name = node.name;
}
public readonly name: string;
public outgoingTransitions: readonly TransitionEval[] = [];
}
const DEFAULT_ENTER_METHOD = StateMachineComponent.prototype.onEnter;
const DEFAULT_EXIT_METHOD = StateMachineComponent.prototype.onExit;
class InstantiatedComponents {
constructor (node: InteractiveState) {
this._components = node.instantiateComponents();
}
public callEnterMethods (newGenAnim: AnimationController) {
const { _components: components } = this;
const nComponents = components.length;
for (let iComponent = 0; iComponent < nComponents; ++iComponent) {
const component = components[iComponent];
if (component.onEnter !== DEFAULT_ENTER_METHOD) {
component.onEnter(newGenAnim);
}
}
}
public callExitMethods (newGenAnim: AnimationController) {
const { _components: components } = this;
const nComponents = components.length;
for (let iComponent = 0; iComponent < nComponents; ++iComponent) {
const component = components[iComponent];
if (component.onExit !== DEFAULT_EXIT_METHOD) {
component.onExit(newGenAnim);
}
}
}
private declare _components: StateMachineComponent[];
}
interface StateMachineInfo {
parent: StateMachineInfo | null;
entry: NodeEval;
exit: NodeEval;
any: NodeEval;
components: InstantiatedComponents | null;
}
export class MotionStateEval extends StateEval {
constructor (node: MotionState, context: LayerContext) {
super(node);
const speed = bindOr(
context,
node.speed,
VariableType.FLOAT,
this._setSpeed,
this,
);
this._speed = speed;
const sourceEvalContext: MotionEvalContext = {
...context,
};
const sourceEval = node.motion?.[createEval](sourceEvalContext) ?? null;
if (sourceEval) {
Object.defineProperty(sourceEval, '__DEBUG_ID__', { value: this.name });
}
this._source = sourceEval;
this.components = new InstantiatedComponents(node);
}
public readonly kind = NodeKind.animation;
public declare components: InstantiatedComponents;
get duration () {
return this._source?.duration ?? 0.0;
}
get fromPortTime () {
return this._fromPort.progress * this.duration;
}
public updateFromPort (deltaTime: number) {
this._fromPort.progress = calcProgressUpdate(
this._fromPort.progress,
this.duration,
deltaTime * this._speed,
);
}
public updateToPort (deltaTime: number) {
this._toPort.progress = calcProgressUpdate(
this._toPort.progress,
this.duration,
deltaTime * this._speed,
);
}
public resetToPort () {
this._toPort.progress = 0.0;
}
public finishTransition () {
this._fromPort.progress = this._toPort.progress;
}
public sampleFromPort (weight: number) {
const normalized = normalizeProgress(this._fromPort.progress);
this._source?.sample(normalized, weight);
}
public sampleToPort (weight: number) {
const normalized = normalizeProgress(this._toPort.progress);
this._source?.sample(normalized, weight);
}
public getClipStatuses (baseWeight: number): Iterable<ClipStatus> {
const { _source: source } = this;
if (!source) {
return emptyClipStatusesIterable;
} else {
return {
[Symbol.iterator]: () => source.getClipStatuses(baseWeight),
};
}
}
private _source: MotionEval | null = null;
private _speed = 1.0;
private _fromPort: MotionEvalPort = {
progress: 0.0,
};
private _toPort: MotionEvalPort = {
progress: 0.0,
};
private _setSpeed (value: number) {
this._speed = value;
}
}
function calcProgressUpdate (currentProgress: number, duration: number, deltaTime: number) {
if (duration === 0.0) {
// TODO?
return 0.0;
}
const progress = currentProgress + deltaTime / duration;
return progress;
}
function normalizeProgress (progress: number) {
return progress - Math.trunc(progress);
}
interface MotionEvalPort {
progress: number;
}
export class SpecialStateEval extends StateEval {
constructor (node: State, kind: SpecialStateEval['kind'], name: string) {
super(node);
this.kind = kind;
}
public readonly kind: NodeKind.entry | NodeKind.exit | NodeKind.any;
}
export type NodeEval = MotionStateEval | SpecialStateEval;
interface TransitionEval {
to: NodeEval;
duration: number;
normalizedDuration: boolean;
conditions: ConditionEval[];
exitConditionEnabled: boolean;
exitCondition: number;
/**
* Bound triggers, once this transition satisfied. All triggers would be reset.
*/
triggers: string[] | undefined;
}
class VarInstance {
public type: VariableType;
constructor (type: VariableType, value: Value) {
this.type = type;
this._value = value;
}
get value () {
return this._value;
}
set value (value) {
this._value = value;
for (const { fn, thisArg, args } of this._refs) {
fn.call(thisArg, value, ...args);
}
}
public bind <T, TThis, ExtraArgs extends any[]> (
fn: (this: TThis, value: T, ...args: ExtraArgs) => void,
thisArg: TThis,
...args: ExtraArgs
) {
this._refs.push({
fn: fn as (this: unknown, value: unknown, ...args: unknown[]) => void,
thisArg,
args,
});
return this._value;
}
private _value: Value;
private _refs: VarRef[] = [];
}
export type { VarInstance };
interface VarRefs {
type: VariableType;
value: Value;
refs: VarRef[];
}
interface VarRef {
fn: (this: unknown, value: unknown, ...args: unknown[]) => void;
thisArg: unknown;
args: unknown[];
} | the_stack |
import 'chrome://resources/cr_elements/policy/cr_tooltip_icon.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js';
import '../settings_shared_css.js';
import '../i18n_setup.js';
import {CrTooltipIconElement} from 'chrome://resources/cr_elements/policy/cr_tooltip_icon.m.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {I18nMixin, I18nMixinInterface} from 'chrome://resources/js/i18n_mixin.js';
import {WebUIListenerMixin, WebUIListenerMixinInterface} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {PaperTooltipElement} from 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {routes} from '../route.js';
import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js';
import {AllSitesAction2, ContentSetting, ContentSettingsTypes, SiteSettingSource} from '../site_settings/constants.js';
import {SiteSettingsMixin, SiteSettingsMixinInterface} from '../site_settings/site_settings_mixin.js';
import {RawSiteException, RecentSitePermissions} from '../site_settings/site_settings_prefs_browser_proxy.js';
type FocusConfig = Map<string, (string|(() => void))>;
/** Event interface for dom-repeat. */
interface RepeaterEvent extends CustomEvent {
model: {
item: RecentSitePermissions,
index: number,
};
}
export interface SettingsRecentSitePermissionsElement {
$: {
tooltip: PaperTooltipElement,
};
}
const SettingsRecentSitePermissionsElementBase =
RouteObserverMixin(
SiteSettingsMixin(WebUIListenerMixin(I18nMixin(PolymerElement)))) as {
new ():
PolymerElement & I18nMixinInterface & WebUIListenerMixinInterface &
SiteSettingsMixinInterface & RouteObserverMixinInterface
};
export class SettingsRecentSitePermissionsElement extends
SettingsRecentSitePermissionsElementBase {
static get is() {
return 'settings-recent-site-permissions';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
noRecentPermissions: {
type: Boolean,
computed: 'computeNoRecentPermissions_(recentSitePermissionsList_)',
notify: true,
},
shouldFocusAfterPopulation_: Boolean,
/**
* List of recent site permissions grouped by source.
*/
recentSitePermissionsList_: {
type: Array,
value: () => [],
},
focusConfig: {
type: Object,
observer: 'focusConfigChanged_',
},
};
}
noRecentPermissions: boolean;
private shouldFocusAfterPopulation_: boolean;
private recentSitePermissionsList_: Array<RecentSitePermissions>;
focusConfig: FocusConfig;
private lastSelected_: {origin: string, incognito: boolean, index: number}|
null;
constructor() {
super();
/**
* When navigating to a site details sub-page, |lastSelected_| holds the
* origin and incognito bit associated with the link that sent the user
* there, as well as the index in recent permission list for that entry.
* This allows for an intelligent re-focus upon a back navigation.
*/
this.lastSelected_ = null;
}
private focusConfigChanged_(_newConfig: FocusConfig, oldConfig: FocusConfig) {
// focusConfig is set only once on the parent, so this observer should
// only fire once.
assert(!oldConfig);
this.focusConfig.set(
routes.SITE_SETTINGS_SITE_DETAILS.path + '_' +
routes.SITE_SETTINGS.path,
() => {
this.shouldFocusAfterPopulation_ = true;
});
}
/**
* Reload the site recent site permission list whenever the user navigates
* to the site settings page.
*/
currentRouteChanged(currentRoute: Route) {
if (currentRoute.path === routes.SITE_SETTINGS.path) {
this.populateList_();
}
}
ready() {
super.ready();
this.addWebUIListener(
'onIncognitoStatusChanged',
(hasIncognito: boolean) =>
this.onIncognitoStatusChanged_(hasIncognito));
this.browserProxy.updateIncognitoStatus();
}
/**
* Perform internationalization for the given content settings type.
*/
private getI18nContentTypeString_(contentSettingsType: ContentSettingsTypes):
string {
switch (contentSettingsType) {
case ContentSettingsTypes.COOKIES:
return this.i18n('siteSettingsCookiesMidSentence');
case ContentSettingsTypes.IMAGES:
return this.i18n('siteSettingsImagesMidSentence');
case ContentSettingsTypes.JAVASCRIPT:
return this.i18n('siteSettingsJavascriptMidSentence');
case ContentSettingsTypes.SOUND:
return this.i18n('siteSettingsSoundMidSentence');
case ContentSettingsTypes.POPUPS:
return this.i18n('siteSettingsPopupsMidSentence');
case ContentSettingsTypes.GEOLOCATION:
return this.i18n('siteSettingsLocationMidSentence');
case ContentSettingsTypes.NOTIFICATIONS:
return this.i18n('siteSettingsNotificationsMidSentence');
case ContentSettingsTypes.MIC:
return this.i18n('siteSettingsMicMidSentence');
case ContentSettingsTypes.CAMERA:
return this.i18n('siteSettingsCameraMidSentence');
case ContentSettingsTypes.PROTOCOL_HANDLERS:
return this.i18n('siteSettingsHandlersMidSentence');
case ContentSettingsTypes.AUTOMATIC_DOWNLOADS:
return this.i18n('siteSettingsAutomaticDownloadsMidSentence');
case ContentSettingsTypes.BACKGROUND_SYNC:
return this.i18n('siteSettingsBackgroundSyncMidSentence');
case ContentSettingsTypes.MIDI_DEVICES:
return this.i18n('siteSettingsMidiDevicesMidSentence');
case ContentSettingsTypes.USB_DEVICES:
return this.i18n('siteSettingsUsbDevicesMidSentence');
case ContentSettingsTypes.SERIAL_PORTS:
return this.i18n('siteSettingsSerialPortsMidSentence');
case ContentSettingsTypes.BLUETOOTH_DEVICES:
return this.i18n('siteSettingsBluetoothDevicesMidSentence');
case ContentSettingsTypes.ZOOM_LEVELS:
return this.i18n('siteSettingsZoomLevelsMidSentence');
case ContentSettingsTypes.PROTECTED_CONTENT:
return this.i18n('siteSettingsProtectedContentMidSentence');
case ContentSettingsTypes.ADS:
return this.i18n('siteSettingsAdsMidSentence');
case ContentSettingsTypes.CLIPBOARD:
return this.i18n('siteSettingsClipboardMidSentence');
case ContentSettingsTypes.SENSORS:
return this.i18n('siteSettingsSensorsMidSentence');
case ContentSettingsTypes.PAYMENT_HANDLER:
return this.i18n('siteSettingsPaymentHandlerMidSentence');
case ContentSettingsTypes.MIXEDSCRIPT:
return this.i18n('siteSettingsInsecureContentMidSentence');
case ContentSettingsTypes.BLUETOOTH_SCANNING:
return this.i18n('siteSettingsBluetoothScanningMidSentence');
case ContentSettingsTypes.FILE_SYSTEM_WRITE:
return this.i18n('siteSettingsFileSystemWriteMidSentence');
case ContentSettingsTypes.HID_DEVICES:
return this.i18n('siteSettingsHidDevicesMidSentence');
case ContentSettingsTypes.AR:
return this.i18n('siteSettingsArMidSentence');
case ContentSettingsTypes.VR:
return this.i18n('siteSettingsVrMidSentence');
case ContentSettingsTypes.WINDOW_PLACEMENT:
return this.i18n('siteSettingsWindowPlacementMidSentence');
case ContentSettingsTypes.FONT_ACCESS:
return this.i18n('siteSettingsFontAccessMidSentence');
case ContentSettingsTypes.IDLE_DETECTION:
return this.i18n('siteSettingsIdleDetectionMidSentence');
default:
return '';
}
}
/**
* @return a user-friendly name for the origin a set of recent permissions
* is associated with.
*/
private getDisplayName_(recentSitePermissions: RecentSitePermissions):
string {
return this.toUrl(recentSitePermissions.origin)!.host;
}
/**
* @return the site scheme for the origin of a set of recent permissions.
*/
private getSiteScheme_({origin}: RecentSitePermissions): string {
const scheme = this.toUrl(origin)!.protocol.slice(0, -1);
return scheme === 'https' ? '' : scheme;
}
/**
* @return the display text which describes the set of recent permissions.
*/
private getPermissionsText_({recentPermissions}: RecentSitePermissions):
string {
// Recently changed permisisons for a site are grouped into three buckets,
// each described by a single sentence.
const groupSentences = [
this.getPermissionGroupText_(
'Allowed',
recentPermissions.filter(
exception => exception.setting === ContentSetting.ALLOW)),
this.getPermissionGroupText_(
'AutoBlocked',
recentPermissions.filter(
exception => exception.source === SiteSettingSource.EMBARGO)),
this.getPermissionGroupText_(
'Blocked',
recentPermissions.filter(
exception => exception.setting === ContentSetting.BLOCK &&
exception.source !== SiteSettingSource.EMBARGO)),
].filter(string => string.length > 0);
let finalText = '';
// The final text may be composed of multiple sentences, so may need the
// appropriate sentence separators.
for (const sentence of groupSentences) {
if (finalText.length > 0) {
// Whitespace is a valid sentence separator w.r.t i18n.
finalText += `${this.i18n('sentenceEnd')} ${sentence}`;
} else {
finalText = sentence;
}
}
if (groupSentences.length > 1) {
finalText += this.i18n('sentenceEnd');
}
return finalText;
}
/**
* @return the display sentence which groups the provided |exceptions|
* together and applies the appropriate description based on |setting|.
*/
private getPermissionGroupText_(
setting: string, exceptions: Array<RawSiteException>): string {
const typeStrings = exceptions.map(
exception => this.getI18nContentTypeString_(
exception.type as ContentSettingsTypes));
if (exceptions.length === 0) {
return '';
}
if (exceptions.length === 1) {
return this.i18n(`recentPermission${setting}OneItem`, ...typeStrings);
}
if (exceptions.length === 2) {
return this.i18n(`recentPermission${setting}TwoItems`, ...typeStrings);
}
return this.i18n(
`recentPermission${setting}MoreThanTwoItems`, typeStrings[0],
exceptions.length - 1);
}
/**
* @return the correct CSS class to apply depending on this recent site
* permissions entry based on the index.
*/
private getClassForIndex_(index: number): string {
return index === 0 ? 'first' : '';
}
/**
* @return true if there are no recent site permissions to display
*/
private computeNoRecentPermissions_(): boolean {
return this.recentSitePermissionsList_.length === 0;
}
/**
* Called for when incognito is enabled or disabled. Only called on change
* (opening N incognito windows only fires one message). Another message is
* sent when the *last* incognito window closes.
*/
private onIncognitoStatusChanged_(hasIncognito: boolean) {
// We're only interested in the case where we transition out of incognito
// and we are currently displaying an incognito entry.
if (hasIncognito === false &&
this.recentSitePermissionsList_.some(p => p.incognito)) {
this.populateList_();
}
}
/**
* A handler for selecting a recent site permissions entry.
*/
private onRecentSitePermissionClick_(e: RepeaterEvent) {
const origin = this.recentSitePermissionsList_[e.model.index].origin;
Router.getInstance().navigateTo(
routes.SITE_SETTINGS_SITE_DETAILS, new URLSearchParams({site: origin}));
this.browserProxy.recordAction(AllSitesAction2.ENTER_SITE_DETAILS);
this.lastSelected_ = {
index: e.model.index,
origin: e.model.item.origin,
incognito: e.model.item.incognito,
};
}
private onShowIncognitoTooltip_(e: Event) {
e.stopPropagation();
const target = e.target!;
const tooltip = this.$.tooltip;
tooltip.target = target;
tooltip.updatePosition();
const hide = () => {
tooltip.hide();
target.removeEventListener('mouseleave', hide);
target.removeEventListener('blur', hide);
target.removeEventListener('click', hide);
tooltip.removeEventListener('mouseenter', hide);
};
target.addEventListener('mouseleave', hide);
target.addEventListener('blur', hide);
target.addEventListener('click', hide);
tooltip.addEventListener('mouseenter', hide);
tooltip.show();
}
/**
* Called after the list has finished populating and |lastSelected_| contains
* a valid entry that should attempt to be focused. If lastSelected_ cannot
* be found the index where it used to be is focused. This may result in
* focusing another link arrow, or an incognito information icon. If the
* recent permission list is empty, focus is lost.
*/
private focusLastSelected_() {
if (this.noRecentPermissions) {
return;
}
const currentIndex =
this.recentSitePermissionsList_.findIndex((permissions) => {
return permissions.origin === this.lastSelected_!.origin &&
permissions.incognito === this.lastSelected_!.incognito;
});
const fallbackIndex = Math.min(
this.lastSelected_!.index, this.recentSitePermissionsList_.length - 1);
const index = currentIndex > -1 ? currentIndex : fallbackIndex;
if (this.recentSitePermissionsList_[index].incognito) {
focusWithoutInk(assert(
(this.shadowRoot!.querySelector(`#incognitoInfoIcon_${index}`) as
CrTooltipIconElement)
.getFocusableElement()));
} else {
focusWithoutInk(
assert(this.shadowRoot!.querySelector(`#siteEntryButton_${index}`)!));
}
}
/**
* Retrieve the list of recently changed permissions and implicitly trigger
* the update of the display list.
*/
private async populateList_() {
this.recentSitePermissionsList_ =
await this.browserProxy.getRecentSitePermissions(3);
}
/**
* Called when the dom-repeat DOM has changed. This allows updating the
* focused element after the elements have been adjusted.
*/
private onDomChange_() {
if (this.shouldFocusAfterPopulation_) {
this.focusLastSelected_();
this.shouldFocusAfterPopulation_ = false;
}
}
}
declare global {
interface HTMLElementTagNameMap {
'settings-recent-site-permissions': SettingsRecentSitePermissionsElement;
}
}
customElements.define(
SettingsRecentSitePermissionsElement.is,
SettingsRecentSitePermissionsElement); | the_stack |
* ============================================================================
* IMPORTS
* ============================================================================
* @hidden
*/
import { Disposer, IDisposer, MultiDisposer } from "./Disposer";
import * as $array from "./Array";
import * as $type from "./Type";
/**
* @ignore
*/
export type Events<Target, T> = {
[K in keyof T]: T[K] & { type: K, target: Target }
};
/**
* A universal interface for event listeners.
*
* @ignore
*/
export interface EventListener {
killed: boolean;
once: boolean;
type: any | null;
callback: (event: any) => void;
context: unknown;
shouldClone: boolean;
dispatch: (type: any, event: any) => void;
disposer: IDisposer;
}
/**
* Universal Event Dispatcher.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/events/} for more info
*/
export class EventDispatcher<T> implements IDisposer {
protected _listeners: Array<EventListener>;
protected _killed: Array<EventListener>;
protected _disabled: { [key in keyof T]?: number };
protected _iterating: number;
protected _enabled: boolean;
protected _disposed: boolean;
/**
* Constructor
*/
constructor() {
this._listeners = [];
this._killed = [];
this._disabled = {};
this._iterating = 0;
this._enabled = true;
this._disposed = false;
}
/**
* Returns if this object has been already disposed.
*
* @return Disposed?
*/
public isDisposed(): boolean {
return this._disposed;
}
/**
* Dispose (destroy) this object.
*/
public dispose(): void {
if (!this._disposed) {
this._disposed = true;
const a = this._listeners;
this._iterating = 1;
this._listeners = <any>null;
this._disabled = <any>null;
try {
$array.each(a, (x) => {
x.disposer.dispose();
});
} finally {
this._killed = <any>null;
this._iterating = <any>null;
}
}
}
/**
* Checks if this particular event dispatcher has any listeners set.
*
* @return Has listeners?
*/
public hasListeners(): boolean {
return this._listeners.length !== 0;
}
/**
* Checks if this particular event dispatcher has any particular listeners set.
*
* @return Has particular event listeners?
*/
public hasListenersByType<Key extends keyof T>(type: Key): boolean {
return $array.any(this._listeners, (x) => (x.type === null || x.type === type) && !x.killed);
}
/**
* Enable dispatching of events if they were previously disabled by
* `disable()`.
*/
public enable(): void {
this._enabled = true;
}
/**
* Disable dispatching of events until re-enabled by `enable()`.
*/
public disable(): void {
this._enabled = false;
}
/**
* Enable dispatching particular event, if it was disabled before by
* `disableType()`.
*
* @param type Event type
*/
public enableType<Key extends keyof T>(type: Key): void {
delete this._disabled[type];
}
/**
* Disable dispatching of events for a certain event type.
*
* Optionally, can set how many dispatches to skip before automatically
* re-enabling the dispatching.
*
* @param type Event type
* @param amount Number of event dispatches to skip
*/
public disableType<Key extends keyof T>(type: Key, amount: number = Infinity): void {
this._disabled[type] = amount;
}
/**
* Removes listener from dispatcher.
*
* Will throw an exception if such listener does not exists.
*
* @param listener Listener to remove
*/
protected _removeListener(listener: EventListener): void {
if (this._iterating === 0) {
const index = this._listeners.indexOf(listener);
if (index === -1) {
throw new Error("Invalid state: could not remove listener");
}
this._listeners.splice(index, 1);
} else {
this._killed.push(listener);
}
}
/**
* Removes existing listener by certain parameters.
*
* @param once Listener's once setting
* @param type Listener's type
* @param callback Callback function
* @param context Callback context
*/
protected _removeExistingListener<C, Key extends keyof T>(once: boolean, type: Key | null, callback?: (this: C, event: T[Key]) => void, context?: C): void {
if (this._disposed) {
throw new Error("EventDispatcher is disposed");
}
this._eachListener((info) => {
if (info.once === once && // TODO is this correct ?
info.type === type &&
(callback === undefined || info.callback === callback) &&
info.context === context) {
info.disposer.dispose();
}
});
}
/**
* Checks if dispatching for particular event type is enabled.
*
* @param type Event type
* @return Enabled?
*/
public isEnabled<Key extends keyof T>(type: Key): boolean {
if (this._disposed) {
throw new Error("EventDispatcher is disposed");
}
// TODO is this check correct ?
return this._enabled && this._listeners.length > 0 && this.hasListenersByType(type) && this._disabled[type] === undefined;
}
/**
* Checks if there's already a listener with specific parameters.
*
* @param type Listener's type
* @param callback Callback function
* @param context Callback context
* @return Has listener?
*/
public has<C, Key extends keyof T>(type: Key, callback?: (this: C, event: T[Key]) => void, context?: C): boolean {
const index = $array.findIndex(this._listeners, (info) => {
return info.once !== true && // Ignoring "once" listeners
info.type === type &&
(callback === undefined || info.callback === callback) &&
info.context === context;
});
return index !== -1;
}
/**
* Checks whether event of the particular type should be dispatched.
*
* @param type Event type
* @return Dispatch?
*/
protected _shouldDispatch<Key extends keyof T>(type: Key): boolean {
if (this._disposed) {
throw new Error("EventDispatcher is disposed");
}
const count = this._disabled[type];
if (!$type.isNumber(count)) {
return this._enabled;
} else {
if (count <= 1) {
delete this._disabled[type];
} else {
--this._disabled[type]!;
}
return false;
}
}
/**
* [_eachListener description]
*
* All of this extra code is needed when a listener is removed while iterating
*
* @todo Description
* @param fn [description]
*/
protected _eachListener(fn: (listener: EventListener) => void): void {
++this._iterating;
try {
$array.each(this._listeners, fn);
} finally {
--this._iterating;
// TODO should this be inside or outside the finally ?
if (this._iterating === 0 && this._killed.length !== 0) {
// Remove killed listeners
$array.each(this._killed, (killed) => {
this._removeListener(killed);
});
this._killed.length = 0;
}
}
}
/**
* Dispatches an event immediately without waiting for next cycle.
*
* @param type Event type
* @param event Event object
* @todo automatically add in type and target properties if they are missing
*/
public dispatch<Key extends keyof T>(type: Key, event: T[Key]): void {
if (this._shouldDispatch(type)) {
// TODO check if it's faster to use an object of listeners rather than a single big array
// TODO if the function throws, maybe it should keep going ?
this._eachListener((listener) => {
if (!listener.killed && (listener.type === null || listener.type === type)) {
listener.dispatch(type, event);
}
});
}
}
/**
* Shelves the event to be dispatched within next update cycle.
*
* @param type Event type
* @param event Event object
* @todo automatically add in type and target properties if they are missing
*/
/*public dispatchLater<Key extends keyof T>(type: Key, event: T[Key]): void {
if (this._shouldDispatch(type)) {
this._eachListener((listener) => {
// TODO check if it's faster to use an object of listeners rather than a single big array
if (!listener.killed && (listener.type === null || listener.type === type)) {
// TODO if the function throws, maybe it should keep going ?
// TODO dispatch during the update cycle, rather than using whenIdle
$async.whenIdle(() => {
if (!listener.killed) {
listener.dispatch(type, event);
}
});
}
});
}
}*/
/**
* Creates, catalogs and returns an [[EventListener]].
*
* Event listener can be disposed.
*
* @param once Listener's once setting
* @param type Listener's type
* @param callback Callback function
* @param context Callback context
* @param shouldClone Whether the listener should be copied when the EventDispatcher is copied
* @param dispatch
* @returns An event listener
*/
protected _on<C, Key extends keyof T>(once: boolean, type: Key | null, callback: any, context: C, shouldClone: boolean, dispatch: (type: Key, event: T[Key]) => void): EventListener {
if (this._disposed) {
throw new Error("EventDispatcher is disposed");
}
this._removeExistingListener(once, type, callback, context);
const info: EventListener = {
type: type,
callback: callback,
context: context,
shouldClone: shouldClone,
dispatch: <any>dispatch,
killed: false,
once: once,
disposer: new Disposer(() => {
info.killed = true;
this._removeListener(info);
})
};
this._listeners.push(info);
return info;
}
/**
* Creates an event listener to be invoked on **any** event.
*
* @param callback Callback function
* @param context Callback context
* @param shouldClone Whether the listener should be copied when the EventDispatcher is copied
* @returns A disposable event listener
*/
public onAll<C, K extends keyof T>(callback: (this: C, event: T[K]) => void, context?: C, shouldClone: boolean = true): IDisposer {
return this._on(false, null, callback, context, shouldClone, (_type, event) => (<any>callback).call(context, event as any)).disposer;
}
/**
* Creates an event listener to be invoked on a specific event type.
*
* ```TypeScript
* button.events.once("click", (ev) => {
* console.log("Button clicked");
* }, this);
* ```
* ```JavaScript
* button.events.once("click", (ev) => {
* console.log("Button clicked");
* }, this);
* ```
*
* The above will invoke our custom event handler whenever series we put
* event on is hidden.
*
* @param type Listener's type
* @param callback Callback function
* @param context Callback context
* @param shouldClone Whether the listener should be copied when the EventDispatcher is copied
* @returns A disposable event listener
*/
public on<C, Key extends keyof T>(type: Key, callback: (this: C | undefined, event: T[Key]) => void, context?: C, shouldClone: boolean = true): IDisposer {
return this._on(false, type, callback, context, shouldClone, (_type, event) => callback.call(context, event)).disposer;
}
/**
* Creates an event listener to be invoked on a specific event type once.
*
* Once the event listener is invoked, it is automatically disposed.
*
* ```TypeScript
* button.events.once("click", (ev) => {
* console.log("Button clicked");
* }, this);
* ```
* ```JavaScript
* button.events.once("click", (ev) => {
* console.log("Button clicked");
* }, this);
* ```
*
* The above will invoke our custom event handler the first time series we
* put event on is hidden.
*
* @param type Listener's type
* @param callback Callback function
* @param context Callback context
* @param shouldClone Whether the listener should be copied when the EventDispatcher is copied
* @returns A disposable event listener
*/
public once<C, Key extends keyof T>(type: Key, callback: (this: C | undefined, event: T[Key]) => void, context?: C, shouldClone: boolean = true): IDisposer {
const x = this._on(true, type, callback, context, shouldClone, (_type, event) => {
x.disposer.dispose();
callback.call(context, event)
});
// TODO maybe this should return a different Disposer ?
return x.disposer;
}
/**
* Removes the event listener with specific parameters.
*
* @param type Listener's type
* @param callback Callback function
* @param context Callback context
*/
public off<C, Key extends keyof T>(type: Key, callback?: (this: C, event: T[Key]) => void, context?: C): void {
this._removeExistingListener(false, type, callback, context);
}
/**
* Copies all dispatcher parameters, including listeners, from another event
* dispatcher.
*
* @param source Source event dispatcher
* @ignore
*/
public copyFrom(source: this): IDisposer {
if (this._disposed) {
throw new Error("EventDispatcher is disposed");
}
if (source === this) {
throw new Error("Cannot copyFrom the same TargetedEventDispatcher");
}
const disposers: Array<IDisposer> = [];
$array.each(source._listeners, (x) => {
// TODO is this correct ?
if (!x.killed && x.shouldClone) {
if (x.type === null) {
disposers.push(this.onAll(x.callback as any, x.context));
} else if (x.once) {
disposers.push(this.once(x.type, x.callback, x.context));
} else {
disposers.push(this.on(x.type, x.callback, x.context));
}
}
});
return new MultiDisposer(disposers);
}
}
/**
* A version of the [[EventDispatcher]] that dispatches events for a specific
* target object.
*
* @ignore
*/
export class TargetedEventDispatcher<Target, T> extends EventDispatcher<T> {
/**
* A target object which is originating events using this dispatcher.
*/
public target: Target;
/**
* Constructor
*
* @param target Event dispatcher target
*/
constructor(target: Target) {
super();
this.target = target;
}
/**
* Copies all dispatcher parameters, including listeners, from another event
* dispatcher.
*
* @param source Source event dispatcher
* @ignore
*/
public copyFrom(source: this): IDisposer {
if (this._disposed) {
throw new Error("EventDispatcher is disposed");
}
if (source === this) {
throw new Error("Cannot copyFrom the same TargetedEventDispatcher");
}
const disposers: Array<IDisposer> = [];
$array.each(source._listeners, (x) => {
// TODO very hacky
if (x.context === source.target) {
return;
}
// TODO is this correct ?
if (!x.killed && x.shouldClone) {
if (x.type === null) {
disposers.push(this.onAll(x.callback as any, x.context));
} else if (x.once) {
disposers.push(this.once(x.type, x.callback, x.context));
} else {
disposers.push(this.on(x.type, x.callback, x.context));
}
}
});
return new MultiDisposer(disposers);
}
} | the_stack |
import inspect from '../jsutils/inspect.js';
import { isNode } from './ast.js';
/**
* A visitor is provided to visit, it contains the collection of
* relevant functions to be called during the visitor's traversal.
*/
export const QueryDocumentKeys = {
Name: [],
Document: ['definitions'],
OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],
VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],
Variable: ['name'],
SelectionSet: ['selections'],
Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
Argument: ['name', 'value'],
FragmentSpread: ['name', 'directives'],
InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed
// or removed in the future.
'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'],
IntValue: [],
FloatValue: [],
StringValue: [],
BooleanValue: [],
NullValue: [],
EnumValue: [],
ListValue: ['values'],
ObjectValue: ['fields'],
ObjectField: ['name', 'value'],
Directive: ['name', 'arguments'],
NamedType: ['name'],
ListType: ['type'],
NonNullType: ['type'],
SchemaDefinition: ['description', 'directives', 'operationTypes'],
OperationTypeDefinition: ['type'],
ScalarTypeDefinition: ['description', 'name', 'directives'],
ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],
InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'],
InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
UnionTypeDefinition: ['description', 'name', 'directives', 'types'],
EnumTypeDefinition: ['description', 'name', 'directives', 'values'],
EnumValueDefinition: ['description', 'name', 'directives'],
InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],
DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],
SchemaExtension: ['directives', 'operationTypes'],
ScalarTypeExtension: ['name', 'directives'],
ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
UnionTypeExtension: ['name', 'directives', 'types'],
EnumTypeExtension: ['name', 'directives', 'values'],
InputObjectTypeExtension: ['name', 'directives', 'fields']
};
export const BREAK = Object.freeze({});
/**
* visit() will walk through an AST using a depth first traversal, calling
* the visitor's enter function at each node in the traversal, and calling the
* leave function after visiting that node and all of its child nodes.
*
* By returning different values from the enter and leave functions, the
* behavior of the visitor can be altered, including skipping over a sub-tree of
* the AST (by returning false), editing the AST by returning a value or null
* to remove the value, or to stop the whole traversal by returning BREAK.
*
* When using visit() to edit an AST, the original AST will not be modified, and
* a new version of the AST with the changes applied will be returned from the
* visit function.
*
* const editedAST = visit(ast, {
* enter(node, key, parent, path, ancestors) {
* // @return
* // undefined: no action
* // false: skip visiting this node
* // visitor.BREAK: stop visiting altogether
* // null: delete this node
* // any value: replace this node with the returned value
* },
* leave(node, key, parent, path, ancestors) {
* // @return
* // undefined: no action
* // false: no action
* // visitor.BREAK: stop visiting altogether
* // null: delete this node
* // any value: replace this node with the returned value
* }
* });
*
* Alternatively to providing enter() and leave() functions, a visitor can
* instead provide functions named the same as the kinds of AST nodes, or
* enter/leave visitors at a named key, leading to four permutations of
* visitor API:
*
* 1) Named visitors triggered when entering a node a specific kind.
*
* visit(ast, {
* Kind(node) {
* // enter the "Kind" node
* }
* })
*
* 2) Named visitors that trigger upon entering and leaving a node of
* a specific kind.
*
* visit(ast, {
* Kind: {
* enter(node) {
* // enter the "Kind" node
* }
* leave(node) {
* // leave the "Kind" node
* }
* }
* })
*
* 3) Generic visitors that trigger upon entering and leaving any node.
*
* visit(ast, {
* enter(node) {
* // enter any node
* },
* leave(node) {
* // leave any node
* }
* })
*
* 4) Parallel visitors for entering and leaving nodes of a specific kind.
*
* visit(ast, {
* enter: {
* Kind(node) {
* // enter the "Kind" node
* }
* },
* leave: {
* Kind(node) {
* // leave the "Kind" node
* }
* }
* })
*/
export function visit(root, visitor, visitorKeys = QueryDocumentKeys) {
/* eslint-disable no-undef-init */
let stack = undefined;
let inArray = Array.isArray(root);
let keys = [root];
let index = -1;
let edits = [];
let node = undefined;
let key = undefined;
let parent = undefined;
const path = [];
const ancestors = [];
let newRoot = root;
/* eslint-enable no-undef-init */
do {
index++;
const isLeaving = index === keys.length;
const isEdited = isLeaving && edits.length !== 0;
if (isLeaving) {
key = ancestors.length === 0 ? undefined : path[path.length - 1];
node = parent;
parent = ancestors.pop();
if (isEdited) {
if (inArray) {
node = node.slice();
} else {
const clone = {};
for (const k of Object.keys(node)) {
clone[k] = node[k];
}
node = clone;
}
let editOffset = 0;
for (let ii = 0; ii < edits.length; ii++) {
let editKey = edits[ii][0];
const editValue = edits[ii][1];
if (inArray) {
editKey -= editOffset;
}
if (inArray && editValue === null) {
node.splice(editKey, 1);
editOffset++;
} else {
node[editKey] = editValue;
}
}
}
index = stack.index;
keys = stack.keys;
edits = stack.edits;
inArray = stack.inArray;
stack = stack.prev;
} else {
key = parent ? inArray ? index : keys[index] : undefined;
node = parent ? parent[key] : newRoot;
if (node === null || node === undefined) {
continue;
}
if (parent) {
path.push(key);
}
}
let result;
if (!Array.isArray(node)) {
if (!isNode(node)) {
throw new Error(`Invalid AST Node: ${inspect(node)}.`);
}
const visitFn = getVisitFn(visitor, node.kind, isLeaving);
if (visitFn) {
result = visitFn.call(visitor, node, key, parent, path, ancestors);
if (result === BREAK) {
break;
}
if (result === false) {
if (!isLeaving) {
path.pop();
continue;
}
} else if (result !== undefined) {
edits.push([key, result]);
if (!isLeaving) {
if (isNode(result)) {
node = result;
} else {
path.pop();
continue;
}
}
}
}
}
if (result === undefined && isEdited) {
edits.push([key, node]);
}
if (isLeaving) {
path.pop();
} else {
stack = {
inArray,
index,
keys,
edits,
prev: stack
};
inArray = Array.isArray(node);
keys = inArray ? node : visitorKeys[node.kind] ?? [];
index = -1;
edits = [];
if (parent) {
ancestors.push(parent);
}
parent = node;
}
} while (stack !== undefined);
if (edits.length !== 0) {
newRoot = edits[edits.length - 1][1];
}
return newRoot;
}
/**
* Creates a new visitor instance which delegates to many visitors to run in
* parallel. Each visitor will be visited for each node before moving on.
*
* If a prior visitor edits a node, no following visitors will see that node.
*/
export function visitInParallel(visitors) {
const skipping = new Array(visitors.length);
return {
enter(node) {
for (let i = 0; i < visitors.length; i++) {
if (skipping[i] == null) {
const fn = getVisitFn(visitors[i], node.kind,
/* isLeaving */
false);
if (fn) {
const result = fn.apply(visitors[i], arguments);
if (result === false) {
skipping[i] = node;
} else if (result === BREAK) {
skipping[i] = BREAK;
} else if (result !== undefined) {
return result;
}
}
}
}
},
leave(node) {
for (let i = 0; i < visitors.length; i++) {
if (skipping[i] == null) {
const fn = getVisitFn(visitors[i], node.kind,
/* isLeaving */
true);
if (fn) {
const result = fn.apply(visitors[i], arguments);
if (result === BREAK) {
skipping[i] = BREAK;
} else if (result !== undefined && result !== false) {
return result;
}
}
} else if (skipping[i] === node) {
skipping[i] = null;
}
}
}
};
}
/**
* Given a visitor instance, if it is leaving or not, and a node kind, return
* the function the visitor runtime should call.
*/
export function getVisitFn(visitor, kind, isLeaving) {
const kindVisitor = visitor[kind];
if (kindVisitor) {
if (!isLeaving && typeof kindVisitor === 'function') {
// { Kind() {} }
return kindVisitor;
}
const kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;
if (typeof kindSpecificVisitor === 'function') {
// { Kind: { enter() {}, leave() {} } }
return kindSpecificVisitor;
}
} else {
const specificVisitor = isLeaving ? visitor.leave : visitor.enter;
if (specificVisitor) {
if (typeof specificVisitor === 'function') {
// { enter() {}, leave() {} }
return specificVisitor;
}
const specificKindVisitor = specificVisitor[kind];
if (typeof specificKindVisitor === 'function') {
// { enter: { Kind() {} }, leave: { Kind() {} } }
return specificKindVisitor;
}
}
}
} | the_stack |
import { AxiosInstance } from "axios";
import { Agent } from "https";
import mixin from "mixin-deep";
import axios from "axios";
interface createSpecInterface {
address: string;
port: number;
protocol: string;
username: string;
password: string;
}
interface rpInterface {
uri: string;
json: any;
}
/**
* Simple axios instance with disabled SSL to allow the self signed cert
*/
const instance: AxiosInstance = axios.create({
httpsAgent: new Agent({
rejectUnauthorized: false,
}),
});
/**
* Since were using legacy code and not using request-promise we just create a
* small work wrapper
* @param uri {string}
* @param json {boolean}
*/
async function rp({ uri, json }: rpInterface): Promise<any> {
const request = await instance.get(uri);
return request.data;
}
/**
* @param address
* @param port
* @param username
* @param password
* @param protocol
* @returns {Promise<{basePath: string, paths: {}, host: string, produces: [string, string, string], schemes: [*], definitions: {}, swagger: string, consumes, info: {description: string, title: string, version: *}}>}
*/
export default async ({
address = "127.0.0.1",
port,
username = "riot",
password,
protocol = "https",
}: createSpecInterface): Promise<any> => {
const helpConsole = await rp({
uri: `${protocol}://${username}:${password}@${address}:${port}/help?format=Console`,
json: true,
});
const helpFull = await rp({
uri: `${protocol}://${username}:${password}@${address}:${port}/help?format=Full`,
json: true,
});
const builds = await rp({
uri: `${protocol}://${username}:${password}@${address}:${port}/system/v1/builds`,
json: true,
});
const swagger = {
host: `${address}:${port}`,
schemes: [protocol],
consumes: [
"application/json",
"application/vnd.api+json",
"application/x-yaml",
"application/x-msgpack",
"application/octet-stream",
"application/x-www-form-urlencoded",
"multipart/form-data",
],
definitions: {},
paths: {},
info: {
description: "Always up to date LCU API documentation",
title: "Rift Explorer 7",
version: builds.version,
},
produces: [
"application/json",
"application/x-yaml",
"application/x-msgpack",
],
swagger: "2.0",
components: {
securitySchemes: {
basicAuth: {
type: "http",
scheme: "basic",
},
},
},
security: {
basicAuth: [],
},
};
// Mix helps to get a more complete version
const funcs = {};
const types = {};
const events = {};
helpFull.functions.forEach((func) => {
funcs[func.name] = func;
});
helpFull.types.forEach((type) => {
types[type.name] = type;
});
helpFull.events.forEach((event) => {
events[event.name] = event;
});
helpFull.functions = funcs;
helpFull.types = types;
helpFull.events = events;
const help = mixin({}, helpConsole, helpFull);
Object.keys(help.types).forEach((type) => {
swagger.definitions[type] = {};
if (help.types[type].description) {
swagger.definitions[type].description = help.types[type].description;
}
// Object
if (help.types[type].fields) {
swagger.definitions[type].properties = {};
help.types[type].fields.forEach((field) => {
const fieldKey = field.name;
swagger.definitions[type].properties[fieldKey] = {};
swagger.definitions[type].properties[fieldKey].type = field.type.type;
if (field.description) {
swagger.definitions[type].properties[fieldKey].description =
field.description;
}
// Check if the type of the field is an (u)int
if (
/^u?int/.test(swagger.definitions[type].properties[fieldKey].type)
) {
swagger.definitions[type].properties[fieldKey].format =
swagger.definitions[type].properties[fieldKey].type;
swagger.definitions[type].properties[fieldKey].type = "integer";
return;
}
// Check if the type of the field is a double
if (swagger.definitions[type].properties[fieldKey].type === "string") {
return;
}
// Check if the type of the field is a double
if (swagger.definitions[type].properties[fieldKey].type === "double") {
swagger.definitions[type].properties[fieldKey].format =
swagger.definitions[type].properties[fieldKey].type;
swagger.definitions[type].properties[fieldKey].type = "number";
return;
}
// Check if the type of the field is a float
if (swagger.definitions[type].properties[fieldKey].type === "float") {
swagger.definitions[type].properties[fieldKey].format =
swagger.definitions[type].properties[fieldKey].type;
swagger.definitions[type].properties[fieldKey].type = "number";
return;
}
// Check if the type of the field is signed as `object`
if (swagger.definitions[type].properties[fieldKey].type === "object") {
swagger.definitions[type].properties[
fieldKey
].additionalProperties = true;
return;
}
// Check if the type of the field is signed as `boolean`
if (swagger.definitions[type].properties[fieldKey].type === "bool") {
swagger.definitions[type].properties[fieldKey].type = "boolean";
return;
}
if (swagger.definitions[type].properties[fieldKey].type === "map") {
swagger.definitions[type].properties[fieldKey].type = "object";
if (field.type.elementType === "object") {
swagger.definitions[type].properties[
fieldKey
].additionalProperties = {
additionalProperties: true,
type: "object",
};
return;
}
if (field.type.elementType === "string") {
swagger.definitions[type].properties[
fieldKey
].additionalProperties = {
type: "string",
};
return;
}
if (/^u?int/.test(field.type.elementType)) {
swagger.definitions[type].properties[
fieldKey
].additionalProperties = {
format: field.type.elementType,
type: "integer",
};
return;
}
if (
field.type.elementType === "double" ||
field.type.elementType === "float"
) {
swagger.definitions[type].properties[
fieldKey
].additionalProperties = {
format: field.type.elementType,
type: "number",
};
return;
}
swagger.definitions[type].properties[
fieldKey
].additionalProperties = {
$ref: `#/definitions/${field.type.elementType}`,
};
return;
}
if (swagger.definitions[type].properties[fieldKey].type === "vector") {
swagger.definitions[type].properties[fieldKey].type = "array";
if (field.type.elementType === "object") {
swagger.definitions[type].properties[fieldKey].items = {
additionalProperties: true,
type: "object",
};
return;
}
if (field.type.elementType === "string") {
swagger.definitions[type].properties[fieldKey].items = {
type: "string",
};
return;
}
if (/^u?int/.test(field.type.elementType)) {
swagger.definitions[type].properties[fieldKey].items = {
format: field.type.elementType,
type: "integer",
};
return;
}
if (
field.type.elementType === "double" ||
field.type.elementType === "float"
) {
swagger.definitions[type].properties[fieldKey].items = {
format: field.type.elementType,
type: "number",
};
return;
}
swagger.definitions[type].properties[fieldKey].items = {
$ref: `#/definitions/${field.type.elementType}`,
};
return;
}
// Check if the type is an actual object
// this is the case when a ref to another definition is made
// if (typeof swagger.definitions[type].properties[fieldKey].type === 'object') {
swagger.definitions[type].properties[
fieldKey
].$ref = `#/definitions/${swagger.definitions[type].properties[fieldKey].type}`;
delete swagger.definitions[type].properties[fieldKey].type;
// }
});
swagger.definitions[type].type = "object";
}
// String
if (help.types[type].values && help.types[type].values.length) {
swagger.definitions[type].type = "string";
swagger.definitions[type].enum = [];
help.types[type].values.forEach((value) => {
swagger.definitions[type].enum[value.value] = value.name;
});
swagger.definitions[type].enum = swagger.definitions[type].enum.filter(
(item) => !!item
);
}
});
const functions = {};
Object.keys(help.functions).forEach((func) => {
const helpFunc = help.functions[func];
if (!functions[helpFunc.url]) {
functions[helpFunc.url] = [];
}
functions[helpFunc.url].push(
Object.assign({ name: func }, help.functions[func])
);
});
Object.keys(functions).forEach((key) => {
const func = functions[key];
const result = {};
func.forEach((funcDef) => {
const method = funcDef.http_method || "";
result[method.toLowerCase()] = {
operationId: funcDef.name,
tags: funcDef.url
? [`Plugins ${funcDef.url.match("^/([^/]*)")[1]}`]
: funcDef.tags,
};
if (funcDef.description) {
result[method.toLowerCase()].summary = funcDef.description;
}
if (!result[method.toLowerCase()].tags.length) {
result[method.toLowerCase()].tags = ["Untagged"];
}
result[method.toLowerCase()].parameters = funcDef.arguments.map(
(argument) => {
let argumentLocation = "body";
if (new RegExp(`{${argument.name}}`).test(funcDef.url)) {
argumentLocation = "path";
// These are the only known header arguments
} else if (["JWT", "if-none-match"].includes(argument.name)) {
argumentLocation = "header";
}
const parameter = {
in: argumentLocation,
name: argument.name,
required: !argument.optional,
format: argument.format,
type: argument.type,
additionalProperties: argument.additionalProperties,
items: argument.items,
schema: argument.schema,
};
if (/^u?int/.test(argument.type.type)) {
parameter.format = argument.type.type;
parameter.type = "integer";
return parameter;
}
// Check if the type of the field is a double
if (argument.type.type === "string") {
parameter.type = argument.type.type;
}
// Check if the type of the field is a double
if (
argument.type.type === "double" ||
argument.type.type === "float"
) {
parameter.format = argument.type.type;
parameter.type = "number";
return parameter;
}
// Check if the type of the field is signed as `object`
if (argument.type.type === "object") {
parameter.additionalProperties = true;
parameter.type = argument.type.type;
return parameter;
}
// Check if the type of the field is signed as `boolean`
if (argument.type.type === "bool") {
parameter.type = "boolean";
return parameter;
}
if (argument.type.type === "map") {
parameter.type = "object";
if (argument.type.elementType === "object") {
parameter.additionalProperties = {
additionalProperties: true,
type: "object",
};
return parameter;
}
if (argument.type.elementType === "string") {
parameter.additionalProperties = {
type: "string",
};
return parameter;
}
if (/^u?int/.test(argument.type.elementType)) {
parameter.additionalProperties = {
format: argument.type.elementType,
type: "integer",
};
return parameter;
}
if (
argument.type.elementType === "double" ||
argument.type.elementType === "float"
) {
parameter.additionalProperties = {
format: argument.type.elementType,
type: "number",
};
return parameter;
}
parameter.additionalProperties = {
$ref: `#/definitions/${argument.type.elementType}`,
};
return parameter;
}
if (argument.type.type === "vector") {
parameter.type = "array";
if (argument.type.elementType === "object") {
parameter.items = {
additionalProperties: true,
type: "object",
};
return parameter;
}
if (argument.type.elementType === "string") {
parameter.items = {
type: "string",
};
return parameter;
}
if (/^u?int/.test(argument.type.elementType)) {
parameter.items = {
format: argument.type.elementType,
type: "integer",
};
return parameter;
}
if (
argument.type.elementType === "double" ||
argument.type.elementType === "float"
) {
parameter.items = {
format: argument.type.elementType,
type: "number",
};
return parameter;
}
parameter.items = {
$ref: `#/definitions/${argument.type.elementType}`,
};
return parameter;
}
parameter.schema = { $ref: `#/definitions/${argument.type.type}` };
delete parameter.type;
return parameter;
}
);
if (funcDef.http_method === "GET" || funcDef.http_method === "POST") {
if (funcDef.returns.type === "object") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
additionalProperties: true,
type: "object",
},
},
};
return;
}
if (funcDef.returns.type === "string") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "string",
},
},
};
return;
}
if (
funcDef.returns.type === "double" ||
funcDef.returns.type === "float"
) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
format: funcDef.returns.type,
type: "number",
},
},
};
return;
}
if (funcDef.returns.type === "bool") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "boolean",
},
},
};
return;
}
if (/^u?int/.test(funcDef.returns.type)) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "integer",
},
},
};
return;
}
// Check if the type of the field is signed as array of definitions
if (funcDef.returns.type === "vector") {
if (funcDef.returns.elementType === "object") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
additionalProperties: true,
type: funcDef.returns.elementType,
},
},
},
};
return;
}
if (funcDef.returns.elementType === "string") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
type: funcDef.returns.elementType,
},
},
},
};
return;
}
if (
funcDef.returns.elementType === "double" ||
funcDef.returns.elementType === "float"
) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
format: funcDef.returns.elementType,
type: "number",
},
},
},
};
return;
}
if (funcDef.returns.elementType === "bool") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
type: "boolean",
},
},
},
};
return;
}
if (/^u?int/.test(funcDef.returns.elementType)) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
type: "integer",
},
},
},
};
return;
}
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
$ref: `#/definitions/${funcDef.returns.elementType}`,
},
},
},
};
return;
}
if (funcDef.returns.type === "map") {
if (funcDef.returns.elementType === "object") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
additionalProperties: true,
type: funcDef.returns.elementType,
},
},
},
};
return;
}
if (funcDef.returns.elementType === "string") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
type: funcDef.returns.elementType,
},
},
},
};
return;
}
if (
funcDef.returns.elementType === "double" ||
funcDef.returns.elementType === "float"
) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
format: funcDef.returns.elementType,
type: "number",
},
},
},
};
return;
}
if (funcDef.returns.elementType === "bool") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
type: "boolean",
},
},
},
};
return;
}
if (/^u?int/.test(funcDef.returns.elementType)) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
type: "integer",
},
},
},
};
return;
}
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
type: funcDef.returns.elementType,
},
},
},
};
return;
}
if (funcDef.returns.type) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
$ref: `#/definitions/${Object.keys(funcDef.returns)[0]}`,
},
},
};
return;
}
result[method.toLowerCase()].responses = {
204: {
description: "No content",
},
};
// Check if the type of the field is signed as map of definitions
// if (/^map of .*$/.test(swagger.definitions[type].properties[fieldKey].type)) {
// const [, def] = swagger.definitions[type].properties[fieldKey].type.match(/^map of (.*)$/);
// swagger.definitions[type].properties[fieldKey].type = 'object';
// swagger.definitions[type].properties[fieldKey].additionalProperties = {
// $ref: `#/definitions/${def}`,
// };
// }
}
if (funcDef.http_method === "DELETE") {
result[method.toLowerCase()].responses = {
204: {
description: "No content",
},
};
}
});
functions[key] = result;
});
swagger.paths = functions;
return swagger;
};
/* eslint-enable */ | the_stack |
import {device} from "platform";
import Platform = require('platform');
const TAG = "TSLocationManager";
let emptyFn = function(){};
/**
* Url to transistorsoft tracking test server. Configure the plugin with a #username to automatically post
* locations to the test server, eg:
{
username: 'my-username'
}
* View your tracking online by visiting:
* http://tracker.transistorsoft.com/username
*
*/
const TEST_SERVER_URL = 'http://tracker.transistorsoft.com/locations/';
/**
* Logger
*/
export class Logger {
private api:any;
constructor(api:any) {
this.api = api;
}
public error(msg:string) {
this.log('error', msg);
}
public warn(msg:string) {
this.log('warn', msg);
}
public debug(msg:string) {
this.log('debug', msg);
}
public notice(msg:string) {
this.log('notice', msg);
}
public header(msg:string) {
this.log('header', msg);
}
public on(msg:string) {
this.log('on', msg);
}
public off(msg:string) {
this.log('off', msg);
}
public ok(msg:string) {
this.log('ok', msg);
}
private log(level:string, msg:string) {
this.api.log(level, msg);
}
}
/**
* BackgroundGeolocation
*/
export class BackgroundGeolocation {
private static api: any;
public static logger:Logger;
public static LOG_LEVEL_OFF:number = 0;
public static LOG_LEVEL_ERROR:number = 1;
public static LOG_LEVEL_WARNING:number = 2;
public static LOG_LEVEL_INFO:number = 3;
public static LOG_LEVEL_DEBUG:number = 4;
public static LOG_LEVEL_VERBOSE:number = 5;
public static DESIRED_ACCURACY_NAVIGATION:number = -2;
public static DESIRED_ACCURACY_HIGH:number = -1;
public static DESIRED_ACCURACY_MEDIUM:number = 10;
public static DESIRED_ACCURACY_LOW:number = 100;
public static DESIRED_ACCURACY_VERY_LOW:number = 1000;
public static DESIRED_ACCURACY_LOWEST:number = 3000;
public static AUTHORIZATION_STATUS_NOT_DETERMINED:number = 0;
public static AUTHORIZATION_STATUS_RESTRICTED:number = 1;
public static AUTHORIZATION_STATUS_DENIED:number = 2;
public static AUTHORIZATION_STATUS_ALWAYS:number = 3;
public static AUTHORIZATION_STATUS_WHEN_IN_USE:number = 4;
public static NOTIFICATION_PRIORITY_DEFAULT:number = 0;
public static NOTIFICATION_PRIORITY_HIGH:number = 1;
public static NOTIFICATION_PRIORITY_LOW:number =-1;
public static NOTIFICATION_PRIORITY_MAX:number = 2;
public static NOTIFICATION_PRIORITY_MIN:number =-2;
public static mountNativeApi(api) {
this.api = api;
this.logger = new Logger(api);
}
public static EVENTS:String[] = [
'heartbeat',
'http',
'location',
'error',
'motionchange',
'geofence',
'schedule',
'activitychange',
'providerchange',
'geofenceschange',
'watchposition',
'powersavechange',
'connectivitychange',
'enabledchange'
];
private static listeners = {
location: [],
http: [],
motionchange: [],
error: [],
heartbeat: [],
schedule: [],
activitychange: [],
providerchange: [],
geofence: [],
geofenceschange: [],
powersavechange: [],
connectivitychange: [],
enabledchange: []
};
private static headlessTask: Function;
public static registerHeadlessTask(callback:Function) {
this.headlessTask = callback;
}
public static runHeadlessTask(event:any, completionHandler:Function) {
if (this.headlessTask) {
this.headlessTask(event, completionHandler);
}
}
/**
* Core Plugin Control Methods
*/
public static ready(config:any, success?:Function, failure?:Function) {
config = this.validate(config);
if (arguments.length <= 1) {
return this.api.ready(config||{});
} else {
this.api.ready(config).then(success).catch(failure);
}
}
/**
* Reset plugin confg to default
*/
static reset(config?:any, success?:Function, failure?:Function) {
if ((typeof(config) === 'function') || (typeof(success) === 'function')) {
if (typeof(config) === 'function') {
success = config;
config = {};
}
config = this.validate(config||{});
this.api.reset(config).then(success).catch(failure);
} else {
return this.api.reset(this.validate(config||{}));
}
}
/**
* Perform initial configuration of plugin. Reset config to default before applying supplied configuration
*/
public static configure(config:any, success?:Function, failure?:Function) {
config = this.validate(config);
if (arguments.length == 1) {
return this.api.configure(config);
} else {
this.api.configure(config).then(success).catch(failure);
}
}
/**
* Listen to a plugin event
*/
public static addListener(event:string, success:Function, failure?:Function) {
if (this.EVENTS.indexOf(event) < 0) { throw "BackgroundGeolocation#on - Unknown event '" + event + "'" }
let nativeCallback = this.api.addListener.apply(this.api, arguments);
if (nativeCallback) {
this.registerCallback(event, success, nativeCallback);
}
}
private static registerCallback(event:string, clientCallback:Function, nativeCallback:Function) {
this.listeners[event].push({
clientCallback: clientCallback,
nativeCallback: nativeCallback
});
}
// @alias #addListener
public static on(event:string, success:Function, failure?:Function) {
this.addListener.apply(this, arguments);
}
/**
* Remove a single plugin event-listener, supplying a reference to the handler initially supplied to #un
*/
public static removeListener(event:string, clientCallback:Function, success?:Function, failure?:Function) {
if (this.EVENTS.indexOf(event) < 0) { throw "BackgroundGeolocation#un - Unknown event '" + event + "'" }
let listeners = this.listeners[event];
let listener = listeners.find((i) => { return i.clientCallback === clientCallback; });
if (listener) {
listeners.splice(listeners.indexOf(listener), 1);
if (arguments.length == 2) {
return this.api.removeListener(event, listener.nativeCallback);
} else {
this.api.removeListener(event, listener.nativeCallback).then(success).catch(failure);
}
} else {
let error = 'Failed to removeListener for event: ' + event;
failure = failure || emptyFn;
console.warn(error);
if (arguments.length == 2) {
return new Promise((resolve, reject) => {
reject(error);
});
} else {
failure(msg);
}
}
}
// @alias #removeListener
public static un(event:string, handler:Function, success?:Function, failiure?:Function) {
this.removeListener.apply(this, arguments);
}
/**
* Remove all event listeners
*/
public static removeListeners(event?:any, success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.removeListeners(); // #removeListeners()
} else if(typeof(arguments[0]) === 'string') {
if (this.EVENTS.indexOf(event) < 0) {
throw "BackgroundGeolocation#removeListeners - Unknown event: " + event;
}
// Clear client-calllbacks.
this.listeners[event] = [];
if (typeof(arguments[1]) === 'function') { // #removeListeners(event, success, failure);
this.api.removeListeners(event).then(success).catch(failure);
} else { // #removeListeners(event)
return this.api.removeListeners(event);
}
} else if (typeof(arguments[0]) === 'function') { // #removeListeners(success, failure)
success = event;
failure = success;
this.api.removeListeners().then(success).catch(failure);
}
}
/**
* Fetch current plugin configuration
*/
public static getState(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.getState();
} else {
this.api.getState().then(success).catch(failure);
}
}
/**
* Start the plugin
*/
public static start(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.start();
} else {
this.api.start().then(success).catch(failure);
}
}
/**
* Stop the plugin
*/
public static stop(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.stop();
} else {
this.api.stop().then(success).catch(failure);
}
}
/**
* Start the scheduler
*/
public static startSchedule(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.startSchedule();
} else {
this.api.startSchedule().then(success).catch(failure);
}
}
/**
* Stop the scheduler
*/
public static stopSchedule(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.stopSchedule();
} else {
this.api.stopSchedule().then(success).catch(failure);
}
}
/**
* Initiate geofences-only mode
*/
public static startGeofences(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.startGeofences();
} else {
this.api.startGeofences().then(success).catch(failure);
}
}
/**
* Start an iOS background-task, provding 180s of background running time
*/
public static startBackgroundTask(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.startBackgroundTask();
} else {
if (typeof(success) !== 'function') {
throw TAG + "#startBackgroundTask must be provided with a callback to recieve the taskId";
}
this.api.startBackgroundTask().then(success).catch(failure);
}
}
/**
* Signal to iOS that your background-task from #startBackgroundTask is complete
*/
public static finish(taskId:number, success?:Function, failure?:Function) {
// No taskId? Ignore it.
if (arguments.length == 1) {
return this.api.finish(taskId);
} else {
this.api.finish(taskId).then(success).catch(failure);
}
}
/**
* Toggle motion-state between stationary <-> moving
*/
public static changePace(isMoving:boolean, success?:Function, failure?:Function) {
if (arguments.length == 1) {
return this.api.changePace(isMoving);
} else {
this.api.changePace(isMoving).then(success).catch(failure);
}
}
/**
* Provide new configuration to the plugin. This configuration will be *merged* to current configuration
*/
public static setConfig(config:any, success?:Function, failure?:Function) {
if (arguments.length == 1) {
return this.api.setConfig(config);
} else {
this.api.setConfig(config).then(success).catch(failure);
}
}
/**
* HTTP & Persistence
*
*/
public static getLocations(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.getLocations();
} else {
this.api.getLocations().then(success).catch(failure);
}
}
/**
* Fetch the current count of location records in database
*/
public static getCount(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.getCount();
} else {
this.api.getCount().then(success).catch(failure);
}
}
/**
* Destroy all records in locations database
*/
public static destroyLocations(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.destroyLocations();
} else {
this.api.destroyLocations().then(success).catch(failure);
}
}
// @deprecated
public static clearDatabase(success?:Function, failure?:Function) {
return this.destroyLocations.apply(this, arguments);
}
/**
* Insert a single record into locations database
*/
public static insertLocation(location:any, success?:Function, failure?:Function) {
if (arguments.length == 1) {
return this.api.insertLocation(location);
} else {
this.api.insertLocation(location).then(success).catch(failure);
}
}
/**
* Manually initiate an HTTP sync operation
*/
public static sync(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.sync();
} else {
this.api.sync().then(success).catch(failure);
}
}
/**
* Fetch the current value of odometer
*/
public static getOdometer(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.getOdometer();
} else {
this.api.getOdometer().then(success).catch(failure);
}
}
/**
* Set the value of the odometer
*/
public static setOdometer(value:number, success?:Function, failure?:Function) {
if (arguments.length == 1) {
return this.api.setOdometer(value);
} else {
this.api.setOdometer(value).then(success).catch(failure);
}
}
/**
* Reset the value of odometer to 0
*/
public static resetOdometer(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.setOdometer(0);
} else {
this.api.setOdometer(0).then(success).catch(failure);
}
}
/**
* Geofencing Methods
*/
/**
* Add a single geofence
*/
public static addGeofence(config:any, success?:Function, failure?:Function) {
if (arguments.length == 1) {
return this.api.addGeofence(config);
} else {
this.api.addGeofence(config).then(success).catch(failure);
}
}
/**
* Remove a single geofence by identifier
*/
public static removeGeofence(identifier:string, success?:Function, failure?:Function) {
if (arguments.length == 1) {
return this.api.removeGeofence(identifier);
} else {
this.api.removeGeofence(identifier).then(success).catch(failure);
}
}
/**
* Add a list of geofences
*/
public static addGeofences(geofences:any, success?:Function, failure?:Function) {
if (arguments.length == 1) {
return this.api.addGeofences(geofences);
} else {
this.api.addGeofences(geofences).then(success).catch(failure);
}
}
/**
* Remove geofences. You may either supply an array of identifiers or nothing to destroy all geofences.
* 1. removeGeofences() <-- Promise
* 2. removeGeofences(['foo']) <-- Promise
*
* 3. removeGeofences(success, [failure])
* 4. removeGeofences(['foo'], success, [failure])
*/
public static removeGeofences(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.removeGeofences();
} else {
this.api.removeGeofences().then(success).catch(failure);
}
}
/**
* Fetch all geofences from database
*/
public static getGeofences(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.getGeofences();
} else {
this.api.getGeofences().then(success).catch(failure);
}
}
/**
* Fetch the current position from location-services
*/
public static getCurrentPosition(success:any, failure?:any, options?:any) {
if (typeof(success) == 'function') {
if (typeof(failure) == 'object') {
options = failure;
failure = emptyFn;
}
options = options || {};
this.api.getCurrentPosition(options).then(success).catch(failure);
} else {
options = success || {};
return this.api.getCurrentPosition(options);
}
}
/**
* Begin watching a stream of locations
*/
public static watchPosition(success:Function, failure?:Function, options?:any) {
this.api.watchPosition(success, failure||emptyFn, options||{});
}
/**
* Stop watching location
*/
public static stopWatchPosition(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.stopWatchPosition();
} else {
this.api.stopWatchPosition().then(success).catch(failure);
}
}
/**
* Set the logLevel. This is just a helper method for setConfig({logLevel: level})
*/
public static setLogLevel(value:number, success?:Function, failure?:Function) {
if (arguments.length == 1) {
return this.api.setLogLevel(value);
} else {
this.api.setLogLevel(value).then(success).catch(failure);
}
}
/**
* Fetch the entire contents of log database returned as a String
*/
public static getLog(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.getLog();
} else {
this.api.getLog().then(success).catch(failure);
}
}
/**
* Destroy all contents of log database
*/
public static destroyLog(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.destroyLog();
} else {
this.api.destroyLog().then(success).catch(failure);
}
}
/**
* Open deafult email client on device to email the contents of log database attached as a compressed file attachement
*/
public static emailLog(email:string, success?:Function, failure?:Function) {
if (typeof(email) != 'string') { throw TAG + "#emailLog requires an email address as 1st argument"}
if (arguments.length == 1) {
return this.api.emailLog(email);
} else {
this.api.emailLog(email).then(success).catch(failure);
}
}
/**
* Has device OS initiated power-saving mode?
*/
public static isPowerSaveMode(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.isPowerSaveMode();
} else {
this.api.isPowerSaveMode().then(success).catch(failure);
}
}
/**
* Fetch the state of this device's available motion-sensors
*/
public static getSensors(success?:Function, failure?:Function) {
if (!arguments.length) {
return this.api.getSensors();
} else {
this.api.getSensors().then(success).catch(failure);
}
}
/**
* Play a system sound via the plugin's Sound API
*/
public static playSound(soundId:number, success?:Function, failure?:Function) {
if (arguments.length == 1) {
return this.api.playSound(soundId);
} else {
this.api.playSound(soundId).then(success).catch(failure);
}
}
private static validate(config:any):any {
if (config.username) {
config.url = TEST_SERVER_URL + config.username;
config.params = {
device: {
uuid: Platform.device.uuid,
model: Platform.device.model,
platform: Platform.device.os,
manufacturer: Platform.device.manufacturer,
version: Platform.device.osVersion,
framework: '{N}'
}
}
delete config.username;
}
return config;
}
} | the_stack |
import 'jest-extended';
import { isElement } from '@antv/util';
import { Chart } from '../../../src/';
import { COMPONENT_TYPE } from '../../../src/constant';
import { createDiv, removeDom } from '../../util/dom';
import { delay } from '../../util/delay';
import { IGroup } from '@antv/g-base';
const IMAGE = 'https://img.alicdn.com/tfs/TB1M.wKkND1gK0jSZFyXXciOVXa-120-120.png';
export const DATA = [
{ city: '杭州', sale: 100 },
{ city: '广州', sale: 30 },
{ city: '上海', sale: 110 },
{ city: '呼和浩特', sale: 40 },
];
describe('annotation', () => {
const div = createDiv();
const chart = new Chart({
container: div,
width: 800,
height: 600,
padding: 24,
autoFit: false,
});
chart.data(DATA);
chart.scale('sale', { nice: true });
chart.animate(false);
chart.interval().position('city*sale');
chart.animate(false);
it('image', () => {
chart.annotation().image({
start: { city: '广州', sale: 30 },
end: { city: '广州', sale: 30 },
src: IMAGE,
offsetX: -12,
style: {
width: 24,
height: 24,
},
});
chart.render();
const image = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[0].component;
expect(image.get('src')).toBe(IMAGE);
expect(image.get('offsetX')).toBe(-12);
expect(image.get('style').width).toBe(24);
expect(image.get('animate')).toBe(false);
});
it('line', () => {
chart.animate(true);
chart.annotation().line({
start: { city: '上海', sale: 110 },
end: { city: '呼和浩特', sale: 110 },
style: {
stroke: 'green',
lineDash: [2, 2],
},
text: {
position: 'end',
content: '呼和浩特和上海',
maxLength: 60,
autoEllipsis: true,
background: {
padding: 5,
style: {
fill: '#1890ff',
fillOpacity: 0.3,
radius: 3,
},
},
style: {
fill: 'red',
fontSize: 14,
},
},
});
chart.render();
const line = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[1].component;
// theme
expect(line.get('style').lineDash).toEqual([2, 2]);
// pos
expect(line.get('start').x).toBe(494);
expect(line.get('start').y).toBe(70);
expect(line.get('end').x).toBe(682);
expect(line.get('end').y).toBe(70);
// style
expect(line.get('style').stroke).toBe('green');
expect(line.get('text').style.fill).toBe('red');
expect(line.get('text').style.fontSize).toBe(14);
// @ts-ignore
expect(line.getElementById('-annotation-line-text').attr('text').indexOf('…')).toBeGreaterThan(-1);
// @ts-ignore
expect(line.getElementById('-annotation-line-text-bg')).toBeDefined();
expect(line.get('animate')).toBe(true);
});
it('region', () => {
chart.annotation().region({
start: { city: '上海', sale: 0 },
end: { city: '呼和浩特', sale: 120 },
style: {
fill: 'grey',
},
});
chart.render();
const region = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[2].component;
expect(chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[2].layer).toBe('bg');
// theme
expect(region.get('style').fillOpacity).toBe(0.06);
// pos
expect(region.get('start').x).toBe(494);
expect(region.get('start').y).toBe(576);
expect(region.get('end').x).toBe(682);
expect(region.get('end').y).toBe(24);
expect(region.get('style').fill).toBe('grey');
});
it('text', () => {
chart.annotation().text({
position: { city: '杭州', sale: 100 },
content: '杭州的数据' + 100,
maxLength: 80,
autoEllipsis: true,
background: {
padding: 3,
style: {
fill: '#ccc',
fillOpacity: 0.5,
radius: 3,
},
},
style: {
fill: 'red',
textBaseline: 'bottom',
textAlign: 'center',
},
rotate: Math.PI * 0.25,
});
chart.render();
const text = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[3].component;
// theme
// @ts-ignore
expect(text.get('style').fontFamily).toEqual(chart.getTheme().fontFamily);
// pos
expect(text.get('x')).toBe(118);
expect(text.get('y')).toBe(116);
// style
expect(text.get('style').fill).toBe('red');
expect(text.get('rotate')).toBeCloseTo(Math.PI * 0.25);
expect(text.get('group').getFirst().attr('matrix')).not.toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]);
// @ts-ignore
expect(text.getElementById('-annotation-text').attr('text').indexOf('…')).toBeGreaterThan(-1);
// @ts-ignore
expect(text.getElementById('-annotation-text-bg')).toBeDefined();
});
it('use percentage position', () => {
chart.annotation().text({
position: ['50%', '50%'],
content: '坐标系中心点',
style: {
fill: 'red',
textBaseline: 'bottom',
textAlign: 'center',
},
});
chart.render();
const text = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[4].component;
const coordinateCenter = chart.getCoordinate().getCenter();
// pos
expect(text.get('x')).toBe(coordinateCenter.x);
expect(text.get('y')).toBe(coordinateCenter.y);
});
it('use array', () => {
chart.annotation().text({
position: ['杭州', 100],
content: '杭州杭州',
style: {
fill: 'red',
textBaseline: 'bottom',
textAlign: 'center',
},
});
chart.render();
const text = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[5].component;
// // pos
expect(text.get('x')).toBe(118);
expect(text.get('y')).toBe(116);
});
it('arc', () => {
chart.coordinate('polar');
chart.annotation().arc({
start: { city: '杭州', sale: 100 },
end: { city: '上海', sale: 100 },
style: {
stroke: '#289990',
lineWidth: 4,
},
});
chart.render();
const arc = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[6].component;
expect(arc.get('startAngle')).toBe(-Math.PI / 2);
expect(arc.get('endAngle')).toBe(Math.PI / 2);
// @ts-ignore
expect(arc.get('radius')).toBe(230);
});
it('dataMarker', () => {
chart.coordinate('rect');
chart.annotation().dataMarker({
position: { city: '上海', sale: 110 },
text: {
content: 'data marker test',
maxLength: 80,
autoEllipsis: true,
background: {
padding: 5,
style: {
fill: '#289990',
fillOpacity: 0.3,
stroke: '#289990',
lineWidth: 1,
},
},
},
});
chart.render();
const dataMarker = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[7].component;
expect(dataMarker.get('type')).toEqual('dataMarker');
expect(dataMarker.get('x')).toEqual(494);
expect(dataMarker.get('y')).toEqual(70);
// @ts-ignore
expect(dataMarker.getElementById('-annotation-text').attr('text').indexOf('…')).toBeGreaterThan(-1);
// @ts-ignore
expect(dataMarker.getElementById('-annotation-text-bg')).toBeDefined();
});
it('dataRegion', () => {
chart.annotation().dataRegion({
start: { city: '杭州', sale: 100 },
end: { city: '上海', sale: 110 },
text: {
content: 'data region test',
maxLength: 80,
autoEllipsis: true,
background: {
padding: 5,
style: {
fill: '#289990',
fillOpacity: 0.3,
stroke: '#289990',
lineWidth: 1,
radius: 4,
},
},
},
});
chart.render();
const dataRegion = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[8].component;
expect(dataRegion.get('type')).toEqual('dataRegion');
expect(dataRegion.get('points')).toEqual([
{ x: 118, y: 116 },
{ x: 306, y: 438 },
{ x: 494, y: 70 },
]);
// @ts-ignore
expect(dataRegion.getElementById('-annotation-text').attr('text').indexOf('…')).toBeGreaterThan(-1);
// @ts-ignore
expect(dataRegion.getElementById('-annotation-text-bg')).toBeDefined();
});
it('regionFilter', async () => {
chart.line().position('city*sale');
chart.annotation().regionFilter({
start: { city: '广州', sale: 30 },
end: { city: '上海', sale: 110 },
color: '#ff0000',
apply: ['line'],
});
chart.render();
await delay(700);
const regionFilter = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[9].component;
expect(regionFilter.get('type')).toEqual('regionFilter');
expect(regionFilter.get('shapes')).toHaveLength(1);
});
it('text with callback', () => {
// @ts-ignore
chart.getController('annotation').clear(true);
chart.annotation().text({
position: ['50%', '50%'],
content: (filteredData) => `${filteredData.reduce((a, b: any) => a + b.sale, 0)}`,
});
chart.render();
const text = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[0].component;
expect(text).toBeDefined();
// @ts-ignore
expect(text.get('content')).toBe(`${DATA.reduce((a, b) => a + b.sale, 0)}`);
});
afterAll(() => {
chart.destroy();
removeDom(div);
});
});
describe('shape annotation', () => {
const containerDiv = createDiv();
it('/w single shape', () => {
const chart = new Chart({
container: containerDiv,
width: 800,
height: 600,
padding: 24,
autoFit: false,
});
chart.data(DATA);
chart.scale('sale', { nice: true });
chart.animate(false);
chart.interval().position('city*sale');
chart.animate(false);
chart.annotation().shape({
render: (group, view) => {
const bbox = view.viewBBox;
group.addShape('text', {
attrs: {
text: 'Hello World!',
fill: 'red',
x: bbox.x + bbox.width / 2,
y: bbox.y + bbox.height / 2,
},
});
},
});
chart.render();
const component = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[0].component;
expect(component).toBeDefined();
const container = component.get('group') as IGroup;
expect(container.getChildren()).toHaveLength(1);
expect(container.getChildren()[0].get('type')).toBe('text');
expect(container.getChildren()[0].attr('x')).toBe(400);
expect(container.getChildren()[0].attr('y')).toBe(300);
});
it('/w group', () => {
const chart = new Chart({
container: containerDiv,
width: 800,
height: 600,
padding: 24,
autoFit: false,
});
chart.data(DATA);
chart.scale('sale', { nice: true });
chart.animate(false);
chart.interval().position('city*sale');
chart.animate(false);
chart.annotation().shape({
render: (group, view) => {
const bbox = view.viewBBox;
const parent = group.addGroup({
id: 'my-group',
});
parent.addShape('line', {
id: 'my-line1',
attrs: {
x1: bbox.x,
y1: bbox.y + bbox.height / 2,
x2: bbox.maxX,
y2: bbox.y + bbox.height / 2,
stroke: 'blue',
},
});
parent.addShape('line', {
id: 'my-line2',
attrs: {
x1: bbox.x + bbox.width / 2,
y1: bbox.y,
x2: bbox.x + bbox.width / 2,
y2: bbox.maxY,
stroke: 'blue',
},
});
parent.addShape('text', {
id: 'my-text',
attrs: {
text: 'center',
fill: 'red',
textAlign: 'center',
x: bbox.x + bbox.width / 2,
y: bbox.y + bbox.height / 2,
},
});
},
});
chart.render();
const component = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[0].component;
expect(component).toBeDefined();
const container = component.get('group') as IGroup;
expect(container.getChildren()).toHaveLength(1);
expect(container.getChildren()[0].isGroup()).toBeTrue();
const parent = container.getChildren()[0] as IGroup;
expect(parent.getChildren()).toHaveLength(3);
expect(parent.getChildByIndex(0).get('type')).toBe('line');
expect(parent.getChildByIndex(1).get('type')).toBe('line');
expect(parent.getChildByIndex(2).get('type')).toBe('text');
expect(parent.getChildByIndex(2).attr('text')).toBe('center');
});
it('update', async () => {
const chart = new Chart({
container: containerDiv,
width: 800,
height: 600,
padding: 24,
autoFit: false,
});
chart.data(DATA);
chart.scale('sale', { nice: true });
chart.animate(false);
chart.interval().position('city*sale');
chart.animate(false);
chart.annotation().shape({
render: (group, view) => {
const bbox = view.viewBBox;
group.addShape('text', {
id: 'my-test',
attrs: {
text: 'Hello World!',
fill: 'red',
x: bbox.x + bbox.width / 2,
y: bbox.y + bbox.height / 2,
},
});
},
});
chart.render();
await delay(500);
chart.changeSize(600, 400);
const component = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[0].component;
expect(component).toBeDefined();
const container = component.get('group') as IGroup;
expect(container.getChildren()).toHaveLength(1);
expect(container.getChildren()[0].get('type')).toBe('text');
expect(container.getChildren()[0].attr('x')).toBe(300);
expect(container.getChildren()[0].attr('y')).toBe(200);
});
it('helpers', () => {
const chart = new Chart({
container: containerDiv,
width: 800,
height: 600,
padding: 24,
autoFit: false,
});
chart.data(DATA);
chart.scale('sale', { nice: true });
chart.animate(false);
chart.interval().position('city*sale');
chart.animate(false);
chart.annotation().shape({
render: (group, view, helpers) => {
const parent = group.addGroup();
const points = DATA.map((datum) => helpers.parsePosition(datum));
points.forEach((point, idx) => {
if (idx < points.length - 1) {
parent.addShape('line', {
id: `my-line${idx}`,
attrs: {
x1: point.x,
y1: point.y,
x2: points[idx + 1].x,
y2: points[idx + 1].y,
stroke: point.y < points[idx + 1].y ? 'red' : 'green',
},
});
}
});
},
});
chart.render();
const component = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[0].component;
expect(component).toBeDefined();
const container = component.get('group') as IGroup;
expect(container.getChildren()).toHaveLength(1);
const parent = container.getChildren()[0] as IGroup;
expect(parent.getChildren()).toHaveLength(DATA.length - 1);
});
afterAll(() => {
removeDom(containerDiv);
});
});
describe('html annotation', () => {
const containerDiv = createDiv();
it('html string', () => {
const chart = new Chart({
container: containerDiv,
width: 800,
height: 600,
padding: 24,
autoFit: false,
});
chart.data(DATA);
chart.scale('sale', { nice: true });
chart.animate(false);
chart.interval().position('city*sale');
chart.animate(false);
const htmlStr = '<span style="color:red">html string</span>';
chart.annotation().html({
html: htmlStr,
position: ['50%', '50%'],
});
chart.render();
const component = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[0].component;
expect(component).toBeDefined();
const container = component.getContainer() as HTMLElement;
expect(isElement(container)).toBeTrue();
expect(container.innerHTML).toEqual(htmlStr);
expect(container.style.position).toBe('absolute');
expect(container.style.left).toBe('400px');
expect(container.style.top).toEqual('300px');
});
it('html element', () => {
const chart = new Chart({
container: containerDiv,
width: 800,
height: 600,
padding: 24,
autoFit: false,
});
chart.data(DATA);
chart.scale('sale', { nice: true });
chart.animate(false);
chart.interval().position('city*sale');
chart.animate(false);
const htmlElem = document.createElement('SPAN');
htmlElem.appendChild(document.createTextNode('html string'));
chart.annotation().html({
html: htmlElem,
position: ['50%', '50%'],
});
chart.render();
const component = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[0].component;
expect(component).toBeDefined();
const container = component.getContainer() as HTMLElement;
expect(isElement(container)).toBeTrue();
expect(container.innerHTML).toEqual(`<span>html string</span>`);
});
it('html callback', () => {
const chart = new Chart({
container: containerDiv,
width: 800,
height: 600,
padding: 24,
autoFit: false,
});
chart.data(DATA);
chart.scale('sale', { nice: true });
chart.animate(false);
chart.interval().position('city*sale');
chart.animate(false);
chart.annotation().html({
html: (container) => {
const span = document.createElement('SPAN');
span.appendChild(document.createTextNode('html string'));
container.appendChild(span);
},
position: ['50%', '50%'],
});
chart.render();
const component = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[0].component;
expect(component).toBeDefined();
const container = component.getContainer() as HTMLElement;
expect(isElement(container)).toBeTrue();
expect(container.innerHTML).toEqual(`<span>html string</span>`);
});
it('update', async () => {
const chart = new Chart({
container: containerDiv,
width: 800,
height: 600,
padding: 24,
autoFit: false,
});
chart.data(DATA);
chart.scale('sale', { nice: true });
chart.animate(false);
chart.interval().position('city*sale');
chart.animate(false);
const htmlStr = '<span style="color:red">html string</span>';
chart.annotation().html({
html: htmlStr,
position: ['50%', '50%'],
});
chart.render();
await delay(500);
chart.changeSize(600, 400);
const component = chart.getComponents().filter((co) => co.type === COMPONENT_TYPE.ANNOTATION)[0].component;
expect(component).toBeDefined();
const container = component.getContainer() as HTMLElement;
expect(isElement(container)).toBeTrue();
expect(container.innerHTML).toEqual(htmlStr);
expect(container.style.position).toBe('absolute');
expect(container.style.left).toBe('300px');
expect(container.style.top).toEqual('200px');
});
afterAll(() => {
removeDom(containerDiv);
});
}); | the_stack |
import {
CLASS_TYPE
} from './const';
import { DSL,Layer } from './types';
import { uniqueId } from './utils';
const handleSpan = (data:Layer[]) => {
let positionList = [];
let noPostionList = [];
data.forEach((item) => {
if (item.isPosition) {
positionList.push(item);
} else {
noPostionList.push(item);
}
});
data = noPostionList;
//让宽度最大的元素放在最前面
data = data.sort((a, b) => b.structure.width - a.structure.width);
//处理进行分列
//同列的元素外面加一个Span容器
// 结构调整data
//children本身全部在一行的不需要加Span容器
let assignSpanList:DSL[] = [];
for (let i = 0; i < data.length; i++) {
let flag = true;
for (let j = 0; j < assignSpanList.length; j++) {
//属于哪个容器就放到哪个容器中
for (let n = 0; n < assignSpanList[j].length; n++) {
if (flag && ((assignSpanList[j][n].structure.x <= data[i].structure.x && data[i].structure.x < (+assignSpanList[j][n].structure.x + assignSpanList[j][n].structure.width)) ||
(+assignSpanList[j][n].structure.x < +data[i].structure.x + data[i].structure.width && +data[i].structure.x + data[i].structure.width <= (+assignSpanList[j][n].structure.x + assignSpanList[j][n].structure.width)))) {
assignSpanList[j].push(data[i]);
flag = false;
}
}
}
//都不属于则新建容器,放入其中
if (flag) {
assignSpanList.push([data[i]]);
}
}
//children本身全部在一列的不需要加Span容器
if (data.length == assignSpanList[0].length) {
assignSpanList = assignSpanList[0].map(item => [item]);
}
/**
* 分列完成后,给属于同一列的加容器
* 同时给容器赋值x,y,width,height
* 获取结构调整后的data
*/
let spanList: Layer[] = [];
for (let i = 0; i < assignSpanList.length; i++) {
if (assignSpanList[i].length == 1) {
spanList.push(assignSpanList[i][0]);
} else {
let currSpan = [],
currDivX = 0,
currDivY = 0,
currMaxX = 0,
currMaxY = 0,
zIndex = 0;
currSpan = assignSpanList[i].sort((a, b) => a.structure.y - b.structure.y);
// currSpan = assignSpanList[i];
zIndex = currSpan[0].structure.zIndex;
for (let j = 0; j < currSpan.length; j++) {
zIndex = currSpan[j].structure.zIndex > zIndex ? currSpan[j].structure.zIndex : zIndex;
if (j == 0) {
currDivX = currSpan[j].structure.x;
currDivY = currSpan[j].structure.y;
currMaxX = currSpan[j].structure.x + currSpan[j].structure.width;
currMaxY = currSpan[j].structure.y + currSpan[j].structure.height;
} else {
if (currDivX > currSpan[j].structure.x) {
currDivX = currSpan[j].structure.x
}
if (currDivY > currSpan[j].structure.y) {
currDivY = currSpan[j].structure.y
}
if (currMaxX < currSpan[j].structure.x + currSpan[j].structure.width) {
currMaxX = currSpan[j].structure.x + currSpan[j].structure.width;
}
if (currMaxY < currSpan[j].structure.y + currSpan[j].structure.height) {
currMaxY = currSpan[j].structure.y + currSpan[j].structure.height;
}
}
}
spanList.push({
id: uniqueId(),
name: 'Span1',
class: 'Span',
type: 'Container',
structure: {
zIndex,
x: currDivX,
y: currDivY,
width: currMaxX - currDivX,
height: currMaxY - currDivY,
},
children: currSpan,
style: {}
});
}
}
data = spanList.sort((a, b) => a.structure.x - b.structure.x);
data = [...data, ...positionList];
return data;
}
//分行处理
//判断是否为同一行
//同一行给予DIV包裹并且将该行元素作为DIV的子元素
function isSame(data:Layer[]) {
let flag = true;
if (Array.isArray(data) && data.length > 2) {
let firstItemWidth = data[0].structure.width;
let firstItemHeight = data[0].structure.height;
data.forEach((item) => {
if (Math.abs(firstItemWidth - item.structure.width) > 1 || Math.abs(firstItemHeight - item.structure.height) > 1) {
flag = false;
}
})
}
return flag;
}
//判断属于左边的图片
const isLeftImg = (layer:Layer, parent?:Layer) => {
//必须为图片类型
if (layer.type !== 'Image') {
return false;
}
//距离画板左边的距离<100
if (layer.structure.x > 100) {
return false;
}
//距离画板左边的距离<100
if (layer.structure.width < 40) {
return false;
}
//父元素必须存在
if (!parent) {
return false;
}
//容器的宽度>750*0.7
if (parent.structure.width < 750 * 0.7) {
return false;
}
for (let i = 1; i < parent.children.length; i++) {
const item = parent.children[i];
if (item.structure.x < layer.structure.x + layer.structure.width) {
return false;
}
}
return true;
}
const isLeftImgRightInfo = (item:Layer) => {
if (Array.isArray(item.children) && item.children.length > 3 && isLeftImg(item.children[0], item)) {
let itemChildren: Layer[] = [...item.children];
let firstChildren = itemChildren.shift();
let currSpan = itemChildren;
let flag = false;
for (let j = 0; j < currSpan.length; j++) {
let item = currSpan[j];
for (let i = j; i < currSpan.length; i++) {
const itemI = currSpan[i];
if (
(
(itemI.structure.x + itemI.structure.width > item.structure.x && item.structure.x >= itemI.structure.x) ||
(item.structure.x + item.structure.width > itemI.structure.x && itemI.structure.x >= item.structure.x)
) && (
item.structure.y + item.structure.height <= itemI.structure.y ||
itemI.structure.y + itemI.structure.height <= item.structure.y
)
) {
flag = true;
}
}
}
if (flag) {
let currDivX, currDivY, currMaxX, currMaxY;
let zIndex = currSpan[0].structure.zIndex;
for (let j = 0; j < currSpan.length; j++) {
zIndex = currSpan[j].structure.zIndex > zIndex ? currSpan[j].structure.zIndex : zIndex;
if (j == 0) {
currDivX = currSpan[j].structure.x;
currDivY = currSpan[j].structure.y;
currMaxX = currSpan[j].structure.x + currSpan[j].structure.width;
currMaxY = currSpan[j].structure.y + currSpan[j].structure.height;
} else {
if (currDivX > currSpan[j].structure.x) {
currDivX = currSpan[j].structure.x
}
if (currDivY > currSpan[j].structure.y) {
currDivY = currSpan[j].structure.y
}
if (currMaxX < currSpan[j].structure.x + currSpan[j].structure.width) {
currMaxX = currSpan[j].structure.x + currSpan[j].structure.width;
}
if (currMaxY < currSpan[j].structure.y + currSpan[j].structure.height) {
currMaxY = currSpan[j].structure.y + currSpan[j].structure.height;
}
}
}
item.name = 'LeftImgRightInfo';
firstChildren.class_name = 'left';
firstChildren.class_type = CLASS_TYPE.RELY_ON_PARENT;
item.children = [firstChildren, {
id: uniqueId(),
name: 'Span2',
class: 'Span',
type: 'Container',
structure: {
zIndex,
x: currDivX,
y: currDivY,
width: currMaxX - currDivX,
height: currMaxY - currDivY,
},
children: currSpan,
style: {},
class_name: 'right',
class_type: CLASS_TYPE.RELY_ON_PARENT,
}];
} else {
item.children = handleSpan(item.children);
}
return item;
} else {
item.children = handleSpan(item.children);
}
return item;
}
//上下合并
const handleMerge = (data:Layer[]) => {
let leftRItem:Layer = {};
let flag = false;
for (let i = 0; i < data.length; i++) {
if (flag) {
let secondChild = leftRItem.children[1];
if (data[i].structure.x > secondChild.structure.x - 2) {
secondChild.children.push({ ...data[i] });
secondChild.structure.height = data[i].structure.y + data[i].structure.height - secondChild.structure.y;
leftRItem.structure.height = data[i].structure.y + data[i].structure.height - leftRItem.structure.y;
if (secondChild.structure.width + secondChild.structure.x < data[i].structure.x + data[i].structure.width) {
secondChild.structure.width = data[i].structure.x + data[i].structure.width - secondChild.structure.x;
}
leftRItem.structure.width = secondChild.structure.width + secondChild.structure.x - leftRItem.structure.x;
data[i].delete = true;
} else {
flag = false;
}
}
if (data[i].name == 'LeftImgRightInfo') {
flag = true;
leftRItem = data[i];
}
}
return data.filter(item => !item.delete);
}
const handleRow = (data:Layer[], parent?:Layer) => {
if (parent && parent.textContainer) {
return data;
}
if (isSame(data)) {
//递归处理children
for (let i = 0; i < data.length; i++) {
if (Array.isArray(data[i].children) && data[i].children.length > 0) {
data[i].children = handleRow(data[i].children, data[i]);
}
}
return data;
}
//让高度最大的元素放在最前面
data = data.sort((a, b) => b.structure.height - a.structure.height);
//处理进行分行
//同行的元素外面加一个Row容器
// 结构调整data
//children本身全部在一行的不需要加Row容器
//let assignRowList = [];
// let rowArr = [];
// for (let i = 0; i < data.length; i++) {
// let flag = true;
// if (rowArr.length > 0) {
// flag = false;
// for (let j = 0; j < rowArr.length; j++) {
// const item = rowArr[j];
// if (data[i].structure.y + data[i].structure.height > item.structure.y && item.structure.y + item.structure.height > data[i].structure.y) {
// flag = true;
// }
// }
// if (!flag) {
// assignRowList.push(rowArr);
// rowArr = [];
// }
// }
// rowArr.push(data[i]);
// }
// if (rowArr.length > 0) {
// if (rowArr.length == data.length) {
// //等待华哥算法更新后 过滤掉其中已经处理的部分
// if (parent && parent.type != '__li') {
// data = handleSpan(data);
// }
// for (let i = 0; i < data.length; i++) {
// if (Array.isArray(data[i].children) && data[i].children.length > 0) {
// data[i].children = handleRow(data[i].children, data[i]);
// }
// }
// return data;
// } else {
// assignRowList.push(rowArr);
// }
// }
let assignRowList = [];
for (let i = 0; i < data.length; i++) {
let flag = true;
for (let j = 0; j < assignRowList.length; j++) {
//属于哪个容器就放到哪个容器中
for (let n = 0; n < assignRowList[j].length; n++) {
if (flag && ((assignRowList[j][n].structure.y <= data[i].structure.y && data[i].structure.y < (+assignRowList[j][n].structure.y + assignRowList[j][n].structure.height)) ||
(+assignRowList[j][n].structure.y < +data[i].structure.y + data[i].structure.height && +data[i].structure.y + data[i].structure.height <= (+assignRowList[j][n].structure.y + assignRowList[j][n].structure.height)))) {
assignRowList[j].push(data[i]);
flag = false;
}
}
}
//都不属于则新建容器,放入其中
if (flag) {
assignRowList.push([data[i]]);
}
}
/**
* 分行完成后,给属于同一行的加容器
* 同时给容器赋值x,y,width,height
* 获取结构调整后的data
*/
let rowList = [];
//children本身全部在一行的不需要加Row容器
if (assignRowList.length && data.length == assignRowList[0].length) {
if (parent && parent.sign != '__li') {
rowList = handleSpan(assignRowList[0]);
} else {
rowList = assignRowList[0];
}
if (parent) {
parent.class = 'Row';
}
} else {
for (let i = 0; i < assignRowList.length; i++) {
if (assignRowList[i].length == 1) {
//分行之后进行分列
if (assignRowList[i][0].children && assignRowList[i].name == 'Row') {
assignRowList[i][0].children = handleSpan(assignRowList[i][0].children);
}
rowList.push(assignRowList[i][0]);
} else {
let currRow = [],
currDivX = 0,
currDivY = 0,
currMaxX = 0,
currMaxY = 0,
zIndex = 0;
currRow = assignRowList[i].sort((a, b) => a.structure.x - b.structure.x);
zIndex = currRow[0].structure.zIndex;
for (let j = 0; j < currRow.length; j++) {
zIndex = currRow[j].structure.zIndex > zIndex ? currRow[j].structure.zIndex : zIndex;
if (j == 0) {
currDivX = currRow[j].structure.x;
currDivY = currRow[j].structure.y;
currMaxX = currRow[j].structure.x + currRow[j].structure.width;
currMaxY = currRow[j].structure.y + currRow[j].structure.height;
} else {
if (currDivX > currRow[j].structure.x) {
currDivX = currRow[j].structure.x
}
if (currDivY > currRow[j].structure.y) {
currDivY = currRow[j].structure.y
}
if (currMaxX < currRow[j].structure.x + currRow[j].structure.width) {
currMaxX = currRow[j].structure.x + currRow[j].structure.width;
}
if (currMaxY < currRow[j].structure.y + currRow[j].structure.height) {
currMaxY = currRow[j].structure.y + currRow[j].structure.height;
}
}
}
//分行之后进行分列表
let currWidth = currMaxX - currDivX;
let currX = currDivX;
//特征分列
let item = isLeftImgRightInfo({
id: uniqueId(),
class: 'Row',
type: 'Container',
name: 'Row',
structure: {
zIndex,
x: currX,
y: currDivY,
width: currWidth,
height: currMaxY - currDivY,
},
children: currRow,
style: {}
});
// if (parent && parent.structure.width) {
// currWidth = parent.structure.width;
// currX = parent.structure.x;
// // 处理border的影响
// if (parent.border && parent.border.structure.width) {
// currWidth = currWidth - parent.border.structure.width * 2;
// currX = currX + parent.border.structure.width;
// }
// }
rowList.push(item);
}
}
}
// data = [...data,...positionList];
data = rowList.sort((a, b) => a.structure.y - b.structure.y);
data = handleMerge(data);
//递归处理children
for (let i = 0; i < data.length; i++) {
if (Array.isArray(data[i].children) && data[i].children.length > 0) {
data[i].children = handleRow(data[i].children, data[i]);
}
}
return data;
}
export default handleRow; | the_stack |
import { Injectable } from '@angular/core';
import { AbstractControl, FormGroup } from '@angular/forms';
import {
DYNAMIC_FORM_CONTROL_TYPE_ARRAY,
DYNAMIC_FORM_CONTROL_TYPE_CHECKBOX_GROUP,
DYNAMIC_FORM_CONTROL_TYPE_GROUP,
DYNAMIC_FORM_CONTROL_TYPE_INPUT,
DYNAMIC_FORM_CONTROL_TYPE_RADIO_GROUP,
DynamicFormArrayModel,
DynamicFormComponentService,
DynamicFormControlEvent,
DynamicFormControlModel,
DynamicFormGroupModel,
DynamicFormService,
DynamicFormValidationService,
DynamicPathable,
parseReviver,
} from '@ng-dynamic-forms/core';
import { isObject, isString, mergeWith } from 'lodash';
import { hasValue, isEmpty, isNotEmpty, isNotNull, isNotUndefined, isNull } from '../../empty.util';
import { DynamicQualdropModel } from './ds-dynamic-form-ui/models/ds-dynamic-qualdrop.model';
import { SubmissionFormsModel } from '../../../core/config/models/config-submission-forms.model';
import { DYNAMIC_FORM_CONTROL_TYPE_TAG } from './ds-dynamic-form-ui/models/tag/dynamic-tag.model';
import { RowParser } from './parsers/row-parser';
import { DynamicRelationGroupModel } from './ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.model';
import { DynamicRowArrayModel } from './ds-dynamic-form-ui/models/ds-dynamic-row-array-model';
import { DsDynamicInputModel } from './ds-dynamic-form-ui/models/ds-dynamic-input.model';
import { FormFieldMetadataValueObject } from './models/form-field-metadata-value.model';
import { dateToString, isNgbDateStruct } from '../../date.util';
import { DYNAMIC_FORM_CONTROL_TYPE_RELATION_GROUP } from './ds-dynamic-form-ui/ds-dynamic-form-constants';
import { CONCAT_GROUP_SUFFIX, DynamicConcatModel } from './ds-dynamic-form-ui/models/ds-dynamic-concat.model';
import { VIRTUAL_METADATA_PREFIX } from '../../../core/shared/metadata.models';
@Injectable()
export class FormBuilderService extends DynamicFormService {
constructor(
componentService: DynamicFormComponentService,
validationService: DynamicFormValidationService,
protected rowParser: RowParser
) {
super(componentService, validationService);
}
findById(id: string, groupModel: DynamicFormControlModel[], arrayIndex = null): DynamicFormControlModel | null {
let result = null;
const findByIdFn = (findId: string, findGroupModel: DynamicFormControlModel[], findArrayIndex): void => {
for (const controlModel of findGroupModel) {
if (controlModel.id === findId) {
if (this.isArrayGroup(controlModel) && isNotNull(findArrayIndex)) {
result = (controlModel as DynamicFormArrayModel).get(findArrayIndex);
} else {
result = controlModel;
}
break;
}
if (this.isConcatGroup(controlModel)) {
if (controlModel.id.match(new RegExp(findId + CONCAT_GROUP_SUFFIX + `_\\d+$`))) {
result = (controlModel as DynamicConcatModel).group[0];
break;
}
}
if (this.isGroup(controlModel)) {
findByIdFn(findId, (controlModel as DynamicFormGroupModel).group, findArrayIndex);
}
if (this.isArrayGroup(controlModel)
&& (isNull(findArrayIndex) || (controlModel as DynamicFormArrayModel).size > (findArrayIndex))) {
const index = (isNull(findArrayIndex)) ? 0 : findArrayIndex;
findByIdFn(findId, (controlModel as DynamicFormArrayModel).get(index).group, index);
}
}
};
findByIdFn(id, groupModel, arrayIndex);
return result;
}
clearAllModelsValue(groupModel: DynamicFormControlModel[]): void {
const iterateControlModels = (findGroupModel: DynamicFormControlModel[]): void => {
for (const controlModel of findGroupModel) {
if (this.isGroup(controlModel)) {
iterateControlModels((controlModel as DynamicFormGroupModel).group);
continue;
}
if (this.isArrayGroup(controlModel)) {
iterateControlModels((controlModel as DynamicFormArrayModel).groupFactory());
continue;
}
if (controlModel.hasOwnProperty('valueChanges')) {
(controlModel as any).value = undefined;
}
}
};
iterateControlModels(groupModel);
}
getValueFromModel(groupModel: DynamicFormControlModel[]): void {
let result = Object.create({});
const customizer = (objValue, srcValue) => {
if (Array.isArray(objValue)) {
return objValue.concat(srcValue);
}
};
const normalizeValue = (controlModel, controlValue, controlModelIndex) => {
const controlLanguage = (controlModel as DsDynamicInputModel).hasLanguages ? (controlModel as DsDynamicInputModel).language : null;
if (controlModel?.metadataValue?.authority?.includes(VIRTUAL_METADATA_PREFIX)) {
return controlModel.metadataValue;
}
if (isString(controlValue)) {
return new FormFieldMetadataValueObject(controlValue, controlLanguage, null, null, controlModelIndex);
} else if (isNgbDateStruct(controlValue)) {
return new FormFieldMetadataValueObject(dateToString(controlValue));
} else if (isObject(controlValue)) {
const authority = (controlValue as any).authority || (controlValue as any).id || null;
const place = controlModelIndex || (controlValue as any).place;
if (isNgbDateStruct(controlValue)) {
return new FormFieldMetadataValueObject(controlValue, controlLanguage, authority, controlValue as any, place);
} else {
return new FormFieldMetadataValueObject((controlValue as any).value, controlLanguage, authority, (controlValue as any).display, place, (controlValue as any).confidence);
}
}
};
const iterateControlModels = (findGroupModel: DynamicFormControlModel[], controlModelIndex: number = 0): void => {
let iterateResult = Object.create({});
// Iterate over all group's controls
for (const controlModel of findGroupModel) {
if (this.isRowGroup(controlModel) && !this.isCustomOrListGroup(controlModel)) {
iterateResult = mergeWith(iterateResult, iterateControlModels((controlModel as DynamicFormGroupModel).group), customizer);
continue;
}
if (this.isGroup(controlModel) && !this.isCustomOrListGroup(controlModel)) {
iterateResult[controlModel.name] = iterateControlModels((controlModel as DynamicFormGroupModel).group);
continue;
}
if (this.isRowArrayGroup(controlModel)) {
for (const arrayItemModel of (controlModel as DynamicRowArrayModel).groups) {
iterateResult = mergeWith(iterateResult, iterateControlModels(arrayItemModel.group, arrayItemModel.index), customizer);
}
continue;
}
if (this.isArrayGroup(controlModel)) {
iterateResult[controlModel.name] = [];
for (const arrayItemModel of (controlModel as DynamicFormArrayModel).groups) {
iterateResult[controlModel.name].push(iterateControlModels(arrayItemModel.group, arrayItemModel.index));
}
continue;
}
let controlId;
// Get the field's name
if (this.isQualdropGroup(controlModel)) {
// If is instance of DynamicQualdropModel take the qualdrop id as field's name
controlId = (controlModel as DynamicQualdropModel).qualdropId;
} else {
controlId = controlModel.name;
}
if (this.isRelationGroup(controlModel)) {
const values = (controlModel as DynamicRelationGroupModel).getGroupValue();
values.forEach((groupValue, groupIndex) => {
const newGroupValue = Object.create({});
Object.keys(groupValue)
.forEach((key) => {
const normValue = normalizeValue(controlModel, groupValue[key], groupIndex);
if (isNotEmpty(normValue) && normValue.hasValue()) {
if (iterateResult.hasOwnProperty(key)) {
iterateResult[key].push(normValue);
} else {
iterateResult[key] = [normValue];
}
}
});
});
} else if (isNotUndefined((controlModel as any).value) && isNotEmpty((controlModel as any).value)) {
const controlArrayValue = [];
// Normalize control value as an array of FormFieldMetadataValueObject
const values = Array.isArray((controlModel as any).value) ? (controlModel as any).value : [(controlModel as any).value];
values.forEach((controlValue) => {
controlArrayValue.push(normalizeValue(controlModel, controlValue, controlModelIndex));
});
if (controlId && iterateResult.hasOwnProperty(controlId) && isNotNull(iterateResult[controlId])) {
iterateResult[controlId] = iterateResult[controlId].concat(controlArrayValue);
} else {
iterateResult[controlId] = isNotEmpty(controlArrayValue) ? controlArrayValue : null;
}
}
}
return iterateResult;
};
result = iterateControlModels(groupModel);
return result;
}
modelFromConfiguration(submissionId: string, json: string | SubmissionFormsModel, scopeUUID: string, sectionData: any = {}, submissionScope?: string, readOnly = false): DynamicFormControlModel[] | never {
let rows: DynamicFormControlModel[] = [];
const rawData = typeof json === 'string' ? JSON.parse(json, parseReviver) : json;
if (rawData.rows && !isEmpty(rawData.rows)) {
rawData.rows.forEach((currentRow) => {
const rowParsed = this.rowParser.parse(submissionId, currentRow, scopeUUID, sectionData, submissionScope, readOnly);
if (isNotNull(rowParsed)) {
if (Array.isArray(rowParsed)) {
rows = rows.concat(rowParsed);
} else {
rows.push(rowParsed);
}
}
});
}
return rows;
}
isModelInCustomGroup(model: DynamicFormControlModel): boolean {
return this.isCustomGroup((model as any).parent);
}
hasArrayGroupValue(model: DynamicFormControlModel): boolean {
return model && (this.isListGroup(model) || model.type === DYNAMIC_FORM_CONTROL_TYPE_TAG);
}
hasMappedGroupValue(model: DynamicFormControlModel): boolean {
return (this.isQualdropGroup((model as any).parent)
|| this.isRelationGroup((model as any).parent));
}
isGroup(model: DynamicFormControlModel): boolean {
return model && (model.type === DYNAMIC_FORM_CONTROL_TYPE_GROUP || model.type === DYNAMIC_FORM_CONTROL_TYPE_CHECKBOX_GROUP);
}
isQualdropGroup(model: DynamicFormControlModel): boolean {
return (model && model.type === DYNAMIC_FORM_CONTROL_TYPE_GROUP && hasValue((model as any).qualdropId));
}
isCustomGroup(model: DynamicFormControlModel): boolean {
return model && ((model as any).type === DYNAMIC_FORM_CONTROL_TYPE_GROUP && (model as any).isCustomGroup === true);
}
isConcatGroup(model: DynamicFormControlModel): boolean {
return this.isCustomGroup(model) && (model.id.indexOf(CONCAT_GROUP_SUFFIX) !== -1);
}
isRowGroup(model: DynamicFormControlModel): boolean {
return model && ((model as any).type === DYNAMIC_FORM_CONTROL_TYPE_GROUP && (model as any).isRowGroup === true);
}
isCustomOrListGroup(model: DynamicFormControlModel): boolean {
return model &&
(this.isCustomGroup(model)
|| this.isListGroup(model));
}
isListGroup(model: DynamicFormControlModel): boolean {
return model &&
((model.type === DYNAMIC_FORM_CONTROL_TYPE_CHECKBOX_GROUP && (model as any).isListGroup === true)
|| (model.type === DYNAMIC_FORM_CONTROL_TYPE_RADIO_GROUP && (model as any).isListGroup === true));
}
isRelationGroup(model: DynamicFormControlModel): boolean {
return model && model.type === DYNAMIC_FORM_CONTROL_TYPE_RELATION_GROUP;
}
isRowArrayGroup(model: DynamicFormControlModel): boolean {
return model.type === DYNAMIC_FORM_CONTROL_TYPE_ARRAY && (model as any).isRowArray === true;
}
isArrayGroup(model: DynamicFormControlModel): boolean {
return model.type === DYNAMIC_FORM_CONTROL_TYPE_ARRAY;
}
isInputModel(model: DynamicFormControlModel): boolean {
return model.type === DYNAMIC_FORM_CONTROL_TYPE_INPUT;
}
getFormControlById(id: string, formGroup: FormGroup, groupModel: DynamicFormControlModel[], index = 0): AbstractControl {
const fieldModel = this.findById(id, groupModel, index);
return isNotEmpty(fieldModel) ? formGroup.get(this.getPath(fieldModel)) : null;
}
/**
* Note (discovered while debugging) this is not the ID as used in the form,
* but the first part of the path needed in a patch operation:
* e.g. add foo/0 -> the id is 'foo'
*/
getId(model: DynamicPathable): string {
let tempModel: DynamicFormControlModel;
if (this.isArrayGroup(model as DynamicFormControlModel)) {
return model.index.toString();
} else if (this.isModelInCustomGroup(model as DynamicFormControlModel)) {
tempModel = (model as any).parent;
} else {
tempModel = (model as any);
}
return (tempModel.id !== tempModel.name) ? tempModel.name : tempModel.id;
}
/**
* Calculate the metadata list related to the event.
* @param event
*/
getMetadataIdsFromEvent(event: DynamicFormControlEvent): string[] {
let model = event.model;
while (model.parent) {
model = model.parent as any;
}
const iterateControlModels = (findGroupModel: DynamicFormControlModel[], controlModelIndex: number = 0): string[] => {
let iterateResult = Object.create({});
// Iterate over all group's controls
for (const controlModel of findGroupModel) {
if (this.isRowGroup(controlModel) && !this.isCustomOrListGroup(controlModel)) {
iterateResult = mergeWith(iterateResult, iterateControlModels((controlModel as DynamicFormGroupModel).group));
continue;
}
if (this.isGroup(controlModel) && !this.isCustomOrListGroup(controlModel)) {
iterateResult[controlModel.name] = iterateControlModels((controlModel as DynamicFormGroupModel).group);
continue;
}
if (this.isRowArrayGroup(controlModel)) {
for (const arrayItemModel of (controlModel as DynamicRowArrayModel).groups) {
iterateResult = mergeWith(iterateResult, iterateControlModels(arrayItemModel.group, arrayItemModel.index));
}
continue;
}
if (this.isArrayGroup(controlModel)) {
iterateResult[controlModel.name] = [];
for (const arrayItemModel of (controlModel as DynamicFormArrayModel).groups) {
iterateResult[controlModel.name].push(iterateControlModels(arrayItemModel.group, arrayItemModel.index));
}
continue;
}
let controlId;
// Get the field's name
if (this.isQualdropGroup(controlModel)) {
// If is instance of DynamicQualdropModel take the qualdrop id as field's name
controlId = (controlModel as DynamicQualdropModel).qualdropId;
} else {
controlId = controlModel.name;
}
if (this.isRelationGroup(controlModel)) {
const values = (controlModel as DynamicRelationGroupModel).getGroupValue();
values.forEach((groupValue, groupIndex) => {
Object.keys(groupValue).forEach((key) => {
iterateResult[key] = true;
});
});
} else {
iterateResult[controlId] = true;
}
}
return iterateResult;
};
const result = iterateControlModels([model]);
return Object.keys(result);
}
} | the_stack |
module android.widget {
import Canvas = android.graphics.Canvas;
import Paint = android.graphics.Paint;
import PixelFormat = android.graphics.PixelFormat;
import Rect = android.graphics.Rect;
import Drawable = android.graphics.drawable.Drawable;
import MathUtils = android.util.MathUtils;
import SparseBooleanArray = android.util.SparseBooleanArray;
import FocusFinder = android.view.FocusFinder;
import KeyEvent = android.view.KeyEvent;
import SoundEffectConstants = android.view.SoundEffectConstants;
import View = android.view.View;
import ViewGroup = android.view.ViewGroup;
import ViewParent = android.view.ViewParent;
import ViewRootImpl = android.view.ViewRootImpl;
import Trace = android.os.Trace;
import ArrayList = java.util.ArrayList;
import Integer = java.lang.Integer;
import System = java.lang.System;
import Runnable = java.lang.Runnable;
import AbsListView = android.widget.AbsListView;
import Adapter = android.widget.Adapter;
import AdapterView = android.widget.AdapterView;
import Checkable = android.widget.Checkable;
import HeaderViewListAdapter = android.widget.HeaderViewListAdapter;
import ListAdapter = android.widget.ListAdapter;
import WrapperListAdapter = android.widget.WrapperListAdapter;
import AttrBinder = androidui.attr.AttrBinder;
/**
* A view that shows items in a vertically scrolling list. The items
* come from the {@link ListAdapter} associated with this view.
*
* <p>See the <a href="{@docRoot}guide/topics/ui/layout/listview.html">List View</a>
* guide.</p>
*
* @attr ref android.R.styleable#ListView_entries
* @attr ref android.R.styleable#ListView_divider
* @attr ref android.R.styleable#ListView_dividerHeight
* @attr ref android.R.styleable#ListView_headerDividersEnabled
* @attr ref android.R.styleable#ListView_footerDividersEnabled
*/
export class ListView extends AbsListView {
/**
* Used to indicate a no preference for a position type.
*/
static NO_POSITION:number = -1;
/**
* When arrow scrolling, ListView will never scroll more than this factor
* times the height of the list.
*/
private static MAX_SCROLL_FACTOR:number = 0.33;
/**
* When arrow scrolling, need a certain amount of pixels to preview next
* items. This is usually the fading edge, but if that is small enough,
* we want to make sure we preview at least this many pixels.
*/
private static MIN_SCROLL_PREVIEW_PIXELS:number = 2;
private mHeaderViewInfos:ArrayList<ListView.FixedViewInfo> = new ArrayList<ListView.FixedViewInfo>();
private mFooterViewInfos:ArrayList<ListView.FixedViewInfo> = new ArrayList<ListView.FixedViewInfo>();
mDivider:Drawable;
mDividerHeight:number = 0;
mOverScrollHeader:Drawable;
mOverScrollFooter:Drawable;
private mIsCacheColorOpaque:boolean = false;
private mDividerIsOpaque:boolean = false;
private mHeaderDividersEnabled:boolean = true;
private mFooterDividersEnabled:boolean = true;
private mAreAllItemsSelectable:boolean = true;
private mItemsCanFocus:boolean = false;
// used for temporary calculations.
private mTempRect:Rect = new Rect();
private mDividerPaint:Paint;
// the single allocated result per list view; kinda cheesey but avoids
// allocating these thingies too often.
private mArrowScrollFocusResult:ListView.ArrowScrollFocusResult = new ListView.ArrowScrollFocusResult();
// Keeps focused children visible through resizes
private mFocusSelector:ListView.FocusSelector;
constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle=android.R.attr.listViewStyle) {
super(context, bindElement, defStyle);
let a = context.obtainStyledAttributes(bindElement, defStyle);
// let entries = a.getTextArray('entries');
// if (entries != null) {
// this.setAdapter(new ArrayAdapter<string>(context, R.layout.simple_list_item_1, entries));
// }
const d: Drawable = a.getDrawable('divider');
if (d != null) {
// If a divider is specified use its intrinsic height for divider height
this.setDivider(d);
}
const osHeader: Drawable = a.getDrawable('overScrollHeader');
if (osHeader != null) {
this.setOverscrollHeader(osHeader);
}
const osFooter: Drawable = a.getDrawable('overScrollFooter');
if (osFooter != null) {
this.setOverscrollFooter(osFooter);
}
// Use the height specified, zero being the default
const dividerHeight: number = a.getDimensionPixelSize('dividerHeight', 0);
if (dividerHeight != 0) {
this.setDividerHeight(dividerHeight);
}
this.mHeaderDividersEnabled = a.getBoolean('headerDividersEnabled', true);
this.mFooterDividersEnabled = a.getBoolean('footerDividersEnabled', true);
a.recycle();
}
protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap {
return super.createClassAttrBinder().set('divider', {
setter(v:ListView, value:any, attrBinder:AttrBinder) {
let divider = attrBinder.parseDrawable(value);
if(divider) v.setDivider(divider);
}, getter(v:ListView) {
return v.mDivider;
}
}).set('overScrollHeader', {
setter(v:ListView, value:any, attrBinder:AttrBinder) {
let header = attrBinder.parseDrawable(value);
if(header) v.setOverscrollHeader(header);
}, getter(v:ListView) {
return v.getOverscrollHeader();
}
}).set('overScrollFooter', {
setter(v:ListView, value:any, attrBinder:AttrBinder) {
let footer = attrBinder.parseDrawable(value);
if(footer) v.setOverscrollFooter(footer);
}, getter(v:ListView) {
return v.getOverscrollFooter();
}
}).set('dividerHeight', {
setter(v:ListView, value:any, attrBinder:AttrBinder) {
v.setDividerHeight(attrBinder.parseNumberPixelSize(value, v.getDividerHeight()));
}, getter(v:ListView) {
return v.getDividerHeight();
}
}).set('headerDividersEnabled', {
setter(v:ListView, value:any, attrBinder:AttrBinder) {
v.setHeaderDividersEnabled(attrBinder.parseBoolean(value, v.mHeaderDividersEnabled));
}, getter(v:ListView) {
return v.mHeaderDividersEnabled;
}
}).set('dividerHeight', {
setter(v:ListView, value:any, attrBinder:AttrBinder) {
v.setFooterDividersEnabled(attrBinder.parseBoolean(value, v.mFooterDividersEnabled));
}, getter(v:ListView) {
return v.mFooterDividersEnabled;
}
});
}
/**
* @return The maximum amount a list view will scroll in response to
* an arrow event.
*/
getMaxScrollAmount():number {
return Math.floor((ListView.MAX_SCROLL_FACTOR * (this.mBottom - this.mTop)));
}
/**
* Make sure views are touching the top or bottom edge, as appropriate for
* our gravity
*/
private adjustViewsUpOrDown():void {
const childCount:number = this.getChildCount();
let delta:number;
if (childCount > 0) {
let child:View;
if (!this.mStackFromBottom) {
// Uh-oh -- we came up short. Slide all views up to make them
// align with the top
child = this.getChildAt(0);
delta = child.getTop() - this.mListPadding.top;
if (this.mFirstPosition != 0) {
// It's OK to have some space above the first item if it is
// part of the vertical spacing
delta -= this.mDividerHeight;
}
if (delta < 0) {
// We only are looking to see if we are too low, not too high
delta = 0;
}
} else {
// we are too high, slide all views down to align with bottom
child = this.getChildAt(childCount - 1);
delta = child.getBottom() - (this.getHeight() - this.mListPadding.bottom);
if (this.mFirstPosition + childCount < this.mItemCount) {
// It's OK to have some space below the last item if it is
// part of the vertical spacing
delta += this.mDividerHeight;
}
if (delta > 0) {
delta = 0;
}
}
if (delta != 0) {
this.offsetChildrenTopAndBottom(-delta);
}
}
}
/**
* Add a fixed view to appear at the top of the list. If this method is
* called more than once, the views will appear in the order they were
* added. Views added using this call can take focus if they want.
* <p>
* Note: When first introduced, this method could only be called before
* setting the adapter with {@link #setAdapter(ListAdapter)}. Starting with
* {@link android.os.Build.VERSION_CODES#KITKAT}, this method may be
* called at any time. If the ListView's adapter does not extend
* {@link HeaderViewListAdapter}, it will be wrapped with a supporting
* instance of {@link WrapperListAdapter}.
*
* @param v The view to add.
* @param data Data to associate with this view
* @param isSelectable whether the item is selectable
*/
addHeaderView(v:View, data:any=null, isSelectable:boolean=true):void {
const info:ListView.FixedViewInfo = new ListView.FixedViewInfo(this);
info.view = v;
info.data = data;
info.isSelectable = isSelectable;
this.mHeaderViewInfos.add(info);
// Wrap the adapter if it wasn't already wrapped.
if (this.mAdapter != null) {
if (!(this.mAdapter instanceof HeaderViewListAdapter)) {
this.mAdapter = new HeaderViewListAdapter(this.mHeaderViewInfos, this.mFooterViewInfos, this.mAdapter);
}
// we need to notify the observer.
if (this.mDataSetObserver != null) {
this.mDataSetObserver.onChanged();
}
}
}
getHeaderViewsCount():number {
return this.mHeaderViewInfos.size();
}
/**
* Removes a previously-added header view.
*
* @param v The view to remove
* @return true if the view was removed, false if the view was not a header
* view
*/
removeHeaderView(v:View):boolean {
if (this.mHeaderViewInfos.size() > 0) {
let result:boolean = false;
if (this.mAdapter != null && (<HeaderViewListAdapter> this.mAdapter).removeHeader(v)) {
if (this.mDataSetObserver != null) {
this.mDataSetObserver.onChanged();
}
result = true;
}
this.removeFixedViewInfo(v, this.mHeaderViewInfos);
return result;
}
return false;
}
private removeFixedViewInfo(v:View, where:ArrayList<ListView.FixedViewInfo>):void {
let len:number = where.size();
for (let i:number = 0; i < len; ++i) {
let info:ListView.FixedViewInfo = where.get(i);
if (info.view == v) {
where.remove(i);
break;
}
}
}
/**
* Add a fixed view to appear at the bottom of the list. If addFooterView is
* called more than once, the views will appear in the order they were
* added. Views added using this call can take focus if they want.
* <p>
* Note: When first introduced, this method could only be called before
* setting the adapter with {@link #setAdapter(ListAdapter)}. Starting with
* {@link android.os.Build.VERSION_CODES#KITKAT}, this method may be
* called at any time. If the ListView's adapter does not extend
* {@link HeaderViewListAdapter}, it will be wrapped with a supporting
* instance of {@link WrapperListAdapter}.
*
* @param v The view to add.
* @param data Data to associate with this view
* @param isSelectable true if the footer view can be selected
*/
addFooterView(v:View, data:any=null, isSelectable:boolean=true):void {
const info:ListView.FixedViewInfo = new ListView.FixedViewInfo(this);
info.view = v;
info.data = data;
info.isSelectable = isSelectable;
this.mFooterViewInfos.add(info);
// Wrap the adapter if it wasn't already wrapped.
if (this.mAdapter != null) {
if (!(this.mAdapter instanceof HeaderViewListAdapter)) {
this.mAdapter = new HeaderViewListAdapter(this.mHeaderViewInfos, this.mFooterViewInfos, this.mAdapter);
}
// we need to notify the observer.
if (this.mDataSetObserver != null) {
this.mDataSetObserver.onChanged();
}
}
}
getFooterViewsCount():number {
return this.mFooterViewInfos.size();
}
/**
* Removes a previously-added footer view.
*
* @param v The view to remove
* @return
* true if the view was removed, false if the view was not a footer view
*/
removeFooterView(v:View):boolean {
if (this.mFooterViewInfos.size() > 0) {
let result:boolean = false;
if (this.mAdapter != null && (<HeaderViewListAdapter> this.mAdapter).removeFooter(v)) {
if (this.mDataSetObserver != null) {
this.mDataSetObserver.onChanged();
}
result = true;
}
this.removeFixedViewInfo(v, this.mFooterViewInfos);
return result;
}
return false;
}
/**
* Returns the adapter currently in use in this ListView. The returned adapter
* might not be the same adapter passed to {@link #setAdapter(ListAdapter)} but
* might be a {@link WrapperListAdapter}.
*
* @return The adapter currently used to display data in this ListView.
*
* @see #setAdapter(ListAdapter)
*/
getAdapter():ListAdapter {
return this.mAdapter;
}
/**
* Sets the data behind this ListView.
*
* The adapter passed to this method may be wrapped by a {@link WrapperListAdapter},
* depending on the ListView features currently in use. For instance, adding
* headers and/or footers will cause the adapter to be wrapped.
*
* @param adapter The ListAdapter which is responsible for maintaining the
* data backing this list and for producing a view to represent an
* item in that data set.
*
* @see #getAdapter()
*/
setAdapter(adapter:ListAdapter):void {
if (this.mAdapter != null && this.mDataSetObserver != null) {
this.mAdapter.unregisterDataSetObserver(this.mDataSetObserver);
}
this.resetList();
this.mRecycler.clear();
if (this.mHeaderViewInfos.size() > 0 || this.mFooterViewInfos.size() > 0) {
this.mAdapter = new HeaderViewListAdapter(this.mHeaderViewInfos, this.mFooterViewInfos, adapter);
} else {
this.mAdapter = adapter;
}
this.mOldSelectedPosition = ListView.INVALID_POSITION;
this.mOldSelectedRowId = ListView.INVALID_ROW_ID;
// AbsListView#setAdapter will update choice mode states.
super.setAdapter(adapter);
if (this.mAdapter != null) {
this.mAreAllItemsSelectable = this.mAdapter.areAllItemsEnabled();
this.mOldItemCount = this.mItemCount;
this.mItemCount = this.mAdapter.getCount();
this.checkFocus();
this.mDataSetObserver = new AbsListView.AdapterDataSetObserver(this);
this.mAdapter.registerDataSetObserver(this.mDataSetObserver);
this.mRecycler.setViewTypeCount(this.mAdapter.getViewTypeCount());
let position:number;
if (this.mStackFromBottom) {
position = this.lookForSelectablePosition(this.mItemCount - 1, false);
} else {
position = this.lookForSelectablePosition(0, true);
}
this.setSelectedPositionInt(position);
this.setNextSelectedPositionInt(position);
if (this.mItemCount == 0) {
// Nothing selected
this.checkSelectionChanged();
}
} else {
this.mAreAllItemsSelectable = true;
this.checkFocus();
// Nothing selected
this.checkSelectionChanged();
}
this.requestLayout();
}
/**
* The list is empty. Clear everything out.
*/
resetList():void {
// The parent's resetList() will remove all views from the layout so we need to
// cleanup the state of our footers and headers
this.clearRecycledState(this.mHeaderViewInfos);
this.clearRecycledState(this.mFooterViewInfos);
super.resetList();
this.mLayoutMode = ListView.LAYOUT_NORMAL;
}
private clearRecycledState(infos:ArrayList<ListView.FixedViewInfo>):void {
if (infos != null) {
const count:number = infos.size();
for (let i:number = 0; i < count; i++) {
const child:View = infos.get(i).view;
const p:AbsListView.LayoutParams = <AbsListView.LayoutParams> child.getLayoutParams();
if (p != null) {
p.recycledHeaderFooter = false;
}
}
}
}
/**
* @return Whether the list needs to show the top fading edge
*/
private showingTopFadingEdge():boolean {
const listTop:number = this.mScrollY + this.mListPadding.top;
return (this.mFirstPosition > 0) || (this.getChildAt(0).getTop() > listTop);
}
/**
* @return Whether the list needs to show the bottom fading edge
*/
private showingBottomFadingEdge():boolean {
const childCount:number = this.getChildCount();
const bottomOfBottomChild:number = this.getChildAt(childCount - 1).getBottom();
const lastVisiblePosition:number = this.mFirstPosition + childCount - 1;
const listBottom:number = this.mScrollY + this.getHeight() - this.mListPadding.bottom;
return (lastVisiblePosition < this.mItemCount - 1) || (bottomOfBottomChild < listBottom);
}
requestChildRectangleOnScreen(child:View, rect:Rect, immediate:boolean):boolean {
let rectTopWithinChild:number = rect.top;
// offset so rect is in coordinates of the this view
rect.offset(child.getLeft(), child.getTop());
rect.offset(-child.getScrollX(), -child.getScrollY());
const height:number = this.getHeight();
let listUnfadedTop:number = this.getScrollY();
let listUnfadedBottom:number = listUnfadedTop + height;
const fadingEdge:number = this.getVerticalFadingEdgeLength();
if (this.showingTopFadingEdge()) {
// leave room for top fading edge as long as rect isn't at very top
if ((this.mSelectedPosition > 0) || (rectTopWithinChild > fadingEdge)) {
listUnfadedTop += fadingEdge;
}
}
let childCount:number = this.getChildCount();
let bottomOfBottomChild:number = this.getChildAt(childCount - 1).getBottom();
if (this.showingBottomFadingEdge()) {
// leave room for bottom fading edge as long as rect isn't at very bottom
if ((this.mSelectedPosition < this.mItemCount - 1) || (rect.bottom < (bottomOfBottomChild - fadingEdge))) {
listUnfadedBottom -= fadingEdge;
}
}
let scrollYDelta:number = 0;
if (rect.bottom > listUnfadedBottom && rect.top > listUnfadedTop) {
if (rect.height() > height) {
// just enough to get screen size chunk on
scrollYDelta += (rect.top - listUnfadedTop);
} else {
// get entire rect at bottom of screen
scrollYDelta += (rect.bottom - listUnfadedBottom);
}
// make sure we aren't scrolling beyond the end of our children
let distanceToBottom:number = bottomOfBottomChild - listUnfadedBottom;
scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
} else if (rect.top < listUnfadedTop && rect.bottom < listUnfadedBottom) {
if (rect.height() > height) {
// screen size chunk
scrollYDelta -= (listUnfadedBottom - rect.bottom);
} else {
// entire rect at top
scrollYDelta -= (listUnfadedTop - rect.top);
}
// make sure we aren't scrolling any further than the top our children
let top:number = this.getChildAt(0).getTop();
let deltaToTop:number = top - listUnfadedTop;
scrollYDelta = Math.max(scrollYDelta, deltaToTop);
}
const scroll:boolean = scrollYDelta != 0;
if (scroll) {
this.scrollListItemsBy(-scrollYDelta);
this.positionSelector(ListView.INVALID_POSITION, child);
this.mSelectedTop = child.getTop();
this.invalidate();
}
return scroll;
}
/**
* {@inheritDoc}
*/
fillGap(down:boolean):void {
const count:number = this.getChildCount();
if (down) {
let paddingTop:number = 0;
if ((this.mGroupFlags & ListView.CLIP_TO_PADDING_MASK) == ListView.CLIP_TO_PADDING_MASK) {
paddingTop = this.getListPaddingTop();
}
const startOffset:number = count > 0 ? this.getChildAt(count - 1).getBottom() + this.mDividerHeight : paddingTop;
this.fillDown(this.mFirstPosition + count, startOffset);
this.correctTooHigh(this.getChildCount());
} else {
let paddingBottom:number = 0;
if ((this.mGroupFlags & ListView.CLIP_TO_PADDING_MASK) == ListView.CLIP_TO_PADDING_MASK) {
paddingBottom = this.getListPaddingBottom();
}
const startOffset:number = count > 0 ? this.getChildAt(0).getTop() - this.mDividerHeight : this.getHeight() - paddingBottom;
this.fillUp(this.mFirstPosition - 1, startOffset);
this.correctTooLow(this.getChildCount());
}
}
/**
* Fills the list from pos down to the end of the list view.
*
* @param pos The first position to put in the list
*
* @param nextTop The location where the top of the item associated with pos
* should be drawn
*
* @return The view that is currently selected, if it happens to be in the
* range that we draw.
*/
private fillDown(pos:number, nextTop:number):View {
let selectedView:View = null;
let end:number = (this.mBottom - this.mTop);
if ((this.mGroupFlags & ListView.CLIP_TO_PADDING_MASK) == ListView.CLIP_TO_PADDING_MASK) {
end -= this.mListPadding.bottom;
}
while (nextTop < end && pos < this.mItemCount) {
// is this the selected item?
let selected:boolean = pos == this.mSelectedPosition;
let child:View = this.makeAndAddView(pos, nextTop, true, this.mListPadding.left, selected);
nextTop = child.getBottom() + this.mDividerHeight;
if (selected) {
selectedView = child;
}
pos++;
}
this.setVisibleRangeHint(this.mFirstPosition, this.mFirstPosition + this.getChildCount() - 1);
return selectedView;
}
/**
* Fills the list from pos up to the top of the list view.
*
* @param pos The first position to put in the list
*
* @param nextBottom The location where the bottom of the item associated
* with pos should be drawn
*
* @return The view that is currently selected
*/
private fillUp(pos:number, nextBottom:number):View {
let selectedView:View = null;
let end:number = 0;
if ((this.mGroupFlags & ListView.CLIP_TO_PADDING_MASK) == ListView.CLIP_TO_PADDING_MASK) {
end = this.mListPadding.top;
}
while (nextBottom > end && pos >= 0) {
// is this the selected item?
let selected:boolean = pos == this.mSelectedPosition;
let child:View = this.makeAndAddView(pos, nextBottom, false, this.mListPadding.left, selected);
nextBottom = child.getTop() - this.mDividerHeight;
if (selected) {
selectedView = child;
}
pos--;
}
this.mFirstPosition = pos + 1;
this.setVisibleRangeHint(this.mFirstPosition, this.mFirstPosition + this.getChildCount() - 1);
return selectedView;
}
/**
* Fills the list from top to bottom, starting with mFirstPosition
*
* @param nextTop The location where the top of the first item should be
* drawn
*
* @return The view that is currently selected
*/
private fillFromTop(nextTop:number):View {
this.mFirstPosition = Math.min(this.mFirstPosition, this.mSelectedPosition);
this.mFirstPosition = Math.min(this.mFirstPosition, this.mItemCount - 1);
if (this.mFirstPosition < 0) {
this.mFirstPosition = 0;
}
return this.fillDown(this.mFirstPosition, nextTop);
}
/**
* Put mSelectedPosition in the middle of the screen and then build up and
* down from there. This method forces mSelectedPosition to the center.
*
* @param childrenTop Top of the area in which children can be drawn, as
* measured in pixels
* @param childrenBottom Bottom of the area in which children can be drawn,
* as measured in pixels
* @return Currently selected view
*/
private fillFromMiddle(childrenTop:number, childrenBottom:number):View {
let height:number = childrenBottom - childrenTop;
let position:number = this.reconcileSelectedPosition();
let sel:View = this.makeAndAddView(position, childrenTop, true, this.mListPadding.left, true);
this.mFirstPosition = position;
let selHeight:number = sel.getMeasuredHeight();
if (selHeight <= height) {
sel.offsetTopAndBottom((height - selHeight) / 2);
}
this.fillAboveAndBelow(sel, position);
if (!this.mStackFromBottom) {
this.correctTooHigh(this.getChildCount());
} else {
this.correctTooLow(this.getChildCount());
}
return sel;
}
/**
* Once the selected view as been placed, fill up the visible area above and
* below it.
*
* @param sel The selected view
* @param position The position corresponding to sel
*/
private fillAboveAndBelow(sel:View, position:number):void {
const dividerHeight:number = this.mDividerHeight;
if (!this.mStackFromBottom) {
this.fillUp(position - 1, sel.getTop() - dividerHeight);
this.adjustViewsUpOrDown();
this.fillDown(position + 1, sel.getBottom() + dividerHeight);
} else {
this.fillDown(position + 1, sel.getBottom() + dividerHeight);
this.adjustViewsUpOrDown();
this.fillUp(position - 1, sel.getTop() - dividerHeight);
}
}
/**
* Fills the grid based on positioning the new selection at a specific
* location. The selection may be moved so that it does not intersect the
* faded edges. The grid is then filled upwards and downwards from there.
*
* @param selectedTop Where the selected item should be
* @param childrenTop Where to start drawing children
* @param childrenBottom Last pixel where children can be drawn
* @return The view that currently has selection
*/
private fillFromSelection(selectedTop:number, childrenTop:number, childrenBottom:number):View {
let fadingEdgeLength:number = this.getVerticalFadingEdgeLength();
const selectedPosition:number = this.mSelectedPosition;
let sel:View;
const topSelectionPixel:number = this.getTopSelectionPixel(childrenTop, fadingEdgeLength, selectedPosition);
const bottomSelectionPixel:number = this.getBottomSelectionPixel(childrenBottom, fadingEdgeLength, selectedPosition);
sel = this.makeAndAddView(selectedPosition, selectedTop, true, this.mListPadding.left, true);
// Some of the newly selected item extends below the bottom of the list
if (sel.getBottom() > bottomSelectionPixel) {
// Find space available above the selection into which we can scroll
// upwards
const spaceAbove:number = sel.getTop() - topSelectionPixel;
// Find space required to bring the bottom of the selected item
// fully into view
const spaceBelow:number = sel.getBottom() - bottomSelectionPixel;
const offset:number = Math.min(spaceAbove, spaceBelow);
// Now offset the selected item to get it into view
sel.offsetTopAndBottom(-offset);
} else if (sel.getTop() < topSelectionPixel) {
// Find space required to bring the top of the selected item fully
// into view
const spaceAbove:number = topSelectionPixel - sel.getTop();
// Find space available below the selection into which we can scroll
// downwards
const spaceBelow:number = bottomSelectionPixel - sel.getBottom();
const offset:number = Math.min(spaceAbove, spaceBelow);
// Offset the selected item to get it into view
sel.offsetTopAndBottom(offset);
}
// Fill in views above and below
this.fillAboveAndBelow(sel, selectedPosition);
if (!this.mStackFromBottom) {
this.correctTooHigh(this.getChildCount());
} else {
this.correctTooLow(this.getChildCount());
}
return sel;
}
/**
* Calculate the bottom-most pixel we can draw the selection into
*
* @param childrenBottom Bottom pixel were children can be drawn
* @param fadingEdgeLength Length of the fading edge in pixels, if present
* @param selectedPosition The position that will be selected
* @return The bottom-most pixel we can draw the selection into
*/
private getBottomSelectionPixel(childrenBottom:number, fadingEdgeLength:number, selectedPosition:number):number {
let bottomSelectionPixel:number = childrenBottom;
if (selectedPosition != this.mItemCount - 1) {
bottomSelectionPixel -= fadingEdgeLength;
}
return bottomSelectionPixel;
}
/**
* Calculate the top-most pixel we can draw the selection into
*
* @param childrenTop Top pixel were children can be drawn
* @param fadingEdgeLength Length of the fading edge in pixels, if present
* @param selectedPosition The position that will be selected
* @return The top-most pixel we can draw the selection into
*/
private getTopSelectionPixel(childrenTop:number, fadingEdgeLength:number, selectedPosition:number):number {
// first pixel we can draw the selection into
let topSelectionPixel:number = childrenTop;
if (selectedPosition > 0) {
topSelectionPixel += fadingEdgeLength;
}
return topSelectionPixel;
}
/**
* Smoothly scroll to the specified adapter position. The view will
* scroll such that the indicated position is displayed.
* @param position Scroll to this adapter position.
*/
smoothScrollToPosition(position:number, boundPosition?:number):void {
super.smoothScrollToPosition(position, boundPosition);
}
/**
* Smoothly scroll to the specified adapter position offset. The view will
* scroll such that the indicated position is displayed.
* @param offset The amount to offset from the adapter position to scroll to.
*/
smoothScrollByOffset(offset:number):void {
super.smoothScrollByOffset(offset);
}
/**
* Fills the list based on positioning the new selection relative to the old
* selection. The new selection will be placed at, above, or below the
* location of the new selection depending on how the selection is moving.
* The selection will then be pinned to the visible part of the screen,
* excluding the edges that are faded. The list is then filled upwards and
* downwards from there.
*
* @param oldSel The old selected view. Useful for trying to put the new
* selection in the same place
* @param newSel The view that is to become selected. Useful for trying to
* put the new selection in the same place
* @param delta Which way we are moving
* @param childrenTop Where to start drawing children
* @param childrenBottom Last pixel where children can be drawn
* @return The view that currently has selection
*/
private moveSelection(oldSel:View, newSel:View, delta:number, childrenTop:number, childrenBottom:number):View {
let fadingEdgeLength:number = this.getVerticalFadingEdgeLength();
const selectedPosition:number = this.mSelectedPosition;
let sel:View;
const topSelectionPixel:number = this.getTopSelectionPixel(childrenTop, fadingEdgeLength, selectedPosition);
const bottomSelectionPixel:number = this.getBottomSelectionPixel(childrenTop, fadingEdgeLength, selectedPosition);
if (delta > 0) {
/*
* Case 1: Scrolling down.
*/
/*
* Before After
* | | | |
* +-------+ +-------+
* | A | | A |
* | 1 | => +-------+
* +-------+ | B |
* | B | | 2 |
* +-------+ +-------+
* | | | |
*
* Try to keep the top of the previously selected item where it was.
* oldSel = A
* sel = B
*/
// Put oldSel (A) where it belongs
oldSel = this.makeAndAddView(selectedPosition - 1, oldSel.getTop(), true, this.mListPadding.left, false);
const dividerHeight:number = this.mDividerHeight;
// Now put the new selection (B) below that
sel = this.makeAndAddView(selectedPosition, oldSel.getBottom() + dividerHeight, true, this.mListPadding.left, true);
// Some of the newly selected item extends below the bottom of the list
if (sel.getBottom() > bottomSelectionPixel) {
// Find space available above the selection into which we can scroll upwards
let spaceAbove:number = sel.getTop() - topSelectionPixel;
// Find space required to bring the bottom of the selected item fully into view
let spaceBelow:number = sel.getBottom() - bottomSelectionPixel;
// Don't scroll more than half the height of the list
let halfVerticalSpace:number = (childrenBottom - childrenTop) / 2;
let offset:number = Math.min(spaceAbove, spaceBelow);
offset = Math.min(offset, halfVerticalSpace);
// We placed oldSel, so offset that item
oldSel.offsetTopAndBottom(-offset);
// Now offset the selected item to get it into view
sel.offsetTopAndBottom(-offset);
}
// Fill in views above and below
if (!this.mStackFromBottom) {
this.fillUp(this.mSelectedPosition - 2, sel.getTop() - dividerHeight);
this.adjustViewsUpOrDown();
this.fillDown(this.mSelectedPosition + 1, sel.getBottom() + dividerHeight);
} else {
this.fillDown(this.mSelectedPosition + 1, sel.getBottom() + dividerHeight);
this.adjustViewsUpOrDown();
this.fillUp(this.mSelectedPosition - 2, sel.getTop() - dividerHeight);
}
} else if (delta < 0) {
if (newSel != null) {
// Try to position the top of newSel (A) where it was before it was selected
sel = this.makeAndAddView(selectedPosition, newSel.getTop(), true, this.mListPadding.left, true);
} else {
// If (A) was not on screen and so did not have a view, position
// it above the oldSel (B)
sel = this.makeAndAddView(selectedPosition, oldSel.getTop(), false, this.mListPadding.left, true);
}
// Some of the newly selected item extends above the top of the list
if (sel.getTop() < topSelectionPixel) {
// Find space required to bring the top of the selected item fully into view
let spaceAbove:number = topSelectionPixel - sel.getTop();
// Find space available below the selection into which we can scroll downwards
let spaceBelow:number = bottomSelectionPixel - sel.getBottom();
// Don't scroll more than half the height of the list
let halfVerticalSpace:number = (childrenBottom - childrenTop) / 2;
let offset:number = Math.min(spaceAbove, spaceBelow);
offset = Math.min(offset, halfVerticalSpace);
// Offset the selected item to get it into view
sel.offsetTopAndBottom(offset);
}
// Fill in views above and below
this.fillAboveAndBelow(sel, selectedPosition);
} else {
let oldTop:number = oldSel.getTop();
/*
* Case 3: Staying still
*/
sel = this.makeAndAddView(selectedPosition, oldTop, true, this.mListPadding.left, true);
// We're staying still...
if (oldTop < childrenTop) {
// ... but the top of the old selection was off screen.
// (This can happen if the data changes size out from under us)
let newBottom:number = sel.getBottom();
if (newBottom < childrenTop + 20) {
// Not enough visible -- bring it onscreen
sel.offsetTopAndBottom(childrenTop - sel.getTop());
}
}
// Fill in views above and below
this.fillAboveAndBelow(sel, selectedPosition);
}
return sel;
}
protected onSizeChanged(w:number, h:number, oldw:number, oldh:number):void {
if (this.getChildCount() > 0) {
let focusedChild:View = this.getFocusedChild();
if (focusedChild != null) {
const childPosition:number = this.mFirstPosition + this.indexOfChild(focusedChild);
const childBottom:number = focusedChild.getBottom();
const offset:number = Math.max(0, childBottom - (h - this.mPaddingTop));
const top:number = focusedChild.getTop() - offset;
if (this.mFocusSelector == null) {
this.mFocusSelector = new ListView.FocusSelector(this);
}
this.post(this.mFocusSelector.setup(childPosition, top));
}
}
super.onSizeChanged(w, h, oldw, oldh);
}
protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void {
// Sets up mListPadding
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
let widthMode:number = View.MeasureSpec.getMode(widthMeasureSpec);
let heightMode:number = View.MeasureSpec.getMode(heightMeasureSpec);
let widthSize:number = View.MeasureSpec.getSize(widthMeasureSpec);
let heightSize:number = View.MeasureSpec.getSize(heightMeasureSpec);
let childWidth:number = 0;
let childHeight:number = 0;
let childState:number = 0;
this.mItemCount = this.mAdapter == null ? 0 : this.mAdapter.getCount();
if (this.mItemCount > 0 && (widthMode == View.MeasureSpec.UNSPECIFIED || heightMode == View.MeasureSpec.UNSPECIFIED)) {
const child:View = this.obtainView(0, this.mIsScrap);
this.measureScrapChild(child, 0, widthMeasureSpec);
childWidth = child.getMeasuredWidth();
childHeight = child.getMeasuredHeight();
childState = ListView.combineMeasuredStates(childState, child.getMeasuredState());
if (this.recycleOnMeasure() && this.mRecycler.shouldRecycleViewType((<AbsListView.LayoutParams> child.getLayoutParams()).viewType)) {
this.mRecycler.addScrapView(child, -1);
}
}
if (widthMode == View.MeasureSpec.UNSPECIFIED) {
widthSize = this.mListPadding.left + this.mListPadding.right + childWidth + this.getVerticalScrollbarWidth();
} else {
widthSize |= (childState & ListView.MEASURED_STATE_MASK);
}
if (heightMode == View.MeasureSpec.UNSPECIFIED) {
heightSize = this.mListPadding.top + this.mListPadding.bottom + childHeight + this.getVerticalFadingEdgeLength() * 2;
}
if (heightMode == View.MeasureSpec.AT_MOST) {
// TODO: after first layout we should maybe start at the first visible position, not 0
heightSize = this.measureHeightOfChildren(widthMeasureSpec, 0, ListView.NO_POSITION, heightSize, -1);
}
this.setMeasuredDimension(widthSize, heightSize);
this.mWidthMeasureSpec = widthMeasureSpec;
}
private measureScrapChild(child:View, position:number, widthMeasureSpec:number):void {
let p:AbsListView.LayoutParams = <AbsListView.LayoutParams> child.getLayoutParams();
if (p == null) {
p = <AbsListView.LayoutParams> this.generateDefaultLayoutParams();
child.setLayoutParams(p);
}
p.viewType = this.mAdapter.getItemViewType(position);
p.forceAdd = true;
let childWidthSpec:number = ViewGroup.getChildMeasureSpec(widthMeasureSpec, this.mListPadding.left + this.mListPadding.right, p.width);
let lpHeight:number = p.height;
let childHeightSpec:number;
if (lpHeight > 0) {
childHeightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight, View.MeasureSpec.EXACTLY);
} else {
childHeightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
/**
* @return True to recycle the views used to measure this ListView in
* UNSPECIFIED/AT_MOST modes, false otherwise.
* @hide
*/
protected recycleOnMeasure():boolean {
return true;
}
/**
* Measures the height of the given range of children (inclusive) and
* returns the height with this ListView's padding and divider heights
* included. If maxHeight is provided, the measuring will stop when the
* current height reaches maxHeight.
*
* @param widthMeasureSpec The width measure spec to be given to a child's
* {@link View#measure(int, int)}.
* @param startPosition The position of the first child to be shown.
* @param endPosition The (inclusive) position of the last child to be
* shown. Specify {@link #NO_POSITION} if the last child should be
* the last available child from the adapter.
* @param maxHeight The maximum height that will be returned (if all the
* children don't fit in this value, this value will be
* returned).
* @param disallowPartialChildPosition In general, whether the returned
* height should only contain entire children. This is more
* powerful--it is the first inclusive position at which partial
* children will not be allowed. Example: it looks nice to have
* at least 3 completely visible children, and in portrait this
* will most likely fit; but in landscape there could be times
* when even 2 children can not be completely shown, so a value
* of 2 (remember, inclusive) would be good (assuming
* startPosition is 0).
* @return The height of this ListView with the given children.
*/
measureHeightOfChildren(widthMeasureSpec:number, startPosition:number, endPosition:number, maxHeight:number, disallowPartialChildPosition:number):number {
const adapter:ListAdapter = this.mAdapter;
if (adapter == null) {
return this.mListPadding.top + this.mListPadding.bottom;
}
// Include the padding of the list
let returnedHeight:number = this.mListPadding.top + this.mListPadding.bottom;
const dividerHeight:number = ((this.mDividerHeight > 0) && this.mDivider != null) ? this.mDividerHeight : 0;
// The previous height value that was less than maxHeight and contained
// no partial children
let prevHeightWithoutPartialChild:number = 0;
let i:number;
let child:View;
// mItemCount - 1 since endPosition parameter is inclusive
endPosition = (endPosition == ListView.NO_POSITION) ? adapter.getCount() - 1 : endPosition;
const recycleBin:AbsListView.RecycleBin = this.mRecycler;
const recyle:boolean = this.recycleOnMeasure();
const isScrap:boolean[] = this.mIsScrap;
for (i = startPosition; i <= endPosition; ++i) {
child = this.obtainView(i, isScrap);
this.measureScrapChild(child, i, widthMeasureSpec);
if (i > 0) {
// Count the divider for all but one child
returnedHeight += dividerHeight;
}
// Recycle the view before we possibly return from the method
if (recyle && recycleBin.shouldRecycleViewType((<AbsListView.LayoutParams> child.getLayoutParams()).viewType)) {
recycleBin.addScrapView(child, -1);
}
returnedHeight += child.getMeasuredHeight();
if (returnedHeight >= maxHeight) {
// then the i'th position did not fit completely.
// Disallowing is enabled (> -1)
return (disallowPartialChildPosition >= 0) && // We've past the min pos
(i > disallowPartialChildPosition) && // We have a prev height
(prevHeightWithoutPartialChild > 0) && // i'th child did not fit completely
(returnedHeight != maxHeight) ? prevHeightWithoutPartialChild : maxHeight;
}
if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) {
prevHeightWithoutPartialChild = returnedHeight;
}
}
// completely fit, so return the returnedHeight
return returnedHeight;
}
findMotionRow(y:number):number {
let childCount:number = this.getChildCount();
if (childCount > 0) {
if (!this.mStackFromBottom) {
for (let i:number = 0; i < childCount; i++) {
let v:View = this.getChildAt(i);
if (y <= v.getBottom()) {
return this.mFirstPosition + i;
}
}
} else {
for (let i:number = childCount - 1; i >= 0; i--) {
let v:View = this.getChildAt(i);
if (y >= v.getTop()) {
return this.mFirstPosition + i;
}
}
}
}
return ListView.INVALID_POSITION;
}
/**
* Put a specific item at a specific location on the screen and then build
* up and down from there.
*
* @param position The reference view to use as the starting point
* @param top Pixel offset from the top of this view to the top of the
* reference view.
*
* @return The selected view, or null if the selected view is outside the
* visible area.
*/
private fillSpecific(position:number, top:number):View {
let tempIsSelected:boolean = position == this.mSelectedPosition;
let temp:View = this.makeAndAddView(position, top, true, this.mListPadding.left, tempIsSelected);
// Possibly changed again in fillUp if we add rows above this one.
this.mFirstPosition = position;
let above:View;
let below:View;
const dividerHeight:number = this.mDividerHeight;
if (!this.mStackFromBottom) {
above = this.fillUp(position - 1, temp.getTop() - dividerHeight);
// This will correct for the top of the first view not touching the top of the list
this.adjustViewsUpOrDown();
below = this.fillDown(position + 1, temp.getBottom() + dividerHeight);
let childCount:number = this.getChildCount();
if (childCount > 0) {
this.correctTooHigh(childCount);
}
} else {
below = this.fillDown(position + 1, temp.getBottom() + dividerHeight);
// This will correct for the bottom of the last view not touching the bottom of the list
this.adjustViewsUpOrDown();
above = this.fillUp(position - 1, temp.getTop() - dividerHeight);
let childCount:number = this.getChildCount();
if (childCount > 0) {
this.correctTooLow(childCount);
}
}
if (tempIsSelected) {
return temp;
} else if (above != null) {
return above;
} else {
return below;
}
}
/**
* Check if we have dragged the bottom of the list too high (we have pushed the
* top element off the top of the screen when we did not need to). Correct by sliding
* everything back down.
*
* @param childCount Number of children
*/
private correctTooHigh(childCount:number):void {
// First see if the last item is visible. If it is not, it is OK for the
// top of the list to be pushed up.
let lastPosition:number = this.mFirstPosition + childCount - 1;
if (lastPosition == this.mItemCount - 1 && childCount > 0) {
// Get the last child ...
const lastChild:View = this.getChildAt(childCount - 1);
// ... and its bottom edge
const lastBottom:number = lastChild.getBottom();
// This is bottom of our drawable area
const end:number = (this.mBottom - this.mTop) - this.mListPadding.bottom;
// This is how far the bottom edge of the last view is from the bottom of the
// drawable area
let bottomOffset:number = end - lastBottom;
let firstChild:View = this.getChildAt(0);
const firstTop:number = firstChild.getTop();
// first row or the first row is scrolled off the top of the drawable area
if (bottomOffset > 0 && (this.mFirstPosition > 0 || firstTop < this.mListPadding.top)) {
if (this.mFirstPosition == 0) {
// Don't pull the top too far down
bottomOffset = Math.min(bottomOffset, this.mListPadding.top - firstTop);
}
// Move everything down
this.offsetChildrenTopAndBottom(bottomOffset);
if (this.mFirstPosition > 0) {
// Fill the gap that was opened above mFirstPosition with more rows, if
// possible
this.fillUp(this.mFirstPosition - 1, firstChild.getTop() - this.mDividerHeight);
// Close up the remaining gap
this.adjustViewsUpOrDown();
}
}
}
}
/**
* Check if we have dragged the bottom of the list too low (we have pushed the
* bottom element off the bottom of the screen when we did not need to). Correct by sliding
* everything back up.
*
* @param childCount Number of children
*/
private correctTooLow(childCount:number):void {
// bottom of the list to be pushed down.
if (this.mFirstPosition == 0 && childCount > 0) {
// Get the first child ...
const firstChild:View = this.getChildAt(0);
// ... and its top edge
const firstTop:number = firstChild.getTop();
// This is top of our drawable area
const start:number = this.mListPadding.top;
// This is bottom of our drawable area
const end:number = (this.mBottom - this.mTop) - this.mListPadding.bottom;
// This is how far the top edge of the first view is from the top of the
// drawable area
let topOffset:number = firstTop - start;
let lastChild:View = this.getChildAt(childCount - 1);
const lastBottom:number = lastChild.getBottom();
let lastPosition:number = this.mFirstPosition + childCount - 1;
// last row or the last row is scrolled off the bottom of the drawable area
if (topOffset > 0) {
if (lastPosition < this.mItemCount - 1 || lastBottom > end) {
if (lastPosition == this.mItemCount - 1) {
// Don't pull the bottom too far up
topOffset = Math.min(topOffset, lastBottom - end);
}
// Move everything up
this.offsetChildrenTopAndBottom(-topOffset);
if (lastPosition < this.mItemCount - 1) {
// Fill the gap that was opened below the last position with more rows, if
// possible
this.fillDown(lastPosition + 1, lastChild.getBottom() + this.mDividerHeight);
// Close up the remaining gap
this.adjustViewsUpOrDown();
}
} else if (lastPosition == this.mItemCount - 1) {
this.adjustViewsUpOrDown();
}
}
}
}
layoutChildren():void {
const blockLayoutRequests:boolean = this.mBlockLayoutRequests;
if (blockLayoutRequests) {
return;
}
this.mBlockLayoutRequests = true;
try {
super.layoutChildren();
this.invalidate();
if (this.mAdapter == null) {
this.resetList();
this.invokeOnItemScrollListener();
return;
}
const childrenTop:number = this.mListPadding.top;
const childrenBottom:number = this.mBottom - this.mTop - this.mListPadding.bottom;
const childCount:number = this.getChildCount();
let index:number = 0;
let delta:number = 0;
let sel:View;
let oldSel:View = null;
let oldFirst:View = null;
let newSel:View = null;
// Remember stuff we will need down below
switch(this.mLayoutMode) {
case ListView.LAYOUT_SET_SELECTION:
index = this.mNextSelectedPosition - this.mFirstPosition;
if (index >= 0 && index < childCount) {
newSel = this.getChildAt(index);
}
break;
case ListView.LAYOUT_FORCE_TOP:
case ListView.LAYOUT_FORCE_BOTTOM:
case ListView.LAYOUT_SPECIFIC:
case ListView.LAYOUT_SYNC:
break;
case ListView.LAYOUT_MOVE_SELECTION:
default:
// Remember the previously selected view
index = this.mSelectedPosition - this.mFirstPosition;
if (index >= 0 && index < childCount) {
oldSel = this.getChildAt(index);
}
// Remember the previous first child
oldFirst = this.getChildAt(0);
if (this.mNextSelectedPosition >= 0) {
delta = this.mNextSelectedPosition - this.mSelectedPosition;
}
// Caution: newSel might be null
newSel = this.getChildAt(index + delta);
}
let dataChanged:boolean = this.mDataChanged;
if (dataChanged) {
this.handleDataChanged();
}
// and calling it a day
if (this.mItemCount == 0) {
this.resetList();
this.invokeOnItemScrollListener();
return;
} else if (this.mItemCount != this.mAdapter.getCount()) {
throw Error(`IllegalStateException("The content of the adapter has changed but
ListView did not receive a notification. Make sure the content of
your adapter is not modified from a background thread, but only from
the UI thread. Make sure your adapter calls notifyDataSetChanged()
when its content changes. [in ListView(${this.getId()},${this.constructor.name})
with Adapter(${this.mAdapter.constructor.name})]")`);
}
this.setSelectedPositionInt(this.mNextSelectedPosition);
// Remember which child, if any, had accessibility focus.
//let accessibilityFocusPosition:number;
const accessFocusedChild:View = null;//this.getAccessibilityFocusedChild();
//if (accessFocusedChild != null) {
// accessibilityFocusPosition = this.getPositionForView(accessFocusedChild);
// accessFocusedChild.setHasTransientState(true);
//} else {
// accessibilityFocusPosition = ListView.INVALID_POSITION;
//}
// Ensure the child containing focus, if any, has transient state.
// If the list data hasn't changed, or if the adapter has stable
// IDs, this will maintain focus.
const focusedChild:View = this.getFocusedChild();
if (focusedChild != null) {
focusedChild.setHasTransientState(true);
}
// Pull all children into the RecycleBin.
// These views will be reused if possible
const firstPosition:number = this.mFirstPosition;
const recycleBin:AbsListView.RecycleBin = this.mRecycler;
if (dataChanged) {
for (let i:number = 0; i < childCount; i++) {
recycleBin.addScrapView(this.getChildAt(i), firstPosition + i);
}
} else {
recycleBin.fillActiveViews(childCount, firstPosition);
}
// Clear out old views
this.detachAllViewsFromParent();
recycleBin.removeSkippedScrap();
switch(this.mLayoutMode) {
case ListView.LAYOUT_SET_SELECTION:
if (newSel != null) {
sel = this.fillFromSelection(newSel.getTop(), childrenTop, childrenBottom);
} else {
sel = this.fillFromMiddle(childrenTop, childrenBottom);
}
break;
case ListView.LAYOUT_SYNC:
sel = this.fillSpecific(this.mSyncPosition, this.mSpecificTop);
break;
case ListView.LAYOUT_FORCE_BOTTOM:
sel = this.fillUp(this.mItemCount - 1, childrenBottom);
this.adjustViewsUpOrDown();
break;
case ListView.LAYOUT_FORCE_TOP:
this.mFirstPosition = 0;
sel = this.fillFromTop(childrenTop);
this.adjustViewsUpOrDown();
break;
case ListView.LAYOUT_SPECIFIC:
sel = this.fillSpecific(this.reconcileSelectedPosition(), this.mSpecificTop);
break;
case ListView.LAYOUT_MOVE_SELECTION:
sel = this.moveSelection(oldSel, newSel, delta, childrenTop, childrenBottom);
break;
default:
if (childCount == 0) {
if (!this.mStackFromBottom) {
const position:number = this.lookForSelectablePosition(0, true);
this.setSelectedPositionInt(position);
sel = this.fillFromTop(childrenTop);
} else {
const position:number = this.lookForSelectablePosition(this.mItemCount - 1, false);
this.setSelectedPositionInt(position);
sel = this.fillUp(this.mItemCount - 1, childrenBottom);
}
} else {
if (this.mSelectedPosition >= 0 && this.mSelectedPosition < this.mItemCount) {
sel = this.fillSpecific(this.mSelectedPosition, oldSel == null ? childrenTop : oldSel.getTop());
} else if (this.mFirstPosition < this.mItemCount) {
sel = this.fillSpecific(this.mFirstPosition, oldFirst == null ? childrenTop : oldFirst.getTop());
} else {
sel = this.fillSpecific(0, childrenTop);
}
}
break;
}
// Flush any cached views that did not get reused above
recycleBin.scrapActiveViews();
if (sel != null) {
const shouldPlaceFocus:boolean = this.mItemsCanFocus && this.hasFocus();
const maintainedFocus:boolean = focusedChild != null && focusedChild.hasFocus();
if (shouldPlaceFocus && !maintainedFocus && !sel.hasFocus()) {
if (sel.requestFocus()) {
// Successfully placed focus, clear selection.
sel.setSelected(false);
this.mSelectorRect.setEmpty();
} else {
// Failed to place focus, clear current (invalid) focus.
const focused:View = this.getFocusedChild();
if (focused != null) {
focused.clearFocus();
}
this.positionSelector(ListView.INVALID_POSITION, sel);
}
} else {
this.positionSelector(ListView.INVALID_POSITION, sel);
}
this.mSelectedTop = sel.getTop();
} else {
// Otherwise, clear selection.
if (this.mTouchMode == ListView.TOUCH_MODE_TAP || this.mTouchMode == ListView.TOUCH_MODE_DONE_WAITING) {
const child:View = this.getChildAt(this.mMotionPosition - this.mFirstPosition);
if (child != null) {
this.positionSelector(this.mMotionPosition, child);
}
} else {
this.mSelectedTop = 0;
this.mSelectorRect.setEmpty();
}
}
if (accessFocusedChild != null) {
accessFocusedChild.setHasTransientState(false);
// view, attempt to restore it to the previous position.
//if (!accessFocusedChild.isAccessibilityFocused() && accessibilityFocusPosition != ListView.INVALID_POSITION) {
// // Bound the position within the visible children.
// const position:number = MathUtils.constrain(accessibilityFocusPosition - this.mFirstPosition, 0, this.getChildCount() - 1);
// const restoreView:View = this.getChildAt(position);
// if (restoreView != null) {
// restoreView.requestAccessibilityFocus();
// }
//}
}
if (focusedChild != null) {
focusedChild.setHasTransientState(false);
}
this.mLayoutMode = ListView.LAYOUT_NORMAL;
this.mDataChanged = false;
if (this.mPositionScrollAfterLayout != null) {
this.post(this.mPositionScrollAfterLayout);
this.mPositionScrollAfterLayout = null;
}
this.mNeedSync = false;
this.setNextSelectedPositionInt(this.mSelectedPosition);
this.updateScrollIndicators();
if (this.mItemCount > 0) {
this.checkSelectionChanged();
}
this.invokeOnItemScrollListener();
} finally {
if (!blockLayoutRequests) {
this.mBlockLayoutRequests = false;
}
}
}
/**
* @return the direct child that contains accessibility focus, or null if no
* child contains accessibility focus
*/
//private getAccessibilityFocusedChild():View {
// const viewRootImpl:ViewRootImpl = this.getViewRootImpl();
// if (viewRootImpl == null) {
// return null;
// }
// let focusedView:View = viewRootImpl.getAccessibilityFocusedHost();
// if (focusedView == null) {
// return null;
// }
// let viewParent:ViewParent = focusedView.getParent();
// while ((viewParent instanceof View) && (viewParent != this)) {
// focusedView = <View> viewParent;
// viewParent = viewParent.getParent();
// }
// if (!(viewParent instanceof View)) {
// return null;
// }
// return focusedView;
//}
/**
* Obtain the view and add it to our list of children. The view can be made
* fresh, converted from an unused view, or used as is if it was in the
* recycle bin.
*
* @param position Logical position in the list
* @param y Top or bottom edge of the view to add
* @param flow If flow is true, align top edge to y. If false, align bottom
* edge to y.
* @param childrenLeft Left edge where children should be positioned
* @param selected Is this position selected?
* @return View that was added
*/
private makeAndAddView(position:number, y:number, flow:boolean, childrenLeft:number, selected:boolean):View {
let child:View;
if (!this.mDataChanged) {
// Try to use an existing view for this position
child = this.mRecycler.getActiveView(position);
if (child != null) {
// Found it -- we're using an existing child
// This just needs to be positioned
this.setupChild(child, position, y, flow, childrenLeft, selected, true);
return child;
}
}
// Make a new view for this position, or convert an unused view if possible
child = this.obtainView(position, this.mIsScrap);
// This needs to be positioned and measured
this.setupChild(child, position, y, flow, childrenLeft, selected, this.mIsScrap[0]);
return child;
}
/**
* Add a view as a child and make sure it is measured (if necessary) and
* positioned properly.
*
* @param child The view to add
* @param position The position of this child
* @param y The y position relative to which this view will be positioned
* @param flowDown If true, align top edge to y. If false, align bottom
* edge to y.
* @param childrenLeft Left edge where children should be positioned
* @param selected Is this position selected?
* @param recycled Has this view been pulled from the recycle bin? If so it
* does not need to be remeasured.
*/
private setupChild(child:View, position:number, y:number, flowDown:boolean, childrenLeft:number, selected:boolean, recycled:boolean):void {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "setupListItem");
const isSelected:boolean = selected && this.shouldShowSelector();
const updateChildSelected:boolean = isSelected != child.isSelected();
const mode:number = this.mTouchMode;
const isPressed:boolean = mode > ListView.TOUCH_MODE_DOWN && mode < ListView.TOUCH_MODE_SCROLL && this.mMotionPosition == position;
const updateChildPressed:boolean = isPressed != child.isPressed();
const needToMeasure:boolean = !recycled || updateChildSelected || child.isLayoutRequested();
// Respect layout params that are already in the view. Otherwise make some up...
// noinspection unchecked
let p:AbsListView.LayoutParams = <AbsListView.LayoutParams> child.getLayoutParams();
if (p == null) {
p = <AbsListView.LayoutParams> this.generateDefaultLayoutParams();
}
if(!(p instanceof AbsListView.LayoutParams)){
const name = p instanceof Function ? (<Function>p).constructor.name : p + '';
throw Error('ClassCaseException(' + name + ' can\'t case to AbsListView.LayoutParams)');
}
p.viewType = this.mAdapter.getItemViewType(position);
if ((recycled && !p.forceAdd) || (p.recycledHeaderFooter && p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) {
this.attachViewToParent(child, flowDown ? -1 : 0, p);
} else {
p.forceAdd = false;
if (p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
p.recycledHeaderFooter = true;
}
this.addViewInLayout(child, flowDown ? -1 : 0, p, true);
}
if (updateChildSelected) {
child.setSelected(isSelected);
}
if (updateChildPressed) {
child.setPressed(isPressed);
}
if (this.mChoiceMode != ListView.CHOICE_MODE_NONE && this.mCheckStates != null) {
if (child['setChecked']) {
(<Checkable><any>child).setChecked(this.mCheckStates.get(position));
} else {
child.setActivated(this.mCheckStates.get(position));
}
}
if (needToMeasure) {
let childWidthSpec:number = ViewGroup.getChildMeasureSpec(this.mWidthMeasureSpec, this.mListPadding.left + this.mListPadding.right, p.width);
let lpHeight:number = p.height;
let childHeightSpec:number;
if (lpHeight > 0) {
childHeightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight, View.MeasureSpec.EXACTLY);
} else {
childHeightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
} else {
this.cleanupLayoutState(child);
}
const w:number = child.getMeasuredWidth();
const h:number = child.getMeasuredHeight();
const childTop:number = flowDown ? y : y - h;
if (needToMeasure) {
const childRight:number = childrenLeft + w;
const childBottom:number = childTop + h;
child.layout(childrenLeft, childTop, childRight, childBottom);
} else {
child.offsetLeftAndRight(childrenLeft - child.getLeft());
child.offsetTopAndBottom(childTop - child.getTop());
}
if (this.mCachingStarted && !child.isDrawingCacheEnabled()) {
child.setDrawingCacheEnabled(true);
}
if (recycled && ((<AbsListView.LayoutParams> child.getLayoutParams()).scrappedFromPosition) != position) {
child.jumpDrawablesToCurrentState();
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
canAnimate():boolean {
return super.canAnimate() && this.mItemCount > 0;
}
/**
* Sets the currently selected item. If in touch mode, the item will not be selected
* but it will still be positioned appropriately. If the specified selection position
* is less than 0, then the item at position 0 will be selected.
*
* @param position Index (starting at 0) of the data item to be selected.
*/
setSelection(position:number):void {
this.setSelectionFromTop(position, 0);
}
/**
* Sets the selected item and positions the selection y pixels from the top edge
* of the ListView. (If in touch mode, the item will not be selected but it will
* still be positioned appropriately.)
*
* @param position Index (starting at 0) of the data item to be selected.
* @param y The distance from the top edge of the ListView (plus padding) that the
* item will be positioned.
*/
setSelectionFromTop(position:number, y:number):void {
if (this.mAdapter == null) {
return;
}
if (!this.isInTouchMode()) {
position = this.lookForSelectablePosition(position, true);
if (position >= 0) {
this.setNextSelectedPositionInt(position);
}
} else {
this.mResurrectToPosition = position;
}
if (position >= 0) {
this.mLayoutMode = ListView.LAYOUT_SPECIFIC;
this.mSpecificTop = this.mListPadding.top + y;
if (this.mNeedSync) {
this.mSyncPosition = position;
this.mSyncRowId = this.mAdapter.getItemId(position);
}
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
this.requestLayout();
}
}
/**
* Makes the item at the supplied position selected.
*
* @param position the position of the item to select
*/
setSelectionInt(position:number):void {
this.setNextSelectedPositionInt(position);
let awakeScrollbars:boolean = false;
const selectedPosition:number = this.mSelectedPosition;
if (selectedPosition >= 0) {
if (position == selectedPosition - 1) {
awakeScrollbars = true;
} else if (position == selectedPosition + 1) {
awakeScrollbars = true;
}
}
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
this.layoutChildren();
if (awakeScrollbars) {
this.awakenScrollBars();
}
}
/**
* Find a position that can be selected (i.e., is not a separator).
*
* @param position The starting position to look at.
* @param lookDown Whether to look down for other positions.
* @return The next selectable position starting at position and then searching either up or
* down. Returns {@link #INVALID_POSITION} if nothing can be found.
*/
lookForSelectablePosition(position:number, lookDown:boolean):number {
const adapter:ListAdapter = this.mAdapter;
if (adapter == null || this.isInTouchMode()) {
return ListView.INVALID_POSITION;
}
const count:number = adapter.getCount();
if (!this.mAreAllItemsSelectable) {
if (lookDown) {
position = Math.max(0, position);
while (position < count && !adapter.isEnabled(position)) {
position++;
}
} else {
position = Math.min(position, count - 1);
while (position >= 0 && !adapter.isEnabled(position)) {
position--;
}
}
}
if (position < 0 || position >= count) {
return ListView.INVALID_POSITION;
}
return position;
}
/**
* Find a position that can be selected (i.e., is not a separator). If there
* are no selectable positions in the specified direction from the starting
* position, searches in the opposite direction from the starting position
* to the current position.
*
* @param current the current position
* @param position the starting position
* @param lookDown whether to look down for other positions
* @return the next selectable position, or {@link #INVALID_POSITION} if
* nothing can be found
*/
lookForSelectablePositionAfter(current:number, position:number, lookDown:boolean):number {
const adapter:ListAdapter = this.mAdapter;
if (adapter == null || this.isInTouchMode()) {
return ListView.INVALID_POSITION;
}
// First check after the starting position in the specified direction.
const after:number = this.lookForSelectablePosition(position, lookDown);
if (after != ListView.INVALID_POSITION) {
return after;
}
// Then check between the starting position and the current position.
const count:number = adapter.getCount();
current = MathUtils.constrain(current, -1, count - 1);
if (lookDown) {
position = Math.min(position - 1, count - 1);
while ((position > current) && !adapter.isEnabled(position)) {
position--;
}
if (position <= current) {
return ListView.INVALID_POSITION;
}
} else {
position = Math.max(0, position + 1);
while ((position < current) && !adapter.isEnabled(position)) {
position++;
}
if (position >= current) {
return ListView.INVALID_POSITION;
}
}
return position;
}
/**
* setSelectionAfterHeaderView set the selection to be the first list item
* after the header views.
*/
setSelectionAfterHeaderView():void {
const count:number = this.mHeaderViewInfos.size();
if (count > 0) {
this.mNextSelectedPosition = 0;
return;
}
if (this.mAdapter != null) {
this.setSelection(count);
} else {
this.mNextSelectedPosition = count;
this.mLayoutMode = ListView.LAYOUT_SET_SELECTION;
}
}
dispatchKeyEvent(event:KeyEvent):boolean {
// Dispatch in the normal way
let handled:boolean = super.dispatchKeyEvent(event);
if (!handled) {
// If we didn't handle it...
let focused:View = this.getFocusedChild();
if (focused != null && event.getAction() == KeyEvent.ACTION_DOWN) {
// ... and our focused child didn't handle it
// ... give it to ourselves so we can scroll if necessary
handled = this.onKeyDown(event.getKeyCode(), event);
}
}
return handled;
}
onKeyDown(keyCode:number, event:KeyEvent):boolean {
return this.commonKey(keyCode, 1, event);
}
onKeyMultiple(keyCode:number, repeatCount:number, event:KeyEvent):boolean {
return this.commonKey(keyCode, repeatCount, event);
}
onKeyUp(keyCode:number, event:KeyEvent):boolean {
return this.commonKey(keyCode, 1, event);
}
private commonKey(keyCode:number, count:number, event:KeyEvent):boolean {
if (this.mAdapter == null || !this.isAttachedToWindow()) {
return false;
}
if (this.mDataChanged) {
this.layoutChildren();
}
let handled:boolean = false;
let action:number = event.getAction();
if (action != KeyEvent.ACTION_UP) {
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
if (event.hasNoModifiers()) {
handled = this.resurrectSelectionIfNeeded();
if (!handled) {
while (count-- > 0) {
if (this.arrowScroll(ListView.FOCUS_UP)) {
handled = true;
} else {
break;
}
}
}
} else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
handled = this.resurrectSelectionIfNeeded() || this.fullScroll(ListView.FOCUS_UP);
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (event.hasNoModifiers()) {
handled = this.resurrectSelectionIfNeeded();
if (!handled) {
while (count-- > 0) {
if (this.arrowScroll(ListView.FOCUS_DOWN)) {
handled = true;
} else {
break;
}
}
}
} else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
handled = this.resurrectSelectionIfNeeded() || this.fullScroll(ListView.FOCUS_DOWN);
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.hasNoModifiers()) {
handled = this.handleHorizontalFocusWithinListItem(View.FOCUS_LEFT);
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.hasNoModifiers()) {
handled = this.handleHorizontalFocusWithinListItem(View.FOCUS_RIGHT);
}
break;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if (event.hasNoModifiers()) {
handled = this.resurrectSelectionIfNeeded();
if (!handled && event.getRepeatCount() == 0 && this.getChildCount() > 0) {
this.keyPressed();
handled = true;
}
}
break;
case KeyEvent.KEYCODE_SPACE:
//if (this.mPopup == null || !this.mPopup.isShowing()) {
if (event.hasNoModifiers()) {
handled = this.resurrectSelectionIfNeeded() || this.pageScroll(ListView.FOCUS_DOWN);
} else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
handled = this.resurrectSelectionIfNeeded() || this.pageScroll(ListView.FOCUS_UP);
}
handled = true;
//}
break;
case KeyEvent.KEYCODE_PAGE_UP:
if (event.hasNoModifiers()) {
handled = this.resurrectSelectionIfNeeded() || this.pageScroll(ListView.FOCUS_UP);
} else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
handled = this.resurrectSelectionIfNeeded() || this.fullScroll(ListView.FOCUS_UP);
}
break;
case KeyEvent.KEYCODE_PAGE_DOWN:
if (event.hasNoModifiers()) {
handled = this.resurrectSelectionIfNeeded() || this.pageScroll(ListView.FOCUS_DOWN);
} else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
handled = this.resurrectSelectionIfNeeded() || this.fullScroll(ListView.FOCUS_DOWN);
}
break;
case KeyEvent.KEYCODE_MOVE_HOME:
if (event.hasNoModifiers()) {
handled = this.resurrectSelectionIfNeeded() || this.fullScroll(ListView.FOCUS_UP);
}
break;
case KeyEvent.KEYCODE_MOVE_END:
if (event.hasNoModifiers()) {
handled = this.resurrectSelectionIfNeeded() || this.fullScroll(ListView.FOCUS_DOWN);
}
break;
case KeyEvent.KEYCODE_TAB:
// XXX Sometimes it is useful to be able to TAB through the items in
// a ListView sequentially. Unfortunately this can create an
// asymmetry in TAB navigation order unless the list selection
// always reverts to the top or bottom when receiving TAB focus from
// another widget. Leaving this behavior disabled for now but
// perhaps it should be configurable (and more comprehensive).
// if (false) {
// if (event.hasNoModifiers()) {
// handled = this.resurrectSelectionIfNeeded() || this.arrowScroll(ListView.FOCUS_DOWN);
// } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
// handled = this.resurrectSelectionIfNeeded() || this.arrowScroll(ListView.FOCUS_UP);
// }
// }
break;
}
}
if (handled) {
return true;
}
//if (this.sendToTextFilter(keyCode, count, event)) {
// return true;
//}
switch(action) {
case KeyEvent.ACTION_DOWN:
return super.onKeyDown(keyCode, event);
case KeyEvent.ACTION_UP:
return super.onKeyUp(keyCode, event);
//case KeyEvent.ACTION_MULTIPLE:
// return super.onKeyMultiple(keyCode, count, event);
default:
// shouldn't happen
return false;
}
}
/**
* Scrolls up or down by the number of items currently present on screen.
*
* @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
* @return whether selection was moved
*/
pageScroll(direction:number):boolean {
let nextPage:number;
let down:boolean;
if (direction == ListView.FOCUS_UP) {
nextPage = Math.max(0, this.mSelectedPosition - this.getChildCount() - 1);
down = false;
} else if (direction == ListView.FOCUS_DOWN) {
nextPage = Math.min(this.mItemCount - 1, this.mSelectedPosition + this.getChildCount() - 1);
down = true;
} else {
return false;
}
if (nextPage >= 0) {
const position:number = this.lookForSelectablePositionAfter(this.mSelectedPosition, nextPage, down);
if (position >= 0) {
this.mLayoutMode = ListView.LAYOUT_SPECIFIC;
this.mSpecificTop = this.mPaddingTop + this.getVerticalFadingEdgeLength();
if (down && (position > (this.mItemCount - this.getChildCount()))) {
this.mLayoutMode = ListView.LAYOUT_FORCE_BOTTOM;
}
if (!down && (position < this.getChildCount())) {
this.mLayoutMode = ListView.LAYOUT_FORCE_TOP;
}
this.setSelectionInt(position);
this.invokeOnItemScrollListener();
if (!this.awakenScrollBars()) {
this.invalidate();
}
return true;
}
}
return false;
}
/**
* Go to the last or first item if possible (not worrying about panning
* across or navigating within the internal focus of the currently selected
* item.)
*
* @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
* @return whether selection was moved
*/
fullScroll(direction:number):boolean {
let moved:boolean = false;
if (direction == ListView.FOCUS_UP) {
if (this.mSelectedPosition != 0) {
const position:number = this.lookForSelectablePositionAfter(this.mSelectedPosition, 0, true);
if (position >= 0) {
this.mLayoutMode = ListView.LAYOUT_FORCE_TOP;
this.setSelectionInt(position);
this.invokeOnItemScrollListener();
}
moved = true;
}
} else if (direction == ListView.FOCUS_DOWN) {
const lastItem:number = (this.mItemCount - 1);
if (this.mSelectedPosition < lastItem) {
const position:number = this.lookForSelectablePositionAfter(this.mSelectedPosition, lastItem, false);
if (position >= 0) {
this.mLayoutMode = ListView.LAYOUT_FORCE_BOTTOM;
this.setSelectionInt(position);
this.invokeOnItemScrollListener();
}
moved = true;
}
}
if (moved && !this.awakenScrollBars()) {
this.awakenScrollBars();
this.invalidate();
}
return moved;
}
/**
* To avoid horizontal focus searches changing the selected item, we
* manually focus search within the selected item (as applicable), and
* prevent focus from jumping to something within another item.
* @param direction one of {View.FOCUS_LEFT, View.FOCUS_RIGHT}
* @return Whether this consumes the key event.
*/
private handleHorizontalFocusWithinListItem(direction:number):boolean {
if (direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT) {
throw Error(`new IllegalArgumentException("direction must be one of" + " {View.FOCUS_LEFT, View.FOCUS_RIGHT}")`);
}
const numChildren:number = this.getChildCount();
if (this.mItemsCanFocus && numChildren > 0 && this.mSelectedPosition != ListView.INVALID_POSITION) {
const selectedView:View = this.getSelectedView();
if (selectedView != null && selectedView.hasFocus() && selectedView instanceof ViewGroup) {
const currentFocus:View = selectedView.findFocus();
const nextFocus:View = FocusFinder.getInstance().findNextFocus(<ViewGroup> selectedView, currentFocus, direction);
if (nextFocus != null) {
// do the math to get interesting rect in next focus' coordinates
currentFocus.getFocusedRect(this.mTempRect);
this.offsetDescendantRectToMyCoords(currentFocus, this.mTempRect);
this.offsetRectIntoDescendantCoords(nextFocus, this.mTempRect);
if (nextFocus.requestFocus(direction, this.mTempRect)) {
return true;
}
}
// we are blocking the key from being handled (by returning true)
// if the global result is going to be some other view within this
// list. this is to acheive the overall goal of having
// horizontal d-pad navigation remain in the current item.
const globalNextFocus:View = FocusFinder.getInstance().findNextFocus(<ViewGroup> this.getRootView(), currentFocus, direction);
if (globalNextFocus != null) {
return this.isViewAncestorOf(globalNextFocus, this);
}
}
}
return false;
}
/**
* Scrolls to the next or previous item if possible.
*
* @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
*
* @return whether selection was moved
*/
arrowScroll(direction:number):boolean {
try {
this.mInLayout = true;
const handled:boolean = this.arrowScrollImpl(direction);
if (handled) {
this.playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
}
return handled;
} finally {
this.mInLayout = false;
}
}
/**
* Used by {@link #arrowScrollImpl(int)} to help determine the next selected position
* to move to. This return a position in the direction given if the selected item
* is fully visible.
*
* @param selectedView Current selected view to move from
* @param selectedPos Current selected position to move from
* @param direction Direction to move in
* @return Desired selected position after moving in the given direction
*/
private nextSelectedPositionForDirection(selectedView:View, selectedPos:number, direction:number):number {
let nextSelected:number;
if (direction == View.FOCUS_DOWN) {
const listBottom:number = this.getHeight() - this.mListPadding.bottom;
if (selectedView != null && selectedView.getBottom() <= listBottom) {
nextSelected = selectedPos != ListView.INVALID_POSITION && selectedPos >= this.mFirstPosition ? selectedPos + 1 : this.mFirstPosition;
} else {
return ListView.INVALID_POSITION;
}
} else {
const listTop:number = this.mListPadding.top;
if (selectedView != null && selectedView.getTop() >= listTop) {
const lastPos:number = this.mFirstPosition + this.getChildCount() - 1;
nextSelected = selectedPos != ListView.INVALID_POSITION && selectedPos <= lastPos ? selectedPos - 1 : lastPos;
} else {
return ListView.INVALID_POSITION;
}
}
if (nextSelected < 0 || nextSelected >= this.mAdapter.getCount()) {
return ListView.INVALID_POSITION;
}
return this.lookForSelectablePosition(nextSelected, direction == View.FOCUS_DOWN);
}
/**
* Handle an arrow scroll going up or down. Take into account whether items are selectable,
* whether there are focusable items etc.
*
* @param direction Either {@link android.view.View#FOCUS_UP} or {@link android.view.View#FOCUS_DOWN}.
* @return Whether any scrolling, selection or focus change occured.
*/
private arrowScrollImpl(direction:number):boolean {
if (this.getChildCount() <= 0) {
return false;
}
let selectedView:View = this.getSelectedView();
let selectedPos:number = this.mSelectedPosition;
let nextSelectedPosition:number = this.nextSelectedPositionForDirection(selectedView, selectedPos, direction);
let amountToScroll:number = this.amountToScroll(direction, nextSelectedPosition);
// if we are moving focus, we may OVERRIDE the default behavior
const focusResult:ListView.ArrowScrollFocusResult = this.mItemsCanFocus ? this.arrowScrollFocused(direction) : null;
if (focusResult != null) {
nextSelectedPosition = focusResult.getSelectedPosition();
amountToScroll = focusResult.getAmountToScroll();
}
let needToRedraw:boolean = focusResult != null;
if (nextSelectedPosition != ListView.INVALID_POSITION) {
this.handleNewSelectionChange(selectedView, direction, nextSelectedPosition, focusResult != null);
this.setSelectedPositionInt(nextSelectedPosition);
this.setNextSelectedPositionInt(nextSelectedPosition);
selectedView = this.getSelectedView();
selectedPos = nextSelectedPosition;
if (this.mItemsCanFocus && focusResult == null) {
// there was no new view found to take focus, make sure we
// don't leave focus with the old selection
const focused:View = this.getFocusedChild();
if (focused != null) {
focused.clearFocus();
}
}
needToRedraw = true;
this.checkSelectionChanged();
}
if (amountToScroll > 0) {
this.scrollListItemsBy((direction == View.FOCUS_UP) ? amountToScroll : -amountToScroll);
needToRedraw = true;
}
// item that was panned off screen gives up focus.
if (this.mItemsCanFocus && (focusResult == null) && selectedView != null && selectedView.hasFocus()) {
const focused:View = selectedView.findFocus();
if (!this.isViewAncestorOf(focused, this) || this.distanceToView(focused) > 0) {
focused.clearFocus();
}
}
// if the current selection is panned off, we need to remove the selection
if (nextSelectedPosition == ListView.INVALID_POSITION && selectedView != null && !this.isViewAncestorOf(selectedView, this)) {
selectedView = null;
this.hideSelector();
// but we don't want to set the ressurect position (that would make subsequent
// unhandled key events bring back the item we just scrolled off!)
this.mResurrectToPosition = ListView.INVALID_POSITION;
}
if (needToRedraw) {
if (selectedView != null) {
this.positionSelector(selectedPos, selectedView);
this.mSelectedTop = selectedView.getTop();
}
if (!this.awakenScrollBars()) {
this.invalidate();
}
this.invokeOnItemScrollListener();
return true;
}
return false;
}
/**
* When selection changes, it is possible that the previously selected or the
* next selected item will change its size. If so, we need to offset some folks,
* and re-layout the items as appropriate.
*
* @param selectedView The currently selected view (before changing selection).
* should be <code>null</code> if there was no previous selection.
* @param direction Either {@link android.view.View#FOCUS_UP} or
* {@link android.view.View#FOCUS_DOWN}.
* @param newSelectedPosition The position of the next selection.
* @param newFocusAssigned whether new focus was assigned. This matters because
* when something has focus, we don't want to show selection (ugh).
*/
private handleNewSelectionChange(selectedView:View, direction:number, newSelectedPosition:number, newFocusAssigned:boolean):void {
if (newSelectedPosition == ListView.INVALID_POSITION) {
throw Error(`new IllegalArgumentException("newSelectedPosition needs to be valid")`);
}
// whether or not we are moving down or up, we want to preserve the
// top of whatever view is on top:
// - moving down: the view that had selection
// - moving up: the view that is getting selection
let topView:View;
let bottomView:View;
let topViewIndex:number, bottomViewIndex:number;
let topSelected:boolean = false;
const selectedIndex:number = this.mSelectedPosition - this.mFirstPosition;
const nextSelectedIndex:number = newSelectedPosition - this.mFirstPosition;
if (direction == View.FOCUS_UP) {
topViewIndex = nextSelectedIndex;
bottomViewIndex = selectedIndex;
topView = this.getChildAt(topViewIndex);
bottomView = selectedView;
topSelected = true;
} else {
topViewIndex = selectedIndex;
bottomViewIndex = nextSelectedIndex;
topView = selectedView;
bottomView = this.getChildAt(bottomViewIndex);
}
const numChildren:number = this.getChildCount();
// start with top view: is it changing size?
if (topView != null) {
topView.setSelected(!newFocusAssigned && topSelected);
this.measureAndAdjustDown(topView, topViewIndex, numChildren);
}
// is the bottom view changing size?
if (bottomView != null) {
bottomView.setSelected(!newFocusAssigned && !topSelected);
this.measureAndAdjustDown(bottomView, bottomViewIndex, numChildren);
}
}
/**
* Re-measure a child, and if its height changes, lay it out preserving its
* top, and adjust the children below it appropriately.
* @param child The child
* @param childIndex The view group index of the child.
* @param numChildren The number of children in the view group.
*/
private measureAndAdjustDown(child:View, childIndex:number, numChildren:number):void {
let oldHeight:number = child.getHeight();
this.measureItem(child);
if (child.getMeasuredHeight() != oldHeight) {
// lay out the view, preserving its top
this.relayoutMeasuredItem(child);
// adjust views below appropriately
const heightDelta:number = child.getMeasuredHeight() - oldHeight;
for (let i:number = childIndex + 1; i < numChildren; i++) {
this.getChildAt(i).offsetTopAndBottom(heightDelta);
}
}
}
/**
* Measure a particular list child.
* TODO: unify with setUpChild.
* @param child The child.
*/
private measureItem(child:View):void {
let p:ViewGroup.LayoutParams = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
let childWidthSpec:number = ViewGroup.getChildMeasureSpec(this.mWidthMeasureSpec, this.mListPadding.left + this.mListPadding.right, p.width);
let lpHeight:number = p.height;
let childHeightSpec:number;
if (lpHeight > 0) {
childHeightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight, View.MeasureSpec.EXACTLY);
} else {
childHeightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
/**
* Layout a child that has been measured, preserving its top position.
* TODO: unify with setUpChild.
* @param child The child.
*/
private relayoutMeasuredItem(child:View):void {
const w:number = child.getMeasuredWidth();
const h:number = child.getMeasuredHeight();
const childLeft:number = this.mListPadding.left;
const childRight:number = childLeft + w;
const childTop:number = child.getTop();
const childBottom:number = childTop + h;
child.layout(childLeft, childTop, childRight, childBottom);
}
/**
* @return The amount to preview next items when arrow srolling.
*/
private getArrowScrollPreviewLength():number {
return Math.max(ListView.MIN_SCROLL_PREVIEW_PIXELS, this.getVerticalFadingEdgeLength());
}
/**
* Determine how much we need to scroll in order to get the next selected view
* visible, with a fading edge showing below as applicable. The amount is
* capped at {@link #getMaxScrollAmount()} .
*
* @param direction either {@link android.view.View#FOCUS_UP} or
* {@link android.view.View#FOCUS_DOWN}.
* @param nextSelectedPosition The position of the next selection, or
* {@link #INVALID_POSITION} if there is no next selectable position
* @return The amount to scroll. Note: this is always positive! Direction
* needs to be taken into account when actually scrolling.
*/
private amountToScroll(direction:number, nextSelectedPosition:number):number {
const listBottom:number = this.getHeight() - this.mListPadding.bottom;
const listTop:number = this.mListPadding.top;
let numChildren:number = this.getChildCount();
if (direction == View.FOCUS_DOWN) {
let indexToMakeVisible:number = numChildren - 1;
if (nextSelectedPosition != ListView.INVALID_POSITION) {
indexToMakeVisible = nextSelectedPosition - this.mFirstPosition;
}
while (numChildren <= indexToMakeVisible) {
// Child to view is not attached yet.
this.addViewBelow(this.getChildAt(numChildren - 1), this.mFirstPosition + numChildren - 1);
numChildren++;
}
const positionToMakeVisible:number = this.mFirstPosition + indexToMakeVisible;
const viewToMakeVisible:View = this.getChildAt(indexToMakeVisible);
let goalBottom:number = listBottom;
if (positionToMakeVisible < this.mItemCount - 1) {
goalBottom -= this.getArrowScrollPreviewLength();
}
if (viewToMakeVisible.getBottom() <= goalBottom) {
// item is fully visible.
return 0;
}
if (nextSelectedPosition != ListView.INVALID_POSITION && (goalBottom - viewToMakeVisible.getTop()) >= this.getMaxScrollAmount()) {
// item already has enough of it visible, changing selection is good enough
return 0;
}
let amountToScroll:number = (viewToMakeVisible.getBottom() - goalBottom);
if ((this.mFirstPosition + numChildren) == this.mItemCount) {
// last is last in list -> make sure we don't scroll past it
const max:number = this.getChildAt(numChildren - 1).getBottom() - listBottom;
amountToScroll = Math.min(amountToScroll, max);
}
return Math.min(amountToScroll, this.getMaxScrollAmount());
} else {
let indexToMakeVisible:number = 0;
if (nextSelectedPosition != ListView.INVALID_POSITION) {
indexToMakeVisible = nextSelectedPosition - this.mFirstPosition;
}
while (indexToMakeVisible < 0) {
// Child to view is not attached yet.
this.addViewAbove(this.getChildAt(0), this.mFirstPosition);
this.mFirstPosition--;
indexToMakeVisible = nextSelectedPosition - this.mFirstPosition;
}
const positionToMakeVisible:number = this.mFirstPosition + indexToMakeVisible;
const viewToMakeVisible:View = this.getChildAt(indexToMakeVisible);
let goalTop:number = listTop;
if (positionToMakeVisible > 0) {
goalTop += this.getArrowScrollPreviewLength();
}
if (viewToMakeVisible.getTop() >= goalTop) {
// item is fully visible.
return 0;
}
if (nextSelectedPosition != ListView.INVALID_POSITION && (viewToMakeVisible.getBottom() - goalTop) >= this.getMaxScrollAmount()) {
// item already has enough of it visible, changing selection is good enough
return 0;
}
let amountToScroll:number = (goalTop - viewToMakeVisible.getTop());
if (this.mFirstPosition == 0) {
// first is first in list -> make sure we don't scroll past it
const max:number = listTop - this.getChildAt(0).getTop();
amountToScroll = Math.min(amountToScroll, max);
}
return Math.min(amountToScroll, this.getMaxScrollAmount());
}
}
/**
* @param direction either {@link android.view.View#FOCUS_UP} or
* {@link android.view.View#FOCUS_DOWN}.
* @return The position of the next selectable position of the views that
* are currently visible, taking into account the fact that there might
* be no selection. Returns {@link #INVALID_POSITION} if there is no
* selectable view on screen in the given direction.
*/
private lookForSelectablePositionOnScreen(direction:number):number {
const firstPosition:number = this.mFirstPosition;
if (direction == View.FOCUS_DOWN) {
let startPos:number = (this.mSelectedPosition != ListView.INVALID_POSITION) ? this.mSelectedPosition + 1 : firstPosition;
if (startPos >= this.mAdapter.getCount()) {
return ListView.INVALID_POSITION;
}
if (startPos < firstPosition) {
startPos = firstPosition;
}
const lastVisiblePos:number = this.getLastVisiblePosition();
const adapter:ListAdapter = this.getAdapter();
for (let pos:number = startPos; pos <= lastVisiblePos; pos++) {
if (adapter.isEnabled(pos) && this.getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
return pos;
}
}
} else {
let last:number = firstPosition + this.getChildCount() - 1;
let startPos:number = (this.mSelectedPosition != ListView.INVALID_POSITION) ? this.mSelectedPosition - 1 : firstPosition + this.getChildCount() - 1;
if (startPos < 0 || startPos >= this.mAdapter.getCount()) {
return ListView.INVALID_POSITION;
}
if (startPos > last) {
startPos = last;
}
const adapter:ListAdapter = this.getAdapter();
for (let pos:number = startPos; pos >= firstPosition; pos--) {
if (adapter.isEnabled(pos) && this.getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
return pos;
}
}
}
return ListView.INVALID_POSITION;
}
/**
* Do an arrow scroll based on focus searching. If a new view is
* given focus, return the selection delta and amount to scroll via
* an {@link ArrowScrollFocusResult}, otherwise, return null.
*
* @param direction either {@link android.view.View#FOCUS_UP} or
* {@link android.view.View#FOCUS_DOWN}.
* @return The result if focus has changed, or <code>null</code>.
*/
private arrowScrollFocused(direction:number):ListView.ArrowScrollFocusResult {
const selectedView:View = this.getSelectedView();
let newFocus:View;
if (selectedView != null && selectedView.hasFocus()) {
let oldFocus:View = selectedView.findFocus();
newFocus = FocusFinder.getInstance().findNextFocus(this, oldFocus, direction);
} else {
if (direction == View.FOCUS_DOWN) {
const topFadingEdgeShowing:boolean = (this.mFirstPosition > 0);
const listTop:number = this.mListPadding.top + (topFadingEdgeShowing ? this.getArrowScrollPreviewLength() : 0);
const ySearchPoint:number = (selectedView != null && selectedView.getTop() > listTop) ? selectedView.getTop() : listTop;
this.mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
} else {
const bottomFadingEdgeShowing:boolean = (this.mFirstPosition + this.getChildCount() - 1) < this.mItemCount;
const listBottom:number = this.getHeight() - this.mListPadding.bottom - (bottomFadingEdgeShowing ? this.getArrowScrollPreviewLength() : 0);
const ySearchPoint:number = (selectedView != null && selectedView.getBottom() < listBottom) ? selectedView.getBottom() : listBottom;
this.mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
}
newFocus = FocusFinder.getInstance().findNextFocusFromRect(this, this.mTempRect, direction);
}
if (newFocus != null) {
const positionOfNewFocus:number = this.positionOfNewFocus(newFocus);
// we aren't jumping over another selectable position
if (this.mSelectedPosition != ListView.INVALID_POSITION && positionOfNewFocus != this.mSelectedPosition) {
const selectablePosition:number = this.lookForSelectablePositionOnScreen(direction);
if (selectablePosition != ListView.INVALID_POSITION && ((direction == View.FOCUS_DOWN && selectablePosition < positionOfNewFocus) || (direction == View.FOCUS_UP && selectablePosition > positionOfNewFocus))) {
return null;
}
}
let focusScroll:number = this.amountToScrollToNewFocus(direction, newFocus, positionOfNewFocus);
const maxScrollAmount:number = this.getMaxScrollAmount();
if (focusScroll < maxScrollAmount) {
// not moving too far, safe to give next view focus
newFocus.requestFocus(direction);
this.mArrowScrollFocusResult.populate(positionOfNewFocus, focusScroll);
return this.mArrowScrollFocusResult;
} else if (this.distanceToView(newFocus) < maxScrollAmount) {
// Case to consider:
// too far to get entire next focusable on screen, but by going
// max scroll amount, we are getting it at least partially in view,
// so give it focus and scroll the max ammount.
newFocus.requestFocus(direction);
this.mArrowScrollFocusResult.populate(positionOfNewFocus, maxScrollAmount);
return this.mArrowScrollFocusResult;
}
}
return null;
}
/**
* @param newFocus The view that would have focus.
* @return the position that contains newFocus
*/
private positionOfNewFocus(newFocus:View):number {
const numChildren:number = this.getChildCount();
for (let i:number = 0; i < numChildren; i++) {
const child:View = this.getChildAt(i);
if (this.isViewAncestorOf(newFocus, child)) {
return this.mFirstPosition + i;
}
}
throw Error(`new IllegalArgumentException("newFocus is not a child of any of the" + " children of the list!")`);
}
/**
* Return true if child is an ancestor of parent, (or equal to the parent).
*/
private isViewAncestorOf(child:View, parent:View):boolean {
if (child == parent) {
return true;
}
const theParent:ViewParent = child.getParent();
return (theParent instanceof ViewGroup) && this.isViewAncestorOf(<View> theParent, parent);
}
/**
* Determine how much we need to scroll in order to get newFocus in view.
* @param direction either {@link android.view.View#FOCUS_UP} or
* {@link android.view.View#FOCUS_DOWN}.
* @param newFocus The view that would take focus.
* @param positionOfNewFocus The position of the list item containing newFocus
* @return The amount to scroll. Note: this is always positive! Direction
* needs to be taken into account when actually scrolling.
*/
private amountToScrollToNewFocus(direction:number, newFocus:View, positionOfNewFocus:number):number {
let amountToScroll:number = 0;
newFocus.getDrawingRect(this.mTempRect);
this.offsetDescendantRectToMyCoords(newFocus, this.mTempRect);
if (direction == View.FOCUS_UP) {
if (this.mTempRect.top < this.mListPadding.top) {
amountToScroll = this.mListPadding.top - this.mTempRect.top;
if (positionOfNewFocus > 0) {
amountToScroll += this.getArrowScrollPreviewLength();
}
}
} else {
const listBottom:number = this.getHeight() - this.mListPadding.bottom;
if (this.mTempRect.bottom > listBottom) {
amountToScroll = this.mTempRect.bottom - listBottom;
if (positionOfNewFocus < this.mItemCount - 1) {
amountToScroll += this.getArrowScrollPreviewLength();
}
}
}
return amountToScroll;
}
/**
* Determine the distance to the nearest edge of a view in a particular
* direction.
*
* @param descendant A descendant of this list.
* @return The distance, or 0 if the nearest edge is already on screen.
*/
private distanceToView(descendant:View):number {
let distance:number = 0;
descendant.getDrawingRect(this.mTempRect);
this.offsetDescendantRectToMyCoords(descendant, this.mTempRect);
const listBottom:number = this.mBottom - this.mTop - this.mListPadding.bottom;
if (this.mTempRect.bottom < this.mListPadding.top) {
distance = this.mListPadding.top - this.mTempRect.bottom;
} else if (this.mTempRect.top > listBottom) {
distance = this.mTempRect.top - listBottom;
}
return distance;
}
/**
* Scroll the children by amount, adding a view at the end and removing
* views that fall off as necessary.
*
* @param amount The amount (positive or negative) to scroll.
*/
private scrollListItemsBy(amount:number):void {
this.offsetChildrenTopAndBottom(amount);
const listBottom:number = this.getHeight() - this.mListPadding.bottom;
const listTop:number = this.mListPadding.top;
const recycleBin:AbsListView.RecycleBin = this.mRecycler;
if (amount < 0) {
// shifted items up
// may need to pan views into the bottom space
let numChildren:number = this.getChildCount();
let last:View = this.getChildAt(numChildren - 1);
while (last.getBottom() < listBottom) {
const lastVisiblePosition:number = this.mFirstPosition + numChildren - 1;
if (lastVisiblePosition < this.mItemCount - 1) {
last = this.addViewBelow(last, lastVisiblePosition);
numChildren++;
} else {
break;
}
}
// to shift back
if (last.getBottom() < listBottom) {
this.offsetChildrenTopAndBottom(listBottom - last.getBottom());
}
// top views may be panned off screen
let first:View = this.getChildAt(0);
while (first.getBottom() < listTop) {
let layoutParams:AbsListView.LayoutParams = <AbsListView.LayoutParams> first.getLayoutParams();
if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
recycleBin.addScrapView(first, this.mFirstPosition);
}
this.detachViewFromParent(first);
first = this.getChildAt(0);
this.mFirstPosition++;
}
} else {
// shifted items down
let first:View = this.getChildAt(0);
// may need to pan views into top
while ((first.getTop() > listTop) && (this.mFirstPosition > 0)) {
first = this.addViewAbove(first, this.mFirstPosition);
this.mFirstPosition--;
}
// need to shift it back
if (first.getTop() > listTop) {
this.offsetChildrenTopAndBottom(listTop - first.getTop());
}
let lastIndex:number = this.getChildCount() - 1;
let last:View = this.getChildAt(lastIndex);
// bottom view may be panned off screen
while (last.getTop() > listBottom) {
let layoutParams:AbsListView.LayoutParams = <AbsListView.LayoutParams> last.getLayoutParams();
if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
recycleBin.addScrapView(last, this.mFirstPosition + lastIndex);
}
this.detachViewFromParent(last);
last = this.getChildAt(--lastIndex);
}
}
}
private addViewAbove(theView:View, position:number):View {
let abovePosition:number = position - 1;
let view:View = this.obtainView(abovePosition, this.mIsScrap);
let edgeOfNewChild:number = theView.getTop() - this.mDividerHeight;
this.setupChild(view, abovePosition, edgeOfNewChild, false, this.mListPadding.left, false, this.mIsScrap[0]);
return view;
}
private addViewBelow(theView:View, position:number):View {
let belowPosition:number = position + 1;
let view:View = this.obtainView(belowPosition, this.mIsScrap);
let edgeOfNewChild:number = theView.getBottom() + this.mDividerHeight;
this.setupChild(view, belowPosition, edgeOfNewChild, true, this.mListPadding.left, false, this.mIsScrap[0]);
return view;
}
/**
* Indicates that the views created by the ListAdapter can contain focusable
* items.
*
* @param itemsCanFocus true if items can get focus, false otherwise
*/
setItemsCanFocus(itemsCanFocus:boolean):void {
this.mItemsCanFocus = itemsCanFocus;
if (!itemsCanFocus) {
this.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
}
}
/**
* @return Whether the views created by the ListAdapter can contain focusable
* items.
*/
getItemsCanFocus():boolean {
return this.mItemsCanFocus;
}
isOpaque():boolean {
let retValue:boolean = (this.mCachingActive && this.mIsCacheColorOpaque && this.mDividerIsOpaque && this.hasOpaqueScrollbars()) || super.isOpaque();
if (retValue) {
// only return true if the list items cover the entire area of the view
const listTop:number = this.mListPadding != null ? this.mListPadding.top : this.mPaddingTop;
let first:View = this.getChildAt(0);
if (first == null || first.getTop() > listTop) {
return false;
}
const listBottom:number = this.getHeight() - (this.mListPadding != null ? this.mListPadding.bottom : this.mPaddingBottom);
let last:View = this.getChildAt(this.getChildCount() - 1);
if (last == null || last.getBottom() < listBottom) {
return false;
}
}
return retValue;
}
setCacheColorHint(color:number):void {
const opaque:boolean = (color >>> 24) == 0xFF;
this.mIsCacheColorOpaque = opaque;
if (opaque) {
if (this.mDividerPaint == null) {
this.mDividerPaint = new Paint();
}
this.mDividerPaint.setColor(color);
}
super.setCacheColorHint(color);
}
drawOverscrollHeader(canvas:Canvas, drawable:Drawable, bounds:Rect):void {
const height:number = drawable.getMinimumHeight();
canvas.save();
canvas.clipRect(bounds);
const span:number = bounds.bottom - bounds.top;
if (span < height) {
bounds.top = bounds.bottom - height;
}
drawable.setBounds(bounds);
drawable.draw(canvas);
canvas.restore();
}
drawOverscrollFooter(canvas:Canvas, drawable:Drawable, bounds:Rect):void {
const height:number = drawable.getMinimumHeight();
canvas.save();
canvas.clipRect(bounds);
const span:number = bounds.bottom - bounds.top;
if (span < height) {
bounds.bottom = bounds.top + height;
}
drawable.setBounds(bounds);
drawable.draw(canvas);
canvas.restore();
}
protected dispatchDraw(canvas:Canvas):void {
if (this.mCachingStarted) {
this.mCachingActive = true;
}
// Draw the dividers
const dividerHeight:number = this.mDividerHeight;
const overscrollHeader:Drawable = this.mOverScrollHeader;
const overscrollFooter:Drawable = this.mOverScrollFooter;
const drawOverscrollHeader:boolean = overscrollHeader != null;
const drawOverscrollFooter:boolean = overscrollFooter != null;
const drawDividers:boolean = dividerHeight > 0 && this.mDivider != null;
if (drawDividers || drawOverscrollHeader || drawOverscrollFooter) {
// Only modify the top and bottom in the loop, we set the left and right here
const bounds:Rect = this.mTempRect;
bounds.left = this.mPaddingLeft;
bounds.right = this.mRight - this.mLeft - this.mPaddingRight;
const count:number = this.getChildCount();
const headerCount:number = this.mHeaderViewInfos.size();
const itemCount:number = this.mItemCount;
const footerLimit:number = (itemCount - this.mFooterViewInfos.size());
const headerDividers:boolean = this.mHeaderDividersEnabled;
const footerDividers:boolean = this.mFooterDividersEnabled;
const first:number = this.mFirstPosition;
const areAllItemsSelectable:boolean = this.mAreAllItemsSelectable;
const adapter:ListAdapter = this.mAdapter;
// If the list is opaque *and* the background is not, we want to
// fill a rect where the dividers would be for non-selectable items
// If the list is opaque and the background is also opaque, we don't
// need to draw anything since the background will do it for us
const fillForMissingDividers:boolean = this.isOpaque() && !super.isOpaque();
if (fillForMissingDividers && this.mDividerPaint == null && this.mIsCacheColorOpaque) {
this.mDividerPaint = new Paint();
this.mDividerPaint.setColor(this.getCacheColorHint());
}
const paint:Paint = this.mDividerPaint;
let effectivePaddingTop:number = 0;
let effectivePaddingBottom:number = 0;
if ((this.mGroupFlags & ListView.CLIP_TO_PADDING_MASK) == ListView.CLIP_TO_PADDING_MASK) {
effectivePaddingTop = this.mListPadding.top;
effectivePaddingBottom = this.mListPadding.bottom;
}
const listBottom:number = this.mBottom - this.mTop - effectivePaddingBottom + this.mScrollY;
if (!this.mStackFromBottom) {
let bottom:number = 0;
// Draw top divider or header for overscroll
const scrollY:number = this.mScrollY;
if (count > 0 && scrollY < 0) {
if (drawOverscrollHeader) {
bounds.bottom = 0;
bounds.top = scrollY;
this.drawOverscrollHeader(canvas, overscrollHeader, bounds);
} else if (drawDividers) {
bounds.bottom = 0;
bounds.top = -dividerHeight;
this.drawDivider(canvas, bounds, -1);
}
}
for (let i:number = 0; i < count; i++) {
const itemIndex:number = (first + i);
const isHeader:boolean = (itemIndex < headerCount);
const isFooter:boolean = (itemIndex >= footerLimit);
if ((headerDividers || !isHeader) && (footerDividers || !isFooter)) {
const child:View = this.getChildAt(i);
bottom = child.getBottom();
const isLastItem:boolean = (i == (count - 1));
if (drawDividers && (bottom < listBottom) && !(drawOverscrollFooter && isLastItem)) {
const nextIndex:number = (itemIndex + 1);
// footers when enabled, and the end of the list.
if (areAllItemsSelectable || ((adapter.isEnabled(itemIndex) || (headerDividers && isHeader) || (footerDividers && isFooter)) && (isLastItem || adapter.isEnabled(nextIndex) || (headerDividers && (nextIndex < headerCount)) || (footerDividers && (nextIndex >= footerLimit))))) {
bounds.top = bottom;
bounds.bottom = bottom + dividerHeight;
this.drawDivider(canvas, bounds, i);
} else if (fillForMissingDividers) {
bounds.top = bottom;
bounds.bottom = bottom + dividerHeight;
canvas.drawRect(bounds, paint);
}
}
}
}
const overFooterBottom:number = this.mBottom + this.mScrollY;
if (drawOverscrollFooter && first + count == itemCount && overFooterBottom > bottom) {
bounds.top = bottom;
bounds.bottom = overFooterBottom;
this.drawOverscrollFooter(canvas, overscrollFooter, bounds);
}
} else {
let top:number;
const scrollY:number = this.mScrollY;
if (count > 0 && drawOverscrollHeader) {
bounds.top = scrollY;
bounds.bottom = this.getChildAt(0).getTop();
this.drawOverscrollHeader(canvas, overscrollHeader, bounds);
}
const start:number = drawOverscrollHeader ? 1 : 0;
for (let i:number = start; i < count; i++) {
const itemIndex:number = (first + i);
const isHeader:boolean = (itemIndex < headerCount);
const isFooter:boolean = (itemIndex >= footerLimit);
if ((headerDividers || !isHeader) && (footerDividers || !isFooter)) {
const child:View = this.getChildAt(i);
top = child.getTop();
if (drawDividers && (top > effectivePaddingTop)) {
const isFirstItem:boolean = (i == start);
const previousIndex:number = (itemIndex - 1);
// footers when enabled, and the end of the list.
if (areAllItemsSelectable || ((adapter.isEnabled(itemIndex) || (headerDividers && isHeader) || (footerDividers && isFooter)) && (isFirstItem || adapter.isEnabled(previousIndex) || (headerDividers && (previousIndex < headerCount)) || (footerDividers && (previousIndex >= footerLimit))))) {
bounds.top = top - dividerHeight;
bounds.bottom = top;
// Give the method the child ABOVE the divider,
// so we subtract one from our child position.
// Give -1 when there is no child above the
// divider.
this.drawDivider(canvas, bounds, i - 1);
} else if (fillForMissingDividers) {
bounds.top = top - dividerHeight;
bounds.bottom = top;
canvas.drawRect(bounds, paint);
}
}
}
}
if (count > 0 && scrollY > 0) {
if (drawOverscrollFooter) {
const absListBottom:number = this.mBottom;
bounds.top = absListBottom;
bounds.bottom = absListBottom + scrollY;
this.drawOverscrollFooter(canvas, overscrollFooter, bounds);
} else if (drawDividers) {
bounds.top = listBottom;
bounds.bottom = listBottom + dividerHeight;
this.drawDivider(canvas, bounds, -1);
}
}
}
}
// Draw the indicators (these should be drawn above the dividers) and children
super.dispatchDraw(canvas);
}
protected drawChild(canvas:Canvas, child:View, drawingTime:number):boolean {
let more:boolean = super.drawChild(canvas, child, drawingTime);
if (this.mCachingActive && child.mCachingFailed) {
this.mCachingActive = false;
}
return more;
}
/**
* Draws a divider for the given child in the given bounds.
*
* @param canvas The canvas to draw to.
* @param bounds The bounds of the divider.
* @param childIndex The index of child (of the View) above the divider.
* This will be -1 if there is no child above the divider to be
* drawn.
*/
drawDivider(canvas:Canvas, bounds:Rect, childIndex:number):void {
// This widget draws the same divider for all children
const divider:Drawable = this.mDivider;
divider.setBounds(bounds);
divider.draw(canvas);
}
/**
* Returns the drawable that will be drawn between each item in the list.
*
* @return the current drawable drawn between list elements
*/
getDivider():Drawable {
return this.mDivider;
}
/**
* Sets the drawable that will be drawn between each item in the list. If the drawable does
* not have an intrinsic height, you should also call {@link #setDividerHeight(int)}
*
* @param divider The drawable to use.
*/
setDivider(divider:Drawable):void {
if (divider != null) {
this.mDividerHeight = divider.getIntrinsicHeight();
} else {
this.mDividerHeight = 0;
}
this.mDivider = divider;
this.mDividerIsOpaque = divider == null || divider.getOpacity() == PixelFormat.OPAQUE;
this.requestLayout();
this.invalidate();
}
/**
* @return Returns the height of the divider that will be drawn between each item in the list.
*/
getDividerHeight():number {
return this.mDividerHeight;
}
/**
* Sets the height of the divider that will be drawn between each item in the list. Calling
* this will override the intrinsic height as set by {@link #setDivider(Drawable)}
*
* @param height The new height of the divider in pixels.
*/
setDividerHeight(height:number):void {
this.mDividerHeight = height;
this.requestLayout();
this.invalidate();
}
/**
* Enables or disables the drawing of the divider for header views.
*
* @param headerDividersEnabled True to draw the headers, false otherwise.
*
* @see #setFooterDividersEnabled(boolean)
* @see #areHeaderDividersEnabled()
* @see #addHeaderView(android.view.View)
*/
setHeaderDividersEnabled(headerDividersEnabled:boolean):void {
this.mHeaderDividersEnabled = headerDividersEnabled;
this.invalidate();
}
/**
* @return Whether the drawing of the divider for header views is enabled
*
* @see #setHeaderDividersEnabled(boolean)
*/
areHeaderDividersEnabled():boolean {
return this.mHeaderDividersEnabled;
}
/**
* Enables or disables the drawing of the divider for footer views.
*
* @param footerDividersEnabled True to draw the footers, false otherwise.
*
* @see #setHeaderDividersEnabled(boolean)
* @see #areFooterDividersEnabled()
* @see #addFooterView(android.view.View)
*/
setFooterDividersEnabled(footerDividersEnabled:boolean):void {
this.mFooterDividersEnabled = footerDividersEnabled;
this.invalidate();
}
/**
* @return Whether the drawing of the divider for footer views is enabled
*
* @see #setFooterDividersEnabled(boolean)
*/
areFooterDividersEnabled():boolean {
return this.mFooterDividersEnabled;
}
/**
* Sets the drawable that will be drawn above all other list content.
* This area can become visible when the user overscrolls the list.
*
* @param header The drawable to use
*/
setOverscrollHeader(header:Drawable):void {
this.mOverScrollHeader = header;
if (this.mScrollY < 0) {
this.invalidate();
}
}
/**
* @return The drawable that will be drawn above all other list content
*/
getOverscrollHeader():Drawable {
return this.mOverScrollHeader;
}
/**
* Sets the drawable that will be drawn below all other list content.
* This area can become visible when the user overscrolls the list,
* or when the list's content does not fully fill the container area.
*
* @param footer The drawable to use
*/
setOverscrollFooter(footer:Drawable):void {
this.mOverScrollFooter = footer;
this.invalidate();
}
/**
* @return The drawable that will be drawn below all other list content
*/
getOverscrollFooter():Drawable {
return this.mOverScrollFooter;
}
onFocusChanged(gainFocus:boolean, direction:number, previouslyFocusedRect:Rect):void {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
const adapter:ListAdapter = this.mAdapter;
let closetChildIndex:number = -1;
let closestChildTop:number = 0;
if (adapter != null && gainFocus && previouslyFocusedRect != null) {
previouslyFocusedRect.offset(this.mScrollX, this.mScrollY);
// it could change in layoutChildren.
if (adapter.getCount() < this.getChildCount() + this.mFirstPosition) {
this.mLayoutMode = ListView.LAYOUT_NORMAL;
this.layoutChildren();
}
// figure out which item should be selected based on previously
// focused rect
let otherRect:Rect = this.mTempRect;
let minDistance:number = Integer.MAX_VALUE;
const childCount:number = this.getChildCount();
const firstPosition:number = this.mFirstPosition;
for (let i:number = 0; i < childCount; i++) {
// only consider selectable views
if (!adapter.isEnabled(firstPosition + i)) {
continue;
}
let other:View = this.getChildAt(i);
other.getDrawingRect(otherRect);
this.offsetDescendantRectToMyCoords(other, otherRect);
let distance:number = ListView.getDistance(previouslyFocusedRect, otherRect, direction);
if (distance < minDistance) {
minDistance = distance;
closetChildIndex = i;
closestChildTop = other.getTop();
}
}
}
if (closetChildIndex >= 0) {
this.setSelectionFromTop(closetChildIndex + this.mFirstPosition, closestChildTop);
} else {
this.requestLayout();
}
}
/*
* (non-Javadoc)
*
* Children specified in XML are assumed to be header views. After we have
* parsed them move them out of the children list and into mHeaderViews.
*/
protected onFinishInflate():void {
super.onFinishInflate();
let count:number = this.getChildCount();
if (count > 0) {
for (let i:number = 0; i < count; ++i) {
this.addHeaderView(this.getChildAt(i));
}
this.removeAllViews();
}
}
/* (non-Javadoc)
* @see android.view.View#findViewById(int)
* First look in our children, then in any header and footer views that may be scrolled off.
*/
protected findViewTraversal(id:string):View {
let v:View;
v = super.findViewTraversal(id);
if (v == null) {
v = this.findViewInHeadersOrFooters(this.mHeaderViewInfos, id);
if (v != null) {
return v;
}
v = this.findViewInHeadersOrFooters(this.mFooterViewInfos, id);
if (v != null) {
return v;
}
}
return v;
}
/* (non-Javadoc)
*
* Look in the passed in list of headers or footers for the view.
*/
findViewInHeadersOrFooters(where:ArrayList<ListView.FixedViewInfo>, id:string):View {
if (where != null) {
let len:number = where.size();
let v:View;
for (let i:number = 0; i < len; i++) {
v = where.get(i).view;
if (!v.isRootNamespace()) {
v = v.findViewById(id);
if (v != null) {
return v;
}
}
}
}
return null;
}
/* (non-Javadoc)
* @see android.view.View#findViewWithTag(Object)
* First look in our children, then in any header and footer views that may be scrolled off.
*/
//findViewWithTagTraversal(tag:any):View {
// let v:View;
// v = super.findViewWithTagTraversal(tag);
// if (v == null) {
// v = this.findViewWithTagInHeadersOrFooters(this.mHeaderViewInfos, tag);
// if (v != null) {
// return v;
// }
// v = this.findViewWithTagInHeadersOrFooters(this.mFooterViewInfos, tag);
// if (v != null) {
// return v;
// }
// }
// return v;
//}
/* (non-Javadoc)
*
* Look in the passed in list of headers or footers for the view with the tag.
*/
//findViewWithTagInHeadersOrFooters(where:ArrayList<ListView.FixedViewInfo>, tag:any):View {
// if (where != null) {
// let len:number = where.size();
// let v:View;
// for (let i:number = 0; i < len; i++) {
// v = where.get(i).view;
// if (!v.isRootNamespace()) {
// v = v.findViewWithTag(tag);
// if (v != null) {
// return v;
// }
// }
// }
// }
// return null;
//}
/**
* @hide
* @see android.view.View#findViewByPredicate(Predicate)
* First look in our children, then in any header and footer views that may be scrolled off.
*/
protected findViewByPredicateTraversal(predicate:View.Predicate<View>, childToSkip:View):View {
let v:View;
v = super.findViewByPredicateTraversal(predicate, childToSkip);
if (v == null) {
v = this.findViewByPredicateInHeadersOrFooters(this.mHeaderViewInfos, predicate, childToSkip);
if (v != null) {
return v;
}
v = this.findViewByPredicateInHeadersOrFooters(this.mFooterViewInfos, predicate, childToSkip);
if (v != null) {
return v;
}
}
return v;
}
/* (non-Javadoc)
*
* Look in the passed in list of headers or footers for the first view that matches
* the predicate.
*/
findViewByPredicateInHeadersOrFooters(where:ArrayList<ListView.FixedViewInfo>, predicate:View.Predicate<View>, childToSkip:View):View {
if (where != null) {
let len:number = where.size();
let v:View;
for (let i:number = 0; i < len; i++) {
v = where.get(i).view;
if (v != childToSkip && !v.isRootNamespace()) {
v = v.findViewByPredicate(predicate);
if (v != null) {
return v;
}
}
}
}
return null;
}
/**
* Returns the set of checked items ids. The result is only valid if the
* choice mode has not been set to {@link #CHOICE_MODE_NONE}.
*
* @return A new array which contains the id of each checked item in the
* list.
*
* @deprecated Use {@link #getCheckedItemIds()} instead.
*/
getCheckItemIds():number[] {
// Use new behavior that correctly handles stable ID mapping.
if (this.mAdapter != null && this.mAdapter.hasStableIds()) {
return this.getCheckedItemIds();
}
// Fall back to it to support legacy apps.
if (this.mChoiceMode != ListView.CHOICE_MODE_NONE && this.mCheckStates != null && this.mAdapter != null) {
const states:SparseBooleanArray = this.mCheckStates;
const count:number = states.size();
const ids:number[] = androidui.util.ArrayCreator.newNumberArray(count);
const adapter:ListAdapter = this.mAdapter;
let checkedCount:number = 0;
for (let i:number = 0; i < count; i++) {
if (states.valueAt(i)) {
ids[checkedCount++] = adapter.getItemId(states.keyAt(i));
}
}
// resulting in checkedCount being smaller than count.
if (checkedCount == count) {
return ids;
} else {
const result:number[] = androidui.util.ArrayCreator.newNumberArray(checkedCount);
System.arraycopy(ids, 0, result, 0, checkedCount);
return result;
}
}
return androidui.util.ArrayCreator.newNumberArray(0);
}
//onInitializeAccessibilityEvent(event:AccessibilityEvent):void {
// super.onInitializeAccessibilityEvent(event);
// event.setClassName(ListView.class.getName());
//}
//
//onInitializeAccessibilityNodeInfo(info:AccessibilityNodeInfo):void {
// super.onInitializeAccessibilityNodeInfo(info);
// info.setClassName(ListView.class.getName());
// const count:number = this.getCount();
// const collectionInfo:CollectionInfo = CollectionInfo.obtain(1, count, false);
// info.setCollectionInfo(collectionInfo);
//}
//
//onInitializeAccessibilityNodeInfoForItem(view:View, position:number, info:AccessibilityNodeInfo):void {
// super.onInitializeAccessibilityNodeInfoForItem(view, position, info);
// const lp:LayoutParams = <LayoutParams> view.getLayoutParams();
// const isHeading:boolean = lp != null && lp.viewType != ListView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER;
// const itemInfo:CollectionItemInfo = CollectionItemInfo.obtain(0, 1, position, 1, isHeading);
// info.setCollectionItemInfo(itemInfo);
//}
}
export module ListView{
/**
* A class that represents a fixed view in a list, for example a header at the top
* or a footer at the bottom.
*/
export class FixedViewInfo {
_ListView_this:ListView;
constructor(arg:ListView){
this._ListView_this = arg;
}
/** The view to add to the list */
view:View;
/** The data backing the view. This is returned from {@link ListAdapter#getItem(int)}. */
data:any;
/** <code>true</code> if the fixed view should be selectable in the list */
isSelectable:boolean;
}
export class FocusSelector implements Runnable {
_ListView_this:ListView;
constructor(arg:ListView){
this._ListView_this = arg;
}
private mPosition:number = 0;
private mPositionTop:number = 0;
setup(position:number, top:number):ListView.FocusSelector {
this.mPosition = position;
this.mPositionTop = top;
return this;
}
run():void {
this._ListView_this.setSelectionFromTop(this.mPosition, this.mPositionTop);
}
}
/**
* Holds results of focus aware arrow scrolling.
*/
export class ArrowScrollFocusResult {
private mSelectedPosition:number = 0;
private mAmountToScroll:number = 0;
/**
* How {@link android.widget.ListView#arrowScrollFocused} returns its values.
*/
populate(selectedPosition:number, amountToScroll:number):void {
this.mSelectedPosition = selectedPosition;
this.mAmountToScroll = amountToScroll;
}
getSelectedPosition():number {
return this.mSelectedPosition;
}
getAmountToScroll():number {
return this.mAmountToScroll;
}
}
}
} | the_stack |
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit, ViewChildren, QueryList, ChangeDetectorRef } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { forkJoin as observableForkJoin, fromEvent, Observable, Subject } from 'rxjs';
import {ConfigureTableService} from '../../service/configure-table.service';
import {ClusterMetaDataService} from '../../service/cluster-metadata.service';
import {ColumnMetadata} from '../../model/column-metadata';
import {ColumnNamesService} from '../../service/column-names.service';
import {ColumnNames} from '../../model/column-names';
import {SearchService} from '../../service/search.service';
import { debounceTime } from 'rxjs/operators';
import { DragulaService } from 'ng2-dragula';
export enum AlertState {
NEW, OPEN, ESCALATE, DISMISS, RESOLVE
}
export class ColumnMetadataWrapper {
columnMetadata: ColumnMetadata;
displayName: string;
selected: boolean;
constructor(columnMetadata: ColumnMetadata, selected: boolean, displayName: string) {
this.columnMetadata = columnMetadata;
this.selected = selected;
this.displayName = displayName;
}
}
@Component({
selector: 'app-configure-table',
templateUrl: './configure-table.component.html',
styleUrls: ['./configure-table.component.scss']
})
export class ConfigureTableComponent implements OnInit, AfterViewInit {
@ViewChild('columnFilterInput') columnFilterInput: ElementRef;
@ViewChildren('moveColUpBtn') moveColUpBtn: QueryList<ElementRef>;
columnHeaders: string;
allColumns$: Subject<ColumnMetadataWrapper[]> = new Subject<ColumnMetadataWrapper[]>();
visibleColumns$: Observable<ColumnMetadataWrapper[]>;
availableColumns$: Observable<ColumnMetadataWrapper[]>;
visibleColumns: ColumnMetadataWrapper[] = [];
availableColumns: ColumnMetadataWrapper[] = [];
filteredColumns: ColumnMetadataWrapper[] = [];
constructor(
private router: Router, private activatedRoute: ActivatedRoute,
private configureTableService: ConfigureTableService,
private clusterMetaDataService: ClusterMetaDataService,
private columnNamesService: ColumnNamesService,
private searchService: SearchService,
private dragulaService: DragulaService,
private cdRef: ChangeDetectorRef
) {
if (!dragulaService.find('configure-table')) {
dragulaService.setOptions('configure-table', {
/**
* In the list of alerts there can be certain items which should not be allowed to be dragged.
* This is a simple solution where you can prevent items from being dragged by adding the
* out-of-dragula class on the list item in the html template.
*
* Reference: https://github.com/bevacqua/dragula#optionsmoves
*/
moves(el: HTMLElement) {
return !(el.classList.contains('out-of-dragula'));
},
/**
* This is the same as above but it's about not allowing an element to be a drop target.
*
* Reference: https://github.com/bevacqua/dragula#optionsaccepts
*/
accepts(el, target, source, sibling) {
if (!sibling) {
return true;
}
return !(sibling.classList.contains('out-of-dragula'));
}
});
}
/**
*
* I cannot rely on dragula's internal syncing mechanism because it doesn't force angular to re-render
* the component. But it's vital here because the state of the list items changes after changing the order
* (e.g the user is also able to reorder the list by clicking on the arrows on the right).
*
* That's why I'm subscribing the drop event here and rearrange the array manually.
*
* References:
* https://github.com/bevacqua/dragula#drakeon-events
*
* params[0] {String} - groupName (the name of the dragula group)
* params[1] {HTMLElement} - el (the dragged element)
* params[2] {HTMLElement} - target (the target container)
* params[3] {HTMLElement} - source (the source container)
* params[4] {HTMLElement} - sibling (after dropping the dragged element, this is the following element)
*/
dragulaService.drop.subscribe((params: any[]) => {
const el = params[1] as HTMLElement;
const elIndex = +el.dataset.index;
const colToMove = this.visibleColumns[elIndex];
const cols = this.visibleColumns.filter((item, i) => i !== elIndex);
const sibling = params[4] as HTMLElement;
/**
* if there's no sibling, it means that the user is moving the item to the end of the list
*/
if (!sibling) {
this.visibleColumns = [
...cols,
colToMove
];
} else {
const siblingIndex = +sibling.dataset.index;
/**
* if the index of the sibling is 0, it means that the user is moving the item to the
* beginning of the list
*/
if (siblingIndex === 0) {
this.visibleColumns = [
colToMove,
...cols
];
} else {
/**
* Otherwise I'm putting the element in the appropriate place within the array
* by applying a simple reduce function to rearrange the array items.
*/
this.visibleColumns = cols.reduce((acc, item, i) => {
if (elIndex < siblingIndex) { // if the dragged element took place before the new sibling originally
if (i === siblingIndex - 1) {
acc.push(colToMove);
}
} else { // if the dragged element took place after the new sibling originally
if (i === siblingIndex) {
acc.push(colToMove);
}
}
acc.push(item);
return acc;
}, []);
}
}
});
}
goBack() {
this.router.navigateByUrl('/alerts-list');
return false;
}
indexOf(columnMetadata: ColumnMetadata, configuredColumns: ColumnMetadata[]): number {
for (let i = 0; i < configuredColumns.length; i++) {
if (configuredColumns[i].name === columnMetadata.name) {
return i;
}
}
}
indexToInsert(columnMetadata: ColumnMetadata, allColumns: ColumnMetadata[], configuredColumnNames: string[]): number {
let i = 0;
for ( ; i < allColumns.length; i++) {
if (configuredColumnNames.indexOf(allColumns[i].name) === -1 && columnMetadata.name.localeCompare(allColumns[i].name) === -1 ) {
break;
}
}
return i;
}
ngOnInit() {
observableForkJoin(
this.clusterMetaDataService.getDefaultColumns(),
this.searchService.getColumnMetaData(),
this.configureTableService.getTableMetadata()
).subscribe((response: any) => {
const allColumns = this.prepareData(response[0], response[1], response[2].tableColumns);
this.visibleColumns = allColumns.filter(column => column.selected);
this.availableColumns = allColumns.filter(column => !column.selected);
this.filteredColumns = this.availableColumns;
});
}
ngAfterViewInit() {
fromEvent(this.columnFilterInput.nativeElement, 'keyup')
.pipe(debounceTime(250))
.subscribe(e => {
this.filterColumns(e['target'].value);
});
}
filterColumns(val: string) {
const words = val.trim().split(' ');
this.filteredColumns = this.availableColumns.filter(col => {
return !this.isColMissingFilterKeyword(words, col);
});
}
isColMissingFilterKeyword(words: string[], col: ColumnMetadataWrapper) {
return !words.every(word => col.columnMetadata.name.toLowerCase().includes(word.toLowerCase()));
}
clearFilter() {
this.columnFilterInput.nativeElement.value = '';
this.filteredColumns = this.availableColumns;
}
/* Slight variation of insertion sort with bucketing the items in the display order*/
prepareData(defaultColumns: ColumnMetadata[], allColumns: ColumnMetadata[], savedColumns: ColumnMetadata[]): ColumnMetadataWrapper[] {
let configuredColumns: ColumnMetadata[] = (savedColumns && savedColumns.length > 0) ? savedColumns : defaultColumns;
let configuredColumnNames: string[] = configuredColumns.map((mData: ColumnMetadata) => mData.name);
allColumns = allColumns.filter((mData: ColumnMetadata) => configuredColumnNames.indexOf(mData.name) === -1);
allColumns = allColumns.sort(this.defaultColumnSorter);
let sortedConfiguredColumns = JSON.parse(JSON.stringify(configuredColumns));
sortedConfiguredColumns = sortedConfiguredColumns.sort((mData1: ColumnMetadata, mData2: ColumnMetadata) => {
return mData1.name.localeCompare(mData2.name);
});
while (configuredColumns.length > 0 ) {
let columnMetadata = sortedConfiguredColumns.shift();
let index = this.indexOf(columnMetadata, configuredColumns);
let itemsToInsert: any[] = configuredColumns.splice(0, index + 1);
let indexInAll = this.indexToInsert(columnMetadata, allColumns, configuredColumnNames);
allColumns.splice.apply(allColumns, [indexInAll, 0].concat(itemsToInsert));
}
return allColumns.map(mData => {
return new ColumnMetadataWrapper(mData, configuredColumnNames.indexOf(mData.name) > -1,
ColumnNamesService.columnNameToDisplayValueMap[mData.name]);
});
this.filteredColumns = this.availableColumns;
}
private defaultColumnSorter(col1: ColumnMetadata, col2: ColumnMetadata): number {
return col1.name.localeCompare(col2.name);
}
postSave() {
this.configureTableService.fireTableChanged();
this.goBack();
}
save() {
this.configureTableService.saveColumnMetaData(
this.visibleColumns.map(columnMetaWrapper => columnMetaWrapper.columnMetadata))
.subscribe(() => {
this.saveColumnNames();
}, error => {
console.log('Unable to save column preferences ...');
this.saveColumnNames();
});
}
saveColumnNames() {
let columnNames = this.visibleColumns.map(mDataWrapper => {
return new ColumnNames(mDataWrapper.columnMetadata.name, mDataWrapper.displayName);
});
this.columnNamesService.save(columnNames).subscribe(() => {
this.postSave();
}, error => {
console.log('Unable to column names ...');
this.postSave();
});
}
onColumnAdded(column: ColumnMetadataWrapper) {
this.markColumn(column);
this.swapList(column, this.availableColumns, this.visibleColumns);
this.filterColumns(this.columnFilterInput.nativeElement.value);
}
onColumnRemoved(column: ColumnMetadataWrapper) {
this.markColumn(column);
this.swapList(column, this.visibleColumns, this.availableColumns);
this.filterColumns(this.columnFilterInput.nativeElement.value);
}
private markColumn(column: ColumnMetadataWrapper) {
column.selected = !column.selected;
}
private swapList(column: ColumnMetadataWrapper,
source: ColumnMetadataWrapper[],
target: ColumnMetadataWrapper[]) {
target.push(column);
source.splice(source.indexOf(column), 1);
this.availableColumns.sort((colWrapper1: ColumnMetadataWrapper, colWrapper2: ColumnMetadataWrapper) => {
return this.defaultColumnSorter(colWrapper1.columnMetadata, colWrapper2.columnMetadata)
});
}
swapUp(index: number, event: any) {
const colUpButtons = this.moveColUpBtn.toArray();
if (index > 0) {
[this.visibleColumns[index], this.visibleColumns[index - 1]] = [this.visibleColumns[index - 1], this.visibleColumns[index]];
}
/**
* The default behavior of the browser causes the up arrow button to lose focus
* on enter or space keypress, which differs in behavior when compared to the down arrow button.
* This condition runs change detection (which removes the focus by applying default browser behavior)
* and then re-applies focus to the up arrow.
*/
if (event.type === 'keyup') {
this.cdRef.detectChanges();
colUpButtons[index].nativeElement.focus();
}
}
swapDown(index: number) {
if (index + 1 < this.visibleColumns.length) {
[this.visibleColumns[index], this.visibleColumns[index + 1]] = [this.visibleColumns[index + 1], this.visibleColumns[index]];
}
}
} | the_stack |
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resources/cr_elements/cr_fingerprint/cr_fingerprint_progress_arc.m.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js';
import 'chrome://resources/polymer/v3_0/iron-pages/iron-pages.js';
import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js';
import '../settings_shared_css.js';
import '../site_favicon.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import {CrFingerprintProgressArcElement} from 'chrome://resources/cr_elements/cr_fingerprint/cr_fingerprint_progress_arc.m.js';
import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js';
import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js';
import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {IronA11yAnnouncer} from 'chrome://resources/polymer/v3_0/iron-a11y-announcer/iron-a11y-announcer.js';
import {IronListElement} from 'chrome://resources/polymer/v3_0/iron-list/iron-list.js';
import {afterNextRender, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {loadTimeData} from '../i18n_setup.js';
import {Ctap2Status, Enrollment, EnrollmentResponse, SampleResponse, SampleStatus, SecurityKeysBioEnrollProxy, SecurityKeysBioEnrollProxyImpl,} from './security_keys_browser_proxy.js';
import {SettingsSecurityKeysPinFieldElement} from './security_keys_pin_field.js';
export enum BioEnrollDialogPage {
INITIAL = 'initial',
PIN_PROMPT = 'pinPrompt',
ENROLLMENTS = 'enrollments',
ENROLL = 'enroll',
CHOOSE_NAME = 'chooseName',
ERROR = 'error',
}
interface SettingsSecurityKeysBioEnrollDialogElement {
$: {
arc: CrFingerprintProgressArcElement,
confirmButton: HTMLElement,
dialog: CrDialogElement,
enrollmentList: IronListElement,
enrollmentName: HTMLElement,
pin: SettingsSecurityKeysPinFieldElement,
};
}
const SettingsSecurityKeysBioEnrollDialogElementBase =
WebUIListenerMixin(I18nMixin(PolymerElement));
class SettingsSecurityKeysBioEnrollDialogElement extends
SettingsSecurityKeysBioEnrollDialogElementBase {
static get is() {
return 'settings-security-keys-bio-enroll-dialog';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
cancelButtonDisabled_: Boolean,
cancelButtonVisible_: Boolean,
confirmButtonDisabled_: Boolean,
confirmButtonVisible_: Boolean,
confirmButtonLabel_: String,
deleteInProgress_: Boolean,
/**
* The ID of the element currently shown in the dialog.
*/
dialogPage_: {
type: String,
value: BioEnrollDialogPage.INITIAL,
observer: 'dialogPageChanged_',
},
doneButtonVisible_: Boolean,
/**
* The list of enrollments displayed.
*/
enrollments_: Array,
minPinLength_: Number,
progressArcLabel_: String,
recentEnrollmentName_: String,
enrollmentNameError_: String,
enrollmentNameMaxUtf8Length_: Number,
errorMsg_: String,
};
}
private cancelButtonDisabled_: boolean;
private cancelButtonVisible_: boolean;
private confirmButtonDisabled_: boolean;
private confirmButtonVisible_: boolean;
private confirmButtonLabel_: string;
private deleteInProgress_: boolean;
private dialogPage_: BioEnrollDialogPage;
private doneButtonVisible_: boolean;
private enrollments_: Array<Enrollment>;
private minPinLength_: number;
private progressArcLabel_: string;
private recentEnrollmentName_: string;
private enrollmentNameError_: string|null;
private enrollmentNameMaxUtf8Length_: number;
private errorMsg_: string;
private browserProxy_: SecurityKeysBioEnrollProxy =
SecurityKeysBioEnrollProxyImpl.getInstance();
private maxSamples_: number = -1;
private recentEnrollmentId_: string = '';
private showSetPINButton_: boolean = false;
connectedCallback() {
super.connectedCallback();
afterNextRender(this, function() {
IronA11yAnnouncer.requestAvailability();
});
this.$.dialog.showModal();
this.addWebUIListener(
'security-keys-bio-enroll-error',
(error: string, requiresPINChange = false) =>
this.onError_(error, requiresPINChange));
this.addWebUIListener(
'security-keys-bio-enroll-status',
(response: SampleResponse) => this.onEnrollmentSample_(response));
this.browserProxy_.startBioEnroll().then(([minPinLength]) => {
this.minPinLength_ = minPinLength;
this.dialogPage_ = BioEnrollDialogPage.PIN_PROMPT;
});
}
private fire_(eventName: string, detail?: any) {
this.dispatchEvent(
new CustomEvent(eventName, {bubbles: true, composed: true, detail}));
}
private onError_(error: string, requiresPINChange = false) {
this.errorMsg_ = error;
this.showSetPINButton_ = requiresPINChange;
this.dialogPage_ = BioEnrollDialogPage.ERROR;
}
private submitPIN_() {
// Disable the confirm button to prevent concurrent submissions.
this.confirmButtonDisabled_ = true;
this.$.pin.trySubmit(pin => this.browserProxy_.providePIN(pin))
.then(
() => {
this.browserProxy_.getSensorInfo().then(sensorInfo => {
this.enrollmentNameMaxUtf8Length_ =
sensorInfo.maxTemplateFriendlyName;
// Leave confirm button disabled while enumerating fingerprints.
// It will be re-enabled by dialogPageChanged_() where
// appropriate.
this.showEnrollmentsPage_();
});
},
() => {
// Wrong PIN.
this.confirmButtonDisabled_ = false;
});
}
private onEnrollments_(enrollments: Array<Enrollment>) {
this.enrollments_ =
enrollments.slice().sort((a, b) => a.name.localeCompare(b.name));
this.$.enrollmentList.fire('iron-resize');
this.dialogPage_ = BioEnrollDialogPage.ENROLLMENTS;
}
private dialogPageChanged_() {
switch (this.dialogPage_) {
case BioEnrollDialogPage.INITIAL:
this.cancelButtonVisible_ = true;
this.cancelButtonDisabled_ = false;
this.confirmButtonVisible_ = false;
this.doneButtonVisible_ = false;
break;
case BioEnrollDialogPage.PIN_PROMPT:
this.cancelButtonVisible_ = true;
this.cancelButtonDisabled_ = false;
this.confirmButtonVisible_ = true;
this.confirmButtonLabel_ = this.i18n('continue');
this.confirmButtonDisabled_ = false;
this.doneButtonVisible_ = false;
this.$.pin.focus();
break;
case BioEnrollDialogPage.ENROLLMENTS:
this.cancelButtonVisible_ = false;
this.confirmButtonVisible_ = false;
this.doneButtonVisible_ = true;
break;
case BioEnrollDialogPage.ENROLL:
this.cancelButtonVisible_ = true;
this.cancelButtonDisabled_ = false;
this.confirmButtonVisible_ = false;
this.doneButtonVisible_ = false;
break;
case BioEnrollDialogPage.CHOOSE_NAME:
this.cancelButtonVisible_ = false;
this.confirmButtonVisible_ = true;
this.confirmButtonLabel_ = this.i18n('continue');
this.confirmButtonDisabled_ = !this.recentEnrollmentName_.length;
this.doneButtonVisible_ = false;
this.$.enrollmentName.focus();
break;
case BioEnrollDialogPage.ERROR:
this.cancelButtonVisible_ = true;
this.confirmButtonVisible_ = this.showSetPINButton_;
this.confirmButtonLabel_ = this.i18n('securityKeysSetPinButton');
this.doneButtonVisible_ = false;
break;
default:
assertNotReached();
}
this.fire_('bio-enroll-dialog-ready-for-testing');
}
private addButtonClick_() {
assert(this.dialogPage_ === BioEnrollDialogPage.ENROLLMENTS);
this.maxSamples_ = -1; // Reset maxSamples_ before enrolling starts.
this.$.arc.reset();
this.progressArcLabel_ =
this.i18n('securityKeysBioEnrollmentEnrollingLabel');
this.recentEnrollmentId_ = '';
this.recentEnrollmentName_ = '';
this.dialogPage_ = BioEnrollDialogPage.ENROLL;
this.browserProxy_.startEnrolling().then(response => {
this.onEnrollmentComplete_(response);
});
}
private onEnrollmentSample_(response: SampleResponse) {
if (response.status !== SampleStatus.OK) {
this.progressArcLabel_ =
this.i18n('securityKeysBioEnrollmentTryAgainLabel');
this.fire_('iron-announce', {text: this.progressArcLabel_});
return;
}
this.progressArcLabel_ =
this.i18n('securityKeysBioEnrollmentEnrollingLabel');
assert(response.remaining >= 0);
if (this.maxSamples_ === -1) {
this.maxSamples_ = response.remaining + 1;
}
this.$.arc.setProgress(
100 * (this.maxSamples_ - response.remaining - 1) / this.maxSamples_,
100 * (this.maxSamples_ - response.remaining) / this.maxSamples_,
false);
}
private onEnrollmentComplete_(response: EnrollmentResponse) {
switch (response.code) {
case Ctap2Status.OK:
break;
case Ctap2Status.ERR_KEEPALIVE_CANCEL:
this.showEnrollmentsPage_();
return;
case Ctap2Status.ERR_FP_DATABASE_FULL:
this.onError_(this.i18n('securityKeysBioEnrollmentStorageFullLabel'));
return;
default:
this.onError_(
this.i18n('securityKeysBioEnrollmentEnrollingFailedLabel'));
return;
}
this.maxSamples_ = Math.max(this.maxSamples_, 1);
this.$.arc.setProgress(
100 * (this.maxSamples_ - 1) / this.maxSamples_, 100, true);
assert(response.enrollment);
this.recentEnrollmentId_ = response.enrollment!.id;
this.recentEnrollmentName_ = response.enrollment!.name;
this.cancelButtonVisible_ = false;
this.confirmButtonVisible_ = true;
this.confirmButtonDisabled_ = false;
this.progressArcLabel_ =
this.i18n('securityKeysBioEnrollmentEnrollingCompleteLabel');
this.$.confirmButton.focus();
// Make screen-readers announce enrollment completion.
this.fire_('iron-announce', {text: this.progressArcLabel_});
this.fire_('bio-enroll-dialog-ready-for-testing');
}
private confirmButtonClick_() {
switch (this.dialogPage_) {
case BioEnrollDialogPage.PIN_PROMPT:
this.submitPIN_();
break;
case BioEnrollDialogPage.ENROLL:
assert(!!this.recentEnrollmentId_.length);
this.dialogPage_ = BioEnrollDialogPage.CHOOSE_NAME;
break;
case BioEnrollDialogPage.CHOOSE_NAME:
this.renameNewEnrollment_();
break;
case BioEnrollDialogPage.ERROR:
this.$.dialog.close();
this.fire_('bio-enroll-set-pin');
break;
default:
assertNotReached();
}
}
private renameNewEnrollment_() {
assert(this.dialogPage_ === BioEnrollDialogPage.CHOOSE_NAME);
// Check that the user-provided name doesn't exceed the maximum permissible
// length reported by the security key when encoded as UTF-8. (Note that
// JavaScript String length counts code units, but string length maximums in
// CTAP 2.1 are generally on UTF-8 bytes.)
if (new TextEncoder().encode(this.recentEnrollmentName_).length >
this.enrollmentNameMaxUtf8Length_) {
this.enrollmentNameError_ =
this.i18n('securityKeysBioEnrollmentNameLabelTooLong');
return;
}
this.enrollmentNameError_ = null;
// Disable the confirm button to prevent concurrent submissions. It will
// be re-enabled by dialogPageChanged_() where appropriate.
this.confirmButtonDisabled_ = true;
this.browserProxy_
.renameEnrollment(this.recentEnrollmentId_, this.recentEnrollmentName_)
.then(enrollments => {
this.onEnrollments_(enrollments);
});
}
private showEnrollmentsPage_() {
this.browserProxy_.enumerateEnrollments().then(enrollments => {
this.onEnrollments_(enrollments);
});
}
private cancel_() {
if (this.dialogPage_ === BioEnrollDialogPage.ENROLL) {
// Cancel an ongoing enrollment. Will cause the pending
// enumerateEnrollments() promise to be resolved and proceed to the
// enrollments page.
this.cancelButtonDisabled_ = true;
this.browserProxy_.cancelEnrollment();
} else {
// On any other screen, simply close the dialog.
this.done_();
}
}
private done_() {
this.$.dialog.close();
}
private onDialogClosed_() {
this.browserProxy_.close();
}
private onIronSelect_(e: Event) {
// Prevent this event from bubbling since it is unnecessarily triggering
// the listener within settings-animated-pages.
e.stopPropagation();
}
private deleteEnrollment_(event: {model: {index: number}}) {
if (this.deleteInProgress_) {
return;
}
this.deleteInProgress_ = true;
const enrollment = this.enrollments_[event.model.index];
this.browserProxy_.deleteEnrollment(enrollment.id).then(enrollments => {
this.deleteInProgress_ = false;
this.onEnrollments_(enrollments);
});
}
private onEnrollmentNameInput_() {
this.confirmButtonDisabled_ = !this.recentEnrollmentName_.length;
}
/**
* @return The title string for the current dialog page.
*/
private dialogTitle_(dialogPage: BioEnrollDialogPage): string {
if (dialogPage === BioEnrollDialogPage.ENROLL ||
dialogPage === BioEnrollDialogPage.CHOOSE_NAME) {
return this.i18n('securityKeysBioEnrollmentAddTitle');
}
return this.i18n('securityKeysBioEnrollmentDialogTitle');
}
/**
* @return The header label for the enrollments page.
*/
private enrollmentsHeader_(enrollments: Array<Enrollment>|null): string {
return this.i18n(
enrollments && enrollments.length ?
'securityKeysBioEnrollmentEnrollmentsLabel' :
'securityKeysBioEnrollmentNoEnrollmentsLabel');
}
private isNullOrEmpty_(s: string): boolean {
return s === '' || !s;
}
}
customElements.define(
SettingsSecurityKeysBioEnrollDialogElement.is,
SettingsSecurityKeysBioEnrollDialogElement); | the_stack |
module formFor {
export interface FormForController {
/**
* Returns the validation rules for a specific field.
*
* @param fieldName Unique identifier of collection within model
* @return Validations rules for field (if any have been provided)
*/
getValidationRulesForAttribute(fieldName:string):ValidationRules;
/**
* Collection headers should register themselves using this function in order to be notified of validation errors.
*
* @param fieldName Unique identifier of collection within model
* @return A bind-friendly wrapper object describing the state of the collection
*/
registerCollectionLabel(fieldName:string):BindableCollectionWrapper;
/**
* All form-input children of formFor must register using this function.
*
* @param fieldName Unique identifier of field within model; used to map errors back to input fields
* @return Bindable field wrapper
*/
registerFormField(fieldName:string):BindableFieldWrapper;
/**
* All submitButton children must register with formFor using this function.
*
* @param submitButtonScope $scope of submit button directive
* @return Submit button wrapper
*/
registerSubmitButton(submitButtonScope:ng.IScope):SubmitButtonWrapper;
/**
* Resets errors displayed on the <form> without resetting the form data values.
*/
resetErrors():void;
/**
* Reset validation errors for an individual field.
*
* @param fieldName Field name within formFor data object (ex. billing.address)
*/
resetField(fieldName:string):void;
/**
* Alias to resetErrors.
* @memberof form-for
*/
resetFields():void;
/**
* Manually set a validation error message for a given field.
* This method should only be used when formFor's :validateOn attribute has been set to "manual".
*
* @param fieldName Field name within formFor data object (ex. billing.address)
* @param error Error message to display (or null to clear the visible error)
*/
setFieldError(fieldName:string, error:string):void;
/**
* Form fields created within ngRepeat or ngIf directive should clean up themselves on removal.
*
* @param fieldName Unique identifier of field within model
*/
unregisterFormField(fieldName:string):void;
/*
* Update all registered collection labels with the specified error messages.
* Specified map should be keyed with fieldName and should container user-friendly error strings.
* @param {Object} fieldNameToErrorMap Map of collection names (or paths) to errors
*/
updateCollectionErrors(fieldNameToErrorMap:{[fieldName:string]:string}):void;
/*
* Update all registered form fields with the specified error messages.
* Specified map should be keyed with fieldName and should container user-friendly error strings.
* @param {Object} fieldNameToErrorMap Map of field names (or paths) to errors
*/
updateFieldErrors(fieldNameToErrorMap:{[fieldName:string]:string}):void;
/**
* Force validation for an individual field.
* If the field fails validation an error message will automatically be shown.
*
* @param fieldName Field name within formFor data object (ex. billing.address)
*/
validateField(fieldName:string):void;
/**
* Validate all registered form-fields.
* This method returns a promise that is resolved or rejected with a field to error message map.
*
* @param showErrors Mark fields with errors as invalid (visually) after validation
*/
validateForm(showErrors?:boolean):ng.IPromise<any>;
}
/**
* Controller exposed via the FormFor directive's scope.
*
* <p>Intended for use only by formFor directive and fields (children); this class is not exposed to the $injector.
*
* @param target Object to attach controller methods to
* @param $parse Injector-supplied $parse service
* @param $q Injector-supplied $q service
* @param $scope formFor directive $scope
* @param modelValidator ModelValidator service
* @param formForConfiguration
*/
export function createFormForController(target:any,
$parse:ng.IParseService,
$q:ng.IQService,
$scope:FormForScope,
modelValidator:ModelValidator,
formForConfiguration:FormForConfiguration):FormForController {
var nestedObjectHelper = new NestedObjectHelper($parse);
var promiseUtils = new PromiseUtils($q);
/**
* @inheritDocs
*/
target.getValidationRulesForAttribute= (fieldName:string):Object => {
return modelValidator.getRulesForField(fieldName, $scope.$validationRuleset);
};
/**
* @inheritDocs
*/
target.registerCollectionLabel = (fieldName:string):BindableCollectionWrapper => {
var bindableFieldName:string = nestedObjectHelper.flattenAttribute(fieldName);
var bindableWrapper:BindableCollectionWrapper = {
error: null,
required: modelValidator.isCollectionRequired(fieldName, $scope.$validationRuleset)
};
$scope.collectionLabels[bindableFieldName] = bindableWrapper;
var watcherInitialized = false;
$scope.$watch('formFor.' + fieldName + '.length',
() => {
// The initial $watch should not trigger a visible validation...
if (!watcherInitialized) {
watcherInitialized = true;
} else if (!$scope.validateOn || $scope.validateOn === 'change') {
modelValidator.validateCollection($scope.formFor, fieldName, $scope.$validationRuleset).then(
() => {
$scope.formForStateHelper.setFieldError(bindableFieldName, null);
},
(error:string) => {
$scope.formForStateHelper.setFieldError(bindableFieldName, error);
});
}
});
return bindableWrapper;
};
/**
* @inheritDocs
*/
target.registerFormField = function(fieldName:string):BindableFieldWrapper {
if (!fieldName) {
throw Error('Invalid field name "' + fieldName + '" provided.');
}
var bindableFieldName:string = nestedObjectHelper.flattenAttribute(fieldName);
if ($scope['fields'].hasOwnProperty(bindableFieldName)) {
throw Error('Field "' + fieldName + '" has already been registered. Field names must be unique.');
}
var bindableFieldWrapper:BindableFieldWrapper = {
bindable: null,
disabled: $scope.disable,
error: null,
pristine: true,
required: modelValidator.isFieldRequired(fieldName, $scope.$validationRuleset),
uid: FormForGUID.create()
};
// Store information about this field that we'll need for validation and binding purposes.
// @see Above documentation for $scope.fields
var fieldDatum:FieldDatum = {
bindableWrapper: bindableFieldWrapper,
fieldName: fieldName,
formForStateHelper: $scope.formForStateHelper,
unwatchers: []
};
$scope.fields[bindableFieldName] = fieldDatum;
var getter:ng.ICompiledExpression = $parse(fieldName);
var setter:(context:any, value:any) => any = getter.assign;
// Changes made by our field should be synced back to the form-data model.
fieldDatum.unwatchers.push(
$scope.$watch('fields.' + bindableFieldName + '.bindableWrapper.bindable',
(newValue:any, oldValue:any) => {
// Don't update the value unless it changes; (this prevents us from wiping out the default model value).
if (newValue || newValue != oldValue) {
if (formForConfiguration.autoTrimValues && typeof newValue == 'string') {
newValue = newValue.trim();
}
// Keep the form data object and our bindable wrapper in-sync
setter($scope.formFor, newValue);
}
}));
var formDataWatcherInitialized:boolean;
// Changes made to the form-data model should likewise be synced to the field's bindable model.
// (This is necessary for data that is loaded asynchronously after a form has already been displayed.)
fieldDatum.unwatchers.push(
$scope.$watch('formFor.' + fieldName,
(newValue:any, oldValue:any) => {
// An asynchronous formFor data source should reset any dirty flags.
// A user tabbing in and out of a field also shouldn't be counted as dirty.
// Easiest way to guard against this is to reset the initialization flag.
if (newValue !== fieldDatum.bindableWrapper.bindable ||
oldValue === undefined && newValue === '' ||
newValue === undefined) {
formDataWatcherInitialized = false;
}
fieldDatum.bindableWrapper.bindable = newValue;
if (!$scope.validateOn || $scope.validateOn === 'change') {
target.validateField(fieldName);
}
// Changes in form-data should also trigger validations.
// Validation failures will not be displayed unless the form-field has been marked dirty (changed by user).
// We shouldn't mark our field as dirty when Angular auto-invokes the initial watcher though,
// So we ignore the first invocation...
if (!formDataWatcherInitialized) {
formDataWatcherInitialized = true;
$scope.formForStateHelper.setFieldHasBeenModified(bindableFieldName, false);
}
fieldDatum.bindableWrapper.pristine = !$scope.formForStateHelper.hasFieldBeenModified(bindableFieldName);
}));
return bindableFieldWrapper;
};
/**
* @inheritDocs
*/
target.registerSubmitButton = (submitButtonScope:ng.IScope):SubmitButtonWrapper => {
var bindableWrapper:SubmitButtonWrapper = {
disabled: false
};
$scope.buttons.push(bindableWrapper);
return bindableWrapper;
};
/**
* @inheritDocs
*/
target.resetErrors = () => {
for (var bindableFieldName in $scope.fields) {
// If the field is invalid, we don't want it to appear valid- just pristing.
if ($scope.formForStateHelper.getFieldError(bindableFieldName)) {
$scope.formForStateHelper.setFieldHasBeenModified(bindableFieldName, false);
$scope.fields[bindableFieldName].bindableWrapper.pristine = true;
}
}
$scope.formForStateHelper.setFormSubmitted(false);
$scope.formForStateHelper.resetFieldErrors();
};
/**
* @inheritDocs
*/
target.resetField = (fieldName:string) => {
var bindableFieldName:string = nestedObjectHelper.flattenAttribute(fieldName);
// If the field is invalid, we don't want it to appear valid- just pristing.
if ($scope.formForStateHelper.getFieldError(bindableFieldName)) {
$scope.formForStateHelper.setFieldHasBeenModified(bindableFieldName, false);
$scope.fields[bindableFieldName].bindableWrapper.pristine = true;
}
$scope.formForStateHelper.setFieldError(bindableFieldName, null);
};
/**
* @inheritDocs
*/
target.resetFields = () => {
target.resetErrors();
};
/**
* @inheritDocs
*/
target.setFieldError = (fieldName:string, error:string) => {
var bindableFieldName:string = nestedObjectHelper.flattenAttribute(fieldName);
$scope.formForStateHelper.setFieldHasBeenModified(bindableFieldName, true);
$scope.formForStateHelper.setFieldError(bindableFieldName, error);
};
/**
* @inheritDocs
*/
target.unregisterFormField = (fieldName:string) => {
var bindableFieldName = nestedObjectHelper.flattenAttribute(fieldName);
var formField = $scope.fields[bindableFieldName];
if(formField){
angular.forEach(
formField.unwatchers,
function (unwatch) {
unwatch();
});
}
delete $scope.fields[bindableFieldName];
};
/**
* @inheritDocs
*/
target.updateCollectionErrors = (fieldNameToErrorMap:{[fieldName:string]:string}) => {
angular.forEach($scope.collectionLabels,
(bindableWrapper, bindableFieldName) => {
var error:string = nestedObjectHelper.readAttribute(fieldNameToErrorMap, bindableFieldName);
$scope.formForStateHelper.setFieldError(bindableFieldName, error);
});
};
/**
* @inheritDocs
*/
target.updateFieldErrors = function(fieldNameToErrorMap:{[fieldName:string]:string}):void {
angular.forEach($scope.fields,
function(scope, bindableFieldName):void {
var error:string = nestedObjectHelper.readAttribute(fieldNameToErrorMap, scope.fieldName);
$scope.formForStateHelper.setFieldError(bindableFieldName, error);
});
};
/**
* @inheritDocs
*/
target.validateField = function(fieldName:string):void {
var bindableFieldName = nestedObjectHelper.flattenAttribute(fieldName);
$scope.formForStateHelper.setFieldHasBeenModified(bindableFieldName, true);
// Run validations and store the result keyed by our bindableFieldName for easier subsequent lookup.
if ($scope.$validationRuleset) {
modelValidator.validateField(
$scope.formFor,
fieldName,
$scope.$validationRuleset
).then(
() => {
$scope.formForStateHelper.setFieldError(bindableFieldName, null);
},
(error:string) => {
$scope.formForStateHelper.setFieldError(bindableFieldName, error);
});
}
};
/**
* @inheritDocs
*/
target.validateForm = (showErrors?:boolean):ng.IPromise<any> => {
// Reset errors before starting new validation.
target.updateCollectionErrors({});
target.updateFieldErrors({});
var validateCollectionsPromise:ng.IPromise<any>;
var validateFieldsPromise:ng.IPromise<any>;
if ($scope.$validationRuleset) {
var validationKeys:Array<string> = [];
angular.forEach($scope.fields, (fieldDatum:FieldDatum) => {
validationKeys.push(fieldDatum.fieldName);
});
validateFieldsPromise =
modelValidator.validateFields($scope.formFor, validationKeys, $scope.$validationRuleset);
validateFieldsPromise.then(angular.noop, target.updateFieldErrors);
validationKeys = []; // Reset for below re-use
angular.forEach($scope.collectionLabels,
(bindableWrapper:BindableFieldWrapper, bindableFieldName:string) => {
validationKeys.push(bindableFieldName);
});
validateCollectionsPromise =
modelValidator.validateFields($scope.formFor, validationKeys, $scope.$validationRuleset);
validateCollectionsPromise.then(angular.noop, target.updateCollectionErrors);
} else {
validateCollectionsPromise = promiseUtils.resolve();
validateFieldsPromise = promiseUtils.resolve();
}
var deferred:ng.IDeferred<any> = promiseUtils.defer();
promiseUtils.waitForAll([validateCollectionsPromise, validateFieldsPromise]).then(
deferred.resolve,
(errors:Array<any>) => {
// If all collections are valid (or no collections exist) this will be an empty array.
if (angular.isArray(errors[0]) && errors[0].length === 0) {
errors.splice(0, 1);
}
// Errors won't be shown for clean fields, so mark errored fields as dirty.
if (showErrors) {
angular.forEach(errors, (errorObjectOrArray:any) => {
var flattenedFields:Array<string> = nestedObjectHelper.flattenObjectKeys(errorObjectOrArray);
angular.forEach(flattenedFields, (fieldName:string) => {
var error:any = nestedObjectHelper.readAttribute(errorObjectOrArray, fieldName);
if (error) {
var bindableFieldName:string = nestedObjectHelper.flattenAttribute(fieldName);
$scope.formForStateHelper.setFieldHasBeenModified(bindableFieldName, true);
}
});
});
}
deferred.reject(errors);
});
return deferred.promise;
};
return target;
}
} | the_stack |
import type { Hook } from '@feathersjs/feathers';
import makeDebug from 'debug';
import type { FGraphQLHookOptions } from '../types';
import { getItems } from '../utils/get-items';
import { replaceItems } from '../utils/replace-items';
const debug = makeDebug('fgraphql');
const graphqlActions = ['Query', 'Mutation', 'Subscription'];
/**
* Generate Graphql Resolvers for services
* {@link https://medium.com/@eddyystop/38faee75dd1}
*/
export function fgraphql (
options1: FGraphQLHookOptions
): Hook {
debug('init call');
const { parse, recordType, resolvers, runTime, query } = options1;
let { schema } = options1;
let ourResolvers: any; // will be initialized when hook is first called
const options = Object.assign({}, {
skipHookWhen: (context: any) => !!(context.params || {}).graphql,
inclAllFieldsServer: true,
inclAllFieldsClient: true,
inclAllFields: null, // Will be initialized each hook call.
inclJoinedNames: true,
extraAuthProps: []
}, options1.options || {});
// @ts-ignore
schema = isFunction(schema) ? schema() : schema;
if (!isObject(schema) && !isString(schema)) {
throwError(`Resolved schema is typeof ${typeof schema} rather than string or object. (fgraphql)`, 101);
}
if (!isObject(runTime)) {
throwError(`option runTime is typeof ${typeof runTime} rather than an object. (fgraphql)`, 106);
}
if (!isString(recordType)) {
throwError(`recordType is typeof ${typeof recordType} rather than string. (fgraphql)`, 103);
}
// @ts-ignore
if (!isArray(options.extraAuthProps)) {
// @ts-ignore
throwError(`option extraAuthProps is typeof ${typeof options.extraAuthProps} rather than array. (fgraphql)`, 105);
}
const feathersSdl = isObject(schema) ? schema : convertSdlToFeathersSchemaObject(schema, parse);
debug('schema now in internal form');
// Return the hook.
return (context: any) => {
const contextParams = context.params;
// @ts-ignore
const optSkipHookWhen = options.skipHookWhen;
const skipHookWhen = isFunction(optSkipHookWhen) ? optSkipHookWhen(context) : optSkipHookWhen;
debug(`\n.....hook called. type ${context.type} method ${context.method} resolved skipHookWhen ${skipHookWhen}`);
if (context.params.$populate) return context; // populate or fastJoin are running
if (skipHookWhen) return context;
// @ts-ignore
const q = isFunction(query) ? query(context) : query;
if (!isObject(q)) {
throwError(`Resolved query is typeof ${typeof q} rather than object. (fgraphql)`, 102);
}
if (!ourResolvers) {
// @ts-ignore
ourResolvers = resolvers(context.app, runTime);
debug(`ourResolvers has Types ${Object.keys(ourResolvers)}`);
}
if (!ourResolvers[recordType]) {
throwError(`recordType ${recordType} not found in resolvers. (fgraphql)`, 104);
}
// @ts-ignore
options.inclAllFields = contextParams.provider
// @ts-ignore
? options.inclAllFieldsClient
// @ts-ignore
: options.inclAllFieldsServer;
// @ts-ignore
debug(`inclAllField ${options.inclAllFields}`);
// Build content parameter passed to resolver functions.
const resolverContent: Record<string, any> = {
app: context.app,
provider: contextParams.provider,
user: contextParams.user,
authenticated: contextParams.authenticated,
batchLoaders: {},
cache: {}
};
// @ts-ignore
(options.extraAuthProps || []).forEach((name: any) => {
if (name in contextParams && !(name in resolverContent)) {
resolverContent[name] = contextParams[name];
}
});
// Static values used by fgraphql functions.
const store = {
feathersSdl,
ourResolvers,
options,
resolverContent
};
// Populate data.
const recs = getItems(context);
// @ts-ignore
return processRecords(store, q, recs, recordType)
.then(() => {
replaceItems(context, recs);
return context;
});
};
}
// Process records recursively.
function processRecords (
store: any,
query: any,
recs: any,
type: any,
depth = 0
): any {
if (!recs) return; // Catch no data to populate.
recs = isArray(recs) ? recs : [recs];
debug(`\nvvvvvvvvvv enter ${depth}`);
debug(`processRecords depth ${depth} #recs ${recs.length} Type ${type}`);
const storeOurResolversType = store.ourResolvers[type];
if (!isObject(storeOurResolversType)) {
throwError(`Resolvers for Type ${type} are typeof ${typeof storeOurResolversType} not object. (fgraphql)`, 201);
}
if (!isObject(query)) {
throwError(`query at Type ${type} are typeof ${typeof query} not object. (fgraphql)`, 202);
}
return Promise.all(
recs.map((rec: any, j: any) => processRecord(store, query, depth, rec, type, j))
)
.then(() => {
debug(`^^^^^^^^^^ exit ${depth}\n`);
});
}
// Process the a record.
function processRecord (store: any, query: any, depth: any, rec: any, type: any, j: any): any {
debug(`processRecord rec# ${j} typeof ${typeof rec} Type ${type}`);
if (!rec) return; // Catch any null values from resolvers.
const queryPropNames = Object.keys(query);
const recFieldNamesInQuery: any = [];
const joinedNamesInQuery: any = [];
// Process every query item.
return Promise.all(
queryPropNames.map((fieldName, i) => processRecordQuery(
store, query, depth, rec, fieldName, type, recFieldNamesInQuery, joinedNamesInQuery, j, i)
)
)
.then(() => {
// Retain only record fields selected
debug(`field names found ${recFieldNamesInQuery} joined names ${joinedNamesInQuery}`);
if (recFieldNamesInQuery.length || !store.options.inclAllFields || queryPropNames.includes('_none')) {
// recs[0] may have been created by [rec] so can't replace array elem
Object.keys(rec).forEach(key => {
if (!recFieldNamesInQuery.includes(key) && !joinedNamesInQuery.includes(key)) {
delete rec[key];
}
});
}
// Include joined names in record.
if (store.options.inclJoinedNames && joinedNamesInQuery.length) {
rec._include = joinedNamesInQuery;
}
});
}
// Process one query field for a record.
function processRecordQuery (
store: any, query: any, depth: any, rec: any, fieldName: any, type: any,
recFieldNamesInQuery: any, joinedNamesInQuery: any, j: any, i: any
): any {
debug(`\nprocessRecordQuery rec# ${j} Type ${type} field# ${i} name ${fieldName}`);
// One way to include/exclude rec fields is to give their names a falsey value.
// _args and _none are not record field names but special purpose
if (query[fieldName] && fieldName !== '_args' && fieldName !== '_none') {
if (store.ourResolvers[type][fieldName]) {
joinedNamesInQuery.push(fieldName);
return processRecordFieldResolver(store, query, depth, rec, fieldName, type);
} else {
debug('is not resolver call');
recFieldNamesInQuery.push(fieldName);
}
}
}
// Process a resolver call.
function processRecordFieldResolver (store: any, query: any, depth: any, rec: any, fieldName: any, type: any) {
debug('is resolver call');
const ourQuery = store.feathersSdl[type][fieldName];
const ourResolver = store.ourResolvers[type][fieldName];
if (!isFunction(ourResolver)) {
throwError(`Resolver for Type ${type} fieldName ${fieldName} is typeof ${typeof ourResolver} not function. (fgraphql)`, 203);
}
const args = isObject(query[fieldName]) ? query[fieldName]._args : undefined;
debug(`resolver listType ${ourQuery.listType} args ${JSON.stringify(args)}`);
// Call resolver function.
return Promise.resolve(ourResolver(rec, args || {}, store.resolverContent))
.then(async rawResult => {
debug(`resolver returned typeof ${isArray(rawResult) ? `array #recs ${rawResult.length}` : typeof rawResult}`);
// Convert rawResult to query requirements.
const result = convertResolverResult(rawResult, ourQuery, fieldName, type);
if (isArray(rawResult !== isArray(result) || typeof rawResult !== typeof result)) {
debug(`.....resolver result converted to typeof ${isArray(result) ? `array #recs ${result.length}` : typeof result}`);
}
rec[fieldName] = result;
const nextType = ourQuery.typeof;
debug(`Type ${type} fieldName ${fieldName} next Type ${nextType}`);
// Populate returned records if their query defn has more fields or Types.
// Ignore resolvers returning base values like string.
if (store.ourResolvers[nextType] && isObject(query[fieldName])) {
return processRecords(store, query[fieldName], result, nextType, depth + 1);
} else {
debug('no population of results required');
}
});
}
// Convert result of resolver function to match query field requirements.
function convertResolverResult (result: any, ourQuery: any, fieldName: any, type: any) {
if (result === null || result === undefined) {
return ourQuery.listType ? [] : null;
}
if (ourQuery.listType) {
if (!isArray(result)) return [result];
} else if (isArray(result)) {
if (result.length > 1) {
throwError(`Query listType true. Resolver for Type ${type} fieldName ${fieldName} result is array len ${result.length} (fgraphql)`, 204);
}
return result[0];
}
return result;
}
function convertSdlToFeathersSchemaObject (schemaDefinitionLanguage: any, parse: any) {
const graphQLSchemaObj = parse(schemaDefinitionLanguage);
return convertDocument(graphQLSchemaObj);
}
function convertDocument (ast: any) {
const result: Record<string, any> = {};
if (ast.kind !== 'Document' || !isArray(ast.definitions)) {
throw new Error('Not a valid GraphQL Document.');
}
ast.definitions.forEach((definition: any, definitionIndex: any) => {
const [objectName, converted] = convertObjectTypeDefinition(definition, definitionIndex);
if (objectName) {
result[objectName] = converted;
}
});
return result;
}
function convertObjectTypeDefinition (definition: any, definitionIndex: any) {
const converted: Record<string, any> = {};
if (definition.kind !== 'ObjectTypeDefinition' || !isArray(definition.fields)) {
throw new Error(`Type# ${definitionIndex} is not a valid ObjectTypeDefinition`);
}
const objectTypeName = convertName(definition.name, `Type# ${definitionIndex}`);
if (graphqlActions.includes(objectTypeName)) return [null, null];
definition.fields.forEach((field: any) => {
const [fieldName, fieldDefinition] = convertFieldDefinition(field, `Type ${objectTypeName}`);
converted[fieldName] = fieldDefinition;
});
return [objectTypeName, converted];
}
function convertName (nameObj: any, errDesc?: any) {
if (!isObject(nameObj) || !isString(nameObj.value)) {
throw new Error(`${errDesc} does not have a valid name prop.`);
}
return nameObj.value;
}
function convertFieldDefinition (field: any, errDesc: any) {
if (field.kind !== 'FieldDefinition' || !isObject(field.type)) {
throw new Error(`${errDesc} is not a valid ObjectTypeDefinition`);
}
const fieldName = convertName(field.name, errDesc);
const converted = convertFieldDefinitionType(field.type, errDesc);
converted.inputValues = field.arguments && field.arguments.length !== 0;
return [fieldName, converted];
}
function convertFieldDefinitionType (fieldDefinitionType: any, errDesc: any, converted?: any): any {
converted = converted || { nonNullTypeList: false, listType: false, nonNullTypeField: false, typeof: null };
if (!isObject(fieldDefinitionType)) {
throw new Error(`${errDesc} is not a valid Fielddefinition "type".`);
}
switch (fieldDefinitionType.kind) {
case 'NamedType':
converted.typeof = convertName(fieldDefinitionType.name);
return converted;
case 'NonNullType':
if (fieldDefinitionType.type.kind === 'NamedType') {
converted.nonNullTypeField = true;
} else {
converted.nonNullTypeList = true;
}
return convertFieldDefinitionType(fieldDefinitionType.type, errDesc, converted);
case 'ListType':
converted.listType = true;
return convertFieldDefinitionType(fieldDefinitionType.type, errDesc, converted);
}
}
function throwError (msg: any, code: any) {
const err = new Error(msg);
// @ts-ignore
err.code = code;
throw err;
}
function isObject (obj: any) {
return typeof obj === 'object' && obj !== null;
}
function isString (str: any) {
return typeof str === 'string';
}
function isFunction (func: any) {
return typeof func === 'function';
}
function isArray (array: any) {
return Array.isArray(array);
} | the_stack |
import * as ui from "../../ui";
import * as csx from "../../base/csx";
import * as React from "react";
import * as tab from "./tab";
import { server, cast } from "../../../socket/socketClient";
import * as commands from "../../commands/commands";
import * as utils from "../../../common/utils";
import * as d3 from "d3";
import { Types } from "../../../socket/socketContract";
import * as types from "../../../common/types";
import { IconType } from "../../../common/types";
import * as $ from "jquery";
import * as styles from "../../styles/styles";
import * as onresize from "onresize";
import { Clipboard } from "../../components/clipboard";
import * as typeIcon from "../../components/typeIcon";
import * as gls from "../../base/gls";
import * as typestyle from "typestyle";
import { MarkDown } from "../../markdown/markdown";
const {blackHighlightColor} = styles;
export interface Props extends tab.TabProps {
}
export interface State {
filter?: string;
classes?: types.UMLClass[];
selected?: types.UMLClass;
}
export namespace UmlViewStyles {
export const classNameHeaderSection = typestyle.style({
border: '1px solid grey',
padding: '5px',
/** A nice clickable look */
cursor: 'pointer',
$nest: {
'&:hover': {
textDecoration: 'underline'
}
}
});
export const classMemberSection = typestyle.style({
// Common with header
border: '1px solid grey',
padding: '5px',
cursor: 'pointer',
$nest: {
'&:hover': {
textDecoration: 'underline'
}
},
// To eat top border
marginTop: '-1px'
});
}
export class UmlView extends ui.BaseComponent<Props, State> {
constructor(props: Props) {
super(props);
this.filePath = utils.getFilePathFromUrl(props.url);
this.state = {
filter: '',
classes: [],
selected: null,
};
}
refs: {
[string: string]: any;
root: HTMLDivElement;
graphRoot: HTMLDivElement;
controlRoot: HTMLDivElement;
}
filePath: string;
componentDidMount() {
/**
* Initial load + load on project change
*/
this.loadData();
this.disposible.add(
cast.activeProjectFilePathsUpdated.on(() => {
this.loadData();
})
);
/**
* If a file is selected and it gets edited, reload the file module information
*/
const loadDataDebounced = utils.debounce(this.loadData, 3000);
this.disposible.add(
commands.fileContentsChanged.on((res) => {
if (this.filePath !== res.filePath) return;
loadDataDebounced();
})
);
/**
* Handle focus to inform tab container
*/
const focused = () => {
this.props.onFocused();
}
this.refs.root.addEventListener('focus', focused);
this.disposible.add({
dispose: () => {
this.refs.root.removeEventListener('focus', focused);
}
})
// Listen to tab events
const api = this.props.api;
this.disposible.add(api.resize.on(this.resize));
this.disposible.add(api.focus.on(this.focus));
this.disposible.add(api.save.on(this.save));
this.disposible.add(api.close.on(this.close));
this.disposible.add(api.gotoPosition.on(this.gotoPosition));
// Listen to search tab events
this.disposible.add(api.search.doSearch.on(this.search.doSearch));
this.disposible.add(api.search.hideSearch.on(this.search.hideSearch));
this.disposible.add(api.search.findNext.on(this.search.findNext));
this.disposible.add(api.search.findPrevious.on(this.search.findPrevious));
this.disposible.add(api.search.replaceNext.on(this.search.replaceNext));
this.disposible.add(api.search.replacePrevious.on(this.search.replacePrevious));
this.disposible.add(api.search.replaceAll.on(this.search.replaceAll));
}
render() {
return (
<div
ref="root"
tabIndex={0}
style={csx.extend(csx.vertical, csx.flex, csx.newLayerParent, styles.someChildWillScroll, { color: styles.textColor })}
onKeyPress={this.handleKey}>
<div style={{ overflow: 'hidden', padding: '10px 0px 10px 10px', display: 'flex' }}>
<gls.FlexHorizontal style={{}}>
<gls.Content style={{ minWidth: '150px', maxWidth: '250px', overflow: 'auto' }}>
<typeIcon.SectionHeader text="Classes" />
<gls.SmallVerticalSpace />
{
this.state.classes.length
? this.renderClasses()
: "No classes in file"
}
</gls.Content>
<gls.FlexVertical style={{ marginLeft: '5px', overflow: 'auto' }}>
{
this.state.selected
? this.renderSelectedClass()
: 'Select a class from the left to view its diagram 🌹 🎼'
}
<div style={{ marginTop: '10px', marginRight: '10px' }}>
<hr />
<typeIcon.TypeIconClassDiagramLegend />
</div>
</gls.FlexVertical>
</gls.FlexHorizontal>
</div>
</div>
);
}
renderClasses() {
return this.state.classes.map((c, i) => {
const backgroundColor = this.state.selected && this.state.selected.name === c.name
? blackHighlightColor
: 'transparent';
return (
<div
title={c.name + ' ' + c.location.position.line}
key={i}
style={{ cursor: 'pointer', backgroundColor, paddingTop: '2px', paddingBottom: '2px', paddingLeft: '2px' }}
onClick={() => this.handleClassSelected(c)}>
<typeIcon.DocumentedTypeHeader name={c.name} icon={c.icon} />
</div>
);
});
}
renderSelectedClass() {
const c = this.state.selected;
return <gls.Content style={{ textAlign: 'center' }}>
<code style={{ fontWeight: 'bold' }}>{c.name}</code>
<gls.SmallVerticalSpace />
{this.renderClass(c)}
</gls.Content>
}
renderClass(c: types.UMLClass) {
const renderSection = (section, i) => {
return <div key={i} style={{ border: '1px solid grey', padding: '5px', marginTop: '-1px' }}>
{section}
</div>
}
return (
<gls.Content style={{ textAlign: 'center' }}>
<gls.InlineBlock style={{ paddingTop: '1px' }}>
<div className={UmlViewStyles.classNameHeaderSection} onClick={() => this.handleGotoTypeLocation(c.location)}>
<typeIcon.DocumentedTypeHeader name={c.name} icon={c.icon} />
</div>
{
c.members.map((m, i) => {
return <div key={i} className={UmlViewStyles.classMemberSection} onClick={() => this.handleGotoTypeLocation(m.location)}>
<typeIcon.DocumentedTypeHeader name={m.name} icon={m.icon} visibility={m.visibility} lifetime={m.lifetime} override={!!m.override} />
</div>
})
}
{
!!c.extends &&
<gls.Content>
<code>extends</code>
{this.renderClass(c.extends)}
</gls.Content>
}
</gls.InlineBlock>
</gls.Content>
);
}
handleClassSelected(c: types.UMLClass) {
this.setState({ selected: c });
}
handleGotoTypeLocation(location: types.DocumentedTypeLocation) {
commands.doOpenOrFocusFile.emit({
filePath: location.filePath,
position: location.position
});
}
handleKey = (e: any) => {
let unicode = e.charCode;
if (String.fromCharCode(unicode).toLowerCase() === "r") {
this.loadData();
}
}
filter = () => {
// TODO:
}
loadData = () => {
server.getUmlDiagramForFile({ filePath: this.filePath }).then(res => {
// Preserve selected
let selected = this.state.selected && res.classes.find(c => c.name === this.state.selected.name);
// otherwise auto select first
if (!selected && res.classes.length) {
selected = res.classes[0];
}
this.setState({ classes: res.classes, selected });
this.filter();
})
}
/**
* TAB implementation
*/
resize = () => {
// Not needed
}
focus = () => {
this.refs.root.focus();
}
save = () => {
}
close = () => {
}
gotoPosition = (position: EditorPosition) => {
}
search = {
doSearch: (options: FindOptions) => {
this.setState({ filter: options.query });
},
hideSearch: () => {
this.setState({ filter: '' });
},
findNext: (options: FindOptions) => {
},
findPrevious: (options: FindOptions) => {
},
replaceNext: ({newText}: { newText: string }) => {
},
replacePrevious: ({newText}: { newText: string }) => {
},
replaceAll: ({newText}: { newText: string }) => {
}
}
} | the_stack |
import "@azure/core-paging";
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { RoleAssignments } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { AuthorizationManagementClientContext } from "../authorizationManagementClientContext";
import {
RoleAssignment,
RoleAssignmentsListForSubscriptionNextOptionalParams,
RoleAssignmentsListForSubscriptionOptionalParams,
RoleAssignmentsListForResourceGroupNextOptionalParams,
RoleAssignmentsListForResourceGroupOptionalParams,
RoleAssignmentsListForResourceNextOptionalParams,
RoleAssignmentsListForResourceOptionalParams,
RoleAssignmentsListForScopeNextOptionalParams,
RoleAssignmentsListForScopeOptionalParams,
RoleAssignmentsListForSubscriptionResponse,
RoleAssignmentsListForResourceGroupResponse,
RoleAssignmentsListForResourceResponse,
RoleAssignmentsGetOptionalParams,
RoleAssignmentsGetResponse,
RoleAssignmentCreateParameters,
RoleAssignmentsCreateOptionalParams,
RoleAssignmentsCreateResponse,
RoleAssignmentsDeleteOptionalParams,
RoleAssignmentsDeleteResponse,
RoleAssignmentsValidateOptionalParams,
RoleAssignmentsValidateResponse,
RoleAssignmentsListForScopeResponse,
RoleAssignmentsGetByIdOptionalParams,
RoleAssignmentsGetByIdResponse,
RoleAssignmentsCreateByIdOptionalParams,
RoleAssignmentsCreateByIdResponse,
RoleAssignmentsDeleteByIdOptionalParams,
RoleAssignmentsDeleteByIdResponse,
RoleAssignmentsValidateByIdOptionalParams,
RoleAssignmentsValidateByIdResponse,
RoleAssignmentsListForSubscriptionNextResponse,
RoleAssignmentsListForResourceGroupNextResponse,
RoleAssignmentsListForResourceNextResponse,
RoleAssignmentsListForScopeNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing RoleAssignments operations. */
export class RoleAssignmentsImpl implements RoleAssignments {
private readonly client: AuthorizationManagementClientContext;
/**
* Initialize a new instance of the class RoleAssignments class.
* @param client Reference to the service client
*/
constructor(client: AuthorizationManagementClientContext) {
this.client = client;
}
/**
* List all role assignments that apply to a subscription.
* @param options The options parameters.
*/
public listForSubscription(
options?: RoleAssignmentsListForSubscriptionOptionalParams
): PagedAsyncIterableIterator<RoleAssignment> {
const iter = this.listForSubscriptionPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listForSubscriptionPagingPage(options);
}
};
}
private async *listForSubscriptionPagingPage(
options?: RoleAssignmentsListForSubscriptionOptionalParams
): AsyncIterableIterator<RoleAssignment[]> {
let result = await this._listForSubscription(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listForSubscriptionNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listForSubscriptionPagingAll(
options?: RoleAssignmentsListForSubscriptionOptionalParams
): AsyncIterableIterator<RoleAssignment> {
for await (const page of this.listForSubscriptionPagingPage(options)) {
yield* page;
}
}
/**
* List all role assignments that apply to a resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
public listForResourceGroup(
resourceGroupName: string,
options?: RoleAssignmentsListForResourceGroupOptionalParams
): PagedAsyncIterableIterator<RoleAssignment> {
const iter = this.listForResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listForResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listForResourceGroupPagingPage(
resourceGroupName: string,
options?: RoleAssignmentsListForResourceGroupOptionalParams
): AsyncIterableIterator<RoleAssignment[]> {
let result = await this._listForResourceGroup(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listForResourceGroupNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listForResourceGroupPagingAll(
resourceGroupName: string,
options?: RoleAssignmentsListForResourceGroupOptionalParams
): AsyncIterableIterator<RoleAssignment> {
for await (const page of this.listForResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* List all role assignments that apply to a resource.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceProviderNamespace The namespace of the resource provider.
* @param resourceType The resource type name. For example the type name of a web app is 'sites' (from
* Microsoft.Web/sites).
* @param resourceName The resource name.
* @param options The options parameters.
*/
public listForResource(
resourceGroupName: string,
resourceProviderNamespace: string,
resourceType: string,
resourceName: string,
options?: RoleAssignmentsListForResourceOptionalParams
): PagedAsyncIterableIterator<RoleAssignment> {
const iter = this.listForResourcePagingAll(
resourceGroupName,
resourceProviderNamespace,
resourceType,
resourceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listForResourcePagingPage(
resourceGroupName,
resourceProviderNamespace,
resourceType,
resourceName,
options
);
}
};
}
private async *listForResourcePagingPage(
resourceGroupName: string,
resourceProviderNamespace: string,
resourceType: string,
resourceName: string,
options?: RoleAssignmentsListForResourceOptionalParams
): AsyncIterableIterator<RoleAssignment[]> {
let result = await this._listForResource(
resourceGroupName,
resourceProviderNamespace,
resourceType,
resourceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listForResourceNext(
resourceGroupName,
resourceProviderNamespace,
resourceType,
resourceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listForResourcePagingAll(
resourceGroupName: string,
resourceProviderNamespace: string,
resourceType: string,
resourceName: string,
options?: RoleAssignmentsListForResourceOptionalParams
): AsyncIterableIterator<RoleAssignment> {
for await (const page of this.listForResourcePagingPage(
resourceGroupName,
resourceProviderNamespace,
resourceType,
resourceName,
options
)) {
yield* page;
}
}
/**
* List all role assignments that apply to a scope.
* @param scope The scope of the operation or resource. Valid scopes are: subscription (format:
* '/subscriptions/{subscriptionId}'), resource group (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
* @param options The options parameters.
*/
public listForScope(
scope: string,
options?: RoleAssignmentsListForScopeOptionalParams
): PagedAsyncIterableIterator<RoleAssignment> {
const iter = this.listForScopePagingAll(scope, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listForScopePagingPage(scope, options);
}
};
}
private async *listForScopePagingPage(
scope: string,
options?: RoleAssignmentsListForScopeOptionalParams
): AsyncIterableIterator<RoleAssignment[]> {
let result = await this._listForScope(scope, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listForScopeNext(scope, continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listForScopePagingAll(
scope: string,
options?: RoleAssignmentsListForScopeOptionalParams
): AsyncIterableIterator<RoleAssignment> {
for await (const page of this.listForScopePagingPage(scope, options)) {
yield* page;
}
}
/**
* List all role assignments that apply to a subscription.
* @param options The options parameters.
*/
private _listForSubscription(
options?: RoleAssignmentsListForSubscriptionOptionalParams
): Promise<RoleAssignmentsListForSubscriptionResponse> {
return this.client.sendOperationRequest(
{ options },
listForSubscriptionOperationSpec
);
}
/**
* List all role assignments that apply to a resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
private _listForResourceGroup(
resourceGroupName: string,
options?: RoleAssignmentsListForResourceGroupOptionalParams
): Promise<RoleAssignmentsListForResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listForResourceGroupOperationSpec
);
}
/**
* List all role assignments that apply to a resource.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceProviderNamespace The namespace of the resource provider.
* @param resourceType The resource type name. For example the type name of a web app is 'sites' (from
* Microsoft.Web/sites).
* @param resourceName The resource name.
* @param options The options parameters.
*/
private _listForResource(
resourceGroupName: string,
resourceProviderNamespace: string,
resourceType: string,
resourceName: string,
options?: RoleAssignmentsListForResourceOptionalParams
): Promise<RoleAssignmentsListForResourceResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceProviderNamespace,
resourceType,
resourceName,
options
},
listForResourceOperationSpec
);
}
/**
* Get a role assignment by scope and name.
* @param scope The scope of the operation or resource. Valid scopes are: subscription (format:
* '/subscriptions/{subscriptionId}'), resource group (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
* @param roleAssignmentName The name of the role assignment. It can be any valid GUID.
* @param options The options parameters.
*/
get(
scope: string,
roleAssignmentName: string,
options?: RoleAssignmentsGetOptionalParams
): Promise<RoleAssignmentsGetResponse> {
return this.client.sendOperationRequest(
{ scope, roleAssignmentName, options },
getOperationSpec
);
}
/**
* Create or update a role assignment by scope and name.
* @param scope The scope of the operation or resource. Valid scopes are: subscription (format:
* '/subscriptions/{subscriptionId}'), resource group (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
* @param roleAssignmentName The name of the role assignment. It can be any valid GUID.
* @param parameters Parameters for the role assignment.
* @param options The options parameters.
*/
create(
scope: string,
roleAssignmentName: string,
parameters: RoleAssignmentCreateParameters,
options?: RoleAssignmentsCreateOptionalParams
): Promise<RoleAssignmentsCreateResponse> {
return this.client.sendOperationRequest(
{ scope, roleAssignmentName, parameters, options },
createOperationSpec
);
}
/**
* Delete a role assignment by scope and name.
* @param scope The scope of the operation or resource. Valid scopes are: subscription (format:
* '/subscriptions/{subscriptionId}'), resource group (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
* @param roleAssignmentName The name of the role assignment. It can be any valid GUID.
* @param options The options parameters.
*/
delete(
scope: string,
roleAssignmentName: string,
options?: RoleAssignmentsDeleteOptionalParams
): Promise<RoleAssignmentsDeleteResponse> {
return this.client.sendOperationRequest(
{ scope, roleAssignmentName, options },
deleteOperationSpec
);
}
/**
* Validate a role assignment create or update operation by scope and name.
* @param scope The scope of the operation or resource. Valid scopes are: subscription (format:
* '/subscriptions/{subscriptionId}'), resource group (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
* @param roleAssignmentName The name of the role assignment. It can be any valid GUID.
* @param parameters Parameters for the role assignment.
* @param options The options parameters.
*/
validate(
scope: string,
roleAssignmentName: string,
parameters: RoleAssignmentCreateParameters,
options?: RoleAssignmentsValidateOptionalParams
): Promise<RoleAssignmentsValidateResponse> {
return this.client.sendOperationRequest(
{ scope, roleAssignmentName, parameters, options },
validateOperationSpec
);
}
/**
* List all role assignments that apply to a scope.
* @param scope The scope of the operation or resource. Valid scopes are: subscription (format:
* '/subscriptions/{subscriptionId}'), resource group (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
* @param options The options parameters.
*/
private _listForScope(
scope: string,
options?: RoleAssignmentsListForScopeOptionalParams
): Promise<RoleAssignmentsListForScopeResponse> {
return this.client.sendOperationRequest(
{ scope, options },
listForScopeOperationSpec
);
}
/**
* Get a role assignment by ID.
* @param roleAssignmentId The fully qualified ID of the role assignment including scope, resource
* name, and resource type. Format:
* /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example:
* /subscriptions/<SUB_ID>/resourcegroups/<RESOURCE_GROUP>/providers/Microsoft.Authorization/roleAssignments/<ROLE_ASSIGNMENT_NAME>
* @param options The options parameters.
*/
getById(
roleAssignmentId: string,
options?: RoleAssignmentsGetByIdOptionalParams
): Promise<RoleAssignmentsGetByIdResponse> {
return this.client.sendOperationRequest(
{ roleAssignmentId, options },
getByIdOperationSpec
);
}
/**
* Create or update a role assignment by ID.
* @param roleAssignmentId The fully qualified ID of the role assignment including scope, resource
* name, and resource type. Format:
* /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example:
* /subscriptions/<SUB_ID>/resourcegroups/<RESOURCE_GROUP>/providers/Microsoft.Authorization/roleAssignments/<ROLE_ASSIGNMENT_NAME>
* @param parameters Parameters for the role assignment.
* @param options The options parameters.
*/
createById(
roleAssignmentId: string,
parameters: RoleAssignmentCreateParameters,
options?: RoleAssignmentsCreateByIdOptionalParams
): Promise<RoleAssignmentsCreateByIdResponse> {
return this.client.sendOperationRequest(
{ roleAssignmentId, parameters, options },
createByIdOperationSpec
);
}
/**
* Delete a role assignment by ID.
* @param roleAssignmentId The fully qualified ID of the role assignment including scope, resource
* name, and resource type. Format:
* /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example:
* /subscriptions/<SUB_ID>/resourcegroups/<RESOURCE_GROUP>/providers/Microsoft.Authorization/roleAssignments/<ROLE_ASSIGNMENT_NAME>
* @param options The options parameters.
*/
deleteById(
roleAssignmentId: string,
options?: RoleAssignmentsDeleteByIdOptionalParams
): Promise<RoleAssignmentsDeleteByIdResponse> {
return this.client.sendOperationRequest(
{ roleAssignmentId, options },
deleteByIdOperationSpec
);
}
/**
* Validate a role assignment create or update operation by ID.
* @param roleAssignmentId The fully qualified ID of the role assignment including scope, resource
* name, and resource type. Format:
* /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example:
* /subscriptions/<SUB_ID>/resourcegroups/<RESOURCE_GROUP>/providers/Microsoft.Authorization/roleAssignments/<ROLE_ASSIGNMENT_NAME>
* @param parameters Parameters for the role assignment.
* @param options The options parameters.
*/
validateById(
roleAssignmentId: string,
parameters: RoleAssignmentCreateParameters,
options?: RoleAssignmentsValidateByIdOptionalParams
): Promise<RoleAssignmentsValidateByIdResponse> {
return this.client.sendOperationRequest(
{ roleAssignmentId, parameters, options },
validateByIdOperationSpec
);
}
/**
* ListForSubscriptionNext
* @param nextLink The nextLink from the previous successful call to the ListForSubscription method.
* @param options The options parameters.
*/
private _listForSubscriptionNext(
nextLink: string,
options?: RoleAssignmentsListForSubscriptionNextOptionalParams
): Promise<RoleAssignmentsListForSubscriptionNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listForSubscriptionNextOperationSpec
);
}
/**
* ListForResourceGroupNext
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param nextLink The nextLink from the previous successful call to the ListForResourceGroup method.
* @param options The options parameters.
*/
private _listForResourceGroupNext(
resourceGroupName: string,
nextLink: string,
options?: RoleAssignmentsListForResourceGroupNextOptionalParams
): Promise<RoleAssignmentsListForResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listForResourceGroupNextOperationSpec
);
}
/**
* ListForResourceNext
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceProviderNamespace The namespace of the resource provider.
* @param resourceType The resource type name. For example the type name of a web app is 'sites' (from
* Microsoft.Web/sites).
* @param resourceName The resource name.
* @param nextLink The nextLink from the previous successful call to the ListForResource method.
* @param options The options parameters.
*/
private _listForResourceNext(
resourceGroupName: string,
resourceProviderNamespace: string,
resourceType: string,
resourceName: string,
nextLink: string,
options?: RoleAssignmentsListForResourceNextOptionalParams
): Promise<RoleAssignmentsListForResourceNextResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceProviderNamespace,
resourceType,
resourceName,
nextLink,
options
},
listForResourceNextOperationSpec
);
}
/**
* ListForScopeNext
* @param scope The scope of the operation or resource. Valid scopes are: subscription (format:
* '/subscriptions/{subscriptionId}'), resource group (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
* @param nextLink The nextLink from the previous successful call to the ListForScope method.
* @param options The options parameters.
*/
private _listForScopeNext(
scope: string,
nextLink: string,
options?: RoleAssignmentsListForScopeNextOptionalParams
): Promise<RoleAssignmentsListForScopeNextResponse> {
return this.client.sendOperationRequest(
{ scope, nextLink, options },
listForScopeNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listForSubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RoleAssignmentListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter1,
Parameters.tenantId
],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listForResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RoleAssignmentListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter1,
Parameters.tenantId
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const listForResourceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RoleAssignmentListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter1,
Parameters.tenantId
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceProviderNamespace,
Parameters.resourceType,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RoleAssignment
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.tenantId],
urlParameters: [
Parameters.$host,
Parameters.scope,
Parameters.roleAssignmentName
],
headerParameters: [Parameters.accept],
serializer
};
const createOperationSpec: coreClient.OperationSpec = {
path:
"/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.RoleAssignment
},
201: {
bodyMapper: Mappers.RoleAssignment
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters4,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.scope,
Parameters.roleAssignmentName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}",
httpMethod: "DELETE",
responses: {
200: {
bodyMapper: Mappers.RoleAssignment
},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.tenantId],
urlParameters: [
Parameters.$host,
Parameters.scope,
Parameters.roleAssignmentName
],
headerParameters: [Parameters.accept],
serializer
};
const validateOperationSpec: coreClient.OperationSpec = {
path:
"/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}/validate",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.ValidationResponse
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters4,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.scope,
Parameters.roleAssignmentName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listForScopeOperationSpec: coreClient.OperationSpec = {
path: "/{scope}/providers/Microsoft.Authorization/roleAssignments",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RoleAssignmentListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter1,
Parameters.tenantId
],
urlParameters: [Parameters.$host, Parameters.scope],
headerParameters: [Parameters.accept],
serializer
};
const getByIdOperationSpec: coreClient.OperationSpec = {
path: "/{roleAssignmentId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RoleAssignment
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.tenantId],
urlParameters: [Parameters.$host, Parameters.roleAssignmentId],
headerParameters: [Parameters.accept],
serializer
};
const createByIdOperationSpec: coreClient.OperationSpec = {
path: "/{roleAssignmentId}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.RoleAssignment
},
201: {
bodyMapper: Mappers.RoleAssignment
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters4,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.roleAssignmentId],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteByIdOperationSpec: coreClient.OperationSpec = {
path: "/{roleAssignmentId}",
httpMethod: "DELETE",
responses: {
200: {
bodyMapper: Mappers.RoleAssignment
},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.tenantId],
urlParameters: [Parameters.$host, Parameters.roleAssignmentId],
headerParameters: [Parameters.accept],
serializer
};
const validateByIdOperationSpec: coreClient.OperationSpec = {
path: "/{roleAssignmentId}/validate",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.ValidationResponse
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters4,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.roleAssignmentId],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listForSubscriptionNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RoleAssignmentListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter1,
Parameters.tenantId
],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listForResourceGroupNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RoleAssignmentListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter1,
Parameters.tenantId
],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const listForResourceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RoleAssignmentListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter1,
Parameters.tenantId
],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceProviderNamespace,
Parameters.resourceType,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const listForScopeNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RoleAssignmentListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.filter1,
Parameters.tenantId
],
urlParameters: [Parameters.$host, Parameters.scope, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
}; | 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/clustersMappers";
import * as Parameters from "../models/parameters";
import { KustoManagementClientContext } from "../kustoManagementClientContext";
/** Class representing a Clusters. */
export class Clusters {
private readonly client: KustoManagementClientContext;
/**
* Create a Clusters.
* @param {KustoManagementClientContext} client Reference to the service client.
*/
constructor(client: KustoManagementClientContext) {
this.client = client;
}
/**
* Gets a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersGetResponse>
*/
get(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<Models.ClustersGetResponse>;
/**
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param callback The callback
*/
get(
resourceGroupName: string,
clusterName: string,
callback: msRest.ServiceCallback<Models.Cluster>
): void;
/**
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param options The optional parameters
* @param callback The callback
*/
get(
resourceGroupName: string,
clusterName: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.Cluster>
): void;
get(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Cluster>,
callback?: msRest.ServiceCallback<Models.Cluster>
): Promise<Models.ClustersGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
clusterName,
options
},
getOperationSpec,
callback
) as Promise<Models.ClustersGetResponse>;
}
/**
* Create or update a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param parameters The Kusto cluster parameters supplied to the CreateOrUpdate operation.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersCreateOrUpdateResponse>
*/
createOrUpdate(
resourceGroupName: string,
clusterName: string,
parameters: Models.Cluster,
options?: Models.ClustersCreateOrUpdateOptionalParams
): Promise<Models.ClustersCreateOrUpdateResponse> {
return this.beginCreateOrUpdate(
resourceGroupName,
clusterName,
parameters,
options
).then((lroPoller) => lroPoller.pollUntilFinished()) as Promise<
Models.ClustersCreateOrUpdateResponse
>;
}
/**
* Update a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param parameters The Kusto cluster parameters supplied to the Update operation.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersUpdateResponse>
*/
update(
resourceGroupName: string,
clusterName: string,
parameters: Models.ClusterUpdate,
options?: Models.ClustersUpdateOptionalParams
): Promise<Models.ClustersUpdateResponse> {
return this.beginUpdate(resourceGroupName, clusterName, parameters, options).then((lroPoller) =>
lroPoller.pollUntilFinished()
) as Promise<Models.ClustersUpdateResponse>;
}
/**
* Deletes a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(resourceGroupName, clusterName, options).then((lroPoller) =>
lroPoller.pollUntilFinished()
);
}
/**
* Stops a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
stop(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginStop(resourceGroupName, clusterName, options).then((lroPoller) =>
lroPoller.pollUntilFinished()
);
}
/**
* Starts a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
start(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginStart(resourceGroupName, clusterName, options).then((lroPoller) =>
lroPoller.pollUntilFinished()
);
}
/**
* Returns a list of databases that are owned by this cluster and were followed by another cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersListFollowerDatabasesResponse>
*/
listFollowerDatabases(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<Models.ClustersListFollowerDatabasesResponse>;
/**
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param callback The callback
*/
listFollowerDatabases(
resourceGroupName: string,
clusterName: string,
callback: msRest.ServiceCallback<Models.FollowerDatabaseListResult>
): void;
/**
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param options The optional parameters
* @param callback The callback
*/
listFollowerDatabases(
resourceGroupName: string,
clusterName: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.FollowerDatabaseListResult>
): void;
listFollowerDatabases(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.FollowerDatabaseListResult>,
callback?: msRest.ServiceCallback<Models.FollowerDatabaseListResult>
): Promise<Models.ClustersListFollowerDatabasesResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
clusterName,
options
},
listFollowerDatabasesOperationSpec,
callback
) as Promise<Models.ClustersListFollowerDatabasesResponse>;
}
/**
* Detaches all followers of a database owned by this cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param followerDatabaseToRemove The follower databases properties to remove.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
detachFollowerDatabases(
resourceGroupName: string,
clusterName: string,
followerDatabaseToRemove: Models.FollowerDatabaseDefinition,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginDetachFollowerDatabases(
resourceGroupName,
clusterName,
followerDatabaseToRemove,
options
).then((lroPoller) => lroPoller.pollUntilFinished());
}
/**
* Diagnoses network connectivity status for external resources on which the service is dependent
* on.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersDiagnoseVirtualNetworkResponse>
*/
diagnoseVirtualNetwork(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<Models.ClustersDiagnoseVirtualNetworkResponse> {
return this.beginDiagnoseVirtualNetwork(
resourceGroupName,
clusterName,
options
).then((lroPoller) => lroPoller.pollUntilFinished()) as Promise<
Models.ClustersDiagnoseVirtualNetworkResponse
>;
}
/**
* Lists all Kusto clusters within a resource group.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersListByResourceGroupResponse>
*/
listByResourceGroup(
resourceGroupName: string,
options?: msRest.RequestOptionsBase
): Promise<Models.ClustersListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param callback The callback
*/
listByResourceGroup(
resourceGroupName: string,
callback: msRest.ServiceCallback<Models.ClusterListResult>
): void;
/**
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(
resourceGroupName: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.ClusterListResult>
): void;
listByResourceGroup(
resourceGroupName: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ClusterListResult>,
callback?: msRest.ServiceCallback<Models.ClusterListResult>
): Promise<Models.ClustersListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback
) as Promise<Models.ClustersListByResourceGroupResponse>;
}
/**
* Lists all Kusto clusters within a subscription.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.ClustersListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.ClusterListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.ClusterListResult>
): void;
list(
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ClusterListResult>,
callback?: msRest.ServiceCallback<Models.ClusterListResult>
): Promise<Models.ClustersListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback
) as Promise<Models.ClustersListResponse>;
}
/**
* Lists eligible SKUs for Kusto resource provider.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersListSkusResponse>
*/
listSkus(options?: msRest.RequestOptionsBase): Promise<Models.ClustersListSkusResponse>;
/**
* @param callback The callback
*/
listSkus(callback: msRest.ServiceCallback<Models.SkuDescriptionList>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listSkus(
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.SkuDescriptionList>
): void;
listSkus(
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SkuDescriptionList>,
callback?: msRest.ServiceCallback<Models.SkuDescriptionList>
): Promise<Models.ClustersListSkusResponse> {
return this.client.sendOperationRequest(
{
options
},
listSkusOperationSpec,
callback
) as Promise<Models.ClustersListSkusResponse>;
}
/**
* Checks that the cluster name is valid and is not already in use.
* @param location Azure location (region) name.
* @param clusterName The name of the cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersCheckNameAvailabilityResponse>
*/
checkNameAvailability(
location: string,
clusterName: Models.ClusterCheckNameRequest,
options?: msRest.RequestOptionsBase
): Promise<Models.ClustersCheckNameAvailabilityResponse>;
/**
* @param location Azure location (region) name.
* @param clusterName The name of the cluster.
* @param callback The callback
*/
checkNameAvailability(
location: string,
clusterName: Models.ClusterCheckNameRequest,
callback: msRest.ServiceCallback<Models.CheckNameResult>
): void;
/**
* @param location Azure location (region) name.
* @param clusterName The name of the cluster.
* @param options The optional parameters
* @param callback The callback
*/
checkNameAvailability(
location: string,
clusterName: Models.ClusterCheckNameRequest,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.CheckNameResult>
): void;
checkNameAvailability(
location: string,
clusterName: Models.ClusterCheckNameRequest,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CheckNameResult>,
callback?: msRest.ServiceCallback<Models.CheckNameResult>
): Promise<Models.ClustersCheckNameAvailabilityResponse> {
return this.client.sendOperationRequest(
{
location,
clusterName,
options
},
checkNameAvailabilityOperationSpec,
callback
) as Promise<Models.ClustersCheckNameAvailabilityResponse>;
}
/**
* Returns the SKUs available for the provided resource.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersListSkusByResourceResponse>
*/
listSkusByResource(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<Models.ClustersListSkusByResourceResponse>;
/**
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param callback The callback
*/
listSkusByResource(
resourceGroupName: string,
clusterName: string,
callback: msRest.ServiceCallback<Models.ListResourceSkusResult>
): void;
/**
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param options The optional parameters
* @param callback The callback
*/
listSkusByResource(
resourceGroupName: string,
clusterName: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.ListResourceSkusResult>
): void;
listSkusByResource(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ListResourceSkusResult>,
callback?: msRest.ServiceCallback<Models.ListResourceSkusResult>
): Promise<Models.ClustersListSkusByResourceResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
clusterName,
options
},
listSkusByResourceOperationSpec,
callback
) as Promise<Models.ClustersListSkusByResourceResponse>;
}
/**
* Returns a list of language extensions that can run within KQL queries.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersListLanguageExtensionsResponse>
*/
listLanguageExtensions(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<Models.ClustersListLanguageExtensionsResponse>;
/**
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param callback The callback
*/
listLanguageExtensions(
resourceGroupName: string,
clusterName: string,
callback: msRest.ServiceCallback<Models.LanguageExtensionsList>
): void;
/**
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param options The optional parameters
* @param callback The callback
*/
listLanguageExtensions(
resourceGroupName: string,
clusterName: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.LanguageExtensionsList>
): void;
listLanguageExtensions(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.LanguageExtensionsList>,
callback?: msRest.ServiceCallback<Models.LanguageExtensionsList>
): Promise<Models.ClustersListLanguageExtensionsResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
clusterName,
options
},
listLanguageExtensionsOperationSpec,
callback
) as Promise<Models.ClustersListLanguageExtensionsResponse>;
}
/**
* Add a list of language extensions that can run within KQL queries.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param languageExtensionsToAdd The language extensions to add.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
addLanguageExtensions(
resourceGroupName: string,
clusterName: string,
languageExtensionsToAdd: Models.LanguageExtensionsList,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginAddLanguageExtensions(
resourceGroupName,
clusterName,
languageExtensionsToAdd,
options
).then((lroPoller) => lroPoller.pollUntilFinished());
}
/**
* Remove a list of language extensions that can run within KQL queries.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param languageExtensionsToRemove The language extensions to remove.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
removeLanguageExtensions(
resourceGroupName: string,
clusterName: string,
languageExtensionsToRemove: Models.LanguageExtensionsList,
options?: msRest.RequestOptionsBase
): Promise<msRest.RestResponse> {
return this.beginRemoveLanguageExtensions(
resourceGroupName,
clusterName,
languageExtensionsToRemove,
options
).then((lroPoller) => lroPoller.pollUntilFinished());
}
/**
* Create or update a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param parameters The Kusto cluster parameters supplied to the CreateOrUpdate operation.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreateOrUpdate(
resourceGroupName: string,
clusterName: string,
parameters: Models.Cluster,
options?: Models.ClustersBeginCreateOrUpdateOptionalParams
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
parameters,
options
},
beginCreateOrUpdateOperationSpec,
options
);
}
/**
* Update a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param parameters The Kusto cluster parameters supplied to the Update operation.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginUpdate(
resourceGroupName: string,
clusterName: string,
parameters: Models.ClusterUpdate,
options?: Models.ClustersBeginUpdateOptionalParams
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
parameters,
options
},
beginUpdateOperationSpec,
options
);
}
/**
* Deletes a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
options
},
beginDeleteMethodOperationSpec,
options
);
}
/**
* Stops a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginStop(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
options
},
beginStopOperationSpec,
options
);
}
/**
* Starts a Kusto cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginStart(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
options
},
beginStartOperationSpec,
options
);
}
/**
* Detaches all followers of a database owned by this cluster.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param followerDatabaseToRemove The follower databases properties to remove.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDetachFollowerDatabases(
resourceGroupName: string,
clusterName: string,
followerDatabaseToRemove: Models.FollowerDatabaseDefinition,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
followerDatabaseToRemove,
options
},
beginDetachFollowerDatabasesOperationSpec,
options
);
}
/**
* Diagnoses network connectivity status for external resources on which the service is dependent
* on.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDiagnoseVirtualNetwork(
resourceGroupName: string,
clusterName: string,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
options
},
beginDiagnoseVirtualNetworkOperationSpec,
options
);
}
/**
* Add a list of language extensions that can run within KQL queries.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param languageExtensionsToAdd The language extensions to add.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginAddLanguageExtensions(
resourceGroupName: string,
clusterName: string,
languageExtensionsToAdd: Models.LanguageExtensionsList,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
languageExtensionsToAdd,
options
},
beginAddLanguageExtensionsOperationSpec,
options
);
}
/**
* Remove a list of language extensions that can run within KQL queries.
* @param resourceGroupName The name of the resource group containing the Kusto cluster.
* @param clusterName The name of the Kusto cluster.
* @param languageExtensionsToRemove The language extensions to remove.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginRemoveLanguageExtensions(
resourceGroupName: string,
clusterName: string,
languageExtensionsToRemove: Models.LanguageExtensionsList,
options?: msRest.RequestOptionsBase
): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
languageExtensionsToRemove,
options
},
beginRemoveLanguageExtensionsOperationSpec,
options
);
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}",
urlParameters: [Parameters.resourceGroupName, Parameters.clusterName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.Cluster
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listFollowerDatabasesOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/listFollowerDatabases",
urlParameters: [Parameters.resourceGroupName, Parameters.clusterName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.FollowerDatabaseListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters",
urlParameters: [Parameters.resourceGroupName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.ClusterListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Kusto/clusters",
urlParameters: [Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.ClusterListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listSkusOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Kusto/skus",
urlParameters: [Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.SkuDescriptionList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const checkNameAvailabilityOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/providers/Microsoft.Kusto/locations/{location}/checkNameAvailability",
urlParameters: [Parameters.subscriptionId, Parameters.location],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
requestBody: {
parameterPath: "clusterName",
mapper: {
...Mappers.ClusterCheckNameRequest,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.CheckNameResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listSkusByResourceOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/skus",
urlParameters: [Parameters.resourceGroupName, Parameters.clusterName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.ListResourceSkusResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listLanguageExtensionsOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/listLanguageExtensions",
urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.LanguageExtensionsList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}",
urlParameters: [Parameters.resourceGroupName, Parameters.clusterName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.ifMatch, Parameters.ifNoneMatch, Parameters.acceptLanguage],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.Cluster,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Cluster
},
201: {
bodyMapper: Mappers.Cluster
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}",
urlParameters: [Parameters.resourceGroupName, Parameters.clusterName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.ifMatch, Parameters.acceptLanguage],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.ClusterUpdate,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Cluster
},
201: {
bodyMapper: Mappers.Cluster
},
202: {
bodyMapper: Mappers.Cluster
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}",
urlParameters: [Parameters.resourceGroupName, Parameters.clusterName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginStopOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/stop",
urlParameters: [Parameters.resourceGroupName, Parameters.clusterName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginStartOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/start",
urlParameters: [Parameters.resourceGroupName, Parameters.clusterName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDetachFollowerDatabasesOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/detachFollowerDatabases",
urlParameters: [Parameters.resourceGroupName, Parameters.clusterName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
requestBody: {
parameterPath: "followerDatabaseToRemove",
mapper: {
...Mappers.FollowerDatabaseDefinition,
required: true
}
},
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDiagnoseVirtualNetworkOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/diagnoseVirtualNetwork",
urlParameters: [Parameters.resourceGroupName, Parameters.clusterName, Parameters.subscriptionId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.DiagnoseVirtualNetworkResult
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginAddLanguageExtensionsOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/addLanguageExtensions",
urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
requestBody: {
parameterPath: "languageExtensionsToAdd",
mapper: {
...Mappers.LanguageExtensionsList,
required: true
}
},
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginRemoveLanguageExtensionsOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/removeLanguageExtensions",
urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
requestBody: {
parameterPath: "languageExtensionsToRemove",
mapper: {
...Mappers.LanguageExtensionsList,
required: true
}
},
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import * as vscode from 'vscode';
import * as fs from 'fs'
import * as rebar from './RebarRunner';
import * as erlang from './ErlangShell';
import * as path from 'path';
import * as utils from './utils';
import * as adapter from './vscodeAdapter';
import { erlangBridgePath } from './erlangConnection';
export class EunitRunner implements vscode.Disposable {
diagnosticCollection: vscode.DiagnosticCollection;
private eunitCommand: vscode.Disposable;
public activate(context: vscode.ExtensionContext) {
this.eunitCommand = vscode.commands.registerCommand('extension.erleunit', () => { this.runEUnitCommand() });
this.diagnosticCollection = vscode.languages.createDiagnosticCollection("euniterlang");
setExtensionPath(context.extensionPath);
context.subscriptions.push(this);
}
public dispose(): void {
this.diagnosticCollection.clear();
this.diagnosticCollection.dispose();
this.eunitCommand.dispose();
}
private runEUnitCommand() {
let that = this;
runEUnitRequirements().then(_ => {
myoutputChannel.clear();
this.diagnosticCollection.clear();
logTitle("Read configuration...");
readRebarConfigWithErlangShell().then(v => {
//add file type to compile
v.TestDirs = v.TestDirs.map(x => joinPath(x, "*.erl"));
return v;
}).then(x => {
logTitle("Compile units tests...");
compile(x).then(v => {
logTitle("Run units tests...");
runTests(v).then(testResults => {
that.parseTestsResults(testResults).then(ok =>ok,
reason => {
myoutputChannel.appendLine('eunit command failed :' + reason + '\n');
});
});
});
});
}, reason => {
myoutputChannel.appendLine('rebar eunit command failed :' + reason + '\n');
});
}
private parseTestsResults(results: TestResults): Thenable<boolean> {
return new Promise<boolean>((a, r) => {
if (results.failed > 0 || results.aborted > 0) {
var diagnostics: { [id: string]: vscode.Diagnostic[]; } = {};
this.parseForDiag(results.testcases, diagnostics);
var keys = utils.keysFromDictionary(diagnostics);
keys.forEach(element => {
var fileUri = vscode.Uri.file(path.join(vscode.workspace.rootPath, element));
var diags = diagnostics[element];
this.diagnosticCollection.set(fileUri, diags);
});
var failed = Number(results.failed) + Number(results.aborted);
r((failed) + " unittest(s) failed.");
}
a(true);
});
}
private getFile(stacktrace: any[]): string {
if (stacktrace && stacktrace.length > 0) {
return stacktrace[0].file;
}
return "";
}
private getExpected(location: any): string {
if (location.expected) {
return location.expected;
} else if (location.pattern) {
return location.pattern;
}
return JSON.stringify(location);
}
private parseForDiag(testcases: TestCase[], diagnostics: { [id: string]: vscode.Diagnostic[]; }) {
testcases.forEach(testcase => {
if (testcase.result && testcase.result != "ok") {
/*
let message = m[m.length-1];
let range = new vscode.Range(Number(m[2])-1, 0, Number(m[2])-1, peace.length-1);
let diagnostic = new vscode.Diagnostic(range, message, vscode.DiagnosticSeverity.Error);
*/
let message = "";
var failed = testcase.result.failed;
var diagnostic: vscode.Diagnostic = null;
if (failed) {
message = failed.assertion + "/" + failed.location.module + ", expected :" + this.getExpected(failed.location) + ", value :" + failed.location.value;
var file = this.getFile(failed.stacktrace);
var line = Number(failed.location.line) - 1;
let range = new vscode.Range(line, 0, line, 80);
diagnostic = new vscode.Diagnostic(range, message, vscode.DiagnosticSeverity.Error);
} else if (testcase.result.aborted) {
//TODO: when test is aborted
var aborted = testcase.result.aborted;
message = aborted.error;
var file = this.getFile(aborted.stacktrace);
var line = Number(aborted.stacktrace[0].line) - 1;
let range = new vscode.Range(line, 0, line, 80);
diagnostic = new vscode.Diagnostic(range, message, vscode.DiagnosticSeverity.Error);
}
if (!diagnostics[file]) {
diagnostics[file] = [];
}
diagnostics[file].push(diagnostic);
}
});
}
}
var myoutputChannel = adapter.ErlangOutput();
var eunitDirectory = ".eunit";
var myExtensionPath = "";
function setExtensionPath(extensionPath: string) {
myExtensionPath = extensionPath;
}
function joinPath(x: String, y: String): string {
return x + "/" + y;
}
function logTitle(title: string) {
myoutputChannel.appendLine("------------------------------------------");
myoutputChannel.appendLine(title);
myoutputChannel.appendLine("------------------------------------------");
}
function runEUnitRequirements(): Thenable<boolean> {
return new Promise<boolean>((a, r) => {
var rebarConfig = path.join(vscode.workspace.rootPath, "rebar.config");
if (fs.existsSync(rebarConfig)) {
a(true);
}
else {
r("rebar.config is missing !");
}
});
}
function readRebarConfigWithErlangShell(): Thenable<CompileArgs> {
return new Promise<CompileArgs>((a, r) => {
var erlangShell = new erlang.ErlangShell();
erlangShell.erlangPath = vscode.workspace.getConfiguration("erlang").get("erlangPath", null);
erlangShell.Start(vscode.workspace.rootPath, []).then(
_ => {
var compileArgs = new CompileArgs();
var content = fs.readFileSync(path.join(vscode.workspace.rootPath, "rebarconfig.json"), "utf-8");
var o = JSON.parse(content);
compileArgs.IncludeDirs = o.IncludeDirs;
if (compileArgs.IncludeDirs) {
//ADD -I before each élément
insertBeforeEachElement(compileArgs.IncludeDirs, "-I");
}
compileArgs.TestDirs = o.TestDirs;
//todo: test if TestDirs is not empty
a(compileArgs);
},
exitCode => {
r("Erlang shell that get rebar config failed with exitcode :" + exitCode);
});
var cmd = '{ok, Config}=file:consult("./rebar.config"),';
cmd += 'Undef = fun (E) -> case E of (undefined) -> []; (_) -> E end end,';
//read erl_opts
cmd += 'E=Undef(proplists:get_value(erl_opts, Config)),';
//get includes dirs
cmd += 'I=Undef(proplists:get_value(i, E)),';
//read eunit_compile_opts
cmd += 'EunitOpts=Undef(proplists:get_value(eunit_compile_opts, Config)),';
//get src_dirs
cmd += 'SrcDirs=Undef(proplists:get_value(src_dirs, EunitOpts)),';
//get erlang tuples as printable chars
cmd += 'IR=lists:flatten(io_lib:print(case io_lib:printable_list(I) and (string:length(I)>0) of true -> [I]; false -> I end)),';
//json representation
cmd += 'R = "{\\"TestDirs\\":"++lists:flatten(io_lib:print(SrcDirs))++", \\"IncludeDirs\\":"++IR++"}",';
cmd += 'file:write_file("./rebarconfig.json", R),'
cmd += 'q().';
//send command to current erlang shell
erlangShell.Send(cmd);
});
}
function to_modulename(moduleFileName: string): string {
var parsedModuleFileName = path.parse(moduleFileName);
return parsedModuleFileName.name;
}
function relativeTo(ref: string, value: string): string {
var parsedValue = path.parse(value);
if (parsedValue.dir.startsWith(ref)) {
return path.join(".", parsedValue.dir.substring(ref.length), parsedValue.base);
}
return value;
}
function relativePathTo(ref: string, value: string): string {
var parsedValue = path.parse(value);
if (parsedValue.dir.startsWith(ref)) {
return path.join(".", parsedValue.dir.substring(ref.length));
}
return value;
}
function findErlangFiles(dirAndPattern: string): Thenable<string[]> {
//find file from the root of current workspace
return vscode.workspace.findFiles(dirAndPattern, "").then((files: vscode.Uri[]) => {
return files.map((v, i, a) => relativeTo(vscode.workspace.rootPath, v.fsPath));
});
}
function mapToFirstDirLevel(x: vscode.Uri): string {
var y = relativeTo(vscode.workspace.rootPath, x.fsPath);
return y.split(path.sep)[0];
}
function findIncludeDirectories(): Thenable<string[]> {
return vscode.workspace.findFiles("**/*.hrl", "").then((files: vscode.Uri[]) => {
var iDirs = files.map(x => mapToFirstDirLevel(x));
insertBeforeEachElement(iDirs, "-I");
return iDirs;
});
}
function insertBeforeEachElement(A: string[], value: string) {
var startIndex = A.length - 1;
var count = A.length;
for (var index = 0; index < count; index++) {
A.splice(startIndex - index, 0, value);
}
}
function cleanDirectory(dir: string) {
fs.readdirSync(dir).forEach(element => {
var file = path.resolve(dir, element);
var stats = fs.statSync(file);
if (stats && stats.isFile()) {
fs.unlinkSync(file);
}
});
}
function compile(compileArgs: CompileArgs): Thenable<string[]> {
var eunitDir = path.join(vscode.workspace.rootPath, eunitDirectory);
if (fs.existsSync(eunitDir)) {
cleanDirectory(eunitDir);
}
if (!fs.existsSync(eunitDir)) {
fs.mkdirSync(eunitDir);
}
fs.createReadStream(path.resolve(erlangBridgePath, 'eunit_jsonreport.erl'))
.pipe(fs.createWriteStream(path.resolve(eunitDir, 'eunit_jsonreport.erl')));
return findIncludeDirectories()
.then(iDirs => {
compileArgs.IncludeDirs = compileArgs.IncludeDirs.concat(iDirs);
return compileArgs;
}).then(args => {
return findErlangFiles("{" + compileArgs.TestDirs.join(",") + "}").then(erlFiles => {
args.ErlangFiles = erlFiles.concat(['./.eunit/eunit_jsonreport.erl']);
return args;
});
}).then(args => {
var argsCmd = args.IncludeDirs.concat(["-o", eunitDirectory]).concat(args.ErlangFiles);
var erlc = new erlang.ErlangCompilerShell();
erlc.erlangPath = vscode.workspace.getConfiguration("erlang").get("erlangPath", null);
return erlc.Start(vscode.workspace.rootPath, argsCmd.map<string>(x => x.toString()))
.then(exitCode => {
return args.ErlangFiles;
});
});
}
function walkdir(dir: string, done: (err: NodeJS.ErrnoException, files: string[]) => void, accept: (dirName: string, fullPath: string) => boolean) {
//custom function, because 'vscode.workspace.findFiles' use files.exclude from .vscode/settings.json
//so some files are hidden (i.e *.beam)
var results = [];
fs.readdir(dir, (err, list) => {
if (err) return done(err, null);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach((fileName) => {
var file = path.resolve(dir, fileName);
fs.stat(file, (err, stat) => {
if (stat && stat.isDirectory()) {
if (accept(fileName, file)) {
results.push(file);
}
walkdir(file, (err, res) => {
results = results.concat(res);
if (!--pending) done(null, results);
}, accept);
} else {
//results.push(file);
if (!--pending) done(null, results);
}
});
});
});
}
function findebinDirs(): Thenable<string[]> {
return new Promise<string[]>((a, r) => {
walkdir(vscode.workspace.rootPath, (err, files) => {
if (err) r(err);
a(files.map(x => relativePathTo(vscode.workspace.rootPath, path.resolve(x, "dummy.txt"))));
},
//accept only directory that contains ebin
(dirName, fullPath) => dirName.match(/ebin/gi) != null)
});
}
function runTests(filenames: string[]): Thenable<TestResults> {
return new Promise<TestResults>((a, r) => {
findebinDirs().then(pzDirs => {
var erlangShell = new erlang.ErlangShell();
var moduleNames = filenames.map((v, i, a) => to_modulename(v));
insertBeforeEachElement(pzDirs, "-pz");
var args = pzDirs.concat(["-pz", "./" + eunitDirectory]);
erlangShell.Start(vscode.workspace.rootPath, args).then(
_ => {
var jsonResults = fs.readFileSync(path.resolve(vscode.workspace.rootPath, ".eunit", "testsuite_results.json"), "utf-8")
var typedResults = (<TestResults>JSON.parse(jsonResults));
a(typedResults);
},
exitCode => {
r("Erlang shell that run tests failed with exitcode :" + exitCode);
});
//send command to current erlang shell
erlangShell.Send('eunit:test([' + moduleNames.join(',') + '],[{report,{eunit_jsonreport,[{dir,"' + eunitDirectory + '"}]}}]),q().');
});
});
}
class CompileArgs {
TestDirs: string[];
IncludeDirs: string[];
ErlangFiles: string[];
}
class TestResults {
name: string;
time: number;
output: any;
succeeded: number;
failed: number;
aborted: number;
skipped: number;
testcases: TestCase[];
}
class TestCase {
displayname: string;
description: string;
module: string;
function: string;
arity: number;
line: number;
result: any;
time: string;
output: any;
} | the_stack |
import * as utils from "tsutils";
import * as ts from "typescript";
import * as Lint from "../index";
import { arraysAreEqual, Equal } from "../utils";
import { getOverloadKey } from "./adjacentOverloadSignaturesRule";
export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "unified-signatures",
description:
"Warns for any two overloads that could be unified into one by using a union or an optional/rest parameter.",
optionsDescription: "Not configurable.",
options: null,
optionExamples: [true],
type: "typescript",
typescriptOnly: true,
};
/* tslint:enable:object-literal-sort-keys */
public static FAILURE_STRING_OMITTING_SINGLE_PARAMETER(otherLine?: number) {
return `${Rule.FAILURE_STRING_START(otherLine)} with an optional parameter.`;
}
public static FAILURE_STRING_OMITTING_REST_PARAMETER(otherLine?: number) {
return `${Rule.FAILURE_STRING_START(otherLine)} with a rest parameter.`;
}
public static FAILURE_STRING_SINGLE_PARAMETER_DIFFERENCE(
otherLine: number | undefined,
type1: string,
type2: string,
) {
return `${Rule.FAILURE_STRING_START(otherLine)} taking \`${type1} | ${type2}\`.`;
}
private static FAILURE_STRING_START(otherLine?: number): string {
// For only 2 overloads we don't need to specify which is the other one.
const overloads =
otherLine === undefined
? "These overloads"
: `This overload and the one on line ${otherLine}`;
return `${overloads} can be combined into one signature`;
}
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk);
}
}
function walk(ctx: Lint.WalkContext): void {
const { sourceFile } = ctx;
checkStatements(sourceFile.statements);
return ts.forEachChild(sourceFile, function cb(node: ts.Node): void {
switch (node.kind) {
case ts.SyntaxKind.ModuleBlock:
checkStatements((node as ts.ModuleBlock).statements);
break;
case ts.SyntaxKind.InterfaceDeclaration:
case ts.SyntaxKind.ClassDeclaration: {
const { members, typeParameters } = node as
| ts.ClassDeclaration
| ts.InterfaceDeclaration;
checkMembers(members, typeParameters);
break;
}
case ts.SyntaxKind.TypeLiteral:
checkMembers((node as ts.TypeLiteralNode).members);
}
return ts.forEachChild(node, cb);
});
function checkStatements(statements: ReadonlyArray<ts.Statement>): void {
addFailures(
checkOverloads(statements, undefined, statement => {
if (utils.isFunctionDeclaration(statement)) {
const { body, name } = statement;
return body === undefined && name !== undefined
? { signature: statement, key: name.text }
: undefined;
} else {
return undefined;
}
}),
);
}
function checkMembers(
members: ReadonlyArray<ts.TypeElement | ts.ClassElement>,
typeParameters?: ReadonlyArray<ts.TypeParameterDeclaration>,
): void {
addFailures(
checkOverloads(members, typeParameters, member => {
switch (member.kind) {
case ts.SyntaxKind.CallSignature:
case ts.SyntaxKind.ConstructSignature:
case ts.SyntaxKind.MethodSignature:
break;
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.Constructor:
if (
(member as ts.MethodDeclaration | ts.ConstructorDeclaration).body !==
undefined
) {
return undefined;
}
break;
default:
return undefined;
}
const signature = member as
| ts.CallSignatureDeclaration
| ts.ConstructSignatureDeclaration
| ts.MethodSignature
| ts.MethodDeclaration
| ts.ConstructorDeclaration;
const key = getOverloadKey(signature);
return key === undefined ? undefined : { signature, key };
}),
);
}
function addFailures(failures: Failure[]): void {
for (const failure of failures) {
const { unify, only2 } = failure;
switch (unify.kind) {
case "single-parameter-difference": {
const { p0, p1 } = unify;
const lineOfOtherOverload = only2 ? undefined : getLine(p0.getStart());
ctx.addFailureAtNode(
p1,
Rule.FAILURE_STRING_SINGLE_PARAMETER_DIFFERENCE(
lineOfOtherOverload,
typeText(p0),
typeText(p1),
),
);
break;
}
case "extra-parameter": {
const { extraParameter, otherSignature } = unify;
const lineOfOtherOverload = only2 ? undefined : getLine(otherSignature.pos);
ctx.addFailureAtNode(
extraParameter,
extraParameter.dotDotDotToken !== undefined
? Rule.FAILURE_STRING_OMITTING_REST_PARAMETER(lineOfOtherOverload)
: Rule.FAILURE_STRING_OMITTING_SINGLE_PARAMETER(lineOfOtherOverload),
);
}
}
}
}
function getLine(pos: number): number {
return ts.getLineAndCharacterOfPosition(sourceFile, pos).line + 1;
}
}
interface Failure {
unify: Unify;
only2: boolean;
}
type Unify =
| {
kind: "single-parameter-difference";
p0: ts.ParameterDeclaration;
p1: ts.ParameterDeclaration;
}
| {
kind: "extra-parameter";
extraParameter: ts.ParameterDeclaration;
otherSignature: ts.NodeArray<ts.ParameterDeclaration>;
};
function checkOverloads<T>(
signatures: ReadonlyArray<T>,
typeParameters: ReadonlyArray<ts.TypeParameterDeclaration> | undefined,
getOverload: GetOverload<T>,
): Failure[] {
const result: Failure[] = [];
const isTypeParameter = getIsTypeParameter(typeParameters);
for (const overloads of collectOverloads(signatures, getOverload)) {
if (overloads.length === 2) {
const unify = compareSignatures(overloads[0], overloads[1], isTypeParameter);
if (unify !== undefined) {
result.push({ unify, only2: true });
}
} else {
forEachPair(overloads, (a, b) => {
const unify = compareSignatures(a, b, isTypeParameter);
if (unify !== undefined) {
result.push({ unify, only2: false });
}
});
}
}
return result;
}
function compareSignatures(
a: ts.SignatureDeclaration,
b: ts.SignatureDeclaration,
isTypeParameter: IsTypeParameter,
): Unify | undefined {
if (!signaturesCanBeUnified(a, b, isTypeParameter)) {
return undefined;
}
return a.parameters.length === b.parameters.length
? signaturesDifferBySingleParameter(a.parameters, b.parameters)
: signaturesDifferByOptionalOrRestParameter(a.parameters, b.parameters);
}
function signaturesCanBeUnified(
a: ts.SignatureDeclaration,
b: ts.SignatureDeclaration,
isTypeParameter: IsTypeParameter,
): boolean {
// Must return the same type.
return (
typesAreEqual(a.type, b.type) &&
// Must take the same type parameters.
arraysAreEqual(a.typeParameters, b.typeParameters, typeParametersAreEqual) &&
// If one uses a type parameter (from outside) and the other doesn't, they shouldn't be joined.
signatureUsesTypeParameter(a, isTypeParameter) ===
signatureUsesTypeParameter(b, isTypeParameter)
);
}
/** Detect `a(x: number, y: number, z: number)` and `a(x: number, y: string, z: number)`. */
function signaturesDifferBySingleParameter(
types1: ReadonlyArray<ts.ParameterDeclaration>,
types2: ReadonlyArray<ts.ParameterDeclaration>,
): Unify | undefined {
const index = getIndexOfFirstDifference(types1, types2, parametersAreEqual);
if (index === undefined) {
return undefined;
}
// If remaining arrays are equal, the signatures differ by just one parameter type
if (!arraysAreEqual(types1.slice(index + 1), types2.slice(index + 1), parametersAreEqual)) {
return undefined;
}
const a = types1[index];
const b = types2[index];
// Can unify `a?: string` and `b?: number`. Can't unify `...args: string[]` and `...args: number[]`.
// See https://github.com/Microsoft/TypeScript/issues/5077
return parametersHaveEqualSigils(a, b) && a.dotDotDotToken === undefined
? { kind: "single-parameter-difference", p0: a, p1: b }
: undefined;
}
/**
* Detect `a(): void` and `a(x: number): void`.
* Returns the parameter declaration (`x: number` in this example) that should be optional/rest, and overload it's a part of.
*/
function signaturesDifferByOptionalOrRestParameter(
sig1: ts.NodeArray<ts.ParameterDeclaration>,
sig2: ts.NodeArray<ts.ParameterDeclaration>,
): Unify | undefined {
const minLength = Math.min(sig1.length, sig2.length);
const longer = sig1.length < sig2.length ? sig2 : sig1;
const shorter = sig1.length < sig2.length ? sig1 : sig2;
// If one is has 2+ parameters more than the other, they must all be optional/rest.
// Differ by optional parameters: f() and f(x), f() and f(x, ?y, ...z)
// Not allowed: f() and f(x, y)
for (let i = minLength + 1; i < longer.length; i++) {
if (!parameterMayBeMissing(longer[i])) {
return undefined;
}
}
for (let i = 0; i < minLength; i++) {
if (!typesAreEqual(sig1[i].type, sig2[i].type)) {
return undefined;
}
}
if (minLength > 0 && shorter[minLength - 1].dotDotDotToken !== undefined) {
return undefined;
}
return {
extraParameter: longer[longer.length - 1],
kind: "extra-parameter",
otherSignature: shorter,
};
}
/**
* Given a node, if it could potentially be an overload, return its signature and key.
* All signatures which are overloads should have equal keys.
*/
type GetOverload<T> = (node: T) => { signature: ts.SignatureDeclaration; key: string } | undefined;
/**
* Returns true if typeName is the name of an *outer* type parameter.
* In: `interface I<T> { m<U>(x: U): T }`, only `T` is an outer type parameter.
*/
type IsTypeParameter = (typeName: string) => boolean;
/** Given type parameters, returns a function to test whether a type is one of those parameters. */
function getIsTypeParameter(
typeParameters?: ReadonlyArray<ts.TypeParameterDeclaration>,
): IsTypeParameter {
if (typeParameters === undefined) {
return () => false;
}
const set = new Set<string>();
for (const t of typeParameters) {
set.add(t.getText());
}
return (typeName: string) => set.has(typeName);
}
/** True if any of the outer type parameters are used in a signature. */
function signatureUsesTypeParameter(
sig: ts.SignatureDeclaration,
isTypeParameter: IsTypeParameter,
): boolean {
return sig.parameters.some(
p => p.type !== undefined && typeContainsTypeParameter(p.type) === true,
);
function typeContainsTypeParameter(type: ts.Node): boolean | undefined {
if (utils.isTypeReferenceNode(type)) {
const { typeName } = type;
if (typeName.kind === ts.SyntaxKind.Identifier && isTypeParameter(typeName.text)) {
return true;
}
}
return ts.forEachChild(type, typeContainsTypeParameter);
}
}
/**
* Given all signatures, collects an array of arrays of signatures which are all overloads.
* Does not rely on overloads being adjacent. This is similar to code in adjacentOverloadSignaturesRule.ts, but not the same.
*/
function collectOverloads<T>(
nodes: ReadonlyArray<T>,
getOverload: GetOverload<T>,
): ts.SignatureDeclaration[][] {
const map = new Map<string, ts.SignatureDeclaration[]>();
for (const sig of nodes) {
const overload = getOverload(sig);
if (overload === undefined) {
continue;
}
const { signature, key } = overload;
const overloads = map.get(key);
if (overloads !== undefined) {
overloads.push(signature);
} else {
map.set(key, [signature]);
}
}
return Array.from(map.values());
}
function parametersAreEqual(a: ts.ParameterDeclaration, b: ts.ParameterDeclaration): boolean {
return parametersHaveEqualSigils(a, b) && typesAreEqual(a.type, b.type);
}
/** True for optional/rest parameters. */
function parameterMayBeMissing(p: ts.ParameterDeclaration): boolean {
return p.dotDotDotToken !== undefined || p.questionToken !== undefined;
}
/** False if one is optional and the other isn't, or one is a rest parameter and the other isn't. */
function parametersHaveEqualSigils(
a: ts.ParameterDeclaration,
b: ts.ParameterDeclaration,
): boolean {
return (
(a.dotDotDotToken !== undefined) === (b.dotDotDotToken !== undefined) &&
(a.questionToken !== undefined) === (b.questionToken !== undefined)
);
}
function typeParametersAreEqual(
a: ts.TypeParameterDeclaration,
b: ts.TypeParameterDeclaration,
): boolean {
return a.name.text === b.name.text && typesAreEqual(a.constraint, b.constraint);
}
function typesAreEqual(a: ts.TypeNode | undefined, b: ts.TypeNode | undefined): boolean {
// TODO: Could traverse AST so that formatting differences don't affect this.
return a === b || (a !== undefined && b !== undefined && a.getText() === b.getText());
}
/** Returns the first index where `a` and `b` differ. */
function getIndexOfFirstDifference<T>(
a: ReadonlyArray<T>,
b: ReadonlyArray<T>,
equal: Equal<T>,
): number | undefined {
for (let i = 0; i < a.length && i < b.length; i++) {
if (!equal(a[i], b[i])) {
return i;
}
}
return undefined;
}
/** Calls `action` for every pair of values in `values`. */
function forEachPair<T, Out>(
values: ReadonlyArray<T>,
action: (a: T, b: T) => Out | undefined,
): Out | undefined {
for (let i = 0; i < values.length; i++) {
for (let j = i + 1; j < values.length; j++) {
const result = action(values[i], values[j]);
if (result !== undefined) {
return result;
}
}
}
return undefined;
}
function typeText({ type }: ts.ParameterDeclaration) {
return type === undefined ? "any" : type.getText();
} | the_stack |
import { BehaviorSubject, combineLatest as observableCombineLatest, Observable } from 'rxjs';
import { ChangeDetectionStrategy, Component, Inject, OnInit, ViewChild } from '@angular/core';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
import { fadeIn, fadeInOut } from '../../shared/animations/fade';
import { ActivatedRoute, Router } from '@angular/router';
import { RemoteData } from '../../core/data/remote-data';
import { Collection } from '../../core/shared/collection.model';
import { PaginatedList } from '../../core/data/paginated-list.model';
import { map, startWith, switchMap, take } from 'rxjs/operators';
import {
getRemoteDataPayload,
getFirstSucceededRemoteData,
toDSpaceObjectListRD,
getFirstCompletedRemoteData, getAllSucceededRemoteData
} from '../../core/shared/operators';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { DSpaceObjectType } from '../../core/shared/dspace-object-type.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { ItemDataService } from '../../core/data/item-data.service';
import { TranslateService } from '@ngx-translate/core';
import { CollectionDataService } from '../../core/data/collection-data.service';
import { isNotEmpty } from '../../shared/empty.util';
import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-page.component';
import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service';
import { PaginatedSearchOptions } from '../../shared/search/paginated-search-options.model';
import { SearchService } from '../../core/shared/search/search.service';
import { followLink } from '../../shared/utils/follow-link-config.model';
import { NoContent } from '../../core/shared/NoContent.model';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
@Component({
selector: 'ds-collection-item-mapper',
styleUrls: ['./collection-item-mapper.component.scss'],
templateUrl: './collection-item-mapper.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
animations: [
fadeIn,
fadeInOut
],
providers: [
{
provide: SEARCH_CONFIG_SERVICE,
useClass: SearchConfigurationService
}
]
})
/**
* Component used to map items to a collection
*/
export class CollectionItemMapperComponent implements OnInit {
FeatureIds = FeatureID;
/**
* A view on the tabset element
* Used to switch tabs programmatically
*/
@ViewChild('tabs', {static: false}) tabs;
/**
* The collection to map items to
*/
collectionRD$: Observable<RemoteData<Collection>>;
collectionName$: Observable<string>;
/**
* Search options
*/
searchOptions$: Observable<PaginatedSearchOptions>;
/**
* List of items to show under the "Browse" tab
* Items inside the collection
*/
collectionItemsRD$: Observable<RemoteData<PaginatedList<DSpaceObject>>>;
/**
* List of items to show under the "Map" tab
* Items outside the collection
*/
mappedItemsRD$: Observable<RemoteData<PaginatedList<DSpaceObject>>>;
/**
* Sort on title ASC by default
* @type {SortOptions}
*/
defaultSortOptions: SortOptions = new SortOptions('dc.title', SortDirection.ASC);
/**
* Firing this observable (shouldUpdate$.next(true)) forces the two lists to reload themselves
* Usually fired after the lists their cache is cleared (to force a new request to the REST API)
*/
shouldUpdate$: BehaviorSubject<boolean>;
/**
* Track whether at least one search has been performed or not
* As soon as at least one search has been performed, we display the search results
*/
performedSearch = false;
constructor(private route: ActivatedRoute,
private router: Router,
@Inject(SEARCH_CONFIG_SERVICE) private searchConfigService: SearchConfigurationService,
private searchService: SearchService,
private notificationsService: NotificationsService,
private itemDataService: ItemDataService,
private collectionDataService: CollectionDataService,
private translateService: TranslateService,
private dsoNameService: DSONameService) {
}
ngOnInit(): void {
this.collectionRD$ = this.route.parent.data.pipe(
map((data) => data.dso as RemoteData<Collection>),
getFirstSucceededRemoteData()
);
this.collectionName$ = this.collectionRD$.pipe(
map((rd: RemoteData<Collection>) => {
return this.dsoNameService.getName(rd.payload);
})
);
this.searchOptions$ = this.searchConfigService.paginatedSearchOptions;
this.loadItemLists();
}
/**
* Load collectionItemsRD$ with a fixed scope to only obtain the items this collection owns
* Load mappedItemsRD$ to only obtain items this collection doesn't own
*/
loadItemLists() {
this.shouldUpdate$ = new BehaviorSubject<boolean>(true);
const collectionAndOptions$ = observableCombineLatest(
this.collectionRD$,
this.searchOptions$,
this.shouldUpdate$
);
this.collectionItemsRD$ = collectionAndOptions$.pipe(
switchMap(([collectionRD, options, shouldUpdate]) => {
if (shouldUpdate === true) {
this.shouldUpdate$.next(false);
}
return this.itemDataService.findAllByHref(collectionRD.payload._links.mappedItems.href, Object.assign(options, {
sort: this.defaultSortOptions
}),!shouldUpdate, false, followLink('owningCollection')).pipe(
getAllSucceededRemoteData()
);
})
);
this.mappedItemsRD$ = collectionAndOptions$.pipe(
switchMap(([collectionRD, options, shouldUpdate]) => {
return this.searchService.search(Object.assign(new PaginatedSearchOptions(options), {
query: this.buildQuery(collectionRD.payload.id, options.query),
scope: undefined,
dsoTypes: [DSpaceObjectType.ITEM],
sort: this.defaultSortOptions
}), 10000).pipe(
toDSpaceObjectListRD(),
startWith(undefined)
);
})
);
}
/**
* Map/Unmap the selected items to the collection and display notifications
* @param ids The list of item UUID's to map/unmap to the collection
* @param remove Whether or not it's supposed to remove mappings
*/
mapItems(ids: string[], remove?: boolean) {
const responses$ = this.collectionRD$.pipe(
getFirstSucceededRemoteData(),
map((collectionRD: RemoteData<Collection>) => collectionRD.payload),
switchMap((collection: Collection) =>
observableCombineLatest(ids.map((id: string) => {
if (remove) {
return this.itemDataService.removeMappingFromCollection(id, collection.id).pipe(
getFirstCompletedRemoteData()
);
} else {
return this.itemDataService.mapToCollection(id, collection._links.self.href).pipe(
getFirstCompletedRemoteData()
);
}
}
))
)
);
this.showNotifications(responses$, remove);
}
/**
* Display notifications
* @param {Observable<RestResponse[]>} responses$ The responses after adding/removing a mapping
* @param {boolean} remove Whether or not the goal was to remove mappings
*/
private showNotifications(responses$: Observable<RemoteData<NoContent>[]>, remove?: boolean) {
const messageInsertion = remove ? 'unmap' : 'map';
responses$.subscribe((responses: RemoteData<NoContent>[]) => {
const successful = responses.filter((response: RemoteData<any>) => response.hasSucceeded);
const unsuccessful = responses.filter((response: RemoteData<any>) => response.hasFailed);
if (successful.length > 0) {
const successMessages = observableCombineLatest(
this.translateService.get(`collection.edit.item-mapper.notifications.${messageInsertion}.success.head`),
this.translateService.get(`collection.edit.item-mapper.notifications.${messageInsertion}.success.content`, { amount: successful.length })
);
successMessages.subscribe(([head, content]) => {
this.notificationsService.success(head, content);
});
this.shouldUpdate$.next(true);
}
if (unsuccessful.length > 0) {
const unsuccessMessages = observableCombineLatest(
this.translateService.get(`collection.edit.item-mapper.notifications.${messageInsertion}.error.head`),
this.translateService.get(`collection.edit.item-mapper.notifications.${messageInsertion}.error.content`, { amount: unsuccessful.length })
);
unsuccessMessages.subscribe(([head, content]) => {
this.notificationsService.error(head, content);
});
}
this.switchToFirstTab();
});
}
/**
* Clear url parameters on tab change (temporary fix until pagination is improved)
* @param event
*/
tabChange(event) {
this.performedSearch = false;
this.router.navigateByUrl(this.getCurrentUrl());
}
/**
* Get current url without parameters
* @returns {string}
*/
getCurrentUrl(): string {
if (this.router.url.indexOf('?') > -1) {
return this.router.url.substring(0, this.router.url.indexOf('?'));
}
return this.router.url;
}
/**
* Build a query where items that are already mapped to a collection are excluded from
* @param collectionId The collection's UUID
* @param query The query to add to it
*/
buildQuery(collectionId: string, query: string): string {
const excludeColQuery = `-location.coll:\"${collectionId}\"`;
if (isNotEmpty(query)) {
return `${excludeColQuery} AND ${query}`;
} else {
return excludeColQuery;
}
}
/**
* Switch the view to focus on the first tab
*/
switchToFirstTab() {
this.tabs.select('browseTab');
}
/**
* When a cancel event is fired, return to the collection page
*/
onCancel() {
this.collectionRD$.pipe(
getFirstSucceededRemoteData(),
getRemoteDataPayload(),
take(1)
).subscribe((collection: Collection) => {
this.router.navigate(['/collections/', collection.id]);
});
}
} | the_stack |
export interface ChromePerfLoggingPrefs {
/**
* Default: true. Whether or not to collect events from Network domain.
*/
enableNetwork?: boolean | undefined;
/**
* Default: true. Whether or not to collect events from Page domain.
*/
enablePage?: boolean | undefined;
/**
* A comma-separated string of Chrome tracing categories for which trace events should be collected.
* An unspecified or empty string disables tracing.
*/
traceCategories?: string | undefined;
/**
* Default: 1000. The requested number of milliseconds between DevTools trace buffer usage events. For example, if 1000,
* then once per second, DevTools will report how full the trace buffer is. If a report indicates the buffer usage is 100%,
* a warning will be issued.
*/
bufferUsageReportingInterval?: number | undefined;
}
export interface ChromeOptions {
/**
* List of command-line arguments to use when starting Chrome. Arguments with an associated value should be separated by a '=' sign
* (e.g., ['start-maximized', 'user-data-dir=/tmp/temp_profile']).
*/
args?: string[] | undefined;
/**
* Path to the Chrome executable to use (on Mac OS X, this should be the actual binary, not just the app. e.g.,
* '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
*/
binary?: string | undefined;
/**
* A list of Chrome extensions to install on startup. Each item in the list should be a base-64 encoded packed Chrome extension (.crx)
*/
extensions?: string[] | undefined;
/**
* A dictionary with each entry consisting of the name of the preference and its value. These preferences are applied
* to the Local State file in the user data folder.
*/
localState?: Record<string, string> | undefined;
/**
* A dictionary with each entry consisting of the name of the preference and its value. These preferences are only applied
* to the user profile in use.
*/
prefs?: Record<string, string> | undefined;
/**
* Default: false. If false, Chrome will be quit when ChromeDriver is killed, regardless of whether the session is quit.
* If true, Chrome will only be quit if the session is quit (or closed). Note, if true, and the session is not quit,
* ChromeDriver cannot clean up the temporary user data directory that the running Chrome instance is using.
*/
detach?: boolean | undefined;
/**
* An address of a Chrome debugger server to connect to, in the form of <hostname/ip:port>, e.g. '127.0.0.1:38947'
*/
debuggerAddress?: string | undefined;
/**
* List of Chrome command line switches to exclude that ChromeDriver by default passes when starting Chrome.
* Do not prefix switches with --.
*/
excludeSwitches?: string[] | undefined;
/**
* Directory to store Chrome minidumps . (Supported only on Linux.)
*/
minidumpPath?: string | undefined;
/**
* A dictionary with either a value for “deviceName,” or values for “deviceMetrics” and “userAgent.” Refer to Mobile Emulation for more information.
*/
mobileEmulation?: Record<string, string> | undefined;
/**
* An optional dictionary that specifies performance logging preferences. See below for more information.
*/
perfLoggingPrefs?: ChromePerfLoggingPrefs | undefined;
/**
* A list of window types that will appear in the list of window handles. For access to <webview> elements, include "webview" in this list.
*/
windowTypes?: string[] | undefined;
/**
* Flag to activate W3C WebDriver API. Chromedriver (as of version 2.41 at least) simply does not support the W3C WebDriver API.
*/
w3c?: boolean | undefined;
}
export interface NightwatchDesiredCapabilities {
/**
* The name of the browser being used; should be one of {android|chrome|firefox|htmlunit|internet explorer|iPhone|iPad|opera|safari}.
*/
browserName?: string | undefined;
/**
* The browser version, or the empty string if unknown.
*/
version?: string | undefined;
/**
* A key specifying which platform the browser should be running on. This value should be one of {WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANDROID}.
* When requesting a new session, the client may specify ANY to indicate any available platform may be used.
* For more information see [GridPlatforms (https://code.google.com/p/selenium/wiki/GridPlatforms)]
*/
platform?: string | undefined;
/**
* Whether the session supports taking screenshots of the current page.
*/
takesScreenShot?: boolean | undefined;
/**
* Whether the session can interact with modal popups, such as window.alert and window.confirm.
*/
handlesAlerts?: boolean | undefined;
/**
* Whether the session supports CSS selectors when searching for elements.
*/
cssSelectorsEnabled?: boolean | undefined;
/**
* Whether the session supports executing user supplied JavaScript in the context of the current page (only on HTMLUnitDriver).
*/
javascriptEnabled?: boolean | undefined;
/**
* Whether the session can interact with database storage.
*/
databaseEnabled?: boolean | undefined;
/**
* Whether the session can set and query the browser's location context.
*/
locationContextEnabled?: boolean | undefined;
/**
* Whether the session can interact with the application cache.
*/
applicationCacheEnabled?: boolean | undefined;
/**
* Whether the session can query for the browser's connectivity and disable it if desired.
*/
browserConnectionEnabled?: boolean | undefined;
/**
* Whether the session supports interactions with storage objects (http://www.w3.org/TR/2009/WD-webstorage-20091029/).
*/
webStorageEnabled?: boolean | undefined;
/**
* Whether the session should accept all SSL certs by default.
*/
acceptSslCerts?: boolean | undefined;
/**
* Whether the session can rotate the current page's current layout between portrait and landscape orientations (only applies to mobile platforms).
*/
rotatable?: boolean | undefined;
/**
* Whether the session is capable of generating native events when simulating user input.
*/
nativeEvents?: boolean | undefined;
/**
* What the browser should do with an unhandled alert before throwing out the UnhandledAlertException. Possible values are "accept", "dismiss" and "ignore"
*/
unexpectedAlertBehaviour?: string | undefined;
/**
* Allows the user to specify whether elements are scrolled into the viewport for interaction to align with the top (0) or bottom (1) of the viewport.
* The default value is to align with the top of the viewport. Supported in IE and Firefox (since 2.36)
*/
elementScrollBehaviour?: number | undefined;
/**
* A JSON object describing the logging level of different components in the browser, the driver, or any intermediary WebDriver servers.
* Available values for most loggers are "OFF", "SEVERE", "WARNING", "INFO", "CONFIG", "FINE", "FINER", "FINEST", "ALL".
* This produces a JSON object looking something like: {"loggingPrefs": {"driver": "INFO", "server": "OFF", "browser": "FINE"}}.
*/
loggingPrefs?: {
browser?: string | undefined;
driver?: string | undefined;
server?: string | undefined;
} | undefined;
/**
* This is a list of all the Chrome-specific desired capabilities.
*/
chromeOptions?: ChromeOptions | undefined;
}
export interface NightwatchScreenshotOptions {
enabled?: boolean | undefined;
on_failure?: boolean | undefined;
on_error?: boolean | undefined;
path?: string | undefined;
}
export interface NightwatchTestRunner {
"type"?: string | undefined;
options?: {
ui?: string | undefined;
} | undefined;
}
export interface NightwatchTestWorker {
enabled: boolean;
workers: string;
node_options?: string | string[] | undefined;
}
export interface NightwatchOptions {
/**
* An array of folders (excluding subfolders) where the tests are located.
*/
src_folders: string | string[];
/**
* The location where the JUnit XML report files will be saved.
*/
output_folder?: string | undefined;
/**
* Location(s) where custom commands will be loaded from.
*/
custom_commands_path?: string | string[] | undefined;
/**
* Location(s) where custom assertions will be loaded from.
*/
custom_assertions_path?: string | string[] | undefined;
/**
* Location(s) where page object files will be loaded from.
*/
page_objects_path?: string | string[] | undefined;
/**
* Location of an external globals module which will be loaded and made available to the test as a property globals on the main client instance.
* Globals can also be defined/overwritten inside a test_settings environment.
*/
globals_path?: string | undefined;
/**
* An object containing Selenium Server related configuration options. See below for details.
*/
selenium?: NightwatchSeleniumOptions | undefined;
/**
* This object contains all the test related options. See below for details.
*/
test_settings: NightwatchTestSettings;
/**
* Whether or not to buffer the output in case of parallel running. See below for details.
*/
live_output?: boolean | undefined;
/**
* Controls whether or not to disable coloring of the cli output globally.
*/
disable_color?: boolean | undefined;
/**
* Specifies the delay(in milliseconds) between starting the child processes when running in parallel mode.
*/
parallel_process_delay?: number | undefined;
/**
* Whether or not to run individual test files in parallel. If set to true, runs the tests in parallel and determines the number of workers automatically.
* If set to an object, can specify specify the number of workers as "auto" or a number. Example: "test_workers" : {"enabled" : true, "workers" : "auto"}
*/
test_workers?: boolean | NightwatchTestWorker | undefined;
/**
* Specifies which test runner to use when running the tests. Values can be either default (built in nightwatch runner) or mocha.
* Example: "test_runner" : {"type" : "mocha", "options" : {"ui" : "tdd"}}
*/
test_runner?: string | NightwatchTestRunner | undefined;
/**
* Allows for webdriver config (mostly the same as selenium)
*/
webdriver?: {
port: number;
start_process: boolean;
server_path: string;
cli_args: string[];
} | undefined;
}
export interface NightwatchGlobals {
/**
* this controls whether to abort the test execution when an assertion failed and skip the rest
* it's being used in waitFor commands and expect assertions
* @default true
*/
abortOnAssertionFailure?: boolean | undefined;
/**
* this will overwrite the default polling interval (currently 500ms) for waitFor commands
* and expect assertions that use retry
* @default 300
*/
waitForConditionPollInterval?: number | undefined;
/**
* default timeout value in milliseconds for waitFor commands and implicit waitFor value for
* expect assertions
* @default 5000
*/
waitForConditionTimeout?: number | undefined;
/**
* this will cause waitFor commands on elements to throw an error if multiple
* elements are found using the given locate strategy and selector
* @default true
*/
throwOnMultipleElementsReturned?: boolean | undefined;
/**
* controls the timeout time for async hooks. Expects the done() callback to be invoked within this time
* or an error is thrown
* @default 10000
*/
asyncHookTimeout?: number | undefined;
}
export interface NightwatchSeleniumOptions {
/**
* Whether or not to manage the selenium process automatically.
*/
start_process: boolean;
/**
* Whether or not to automatically start the Selenium session.
*/
start_session: boolean;
/**
* The location of the selenium jar file. This needs to be specified if start_process is enabled.E.g.: lib/selenium-server-standalone-2.43.0.jar
*/
server_path: string;
/**
* The location where the selenium Selenium-debug.log file will be placed. Defaults to current directory. To disable Selenium logging, set this to false
*/
log_path: string | boolean;
/**
* Usually not required and only used if start_process is true. Specify the IP address you wish Selenium to listen on.
*/
host: string;
/**
* The port number Selenium will listen on.
*/
port: number;
/**
* List of cli arguments to be passed to the Selenium process. Here you can set various options for browser drivers, such as:
*
* webdriver.firefox.profile: Selenium will be default create a new Firefox profile for each session.
* If you wish to use an existing Firefox profile you can specify its name here.
* Complete list of Firefox Driver arguments available https://code.google.com/p/selenium/wiki/FirefoxDriver.
*
* webdriver.chrome.driver: Nightwatch can run the tests using Chrome browser also. To enable this you have to download the ChromeDriver binary
* (http://chromedriver.storage.googleapis.com/index.html) and specify it's location here. Also don't forget to specify chrome as the browser name in the
* desiredCapabilities object.
* More information can be found on the ChromeDriver website (https://sites.google.com/a/chromium.org/chromedriver/).
*
* webdriver.ie.driver: Nightwatch has support for Internet Explorer also. To enable this you have to download the IE Driver binary
* (https://code.google.com/p/selenium/wiki/InternetExplorerDriver) and specify it's location here. Also don't forget to specify "internet explorer" as the browser
* name in the desiredCapabilities object.
*/
cli_args: any;
}
export interface NightwatchTestSettingGeneric {
/**
* A url which can be used later in the tests as the main url to load. Can be useful if your tests will run on different environments, each one with a different url.
*/
launch_url?: string | undefined;
/**
* The hostname/IP on which the selenium server is accepting connections.
*/
selenium_host?: string | undefined;
/**
* The port number on which the selenium server is accepting connections.
*/
selenium_port?: number | undefined;
/**
* Whether to show extended Selenium command logs.
*/
silent?: boolean | undefined;
/**
* Use to disable terminal output completely.
*/
output?: boolean | undefined;
/**
* Use to disable colored output in the terminal.
*/
disable_colors?: boolean | undefined;
/**
* In case the selenium server requires credentials this username will be used to compute the Authorization header.
* The value can be also an environment variable, in which case it will look like this: "username" : "${SAUCE_USERNAME}"
*/
username?: string | undefined;
/**
* This field will be used together with username to compute the Authorization header.
* Like username, the value can be also an environment variable: "access_key" : "${SAUCE_ACCESS_KEY}"
*/
access_key?: string | undefined;
/**
* Proxy requests to the selenium server. http, https, socks(v5), socks5, sock4, and pac are accepted. Uses node-proxy-agent. Example: http://user:pass@host:port
*/
proxy?: string | undefined;
/**
* An object which will be passed to the Selenium WebDriver when a new session will be created. You can specify browser name for instance along with other capabilities.
* Example:
* "desiredCapabilities" : {
* "browserName" : "firefox",
* "acceptSslCerts" : true
* }
* You can view the complete list of capabilities https://code.google.com/p/selenium/wiki/DesiredCapabilities.
*/
desiredCapabilities?: NightwatchDesiredCapabilities | undefined;
/**
* An object which will be made available within the test and can be overwritten per environment. Example:"globals" : { "myGlobal" : "some_global" }
*/
globals?: NightwatchTestHooks | undefined;
/**
* An array of folders or file patterns to be skipped (relative to the main source folder).
* Example: "exclude" : ["excluded-folder"] or: "exclude" : ["test-folder/*-smoke.js"]
*/
exclude?: string[] | undefined;
/**
* Folder or file pattern to be used when loading the tests. Files that don't match this patter will be ignored.
* Example: "filter" : "tests/*-smoke.js"
*/
filter?: string | undefined;
/**
* Do not show the Base64 image data in the (verbose) log when taking screenshots.
*/
log_screenshot_data?: boolean | undefined;
/**
* Use xpath as the default locator strategy
*/
use_xpath?: boolean | undefined;
/**
* Same as Selenium settings cli_args. You can override the global cli_args on a per-environment basis.
*/
cli_args?: any;
/**
* End the session automatically when the test is being terminated, usually after a failed assertion.
*/
end_session_on_fail?: boolean | undefined;
/**
* Skip the rest of testcases (if any) when one testcase fails..
*/
skip_testcases_on_fail?: boolean | undefined;
}
export interface NightwatchTestSettingScreenshots extends NightwatchTestSettingGeneric {
/**
* Selenium generates screenshots when command errors occur. With on_failure set to true, also generates screenshots for failing or erroring tests. These are saved on the disk.
* Since v0.7.5 you can disable screenshots for command errors by setting "on_error" to false.
* Example:
* "screenshots" : {
* "enabled" : true,
* "on_failure" : true,
* "on_error" : false,
* "path" : ""
* }
*/
screenshots: NightwatchScreenshotOptions;
}
export interface NightwatchTestOptions extends NightwatchTestSettingGeneric {
screenshots: boolean;
screenshotsPath: string;
}
export interface NightwatchTestSuite {
name: string;
"module": string;
group: string;
results: any;
}
export interface NightwatchAssertionsError {
name: string;
message: string;
showDiff: boolean;
stack: string;
}
export interface NightwatchLanguageChains {
to: Expect;
be: Expect;
been: Expect;
is: Expect;
that: Expect;
which: Expect;
and: Expect;
has: Expect;
have: Expect;
with: Expect;
at: Expect;
of: Expect;
}
export interface NightwatchTestSettings {
[key: string]: NightwatchTestSettingScreenshots;
}
export interface Expect extends NightwatchLanguageChains, NightwatchBrowser {
/**
* Returns the DOM Element
*/
element(property: string): this;
/**
* These methods will perform assertions on the specified target on the current element.
* The targets can be an attribute value, the element's inner text and a css property.
*/
equal(value: string): this;
equals(value: string): this;
contain(value: string): this;
contains(value: string): this;
match(value: string | RegExp): this;
startWith(value: string): this;
startsWith(value: string): this;
endWith(value: string): this;
endsWith(value: string): this;
/**
* Negates any of assertions following in the chain.
*/
not: this;
/**
* These methods perform the same thing which is essentially retrying the assertion for the given amount of time (in milliseconds).
* before or after can be chained to any assertion and thus adding retry capability. You can change the polling interval by defining
* a waitForConditionPollInterval property (in milliseconds) as a global property in your nightwatch.json or in
* your external globals file. Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds).
*/
before(value: number): this;
after(value: number): this;
/**
* Checks if the type (i.e. tag name) of a specified element is of an expected value.
*/
a(value: string, message?: string): this;
an(value: string, message?: string): this;
/**
* Checks if a given attribute of an element exists and optionally if it has the expected value.
*/
attribute(name: string, message?: string): this;
/**
* Checks a given css property of an element exists and optionally if it has the expected value.
*/
css(property: string, message?: string): this;
section(property: string): this;
/**
* Property that checks if an element is currently enabled.
*/
enabled: this;
/**
* Property that checks if an element is present in the DOM.
*/
present: this;
/**
* Property that checks if an OPTION element, or an INPUT element of type checkbox or radio button is currently selected.
*/
selected: this;
/**
* Property that retrieves the text contained by an element. Can be chained to check if contains/equals/matches the specified text or regex.
*/
text: this;
/**
* Property that retrieves the value (i.e. the value attributed) of an element. Can be chained to check if contains/equals/matches the specified text or regex.
*/
value: this;
/**
* Property that asserts the visibility of a specified element.
*/
visible: this;
}
export interface NightwatchAssertions extends NightwatchCommonAssertions, NightwatchCustomAssertions {
/**
* Negates any of assertions following in the chain.
*/
not: this;
}
export interface NightwatchCommonAssertions {
/**
* Checks if the given attribute of an element contains the expected value.
*
* ```
* this.demoTest = function (client) {
* browser.assert.attributeContains('#someElement', 'href', 'google.com');
* };
* ```
*/
attributeContains(selector: string, attribute: string, expected: string, message?: string): NightwatchAPI;
/**
* Checks if the given attribute of an element has the expected value.
*
* ```
* this.demoTest = function (client) {
* browser.assert.attributeEquals('body', 'data-attr', 'some value');
* };
* ```
*/
attributeEquals(selector: string, attribute: string, expected: string, message?: string): NightwatchAPI;
/**
* Checks if the given element contains the specified text.
*
* ```
* this.demoTest = function (client) {
* browser.assert.containsText('#main', 'The Night Watch');
* };
* ```
*/
containsText(selector: string, expectedText: string, message?: string): NightwatchAPI;
/**
* Checks if the given element has the specified CSS class.
*
* ```
* this.demoTest = function (client) {
* browser.assert.cssClassPresent('#main', 'container');
* };
* ```
*/
cssClassPresent(selector: string, className: string, message?: string): NightwatchAPI;
/**
* Checks if the given element exists in the DOM.
*
* ```
* this.demoTest = function (client) {
* browser.assert.elementNotPresent(".should_not_exist");
* };
* ```
*/
cssClassNotPresent(selector: string, className: string, msg?: string): NightwatchAPI;
/**
* Checks if the specified css property of a given element has the expected value.
*
* ```
* this.demoTest = function (client) {
* browser.assert.cssProperty('#main', 'display', 'block');
* };
* ```
*/
cssProperty(selector: string, cssProperty: string, expected: string | number, msg?: string): NightwatchAPI;
deepEqual(value: any, expected: any, message?: string): NightwatchAPI;
deepStrictEqual(value: any, expected: any, message?: string): NightwatchAPI;
doesNotThrow(value: any, expected: any, message?: string): NightwatchAPI;
/**
* Checks if the given element exists in the DOM.
*
* ```
* this.demoTest = function (client) {
* browser.assert.elementPresent("#main");
* };
* ```
*/
elementPresent(selector: string, msg?: string): NightwatchAPI;
/**
* Checks if the given element exists in the DOM.
*
* ```
* this.demoTest = function (client) {
* browser.assert.elementNotPresent(".should_not_exist");
* };
* ```
*/
elementNotPresent(selector: string, msg?: string): NightwatchAPI;
equal(value: any, expected: any, message?: string): NightwatchAPI;
fail(actual?: any, expected?: any, message?: string, operator?: string): NightwatchAPI;
/**
* Checks if the given element is not visible on the page.
*
* ```
* this.demoTest = function (client) {
* browser.assert.hidden(".should_not_be_visible");
* };
* ```
*/
hidden(selector: string, msg?: string): NightwatchAPI;
ifError(value: any, message?: string): NightwatchAPI;
notDeepEqual(actual: any, expected: any, message?: string): NightwatchAPI;
notDeepStrictEqual(value: any, message?: string): NightwatchAPI;
notEqual(actual: any, expected: any, message?: string): NightwatchAPI;
notStrictEqual(value: any, expected: any, message?: string): NightwatchAPI;
ok(actual: boolean, message?: string): NightwatchAPI;
strictEqual(value: any, expected: any, message?: string): NightwatchAPI;
throws(fn: () => void, message?: string): NightwatchAPI;
/**
* Checks if the page title equals the given value.
*
* ```
* this.demoTest = function (client) {
* browser.assert.title("Nightwatch.js");
* };
* ```
*/
title(expected: string, message?: string): NightwatchAPI;
/**
* Checks if the page title equals the given value.
*
* ```
* this.demoTest = function (client) {
* browser.assert.title("Nightwatch.js");
* };
* ```
*/
titleContains(expected: string, message?: string): NightwatchAPI;
/**
* Checks if the current URL contains the given value.
*
* ```
* this.demoTest = function (client) {
* browser.assert.urlContains('google');
* };
* ```
*/
urlContains(expectedText: string, message?: string): NightwatchAPI;
/**
* Checks if the current url equals the given value.
*
* ```
* this.demoTest = function (client) {
* browser.assert.urlEquals('https://www.google.com');
* };
* ```
*/
urlEquals(expected: string, message?: string): NightwatchAPI;
/**
* Checks if the given form element's value equals the expected value.
*
* ```
* this.demoTest = function (client) {
* browser.assert.value("form.login input[type=text]", "username");
* };
* ```
*/
value(selector: string, expectedText: string, message?: string): NightwatchAPI;
/**
* Checks if the given form element's value contains the expected value.
*
* ```
* this.demoTest = function (client) {
* browser.assert.valueContains("form.login input[type=text]", "username");
* };
* ```
*/
valueContains(selector: string, expectedText: string, message?: string): NightwatchAPI;
/**
* Checks if the given element is visible on the page.
*
* ```
* this.demoTest = function (client) {
* browser.assert.visible(".should_be_visible");
* };
* ```
*/
visible(selector: string, message?: string): NightwatchAPI;
NightwatchAssertionsError: NightwatchAssertionsError;
}
export interface NightwatchTypedCallbackResult<T> {
status: 0;
value: T;
state: Error | string;
}
export interface NightwatchCallbackResultError {
status: 1; // we cannot use `number` so giving it a "symbolic" value allows to disjoint the union
value: {
message: string;
screen: string;
class: string;
stackTrace: Array<{
fileName: string;
lineNumber: number;
className: string;
methodName: string;
}>;
};
state: Error | string;
}
export type NightwatchCallbackResult<T> =
| NightwatchTypedCallbackResult<T>
| NightwatchCallbackResultError;
export interface NightwatchLogEntry {
/**
* The log entry message.
*/
message: string;
/**
* The time stamp of log entry in seconds.
*/
timestamp: number;
/**
* Severity level
*/
level: "SEVERE" | "WARNING" | "INFO" | "DEBUG";
source?: string | undefined;
}
export interface NightwatchKeys {
/** Releases all held modifier keys. */
"NULL": string;
/** OS-specific keystroke sequence that performs a cancel action. */
"CANCEL": string;
/** The help key. This key only appears on older Apple keyboards in place of the Insert key. */
"HELP": string;
/** The backspace key. */
"BACK_SPACE": string;
/** The tab key. */
"TAB": string;
/** The clear key. This key only appears on full-size Apple keyboards in place of Num Lock key. */
"CLEAR": string;
/** The return key. */
"RETURN": string;
/** The enter (numpad) key. */
"ENTER": string;
/** The shift key. */
"SHIFT": string;
/** The control key. */
"CONTROL": string;
/** The alt key. */
"ALT": string;
/** The pause key. */
"PAUSE": string;
/** The escape key. */
"ESCAPE": string;
/** The space bar. */
"SPACE": string;
/** The page up key. */
"PAGEUP": string;
/** The page down key. */
"PAGEDOWN": string;
/** The end key. */
"END": string;
/** The home key. */
"HOME": string;
/** The left arrow. */
"ARROW_LEFT": string;
"LEFT_ARROW": string;
/** The up arrow. */
"ARROW_UP": string;
"UP_ARROW": string;
/** The right arrow. */
"ARROW_RIGHT": string;
"RIGHT_ARROW": string;
/** The down arrow. */
"ARROW_DOWN": string;
"DOWN_ARROW": string;
/** The insert key. */
"INSERT": string;
/** The delete key. */
"DELETE": string;
/** The semicolon key. */
"SEMICOLON": string;
/** The equals key. */
"EQUALS": string;
/** The numpad zero key. */
"NUMPAD0": string;
/** The numpad one key. */
"NUMPAD1": string;
/** The numpad two key. */
"NUMPAD2": string;
/** The numpad three key. */
"NUMPAD3": string;
/** The numpad four key. */
"NUMPAD4": string;
/** The numpad five key. */
"NUMPAD5": string;
/** The numpad six key. */
"NUMPAD6": string;
/** The numpad seven key. */
"NUMPAD7": string;
/** The numpad eight key. */
"NUMPAD8": string;
/** The numpad nine key. */
"NUMPAD9": string;
/** The numpad multiply (*) key. */
"MULTIPLY": string;
/** The numpad add (+) key. */
"ADD": string;
/** The numpad separator (=) key. */
"SEPARATOR": string;
/** The numpad subtract (-) key. */
"SUBTRACT": string;
/** The numpad decimal (.) key. */
"DECIMAL": string;
/** The numpad divide (/) key. */
"DIVIDE": string;
/** The F1 key. */
"F1": string;
/** The F2 key. */
"F2": string;
/** The F3 key. */
"F3": string;
/** The F4 key. */
"F4": string;
/** The F5 key. */
"F5": string;
/** The F6 key. */
"F6": string;
/** The F7 key. */
"F7": string;
/** The F8 key. */
"F8": string;
/** The F9 key. */
"F9": string;
/** The F10 key. */
"F10": string;
/** The F11 key. */
"F11": string;
/** The F12 key. */
"F12": string;
/** The meta (Windows) key. */
"META": string;
/** The command (⌘) key. */
"COMMAND": string;
}
export interface NightwatchAPI extends SharedCommands, WebDriverProtocol, NightwatchCustomCommands {
assert: NightwatchAssertions;
expect: Expect;
verify: NightwatchAssertions;
page: {
[name: string]: () => EnhancedPageObject<any, any, any>;
} & NightwatchCustomPageObjects;
/**
* SessionId of the session used by the Nightwatch api.
*/
sessionId: string;
/**
* Override the sessionId used by Nightwatch client with another session id.
*/
setSessionId(sessionId: string): this;
options: NightwatchTestOptions;
Keys: NightwatchKeys;
currentTest: NightwatchTestSuite;
globals: NightwatchGlobals;
launchUrl: string;
launch_url: string;
}
// tslint:disable-next-line:no-empty-interface
export interface NightwatchCustomCommands { }
// tslint:disable-next-line:no-empty-interface
export interface NightwatchCustomAssertions { }
// tslint:disable-next-line:no-empty-interface
export interface NightwatchCustomPageObjects { }
export interface NightwatchBrowser extends NightwatchAPI, NightwatchCustomCommands {
}
export type NightwatchTest = (browser: NightwatchBrowser) => void;
export interface NightwatchTestFunctions {
before?: NightwatchTestHook | undefined;
after?: NightwatchTestHook | undefined;
beforeEach?: NightwatchTestHook | undefined;
afterEach?: NightwatchTestHook | undefined;
"@tags"?: string | string[] | undefined;
"@disabled"?: boolean | undefined;
[key: string]: any;
}
export type NightwatchTestHook =
| GlobalNightwatchTestHookEach
| GlobalNightwatchTestHook
;
export type GlobalNightwatchTestHookEach = ((browser: NightwatchBrowser, done: (err?: any) => void) => void);
export type GlobalNightwatchTestHook = ((done: (err?: any) => void) => void);
export interface NightwatchTestHooks extends NightwatchGlobals {
before?: GlobalNightwatchTestHook | undefined;
after?: GlobalNightwatchTestHook | undefined;
beforeEach?: GlobalNightwatchTestHookEach | undefined;
afterEach?: GlobalNightwatchTestHookEach | undefined;
}
export type NightwatchTests = NightwatchTestFunctions | NightwatchTestHooks;
/**
* Performs an assertion
*
*/
export type NightwatchAssert = (passed: boolean, receivedValue?: any, expectedValue?: any, message?: string, abortOnFailure?: boolean, originalStackTrace?: string) => void;
/**
* Abstract assertion class that will subclass all defined assertions
*
* All assertions must implement the following api:
*
* - @param {T|function} expected
* - @param {string} message
* - @param {function} pass
* - @param {function} value
* - @param {function} command
* - @param {function} - Optional failure
*/
export interface NightwatchAssertion<T, U = any> {
expected: (() => T) | T;
message: string;
pass(value: T): any;
value(result: U): T;
command(callback: (result: U) => void): this;
failure?(result: U): boolean;
api: NightwatchAPI;
client: NightwatchClient;
}
export interface NightwatchClient {
api: NightwatchAPI;
assertion: NightwatchAssert;
locateStrategy?: LocateStrategy | undefined;
}
export interface Nightwatch {
api: NightwatchAPI;
client: NightwatchClient;
assert: NightwatchAssertions;
expect: Expect;
verify: NightwatchAssertions;
}
export type LocateStrategy = "class name" | "css selector" | "id" | "name" | "link text" | "partial link text" | "tag name" | "xpath";
/**
* #### [Enhanced Element Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-element-instances)
* Element instances encapsulate the definition used to handle element selectors.
* Generally you won't need to access them directly,
* instead referring to them using their `@`-prefixed names for selector arguments,
* but they are available through a page object or section's elements property.
*/
export interface EnhancedElementInstance<T> {
/**
* The name of the element as defined by its key in the parent section or the page object's `elements` definition.
* This is the same name used with the `@` prefix in selector arguments for page object commands that refer to the element.
*/
name: string;
/**
* The locate strategy to be used with `selector` when finding the element within the DOM.
*/
locateStrategy: LocateStrategy;
/**
* A reference to the parent object instance.
* This is the parent section or the page object that contained the definition for this object.
*/
parent: T;
/**
* The selector string used to find the element in the DOM.
*/
selector: string;
}
export type EnhancedSectionInstance<Commands = {}, Elements = {}, Sections = {}> = EnhancedPageObject<Commands, Elements, Sections>;
export interface EnhancedPageObjectSections {
[name: string]: EnhancedSectionInstance<any, any, any>;
}
/**
* #### [Enhanced Page Object Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-page-object-instances)
* Page object module definitions are used to define page object instances when their respective factory functions within the page reference of the standard command API is called.
* ```
* var myPageObject = browser.page.MyPage(); // defined in MyPage.js module
* ```
* Every time a factory function like MyPage above is called, a new instance of the page object is instantiated.
*/
export type EnhancedPageObject<Commands = {}, Elements = {}, Sections extends EnhancedPageObjectSections = {}> = Nightwatch & SharedCommands & NightwatchCustomCommands & Commands & {
/**
* A map of Element objects (see [Enhanced Element Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-element-instances)) used by element selectors.
*/
elements: {
[name: string]: EnhancedElementInstance<EnhancedPageObject<Commands, Elements, Sections>>;
};
section: Sections;
/**
* The name of the page object as defined by its module name (not including the extension).
* This is the same name used to access the `page` object factory from the page reference in the command API.
*/
name: string;
/**
* This command is an alias to url and also a convenience method because when called without any arguments
* it performs a call to .url() with passing the value of `url` property on the page object.
* Uses `url` protocol command.
*/
navigate(url?: string, callback?: () => void): EnhancedPageObject<Commands, Elements, Sections>;
};
export interface Cookie {
name: string;
value: string;
path: string;
domain: string;
secure: boolean;
}
export interface SharedCommands extends ClientCommands, ElementCommands { }
export interface ClientCommands {
/**
* Close the current window. This can be useful when you're working with multiple windows open (e.g. an OAuth login).
* Uses `window` protocol command.
*
* @example
* this.demoTest = function (client) {
* client.closeWindow();
* };
*
* @see window
*/
closeWindow(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<null>) => void): this;
/**
* Delete the cookie with the given name. This command is a no-op if there is no such cookie visible to the current page.
*
* @example
* this.demoTest = function(browser) {
* browser.deleteCookie("test_cookie", function() {
* // do something more in here
* });
* }
*
* @see cookie
*/
deleteCookie(cookieName: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<null>) => void): this;
/**
* Delete all cookies visible to the current page.
*
* @example
* this.demoTest = function(browser) {
* browser.deleteCookies(function() {
* // do something more in here
* });
* }
*
* @see cookie
*/
deleteCookies(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<null>) => void): this;
/**
* Ends the session. Uses session protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.end();
* };
*
* @see session
*/
end(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<null>) => void): this;
/**
* Retrieve a single cookie visible to the current page. The cookie is returned as a cookie JSON object,
* as defined [here](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object).
*
* Uses `cookie` protocol command.
*
* @example
* this.demoTest = function(browser) {
* browser.getCookie(name, function callback(result) {
* this.assert.equal(result.value, '123456');
* this.assert.equals(result.name, 'test_cookie');
* });
* }
*
* @see cookie
*/
getCookie(name: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<Cookie>) => void): this;
/**
* Retrieve all cookies visible to the current page. The cookies are returned as an array of cookie JSON object,
* as defined [here](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object).
*
* Uses `cookie` protocol command.
*
* @example
* this.demoTest = function(browser) {
* browser.getCookies(function callback(result) {
* this.assert.equal(result.value.length, 1);
* this.assert.equals(result.value[0].name, 'test_cookie');
* });
* }
*
* @see cookie
*/
getCookies(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<Cookie[]>) => void): this;
/**
* Gets a log from Selenium.
*
* @example
* this.demoTest = function(client) {
* this.getLog('browser', function(logEntriesArray) {
* console.log('Log length: ' + logEntriesArray.length);
* logEntriesArray.forEach(function(log) {
* console.log('[' + log.level + '] ' + log.timestamp + ' : ' + log.message);
* });
* });
* };
*
* @see getLogTypes
*/
getLog(typestring: string, callback?: (this: NightwatchAPI, log: NightwatchLogEntry[]) => void): this;
/**
* Gets the available log types. More info about log types in WebDriver can be found here: https://github.com/SeleniumHQ/selenium/wiki/Logging
*
* @example
* this.demoTest = function(client) {
* this.getLogTypes(function(typesArray) {
* console.log(typesArray);
* });
* };
*
* @see sessionLogTypes
*/
getLogTypes(callback?: (this: NightwatchAPI, result: Array<"client" | "driver" | "browser" | "server">) => void): this;
/**
* Returns the title of the current page. Uses title protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.getTitle(function(title) {
* this.assert.equal(typeof title, 'string');
* this.assert.equal(title, 'Nightwatch.js');
* });
* };
*
* @see title
*/
getTitle(callback?: (this: NightwatchAPI, result?: string) => void): this;
/**
* This command is an alias to url and also a convenience method when called without any arguments in the sense
* that it performs a call to .url() with passing the value of `launch_url` field from the settings file.
* Uses `url` protocol command.
*
* @example
* this.demoTest = function (client) {
* client.init();
* };
*
* @see url
*/
init(url?: string): this;
/**
* Utility command to load an external script into the page specified by url.
*
* @example
* this.demoTest = function(client) {
* this.injectScript("{script-url}", function() {
* // we're all done here.
* });
* };
*/
injectScript(scriptUrl: string, id?: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Utility command to test if the log type is available.
*
* @example
* this.demoTest = function(browser) {
* browser.isLogAvailable('browser', function(isAvailable) {
* // do something more in here
* });
* }
*
* @see getLogTypes
*/
isLogAvailable(typeString: string, callback?: (this: NightwatchAPI, result: boolean) => void): this;
/**
* Maximizes the current window.
*
* @example
* this.demoTest = function (browser) {
* browser.maximizeWindow();
* };
*
* @see windowMaximize
*/
maximizeWindow(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Suspends the test for the given time in milliseconds. If the milliseconds argument is missing it will suspend the test indefinitely
*
* @example
* this.demoTest = function (browser) {
* browser.pause(1000);
* // or suspend indefinitely
* browser.pause();
* };
*/
pause(ms?: number, callback?: (this: NightwatchAPI) => void): this;
/**
* A simple perform command which allows access to the Nightwatch API in a callback. Can be useful if you want to read variables set by other commands.
*
* The callback signature can have up to two parameters.
* - no parameters: callback runs and perform completes immediately at the end of the execution of the callback.
* - one parameter: allows for asynchronous execution within the callback providing a done callback function for completion as the first argument.
* - two parameters: allows for asynchronous execution with the Nightwatch `api` object passed in as the first argument, followed by the done callback.
*
* @example
* this.demoTest = function (browser) {
* var elementValue;
* browser
* .getValue('.some-element', function(result) {
* elementValue = result.value;
* })
* // other stuff going on ...
* //
* // self-completing callback
* .perform(function() {
* console.log('elementValue', elementValue);
* // without any defined parameters, perform
* // completes immediately (synchronously)
* })
* //
* // asynchronous completion
* .perform(function(done) {
* console.log('elementValue', elementValue);
* // potentially other async stuff going on
* // on finished, call the done callback
* done();
* })
* //
* // asynchronous completion including api (client)
* .perform(function(client, done) {
* console.log('elementValue', elementValue);
* // similar to before, but now with client
* // potentially other async stuff going on
* // on finished, call the done callback
* done();
* });
* };
*/
perform(
callback:
| (() => (undefined | Promise<any>))
| ((done: () => void) => void)
| ((client: NightwatchAPI, done: () => void) => void)
): this;
/**
* Resizes the current window.
*
* @example
* this.demoTest = function (browser) {
* browser.resizeWindow(1000, 800);
* };
*
* @see windowSize
*/
resizeWindow(width: number, height: number, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Take a screenshot of the current page and saves it as the given filename.
*
* @example
* this.demoTest = function (browser) {
* browser.saveScreenshot('/path/to/fileName.png');
* };
*
* @see screenshot
*/
saveScreenshot(fileName: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Set a cookie, specified as a cookie JSON object, as defined [here](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object).
*
* Uses `cookie` protocol command.
*
* @example
* this.demoTest = function(browser) {
* browser.setCookie({
* name : "test_cookie",
* value : "test_value",
* path : "/", (Optional)
* domain : "example.org", (Optional)
* secure : false, (Optional)
* httpOnly : false, // (Optional)
* expiry : 1395002765 // (Optional) time in seconds since midnight, January 1, 1970 UTC
* });
* }
*
* @see cookie
*/
setCookie(cookie: Cookie, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Sets the current window position.
*
* @example
* this.demoTest = function (browser) {
* browser.setWindowPosition(0, 0);
* };
*
* @see windowPosition
*/
setWindowPosition(offsetX: number, offsetY: number, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Change focus to another window. The window to change focus to may be specified by its server assigned window handle, or by the value of its name attribute.
*
* To find out the window handle use `windowHandles` command
*
* @example
* this.demoTest = function (browser) {
* browser.windowHandles(function(result) {
* var handle = result.value[0];
* browser.switchWindow(handle);
* });
* };
*
* this.demoTestAsync = async function (browser) {
* const result = browser.windowHandles();
* var handle = result.value[0];
* browser.switchWindow(handle);
* };
*
* @see window
*/
switchWindow(handleOrName: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Convenience command that adds the specified hash (i.e. url fragment) to the current value of the `launch_url` as set in `nightwatch.json`.
*
* @example
* this.demoTest = function (client) {
* client.urlHash('#hashvalue');
* // or
* client.urlHash('hashvalue');
* };
*
* @see url
*/
urlHash(hash: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Sets the locate strategy for selectors to `css selector`, therefore every following selector needs to be specified as css.
*
* @example
* this.demoTest = function (browser) {
* browser
* .useCss() // we're back to CSS now
* .setValue('input[type=text]', 'nightwatch');
* };
*/
useCss(callback?: (this: NightwatchAPI) => void): this;
/**
* Sets the locate strategy for selectors to xpath, therefore every following selector needs to be specified as xpath.
*
* @example
* this.demoTest = function (browser) {
* browser
* .useXpath() // every selector now must be xpath
* .click("//tr[@data-recordid]/span[text()='Search Text']");
* };
*/
useXpath(callback?: (this: NightwatchAPI) => void): this;
}
export interface ElementCommands {
/**
* Clear a textarea or a text input element's value. Uses `elementIdValue` protocol action internally.
*
* @example
* this.demoTest = function (browser) {
* browser.clearValue('input[type=text]');
* };
*
* @see elementIdClear
*/
clearValue(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<null>) => void): this;
/**
* Simulates a click event on the given DOM element. Uses `elementIdClick` protocol action internally.
*
* The element is scrolled into view if it is not already pointer-interactable.
* See the WebDriver specification for <a href="https://www.w3.org/TR/webdriver/#element-interactability" target="_blank">element interactability</a>
*
* @example
* this.demoTest = function (browser) {
* browser.click("#main ul li a.first");
* };
*
* @see elementIdClick
*/
click(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<null>) => void): this;
click(using: LocateStrategy, selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<null>) => void): this;
/**
* Retrieve the value of an attribute for a given DOM element. Uses `elementIdAttribute` protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.getAttribute("#main ul li a.first", "href", function(result) {
* this.assert.equal(typeof result, "object");
* this.assert.equal(result.status, 0);
* this.assert.equal(result.value, "#home");
* });
* };
*
* @see elementIdAttribute
*/
getAttribute(selector: string, attribute: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string | null>) => void): this;
/**
* Retrieve the value of a css property for a given DOM element. Uses `elementIdCssProperty` protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.getCssProperty("#main ul li a.first", "display", function(result) {
* this.assert.equal(typeof result, "object");
* this.assert.equal(result.status, 0);
* this.assert.equal(result.value, 'inline');
* });
* };
*
* @see elementIdCssProperty
*/
getCssProperty(selector: string, cssProperty: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Determine an element's size in pixels. Uses `elementIdSize` protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.getElementSize("#main ul li a.first", function(result) {
* this.assert.equal(typeof result, "object");
* this.assert.equal(result.status, 0);
* this.assert.equal(result.value.width, 500);
* this.assert.equal(result.value.height, 20);
* });
* };
*
* @see elementIdSize
*/
getElementSize(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{ width: number; height: number }>) => void): this;
/**
* Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page.
*
* The element's coordinates are returned as a JSON object with x and y properties. Uses `elementIdLocation` protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.getLocation("#main ul li a.first", function(result) {
* this.assert.equal(typeof result, "object");
* this.assert.equal(result.status, 0);
* this.assert.equal(result.value.x, 200);
* this.assert.equal(result.value.y, 200);
* });
* };
*
* @see elementIdLocation
*/
getLocation(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number }>) => void): this;
/**
* Determine an element's location on the screen once it has been scrolled into view. Uses `elementIdLocationInView` protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.getLocationInView("#main ul li a.first", function(result) {
* this.assert.equal(typeof result, "object");
* this.assert.equal(result.status, 0);
* this.assert.equal(result.value.x, 200);
* this.assert.equal(result.value.y, 200);
* });
* };
*
* @see elementIdLocationInView
*/
getLocationInView(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number }>) => void): this;
/**
* Query for an element's tag name. Uses `elementIdName` protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.getTagName("#main ul li .first", function(result) {
* this.assert.equal(typeof result, "object");
* this.assert.equal(result.status, 0);
* this.assert.equal(result.value, "a");
* });
* };
*
* @see elementIdName
*/
getTagName(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Returns the visible text for the element. Uses `elementIdText` protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.getText("#main ul li a.first", function(result) {
* this.assert.equal(typeof result, "object");
* this.assert.equal(result.status, 0);
* this.assert.equal(result.value, "nightwatchjs.org");
* });
* };
*
* @see elementIdText
*/
getText(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Returns a form element current value. Uses `elementIdValue` protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.getValue("form.login input[type=text]", function(result) {
* this.assert.equal(typeof result, "object");
* this.assert.equal(result.status, 0);
* this.assert.equal(result.value, "enter username");
* });
* };
*
* @see elementIdValue
*/
getValue(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Determine if an element is currently displayed. Uses `elementIdDisplayed` protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.isVisible('#main', function(result) {
* this.assert.equal(typeof result, "object");
* this.assert.equal(result.status, 0);
* this.assert.equal(result.value, true);
* });
* };
*
* @see elementIdDisplayed
*/
isVisible(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<boolean>) => void): this;
/**
* Move the mouse by an offset of the specified element. If an element is provided but no offset, the mouse will be moved to the center of the element.
* If the element is not visible, it will be scrolled into view.
*
* @example
* this.demoTest = function (browser) {
* browser.moveToElement('#main', 10, 10);
* };
*
* @see moveTo
*/
moveToElement(selector: string, xoffset: number, yoffset: number, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Sends some text to an element. Can be used to set the value of a form element or to send a sequence of key strokes to an element. Any UTF-8 character may be specified.
*
* <div class="alert alert-warning"><strong>setValue</strong> does not clear the existing value of the element. To do so, use the <strong>clearValue()</strong> command.</div>
*
* An object map with available keys and their respective UTF-8 characters, as defined on [W3C WebDriver draft spec](https://www.w3.org/TR/webdriver/#character-types),
* is loaded onto the main Nightwatch instance as `browser.Keys`.
*
* @example
* // send some simple text to an input
* this.demoTest = function (browser) {
* browser.setValue('input[type=text]', 'nightwatch');
* };
* //
* // send some text to an input and hit enter.
* this.demoTest = function (browser) {
* browser.setValue('input[type=text]', ['nightwatch', browser.Keys.ENTER]);
* };
*
* @see elementIdValue
*/
setValue(selector: string, inputValue: string | string[], callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Alias for `setValue`.
* @see setValue
*/
sendKeys: SharedCommands["setValue"];
/**
* Submit a FORM element. The submit command may also be applied to any element that is a descendant of a FORM element. Uses `submit` protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.submitForm('form.login');
* };
*
* @see submit
*/
submitForm(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Opposite of `waitForElementPresent`. Waits a given time in milliseconds for an element to be not present (i.e. removed)
* in the page before performing any other commands or assertions.
*
* If the element is still present after the specified amount of time, the test fails.
*
* You can change the polling interval by defining a `waitForConditionPollInterval` property (in milliseconds) in as a global property in your `nightwatch.json` or in your external globals file.
*
* Similarly, a default timeout can be specified as a global `waitForConditionTimeout` property (in milliseconds).
*
* @example
* this.demoTest = function (browser) {
* browser.waitForElementNotPresent('#dialog', 1000);
* };
*
* @see waitForElementPresent
* @since v0.4.0
*/
waitForElementNotPresent(selector: string, time?: number, abortOnFailure?: boolean, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void, message?: string): this;
/**
* Opposite of `waitForElementVisible`. Waits a given time in milliseconds for an element to be not visible (i.e. hidden but existing)
* in the page before performing any other commands or assertions.
*
* If the element fails to be hidden in the specified amount of time, the test fails.
*
* You can change the polling interval by defining a `waitForConditionPollInterval` property (in milliseconds) in as a global property in your `nightwatch.json` or in your external globals file.
*
* Similarly, a default timeout can be specified as a global `waitForConditionTimeout` property (in milliseconds).
*
* @example
* this.demoTest = function (browser) {
* browser.waitForElementNotVisible('#dialog', 1000);
* };
*
* @since v0.4.0
* @see waitForElementVisible
*/
waitForElementNotVisible(selector: string, time?: number, abortOnFailure?: boolean, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void, message?: string): this;
/**
* Waits a given time in milliseconds for an element to be present in the page before performing any other commands or assertions.
*
* If the element fails to be present in the specified amount of time, the test fails. You can change this by setting `abortOnFailure` to `false`.
*
* You can change the polling interval by defining a `waitForConditionPollInterval` property (in milliseconds) in as a global property in your `nightwatch.json` or in your external globals file.
*
* Similarly, a default timeout can be specified as a global `waitForConditionTimeout` property (in milliseconds).
*
* @example
* this.demoTest = function (browser) {
* browser.waitForElementPresent('body', 1000);
* // continue if failed
* browser.waitForElementPresent('body', 1000, false);
* // with callback
* browser.waitForElementPresent('body', 1000, function() {
* // do something while we're here
* });
* // custom Spanish message
* browser.waitForElementPresent('body', 1000, 'elemento %s no era presente en %d ms');
* // many combinations possible - the message is always the last argument
* browser.waitForElementPresent('body', 1000, false, function() {}, 'elemento %s no era presente en %d ms');
* };
*/
waitForElementPresent(selector: string, time?: number, abortOnFailure?: boolean, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void, message?: string): this;
/**
* Waits a given time in milliseconds for an element to be visible in the page before performing any other commands or assertions.
*
* If the element fails to be present and visible in the specified amount of time, the test fails. You can change this by setting `abortOnFailure` to `false`.
*
* You can change the polling interval by defining a `waitForConditionPollInterval` property (in milliseconds) in as a global property in your `nightwatch.json` or in your external globals file.
*
* Similarly, a default timeout can be specified as a global `waitForConditionTimeout` property (in milliseconds).
*
* @example
* this.demoTest = function (browser) {
* browser.waitForElementVisible('body', 1000);
* // continue if failed
* browser.waitForElementVisible('body', 1000, false);
* // with callback
* browser.waitForElementVisible('body', 1000, function() {
* // do something while we're here
* });
* // custom Spanish message
* browser.waitForElementVisible('body', 1000, 'elemento %s no era visible en %d ms');
* // many combinations possible - the message is always the last argument
* browser.waitForElementVisible('body', 1000, false, function() {}, 'elemento %s no era visible en %d ms');
* };
*/
waitForElementVisible(selector: string, time?: number, abortOnFailure?: boolean, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void, message?: string): this;
waitForElementVisible(
using: LocateStrategy,
selector: string,
time?: number,
abortOnFailure?: boolean,
callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void,
message?: string
): this;
}
export interface WebDriverProtocol extends
WebDriverProtocolSessions, WebDriverProtocolNavigation,
WebDriverProtocolCommandContexts,
WebDriverProtocolElements, WebDriverProtocolElementState,
WebDriverProtocolElementInteraction, WebDriverProtocolElementLocation,
WebDriverProtocolDocumentHandling, WebDriverProtocolCookies,
WebDriverProtocolUserActions, WebDriverProtocolUserPrompts,
WebDriverProtocolScreenCapture, WebDriverProtocolMobileRelated { }
export interface WebDriverProtocolSessions {
/**
* Get info about, delete or create a new session. Defaults to the current session.
*
* @example
* this.demoTest = function (browser) {
* browser.session(function(result) {
* console.log(result.value);
* });
* //
* browser.session('delete', function(result) {
* console.log(result.value);
* });
* //
* browser.session('delete', '12345-abc', function(result) {
* console.log(result.value);
* });
* }
*/
session(action?: string, sessionId?: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<Record<string, any>>) => void): this;
/**
* Returns a list of the currently active sessions.
*
* @example
* this.demoTest = function (browser) {
* browser.sessions(function(result) {
* console.log(result.value);
* });
* }
*/
sessions(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<Array<Record<string, any>>>) => void): this;
/**
* Configure the amount of time that a particular type of operation can execute for before they are aborted and a |Timeout| error is returned to the client.
*
* @example
* this.demoTest = function (browser) {
* browser.timeouts('script', 10000, function(result) {
* console.log(result);
* });
* }
*/
timeouts(typeOfOperation: string, ms: number, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Set the amount of time, in milliseconds, that asynchronous scripts executed by `.executeAsync` are permitted to run before they are aborted and a |Timeout| error is returned to the client.
*
* @example
* this.demoTest = function (browser) {
* browser.timeoutsAsyncScript(10000, function(result) {
* console.log(result);
* });
* }
*/
timeoutsAsyncScript(ms: number, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Set the amount of time the driver should wait when searching for elements. If this command is never sent, the driver will default to an implicit wait of 0ms.
*
* @example
* this.demoTest = function (browser) {
* browser.timeoutsImplicitWait(10000, function(result) {
* console.log(result);
* });
* }
*/
timeoutsImplicitWait(ms: number, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Query the server's current status.
*/
status(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{
build: { version: string; revision: string; time: string };
status: { arch: string; name: string; version: string };
}>) => void): this;
/**
* Gets the text of the log type specified. To find out the available log types, use `.getLogTypes()`.
*
* Returns a [log entry JSON object](https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#log-entry-json-object).
*
* @example
* this.demoTest = function (browser) {
* browser.sessionLog('client', function(result) {
* console.log(result.value);
* });
* }
*/
sessionLog(typeString: string, callback?: (this: NightwatchAPI, log: NightwatchLogEntry[]) => void): this;
/**
* Gets an array of strings for which log types are available. This methods returns the entire WebDriver response, if you are only interested in the logs array, use `.getLogTypes()` instead.
*
* @example
* this.demoTest = function (browser) {
* browser.sessionLogTypes(function(result) {
* console.log(result.value);
* });
* }
*/
sessionLogTypes(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<Array<"client" | "driver" | "browser" | "server">>) => void): this;
}
export interface WebDriverProtocolNavigation {
/**
* Retrieve the URL of the current page or navigate to a new URL.
*
* @example
* module.exports = {
* 'demo Test' : function(browser) {
* browser.url(function(result) {
* // return the current url
* console.log(result);
* });
* //
* // navigate to new url:
* browser.url('{URL}');
* //
* //
* // navigate to new url:
* browser.url('{URL}', function(result) {
* console.log(result);
* });
* }
* }
*/
url(url: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Retrieve the URL of the current page or navigate to a new URL.
*
* @example
* module.exports = {
* 'demo Test' : function(browser) {
* browser.url(function(result) {
* // return the current url
* console.log(result);
* });
* //
* // navigate to new url:
* browser.url('{URL}');
* //
* //
* // navigate to new url:
* browser.url('{URL}', function(result) {
* console.log(result);
* });
* }
* }
*/
url(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Navigate backwards in the browser history, if possible.
*/
back(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Navigate forwards in the browser history, if possible.
*/
forward(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Refresh the current page.
*/
refresh(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Get the current page title.
*
* @example
* this.demoTest = function (browser) {
* browser.title(function(result) {
* console.log(result.value);
* });
* }
*/
title(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
}
export interface WebDriverProtocolCommandContexts {
/**
* Change focus to another window or close the current window. Shouldn't normally be used directly, instead `.switchWindow()` and `.closeWindow()` should be used.
*/
window(method: string, handleOrName?: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Retrieve the current window handle.
*
* @example
* this.demoTest = function (browser) {
* browser.windowHandle(function(result) {
* console.log(result.value);
* });
* }
*/
windowHandle(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Retrieve the list of all window handles available to the session.
*
* @example
* this.demoTest = function (browser) {
* browser.windowHandles(function(result) {
* // An array of window handles.
* console.log(result.value);
* });
* }
*/
windowHandles(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string[]>) => void): this;
/**
* Increases the window to the maximum available size without going full-screen.
*
* @example
* this.demoTest = function (browser) {
* browser.windowMaximize('current', function(result) {
* console.log(result);
* });
* }
*/
windowMaximize(handleOrName: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Change or get the position of the specified window. If the second argument is a function it will be used as a callback and
* the call will perform a get request to retrieve the existing window position.
*
* @example
* this.demoTest = function (browser) {
*
* // Change the position of the specified window.
* // If the :windowHandle URL parameter is "current", the currently active window will be moved.
* browser.windowPosition('current', 0, 0, function(result) {
* console.log(result);
* });
*
* // Get the position of the specified window.
* // If the :windowHandle URL parameter is "current", the position of the currently active window will be returned.
* browser.windowPosition('current', function(result) {
* console.log(result.value);
* });
* }
*/
windowPosition(windowHandle: string, offsetX: number, offsetY: number, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Change or get the position of the specified window. If the second argument is a function it will be used as a callback and
* the call will perform a get request to retrieve the existing window position.
*
* @example
* this.demoTest = function (browser) {
*
* // Change the position of the specified window.
* // If the :windowHandle URL parameter is "current", the currently active window will be moved.
* browser.windowPosition('current', 0, 0, function(result) {
* console.log(result);
* });
*
* // Get the position of the specified window.
* // If the :windowHandle URL parameter is "current", the position of the currently active window will be returned.
* browser.windowPosition('current', function(result) {
* console.log(result.value);
* });
* }
*/
windowPosition(windowHandle: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number }>) => void): this;
/**
* Change or get the size of the specified window. If the second argument is a function it will be used as a callback and the call will perform a get request to retrieve the existing window size.
*
* @example
* this.demoTest = function (browser) {
*
* // Return the size of the specified window. If the :windowHandle URL parameter is "current", the size of the currently active window will be returned.
* browser.windowSize('current', function(result) {
* console.log(result.value);
* });
*
* // Change the size of the specified window.
* // If the :windowHandle URL parameter is "current", the currently active window will be resized.
* browser.windowSize('current', 300, 300, function(result) {
* console.log(result.value);
* });
* }
*/
windowSize(windowHandle: string, width: number, height: number, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Change or get the size of the specified window. If the second argument is a function it will be used as a callback and the call will perform a get request to retrieve the existing window size.
*
* @example
* this.demoTest = function (browser) {
*
* // Return the size of the specified window. If the :windowHandle URL parameter is "current", the size of the currently active window will be returned.
* browser.windowSize('current', function(result) {
* console.log(result.value);
* });
*
* // Change the size of the specified window.
* // If the :windowHandle URL parameter is "current", the currently active window will be resized.
* browser.windowSize('current', 300, 300, function(result) {
* console.log(result.value);
* });
* }
*/
windowSize(windowHandle: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{ width: number; height: number }>) => void): this;
/**
* Change focus to another frame on the page. If the frame id is missing or null, the server should switch to the page's default content.
*
* @example
* this.demoTest = function (browser) {
* browser.frame('<ID>', function(result) {
* console.log(result);
* });
* }
*/
frame(frameId: string | undefined | null, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Change focus to the parent context. If the current context is the top level browsing context, the context remains unchanged.
*
* @example
* this.demoTest = function (browser) {
* browser.frameParent(function(result) {
* console.log(result);
* });
* }
*
* @since v0.4.8
*/
frameParent(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
}
export interface WebDriverProtocolElements {
/**
* Search for an element on the page, starting from the document root. The located element will be returned as a web element JSON object.
* First argument to be passed is the locator strategy, which is detailed on the [WebDriver docs](https://www.w3.org/TR/webdriver/#locator-strategies).
*
* The locator stragy can be one of:
* - `css selector`
* - `link text`
* - `partial link text`
* - `tag name`
* - `xpath`
*
* @example
* module.exports = {
* 'demo Test' : function(browser) {
* browser.element('css selector', 'body', function(result) {
* console.log(result.value)
* });
* },
*
* 'es6 async demo Test': async function(browser) {
* const result = await browser.element('css selector', 'body');
* console.log('result value is:', result.value);
* }
* }
*/
element(using: LocateStrategy, value: string, callback: (this: NightwatchAPI, result: NightwatchCallbackResult<{ ELEMENT: string }>) => void): this;
/**
* Search for multiple elements on the page, starting from the document root. The located elements will be returned as web element JSON objects.
* First argument to be passed is the locator strategy, which is detailed on the [WebDriver docs](https://www.w3.org/TR/webdriver/#locator-strategies).
*
* * The locator strategy can be one of:
* - `css selector`
* - `link text`
* - `partial link text`
* - `tag name`
* - `xpath`
*
* @example
* module.exports = {
* 'demo Test' : function(browser) {
* browser.elements('css selector', 'ul li', function(result) {
* console.log(result.value)
* });
* },
*
* 'es6 async demo Test': async function(browser) {
* const result = await browser.elements('css selector', 'ul li');
* console.log('result value is:', result.value);
* },
*
* 'page object demo Test': function (browser) {
* var nightwatch = browser.page.nightwatch();
* nightwatch
* .navigate()
* .assert.titleContains('Nightwatch.js');
*
* nightwatch.api.elements('@featuresList', function(result) {
* console.log(result);
* });
*
* browser.end();
* }
* }
*/
elements(using: LocateStrategy, value: string, callback: (this: NightwatchAPI, result: NightwatchCallbackResult<Array<{ ELEMENT: string }>>) => void): this;
/**
* Search for an element on the page, starting from the identified element. The located element will be returned as a Web Element JSON object.
*
* This command operates on a protocol level and requires a [Web Element ID](https://www.w3.org/TR/webdriver1/#dfn-web-elements).
* Read more on [Element retrieval](https://www.w3.org/TR/webdriver1/#element-retrieval) on the W3C WebDriver spec page.
*
* @example
* module.exports = {
* 'demo Test' : function(browser) {
* browser.elementIdElement('<WebElementId>', 'css selector', '.new-element', function(result) {
* console.log(result.value)
* });
* },
*
* 'es6 async demo Test': async function(browser) {
* const result = await browser.elementIdElement('<WebElementId>', 'css selector', '.new-element');
* console.log(result.value);
* }
* }
*/
elementIdElement(id: string, using: LocateStrategy, value: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{ ELEMENT: string }>) => void): this;
/**
* Search for multiple elements on the page, starting from the identified element. The located element will be returned as a web element JSON objects.
*
* @example
* module.exports = {
* 'demo Test' : function(browser) {
* browser.elementIdElements('<WebElementId>', 'css selector', 'ul li', function(result) {
* console.log(result.value)
* });
* },
*
* 'es6 async demo Test': async function(browser) {
* const result = await browser.elementIdElements('<WebElementId>', 'css selector', 'ul li');
* console.log(result.value);
* }
* }
*/
elementIdElements(id: string, using: LocateStrategy, value: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<Array<{ ELEMENT: string }>>) => void): this;
/**
* Test if two web element IDs refer to the same DOM element.
*
* This command is __deprecated__ and is only available on the [JSON Wire protocol](https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#sessionsessionidelementidequalsother)
*
* @example
* module.exports = {
* 'demo Test' : function(browser) {
* browser.elementIdEquals('<ID-1>', '<ID-2>', function(result) {
* console.log(result.value)
* });
* }
* }
*/
elementIdEquals(id: string, otherId: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<boolean>) => void): this;
/**
* Get the element on the page that currently has focus. The element will be returned as a [Web Element](https://www.w3.org/TR/webdriver1/#dfn-web-elements) JSON object.
*
* @example
* module.exports = {
* 'demo Test' : function(browser) {
* browser.elementActive(function(result) {
* console.log(result.value)
* });
* }
* }
*/
elementActive(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{ ELEMENT: string }>) => void): this;
}
export interface WebDriverProtocolElementState {
/**
* Get the value of an element's attribute.
*/
elementIdAttribute(id: string, attributeName: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string | null>) => void): this;
/**
* Retrieve the computed value of the given CSS property of the given element.
*
* The CSS property to query should be specified using the CSS property name, not the JavaScript property name (e.g. background-color instead of backgroundColor).
*/
elementIdCssProperty(id: string, cssPropertyName: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Determine if an element is currently displayed.
*/
elementIdDisplayed(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<boolean>) => void): this;
/**
* Determine if an element is currently enabled.
*/
elementIdEnabled(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<boolean>) => void): this;
/**
* Retrieve the qualified tag name of the given element.
*/
elementIdName(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Determine if an OPTION element, or an INPUT element of type checkbox or radio button is currently selected.
*/
elementIdSelected(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<boolean>) => void): this;
/**
* Determine an element's size in pixels. The size will be returned as a JSON object with width and height properties.
*/
elementIdSize(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{ width: number; height: number }>) => void): this;
/**
* Returns the visible text for the element.
*/
elementIdText(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
}
export interface WebDriverProtocolElementInteraction {
/**
* Scrolls into view a submittable element excluding buttons or editable element, and then attempts to clear its value, reset the checked state, or text content.
*/
elementIdClear(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Scrolls into view the element and clicks the in-view center point. If the element is not pointer-interactable, an <code>element not interactable</code> error is returned.
*/
elementIdClick(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Scrolls into view the form control element and then sends the provided keys to the element, or returns the current value of the element.
* In case the element is not keyboard interactable, an <code>element not interactable error</code> is returned.
*/
elementIdValue(id: string, value: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Scrolls into view the form control element and then sends the provided keys to the element, or returns the current value of the element.
* In case the element is not keyboard interactable, an <code>element not interactable error</code> is returned.
*/
elementIdValue(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Send a sequence of key strokes to the active element. The sequence is defined in the same format as the `sendKeys` command.
* An object map with available keys and their respective UTF-8 characters, as defined on [W3C WebDriver draft spec](https://www.w3.org/TR/webdriver/#character-types),
* is loaded onto the main Nightwatch instance as `client.Keys`.
*
* Rather than the `setValue`, the modifiers are not released at the end of the call. The state of the modifier keys is kept between calls,
* so mouse interactions can be performed while modifier keys are depressed.
*/
keys(keysToSend: string | string[], callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Submit a FORM element. The submit command may also be applied to any element that is a descendant of a FORM element.
*/
submit(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
}
export interface WebDriverProtocolElementLocation {
/**
* Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page.
*
* The element's coordinates are returned as a JSON object with x and y properties.
*/
elementIdLocation(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number }>) => void): this;
/**
* Determine an element's location on the screen once it has been scrolled into view.
*/
elementIdLocationInView(id: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<{ x: number; y: number }>) => void): this;
}
export interface WebDriverProtocolDocumentHandling {
/**
* Returns a string serialisation of the DOM of the current page.
*/
source(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous.
* The script argument defines the script to execute in the form of a function body. The value returned by that function will be returned to the client.
*
* The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified.
*
* Under the hood, if the `body` param is a function it is converted to a string with `<function>.toString()`. Any references to your current scope are ignored.
*
* To ensure cross-browser compatibility, the specified function should not be in ES6 format (i.e. `() => {}`).
* If the execution of the function fails, the first argument of the callback contains error information.
*
* @example
* this.demoTest = function (browser) {
* browser.execute(function(imageData) {
* // resize operation
* return true;
* }, [imageData], function(result) {
* // result.value === true
* });
* }
*/
execute<T>(body: ((this: undefined, ...data: any[]) => T) | string, args?: any[], callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<T>) => void): this;
/**
* Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be asynchronous.
*
* The function to be injected receives the `done` callback as argument which needs to be called when the asynchronous operation finishes.
* The value passed to the `done` callback is returned to the client.
* Additional arguments for the injected function may be passed as a non-empty array which will be passed before the `done` callback.
*
* Asynchronous script commands may not span page loads. If an unload event is fired while waiting for the script result, an error will be returned.
*
* @example
* this.demoTest = function (browser) {
* browser.executeAsync(function(done) {
* setTimeout(function() {
* done(true);
* }, 500);
* }, function(result) {
* // result.value === true
* });
*
* browser.executeAsync(function(arg1, arg2, done) {
* setTimeout(function() {
* done(true);
* }, 500);
* }, [arg1, arg2], function(result) {
* // result.value === true
* });
* }
*/
executeAsync(script: ((this: undefined, ...data: any[]) => any) | string, args?: any[], callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<any>) => void): this;
}
export interface WebDriverProtocolCookies {
/**
* Retrieve or delete all cookies visible to the current page or set a cookie. Normally this shouldn't be used directly, instead the cookie convenience methods should be used:
* <code>getCookie</code>, <code>getCookies</code>, <code>setCookie</code>, <code>deleteCookie</code>, <code>deleteCookies</code>.
*
* @see getCookies
* @see getCookie
* @see setCookie
* @see deleteCookie
* @see deleteCookies
*/
cookie(method: string, callbackOrCookie?: () => void): this;
}
export interface WebDriverProtocolUserActions {
/**
* Double-clicks at the current mouse coordinates (set by `.moveTo()`).
*/
doubleClick(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Click at the current mouse coordinates (set by `.moveTo()`).
*
* The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button.
*/
mouseButtonClick(button: 0 | 1 | 2 | 'left' | 'middle' | 'right', callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Click and hold the left mouse button (at the coordinates set by the last `moveTo` command). Note that the next mouse-related command that should follow is `mouseButtonUp` .
* Any other mouse command (such as click or another call to buttondown) will yield undefined behaviour.
*
* Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button,
* and if you don't pass in a button but do pass in a callback, it will handle it correctly.
*/
mouseButtonDown(button: 0 | 1 | 2 | 'left' | 'middle' | 'right', callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Releases the mouse button previously held (where the mouse is currently at). Must be called once for every `mouseButtonDown` command issued.
*
* Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button,
* and if you don't pass in a button but do pass in a callback, it will handle it correctly.
*/
mouseButtonUp(button: 0 | 1 | 2 | 'left' | 'middle' | 'right', callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Move the mouse by an offset of the specified [Web Element ID](https://www.w3.org/TR/webdriver1/#dfn-web-elements) or relative to the current mouse cursor, if no element is specified.
* If an element is provided but no offset, the mouse will be moved to the center of the element.
*
* If an element is provided but no offset, the mouse will be moved to the center of the element. If the element is not visible, it will be scrolled into view.
*
* @example
* this.demoTest = function (browser) {
* browser.moveTo(null, 110, 100);
* };
*/
moveTo(element: string | null, xoffset: number, yoffset: number, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
}
export interface WebDriverProtocolUserPrompts {
/**
* Accepts the currently displayed alert dialog. Usually, this is equivalent to clicking on the 'OK' button in the dialog.
*/
acceptAlert(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Dismisses the currently displayed alert dialog. For confirm() and prompt() dialogs, this is equivalent to clicking the 'Cancel' button.
*
* For alert() dialogs, this is equivalent to clicking the 'OK' button.
*/
dismissAlert(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Gets the text of the currently displayed JavaScript alert(), confirm(), or prompt() dialog.
*/
getAlertText(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<string>) => void): this;
/**
* Sends keystrokes to a JavaScript prompt() dialog.
*/
setAlertText(value: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
}
export interface WebDriverProtocolScreenCapture {
/**
* Take a screenshot of the current page.
*/
screenshot(log_screenshot_data: boolean, callback?: (screenshotEncoded: string) => void): this;
}
export interface WebDriverProtocolMobileRelated {
/**
* Get the current browser orientation.
*/
getOrientation(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<"LANDSCAPE" | "PORTRAIT">) => void): this;
/**
* Sets the browser orientation.
*/
setOrientation(orientation: "LANDSCAPE" | "PORTRAIT", callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<void>) => void): this;
/**
* Get a list of the available contexts.
*
* Used by Appium when testing hybrid mobile web apps. More info here: https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/hybrid.md.
*/
contexts(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<any>) => void): this;
/**
* Get current context.
*/
currentContext(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult<any>) => void): this;
/**
* Sets the context.
*/
setContext(context: string, callback?: () => void): this;
} | the_stack |
// We're using a dependency to decode Base64 to UTF-8, because of https://stackoverflow.com/a/30106551/503899
import { Base64 } from "js-base64";
import type { App } from "./App";
import { Fetcher } from "./Fetcher";
import { UserProfile } from "./UserProfile";
import { UserStorage } from "./UserStorage";
import { FunctionsFactory } from "./FunctionsFactory";
import { Credentials, ProviderType } from "./Credentials";
import { ApiKeyAuth } from "./auth-providers";
import { createService as createMongoDBRemoteService } from "./services/MongoDBService";
import routes from "./routes";
const DEFAULT_DEVICE_ID = "000000000000000000000000";
type SimpleObject = Record<string, unknown>;
interface HydratableUserParameters {
app: App;
id: string;
}
interface UserParameters {
app: App;
id: string;
providerType: ProviderType;
accessToken: string;
refreshToken: string;
}
type JWT<CustomDataType = SimpleObject> = {
expires: number;
issuedAt: number;
subject: string;
userData: CustomDataType;
};
/** The state of a user within the app */
export enum UserState {
/** Active, with both access and refresh tokens */
Active = "active",
/** Logged out, but there might still be data persisted about the user, in the browser. */
LoggedOut = "logged-out",
/** Logged out and all data about the user has been removed. */
Removed = "removed",
}
/** The type of a user. */
export enum UserType {
/** Created by the user itself. */
Normal = "normal",
/** Created by an administrator of the app. */
Server = "server",
}
/**
* Representation of an authenticated user of an app.
*/
export class User<
FunctionsFactoryType = Realm.DefaultFunctionsFactory,
CustomDataType = SimpleObject,
UserProfileDataType = Realm.DefaultUserProfileData
> implements Realm.User<FunctionsFactoryType, CustomDataType, UserProfileDataType> {
/**
* The app that this user is associated with.
*/
public readonly app: App<FunctionsFactoryType, CustomDataType>;
/** @inheritdoc */
public readonly id: string;
/** @inheritdoc */
public readonly functions: FunctionsFactoryType & Realm.BaseFunctionsFactory;
/** @inheritdoc */
public readonly providerType: ProviderType;
/** @inheritdoc */
public readonly apiKeys: ApiKeyAuth;
private _accessToken: string | null;
private _refreshToken: string | null;
private _profile: UserProfile<UserProfileDataType> | undefined;
private fetcher: Fetcher;
private storage: UserStorage<UserProfileDataType>;
/**
* @param parameters Parameters of the user.
*/
public constructor(parameters: HydratableUserParameters);
/**
* @param parameters Parameters of the user.
*/
public constructor(parameters: UserParameters);
/**
* @param parameters Parameters of the user.
*/
public constructor(parameters: HydratableUserParameters | UserParameters) {
this.app = (parameters.app as App<unknown, unknown>) as App<FunctionsFactoryType, CustomDataType>;
this.id = parameters.id;
this.storage = new UserStorage(this.app.storage, this.id);
if ("accessToken" in parameters && "refreshToken" in parameters && "providerType" in parameters) {
this._accessToken = parameters.accessToken;
this._refreshToken = parameters.refreshToken;
this.providerType = parameters.providerType;
// Save the parameters to storage, for future instances to be hydrated from
this.storage.accessToken = parameters.accessToken;
this.storage.refreshToken = parameters.refreshToken;
this.storage.providerType = parameters.providerType;
} else {
// Hydrate the rest of the parameters from storage
this._accessToken = this.storage.accessToken;
this._refreshToken = this.storage.refreshToken;
const providerType = this.storage.providerType;
this._profile = this.storage.profile;
if (providerType) {
this.providerType = providerType;
} else {
throw new Error("Storage is missing a provider type");
}
}
this.fetcher = this.app.fetcher.clone({
userContext: { currentUser: (this as unknown) as User },
});
this.apiKeys = new ApiKeyAuth(this.fetcher);
this.functions = FunctionsFactory.create(this.fetcher) as FunctionsFactoryType & Realm.BaseFunctionsFactory;
}
/**
* @returns The access token used to authenticate the user towards MongoDB Realm.
*/
get accessToken(): string | null {
return this._accessToken;
}
/**
* @param token The new access token.
*/
set accessToken(token: string | null) {
this._accessToken = token;
this.storage.accessToken = token;
}
/**
* @returns The refresh token used to issue new access tokens.
*/
get refreshToken(): string | null {
return this._refreshToken;
}
/**
* @param token The new refresh token.
*/
set refreshToken(token: string | null) {
this._refreshToken = token;
this.storage.refreshToken = token;
}
/**
* @returns The current state of the user.
*/
get state(): UserState {
if (this.id in this.app.allUsers) {
return this.refreshToken === null ? UserState.LoggedOut : UserState.Active;
} else {
return UserState.Removed;
}
}
/**
* @returns The logged in state of the user.
*/
get isLoggedIn(): boolean {
return this.state === UserState.Active;
}
get customData(): CustomDataType {
if (this.accessToken) {
const decodedToken = this.decodeAccessToken();
return decodedToken.userData;
} else {
throw new Error("Cannot read custom data without an access token");
}
}
/**
* @returns Profile containing detailed information about the user.
*/
get profile(): UserProfileDataType {
if (this._profile) {
return this._profile.data;
} else {
throw new Error("A profile was never fetched for this user");
}
}
get identities(): Realm.UserIdentity[] {
if (this._profile) {
return this._profile.identities;
} else {
throw new Error("A profile was never fetched for this user");
}
}
get deviceId(): string | null {
if (this.accessToken) {
const payload = this.accessToken.split(".")[1];
if (payload) {
const parsedPayload = JSON.parse(Base64.decode(payload));
const deviceId = parsedPayload["baas_device_id"];
if (typeof deviceId === "string" && deviceId !== DEFAULT_DEVICE_ID) {
return deviceId;
}
}
}
return null;
}
/**
* Refresh the users profile data.
*/
public async refreshProfile(): Promise<void> {
// Fetch the latest profile
const response = await this.fetcher.fetchJSON({
method: "GET",
path: routes.api().auth().profile().path,
});
// Create a profile instance
this._profile = new UserProfile(response);
// Store this for later hydration
this.storage.profile = this._profile;
}
/**
* Log out the user, invalidating the session (and its refresh token).
*/
public async logOut(): Promise<void> {
// Invalidate the refresh token
try {
if (this._refreshToken !== null) {
await this.fetcher.fetchJSON({
method: "DELETE",
path: routes.api().auth().session().path,
tokenType: "refresh",
});
}
} finally {
// Forget the access and refresh token
this.accessToken = null;
this.refreshToken = null;
}
}
/** @inheritdoc */
public async linkCredentials(credentials: Credentials): Promise<void> {
const response = await this.app.authenticator.authenticate(credentials, (this as unknown) as User);
// Sanity check the response
if (this.id !== response.userId) {
const details = `got user id ${response.userId} expected ${this.id}`;
throw new Error(`Link response ment for another user (${details})`);
}
// Update the access token
this.accessToken = response.accessToken;
// Refresh the profile to include the new identity
await this.refreshProfile();
}
/**
* Request a new access token, using the refresh token.
*/
public async refreshAccessToken(): Promise<void> {
const response = await this.fetcher.fetchJSON({
method: "POST",
path: routes.api().auth().session().path,
tokenType: "refresh",
});
const { access_token: accessToken } = response as Record<string, unknown>;
if (typeof accessToken === "string") {
this.accessToken = accessToken;
} else {
throw new Error("Expected an 'access_token' in the response");
}
}
/** @inheritdoc */
public async refreshCustomData(): Promise<CustomDataType> {
await this.refreshAccessToken();
return this.customData;
}
/** @inheritdoc */
public callFunction<ReturnType = unknown>(name: string, ...args: unknown[]): Promise<ReturnType> {
return this.functions.callFunction(name, ...args);
}
/**
* @returns A plain ol' JavaScript object representation of the user.
*/
public toJSON(): Record<string, unknown> {
return {
id: this.id,
accessToken: this.accessToken,
refreshToken: this.refreshToken,
profile: this._profile,
state: this.state,
customData: this.customData,
};
}
/** @inheritdoc */
push(): Realm.Services.Push {
throw new Error("Not yet implemented");
}
/** @inheritdoc */
public mongoClient(serviceName: string): Realm.Services.MongoDB {
return createMongoDBRemoteService(this.fetcher, serviceName);
}
private decodeAccessToken(): JWT<CustomDataType> {
if (this.accessToken) {
// Decode and spread the token
const parts = this.accessToken.split(".");
if (parts.length !== 3) {
throw new Error("Expected an access token with three parts");
}
// Decode the payload
const encodedPayload = parts[1];
const decodedPayload = Base64.decode(encodedPayload);
const parsedPayload = JSON.parse(decodedPayload);
const { exp: expires, iat: issuedAt, sub: subject, user_data: userData = {} } = parsedPayload;
// Validate the types
if (typeof expires !== "number") {
throw new Error("Failed to decode access token 'exp'");
} else if (typeof issuedAt !== "number") {
throw new Error("Failed to decode access token 'iat'");
}
return { expires, issuedAt, subject, userData };
} else {
throw new Error("Missing an access token");
}
}
} | the_stack |
import React, {Component, createRef, useContext} from 'react';
import {HorizontalDotsMinor} from '@shopify/polaris-icons';
import isEqual from 'lodash/isEqual';
import {classNames, variationName} from '../../utilities/css';
import {useI18n} from '../../utilities/i18n';
import type {DisableableAction} from '../../types';
import {ActionList} from '../ActionList';
import {Popover} from '../Popover';
import type {AvatarProps} from '../Avatar';
import {UnstyledLink} from '../UnstyledLink';
import type {ThumbnailProps} from '../Thumbnail';
import {ButtonGroup} from '../ButtonGroup';
import {Checkbox} from '../Checkbox';
import {Button, buttonsFrom} from '../Button';
import {
ResourceListContext,
SELECT_ALL_ITEMS,
ResourceListSelectedItems,
} from '../../utilities/resource-list';
import {globalIdGeneratorFactory} from '../../utilities/unique-id';
import styles from './ResourceItem.scss';
type Alignment = 'leading' | 'trailing' | 'center' | 'fill' | 'baseline';
interface BaseProps {
/** Visually hidden text for screen readers used for item link*/
accessibilityLabel?: string;
/** Individual item name used by various text labels */
name?: string;
/** Id of the element the item onClick controls */
ariaControls?: string;
/** Tells screen reader the controlled element is expanded */
ariaExpanded?: boolean;
/** Unique identifier for the item */
id: string;
/** Content for the media area at the left of the item, usually an Avatar or Thumbnail */
media?: React.ReactElement<AvatarProps | ThumbnailProps>;
/** Makes the shortcut actions always visible */
persistActions?: boolean;
/** 1 or 2 shortcut actions; must be available on the page linked to by url */
shortcutActions?: DisableableAction[];
/** The order the item is rendered */
sortOrder?: number;
/** URL for the resource’s details page (required unless onClick is provided) */
url?: string;
/** Allows url to open in a new tab */
external?: boolean;
/** Callback when clicked (required if url is omitted) */
onClick?(id?: string): void;
/** Content for the details area */
children?: React.ReactNode;
/** Adjust vertical alignment of elements */
verticalAlignment?: Alignment;
/** Prefetched url attribute to bind to the main element being returned */
dataHref?: string;
}
interface PropsWithUrl extends BaseProps {
url: string;
onClick?(id?: string): void;
}
interface PropsWithClick extends BaseProps {
url?: string;
onClick(id?: string): void;
}
export type ResourceItemProps = PropsWithUrl | PropsWithClick;
interface PropsFromWrapper {
context: React.ContextType<typeof ResourceListContext>;
i18n: ReturnType<typeof useI18n>;
}
interface State {
actionsMenuVisible: boolean;
focused: boolean;
focusedInner: boolean;
selected: boolean;
}
type CombinedProps = PropsFromWrapper & (PropsWithUrl | PropsWithClick);
const getUniqueCheckboxID = globalIdGeneratorFactory(
'ResourceListItemCheckbox',
);
const getUniqueOverlayID = globalIdGeneratorFactory('ResourceListItemOverlay');
class BaseResourceItem extends Component<CombinedProps, State> {
static getDerivedStateFromProps(nextProps: CombinedProps, prevState: State) {
const selected = isSelected(nextProps.id, nextProps.context.selectedItems);
if (prevState.selected === selected) {
return null;
}
return {selected};
}
state: State = {
actionsMenuVisible: false,
focused: false,
focusedInner: false,
selected: isSelected(this.props.id, this.props.context.selectedItems),
};
private node: HTMLDivElement | null = null;
private checkboxId = getUniqueCheckboxID();
private overlayId = getUniqueOverlayID();
private buttonOverlay = createRef<HTMLButtonElement>();
shouldComponentUpdate(nextProps: CombinedProps, nextState: State) {
const {
children: nextChildren,
context: {selectedItems: nextSelectedItems, ...restNextContext},
...restNextProps
} = nextProps;
const {
children,
context: {selectedItems, ...restContext},
...restProps
} = this.props;
const nextSelectMode = nextProps.context.selectMode;
return (
!isEqual(this.state, nextState) ||
this.props.context.selectMode !== nextSelectMode ||
(!nextProps.context.selectMode &&
(!isEqual(restProps, restNextProps) ||
!isEqual(restContext, restNextContext)))
);
}
render() {
const {
children,
url,
external,
media,
shortcutActions,
ariaControls,
ariaExpanded,
persistActions = false,
accessibilityLabel,
name,
context: {selectable, selectMode, loading, resourceName},
i18n,
verticalAlignment,
dataHref,
} = this.props;
const {actionsMenuVisible, focused, focusedInner, selected} = this.state;
let ownedMarkup: React.ReactNode = null;
let handleMarkup: React.ReactNode = null;
const mediaMarkup = media ? (
<div className={styles.Media}>{media}</div>
) : null;
if (selectable) {
const checkboxAccessibilityLabel =
name || accessibilityLabel || i18n.translate('Polaris.Common.checkbox');
handleMarkup = (
<div className={styles.Handle} onClick={this.handleLargerSelectionArea}>
<div onClick={stopPropagation} className={styles.CheckboxWrapper}>
<div onChange={this.handleLargerSelectionArea}>
<Checkbox
id={this.checkboxId}
label={checkboxAccessibilityLabel}
labelHidden
checked={selected}
disabled={loading}
/>
</div>
</div>
</div>
);
}
if (media || selectable) {
ownedMarkup = (
<div
className={classNames(
styles.Owned,
!mediaMarkup && styles.OwnedNoMedia,
)}
>
{handleMarkup}
{mediaMarkup}
</div>
);
}
const className = classNames(
styles.ResourceItem,
focused && styles.focused,
selectable && styles.selectable,
selected && styles.selected,
selectMode && styles.selectMode,
persistActions && styles.persistActions,
focusedInner && styles.focusedInner,
);
const listItemClassName = classNames(
styles.ListItem,
focused && !focusedInner && styles.focused,
);
let actionsMarkup: React.ReactNode | null = null;
let disclosureMarkup: React.ReactNode | null = null;
if (shortcutActions && !loading) {
if (persistActions) {
actionsMarkup = (
<div className={styles.Actions} onClick={stopPropagation}>
<ButtonGroup>
{buttonsFrom(shortcutActions, {
plain: true,
})}
</ButtonGroup>
</div>
);
const disclosureAccessibilityLabel = name
? i18n.translate('Polaris.ResourceList.Item.actionsDropdownLabel', {
accessibilityLabel: name,
})
: i18n.translate('Polaris.ResourceList.Item.actionsDropdown');
disclosureMarkup = (
<div className={styles.Disclosure} onClick={stopPropagation}>
<Popover
activator={
<Button
accessibilityLabel={disclosureAccessibilityLabel}
onClick={this.handleActionsClick}
plain
icon={HorizontalDotsMinor}
/>
}
onClose={this.handleCloseRequest}
active={actionsMenuVisible}
>
<ActionList items={shortcutActions} />
</Popover>
</div>
);
} else {
actionsMarkup = (
<div className={styles.Actions} onClick={stopPropagation}>
<ButtonGroup segmented>
{buttonsFrom(shortcutActions, {
size: 'slim',
})}
</ButtonGroup>
</div>
);
}
}
const content = children ? (
<div className={styles.Content}>{children}</div>
) : null;
const containerClassName = classNames(
styles.Container,
verticalAlignment &&
styles[variationName('alignment', verticalAlignment)],
);
const containerMarkup = (
<div className={containerClassName} id={this.props.id}>
{ownedMarkup}
{content}
{actionsMarkup}
{disclosureMarkup}
</div>
);
const tabIndex = loading ? -1 : 0;
const ariaLabel =
accessibilityLabel ||
i18n.translate('Polaris.ResourceList.Item.viewItem', {
itemName: name || (resourceName && resourceName.singular) || '',
});
const accessibleMarkup = url ? (
<UnstyledLink
aria-describedby={this.props.id}
aria-label={ariaLabel}
className={styles.Link}
url={url}
external={external}
tabIndex={tabIndex}
id={this.overlayId}
/>
) : (
<button
className={styles.Button}
aria-label={ariaLabel}
aria-controls={ariaControls}
aria-expanded={ariaExpanded}
onClick={this.handleClick}
tabIndex={tabIndex}
ref={this.buttonOverlay}
/>
);
return (
<li className={listItemClassName} data-href={dataHref}>
<div className={styles.ItemWrapper}>
<div
ref={this.setNode}
className={className}
onClick={this.handleClick}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onKeyUp={this.handleKeyUp}
onMouseOut={this.handleMouseOut}
data-href={url}
>
{accessibleMarkup}
{containerMarkup}
</div>
</div>
</li>
);
}
private setNode = (node: HTMLDivElement | null) => {
this.node = node;
};
private handleFocus = (event: React.FocusEvent<HTMLElement>) => {
if (
event.target === this.buttonOverlay.current ||
(this.node &&
event.target === this.node.querySelector(`#${this.overlayId}`))
) {
this.setState({focused: true, focusedInner: false});
} else if (this.node && this.node.contains(event.target)) {
this.setState({focused: true, focusedInner: true});
}
};
private handleBlur = ({relatedTarget}: React.FocusEvent) => {
if (
this.node &&
relatedTarget instanceof Element &&
this.node.contains(relatedTarget)
) {
return;
}
this.setState({focused: false, focusedInner: false});
};
private handleMouseOut = () => {
this.state.focused && this.setState({focused: false, focusedInner: false});
};
private handleLargerSelectionArea = (event: React.MouseEvent<any>) => {
stopPropagation(event);
this.handleSelection(!this.state.selected, event.nativeEvent.shiftKey);
};
private handleSelection = (value: boolean, shiftKey: boolean) => {
const {
id,
sortOrder,
context: {onSelectionChange},
} = this.props;
if (id == null || onSelectionChange == null) {
return;
}
this.setState({focused: value, focusedInner: value});
onSelectionChange(value, id, sortOrder, shiftKey);
};
private handleClick = (event: React.MouseEvent<any>) => {
stopPropagation(event);
const {
id,
onClick,
url,
context: {selectMode},
} = this.props;
const {ctrlKey, metaKey} = event.nativeEvent;
const anchor = this.node && this.node.querySelector('a');
if (selectMode) {
this.handleLargerSelectionArea(event);
return;
}
if (anchor === event.target) {
return;
}
if (onClick) {
onClick(id);
}
if (url && (ctrlKey || metaKey)) {
window.open(url, '_blank');
return;
}
if (url && anchor) {
anchor.click();
}
};
// This fires onClick when there is a URL on the item
private handleKeyUp = (event: React.KeyboardEvent<HTMLElement>) => {
const {
onClick = noop,
context: {selectMode},
} = this.props;
const {key} = event;
if (key === 'Enter' && this.props.url && !selectMode) {
onClick();
}
};
private handleActionsClick = () => {
this.setState(({actionsMenuVisible}) => ({
actionsMenuVisible: !actionsMenuVisible,
}));
};
private handleCloseRequest = () => {
this.setState({actionsMenuVisible: false});
};
}
function noop() {}
function stopPropagation(event: React.MouseEvent<any>) {
event.stopPropagation();
}
function isSelected(id: string, selectedItems?: ResourceListSelectedItems) {
return Boolean(
selectedItems &&
((Array.isArray(selectedItems) && selectedItems.includes(id)) ||
selectedItems === SELECT_ALL_ITEMS),
);
}
export function ResourceItem(props: ResourceItemProps) {
return (
<BaseResourceItem
{...props}
context={useContext(ResourceListContext)}
i18n={useI18n()}
/>
);
} | the_stack |
* @module Metadata
*/
import { FormatProps } from "../Deserialization/JsonProps";
import { XmlSerializationUtils } from "../Deserialization/XmlSerializationUtils";
import { SchemaItemType } from "../ECObjects";
import { ECObjectsError, ECObjectsStatus } from "../Exception";
import {
DecimalPrecision, FormatTraits, formatTraitsToArray, FormatType, formatTypeToString, FractionalPrecision, parseFormatTrait, parseFormatType,
parsePrecision, parseScientificType, parseShowSignOption, ScientificType, scientificTypeToString, ShowSignOption, showSignOptionToString,
} from "../utils/FormatEnums";
import { InvertedUnit } from "./InvertedUnit";
import { Schema } from "./Schema";
import { SchemaItem } from "./SchemaItem";
import { Unit } from "./Unit";
/**
* @beta
*/
export class Format extends SchemaItem {
public override readonly schemaItemType!: SchemaItemType.Format; // eslint-disable-line
protected _roundFactor: number;
protected _type: FormatType; // required; options are decimal, fractional, scientific, station
protected _precision: number; // required
protected _showSignOption: ShowSignOption; // options: noSign, onlyNegative, signAlways, negativeParentheses
protected _decimalSeparator: string; // optional; default is based on current locale.... TODO: Default is based on current locale
protected _thousandSeparator: string; // optional; default is based on current locale.... TODO: Default is based on current locale
protected _uomSeparator: string; // optional; default is " "; defined separator between magnitude and the unit
protected _stationSeparator: string; // optional; default is "+"
protected _formatTraits: FormatTraits;
protected _spacer: string; // optional; default is " "
protected _includeZero: boolean; // optional; default is true
protected _minWidth?: number; // optional; positive int
protected _scientificType?: ScientificType; // required if type is scientific; options: normalized, zeroNormalized
protected _stationOffsetSize?: number; // required when type is station; positive integer > 0
protected _units?: Array<[Unit | InvertedUnit, string | undefined]>;
constructor(schema: Schema, name: string) {
super(schema, name);
this.schemaItemType = SchemaItemType.Format;
this._roundFactor = 0.0;
this._type = FormatType.Decimal;
this._precision = DecimalPrecision.Six;
this._showSignOption = ShowSignOption.OnlyNegative;
this._decimalSeparator = ".";
this._thousandSeparator = ",";
this._uomSeparator = " ";
this._stationSeparator = "+";
this._formatTraits = 0x0;
this._spacer = " ";
this._includeZero = true;
}
public get roundFactor(): number { return this._roundFactor; }
public get type(): FormatType { return this._type; }
public get precision(): DecimalPrecision | FractionalPrecision { return this._precision; }
public get minWidth(): number | undefined { return this._minWidth; }
public get scientificType(): ScientificType | undefined { return this._scientificType; }
public get showSignOption(): ShowSignOption { return this._showSignOption; }
public get decimalSeparator(): string { return this._decimalSeparator; }
public get thousandSeparator(): string { return this._thousandSeparator; }
public get uomSeparator(): string { return this._uomSeparator; }
public get stationSeparator(): string { return this._stationSeparator; }
public get stationOffsetSize(): number | undefined { return this._stationOffsetSize; }
public get formatTraits(): FormatTraits { return this._formatTraits; }
public get spacer(): string | undefined { return this._spacer; }
public get includeZero(): boolean | undefined { return this._includeZero; }
public get units(): Array<[Unit | InvertedUnit, string | undefined]> | undefined { return this._units; }
private parseFormatTraits(formatTraitsFromJson: string | string[]) {
const formatTraits = Array.isArray(formatTraitsFromJson) ? formatTraitsFromJson : formatTraitsFromJson.split(/,|;|\|/);
for (const traitStr of formatTraits) {
const formatTrait = parseFormatTrait(traitStr);
if (undefined === formatTrait)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'formatTraits' attribute. The string '${traitStr}' is not a valid format trait.`);
this._formatTraits = this._formatTraits | formatTrait;
}
}
public hasFormatTrait(formatTrait: FormatTraits) {
return (this._formatTraits & formatTrait) === formatTrait;
}
/**
* Adds a Unit, or InvertedUnit, with an optional label override.
* @param unit The Unit, or InvertedUnit, to add to this Format.
* @param label A label that overrides the label defined within the Unit when a value is formatted.
*/
protected addUnit(unit: Unit | InvertedUnit, label?: string) {
if (undefined === this._units)
this._units = [];
else { // Validate that a duplicate is not added.
for (const existingUnit of this._units) {
if (unit.fullName.toLowerCase() === existingUnit[0].fullName.toLowerCase())
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has duplicate units, '${unit.fullName}'.`); // TODO: Validation - this should be a validation error not a hard failure.
}
}
this._units.push([unit, label]);
}
protected setPrecision(precision: number) { this._precision = precision; }
private typecheck(formatProps: FormatProps) {
const formatType = parseFormatType(formatProps.type);
if (undefined === formatType)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'type' attribute.`);
this._type = formatType;
if (undefined !== formatProps.precision) {
if (!Number.isInteger(formatProps.precision)) // must be an integer
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'precision' attribute. It should be an integer.`);
const precision = parsePrecision(formatProps.precision, this._type);
if (undefined === precision)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'precision' attribute.`);
this._precision = precision;
}
if (undefined !== formatProps.minWidth) {
if (!Number.isInteger(formatProps.minWidth) || formatProps.minWidth < 0) // must be a positive int
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'minWidth' attribute. It should be a positive integer.`);
this._minWidth = formatProps.minWidth;
}
if (FormatType.Scientific === this.type) {
if (undefined === formatProps.scientificType) // if format type is scientific and scientific type is undefined, throw
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} is 'Scientific' type therefore the attribute 'scientificType' is required.`);
const scientificType = parseScientificType(formatProps.scientificType);
if (undefined === scientificType)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'scientificType' attribute.`);
this._scientificType = scientificType;
}
if (FormatType.Station === this.type) {
if (undefined === formatProps.stationOffsetSize)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} is 'Station' type therefore the attribute 'stationOffsetSize' is required.`);
if (!Number.isInteger(formatProps.stationOffsetSize) || formatProps.stationOffsetSize < 0) // must be a positive int > 0
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'stationOffsetSize' attribute. It should be a positive integer.`);
this._stationOffsetSize = formatProps.stationOffsetSize;
}
if (undefined !== formatProps.showSignOption) {
const signOption = parseShowSignOption(formatProps.showSignOption);
if (undefined === signOption)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'showSignOption' attribute.`);
this._showSignOption = signOption;
}
if (undefined !== formatProps.formatTraits && formatProps.formatTraits.length !== 0)
this.parseFormatTraits(formatProps.formatTraits);
if (undefined !== formatProps.roundFactor)
this._roundFactor = formatProps.roundFactor;
if (undefined !== formatProps.decimalSeparator) {
if (formatProps.decimalSeparator.length > 1)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'decimalSeparator' attribute. It should be an empty or one character string.`);
this._decimalSeparator = formatProps.decimalSeparator;
}
if (undefined !== formatProps.thousandSeparator) {
if (formatProps.thousandSeparator.length > 1)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'thousandSeparator' attribute. It should be an empty or one character string.`);
this._thousandSeparator = formatProps.thousandSeparator;
}
if (undefined !== formatProps.uomSeparator) {
if (formatProps.uomSeparator.length > 1)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'uomSeparator' attribute. It should be an empty or one character string.`);
this._uomSeparator = formatProps.uomSeparator;
}
if (undefined !== formatProps.stationSeparator) {
if (formatProps.stationSeparator.length > 1)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'stationSeparator' attribute. It should be an empty or one character string.`);
this._stationSeparator = formatProps.stationSeparator;
}
if (undefined !== formatProps.composite) { // TODO: This is duplicated below when the units need to be processed...
if (undefined !== formatProps.composite.includeZero)
this._includeZero = formatProps.composite.includeZero;
if (undefined !== formatProps.composite.spacer) {
if (formatProps.composite.spacer.length > 1)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has a composite with an invalid 'spacer' attribute. It should be an empty or one character string.`);
this._spacer = formatProps.composite.spacer;
}
// Composite requires 1-4 units
if (formatProps.composite.units.length <= 0 || formatProps.composite.units.length > 4)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'Composite' attribute. It should have 1-4 units.`);
}
}
public override fromJSONSync(formatProps: FormatProps) {
super.fromJSONSync(formatProps);
this.typecheck(formatProps);
if (undefined === formatProps.composite)
return;
// Units are separated from the rest of the deserialization because of the need to have separate sync and async implementation
for (const unit of formatProps.composite.units) {
const newUnit = this.schema.lookupItemSync<Unit | InvertedUnit>(unit.name);
if (undefined === newUnit)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, ``);
this.addUnit(newUnit, unit.label);
}
}
public override async fromJSON(formatProps: FormatProps) {
await super.fromJSON(formatProps);
this.typecheck(formatProps);
if (undefined === formatProps.composite)
return;
// Units are separated from the rest of the deserialization because of the need to have separate sync and async implementation
for (const unit of formatProps.composite.units) {
const newUnit = await this.schema.lookupItem<Unit | InvertedUnit>(unit.name);
if (undefined === newUnit)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, ``);
this.addUnit(newUnit, unit.label);
}
}
/**
* Save this Format's properties to an object for serializing to JSON.
* @param standalone Serialization includes only this object (as opposed to the full schema).
* @param includeSchemaVersion Include the Schema's version information in the serialized object.
*/
public override toJSON(standalone: boolean = false, includeSchemaVersion: boolean = false): FormatProps {
const schemaJson = super.toJSON(standalone, includeSchemaVersion) as any;
schemaJson.type = formatTypeToString(this.type);
schemaJson.precision = this.precision;
// this._spacer = " ";
// this._includeZero = true;
// Serialize the minimal amount of information needed so anything that is the same as the default, do not serialize.
if (0.0 !== this.roundFactor) schemaJson.roundFactor = this.roundFactor;
if (ShowSignOption.OnlyNegative !== this.showSignOption) schemaJson.showSignOption = showSignOptionToString(this.showSignOption);
if (0x0 !== this.formatTraits) schemaJson.formatTraits = formatTraitsToArray(this.formatTraits);
if ("." !== this.decimalSeparator) schemaJson.decimalSeparator = this.decimalSeparator;
if ("," !== this.thousandSeparator) schemaJson.thousandSeparator = this.thousandSeparator;
if (" " !== this.uomSeparator) schemaJson.uomSeparator = this.uomSeparator;
if (undefined !== this.minWidth) schemaJson.minWidth = this.minWidth;
if (FormatType.Scientific === this.type && undefined !== this.scientificType)
schemaJson.scientificType = scientificTypeToString(this.scientificType);
if (FormatType.Station === this.type) {
if (undefined !== this.stationOffsetSize)
schemaJson.stationOffsetSize = this.stationOffsetSize;
if (" " !== this.stationSeparator)
schemaJson.stationSeparator = this.stationSeparator;
}
if (undefined === this.units)
return schemaJson;
schemaJson.composite = {};
if (" " !== this.spacer) schemaJson.composite.spacer = this.spacer;
if (true !== this.includeZero) schemaJson.composite.includeZero = this.includeZero;
schemaJson.composite.units = [];
for (const unit of this.units) {
schemaJson.composite.units.push({
name: unit[0].fullName,
label: unit[1],
});
}
return schemaJson;
}
/** @internal */
public override async toXml(schemaXml: Document): Promise<Element> {
const itemElement = await super.toXml(schemaXml);
itemElement.setAttribute("type", formatTypeToString(this.type).toLowerCase());
itemElement.setAttribute("precision", this.precision.toString());
itemElement.setAttribute("roundFactor", this.roundFactor.toString());
itemElement.setAttribute("showSignOption", showSignOptionToString(this.showSignOption));
itemElement.setAttribute("decimalSeparator", this.decimalSeparator);
itemElement.setAttribute("thousandSeparator", this.thousandSeparator);
itemElement.setAttribute("uomSeparator", this.uomSeparator);
itemElement.setAttribute("stationSeparator", this.stationSeparator);
if (undefined !== this.minWidth)
itemElement.setAttribute("minWidth", this.minWidth.toString());
if (undefined !== this.scientificType)
itemElement.setAttribute("scientificType", scientificTypeToString(this.scientificType));
if (undefined !== this.stationOffsetSize)
itemElement.setAttribute("stationOffsetSize", this.stationOffsetSize.toString());
const formatTraits = formatTraitsToArray(this.formatTraits);
if (formatTraits.length > 0)
itemElement.setAttribute("formatTraits", formatTraits.join("|"));
if (undefined !== this.units) {
const compositeElement = schemaXml.createElement("Composite");
if (undefined !== this.spacer)
compositeElement.setAttribute("spacer", this.spacer);
if (undefined !== this.includeZero)
compositeElement.setAttribute("includeZero", this.includeZero.toString());
this.units.forEach(([unit, label]) => {
const unitElement = schemaXml.createElement("Unit");
if (undefined !== label)
unitElement.setAttribute("label", label);
const unitName = XmlSerializationUtils.createXmlTypedName(this.schema, unit.schema, unit.name);
unitElement.textContent = unitName;
compositeElement.appendChild(unitElement);
});
itemElement.appendChild(compositeElement);
}
return itemElement;
}
/**
* @alpha Used in schema editing.
*/
protected setFormatType(formatType: FormatType) {
this._type = formatType;
}
/**
* @alpha Used in schema editing.
*/
protected setRoundFactor(roundFactor: number) {
this._roundFactor = roundFactor;
}
/**
* @alpha Used in schema editing.
*/
protected setShowSignOption(signOption: ShowSignOption) {
this._showSignOption = signOption;
}
/**
* @alpha Used in schema editing.
*/
protected setDecimalSeparator(separator: string) {
this._decimalSeparator = separator;
}
/**
* @alpha Used in schema editing.
*/
protected setThousandSeparator(separator: string) {
this._thousandSeparator = separator;
}
/**
* @alpha Used in schema editing.
*/
protected setUomSeparator(separator: string) {
this._uomSeparator = separator;
}
/**
* @alpha Used in schema editing.
*/
protected setStationSeparator(separator: string) {
this._stationSeparator = separator;
}
}
/**
* @internal
* An abstract class used for schema editing.
*/
export abstract class MutableFormat extends Format {
public abstract override addUnit(unit: Unit | InvertedUnit, label?: string): void;
public abstract override setPrecision(precision: number): void;
public abstract override setFormatType(formatType: FormatType): void;
public abstract override setRoundFactor(roundFactor: number): void;
public abstract override setShowSignOption(signOption: ShowSignOption): void;
public abstract override setDecimalSeparator(separator: string): void;
public abstract override setThousandSeparator(separator: string): void;
public abstract override setUomSeparator(separator: string): void;
public abstract override setStationSeparator(separator: string): void;
public abstract override setDisplayLabel(displayLabel: string): void;
} | the_stack |
import type { Point } from '@yozora/ast'
import { isSpaceCharacter, isWhitespaceCharacter } from '@yozora/character'
import type {
IPartialYastBlockToken,
IPhrasingContentLine,
IResultOfEatContinuationText,
IYastBlockToken,
} from '@yozora/core-tokenizer'
import { calcEndPoint } from '@yozora/core-tokenizer'
import invariant from '@yozora/invariant'
import type {
IBlockContentProcessor,
IMatchBlockPhaseHook,
IYastBlockTokenTree,
IYastMatchBlockState,
} from './types'
/**
* Factory function for creating IBlockContentProcessor
*
* @param api
* @param hooks
* @param fallbackHook
*/
export const createBlockContentProcessor = (
hooks: ReadonlyArray<IMatchBlockPhaseHook>,
fallbackHook: IMatchBlockPhaseHook | null,
): IBlockContentProcessor => {
const root: IYastBlockTokenTree = {
_tokenizer: 'root',
nodeType: 'root',
position: {
start: { line: 1, column: 1, offset: 0 },
end: { line: 1, column: 1, offset: 0 },
},
children: [],
}
const stateStack: IYastMatchBlockState[] = []
stateStack.push({
hook: { isContainingBlock: true } as unknown as IMatchBlockPhaseHook,
token: root,
})
/**
* Update the ancients position.
* @param endPoint
*/
let currentStackIndex = 0
const refreshPosition = (endPoint: Point): void => {
for (let sIndex = currentStackIndex; sIndex >= 0; --sIndex) {
const o = stateStack[sIndex]
o.token.position.end = { ...endPoint }
}
}
/**
* Create a processor for processing failed lines.
* @param lines
*/
const createRollbackProcessor = (
hook: IMatchBlockPhaseHook,
lines: ReadonlyArray<IPhrasingContentLine>,
): IBlockContentProcessor | null => {
if (lines.length <= 0) return null
// Reprocess lines.
const candidateHooks = hooks.filter(h => h != hook)
const processor = createBlockContentProcessor(candidateHooks, fallbackHook)
for (const line of lines) {
processor.consume(line)
}
// Return the processor
return processor
}
/**
* Pop the top element up from the IYastMatchBlockState stack.
* @param item
*/
const popup = (): IYastMatchBlockState | undefined => {
const topState = stateStack.pop()
if (topState == null) return undefined
if (stateStack.length > 0) {
const parent = stateStack[stateStack.length - 1]
// Call the `onClose()` hook.
if (topState.hook.onClose != null) {
const result = topState.hook.onClose(topState.token)
if (result != null) {
switch (result.status) {
case 'closingAndRollback': {
const processor = createRollbackProcessor(topState.hook, result.lines)
if (processor == null) break
const internalRoot = processor.done()
parent.token.children!.push(...internalRoot.children)
break
}
case 'failedAndRollback': {
parent.token.children!.pop()
const processor = createRollbackProcessor(topState.hook, result.lines)
if (processor == null) break
const internalRoot = processor.done()
parent.token.children!.push(...internalRoot.children)
break
}
}
}
}
}
if (currentStackIndex >= stateStack.length) {
currentStackIndex = stateStack.length - 1
}
return topState
}
/**
* Remove stale nodes.
* @param includeCurrent whether should also remove the stateStack[currentStackIndex]
*/
const cutStaleBranch = (nextTopIndex: number): void => {
while (stateStack.length > nextTopIndex) popup()
}
/**
* Push the given token into the stateStack, and update the ancients position.
* @param hook
* @param nextToken
* @param saturated
*/
const push = (
hook: IMatchBlockPhaseHook,
nextToken: IYastBlockToken,
saturated: boolean,
): void => {
cutStaleBranch(currentStackIndex + 1)
const parent = stateStack[currentStackIndex]
parent.token.children!.push(nextToken)
refreshPosition(nextToken.position.end)
// Push into the IYastMatchBlockState stack.
currentStackIndex += 1
stateStack.push({ hook, token: nextToken })
// If the give token is saturated, then close it and pop it up.
if (saturated) {
popup()
}
}
/**
* Reprocess failed lines.
* @param hook
* @param lines
* @param parent
*/
const rollback = (
hook: IMatchBlockPhaseHook,
lines: IPhrasingContentLine[],
parent: IYastMatchBlockState,
): boolean => {
const processor = createRollbackProcessor(hook, lines)
if (processor == null) return false
// Refresh the ancient nodes position.
const internalStateStack = processor.shallowSnapshot()
const internalStateRoot = internalStateStack[0]
if (internalStateRoot.token.children != null) {
parent.token.children!.push(...internalStateRoot.token.children)
}
refreshPosition(internalStateRoot.token.position.end)
// Refresh the stateStack and currentStackIndex
for (let i = 1; i < internalStateStack.length; ++i) {
const internalState = internalStateStack[i]
stateStack.push(internalState)
}
currentStackIndex = stateStack.length - 1
return true
}
/**
* Consume simple line.
*/
const consume = (line: Readonly<IPhrasingContentLine>): void => {
const { nodePoints, startIndex: startIndexOfLine, endIndex: endIndexOfLine } = line
let { firstNonWhitespaceIndex, countOfPrecedeSpaces, startIndex: i } = line
/**
* Generate eating line info from current start position.
*/
const getEatingInfo = (): IPhrasingContentLine => ({
nodePoints,
startIndex: i,
endIndex: endIndexOfLine,
firstNonWhitespaceIndex,
countOfPrecedeSpaces,
})
/**
* Update the `i` to the next start index.
* @param nextIndex the next start index.
* @param shouldRefreshPosition
*/
const moveForward = (nextIndex: number, shouldRefreshPosition: boolean): void => {
invariant(
i <= nextIndex,
`[DBTContext#moveForward] nextIndex(${nextIndex}) is behind i(${i}).`,
)
if (shouldRefreshPosition) {
const endPoint = calcEndPoint(nodePoints, nextIndex - 1)
refreshPosition(endPoint)
}
if (i === nextIndex) return
i = nextIndex
countOfPrecedeSpaces = 0
firstNonWhitespaceIndex = nextIndex
for (; firstNonWhitespaceIndex < endIndexOfLine; ++firstNonWhitespaceIndex) {
const c = nodePoints[firstNonWhitespaceIndex].codePoint
if (isSpaceCharacter(c)) {
countOfPrecedeSpaces += 1
continue
}
if (!isWhitespaceCharacter(c)) break
}
}
/**
* Try to Consume nodePoints with a new opener.
* @param hook
* @param line
*/
const consumeNewOpener = (hook: IMatchBlockPhaseHook, line: IPhrasingContentLine): boolean => {
const { token: parentToken } = stateStack[currentStackIndex]
const result = hook.eatOpener(line, parentToken)
if (result == null) return false
// The marker of the new data node cannot be empty.
invariant(
result.nextIndex > i,
'[consumeNewOpener] The marker of the new data node cannot be empty.\n' +
` tokenizer(${result.token._tokenizer})`,
)
// Move forward
moveForward(result.nextIndex, false)
const nextToken: IPartialYastBlockToken = result.token
nextToken._tokenizer = hook.name
push(hook, nextToken as IYastBlockToken, Boolean(result.saturated))
return true
}
/**
* Try to interrupt previous sibling token.
* @param hook
* @param line
* @param stackIndex
*/
const interruptSibling = (hook: IMatchBlockPhaseHook, line: IPhrasingContentLine): boolean => {
if (hook.eatAndInterruptPreviousSibling == null) return false
const { hook: siblingHook, token: siblingToken } = stateStack[currentStackIndex]
const { token: parentToken } = stateStack[currentStackIndex - 1]
if (hook.priority <= siblingHook.priority) return false
// try `eatAndInterruptPreviousSibling` first
const result = hook.eatAndInterruptPreviousSibling(line, siblingToken, parentToken)
if (result == null) return false
// Successfully interrupt the previous node.
cutStaleBranch(currentStackIndex)
// Remove previous sibling from its parent, then append the remaining
// sibling token returned from the `hook.eatAndInterruptPreviousSibling()`
parentToken.children!.pop()
if (result.remainingSibling != null) {
if (Array.isArray(result.remainingSibling)) {
parentToken.children!.push(...result.remainingSibling)
} else {
parentToken.children!.push(result.remainingSibling)
}
}
// Move forward
moveForward(result.nextIndex, false)
const nextToken: IPartialYastBlockToken = result.token
nextToken._tokenizer = hook.name
push(hook, nextToken as IYastBlockToken, Boolean(result.saturated))
return true
}
/**
* Step 1: First we iterate through the open blocks, starting with the
* root document, and descending through last children down to
* the last open block. Each block imposes a condition that the
* line must satisfy if the block is to remain open.
* @see https://github.github.com/gfm/#phase-1-block-structure
*/
const step1 = (): void => {
// Reset current stack index to 1.
currentStackIndex = 1
// The root container block always successfully matches the continuation text.
if (stateStack.length < 2) return
let { token: parentToken } = stateStack[currentStackIndex - 1]
while (i < endIndexOfLine && currentStackIndex < stateStack.length) {
const currentStateItem = stateStack[currentStackIndex]
const currentHook = currentStateItem.hook
const eatingInfo = getEatingInfo()
// Try to interrupt the current token.
if (hooks.some(hook => hook !== currentHook && interruptSibling(hook, eatingInfo))) {
break
}
const result: IResultOfEatContinuationText =
currentHook.eatContinuationText == null
? { status: 'notMatched' }
: currentHook.eatContinuationText(eatingInfo, currentStateItem.token, parentToken)
let finished = false,
rolledBack = false
switch (result.status) {
case 'failedAndRollback': {
// Removed from parent token.
parentToken.children!.pop()
// Cut the stale branch from IYastMatchBlockState stack without call onClose.
stateStack.length = currentStackIndex
currentStackIndex -= 1
if (result.lines.length > 0) {
const parent = stateStack[currentStackIndex]
if (rollback(currentHook, result.lines, parent)) {
rolledBack = true
break
}
}
finished = true
break
}
case 'closingAndRollback': {
// Cut the stale branch before rollback.
cutStaleBranch(currentStackIndex)
if (result.lines.length > 0) {
const parent = stateStack[currentStackIndex]
if (rollback(currentHook, result.lines, parent)) {
rolledBack = true
break
}
}
finished = true
break
}
case 'notMatched': {
currentStackIndex -= 1
finished = true
break
}
case 'closing': {
moveForward(result.nextIndex, true)
currentStackIndex -= 1
finished = true
break
}
case 'opening': {
moveForward(result.nextIndex, true)
break
}
default:
throw new TypeError(
`[eatContinuationText] unexpected status (${(result as any).status}).`,
)
}
if (finished) break
if (rolledBack) continue
// Descend down the tree to the next unclosed node.
currentStackIndex += 1
parentToken = currentStateItem.token
}
}
/**
* Step 2: Next, after consuming the continuation markers for existing
* blocks, we look for new block starts (e.g. '>' for a blockquote)
*/
const step2 = (): void => {
if (i >= endIndexOfLine) return
/**
* If currentStackIndex less than stateStack.length, that means the step1
* ended prematurely, so we should ensure the first newOpener could
* interrupt the potential lazy continuation text (if it present).
*/
if (currentStackIndex < stateStack.length) {
const lastChild = stateStack[stateStack.length - 1]
if (lastChild.hook.eatLazyContinuationText != null) {
// Try to find a new internal block.
const eatingInfo = getEatingInfo()
/**
* An indented code block cannot interrupt a paragraph.
* @see https://github.github.com/gfm/#example-77
* @see https://github.github.com/gfm/#example-216
* @see https://github.github.com/gfm/#example-292
* @see https://github.github.com/gfm/#example-269
*/
if (eatingInfo.countOfPrecedeSpaces >= 4) return
}
} else {
// Otherwise, reset the currentStackIndex point to the top of the stack.
currentStackIndex = stateStack.length - 1
}
while (i < endIndexOfLine && stateStack[currentStackIndex].hook.isContainingBlock) {
// Try to eat a new internal block.
let hasNewOpener = false
const eatingInfo = getEatingInfo()
for (const hook of hooks) {
if (consumeNewOpener(hook, eatingInfo)) {
hasNewOpener = true
break
}
}
if (!hasNewOpener) break
}
}
/**
* Step 3: Finally, we look at the remainder of the line (after block
* markers like >, list markers, and indentation have been consumed).
* This is text that can be incorporated into the last open block
* (a paragraph, code block, heading, or raw HTML).
*
* If no lazy continuation text found, then close current opening
* token.
*/
const step3 = (): boolean => {
if (i >= endIndexOfLine || currentStackIndex + 1 >= stateStack.length) return false
const { hook, token } = stateStack[stateStack.length - 1]
if (hook.eatLazyContinuationText == null) return false
const { token: parentToken } = stateStack[stateStack.length - 2]
const eatingInfo = getEatingInfo()
const result = hook.eatLazyContinuationText(eatingInfo, token, parentToken)
switch (result.status) {
case 'notMatched': {
return false
}
case 'opening': {
// Move forward and update position
currentStackIndex = stateStack.length - 1
moveForward(result.nextIndex, true)
// Lazy continuation text found, so move forward the currentStackIndex
// to the top of the stateStack.
currentStackIndex = stateStack.length - 1
return true
}
default:
throw new TypeError(
`[eatLazyContinuationText] unexpected status (${(result as any).status}).`,
)
}
}
/**
* Initialize the first non-whitespace index.
*
* Not need, as the passed phrasing content line has already be initialized
* the values.
*/
// moveForward(startIndexOfLine, false)
step1()
step2()
// No lazy continuation text found, so closed the stale branch.
if (!step3()) {
cutStaleBranch(currentStackIndex + 1)
}
// Try fallback tokenizer
if (fallbackHook != null && i < endIndexOfLine) {
const eatingInfo = getEatingInfo()
consumeNewOpener(fallbackHook, eatingInfo)
}
invariant(
firstNonWhitespaceIndex >= endIndexOfLine,
'[IBlockContentProcessor] there is still unprocessed contents.' +
` startIndexOfLine(${startIndexOfLine}), endIndexOfLine(${endIndexOfLine})`,
)
}
/**
* All the content has been processed and perform the final collation actions.
*/
const done = (): IYastBlockTokenTree => {
while (stateStack.length > 1) popup()
return root
}
return {
consume,
done,
shallowSnapshot: () => [...stateStack],
}
} | the_stack |
'use strict';
import * as assert from 'assert';
import * as platform from 'vs/base/common/platform';
import fs = require('fs');
import os = require('os');
import path = require('path');
import extfs = require('vs/base/node/extfs');
import pfs = require('vs/base/node/pfs');
import Uri from 'vs/base/common/uri';
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
import { parseArgs } from 'vs/platform/environment/node/argv';
import { BackupMainService } from 'vs/platform/backup/electron-main/backupMainService';
import { IBackupWorkspacesFormat } from 'vs/platform/backup/common/backup';
import { HotExitConfiguration } from 'vs/platform/files/common/files';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
class TestBackupMainService extends BackupMainService {
constructor(backupHome: string, backupWorkspacesPath: string, configService: TestConfigurationService) {
super(new EnvironmentService(parseArgs(process.argv), process.execPath), configService);
this.backupHome = backupHome;
this.workspacesJsonPath = backupWorkspacesPath;
// Force a reload with the new paths
this.loadSync();
}
public removeBackupPathSync(workspaceIdenfitier: string, isEmptyWorkspace: boolean): void {
return super.removeBackupPathSync(workspaceIdenfitier, isEmptyWorkspace);
}
public loadSync(): void {
super.loadSync();
}
public dedupeFolderWorkspaces(backups: IBackupWorkspacesFormat): IBackupWorkspacesFormat {
return super.dedupeFolderWorkspaces(backups);
}
public toBackupPath(workspacePath: string): string {
return path.join(this.backupHome, super.getWorkspaceHash(workspacePath));
}
public getWorkspaceHash(workspacePath: string): string {
return super.getWorkspaceHash(workspacePath);
}
}
suite('BackupMainService', () => {
const parentDir = path.join(os.tmpdir(), 'vsctests', 'service');
const backupHome = path.join(parentDir, 'Backups');
const backupWorkspacesPath = path.join(backupHome, 'workspaces.json');
const fooFile = Uri.file(platform.isWindows ? 'C:\\foo' : '/foo');
const barFile = Uri.file(platform.isWindows ? 'C:\\bar' : '/bar');
let service: TestBackupMainService;
let configService: TestConfigurationService;
setup(done => {
configService = new TestConfigurationService();
service = new TestBackupMainService(backupHome, backupWorkspacesPath, configService);
// Delete any existing backups completely and then re-create it.
extfs.del(backupHome, os.tmpdir(), () => {
pfs.mkdirp(backupHome).then(() => {
done();
});
});
});
teardown(done => {
extfs.del(backupHome, os.tmpdir(), done);
});
test('service validates backup workspaces on startup and cleans up', done => {
// 1) backup workspace path does not exist
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
service.registerWindowForBackupsSync(2, false, null, barFile.fsPath);
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
// 2) backup workspace path exists with empty contents within
fs.mkdirSync(service.toBackupPath(fooFile.fsPath));
fs.mkdirSync(service.toBackupPath(barFile.fsPath));
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
service.registerWindowForBackupsSync(2, false, null, barFile.fsPath);
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
assert.ok(!fs.exists(service.toBackupPath(fooFile.fsPath)));
assert.ok(!fs.exists(service.toBackupPath(barFile.fsPath)));
// 3) backup workspace path exists with empty folders within
fs.mkdirSync(service.toBackupPath(fooFile.fsPath));
fs.mkdirSync(service.toBackupPath(barFile.fsPath));
fs.mkdirSync(path.join(service.toBackupPath(fooFile.fsPath), 'file'));
fs.mkdirSync(path.join(service.toBackupPath(barFile.fsPath), 'untitled'));
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
service.registerWindowForBackupsSync(2, false, null, barFile.fsPath);
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
assert.ok(!fs.exists(service.toBackupPath(fooFile.fsPath)));
assert.ok(!fs.exists(service.toBackupPath(barFile.fsPath)));
// 4) backup workspace path points to a workspace that no longer exists
// so it should convert the backup worspace to an empty workspace backup
const fileBackups = path.join(service.toBackupPath(fooFile.fsPath), 'file');
fs.mkdirSync(service.toBackupPath(fooFile.fsPath));
fs.mkdirSync(service.toBackupPath(barFile.fsPath));
fs.mkdirSync(fileBackups);
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
assert.equal(service.getWorkspaceBackupPaths().length, 1);
assert.equal(service.getEmptyWorkspaceBackupPaths().length, 0);
fs.writeFileSync(path.join(fileBackups, 'backup.txt'), '');
service.loadSync();
assert.equal(service.getWorkspaceBackupPaths().length, 0);
assert.equal(service.getEmptyWorkspaceBackupPaths().length, 1);
done();
});
suite('loadSync', () => {
test('getWorkspaceBackupPaths() should return [] when workspaces.json doesn\'t exist', () => {
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
});
test('getWorkspaceBackupPaths() should return [] when workspaces.json is not properly formed JSON', () => {
fs.writeFileSync(backupWorkspacesPath, '');
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{]');
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, 'foo');
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
});
test('getWorkspaceBackupPaths() should return [] when folderWorkspaces in workspaces.json is absent', () => {
fs.writeFileSync(backupWorkspacesPath, '{}');
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
});
test('getWorkspaceBackupPaths() should return [] when folderWorkspaces in workspaces.json is not a string array', () => {
fs.writeFileSync(backupWorkspacesPath, '{"folderWorkspaces":{}}');
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{"folderWorkspaces":{"foo": ["bar"]}}');
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{"folderWorkspaces":{"foo": []}}');
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{"folderWorkspaces":{"foo": "bar"}}');
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{"folderWorkspaces":"foo"}');
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{"folderWorkspaces":1}');
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
});
test('getWorkspaceBackupPaths() should return [] when files.hotExit = "onExitAndWindowClose"', () => {
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath.toUpperCase());
assert.deepEqual(service.getWorkspaceBackupPaths(), [fooFile.fsPath.toUpperCase()]);
configService.setUserConfiguration('files.hotExit', HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE);
service.loadSync();
assert.deepEqual(service.getWorkspaceBackupPaths(), []);
});
test('getEmptyWorkspaceBackupPaths() should return [] when workspaces.json doesn\'t exist', () => {
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
});
test('getEmptyWorkspaceBackupPaths() should return [] when workspaces.json is not properly formed JSON', () => {
fs.writeFileSync(backupWorkspacesPath, '');
service.loadSync();
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{]');
service.loadSync();
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, 'foo');
service.loadSync();
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
});
test('getEmptyWorkspaceBackupPaths() should return [] when folderWorkspaces in workspaces.json is absent', () => {
fs.writeFileSync(backupWorkspacesPath, '{}');
service.loadSync();
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
});
test('getEmptyWorkspaceBackupPaths() should return [] when folderWorkspaces in workspaces.json is not a string array', () => {
fs.writeFileSync(backupWorkspacesPath, '{"emptyWorkspaces":{}}');
service.loadSync();
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{"emptyWorkspaces":{"foo": ["bar"]}}');
service.loadSync();
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{"emptyWorkspaces":{"foo": []}}');
service.loadSync();
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{"emptyWorkspaces":{"foo": "bar"}}');
service.loadSync();
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{"emptyWorkspaces":"foo"}');
service.loadSync();
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
fs.writeFileSync(backupWorkspacesPath, '{"emptyWorkspaces":1}');
service.loadSync();
assert.deepEqual(service.getEmptyWorkspaceBackupPaths(), []);
});
});
suite('dedupeFolderWorkspaces', () => {
test('should ignore duplicates on Windows and Mac', () => {
// Skip test on Linux
if (platform.isLinux) {
return;
}
const backups: IBackupWorkspacesFormat = {
folderWorkspaces: platform.isWindows ? ['c:\\FOO', 'C:\\FOO', 'c:\\foo'] : ['/FOO', '/foo'],
emptyWorkspaces: []
};
service.dedupeFolderWorkspaces(backups);
assert.equal(backups.folderWorkspaces.length, 1);
if (platform.isWindows) {
assert.deepEqual(backups.folderWorkspaces, ['c:\\FOO'], 'should return the first duplicated entry');
} else {
assert.deepEqual(backups.folderWorkspaces, ['/FOO'], 'should return the first duplicated entry');
}
});
});
suite('registerWindowForBackups', () => {
test('should persist paths to workspaces.json', done => {
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
service.registerWindowForBackupsSync(2, false, null, barFile.fsPath);
assert.deepEqual(service.getWorkspaceBackupPaths(), [fooFile.fsPath, barFile.fsPath]);
pfs.readFile(backupWorkspacesPath, 'utf-8').then(buffer => {
const json = <IBackupWorkspacesFormat>JSON.parse(buffer);
assert.deepEqual(json.folderWorkspaces, [fooFile.fsPath, barFile.fsPath]);
done();
});
});
test('should always store the workspace path in workspaces.json using the case given, regardless of whether the file system is case-sensitive', done => {
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath.toUpperCase());
assert.deepEqual(service.getWorkspaceBackupPaths(), [fooFile.fsPath.toUpperCase()]);
pfs.readFile(backupWorkspacesPath, 'utf-8').then(buffer => {
const json = <IBackupWorkspacesFormat>JSON.parse(buffer);
assert.deepEqual(json.folderWorkspaces, [fooFile.fsPath.toUpperCase()]);
done();
});
});
});
suite('removeBackupPathSync', () => {
test('should remove folder workspaces from workspaces.json', done => {
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
service.registerWindowForBackupsSync(2, false, null, barFile.fsPath);
service.removeBackupPathSync(fooFile.fsPath, false);
pfs.readFile(backupWorkspacesPath, 'utf-8').then(buffer => {
const json = <IBackupWorkspacesFormat>JSON.parse(buffer);
assert.deepEqual(json.folderWorkspaces, [barFile.fsPath]);
service.removeBackupPathSync(barFile.fsPath, false);
pfs.readFile(backupWorkspacesPath, 'utf-8').then(content => {
const json2 = <IBackupWorkspacesFormat>JSON.parse(content);
assert.deepEqual(json2.folderWorkspaces, []);
done();
});
});
});
test('should remove empty workspaces from workspaces.json', done => {
service.registerWindowForBackupsSync(1, true, 'foo');
service.registerWindowForBackupsSync(2, true, 'bar');
service.removeBackupPathSync('foo', true);
pfs.readFile(backupWorkspacesPath, 'utf-8').then(buffer => {
const json = <IBackupWorkspacesFormat>JSON.parse(buffer);
assert.deepEqual(json.emptyWorkspaces, ['bar']);
service.removeBackupPathSync('bar', true);
pfs.readFile(backupWorkspacesPath, 'utf-8').then(content => {
const json2 = <IBackupWorkspacesFormat>JSON.parse(content);
assert.deepEqual(json2.emptyWorkspaces, []);
done();
});
});
});
test('should fail gracefully when removing a path that doesn\'t exist', done => {
const workspacesJson: IBackupWorkspacesFormat = { folderWorkspaces: [fooFile.fsPath], emptyWorkspaces: [] };
pfs.writeFile(backupWorkspacesPath, JSON.stringify(workspacesJson)).then(() => {
service.removeBackupPathSync(barFile.fsPath, false);
service.removeBackupPathSync('test', true);
pfs.readFile(backupWorkspacesPath, 'utf-8').then(content => {
const json = <IBackupWorkspacesFormat>JSON.parse(content);
assert.deepEqual(json.folderWorkspaces, [fooFile.fsPath]);
done();
});
});
});
});
suite('getWorkspaceHash', () => {
test('should perform an md5 hash on the path', () => {
assert.equal(service.getWorkspaceHash('/foo'), '1effb2475fcfba4f9e8b8a1dbc8f3caf');
});
test('should ignore case on Windows and Mac', () => {
// Skip test on Linux
if (platform.isLinux) {
return;
}
if (platform.isMacintosh) {
assert.equal(service.getWorkspaceHash('/foo'), service.getWorkspaceHash('/FOO'));
}
if (platform.isWindows) {
assert.equal(service.getWorkspaceHash('c:\\foo'), service.getWorkspaceHash('C:\\FOO'));
}
});
});
suite('getBackupPath', () => {
test('should return the window\'s correct path', done => {
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
service.registerWindowForBackupsSync(2, true, 'test');
service.getBackupPath(1).then(window1Path => {
assert.equal(window1Path, service.toBackupPath(fooFile.fsPath));
service.getBackupPath(2).then(window2Path => {
assert.equal(window2Path, path.join(backupHome, 'test'));
done();
});
});
});
test('should override stale window paths with new paths', done => {
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
service.registerWindowForBackupsSync(1, false, null, barFile.fsPath);
service.getBackupPath(1).then(windowPath => {
assert.equal(windowPath, service.toBackupPath(barFile.fsPath));
done();
});
});
test('should throw when the window is not registered', () => {
assert.throws(() => service.getBackupPath(1));
});
});
suite('mixed path casing', () => {
test('should handle case insensitive paths properly (registerWindowForBackupsSync)', done => {
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath.toUpperCase());
if (platform.isLinux) {
assert.equal(service.getWorkspaceBackupPaths().length, 2);
} else {
assert.equal(service.getWorkspaceBackupPaths().length, 1);
}
done();
});
test('should handle case insensitive paths properly (removeBackupPathSync)', done => {
// same case
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
service.removeBackupPathSync(fooFile.fsPath, false);
assert.equal(service.getWorkspaceBackupPaths().length, 0);
// mixed case
service.registerWindowForBackupsSync(1, false, null, fooFile.fsPath);
service.removeBackupPathSync(fooFile.fsPath.toUpperCase(), false);
if (platform.isLinux) {
assert.equal(service.getWorkspaceBackupPaths().length, 1);
} else {
assert.equal(service.getWorkspaceBackupPaths().length, 0);
}
done();
});
});
}); | the_stack |
import { Injectable, Autowired } from '@opensumi/di';
import {
IToolbarActionBtnDelegate,
IToolbarRegistry,
createToolbarActionBtn,
CommandService,
CommandRegistry,
IDisposable,
IToolbarActionBtnState,
IToolbarActionSelectDelegate,
createToolbarActionSelect,
IEventBus,
ExtensionActivateEvent,
IToolbarPopoverRegistry,
} from '@opensumi/ide-core-browser';
import { Disposable } from '@opensumi/ide-core-browser';
import { IIconService, IconType } from '@opensumi/ide-theme';
import { EMIT_EXT_HOST_EVENT } from '../../common';
import { IMainThreadToolbar } from '../../common/sumi/toolbar';
import { ExtensionLoadingView } from '../components';
import { IToolbarButtonContribution, IToolbarSelectContribution } from './types';
@Injectable()
export class KaitianExtensionToolbarService {
private btnDelegates = new Map<string, IToolbarActionBtnDelegate>();
private selectDelegates = new Map<string, IToolbarActionSelectDelegate<any>>();
private connected = new Set<string>();
@Autowired(IEventBus)
protected eventBus: IEventBus;
@Autowired(IToolbarPopoverRegistry)
protected readonly toolbarPopover: IToolbarPopoverRegistry;
@Autowired(IToolbarRegistry)
toolbarRegistry: IToolbarRegistry;
@Autowired(IIconService)
iconService: IIconService;
@Autowired(CommandService)
commandService: CommandService;
@Autowired(CommandRegistry)
commandRegistry: CommandRegistry;
constructor() {
this.commandRegistry.registerCommand(
{
id: 'sumi-extension.toolbar.btn.setState',
},
{
execute: (id: string, state: string, title?: string) => {
if (this.btnDelegates.has(id)) {
this.btnDelegates.get(id)!.setState(state, title);
}
},
},
);
this.commandRegistry.registerCommand(
{
id: 'sumi-extension.toolbar.btn.setContext',
},
{
execute: (id: string, context: string) => {
if (this.btnDelegates.has(id)) {
const delegate = this.btnDelegates.get(id);
if (delegate) {
delegate.setContext(context);
}
}
},
},
);
this.commandRegistry.registerCommand(
{
id: 'sumi-extension.toolbar.btn.connectHandle',
},
{
execute: (id: string) => {
if (!this.connected.has(id)) {
this.doConnectToolbarButtonHandle(id);
this.connected.add(id);
}
},
},
);
this.commandRegistry.registerCommand(
{
id: 'sumi-extension.toolbar.select.setState',
},
{
execute: (id: string, state: string) => {
if (this.selectDelegates.has(id)) {
this.selectDelegates.get(id)!.setState(state);
}
},
},
);
this.commandRegistry.registerCommand(
{
id: 'sumi-extension.toolbar.select.setOptions',
},
{
execute: (id: string, extensionBasePath: string, options: any) => {
if (this.selectDelegates.has(id)) {
options.forEach((o) => {
if (o.iconPath) {
o.iconClass = this.iconService.fromIcon(
extensionBasePath,
o.iconPath,
o.iconMaskMode ? IconType.Mask : IconType.Background,
)!;
}
});
this.selectDelegates.get(id)!.setOptions(options);
}
},
},
);
this.commandRegistry.registerCommand(
{
id: 'sumi-extension.toolbar.select.setSelect',
},
{
execute: (id: string, value: any) => {
if (this.selectDelegates.has(id)) {
this.selectDelegates.get(id)!.setSelect(value);
}
},
},
);
this.commandRegistry.registerCommand(
{
id: 'sumi-extension.toolbar.select.connectHandle',
},
{
execute: (id: string) => {
if (!this.connected.has(id)) {
this.doConnectToolbarSelectHandle(id);
this.connected.add(id);
}
if (this.selectDelegates.get(id)) {
return this.selectDelegates.get(id)!.getValue();
}
},
},
);
this.commandRegistry.registerCommand(
{
id: 'sumi-extension.toolbar.showPopover',
},
{
execute: (id: string, style) => {
if (this.btnDelegates.has(id)) {
this.btnDelegates.get(id)!.showPopOver(style);
}
},
},
);
this.commandRegistry.registerCommand(
{
id: 'sumi-extension.toolbar.hidePopover',
},
{
execute: (id: string) => {
if (this.btnDelegates.has(id)) {
this.btnDelegates.get(id)!.hidePopOver();
}
},
},
);
}
getPopoverComponent(id: string, contribution: IToolbarButtonContribution): React.FC {
const PlaceHolderComponent = () =>
ExtensionLoadingView({
style: {
minHeight: contribution.popoverStyle?.minHeight ? Number(contribution.popoverStyle?.minHeight) : 200,
minWidth: contribution.popoverStyle?.minWidth ? Number(contribution.popoverStyle?.minWidth) : 300,
},
});
return this.toolbarPopover.getComponent(id) || PlaceHolderComponent;
}
registerToolbarButton(
extensionId: string,
extensionBasePath: string,
contribution: IToolbarButtonContribution,
): IDisposable {
const id = extensionId + '.' + contribution.id;
const styles: { [key: string]: IToolbarActionBtnState } = {};
if (contribution.states) {
Object.keys(contribution.states).forEach((state) => {
const o = contribution.states![state];
styles[state] = {
...o,
};
if (o.iconPath) {
styles[state].iconClass = this.iconService.fromIcon(
extensionBasePath,
o.iconPath,
o.iconMaskMode ? IconType.Mask : IconType.Background,
)!;
}
});
}
return this.toolbarRegistry.registerToolbarAction({
id,
preferredPosition: contribution.preferredPosition,
strictPosition: contribution.strictPosition,
description: contribution.description || contribution.title || id,
weight: contribution.weight,
when: contribution.when,
component: createToolbarActionBtn({
id,
popoverId: `${extensionId}:${contribution.popoverComponent}`,
title: contribution.title,
styles,
defaultState: contribution.defaultState,
iconClass: this.iconService.fromIcon(
extensionBasePath,
contribution.iconPath,
contribution.iconMaskMode ? IconType.Mask : IconType.Background,
)!,
// 这里放一个 LoadingView 用于占位,因为 contributes 执行时插件还没有激活完成
popoverComponent: contribution.popoverComponent
? this.getPopoverComponent(`${extensionId}:${contribution.popoverComponent}`, contribution)
: undefined,
popoverStyle: contribution.popoverStyle || {
noContainerStyle: false,
},
delegate: (delegate) => {
if (delegate) {
this.btnDelegates.set(id, delegate);
if (contribution.command) {
delegate.onClick(async () => {
delegate.showPopOver();
await this.eventBus.fireAndAwait(
new ExtensionActivateEvent({ topic: 'onAction', data: contribution.id }),
);
this.commandService.executeCommand(contribution.command!);
});
}
if (this.connected.has(id)) {
this.doConnectToolbarButtonHandle(id);
}
}
},
}),
});
}
doConnectToolbarButtonHandle(id: string) {
const delegate = this.btnDelegates.get(id);
if (delegate) {
delegate.onClick(() =>
this.commandService.executeCommand(EMIT_EXT_HOST_EVENT.id, 'sumi-extension.toolbar.btn.click', id),
);
delegate.onChangeState((args) =>
this.commandService.executeCommand(EMIT_EXT_HOST_EVENT.id, 'sumi-extension.toolbar.btn.stateChange', id, args),
);
}
}
registerToolbarSelect<T = any>(
extensionId: string,
extensionBasePath: string,
contribution: IToolbarSelectContribution<T>,
) {
const id = extensionId + '.' + contribution.id;
const options: { iconClass?: string; label?: string; value: T; iconPath?: string; iconMaskMode?: boolean }[] =
contribution.options || [];
options.forEach((o) => {
if (o.iconPath) {
o.iconClass = this.iconService.fromIcon(
extensionBasePath,
o.iconPath,
o.iconMaskMode ? IconType.Mask : IconType.Background,
)!;
}
});
return this.toolbarRegistry.registerToolbarAction({
id,
preferredPosition: contribution.preferredPosition,
strictPosition: contribution.strictPosition,
description: contribution.description,
component: createToolbarActionSelect<T>({
styles: contribution.states,
options,
defaultState: contribution.defaultState,
defaultValue: contribution.defaultValue,
equals: contribution.optionEqualityKey
? (v1, v2) => {
const key = contribution.optionEqualityKey!;
if (!v1 || !v2) {
return v1 === v2;
} else {
return v1[key] === v2[key];
}
}
: undefined,
delegate: (delegate) => {
if (delegate) {
this.selectDelegates.set(id, delegate);
if (contribution.command) {
delegate.onSelect((v) => {
this.commandService.executeCommand(contribution.command!, v);
});
}
if (this.connected.has(id)) {
this.doConnectToolbarSelectHandle(id);
}
}
},
}),
});
}
doConnectToolbarSelectHandle(id: string) {
const delegate = this.selectDelegates.get(id);
if (delegate) {
delegate.onSelect((value) =>
this.commandService.executeCommand(EMIT_EXT_HOST_EVENT.id, 'sumi-extension.toolbar.select.onSelect', id, value),
);
delegate.onChangeState((args) =>
this.commandService.executeCommand(
EMIT_EXT_HOST_EVENT.id,
'sumi-extension.toolbar.select.stateChange',
id,
args,
),
);
}
}
}
// 与 KaitianExtensionToolbarService 区分一下,只是为了给插件进程调用注册 actions
@Injectable({ multiple: true })
export class MainThreadToolbar extends Disposable implements IMainThreadToolbar {
@Autowired(KaitianExtensionToolbarService)
toolbarService: KaitianExtensionToolbarService;
$registerToolbarButtonAction(
extensionId: string,
extensionPath: string,
contribution: IToolbarButtonContribution,
): Promise<void> {
this.addDispose(this.toolbarService.registerToolbarButton(extensionId, extensionPath, contribution));
return Promise.resolve();
}
$registerToolbarSelectAction<T = any>(
extensionId: string,
extensionPath: string,
contribution: IToolbarSelectContribution<T>,
): Promise<void> {
this.addDispose(this.toolbarService.registerToolbarSelect(extensionId, extensionPath, contribution));
return Promise.resolve();
}
} | the_stack |
import { LowDegreeProof, FriComponent, LogFunction } from "@guildofweavers/genstark";
import { FiniteField, Vector, Matrix, AirContext } from '@guildofweavers/air-assembly';
import { MerkleTree, Hash } from '@guildofweavers/merkle';
import { QueryIndexGenerator } from "./QueryIndexGenerator";
import { readBigInt, rehashMerkleProofValues } from "../utils";
import { StarkError } from '../StarkError';
// MODULE VARIABLES
// ================================================================================================
const MAX_REMAINDER_LENGTH = 256;
const REMAINDER_SLOTS = Math.log2(MAX_REMAINDER_LENGTH) / 2;
// CLASS DEFINITION
// ================================================================================================
export class LowDegreeProver {
private readonly field : FiniteField;
private readonly polyRowSize : number;
private readonly rootOfUnity : bigint;
private readonly idxGenerator : QueryIndexGenerator;
private readonly hash : Hash;
private readonly log : LogFunction
// CONSTRUCTORS
// --------------------------------------------------------------------------------------------
constructor(idxGenerator: QueryIndexGenerator, hash: Hash, context: AirContext, logger: LogFunction) {
this.field = context.field;
this.polyRowSize = this.field.elementSize * 4;
this.rootOfUnity = context.rootOfUnity;
this.hash = hash;
this.idxGenerator = idxGenerator;
this.log = logger;
}
// PUBLIC METHODS
// --------------------------------------------------------------------------------------------
prove(cEvaluations: Vector, domain: Vector, maxDegreePlus1: number): LowDegreeProof {
// transpose composition polynomial evaluations into a matrix with 4 columns
const polyValues = this.field.transposeVector(cEvaluations, 4);
// hash each row and put the result into a Merkle tree
const polyHashes = this.hash.digestValues(polyValues.toBuffer(), this.polyRowSize);
const pTree = MerkleTree.create(polyHashes, this.hash);
this.log('Built liner combination merkle tree');
// build Merkle proofs but swap out hashed values for the un-hashed ones
const exeQueryPositions = this.idxGenerator.getExeIndexes(pTree.root, domain.length);
const lcPositions = getAugmentedPositions(exeQueryPositions, cEvaluations.length);
const lcProof = pTree.proveBatch(lcPositions);
lcProof.values = polyValues.rowsToBuffers(lcPositions);
this.log(`Computed ${lcPositions.length} linear combination spot checks`);
// create a proof object to pass it to the fri() method
const componentCount = getComponentCount(cEvaluations.length);
const proof: LowDegreeProof = {
lcRoot : pTree.root,
lcProof : lcProof,
components : new Array<FriComponent>(componentCount),
remainder : []
};
// build and return FRI proof
this.fri(pTree, polyValues, maxDegreePlus1, 0, domain, proof);
return proof;
}
verify(proof: LowDegreeProof, lcValues: bigint[], exeQueryPositions: number[], maxDegreePlus1: number) {
let rootOfUnity = this.rootOfUnity;
let columnLength = getRootOfUnityDegree(rootOfUnity, this.field);
// powers of the given root of unity 1, p, p**2, p**3 such that p**4 = 1
const quarticRootsOfUnity = [1n,
this.field.exp(rootOfUnity, BigInt(columnLength) / 4n),
this.field.exp(rootOfUnity, BigInt(columnLength) / 2n),
this.field.exp(rootOfUnity, BigInt(columnLength) * 3n / 4n)];
// 1 ----- check correctness of linear combination
let lcProof = proof.lcProof;
const lcPositions = getAugmentedPositions(exeQueryPositions, columnLength);
const lcChecks = this.parseColumnValues(lcProof.values, exeQueryPositions, lcPositions, columnLength);
lcProof = rehashMerkleProofValues(lcProof, this.hash);
if (!MerkleTree.verifyBatch(proof.lcRoot, lcPositions, lcProof, this.hash)) {
throw new StarkError(`Verification of linear combination Merkle proof failed`);
}
for (let i = 0; i < lcValues.length; i++) {
if (lcValues[i] !== lcChecks[i]) {
throw new StarkError(`Verification of linear combination correctness failed`);
}
}
// 2 ----- verify the recursive components of the FRI proof
let pRoot = proof.lcRoot;
columnLength = Math.floor(columnLength / 4);
for (let depth = 0; depth < proof.components.length; depth++) {
let { columnRoot, columnProof, polyProof } = proof.components[depth];
// calculate pseudo-random indexes for column and poly values
let positions = this.idxGenerator.getFriIndexes(columnRoot, columnLength);
let augmentedPositions = getAugmentedPositions(positions, columnLength);
// verify Merkle proof for the column
let columnValues = this.parseColumnValues(columnProof.values, positions, augmentedPositions, columnLength);
columnProof = rehashMerkleProofValues(columnProof, this.hash);
if (!MerkleTree.verifyBatch(columnRoot, augmentedPositions, columnProof, this.hash)) {
throw new StarkError(`Verification of column Merkle proof failed at depth ${depth}`);
}
// verify Merkle proof for polynomials
let polyValues = this.parsePolyValues(polyProof.values);
polyProof = rehashMerkleProofValues(polyProof, this.hash);
if (!MerkleTree.verifyBatch(pRoot, positions, polyProof, this.hash)) {
throw new StarkError(`Verification of polynomial Merkle proof failed at depth ${depth}`);
}
// build a set of x coordinates for each row polynomial
let xs = new Array<bigint[]>(positions.length);
for (let i = 0; i < positions.length; i++) {
let xe = this.field.exp(rootOfUnity, BigInt(positions[i]));
xs[i] = new Array(4);
xs[i][0] = this.field.mul(quarticRootsOfUnity[0], xe);
xs[i][1] = this.field.mul(quarticRootsOfUnity[1], xe);
xs[i][2] = this.field.mul(quarticRootsOfUnity[2], xe);
xs[i][3] = this.field.mul(quarticRootsOfUnity[3], xe);
}
// calculate the pseudo-random x coordinate
let specialX = this.field.prng(pRoot);
// interpolate x and y values into row polynomials
let xValues = this.field.newMatrixFrom(xs);
let yValues = this.field.newMatrixFrom(polyValues);
let polys = this.field.interpolateQuarticBatch(xValues, yValues);
// check that when the polynomials are evaluated at x, the result is equal to the corresponding column value
let pEvaluations = this.field.evalQuarticBatch(polys, specialX);
for (let i = 0; i < polys.rowCount; i++) {
if (pEvaluations.getValue(i) !== columnValues[i]) {
throw new StarkError(`Degree 4 polynomial didn't evaluate to column value at depth ${depth}`);
}
}
// update constants to check the next component
pRoot = columnRoot;
rootOfUnity = this.field.exp(rootOfUnity, 4n);
maxDegreePlus1 = Math.floor(maxDegreePlus1 / 4);
columnLength = Math.floor(columnLength / 4);
}
// 3 ----- verify the remainder of the FRI proof
if (maxDegreePlus1 > proof.remainder.length) {
throw new StarkError(`Remainder degree is greater than number of remainder values`);
}
const remainder = this.field.newVectorFrom(proof.remainder);
// check that Merkle root matches up
const polyValues = this.field.transposeVector(remainder, 4);
const polyHashes = this.hash.digestValues(polyValues.toBuffer(), this.polyRowSize);
const cTree = MerkleTree.create(polyHashes, this.hash);
if (!cTree.root.equals(pRoot)) {
throw new StarkError(`Remainder values do not match Merkle root of the last column`);
}
this.verifyRemainder(remainder, maxDegreePlus1, rootOfUnity);
return true;
}
// HELPER METHODS
// --------------------------------------------------------------------------------------------
private fri(pTree: MerkleTree, polyValues: Matrix, maxDegreePlus1: number, depth: number, domain: Vector, result: LowDegreeProof) {
// if there are not too many values left, use the polynomial values directly as proof
if (polyValues.rowCount * polyValues.colCount <= MAX_REMAINDER_LENGTH) {
const rootOfUnity = this.field.exp(domain.getValue(1), BigInt(4**depth));
const tValues = this.field.transposeMatrix(polyValues);
const remainder = this.field.joinMatrixRows(tValues);
this.verifyRemainder(remainder, maxDegreePlus1, rootOfUnity);
result.remainder = remainder.toValues();
this.log(`Computed FRI remainder of ${remainder.length} values`);
return;
}
// build polynomials from each row of the polynomial value matrix
const xs = this.field.transposeVector(domain, 4, (4**depth));
const polys = this.field.interpolateQuarticBatch(xs, polyValues);
// select a pseudo-random x coordinate and evaluate each row polynomial at that coordinate
const specialX = this.field.prng(pTree.root);
const column = this.field.evalQuarticBatch(polys, specialX);
// break the column in a polynomial value matrix for the next layer of recursion
const newPolyValues = this.field.transposeVector(column, 4);
// put the resulting matrix into a Merkle tree
const rowHashes = this.hash.digestValues(newPolyValues.toBuffer(), this.polyRowSize);
const cTree = MerkleTree.create(rowHashes, this.hash);
// recursively build all other components
this.log(`Computed FRI layer at depth ${depth}`);
this.fri(cTree, newPolyValues, Math.floor(maxDegreePlus1 / 4), depth + 1, domain, result);
// compute spot check positions in the column and corresponding positions in the original values
const positions = this.idxGenerator.getFriIndexes(cTree.root, column.length);
const augmentedPositions = getAugmentedPositions(positions, column.length);
// build Merkle proofs but swap out hashed values for the un-hashed ones
const columnProof = cTree.proveBatch(augmentedPositions);
columnProof.values = newPolyValues.rowsToBuffers(augmentedPositions);
const polyProof = pTree.proveBatch(positions);
polyProof.values = polyValues.rowsToBuffers(positions);
// build and add proof component to the result
result.components[depth] = { columnRoot: cTree.root, columnProof, polyProof };
}
private verifyRemainder(remainder: Vector, maxDegreePlus1: number, rootOfUnity: bigint) {
// exclude points which should be skipped during evaluation
const positions: number[] = [];
for (let i = 0; i < remainder.length; i++) {
if (!this.idxGenerator.extensionFactor || i % this.idxGenerator.extensionFactor) {
positions.push(i);
}
}
// pick a subset of points from the remainder and interpolate them into a polynomial
const domain = this.field.getPowerSeries(rootOfUnity, remainder.length);
const xs = new Array<bigint>(maxDegreePlus1);
const ys = new Array<bigint>(maxDegreePlus1);
for (let i = 0; i < maxDegreePlus1; i++) {
let p = positions[i];
xs[i] = domain.getValue(p);
ys[i] = remainder.getValue(p);
}
const xVector = this.field.newVectorFrom(xs);
const yVector = this.field.newVectorFrom(ys);
const poly = this.field.interpolate(xVector, yVector);
// check that polynomial evaluates correctly for all other points in the remainder
for (let i = maxDegreePlus1; i < positions.length; i++) {
let p = positions[i];
if (this.field.evalPolyAt(poly, domain.getValue(p)) !== remainder.getValue(p)) {
throw new StarkError(`Remainder is not a valid degree ${maxDegreePlus1 - 1} polynomial`);
}
}
}
// PARSERS
// --------------------------------------------------------------------------------------------
private parsePolyValues(buffers: Buffer[]) {
const elementSize = this.field.elementSize;
const result: bigint[][] = [];
for (let buffer of buffers) {
let values = new Array<bigint>(4), offset = 0;;
for (let i = 0; i < 4; i++, offset += elementSize) {
values[i] = readBigInt(buffer, offset, elementSize);
}
result.push(values);
}
return result;
}
private parseColumnValues(buffers: Buffer[], positions: number[], augmentedPositions: number[], columnLength: number) {
const rowLength = columnLength / 4;
const elementSize = this.field.elementSize;
const result: bigint[] = [];
for (let position of positions) {
let idx = augmentedPositions.indexOf(position % rowLength);
let buffer = buffers[idx];
let offset = Math.floor(position / rowLength) * elementSize;
result.push(readBigInt(buffer, offset, elementSize));
}
return result;
}
}
// HELPER FUNCTIONS
// ================================================================================================
function getComponentCount(valueCount: number): number {
let result = Math.ceil(Math.log2(valueCount) / 2); // round up log(valueCount, 4);
result -= REMAINDER_SLOTS;
return Math.min(result, 0);
}
function getRootOfUnityDegree(rootOfUnity: bigint, field: FiniteField): number {
let result = 1;
while (rootOfUnity !== 1n) {
result = result * 2;
rootOfUnity = field.mul(rootOfUnity, rootOfUnity);
}
return result;
}
function getAugmentedPositions(positions: number[], columnLength: number): number[] {
const rowLength = columnLength / 4;
const result = new Set<number>();
for (let position of positions) {
result.add(Math.floor(position % rowLength));
}
return Array.from(result);
} | the_stack |
import { svelte2tsx } from 'svelte2tsx';
import type ts from 'typescript/lib/tsserverlibrary';
import { Logger } from './logger';
import { SourceMapper } from './source-mapper';
import { isNoTextSpanInGeneratedCode, isSvelteFilePath } from './utils';
export class SvelteSnapshot {
private scriptInfo?: ts.server.ScriptInfo;
private lineOffsets?: number[];
private convertInternalCodePositions = false;
constructor(
private typescript: typeof ts,
private fileName: string,
private svelteCode: string,
private mapper: SourceMapper,
private logger: Logger,
public readonly isTsFile: boolean
) {}
update(svelteCode: string, mapper: SourceMapper) {
this.svelteCode = svelteCode;
this.mapper = mapper;
this.lineOffsets = undefined;
this.log('Updated Snapshot');
}
getOriginalTextSpan(textSpan: ts.TextSpan): ts.TextSpan | null {
if (!isNoTextSpanInGeneratedCode(this.getText(), textSpan)) {
return null;
}
const start = this.getOriginalOffset(textSpan.start);
if (start === -1) {
return null;
}
// Assumption: We don't change identifiers itself, so we don't change ranges.
return {
start,
length: textSpan.length
};
}
getOriginalOffset(generatedOffset: number) {
if (!this.scriptInfo) {
return generatedOffset;
}
this.toggleMappingMode(true);
const lineOffset = this.scriptInfo.positionToLineOffset(generatedOffset);
this.debug('try convert offset', generatedOffset, '/', lineOffset);
const original = this.mapper.getOriginalPosition({
line: lineOffset.line - 1,
character: lineOffset.offset - 1
});
this.toggleMappingMode(false);
if (original.line === -1) {
return -1;
}
const originalOffset = this.scriptInfo.lineOffsetToPosition(
original.line + 1,
original.character + 1
);
this.debug('converted offset to', original, '/', originalOffset);
return originalOffset;
}
setAndPatchScriptInfo(scriptInfo: ts.server.ScriptInfo) {
// @ts-expect-error
scriptInfo.scriptKind = this.typescript.ScriptKind.TSX;
const positionToLineOffset = scriptInfo.positionToLineOffset.bind(scriptInfo);
scriptInfo.positionToLineOffset = (position) => {
if (this.convertInternalCodePositions) {
const lineOffset = positionToLineOffset(position);
this.debug('positionToLineOffset for generated code', position, lineOffset);
return lineOffset;
}
const lineOffset = this.positionAt(position);
this.debug('positionToLineOffset for original code', position, lineOffset);
return { line: lineOffset.line + 1, offset: lineOffset.character + 1 };
};
const lineOffsetToPosition = scriptInfo.lineOffsetToPosition.bind(scriptInfo);
scriptInfo.lineOffsetToPosition = (line, offset) => {
if (this.convertInternalCodePositions) {
const position = lineOffsetToPosition(line, offset);
this.debug('lineOffsetToPosition for generated code', { line, offset }, position);
return position;
}
const position = this.offsetAt({ line: line - 1, character: offset - 1 });
this.debug('lineOffsetToPosition for original code', { line, offset }, position);
return position;
};
// TODO do we need to patch this?
// const lineToTextSpan = scriptInfo.lineToTextSpan.bind(scriptInfo);
// scriptInfo.lineToTextSpan = (line) => {
// if (this.convertInternalCodePositions) {
// const span = lineToTextSpan(line);
// this.debug('lineToTextSpan for generated code', line, span);
// return span;
// }
// const lineOffset = this.getLineOffsets();
// const start = lineOffset[line - 1];
// const span: ts.TextSpan = {
// start,
// length: (lineOffset[line] || this.svelteCode.length) - start
// };
// this.debug('lineToTextSpan for original code', line, span);
// return span;
// };
this.scriptInfo = scriptInfo;
this.log('patched scriptInfo');
}
/**
* Get the line and character based on the offset
* @param offset The index of the position
*/
positionAt(offset: number): ts.LineAndCharacter {
offset = this.clamp(offset, 0, this.svelteCode.length);
const lineOffsets = this.getLineOffsets();
let low = 0;
let high = lineOffsets.length;
if (high === 0) {
return { line: 0, character: offset };
}
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (lineOffsets[mid] > offset) {
high = mid;
} else {
low = mid + 1;
}
}
// low is the least x for which the line offset is larger than the current offset
// or array.length if no line offset is larger than the current offset
const line = low - 1;
return { line, character: offset - lineOffsets[line] };
}
/**
* Get the index of the line and character position
* @param position Line and character position
*/
offsetAt(position: ts.LineAndCharacter): number {
const lineOffsets = this.getLineOffsets();
if (position.line >= lineOffsets.length) {
return this.svelteCode.length;
} else if (position.line < 0) {
return 0;
}
const lineOffset = lineOffsets[position.line];
const nextLineOffset =
position.line + 1 < lineOffsets.length
? lineOffsets[position.line + 1]
: this.svelteCode.length;
return this.clamp(nextLineOffset, lineOffset, lineOffset + position.character);
}
private getLineOffsets() {
if (this.lineOffsets) {
return this.lineOffsets;
}
const lineOffsets = [];
const text = this.svelteCode;
let isLineStart = true;
for (let i = 0; i < text.length; i++) {
if (isLineStart) {
lineOffsets.push(i);
isLineStart = false;
}
const ch = text.charAt(i);
isLineStart = ch === '\r' || ch === '\n';
if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
i++;
}
}
if (isLineStart && text.length > 0) {
lineOffsets.push(text.length);
}
this.lineOffsets = lineOffsets;
return lineOffsets;
}
private clamp(num: number, min: number, max: number): number {
return Math.max(min, Math.min(max, num));
}
private log(...args: any[]) {
this.logger.log('SvelteSnapshot:', this.fileName, '-', ...args);
}
private debug(...args: any[]) {
this.logger.debug('SvelteSnapshot:', this.fileName, '-', ...args);
}
private toggleMappingMode(convertInternalCodePositions: boolean) {
this.convertInternalCodePositions = convertInternalCodePositions;
}
private getText() {
const snapshot = this.scriptInfo?.getSnapshot();
if (!snapshot) {
return '';
}
return snapshot.getText(0, snapshot.getLength());
}
}
export class SvelteSnapshotManager {
private snapshots = new Map<string, SvelteSnapshot>();
constructor(
private typescript: typeof ts,
private projectService: ts.server.ProjectService,
private logger: Logger
) {
this.patchProjectServiceReadFile();
}
get(fileName: string) {
return this.snapshots.get(fileName);
}
create(fileName: string): SvelteSnapshot | undefined {
if (this.snapshots.has(fileName)) {
return this.snapshots.get(fileName)!;
}
// This will trigger projectService.host.readFile which is patched below
const scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(
this.typescript.server.toNormalizedPath(fileName),
false
);
if (!scriptInfo) {
this.logger.log('Was not able get snapshot for', fileName);
return;
}
try {
scriptInfo.getSnapshot(); // needed to trigger readFile
} catch (e) {
this.logger.log('Loading Snapshot failed', fileName);
}
const snapshot = this.snapshots.get(fileName);
if (!snapshot) {
this.logger.log(
'Svelte snapshot was not found after trying to load script snapshot for',
fileName
);
return; // should never get here
}
snapshot.setAndPatchScriptInfo(scriptInfo);
this.snapshots.set(fileName, snapshot);
return snapshot;
}
private patchProjectServiceReadFile() {
const readFile = this.projectService.host.readFile;
this.projectService.host.readFile = (path: string) => {
if (isSvelteFilePath(path)) {
this.logger.debug('Read Svelte file:', path);
const svelteCode = readFile(path) || '';
try {
const isTsFile = true; // TODO check file contents? TS might be okay with importing ts into js.
const result = svelte2tsx(svelteCode, {
filename: path.split('/').pop(),
isTsFile
});
const existingSnapshot = this.snapshots.get(path);
if (existingSnapshot) {
existingSnapshot.update(svelteCode, new SourceMapper(result.map.mappings));
} else {
this.snapshots.set(
path,
new SvelteSnapshot(
this.typescript,
path,
svelteCode,
new SourceMapper(result.map.mappings),
this.logger,
isTsFile
)
);
}
this.logger.log('Successfully read Svelte file contents of', path);
return result.code;
} catch (e) {
this.logger.log('Error loading Svelte file:', path);
this.logger.debug('Error:', e);
}
} else {
return readFile(path);
}
};
}
} | the_stack |
* Created by sauravdutta on 27/11/17.
*/
import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
import { HttpService } from '../../shared/services/http-response.service';
import { ErrorHandlingService } from '../../shared/services/error-handling.service';
import { UtilsService } from '../../shared/services/utils.service';
@Injectable()
export class AllPatchingProgressService {
dataArray: any = {};
monthQuarter: any;
dayQuarter: any;
weekVal: any= [];
weekNum: any= [];
dataArrayList: any= [];
lastDate: any;
year: any;
monthValue: any;
endDate: any;
startDate: any;
firstDate: any;
getMethod: any;
constructor( @Inject(HttpService) private httpService: HttpService,
private errorHandling: ErrorHandlingService,
private utilService: UtilsService) { }
getData(data, url, method, assetGroup, year?: any): Observable<any> {
try {
if (method !== 'GET') {
this.year = year !== undefined ? year : data[0].year;
data.forEach( yearlyData => {
if (this.year === yearlyData.year) {
data = yearlyData;
}
});
const patchingProgressUrl = url;
const patchingProgressMethod = method;
const payload = {};
let currentPayload;
const queryParams = {
'ag': assetGroup,
'filter': {},
'year': data.year
};
const quarterArray = data.quarters;
this.getMethod = patchingProgressMethod;
const allObservables: Observable<any>[] = [];
quarterArray.forEach((quarters) => {
currentPayload = Object.assign({}, queryParams);
currentPayload['quarter'] = quarters;
allObservables.push(
this.httpService.getHttpResponse(patchingProgressUrl, patchingProgressMethod, currentPayload, {})
.map(response => this.massageDataYearly(quarters, response))
.catch(error => this.handleCombiningError(quarters, error))
);
});
return allObservables.length > 0 ? Observable.combineLatest(allObservables) : Observable.of([]);
} else {
this.year = 2018;
try {
return this.httpService.getHttpResponse(url, method, {}, {})
.map(response => {
return [this.massageDataYearly(1, response)];
})
.catch(error => this.handleCombiningError(1, error));
} catch (error) {
this.errorHandling.handleJavascriptError(error);
}
}
} catch (error) {
this.errorHandling.handleJavascriptError(error);
}
}
getQuarterData(payload, url, method, queryParams): Observable<any> {
try {
return this.httpService.getHttpResponse(url, method, payload, queryParams)
.map(response => {
return this.massageQuarterData(response);
});
} catch (error) {
this.errorHandling.handleJavascriptError(error);
}
}
massageQuarterData(data): any {
// Sort the data in decreasing order
data = data.data.response;
data.sort(function(a, b) {
return b.year - a.year; // For descending order
});
data.forEach(yearData => {
yearData.quarters.sort();
});
return data;
}
massageDataYearly(quarters, data): any {
if (quarters === 'null') {
return data;
} else {
const tempData = JSON.parse(JSON.stringify(data));
const response = tempData.data.response;
const numberOfWeeks = this.utilService.getNumberOfWeeks(response.year, quarters);
const length = response.patching_progress.length;
const newLength = response.patching_progress[length - 1].patching_info.length;
const additionalWeeks = [];
let objPatched;
let objTotal;
const valuesPatched = [];
const valuesTotal = [];
const valuesProjection = [];
let amiavail_dateQuarter;
let end_dateQuarter;
let internal_targetQuarter;
// Extracting the 3 important dates......
if (response.amiavail_date !== undefined) {
amiavail_dateQuarter = response.amiavail_date;
}
if (response.end_date !== undefined) {
end_dateQuarter = response.end_date;
}
if (response.internal_target !== undefined) {
internal_targetQuarter = response.internal_target;
}
const complianceData = response.patching_progress[length - 1].compliance;
const patchedData = response.patched_instances;
const unPatchedData = response.unpatched_instances;
const tomorrow = new Date();
/* If last date of a quarter is less than the actual end date of the quarter,
then fill up the extra dates with -1 */
if (end_dateQuarter !== response.patching_progress[length - 1].patching_info[newLength - 1].date) {
this.lastDate = response.patching_progress[length - 1].patching_info[newLength - 1].date;
if (response.patching_progress[length - 1].patching_info.length < 7) {
const lastDay = new Date(response.patching_progress[length - 1].patching_info[newLength - 1].date);
for (let s = 1; s <= (7 - response.patching_progress[length - 1].patching_info.length); s++) {
const extraDays = tomorrow.setTime(lastDay.getTime() + (24 * 60 * 60 * 1000 * s));
const DaysValue = new Date(extraDays);
this.monthQuarter = DaysValue.getMonth();
this.monthQuarter++;
if (this.monthQuarter < 10) {
this.monthQuarter = '0' + this.monthQuarter;
}
this.dayQuarter = DaysValue.getDate();
if (this.dayQuarter < 10) {
this.dayQuarter = '0' + this.dayQuarter;
}
const year = DaysValue.getFullYear().toString();
const returnDate = year + '-' + this.monthQuarter + '-' + this.dayQuarter;
const additionalDays = {
'date': returnDate,
'patched_instances': -1,
'total_instances': -1,
'target_date': -1
};
additionalWeeks.push(additionalDays);
}
response.patching_progress[length - 1].patching_info.push.apply(response.patching_progress[length - 1].patching_info, additionalWeeks);
}
}
/* If the number of weeks in a quarter is less than 13,
then fill up the rest of the weeks with -1 */
if (length < numberOfWeeks) {
let restDays;
const countValue = 0;
let countWeek = 0;
const weekCount = 0;
let restObj = {};
let restArray = [];
const remainingWeeks = numberOfWeeks - length;
for (let q = 0; q < remainingWeeks; q++) {
const value = new Date(response.patching_progress[length - 1].end_date);
const utcTime = value.getTime() + (value.getTimezoneOffset() * 60 * 1000);
const date2Value = new Date(utcTime);
countWeek = date2Value.getTime() + (24 * 60 * 60 * 1000 * q * 7);
const dateValue = tomorrow.setTime(countWeek);
this.endDate = new Date(dateValue);
this.monthValue = this.endDate.getMonth();
for (let t = 1; t <= 7; t++) {
const nextDay = tomorrow.setTime(this.endDate.getTime() + (24 * 60 * 60 * 1000 * t));
restDays = {
'patched_instances': -1,
'total_instances': -1,
'target_date': -1,
'date': new Date(nextDay)
};
restArray.push(restDays);
}
restObj = {
'week': length + q + 1,
'compliance': '',
'patching_info': restArray
};
restArray = [];
response.patching_progress.push(restObj);
}
let lastWeekResponse = response.patching_progress[12].patching_info;
let indexValue = 0;
for (let i = 0; i < lastWeekResponse.length; i++) {
if (new Date(lastWeekResponse[i].date).getMonth() === new Date(response.end_date).getMonth()) {
if (new Date(lastWeekResponse[i].date).getDate() === new Date(response.end_date).getDate()) {
indexValue = i;
}
}
}
lastWeekResponse = lastWeekResponse.splice(0, indexValue + 1);
response.patching_progress[12].patching_info = lastWeekResponse;
}
// Making the Array of dates.....
this.weekVal = [];
this.weekNum = [];
this.startDate = response.patching_progress[0].start_date;
for (let i = 0; i < response.patching_progress.length; i++) {
this.weekVal.push(response.patching_progress[i].compliance);
this.weekNum.push(response.patching_progress[i].week);
for (let j = 0; j < response.patching_progress[i].patching_info.length; j++) {
objPatched = {
'date': new Date(response.patching_progress[i].patching_info[j].date),
'value': response.patching_progress[i].patching_info[j].patched_instances
};
valuesPatched.push(objPatched);
objTotal = {
'date': new Date(response.patching_progress[i].patching_info[j].date),
'value': response.patching_progress[i].patching_info[j].total_instances
};
valuesTotal.push(objTotal);
}
}
// Making the array of patching_info/projection count till the given weeks
const sortedWeeks = response.projection_info;
sortedWeeks.map(element => {
element.week = Number(element.week);
});
sortedWeeks.sort(function(a, b) {
return (a.week) - (b.week);
});
let objProjection = {};
const tomorrowDate = new Date();
this.firstDate = new Date(this.startDate);
if (response.projection_info !== undefined) {
if (response.projection_info.length > 0) {
for (let i = 0; i < response.projection_info.length; i++) {
const firstDateValue = new Date(tomorrowDate.setTime(this.firstDate.getTime() + 86400000 * (7 * i)));
for (let j = 0; j < 7; j++) {
objProjection = {
'date': new Date(tomorrowDate.setTime(firstDateValue.getTime() + 86400000 * j)),
'value': response.projection_info[i].count
};
valuesProjection.push(objProjection);
}
}
}
}
valuesProjection.splice(-1, 1);
let temp = {};
temp = {
'ami': amiavail_dateQuarter,
'int': internal_targetQuarter,
'end': end_dateQuarter,
'weekVal': this.weekVal,
'weekNum': this.weekNum,
'key': quarters,
'lastDate': this.lastDate,
'year': this.year,
'compliance': complianceData,
'patched': patchedData,
'unpatched': unPatchedData,
'id': 'q0',
'data':
[{
'values': valuesPatched
}, {
'values': valuesTotal
}, {
'values': valuesProjection
}
]
};
if (valuesProjection.length > 0) {
temp[`projectedTarget`] = 'valid';
} else {
temp[`projectedTarget`] = 'invalid';
}
this.dataArrayList = [];
this.dataArrayList.push(temp);
return temp;
}
}
massageData(data): any {
if (this.getMethod === 'POST') {
const response = data;
this.dataArray = response;
return this.dataArray;
} else {
let dataArray = [];
const valuesTotal = [];
const valuesPatched = [];
let objPatched;
let objTotal;
for (let i = 0; i < data.patchingprogress.length; i++) {
objPatched = {
'date': new Date(data.patchingprogress[i].date),
'value': data.patchingprogress[i].patched
};
valuesPatched.push(objPatched);
objTotal = {
'date': new Date(data.patchingprogress[i].date),
'value': data.patchingprogress[i].total
};
valuesTotal.push(objTotal);
}
dataArray = [{
'values': valuesPatched
}, {
'values': valuesTotal
}];
return dataArray;
}
}
handleCombiningError(quarters, error: any): Observable<any> {
if (quarters === 'null') {
return Observable.of(this.massageDataYearly('null', []));
} else {
return Observable.of(this.massageDataYearly(quarters, []));
}
}
} | the_stack |
declare module 'websocket' {
export class w3cwebsocket { // tslint:disable-line
constructor(url: string);
onopen(): void;
onclose: (() => void) | null;
onmessage(event: {data: string}): void;
send(message: string): void;
close(): void;
CONNECTING: string;
OPEN: string;
readyState: string;
}
}
import { w3cwebsocket as WebSocket } from 'websocket';
/**
* Connection to the backend.
*
* The standard template is to create a connection first, then use it to
* wire all UI elements, to add custom callback functions and at last to run
* [[Connection.connect]] to create a WebSocket connection to the backend
* server (see example below).
*
* The other two essential functions to know about are
* [[Connection.on]] and [[Connection.emit]].
*
* Logging across frontend and backend can be done by emitting `log`,
* `warn` or `error`, e.g. `emit('log', 'Hello World')`.
*
* ```js
* var databench = new Databench.Connection();
* Databench.ui.wire(databench);
*
*
* // put custom databench.on() methods here
*
*
* databench.connect();
* ```
*/
export class Connection {
wsUrl: string;
requestArgs?: string;
analysisId?: string;
databenchBackendVersion?: string;
analysesVersion?: string;
errorCB: (message?: string) => void;
private onCallbacks: {[field: string]: ((message: any, signal?: string) => void)[]};
private onProcessCallbacks: {[field: string]: ((status: any) => void)[]};
private preEmitCallbacks: {[field: string]: ((message: any) => any)[]};
private connectCallback: (connection: Connection) => void;
private wsReconnectAttempt: number;
private wsReconnectDelay: number;
private socket?: WebSocket;
private socketCheckOpen?: number;
/**
* @param wsUrl URL of WebSocket endpoint or undefined to guess it.
* @param requestArgs `search` part of request url or undefined to take from
* `window.location.search`.
* @param analysisId Specify an analysis id or undefined to have one generated.
* The connection will try to connect to a previously created
* analysis with that id.
*/
constructor(wsUrl?: string, requestArgs?: string, analysisId?: string) {
this.wsUrl = wsUrl || Connection.guessWSUrl();
this.requestArgs = (!requestArgs && (typeof window !== 'undefined')) ?
window.location.search : requestArgs;
this.analysisId = analysisId;
this.errorCB = msg => (msg != null ? console.log(`connection error: ${msg}`) : null);
this.onCallbacks = {};
this.onProcessCallbacks = {};
this.preEmitCallbacks = {};
this.connectCallback = connection => {};
this.wsReconnectAttempt = 0;
this.wsReconnectDelay = 100.0;
// wire log, warn, error messages into console outputs
['log', 'warn', 'error'].forEach(wireSignal => {
this.on(wireSignal, message => console[wireSignal]('backend: ', message));
this.preEmit(wireSignal, message => {
console[wireSignal]('frontend: ', message);
return message;
});
});
}
static guessWSUrl(): string {
if (typeof location === 'undefined') return '';
const WSProtocol = location.origin.indexOf('https://') === 0 ? 'wss' : 'ws';
const path = location.pathname.substring(0, location.pathname.lastIndexOf('/'));
return `${WSProtocol}://${document.domain}:${location.port}${path}/ws`;
}
/** initialize connection */
connect(callback?: (connection: Connection) => void): Connection {
if (!this.wsUrl) throw Error('Need a wsUrl.');
this.connectCallback = callback ? callback : () => this;
this.socket = new WebSocket(this.wsUrl);
this.socketCheckOpen = setInterval(this.wsCheckOpen.bind(this), 2000);
this.socket.onopen = this.wsOnOpen.bind(this);
this.socket.onclose = this.wsOnClose.bind(this);
this.socket.onmessage = this.wsOnMessage.bind(this);
return this;
}
/** close connection */
disconnect() {
if (this.socketCheckOpen) {
clearInterval(this.socketCheckOpen);
this.socketCheckOpen = undefined;
}
if (this.socket) {
this.socket.onclose = null;
this.socket.close();
this.socket = undefined;
}
}
wsCheckOpen() {
if (!this.socket) return;
if (this.socket.readyState === this.socket.CONNECTING) {
return;
}
if (this.socket.readyState !== this.socket.OPEN) {
this.errorCB(
'Connection could not be opened. ' +
'Please <a href="javascript:location.reload(true);" ' +
'class="alert-link">reload</a> this page to try again.'
);
}
if (this.socketCheckOpen) {
clearInterval(this.socketCheckOpen);
this.socketCheckOpen = undefined;
}
}
wsOnOpen() {
if (!this.socket) return;
this.wsReconnectAttempt = 0;
this.wsReconnectDelay = 100.0;
this.errorCB(); // clear errors
this.socket.send(JSON.stringify({
__connect: this.analysisId ? this.analysisId : null,
__request_args: this.requestArgs, // eslint-disable-line camelcase
}));
}
wsOnClose() {
if (this.socketCheckOpen) {
clearInterval(this.socketCheckOpen);
this.socketCheckOpen = undefined;
}
this.wsReconnectAttempt += 1;
this.wsReconnectDelay *= 2;
if (this.wsReconnectAttempt > 5) {
this.errorCB(
'Connection closed. ' +
'Please <a href="javascript:location.reload(true);" ' +
'class="alert-link">reload</a> this page to reconnect.'
);
return;
}
const actualDelay = 0.7 * this.wsReconnectDelay + 0.3 * Math.random() *
this.wsReconnectDelay;
console.log(`WebSocket reconnect attempt ${this.wsReconnectAttempt} ` +
`in ${actualDelay.toFixed(0)}ms.`);
setTimeout(this.connect.bind(this), actualDelay);
}
/**
* Trigger all callbacks for this signal with this message.
* @param signal Name of the signal to trigger.
* @param message Payload for the triggered signal.
*/
trigger(signal: string, message?: any) {
this.onCallbacks[signal].forEach(cb => cb(message, signal));
}
wsOnMessage(event: {data: string}) {
const message = JSON.parse(event.data);
// connect response
if (message.signal === '__connect') {
this.analysisId = message.load.analysis_id;
this.databenchBackendVersion = message.load.databench_backend_version;
const newVersion = message.load.analyses_version;
if (this.analysesVersion && this.analysesVersion !== newVersion) {
location.reload();
}
this.analysesVersion = newVersion;
this.connectCallback(this);
}
// processes
if (message.signal === '__process') {
const id = message.load.id;
const status = message.load.status;
this.onProcessCallbacks[id].forEach(cb => cb(status));
}
// normal message
if (message.signal in this.onCallbacks) {
this.trigger(message.signal, message.load);
}
}
/**
* Register a callback that listens for a signal.
*
* The signal can be a simple string (the name for a signal/action), but it
* can also be an Object of the form `{data: 'current_value'}` which would
* trigger on `data` actions that are sending a JSON dictionary that contains
* the key `current_value`. In this case, the value that is
* given to the callback function is the value assigned to `current_value`.
*
* ~~~
* d.on('data', value => { console.log(value); });
* // If the backend sends an action called 'data' with a message
* // {current_value: 3.0}, this function would log `{current_value: 3.0}`.
* ~~~
*
* ~~~
* d.on({data: 'current_value'}, value => { console.log(value); });
* // If the backend sends an action called 'data' with a
* // message {current_value: 3.0}, this function would log `3.0`.
* // This callback is not triggered when the message does not contain a
* // `current_value` key.
* ~~~
*
* @param signal Signal name to listen for.
* @param callback A callback function that takes the attached data.
*/
on(signal: string|{[field: string]: string}|{[field: string]: RegExp},
callback: (message: any, key?: string) => void): Connection {
if (typeof signal === 'object') {
this._on_object(signal, callback);
return this;
}
if (!(signal in this.onCallbacks)) this.onCallbacks[signal] = [];
this.onCallbacks[signal].push(callback);
return this;
}
/**
* Listen for a signal once.
*
* Similar to [on] but returns a `Promise` instead of taking a callback.
* This is mostly useful for unit tests.
*
* @param signal Signal name to listen for.
*/
once(signal: string|{[field: string]: string}|{[field: string]: RegExp}): Promise<{message: any, key?: string}> {
return new Promise(resolve => {
this.on(signal, resolve);
});
}
_on_object(signal: {[field: string]: string}|{[field: string]: RegExp},
callback: (message: any, key?: string) => void): Connection {
Object.keys(signal).forEach(signalName => {
const entryName = signal[signalName];
const filteredCallback = (data: any, signalName: string) => {
Object.keys(data).forEach(dataKey => {
if (dataKey.match(entryName) === null) return;
callback(data[dataKey], dataKey);
});
};
this.on(signalName, filteredCallback);
});
return this;
}
/**
* Set a pre-emit hook.
* @param signalName A signal name.
* @param callback Callback function.
*/
preEmit(signalName: string, callback: (message: any) => any): Connection {
if (!(signalName in this.preEmitCallbacks)) this.preEmitCallbacks[signalName] = [];
this.preEmitCallbacks[signalName].push(callback);
return this;
}
/**
* Emit a signal/action to the backend.
* @param signalName A signal name. Usually an action name.
* @param message Payload attached to the action.
*/
emit(signalName: string, message?: any): Connection {
// execute preEmit hooks before sending message to backend
if (signalName in this.preEmitCallbacks) {
this.preEmitCallbacks[signalName].forEach(cb => {
message = cb(message);
});
}
// socket will never be open
if (!this.socket) return this;
// socket is not open yet
if (this.socket.readyState !== this.socket.OPEN) {
setTimeout(() => this.emit(signalName, message), 5);
return this;
}
// send to backend
this.socket.send(JSON.stringify({ signal: signalName, load: message }));
return this;
}
onProcess(processID: number, callback: (message: any) => void): Connection {
if (!(processID in this.onProcessCallbacks)) {
this.onProcessCallbacks[processID] = [];
}
this.onProcessCallbacks[processID].push(callback);
return this;
}
}
/**
* Create a Connection and immediately connect to it.
*
* This is a shorthand for
* ~~~
* new Connection(wsUrl, requestArgs, analysisId).connect();
* ~~~
*
* Use this function in tests where you know that `connect()` will not trigger
* any callbacks that you should listen to. In regular code, it is better
* to define all `on` callbacks before calling `connect()` and so this
* shorthand should not be used.
*
* @param wsUrl URL of WebSocket endpoint or undefined to guess it.
* @param requestArgs `search` part of request url or undefined to take from
* `window.location.search`.
* @param analysisId Specify an analysis id or undefined to have one generated.
* The connection will try to connect to a previously created
* analysis with that id.
* @param callback Called when connection is established.
*/
export function connect(wsUrl?: string, requestArgs?: string, analysisId?: string, callback?: (connection: Connection) => void) {
return new Connection(wsUrl, requestArgs, analysisId).connect(callback);
}
/**
* Attach to a backend.
*
* Similar to [connect](globals.html#connect). Instead of a callback parameter, it
* returns a Promise that resolves to a [[Connection]] instance once the connection is
* established.
*
* @param wsUrl URL of WebSocket endpoint or undefined to guess it.
* @param requestArgs `search` part of request url or undefined to take from
* `window.location.search`.
* @param analysisId Specify an analysis id or undefined to have one generated.
* The connection will try to connect to a previously created
* analysis with that id.
*/
export function attach(wsUrl?: string, requestArgs?: string, analysisId?: string): Promise<Connection> {
const connection = new Connection(wsUrl, requestArgs, analysisId);
return new Promise((resolve) => connection.connect(resolve));
} | the_stack |
import {QnaBuildCore} from './core'
import {Settings} from './settings'
import {MultiLanguageRecognizer} from './multi-language-recognizer'
import {Recognizer} from './recognizer'
import {CrossTrainedRecognizer} from './cross-trained-recognizer'
const path = require('path')
const fs = require('fs-extra')
const delay = require('delay')
const fileHelper = require('./../../utils/filehelper')
const fileExtEnum = require('./../utils/helpers').FileExtTypeEnum
const retCode = require('./../utils/enums/CLI-errors')
const exception = require('./../utils/exception')
const qnaBuilderVerbose = require('./../qna/qnamaker/kbCollate')
const qnaMakerBuilder = require('./../qna/qnamaker/qnaMakerBuilder')
const qnaOptions = require('./../lu/qnaOptions')
const Content = require('./../lu/qna')
const KB = require('./../qna/qnamaker/kb')
const recognizerType = require('./../utils/enums/recognizertypes')
const LUOptions = require('./../lu/luOptions')
export class Builder {
private readonly handler: (input: string) => any
constructor(handler: any) {
this.handler = handler
}
async loadContents(
files: string[],
botName: string,
suffix: string,
region: string,
culture: string,
schema?: string,
importResolver?: object) {
let multiRecognizers = new Map<string, MultiLanguageRecognizer>()
let settings: any
let recognizers = new Map<string, Recognizer>()
let qnaContents = new Map<string, any>()
let crosstrainedRecognizers = new Map<string, CrossTrainedRecognizer>()
let qnaObjects = new Map<string, any[]>()
for (const file of files) {
let fileCulture: string
let fileName: string
let cultureFromPath = fileHelper.getCultureFromPath(file)
if (cultureFromPath) {
fileCulture = cultureFromPath
let fileNameWithCulture = path.basename(file, path.extname(file))
fileName = fileNameWithCulture.substring(0, fileNameWithCulture.length - cultureFromPath.length - 1)
} else {
fileCulture = culture
fileName = path.basename(file, path.extname(file))
}
const fileFolder = path.dirname(file)
const crossTrainedFileName = fileName + '.lu.qna.dialog'
const crossTrainedRecognizerPath = path.join(fileFolder, crossTrainedFileName)
if (!crosstrainedRecognizers.has(fileName)) {
let crosstrainedRecognizerContent = []
let crosstrainedRecognizerSchema = schema
if (fs.existsSync(crossTrainedRecognizerPath)) {
let crosstrainedRecognizerObject = JSON.parse(await fileHelper.getContentFromFile(crossTrainedRecognizerPath))
crosstrainedRecognizerContent = crosstrainedRecognizerObject.recognizers
crosstrainedRecognizerSchema = crosstrainedRecognizerSchema || crosstrainedRecognizerObject.$schema
this.handler(`${crossTrainedRecognizerPath} loaded\n`)
}
crosstrainedRecognizers.set(fileName, new CrossTrainedRecognizer(crossTrainedRecognizerPath, crosstrainedRecognizerContent, crosstrainedRecognizerSchema as string))
}
let qnaFiles = await fileHelper.getLuObjects(undefined, file, true, fileExtEnum.QnAFile)
this.handler(`${file} loaded\n`)
// filter empty qna files
qnaFiles = qnaFiles.filter((file: any) => file.content !== '')
if (qnaFiles.length <= 0) continue
const multiRecognizerPath = path.join(fileFolder, `${fileName}.qna.dialog`)
if (!multiRecognizers.has(fileName)) {
let multiRecognizerContent = {}
let multiRecognizerSchema = schema
if (fs.existsSync(multiRecognizerPath)) {
let multiRecognizerObject = JSON.parse(await fileHelper.getContentFromFile(multiRecognizerPath))
multiRecognizerContent = multiRecognizerObject.recognizers
multiRecognizerSchema = multiRecognizerSchema || multiRecognizerObject.$schema
this.handler(`${multiRecognizerPath} loaded\n`)
}
multiRecognizers.set(fileName, new MultiLanguageRecognizer(multiRecognizerPath, multiRecognizerContent, multiRecognizerSchema as string))
}
if (settings === undefined) {
const settingsPath = path.join(fileFolder, `qnamaker.settings.${suffix}.${region}.json`)
let settingsContent = {}
if (fs.existsSync(settingsPath)) {
settingsContent = JSON.parse(await fileHelper.getContentFromFile(settingsPath)).qna
this.handler(`${settingsPath} loaded\n`)
}
settings = new Settings(settingsPath, settingsContent)
}
const dialogName = `${fileName}.${fileCulture}.qna`
const dialogFile = path.join(fileFolder, dialogName + '.dialog')
let existingDialogObj: any
if (fs.existsSync(dialogFile)) {
existingDialogObj = JSON.parse(await fileHelper.getContentFromFile(dialogFile))
this.handler(`${dialogFile} loaded\n`)
}
if (existingDialogObj && schema) {
existingDialogObj.$schema = schema
}
let recognizer = Recognizer.load(file, dialogName, dialogFile, settings, existingDialogObj, schema)
recognizers.set(dialogName, recognizer)
if (!qnaContents.has(fileCulture)) {
let contentPerCulture = new Content('', new qnaOptions(botName, true, fileCulture, file))
qnaContents.set(fileCulture, contentPerCulture)
qnaObjects.set(fileCulture, qnaFiles)
} else {
// merge contents of qna files with same culture
let qnaObject = qnaObjects.get(fileCulture)
if (qnaObject !== undefined) {
qnaObject.push(...qnaFiles)
}
}
}
await this.resolveMergedQnAContentIds(qnaContents, qnaObjects, importResolver)
return {qnaContents: [...qnaContents.values()], recognizers, multiRecognizers, settings, crosstrainedRecognizers}
}
async build(
qnaContents: any[],
recognizers: Map<string, Recognizer>,
subscriptionkey: string,
endpoint: string,
botName: string,
suffix: string,
fallbackLocale: string,
multiRecognizers?: Map<string, MultiLanguageRecognizer>,
settings?: Settings,
crosstrainedRecognizers?: Map<string, CrossTrainedRecognizer>,
dialogType?: string) {
// qna api TPS which means concurrent transactions to qna maker api in 1 second
let qnaApiTps = 3
// set qna maker call delay duration to 1100 millisecond because 1000 can hit corner case of rate limit
let delayDuration = 1100
//default returned recognizer values
let recognizerValues: Recognizer[] = []
let multiRecognizerValues: MultiLanguageRecognizer[] = []
let settingsValue: any
let crosstrainedRecognizerValues: CrossTrainedRecognizer[] = []
// filter if all qna contents are emtty
let isAllQnAEmpty = fileHelper.isAllFilesSectionEmpty(qnaContents)
if (!isAllQnAEmpty) {
const qnaBuildCore = new QnaBuildCore(subscriptionkey, endpoint)
const kbs = (await qnaBuildCore.getKBList()).knowledgebases
// here we do a while loop to make full use of qna tps capacity
while (qnaContents.length > 0) {
// get a number(set by qnaApiTps) of contents for each loop
const subQnaContents = qnaContents.splice(0, qnaApiTps)
// concurrently handle applications
await Promise.all(subQnaContents.map(async content => {
// init current kb object from qna content
const qnaObj = await this.initQnaFromContent(content, botName, suffix)
let currentKB = qnaObj.kb
let currentAlt = qnaObj.alterations
let culture = content.language as string
let hostName = ''
// get recognizer
let recognizersOfContentCulture: Recognizer[] = []
for (let [dialogFileName, recognizer] of recognizers) {
const fileNameSplit = dialogFileName.split('.')
if (fileNameSplit[fileNameSplit.length - 2] === culture) {
// find if there is a matched name with current kb under current authoring key
if (!recognizer.getKBId()) {
for (let kb of kbs) {
if (kb.name === currentKB.name) {
recognizer.setKBId(kb.id)
hostName = kb.hostName
break
}
}
}
recognizersOfContentCulture.push(recognizer)
}
}
let needPublish = false
// compare models to update the model if a match found
// otherwise create a new kb
let recognizerWithKBId = recognizersOfContentCulture.find((r: Recognizer) => r.getKBId() !== '')
if (recognizerWithKBId !== undefined) {
// To see if need update the model
needPublish = await this.updateKB(currentKB, qnaBuildCore, recognizerWithKBId, delayDuration)
} else {
// create a new kb
needPublish = await this.createKB(currentKB, qnaBuildCore, recognizersOfContentCulture, delayDuration)
}
const publishRecognizer = recognizerWithKBId || recognizersOfContentCulture[0]
if (needPublish) {
// train and publish kb
await this.publishKB(qnaBuildCore, publishRecognizer, currentKB.name, delayDuration)
}
if (hostName === '') hostName = (await qnaBuildCore.getKB(publishRecognizer.getKBId())).hostName
hostName += '/qnamaker'
// update alterations if there are
if (currentAlt.wordAlterations && currentAlt.wordAlterations.length > 0) {
this.handler('Replacing alterations...\n')
await qnaBuildCore.replaceAlt(currentAlt)
}
for (const recognizer of recognizersOfContentCulture) {
// update multiLanguageRecognizer asset
const dialogName = path.basename(recognizer.getDialogPath(), `.${culture}.qna.dialog`)
const dialogFileName = path.basename(recognizer.getDialogPath(), '.dialog')
if (multiRecognizers && multiRecognizers.has(dialogName)) {
let multiRecognizer = multiRecognizers.get(dialogName) as MultiLanguageRecognizer
multiRecognizer.recognizers[culture] = dialogFileName
if (culture.toLowerCase() === fallbackLocale.toLowerCase()) {
multiRecognizer.recognizers[''] = dialogFileName
}
}
if (crosstrainedRecognizers && crosstrainedRecognizers.has(dialogName)) {
let crosstrainedRecognizer = crosstrainedRecognizers.get(dialogName) as CrossTrainedRecognizer
if (!crosstrainedRecognizer.recognizers.includes(dialogName + '.qna')) {
crosstrainedRecognizer.recognizers.push(dialogName + '.qna')
}
}
// update settings asset
if (settings) {
settings.qna[dialogFileName.split('.').join('_').replace(/-/g, '_')] = recognizer.getKBId()
settings.qna.hostname = hostName
}
}
}))
}
// write dialog assets
if (recognizers) {
recognizerValues = Array.from(recognizers.values())
}
if (multiRecognizers) {
multiRecognizerValues = Array.from(multiRecognizers.values())
}
if (settings) {
settingsValue = settings as Settings
}
}
if (dialogType === recognizerType.CROSSTRAINED && crosstrainedRecognizers) {
crosstrainedRecognizerValues = Array.from(crosstrainedRecognizers.values())
}
const dialogContents = this.generateDeclarativeAssets(recognizerValues, multiRecognizerValues, settingsValue, crosstrainedRecognizerValues)
return dialogContents
}
async getEndpointKeys(subscriptionkey: string, endpoint: string) {
const qnaBuildCore = new QnaBuildCore(subscriptionkey, endpoint)
const endPointKeys = await qnaBuildCore.getEndpointKeys()
return endPointKeys
}
async importUrlReference(
url: string,
subscriptionkey: string,
endpoint: string,
kbName: string) {
const qnaBuildCore = new QnaBuildCore(subscriptionkey, endpoint)
const kbs = (await qnaBuildCore.getKBList()).knowledgebases
let kbId = ''
// find if there is a matched name with current kb under current authoring key
for (let kb of kbs) {
if (kb.name === kbName) {
kbId = kb.id
break
}
}
// delete the kb if it already exists
if (kbId !== '') {
await qnaBuildCore.deleteKB(kbId)
}
// create a new kb
kbId = await this.createUrlKB(qnaBuildCore, url, kbName)
const kbJson = await qnaBuildCore.exportKB(kbId, 'Test')
const kb = new KB(kbJson)
const kbToLuContent = kb.parseToLuContent()
await qnaBuildCore.deleteKB(kbId)
return kbToLuContent
}
async importFileReference(
fileName: string,
fileUri: string,
subscriptionkey: string,
endpoint: string,
kbName: string) {
const qnaBuildCore = new QnaBuildCore(subscriptionkey, endpoint)
const kbs = (await qnaBuildCore.getKBList()).knowledgebases
let kbId = ''
// find if there is a matched name with current kb under current authoring key
for (let kb of kbs) {
if (kb.name === kbName) {
kbId = kb.id
break
}
}
// delete the kb if it already exists
if (kbId !== '') {
await qnaBuildCore.deleteKB(kbId)
}
// create a new kb
kbId = await this.createFileKB(qnaBuildCore, fileName, fileUri, kbName)
const kbJson = await qnaBuildCore.exportKB(kbId, 'Test')
const kb = new KB(kbJson)
const kbToLuContent = kb.parseToLuContent()
await qnaBuildCore.deleteKB(kbId)
return kbToLuContent
}
async writeDialogAssets(contents: any[], force: boolean, out: string) {
let writeDone = false
for (const content of contents) {
let outFilePath
if (out) {
outFilePath = path.join(path.resolve(out), path.basename(content.path))
} else {
outFilePath = content.path
}
let fileExists = fs.existsSync(outFilePath)
if (fileExists && outFilePath.endsWith('.lu.qna.dialog')) {
let existingCTRecognizerObject = JSON.parse(await fileHelper.getContentFromFile(outFilePath))
let currentCTRecognizerObject = JSON.parse(content.content)
let ctRecognizerToBeMerged = currentCTRecognizerObject.recognizers.filter((r: string) => !existingCTRecognizerObject.recognizers.includes(r))
existingCTRecognizerObject.recognizers = existingCTRecognizerObject.recognizers.concat(ctRecognizerToBeMerged)
content.content = JSON.stringify(existingCTRecognizerObject, null, 4)
}
if (force || !fileExists) {
this.handler(`Writing to ${outFilePath}\n`)
await fs.writeFile(outFilePath, content.content, 'utf-8')
writeDone = true
}
}
return writeDone
}
generateDeclarativeAssets(recognizers: Array<Recognizer>, multiRecognizers: Array<MultiLanguageRecognizer>, settings: Settings, crosstrainedRecognizers: Array<CrossTrainedRecognizer>)
: Array<any> {
let contents = new Array<any>()
for (const recognizer of recognizers) {
let content = new Content(recognizer.save(), new LUOptions(path.basename(recognizer.getDialogPath()), true, '', recognizer.getDialogPath()))
contents.push(content)
}
for (const multiRecognizer of multiRecognizers) {
const multiLangContent = new Content(multiRecognizer.save(), new LUOptions(path.basename(multiRecognizer.getDialogPath()), true, '', multiRecognizer.getDialogPath()))
contents.push(multiLangContent)
}
if (settings) {
const settingsContent = new Content(settings.save(), new LUOptions(path.basename(settings.getSettingsPath()), true, '', settings.getSettingsPath()))
contents.push(settingsContent)
}
for (const crosstrainedRecognizer of crosstrainedRecognizers) {
const crosstrainedContent = new Content(crosstrainedRecognizer.save(), new LUOptions(path.basename(crosstrainedRecognizer.getDialogPath()), true, '', crosstrainedRecognizer.getDialogPath()))
contents.push(crosstrainedContent)
}
return contents
}
async initQnaFromContent(content: any, botName: string, suffix: string) {
let currentQna = await qnaMakerBuilder.fromContent(content.content)
if (!currentQna.kb.name) currentQna.kb.name = `${botName}(${suffix}).${content.language}.qna`
return {kb: currentQna.kb, alterations: currentQna.alterations}
}
async updateKB(currentKB: any, qnaBuildCore: QnaBuildCore, recognizer: Recognizer, delayDuration: number) {
await delay(delayDuration)
const existingKB = await qnaBuildCore.exportKB(recognizer.getKBId(), 'Prod')
// compare models
const isKBEqual = qnaBuildCore.isKBEqual(currentKB, existingKB)
if (!isKBEqual) {
try {
this.handler(`Updating to new version for kb ${currentKB.name}...\n`)
await delay(delayDuration)
await qnaBuildCore.replaceKB(recognizer.getKBId(), currentKB)
this.handler(`Updating finished for kb ${currentKB.name}\n`)
} catch (err) {
err.text = `Updating knowledge base failed: \n${err.text}`
throw err
}
return true
} else {
this.handler(`kb ${currentKB.name} has no changes\n`)
return false
}
}
async createKB(currentKB: any, qnaBuildCore: QnaBuildCore, recognizers: Recognizer[], delayDuration: number) {
this.handler(`Creating qnamaker KB: ${currentKB.name}...\n`)
await delay(delayDuration)
const emptyKBJson = {
name: currentKB.name,
qnaList: [],
urls: [],
files: []
}
let response = await qnaBuildCore.importKB(emptyKBJson)
let operationId = response.operationId
let kbId = ''
try {
const opResult = await this.getKBOperationStatus(qnaBuildCore, operationId, delayDuration)
kbId = opResult.resourceLocation.split('/')[2]
await delay(delayDuration)
await qnaBuildCore.replaceKB(kbId, currentKB)
this.handler(`Creating finished for kb ${currentKB.name}\n`)
} catch (err) {
err.text = `Creating knowledge base failed: \n${err.text}`
throw err
}
recognizers.forEach((recogizer: Recognizer) => recogizer.setKBId(kbId))
return true
}
async createUrlKB(qnaBuildCore: QnaBuildCore, url: string, kbName: string) {
const kbJson = {
name: kbName,
qnaList: [],
urls: [url],
files: []
}
let response = await qnaBuildCore.importKB(kbJson)
let operationId = response.operationId
const opResult = await this.getKBOperationStatus(qnaBuildCore, operationId, 1000)
const kbId = opResult.resourceLocation.split('/')[2]
return kbId
}
async createFileKB(qnaBuildCore: QnaBuildCore, fileName: string, fileUri: string, kbName: string) {
let kbJson = {
name: kbName,
qnaList: [],
urls: [],
files: [{
fileName,
fileUri
}]
}
let response = await qnaBuildCore.importKB(kbJson)
let operationId = response.operationId
const opResult = await this.getKBOperationStatus(qnaBuildCore, operationId, 1000)
const kbId = opResult.resourceLocation.split('/')[2]
return kbId
}
async getKBOperationStatus(qnaBuildCore: QnaBuildCore, operationId: string, delayDuration: number) {
let opResult
let isGetting = true
while (isGetting) {
await delay(delayDuration)
opResult = await qnaBuildCore.getOperationStatus(operationId)
if (opResult.operationState === 'Failed') {
throw(new exception(retCode.errorCode.INVALID_INPUT_FILE, JSON.stringify(opResult, null, 4)))
}
if (opResult.operationState === 'Succeeded') isGetting = false
}
return opResult
}
async publishKB(qnaBuildCore: QnaBuildCore, recognizer: Recognizer, kbName: string, delayDuration: number) {
// publish applications
this.handler(`Publishing kb ${kbName}...\n`)
await delay(delayDuration)
await qnaBuildCore.publishKB(recognizer.getKBId())
this.handler(`Publishing finished for kb ${kbName}\n`)
}
async resolveMergedQnAContentIds(contents: Map<string, any>, objects: Map<string, any[]>, importResolver?: object) {
for (const [name, content] of contents) {
let qnaObjects = objects.get(name)
try {
let result = await qnaBuilderVerbose.build(qnaObjects, true, importResolver)
let mergedContent = result.parseToQnAContent()
content.content = mergedContent
contents.set(name, content)
} catch (err) {
if (err.source) {
err.text = `Invalid QnA file ${err.source}: ${err.text}`
} else {
err.text = `Invalid QnA file ${content.path}: ${err.text}`
}
throw (new exception(retCode.errorCode.INVALID_INPUT_FILE, err.text))
}
}
}
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import Joi from 'joi';
import {
AnySchema,
JoiRoot,
Reference,
Rules,
SchemaLike,
State,
ValidationErrorItem,
ValidationOptions,
} from 'joi';
import { isPlainObject } from 'lodash';
import { isDuration } from 'moment';
import { Stream } from 'stream';
import { ByteSizeValue, ensureByteSizeValue } from '../byte_size_value';
import { ensureDuration } from '../duration';
export { AnySchema, Reference, SchemaLike, ValidationErrorItem };
function isMap<K, V>(o: any): o is Map<K, V> {
return o instanceof Map;
}
const anyCustomRule: Rules = {
name: 'custom',
params: {
validator: Joi.func().maxArity(1).required(),
},
validate(params, value, state, options) {
let validationResultMessage;
try {
validationResultMessage = params.validator(value);
} catch (e) {
validationResultMessage = e.message || e;
}
if (typeof validationResultMessage === 'string') {
return this.createError(
'any.custom',
{ value, message: validationResultMessage },
state,
options
);
}
return value;
},
};
/**
* @internal
*/
export const internals = Joi.extend([
{
name: 'any',
rules: [anyCustomRule],
},
{
name: 'boolean',
base: Joi.boolean(),
coerce(value: any, state: State, options: ValidationOptions) {
// If value isn't defined, let Joi handle default value if it's defined.
if (value === undefined) {
return value;
}
// Allow strings 'true' and 'false' to be coerced to booleans (case-insensitive).
// From Joi docs on `Joi.boolean`:
// > Generates a schema object that matches a boolean data type. Can also
// > be called via bool(). If the validation convert option is on
// > (enabled by default), a string (either "true" or "false") will be
// converted to a boolean if specified.
if (typeof value === 'string') {
const normalized = value.toLowerCase();
value = normalized === 'true' ? true : normalized === 'false' ? false : value;
}
if (typeof value !== 'boolean') {
return this.createError('boolean.base', { value }, state, options);
}
return value;
},
rules: [anyCustomRule],
},
{
name: 'binary',
base: Joi.binary(),
coerce(value: any, state: State, options: ValidationOptions) {
// If value isn't defined, let Joi handle default value if it's defined.
if (value !== undefined && !(typeof value === 'object' && Buffer.isBuffer(value))) {
return this.createError('binary.base', { value }, state, options);
}
return value;
},
rules: [anyCustomRule],
},
{
name: 'stream',
pre(value: any, state: State, options: ValidationOptions) {
// If value isn't defined, let Joi handle default value if it's defined.
if (value instanceof Stream) {
return value as any;
}
return this.createError('stream.base', { value }, state, options);
},
rules: [anyCustomRule],
},
{
name: 'string',
base: Joi.string(),
rules: [anyCustomRule],
},
{
name: 'bytes',
coerce(value: any, state: State, options: ValidationOptions) {
try {
if (typeof value === 'string') {
return ByteSizeValue.parse(value);
}
if (typeof value === 'number') {
return new ByteSizeValue(value);
}
} catch (e) {
return this.createError('bytes.parse', { value, message: e.message }, state, options);
}
return value;
},
pre(value: any, state: State, options: ValidationOptions) {
// If value isn't defined, let Joi handle default value if it's defined.
if (value instanceof ByteSizeValue) {
return value as any;
}
return this.createError('bytes.base', { value }, state, options);
},
rules: [
anyCustomRule,
{
name: 'min',
params: {
limit: Joi.alternatives([Joi.number(), Joi.string()]).required(),
},
validate(params, value, state, options) {
const limit = ensureByteSizeValue(params.limit);
if (value.isLessThan(limit)) {
return this.createError('bytes.min', { value, limit }, state, options);
}
return value;
},
},
{
name: 'max',
params: {
limit: Joi.alternatives([Joi.number(), Joi.string()]).required(),
},
validate(params, value, state, options) {
const limit = ensureByteSizeValue(params.limit);
if (value.isGreaterThan(limit)) {
return this.createError('bytes.max', { value, limit }, state, options);
}
return value;
},
},
],
},
{
name: 'duration',
coerce(value: any, state: State, options: ValidationOptions) {
try {
if (typeof value === 'string' || typeof value === 'number') {
return ensureDuration(value);
}
} catch (e) {
return this.createError('duration.parse', { value, message: e.message }, state, options);
}
return value;
},
pre(value: any, state: State, options: ValidationOptions) {
if (!isDuration(value)) {
return this.createError('duration.base', { value }, state, options);
}
return value;
},
rules: [anyCustomRule],
},
{
name: 'number',
base: Joi.number(),
coerce(value: any, state: State, options: ValidationOptions) {
// If value isn't defined, let Joi handle default value if it's defined.
if (value === undefined) {
return value;
}
// Do we want to allow strings that can be converted, e.g. "2"? (Joi does)
// (this can for example be nice in http endpoints with query params)
//
// From Joi docs on `Joi.number`:
// > Generates a schema object that matches a number data type (as well as
// > strings that can be converted to numbers)
const coercedValue: any = typeof value === 'string' ? Number(value) : value;
if (typeof coercedValue !== 'number' || isNaN(coercedValue)) {
return this.createError('number.base', { value }, state, options);
}
return value;
},
rules: [anyCustomRule],
},
{
name: 'object',
base: Joi.object(),
coerce(value: any, state: State, options: ValidationOptions) {
if (value === undefined || isPlainObject(value)) {
return value;
}
if (options.convert && typeof value === 'string') {
try {
const parsed = JSON.parse(value);
if (isPlainObject(parsed)) {
return parsed;
}
return this.createError('object.base', { value: parsed }, state, options);
} catch (e) {
return this.createError('object.parse', { value }, state, options);
}
}
return this.createError('object.base', { value }, state, options);
},
rules: [anyCustomRule],
},
{
name: 'map',
coerce(value: any, state: State, options: ValidationOptions) {
if (value === undefined) {
return value;
}
if (isPlainObject(value)) {
return new Map(Object.entries(value));
}
if (options.convert && typeof value === 'string') {
try {
const parsed = JSON.parse(value);
if (isPlainObject(parsed)) {
return new Map(Object.entries(parsed));
}
return this.createError('map.base', { value: parsed }, state, options);
} catch (e) {
return this.createError('map.parse', { value }, state, options);
}
}
return value;
},
pre(value: any, state: State, options: ValidationOptions) {
if (!isMap(value)) {
return this.createError('map.base', { value }, state, options);
}
return value as any;
},
rules: [
anyCustomRule,
{
name: 'entries',
params: {
key: Joi.object().schema(),
value: Joi.object().schema(),
},
validate(params, value, state, options) {
const result = new Map();
for (const [entryKey, entryValue] of value) {
const { value: validatedEntryKey, error: keyError } = Joi.validate(
entryKey,
params.key,
{ presence: 'required' }
);
if (keyError) {
return this.createError('map.key', { entryKey, reason: keyError }, state, options);
}
const { value: validatedEntryValue, error: valueError } = Joi.validate(
entryValue,
params.value,
{ presence: 'required' }
);
if (valueError) {
return this.createError(
'map.value',
{ entryKey, reason: valueError },
state,
options
);
}
result.set(validatedEntryKey, validatedEntryValue);
}
return result as any;
},
},
],
},
{
name: 'record',
pre(value: any, state: State, options: ValidationOptions) {
if (value === undefined || isPlainObject(value)) {
return value;
}
if (options.convert && typeof value === 'string') {
try {
const parsed = JSON.parse(value);
if (isPlainObject(parsed)) {
return parsed;
}
return this.createError('record.base', { value: parsed }, state, options);
} catch (e) {
return this.createError('record.parse', { value }, state, options);
}
}
return this.createError('record.base', { value }, state, options);
},
rules: [
anyCustomRule,
{
name: 'entries',
params: { key: Joi.object().schema(), value: Joi.object().schema() },
validate(params, value, state, options) {
const result = {} as Record<string, any>;
for (const [entryKey, entryValue] of Object.entries(value)) {
const { value: validatedEntryKey, error: keyError } = Joi.validate(
entryKey,
params.key,
{ presence: 'required' }
);
if (keyError) {
return this.createError('record.key', { entryKey, reason: keyError }, state, options);
}
const { value: validatedEntryValue, error: valueError } = Joi.validate(
entryValue,
params.value,
{ presence: 'required' }
);
if (valueError) {
return this.createError(
'record.value',
{ entryKey, reason: valueError },
state,
options
);
}
result[validatedEntryKey] = validatedEntryValue;
}
return result as any;
},
},
],
},
{
name: 'array',
base: Joi.array(),
coerce(value: any, state: State, options: ValidationOptions) {
if (value === undefined || Array.isArray(value)) {
return value;
}
if (options.convert && typeof value === 'string') {
try {
const parsed = JSON.parse(value);
if (Array.isArray(parsed)) {
return parsed;
}
return this.createError('array.base', { value: parsed }, state, options);
} catch (e) {
return this.createError('array.parse', { value }, state, options);
}
}
return this.createError('array.base', { value }, state, options);
},
rules: [anyCustomRule],
},
]) as JoiRoot; | the_stack |
import "@fortawesome/fontawesome-free/css/fontawesome.css";
import "@fortawesome/fontawesome-free/css/solid.css";
import "@fortawesome/fontawesome-free/css/brands.css";
import "./editor.css";
import {
API_ANIMATION_CREATE,
API_ANIMATION_JSON
} from "../../../common/common";
import {
Auth,
Deferred,
EVENT_MENU_OPEN,
NeverAsync,
abortableJsonFetch,
isDevEnvironment,
makeLocalUrl
} from "../shared/shared";
import {RenderFrameEvent, Renderer} from "./renderer";
import $ from "jquery";
import {Background} from "./background";
import {Manager} from "./manager";
import {Modal} from "./modal";
import {ModalProgress} from "./modalProgress";
import React from "react";
import {StickerSearch} from "./stickerSearch";
import TextField from "@material-ui/core/TextField";
import TextToSVG from "text-to-svg";
import {Timeline} from "./timeline";
import {Utility} from "./utility";
import {VideoEncoder} from "./videoEncoder";
import {VideoEncoderH264MP4} from "./videoEncoderH264MP4";
import {VideoPlayer} from "./videoPlayer";
import {setHasUnsavedChanges} from "../shared/unload";
import svgToMiniDataURI from "mini-svg-data-uri";
export class Editor {
public root: JQuery;
private background: Background;
private manager: Manager;
public constructor (parent: HTMLElement, history: import("history").History, remixId?: string) {
document.documentElement.style.overflow = "hidden";
this.root = $(require("./editor.html").default).appendTo(parent);
const getElement = (name: string) => parent.querySelector(`#${name}`);
const videoParent = getElement("container") as HTMLDivElement;
const widgetContainer = getElement("widgets") as HTMLDivElement;
const player = new VideoPlayer(videoParent, parent);
const timeline = new Timeline();
const canvas = getElement("canvas") as HTMLCanvasElement;
const renderer = new Renderer(canvas, widgetContainer, player, timeline);
const background = new Background(parent, player.video);
this.background = background;
const manager = new Manager(background, videoParent, widgetContainer, player, timeline, renderer);
this.manager = manager;
(async () => {
manager.spinner.show();
if (remixId) {
const animation = await abortableJsonFetch(API_ANIMATION_JSON, Auth.Optional, {id: remixId});
await manager.load(animation);
} else {
await player.setAttributedSrc({
originUrl: "",
title: "",
previewUrl: "",
mimeType: "video/mp4",
src: isDevEnvironment()
? require("../public/sample.webm").default as string
: require("../public/sample.mp4").default as string
});
}
manager.spinner.hide();
})();
getElement("menu").addEventListener(
"click",
() => window.dispatchEvent(new Event(EVENT_MENU_OPEN))
);
getElement("sticker").addEventListener("click", async () => {
const attributedSource = await StickerSearch.searchForStickerUrl("stickers");
if (attributedSource) {
await manager.addWidget({attributedSource});
}
});
const fontPromise = new Promise<any>((resolve, reject) => {
const src = require("../public/arvo.ttf").default as string;
TextToSVG.load(src, (err, textToSVG) => {
if (err) {
reject(err);
return;
}
resolve(textToSVG);
});
});
getElement("text").addEventListener("click", async () => {
const modal = new Modal();
let text = "";
const button = await modal.open({
buttons: [{dismiss: true, name: "OK", submitOnEnter: true}],
render: () => <TextField fullWidth id="text-input" autoFocus onChange={(e) => {
text = e.target.value;
}}/>,
dismissable: true,
title: "Text"
});
if (button && text) {
const textToSVG = await fontPromise;
const svgText = textToSVG.getSVG(text, {
anchor: "left top",
attributes: {
fill: "white",
stroke: "black"
}
});
const svg = $(svgText);
const src = svgToMiniDataURI(svg.get(0).outerHTML) as string;
await manager.addWidget({
attributedSource: {
originUrl: "",
title: "",
previewUrl: "",
mimeType: "image/svg+xml",
src
}
});
}
});
getElement("video").addEventListener("click", async () => {
const attributedSource = await StickerSearch.searchForStickerUrl("gifs");
if (attributedSource) {
manager.spinner.show();
await player.setAttributedSrc(attributedSource);
manager.spinner.hide();
}
});
const render = async () => {
const modal = new ModalProgress();
const videoEncoder: VideoEncoder = new VideoEncoderH264MP4();
modal.open({
buttons: [
{
callback: async () => {
await renderer.stop();
await videoEncoder.stop();
},
name: "Cancel"
}
],
title: "Rendering & Encoding"
});
await videoEncoder.initialize(
renderer.resizeCanvas,
renderer.resizeContext,
player,
(progress) => modal.setProgress(progress, "Encoding")
);
manager.updateExternally = true;
renderer.onRenderFrame = async (event: RenderFrameEvent) => {
await videoEncoder.processFrame();
modal.setProgress(event.progress, "Rendering");
};
const videoBlob = await (async () => {
if (await renderer.render()) {
return videoEncoder.getOutputVideo();
}
return null;
})();
modal.hide();
renderer.onRenderFrame = null;
manager.updateExternally = false;
if (videoBlob) {
return {
videoBlob,
width: renderer.resizeCanvas.width,
height: renderer.resizeCanvas.height
};
}
return null;
};
const makeLengthBuffer = (size: number) => {
const view = new DataView(new ArrayBuffer(4));
view.setUint32(0, size, true);
return view.buffer;
};
const makePost = async (title: string, message: string) => {
// Since we use 'updateExternally', any widget won't be updated, so just deselect for now.
this.manager.selectWidget(null);
const result = await render();
if (result) {
const jsonBuffer = new TextEncoder().encode(JSON.stringify(manager.save()));
const videoBuffer = await result.videoBlob.arrayBuffer();
const blob = new Blob([
makeLengthBuffer(jsonBuffer.byteLength),
jsonBuffer,
makeLengthBuffer(videoBuffer.byteLength),
videoBuffer
]);
const post = await abortableJsonFetch(
API_ANIMATION_CREATE,
Auth.Required,
{
title,
message,
width: result.width,
height: result.height,
replyId: remixId
},
blob
);
setHasUnsavedChanges(false);
// If the user goes back to the editor in history, they'll be editing a remix of their post.
history.replace(makeLocalUrl("/editor", {remixId: post.id}));
if (post.id === post.threadId) {
history.push(makeLocalUrl("/thread", {threadId: post.threadId}));
} else {
history.push(makeLocalUrl("/thread", {threadId: post.threadId}, post.id));
}
}
};
getElement("post").addEventListener("click", (): NeverAsync => {
let title = "";
let message = "";
const modal = new Modal();
modal.open({
buttons: [
{
callback: () => makePost(title, message),
dismiss: true,
submitOnEnter: true,
name: "Post"
}
],
render: () => <div>
<div>
<TextField
id="post-title"
fullWidth
autoFocus
label="Title"
inputProps={{maxLength: API_ANIMATION_CREATE.props.title.maxLength}}
onChange={(e) => {
title = e.target.value;
}}/>
</div>
<div>
<TextField
id="post-message"
fullWidth
label="Message"
inputProps={{maxLength: API_ANIMATION_CREATE.props.message.maxLength}}
onChange={(e) => {
message = e.target.value;
}}/>
</div>
</div>,
dismissable: true,
title: "Post"
});
});
getElement("motion").addEventListener("click", async () => {
const {selection} = manager;
if (!selection) {
await Modal.messageBox("Motion Tracking", "You must have something selected to perform motion tracking");
return;
}
const motionTrackerPromise = new Deferred<import("./motionTracker").MotionTracker>();
const modal = new ModalProgress();
modal.open({
buttons: [
{
callback: async () => {
await (await motionTrackerPromise).stop();
modal.hide();
},
name: "Stop"
}
],
title: "Tracking"
});
const {MotionTracker} = await import("./motionTracker");
const motionTracker = new MotionTracker(player);
motionTrackerPromise.resolve(motionTracker);
const transform = Utility.getTransform(selection.widget.element);
motionTracker.addPoint(transform.translate[0], transform.translate[1]);
motionTracker.onMotionFrame = async (event: import("./motionTracker").MotionTrackerEvent) => {
modal.setProgress(event.progress, "");
if (event.found) {
transform.translate[0] = event.x;
transform.translate[1] = event.y;
selection.setTransform(transform);
selection.emitKeyframe();
}
};
await motionTracker.track();
motionTracker.onMotionFrame = null;
modal.hide();
});
getElement("visibility").addEventListener("click", async () => {
if (!this.manager.selection) {
await Modal.messageBox("Toggle Visibility", "You must have something selected to toggle visibility");
return;
}
const {element} = this.manager.selection.widget;
manager.toggleVisibility(element);
});
getElement("delete").addEventListener("click", async () => {
manager.attemptDeleteSelection();
});
getElement("clear").addEventListener("click", async () => {
const {selection} = manager;
if (!selection) {
await Modal.messageBox("Clear Keyframes", "You must have something selected to delete its key frames");
return;
}
const range = player.getSelectionRangeInOrder();
if (range[0] === range[1]) {
await Modal.messageBox(
"Clear Keyframes",
"No keyframes were selected. Click and drag on the timeline to create a blue keyframe selection."
);
return;
}
if (!manager.deleteKeyframesInRange(`#${selection.widget.init.id}`, range)) {
await Modal.messageBox("Clear Keyframes", "No keyframes were deleted");
return;
}
manager.updateChanges();
setHasUnsavedChanges(true);
});
}
public destroy () {
this.background.destroy();
this.manager.destroy();
this.root.remove();
document.documentElement.style.overflow = null;
}
} | the_stack |
import { MuWriteStream, MuReadStream } from '../stream';
import { MuSchema } from './schema';
import { MuArray } from './array';
function defaultCompare<T> (a:T, b:T) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
enum SortedOp {
NONE = -1,
SKIP = 0,
PATCH = 1,
INSERT = 2,
INSERT_IDENTITY = 3,
COPY = 4,
}
export class MuSortedArray<ValueSchema extends MuSchema<any>>
implements MuSchema<ValueSchema['identity'][]> {
public readonly muType = 'sorted-array';
public readonly identity:ValueSchema['identity'][];
public readonly muData:ValueSchema;
public readonly json:object;
public readonly compare:(a:ValueSchema['identity'], b:ValueSchema['identity']) => number;
public readonly capacity:number;
constructor (
schema:ValueSchema,
capacity:number,
compare?:(a:ValueSchema['identity'], b:ValueSchema['identity']) => number,
identity?:ValueSchema['identity'][],
) {
this.muData = schema;
this.capacity = capacity;
this.compare = compare || defaultCompare;
const arraySchema = new MuArray(schema, capacity, identity);
this.identity = arraySchema.identity.sort(this.compare);
this.json = {
type: 'sorted-array',
valueType: schema.json,
// FIXME: use diff instead
identity: JSON.stringify(this.identity),
};
this.alloc = arraySchema.alloc;
this.free = arraySchema.free;
this.equal = arraySchema.equal;
this.clone = arraySchema.clone;
this.assign = arraySchema.assign;
this.toJSON = arraySchema.toJSON;
this.fromJSON = arraySchema.fromJSON;
}
public alloc:() => ValueSchema['identity'][];
public free:(set:ValueSchema['identity'][]) => void;
public equal:(a:ValueSchema['identity'][], b:ValueSchema['identity'][]) => boolean;
public clone:(set:ValueSchema['identity'][]) => ValueSchema['identity'][];
public assign:(dst:ValueSchema['identity'][], src:ValueSchema['identity'][]) => ValueSchema['identity'][];
public toJSON:(set:ValueSchema['identity'][]) => any[];
public fromJSON:(json:any[]) => ValueSchema['identity'][];
public diff (
base:ValueSchema['identity'][],
target:ValueSchema['identity'][],
out:MuWriteStream,
) : boolean {
if (base.length === 0 && target.length === 0) {
return false;
}
const schema = this.muData;
const compare = this.compare;
// console.log(`base:[${base.join()}]\ntarget:[${target.join()}]`);
// reserve space for op count
out.grow(8);
const head = out.offset;
let opPtr = head;
let opCount = 0;
let opCode:number = SortedOp.NONE;
out.offset += 4;
let numOps = 0;
function emitOp() {
if (opCount > 0) {
// console.log(`diff: ${SortedOp[opCode]} x ${opCount} @ ${opPtr}`);
out.writeUint32At(opPtr, (opCount << 3) | opCode);
numOps++;
}
// reserve space for next op
out.grow(4);
opPtr = out.offset;
out.offset += 4;
}
// walk list
let basePtr = 0;
let targetPtr = 0;
while (basePtr < base.length && targetPtr < target.length) {
const baseItem = base[basePtr];
const targetItem = target[targetPtr];
const cmp = compare(baseItem, targetItem);
if (cmp < 0) {
if (opCode !== SortedOp.SKIP) {
emitOp();
opCount = 1;
opCode = SortedOp.SKIP;
} else {
opCount++;
}
basePtr++;
} else if (0 < cmp) {
if (opCode === SortedOp.INSERT) {
if (schema.diff(schema.identity, targetItem, out)) {
opCount++;
} else {
emitOp();
opCode = SortedOp.INSERT_IDENTITY;
opCount = 1;
}
} else if (opCode === SortedOp.INSERT_IDENTITY) {
const prevOffset = out.offset;
out.grow(4);
out.offset += 4;
if (schema.diff(schema.identity, targetItem, out)) {
emitOp();
out.offset -= 4;
opPtr = prevOffset;
opCode = SortedOp.INSERT;
opCount = 1;
} else {
out.offset -= 4;
opCount += 1;
}
} else {
emitOp();
opCount = 1;
if (schema.diff(schema.identity, targetItem, out)) {
opCode = SortedOp.INSERT;
} else {
opCode = SortedOp.INSERT_IDENTITY;
}
}
targetPtr++;
} else {
if (opCode === SortedOp.PATCH) {
if (schema.diff(baseItem, targetItem, out)) {
opCount++;
} else {
emitOp();
opCode = SortedOp.COPY;
opCount = 1;
}
} else if (opCode === SortedOp.COPY) {
const prevOffset = out.offset;
out.grow(4);
out.offset += 4;
if (schema.diff(baseItem, targetItem, out)) {
emitOp();
out.offset -= 4;
opPtr = prevOffset;
opCode = SortedOp.PATCH;
opCount = 1;
} else {
out.offset -= 4;
opCount += 1;
}
} else {
emitOp();
opCount = 1;
if (schema.diff(baseItem, targetItem, out)) {
opCode = SortedOp.PATCH;
} else {
opCode = SortedOp.COPY;
}
}
basePtr++;
targetPtr++;
}
}
if (basePtr < base.length) {
if (opCode !== SortedOp.SKIP) {
emitOp();
opCount = base.length - basePtr;
opCode = SortedOp.SKIP;
} else {
opCount += base.length - basePtr;
}
basePtr++;
}
while (targetPtr < target.length) {
const targetItem = target[targetPtr];
if (opCode === SortedOp.INSERT) {
if (schema.diff(schema.identity, targetItem, out)) {
opCount++;
} else {
emitOp();
opCode = SortedOp.INSERT_IDENTITY;
opCount = 1;
}
} else if (opCode === SortedOp.INSERT_IDENTITY) {
const prevOffset = out.offset;
out.grow(4);
out.offset += 4;
if (schema.diff(schema.identity, targetItem, out)) {
emitOp();
out.offset -= 4;
opPtr = prevOffset;
opCode = SortedOp.INSERT;
opCount = 1;
} else {
out.offset -= 4;
opCount += 1;
}
} else {
emitOp();
opCount = 1;
if (schema.diff(schema.identity, targetItem, out)) {
opCode = SortedOp.INSERT;
} else {
opCode = SortedOp.INSERT_IDENTITY;
}
}
targetPtr++;
}
if (numOps === 0 && opCode === SortedOp.COPY && opCount === base.length) {
out.offset = head;
return false;
}
if (opCode !== SortedOp.SKIP) {
emitOp();
}
// write op count
out.offset -= 4;
out.writeUint32At(head, numOps);
return true;
}
public patch (
base:ValueSchema['identity'][],
inp:MuReadStream,
) : ValueSchema['identity'][] {
const schema = this.muData;
const result = this.alloc();
const numOps = inp.readUint32();
let ptr = 0;
let tLength = 0;
for (let i = 0; i < numOps; ++i) {
const code = inp.readUint32();
const count = code >> 3;
tLength += count;
if (tLength > this.capacity) {
throw new RangeError(`target length exceeds capacity ${this.capacity}`);
}
const op = code & 0x7;
// console.log(`patch: ${SortedOp[op]} x ${count} @ ${inp.offset - 4}, ptr=${ptr}`);
switch (op) {
case SortedOp.INSERT_IDENTITY:
for (let j = 0; j < count; ++j) {
result.push(schema.clone(schema.identity));
}
break;
case SortedOp.INSERT:
for (let j = 0; j < count; ++j) {
result.push(schema.patch(schema.identity, inp));
}
break;
case SortedOp.PATCH:
for (let j = 0; j < count; ++j) {
result.push(schema.patch(base[ptr++], inp));
}
break;
case SortedOp.COPY:
for (let j = 0; j < count; ++j) {
result.push(schema.clone(base[ptr++]));
}
break;
case SortedOp.SKIP:
ptr += count;
break;
}
}
return result;
}
} | the_stack |
import React, {createContext} from 'react';
import {getCSSData} from './common/utils';
import { EasingFunction, Vec2 } from './common/types';
namespace SharedElement {
//https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin#formal_syntax
//https://stackoverflow.com/questions/51445767/how-to-define-a-regex-matched-string-type-in-typescript
enum TransformOriginKeywordEnum {
top,
bottom,
left,
right,
};
enum TransformOriginLengthUnitEnum {
cap, ch, em, ex, ic, lh, rem, rlh, //relative length
vh, vw, vi, vb, vmin, vmax, //viewport percentage length
px, cm, mm, Q, in, pc, pt, //absolute length
'%'
}
enum TransformOriginGlobalEnum {
inital,
inherit,
revert,
unset
}
enum TransitionAnimationEnum {
"morph",
"fade-through",
"fade",
"cross-fade"
}
type TransitionAnimation = keyof typeof TransitionAnimationEnum;
type TransformOriginGlobal = keyof typeof TransformOriginGlobalEnum;
type TransformOriginLengthUnit = keyof typeof TransformOriginLengthUnitEnum;
//e.g. 20px, 20%, 20rem
type TransformOriginLength = `${number}${TransformOriginLengthUnit}` | 0;
type TransformOriginKeyword = keyof typeof TransformOriginKeywordEnum;
type OneValueTransformOrigin = TransformOriginKeyword | TransformOriginLength;
type TwoValueTransformOrigin = `${OneValueTransformOrigin} ${OneValueTransformOrigin}`;
type ThreeValueTransformOrigin = `${OneValueTransformOrigin} ${OneValueTransformOrigin} ${TransformOriginLength}`;
type TransformOrigin = TransformOriginGlobal | OneValueTransformOrigin | TwoValueTransformOrigin | ThreeValueTransformOrigin;
export interface SharedElementNode {
id: string;
node: HTMLElement;
instance: SharedElement;
}
export type NodeMap = Map<string, SharedElementNode>;
export class Scene {
private _nodes: NodeMap = new Map<string, SharedElementNode>();
private _name: string = '';
private _scrollPos: Vec2 | null = null;
private _x: number = 0;
private _y: number = 0;
private _xRatio: number = 0;
private _yRatio: number = 0;
private _keepAlive: boolean = false;
constructor(name: string) {
this._name = name;
}
addNode(node: SharedElementNode | null) {
if (!node) return;
console.assert(!this.nodes.has(node.id), `Duplicate Shared Element ID: ${node.id} in ${this._name}`);
this._nodes.set(node.id, node);
}
removeNode(_id: string) {
this._nodes.delete(_id);
}
get xRatio() {
return this._xRatio;
}
get yRatio() {
return this._yRatio;
}
get nodes(): NodeMap {
return this._nodes;
}
get name(): string {
return this._name;
}
get scrollPos() {
return this._scrollPos || {
x: 0,
y: 0
};
}
get x() {
return this._x;
}
get y() {
return this._y;
}
get keepAlive() {
return this._keepAlive;
}
set scrollPos(_scrollPos: Vec2) {
this._scrollPos = _scrollPos;
}
set x(_x: number) {
this._x = _x;
}
set y(_y: number) {
this._y = _y;
}
set xRatio(_xRatio: number) {
this._xRatio = _xRatio;
}
set yRatio(_yRatio: number) {
this._yRatio = _yRatio;
}
set keepAlive(_keepAlive: boolean) {
this._keepAlive = _keepAlive
}
isEmpty() {
return !Boolean(this._nodes.size);
}
}
export const SceneContext = createContext<Scene | null>(null);
function nodeFromRef(
id: string,
_ref: Element,
instance: SharedElement.SharedElement
): SharedElementNode | null {
const node: HTMLElement = _ref.cloneNode(true) as HTMLElement;
const firstChild = node.firstElementChild as HTMLElement | null;
if (!firstChild) return null;
if (instance.props.config && instance.props.config.transformOrigin) {
firstChild.style.transformOrigin = instance.props.config.transformOrigin;
}
return {
id: id,
node: node,
instance: instance
};
}
interface SharedElementConfig {
type?: TransitionAnimation;
transformOrigin?: TransformOrigin;
easingFunction?: EasingFunction;
duration?: number;
x?: {
duration?: number;
easingFunction?: EasingFunction
};
y?: {
duration?: number;
easingFunction?: EasingFunction
};
}
interface SharedElementProps {
id: string | number;
children: React.ReactChild;
config?: SharedElementConfig;
}
interface SharedElementState {
hidden: boolean;
keepAlive: boolean;
}
export class SharedElement extends React.Component<SharedElementProps, SharedElementState> {
private _id : string = this.props.id.toString();
private _ref: HTMLDivElement | null = null;
private _scene: Scene | null = null;
private _mutationObserver = new MutationObserver(this.updateScene.bind(this));
private _idleCallbackID: number = 0;
private _computedStyle: CSSStyleDeclaration | null = null;
private _isMounted = false;
private onRef = this.setRef.bind(this);
state: SharedElementState = {
hidden: false,
keepAlive: false
}
get scene() {
return this._scene;
}
get clientRect() {
if (this._ref && this._ref.firstElementChild) {
const clientRect = this._ref.firstElementChild.getBoundingClientRect();
return clientRect;
}
return new DOMRect();
}
get CSSData(): [string, {[key:string]:string}] {
const _computedStyle = this._computedStyle;
if (_computedStyle) return getCSSData(_computedStyle);
return ['', {}];
}
get CSSText(): string {
const _computedStyle = this._computedStyle;
if (_computedStyle) {
const [CSSText] = getCSSData(_computedStyle, false);
return CSSText;
};
return '';
}
get id() {
return this._id;
}
get transitionType() {
return this.props.config?.type;
}
keepAlive(_keepAlive: boolean): Promise<void> {
return new Promise((resolve) => {
this.setState({keepAlive: _keepAlive}, () => resolve());
});
}
hidden(_hidden: boolean): Promise<void> {
return new Promise((resolve, _) => {
if (this._isMounted) {
this.setState({hidden: _hidden}, () => {
resolve();
});
} else {
resolve();
}
});
}
private setRef(_ref: HTMLDivElement | null) {
if (this._ref !== _ref) {
if (this._ref) {
this.scene?.removeNode(this._id);
this._mutationObserver.disconnect();
this._computedStyle = null;
}
this._ref = _ref;
if (_ref) {
this.scene?.addNode(nodeFromRef(this._id, _ref, this));
if (_ref.firstElementChild) {
this._computedStyle = window.getComputedStyle(_ref.firstElementChild);
this._mutationObserver.observe(_ref.firstElementChild, {
attributes: true,
childList: true,
subtree: true
});
}
}
}
}
updateScene() {
cancelIdleCallback(this._idleCallbackID);
this._idleCallbackID = requestIdleCallback(() => {
if (this._ref) {
this.scene?.removeNode(this._id);
this.scene?.addNode(nodeFromRef(this._id, this._ref, this));
if (this._ref.firstElementChild)
this._computedStyle = window.getComputedStyle(this._ref.firstElementChild);
}
this._idleCallbackID = 0;
});
}
componentDidMount() {
this._isMounted = true;
}
componentDidUpdate() {
if (this._id !== this.props.id.toString()) {
if (this._ref) {
this.scene?.removeNode(this._id);
this._id = this.props.id.toString();
this.scene?.addNode(nodeFromRef(this._id, this._ref, this));
}
}
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
return (
<SceneContext.Consumer>
{(scene) => {
this._scene = scene;
return (
<div
ref={this.onRef}
id={`shared-element-${this._id}`}
style={{
display: this.state.hidden && !this.keepAlive ? 'block' : 'contents',
visibility: this.state.hidden ? 'hidden': 'visible'
}}
>
{this.props.children}
</div>
);
}}
</SceneContext.Consumer>
);
}
}
}
export default SharedElement; | the_stack |
import assert = require('assert');
import react = require('react');
import style = require('ts-style');
import url = require('url');
import app_theme = require('./theme');
import auth_dialog = require('./auth_dialog');
import autofill = require('./autofill');
import colors = require('./controls/colors');
import details_view = require('./details_view');
import item_builder = require('../lib/item_builder');
import item_list = require('./item_list_view');
import item_icons = require('./item_icons');
import item_store = require('../lib/item_store');
import key_agent = require('../lib/key_agent');
import menu = require('./controls/menu');
import browser_access = require('./browser_access');
import password_gen = require('../lib/password_gen');
import reactutil = require('./base/reactutil');
import settings = require('./settings');
import setup_view = require('./setup_view');
import status_message = require('./status');
import sync = require('../lib/sync');
import toaster = require('./controls/toaster');
import unlock_view = require('./unlock_view');
import url_util = require('../lib/base/url_util');
import app_state = require('./stores/app');
import { delay } from '../lib/base/promise_util';
import { div } from './base/dom_factory';
var theme = style.create(
{
appView: {
width: '100%',
height: '100%',
userSelect: 'none',
color: colors.MATERIAL_TEXT_PRIMARY,
},
},
__filename
);
export interface AppViewState {
selectedItemRect?: reactutil.Rect;
status?: status_message.Status;
appMenuSourceRect?: reactutil.Rect;
viewportRect?: reactutil.Rect;
}
export interface AppServices {
pageAccess: browser_access.BrowserAccess;
autofiller: autofill.AutoFillHandler;
iconProvider: item_icons.IconProvider;
keyAgent: key_agent.KeyAgent;
clipboard: browser_access.ClipboardAccess;
settings?: settings.Store;
}
export interface AppViewProps extends react.Props<void> {
services: AppServices;
viewportRect: reactutil.Rect;
appState: app_state.Store;
}
/** The main top-level app view. */
class AppView extends react.Component<AppViewProps, AppViewState> {
private mounted: boolean;
constructor(props: AppViewProps) {
super(props);
this.state = { viewportRect: this.props.viewportRect };
}
componentWillMount() {
this.mounted = true;
this.props.appState.stateChanged.listen(state => {
this.forceUpdate();
}, this);
}
componentWillUnmount() {
this.props.appState.stateChanged.ignoreContext(this);
}
private showError(error: Error, context?: string) {
assert(error.message);
let message = context || '';
if (message) {
message += ': ';
}
message += error.message;
var status = new status_message.Status(
status_message.StatusType.Error,
message
);
this.showStatus(status);
console.log('App error:', error.message, error.stack);
}
private showStatus(status: status_message.Status) {
status.expired.listen(() => {
if (this.state.status == status) {
this.setState({ status: null });
}
});
this.setState({ status: status });
}
private autofill(item: item_store.Item) {
this.props.services.autofiller
.autofill(item)
.then(result => {
if (result.count > 0) {
this.props.services.pageAccess.hidePanel();
}
})
.catch(err => {
this.showError(err.message);
});
}
private setSelectedItem(item: item_store.Item, rect?: reactutil.Rect) {
var state = <app_state.State>{
selectedItem: item,
};
if (item) {
if (item.isSaved()) {
state.itemEditMode = details_view.ItemEditMode.EditItem;
} else {
state.itemEditMode = details_view.ItemEditMode.AddItem;
}
}
this.props.appState.update(state);
this.setState({ selectedItemRect: rect });
}
render(): react.ReactElement<any> {
if (!this.props.appState.state.store) {
return setup_view.SetupViewF({
settings: this.props.services.settings,
});
}
var children: react.ReactElement<any>[] = [];
var itemStoreState = this.props.appState.state;
children.push(
unlock_view.UnlockViewF({
key: 'unlockPane',
store: itemStoreState.store,
isLocked: itemStoreState.isLocked,
focus: itemStoreState.isLocked,
onUnlock: () => {
this.props.appState.update({ isLocked: false });
itemStoreState.syncer
.syncItems()
.then(result => {
if (result.failed > 0) {
this.showError(
new Error(
`Sync completed but ${
result.failed
} items failed to sync`
)
);
}
})
.catch(err => {
this.showError(
new Error(
`Unable to sync items: ${err.toString()}`
)
);
});
},
onUnlockErr: err => {
this.showError(err);
},
onMenuClicked: rect => {
this.setState({ appMenuSourceRect: rect });
},
})
);
children.push(this.renderItemList());
children.push(this.renderItemDetails());
children.push(this.renderToasters());
children.push(this.renderDialogs());
var menu = reactutil.TransitionGroupF(
<any>{ key: 'toolbar-menu' },
this.state.appMenuSourceRect ? this.renderMenu('menu') : null
);
children.push(menu);
return div(style.mixin(theme.appView, { ref: 'app' }), children);
}
private renderDialogs() {
let activeDialog: react.ReactElement<{}>;
if (this.props.appState.state.isSigningIn) {
activeDialog = auth_dialog.AuthDialogF({
authServerURL: this.props.appState.state.authServerURL,
onComplete: credentials => {
if (credentials) {
this.props.appState.state.onReceiveCredentials(
credentials
);
}
this.props.appState.update({ isSigningIn: false });
},
});
}
return activeDialog;
}
private renderToasters() {
var toasters: react.ReactElement<toaster.ToasterProps>[] = [];
if (this.state.status) {
toasters.push(
toaster.ToasterF({
key: 'status-toaster',
message: this.state.status.text,
})
);
}
var syncState = this.props.appState.state.syncState;
if (syncState && syncState.state !== sync.SyncState.Idle) {
toasters.push(
toaster.ToasterF({
key: 'sync-toaster',
message: 'Syncing...',
progressValue: syncState.updated,
progressMax: syncState.total,
})
);
}
return reactutil.TransitionGroupF(
<any>{ key: 'toasterList' },
toasters
);
}
private renderItemList() {
var itemStoreState = this.props.appState.state;
return item_list.ItemListViewF({
key: 'itemList',
ref: 'itemList',
items: itemStoreState.items,
selectedItem: itemStoreState.selectedItem,
onSelectedItemChanged: (item, rect) => {
this.setSelectedItem(item, rect);
},
currentUrl: itemStoreState.currentUrl,
iconProvider: this.props.services.iconProvider,
onLockClicked: () => this.props.services.keyAgent.forgetKeys(),
onMenuClicked: e => {
this.setState({ appMenuSourceRect: e.itemRect });
},
focus: !itemStoreState.isLocked && !itemStoreState.selectedItem,
});
}
private itemStoreState() {
return this.props.appState.state;
}
private renderItemDetails() {
var detailsView: react.ReactElement<{}>;
if (this.itemStoreState().selectedItem) {
var appRect = this.state.viewportRect;
var selectedItemRect = this.state.selectedItemRect;
if (!selectedItemRect) {
// when adding a new item, the details view
// will slide up from the bottom of the screen
selectedItemRect = {
top: appRect.bottom,
bottom: appRect.bottom,
left: appRect.left,
right: appRect.right,
};
}
detailsView = details_view.DetailsViewF({
key: 'detailsView',
item: this.itemStoreState().selectedItem,
editMode: this.itemStoreState().itemEditMode,
iconProvider: this.props.services.iconProvider,
currentUrl: this.itemStoreState().currentUrl,
onGoBack: () => {
this.setSelectedItem(null);
},
onSave: updatedItem => {
// defer saving the item until the details view has
// transitioned out
var SAVE_DELAY = 1000;
delay(null, SAVE_DELAY)
.then(() => {
return updatedItem.item.saveTo(
this.itemStoreState().store
);
})
.then(() => {
return this.itemStoreState().syncer.syncItems();
})
.then(() => {
this.showStatus(
new status_message.Status(
status_message.StatusType.Success,
'Changes saved and synced'
)
);
})
.catch(err => {
this.showError(err);
});
},
autofill: () => {
this.autofill(this.itemStoreState().selectedItem);
},
clipboard: this.props.services.clipboard,
focus: this.itemStoreState().selectedItem != null,
// make the details view expand from the entry
// in the item list, but only if we switch to it
// after the app is initially shown
animateEntry: this.mounted,
entryRect: {
left: appRect.left,
right: appRect.right,
top: selectedItemRect.top,
bottom: selectedItemRect.bottom,
},
viewportRect: this.state.viewportRect,
});
}
return detailsView;
}
private createNewItemTemplate() {
// use the most common account (very likely the user's email address)
// as the default account login for new items
var accountFreq: { [id: string]: number } = {};
this.itemStoreState().items.forEach(item => {
if (!accountFreq.hasOwnProperty(item.account)) {
accountFreq[item.account] = 1;
} else {
++accountFreq[item.account];
}
});
var defaultAccount: string;
Object.keys(accountFreq).forEach(account => {
if (
!defaultAccount ||
accountFreq[account] > accountFreq[defaultAccount]
) {
defaultAccount = account;
}
});
if (!defaultAccount) {
// TODO - Use the user's Dropbox login if there is no
// default account set
defaultAccount = '';
}
var randomPassword = password_gen.generatePassword(12);
var builder = new item_builder.Builder(item_store.ItemTypes.LOGIN)
.addLogin(defaultAccount)
.addPassword(randomPassword);
// prefill the new item with the current URL for web pages.
// Avoid prefilling for special browser pages (eg. 'about:version',
// 'chrome://settings') or blank tabs
var AUTOFILL_URL_SCHEMES = ['http:', 'https:', 'ftp:'];
var currentUrlProtocol = url.parse(this.itemStoreState().currentUrl)
.protocol;
if (AUTOFILL_URL_SCHEMES.indexOf(currentUrlProtocol) !== -1) {
builder.setTitle(
url_util.topLevelDomain(this.itemStoreState().currentUrl)
);
const url = new URL(this.itemStoreState().currentUrl);
builder.addUrl(url.origin);
} else {
builder.setTitle('New Login');
}
return builder.item();
}
private renderMenu(key: string) {
var menuItems: menu.MenuItem[] = [];
if (!this.itemStoreState().isLocked) {
menuItems = menuItems.concat([
{
label: 'Add Item',
onClick: () => {
this.setSelectedItem(this.createNewItemTemplate());
},
},
]);
}
menuItems = menuItems.concat([
{
label: 'Clear Offline Storage',
onClick: () => {
return this.props.services.keyAgent
.forgetKeys()
.then(() => {
return this.itemStoreState().store.clear();
})
.then(() => {
return this.itemStoreState().syncer.syncKeys();
})
.catch(err => {
this.showError(err);
});
},
},
{
label: 'Switch Store',
onClick: () => {
this.props.services.settings.clear(
settings.Setting.ActiveAccount
);
},
},
{
label: 'Help',
onClick: () => {
var win = window.open(
'https://robertknight.github.io/passcards',
'_blank'
);
win.focus();
},
},
]);
return menu.MenuF({
key: key,
items: menuItems,
sourceRect: this.state.appMenuSourceRect,
viewportRect: this.state.viewportRect,
onDismiss: () => {
this.setState({ appMenuSourceRect: null });
},
zIndex: app_theme.Z_LAYERS.MENU_LAYER,
});
}
}
export var AppViewF = react.createFactory(AppView); | the_stack |
import { Dictionary} from './../../../collections/dictionary';
/**
* `Metrics` of the font.
* @private
*/
export class Bidi {
//#region Fields
private indexes : number[] = [];
private indexLevels : number[] = [];
private mirroringShapeCharacters : Dictionary<number, number> = new Dictionary<number, number>();
//#endregion
//#region Constructor
public constructor() {
this.update();
}
//#endregion
//#region implementation
private doMirrorShaping( text : string) : string {
let result : string[] = [];
for (let i : number = 0; i < text.length; i++) {
if (((this.indexLevels[i] & 1) === 1) && this.mirroringShapeCharacters.containsKey(text[i].charCodeAt(0))) {
result[i] = String.fromCharCode(this.mirroringShapeCharacters.getValue(text[i].charCodeAt(0)));
} else {
result[i] = text[i].toString();
}
}
let res : string = '';
for (let j : number = 0; j < result.length; j++) {
res = res + result[j];
}
return res;
}
public getLogicalToVisualString( inputText : string, isRtl : boolean) : string {
let rtlCharacters : RtlCharacters = new RtlCharacters();
this.indexLevels = rtlCharacters.getVisualOrder(inputText, isRtl);
this.setDefaultIndexLevel();
this.doOrder(0, this.indexLevels.length - 1);
let text : string = this.doMirrorShaping(inputText);
//let text : string = inputText;
let resultBuilder : string = '';
for (let i : number = 0; i < this.indexes.length; i++) {
let index : number = this.indexes[i];
resultBuilder += text[index];
}
return resultBuilder.toString();
}
private setDefaultIndexLevel() : void {
for (let i : number = 0; i < this.indexLevels.length; i++) {
this.indexes[i] = i;
}
}
private doOrder(sIndex : number, eIndex : number): void {
let max : number = this.indexLevels[sIndex];
let min : number = max;
let odd : number = max;
let even : number = max;
for (let i : number = sIndex + 1; i <= eIndex; ++i) {
let data : number = this.indexLevels[i];
if (data > max) {
max = data;
} else if (data < min) {
min = data;
}
odd &= data;
even |= data;
}
if ((even & 1) === 0) {
return;
}
if ((odd & 1) === 1) {
this.reArrange(sIndex, eIndex + 1);
return;
}
min |= 1;
while (max >= min) {
let pstart : number = sIndex;
/*tslint:disable:no-constant-condition */
while (true) {
while (pstart <= eIndex) {
if (this.indexLevels[pstart] >= max) {
break;
}
pstart += 1;
}
if (pstart > eIndex) {
break;
}
let pend : number = pstart + 1;
while (pend <= eIndex) {
if (this.indexLevels[pend] < max) {
break;
}
pend += 1;
}
this.reArrange(pstart, pend);
pstart = pend + 1;
}
max -= 1;
}
}
private reArrange(i : number , j : number) : void {
let length : number = (i + j) / 2;
--j;
for (; i < length; ++i, --j) {
let temp : number = this.indexes[i];
this.indexes[i] = this.indexes[j];
this.indexes[j] = temp;
}
}
private update() : void {
this.mirroringShapeCharacters.setValue(40, 41);
this.mirroringShapeCharacters.setValue(41, 40);
this.mirroringShapeCharacters.setValue(60, 62);
this.mirroringShapeCharacters.setValue(62, 60);
this.mirroringShapeCharacters.setValue(91, 93);
this.mirroringShapeCharacters.setValue(93, 91);
this.mirroringShapeCharacters.setValue(123, 125);
this.mirroringShapeCharacters.setValue(125, 123);
this.mirroringShapeCharacters.setValue(171, 187);
this.mirroringShapeCharacters.setValue(187, 171);
this.mirroringShapeCharacters.setValue(8249, 8250);
this.mirroringShapeCharacters.setValue(8250, 8249);
this.mirroringShapeCharacters.setValue(8261, 8262);
this.mirroringShapeCharacters.setValue(8262, 8261);
this.mirroringShapeCharacters.setValue(8317, 8318);
this.mirroringShapeCharacters.setValue(8318, 8317);
this.mirroringShapeCharacters.setValue(8333, 8334);
this.mirroringShapeCharacters.setValue(8334, 8333);
this.mirroringShapeCharacters.setValue(8712, 8715);
this.mirroringShapeCharacters.setValue(8713, 8716);
this.mirroringShapeCharacters.setValue(8714, 8717);
this.mirroringShapeCharacters.setValue(8715, 8712);
this.mirroringShapeCharacters.setValue(8716, 8713);
this.mirroringShapeCharacters.setValue(8717, 8714);
this.mirroringShapeCharacters.setValue(8725, 10741);
this.mirroringShapeCharacters.setValue(8764, 8765);
this.mirroringShapeCharacters.setValue(8765, 8764);
this.mirroringShapeCharacters.setValue(8771, 8909);
this.mirroringShapeCharacters.setValue(8786, 8787);
this.mirroringShapeCharacters.setValue(8787, 8786);
this.mirroringShapeCharacters.setValue(8788, 8789);
this.mirroringShapeCharacters.setValue(8789, 8788);
this.mirroringShapeCharacters.setValue(8804, 8805);
this.mirroringShapeCharacters.setValue(8805, 8804);
this.mirroringShapeCharacters.setValue(8806, 8807);
this.mirroringShapeCharacters.setValue(8807, 8806);
this.mirroringShapeCharacters.setValue(8808, 8809);
this.mirroringShapeCharacters.setValue(8809, 8808);
this.mirroringShapeCharacters.setValue(8810, 8811);
this.mirroringShapeCharacters.setValue(8811, 8810);
this.mirroringShapeCharacters.setValue(8814, 8815);
this.mirroringShapeCharacters.setValue(8815, 8814);
this.mirroringShapeCharacters.setValue(8816, 8817);
this.mirroringShapeCharacters.setValue(8817, 8816);
this.mirroringShapeCharacters.setValue(8818, 8819);
this.mirroringShapeCharacters.setValue(8819, 8818);
this.mirroringShapeCharacters.setValue(8820, 8821);
this.mirroringShapeCharacters.setValue(8821, 8820);
this.mirroringShapeCharacters.setValue(8822, 8823);
this.mirroringShapeCharacters.setValue(8823, 8822);
this.mirroringShapeCharacters.setValue(8824, 8825);
this.mirroringShapeCharacters.setValue(8825, 8824);
this.mirroringShapeCharacters.setValue(8826, 8827);
this.mirroringShapeCharacters.setValue(8827, 8826);
this.mirroringShapeCharacters.setValue(8828, 8829);
this.mirroringShapeCharacters.setValue(8829, 8828);
this.mirroringShapeCharacters.setValue(8830, 8831);
this.mirroringShapeCharacters.setValue(8831, 8830);
this.mirroringShapeCharacters.setValue(8832, 8833);
this.mirroringShapeCharacters.setValue(8833, 8832);
this.mirroringShapeCharacters.setValue(8834, 8835);
this.mirroringShapeCharacters.setValue(8835, 8834);
this.mirroringShapeCharacters.setValue(8836, 8837);
this.mirroringShapeCharacters.setValue(8837, 8836);
this.mirroringShapeCharacters.setValue(8838, 8839);
this.mirroringShapeCharacters.setValue(8839, 8838);
this.mirroringShapeCharacters.setValue(8840, 8841);
this.mirroringShapeCharacters.setValue(8841, 8840);
this.mirroringShapeCharacters.setValue(8842, 8843);
this.mirroringShapeCharacters.setValue(8843, 8842);
this.mirroringShapeCharacters.setValue(8847, 8848);
this.mirroringShapeCharacters.setValue(8848, 8847);
this.mirroringShapeCharacters.setValue(8849, 8850);
this.mirroringShapeCharacters.setValue(8850, 8849);
this.mirroringShapeCharacters.setValue(8856, 10680);
this.mirroringShapeCharacters.setValue(8866, 8867);
this.mirroringShapeCharacters.setValue(8867, 8866);
this.mirroringShapeCharacters.setValue(8870, 10974);
this.mirroringShapeCharacters.setValue(8872, 10980);
this.mirroringShapeCharacters.setValue(8873, 10979);
this.mirroringShapeCharacters.setValue(8875, 10981);
this.mirroringShapeCharacters.setValue(8880, 8881);
this.mirroringShapeCharacters.setValue(8881, 8880);
this.mirroringShapeCharacters.setValue(8882, 8883);
this.mirroringShapeCharacters.setValue(8883, 8882);
this.mirroringShapeCharacters.setValue(8884, 8885);
this.mirroringShapeCharacters.setValue(8885, 8884);
/*tslint:disable:max-func-body-length */
this.mirroringShapeCharacters.setValue(8886, 8887);
this.mirroringShapeCharacters.setValue(8887, 8886);
this.mirroringShapeCharacters.setValue(8905, 8906);
this.mirroringShapeCharacters.setValue(8906, 8905);
this.mirroringShapeCharacters.setValue(8907, 8908);
this.mirroringShapeCharacters.setValue(8908, 8907);
this.mirroringShapeCharacters.setValue(8909, 8771);
this.mirroringShapeCharacters.setValue(8912, 8913);
this.mirroringShapeCharacters.setValue(8913, 8912);
this.mirroringShapeCharacters.setValue(8918, 8919);
this.mirroringShapeCharacters.setValue(8919, 8918);
this.mirroringShapeCharacters.setValue(8920, 8921);
this.mirroringShapeCharacters.setValue(8921, 8920);
this.mirroringShapeCharacters.setValue(8922, 8923);
this.mirroringShapeCharacters.setValue(8923, 8922);
this.mirroringShapeCharacters.setValue(8924, 8925);
this.mirroringShapeCharacters.setValue(8925, 8924);
this.mirroringShapeCharacters.setValue(8926, 8927);
this.mirroringShapeCharacters.setValue(8927, 8926);
this.mirroringShapeCharacters.setValue(8928, 8929);
this.mirroringShapeCharacters.setValue(8929, 8928);
this.mirroringShapeCharacters.setValue(8930, 8931);
this.mirroringShapeCharacters.setValue(8931, 8930);
this.mirroringShapeCharacters.setValue(8932, 8933);
this.mirroringShapeCharacters.setValue(8933, 8932);
this.mirroringShapeCharacters.setValue(8934, 8935);
this.mirroringShapeCharacters.setValue(8935, 8934);
this.mirroringShapeCharacters.setValue(8936, 8937);
this.mirroringShapeCharacters.setValue(8937, 8936);
this.mirroringShapeCharacters.setValue(8938, 8939);
this.mirroringShapeCharacters.setValue(8939, 8938);
this.mirroringShapeCharacters.setValue(8940, 8941);
this.mirroringShapeCharacters.setValue(8941, 8940);
this.mirroringShapeCharacters.setValue(8944, 8945);
this.mirroringShapeCharacters.setValue(8945, 8944);
this.mirroringShapeCharacters.setValue(8946, 8954);
this.mirroringShapeCharacters.setValue(8947, 8955);
this.mirroringShapeCharacters.setValue(8948, 8956);
this.mirroringShapeCharacters.setValue(8950, 8957);
this.mirroringShapeCharacters.setValue(8951, 8958);
this.mirroringShapeCharacters.setValue(8954, 8946);
this.mirroringShapeCharacters.setValue(8955, 8947);
this.mirroringShapeCharacters.setValue(8956, 8948);
this.mirroringShapeCharacters.setValue(8957, 8950);
this.mirroringShapeCharacters.setValue(8958, 8951);
this.mirroringShapeCharacters.setValue(8968, 8969);
this.mirroringShapeCharacters.setValue(8969, 8968);
this.mirroringShapeCharacters.setValue(8970, 8971);
this.mirroringShapeCharacters.setValue(8971, 8970);
this.mirroringShapeCharacters.setValue(9001, 9002);
this.mirroringShapeCharacters.setValue(9002, 9001);
this.mirroringShapeCharacters.setValue(10088, 10089);
this.mirroringShapeCharacters.setValue(10089, 10088);
this.mirroringShapeCharacters.setValue(10090, 10091);
this.mirroringShapeCharacters.setValue(10091, 10090);
this.mirroringShapeCharacters.setValue(10092, 10093);
this.mirroringShapeCharacters.setValue(10093, 10092);
this.mirroringShapeCharacters.setValue(10094, 10095);
this.mirroringShapeCharacters.setValue(10095, 10094);
this.mirroringShapeCharacters.setValue(10096, 10097);
this.mirroringShapeCharacters.setValue(10097, 10096);
this.mirroringShapeCharacters.setValue(10098, 10099);
this.mirroringShapeCharacters.setValue(10099, 10098);
this.mirroringShapeCharacters.setValue(10100, 10101);
this.mirroringShapeCharacters.setValue(10101, 10100);
this.mirroringShapeCharacters.setValue(10197, 10198);
this.mirroringShapeCharacters.setValue(10198, 10197);
this.mirroringShapeCharacters.setValue(10205, 10206);
this.mirroringShapeCharacters.setValue(10206, 10205);
this.mirroringShapeCharacters.setValue(10210, 10211);
this.mirroringShapeCharacters.setValue(10211, 10210);
this.mirroringShapeCharacters.setValue(10212, 10213);
this.mirroringShapeCharacters.setValue(10213, 10212);
this.mirroringShapeCharacters.setValue(10214, 10215);
this.mirroringShapeCharacters.setValue(10215, 10214);
this.mirroringShapeCharacters.setValue(10216, 10217);
this.mirroringShapeCharacters.setValue(10217, 10216);
this.mirroringShapeCharacters.setValue(10218, 10219);
this.mirroringShapeCharacters.setValue(10219, 10218);
this.mirroringShapeCharacters.setValue(10627, 10628);
this.mirroringShapeCharacters.setValue(10628, 10627);
this.mirroringShapeCharacters.setValue(10629, 10630);
this.mirroringShapeCharacters.setValue(10630, 10629);
this.mirroringShapeCharacters.setValue(10631, 10632);
this.mirroringShapeCharacters.setValue(10632, 10631);
this.mirroringShapeCharacters.setValue(10633, 10634);
this.mirroringShapeCharacters.setValue(10634, 10633);
this.mirroringShapeCharacters.setValue(10635, 10636);
this.mirroringShapeCharacters.setValue(10636, 10635);
this.mirroringShapeCharacters.setValue(10637, 10640);
this.mirroringShapeCharacters.setValue(10638, 10639);
this.mirroringShapeCharacters.setValue(10639, 10638);
this.mirroringShapeCharacters.setValue(10640, 10637);
this.mirroringShapeCharacters.setValue(10641, 10642);
this.mirroringShapeCharacters.setValue(10642, 10641);
this.mirroringShapeCharacters.setValue(10643, 10644);
this.mirroringShapeCharacters.setValue(10644, 10643);
this.mirroringShapeCharacters.setValue(10645, 10646);
this.mirroringShapeCharacters.setValue(10646, 10645);
this.mirroringShapeCharacters.setValue(10647, 10648);
this.mirroringShapeCharacters.setValue(10648, 10647);
this.mirroringShapeCharacters.setValue(10680, 8856);
this.mirroringShapeCharacters.setValue(10688, 10689);
this.mirroringShapeCharacters.setValue(10689, 10688);
this.mirroringShapeCharacters.setValue(10692, 10693);
this.mirroringShapeCharacters.setValue(10693, 10692);
this.mirroringShapeCharacters.setValue(10703, 10704);
this.mirroringShapeCharacters.setValue(10704, 10703);
this.mirroringShapeCharacters.setValue(10705, 10706);
this.mirroringShapeCharacters.setValue(10706, 10705);
this.mirroringShapeCharacters.setValue(10708, 10709);
this.mirroringShapeCharacters.setValue(10709, 10708);
this.mirroringShapeCharacters.setValue(10712, 10713);
this.mirroringShapeCharacters.setValue(10713, 10712);
this.mirroringShapeCharacters.setValue(10714, 10715);
this.mirroringShapeCharacters.setValue(10715, 10714);
this.mirroringShapeCharacters.setValue(10741, 8725);
this.mirroringShapeCharacters.setValue(10744, 10745);
this.mirroringShapeCharacters.setValue(10745, 10744);
this.mirroringShapeCharacters.setValue(10748, 10749);
this.mirroringShapeCharacters.setValue(10749, 10748);
this.mirroringShapeCharacters.setValue(10795, 10796);
this.mirroringShapeCharacters.setValue(10796, 10795);
this.mirroringShapeCharacters.setValue(10797, 10796);
this.mirroringShapeCharacters.setValue(10798, 10797);
this.mirroringShapeCharacters.setValue(10804, 10805);
this.mirroringShapeCharacters.setValue(10805, 10804);
this.mirroringShapeCharacters.setValue(10812, 10813);
this.mirroringShapeCharacters.setValue(10813, 10812);
this.mirroringShapeCharacters.setValue(10852, 10853);
this.mirroringShapeCharacters.setValue(10853, 10852);
this.mirroringShapeCharacters.setValue(10873, 10874);
this.mirroringShapeCharacters.setValue(10874, 10873);
this.mirroringShapeCharacters.setValue(10877, 10878);
this.mirroringShapeCharacters.setValue(10878, 10877);
this.mirroringShapeCharacters.setValue(10879, 10880);
this.mirroringShapeCharacters.setValue(10880, 10879);
this.mirroringShapeCharacters.setValue(10881, 10882);
this.mirroringShapeCharacters.setValue(10882, 10881);
this.mirroringShapeCharacters.setValue(10883, 10884);
this.mirroringShapeCharacters.setValue(10884, 10883);
this.mirroringShapeCharacters.setValue(10891, 10892);
this.mirroringShapeCharacters.setValue(10892, 10891);
this.mirroringShapeCharacters.setValue(10897, 10898);
this.mirroringShapeCharacters.setValue(10898, 10897);
this.mirroringShapeCharacters.setValue(10899, 10900);
this.mirroringShapeCharacters.setValue(10900, 10899);
this.mirroringShapeCharacters.setValue(10901, 10902);
this.mirroringShapeCharacters.setValue(10902, 10901);
this.mirroringShapeCharacters.setValue(10903, 10904);
this.mirroringShapeCharacters.setValue(10904, 10903);
this.mirroringShapeCharacters.setValue(10905, 10906);
this.mirroringShapeCharacters.setValue(10906, 10905);
this.mirroringShapeCharacters.setValue(10907, 10908);
this.mirroringShapeCharacters.setValue(10908, 10907);
this.mirroringShapeCharacters.setValue(10913, 10914);
this.mirroringShapeCharacters.setValue(10914, 10913);
this.mirroringShapeCharacters.setValue(10918, 10919);
this.mirroringShapeCharacters.setValue(10919, 10918);
this.mirroringShapeCharacters.setValue(10920, 10921);
this.mirroringShapeCharacters.setValue(10921, 10920);
this.mirroringShapeCharacters.setValue(10922, 10923);
this.mirroringShapeCharacters.setValue(10923, 10922);
this.mirroringShapeCharacters.setValue(10924, 10925);
this.mirroringShapeCharacters.setValue(10925, 10924);
this.mirroringShapeCharacters.setValue(10927, 10928);
this.mirroringShapeCharacters.setValue(10928, 10927);
this.mirroringShapeCharacters.setValue(10931, 10932);
this.mirroringShapeCharacters.setValue(10932, 10931);
this.mirroringShapeCharacters.setValue(10939, 10940);
this.mirroringShapeCharacters.setValue(10940, 10939);
this.mirroringShapeCharacters.setValue(10941, 10942);
this.mirroringShapeCharacters.setValue(10942, 10941);
this.mirroringShapeCharacters.setValue(10943, 10944);
this.mirroringShapeCharacters.setValue(10944, 10943);
this.mirroringShapeCharacters.setValue(10945, 10946);
this.mirroringShapeCharacters.setValue(10946, 10945);
this.mirroringShapeCharacters.setValue(10947, 10948);
this.mirroringShapeCharacters.setValue(10948, 10947);
this.mirroringShapeCharacters.setValue(10949, 10950);
this.mirroringShapeCharacters.setValue(10950, 10949);
this.mirroringShapeCharacters.setValue(10957, 10958);
this.mirroringShapeCharacters.setValue(10958, 10957);
this.mirroringShapeCharacters.setValue(10959, 10960);
this.mirroringShapeCharacters.setValue(10960, 10959);
this.mirroringShapeCharacters.setValue(10961, 10962);
this.mirroringShapeCharacters.setValue(10962, 10961);
this.mirroringShapeCharacters.setValue(10963, 10964);
this.mirroringShapeCharacters.setValue(10964, 10963);
this.mirroringShapeCharacters.setValue(10965, 10966);
this.mirroringShapeCharacters.setValue(10966, 10965);
this.mirroringShapeCharacters.setValue(10974, 8870);
this.mirroringShapeCharacters.setValue(10979, 8873);
this.mirroringShapeCharacters.setValue(10980, 8872);
this.mirroringShapeCharacters.setValue(10981, 8875);
this.mirroringShapeCharacters.setValue(10988, 10989);
this.mirroringShapeCharacters.setValue(10989, 10988);
this.mirroringShapeCharacters.setValue(10999, 11000);
this.mirroringShapeCharacters.setValue(11000, 10999);
this.mirroringShapeCharacters.setValue(11001, 11002);
this.mirroringShapeCharacters.setValue(11002, 11001);
this.mirroringShapeCharacters.setValue(12296, 12297);
this.mirroringShapeCharacters.setValue(12297, 12296);
this.mirroringShapeCharacters.setValue(12298, 12299);
this.mirroringShapeCharacters.setValue(12299, 12298);
this.mirroringShapeCharacters.setValue(12300, 12301);
this.mirroringShapeCharacters.setValue(12301, 12300);
this.mirroringShapeCharacters.setValue(12302, 12303);
this.mirroringShapeCharacters.setValue(12303, 12302);
this.mirroringShapeCharacters.setValue(12304, 12305);
this.mirroringShapeCharacters.setValue(12305, 12304);
this.mirroringShapeCharacters.setValue(12308, 12309);
this.mirroringShapeCharacters.setValue(12309, 12308);
this.mirroringShapeCharacters.setValue(12310, 12311);
this.mirroringShapeCharacters.setValue(12311, 12310);
this.mirroringShapeCharacters.setValue(12312, 12313);
this.mirroringShapeCharacters.setValue(12313, 12312);
this.mirroringShapeCharacters.setValue(12314, 12315);
this.mirroringShapeCharacters.setValue(12315, 12314);
this.mirroringShapeCharacters.setValue(65288, 65289);
this.mirroringShapeCharacters.setValue(65289, 65288);
this.mirroringShapeCharacters.setValue(65308, 65310);
this.mirroringShapeCharacters.setValue(65310, 65308);
this.mirroringShapeCharacters.setValue(65339, 65341);
this.mirroringShapeCharacters.setValue(65341, 65339);
this.mirroringShapeCharacters.setValue(65371, 65373);
this.mirroringShapeCharacters.setValue(65373, 65371);
this.mirroringShapeCharacters.setValue(65375, 65376);
this.mirroringShapeCharacters.setValue(65376, 65375);
this.mirroringShapeCharacters.setValue(65378, 65379);
this.mirroringShapeCharacters.setValue(65379, 65378);
}
//#endregion
}
export class RtlCharacters {
//#region fields
/// <summary>
/// Specifies the character types.
/// </summary>
private types : number[] = [];
/// <summary>
/// Specifies the text order (RTL or LTR).
/// </summary>
private textOrder : number = -1;
/// <summary>
/// Specifies the text length.
/// </summary>
private length : number;
/// <summary>
/// Specifies the resultant types.
/// </summary>
private result : number[];
/// <summary>
/// Specifies the resultant levels.
/// </summary>
private levels : number[];
/// <summary>
/// Specifies the RTL character types.
/// </summary>
/* tslint:disable-next-line:prefer-array-literal */
public rtlCharacterTypes : number[] = new Array(65536);
//#endregion
//#region constants
/// <summary>
/// Left-to-Right (Non-European or non-Arabic digits).
/// </summary>
private readonly L : number = 0;
/// <summary>
/// Left-to-Right Embedding
/// </summary>
private readonly LRE : number = 1;
/// <summary>
/// Left-to-Right Override
/// </summary>
private readonly LRO : number = 2;
/// <summary>
/// Right-to-Left (Hebrew alphabet, and related punctuation).
/// </summary>
private readonly R : number = 3;
/// <summary>
/// Right-to-Left Arabic
/// </summary>
private readonly AL : number = 4;
/// <summary>
/// Right-to-Left Embedding.
/// </summary>
private readonly RLE : number = 5;
/// <summary>
/// Right-to-Left Override
/// </summary>
private readonly RLO : number = 6;
/// <summary>
/// Pop Directional Format
/// </summary>
private readonly PDF : number = 7;
/// <summary>
/// European Number (European digits, Eastern Arabic-Indic digits).
/// </summary>
private readonly EN : number = 8;
/// <summary>
/// European Number Separator (Plus sign, Minus sign).
/// </summary>
private readonly ES : number = 9;
/// <summary>
/// European Number Terminator (Degree sign, currency symbols).
/// </summary>
private readonly ET : number = 10;
/// <summary>
/// Arabic Number (Arabic-Indic digits, Arabic decimal and thousands separators).
/// </summary>
private readonly AN : number = 11;
/// <summary>
/// Common Number Separator (Colon, Comma, Full Stop, No-Break Space.
/// </summary>
private readonly CS : number = 12;
/// <summary>
/// Nonspacing Mark (Characters with the General_Category values).
/// </summary>
private readonly NSM : number = 13;
/// <summary>
/// Boundary Neutral (Default ignorables, non-characters, and control characters, other than those explicitly given other types.)
/// </summary>
private readonly BN : number = 14;
/// <summary>
/// Paragraph Separator (Paragraph separator, appropriate Newline Functions, higher-level protocol paragraph determination).
/// </summary>
private readonly B : number = 15;
/// <summary>
/// Segment Separator (tab).
/// </summary>
private readonly S : number = 16;
/// <summary>
/// Whitespace (Space, Figure space, Line separator, Form feed, General Punctuation spaces).
/// </summary>
private readonly WS : number = 17;
/// <summary>
/// Other Neutrals (All other characters, including object replacement character).
/// </summary>
private readonly ON : number = 18;
/// <summary>
/// RTL character types.
/// </summary>
private readonly charTypes : number[] = [
this.L, this.EN, this.BN, this.ES, this.ES, this.S, this.ET, this.ET, this.B, this.AN, this.AN, this.S, this.CS, this.CS,
this.WS, this.NSM, this.NSM, this.B, this.BN, 27, this.BN, 28, 30, this.B, 31, 31, this.S, 32, 32, this.WS, 33, 34,
this.ON, 35, 37, this.ET, 38, 42, this.ON, 43, 43, this.ET, 44, 44, this.CS, 45, 45, this.ET, 46, 46, this.CS,
47, 47, this.CS, 48, 57, this.EN, 58, 58, this.CS, 59, 64, this.ON, 65, 90, this.L, 91, 96, this.ON, 97, 122, this.L,
123, 126, this.ON, 127, 132, this.BN, 133, 133, this.B, 134, 159, this.BN, 160, 160, this.CS,
161, 161, this.ON, 162, 165, this.ET, 166, 169, this.ON, 170, 170, this.L, 171, 175, this.ON,
176, 177, this.ET, 178, 179, this.EN, 180, 180, this.ON, 181, 181, this.L, 182, 184, this.ON,
185, 185, this.EN, 186, 186, this.L, 187, 191, this.ON, 192, 214, this.L, 215, 215, this.ON,
216, 246, this.L, 247, 247, this.ON, 248, 696, this.L, 697, 698, this.ON, 699, 705, this.L,
706, 719, this.ON, 720, 721, this.L, 722, 735, this.ON, 736, 740, this.L, 741, 749, this.ON,
750, 750, this.L, 751, 767, this.ON, 768, 855, this.NSM, 856, 860, this.L, 861, 879, this.NSM,
880, 883, this.L, 884, 885, this.ON, 886, 893, this.L, 894, 894, this.ON, 895, 899, this.L,
900, 901, this.ON, 902, 902, this.L, 903, 903, this.ON, 904, 1013, this.L, 1014, 1014, this.ON,
1015, 1154, this.L, 1155, 1158, this.NSM, 1159, 1159, this.L, 1160, 1161, this.NSM,
1162, 1417, this.L, 1418, 1418, this.ON, 1419, 1424, this.L, 1425, 1441, this.NSM,
1442, 1442, this.L, 1443, 1465, this.NSM, 1466, 1466, this.L, 1467, 1469, this.NSM,
1470, 1470, this.R, 1471, 1471, this.NSM, 1472, 1472, this.R, 1473, 1474, this.NSM,
1475, 1475, this.R, 1476, 1476, this.NSM, 1477, 1487, this.L, 1488, 1514, this.R,
1515, 1519, this.L, 1520, 1524, this.R, 1525, 1535, this.L, 1536, 1539, this.AL,
1540, 1547, this.L, 1548, 1548, this.CS, 1549, 1549, this.AL, 1550, 1551, this.ON,
1552, 1557, this.NSM, 1558, 1562, this.L, 1563, 1563, this.AL, 1564, 1566, this.L,
1567, 1567, this.AL, 1568, 1568, this.L, 1569, 1594, this.AL, 1595, 1599, this.L,
1600, 1610, this.AL, 1611, 1624, this.NSM, 1625, 1631, this.L, 1632, 1641, this.AN,
1642, 1642, this.ET, 1643, 1644, this.AN, 1645, 1647, this.AL, 1648, 1648, this.NSM,
1649, 1749, this.AL, 1750, 1756, this.NSM, 1757, 1757, this.AL, 1758, 1764, this.NSM,
1765, 1766, this.AL, 1767, 1768, this.NSM, 1769, 1769, this.ON, 1770, 1773, this.NSM,
1774, 1775, this.AL, 1776, 1785, this.EN, 1786, 1805, this.AL, 1806, 1806, this.L,
1807, 1807, this.BN, 1808, 1808, this.AL, 1809, 1809, this.NSM, 1810, 1839, this.AL,
1840, 1866, this.NSM, 1867, 1868, this.L, 1869, 1871, this.AL, 1872, 1919, this.L,
1920, 1957, this.AL, 1958, 1968, this.NSM, 1969, 1969, this.AL, 1970, 2304, this.L,
2305, 2306, this.NSM, 2307, 2363, this.L, 2364, 2364, this.NSM, 2365, 2368, this.L,
2369, 2376, this.NSM, 2377, 2380, this.L, 2381, 2381, this.NSM, 2382, 2384, this.L,
2385, 2388, this.NSM, 2389, 2401, this.L, 2402, 2403, this.NSM, 2404, 2432, this.L,
2433, 2433, this.NSM, 2434, 2491, this.L, 2492, 2492, this.NSM, 2493, 2496, this.L,
2497, 2500, this.NSM, 2501, 2508, this.L, 2509, 2509, this.NSM, 2510, 2529, this.L,
2530, 2531, this.NSM, 2532, 2545, this.L, 2546, 2547, this.ET, 2548, 2560, this.L,
2561, 2562, this.NSM, 2563, 2619, this.L, 2620, 2620, this.NSM, 2621, 2624, this.L,
2625, 2626, this.NSM, 2627, 2630, this.L, 2631, 2632, this.NSM, 2633, 2634, this.L,
2635, 2637, this.NSM, 2638, 2671, this.L, 2672, 2673, this.NSM, 2674, 2688, this.L,
2689, 2690, this.NSM, 2691, 2747, this.L, 2748, 2748, this.NSM, 2749, 2752, this.L,
2753, 2757, this.NSM, 2758, 2758, this.L, 2759, 2760, this.NSM, 2761, 2764, this.L,
2765, 2765, this.NSM, 2766, 2785, this.L, 2786, 2787, this.NSM, 2788, 2800, this.L,
2801, 2801, this.ET, 2802, 2816, this.L, 2817, 2817, this.NSM, 2818, 2875, this.L,
2876, 2876, this.NSM, 2877, 2878, this.L, 2879, 2879, this.NSM, 2880, 2880, this.L,
2881, 2883, this.NSM, 2884, 2892, this.L, 2893, 2893, this.NSM, 2894, 2901, this.L,
2902, 2902, this.NSM, 2903, 2945, this.L, 2946, 2946, this.NSM, 2947, 3007, this.L,
3008, 3008, this.NSM, 3009, 3020, this.L, 3021, 3021, this.NSM, 3022, 3058, this.L,
3059, 3064, this.ON, 3065, 3065, this.ET, 3066, 3066, this.ON, 3067, 3133, this.L,
3134, 3136, this.NSM, 3137, 3141, this.L, 3142, 3144, this.NSM, 3145, 3145, this.L,
3146, 3149, this.NSM, 3150, 3156, this.L, 3157, 3158, this.NSM, 3159, 3259, this.L,
3260, 3260, this.NSM, 3261, 3275, this.L, 3276, 3277, this.NSM, 3278, 3392, this.L,
3393, 3395, this.NSM, 3396, 3404, this.L, 3405, 3405, this.NSM, 3406, 3529, this.L,
3530, 3530, this.NSM, 3531, 3537, this.L, 3538, 3540, this.NSM, 3541, 3541, this.L,
3542, 3542, this.NSM, 3543, 3632, this.L, 3633, 3633, this.NSM, 3634, 3635, this.L,
3636, 3642, this.NSM, 3643, 3646, this.L, 3647, 3647, this.ET, 3648, 3654, this.L,
3655, 3662, this.NSM, 3663, 3760, this.L, 3761, 3761, this.NSM, 3762, 3763, this.L,
3764, 3769, this.NSM, 3770, 3770, this.L, 3771, 3772, this.NSM, 3773, 3783, this.L,
3784, 3789, this.NSM, 3790, 3863, this.L, 3864, 3865, this.NSM, 3866, 3892, this.L,
3893, 3893, this.NSM, 3894, 3894, this.L, 3895, 3895, this.NSM, 3896, 3896, this.L,
3897, 3897, this.NSM, 3898, 3901, this.ON, 3902, 3952, this.L, 3953, 3966, this.NSM,
3967, 3967, this.L, 3968, 3972, this.NSM, 3973, 3973, this.L, 3974, 3975, this.NSM,
3976, 3983, this.L, 3984, 3991, this.NSM, 3992, 3992, this.L, 3993, 4028, this.NSM,
4029, 4037, this.L, 4038, 4038, this.NSM, 4039, 4140, this.L, 4141, 4144, this.NSM,
4145, 4145, this.L, 4146, 4146, this.NSM, 4147, 4149, this.L, 4150, 4151, this.NSM,
4152, 4152, this.L, 4153, 4153, this.NSM, 4154, 4183, this.L, 4184, 4185, this.NSM,
4186, 5759, this.L, 5760, 5760, this.WS, 5761, 5786, this.L, 5787, 5788, this.ON,
5789, 5905, this.L, 5906, 5908, this.NSM, 5909, 5937, this.L, 5938, 5940, this.NSM,
5941, 5969, this.L, 5970, 5971, this.NSM, 5972, 6001, this.L, 6002, 6003, this.NSM,
6004, 6070, this.L, 6071, 6077, this.NSM, 6078, 6085, this.L, 6086, 6086, this.NSM,
6087, 6088, this.L, 6089, 6099, this.NSM, 6100, 6106, this.L, 6107, 6107, this.ET,
6108, 6108, this.L, 6109, 6109, this.NSM, 6110, 6127, this.L, 6128, 6137, this.ON,
6138, 6143, this.L, 6144, 6154, this.ON, 6155, 6157, this.NSM, 6158, 6158, this.WS,
6159, 6312, this.L, 6313, 6313, this.NSM, 6314, 6431, this.L, 6432, 6434, this.NSM,
6435, 6438, this.L, 6439, 6443, this.NSM, 6444, 6449, this.L, 6450, 6450, this.NSM,
6451, 6456, this.L, 6457, 6459, this.NSM, 6460, 6463, this.L, 6464, 6464, this.ON,
6465, 6467, this.L, 6468, 6469, this.ON, 6470, 6623, this.L, 6624, 6655, this.ON,
6656, 8124, this.L, 8125, 8125, this.ON, 8126, 8126, this.L, 8127, 8129, this.ON,
8130, 8140, this.L, 8141, 8143, this.ON, 8144, 8156, this.L, 8157, 8159, this.ON,
8160, 8172, this.L, 8173, 8175, this.ON, 8176, 8188, this.L, 8189, 8190, this.ON,
8191, 8191, this.L, 8192, 8202, this.WS, 8203, 8205, this.BN, 8206, 8206, this.L,
8207, 8207, this.R, 8208, 8231, this.ON, 8232, 8232, this.WS, 8233, 8233, this.B,
8234, 8234, this.LRE, 8235, 8235, this.RLE, 8236, 8236, this.PDF, 8237, 8237, this.LRO,
8238, 8238, this.RLO, 8239, 8239, this.WS, 8240, 8244, this.ET, 8245, 8276, this.ON,
8277, 8278, this.L, 8279, 8279, this.ON, 8280, 8286, this.L, 8287, 8287, this.WS,
8288, 8291, this.BN, 8292, 8297, this.L, 8298, 8303, this.BN, 8304, 8304, this.EN,
8305, 8307, this.L, 8308, 8313, this.EN, 8314, 8315, this.ET, 8316, 8318, this.ON,
8319, 8319, this.L, 8320, 8329, this.EN, 8330, 8331, this.ET, 8332, 8334, this.ON,
8335, 8351, this.L, 8352, 8369, this.ET, 8370, 8399, this.L, 8400, 8426, this.NSM,
8427, 8447, this.L, 8448, 8449, this.ON, 8450, 8450, this.L, 8451, 8454, this.ON,
8455, 8455, this.L, 8456, 8457, this.ON, 8458, 8467, this.L, 8468, 8468, this.ON,
8469, 8469, this.L, 8470, 8472, this.ON, 8473, 8477, this.L, 8478, 8483, this.ON,
8484, 8484, this.L, 8485, 8485, this.ON, 8486, 8486, this.L, 8487, 8487, this.ON,
8488, 8488, this.L, 8489, 8489, this.ON, 8490, 8493, this.L, 8494, 8494, this.ET,
8495, 8497, this.L, 8498, 8498, this.ON, 8499, 8505, this.L, 8506, 8507, this.ON,
8508, 8511, this.L, 8512, 8516, this.ON, 8517, 8521, this.L, 8522, 8523, this.ON,
8524, 8530, this.L, 8531, 8543, this.ON, 8544, 8591, this.L, 8592, 8721, this.ON,
8722, 8723, this.ET, 8724, 9013, this.ON, 9014, 9082, this.L, 9083, 9108, this.ON,
9109, 9109, this.L, 9110, 9168, this.ON, 9169, 9215, this.L, 9216, 9254, this.ON,
9255, 9279, this.L, 9280, 9290, this.ON, 9291, 9311, this.L, 9312, 9371, this.EN,
9372, 9449, this.L, 9450, 9450, this.EN, 9451, 9751, this.ON, 9752, 9752, this.L,
9753, 9853, this.ON, 9854, 9855, this.L, 9856, 9873, this.ON, 9874, 9887, this.L,
9888, 9889, this.ON, 9890, 9984, this.L, 9985, 9988, this.ON, 9989, 9989, this.L,
9990, 9993, this.ON, 9994, 9995, this.L, 9996, 10023, this.ON, 10024, 10024, this.L,
10025, 10059, this.ON, 10060, 10060, this.L, 10061, 10061, this.ON, 10062, 10062, this.L,
10063, 10066, this.ON, 10067, 10069, this.L, 10070, 10070, this.ON, 10071, 10071, this.L,
10072, 10078, this.ON, 10079, 10080, this.L, 10081, 10132, this.ON, 10133, 10135, this.L,
10136, 10159, this.ON, 10160, 10160, this.L, 10161, 10174, this.ON, 10175, 10191, this.L,
10192, 10219, this.ON, 10220, 10223, this.L, 10224, 11021, this.ON, 11022, 11903, this.L,
11904, 11929, this.ON, 11930, 11930, this.L, 11931, 12019, this.ON, 12020, 12031, this.L,
12032, 12245, this.ON, 12246, 12271, this.L, 12272, 12283, this.ON, 12284, 12287, this.L,
12288, 12288, this.WS, 12289, 12292, this.ON, 12293, 12295, this.L, 12296, 12320, this.ON,
12321, 12329, this.L, 12330, 12335, this.NSM, 12336, 12336, this.ON, 12337, 12341, this.L,
12342, 12343, this.ON, 12344, 12348, this.L, 12349, 12351, this.ON, 12352, 12440, this.L,
12441, 12442, this.NSM, 12443, 12444, this.ON, 12445, 12447, this.L, 12448, 12448, this.ON,
12449, 12538, this.L, 12539, 12539, this.ON, 12540, 12828, this.L, 12829, 12830, this.ON,
12831, 12879, this.L, 12880, 12895, this.ON, 12896, 12923, this.L, 12924, 12925, this.ON,
12926, 12976, this.L, 12977, 12991, this.ON, 12992, 13003, this.L, 13004, 13007, this.ON,
13008, 13174, this.L, 13175, 13178, this.ON, 13179, 13277, this.L, 13278, 13279, this.ON,
13280, 13310, this.L, 13311, 13311, this.ON, 13312, 19903, this.L, 19904, 19967, this.ON,
19968, 42127, this.L, 42128, 42182, this.ON, 42183, 64284, this.L, 64285, 64285, this.R,
64286, 64286, this.NSM, 64287, 64296, this.R, 64297, 64297, this.ET, 64298, 64310, this.R,
64311, 64311, this.L, 64312, 64316, this.R, 64317, 64317, this.L, 64318, 64318, this.R,
64319, 64319, this.L, 64320, 64321, this.R, 64322, 64322, this.L, 64323, 64324, this.R,
64325, 64325, this.L, 64326, 64335, this.R, 64336, 64433, this.AL, 64434, 64466, this.L,
64467, 64829, this.AL, 64830, 64831, this.ON, 64832, 64847, this.L, 64848, 64911, this.AL,
64912, 64913, this.L, 64914, 64967, this.AL, 64968, 65007, this.L, 65008, 65020, this.AL,
65021, 65021, this.ON, 65022, 65023, this.L, 65024, 65039, this.NSM, 65040, 65055, this.L,
65056, 65059, this.NSM, 65060, 65071, this.L, 65072, 65103, this.ON, 65104, 65104, this.CS,
65105, 65105, this.ON, 65106, 65106, this.CS, 65107, 65107, this.L, 65108, 65108, this.ON,
65109, 65109, this.CS, 65110, 65118, this.ON, 65119, 65119, this.ET, 65120, 65121, this.ON,
65122, 65123, this.ET, 65124, 65126, this.ON, 65127, 65127, this.L, 65128, 65128, this.ON,
65129, 65130, this.ET, 65131, 65131, this.ON, 65132, 65135, this.L, 65136, 65140, this.AL,
65141, 65141, this.L, 65142, 65276, this.AL, 65277, 65278, this.L, 65279, 65279, this.BN,
65280, 65280, this.L, 65281, 65282, this.ON, 65283, 65285, this.ET, 65286, 65290, this.ON,
65291, 65291, this.ET, 65292, 65292, this.CS, 65293, 65293, this.ET, 65294, 65294, this.CS,
65295, 65295, this.ES, 65296, 65305, this.EN, 65306, 65306, this.CS, 65307, 65312, this.ON,
65313, 65338, this.L, 65339, 65344, this.ON, 65345, 65370, this.L, 65371, 65381, this.ON,
65382, 65503, this.L, 65504, 65505, this.ET, 65506, 65508, this.ON, 65509, 65510, this.ET,
65511, 65511, this.L, 65512, 65518, this.ON, 65519, 65528, this.L, 65529, 65531, this.BN,
65532, 65533, this.ON, 65534, 65535, this.L];
//#endregion
//#region constructors
public constructor() {
for (let i : number = 0; i < this.charTypes.length; ++i) {
let start : number = this.charTypes[i];
let end : number = this.charTypes[++i];
let b : number = this.charTypes[++i];
while (start <= end) {
this.rtlCharacterTypes[start++] = b;
}
}
}
//#endregion
//#region implementation
public getVisualOrder( inputText : string, isRtl : boolean) : number[] {
this.types = this.getCharacterCode(inputText);
this.textOrder = isRtl ? this.LRE : this.L;
this.doVisualOrder();
let result : number[] = [];
for (let i : number = 0; i < this.levels.length; i++) {
result[i] = this.levels[i];
}
return result;
}
private getCharacterCode( text : string) : number[] {
let characterCodes : number[] = [];
for (let i : number = 0; i < text.length; i++) {
characterCodes[i] = this.rtlCharacterTypes[text[i].charCodeAt(0)];
}
return characterCodes;
}
private setDefaultLevels() : void {
for (let i : number = 0; i < this.length; i++) {
this.levels[i] = this.textOrder;
}
}
private setLevels(): void {
this.setDefaultLevels();
for (let n : number = 0; n < this.length; ++n) {
let level : number = this.levels[n];
if ((level & 0x80) !== 0) {
level &= 0x7f;
this.result[n] = ((level & 0x1) === 0) ? this.L : this.R;
}
this.levels[n] = level;
}
}
private updateLevels( index : number, level : number, length : number) : void {
if ((level & 1) === 0) {
for (let i : number = index; i < length; ++i) {
if (this.result[i] === this.R) {
this.levels[i] += 1;
} else if (this.result[i] !== this.L) {
this.levels[i] += 2;
}
}
} else {
for (let i : number = index; i < length; ++i) {
if (this.result[i] !== this.R) {
this.levels[i] += 1;
}
}
}
}
private doVisualOrder() : void {
this.length = this.types.length;
this.result = this.types;
this.levels = [];
this.setLevels();
this.length = this.getEmbeddedCharactersLength();
let preview : number = this.textOrder;
let i : number = 0;
while (i < this.length) {
let level : number = this.levels[i];
let preType : number = ((Math.max(preview, level) & 0x1) === 0) ? this.L : this.R;
let length : number = i + 1;
while (length < this.length && this.levels[length] === level) {
++length;
}
let success : number = length < this.length ? this.levels[length] : this.textOrder;
let type : number = ((Math.max(success, level) & 0x1) === 0) ? this.L : this.R;
this.checkNSM(i, length, level, preType, type);
this.updateLevels(i, level, length);
preview = level;
i = length;
}
this.checkEmbeddedCharacters(this.length);
}
private getEmbeddedCharactersLength() : number {
let index : number = 0;
for (let i : number = 0; i < this.length; ++i) {
if (!(this.types[i] === this.LRE || this.types[i] === this.RLE || this.types[i] === this.LRO ||
this.types[i] === this.RLO || this.types[i] === this.PDF || this.types[i] === this.BN)) {
this.result[index] = this.result[i];
this.levels[index] = this.levels[i];
index++;
}
}
return index;
}
private checkEmbeddedCharacters( length : number) : void {
for (let i : number = this.types.length - 1; i >= 0; --i) {
if (this.types[i] === this.LRE || this.types[i] === this.RLE || this.types[i] === this.LRO ||
this.types[i] === this.RLO || this.types[i] === this.PDF || this.types[i] === this.BN) {
this.result[i] = this.types[i];
this.levels[i] = -1;
} else {
length -= 1;
this.result[i] = this.result[length];
this.levels[i] = this.levels[length];
}
}
for (let i : number = 0; i < this.types.length; i++) {
if (this.levels[i] === -1) {
if (i === 0) {
this.levels[i] = this.textOrder;
} else {
this.levels[i] = this.levels[i - 1];
}
}
}
}
private checkNSM( index : number, length : number, level : number, startType : number, endType : number) : void {
let charType : number = startType;
for (let i : number = index; i < length; ++i) {
if (this.result[i] === this.NSM) {
this.result[i] = charType;
} else {
charType = this.result[i];
}
}
this.checkEuropeanDigits(index, length, level, startType, endType);
}
private checkEuropeanDigits( index : number, length : number, level : number, startType : number, endType : number) : void {
for (let i : number = index; i < length; ++i) {
if (this.result[i] === this.EN) {
for (let j : number = i - 1; j >= index; --j) {
if (this.result[j] === this.L || this.result[j] === this.R || this.result[j] === this.AL) {
if (this.result[j] === this.AL) {
this.result[i] = this.AN;
}
break;
}
}
}
}
this.checkArabicCharacters(index, length, level, startType, endType);
}
private checkArabicCharacters( index : number, length : number, level: number, startType : number, endType: number) : void {
for (let i : number = index; i < length; ++i) {
if (this.result[i] === this.AL) {
this.result[i] = this.R;
}
}
this.checkEuropeanNumberSeparator(index, length, level, startType, endType);
}
private checkEuropeanNumberSeparator(index : number, length : number, level : number, startType : number, endType : number) : void {
for (let i : number = index + 1; i < length - 1; ++i) {
if (this.result[i] === this.ES || this.result[i] === this.CS) {
let preview : number = this.result[i - 1];
let success : number = this.result[i + 1];
if (preview === this.EN && success === this.EN) {
this.result[i] = this.EN;
} else if (this.result[i] === this.CS && preview === this.AN && success === this.AN) {
this.result[i] = this.AN;
}
}
}
this.checkEuropeanNumberTerminator(index, length, level, startType, endType);
}
private checkEuropeanNumberTerminator( index: number, length : number, level: number, startType: number, endType: number) : void {
for (let i : number = index; i < length; ++i) {
if (this.result[i] === this.ET) {
let s : number = i;
let b : number[] = [];
b.push(this.ET);
let l : number = this.getLength(s, length, b);
let data : number = s === index ? startType : this.result[s - 1];
if (data !== this.EN) {
data = (l === length) ? endType : this.result[l];
}
if (data === this.EN) {
for (let j : number = s; j < l; ++j) {
this.result[j] = this.EN;
}
}
i = l;
}
}
this.checkOtherNeutrals(index, length, level, startType, endType);
}
private checkOtherNeutrals( index : number, length : number, level : number, startType : number, endType: number) : void {
for (let i : number = index; i < length; ++i) {
if (this.result[i] === this.ES || this.result[i] === this.ET || this.result[i] === this.CS) {
this.result[i] = this.ON;
}
}
this.checkOtherCharacters(index, length, level, startType, endType);
}
private checkOtherCharacters( index : number, length : number, level : number, startType : number, endType: number) : void {
for (let i : number = index; i < length; ++i) {
if (this.result[i] === this.EN) {
let pst : number = startType;
for (let j : number = i - 1; j >= index; --j) {
if (this.result[j] === this.L || this.result[j] === this.R) {
pst = this.result[j];
break;
}
}
if (pst === this.L) {
this.result[i] = this.L;
}
}
}
this.checkCommanCharacters(index, length, level, startType, endType);
}
private getLength( index : number, length : number, validSet : number[]) : number {
--index;
while (++index < length) {
let t : number = this.result[index];
for (let i : number = 0; i < validSet.length; ++i) {
if (t === validSet[i]) {
index = this.getLength(++index, length, validSet);
}
}
return index;
}
return length;
}
private checkCommanCharacters( index : number, length : number, level : number, startType : number, endType : number) : void {
for (let i : number = index; i < length; ++i) {
if (this.result[i] === this.WS || this.result[i] === this.ON || this.result[i] === this.B ||
this.result[i] === this.S) {
let s : number = i;
let byte : number[] = [this.B, this.S, this.WS, this.ON];
let l : number = this.getLength(s, length, byte);
let lt : number = 0;
let tt : number = 0;
let rt : number = 0;
if (s === index) {
lt = startType;
} else {
lt = this.result[s - 1];
if (lt === this.AN) {
lt = this.R;
} else if (lt === this.EN) {
lt = this.R;
}
}
if (l === length) {
tt = endType;
} else {
tt = this.result[l];
if (tt === this.AN) {
tt = this.R;
} else if (tt === this.EN) {
tt = this.R;
}
}
if (lt === tt) {
rt = lt;
} else {
rt = ((level & 0x1) === 0) ? this.L : this.R;
}
for (let j : number = s; j < l; ++j) {
this.result[j] = rt;
}
i = l;
}
}
}
//#endregion
} | the_stack |
// Documentation: http://www.numericjs.com/documentation.html
type NonNullPrimitive = number | string | boolean | undefined;
type Scalar = number;
type Vector = number[];
type VectorBoolean = boolean[];
type Matrix = number[][];
type SparseMatrix = [Vector, Vector, Vector];
type DeprecatedSparseMatrix = Array<Array<number | undefined>>;
type DeprecatedSparseVector = Array<number | undefined>;
type CCSComparisonResult = [Vector, Vector, VectorBoolean];
type ShapeFunction = (i: number, j: number) => boolean;
interface LUPP {
L: SparseMatrix;
U: SparseMatrix;
P: Vector;
Pinv: Vector;
}
interface LU {
L: Matrix;
U: Matrix;
}
type MultidimensionalArray<T> =
| T[][]
| T[][][]
| T[][][][]
| T[][][][][]
| T[][][][][][]
| T[][][][][][][]
| T[][][][][][][][]
| T[][][][][][][][][][]
| T[][][][][][][][][][][]
| T[][][][][][][][][][][][]
| T[][][][][][][][][][][][][]
| T[][][][][][][][][][][][][][]
| T[][][][][][][][][][][][][][][]
| T[][][][][][][][][][][][][][][][];
type MultidimensionalMatrix = MultidimensionalArray<number>;
type TensorValue = Scalar | Vector | MultidimensionalMatrix;
type NonScalar = Vector | MultidimensionalMatrix;
declare class Tensor {
x: TensorValue;
y?: TensorValue | undefined;
add(tensor: Tensor | TensorValue): Tensor;
sub(tensor: Tensor | TensorValue): Tensor;
mul(tensor: Tensor | TensorValue): Tensor;
// it's buggy. https://github.com/sloisel/numeric/pull/59
reciprocal(): Tensor;
div(tensor: Tensor | TensorValue): Tensor;
dot(tensor: Tensor | TensorValue): Tensor;
transpose(): Tensor;
transjugate(): Tensor;
exp(): Tensor;
conj(): Tensor;
neg(): Tensor;
sin(): Tensor;
cos(): Tensor;
abs(): Tensor;
log(): Tensor;
norm2(): Tensor;
inv(): Tensor;
get(i: Vector): Tensor;
set(i: Vector, value: Tensor): Tensor;
getRows(i0: number, i1: number): Tensor;
setRows(i0: number, i1: number, tensor: Tensor): Tensor;
getRow(k: number): Tensor;
setRow(i: number, tensor: Tensor): Tensor;
getBlock(from: Vector, to: Vector): Tensor;
setBlock(from: Vector, to: Vector, tensor: Tensor): Tensor;
rep(s: Vector, value: Tensor | TensorValue): Tensor;
diag(d: Tensor | TensorValue): Tensor;
eig(): { lambda: Tensor; E: Tensor };
identity(n: number): Tensor;
getDiag(): Tensor;
// fast fourier transforms
fft(): Tensor;
ifft(): Tensor;
}
declare class Spline {
x: Vector;
yl: Vector;
yr: Vector;
kl: Vector;
kr: Vector;
at(x0: Vector | Scalar): Vector | Scalar;
diff(): Spline;
roots(): Vector;
}
declare class Dopri {
x: Vector;
y: Vector;
f: Vector;
ymid: Vector;
iterations: number;
msg: string;
events?: boolean | VectorBoolean | undefined;
at(x: Vector): Vector | Matrix;
}
interface Numeric {
readonly epsilon: number;
largeArray: number;
precision: number;
readonly version: string;
seedrandom: {
seedrandom(seed: number | string, useEntropy?: boolean): string;
random(): number;
};
// utility functions
// Benchmarking routine
bench(func: () => any, interval?: number): number;
prettyPrint(x?: any): string;
parseDate(date: string): number;
parseDate(dates: string[]): number[];
parseFloat(input: string): number;
parseFloat(inputs: string[]): number[];
parseCSV(csv: string): string[][];
// toCSV is buggy.
// https://github.com/sloisel/numeric/pull/51
toCSV(csvArray: any[][]): string;
// Encode a matrix as an image URL
imageURL(img: number[][]): string;
getURL(url: string): any;
// linear algebra with arrays
// Get Array dimensions
dim(arr: any): Vector;
// x and y are entrywise identical
same(x: any, y: any): boolean;
// Create an Array by duplicating values
rep<T>(scale: Vector, value: T, key?: number): MultidimensionalArray<T>;
// Matrix-Matrix, Matrix-Vector, Vector-Matrix and Vector-Vector product
dot(
x: Vector | Matrix | Scalar,
y: Vector | Matrix | Scalar
): Vector | Matrix | Scalar;
dotMMsmall(x: Matrix, y: Matrix): Matrix;
dotMMbig(x: Matrix, y: Matrix): Matrix;
dotMV(x: Matrix, y: Vector): Vector;
dotVM(x: Vector, y: Matrix): Vector;
dotVV(x: Vector, y: Vector): Scalar;
// Create diagonal matrix
diag(diagonal: Vector): Matrix;
// Get the diagonal of a Matrix
getDiag(matrix: Matrix): Vector;
// Identity matrix
identity(num: number): Matrix;
// Pointwise Math.abs(x)
abs<T extends NonScalar>(x: T): T;
absV(x: Vector): Vector;
abseqV(x: Vector): Vector;
abseq<T extends NonScalar>(x: T): T;
// Pointwise arc-cosine
acos<T extends NonScalar>(x: T): T;
acosV(x: Vector): Vector;
acoseqV(x: Vector): Vector;
acoseq<T extends NonScalar>(x: T): T;
// Pointwise arc-sine
asin<T extends NonScalar>(x: T): T;
asinV(x: Vector): Vector;
asineqV(x: Vector): Vector;
asineq<T extends NonScalar>(x: T): T;
// Pointwise arc-tangent
atan<T extends NonScalar>(x: T): T;
atanV(x: Vector): Vector;
ataneqV(x: Vector): Vector;
ataneq<T extends NonScalar>(x: T): T;
// Pointwise Math.ceil(x)
ceil<T extends NonScalar>(x: T): T;
ceilV(x: Vector): Vector;
ceileqV(x: Vector): Vector;
ceileq<T extends NonScalar>(x: T): T;
// Pointwise Math.cos(x)
cos<T extends NonScalar>(x: T): T;
cosV(x: Vector): Vector;
coseqV(x: Vector): Vector;
coseq<T extends NonScalar>(x: T): T;
// Pointwise Math.exp(x)
exp<T extends NonScalar>(x: T): T;
expV(x: Vector): Vector;
expeqV(x: Vector): Vector;
expeq<T extends NonScalar>(x: T): T;
// Poinwise Math.floor(x)
floor<T extends NonScalar>(x: T): T;
floorV(x: Vector): Vector;
flooreqV(x: Vector): Vector;
flooreq<T extends NonScalar>(x: T): T;
// Pointwise Math.log(x)
log<T extends NonScalar>(x: T): T;
logV(x: Vector): Vector;
logeqV(x: Vector): Vector;
logeq<T extends NonScalar>(x: T): T;
// Pointwise Math.round(x)
round<T extends NonScalar>(x: T): T;
roundV(x: Vector): Vector;
roundeqV(x: Vector): Vector;
roundeq<T extends NonScalar>(x: T): T;
// Pointwise Math.sin(x)
sin<T extends NonScalar>(x: T): T;
sinV(x: Vector): Vector;
sineqV(x: Vector): Vector;
sineq<T extends NonScalar>(x: T): T;
// Pointwise Math.sqrt(x)
sqrt<T extends NonScalar>(x: T): T;
sqrtV(x: Vector): Vector;
sqrteqV(x: Vector): Vector;
sqrteq<T extends NonScalar>(x: T): T;
// Pointwise tangent
tan<T extends NonScalar>(x: T): T;
tanV(x: Vector): Vector;
taneqV(x: Vector): Vector;
taneq<T extends NonScalar>(x: T): T;
// Pointwise Number.isNan(x)
isNaN(x: Vector): VectorBoolean;
isNaN(x: MultidimensionalMatrix): MultidimensionalArray<boolean>;
isNaNV(x: Vector): VectorBoolean;
isNaNeqV(x: Vector): VectorBoolean;
isNaNeq(x: Vector): VectorBoolean;
isNaNeq(x: MultidimensionalMatrix): MultidimensionalArray<boolean>;
// Pointwise Number.isFinite(x)
isFinite(x: Vector): VectorBoolean;
isFinite(x: MultidimensionalMatrix): MultidimensionalArray<boolean>;
isFiniteV(x: Vector): VectorBoolean;
isFiniteeqV(x: Vector): VectorBoolean;
isFiniteeq(x: Vector): VectorBoolean;
isFiniteeq(x: MultidimensionalMatrix): MultidimensionalArray<boolean>;
// Pointwise -x
neg<T extends TensorValue>(x: T): T;
negV(x: Vector): Vector;
negeq<T extends TensorValue>(x: T): T;
negeqV(x: Vector): Vector;
// Pointwise logical negation !x
not(x: NonNullPrimitive): boolean;
not(x: NonNullPrimitive[]): VectorBoolean;
not(
x: MultidimensionalArray<NonNullPrimitive>
): MultidimensionalArray<boolean>;
notV(x: NonNullPrimitive[]): VectorBoolean;
noteq(x: NonNullPrimitive): boolean;
noteq(x: NonNullPrimitive[]): VectorBoolean;
noteq(
x: MultidimensionalArray<NonNullPrimitive>
): MultidimensionalArray<boolean>;
noteqV(x: NonNullPrimitive[]): VectorBoolean;
// Pointwise binary negation ~x
bnot<T extends TensorValue>(x: T): T;
bnotV(x: Vector): Vector;
bnoteq<T extends TensorValue>(x: T): T;
bnoteqV(x: Vector): Vector;
// Deep copy of Array
clone<
T extends NonNullPrimitive[] | MultidimensionalArray<NonNullPrimitive>
>(
x: T
): T;
cloneV(x: NonNullPrimitive[]): NonNullPrimitive[];
cloneeq(x: NonNullPrimitive[]): NonNullPrimitive[];
cloneeq<
T extends NonNullPrimitive[] | MultidimensionalArray<NonNullPrimitive>
>(
x: T
): T;
cloneeqV(x: NonNullPrimitive[]): NonNullPrimitive[];
// Pointwise sum x+y
add(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
add(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
add<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<T | Scalar>
): T;
"+"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"+"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"+"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
addVV(x: Vector, y: Vector): Vector;
addSV(x: Scalar, y: Vector): Vector;
addVS(x: Vector, y: Scalar): Vector;
addeq(x: Vector, y: Vector | Scalar): Vector;
addeqV(x: Vector, y: Vector): Vector;
addeqS(x: Vector, y: Scalar): Vector;
// Pointwise x-y
sub(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
sub(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
sub<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
"-"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"-"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"-"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
subVV(x: Vector, y: Vector): Vector;
subSV(x: Scalar, y: Vector): Vector;
subVS(x: Vector, y: Scalar): Vector;
subeq(x: Vector, y: Vector | Scalar): Vector;
subeqV(x: Vector, y: Vector): Vector;
subeqS(x: Vector, y: Scalar): Vector;
// Pointwise x*y
mul(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
mul(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
mul<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
"*"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"*"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"*"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
mulVV(x: Vector, y: Vector): Vector;
mulSV(x: Scalar, y: Vector): Vector;
mulVS(x: Vector, y: Scalar): Vector;
muleq(x: Vector, y: Vector | Scalar): Vector;
muleqV(x: Vector, y: Vector): Vector;
muleqS(x: Vector, y: Scalar): Vector;
// Pointwise x/y
div(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
div(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
div<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
"/"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"/"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"/"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
divVV(x: Vector, y: Vector): Vector;
divSV(x: Scalar, y: Vector): Vector;
divVS(x: Vector, y: Scalar): Vector;
diveq(x: Vector, y: Vector | Scalar): Vector;
diveqV(x: Vector, y: Vector): Vector;
diveqS(x: Vector, y: Scalar): Vector;
// Pointwise x%y
mod(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
mod(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
mod<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
"%"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"%"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"%"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
modVV(x: Vector, y: Vector): Vector;
modSV(x: Scalar, y: Vector): Vector;
modVS(x: Vector, y: Scalar): Vector;
modeq(x: Vector, y: Vector | Scalar): Vector;
modeqV(x: Vector, y: Vector): Vector;
modeqS(x: Vector, y: Scalar): Vector;
// Pointwise x && y
and(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
and(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
and<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
"&&"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"&&"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"&&"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
andVV(x: Vector, y: Vector): Vector;
andSV(x: Scalar, y: Vector): Vector;
andVS(x: Vector, y: Scalar): Vector;
andeq(x: Vector, y: Vector | Scalar): Vector;
andeqV(x: Vector, y: Vector): Vector;
andeqS(x: Vector, y: Scalar): Vector;
// Pointwise logical or x||y
or(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
or(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
or<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
"||"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"||"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"||"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
orVV(x: Vector, y: Vector): Vector;
orSV(x: Scalar, y: Vector): Vector;
orVS(x: Vector, y: Scalar): Vector;
oreq(x: Vector, y: Vector | Scalar): Vector;
oreqV(x: Vector, y: Vector): Vector;
oreqS(x: Vector, y: Scalar): Vector;
// Pointwise comparison x === y
eq(x: Scalar, y: Scalar): boolean;
eq(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
eq(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
"==="(x: Scalar, y: Scalar, ...args: Scalar[]): boolean;
"==="(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
"==="(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
eqVV(x: Vector, y: Vector): VectorBoolean;
eqSV(x: Scalar, y: Vector): VectorBoolean;
eqVS(x: Vector, y: Scalar): VectorBoolean;
eqeq(x: Vector, y: Vector | Scalar): VectorBoolean;
eqeqV(x: Vector, y: Vector): VectorBoolean;
eqeqS(x: Vector, y: Scalar): VectorBoolean;
// Pointwise x!==y
neq(x: Scalar, y: Scalar): boolean;
neq(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
neq(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
"!=="(x: Scalar, y: Scalar, ...args: Scalar[]): boolean;
"!=="(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
"!=="(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
neqVV(x: Vector, y: Vector): VectorBoolean;
neqSV(x: Scalar, y: Vector): VectorBoolean;
neqVS(x: Vector, y: Scalar): VectorBoolean;
neqeq(x: Vector, y: Vector | Scalar): VectorBoolean;
neqeqV(x: Vector, y: Vector): VectorBoolean;
neqeqS(x: Vector, y: Scalar): VectorBoolean;
// Pointwise x<y
lt(x: Scalar, y: Scalar): boolean;
lt(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
lt(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
"<"(x: Scalar, y: Scalar, ...args: Scalar[]): boolean;
"<"(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
"<"(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
ltVV(x: Vector, y: Vector): VectorBoolean;
ltSV(x: Scalar, y: Vector): VectorBoolean;
ltVS(x: Vector, y: Scalar): VectorBoolean;
lteq(x: Vector, y: Vector | Scalar): VectorBoolean;
lteqV(x: Vector, y: Vector): VectorBoolean;
lteqS(x: Vector, y: Scalar): VectorBoolean;
// Pointwise x>y
gt(x: Scalar, y: Scalar): boolean;
gt(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
gt(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
">"(x: Scalar, y: Scalar, ...args: Scalar[]): boolean;
">"(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
">"(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
gtVV(x: Vector, y: Vector): VectorBoolean;
gtSV(x: Scalar, y: Vector): VectorBoolean;
gtVS(x: Vector, y: Scalar): VectorBoolean;
gteq(x: Vector, y: Vector | Scalar): VectorBoolean;
gteqV(x: Vector, y: Vector): VectorBoolean;
gteqS(x: Vector, y: Scalar): VectorBoolean;
// Pointwise x<=y
leq(x: Scalar, y: Scalar): boolean;
leq(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
leq(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
"<="(x: Scalar, y: Scalar, ...args: Scalar[]): boolean;
"<="(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
"<="(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
leqVV(x: Vector, y: Vector): VectorBoolean;
leqSV(x: Scalar, y: Vector): VectorBoolean;
leqVS(x: Vector, y: Scalar): VectorBoolean;
leqeq(x: Vector, y: Vector | Scalar): VectorBoolean;
leqeqV(x: Vector, y: Vector): VectorBoolean;
leqeqS(x: Vector, y: Scalar): VectorBoolean;
// Pointwise x>=y
geq(x: Scalar, y: Scalar): boolean;
geq(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
geq(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
">="(x: Scalar, y: Scalar, ...args: Scalar[]): boolean;
">="(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean;
">="(
x: MultidimensionalMatrix,
y: MultidimensionalMatrix
): MultidimensionalArray<boolean>;
geqVV(x: Vector, y: Vector): VectorBoolean;
geqSV(x: Scalar, y: Vector): VectorBoolean;
geqVS(x: Vector, y: Scalar): VectorBoolean;
geqeq(x: Vector, y: Vector | Scalar): VectorBoolean;
geqeqV(x: Vector, y: Vector): VectorBoolean;
geqeqS(x: Vector, y: Scalar): VectorBoolean;
// Pointwise x & y
band(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
band(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
band<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
"&"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"&"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"&"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
bandVV(x: Vector, y: Vector): Vector;
bandSV(x: Scalar, y: Vector): Vector;
bandVS(x: Vector, y: Scalar): Vector;
bandeq(x: Vector, y: Vector | Scalar): Vector;
bandeqV(x: Vector, y: Vector): Vector;
bandeqS(x: Vector, y: Scalar): Vector;
// Pointwise binary or x|y
bor(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
bor(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
bor<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
"|"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"|"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"|"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
borVV(x: Vector, y: Vector): Vector;
borSV(x: Scalar, y: Vector): Vector;
borVS(x: Vector, y: Scalar): Vector;
boreq(x: Vector, y: Vector | Scalar): Vector;
boreqV(x: Vector, y: Vector): Vector;
boreqS(x: Vector, y: Scalar): Vector;
// Pointwise binary xor x^y
bxor(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
bxor(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
bxor<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
"^"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"^"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"^"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
bxorVV(x: Vector, y: Vector): Vector;
bxorSV(x: Scalar, y: Vector): Vector;
bxorVS(x: Vector, y: Scalar): Vector;
bxoreq(x: Vector, y: Vector | Scalar): Vector;
bxoreqV(x: Vector, y: Vector): Vector;
bxoreqS(x: Vector, y: Scalar): Vector;
// Pointwise x<<y
lshift(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
lshift(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
lshift<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<T | Scalar>
): T;
"<<"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
"<<"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
"<<"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
lshiftVV(x: Vector, y: Vector): Vector;
lshiftSV(x: Scalar, y: Vector): Vector;
lshiftVS(x: Vector, y: Scalar): Vector;
lshifteq(x: Vector, y: Vector | Scalar): Vector;
lshifteqV(x: Vector, y: Vector): Vector;
lshifteqS(x: Vector, y: Scalar): Vector;
// Pointwise x>>y
rshift(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
rshift(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
rshift<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<T | Scalar>
): T;
">>"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
">>"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
">>"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
rshiftVV(x: Vector, y: Vector): Vector;
rshiftSV(x: Scalar, y: Vector): Vector;
rshiftVS(x: Vector, y: Scalar): Vector;
rshifteq(x: Vector, y: Vector | Scalar): Vector;
rshifteqV(x: Vector, y: Vector): Vector;
rshifteqS(x: Vector, y: Scalar): Vector;
// Pointwise x>>>y
rrshift(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
rrshift(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
rrshift<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<T | Scalar>
): T;
">>>"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
">>>"(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
">>>"<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<T | Scalar>
): T;
rrshiftVV(x: Vector, y: Vector): Vector;
rrshiftSV(x: Scalar, y: Vector): Vector;
rrshiftVS(x: Vector, y: Scalar): Vector;
rrshifteq(x: Vector, y: Vector | Scalar): Vector;
rrshifteqV(x: Vector, y: Vector): Vector;
rrshifteqS(x: Vector, y: Scalar): Vector;
// Pointwise arc-tangent (two parameters)
atan2(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
atan2(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
atan2<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<T | Scalar>
): T;
atan2VV(x: Vector, y: Vector): Vector;
atan2SV(x: Scalar, y: Vector): Vector;
atan2VS(x: Vector, y: Scalar): Vector;
atan2eq(x: Vector, y: Vector | Scalar): Vector;
atan2eqV(x: Vector, y: Vector): Vector;
atan2eqS(x: Vector, y: Scalar): Vector;
// Pointwise x**y
pow(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
pow(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
pow<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
powVV(x: Vector, y: Vector): Vector;
powSV(x: Scalar, y: Vector): Vector;
powVS(x: Vector, y: Scalar): Vector;
poweq(x: Vector, y: Vector | Scalar): Vector;
poweqV(x: Vector, y: Vector): Vector;
poweqS(x: Vector, y: Scalar): Vector;
// Pointwise max(x,y)
max(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
max(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
max<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
maxVV(x: Vector, y: Vector): Vector;
maxSV(x: Scalar, y: Vector): Vector;
maxVS(x: Vector, y: Scalar): Vector;
maxeq(x: Vector, y: Vector | Scalar): Vector;
maxeqV(x: Vector, y: Vector): Vector;
maxeqS(x: Vector, y: Scalar): Vector;
// Pointwise min(x,y)
min(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar;
min(
x: Scalar | Vector,
y: Scalar | Vector,
...args: Array<Scalar | Vector>
): Vector;
min<T extends MultidimensionalMatrix>(
x: T,
y: T | Scalar,
...args: Array<Scalar | T>
): T;
minVV(x: Vector, y: Vector): Vector;
minSV(x: Scalar, y: Vector): Vector;
minVS(x: Vector, y: Scalar): Vector;
mineq(x: Vector, y: Vector | Scalar): Vector;
mineqV(x: Vector, y: Vector): Vector;
mineqS(x: Vector, y: Scalar): Vector;
// One or more of the components of x are true
any(x: any): boolean;
anyV(x: any[]): boolean;
// All the components of x are true
all(x: any): boolean;
allV(x: any[]): boolean;
// Sum all the entries of x
sum(x: Scalar | Vector | MultidimensionalMatrix): number;
sumV(x: Vector): number;
// Product of all the entries of x
prod(x: Scalar | Vector | MultidimensionalMatrix): number;
prodV(x: Vector): number;
// Sum of squares of entries of x
norm2Squared(x: Scalar | Vector | MultidimensionalMatrix): number;
norm2SquaredV(x: Vector): number;
// Largest modulus entry of x
norminf(x: Scalar | Vector | MultidimensionalMatrix): number;
norminfV(x: Vector): number;
// Sum all absolute values of entries
norm1(x: Scalar | Vector | MultidimensionalMatrix): number;
norm1V(x: Vector): number;
// Largest value of entries (not modulus)
sup(x: Scalar | Vector | MultidimensionalMatrix): number;
supV(x: Vector): number;
// Smallest value of entries (not modulus)
inf(x: Scalar | Vector | MultidimensionalMatrix): number;
infV(x: Vector): number;
// Round the values of entries
truncVV(x: Vector, y: Vector): Vector;
truncVS(x: Vector, y: number): Vector;
truncSV(x: number, y: Vector): Vector;
trunc(x: number | Vector, y: number | Vector): Vector;
// Matrix inverse
inv(x: Matrix): Matrix;
// Determinant
det(x: Matrix): number;
// Matrix transpose
transpose(x: Matrix): Matrix;
// Negate matrix and transpose
negtranspose(x: Matrix): Matrix;
// Create an Array of random numbers
random(s: Vector): Vector | MultidimensionalMatrix;
// Square root of the sum of the square of the entries of x
norm2(x: Scalar | Vector | MultidimensionalMatrix): number;
// Generate evenly spaced values
linspace(from: number, to: number, numberOfValues?: number): Vector;
// Extract a block from a matrix
getBlock<T extends MultidimensionalMatrix>(
x: T,
from: Vector,
to: Vector
): T;
// Set a block of a matrix
setBlock<T extends MultidimensionalMatrix>(
x: T,
from: Vector,
to: Vector,
b: T
): T;
// create two-dimensional matrix
blockMatrix(x: Scalar | Vector | MultidimensionalMatrix): Matrix;
// x * y
tensor(x: Scalar, y: Scalar): Scalar;
// TensorValue product ret[i][j] = x[i]*y[j]
tensor(x: Vector, y: Vector): Matrix;
// return instance of Tensor class. X — real value, y — imaginary part.
t(x: TensorValue, y?: TensorValue): Tensor;
// Eigenvalues of real matrices
house(x: Vector): Vector;
toUpperHessenberg(matrix: Matrix): { H: Matrix; Q: Matrix };
QRFrancis(x: Matrix, maxiter?: number): { Q: Matrix; B: Matrix };
eig(A: Matrix, maxiter?: number): { lambda: Tensor; E: Tensor };
// Compressed Column Storage matrices
ccsSparse(matrix: Matrix): SparseMatrix;
ccsFull(matrix: SparseMatrix): Matrix;
ccsTSolve(
matrix: SparseMatrix,
b: Vector,
x?: Vector,
bj?: Vector,
xj?: Vector
): Vector;
ccsDot(A: SparseMatrix, B: SparseMatrix): SparseMatrix;
ccsLUP(matrix: SparseMatrix, threshold?: number): LUPP;
ccsDim(matrix: SparseMatrix): Vector;
ccsGetBlock(
matrix: SparseMatrix,
i?: Vector | Scalar,
j?: Vector | Scalar
): SparseMatrix;
ccsLUPSolve(lup: LUPP, B: SparseMatrix): Vector;
ccsScatter(matrix: SparseMatrix): SparseMatrix;
ccsGather(matrix: SparseMatrix): SparseMatrix;
ccsadd(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsadd(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsaddMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccssub(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccssub(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccssubMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsmul(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsmul(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsmulMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsdiv(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsdiv(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsdivMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsmod(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsmod(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsmodMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsand(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsand(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsandMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsor(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsor(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsorMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccseq(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult;
ccseq(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccseqMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccsneq(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult;
ccsneq(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccsneqMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccslt(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult;
ccslt(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccsltMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccsgt(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult;
ccsgt(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccsgtMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccsleq(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult;
ccsleq(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccsleqMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccsgeq(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult;
ccsgeq(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccsgeqMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult;
ccsband(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsband(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsbandMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsbor(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsbor(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsborMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsbxor(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsbxor(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsbxorMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccslshift(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccslshift(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccslshiftMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsrshift(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsrshift(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsrshiftMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsrrshift(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix;
ccsrrshift(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix;
ccsrrshiftMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix;
/** @deprecated */
sdim(matrix: any, ret?: Vector, k?: number): Vector;
/** @deprecated */
sclone<T>(matrix: T, k?: number, n?: number): T;
/** @deprecated */
sdiag(d: Vector): DeprecatedSparseMatrix;
/** @deprecated */
sidentity(n: Scalar): DeprecatedSparseMatrix;
/** @deprecated */
stranspose(matrix: DeprecatedSparseMatrix): DeprecatedSparseMatrix;
/** @deprecated */
sdotMM(
a: DeprecatedSparseMatrix,
b: DeprecatedSparseMatrix
): DeprecatedSparseMatrix;
/** @deprecated */
sdotMV(
matrix: DeprecatedSparseMatrix,
vector: DeprecatedSparseVector
): DeprecatedSparseVector;
/** @deprecated */
sdotVM(
vector: DeprecatedSparseVector,
matrix: DeprecatedSparseMatrix
): DeprecatedSparseMatrix;
/** @deprecated */
sdotVV(x: DeprecatedSparseVector, y: DeprecatedSparseVector): number;
/** @deprecated */
sdot(
x: Scalar | DeprecatedSparseVector | DeprecatedSparseMatrix,
y: Scalar | DeprecatedSparseVector | DeprecatedSparseMatrix
): Scalar | DeprecatedSparseVector | DeprecatedSparseMatrix;
/** @deprecated */
sscatter(matrix: DeprecatedSparseMatrix): DeprecatedSparseMatrix;
/** @deprecated */
sgather(
matrix: DeprecatedSparseMatrix,
ret?: DeprecatedSparseVector,
k?: DeprecatedSparseVector
): DeprecatedSparseMatrix;
// Coordinate matrices
cLU(matrix: Matrix): LU;
cLUSolve(lu: LU, b: Vector): Vector;
cgrid(n: number | [number, number], shape?: "L" | ShapeFunction): Matrix;
cdelsq(g: Matrix): Matrix;
cdotmv(matrix: Matrix, x: Vector): Vector;
// Splines
spline(
x: Vector,
y: Vector | Matrix,
k1?: "periodic" | Scalar,
kn?: "periodic" | Scalar
): Spline;
// Unconstrained optimisations
uncmin(
f: (x: Vector) => Scalar,
x0: Vector,
tol?: number,
gradient?: any,
maxit?: number,
callback?: (
it: number,
x0: Vector,
f0: Scalar,
g0: Vector,
h1: Matrix
) => any,
options?: { Hinv: Matrix }
): {
solution: Vector;
f: Scalar;
gradient: Vector;
invHessian: Matrix;
iterations: number;
message: string;
};
gradient(f: (x: Vector) => Scalar, x: Vector): Vector;
// Ode solver (Dormand-Prince)
dopri(
x0: Scalar,
x1: Scalar,
y0: Scalar,
f: (x: Vector | Scalar, y: Vector | Scalar) => Vector | Scalar,
tol?: number,
maxit?: number,
event?: (x: Vector | Scalar, y: Vector | Scalar) => Vector | Scalar
): Dopri;
// Solving the linear problem Ax=b
solve(matrix: Matrix, vector: Vector): Vector;
LU(matrix: Matrix, fast?: boolean): { LU: Matrix; P: Vector };
LUsolve(lup: { LU: Matrix; P: Vector }, vector: Vector): Vector;
// Linear programming
echelonize(matrix: Matrix): { I: Matrix; A: Matrix; P: Vector };
solveLP(
c: Vector,
A: Matrix,
b: Vector,
Aeq?: Matrix,
beq?: Matrix,
tol?: number,
maxit?: number
): { solution: Scalar | Vector; message: string; iterations: number };
solveQP(
Dmat: Matrix,
dvec: Vector,
Amat: Matrix,
bvec: Vector,
meq?: number,
factorized?: any
): {
solution: Vector;
value: Vector;
unconstrained_solution: Vector;
iterations: Vector;
iact: Vector;
message: string;
};
svd(matrix: Matrix): { U: Matrix; S: Vector; V: Matrix };
}
declare const numeric: Numeric;
export = numeric; | the_stack |
import React from "react";
import { Component } from "@react-fullstack/fullstack";
import WindowInterface, {
WindowState as LocalWindowState,
} from "@web-desktop-environment/interfaces/lib/views/Window";
import { withStyles, createStyles, WithStyles } from "@material-ui/styles";
import { Theme } from "@web-desktop-environment/interfaces/lib/shared/settings";
import ReactDOM from "react-dom";
import windowManager from "@state/WindowManager";
import { windowsBarHeight as desktopWindowsBarHeight } from "@views/Desktop";
import Icon from "@components/icon";
import { Rnd, RndDragCallback, RndResizeCallback } from "react-rnd";
import { ConnectionContext } from "@root/contexts";
import { lastTaskQueuer } from "@utils/tasks";
import { isMobile } from "@utils/environment";
export const defaultWindowSize = {
height: 600,
width: 700,
maxHeight: 700,
maxWidth: 1000,
minHeight: 300,
minWidth: 400,
};
// for now windows will not support hot reloading from mobile mode to regular mode
const constantIsMobile = isMobile();
export const windowBarHeight = constantIsMobile ? 35 : 25;
const styles = (theme: Theme) =>
createStyles({
root: {
width: "100%",
height: "100%",
animation: "$startAnimationDesktop 500ms",
},
rootY: {
width: "100%",
height: "100%",
},
"@media (max-width: 768px)": {
root: {
animation: "$startAnimationMobileTranslation 500ms ease-out",
},
rootY: {
animation: "$startAnimationMobileScale 500ms ease-out",
},
"@keyframes startAnimationMobileTranslation": {
"0%": {
transform: "translate(-100%, 0)",
},
"100%": {
transform: "translate(0, 0)",
},
},
"@keyframes startAnimationMobileScale": {
"0%": {
transform: "scale(1)",
},
"50%": {
transform: "scale(0.6)",
},
"100%": {
transform: "scale(1)",
},
},
},
rootUnmounted: {
animation: "$endAnimationMobileTransform 450ms ease-in reverse",
opacity: 0,
},
rootYUnmounted: {
animation: "$endAnimationMobileScale 450ms ease-in",
},
"@keyframes endAnimationMobileTransform": {
"0%": {
transform: "translate(100%, 0)",
opacity: 1,
},
"100%": {
transform: "translate(0, 0)",
opacity: 1,
},
},
"@keyframes endAnimationMobileScale": {
"0%": {
transform: "scale(1)",
},
"50%": {
transform: "scale(0.6)",
},
"100%": {
transform: "scale(1)",
},
},
"@keyframes startAnimationDesktop": {
from: {
transform: "translate(-100%, 100%) scale(0.2)",
},
to: {
transform: "translate(0, 0) scale(1)",
},
},
bar: {
background: theme.windowBarColor,
backdropFilter: theme.type === "transparent" ? "blur(15px)" : "none",
border: theme.windowBorder
? `1px solid ${theme.windowBorderColor}`
: "none",
borderBottom: "none",
borderRadius: "7px 7px 0 0",
cursor: "move",
display: "flex",
flexDirection: "row-reverse",
height: windowBarHeight,
width: "100%",
justifyContent: "space-between",
},
smoothMove: {
transition: "top 305ms, left 305ms",
},
barCollapse: {
borderRadius: "7px 7px 7px 7px",
borderBottom: `1px solid ${theme.windowBorderColor}`,
},
body: {
borderRadius: "0 0 3px 3px",
width: "100%",
height: `calc(100% - ${windowBarHeight}px)`,
},
barButtonsContainer: {
position: "relative",
top: constantIsMobile ? (windowBarHeight - 20) / 2 : 4,
right: constantIsMobile ? 10 : 5,
width: constantIsMobile ? 25 : 40,
height: 20,
display: "flex",
justifyContent: "space-between",
},
barButton: {
width: constantIsMobile ? 20 : 15,
height: constantIsMobile ? 20 : 15,
borderRadius: "50%",
zIndex: 2,
border: "1px solid #0004",
},
barButtonExit: {
cursor: "pointer",
background: theme.error.main,
"&:hover": {
background: theme.error.dark,
},
},
barButtonCollapse: {
cursor: "pointer",
background: theme.success.main,
"&:hover": {
background: theme.success.dark,
},
},
barButtonInactive: {
background: theme.primary.transparent,
},
barTitle: {
position: "relative",
top: constantIsMobile ? 6 : 2,
fontSize: constantIsMobile ? 17 : 14,
left: 45,
width: "100%",
textAlign: "center",
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
maxWidth: constantIsMobile ? "calc(100% - 75px)" : "calc(100% - 90px)",
userSelect: "none",
color: theme.background.text,
},
barTitleIcon: {
position: "relative",
top: 3,
},
});
type WindowSnap = "fullscreen" | "right" | "left";
interface WindowState {
canDrag: boolean;
collapse: boolean;
mountAnimationDone: boolean;
isActive?: boolean;
localWindowState?: LocalWindowState;
useLocalWindowState: boolean;
isResizing: boolean;
zIndex?: number;
snap?: WindowSnap;
}
export const MountAnimationContext = React.createContext(false);
class Window extends Component<
WindowInterface,
WindowState,
WithStyles<typeof styles>
> {
domContainer: Element;
id!: number;
wrapperRef?: HTMLDivElement;
constructor(props: Window["props"]) {
super(props);
this.state = {
canDrag: false,
mountAnimationDone: false,
collapse: props.window.minimized || false,
useLocalWindowState: false,
isResizing: false,
};
this.domContainer = document.createElement("div");
document.getElementById("app")?.appendChild(this.domContainer);
}
static contextType = ConnectionContext;
context!: React.ContextType<typeof ConnectionContext>;
percentageToNumber = (size: number | string, from: number) => {
if (typeof size === "number") {
return size;
}
return (100 / Number(size.replace("%", ""))) * from;
};
screenSizesToNumbers = () => {
const { maxHeight, maxWidth, minHeight, minWidth } = this.props.window;
return {
maxHeight: this.percentageToNumber(
maxHeight || defaultWindowSize.maxHeight,
window.innerHeight
),
minHeight: this.percentageToNumber(
minHeight || defaultWindowSize.minHeight,
window.innerHeight
),
maxWidth: this.percentageToNumber(
maxWidth || defaultWindowSize.maxWidth,
window.innerWidth
),
minWidth: this.percentageToNumber(
minWidth || defaultWindowSize.minWidth,
window.innerWidth
),
};
};
getSize = () => {
const size = { ...(this.windowProperties.size || {}) };
const { collapse } = this.state;
const {
maxHeight,
maxWidth,
minHeight,
minWidth,
} = this.screenSizesToNumbers();
if (size.height && size.width) {
if (maxHeight < size.height) {
size.height = maxHeight;
}
if (minHeight > size.height) {
size.height = minHeight;
}
if (maxWidth < size.width) {
size.width = maxWidth;
}
if (minWidth > size.width) {
size.width = minWidth;
}
if (collapse) {
size.height = windowBarHeight;
}
return size as { width: number; height: number };
} else {
return {
width: defaultWindowSize.width,
height: collapse ? windowBarHeight : defaultWindowSize.height,
};
}
};
getPosition = () => {
const size = this.getSize();
const { position } = this.windowProperties;
const { useLocalWindowState } = this.state;
if (position && size) {
if (position.x < 0) {
if (!useLocalWindowState) {
position.x = -position.x;
} else {
position.x = 0;
}
}
if (position.x > window.innerWidth - size.width) {
if (!useLocalWindowState) {
position.x =
window.innerWidth -
size.width -
((window.innerWidth - size.width) % position.x);
} else {
position.x = window.innerWidth - size.width;
}
}
if (
position.y >
window.innerHeight - desktopWindowsBarHeight - windowBarHeight
) {
position.y =
window.innerHeight - desktopWindowsBarHeight - windowBarHeight;
}
if (position.y < 0) {
position.y = 0;
}
return position;
} else {
return {
x: window.screen.availWidth / 3,
y: window.screen.availHeight / 3,
};
}
};
private willUnmount = false;
componentDidMount() {
this.updateWindowPositionORSizeQueuer.start();
windowManager.emitter.on("minimizeWindow", ({ id }) => {
this.props.setWindowState({
minimized: true,
});
if (id === this.id) {
this.setState({ collapse: true, isActive: true });
} else this.setState({ isActive: false });
});
windowManager.emitter.on("maximizeWindow", ({ id }) => {
this.props.setWindowState({
minimized: false,
});
if (id === this.id) {
this.setState({ collapse: false, isActive: true });
} else this.setState({ isActive: false });
});
windowManager.emitter.on("setActiveWindow", ({ id }) => {
if (id === this.id) {
this.setState({ isActive: true });
} else {
this.setState({ isActive: false });
}
});
windowManager.emitter.on("updateZIndex", ({ id, layer }) => {
if (id === this.id) {
this.setState({ zIndex: layer });
}
});
document.addEventListener("mousedown", (e) => {
if (this.wrapperRef && e.target) {
if (
this.wrapperRef &&
!this.wrapperRef.contains(e.target as HTMLElement)
) {
this.handleClickOutside();
}
}
});
this.id = windowManager.addWindow(
this.props.name,
this.props.icon,
this.props.color,
{
minimized: this.props.window.minimized || false,
}
);
windowManager.reloadWindowsLayers();
const switchPosition = () => {
if (!this.willUnmount) {
this.switchToAbsolutePosition();
window.requestAnimationFrame(switchPosition);
}
};
switchPosition();
this.setActive();
}
componentWillUnmount = () => {
this.willUnmount = true;
windowManager.closeWindow(this.id);
};
handleClickOutside = () => {
this.setState({ isActive: false });
};
setActive = () => {
if (windowManager.activeWindowId === this.id) {
this.setState({ isActive: true });
} else {
windowManager.setActiveWindow(this.id);
}
};
get serverWindowProperties() {
return {
size:
this.props.window.width && this.props.window.height
? {
width: this.props.window.width,
height: this.props.window.height,
}
: undefined,
position: this.props.window.position,
};
}
get windowProperties() {
if (this.state.useLocalWindowState) {
return this.state.localWindowState || this.serverWindowProperties;
} else {
return this.serverWindowProperties;
}
}
updateWindowPositionORSizeQueuer = lastTaskQueuer();
/**
* update window size or position locally on remotely
*/
setWindowState(state: LocalWindowState) {
this.setState({
localWindowState: { ...this.state.localWindowState, ...state },
});
this.updateWindowPositionORSizeQueuer.queueTask(() =>
this.props.setWindowState(state)
);
}
snapWindow = (snap?: WindowSnap | undefined, forceState?: boolean) => {
const {
props: {
window: { allowLocalScreenSnapping },
},
state: { snap: currentSnap, collapse },
} = this;
if (!collapse) {
if (allowLocalScreenSnapping) {
const snapNow = forceState !== undefined ? forceState : !currentSnap;
this.setState({ snap: snapNow ? snap : undefined });
}
}
};
/**
* static constance window properties to use when we are in fullscreen mode
*/
static fullscreenWindowPosition = { x: 0, y: 0 };
/*
* we are removing the translation base position and replace it with an absolute position using top and left
* css properties in the render we need to avoid using translation base position since it is causing blurriness in iframes
*/
switchToAbsolutePosition = () => {
const rndElement = document.getElementsByClassName(
this.randomClassNameForRndContainer
)[0] as HTMLDivElement;
rndElement.style.transform = "";
const newStyles = this.getWindowTransformStyles();
Object.keys(newStyles).map((keyNameAsString) => {
const key = keyNameAsString as keyof typeof newStyles;
const value = newStyles[key];
if (typeof value === "number") {
rndElement.style[key] = `${value}px`;
} else if (typeof value === "string") {
rndElement.style[key] = value;
}
});
};
randomClassNameForRndContainer = `rndElement${Math.random()}`;
getWindowTransformStyles = () => {
const position = this.getWindowPosition();
const size = this.getWindowSize();
return {
top: position?.y || 0,
left: position?.x || 0,
height: size?.height,
width: size?.width,
};
};
onDrag: RndDragCallback = (e, newPosition) => {
this.setActive();
const { isResizing } = this.state;
if (isResizing) {
return;
}
const position = this.getPosition();
const size = this.getSize();
const { clientX, clientY } = e as MouseEvent;
const updatedPosition = {
x: position.x + newPosition.deltaX,
y: position.y + newPosition.deltaY,
};
// snap window drag to mouse
if (updatedPosition.x > clientX) {
updatedPosition.x = clientX;
}
if (updatedPosition.x < clientX - size.width) {
updatedPosition.x = clientX - size.width;
}
if (updatedPosition.y > clientY - windowBarHeight) {
updatedPosition.y = clientY - windowBarHeight;
}
if (updatedPosition.y < clientY) {
updatedPosition.y = clientY - windowBarHeight / 2;
}
// calculate if the window is touching one of the screen borders
const touchTop = clientY < 2; // need to go a bit over the edge to go fullscreen
const farFromTop = clientY > 50;
const touchMinimumLeft = clientX < 25;
const farFromMinimumLeft = clientX > 50;
const touchMinimumRight = clientX > window.innerWidth - 25;
const farFromMinimumRight = clientX < window.innerWidth - 50;
// in case the window touches one of the screen edges snap to it
if (touchTop) {
this.snapWindow("fullscreen", true);
return;
}
if (touchMinimumLeft) {
this.snapWindow("left", true);
return;
}
if (touchMinimumRight) {
this.snapWindow("right", true);
return;
}
if (farFromMinimumLeft && farFromMinimumRight && farFromTop) {
this.snapWindow(undefined, false);
}
this.setWindowState({
position: updatedPosition,
});
};
onResize: RndResizeCallback = (e, dir, ele, delta) => {
const position = this.getPosition();
const { localWindowState, collapse } = this.state;
if (localWindowState?.size) {
const { size } = localWindowState;
const {
maxHeight,
maxWidth,
minHeight,
minWidth,
} = this.screenSizesToNumbers();
const newSize = {
width: size.width + delta.width - this.lastResizeDelta.width,
height: size.height + delta.height - this.lastResizeDelta.height,
};
if (collapse) {
newSize.height -= delta.height - this.lastResizeDelta.height;
}
switch (dir) {
case "topRight":
case "top": {
if (newSize.height < maxHeight && newSize.height > minHeight) {
position.y -= delta.height - this.lastResizeDelta.height;
}
break;
}
case "bottomLeft":
case "left": {
if (newSize.width < maxWidth && newSize.width > minWidth) {
position.x -= delta.width - this.lastResizeDelta.width;
}
break;
}
case "topLeft": {
if (newSize.height < maxHeight && newSize.height > minHeight) {
position.y -= delta.height - this.lastResizeDelta.height;
}
if (newSize.width < maxWidth && newSize.width > minWidth) {
position.x -= delta.width - this.lastResizeDelta.width;
}
break;
}
}
this.setWindowState({
size: newSize,
position: {
...position,
},
});
this.lastResizeDelta = delta;
}
};
getWindowSize = () => {
const size = this.getSize();
const { snap } = this.state;
if (!snap && !isMobile()) {
return size;
// mobile is always fullscreen
} else if (snap === "fullscreen" || isMobile()) {
return {
width: "100%",
height: `calc(100% - ${
desktopWindowsBarHeight + 10 /* add 5 to account for margin */
}px)`,
};
} else if (snap === "left" || snap === "right") {
return {
width: "50%",
height: `calc(100% - ${
desktopWindowsBarHeight + 10 /* add 5 to account for margin */
}px)`,
};
}
};
getWindowPosition = () => {
const position = this.getPosition();
const { snap } = this.state;
if (!snap && !isMobile()) {
return position;
// mobile is always fullscreen
} else if (snap === "fullscreen" || snap === "left" || isMobile()) {
return {
x: 0,
y: 0,
};
} else if (snap === "right") {
return {
x: window.innerWidth / 2,
y: 0,
};
}
};
shouldCollapse = () => {
const { collapse, snap, useLocalWindowState, isResizing } = this.state;
return (
(collapse || (useLocalWindowState && !snap && !isResizing)) && !isMobile()
);
};
lastResizeDelta = { width: 0, height: 0 };
render() {
const {
canDrag,
collapse,
isActive,
zIndex,
snap,
useLocalWindowState,
mountAnimationDone,
} = this.state;
const { children, classes, title, icon, onClose } = this.props;
const size = this.getSize();
const position = this.getPosition();
const onMobile = isMobile();
const isCurrentWindow = windowManager.activeWindowId === this.id;
return ReactDOM.createPortal(
<div
ref={(element) => {
if (element) this.wrapperRef = element;
}}
>
<Rnd
className={`${this.randomClassNameForRndContainer} ${
useLocalWindowState ? "" : classes.smoothMove
}`}
disableDragging={!canDrag}
size={this.getWindowSize()}
position={this.getWindowPosition()}
onDrag={!onMobile ? this.onDrag : undefined}
onDragStart={(e) => {
if (onMobile) {
return;
}
if (snap) {
const { clientX, clientY } = e as MouseEvent;
this.setState({
useLocalWindowState: true,
localWindowState: {
position: {
x: clientX - size.width / 2,
y: clientY + windowBarHeight / 2,
},
size,
},
snap: undefined,
});
} else {
this.setState({
useLocalWindowState: true,
localWindowState: {
position,
size,
},
});
}
}}
onDragStop={() => {
if (onMobile) {
return;
}
this.updateWindowPositionORSizeQueuer.idle().then(() =>
this.setState({
useLocalWindowState: false,
localWindowState: undefined,
})
);
}}
defaultSize={size}
onResizeStart={() => {
if (onMobile) {
return;
}
this.setState({
useLocalWindowState: true,
localWindowState: {
position,
size: size,
},
snap: undefined,
isResizing: true,
});
}}
onResizeStop={() => {
if (onMobile) {
return;
}
this.lastResizeDelta = { height: 0, width: 0 };
this.setState(
{
isResizing: false,
},
() =>
this.updateWindowPositionORSizeQueuer.idle().then(() => {
this.setState({
useLocalWindowState: false,
localWindowState: undefined,
});
})
);
}}
onResize={this.onResize}
style={{ zIndex, ...this.getWindowTransformStyles() }}
>
<div
className={`${classes.root} ${
(!isCurrentWindow || collapse) &&
onMobile &&
classes.rootUnmounted
}`}
onAnimationEnd={() => this.setState({ mountAnimationDone: true })}
onClick={() => this.setActive()}
>
<div
className={`${classes.rootY} ${
(!isCurrentWindow || collapse) &&
onMobile &&
classes.rootYUnmounted
}`}
>
<div
onMouseEnter={() => this.setState({ canDrag: true })}
onMouseLeave={() => this.setState({ canDrag: false })}
onDoubleClick={() => this.snapWindow("fullscreen")}
className={`${classes.bar} ${
this.shouldCollapse() ? classes.barCollapse : ""
}`}
>
<div className={classes.barButtonsContainer}>
{!onMobile && (
<div
onClick={() => {
windowManager.updateState(this.id, {
minimized: !collapse,
});
}}
onMouseDown={(e) => e.stopPropagation()}
className={`${classes.barButton} ${
isActive
? classes.barButtonCollapse
: classes.barButtonInactive
}`}
/>
)}
<div
className={`${classes.barButton} ${
isActive
? classes.barButtonExit
: classes.barButtonInactive
}`}
onMouseDown={(e) => e.stopPropagation()}
onClick={() => {
onClose();
}}
/>
</div>
<div className={classes.barTitle}>
{title} -{" "}
{icon.type === "icon" ? (
<Icon
containerClassName={classes.barTitleIcon}
name={icon.icon}
/>
) : (
<img
className={classes.barTitleIcon}
alt="windows icon"
width={14}
height={14}
/>
)}
</div>
</div>
<div
className={classes.body}
style={this.shouldCollapse() ? { display: "none" } : {}}
>
<MountAnimationContext.Provider value={mountAnimationDone}>
{children}
</MountAnimationContext.Provider>
</div>
</div>
</div>
</Rnd>
</div>,
this.domContainer
);
}
}
export default withStyles(styles, { withTheme: true, name: "Window" })(Window); | the_stack |
import { expect } from 'chai';
import * as fs from 'fs';
import { withData } from 'leche';
import 'mocha';
import { TableDetectionModule } from '../server/src/processing/TableDetectionModule/TableDetectionModule';
import { Table } from '../server/src/types/DocumentRepresentation';
import { getDocFromJson, runModules, TableExtractorStub } from './helpers';
const assetsDir = __dirname + '/assets/';
describe('Table Reconstruction Module', () => {
describe('horizontal cell merge', () => {
withData(
{
'table with no joined cells': [
'table-very-simple-output.json',
[
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
],
],
'only one cell merge': [
'table-one-cell-merged.json',
[
[2, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
],
],
'two different merges in same row': [
'table-two-different-merges-in-same-row.json',
[
[2, 1, 1, 2],
[1, 2, 2, 1],
[1, 1, 1, 1, 1, 1],
],
],
'two different consecutive merges in same row': [
'table-two-different-consecutive-merges-in-same-row.json',
[
[2, 2, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 2, 2, 1],
],
],
'multiple colspan merge in multiple rows': [
'table-multiple-colspan-merge.json',
[[4, 1, 1], [1, 3, 2], [6]],
],
},
(fileName, cellInfo) => {
let table: Table;
before(done => {
const camelotOutput = fs.readFileSync(assetsDir + fileName, { encoding: 'utf8' });
const tableExtractor = new TableExtractorStub(0, '', camelotOutput);
const tableDetectionModule = new TableDetectionModule();
tableDetectionModule.setExtractor(tableExtractor);
getDocFromJson(
doc => runModules(doc, [tableDetectionModule]),
'table-reconstruction.json',
'test-table-reconstruction.pdf',
).then(after => {
table = after.getElementsOfType<Table>(Table)[0];
done();
});
});
it(`should have correctly merged cells`, () => {
cellInfo.forEach((row, rowIndex) => {
row.forEach((colspan, colIndex) => {
expect(table.content[rowIndex].content[colIndex].colspan).to.equal(colspan);
});
});
});
it(`row should have correct amount of cells`, () => {
cellInfo.forEach((row, rowIndex) => {
expect(table.content[rowIndex].content.length).to.equal(row.length);
});
});
},
);
});
describe('table markdown validation', () => {
withData({
'row_span.pdf': [
'camelot-row_span.json',
'row_span.json',
'row_span.pdf',
[
'| Plan Type | County | Plan Name | Totals |',
'|---|---|---|---|',
'| GMC | Sacramento | Anthem Blue Cross | 164,380 |',
'|^|^| Health Net | 126,547 |',
'|^|^| Kaiser Foundation | 74,620 |',
'|^|^| Molina Healthcare | 59,989 |',
'|^| San Diego | Care 1st Health Plan | 71,831 |',
'|^|^| Community Health Group | 264,639 |',
'|^|^| Health Net | 72,404 |',
'|^|^| Kaiser | 50,415 |',
'|^|^| Molina Healthcare | 206,430 |',
'|^| Total GMC Enrollment |<| 1,091,255 |',
'| COHS | Marin | Partnership Health Plan of CA | 36,006 |',
'|^| Mendocino |^| 37,243 |',
'|^| Napa |^| 28,398 |',
'|^| Solano |^| 113,220 |',
'|^| Sonoma |^| 112,271 |',
'|^| Yolo |^| 52,674 |',
'|^| Del Norte |^| 11,242 |',
'|^| Humboldt |^| 49,911 |',
'|^| Lake |^| 29,149 |',
'|^| Lassen |^| 7,360 |',
'|^| Modoc |^| 2,940 |',
'|^| Shasta |^| 61,763 |',
'|^| Siskiyou |^| 16,715 |',
'|^| Trinity |^| 4,542 |',
'|^| Merced | Central California Alliance for Health | 123,907 |',
'|^| Monterey |^| 147,397 |',
'|^| Santa Cruz |^| 69,458 |',
'|^| Santa Barbara | CenCal | 117,609 |',
'|^| San Luis Obispo |^| 55,761 |',
'|^| Orange | CalOptima | 783,079 |',
'|^| San Mateo | Health Plan of San Mateo | 113,202 |',
'|^| Ventura | Gold Coast Health Plan | 202,217 |',
'|^| Total COHS Enrollment |<| 2,176,064 |',
'| Subtotal for Two-Plan, Regional Model, GMC and COHS |<|<| 10,132,022 |',
'| PCCM | Los Angeles | AIDS Healthcare Foundation | 828 |',
'|^| San Francisco | Family Mosaic | 25 |',
'|^| Total PHP Enrollment |<| 853 |',
'| All Models Total Enrollments |<|<| 10,132,875 |',
'| Source: Data Warehouse 12/14/15 |<|<|<|',
],
],
'column_span_1.pdf': [
'camelot-column_span_1.json',
'column_span_1.json',
'column_span_1.pdf',
[
'| Sl. No. | Year | Population (in Lakh) | Accidental Deaths |<| Suicides |<| Percentage Population growth |',
'|---|---|---|---|---|---|---|---|',
'|^|^|^| Incidence | Rate | Incidence | Rate |^|',
'| (1) | (2) | (3) | (4) | (5) | (6) | (7) | (8) |',
'| 1. | 1967 | 4999 | 126762 | 25.4 | 38829 | 7.8 | 2.2 |',
'| 2. | 1968 | 5111 | 126232 | 24.7 | 40688 | 8.0 | 2.2 |',
'| 3. | 1969 | 5225 | 130755 | 25.0 | 43633 | 8.4 | 2.2 |',
'| 4. | 1970 | 5343 | 139752 | 26.2 | 48428 | 9.1 | 2.3 |',
'| 5. | 1971 | 5512 | 105601 | 19.2 | 43675 | 7.9 | 3.2 |',
'| 6. | 1972 | 5635 | 106184 | 18.8 | 43601 | 7.7 | 2.2 |',
'| 7. | 1973 | 5759 | 130654 | 22.7 | 40807 | 7.1 | 2.2 |',
'| 8. | 1974 | 5883 | 110624 | 18.8 | 46008 | 7.8 | 2.2 |',
'| 9. | 1975 | 6008 | 113016 | 18.8 | 42890 | 7.1 | 2.1 |',
'| 10. | 1976 | 6136 | 111611 | 18.2 | 41415 | 6.7 | 2.1 |',
'| 11. | 1977 | 6258 | 117338 | 18.8 | 39718 | 6.3 | 2.0 |',
'| 12. | 1978 | 6384 | 118594 | 18.6 | 40207 | 6.3 | 2.0 |',
'| 13. | 1979 | 6510 | 108987 | 16.7 | 38217 | 5.9 | 2.0 |',
'| 14. | 1980 | 6636 | 116912 | 17.6 | 41663 | 6.3 | 1.9 |',
'| 15. | 1981 | 6840 | 122221 | 17.9 | 40245 | 5.9 | 3.1 |',
'| 16. | 1982 | 7052 | 125993 | 17.9 | 44732 | 6.3 | 3.1 |',
'| 17. | 1983 | 7204 | 128576 | 17.8 | 46579 | 6.5 | 2.2 |',
'| 18. | 1984 | 7356 | 134628 | 18.3 | 50571 | 6.9 | 2.1 |',
'| 19. | 1985 | 7509 | 139657 | 18.6 | 52811 | 7.0 | 2.1 |',
'| 20. | 1986 | 7661 | 147023 | 19.2 | 54357 | 7.1 | 2.0 |',
'| 21. | 1987 | 7814 | 152314 | 19.5 | 58568 | 7.5 | 2.0 |',
'| 22. | 1988 | 7966 | 163522 | 20.5 | 64270 | 8.1 | 1.9 |',
'| 23. | 1989 | 8118 | 169066 | 20.8 | 68744 | 8.5 | 1.9 |',
'| 24. | 1990 | 8270 | 174401 | 21.1 | 73911 | 8.9 | 1.9 |',
'| 25. | 1991 | 8496 | 188003 | 22.1 | 78450 | 9.2 | 2.7 |',
'| 26. | 1992 | 8677 | 194910 | 22.5 | 80149 | 9.2 | 2.1 |',
'| 27. | 1993 | 8838 | 192357 | 21.8 | 84244 | 9.5 | 1.9 |',
'| 28. | 1994 | 8997 | 190435 | 21.2 | 89195 | 9.9 | 1.8 |',
'| 29. | 1995 | 9160 | 222487 | 24.3 | 89178 | 9.7 | 1.8 |',
'| 30. | 1996 | 9319 | 220094 | 23.6 | 88241 | 9.5 | 1.7 |',
'| 31. | 1997 | 9552 | 233903 | 24.5 | 95829 | 10.0 | 2.5 |',
'| 32. | 1998 | 9709 | 258409 | 26.6 | 104713 | 10.8 | 1.6 |',
'| 33. | 1999 | 9866 | 271918 | 27.6 | 110587 | 11.2 | 1.6 |',
'| 34. | 2000 | 10021 | 255883 | 25.5 | 108593 | 10.8 | 1.6 |',
'| 35. | 2001 | 10270 | 271019 | 26.4 | 108506 | 10.6 | 2.5 |',
'| 36. | 2002 | 10506 | 260122 | 24.8 | 110417 | 10.5 | 2.3 |',
'| 37. | 2003 | 10682 | 259625 | 24.3 | 110851 | 10.4 | 1.7 |',
'| 38. | 2004 | 10856 | 277263 | 25.5 | 113697 | 10.5 | 1.6 |',
'| 39. | 2005 | 11028 | 294175 | 26.7 | 113914 | 10.3 | 1.6 |',
'| 40. | 2006 | 11198 | 314704 | 28.1 | 118112 | 10.5 | 1.5 |',
'| 41. | 2007 | 11366 | 340794 | 30.0 | 122637 | 10.8 | 1.5 |',
'| 42. | 2008 | 11531 | 342309 | 29.7 | 125017 | 10.8 | 1.4 |',
'| 43. | 2009 | 11694 | 357021 | 30.5 | 127151 | 10.9 | 1.4 |',
'| 44. | 2010 | 11858 | 384649 | 32.4 | 134599 | 11.4 | 1.4 |',
'| 45. | 2011 | 12102 | 390884 | 32.3 | 135585 | 11.2 | 2.1 |',
'| 46. | 2012 | 12134 | 394982 | 32.6 | 135445 | 11.2 | 1.0 |',
'| 47. | 2013 | 12288 | 400517 | 32.6 | 134799 | 11.0 | 1.0 |',
],
],
'column_span_2.pdf': [
'camelot-column_span_2.json',
'column_span_2.json',
'column_span_2.pdf',
[
'| Investigations | No. of HHs | Age/Sex/ Physiological Group | Preva- lence | C.I\\* | Relative Precision | Sample size per State |',
'|---|---|---|---|---|---|---|',
'| Anthropometry | 2400 | All the available individuals |<|<|<|<|',
'| Clinical Examination |^|^|<|<|<|<|',
'| History of morbidity |^|^|<|<|<|<|',
'| Diet survey | 1200 | All the individuals partaking meals in the HH |<|<|<|<|',
'| Blood Pressure \\# | 2400 | Men (≥ 18yrs) | 10% | 95% | 20% | 1728 |',
'|^|^| Women (≥ 18 yrs) |^|^|^| 1728 |',
'| Fasting blood glucose | 2400 | Men (≥ 18 yrs) | 5% | 95% | 20% | 1825 |',
'|^|^| Women (≥ 18 yrs) |^|^|^| 1825 |',
'| Knowledge & Practices on HTN & DM | 2400 | Men (≥ 18 yrs) | - | - | - | 1728 |',
'|^| 2400 | Women (≥ 18 yrs) | - | - | - | 1728 |',
],
],
'sncfTicket.pdf': [
'camelot-sncfTicket.json',
'sncfTicket.json',
'sncfTicket.pdf',
[
'| Departure / Arrival | Date / Time | TGV LYRIA | STANDARD 1st Class - Ticket can be exchanged and refunded before departure subject to a fee of € 30 per person and per journey and subject to the fare applicable on that day. Tickets will not be exchangeable or refundable after departure. More spacious seats, Electrical socket. RIn-seat restaurant service (subject to charge). CARRIERS 1185 1187 |',
'|---|---|---|---|',
'| VALLORBE | 25/09 at 19:01 | TRAIN NUMBER 9272 COACH 11 - SEAT 035 1\. CLASS DUAL SIDE BY SIDE |^|',
'| PARIS GARE LYON | 25/09 at 22:03 |^|^|',
],
],
},
(camelotJson, parsrJson, pdfFile, expectedMarkdownRows) => {
let table: Table;
before(done => {
const camelotOutput = fs.readFileSync(assetsDir + camelotJson, { encoding: 'utf8' });
const tableExtractor = new TableExtractorStub(0, '', camelotOutput);
const tableDetectionModule = new TableDetectionModule();
tableDetectionModule.setExtractor(tableExtractor);
getDocFromJson(
doc => runModules(doc, [tableDetectionModule]),
parsrJson,
pdfFile,
).then(after => {
table = after.getElementsOfType<Table>(Table)[0];
done();
});
});
it('should export expected markdown', () => {
const md = table.toMarkdown();
md.split('\n').forEach((row, i) => {
if (row) {
expect(row.trim()).to.eq(expectedMarkdownRows[i].trim());
}
});
});
});
});
}); | the_stack |
import { expect, assert } from 'chai';
import * as lexer from '../../../compiler/lexical-analysis/lexer';
import * as lexical from '../../../compiler/lexical-analysis/lexical';
import * as parser from '../../../compiler/lexical-analysis/parser';
const tests = [
`true`,
`1`,
`1.2e3`,
`!true`,
`null`,
`$.foo.bar`,
`self.foo.bar`,
`super.foo.bar`,
`super[1]`,
`error "Error!"`,
`"world"`,
`'world'`,
"|||\
\n world\
\n|||",
`foo(bar)`,
`foo(bar=99)`,
`foo(bar) tailstrict`,
`foo.bar`,
`foo[bar]`,
`true || false`,
`0 && 1 || 0`,
`0 && (1 || 0)`,
`local foo = "bar"; foo`,
`local foo(bar) = bar; foo(1)`,
`local foo(bar=4) = bar; foo(1)`,
`{ local foo = "bar", baz: 1}`,
`{ local foo(bar) = bar, baz: foo(1)}`,
`{ local foo(bar=[1]) = bar, baz: foo(1)}`,
`{ foo(bar, baz): bar+baz }`,
`{ foo(bar={a:1}):: bar }`,
`{ ["foo" + "bar"]: 3 }`,
`{ ["field" + x]: x for x in [1, 2, 3] }`,
`{ local y = x, ["field" + x]: x for x in [1, 2, 3] }`,
`{ ["field" + x]: x for x in [1, 2, 3] if x <= 2 }`,
`{ ["field" + x + y]: x + y for x in [1, 2, 3] if x <= 2 for y in [4, 5, 6]}`,
`[]`,
`[a, b, c]`,
`[x for x in [1,2,3] ]`,
`[x for x in [1,2,3] if x <= 2]`,
`[x+y for x in [1,2,3] if x <= 2 for y in [4, 5, 6]]`,
`{}`,
`{ hello: "world" }`,
`{ hello +: "world" }`,
"{\
\n hello: \"world\",\
\n \"name\":: joe,\
\n 'mood'::: \"happy\",\
\n |||\
\n key type\
\n|||: \"block\",\
\n}",
`assert true: 'woah!'; true`,
`{ assert true: 'woah!', foo: bar }`,
`if n > 1 then 'foos' else 'foo'`,
`local foo = function(x) x + 1; true`,
`import 'foo.jsonnet'`,
`importstr 'foo.text'`,
`{a: b} + {c: d}`,
`{a: b}{c: d}`,
]
describe("Successfully parsing text", () => {
for (let s of tests) {
it(`${JSON.stringify(s)}`, () => {
const tokens = lexer.Lex("test", s);
if (lexical.isStaticError(tokens)) {
throw new Error(`Unexpected lexer to emit tokens\n input: ${s}`);
}
const parse = parser.Parse(<lexer.Tokens>tokens);
if (lexical.isStaticError(parse)) {
throw new Error(
`Unexpected parse error\n input: ${s}\n error: ${parse.Error()}`);
}
});
}
});
interface testError {
readonly input: string
readonly err: string
}
const makeTestError = (input: string, err: string): testError => {
return <testError>{
input: input,
err: err,
};
}
const errorTests: testError[] = [
makeTestError(`function(a, b c)`, `test:1:15-16 Expected a comma before next function parameter.`),
makeTestError(`function(a, 1)`, `test:1:13-14 Expected simple identifier but got a complex expression.`),
makeTestError(`a b`, `test:1:3-4 Did not expect: (IDENTIFIER, "b")`),
makeTestError(`foo(a, bar(a b))`, `test:1:14-15 Expected a comma before next function argument.`),
makeTestError(`local`, `test:1:6 Expected token IDENTIFIER but got end of file`),
makeTestError(`local foo = 1, foo = 2; true`, `test:1:16-19 Duplicate local var: foo`),
makeTestError(`local foo(a b) = a; true`, `test:1:13-14 Expected a comma before next function parameter.`),
makeTestError(`local foo(a): a; true`, `test:1:13-14 Expected operator = but got ":"`),
makeTestError(`local foo(a) = bar(a b); true`, `test:1:22-23 Expected a comma before next function argument.`),
makeTestError(`local foo: 1; true`, `test:1:10-11 Expected operator = but got ":"`),
makeTestError(`local foo = bar(a b); true`, `test:1:19-20 Expected a comma before next function argument.`),
makeTestError(`{a b}`, `test:1:4-5 Expected token OPERATOR but got (IDENTIFIER, "b")`),
makeTestError(`{a = b}`, `test:1:4-5 Expected one of :, ::, :::, +:, +::, +:::, got: =`),
makeTestError(`{a :::: b}`, `test:1:4-8 Expected one of :, ::, :::, +:, +::, +:::, got: ::::`),
makeTestError(`{assert x for x in [1, 2, 3]}`, `test:1:11-14 Object comprehension cannot have asserts.`),
makeTestError(`{['foo' + x]: true, [x]: x for x in [1, 2, 3]}`, `test:1:28-31 Object comprehension can only have one field.`),
makeTestError(`{foo: x for x in [1, 2, 3]}`, `test:1:9-12 Object comprehensions can only have [e] fields.`),
makeTestError(`{[x]:: true for x in [1, 2, 3]}`, `test:1:13-16 Object comprehensions cannot have hidden fields.`),
makeTestError(`{[x]: true for 1 in [1, 2, 3]}`, `test:1:16-17 Expected token IDENTIFIER but got (NUMBER, "1")`),
makeTestError(`{[x]: true for x at [1, 2, 3]}`, `test:1:18-20 Expected token in but got (IDENTIFIER, "at")`),
makeTestError(`{[x]: true for x in [1, 2 3]}`, `test:1:27-28 Expected a comma before next array element.`),
makeTestError(`{[x]: true for x in [1, 2, 3] if (a b)}`, `test:1:37-38 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`{[x]: true for x in [1, 2, 3] if a b}`, `test:1:36-37 Expected for, if or "}" after for clause, got: (IDENTIFIER, "b")`),
makeTestError(`{a: b c:d}`, `test:1:7-8 Expected a comma before next field.`),
makeTestError(`{[(x y)]: z}`, `test:1:6-7 Expected token ")" but got (IDENTIFIER, "y")`),
makeTestError(`{[x y]: z}`, `test:1:5-6 Expected token "]" but got (IDENTIFIER, "y")`),
makeTestError(`{foo(x y): z}`, `test:1:8-9 Expected a comma before next method parameter.`),
makeTestError(`{foo(x)+: z}`, `test:1:2-5 Cannot use +: syntax sugar in a method: foo`),
makeTestError(`{foo: 1, foo: 2}`, `test:1:10-13 Duplicate field: foo`),
makeTestError(`{foo: (1 2)}`, `test:1:10-11 Expected token ")" but got (NUMBER, "2")`),
makeTestError(`{local 1 = 3, true}`, `test:1:8-9 Expected token IDENTIFIER but got (NUMBER, "1")`),
makeTestError(`{local foo = 1, local foo = 2, true}`, `test:1:23-26 Duplicate local var: foo`),
makeTestError(`{local foo(a b) = 1, a: true}`, `test:1:14-15 Expected a comma before next function parameter.`),
makeTestError(`{local foo(a): 1, a: true}`, `test:1:14-15 Expected operator = but got ":"`),
makeTestError(`{local foo(a) = (a b), a: true}`, `test:1:20-21 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`{assert (a b), a: true}`, `test:1:12-13 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`{assert a: (a b), a: true}`, `test:1:15-16 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`{function(a, b) a+b: true}`, `test:1:2-10 Unexpected: (function, "function") while parsing field definition`),
makeTestError(`[(a b), 2, 3]`, `test:1:5-6 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`[1, (a b), 2, 3]`, `test:1:8-9 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`[a for b in [1 2 3]]`, `test:1:16-17 Expected a comma before next array element.`),
makeTestError(`for`, `test:1:1-4 Unexpected: (for, "for") while parsing terminal`),
makeTestError(``, `test:1:1 Unexpected end of file.`),
makeTestError(`((a b))`, `test:1:5-6 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`a.1`, `test:1:3-4 Expected token IDENTIFIER but got (NUMBER, "1")`),
makeTestError(`super.1`, `test:1:7-8 Expected token IDENTIFIER but got (NUMBER, "1")`),
makeTestError(`super[(a b)]`, `test:1:10-11 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`super[a b]`, `test:1:9-10 Expected token "]" but got (IDENTIFIER, "b")`),
makeTestError(`super`, `test:1:1-6 Expected . or [ after super.`),
makeTestError(`assert (a b); true`, `test:1:11-12 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`assert a: (a b); true`, `test:1:14-15 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`assert a: 'foo', true`, `test:1:16-17 Expected token ";" but got (",", ",")`),
makeTestError(`assert a: 'foo'; (a b)`, `test:1:21-22 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`error (a b)`, `test:1:10-11 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`if (a b) then c`, `test:1:7-8 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`if a b c`, `test:1:6-7 Expected token then but got (IDENTIFIER, "b")`),
makeTestError(`if a then (b c)`, `test:1:14-15 Expected token ")" but got (IDENTIFIER, "c")`),
makeTestError(`if a then b else (c d)`, `test:1:21-22 Expected token ")" but got (IDENTIFIER, "d")`),
makeTestError(`function(a) (a b)`, `test:1:16-17 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`function a a`, `test:1:10-11 Expected ( but got (IDENTIFIER, "a")`),
makeTestError(`import (a b)`, `test:1:11-12 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`import (a+b)`, `test:1:9-12 Computed imports are not allowed`),
makeTestError(`importstr (a b)`, `test:1:14-15 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`importstr (a+b)`, `test:1:12-15 Computed imports are not allowed`),
makeTestError(`local a = b ()`, `test:1:15 Expected , or ; but got end of file`),
makeTestError(`local a = b; (a b)`, `test:1:17-18 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`1+ <<`, `test:1:4-6 Not a unary operator: <<`),
makeTestError(`-(a b)`, `test:1:5-6 Expected token ")" but got (IDENTIFIER, "b")`),
makeTestError(`1~2`, `test:1:2-3 Not a binary operator: ~`),
makeTestError(`a[(b c)]`, `test:1:6-7 Expected token ")" but got (IDENTIFIER, "c")`),
makeTestError(`a[b c]`, `test:1:5-6 Expected token "]" but got (IDENTIFIER, "c")`),
makeTestError(`a{b c}`, `test:1:5-6 Expected token OPERATOR but got (IDENTIFIER, "c")`),
]
describe("Parsing from text", () => {
for (let s of errorTests) {
it(`${JSON.stringify(s.input)}`, () => {
const tokens = lexer.Lex("test", s.input);
if (lexical.isStaticError(tokens)) {
throw new Error(
`Unexpected lex error\n input: ${s}\n error: ${tokens.Error()}`);
}
const parse = parser.Parse(tokens);
if (!lexical.isStaticError(parse)) {
throw new Error(
`Expected parse error but got success\n input: ${s.input}`);
}
assert.equal(parse.Error(), s.err);
});
}
});
// func TestAST(t *testing.T) {
// files, _ := ioutil.ReadDir("./test_data/ast")
// for _, f := range files {
// if strings.HasSuffix(f.Name(), ".ast") {
// continue
// }
// assertParse(
// t,
// "./test_data/ast/"+f.Name(),
// "./test_data/ast/"+f.Name()+".ast")
// }
// }
// func assertParse(t *testing.T, sourceFile string, targetFile string) {
// // Parse source document into a JSON string.
// sourceBytes, err := ioutil.ReadFile(sourceFile)
// if err != nil {
// t.Errorf("Failed to read test file\n file name: %s\n error: %v", sourceFile, err)
// }
// source := string(sourceBytes)
// sourceTokens, err := Lex("stdin", source)
// if err != nil {
// log.Fatalf("Unexpected lex error\n filename: %s\n input: %v\n error: %v", sourceFile, source, err)
// }
// node, err := Parse(sourceTokens)
// if err != nil {
// log.Fatalf("Unexpected parse error\n filename: %s\n input: %v\n error: %v", sourceFile, sourceTokens, err)
// }
// sourceAstBytes, err := json.MarshalIndent(node, "", " ")
// if err != nil {
// log.Fatalf("Unexpected serialization error\n input: %v\n error: %v", source, err)
// }
// sourceAstString := strings.TrimSpace(string(sourceAstBytes))
// // Get target source as a JSON string.
// targetAstBytes, err := ioutil.ReadFile(targetFile)
// if err != nil {
// t.Errorf("Failed to read test file\n file name: %s\n error: %v", sourceFile, err)
// }
// targetAstString := strings.TrimSpace(string(targetAstBytes))
// // Compare.
// if sourceAstString != targetAstString {
// t.Errorf(
// "Parsed AST does not match target AST\n filename: %s\n parsed output:\n%s",
// sourceFile,
// sourceAstString)
// }
// } | the_stack |
import {
AfterViewInit,
ChangeDetectorRef,
Component,
ElementRef,
Inject,
OnDestroy,
OnInit,
ViewChild,
} from '@angular/core';
import { NgbDropdownConfig, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { Store } from '@ngrx/store';
import { DOCUMENT } from '@angular/common';
import { ActivatedRoute, NavigationEnd, Params, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
import { Title } from '@angular/platform-browser';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import {
AppState,
MailBoxesState,
MailState,
PlanType,
UserState,
NotificationPermission,
} from '../../store/datatypes';
import { ComposeMailService } from '../../store/services/compose-mail.service';
import { Folder, Mail, Mailbox, MailFolderType } from '../../store/models/mail.model';
import { BreakpointsService } from '../../store/services/breakpoint.service';
import {
GetMails,
GetMailsSuccess,
GetUnreadMailsCount,
GetUnreadMailsCountSuccess,
ReadMailSuccess,
SettingsUpdateUsedStorage,
StarredFolderCountUpdate,
SnackErrorPush,
DeleteFolder,
} from '../../store/actions';
import { WebsocketService } from '../../shared/services/websocket.service';
import { ThemeToggleService } from '../../shared/services/theme-toggle-service';
import { WebSocketState } from '../../store';
import { PushNotificationOptions, PushNotificationService } from '../../shared/services/push-notification.service';
import { ElectronService, SharedService } from '../../store/services';
import { PRIMARY_WEBSITE } from '../../shared/config';
import { QuoteType } from '../../store/quotes';
import { CreateFolderComponent } from '../dialogs/create-folder/create-folder.component';
@UntilDestroy()
@Component({
selector: 'app-mail-sidebar',
templateUrl: './mail-sidebar.component.html',
styleUrls: ['./mail-sidebar.component.scss'],
})
export class MailSidebarComponent implements OnInit, AfterViewInit, OnDestroy {
LIMIT = 3; // limit of displayed custom folder's count
EMAIL_LIMIT = 20; // limit to display emails
starredCount = 0; // starred folder count
// Public property of boolean type set false by default
public isComposeVisible = false;
public userState: UserState;
mailState: MailState;
mailFolderType = MailFolderType;
currentRoute: string;
isloading = true;
quote: QuoteType;
isMenuOpened: boolean;
notificationsPermission: string;
notificationPermissionType = NotificationPermission;
isSidebarOpened: boolean;
customFolders: Folder[] = [];
currentMailbox: Mailbox;
@ViewChild('input') input: ElementRef;
currentPlan: PlanType;
currentFolder: MailFolderType;
primaryWebsite = PRIMARY_WEBSITE;
private forceLightMode: boolean;
@ViewChild('confirmationModal') confirmationModal: any;
confirmModalRef: NgbModalRef;
selectedFolderForRemove: Folder;
constructor(
private store: Store<AppState>,
config: NgbDropdownConfig,
private breakpointsService: BreakpointsService,
private composeMailService: ComposeMailService,
private router: Router,
private websocketService: WebsocketService,
private pushNotificationService: PushNotificationService,
private titleService: Title,
private activatedRoute: ActivatedRoute,
@Inject(DOCUMENT) private document: Document,
private sharedService: SharedService,
private cdr: ChangeDetectorRef,
private themeToggleService: ThemeToggleService,
private modalService: NgbModal,
private electronService: ElectronService,
) {
// customize default values of dropdowns used by this component tree
config.autoClose = 'outside';
const nextPage = localStorage.getItem('nextPage');
if (nextPage) {
localStorage.setItem('nextPage', '');
this.router.navigateByUrl(nextPage);
}
this.currentRoute = router.url;
this.store.dispatch(new GetUnreadMailsCount());
this.websocketService.connect();
/**
* Listen to web sockets events to get new emails from server
*/
this.store
.select(state => state.webSocket)
.pipe(untilDestroyed(this))
.subscribe((webSocketState: WebSocketState) => {
if (webSocketState.message && !webSocketState.isClosed) {
if (webSocketState.message.mail) {
this.store.dispatch(
new GetMailsSuccess({
limit: this.EMAIL_LIMIT,
offset: 0,
folder: webSocketState.message.folder,
folders: webSocketState.message.folders,
read: false,
mails: [webSocketState.message.mail],
total_mail_count: webSocketState.message.total_count,
is_from_socket: true,
}),
);
if (
webSocketState.message.folder !== MailFolderType.SPAM &&
this.notificationsPermission === this.notificationPermissionType.GRANTED
) {
this.showNotification(webSocketState.message.mail, webSocketState.message.folder);
}
this.updateUnreadCount(webSocketState);
} else if (webSocketState.message.is_outbox_mail_sent) {
this.store.dispatch(
new GetUnreadMailsCountSuccess({ ...webSocketState.message.unread_count, updateUnreadCount: true }),
);
if (this.mailState.currentFolder === MailFolderType.OUTBOX) {
this.store.dispatch(new GetMails({ limit: this.LIMIT, offset: 0, folder: MailFolderType.OUTBOX }));
}
} else if (Object.prototype.hasOwnProperty.call(webSocketState.message, 'used_storage')) {
this.store.dispatch(new SettingsUpdateUsedStorage(webSocketState.message));
} else if (Object.prototype.hasOwnProperty.call(webSocketState.message, 'starred_count')) {
this.store.dispatch(new StarredFolderCountUpdate(webSocketState.message));
} else if (webSocketState.message.marked_as_read !== null) {
this.updateUnreadCount(webSocketState);
this.store.dispatch(
new ReadMailSuccess({
ids: webSocketState.message.ids.join(','),
read: webSocketState.message.marked_as_read,
}),
);
}
}
});
}
ngOnInit() {
this.quote = { content: 'Loading your settings...', author: '' };
if (this.pushNotificationService.isDefault()) {
setTimeout(() => {
this.pushNotificationService.requestPermission();
}, 3000);
}
if ('Notification' in window) {
this.notificationsPermission = Notification.permission;
}
/**
* Set state variables from user's settings.
*/
this.store
.select(state => state.user)
.pipe(untilDestroyed(this))
.subscribe((user: UserState) => {
this.userState = user;
this.currentPlan = user.settings.plan_type || PlanType.FREE;
this.EMAIL_LIMIT = this.userState.settings.emails_per_page ? this.userState.settings.emails_per_page : 20;
this.customFolders = user.customFolders;
if (this.breakpointsService.isSM() || this.breakpointsService.isXS()) {
this.LIMIT = this.customFolders.length;
}
this.themeToggleService.handleCustomCss(user.settings.theme);
if (user.settings) {
setTimeout(() => {
this.isloading = false;
}, 1000);
}
});
this.store
.select(state => state.mailboxes)
.pipe(untilDestroyed(this))
.subscribe((mailboxes: MailBoxesState) => {
this.currentMailbox = mailboxes.currentMailbox;
});
this.store
.select(state => state.mail)
.pipe(untilDestroyed(this))
.subscribe((mailState: MailState) => {
this.mailState = mailState;
this.starredCount = this.mailState.starredFolderCount ? this.mailState.starredFolderCount : 0;
this.currentFolder = mailState.currentFolder;
this.updateTitle();
});
/**
* Update Title on contacts or settings page
*/
this.router.events
.pipe(
untilDestroyed(this),
filter(event => event instanceof NavigationEnd),
)
.subscribe((event: NavigationEnd) => {
this.currentRoute = event.url;
if (event.url === '/mail/contacts') {
this.updateTitle(`${this.capitalize(event.url.split('/mail/')[1])} - CTemplar: Armored Email`);
} else if (event.url.includes('/mail/settings/')) {
this.updateTitle(`Settings - CTemplar: Armored Email`);
}
});
this.activatedRoute.queryParams.pipe(untilDestroyed(this)).subscribe((parameters: Params) => {
this.forceLightMode = parameters.lightMode;
if (this.forceLightMode) {
this.themeToggleService.forceLightModeTheme();
}
});
}
ngAfterViewInit(): void {
this.cdr.detectChanges();
}
private updateUnreadCount(webSocketState: WebSocketState) {
this.store.dispatch(
new GetUnreadMailsCountSuccess({ ...webSocketState.message.unread_count, updateUnreadCount: true }),
);
}
updateTitle(title: string = null) {
// Set tab title
if (!title) {
title = `${this.mailState.currentFolder ? this.capitalize(this.mailState.currentFolder) : ''} `;
if (
this.mailState.currentFolder &&
this.mailState.unreadMailsCount[this.mailState.currentFolder] &&
(this.mailState.currentFolder === 'inbox' ||
this.customFolders.some(folder => this.mailState.currentFolder === folder.name))
) {
title += `(${this.mailState.unreadMailsCount[this.mailState.currentFolder]}) - `;
} else if (this.mailState.currentFolder) {
title += ' - ';
}
title += 'CTemplar: Armored Email';
}
this.titleService.setTitle(title);
}
capitalize(s: string) {
if (typeof s !== 'string') {
return '';
}
return s.charAt(0).toUpperCase() + s.slice(1);
}
/**
* @description
* Prime Users - Can create as many folders as they want
* Free Users - Only allow a maximum of 5 folders per account
*/
// == Open NgbModal
createFolder() {
this.sharedService.openCreateFolderDialog(this.userState.isPrime, this.customFolders, undefined);
}
// == Show mail compose modal
openComposeMailDialog() {
this.composeMailService.openComposeMailDialog({ isFullScreen: this.userState.settings.is_composer_full_screen });
}
// Toggle between display entire custom folders or limited count of folders
toggleDisplayLimit(totalItems: number) {
this.LIMIT = this.LIMIT === totalItems ? 3 : totalItems;
}
// Toggle menu according to screen size
toggleMenu(event?: any) {
if (this.breakpointsService.isXS()) {
if (this.isMenuOpened) {
this.document.body.classList.remove('menu-open');
this.isMenuOpened = false;
}
if (this.document.body.classList.contains('menu-open')) {
this.isMenuOpened = true;
}
} else if (this.breakpointsService.isMD()) {
this.isSidebarOpened = event ? false : !this.isSidebarOpened;
}
}
changeAsideExpand(event: any) {
if (this.breakpointsService.isSM()) {
this.isSidebarOpened = event.type === 'mouseover';
}
}
showNotification(mail: Mail, folder: string) {
let title = mail.sender_display_name ? mail.sender_display_name : mail.sender_display.name;
if (mail.children?.length > 0) {
const lastMail = mail.children[mail.children.length - 1];
title = lastMail.sender_display_name ? lastMail.sender_display_name : lastMail.sender_display.name;
}
const options = new PushNotificationOptions();
options.body = 'You have received a new email';
options.icon = 'https://mail.ctemplar.com/assets/images/media-kit/mediakit-logo4.png';
if (this.electronService.isElectron) {
this.electronService.showNotification(
options.body,
`https://mail.ctemplar.com/mail/${folder}/page/1/message/${mail.id}`,
);
} else {
this.pushNotificationService.create(title, options).subscribe(
(notify: any) => {
if (notify.event.type === 'click') {
notify.notification.close();
window.open(`/mail/${folder}/page/1/message/${mail.id}`, '_blank');
}
},
() => {
this.store.dispatch(new SnackErrorPush({ message: 'Failed to send push notification.' }));
},
);
}
}
/**
* @description
*/
// == Open NgbModal
editFolder(folder: Folder) {
if (folder) {
const options: any = {
centered: true,
windowClass: 'modal-sm mailbox-modal create-folder-modal',
};
const component = this.modalService.open(CreateFolderComponent, options).componentInstance;
component.folder = folder;
component.edit = true;
}
}
showConfirmationModal(folder: Folder) {
this.confirmModalRef = this.modalService.open(this.confirmationModal, {
centered: true,
windowClass: 'modal-sm users-action-modal',
});
this.selectedFolderForRemove = folder;
}
deleteFolder() {
this.store.dispatch(new DeleteFolder(this.selectedFolderForRemove));
setTimeout(() => {
this.confirmModalRef.dismiss();
}, 1000);
}
ngOnDestroy(): void {
this.titleService.setTitle('CTemplar: Armored Email');
}
} | the_stack |
import Status from "./status"
import Article from "./article"
import Articles from "./articles"
import Artwork from "./artwork"
import { ArtworkVersionResolver } from "./artwork_version"
import Artworks from "./artworks"
import Artist from "./artist"
import Artists from "./artists"
import Collection from "./collection"
import { CreditCard } from "./credit_card"
import ExternalPartner from "./external_partner"
import Fair from "./fair"
import Fairs from "./fairs"
import Gene from "./gene"
import Genes from "./genes"
import GeneFamilies from "./gene_families"
import GeneFamily from "./gene_family"
import HomePage from "./home"
import { City } from "./city"
import { Order } from "./ecommerce/order"
import { Orders } from "./ecommerce/orders"
import { CreateOrderWithArtworkMutation } from "./ecommerce/create_order_with_artwork_mutation"
import { CreateOfferOrderWithArtworkMutation } from "./ecommerce/create_offer_order_with_artwork_mutation"
import { SetOrderShippingMutation } from "./ecommerce/set_order_shipping_mutation"
import { SetOrderPaymentMutation } from "./ecommerce/set_order_payment_mutation"
import { SubmitOrderMutation } from "./ecommerce/submit_order_mutation"
import { SubmitOrderWithOfferMutation } from "./ecommerce/submit_order_with_offer"
import { ApproveOrderMutation } from "./ecommerce/approve_order_mutation"
import { BuyerAcceptOfferMutation } from "./ecommerce/buyer_accept_offer_mutation"
import { SellerAcceptOfferMutation } from "./ecommerce/seller_accept_offer_mutation"
import { BuyerCounterOfferMutation } from "./ecommerce/buyer_counter_offer_mutation"
import { SubmitPendingOfferMutation } from "./ecommerce/submit_pending_offer_mutation"
import { SellerCounterOfferMutation } from "./ecommerce/seller_counter_offer_mutation"
import { BuyerRejectOfferMutation } from "./ecommerce/buyer_reject_offer_mutation"
import { SellerRejectOfferMutation } from "./ecommerce/seller_reject_offer_mutation"
import { FulfillOrderAtOnceMutation } from "./ecommerce/fulfill_order_at_once_mutation"
import { ConfirmPickupMutation } from "./ecommerce/confirm_pickup_mutation"
import { RejectOrderMutation } from "./ecommerce/reject_order_mutation"
import { FixFailedPaymentMutation } from "./ecommerce/fix_failed_payment"
import OrderedSet from "./ordered_set"
import OrderedSets from "./ordered_sets"
import Profile from "./profile"
import Partner from "./partner"
import Partners from "./partners"
import FilterPartners from "./filter_partners"
import filterArtworks from "./filter_artworks"
import FilterSaleArtworks from "./filter_sale_artworks"
import FollowArtist from "./me/follow_artist"
import FollowProfile from "./me/follow_profile"
import FollowGene from "./me/follow_gene"
import FollowShow from "./me/follow_show"
import PartnerCategory from "./partner_category"
import PartnerCategories from "./partner_categories"
import PartnerShow from "./partner_show"
import PartnerShows from "./partner_shows"
import PopularArtists from "./artists/popular"
import Sale from "./sale/index"
import Sales from "./sales"
import SaleArtwork from "./sale_artwork"
import SaleArtworks from "./sale_artworks"
import { Search } from "./search"
import Services from "./services"
import Show from "./show"
import SuggestedGenes from "./suggested_genes"
import System from "./system"
import Tag from "./tag"
import TrendingArtists from "./artists/trending"
import Users from "./users"
import { User } from "./user"
import MatchArtist from "./match/artist"
import MatchGene from "./match/gene"
import Me from "./me"
import UpdateConversationMutation from "./me/conversation/update_conversation_mutation"
import SendConversationMessageMutation from "./me/conversation/send_message_mutation"
import UpdateCollectorProfile from "./me/update_collector_profile"
import SaveArtworkMutation from "./me/save_artwork_mutation"
import { endSaleMutation } from "./sale/end_sale_mutation"
import CreateAssetRequestLoader from "./asset_uploads/create_asset_request_mutation"
import CreateGeminiEntryForAsset from "./asset_uploads/finalize_asset_mutation"
import UpdateMyUserProfileMutation from "./me/update_me_mutation"
import createBidderMutation from "./me/create_bidder_mutation"
import createCreditCardMutation from "./me/create_credit_card_mutation"
import { deleteCreditCardMutation } from "./me/delete_credit_card_mutation"
import { BidderPositionMutation } from "./me/bidder_position_mutation"
import { sendFeedbackMutation } from "./sendFeedbackMutation"
import StaticContent from "./static_content"
import CausalityJWT from "./causality_jwt"
import ObjectIdentification from "./object_identification"
import {
GraphQLSchema,
GraphQLObjectType,
GraphQLFieldConfigMap,
GraphQLDirective,
DirectiveLocation,
specifiedDirectives,
} from "graphql"
import { ResolverContext } from "types/graphql"
import { BuyOrderType, OfferOrderType } from "./ecommerce/types/order"
import { AddInitialOfferToOrderMutation } from "./ecommerce/add_initial_offer_to_order_mutation"
import { SearchableItem } from "./SearchableItem"
import ArtworkAttributionClasses from "./artworkAttributionClasses"
import { ArtistArtworkGridType } from "./artwork/artworkContextGrids/ArtistArtworkGrid"
import { AuctionArtworkGridType } from "./artwork/artworkContextGrids/AuctionArtworkGrid"
import { PartnerArtworkGridType } from "./artwork/artworkContextGrids/PartnerArtworkGrid"
import { RelatedArtworkGridType } from "./artwork/artworkContextGrids/RelatedArtworkGrid"
import { ShowArtworkGridType } from "./artwork/artworkContextGrids/ShowArtworkGrid"
const rootFields: GraphQLFieldConfigMap<any, ResolverContext> = {
artworkAttributionClasses: ArtworkAttributionClasses,
article: Article,
articles: Articles,
artwork: Artwork,
artworkVersion: ArtworkVersionResolver,
artworks: Artworks,
artist: Artist,
artists: Artists,
causality_jwt: CausalityJWT,
city: City,
collection: Collection,
credit_card: CreditCard,
external_partner: ExternalPartner,
fair: Fair,
fairs: Fairs,
filter_partners: FilterPartners,
// FIXME: Expected 1 arguments, but got 0
// @ts-ignore
filter_artworks: filterArtworks(),
filter_sale_artworks: FilterSaleArtworks,
gene: Gene,
genes: Genes,
suggested_genes: SuggestedGenes,
gene_families: GeneFamilies,
gene_family: GeneFamily,
home_page: HomePage,
match_artist: MatchArtist,
match_gene: MatchGene,
me: Me,
node: ObjectIdentification.NodeField,
ordered_set: OrderedSet,
ordered_sets: OrderedSets,
partner: Partner,
partner_categories: PartnerCategories,
partner_category: PartnerCategory,
partner_show: PartnerShow,
partner_shows: PartnerShows,
partners: Partners,
profile: Profile,
sale: Sale,
sale_artwork: SaleArtwork,
sale_artworks: SaleArtworks,
sales: Sales,
search: Search,
services: Services,
show: Show,
status: Status,
staticContent: StaticContent,
system: System,
tag: Tag,
trending_artists: TrendingArtists,
user: User,
users: Users,
popular_artists: PopularArtists,
}
const ViewerType = new GraphQLObjectType<any, ResolverContext>({
name: "Viewer",
description: "A wildcard used to support complex root queries in Relay",
fields: rootFields,
})
const Viewer = {
type: ViewerType,
description: "A wildcard used to support complex root queries in Relay",
resolve: (x) => x,
}
// A set of fields which are overridden when coming in from stitching
const stitchedRootFields: any = {}
// If you're using stitching then we _don't_ want to include particular mutations
// which come from the stitching instead of our manual version
const stitchedMutations: any = {}
stitchedRootFields.ecommerceOrder = Order
stitchedRootFields.ecommerceOrders = Orders
stitchedMutations.ecommerceCreateOrderWithArtwork = CreateOrderWithArtworkMutation
stitchedMutations.ecommerceCreateOfferOrderWithArtwork = CreateOfferOrderWithArtworkMutation
stitchedMutations.ecommerceSetOrderShipping = SetOrderShippingMutation
stitchedMutations.ecommerceSetOrderPayment = SetOrderPaymentMutation
stitchedMutations.ecommerceApproveOrder = ApproveOrderMutation
stitchedMutations.ecommerceBuyerAcceptOffer = BuyerAcceptOfferMutation
stitchedMutations.ecommerceSellerAcceptOffer = SellerAcceptOfferMutation
stitchedMutations.ecommerceBuyerCounterOffer = BuyerCounterOfferMutation
stitchedMutations.ecommerceSubmitPendingOffer = SubmitPendingOfferMutation
stitchedMutations.ecommerceSellerCounterOffer = SellerCounterOfferMutation
stitchedMutations.ecommerceBuyerRejectOffer = BuyerRejectOfferMutation
stitchedMutations.ecommerceSellerRejectOffer = SellerRejectOfferMutation
stitchedMutations.ecommerceConfirmPickup = ConfirmPickupMutation
stitchedMutations.ecommerceFulfillOrderAtOnce = FulfillOrderAtOnceMutation
stitchedMutations.ecommerceRejectOrder = RejectOrderMutation
stitchedMutations.ecommerceSubmitOrder = SubmitOrderMutation
stitchedMutations.ecommerceAddInitialOfferToOrder = AddInitialOfferToOrderMutation
stitchedMutations.ecommerceSubmitOrderWithOffer = SubmitOrderWithOfferMutation
stitchedMutations.ecommerceFixFailedPayment = FixFailedPaymentMutation
// Deprecated
stitchedRootFields.order = Order
stitchedRootFields.orders = Orders
// Deprecated
stitchedMutations.createOrderWithArtwork = CreateOrderWithArtworkMutation
stitchedMutations.setOrderShipping = SetOrderShippingMutation
stitchedMutations.setOrderPayment = SetOrderPaymentMutation
stitchedMutations.approveOrder = ApproveOrderMutation
stitchedMutations.fulfillOrderAtOnce = FulfillOrderAtOnceMutation
stitchedMutations.rejectOrder = RejectOrderMutation
stitchedMutations.submitOrder = SubmitOrderMutation
const PrincipalFieldDirective = new GraphQLDirective({
name: "principalField",
locations: [DirectiveLocation.FIELD],
})
export default new GraphQLSchema({
allowedLegacyNames: ["__id"],
mutation: new GraphQLObjectType<any, ResolverContext>({
name: "Mutation",
fields: {
createBidder: createBidderMutation,
createBidderPosition: BidderPositionMutation,
createCreditCard: createCreditCardMutation,
deleteCreditCard: deleteCreditCardMutation,
followArtist: FollowArtist,
followProfile: FollowProfile,
followGene: FollowGene,
followShow: FollowShow,
updateCollectorProfile: UpdateCollectorProfile,
updateMyUserProfile: UpdateMyUserProfileMutation,
updateConversation: UpdateConversationMutation,
sendConversationMessage: SendConversationMessageMutation,
sendFeedback: sendFeedbackMutation,
saveArtwork: SaveArtworkMutation,
endSale: endSaleMutation,
requestCredentialsForAssetUpload: CreateAssetRequestLoader,
createGeminiEntryForAsset: CreateGeminiEntryForAsset,
...stitchedMutations,
},
}),
query: new GraphQLObjectType<any, ResolverContext>({
name: "Query",
fields: {
...rootFields,
...stitchedRootFields,
viewer: Viewer,
},
}),
// These are for orphaned types which are types which should be in the schema,
// but can’t be discovered by traversing the types and fields from query.
//
// In this case, the interface "Offer" is exposed everywhere, but the underlaying type BuyOrder needs to exist
types: [
BuyOrderType,
OfferOrderType,
SearchableItem,
ArtistArtworkGridType,
AuctionArtworkGridType,
PartnerArtworkGridType,
RelatedArtworkGridType,
ShowArtworkGridType,
],
directives: specifiedDirectives.concat([PrincipalFieldDirective]),
}) | the_stack |
import React, { FC, useState, useEffect } from 'react';
import { render, cleanup } from '@testing-library/react';
import { makeJestMoveTimeTo } from '../../test-utils/makeJestMoveTimeTo';
import { ActJestMoveTimeTo, makeActJestMoveTimeTo } from '../../test-utils/makeActJestMoveTimeTo';
import { EXITED, EXITING, ENTERED, ENTERING } from '../constants';
import { useAnimator } from '../useAnimator';
import { Animator } from './Animator.component';
let actJestMoveTimeTo: ActJestMoveTimeTo;
jest.useFakeTimers();
beforeEach(() => {
const jestMoveTimeTo = makeJestMoveTimeTo();
actJestMoveTimeTo = makeActJestMoveTimeTo(jestMoveTimeTo);
});
afterEach(cleanup);
test('Should transition from "exited" to "entering" if "activate" with default "duration" (by default)', () => {
let flow: any;
const Example: FC = () => {
flow = useAnimator()?.flow;
return null;
};
render(<Animator><Example /></Animator>);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(1);
expect(flow.value).toBe(ENTERING);
actJestMoveTimeTo(99);
expect(flow.value).toBe(ENTERING);
actJestMoveTimeTo(101);
expect(flow.value).toBe(ENTERED);
});
test('Should not transition from "exited" if "activate=false"', () => {
let flow: any;
const Example: FC = () => {
flow = useAnimator()?.flow;
return null;
};
render(
<Animator animator={{ activate: false }}>
<Example />
</Animator>
);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(10);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(110);
expect(flow.value).toBe(EXITED);
});
test('Should transition on "activate" changes with default "duration"', () => {
let flow: any;
const ExampleChild: FC = () => {
flow = useAnimator()?.flow;
return null;
};
const ExampleApp: FC = () => {
const [activate, setActivate] = useState(false);
useEffect(() => {
setTimeout(() => setActivate(true), 500);
setTimeout(() => setActivate(false), 1000);
}, []);
return (
<Animator animator={{ activate }}>
<ExampleChild />
</Animator>
);
};
render(<ExampleApp />);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(1);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(499);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(501);
expect(flow.value).toBe(ENTERING);
actJestMoveTimeTo(599);
expect(flow.value).toBe(ENTERING);
actJestMoveTimeTo(601);
expect(flow.value).toBe(ENTERED);
actJestMoveTimeTo(999);
expect(flow.value).toBe(ENTERED);
actJestMoveTimeTo(1001);
expect(flow.value).toBe(EXITING);
actJestMoveTimeTo(1099);
expect(flow.value).toBe(EXITING);
actJestMoveTimeTo(1101);
expect(flow.value).toBe(EXITED);
});
test('Should receive flow state object when transitioning', () => {
let flowReceived: any;
const isFlow = (flowExpected: any): void => expect(flowReceived).toEqual(flowExpected);
const ExampleChild: FC = () => {
flowReceived = useAnimator()?.flow;
return null;
};
const ExampleApp: FC = () => {
const [activate, setActivate] = useState(false);
useEffect(() => {
setTimeout(() => setActivate(true), 1000);
setTimeout(() => setActivate(false), 2000);
}, []);
return (
<Animator animator={{ activate }}>
<ExampleChild />
</Animator>
);
};
render(<ExampleApp />);
isFlow({ value: EXITED, [EXITED]: true, hasEntered: false, hasExited: true });
actJestMoveTimeTo(1);
isFlow({ value: EXITED, [EXITED]: true, hasEntered: false, hasExited: true });
actJestMoveTimeTo(999);
isFlow({ value: EXITED, [EXITED]: true, hasEntered: false, hasExited: true });
actJestMoveTimeTo(1001);
isFlow({ value: ENTERING, [ENTERING]: true, hasEntered: false, hasExited: true });
actJestMoveTimeTo(1099);
isFlow({ value: ENTERING, [ENTERING]: true, hasEntered: false, hasExited: true });
actJestMoveTimeTo(1101);
isFlow({ value: ENTERED, [ENTERED]: true, hasEntered: true, hasExited: true });
actJestMoveTimeTo(1999);
isFlow({ value: ENTERED, [ENTERED]: true, hasEntered: true, hasExited: true });
actJestMoveTimeTo(2001);
isFlow({ value: EXITING, [EXITING]: true, hasEntered: true, hasExited: true });
actJestMoveTimeTo(2099);
isFlow({ value: EXITING, [EXITING]: true, hasEntered: true, hasExited: true });
actJestMoveTimeTo(2101);
isFlow({ value: EXITED, [EXITED]: true, hasEntered: true, hasExited: true });
});
test('Should get notified "onTransition" with flow state object if provided', () => {
const onTransition = jest.fn();
const onNthWith = (time: number, value: any): void => expect(onTransition).toHaveBeenNthCalledWith(time, value);
const ExampleApp: FC = () => {
const [activate, setActivate] = useState(false);
useEffect(() => {
setTimeout(() => setActivate(true), 1000);
setTimeout(() => setActivate(false), 2000);
}, []);
return <Animator animator={{ activate, onTransition }} />;
};
render(<ExampleApp />);
expect(onTransition).toHaveBeenCalledTimes(1);
onNthWith(1, { value: EXITED, [EXITED]: true, hasEntered: false, hasExited: true });
actJestMoveTimeTo(1);
expect(onTransition).toHaveBeenCalledTimes(1);
actJestMoveTimeTo(999);
expect(onTransition).toHaveBeenCalledTimes(1);
actJestMoveTimeTo(1001);
expect(onTransition).toHaveBeenCalledTimes(2);
onNthWith(2, { value: ENTERING, [ENTERING]: true, hasEntered: false, hasExited: true });
actJestMoveTimeTo(1099);
expect(onTransition).toHaveBeenCalledTimes(2);
actJestMoveTimeTo(1101);
expect(onTransition).toHaveBeenCalledTimes(3);
onNthWith(3, { value: ENTERED, [ENTERED]: true, hasEntered: true, hasExited: true });
actJestMoveTimeTo(1999);
expect(onTransition).toHaveBeenCalledTimes(3);
actJestMoveTimeTo(2001);
expect(onTransition).toHaveBeenCalledTimes(4);
onNthWith(4, { value: EXITING, [EXITING]: true, hasEntered: true, hasExited: true });
actJestMoveTimeTo(2099);
expect(onTransition).toHaveBeenCalledTimes(4);
actJestMoveTimeTo(2101);
expect(onTransition).toHaveBeenCalledTimes(5);
onNthWith(5, { value: EXITED, [EXITED]: true, hasEntered: true, hasExited: true });
});
test('Should not call "onTransition" if provided and "animate=false"', () => {
const onTransition = jest.fn();
render(<Animator animator={{ animate: false, onTransition }} />);
actJestMoveTimeTo(1000);
expect(onTransition).not.toHaveBeenCalled();
});
test('Should still be the "root" even if configured "root=false" but no parent found', () => {
let flow: any;
const Example: FC = () => {
flow = useAnimator()?.flow;
return null;
};
render(
<Animator animator={{ root: false }}>
<Example />
</Animator>
);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(1);
expect(flow.value).toBe(ENTERING);
});
test('Should transition on "activate" changes with provided "duration"', () => {
let flow: any;
const ExampleChild: FC = () => {
flow = useAnimator()?.flow;
return null;
};
const ExampleApp: FC = () => {
const [activate, setActivate] = useState(false);
const duration = { enter: 400, exit: 200 };
useEffect(() => {
setTimeout(() => setActivate(true), 1000);
setTimeout(() => setActivate(false), 2000);
}, []);
return (
<Animator animator={{ activate, duration }}>
<ExampleChild />
</Animator>
);
};
render(<ExampleApp />);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(1);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(999);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(1001);
expect(flow.value).toBe(ENTERING);
actJestMoveTimeTo(1399);
expect(flow.value).toBe(ENTERING);
actJestMoveTimeTo(1401);
expect(flow.value).toBe(ENTERED);
actJestMoveTimeTo(1999);
expect(flow.value).toBe(ENTERED);
actJestMoveTimeTo(2001);
expect(flow.value).toBe(EXITING);
actJestMoveTimeTo(2199);
expect(flow.value).toBe(EXITING);
actJestMoveTimeTo(2201);
expect(flow.value).toBe(EXITED);
});
test('Should delay transition from "exited" to "entering" if provided "duration.delay"', () => {
let flow: any;
const ExampleChild: FC = () => {
flow = useAnimator()?.flow;
return null;
};
const ExampleApp: FC = () => {
const [activate, setActivate] = useState(false);
const duration = { delay: 100 };
useEffect(() => {
setTimeout(() => setActivate(true), 1000);
setTimeout(() => setActivate(false), 2000);
}, []);
return (
<Animator animator={{ activate, duration }}>
<ExampleChild />
</Animator>
);
};
render(<ExampleApp />);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(1);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(999);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(1001);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(1099);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(1101);
expect(flow.value).toBe(ENTERING);
actJestMoveTimeTo(1199);
expect(flow.value).toBe(ENTERING);
actJestMoveTimeTo(1201);
expect(flow.value).toBe(ENTERED);
actJestMoveTimeTo(1999);
expect(flow.value).toBe(ENTERED);
actJestMoveTimeTo(2001);
expect(flow.value).toBe(EXITING);
actJestMoveTimeTo(2099);
expect(flow.value).toBe(EXITING);
actJestMoveTimeTo(2101);
expect(flow.value).toBe(EXITED);
});
test('Should transition even with zero durations', () => {
let flow: any;
const ExampleChild: FC = () => {
flow = useAnimator()?.flow;
return null;
};
const ExampleApp: FC = () => {
const [activate, setActivate] = useState(false);
const duration = { enter: 0, exit: 0 };
useEffect(() => {
setTimeout(() => setActivate(true), 1000);
setTimeout(() => setActivate(false), 2000);
}, []);
return (
<Animator animator={{ activate, duration }}>
<ExampleChild />
</Animator>
);
};
render(<ExampleApp />);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(1);
expect(flow.value).toBe(EXITED);
actJestMoveTimeTo(999);
expect(flow.value).toBe(EXITED);
// At 1000ms it is supposed to change to ENTERING and immediately to ENTERED.
actJestMoveTimeTo(1001);
expect(flow.value).toBe(ENTERED);
actJestMoveTimeTo(1999);
expect(flow.value).toBe(ENTERED);
// At 2000ms it is supposed to change to EXITING and immediately to EXITED.
actJestMoveTimeTo(2001);
expect(flow.value).toBe(EXITED);
});
test('Should imperatively update duration', () => {
let flow: any;
let duration: any;
const ExampleChild: FC = () => {
const animator = useAnimator();
flow = animator?.flow;
duration = animator?.duration;
useEffect(() => {
animator?.updateDuration({ enter: 500, exit: 500 });
}, []);
return null;
};
render(
<Animator>
<ExampleChild />
</Animator>
);
expect(flow.value).toBe(EXITED);
expect(duration).toMatchObject({ enter: 500, exit: 500 });
actJestMoveTimeTo(1);
expect(flow.value).toBe(ENTERING);
actJestMoveTimeTo(499);
expect(flow.value).toBe(ENTERING);
actJestMoveTimeTo(501);
expect(flow.value).toBe(ENTERED);
}); | the_stack |
import { Accessibility, toolbarMenuItemBehavior } from '@fluentui/accessibility'
import * as React from 'react'
import * as _ from 'lodash'
import cx from 'classnames'
import * as PropTypes from 'prop-types'
import { EventListener } from '@fluentui/react-component-event-listener'
import { Ref } from '@fluentui/react-component-ref'
import * as customPropTypes from '@fluentui/react-proptypes'
import { focusAsync } from '@fluentui/react-bindings'
import { GetRefs, NodeRef, Unstable_NestingAuto } from '@fluentui/react-component-nesting-registry'
import {
ChildrenComponentProps,
commonPropTypes,
ContentComponentProps,
AutoControlledComponent,
UIComponentProps,
createShorthandFactory,
childrenExist,
applyAccessibilityKeyHandlers,
ShorthandFactory,
doesNodeContainClick,
} from '../../utils'
import {
ComponentEventHandler,
ShorthandValue,
WithAsProp,
withSafeTypeForAs,
Omit,
ShorthandCollection,
} from '../../types'
import { Popper } from '../../utils/positioner'
import Box, { BoxProps } from '../Box/Box'
import Icon, { IconProps } from '../Icon/Icon'
import Popup, { PopupProps } from '../Popup/Popup'
import {
ToolbarMenuProps,
ToolbarMenuItemShorthandKinds,
default as ToolbarMenu,
} from './ToolbarMenu'
export interface ToolbarMenuItemProps
extends UIComponentProps,
ChildrenComponentProps,
ContentComponentProps {
/**
* Accessibility behavior if overridden by the user.
*/
accessibility?: Accessibility
/** A toolbar item can be active. */
active?: boolean
/** A slot for a selected indicator in the dropdown list. */
activeIndicator?: ShorthandValue<IconProps>
/** A toolbar item can show it is currently unable to be interacted with. */
disabled?: boolean
/** Name or shorthand for Toolbar Item Icon */
icon?: ShorthandValue<IconProps>
/** ToolbarMenuItem index inside ToolbarMenu. */
index?: number
/** Shorthand for the submenu indicator. */
submenuIndicator?: ShorthandValue<IconProps>
/** Indicates whether the menu item is part of submenu. */
inSubmenu?: boolean
/** Shorthand for the submenu. */
menu?:
| ShorthandValue<ToolbarMenuProps>
| ShorthandCollection<ToolbarMenuItemProps, ToolbarMenuItemShorthandKinds>
/** Indicates if the menu inside the item is open. */
menuOpen?: boolean
/** Default menu open */
defaultMenuOpen?: boolean
/**
* Called on click.
*
* @param event - React's original SyntheticEvent.
* @param data - All props.
*/
onClick?: ComponentEventHandler<ToolbarMenuItemProps>
/**
* Called when the menu inside the item opens or closes.
* @param event - React's original SyntheticEvent.
* @param data - All props, with `menuOpen` reflecting the new state.
*/
onMenuOpenChange?: ComponentEventHandler<ToolbarMenuItemProps>
/**
* Attaches a `Popup` component to the ToolbarMenuItem.
* Accepts all props as a `Popup`, except `trigger` and `children`.
* Traps focus by default.
* @see PopupProps
*/
popup?: Omit<PopupProps, 'trigger' | 'children'> | string
/** Shorthand for the wrapper component. */
wrapper?: ShorthandValue<BoxProps>
}
export interface ToolbarMenuItemState {
menuOpen: boolean
}
export interface ToolbarMenuItemSlotClassNames {
activeIndicator: string
wrapper: string
submenu: string
}
class ToolbarMenuItem extends AutoControlledComponent<
WithAsProp<ToolbarMenuItemProps>,
ToolbarMenuItemState
> {
static displayName = 'ToolbarMenuItem'
static className = 'ui-toolbar__menuitem'
static slotClassNames: ToolbarMenuItemSlotClassNames = {
activeIndicator: `${ToolbarMenuItem.className}__activeIndicator`,
wrapper: `${ToolbarMenuItem.className}__wrapper`,
submenu: `${ToolbarMenuItem.className}__submenu`,
}
static create: ShorthandFactory<ToolbarMenuItemProps>
static propTypes = {
...commonPropTypes.createCommon(),
active: PropTypes.bool,
activeIndicator: customPropTypes.itemShorthandWithoutJSX,
defaultMenuOpen: PropTypes.bool,
disabled: PropTypes.bool,
icon: customPropTypes.itemShorthand,
index: PropTypes.number,
submenuIndicator: customPropTypes.itemShorthandWithoutJSX,
inSubmenu: PropTypes.bool,
menu: PropTypes.oneOfType([customPropTypes.itemShorthand, customPropTypes.collectionShorthand]),
menuOpen: PropTypes.bool,
onClick: PropTypes.func,
onMenuOpenChange: PropTypes.func,
popup: PropTypes.oneOfType([
PropTypes.shape({
...Popup.propTypes,
trigger: customPropTypes.never,
children: customPropTypes.never,
}),
PropTypes.string,
]),
wrapper: customPropTypes.itemShorthand,
}
static defaultProps = {
as: 'button',
accessibility: toolbarMenuItemBehavior as Accessibility,
activeIndicator: 'icon-checkmark',
submenuIndicator: 'icon-menu-arrow-end',
wrapper: { as: 'li' },
}
static autoControlledProps = ['menuOpen']
itemRef = React.createRef<HTMLElement>()
menuRef = React.createRef<HTMLElement>() as React.MutableRefObject<HTMLElement>
actionHandlers = {
performClick: event => {
event.preventDefault()
this.handleClick(event)
},
openMenu: event => this.openMenu(event),
closeAllMenusAndFocusNextParentItem: event => this.closeAllMenus(event),
closeMenu: event => this.closeMenu(event),
closeMenuAndFocusTrigger: event => this.closeMenu(event),
doNotNavigateNextParentItem: event => {
event.stopPropagation()
},
closeAllMenus: event => this.closeAllMenus(event),
}
openMenu = (e: React.KeyboardEvent) => {
const { menu } = this.props
const { menuOpen } = this.state
if (menu && !menuOpen) {
this.trySetMenuOpen(true, e)
e.stopPropagation()
e.preventDefault()
}
}
closeMenu = (e: React.KeyboardEvent) => {
if (!this.isSubmenuOpen()) {
return
}
this.trySetMenuOpen(false, e, () => {
focusAsync(this.itemRef.current)
})
e.stopPropagation()
}
closeAllMenus = (e: Event) => {
if (!this.isSubmenuOpen()) {
return
}
const { inSubmenu } = this.props
this.trySetMenuOpen(false, e, () => {
if (!inSubmenu) {
focusAsync(this.itemRef.current)
}
})
// avoid spacebar scrolling the page
if (!inSubmenu) {
e.preventDefault()
}
}
isSubmenuOpen = (): boolean => {
const { menu } = this.props
const { menuOpen } = this.state
return !!(menu && menuOpen)
}
trySetMenuOpen(newValue: boolean, e: Event | React.SyntheticEvent, onStateChanged?: any) {
this.setState({ menuOpen: newValue })
// The reason why post-effect is not passed as callback to trySetState method
// is that in 'controlled' mode the post-effect is applied before final re-rendering
// which cause a broken behavior: for e.g. when it is needed to focus submenu trigger on ESC.
// TODO: all DOM post-effects should be applied at componentDidMount & componentDidUpdated stages.
onStateChanged && onStateChanged()
_.invoke(this.props, 'onMenuOpenChange', e, {
...this.props,
menuOpen: newValue,
})
}
outsideClickHandler = (getRefs: GetRefs) => (e: MouseEvent) => {
const isItemClick = doesNodeContainClick(this.itemRef.current, e, this.context.target)
const isNestedClick = _.some(getRefs(), (childRef: NodeRef) => {
return doesNodeContainClick(childRef.current as HTMLElement, e, this.context.target)
})
const isInside = isItemClick || isNestedClick
if (!isInside) {
this.trySetMenuOpen(false, e)
}
}
handleMenuOverrides = (getRefs: GetRefs) => (predefinedProps: ToolbarMenuProps) => ({
onItemClick: (e, itemProps: ToolbarMenuItemProps) => {
const { popup, menuOpen } = itemProps
_.invoke(predefinedProps, 'onItemClick', e, itemProps)
if (popup) {
return
}
this.trySetMenuOpen(menuOpen, e)
if (!menuOpen) {
_.invoke(this.itemRef.current, 'focus')
}
},
})
renderComponent({ ElementType, classes, accessibility, unhandledProps, styles, rtl }) {
const {
active,
activeIndicator,
children,
content,
disabled,
submenuIndicator,
icon,
menu,
popup,
wrapper,
} = this.props
const { menuOpen } = this.state
const elementType = (
<ElementType
{...accessibility.attributes.root}
{...unhandledProps}
{...applyAccessibilityKeyHandlers(accessibility.keyHandlers.root, unhandledProps)}
disabled={disabled}
className={classes.root}
onClick={this.handleClick}
>
{childrenExist(children) ? (
children
) : (
<>
{Icon.create(icon, {
defaultProps: () => ({ xSpacing: !!content ? 'after' : 'none' }),
})}
{content}
{active &&
Icon.create(activeIndicator, {
defaultProps: () => ({
className: ToolbarMenuItem.slotClassNames.activeIndicator,
styles: styles.activeIndicator,
}),
})}
{menu &&
Icon.create(submenuIndicator, {
defaultProps: () => ({
name: 'icon-menu-arrow-end',
styles: styles.submenuIndicator,
}),
})}
</>
)}
</ElementType>
)
const hasChildren = childrenExist(children)
if (popup && !hasChildren) {
return Popup.create(popup, {
defaultProps: () => ({
trapFocus: true,
onOpenChange: e => {
e.stopPropagation()
},
}),
overrideProps: {
trigger: elementType,
children: undefined, // force-reset `children` defined for `Popup` as it collides with the `trigger`
},
})
}
const menuItemInner = hasChildren ? children : <Ref innerRef={this.itemRef}>{elementType}</Ref>
const maybeSubmenu =
menu && menuOpen ? (
<Unstable_NestingAuto>
{(getRefs, nestingRef) => (
<>
<Ref
innerRef={(node: HTMLElement) => {
nestingRef.current = node
this.menuRef.current = node
}}
>
<Popper align="top" position={rtl ? 'before' : 'after'} targetRef={this.itemRef}>
{ToolbarMenu.create(menu, {
defaultProps: () => ({
className: ToolbarMenuItem.slotClassNames.submenu,
styles: styles.menu,
submenu: true,
submenuIndicator,
}),
overrideProps: this.handleMenuOverrides(getRefs),
})}
</Popper>
</Ref>
<EventListener
listener={this.outsideClickHandler(getRefs)}
target={this.context.target}
type="click"
/>
</>
)}
</Unstable_NestingAuto>
) : null
if (!wrapper) {
return menuItemInner
}
return Box.create(wrapper, {
defaultProps: () => ({
className: cx(ToolbarMenuItem.slotClassNames.wrapper, classes.wrapper),
...accessibility.attributes.wrapper,
...applyAccessibilityKeyHandlers(accessibility.keyHandlers.wrapper, wrapper),
}),
overrideProps: () => ({
children: (
<>
{menuItemInner}
{maybeSubmenu}
</>
),
}),
})
}
handleClick = (e: React.MouseEvent) => {
const { disabled, menu, popup } = this.props
if (disabled) {
e.preventDefault()
return
}
if (menu) {
// the menuItem element was clicked => toggle the open/close and stop propagation
this.trySetMenuOpen(!this.state.menuOpen, e)
e.stopPropagation()
e.preventDefault()
}
if (popup) {
e.stopPropagation()
e.preventDefault()
return
}
_.invoke(this.props, 'onClick', e, this.props)
}
}
ToolbarMenuItem.create = createShorthandFactory({
Component: ToolbarMenuItem,
mappedProp: 'content',
})
/**
* A ToolbarMenuItem renders ToolbarMenu item as button.
*/
export default withSafeTypeForAs<typeof ToolbarMenuItem, ToolbarMenuItemProps, 'button'>(
ToolbarMenuItem,
) | the_stack |
import { dirname } from 'path';
import * as postcss from 'postcss';
import type { Diagnostics } from './diagnostics';
import { resolveArgumentsValue } from './functions';
import { cssObjectToAst } from './parser';
import { fixRelativeUrls } from './stylable-assets';
import type { ImportSymbol } from './stylable-meta';
import type { RefedMixin, SRule, StylableMeta } from './stylable-processor';
import type { CSSResolve } from './stylable-resolver';
import type { StylableTransformer } from './stylable-transformer';
import { createSubsetAst, isValidDeclaration, mergeRules } from './stylable-utils';
import { valueMapping, mixinDeclRegExp, strategies } from './stylable-value-parsers';
export const mixinWarnings = {
FAILED_TO_APPLY_MIXIN(error: string) {
return `could not apply mixin: ${error}`;
},
JS_MIXIN_NOT_A_FUNC() {
return `js mixin must be a function`;
},
CIRCULAR_MIXIN(circularPaths: string[]) {
return `circular mixin found: ${circularPaths.join(' --> ')}`;
},
UNKNOWN_MIXIN_SYMBOL(name: string) {
return `cannot mixin unknown symbol "${name}"`;
},
};
export function appendMixins(
transformer: StylableTransformer,
rule: SRule,
meta: StylableMeta,
variableOverride: Record<string, string>,
cssVarsMapping: Record<string, string>,
path: string[] = []
) {
if (!rule.mixins || rule.mixins.length === 0) {
return;
}
rule.mixins.forEach((mix) => {
appendMixin(mix, transformer, rule, meta, variableOverride, cssVarsMapping, path);
});
rule.mixins.length = 0;
rule.walkDecls(mixinDeclRegExp, (node) => {
node.remove();
});
}
export function appendMixin(
mix: RefedMixin,
transformer: StylableTransformer,
rule: SRule,
meta: StylableMeta,
variableOverride: Record<string, string>,
cssVarsMapping: Record<string, string>,
path: string[] = []
) {
if (checkRecursive(transformer, meta, mix, rule, path)) {
return;
}
const local = meta.mappedSymbols[mix.mixin.type];
if (local && (local._kind === 'class' || local._kind === 'element')) {
handleLocalClassMixin(
reParseMixinNamedArgs(mix, rule, transformer.diagnostics),
transformer,
meta,
variableOverride,
cssVarsMapping,
path,
rule
);
} else {
const resolvedMixin = transformer.resolver.deepResolve(mix.ref);
if (resolvedMixin) {
if (resolvedMixin._kind === 'js') {
if (typeof resolvedMixin.symbol === 'function') {
try {
handleJSMixin(
transformer,
reParseMixinArgs(mix, rule, transformer.diagnostics),
resolvedMixin.symbol,
meta,
rule,
variableOverride
);
} catch (e) {
transformer.diagnostics.error(
rule,
mixinWarnings.FAILED_TO_APPLY_MIXIN(String(e)),
{ word: mix.mixin.type }
);
return;
}
} else {
transformer.diagnostics.error(rule, mixinWarnings.JS_MIXIN_NOT_A_FUNC(), {
word: mix.mixin.type,
});
}
} else {
handleImportedCSSMixin(
transformer,
reParseMixinNamedArgs(mix, rule, transformer.diagnostics),
rule,
meta,
path,
variableOverride,
cssVarsMapping
);
}
} else {
// TODO: error cannot resolve mixin - this should be a diagnostic covered by unknown symbol
}
}
}
function checkRecursive(
transformer: StylableTransformer,
meta: StylableMeta,
mix: RefedMixin,
rule: postcss.Rule,
path: string[]
) {
const symbolName =
mix.ref.name === meta.root
? mix.ref._kind === 'class'
? meta.root
: 'default'
: mix.mixin.type;
const isRecursive = path.includes(symbolName + ' from ' + meta.source);
if (isRecursive) {
// Todo: add test verifying word
transformer.diagnostics.warn(rule, mixinWarnings.CIRCULAR_MIXIN(path), {
word: symbolName,
});
return true;
}
return false;
}
function handleJSMixin(
transformer: StylableTransformer,
mix: RefedMixin,
mixinFunction: (...args: any[]) => any,
meta: StylableMeta,
rule: postcss.Rule,
variableOverride?: Record<string, string>
) {
const res = mixinFunction((mix.mixin.options as any[]).map((v) => v.value));
const mixinRoot = cssObjectToAst(res).root;
mixinRoot.walkDecls((decl) => {
if (!isValidDeclaration(decl)) {
decl.value = String(decl);
}
});
transformer.transformAst(mixinRoot, meta, undefined, variableOverride, [], true);
const mixinPath = (mix.ref as ImportSymbol).import.from;
fixRelativeUrls(
mixinRoot,
transformer.fileProcessor.resolvePath(mixinPath, dirname(meta.source)),
meta.source
);
mergeRules(mixinRoot, rule);
}
function createMixinRootFromCSSResolve(
transformer: StylableTransformer,
mix: RefedMixin,
meta: StylableMeta,
resolvedClass: CSSResolve,
path: string[],
decl: postcss.Declaration,
variableOverride: Record<string, string>,
cssVarsMapping: Record<string, string>
) {
const isRootMixin = resolvedClass.symbol.name === resolvedClass.meta.root;
const mixinRoot = createSubsetAst<postcss.Root>(
resolvedClass.meta.ast,
(resolvedClass.symbol._kind === 'class' ? '.' : '') + resolvedClass.symbol.name,
undefined,
isRootMixin
);
const namedArgs = mix.mixin.options as Record<string, string>;
if (mix.mixin.partial) {
filterPartialMixinDecl(meta, mixinRoot, Object.keys(namedArgs));
}
const resolvedArgs = resolveArgumentsValue(
namedArgs,
transformer,
meta,
transformer.diagnostics,
decl,
variableOverride,
path,
cssVarsMapping
);
const mixinMeta: StylableMeta = isRootMixin
? resolvedClass.meta
: createInheritedMeta(resolvedClass);
const symbolName = isRootMixin ? 'default' : mix.mixin.type;
transformer.transformAst(
mixinRoot,
mixinMeta,
undefined,
resolvedArgs,
path.concat(symbolName + ' from ' + meta.source),
true
);
fixRelativeUrls(mixinRoot, mixinMeta.source, meta.source);
return mixinRoot;
}
function handleImportedCSSMixin(
transformer: StylableTransformer,
mix: RefedMixin,
rule: postcss.Rule,
meta: StylableMeta,
path: string[],
variableOverride: Record<string, string>,
cssVarsMapping: Record<string, string>
) {
const isPartial = mix.mixin.partial;
const namedArgs = mix.mixin.options as Record<string, string>;
const overrideKeys = Object.keys(namedArgs);
if (isPartial && overrideKeys.length === 0) {
return;
}
let resolvedClass = transformer.resolver.resolve(mix.ref) as CSSResolve;
const roots = [];
while (resolvedClass && resolvedClass.symbol && resolvedClass._kind === 'css') {
const mixinDecl = getMixinDeclaration(rule) || postcss.decl();
roots.push(
createMixinRootFromCSSResolve(
transformer,
mix,
meta,
resolvedClass,
path,
mixinDecl,
variableOverride,
cssVarsMapping
)
);
if (
(resolvedClass.symbol._kind === 'class' || resolvedClass.symbol._kind === 'element') &&
!resolvedClass.symbol[valueMapping.extends]
) {
resolvedClass = transformer.resolver.resolve(resolvedClass.symbol) as CSSResolve;
} else {
break;
}
}
if (roots.length === 1) {
mergeRules(roots[0], rule);
} else if (roots.length > 1) {
const mixinRoot = postcss.root();
roots.forEach((root) => mixinRoot.prepend(...root.nodes));
mergeRules(mixinRoot, rule);
} else {
const mixinDecl = getMixinDeclaration(rule);
if (mixinDecl) {
transformer.diagnostics.error(
mixinDecl,
mixinWarnings.UNKNOWN_MIXIN_SYMBOL(mixinDecl.value),
{ word: mixinDecl.value }
);
}
}
}
function handleLocalClassMixin(
mix: RefedMixin,
transformer: StylableTransformer,
meta: StylableMeta,
variableOverride: ({ [key: string]: string } & object) | undefined,
cssVarsMapping: Record<string, string>,
path: string[],
rule: SRule
) {
const isPartial = mix.mixin.partial;
const namedArgs = mix.mixin.options as Record<string, string>;
const overrideKeys = Object.keys(namedArgs);
if (isPartial && overrideKeys.length === 0) {
return;
}
const isRootMixin = mix.ref.name === meta.root;
const mixinDecl = getMixinDeclaration(rule) || postcss.decl();
const resolvedArgs = resolveArgumentsValue(
namedArgs,
transformer,
meta,
transformer.diagnostics,
mixinDecl,
variableOverride,
path,
cssVarsMapping
);
const mixinRoot = createSubsetAst<postcss.Root>(
meta.ast,
'.' + mix.ref.name,
undefined,
isRootMixin
);
if (isPartial) {
filterPartialMixinDecl(meta, mixinRoot, overrideKeys);
}
transformer.transformAst(
mixinRoot,
isRootMixin ? meta : createInheritedMeta({ meta, symbol: mix.ref, _kind: 'css' }),
undefined,
resolvedArgs,
path.concat(mix.mixin.type + ' from ' + meta.source),
true
);
mergeRules(mixinRoot, rule);
}
function createInheritedMeta(resolvedClass: CSSResolve) {
const mixinMeta: StylableMeta = Object.create(resolvedClass.meta);
mixinMeta.parent = resolvedClass.meta;
mixinMeta.mappedSymbols = Object.create(resolvedClass.meta.mappedSymbols);
mixinMeta.mappedSymbols[resolvedClass.meta.root] =
resolvedClass.meta.mappedSymbols[resolvedClass.symbol.name];
return mixinMeta;
}
function getMixinDeclaration(rule: postcss.Rule): postcss.Declaration | undefined {
return (
rule.nodes &&
(rule.nodes.find((node) => {
return (
node.type === 'decl' &&
(node.prop === valueMapping.mixin || node.prop === valueMapping.partialMixin)
);
}) as postcss.Declaration)
);
}
const partialsOnly = ({ mixin: { partial } }: RefedMixin): boolean => {
return !!partial;
};
const nonPartials = ({ mixin: { partial } }: RefedMixin): boolean => {
return !partial;
};
/** we assume that mixinRoot is freshly created nodes from the ast */
function filterPartialMixinDecl(
meta: StylableMeta,
mixinRoot: postcss.Root,
overrideKeys: string[]
) {
let regexp: RegExp;
const overrideSet = new Set(overrideKeys);
let size;
do {
size = overrideSet.size;
regexp = new RegExp(`value\\((\\s*${Array.from(overrideSet).join('\\s*)|(\\s*')}\\s*)\\)`);
for (const { text, name } of meta.vars) {
if (!overrideSet.has(name) && text.match(regexp)) {
overrideSet.add(name);
}
}
} while (overrideSet.size !== size);
mixinRoot.walkDecls((decl) => {
if (!decl.value.match(regexp)) {
const parent = decl.parent as SRule; // ref the parent before remove
decl.remove();
if (parent?.nodes?.length === 0) {
parent.remove();
} else if (parent) {
if (decl.prop === valueMapping.mixin) {
parent.mixins = parent.mixins!.filter(partialsOnly);
} else if (decl.prop === valueMapping.partialMixin) {
parent.mixins = parent.mixins!.filter(nonPartials);
}
}
}
});
}
/** this is a workaround for parsing the mixin args too early */
function reParseMixinNamedArgs(
mix: RefedMixin,
rule: postcss.Rule,
diagnostics: Diagnostics
): RefedMixin {
const options =
mix.mixin.valueNode?.type === 'function'
? strategies.named(mix.mixin.valueNode, (message, options) => {
diagnostics.warn(mix.mixin.originDecl || rule, message, options);
})
: (mix.mixin.options as Record<string, string>) || {};
return {
...mix,
mixin: {
...mix.mixin,
options,
},
};
}
function reParseMixinArgs(
mix: RefedMixin,
rule: postcss.Rule,
diagnostics: Diagnostics
): RefedMixin {
const options =
mix.mixin.valueNode?.type === 'function'
? strategies.args(mix.mixin.valueNode, (message, options) => {
diagnostics.warn(mix.mixin.originDecl || rule, message, options);
})
: Array.isArray(mix.mixin.options)
? (mix.mixin.options as { value: string }[])
: [];
return {
...mix,
mixin: {
...mix.mixin,
options,
},
};
} | the_stack |
import * as React from "react";
import { IModelApp, IModelConnection } from "@itwin/core-frontend";
import { Field } from "@itwin/presentation-common";
import {
IPresentationPropertyDataProvider, PresentationPropertyDataProvider, usePropertyDataProviderWithUnifiedSelection,
} from "@itwin/presentation-components";
import { FavoritePropertiesScope, Presentation } from "@itwin/presentation-frontend";
import {
ActionButtonRendererProps, PropertyGridContextMenuArgs, useAsyncValue, VirtualizedPropertyGridWithDataProvider,
VirtualizedPropertyGridWithDataProviderProps,
} from "@itwin/components-react";
import { ContextMenuItem, ContextMenuItemProps, FillCentered, GlobalContextMenu, Icon, Orientation, ResizableContainerObserver } from "@itwin/core-react";
import { ConfigurableCreateInfo, useActiveIModelConnection, useFrameworkVersion, WidgetControl } from "@itwin/appui-react";
export type ContextMenuItemInfo = ContextMenuItemProps & React.Attributes & { label: string };
// eslint-disable-next-line @typescript-eslint/naming-convention
function FavoriteActionButton({ field, imodel }: { field: Field, imodel: IModelConnection }) {
const isMountedRef = React.useRef(false);
React.useEffect(() => {
isMountedRef.current = true;
return () => { isMountedRef.current = false; };
}, []);
const getIsFavoriteField = React.useCallback(() => {
return Presentation.favoriteProperties.has(field, imodel, FavoritePropertiesScope.IModel);
}, [field, imodel]);
const [isFavorite, setIsFavorite] = React.useState(false);
const toggleFavoriteProperty = React.useCallback(async () => {
if (getIsFavoriteField()) {
await Presentation.favoriteProperties.remove(field, imodel, FavoritePropertiesScope.IModel);
isMountedRef.current && setIsFavorite(false);
} else {
await Presentation.favoriteProperties.add(field, imodel, FavoritePropertiesScope.IModel);
isMountedRef.current && setIsFavorite(true);
}
}, [field, getIsFavoriteField, imodel]);
const onActionButtonClicked = React.useCallback(async () => {
void toggleFavoriteProperty();
}, [toggleFavoriteProperty]);
return (
<div onClick={onActionButtonClicked}>
{isFavorite ?
<Icon iconSpec="icon-star" /> :
<Icon iconSpec="icon-star" />}
</div>
);
}
// eslint-disable-next-line @typescript-eslint/naming-convention
function PresentationPropertyGrid(props: VirtualizedPropertyGridWithDataProviderProps & { dataProvider: IPresentationPropertyDataProvider }) {
const { isOverLimit } = usePropertyDataProviderWithUnifiedSelection({ dataProvider: props.dataProvider });
if (isOverLimit) {
return (<FillCentered>{IModelApp.localization.getLocalizedString("uiTestExtension:properties.too-many-elements-selected")}</FillCentered>);
}
return <VirtualizedPropertyGridWithDataProvider {...props} />;
}
function createDataProvider(imodel: IModelConnection | undefined): PresentationPropertyDataProvider | undefined {
if (imodel) {
const provider = new PresentationPropertyDataProvider({ imodel });
provider.isNestedPropertyCategoryGroupingEnabled = true;
return provider;
}
return undefined;
}
function useDataProvider(iModelConnection: IModelConnection | undefined): PresentationPropertyDataProvider | undefined {
const [dataProvider, setDataProvider] = React.useState(createDataProvider(iModelConnection));
React.useEffect(() => {
setDataProvider(createDataProvider(iModelConnection));
}, [iModelConnection]);
return dataProvider;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
export function PresentationPropertyGridWidget() {
const iModelConnection = useActiveIModelConnection();
const dataProvider = useDataProvider(iModelConnection);
const [contextMenu, setContextMenu] = React.useState<PropertyGridContextMenuArgs | undefined>(undefined);
const [contextMenuItemInfos, setContextMenuItemInfos] = React.useState<ContextMenuItemInfo[] | undefined>(undefined);
const version = useFrameworkVersion();
const componentId = ("2" === version) ? "uifw-v2-container" : "uifw-v1-container";
const style: React.CSSProperties = ("2" === version) ? { height: "100%", width: "100%", position: "absolute" } : { height: "100%" };
const onAddFavorite = React.useCallback(async (propertyField: Field) => {
if (iModelConnection)
await Presentation.favoriteProperties.add(propertyField, iModelConnection, FavoritePropertiesScope.IModel);
setContextMenu(undefined);
}, [iModelConnection]);
const onRemoveFavorite = React.useCallback(async (propertyField: Field) => {
if (iModelConnection)
await Presentation.favoriteProperties.remove(propertyField, iModelConnection, FavoritePropertiesScope.IModel);
setContextMenu(undefined);
}, [iModelConnection]);
const setupContextMenu = React.useCallback((args: PropertyGridContextMenuArgs) => {
if (iModelConnection && dataProvider) {
void dataProvider.getFieldByPropertyRecord(args.propertyRecord)
.then((field) => {
const items: ContextMenuItemInfo[] = [];
if (field !== undefined) {
if (Presentation.favoriteProperties.has(field, iModelConnection, FavoritePropertiesScope.IModel)) {
items.push({
key: "remove-favorite",
icon: "icon-remove-2",
onSelect: async () => onRemoveFavorite(field),
title: IModelApp.localization.getLocalizedString("uiTestExtension:properties.context-menu.remove-favorite.description"),
label: IModelApp.localization.getLocalizedString("uiTestExtension:properties.context-menu.remove-favorite.label"),
});
} else {
items.push({
key: "add-favorite",
icon: "icon-add",
onSelect: async () => onAddFavorite(field),
title: IModelApp.localization.getLocalizedString("uiTestExtension:properties.context-menu.add-favorite.description"),
label: IModelApp.localization.getLocalizedString("uiTestExtension:properties.context-menu.add-favorite.label"),
});
}
}
setContextMenu(args);
setContextMenuItemInfos(items.length > 0 ? items : undefined);
});
}
}, [iModelConnection, dataProvider, onRemoveFavorite, onAddFavorite]);
const onPropertyContextMenu = React.useCallback((args: PropertyGridContextMenuArgs) => {
args.event.persist();
setupContextMenu(args);
}, [setupContextMenu]);
const onContextMenuOutsideClick = React.useCallback(() => {
setContextMenu(undefined);
}, []);
const onContextMenuEsc = React.useCallback(() => {
setContextMenu(undefined);
}, []);
const favoriteActionButtonRenderer = React.useCallback((props: ActionButtonRendererProps) => {
if (iModelConnection && dataProvider) {
const { property } = props;
// eslint-disable-next-line react-hooks/rules-of-hooks
const field = useAsyncValue(React.useMemo(async () => dataProvider.getFieldByPropertyRecord(property), [property]));
return (
<div>
{
field &&
(Presentation.favoriteProperties.has(field, iModelConnection, FavoritePropertiesScope.IModel) || props.isPropertyHovered) &&
<FavoriteActionButton
field={field}
imodel={iModelConnection} />
}
</div>
);
}
return null;
}, [dataProvider, iModelConnection]);
const [gridSize, setGridSize] = React.useState<{ width: number, height: number }>();
const onGridResize = React.useCallback((width, height) => setGridSize({ width, height }), []);
return (
<div data-component-id={componentId} style={style}>
{dataProvider && gridSize?.width && gridSize.height &&
<>
<PresentationPropertyGrid
dataProvider={dataProvider}
orientation={Orientation.Horizontal}
width={gridSize.width}
height={gridSize.height}
isPropertyHoverEnabled={true}
onPropertyContextMenu={onPropertyContextMenu}
actionButtonRenderers={[favoriteActionButtonRenderer]}
/>
{contextMenu && contextMenuItemInfos &&
<GlobalContextMenu
opened={true}
onOutsideClick={onContextMenuOutsideClick}
onEsc={onContextMenuEsc}
identifier="TableWidget"
x={contextMenu.event.clientX}
y={contextMenu.event.clientY}
>
{contextMenuItemInfos.map((info: ContextMenuItemInfo) =>
<ContextMenuItem
key={info.key}
onSelect={info.onSelect}
title={info.title}
icon={info.icon}
>
{info.label}
</ContextMenuItem>
)}
</GlobalContextMenu>
}
</>
}
<ResizableContainerObserver onResize={onGridResize} />
</div>
);
}
/** PresentationPropertyGridWidgetControl provides a widget that shows properties returned from Presentation System
* based of the active element selection. To use in a frontstage use the following in the frontstageDef.
* ``` tsx
* <Widget id={PresentationPropertyGridWidgetControl.id} label={PresentationPropertyGridWidgetControl.label} control={PresentationPropertyGridWidgetControl}
* iconSpec={PresentationPropertyGridWidgetControl.iconSpec} />,
* ```
*/
export class PresentationPropertyGridWidgetControl extends WidgetControl {
public static id = "uiTestExtension:PresentationPropertyGridWidget";
public static iconSpec = "icon-info";
public static get label(): string {
return IModelApp.localization.getLocalizedString("uiTestExtension:properties.widget-label");
}
constructor(info: ConfigurableCreateInfo, options: any) {
super(info, options);
this.reactNode = <PresentationPropertyGridWidget />;
}
} | the_stack |
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodePropertyOptions,
INodeType,
INodeTypeDescription,
} from 'n8n-workflow';
import {
clockifyApiRequest,
clockifyApiRequestAllItems,
} from './GenericFunctions';
import {
IClientDto,
IWorkspaceDto,
} from './WorkpaceInterfaces';
import {
IUserDto,
} from './UserDtos';
import {
IProjectDto,
} from './ProjectInterfaces';
import {
projectFields,
projectOperations,
} from './ProjectDescription';
import {
tagFields,
tagOperations,
} from './TagDescription';
import {
taskFields,
taskOperations,
} from './TaskDescription';
import {
timeEntryFields,
timeEntryOperations,
} from './TimeEntryDescription';
import * as moment from 'moment-timezone';
export class Clockify implements INodeType {
description: INodeTypeDescription = {
displayName: 'Clockify',
name: 'clockify',
icon: 'file:clockify.svg',
group: ['transform'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Consume Clockify REST API',
defaults: {
name: 'Clockify',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'clockifyApi',
required: true,
},
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
options: [
{
name: 'Project',
value: 'project',
},
{
name: 'Tag',
value: 'tag',
},
{
name: 'Task',
value: 'task',
},
{
name: 'Time Entry',
value: 'timeEntry',
},
],
default: 'project',
description: 'The resource to operate on.',
},
...projectOperations,
...tagOperations,
...taskOperations,
...timeEntryOperations,
{
displayName: 'Workspace ID',
name: 'workspaceId',
type: 'options',
typeOptions: {
loadOptionsMethod: 'listWorkspaces',
},
required: true,
default: [],
},
...projectFields,
...tagFields,
...taskFields,
...timeEntryFields,
],
};
methods = {
loadOptions: {
async listWorkspaces(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const rtv: INodePropertyOptions[] = [];
const workspaces: IWorkspaceDto[] = await clockifyApiRequest.call(this, 'GET', 'workspaces');
if (undefined !== workspaces) {
workspaces.forEach(value => {
rtv.push(
{
name: value.name,
value: value.id,
});
});
}
return rtv;
},
async loadUsersForWorkspace(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const rtv: INodePropertyOptions[] = [];
const workspaceId = this.getCurrentNodeParameter('workspaceId');
if (undefined !== workspaceId) {
const resource = `workspaces/${workspaceId}/users`;
const users: IUserDto[] = await clockifyApiRequest.call(this, 'GET', resource);
if (undefined !== users) {
users.forEach(value => {
rtv.push(
{
name: value.name,
value: value.id,
});
});
}
}
return rtv;
},
async loadClientsForWorkspace(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const rtv: INodePropertyOptions[] = [];
const workspaceId = this.getCurrentNodeParameter('workspaceId');
if (undefined !== workspaceId) {
const resource = `workspaces/${workspaceId}/clients`;
const clients: IClientDto[] = await clockifyApiRequest.call(this, 'GET', resource);
if (undefined !== clients) {
clients.forEach(value => {
rtv.push(
{
name: value.name,
value: value.id,
});
});
}
}
return rtv;
},
async loadProjectsForWorkspace(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const rtv: INodePropertyOptions[] = [];
const workspaceId = this.getCurrentNodeParameter('workspaceId');
if (undefined !== workspaceId) {
const resource = `workspaces/${workspaceId}/projects`;
const users: IProjectDto[] = await clockifyApiRequest.call(this, 'GET', resource);
if (undefined !== users) {
users.forEach(value => {
rtv.push(
{
name: value.name,
value: value.id,
});
});
}
}
return rtv;
},
async loadTagsForWorkspace(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const rtv: INodePropertyOptions[] = [];
const workspaceId = this.getCurrentNodeParameter('workspaceId');
if (undefined !== workspaceId) {
const resource = `workspaces/${workspaceId}/tags`;
const users: IProjectDto[] = await clockifyApiRequest.call(this, 'GET', resource);
if (undefined !== users) {
users.forEach(value => {
rtv.push(
{
name: value.name,
value: value.id,
});
});
}
}
return rtv;
},
async loadCustomFieldsForWorkspace(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const rtv: INodePropertyOptions[] = [];
const workspaceId = this.getCurrentNodeParameter('workspaceId');
if (undefined !== workspaceId) {
const resource = `workspaces/${workspaceId}/custom-fields`;
const customFields = await clockifyApiRequest.call(this, 'GET', resource);
for (const customField of customFields) {
rtv.push(
{
name: customField.name,
value: customField.id,
});
}
}
return rtv;
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
const length = (items.length as unknown) as number;
const qs: IDataObject = {};
let responseData;
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
for (let i = 0; i < length; i++) {
try {
if (resource === 'project') {
if (operation === 'create') {
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const name = this.getNodeParameter('name', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: IDataObject = {
name,
};
Object.assign(body, additionalFields);
if (body.estimateUi) {
body.estimate = (body.estimateUi as IDataObject).estimateValues;
delete body.estimateUi;
}
responseData = await clockifyApiRequest.call(
this,
'POST',
`/workspaces/${workspaceId}/projects`,
body,
qs,
);
}
if (operation === 'delete') {
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const projectId = this.getNodeParameter('projectId', i) as string;
responseData = await clockifyApiRequest.call(
this,
'DELETE',
`/workspaces/${workspaceId}/projects/${projectId}`,
{},
qs,
);
responseData = { success: true };
}
if (operation === 'get') {
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const projectId = this.getNodeParameter('projectId', i) as string;
responseData = await clockifyApiRequest.call(
this,
'GET',
`/workspaces/${workspaceId}/projects/${projectId}`,
{},
qs,
);
}
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
Object.assign(qs, additionalFields);
if (returnAll) {
responseData = await clockifyApiRequestAllItems.call(
this,
'GET',
`/workspaces/${workspaceId}/projects`,
{},
qs,
);
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
responseData = await clockifyApiRequestAllItems.call(
this,
'GET',
`/workspaces/${workspaceId}/projects`,
{},
qs,
);
responseData = responseData.splice(0, qs.limit);
}
}
if (operation === 'update') {
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const projectId = this.getNodeParameter('projectId', i) as string;
const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;
const body: IDataObject = {};
Object.assign(body, updateFields);
if (body.estimateUi) {
body.estimate = (body.estimateUi as IDataObject).estimateValues;
delete body.estimateUi;
}
responseData = await clockifyApiRequest.call(
this,
'PUT',
`/workspaces/${workspaceId}/projects/${projectId}`,
body,
qs,
);
}
}
if (resource === 'tag') {
if (operation === 'create') {
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const name = this.getNodeParameter('name', i) as string;
const body: IDataObject = {
name,
};
responseData = await clockifyApiRequest.call(
this,
'POST',
`/workspaces/${workspaceId}/tags`,
body,
qs,
);
}
if (operation === 'delete') {
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const tagId = this.getNodeParameter('tagId', i) as string;
responseData = await clockifyApiRequest.call(
this,
'DELETE',
`/workspaces/${workspaceId}/tags/${tagId}`,
{},
qs,
);
responseData = { success: true };
}
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
Object.assign(qs, additionalFields);
if (returnAll) {
responseData = await clockifyApiRequestAllItems.call(
this,
'GET',
`/workspaces/${workspaceId}/tags`,
{},
qs,
);
} else {
qs.limit = this.getNodeParameter('limit', i) as number;
responseData = await clockifyApiRequestAllItems.call(
this,
'GET',
`/workspaces/${workspaceId}/tags`,
{},
qs,
);
responseData = responseData.splice(0, qs.limit);
}
}
if (operation === 'update') {
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const tagId = this.getNodeParameter('tagId', i) as string;
const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;
const body: IDataObject = {};
Object.assign(body, updateFields);
responseData = await clockifyApiRequest.call(
this,
'PUT',
`/workspaces/${workspaceId}/tags/${tagId}`,
body,
qs,
);
}
}
if (resource === 'task') {
if (operation === 'create') {
const workspaceId = this.getNodeParameter(
'workspaceId',
i,
) as string;
const projectId = this.getNodeParameter('projectId', i) as string;
const name = this.getNodeParameter('name', i) as string;
const additionalFields = this.getNodeParameter(
'additionalFields',
i,
) as IDataObject;
const body: IDataObject = {
name,
};
Object.assign(body, additionalFields);
if (body.estimate) {
const [hour, minute] = (body.estimate as string).split(':');
body.estimate = `PT${hour}H${minute}M`;
}
responseData = await clockifyApiRequest.call(
this,
'POST',
`/workspaces/${workspaceId}/projects/${projectId}/tasks`,
body,
qs,
);
}
if (operation === 'delete') {
const workspaceId = this.getNodeParameter(
'workspaceId',
i,
) as string;
const projectId = this.getNodeParameter('projectId', i) as string;
const taskId = this.getNodeParameter('taskId', i) as string;
responseData = await clockifyApiRequest.call(
this,
'DELETE',
`/workspaces/${workspaceId}/projects/${projectId}/tasks/${taskId}`,
{},
qs,
);
}
if (operation === 'get') {
const workspaceId = this.getNodeParameter(
'workspaceId',
i,
) as string;
const projectId = this.getNodeParameter('projectId', i) as string;
const taskId = this.getNodeParameter('taskId', i) as string;
responseData = await clockifyApiRequest.call(
this,
'GET',
`/workspaces/${workspaceId}/projects/${projectId}/tasks/${taskId}`,
{},
qs,
);
}
if (operation === 'getAll') {
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const workspaceId = this.getNodeParameter(
'workspaceId',
i,
) as string;
const projectId = this.getNodeParameter('projectId', i) as string;
const filters = this.getNodeParameter(
'filters',
i,
) as IDataObject;
Object.assign(qs, filters);
if (returnAll) {
responseData = await clockifyApiRequestAllItems.call(
this,
'GET',
`/workspaces/${workspaceId}/projects/${projectId}/tasks`,
{},
qs,
);
} else {
qs['page-size'] = this.getNodeParameter('limit', i) as number;
responseData = await clockifyApiRequest.call(
this,
'GET',
`/workspaces/${workspaceId}/projects/${projectId}/tasks`,
{},
qs,
);
}
}
if (operation === 'update') {
const workspaceId = this.getNodeParameter(
'workspaceId',
i,
) as string;
const projectId = this.getNodeParameter('projectId', i) as string;
const taskId = this.getNodeParameter('taskId', i) as string;
const updateFields = this.getNodeParameter(
'updateFields',
i,
) as IDataObject;
const body: IDataObject = {};
Object.assign(body, updateFields);
if (body.estimate) {
const [hour, minute] = (body.estimate as string).split(':');
body.estimate = `PT${hour}H${minute}M`;
}
responseData = await clockifyApiRequest.call(
this,
'PUT',
`/workspaces/${workspaceId}/projects/${projectId}/tasks/${taskId}`,
body,
qs,
);
}
}
if (resource === 'timeEntry') {
if (operation === 'create') {
const timezone = this.getTimezone();
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const start = this.getNodeParameter('start', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: IDataObject = {
start: moment.tz(start, timezone).utc().format(),
};
Object.assign(body, additionalFields);
if (body.end) {
body.end = moment.tz(body.end, timezone).utc().format();
}
if (body.customFieldsUi) {
const customFields = (body.customFieldsUi as IDataObject).customFieldsValues as IDataObject[];
body.customFields = customFields;
}
responseData = await clockifyApiRequest.call(
this,
'POST',
`/workspaces/${workspaceId}/time-entries`,
body,
qs,
);
}
if (operation === 'delete') {
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const timeEntryId = this.getNodeParameter('timeEntryId', i) as string;
responseData = await clockifyApiRequest.call(
this,
'DELETE',
`/workspaces/${workspaceId}/time-entries/${timeEntryId}`,
{},
qs,
);
responseData = { success: true };
}
if (operation === 'get') {
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const timeEntryId = this.getNodeParameter('timeEntryId', i) as string;
responseData = await clockifyApiRequest.call(
this,
'GET',
`/workspaces/${workspaceId}/time-entries/${timeEntryId}`,
{},
qs,
);
}
if (operation === 'update') {
const timezone = this.getTimezone();
const workspaceId = this.getNodeParameter('workspaceId', i) as string;
const timeEntryId = this.getNodeParameter('timeEntryId', i) as string;
const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;
const body: IDataObject = {};
Object.assign(body, updateFields);
if (body.end) {
body.end = moment.tz(body.end, timezone).utc().format();
}
if (body.start) {
body.start = moment.tz(body.start, timezone).utc().format();
} else {
// even if you do not want to update the start time, it always has to be set
// to make it more simple to the user, if he did not set a start time look for the current start time
// and set it
const { timeInterval: { start } } = await clockifyApiRequest.call(
this,
'GET',
`/workspaces/${workspaceId}/time-entries/${timeEntryId}`,
{},
qs,
);
body.start = start;
}
responseData = await clockifyApiRequest.call(
this,
'PUT',
`/workspaces/${workspaceId}/time-entries/${timeEntryId}`,
body,
qs,
);
}
}
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData as IDataObject[]);
} else if (responseData !== undefined) {
returnData.push(responseData as IDataObject);
}
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
} | the_stack |
import {
CreateHmacKey,
HASH_ALGORITHMS,
HashAlgorithms,
HexString,
KeyEncodings,
SecretKey,
Strategy,
createDigestPlaceholder,
isTokenValid,
keyuri
} from './utils';
import { HOTP, HOTPOptions, hotpOptionsValidator, hotpToken } from './hotp';
/**
* Interface for options used in TOTP.
*
* Contains additional options in addition to
* those within HOTP.
*/
export interface TOTPOptions<T = string> extends HOTPOptions<T> {
/**
* The starting time since the JavasSript epoch (seconds) (UNIX epoch * 1000).
*/
epoch: number;
/**
* Time step (seconds).
*/
step: number;
/**
* How many windows (x * step) past and future do we consider as valid during check.
*/
window: number | [number, number];
}
/**
* Interface for available epoches derived from
* the current epoch.
*/
export interface EpochAvailable {
current: number;
future: number[];
past: number[];
}
/**
* Validates and formats the given window into an array
* containing how many windows past and future to check.
*
* @ignore
*/
function parseWindowBounds(win?: unknown): [number, number] {
if (typeof win === 'number') {
return [Math.abs(win), Math.abs(win)];
}
if (Array.isArray(win)) {
const [past, future] = win;
if (typeof past === 'number' && typeof future === 'number') {
return [Math.abs(past), Math.abs(future)];
}
}
throw new Error(
'Expecting options.window to be an number or [number, number].'
);
}
/**
* Validates the given [[TOTPOptions]].
*/
export function totpOptionsValidator<
T extends TOTPOptions<unknown> = TOTPOptions<unknown>
>(options: Readonly<Partial<T>>): void {
hotpOptionsValidator<T>(options);
parseWindowBounds(options.window);
if (typeof options.epoch !== 'number') {
throw new Error('Expecting options.epoch to be a number.');
}
if (typeof options.step !== 'number') {
throw new Error('Expecting options.step to be a number.');
}
}
/**
* Pads the secret to the expected minimum length
* and returns a hex representation of the string.
*/
export const totpPadSecret = (
secret: SecretKey,
encoding: KeyEncodings,
minLength: number
): HexString => {
const currentLength = secret.length;
const hexSecret = Buffer.from(secret, encoding).toString('hex');
if (currentLength < minLength) {
const newSecret = new Array(minLength - currentLength + 1).join(hexSecret);
return Buffer.from(newSecret, 'hex')
.slice(0, minLength)
.toString('hex');
}
return hexSecret;
};
/**
* Takes a TOTP secret and derives the HMAC key
* for use in token generation.
*
* In RFC 6238, the secret / seed length for different algorithms
* are predefined.
*
* - HMAC-SHA1 (20 bytes)
* - HMAC-SHA256 (32 bytes)
* - HMAC-SHA512 (64 bytes)
*
* @param algorithm - Reference: [[TOTPOptions.algorithm]]
* @param secret
* @param encoding - Reference: [[TOTPOptions.encoding]]
*/
export const totpCreateHmacKey: CreateHmacKey = (
algorithm: HashAlgorithms,
secret: SecretKey,
encoding: KeyEncodings
): HexString => {
switch (algorithm) {
case HashAlgorithms.SHA1:
return totpPadSecret(secret, encoding, 20);
case HashAlgorithms.SHA256:
return totpPadSecret(secret, encoding, 32);
case HashAlgorithms.SHA512:
return totpPadSecret(secret, encoding, 64);
default:
throw new Error(
`Expecting algorithm to be one of ${HASH_ALGORITHMS.join(
', '
)}. Received ${algorithm}.`
);
}
};
/**
* Returns a set of default options for TOTP at the current epoch.
*/
export function totpDefaultOptions<
T extends TOTPOptions<unknown> = TOTPOptions<unknown>
>(): Partial<T> {
const options = {
algorithm: HashAlgorithms.SHA1,
createDigest: createDigestPlaceholder,
createHmacKey: totpCreateHmacKey,
digits: 6,
encoding: KeyEncodings.ASCII,
epoch: Date.now(),
step: 30,
window: 0
};
return (options as unknown) as Partial<T>;
}
/**
* Takes an TOTP Option object and provides presets for
* some of the missing required TOTP option fields and validates
* the resultant options.
*/
export function totpOptions<
T extends TOTPOptions<unknown> = TOTPOptions<unknown>
>(opt: Partial<T>): Readonly<T> {
const options = {
...totpDefaultOptions<T>(),
...opt
};
totpOptionsValidator<T>(options);
return Object.freeze(options) as Readonly<T>;
}
/**
* Generates the counter based on the current epoch and step.
* This dynamic counter is used in the HOTP algorithm.
*
* @param epoch - Reference: [[TOTPOptions.epoch]]
* @param step - Reference: [[TOTPOptions.step]]
*/
export function totpCounter(epoch: number, step: number): number {
return Math.floor(epoch / step / 1000);
}
/**
* Generates a Time-based One-time Token (TOTP)
*
* tl;dr: TOTP = HOTP + counter based on current time.
*
* **References**
*
* - http://tools.ietf.org/html/rfc6238
* - http://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm
*
*/
export function totpToken<
T extends TOTPOptions<unknown> = TOTPOptions<unknown>
>(secret: SecretKey, options: Readonly<T>): string {
const counter = totpCounter(options.epoch, options.step);
return hotpToken<T>(secret, counter, options);
}
function totpEpochsInWindow(
epoch: number,
direction: number,
deltaPerEpoch: number,
numOfEpoches: number
): number[] {
const result: number[] = [];
if (numOfEpoches === 0) {
return result;
}
for (let i = 1; i <= numOfEpoches; i++) {
const delta = direction * i * deltaPerEpoch;
result.push(epoch + delta);
}
return result;
}
/**
* Gets a set of epoches derived from
* the current epoch and the acceptable window.
*
* @param epoch - Reference: [[TOTPOptions.epoch]]
* @param step - Reference: [[TOTPOptions.step]]
* @param win - Reference: [[TOTPOptions.window]]
*/
export function totpEpochAvailable(
epoch: number,
step: number,
win: number | [number, number]
): EpochAvailable {
const bounds = parseWindowBounds(win);
const delta = step * 1000; // to JS Time
return {
current: epoch,
past: totpEpochsInWindow(epoch, -1, delta, bounds[0]),
future: totpEpochsInWindow(epoch, 1, delta, bounds[1])
};
}
/**
* Checks the given token against the system generated token.
*
* **Note**: Token is valid only if it is a number string.
*/
export function totpCheck<
T extends TOTPOptions<unknown> = TOTPOptions<unknown>
>(token: string, secret: SecretKey, options: Readonly<T>): boolean {
if (!isTokenValid(token)) {
return false;
}
const systemToken = totpToken(secret, options);
return token === systemToken;
}
/**
* Checks if there is a valid TOTP token in a given list of epoches.
* Returns the (index + 1) of a valid epoch in the list.
*
* @param epochs - List of epochs to check token against
* @param token - The token to check
* @param secret - Your secret key.
* @param options - A TOTPOptions object.
*/
export function totpCheckByEpoch<T extends TOTPOptions = TOTPOptions>(
epochs: number[],
token: string,
secret: SecretKey,
options: Readonly<T>
): number | null {
let position = null;
epochs.some((epoch, idx): boolean => {
if (totpCheck<T>(token, secret, { ...options, epoch })) {
position = idx + 1;
return true;
}
return false;
});
return position;
}
/**
* Checks the provided OTP token against system generated token
* with support for checking past or future x * step windows.
*
* Return values:
*
* - null = check failed
* - positive number = token at future x * step
* - negative number = token at past x * step
*
* @param token - The token to check
* @param secret - Your secret key.
* @param options - A TOTPOptions object.
*/
export function totpCheckWithWindow<T extends TOTPOptions = TOTPOptions>(
token: string,
secret: SecretKey,
options: Readonly<T>
): number | null {
if (totpCheck(token, secret, options)) {
return 0;
}
const epochs = totpEpochAvailable(
options.epoch,
options.step,
options.window
);
const backward = totpCheckByEpoch<T>(epochs.past, token, secret, options);
if (backward !== null) {
return backward * -1;
}
return totpCheckByEpoch<T>(epochs.future, token, secret, options);
}
/**
* Calculates the number of seconds used in the current tick for TOTP.
*
* The start of a new token: `timeUsed() === 0`
*
* @param epoch - Reference: [[TOTPOptions.epoch]]
* @param step - Reference: [[TOTPOptions.step]]
*/
export function totpTimeUsed(epoch: number, step: number): number {
return Math.floor(epoch / 1000) % step;
}
/**
* Calculates the number of seconds till next tick for TOTP.
*
* The start of a new token: `timeRemaining() === step`
*
* @param epoch - Reference: [[TOTPOptions.epoch]]
* @param step - Reference: [[TOTPOptions.step]]
*/
export function totpTimeRemaining(epoch: number, step: number): number {
return step - totpTimeUsed(epoch, step);
}
/**
* Generates a [keyuri](../#keyuri) from options provided
* and it's type set to TOTP.
*/
export function totpKeyuri<
T extends TOTPOptions<unknown> = TOTPOptions<unknown>
>(
accountName: string,
issuer: string,
secret: SecretKey,
options: Readonly<T>
): string {
return keyuri({
algorithm: options.algorithm,
digits: options.digits,
step: options.step,
type: Strategy.TOTP,
accountName,
issuer,
secret
});
}
/**
* A class wrapper containing all TOTP methods.
*/
export class TOTP<T extends TOTPOptions = TOTPOptions> extends HOTP<T> {
/**
* Creates a new instance with all defaultOptions and options reset.
*/
public create(defaultOptions: Partial<T> = {}): TOTP<T> {
return new TOTP<T>(defaultOptions);
}
/**
* Returns class options polyfilled with some of
* the missing required options.
*
* Reference: [[totpOptions]]
*/
public allOptions(): Readonly<T> {
return totpOptions<T>(this.options);
}
/**
* Reference: [[totpToken]]
*/
public generate(secret: SecretKey): string {
return totpToken<T>(secret, this.allOptions());
}
/**
* Reference: [[totpCheckWithWindow]]
*/
public checkDelta(token: string, secret: SecretKey): number | null {
return totpCheckWithWindow<T>(token, secret, this.allOptions());
}
/**
* Checks if a given TOTP token matches the generated
* token at the given epoch (default to current time).
*
* This method will return true as long as the token is
* still within the acceptable time window defined.
*
* i.e when [[checkDelta]] returns a number.
*/
public check(token: string, secret: SecretKey): boolean {
const delta = this.checkDelta(token, secret);
return typeof delta === 'number';
}
/**
* Same as [[check]] but accepts a single object based argument.
*/
public verify(opts: { token: string; secret: SecretKey }): boolean {
if (typeof opts !== 'object') {
throw new Error('Expecting argument 0 of verify to be an object');
}
return this.check(opts.token, opts.secret);
}
/**
* Reference: [[totpTimeRemaining]]
*/
public timeRemaining(): number {
const options = this.allOptions();
return totpTimeRemaining(options.epoch, options.step);
}
/**
* Reference: [[totpTimeUsed]]
*/
public timeUsed(): number {
const options = this.allOptions();
return totpTimeUsed(options.epoch, options.step);
}
/**
* Reference: [[totpKeyuri]]
*/
public keyuri(
accountName: string,
issuer: string,
secret: SecretKey
): string {
return totpKeyuri<T>(accountName, issuer, secret, this.allOptions());
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.